Completed
Push — master ( 567fae...5b6c4c )
by cam
01:19
created
ecrire/src/Chiffrer/Cles.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
 	public function generate(string $name): string {
31 31
 		$key = Chiffrement::keygen();
32 32
 		$this->keys[$name] = $key;
33
-		spip_log("Création de la cle $name", 'chiffrer' . _LOG_INFO_IMPORTANTE);
33
+		spip_log("Création de la cle $name", 'chiffrer'._LOG_INFO_IMPORTANTE);
34 34
 		return $key;
35 35
 	}
36 36
 
Please login to merge, or discard this patch.
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -14,48 +14,48 @@
 block discarded – undo
14 14
 
15 15
 /** Conteneur de clés (chiffrement, authentification) */
16 16
 class Cles implements \Countable /* , ContainerInterface */ {
17
-	private array $keys;
18
-	public function __construct(array $keys) {
19
-		$this->keys = $keys;
20
-	}
21
-
22
-	public function has(string $name): bool {
23
-		return array_key_exists($name, $this->keys);
24
-	}
25
-
26
-	public function get(string $name): ?string {
27
-		return $this->keys[$name] ?? null;
28
-	}
29
-
30
-	public function generate(string $name): string {
31
-		$key = Chiffrement::keygen();
32
-		$this->keys[$name] = $key;
33
-		spip_log("Création de la cle $name", 'chiffrer' . _LOG_INFO_IMPORTANTE);
34
-		return $key;
35
-	}
36
-
37
-	public function set(
38
-		string $name,
39
-		#[\SensitiveParameter]
40
-		string $key
41
-	): void {
42
-		$this->keys[$name] = $key;
43
-	}
44
-
45
-	public function delete(string $name): bool {
46
-		if (isset($this->keys[$name])) {
47
-			unset($this->keys[$name]);
48
-			return true;
49
-		};
50
-		return false;
51
-	}
52
-
53
-	public function count(): int {
54
-		return count($this->keys);
55
-	}
56
-
57
-	public function toJson(): string {
58
-		$json = array_map('base64_encode', $this->keys);
59
-		return \json_encode($json);
60
-	}
17
+    private array $keys;
18
+    public function __construct(array $keys) {
19
+        $this->keys = $keys;
20
+    }
21
+
22
+    public function has(string $name): bool {
23
+        return array_key_exists($name, $this->keys);
24
+    }
25
+
26
+    public function get(string $name): ?string {
27
+        return $this->keys[$name] ?? null;
28
+    }
29
+
30
+    public function generate(string $name): string {
31
+        $key = Chiffrement::keygen();
32
+        $this->keys[$name] = $key;
33
+        spip_log("Création de la cle $name", 'chiffrer' . _LOG_INFO_IMPORTANTE);
34
+        return $key;
35
+    }
36
+
37
+    public function set(
38
+        string $name,
39
+        #[\SensitiveParameter]
40
+        string $key
41
+    ): void {
42
+        $this->keys[$name] = $key;
43
+    }
44
+
45
+    public function delete(string $name): bool {
46
+        if (isset($this->keys[$name])) {
47
+            unset($this->keys[$name]);
48
+            return true;
49
+        };
50
+        return false;
51
+    }
52
+
53
+    public function count(): int {
54
+        return count($this->keys);
55
+    }
56
+
57
+    public function toJson(): string {
58
+        $json = array_map('base64_encode', $this->keys);
59
+        return \json_encode($json);
60
+    }
61 61
 }
Please login to merge, or discard this patch.
ecrire/inc/presenter_enfants.php 2 patches
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 include_spip('inc/autoriser');
@@ -30,80 +30,80 @@  discard block
 block discarded – undo
30 30
  *  Un tableau des sous rubriques
31 31
  */
32 32
 function enfant_rub($collection, $debut = 0, $limite = 500) {
33
-	$voir_logo = (isset($GLOBALS['meta']['image_process']) and $GLOBALS['meta']['image_process'] != 'non');
34
-	$logo = '';
35
-
36
-	if ($voir_logo) {
37
-		$chercher_logo = charger_fonction('chercher_logo', 'inc');
38
-		include_spip('inc/filtres_images_mini');
39
-	}
40
-
41
-	$res = [];
42
-
43
-	$result = sql_select(
44
-		'id_rubrique, id_parent, titre, descriptif, lang',
45
-		'spip_rubriques',
46
-		'id_parent=' . intval($collection),
47
-		'',
48
-		'0+titre,titre',
49
-		$debut == -1 ? '' : "$debut,$limite"
50
-	);
51
-	while ($row = sql_fetch($result)) {
52
-		$id_rubrique = $row['id_rubrique'];
53
-		$id_parent = $row['id_parent'];
54
-		// pour etre sur de passer par tous les traitements
55
-		$titre = generer_objet_info($id_rubrique, 'rubrique', 'titre');
56
-		if ('' !== ($rang = recuperer_numero($row['titre']))) {
57
-			$rang = "<span class='rang'>$rang.</span> ";
58
-		}
59
-
60
-		if (autoriser('voir', 'rubrique', $id_rubrique)) {
61
-			$les_sous_enfants = sous_enfant_rub($id_rubrique);
62
-
63
-			changer_typo($row['lang']);
64
-			$lang_dir = lang_dir($row['lang']);
65
-			$descriptif = propre($row['descriptif']);
66
-
67
-			if ($voir_logo) {
68
-				if ($logo = $chercher_logo($id_rubrique, 'id_rubrique', 'on')) {
69
-					[$fid, $dir, $nom, $format] = $logo;
70
-					$logo = image_recadre_avec_fallback("<img src='$fid' alt='' />", 70, 70);
71
-					if ($logo) {
72
-						$logo = wrap(inserer_attribut($logo, 'class', 'logo'), '<span class="logo-carre">');
73
-					}
74
-				}
75
-			}
76
-
77
-			$lib_bouton = (!acces_restreint_rubrique($id_rubrique) ? '' :
78
-					http_img_pack(
79
-						'auteur-0minirezo-16.png',
80
-						'',
81
-						" width='16' height='16'",
82
-						_T('image_administrer_rubrique')
83
-					)) .
84
-				" <a class='titremlien' dir='$lang_dir'" .
85
-				($row['lang'] !== $GLOBALS['spip_lang'] ? " hreflang='" . $row['lang'] . "'" : '') .
86
-				" href='" .
87
-				generer_objet_url($id_rubrique, 'rubrique') .
88
-				"'><span class='titre'>" .
89
-				$rang . $titre
90
-				. '</span>'
91
-				. (is_string($logo) ? $logo : '')
92
-				. '</a>';
93
-
94
-			$titre = bouton_block_depliable($lib_bouton, $les_sous_enfants ? false : -1, "enfants$id_rubrique")
95
-				. (!$descriptif ? '' : "\n<div class='descriptif'>$descriptif</div>")
96
-				;
97
-
98
-			$res[] =
99
-				debut_cadre_sous_rub(($id_parent ? 'rubrique-24.png' : 'secteur-24.png'), true, '', $titre) .
100
-				$les_sous_enfants .
101
-				fin_cadre_sous_rub();
102
-		}
103
-	}
104
-
105
-	changer_typo($GLOBALS['spip_lang']); # remettre la typo de l'interface pour la suite
106
-	return $res;
33
+    $voir_logo = (isset($GLOBALS['meta']['image_process']) and $GLOBALS['meta']['image_process'] != 'non');
34
+    $logo = '';
35
+
36
+    if ($voir_logo) {
37
+        $chercher_logo = charger_fonction('chercher_logo', 'inc');
38
+        include_spip('inc/filtres_images_mini');
39
+    }
40
+
41
+    $res = [];
42
+
43
+    $result = sql_select(
44
+        'id_rubrique, id_parent, titre, descriptif, lang',
45
+        'spip_rubriques',
46
+        'id_parent=' . intval($collection),
47
+        '',
48
+        '0+titre,titre',
49
+        $debut == -1 ? '' : "$debut,$limite"
50
+    );
51
+    while ($row = sql_fetch($result)) {
52
+        $id_rubrique = $row['id_rubrique'];
53
+        $id_parent = $row['id_parent'];
54
+        // pour etre sur de passer par tous les traitements
55
+        $titre = generer_objet_info($id_rubrique, 'rubrique', 'titre');
56
+        if ('' !== ($rang = recuperer_numero($row['titre']))) {
57
+            $rang = "<span class='rang'>$rang.</span> ";
58
+        }
59
+
60
+        if (autoriser('voir', 'rubrique', $id_rubrique)) {
61
+            $les_sous_enfants = sous_enfant_rub($id_rubrique);
62
+
63
+            changer_typo($row['lang']);
64
+            $lang_dir = lang_dir($row['lang']);
65
+            $descriptif = propre($row['descriptif']);
66
+
67
+            if ($voir_logo) {
68
+                if ($logo = $chercher_logo($id_rubrique, 'id_rubrique', 'on')) {
69
+                    [$fid, $dir, $nom, $format] = $logo;
70
+                    $logo = image_recadre_avec_fallback("<img src='$fid' alt='' />", 70, 70);
71
+                    if ($logo) {
72
+                        $logo = wrap(inserer_attribut($logo, 'class', 'logo'), '<span class="logo-carre">');
73
+                    }
74
+                }
75
+            }
76
+
77
+            $lib_bouton = (!acces_restreint_rubrique($id_rubrique) ? '' :
78
+                    http_img_pack(
79
+                        'auteur-0minirezo-16.png',
80
+                        '',
81
+                        " width='16' height='16'",
82
+                        _T('image_administrer_rubrique')
83
+                    )) .
84
+                " <a class='titremlien' dir='$lang_dir'" .
85
+                ($row['lang'] !== $GLOBALS['spip_lang'] ? " hreflang='" . $row['lang'] . "'" : '') .
86
+                " href='" .
87
+                generer_objet_url($id_rubrique, 'rubrique') .
88
+                "'><span class='titre'>" .
89
+                $rang . $titre
90
+                . '</span>'
91
+                . (is_string($logo) ? $logo : '')
92
+                . '</a>';
93
+
94
+            $titre = bouton_block_depliable($lib_bouton, $les_sous_enfants ? false : -1, "enfants$id_rubrique")
95
+                . (!$descriptif ? '' : "\n<div class='descriptif'>$descriptif</div>")
96
+                ;
97
+
98
+            $res[] =
99
+                debut_cadre_sous_rub(($id_parent ? 'rubrique-24.png' : 'secteur-24.png'), true, '', $titre) .
100
+                $les_sous_enfants .
101
+                fin_cadre_sous_rub();
102
+        }
103
+    }
104
+
105
+    changer_typo($GLOBALS['spip_lang']); # remettre la typo de l'interface pour la suite
106
+    return $res;
107 107
 }
108 108
 
109 109
 /**
@@ -116,71 +116,71 @@  discard block
 block discarded – undo
116 116
  *  Le contenu du bloc dépliable
117 117
  */
118 118
 function sous_enfant_rub($collection2) {
119
-	$nb = sql_countsel('spip_rubriques', 'id_parent=' . intval($collection2));
120
-
121
-	$retour = '';
122
-	$pagination = '';
123
-	$debut = 0;
124
-	$limite = 500;
125
-
126
-	/**
127
-	 * On ne va afficher que 500 résultats max
128
-	 * Si > 500 on affiche une pagination
129
-	 */
130
-	if ($nb > $limite) {
131
-		$debut = _request('debut_rubrique' . $collection2) ?: $debut;
132
-		$pagination = chercher_filtre('pagination');
133
-		$pagination = '<nav class="pagination">' . $pagination(
134
-			$nb,
135
-			'_rubrique' . $collection2,
136
-			$debut,
137
-			$limite,
138
-			true,
139
-			'prive'
140
-		) . '</nav>';
141
-		$limite = $debut + $limite;
142
-	}
143
-
144
-	$result = sql_select(
145
-		'id_rubrique, id_parent, titre, lang',
146
-		'spip_rubriques',
147
-		'id_parent=' . intval($collection2),
148
-		'',
149
-		'0+titre,titre',
150
-		$debut == -1 ? '' : "$debut,$limite"
151
-	);
152
-
153
-	while ($row = sql_fetch($result)) {
154
-		$id_rubrique2 = $row['id_rubrique'];
155
-		$titre2 = generer_objet_info(
156
-			$id_rubrique2,
157
-			'rubrique',
158
-			'titre'
159
-		); // pour etre sur de passer par tous les traitements
160
-		if ('' !== ($rang2 = recuperer_numero($row['titre']))) {
161
-			$rang2 = "<span class='rang'>$rang2.</span> ";
162
-		}
163
-
164
-		changer_typo($row['lang']);
165
-		$lang_dir = lang_dir($row['lang']);
166
-		if (autoriser('voir', 'rubrique', $id_rubrique2)) {
167
-			$retour .= "\n<li class='item' dir='$lang_dir'><a href='" . generer_objet_url(
168
-				$id_rubrique2,
169
-				'rubrique'
170
-			) . "'>" . $rang2 . $titre2 . "</a></li>\n";
171
-		}
172
-	}
173
-
174
-	$retour = $pagination . $retour . $pagination;
175
-
176
-	if (!$retour) {
177
-		return '';
178
-	}
179
-
180
-	return debut_block_depliable($debut > 0 ? true : false, "enfants$collection2")
181
-	. "\n<ul class='liste-items sous-sous-rub'>\n"
182
-	. $retour
183
-	. "</ul>\n" . fin_block() . "\n\n";
119
+    $nb = sql_countsel('spip_rubriques', 'id_parent=' . intval($collection2));
120
+
121
+    $retour = '';
122
+    $pagination = '';
123
+    $debut = 0;
124
+    $limite = 500;
125
+
126
+    /**
127
+     * On ne va afficher que 500 résultats max
128
+     * Si > 500 on affiche une pagination
129
+     */
130
+    if ($nb > $limite) {
131
+        $debut = _request('debut_rubrique' . $collection2) ?: $debut;
132
+        $pagination = chercher_filtre('pagination');
133
+        $pagination = '<nav class="pagination">' . $pagination(
134
+            $nb,
135
+            '_rubrique' . $collection2,
136
+            $debut,
137
+            $limite,
138
+            true,
139
+            'prive'
140
+        ) . '</nav>';
141
+        $limite = $debut + $limite;
142
+    }
143
+
144
+    $result = sql_select(
145
+        'id_rubrique, id_parent, titre, lang',
146
+        'spip_rubriques',
147
+        'id_parent=' . intval($collection2),
148
+        '',
149
+        '0+titre,titre',
150
+        $debut == -1 ? '' : "$debut,$limite"
151
+    );
152
+
153
+    while ($row = sql_fetch($result)) {
154
+        $id_rubrique2 = $row['id_rubrique'];
155
+        $titre2 = generer_objet_info(
156
+            $id_rubrique2,
157
+            'rubrique',
158
+            'titre'
159
+        ); // pour etre sur de passer par tous les traitements
160
+        if ('' !== ($rang2 = recuperer_numero($row['titre']))) {
161
+            $rang2 = "<span class='rang'>$rang2.</span> ";
162
+        }
163
+
164
+        changer_typo($row['lang']);
165
+        $lang_dir = lang_dir($row['lang']);
166
+        if (autoriser('voir', 'rubrique', $id_rubrique2)) {
167
+            $retour .= "\n<li class='item' dir='$lang_dir'><a href='" . generer_objet_url(
168
+                $id_rubrique2,
169
+                'rubrique'
170
+            ) . "'>" . $rang2 . $titre2 . "</a></li>\n";
171
+        }
172
+    }
173
+
174
+    $retour = $pagination . $retour . $pagination;
175
+
176
+    if (!$retour) {
177
+        return '';
178
+    }
179
+
180
+    return debut_block_depliable($debut > 0 ? true : false, "enfants$collection2")
181
+    . "\n<ul class='liste-items sous-sous-rub'>\n"
182
+    . $retour
183
+    . "</ul>\n" . fin_block() . "\n\n";
184 184
 }
185 185
 
186 186
 /**
@@ -195,44 +195,44 @@  discard block
 block discarded – undo
195 195
  *  Le contenu textuel affiché, la liste des sous rubriques
196 196
  */
197 197
 function afficher_enfant_rub($id_rubrique = 0) {
198
-	$pagination = '';
199
-	$debut = 0;
200
-	$limite = 500;
201
-
202
-	$nb = sql_countsel('spip_rubriques', 'id_parent=' . intval($id_rubrique));
203
-
204
-	if ($nb > $limite) {
205
-		$debut = _request('debut_rubrique' . $id_rubrique) ?: $debut;
206
-		$pagination = chercher_filtre('pagination');
207
-		$pagination = '<br class="nettoyeur"><nav class="pagination">' .
208
-			$pagination($nb, '_rubrique' . $id_rubrique, $debut, $limite, true, 'prive') .
209
-		'</nav>';
210
-	}
211
-
212
-	$les_enfants = enfant_rub($id_rubrique, $debut, $limite);
213
-
214
-	if (!$n = count($les_enfants)) {
215
-		return '';
216
-	}
217
-
218
-	if ($n == 1) {
219
-		$les_enfants = reset($les_enfants);
220
-		$les_enfants2 = '';
221
-	} else {
222
-		$n = ceil($n / 2);
223
-		$les_enfants2 = implode('', array_slice($les_enfants, $n));
224
-		$les_enfants = implode('', array_slice($les_enfants, 0, $n));
225
-	}
226
-
227
-	$res =
228
-		$pagination
229
-		. "<div class='gauche'>"
230
-		. $les_enfants
231
-		. '</div>'
232
-		. "<div class='droite'>"
233
-		. $les_enfants2
234
-		. '</div>'
235
-		. $pagination;
236
-
237
-	return $res;
198
+    $pagination = '';
199
+    $debut = 0;
200
+    $limite = 500;
201
+
202
+    $nb = sql_countsel('spip_rubriques', 'id_parent=' . intval($id_rubrique));
203
+
204
+    if ($nb > $limite) {
205
+        $debut = _request('debut_rubrique' . $id_rubrique) ?: $debut;
206
+        $pagination = chercher_filtre('pagination');
207
+        $pagination = '<br class="nettoyeur"><nav class="pagination">' .
208
+            $pagination($nb, '_rubrique' . $id_rubrique, $debut, $limite, true, 'prive') .
209
+        '</nav>';
210
+    }
211
+
212
+    $les_enfants = enfant_rub($id_rubrique, $debut, $limite);
213
+
214
+    if (!$n = count($les_enfants)) {
215
+        return '';
216
+    }
217
+
218
+    if ($n == 1) {
219
+        $les_enfants = reset($les_enfants);
220
+        $les_enfants2 = '';
221
+    } else {
222
+        $n = ceil($n / 2);
223
+        $les_enfants2 = implode('', array_slice($les_enfants, $n));
224
+        $les_enfants = implode('', array_slice($les_enfants, 0, $n));
225
+    }
226
+
227
+    $res =
228
+        $pagination
229
+        . "<div class='gauche'>"
230
+        . $les_enfants
231
+        . '</div>'
232
+        . "<div class='droite'>"
233
+        . $les_enfants2
234
+        . '</div>'
235
+        . $pagination;
236
+
237
+    return $res;
238 238
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -26 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 	$result = sql_select(
44 44
 		'id_rubrique, id_parent, titre, descriptif, lang',
45 45
 		'spip_rubriques',
46
-		'id_parent=' . intval($collection),
46
+		'id_parent='.intval($collection),
47 47
 		'',
48 48
 		'0+titre,titre',
49 49
 		$debut == -1 ? '' : "$debut,$limite"
@@ -74,19 +74,18 @@  discard block
 block discarded – undo
74 74
 				}
75 75
 			}
76 76
 
77
-			$lib_bouton = (!acces_restreint_rubrique($id_rubrique) ? '' :
78
-					http_img_pack(
77
+			$lib_bouton = (!acces_restreint_rubrique($id_rubrique) ? '' : http_img_pack(
79 78
 						'auteur-0minirezo-16.png',
80 79
 						'',
81 80
 						" width='16' height='16'",
82 81
 						_T('image_administrer_rubrique')
83
-					)) .
84
-				" <a class='titremlien' dir='$lang_dir'" .
85
-				($row['lang'] !== $GLOBALS['spip_lang'] ? " hreflang='" . $row['lang'] . "'" : '') .
86
-				" href='" .
87
-				generer_objet_url($id_rubrique, 'rubrique') .
88
-				"'><span class='titre'>" .
89
-				$rang . $titre
82
+					)).
83
+				" <a class='titremlien' dir='$lang_dir'".
84
+				($row['lang'] !== $GLOBALS['spip_lang'] ? " hreflang='".$row['lang']."'" : '').
85
+				" href='".
86
+				generer_objet_url($id_rubrique, 'rubrique').
87
+				"'><span class='titre'>".
88
+				$rang.$titre
90 89
 				. '</span>'
91 90
 				. (is_string($logo) ? $logo : '')
92 91
 				. '</a>';
@@ -96,8 +95,8 @@  discard block
 block discarded – undo
96 95
 				;
97 96
 
98 97
 			$res[] =
99
-				debut_cadre_sous_rub(($id_parent ? 'rubrique-24.png' : 'secteur-24.png'), true, '', $titre) .
100
-				$les_sous_enfants .
98
+				debut_cadre_sous_rub(($id_parent ? 'rubrique-24.png' : 'secteur-24.png'), true, '', $titre).
99
+				$les_sous_enfants.
101 100
 				fin_cadre_sous_rub();
102 101
 		}
103 102
 	}
@@ -116,7 +115,7 @@  discard block
 block discarded – undo
116 115
  *  Le contenu du bloc dépliable
117 116
  */
118 117
 function sous_enfant_rub($collection2) {
119
-	$nb = sql_countsel('spip_rubriques', 'id_parent=' . intval($collection2));
118
+	$nb = sql_countsel('spip_rubriques', 'id_parent='.intval($collection2));
120 119
 
121 120
 	$retour = '';
122 121
 	$pagination = '';
@@ -128,23 +127,23 @@  discard block
 block discarded – undo
128 127
 	 * Si > 500 on affiche une pagination
129 128
 	 */
130 129
 	if ($nb > $limite) {
131
-		$debut = _request('debut_rubrique' . $collection2) ?: $debut;
130
+		$debut = _request('debut_rubrique'.$collection2) ?: $debut;
132 131
 		$pagination = chercher_filtre('pagination');
133
-		$pagination = '<nav class="pagination">' . $pagination(
132
+		$pagination = '<nav class="pagination">'.$pagination(
134 133
 			$nb,
135
-			'_rubrique' . $collection2,
134
+			'_rubrique'.$collection2,
136 135
 			$debut,
137 136
 			$limite,
138 137
 			true,
139 138
 			'prive'
140
-		) . '</nav>';
139
+		).'</nav>';
141 140
 		$limite = $debut + $limite;
142 141
 	}
143 142
 
144 143
 	$result = sql_select(
145 144
 		'id_rubrique, id_parent, titre, lang',
146 145
 		'spip_rubriques',
147
-		'id_parent=' . intval($collection2),
146
+		'id_parent='.intval($collection2),
148 147
 		'',
149 148
 		'0+titre,titre',
150 149
 		$debut == -1 ? '' : "$debut,$limite"
@@ -164,14 +163,14 @@  discard block
 block discarded – undo
164 163
 		changer_typo($row['lang']);
165 164
 		$lang_dir = lang_dir($row['lang']);
166 165
 		if (autoriser('voir', 'rubrique', $id_rubrique2)) {
167
-			$retour .= "\n<li class='item' dir='$lang_dir'><a href='" . generer_objet_url(
166
+			$retour .= "\n<li class='item' dir='$lang_dir'><a href='".generer_objet_url(
168 167
 				$id_rubrique2,
169 168
 				'rubrique'
170
-			) . "'>" . $rang2 . $titre2 . "</a></li>\n";
169
+			)."'>".$rang2.$titre2."</a></li>\n";
171 170
 		}
172 171
 	}
173 172
 
174
-	$retour = $pagination . $retour . $pagination;
173
+	$retour = $pagination.$retour.$pagination;
175 174
 
176 175
 	if (!$retour) {
177 176
 		return '';
@@ -180,7 +179,7 @@  discard block
 block discarded – undo
180 179
 	return debut_block_depliable($debut > 0 ? true : false, "enfants$collection2")
181 180
 	. "\n<ul class='liste-items sous-sous-rub'>\n"
182 181
 	. $retour
183
-	. "</ul>\n" . fin_block() . "\n\n";
182
+	. "</ul>\n".fin_block()."\n\n";
184 183
 }
185 184
 
186 185
 /**
@@ -199,13 +198,13 @@  discard block
 block discarded – undo
199 198
 	$debut = 0;
200 199
 	$limite = 500;
201 200
 
202
-	$nb = sql_countsel('spip_rubriques', 'id_parent=' . intval($id_rubrique));
201
+	$nb = sql_countsel('spip_rubriques', 'id_parent='.intval($id_rubrique));
203 202
 
204 203
 	if ($nb > $limite) {
205
-		$debut = _request('debut_rubrique' . $id_rubrique) ?: $debut;
204
+		$debut = _request('debut_rubrique'.$id_rubrique) ?: $debut;
206 205
 		$pagination = chercher_filtre('pagination');
207
-		$pagination = '<br class="nettoyeur"><nav class="pagination">' .
208
-			$pagination($nb, '_rubrique' . $id_rubrique, $debut, $limite, true, 'prive') .
206
+		$pagination = '<br class="nettoyeur"><nav class="pagination">'.
207
+			$pagination($nb, '_rubrique'.$id_rubrique, $debut, $limite, true, 'prive').
209 208
 		'</nav>';
210 209
 	}
211 210
 
Please login to merge, or discard this patch.
ecrire/public/decompiler.php 2 patches
Indentation   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -11,129 +11,129 @@  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
 // Decompilation de l'arbre de syntaxe abstraite d'un squelette SPIP
18 18
 
19 19
 function decompiler_boucle($struct, $fmt = '', $prof = 0) {
20
-	$nom = $struct->id_boucle;
21
-	$preaff = decompiler_($struct->preaff, $fmt, $prof);
22
-	$avant = decompiler_($struct->avant, $fmt, $prof);
23
-	$apres = decompiler_($struct->apres, $fmt, $prof);
24
-	$altern = decompiler_($struct->altern, $fmt, $prof);
25
-	$milieu = decompiler_($struct->milieu, $fmt, $prof);
26
-	$postaff = decompiler_($struct->postaff, $fmt, $prof);
27
-
28
-	$type = $struct->sql_serveur ? "$struct->sql_serveur:" : '';
29
-	$type .= ($struct->type_requete ?: $struct->table_optionnelle);
30
-
31
-	if ($struct->jointures_explicites) {
32
-		$type .= ' ' . $struct->jointures_explicites;
33
-	}
34
-	if ($struct->table_optionnelle) {
35
-		$type .= '?';
36
-	}
37
-	// Revoir le cas de la boucle recursive
38
-
39
-	$crit = $struct->param;
40
-	if ($crit and !is_array($crit[0])) {
41
-		$type = strtolower($type) . array_shift($crit);
42
-	}
43
-	$crit = decompiler_criteres($struct, $fmt, $prof);
44
-
45
-	$f = 'format_boucle_' . $fmt;
46
-
47
-	return $f($preaff, $avant, $nom, $type, $crit, $milieu, $apres, $altern, $postaff, $prof);
20
+    $nom = $struct->id_boucle;
21
+    $preaff = decompiler_($struct->preaff, $fmt, $prof);
22
+    $avant = decompiler_($struct->avant, $fmt, $prof);
23
+    $apres = decompiler_($struct->apres, $fmt, $prof);
24
+    $altern = decompiler_($struct->altern, $fmt, $prof);
25
+    $milieu = decompiler_($struct->milieu, $fmt, $prof);
26
+    $postaff = decompiler_($struct->postaff, $fmt, $prof);
27
+
28
+    $type = $struct->sql_serveur ? "$struct->sql_serveur:" : '';
29
+    $type .= ($struct->type_requete ?: $struct->table_optionnelle);
30
+
31
+    if ($struct->jointures_explicites) {
32
+        $type .= ' ' . $struct->jointures_explicites;
33
+    }
34
+    if ($struct->table_optionnelle) {
35
+        $type .= '?';
36
+    }
37
+    // Revoir le cas de la boucle recursive
38
+
39
+    $crit = $struct->param;
40
+    if ($crit and !is_array($crit[0])) {
41
+        $type = strtolower($type) . array_shift($crit);
42
+    }
43
+    $crit = decompiler_criteres($struct, $fmt, $prof);
44
+
45
+    $f = 'format_boucle_' . $fmt;
46
+
47
+    return $f($preaff, $avant, $nom, $type, $crit, $milieu, $apres, $altern, $postaff, $prof);
48 48
 }
49 49
 
50 50
 function decompiler_include($struct, $fmt = '', $prof = 0) {
51
-	$res = [];
52
-	foreach ($struct->param ?: [] as $couple) {
53
-		array_shift($couple);
54
-		foreach ($couple as $v) {
55
-			$res[] = decompiler_($v, $fmt, $prof);
56
-		}
57
-	}
58
-	$file = is_string($struct->texte) ? $struct->texte :
59
-		decompiler_($struct->texte, $fmt, $prof);
60
-	$f = 'format_inclure_' . $fmt;
61
-
62
-	return $f($file, $res, $prof);
51
+    $res = [];
52
+    foreach ($struct->param ?: [] as $couple) {
53
+        array_shift($couple);
54
+        foreach ($couple as $v) {
55
+            $res[] = decompiler_($v, $fmt, $prof);
56
+        }
57
+    }
58
+    $file = is_string($struct->texte) ? $struct->texte :
59
+        decompiler_($struct->texte, $fmt, $prof);
60
+    $f = 'format_inclure_' . $fmt;
61
+
62
+    return $f($file, $res, $prof);
63 63
 }
64 64
 
65 65
 function decompiler_texte($struct, $fmt = '', $prof = 0) {
66
-	$f = 'format_texte_' . $fmt;
66
+    $f = 'format_texte_' . $fmt;
67 67
 
68
-	return strlen($struct->texte) ? $f($struct->texte, $prof) : '';
68
+    return strlen($struct->texte) ? $f($struct->texte, $prof) : '';
69 69
 }
70 70
 
71 71
 function decompiler_polyglotte($struct, $fmt = '', $prof = 0) {
72
-	$f = 'format_polyglotte_' . $fmt;
72
+    $f = 'format_polyglotte_' . $fmt;
73 73
 
74
-	return $f($struct->traductions, $prof);
74
+    return $f($struct->traductions, $prof);
75 75
 }
76 76
 
77 77
 function decompiler_idiome($struct, $fmt = '', $prof = 0) {
78
-	$args = [];
79
-	foreach ($struct->arg as $k => $v) {
80
-		$args[$k] = public_decompiler($v, $fmt, $prof);
81
-	}
78
+    $args = [];
79
+    foreach ($struct->arg as $k => $v) {
80
+        $args[$k] = public_decompiler($v, $fmt, $prof);
81
+    }
82 82
 
83
-	$filtres = decompiler_liste($struct->param, $fmt, $prof);
83
+    $filtres = decompiler_liste($struct->param, $fmt, $prof);
84 84
 
85
-	$f = 'format_idiome_' . $fmt;
85
+    $f = 'format_idiome_' . $fmt;
86 86
 
87
-	return $f($struct->nom_champ, $struct->module, $args, $filtres, $prof);
87
+    return $f($struct->nom_champ, $struct->module, $args, $filtres, $prof);
88 88
 }
89 89
 
90 90
 function decompiler_champ($struct, $fmt = '', $prof = 0) {
91
-	$avant = decompiler_($struct->avant, $fmt, $prof);
92
-	$apres = decompiler_($struct->apres, $fmt, $prof);
93
-	$args = $filtres = '';
94
-	if ($p = $struct->param) {
95
-		if ($p[0][0] === '') {
96
-			$args = decompiler_liste([array_shift($p)], $fmt, $prof);
97
-		}
98
-		$filtres = decompiler_liste($p, $fmt, $prof);
99
-	}
100
-	$f = 'format_champ_' . $fmt;
101
-
102
-	return $f($struct->nom_champ, $struct->nom_boucle, $struct->etoile, $avant, $apres, $args, $filtres, $prof);
91
+    $avant = decompiler_($struct->avant, $fmt, $prof);
92
+    $apres = decompiler_($struct->apres, $fmt, $prof);
93
+    $args = $filtres = '';
94
+    if ($p = $struct->param) {
95
+        if ($p[0][0] === '') {
96
+            $args = decompiler_liste([array_shift($p)], $fmt, $prof);
97
+        }
98
+        $filtres = decompiler_liste($p, $fmt, $prof);
99
+    }
100
+    $f = 'format_champ_' . $fmt;
101
+
102
+    return $f($struct->nom_champ, $struct->nom_boucle, $struct->etoile, $avant, $apres, $args, $filtres, $prof);
103 103
 }
104 104
 
105 105
 function decompiler_liste($sources, $fmt = '', $prof = 0) {
106
-	if (!is_array($sources)) {
107
-		return '';
108
-	}
109
-	$f = 'format_liste_' . $fmt;
110
-	$res = '';
111
-	foreach ($sources as $arg) {
112
-		if (!is_array($arg)) {
113
-			continue; // ne devrait pas arriver.
114
-		} else {
115
-			$r = array_shift($arg);
116
-		}
117
-		$args = [];
118
-		foreach ($arg as $v) {
119
-			// cas des arguments entoures de ' ou "
120
-			if (
121
-				((is_countable($v) ? count($v) : 0) == 1)
122
-				and $v[0]->type == 'texte'
123
-				and (strlen($v[0]->apres) == 1)
124
-				and $v[0]->apres == $v[0]->avant
125
-			) {
126
-				$args[] = $v[0]->avant . $v[0]->texte . $v[0]->apres;
127
-			} else {
128
-				$args[] = decompiler_($v, $fmt, 0 - $prof);
129
-			}
130
-		}
131
-		if (($r !== '') or $args) {
132
-			$res .= $f($r, $args, $prof);
133
-		}
134
-	}
135
-
136
-	return $res;
106
+    if (!is_array($sources)) {
107
+        return '';
108
+    }
109
+    $f = 'format_liste_' . $fmt;
110
+    $res = '';
111
+    foreach ($sources as $arg) {
112
+        if (!is_array($arg)) {
113
+            continue; // ne devrait pas arriver.
114
+        } else {
115
+            $r = array_shift($arg);
116
+        }
117
+        $args = [];
118
+        foreach ($arg as $v) {
119
+            // cas des arguments entoures de ' ou "
120
+            if (
121
+                ((is_countable($v) ? count($v) : 0) == 1)
122
+                and $v[0]->type == 'texte'
123
+                and (strlen($v[0]->apres) == 1)
124
+                and $v[0]->apres == $v[0]->avant
125
+            ) {
126
+                $args[] = $v[0]->avant . $v[0]->texte . $v[0]->apres;
127
+            } else {
128
+                $args[] = decompiler_($v, $fmt, 0 - $prof);
129
+            }
130
+        }
131
+        if (($r !== '') or $args) {
132
+            $res .= $f($r, $args, $prof);
133
+        }
134
+    }
135
+
136
+    return $res;
137 137
 }
138 138
 
139 139
 // Decompilation des criteres: on triche et on deroge:
@@ -141,93 +141,93 @@  discard block
 block discarded – undo
141 141
 // - le champ apres signale le critere {"separateur"} ou {'separateur'}
142 142
 // - les champs sont implicitement etendus (crochets implicites mais interdits)
143 143
 function decompiler_criteres($boucle, $fmt = '', $prof = 0) {
144
-	$sources = $boucle->param;
145
-	if (!is_array($sources)) {
146
-		return '';
147
-	}
148
-	$res = '';
149
-	$f = 'format_critere_' . $fmt;
150
-	foreach ($sources as $crit) {
151
-		if (!is_array($crit)) {
152
-			continue;
153
-		} // boucle recursive
154
-		array_shift($crit);
155
-		$args = [];
156
-		foreach ($crit as $i => $v) {
157
-			if (
158
-				((is_countable($v) ? count($v) : 0) == 1)
159
-				and $v[0]->type == 'texte'
160
-				and $v[0]->apres
161
-			) {
162
-				$args[] = [['texte', ($v[0]->apres . $v[0]->texte . $v[0]->apres)]];
163
-			} else {
164
-				$res2 = [];
165
-				foreach ($v as $k => $p) {
166
-					if (
167
-						isset($p->type)
168
-						and function_exists($d = 'decompiler_' . $p->type)
169
-					) {
170
-						$r = $d($p, $fmt, (0 - $prof));
171
-						$res2[] = [$p->type, $r];
172
-					} else {
173
-						spip_log("critere $i / $k mal forme");
174
-					}
175
-				}
176
-				$args[] = $res2;
177
-			}
178
-		}
179
-		$res .= $f($args);
180
-	}
181
-
182
-	return $res;
144
+    $sources = $boucle->param;
145
+    if (!is_array($sources)) {
146
+        return '';
147
+    }
148
+    $res = '';
149
+    $f = 'format_critere_' . $fmt;
150
+    foreach ($sources as $crit) {
151
+        if (!is_array($crit)) {
152
+            continue;
153
+        } // boucle recursive
154
+        array_shift($crit);
155
+        $args = [];
156
+        foreach ($crit as $i => $v) {
157
+            if (
158
+                ((is_countable($v) ? count($v) : 0) == 1)
159
+                and $v[0]->type == 'texte'
160
+                and $v[0]->apres
161
+            ) {
162
+                $args[] = [['texte', ($v[0]->apres . $v[0]->texte . $v[0]->apres)]];
163
+            } else {
164
+                $res2 = [];
165
+                foreach ($v as $k => $p) {
166
+                    if (
167
+                        isset($p->type)
168
+                        and function_exists($d = 'decompiler_' . $p->type)
169
+                    ) {
170
+                        $r = $d($p, $fmt, (0 - $prof));
171
+                        $res2[] = [$p->type, $r];
172
+                    } else {
173
+                        spip_log("critere $i / $k mal forme");
174
+                    }
175
+                }
176
+                $args[] = $res2;
177
+            }
178
+        }
179
+        $res .= $f($args);
180
+    }
181
+
182
+    return $res;
183 183
 }
184 184
 
185 185
 
186 186
 function decompiler_($liste, $fmt = '', $prof = 0) {
187
-	if (!is_array($liste)) {
188
-		return '';
189
-	}
190
-	$prof2 = ($prof < 0) ? ($prof - 1) : ($prof + 1);
191
-	$contenu = [];
192
-	foreach ($liste as $k => $p) {
193
-		if (!isset($p->type)) {
194
-			continue;
195
-		} #??????
196
-		$d = 'decompiler_' . $p->type;
197
-		$next = $liste[$k + 1] ?? false;
198
-		// Forcer le champ etendu si son source (pas les reecritures)
199
-		// contenait des args et s'il est suivi d'espaces,
200
-		// le champ simple les eliminant est un bug helas perenne.
201
-
202
-		if (
203
-			$next
204
-			and ($next->type == 'texte')
205
-			and $p->type == 'champ'
206
-			and !$p->apres
207
-			and !$p->avant
208
-			and $p->fonctions
209
-		) {
210
-			$n = strlen($next->texte) - strlen(ltrim($next->texte));
211
-			if ($n) {
212
-				$champ = new Texte();
213
-				$champ->texte = substr($next->texte, 0, $n);
214
-				$champ->ligne = $p->ligne;
215
-				$p->apres = [$champ];
216
-				$next->texte = substr($next->texte, $n);
217
-			}
218
-		}
219
-		$contenu[] = [$d($p, $fmt, $prof2), $p->type];
220
-	}
221
-	$f = 'format_suite_' . $fmt;
222
-
223
-	return $f($contenu);
187
+    if (!is_array($liste)) {
188
+        return '';
189
+    }
190
+    $prof2 = ($prof < 0) ? ($prof - 1) : ($prof + 1);
191
+    $contenu = [];
192
+    foreach ($liste as $k => $p) {
193
+        if (!isset($p->type)) {
194
+            continue;
195
+        } #??????
196
+        $d = 'decompiler_' . $p->type;
197
+        $next = $liste[$k + 1] ?? false;
198
+        // Forcer le champ etendu si son source (pas les reecritures)
199
+        // contenait des args et s'il est suivi d'espaces,
200
+        // le champ simple les eliminant est un bug helas perenne.
201
+
202
+        if (
203
+            $next
204
+            and ($next->type == 'texte')
205
+            and $p->type == 'champ'
206
+            and !$p->apres
207
+            and !$p->avant
208
+            and $p->fonctions
209
+        ) {
210
+            $n = strlen($next->texte) - strlen(ltrim($next->texte));
211
+            if ($n) {
212
+                $champ = new Texte();
213
+                $champ->texte = substr($next->texte, 0, $n);
214
+                $champ->ligne = $p->ligne;
215
+                $p->apres = [$champ];
216
+                $next->texte = substr($next->texte, $n);
217
+            }
218
+        }
219
+        $contenu[] = [$d($p, $fmt, $prof2), $p->type];
220
+    }
221
+    $f = 'format_suite_' . $fmt;
222
+
223
+    return $f($contenu);
224 224
 }
225 225
 
226 226
 function public_decompiler($liste, $fmt = '', $prof = 0, $quoi = '') {
227
-	if (!include_spip('public/format_' . $fmt)) {
228
-		return "'$fmt'?";
229
-	}
230
-	$f = 'decompiler_' . $quoi;
227
+    if (!include_spip('public/format_' . $fmt)) {
228
+        return "'$fmt'?";
229
+    }
230
+    $f = 'decompiler_' . $quoi;
231 231
 
232
-	return $f($liste, $fmt, $prof);
232
+    return $f($liste, $fmt, $prof);
233 233
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -19 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
 	$type .= ($struct->type_requete ?: $struct->table_optionnelle);
30 30
 
31 31
 	if ($struct->jointures_explicites) {
32
-		$type .= ' ' . $struct->jointures_explicites;
32
+		$type .= ' '.$struct->jointures_explicites;
33 33
 	}
34 34
 	if ($struct->table_optionnelle) {
35 35
 		$type .= '?';
@@ -38,11 +38,11 @@  discard block
 block discarded – undo
38 38
 
39 39
 	$crit = $struct->param;
40 40
 	if ($crit and !is_array($crit[0])) {
41
-		$type = strtolower($type) . array_shift($crit);
41
+		$type = strtolower($type).array_shift($crit);
42 42
 	}
43 43
 	$crit = decompiler_criteres($struct, $fmt, $prof);
44 44
 
45
-	$f = 'format_boucle_' . $fmt;
45
+	$f = 'format_boucle_'.$fmt;
46 46
 
47 47
 	return $f($preaff, $avant, $nom, $type, $crit, $milieu, $apres, $altern, $postaff, $prof);
48 48
 }
@@ -55,21 +55,20 @@  discard block
 block discarded – undo
55 55
 			$res[] = decompiler_($v, $fmt, $prof);
56 56
 		}
57 57
 	}
58
-	$file = is_string($struct->texte) ? $struct->texte :
59
-		decompiler_($struct->texte, $fmt, $prof);
60
-	$f = 'format_inclure_' . $fmt;
58
+	$file = is_string($struct->texte) ? $struct->texte : decompiler_($struct->texte, $fmt, $prof);
59
+	$f = 'format_inclure_'.$fmt;
61 60
 
62 61
 	return $f($file, $res, $prof);
63 62
 }
64 63
 
65 64
 function decompiler_texte($struct, $fmt = '', $prof = 0) {
66
-	$f = 'format_texte_' . $fmt;
65
+	$f = 'format_texte_'.$fmt;
67 66
 
68 67
 	return strlen($struct->texte) ? $f($struct->texte, $prof) : '';
69 68
 }
70 69
 
71 70
 function decompiler_polyglotte($struct, $fmt = '', $prof = 0) {
72
-	$f = 'format_polyglotte_' . $fmt;
71
+	$f = 'format_polyglotte_'.$fmt;
73 72
 
74 73
 	return $f($struct->traductions, $prof);
75 74
 }
@@ -82,7 +81,7 @@  discard block
 block discarded – undo
82 81
 
83 82
 	$filtres = decompiler_liste($struct->param, $fmt, $prof);
84 83
 
85
-	$f = 'format_idiome_' . $fmt;
84
+	$f = 'format_idiome_'.$fmt;
86 85
 
87 86
 	return $f($struct->nom_champ, $struct->module, $args, $filtres, $prof);
88 87
 }
@@ -97,7 +96,7 @@  discard block
 block discarded – undo
97 96
 		}
98 97
 		$filtres = decompiler_liste($p, $fmt, $prof);
99 98
 	}
100
-	$f = 'format_champ_' . $fmt;
99
+	$f = 'format_champ_'.$fmt;
101 100
 
102 101
 	return $f($struct->nom_champ, $struct->nom_boucle, $struct->etoile, $avant, $apres, $args, $filtres, $prof);
103 102
 }
@@ -106,7 +105,7 @@  discard block
 block discarded – undo
106 105
 	if (!is_array($sources)) {
107 106
 		return '';
108 107
 	}
109
-	$f = 'format_liste_' . $fmt;
108
+	$f = 'format_liste_'.$fmt;
110 109
 	$res = '';
111 110
 	foreach ($sources as $arg) {
112 111
 		if (!is_array($arg)) {
@@ -123,7 +122,7 @@  discard block
 block discarded – undo
123 122
 				and (strlen($v[0]->apres) == 1)
124 123
 				and $v[0]->apres == $v[0]->avant
125 124
 			) {
126
-				$args[] = $v[0]->avant . $v[0]->texte . $v[0]->apres;
125
+				$args[] = $v[0]->avant.$v[0]->texte.$v[0]->apres;
127 126
 			} else {
128 127
 				$args[] = decompiler_($v, $fmt, 0 - $prof);
129 128
 			}
@@ -146,7 +145,7 @@  discard block
 block discarded – undo
146 145
 		return '';
147 146
 	}
148 147
 	$res = '';
149
-	$f = 'format_critere_' . $fmt;
148
+	$f = 'format_critere_'.$fmt;
150 149
 	foreach ($sources as $crit) {
151 150
 		if (!is_array($crit)) {
152 151
 			continue;
@@ -159,13 +158,13 @@  discard block
 block discarded – undo
159 158
 				and $v[0]->type == 'texte'
160 159
 				and $v[0]->apres
161 160
 			) {
162
-				$args[] = [['texte', ($v[0]->apres . $v[0]->texte . $v[0]->apres)]];
161
+				$args[] = [['texte', ($v[0]->apres.$v[0]->texte.$v[0]->apres)]];
163 162
 			} else {
164 163
 				$res2 = [];
165 164
 				foreach ($v as $k => $p) {
166 165
 					if (
167 166
 						isset($p->type)
168
-						and function_exists($d = 'decompiler_' . $p->type)
167
+						and function_exists($d = 'decompiler_'.$p->type)
169 168
 					) {
170 169
 						$r = $d($p, $fmt, (0 - $prof));
171 170
 						$res2[] = [$p->type, $r];
@@ -193,7 +192,7 @@  discard block
 block discarded – undo
193 192
 		if (!isset($p->type)) {
194 193
 			continue;
195 194
 		} #??????
196
-		$d = 'decompiler_' . $p->type;
195
+		$d = 'decompiler_'.$p->type;
197 196
 		$next = $liste[$k + 1] ?? false;
198 197
 		// Forcer le champ etendu si son source (pas les reecritures)
199 198
 		// contenait des args et s'il est suivi d'espaces,
@@ -218,16 +217,16 @@  discard block
 block discarded – undo
218 217
 		}
219 218
 		$contenu[] = [$d($p, $fmt, $prof2), $p->type];
220 219
 	}
221
-	$f = 'format_suite_' . $fmt;
220
+	$f = 'format_suite_'.$fmt;
222 221
 
223 222
 	return $f($contenu);
224 223
 }
225 224
 
226 225
 function public_decompiler($liste, $fmt = '', $prof = 0, $quoi = '') {
227
-	if (!include_spip('public/format_' . $fmt)) {
226
+	if (!include_spip('public/format_'.$fmt)) {
228 227
 		return "'$fmt'?";
229 228
 	}
230
-	$f = 'decompiler_' . $quoi;
229
+	$f = 'decompiler_'.$quoi;
231 230
 
232 231
 	return $f($liste, $fmt, $prof);
233 232
 }
Please login to merge, or discard this patch.
ecrire/inc/queue.php 2 patches
Indentation   +476 added lines, -476 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Queue
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 define('_JQ_SCHEDULED', 1);
@@ -50,103 +50,103 @@  discard block
 block discarded – undo
50 50
  *  id of job
51 51
  */
52 52
 function queue_add_job(
53
-	$function,
54
-	$description,
55
-	$arguments = [],
56
-	$file = '',
57
-	$no_duplicate = false,
58
-	$time = 0,
59
-	$priority = 0
53
+    $function,
54
+    $description,
55
+    $arguments = [],
56
+    $file = '',
57
+    $no_duplicate = false,
58
+    $time = 0,
59
+    $priority = 0
60 60
 ) {
61
-	include_spip('base/abstract_sql');
62
-
63
-	// cas pourri de ecrire/action/editer_site avec l'option reload=oui
64
-	if (defined('_GENIE_SYNDIC_NOW')) {
65
-		$arguments['id_syndic'] = _GENIE_SYNDIC_NOW;
66
-	}
67
-
68
-	// serialiser les arguments
69
-	$arguments = serialize($arguments);
70
-	$md5args = md5($arguments);
71
-
72
-	// si pas de date programee, des que possible
73
-	$duplicate_where = 'status=' . intval(_JQ_SCHEDULED) . ' AND ';
74
-	if (!$time) {
75
-		$time = time();
76
-		$duplicate_where = ''; // ne pas dupliquer si deja le meme job en cours d'execution
77
-	}
78
-	$date = date('Y-m-d H:i:s', $time);
79
-
80
-	$set_job = [
81
-		'fonction' => $function,
82
-		'descriptif' => $description,
83
-		'args' => $arguments,
84
-		'md5args' => $md5args,
85
-		'inclure' => $file,
86
-		'priorite' => max(-10, min(10, intval($priority))),
87
-		'date' => $date,
88
-		'status' => _JQ_SCHEDULED,
89
-	];
90
-	// si option ne pas dupliquer, regarder si la fonction existe deja
91
-	// avec les memes args et file
92
-	if (
93
-		$no_duplicate
94
-		and
95
-		$id_job = sql_getfetsel(
96
-			'id_job',
97
-			'spip_jobs',
98
-			$duplicate_where =
99
-				$duplicate_where . 'fonction=' . sql_quote($function)
100
-				. (($no_duplicate === 'function_only') ? '' :
101
-			' AND md5args=' . sql_quote($md5args) . ' AND inclure=' . sql_quote($file))
102
-		)
103
-	) {
104
-		return $id_job;
105
-	}
106
-
107
-	$id_job = sql_insertq('spip_jobs', $set_job);
108
-	// en cas de concurrence, deux process peuvent arriver jusqu'ici en parallele
109
-	// avec le meme job unique a inserer. Dans ce cas, celui qui a eu l'id le plus grand
110
-	// doit s'effacer
111
-	if (
112
-		$no_duplicate
113
-		and
114
-		$id_prev = sql_getfetsel('id_job', 'spip_jobs', 'id_job<' . intval($id_job) . " AND $duplicate_where")
115
-	) {
116
-		sql_delete('spip_jobs', 'id_job=' . intval($id_job));
117
-
118
-		return $id_prev;
119
-	}
120
-
121
-	// verifier la non duplication qui peut etre problematique en cas de concurence
122
-	// il faut dans ce cas que seul le dernier ajoute se supprime !
123
-
124
-	// une option de debug pour verifier que les arguments en base sont bons
125
-	// ie cas d'un char non acceptables sur certains type de champs
126
-	// qui coupe la valeur
127
-	if (defined('_JQ_INSERT_CHECK_ARGS') and $id_job) {
128
-		$args = sql_getfetsel('args', 'spip_jobs', 'id_job=' . intval($id_job));
129
-		if ($args !== $arguments) {
130
-			spip_log('arguments job errones / longueur ' . strlen($args) . ' vs ' . strlen($arguments) . ' / valeur : ' . var_export(
131
-				$arguments,
132
-				true
133
-			), 'queue');
134
-		}
135
-	}
136
-
137
-	if ($id_job) {
138
-		queue_update_next_job_time($time);
139
-	}
140
-	// si la mise en file d'attente du job echoue,
141
-	// il ne faut pas perdre l'execution de la fonction
142
-	// on la lance immediatement, c'est un fallback
143
-	// sauf en cas d'upgrade necessaire (table spip_jobs inexistante)
144
-	elseif ($GLOBALS['meta']['version_installee'] == $GLOBALS['spip_version_base']) {
145
-		$set_job['id_job'] = 0;
146
-		queue_start_job($set_job);
147
-	}
148
-
149
-	return $id_job;
61
+    include_spip('base/abstract_sql');
62
+
63
+    // cas pourri de ecrire/action/editer_site avec l'option reload=oui
64
+    if (defined('_GENIE_SYNDIC_NOW')) {
65
+        $arguments['id_syndic'] = _GENIE_SYNDIC_NOW;
66
+    }
67
+
68
+    // serialiser les arguments
69
+    $arguments = serialize($arguments);
70
+    $md5args = md5($arguments);
71
+
72
+    // si pas de date programee, des que possible
73
+    $duplicate_where = 'status=' . intval(_JQ_SCHEDULED) . ' AND ';
74
+    if (!$time) {
75
+        $time = time();
76
+        $duplicate_where = ''; // ne pas dupliquer si deja le meme job en cours d'execution
77
+    }
78
+    $date = date('Y-m-d H:i:s', $time);
79
+
80
+    $set_job = [
81
+        'fonction' => $function,
82
+        'descriptif' => $description,
83
+        'args' => $arguments,
84
+        'md5args' => $md5args,
85
+        'inclure' => $file,
86
+        'priorite' => max(-10, min(10, intval($priority))),
87
+        'date' => $date,
88
+        'status' => _JQ_SCHEDULED,
89
+    ];
90
+    // si option ne pas dupliquer, regarder si la fonction existe deja
91
+    // avec les memes args et file
92
+    if (
93
+        $no_duplicate
94
+        and
95
+        $id_job = sql_getfetsel(
96
+            'id_job',
97
+            'spip_jobs',
98
+            $duplicate_where =
99
+                $duplicate_where . 'fonction=' . sql_quote($function)
100
+                . (($no_duplicate === 'function_only') ? '' :
101
+            ' AND md5args=' . sql_quote($md5args) . ' AND inclure=' . sql_quote($file))
102
+        )
103
+    ) {
104
+        return $id_job;
105
+    }
106
+
107
+    $id_job = sql_insertq('spip_jobs', $set_job);
108
+    // en cas de concurrence, deux process peuvent arriver jusqu'ici en parallele
109
+    // avec le meme job unique a inserer. Dans ce cas, celui qui a eu l'id le plus grand
110
+    // doit s'effacer
111
+    if (
112
+        $no_duplicate
113
+        and
114
+        $id_prev = sql_getfetsel('id_job', 'spip_jobs', 'id_job<' . intval($id_job) . " AND $duplicate_where")
115
+    ) {
116
+        sql_delete('spip_jobs', 'id_job=' . intval($id_job));
117
+
118
+        return $id_prev;
119
+    }
120
+
121
+    // verifier la non duplication qui peut etre problematique en cas de concurence
122
+    // il faut dans ce cas que seul le dernier ajoute se supprime !
123
+
124
+    // une option de debug pour verifier que les arguments en base sont bons
125
+    // ie cas d'un char non acceptables sur certains type de champs
126
+    // qui coupe la valeur
127
+    if (defined('_JQ_INSERT_CHECK_ARGS') and $id_job) {
128
+        $args = sql_getfetsel('args', 'spip_jobs', 'id_job=' . intval($id_job));
129
+        if ($args !== $arguments) {
130
+            spip_log('arguments job errones / longueur ' . strlen($args) . ' vs ' . strlen($arguments) . ' / valeur : ' . var_export(
131
+                $arguments,
132
+                true
133
+            ), 'queue');
134
+        }
135
+    }
136
+
137
+    if ($id_job) {
138
+        queue_update_next_job_time($time);
139
+    }
140
+    // si la mise en file d'attente du job echoue,
141
+    // il ne faut pas perdre l'execution de la fonction
142
+    // on la lance immediatement, c'est un fallback
143
+    // sauf en cas d'upgrade necessaire (table spip_jobs inexistante)
144
+    elseif ($GLOBALS['meta']['version_installee'] == $GLOBALS['spip_version_base']) {
145
+        $set_job['id_job'] = 0;
146
+        queue_start_job($set_job);
147
+    }
148
+
149
+    return $id_job;
150 150
 }
151 151
 
152 152
 /**
@@ -155,11 +155,11 @@  discard block
 block discarded – undo
155 155
  * @return void
156 156
  */
157 157
 function queue_purger() {
158
-	include_spip('base/abstract_sql');
159
-	sql_delete('spip_jobs');
160
-	sql_delete('spip_jobs_liens', 'id_job NOT IN (' . sql_get_select('id_job', 'spip_jobs') . ')');
161
-	include_spip('inc/genie');
162
-	genie_queue_watch_dist();
158
+    include_spip('base/abstract_sql');
159
+    sql_delete('spip_jobs');
160
+    sql_delete('spip_jobs_liens', 'id_job NOT IN (' . sql_get_select('id_job', 'spip_jobs') . ')');
161
+    include_spip('inc/genie');
162
+    genie_queue_watch_dist();
163 163
 }
164 164
 
165 165
 /**
@@ -170,25 +170,25 @@  discard block
 block discarded – undo
170 170
  * @return int|bool
171 171
  */
172 172
 function queue_remove_job($id_job) {
173
-	include_spip('base/abstract_sql');
174
-
175
-	if (
176
-		$row = sql_fetsel('fonction,inclure,date', 'spip_jobs', 'id_job=' . intval($id_job))
177
-		and $res = sql_delete('spip_jobs', 'id_job=' . intval($id_job))
178
-	) {
179
-		queue_unlink_job($id_job);
180
-		// est-ce une tache cron qu'il faut relancer ?
181
-		if ($periode = queue_is_cron_job($row['fonction'], $row['inclure'])) {
182
-			// relancer avec les nouveaux arguments de temps
183
-			include_spip('inc/genie');
184
-			// relancer avec la periode prevue
185
-			queue_genie_replan_job($row['fonction'], $periode, strtotime($row['date']));
186
-		}
187
-		queue_update_next_job_time();
188
-		return $res;
189
-	}
190
-
191
-	return false;
173
+    include_spip('base/abstract_sql');
174
+
175
+    if (
176
+        $row = sql_fetsel('fonction,inclure,date', 'spip_jobs', 'id_job=' . intval($id_job))
177
+        and $res = sql_delete('spip_jobs', 'id_job=' . intval($id_job))
178
+    ) {
179
+        queue_unlink_job($id_job);
180
+        // est-ce une tache cron qu'il faut relancer ?
181
+        if ($periode = queue_is_cron_job($row['fonction'], $row['inclure'])) {
182
+            // relancer avec les nouveaux arguments de temps
183
+            include_spip('inc/genie');
184
+            // relancer avec la periode prevue
185
+            queue_genie_replan_job($row['fonction'], $periode, strtotime($row['date']));
186
+        }
187
+        queue_update_next_job_time();
188
+        return $res;
189
+    }
190
+
191
+    return false;
192 192
 }
193 193
 
194 194
 /**
@@ -201,18 +201,18 @@  discard block
 block discarded – undo
201 201
  *  ou un tableau composé de tableaux simples pour lieur plusieurs objets en une fois
202 202
  */
203 203
 function queue_link_job($id_job, $objets) {
204
-	include_spip('base/abstract_sql');
205
-
206
-	if (is_array($objets) and count($objets)) {
207
-		if (is_array(reset($objets))) {
208
-			foreach ($objets as $k => $o) {
209
-				$objets[$k]['id_job'] = $id_job;
210
-			}
211
-			sql_insertq_multi('spip_jobs_liens', $objets);
212
-		} else {
213
-			sql_insertq('spip_jobs_liens', array_merge(['id_job' => $id_job], $objets));
214
-		}
215
-	}
204
+    include_spip('base/abstract_sql');
205
+
206
+    if (is_array($objets) and count($objets)) {
207
+        if (is_array(reset($objets))) {
208
+            foreach ($objets as $k => $o) {
209
+                $objets[$k]['id_job'] = $id_job;
210
+            }
211
+            sql_insertq_multi('spip_jobs_liens', $objets);
212
+        } else {
213
+            sql_insertq('spip_jobs_liens', array_merge(['id_job' => $id_job], $objets));
214
+        }
215
+    }
216 216
 }
217 217
 
218 218
 /**
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
  *  resultat du sql_delete
225 225
  */
226 226
 function queue_unlink_job($id_job) {
227
-	return sql_delete('spip_jobs_liens', 'id_job=' . intval($id_job));
227
+    return sql_delete('spip_jobs_liens', 'id_job=' . intval($id_job));
228 228
 }
229 229
 
230 230
 /**
@@ -237,36 +237,36 @@  discard block
 block discarded – undo
237 237
  */
238 238
 function queue_start_job($row) {
239 239
 
240
-	// deserialiser les arguments
241
-	$args = unserialize($row['args']);
242
-	if (!is_array($args)) {
243
-		spip_log('arguments job errones ' . var_export($row, true), 'queue');
244
-		$args = [];
245
-	}
246
-
247
-	$fonction = $row['fonction'];
248
-	if (strlen($inclure = trim($row['inclure']))) {
249
-		if (substr($inclure, -1) == '/') { // c'est un chemin pour charger_fonction
250
-			$f = charger_fonction($fonction, rtrim($inclure, '/'), false);
251
-			if ($f) {
252
-				$fonction = $f;
253
-			}
254
-		} else {
255
-			include_spip($inclure);
256
-		}
257
-	}
258
-
259
-	if (!function_exists($fonction)) {
260
-		spip_log("fonction $fonction ($inclure) inexistante " . var_export($row, true), 'queue');
261
-
262
-		return false;
263
-	}
264
-
265
-	spip_log('queue [' . $row['id_job'] . "]: $fonction() start", 'queue');
266
-	$res = $fonction(...$args);
267
-	spip_log('queue [' . $row['id_job'] . "]: $fonction() end", 'queue');
268
-
269
-	return $res;
240
+    // deserialiser les arguments
241
+    $args = unserialize($row['args']);
242
+    if (!is_array($args)) {
243
+        spip_log('arguments job errones ' . var_export($row, true), 'queue');
244
+        $args = [];
245
+    }
246
+
247
+    $fonction = $row['fonction'];
248
+    if (strlen($inclure = trim($row['inclure']))) {
249
+        if (substr($inclure, -1) == '/') { // c'est un chemin pour charger_fonction
250
+            $f = charger_fonction($fonction, rtrim($inclure, '/'), false);
251
+            if ($f) {
252
+                $fonction = $f;
253
+            }
254
+        } else {
255
+            include_spip($inclure);
256
+        }
257
+    }
258
+
259
+    if (!function_exists($fonction)) {
260
+        spip_log("fonction $fonction ($inclure) inexistante " . var_export($row, true), 'queue');
261
+
262
+        return false;
263
+    }
264
+
265
+    spip_log('queue [' . $row['id_job'] . "]: $fonction() start", 'queue');
266
+    $res = $fonction(...$args);
267
+    spip_log('queue [' . $row['id_job'] . "]: $fonction() end", 'queue');
268
+
269
+    return $res;
270 270
 }
271 271
 
272 272
 /**
@@ -293,89 +293,89 @@  discard block
 block discarded – undo
293 293
  *     - true : une planification a été faite.
294 294
  */
295 295
 function queue_schedule($force_jobs = null) {
296
-	$time = time();
297
-	if (defined('_DEBUG_BLOCK_QUEUE')) {
298
-		spip_log('_DEBUG_BLOCK_QUEUE : schedule stop', 'jq' . _LOG_DEBUG);
299
-
300
-		return;
301
-	}
302
-
303
-	// rien a faire si le prochain job est encore dans le futur
304
-	if (queue_sleep_time_to_next_job() > 0 and (!$force_jobs or !count($force_jobs))) {
305
-		spip_log('queue_sleep_time_to_next_job', 'jq' . _LOG_DEBUG);
306
-
307
-		return;
308
-	}
309
-
310
-	include_spip('base/abstract_sql');
311
-	// on ne peut rien faire si pas de connexion SQL
312
-	if (!spip_connect()) {
313
-		return false;
314
-	}
315
-
316
-	if (!defined('_JQ_MAX_JOBS_TIME_TO_EXECUTE')) {
317
-		$max_time = ini_get('max_execution_time') / 2;
318
-		// valeur conservatrice si on a pas reussi a lire le max_execution_time
319
-		if (!$max_time) {
320
-			$max_time = 5;
321
-		}
322
-		define('_JQ_MAX_JOBS_TIME_TO_EXECUTE', min($max_time, 15)); // une valeur maxi en temps.
323
-	}
324
-	$end_time = $time + _JQ_MAX_JOBS_TIME_TO_EXECUTE;
325
-
326
-	spip_log("JQ schedule $time / $end_time", 'jq' . _LOG_DEBUG);
327
-
328
-	if (!defined('_JQ_MAX_JOBS_EXECUTE')) {
329
-		define('_JQ_MAX_JOBS_EXECUTE', 200);
330
-	}
331
-	$nbj = 0;
332
-	// attraper les jobs
333
-	// dont la date est passee (echus en attente),
334
-	// par ordre :
335
-	//	- de priorite
336
-	//	- de date
337
-	// lorsqu'un job cron n'a pas fini, sa priorite est descendue
338
-	// pour qu'il ne bloque pas les autres jobs en attente
339
-	if (is_array($force_jobs) and count($force_jobs)) {
340
-		$cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND ' . sql_in('id_job', $force_jobs);
341
-	} else {
342
-		$now = date('Y-m-d H:i:s', $time);
343
-		$cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND date<=' . sql_quote($now);
344
-	}
345
-
346
-	register_shutdown_function('queue_error_handler'); // recuperer les erreurs auant que possible
347
-	$res = sql_allfetsel('*', 'spip_jobs', $cond, '', 'priorite DESC,date', '0,' . (_JQ_MAX_JOBS_EXECUTE + 1));
348
-	do {
349
-		if ($row = array_shift($res)) {
350
-			$nbj++;
351
-			// il faut un verrou, a base de sql_delete
352
-			if (sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']) . ' AND status=' . intval(_JQ_SCHEDULED))) {
353
-				#spip_log("JQ schedule job ".$nbj." OK",'jq');
354
-				// on reinsert dans la base aussitot avec un status=_JQ_PENDING
355
-				$row['status'] = _JQ_PENDING;
356
-				$row['date'] = date('Y-m-d H:i:s', $time);
357
-				sql_insertq('spip_jobs', $row);
358
-
359
-				// on a la main sur le job :
360
-				// l'executer
361
-				$result = queue_start_job($row);
362
-
363
-				$time = time();
364
-				queue_close_job($row, $time, $result);
365
-			}
366
-		}
367
-		spip_log('JQ schedule job end time ' . $time, 'jq' . _LOG_DEBUG);
368
-	} while ($nbj < _JQ_MAX_JOBS_EXECUTE and $row and $time < $end_time);
369
-	spip_log('JQ schedule end time ' . time(), 'jq' . _LOG_DEBUG);
370
-
371
-	if ($row = array_shift($res)) {
372
-		queue_update_next_job_time(0); // on sait qu'il y a encore des jobs a lancer ASAP
373
-		spip_log('JQ encore !', 'jq' . _LOG_DEBUG);
374
-	} else {
375
-		queue_update_next_job_time();
376
-	}
377
-
378
-	return true;
296
+    $time = time();
297
+    if (defined('_DEBUG_BLOCK_QUEUE')) {
298
+        spip_log('_DEBUG_BLOCK_QUEUE : schedule stop', 'jq' . _LOG_DEBUG);
299
+
300
+        return;
301
+    }
302
+
303
+    // rien a faire si le prochain job est encore dans le futur
304
+    if (queue_sleep_time_to_next_job() > 0 and (!$force_jobs or !count($force_jobs))) {
305
+        spip_log('queue_sleep_time_to_next_job', 'jq' . _LOG_DEBUG);
306
+
307
+        return;
308
+    }
309
+
310
+    include_spip('base/abstract_sql');
311
+    // on ne peut rien faire si pas de connexion SQL
312
+    if (!spip_connect()) {
313
+        return false;
314
+    }
315
+
316
+    if (!defined('_JQ_MAX_JOBS_TIME_TO_EXECUTE')) {
317
+        $max_time = ini_get('max_execution_time') / 2;
318
+        // valeur conservatrice si on a pas reussi a lire le max_execution_time
319
+        if (!$max_time) {
320
+            $max_time = 5;
321
+        }
322
+        define('_JQ_MAX_JOBS_TIME_TO_EXECUTE', min($max_time, 15)); // une valeur maxi en temps.
323
+    }
324
+    $end_time = $time + _JQ_MAX_JOBS_TIME_TO_EXECUTE;
325
+
326
+    spip_log("JQ schedule $time / $end_time", 'jq' . _LOG_DEBUG);
327
+
328
+    if (!defined('_JQ_MAX_JOBS_EXECUTE')) {
329
+        define('_JQ_MAX_JOBS_EXECUTE', 200);
330
+    }
331
+    $nbj = 0;
332
+    // attraper les jobs
333
+    // dont la date est passee (echus en attente),
334
+    // par ordre :
335
+    //	- de priorite
336
+    //	- de date
337
+    // lorsqu'un job cron n'a pas fini, sa priorite est descendue
338
+    // pour qu'il ne bloque pas les autres jobs en attente
339
+    if (is_array($force_jobs) and count($force_jobs)) {
340
+        $cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND ' . sql_in('id_job', $force_jobs);
341
+    } else {
342
+        $now = date('Y-m-d H:i:s', $time);
343
+        $cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND date<=' . sql_quote($now);
344
+    }
345
+
346
+    register_shutdown_function('queue_error_handler'); // recuperer les erreurs auant que possible
347
+    $res = sql_allfetsel('*', 'spip_jobs', $cond, '', 'priorite DESC,date', '0,' . (_JQ_MAX_JOBS_EXECUTE + 1));
348
+    do {
349
+        if ($row = array_shift($res)) {
350
+            $nbj++;
351
+            // il faut un verrou, a base de sql_delete
352
+            if (sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']) . ' AND status=' . intval(_JQ_SCHEDULED))) {
353
+                #spip_log("JQ schedule job ".$nbj." OK",'jq');
354
+                // on reinsert dans la base aussitot avec un status=_JQ_PENDING
355
+                $row['status'] = _JQ_PENDING;
356
+                $row['date'] = date('Y-m-d H:i:s', $time);
357
+                sql_insertq('spip_jobs', $row);
358
+
359
+                // on a la main sur le job :
360
+                // l'executer
361
+                $result = queue_start_job($row);
362
+
363
+                $time = time();
364
+                queue_close_job($row, $time, $result);
365
+            }
366
+        }
367
+        spip_log('JQ schedule job end time ' . $time, 'jq' . _LOG_DEBUG);
368
+    } while ($nbj < _JQ_MAX_JOBS_EXECUTE and $row and $time < $end_time);
369
+    spip_log('JQ schedule end time ' . time(), 'jq' . _LOG_DEBUG);
370
+
371
+    if ($row = array_shift($res)) {
372
+        queue_update_next_job_time(0); // on sait qu'il y a encore des jobs a lancer ASAP
373
+        spip_log('JQ encore !', 'jq' . _LOG_DEBUG);
374
+    } else {
375
+        queue_update_next_job_time();
376
+    }
377
+
378
+    return true;
379 379
 }
380 380
 
381 381
 /**
@@ -393,21 +393,21 @@  discard block
 block discarded – undo
393 393
  * @param int $result
394 394
  */
395 395
 function queue_close_job(&$row, $time, $result = 0) {
396
-	// est-ce une tache cron qu'il faut relancer ?
397
-	if ($periode = queue_is_cron_job($row['fonction'], $row['inclure'])) {
398
-		// relancer avec les nouveaux arguments de temps
399
-		include_spip('inc/genie');
400
-		if ($result < 0) { // relancer tout de suite, mais en baissant la priorite
401
-		queue_genie_replan_job($row['fonction'], $periode, 0 - $result, null, $row['priorite'] - 1);
402
-		} else // relancer avec la periode prevue
403
-		{
404
-			queue_genie_replan_job($row['fonction'], $periode, $time);
405
-		}
406
-	}
407
-	// purger ses liens eventuels avec des objets
408
-	sql_delete('spip_jobs_liens', 'id_job=' . intval($row['id_job']));
409
-	// supprimer le job fini
410
-	sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']));
396
+    // est-ce une tache cron qu'il faut relancer ?
397
+    if ($periode = queue_is_cron_job($row['fonction'], $row['inclure'])) {
398
+        // relancer avec les nouveaux arguments de temps
399
+        include_spip('inc/genie');
400
+        if ($result < 0) { // relancer tout de suite, mais en baissant la priorite
401
+        queue_genie_replan_job($row['fonction'], $periode, 0 - $result, null, $row['priorite'] - 1);
402
+        } else // relancer avec la periode prevue
403
+        {
404
+            queue_genie_replan_job($row['fonction'], $periode, $time);
405
+        }
406
+    }
407
+    // purger ses liens eventuels avec des objets
408
+    sql_delete('spip_jobs_liens', 'id_job=' . intval($row['id_job']));
409
+    // supprimer le job fini
410
+    sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']));
411 411
 }
412 412
 
413 413
 /**
@@ -417,10 +417,10 @@  discard block
 block discarded – undo
417 417
  * @uses queue_update_next_job_time()
418 418
  */
419 419
 function queue_error_handler() {
420
-	// se remettre dans le bon dossier, car Apache le change parfois (toujours?)
421
-	chdir(_ROOT_CWD);
420
+    // se remettre dans le bon dossier, car Apache le change parfois (toujours?)
421
+    chdir(_ROOT_CWD);
422 422
 
423
-	queue_update_next_job_time();
423
+    queue_update_next_job_time();
424 424
 }
425 425
 
426 426
 
@@ -437,18 +437,18 @@  discard block
 block discarded – undo
437 437
  *     Périodicité de la tâche en secondes, si tâche périodique, sinon false.
438 438
  */
439 439
 function queue_is_cron_job($function, $inclure) {
440
-	static $taches = null;
441
-	if (strncmp($inclure, 'genie/', 6) == 0) {
442
-		if (is_null($taches)) {
443
-			include_spip('inc/genie');
444
-			$taches = taches_generales();
445
-		}
446
-		if (isset($taches[$function])) {
447
-			return $taches[$function];
448
-		}
449
-	}
450
-
451
-	return false;
440
+    static $taches = null;
441
+    if (strncmp($inclure, 'genie/', 6) == 0) {
442
+        if (is_null($taches)) {
443
+            include_spip('inc/genie');
444
+            $taches = taches_generales();
445
+        }
446
+        if (isset($taches[$function])) {
447
+            return $taches[$function];
448
+        }
449
+    }
450
+
451
+    return false;
452 452
 }
453 453
 
454 454
 /**
@@ -462,62 +462,62 @@  discard block
 block discarded – undo
462 462
  *  temps de la tache ajoutee ou 0 pour ASAP
463 463
  */
464 464
 function queue_update_next_job_time($next_time = null) {
465
-	static $nb_jobs_scheduled = null;
466
-	static $deja_la = false;
467
-	// prendre le min des $next_time que l'on voit passer ici, en cas de reentrance
468
-	static $next = null;
469
-	// queue_close_job peut etre reentrant ici
470
-	if ($deja_la) {
471
-		return;
472
-	}
473
-	$deja_la = true;
474
-
475
-	include_spip('base/abstract_sql');
476
-	$time = time();
477
-
478
-	// traiter les jobs morts au combat (_JQ_PENDING depuis plus de 180s)
479
-	// pour cause de timeout ou autre erreur fatale
480
-	$res = sql_allfetsel(
481
-		'*',
482
-		'spip_jobs',
483
-		'status=' . intval(_JQ_PENDING) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time - 180))
484
-	);
485
-	if (is_array($res)) {
486
-		foreach ($res as $row) {
487
-			queue_close_job($row, $time);
488
-			spip_log('queue_close_job car _JQ_PENDING depuis +180s : ' . print_r($row, 1), 'job_mort' . _LOG_ERREUR);
489
-		}
490
-	}
491
-
492
-	// chercher la date du prochain job si pas connu
493
-	if (is_null($next) or is_null(queue_sleep_time_to_next_job())) {
494
-		$date = sql_getfetsel('date', 'spip_jobs', 'status=' . intval(_JQ_SCHEDULED), '', 'date', '0,1');
495
-		$next = strtotime($date);
496
-	}
497
-	if (!is_null($next_time)) {
498
-		if (is_null($next) or $next > $next_time) {
499
-			$next = $next_time;
500
-		}
501
-	}
502
-
503
-	if ($next) {
504
-		if (is_null($nb_jobs_scheduled)) {
505
-			$nb_jobs_scheduled = sql_countsel(
506
-				'spip_jobs',
507
-				'status=' . intval(_JQ_SCHEDULED) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time))
508
-			);
509
-		} elseif ($next <= $time) {
510
-			$nb_jobs_scheduled++;
511
-		}
512
-		// si trop de jobs en attente, on force la purge en fin de hit
513
-		// pour assurer le coup
514
-		if ($nb_jobs_scheduled > (defined('_JQ_NB_JOBS_OVERFLOW') ? _JQ_NB_JOBS_OVERFLOW : 10000)) {
515
-			define('_DIRECT_CRON_FORCE', true);
516
-		}
517
-	}
518
-
519
-	queue_set_next_job_time($next);
520
-	$deja_la = false;
465
+    static $nb_jobs_scheduled = null;
466
+    static $deja_la = false;
467
+    // prendre le min des $next_time que l'on voit passer ici, en cas de reentrance
468
+    static $next = null;
469
+    // queue_close_job peut etre reentrant ici
470
+    if ($deja_la) {
471
+        return;
472
+    }
473
+    $deja_la = true;
474
+
475
+    include_spip('base/abstract_sql');
476
+    $time = time();
477
+
478
+    // traiter les jobs morts au combat (_JQ_PENDING depuis plus de 180s)
479
+    // pour cause de timeout ou autre erreur fatale
480
+    $res = sql_allfetsel(
481
+        '*',
482
+        'spip_jobs',
483
+        'status=' . intval(_JQ_PENDING) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time - 180))
484
+    );
485
+    if (is_array($res)) {
486
+        foreach ($res as $row) {
487
+            queue_close_job($row, $time);
488
+            spip_log('queue_close_job car _JQ_PENDING depuis +180s : ' . print_r($row, 1), 'job_mort' . _LOG_ERREUR);
489
+        }
490
+    }
491
+
492
+    // chercher la date du prochain job si pas connu
493
+    if (is_null($next) or is_null(queue_sleep_time_to_next_job())) {
494
+        $date = sql_getfetsel('date', 'spip_jobs', 'status=' . intval(_JQ_SCHEDULED), '', 'date', '0,1');
495
+        $next = strtotime($date);
496
+    }
497
+    if (!is_null($next_time)) {
498
+        if (is_null($next) or $next > $next_time) {
499
+            $next = $next_time;
500
+        }
501
+    }
502
+
503
+    if ($next) {
504
+        if (is_null($nb_jobs_scheduled)) {
505
+            $nb_jobs_scheduled = sql_countsel(
506
+                'spip_jobs',
507
+                'status=' . intval(_JQ_SCHEDULED) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time))
508
+            );
509
+        } elseif ($next <= $time) {
510
+            $nb_jobs_scheduled++;
511
+        }
512
+        // si trop de jobs en attente, on force la purge en fin de hit
513
+        // pour assurer le coup
514
+        if ($nb_jobs_scheduled > (defined('_JQ_NB_JOBS_OVERFLOW') ? _JQ_NB_JOBS_OVERFLOW : 10000)) {
515
+            define('_DIRECT_CRON_FORCE', true);
516
+        }
517
+    }
518
+
519
+    queue_set_next_job_time($next);
520
+    $deja_la = false;
521 521
 }
522 522
 
523 523
 
@@ -528,26 +528,26 @@  discard block
 block discarded – undo
528 528
  */
529 529
 function queue_set_next_job_time($next) {
530 530
 
531
-	// utiliser le temps courant reel plutot que temps de la requete ici
532
-	$time = time();
533
-
534
-	// toujours relire la valeur pour comparer, pour tenir compte des maj concourrantes
535
-	// et ne mettre a jour que si il y a un interet a le faire
536
-	// permet ausis d'initialiser le nom de fichier a coup sur
537
-	$curr_next = $_SERVER['REQUEST_TIME'] + max(0, queue_sleep_time_to_next_job(true));
538
-	if (
539
-		($curr_next <= $time and $next > $time) // le prochain job est dans le futur mais pas la date planifiee actuelle
540
-		or $curr_next > $next // le prochain job est plus tot que la date planifiee actuelle
541
-	) {
542
-		if (function_exists('cache_set') and defined('_MEMOIZE_MEMORY') and _MEMOIZE_MEMORY) {
543
-			cache_set(_JQ_NEXT_JOB_TIME_FILENAME, intval($next));
544
-		} else {
545
-			ecrire_fichier(_JQ_NEXT_JOB_TIME_FILENAME, intval($next));
546
-		}
547
-		queue_sleep_time_to_next_job($next);
548
-	}
549
-
550
-	return queue_sleep_time_to_next_job();
531
+    // utiliser le temps courant reel plutot que temps de la requete ici
532
+    $time = time();
533
+
534
+    // toujours relire la valeur pour comparer, pour tenir compte des maj concourrantes
535
+    // et ne mettre a jour que si il y a un interet a le faire
536
+    // permet ausis d'initialiser le nom de fichier a coup sur
537
+    $curr_next = $_SERVER['REQUEST_TIME'] + max(0, queue_sleep_time_to_next_job(true));
538
+    if (
539
+        ($curr_next <= $time and $next > $time) // le prochain job est dans le futur mais pas la date planifiee actuelle
540
+        or $curr_next > $next // le prochain job est plus tot que la date planifiee actuelle
541
+    ) {
542
+        if (function_exists('cache_set') and defined('_MEMOIZE_MEMORY') and _MEMOIZE_MEMORY) {
543
+            cache_set(_JQ_NEXT_JOB_TIME_FILENAME, intval($next));
544
+        } else {
545
+            ecrire_fichier(_JQ_NEXT_JOB_TIME_FILENAME, intval($next));
546
+        }
547
+        queue_sleep_time_to_next_job($next);
548
+    }
549
+
550
+    return queue_sleep_time_to_next_job();
551 551
 }
552 552
 
553 553
 /**
@@ -564,60 +564,60 @@  discard block
 block discarded – undo
564 564
  * @return string
565 565
  */
566 566
 function queue_affichage_cron() {
567
-	$texte = '';
568
-
569
-	$time_to_next = queue_sleep_time_to_next_job();
570
-	// rien a faire si le prochain job est encore dans le futur
571
-	if ($time_to_next > 0 or defined('_DEBUG_BLOCK_QUEUE')) {
572
-		return $texte;
573
-	}
574
-
575
-	// ne pas relancer si on vient de lancer dans la meme seconde par un hit concurent
576
-	if (file_exists($lock = _DIR_TMP . 'cron.lock') and !(@filemtime($lock) < $_SERVER['REQUEST_TIME'])) {
577
-		return $texte;
578
-	}
579
-
580
-	@touch($lock);
581
-
582
-	// il y a des taches en attentes
583
-	// si depuis plus de 5min, on essaye de lancer le cron par tous les moyens pour rattraper le coup
584
-	// on est sans doute sur un site qui n'autorise pas http sortant ou avec peu de trafic
585
-	$urgent = false;
586
-	if ($time_to_next < -300) {
587
-		$urgent = true;
588
-	}
589
-
590
-	$url_cron = generer_url_action('cron', '', false, true);
591
-
592
-	if (!defined('_HTML_BG_CRON_FORCE') or !_HTML_BG_CRON_FORCE) {
593
-		if (queue_lancer_url_http_async($url_cron) and !$urgent) {
594
-			return $texte;
595
-		}
596
-	}
597
-
598
-	// si deja force, on retourne sans rien
599
-	if (defined('_DIRECT_CRON_FORCE')) {
600
-		return $texte;
601
-	}
602
-
603
-	// si c'est un bot
604
-	// inutile de faire un appel par image background,
605
-	// on force un appel direct en fin de hit
606
-	if ((defined('_IS_BOT') and _IS_BOT)) {
607
-		define('_DIRECT_CRON_FORCE', true);
608
-
609
-		return $texte;
610
-	}
611
-
612
-	if (!defined('_HTML_BG_CRON_INHIB') or !_HTML_BG_CRON_INHIB) {
613
-		// en derniere solution, on insere un appel xhr non bloquant ou une image background dans la page si pas de JS
614
-		$url_cron = generer_url_action('cron');
615
-		$texte = '<!-- SPIP-CRON -->'
616
-		  . "<script>setTimeout(function(){var xo = new XMLHttpRequest();xo.open('GET', '$url_cron', true);xo.send('');},100);</script>"
617
-		  . "<noscript><div style=\"background-image: url('$url_cron');\"></div></noscript>";
618
-	}
619
-
620
-	return $texte;
567
+    $texte = '';
568
+
569
+    $time_to_next = queue_sleep_time_to_next_job();
570
+    // rien a faire si le prochain job est encore dans le futur
571
+    if ($time_to_next > 0 or defined('_DEBUG_BLOCK_QUEUE')) {
572
+        return $texte;
573
+    }
574
+
575
+    // ne pas relancer si on vient de lancer dans la meme seconde par un hit concurent
576
+    if (file_exists($lock = _DIR_TMP . 'cron.lock') and !(@filemtime($lock) < $_SERVER['REQUEST_TIME'])) {
577
+        return $texte;
578
+    }
579
+
580
+    @touch($lock);
581
+
582
+    // il y a des taches en attentes
583
+    // si depuis plus de 5min, on essaye de lancer le cron par tous les moyens pour rattraper le coup
584
+    // on est sans doute sur un site qui n'autorise pas http sortant ou avec peu de trafic
585
+    $urgent = false;
586
+    if ($time_to_next < -300) {
587
+        $urgent = true;
588
+    }
589
+
590
+    $url_cron = generer_url_action('cron', '', false, true);
591
+
592
+    if (!defined('_HTML_BG_CRON_FORCE') or !_HTML_BG_CRON_FORCE) {
593
+        if (queue_lancer_url_http_async($url_cron) and !$urgent) {
594
+            return $texte;
595
+        }
596
+    }
597
+
598
+    // si deja force, on retourne sans rien
599
+    if (defined('_DIRECT_CRON_FORCE')) {
600
+        return $texte;
601
+    }
602
+
603
+    // si c'est un bot
604
+    // inutile de faire un appel par image background,
605
+    // on force un appel direct en fin de hit
606
+    if ((defined('_IS_BOT') and _IS_BOT)) {
607
+        define('_DIRECT_CRON_FORCE', true);
608
+
609
+        return $texte;
610
+    }
611
+
612
+    if (!defined('_HTML_BG_CRON_INHIB') or !_HTML_BG_CRON_INHIB) {
613
+        // en derniere solution, on insere un appel xhr non bloquant ou une image background dans la page si pas de JS
614
+        $url_cron = generer_url_action('cron');
615
+        $texte = '<!-- SPIP-CRON -->'
616
+            . "<script>setTimeout(function(){var xo = new XMLHttpRequest();xo.open('GET', '$url_cron', true);xo.send('');},100);</script>"
617
+            . "<noscript><div style=\"background-image: url('$url_cron');\"></div></noscript>";
618
+    }
619
+
620
+    return $texte;
621 621
 }
622 622
 
623 623
 /**
@@ -626,73 +626,73 @@  discard block
 block discarded – undo
626 626
  * @return bool : true si l'url a pu être appelée en asynchrone, false sinon
627 627
  */
628 628
 function queue_lancer_url_http_async($url_cron) {
629
-	// methode la plus rapide :
630
-	// Si fsockopen est possible, on lance le cron via un socket en asynchrone
631
-	// si fsockopen echoue (disponibilite serveur, firewall) on essaye pas cURL
632
-	// car on a toutes les chances d'echouer pareil mais sans moyen de le savoir
633
-	// mais on renvoie false direct
634
-	if (function_exists('fsockopen')) {
635
-		$parts = parse_url($url_cron);
636
-
637
-		switch ($parts['scheme']) {
638
-			case 'https':
639
-				$scheme = 'ssl://';
640
-				$port = 443;
641
-				break;
642
-			case 'http':
643
-			default:
644
-				$scheme = '';
645
-				$port = 80;
646
-		}
647
-		$fp = @fsockopen(
648
-			$scheme . $parts['host'],
649
-			$parts['port'] ?? $port,
650
-			$errno,
651
-			$errstr,
652
-			1
653
-		);
654
-
655
-		if ($fp) {
656
-			$host_sent = $parts['host'];
657
-			if (isset($parts['port']) and $parts['port'] !== $port) {
658
-				$host_sent .= ':' . $parts['port'];
659
-			}
660
-			$timeout = 200; // ms
661
-			stream_set_timeout($fp, 0, $timeout * 1000);
662
-			$query = $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '');
663
-			$out = 'GET ' . $query . " HTTP/1.1\r\n";
664
-			$out .= 'Host: ' . $host_sent . "\r\n";
665
-			$out .= "Connection: Close\r\n\r\n";
666
-			fwrite($fp, $out);
667
-			spip_timer('read');
668
-			$t = 0;
669
-			// on lit la reponse si possible pour fermer proprement la connexion
670
-			// avec un timeout total de 200ms pour ne pas se bloquer
671
-			while (!feof($fp) and $t < $timeout) {
672
-				@fgets($fp, 1024);
673
-				$t += spip_timer('read', true);
674
-				spip_timer('read');
675
-			}
676
-			fclose($fp);
677
-			return true;
678
-		}
679
-	}
680
-	// si fsockopen n'est pas dispo on essaye cURL :
681
-	// lancer le cron par un cURL asynchrone si cURL est present
682
-	elseif (function_exists('curl_init')) {
683
-		//setting the curl parameters.
684
-		$ch = curl_init($url_cron);
685
-		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
686
-		// cf bug : http://www.php.net/manual/en/function.curl-setopt.php#104597
687
-		curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
688
-		// valeur mini pour que la requete soit lancee
689
-		curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
690
-		// lancer
691
-		curl_exec($ch);
692
-		// fermer
693
-		curl_close($ch);
694
-		return true;
695
-	}
696
-
697
-	return false;
629
+    // methode la plus rapide :
630
+    // Si fsockopen est possible, on lance le cron via un socket en asynchrone
631
+    // si fsockopen echoue (disponibilite serveur, firewall) on essaye pas cURL
632
+    // car on a toutes les chances d'echouer pareil mais sans moyen de le savoir
633
+    // mais on renvoie false direct
634
+    if (function_exists('fsockopen')) {
635
+        $parts = parse_url($url_cron);
636
+
637
+        switch ($parts['scheme']) {
638
+            case 'https':
639
+                $scheme = 'ssl://';
640
+                $port = 443;
641
+                break;
642
+            case 'http':
643
+            default:
644
+                $scheme = '';
645
+                $port = 80;
646
+        }
647
+        $fp = @fsockopen(
648
+            $scheme . $parts['host'],
649
+            $parts['port'] ?? $port,
650
+            $errno,
651
+            $errstr,
652
+            1
653
+        );
654
+
655
+        if ($fp) {
656
+            $host_sent = $parts['host'];
657
+            if (isset($parts['port']) and $parts['port'] !== $port) {
658
+                $host_sent .= ':' . $parts['port'];
659
+            }
660
+            $timeout = 200; // ms
661
+            stream_set_timeout($fp, 0, $timeout * 1000);
662
+            $query = $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '');
663
+            $out = 'GET ' . $query . " HTTP/1.1\r\n";
664
+            $out .= 'Host: ' . $host_sent . "\r\n";
665
+            $out .= "Connection: Close\r\n\r\n";
666
+            fwrite($fp, $out);
667
+            spip_timer('read');
668
+            $t = 0;
669
+            // on lit la reponse si possible pour fermer proprement la connexion
670
+            // avec un timeout total de 200ms pour ne pas se bloquer
671
+            while (!feof($fp) and $t < $timeout) {
672
+                @fgets($fp, 1024);
673
+                $t += spip_timer('read', true);
674
+                spip_timer('read');
675
+            }
676
+            fclose($fp);
677
+            return true;
678
+        }
679
+    }
680
+    // si fsockopen n'est pas dispo on essaye cURL :
681
+    // lancer le cron par un cURL asynchrone si cURL est present
682
+    elseif (function_exists('curl_init')) {
683
+        //setting the curl parameters.
684
+        $ch = curl_init($url_cron);
685
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
686
+        // cf bug : http://www.php.net/manual/en/function.curl-setopt.php#104597
687
+        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
688
+        // valeur mini pour que la requete soit lancee
689
+        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
690
+        // lancer
691
+        curl_exec($ch);
692
+        // fermer
693
+        curl_close($ch);
694
+        return true;
695
+    }
696
+
697
+    return false;
698 698
 }
Please login to merge, or discard this patch.
Spacing   +37 added lines, -38 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 	$md5args = md5($arguments);
71 71
 
72 72
 	// si pas de date programee, des que possible
73
-	$duplicate_where = 'status=' . intval(_JQ_SCHEDULED) . ' AND ';
73
+	$duplicate_where = 'status='.intval(_JQ_SCHEDULED).' AND ';
74 74
 	if (!$time) {
75 75
 		$time = time();
76 76
 		$duplicate_where = ''; // ne pas dupliquer si deja le meme job en cours d'execution
@@ -96,9 +96,8 @@  discard block
 block discarded – undo
96 96
 			'id_job',
97 97
 			'spip_jobs',
98 98
 			$duplicate_where =
99
-				$duplicate_where . 'fonction=' . sql_quote($function)
100
-				. (($no_duplicate === 'function_only') ? '' :
101
-			' AND md5args=' . sql_quote($md5args) . ' AND inclure=' . sql_quote($file))
99
+				$duplicate_where.'fonction='.sql_quote($function)
100
+				. (($no_duplicate === 'function_only') ? '' : ' AND md5args='.sql_quote($md5args).' AND inclure='.sql_quote($file))
102 101
 		)
103 102
 	) {
104 103
 		return $id_job;
@@ -111,9 +110,9 @@  discard block
 block discarded – undo
111 110
 	if (
112 111
 		$no_duplicate
113 112
 		and
114
-		$id_prev = sql_getfetsel('id_job', 'spip_jobs', 'id_job<' . intval($id_job) . " AND $duplicate_where")
113
+		$id_prev = sql_getfetsel('id_job', 'spip_jobs', 'id_job<'.intval($id_job)." AND $duplicate_where")
115 114
 	) {
116
-		sql_delete('spip_jobs', 'id_job=' . intval($id_job));
115
+		sql_delete('spip_jobs', 'id_job='.intval($id_job));
117 116
 
118 117
 		return $id_prev;
119 118
 	}
@@ -125,9 +124,9 @@  discard block
 block discarded – undo
125 124
 	// ie cas d'un char non acceptables sur certains type de champs
126 125
 	// qui coupe la valeur
127 126
 	if (defined('_JQ_INSERT_CHECK_ARGS') and $id_job) {
128
-		$args = sql_getfetsel('args', 'spip_jobs', 'id_job=' . intval($id_job));
127
+		$args = sql_getfetsel('args', 'spip_jobs', 'id_job='.intval($id_job));
129 128
 		if ($args !== $arguments) {
130
-			spip_log('arguments job errones / longueur ' . strlen($args) . ' vs ' . strlen($arguments) . ' / valeur : ' . var_export(
129
+			spip_log('arguments job errones / longueur '.strlen($args).' vs '.strlen($arguments).' / valeur : '.var_export(
131 130
 				$arguments,
132 131
 				true
133 132
 			), 'queue');
@@ -157,7 +156,7 @@  discard block
 block discarded – undo
157 156
 function queue_purger() {
158 157
 	include_spip('base/abstract_sql');
159 158
 	sql_delete('spip_jobs');
160
-	sql_delete('spip_jobs_liens', 'id_job NOT IN (' . sql_get_select('id_job', 'spip_jobs') . ')');
159
+	sql_delete('spip_jobs_liens', 'id_job NOT IN ('.sql_get_select('id_job', 'spip_jobs').')');
161 160
 	include_spip('inc/genie');
162 161
 	genie_queue_watch_dist();
163 162
 }
@@ -173,8 +172,8 @@  discard block
 block discarded – undo
173 172
 	include_spip('base/abstract_sql');
174 173
 
175 174
 	if (
176
-		$row = sql_fetsel('fonction,inclure,date', 'spip_jobs', 'id_job=' . intval($id_job))
177
-		and $res = sql_delete('spip_jobs', 'id_job=' . intval($id_job))
175
+		$row = sql_fetsel('fonction,inclure,date', 'spip_jobs', 'id_job='.intval($id_job))
176
+		and $res = sql_delete('spip_jobs', 'id_job='.intval($id_job))
178 177
 	) {
179 178
 		queue_unlink_job($id_job);
180 179
 		// est-ce une tache cron qu'il faut relancer ?
@@ -224,7 +223,7 @@  discard block
 block discarded – undo
224 223
  *  resultat du sql_delete
225 224
  */
226 225
 function queue_unlink_job($id_job) {
227
-	return sql_delete('spip_jobs_liens', 'id_job=' . intval($id_job));
226
+	return sql_delete('spip_jobs_liens', 'id_job='.intval($id_job));
228 227
 }
229 228
 
230 229
 /**
@@ -240,7 +239,7 @@  discard block
 block discarded – undo
240 239
 	// deserialiser les arguments
241 240
 	$args = unserialize($row['args']);
242 241
 	if (!is_array($args)) {
243
-		spip_log('arguments job errones ' . var_export($row, true), 'queue');
242
+		spip_log('arguments job errones '.var_export($row, true), 'queue');
244 243
 		$args = [];
245 244
 	}
246 245
 
@@ -257,14 +256,14 @@  discard block
 block discarded – undo
257 256
 	}
258 257
 
259 258
 	if (!function_exists($fonction)) {
260
-		spip_log("fonction $fonction ($inclure) inexistante " . var_export($row, true), 'queue');
259
+		spip_log("fonction $fonction ($inclure) inexistante ".var_export($row, true), 'queue');
261 260
 
262 261
 		return false;
263 262
 	}
264 263
 
265
-	spip_log('queue [' . $row['id_job'] . "]: $fonction() start", 'queue');
264
+	spip_log('queue ['.$row['id_job']."]: $fonction() start", 'queue');
266 265
 	$res = $fonction(...$args);
267
-	spip_log('queue [' . $row['id_job'] . "]: $fonction() end", 'queue');
266
+	spip_log('queue ['.$row['id_job']."]: $fonction() end", 'queue');
268 267
 
269 268
 	return $res;
270 269
 }
@@ -295,14 +294,14 @@  discard block
 block discarded – undo
295 294
 function queue_schedule($force_jobs = null) {
296 295
 	$time = time();
297 296
 	if (defined('_DEBUG_BLOCK_QUEUE')) {
298
-		spip_log('_DEBUG_BLOCK_QUEUE : schedule stop', 'jq' . _LOG_DEBUG);
297
+		spip_log('_DEBUG_BLOCK_QUEUE : schedule stop', 'jq'._LOG_DEBUG);
299 298
 
300 299
 		return;
301 300
 	}
302 301
 
303 302
 	// rien a faire si le prochain job est encore dans le futur
304 303
 	if (queue_sleep_time_to_next_job() > 0 and (!$force_jobs or !count($force_jobs))) {
305
-		spip_log('queue_sleep_time_to_next_job', 'jq' . _LOG_DEBUG);
304
+		spip_log('queue_sleep_time_to_next_job', 'jq'._LOG_DEBUG);
306 305
 
307 306
 		return;
308 307
 	}
@@ -323,7 +322,7 @@  discard block
 block discarded – undo
323 322
 	}
324 323
 	$end_time = $time + _JQ_MAX_JOBS_TIME_TO_EXECUTE;
325 324
 
326
-	spip_log("JQ schedule $time / $end_time", 'jq' . _LOG_DEBUG);
325
+	spip_log("JQ schedule $time / $end_time", 'jq'._LOG_DEBUG);
327 326
 
328 327
 	if (!defined('_JQ_MAX_JOBS_EXECUTE')) {
329 328
 		define('_JQ_MAX_JOBS_EXECUTE', 200);
@@ -337,19 +336,19 @@  discard block
 block discarded – undo
337 336
 	// lorsqu'un job cron n'a pas fini, sa priorite est descendue
338 337
 	// pour qu'il ne bloque pas les autres jobs en attente
339 338
 	if (is_array($force_jobs) and count($force_jobs)) {
340
-		$cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND ' . sql_in('id_job', $force_jobs);
339
+		$cond = 'status='.intval(_JQ_SCHEDULED).' AND '.sql_in('id_job', $force_jobs);
341 340
 	} else {
342 341
 		$now = date('Y-m-d H:i:s', $time);
343
-		$cond = 'status=' . intval(_JQ_SCHEDULED) . ' AND date<=' . sql_quote($now);
342
+		$cond = 'status='.intval(_JQ_SCHEDULED).' AND date<='.sql_quote($now);
344 343
 	}
345 344
 
346 345
 	register_shutdown_function('queue_error_handler'); // recuperer les erreurs auant que possible
347
-	$res = sql_allfetsel('*', 'spip_jobs', $cond, '', 'priorite DESC,date', '0,' . (_JQ_MAX_JOBS_EXECUTE + 1));
346
+	$res = sql_allfetsel('*', 'spip_jobs', $cond, '', 'priorite DESC,date', '0,'.(_JQ_MAX_JOBS_EXECUTE + 1));
348 347
 	do {
349 348
 		if ($row = array_shift($res)) {
350 349
 			$nbj++;
351 350
 			// il faut un verrou, a base de sql_delete
352
-			if (sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']) . ' AND status=' . intval(_JQ_SCHEDULED))) {
351
+			if (sql_delete('spip_jobs', 'id_job='.intval($row['id_job']).' AND status='.intval(_JQ_SCHEDULED))) {
353 352
 				#spip_log("JQ schedule job ".$nbj." OK",'jq');
354 353
 				// on reinsert dans la base aussitot avec un status=_JQ_PENDING
355 354
 				$row['status'] = _JQ_PENDING;
@@ -364,13 +363,13 @@  discard block
 block discarded – undo
364 363
 				queue_close_job($row, $time, $result);
365 364
 			}
366 365
 		}
367
-		spip_log('JQ schedule job end time ' . $time, 'jq' . _LOG_DEBUG);
366
+		spip_log('JQ schedule job end time '.$time, 'jq'._LOG_DEBUG);
368 367
 	} while ($nbj < _JQ_MAX_JOBS_EXECUTE and $row and $time < $end_time);
369
-	spip_log('JQ schedule end time ' . time(), 'jq' . _LOG_DEBUG);
368
+	spip_log('JQ schedule end time '.time(), 'jq'._LOG_DEBUG);
370 369
 
371 370
 	if ($row = array_shift($res)) {
372 371
 		queue_update_next_job_time(0); // on sait qu'il y a encore des jobs a lancer ASAP
373
-		spip_log('JQ encore !', 'jq' . _LOG_DEBUG);
372
+		spip_log('JQ encore !', 'jq'._LOG_DEBUG);
374 373
 	} else {
375 374
 		queue_update_next_job_time();
376 375
 	}
@@ -405,9 +404,9 @@  discard block
 block discarded – undo
405 404
 		}
406 405
 	}
407 406
 	// purger ses liens eventuels avec des objets
408
-	sql_delete('spip_jobs_liens', 'id_job=' . intval($row['id_job']));
407
+	sql_delete('spip_jobs_liens', 'id_job='.intval($row['id_job']));
409 408
 	// supprimer le job fini
410
-	sql_delete('spip_jobs', 'id_job=' . intval($row['id_job']));
409
+	sql_delete('spip_jobs', 'id_job='.intval($row['id_job']));
411 410
 }
412 411
 
413 412
 /**
@@ -480,18 +479,18 @@  discard block
 block discarded – undo
480 479
 	$res = sql_allfetsel(
481 480
 		'*',
482 481
 		'spip_jobs',
483
-		'status=' . intval(_JQ_PENDING) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time - 180))
482
+		'status='.intval(_JQ_PENDING).' AND date<'.sql_quote(date('Y-m-d H:i:s', $time - 180))
484 483
 	);
485 484
 	if (is_array($res)) {
486 485
 		foreach ($res as $row) {
487 486
 			queue_close_job($row, $time);
488
-			spip_log('queue_close_job car _JQ_PENDING depuis +180s : ' . print_r($row, 1), 'job_mort' . _LOG_ERREUR);
487
+			spip_log('queue_close_job car _JQ_PENDING depuis +180s : '.print_r($row, 1), 'job_mort'._LOG_ERREUR);
489 488
 		}
490 489
 	}
491 490
 
492 491
 	// chercher la date du prochain job si pas connu
493 492
 	if (is_null($next) or is_null(queue_sleep_time_to_next_job())) {
494
-		$date = sql_getfetsel('date', 'spip_jobs', 'status=' . intval(_JQ_SCHEDULED), '', 'date', '0,1');
493
+		$date = sql_getfetsel('date', 'spip_jobs', 'status='.intval(_JQ_SCHEDULED), '', 'date', '0,1');
495 494
 		$next = strtotime($date);
496 495
 	}
497 496
 	if (!is_null($next_time)) {
@@ -504,7 +503,7 @@  discard block
 block discarded – undo
504 503
 		if (is_null($nb_jobs_scheduled)) {
505 504
 			$nb_jobs_scheduled = sql_countsel(
506 505
 				'spip_jobs',
507
-				'status=' . intval(_JQ_SCHEDULED) . ' AND date<' . sql_quote(date('Y-m-d H:i:s', $time))
506
+				'status='.intval(_JQ_SCHEDULED).' AND date<'.sql_quote(date('Y-m-d H:i:s', $time))
508 507
 			);
509 508
 		} elseif ($next <= $time) {
510 509
 			$nb_jobs_scheduled++;
@@ -573,7 +572,7 @@  discard block
 block discarded – undo
573 572
 	}
574 573
 
575 574
 	// ne pas relancer si on vient de lancer dans la meme seconde par un hit concurent
576
-	if (file_exists($lock = _DIR_TMP . 'cron.lock') and !(@filemtime($lock) < $_SERVER['REQUEST_TIME'])) {
575
+	if (file_exists($lock = _DIR_TMP.'cron.lock') and !(@filemtime($lock) < $_SERVER['REQUEST_TIME'])) {
577 576
 		return $texte;
578 577
 	}
579 578
 
@@ -645,7 +644,7 @@  discard block
 block discarded – undo
645 644
 				$port = 80;
646 645
 		}
647 646
 		$fp = @fsockopen(
648
-			$scheme . $parts['host'],
647
+			$scheme.$parts['host'],
649 648
 			$parts['port'] ?? $port,
650 649
 			$errno,
651 650
 			$errstr,
@@ -655,13 +654,13 @@  discard block
 block discarded – undo
655 654
 		if ($fp) {
656 655
 			$host_sent = $parts['host'];
657 656
 			if (isset($parts['port']) and $parts['port'] !== $port) {
658
-				$host_sent .= ':' . $parts['port'];
657
+				$host_sent .= ':'.$parts['port'];
659 658
 			}
660 659
 			$timeout = 200; // ms
661 660
 			stream_set_timeout($fp, 0, $timeout * 1000);
662
-			$query = $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '');
663
-			$out = 'GET ' . $query . " HTTP/1.1\r\n";
664
-			$out .= 'Host: ' . $host_sent . "\r\n";
661
+			$query = $parts['path'].($parts['query'] ? '?'.$parts['query'] : '');
662
+			$out = 'GET '.$query." HTTP/1.1\r\n";
663
+			$out .= 'Host: '.$host_sent."\r\n";
665 664
 			$out .= "Connection: Close\r\n\r\n";
666 665
 			fwrite($fp, $out);
667 666
 			spip_timer('read');
Please login to merge, or discard this patch.
ecrire/install/etape_ldap2.php 3 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -39,8 +39,7 @@
 block discarded – undo
39 39
 		} else {
40 40
 			$tls = true;
41 41
 		}
42
-	}
43
-	else {
42
+	} else {
44 43
 		$tls_ldap == 'non';
45 44
 	}
46 45
 
Please login to merge, or discard this patch.
Indentation   +83 added lines, -83 removed lines patch added patch discarded remove patch
@@ -10,90 +10,90 @@
 block discarded – undo
10 10
 \***************************************************************************/
11 11
 
12 12
 if (!defined('_ECRIRE_INC_VERSION')) {
13
-	return;
13
+    return;
14 14
 }
15 15
 
16 16
 function install_etape_ldap2_dist() {
17
-	$minipage = new Spip\Afficher\Minipage\Installation();
18
-	echo $minipage->installDebutPage(['onload' => 'document.getElementById(\'suivant\').focus();return false;']);
19
-
20
-	$adresse_ldap = _request('adresse_ldap');
21
-
22
-	$port_ldap = _request('port_ldap');
23
-
24
-	$tls_ldap = _request('tls_ldap');
25
-
26
-	$protocole_ldap = _request('protocole_ldap');
27
-
28
-	$login_ldap = _request('login_ldap');
29
-
30
-	$pass_ldap = _request('pass_ldap');
31
-
32
-	$port_ldap = intval($port_ldap);
33
-
34
-	$tls = false;
35
-
36
-	if ($tls_ldap == 'oui') {
37
-		if ($port_ldap == 636) {
38
-			$adresse_ldap = "ldaps://$adresse_ldap";
39
-		} else {
40
-			$tls = true;
41
-		}
42
-	}
43
-	else {
44
-		$tls_ldap == 'non';
45
-	}
46
-
47
-	// Verifions que l'adresse demandee est valide
48
-	$adresse_ldap = filter_var($adresse_ldap, FILTER_SANITIZE_URL) ?: '';
49
-
50
-	$ldap_link = ldap_connect($adresse_ldap, $port_ldap);
51
-	$erreur = 'ldap_connect(' . spip_htmlspecialchars($adresse_ldap) . ', ' . spip_htmlspecialchars($port_ldap) . ')';
52
-
53
-	if ($ldap_link) {
54
-		if (!ldap_set_option($ldap_link, LDAP_OPT_PROTOCOL_VERSION, $protocole_ldap)) {
55
-			$protocole_ldap = 2;
56
-			ldap_set_option($ldap_link, LDAP_OPT_PROTOCOL_VERSION, $protocole_ldap);
57
-		}
58
-		if ($tls === true) {
59
-			if (!ldap_start_tls($ldap_link)) {
60
-				$erreur = 'ldap_start_tls(' . spip_htmlspecialchars($ldap_link)
61
-					. ' ' . spip_htmlspecialchars($adresse_ldap)
62
-					. ', ' . spip_htmlspecialchars($port_ldap) . ')';
63
-				$ldap_link = false;
64
-			}
65
-		}
66
-		if ($ldap_link) {
67
-			$ldap_link = ldap_bind($ldap_link, $login_ldap, $pass_ldap);
68
-			$erreur = "ldap_bind('" . spip_htmlspecialchars($ldap_link)
69
-				. "', '" . spip_htmlspecialchars($login_ldap)
70
-				. "', '" . spip_htmlspecialchars($pass_ldap)
71
-				. "'): " . spip_htmlspecialchars($adresse_ldap)
72
-				. ', ' . spip_htmlspecialchars($port_ldap);
73
-		}
74
-	}
75
-
76
-	if ($ldap_link) {
77
-		echo info_etape(
78
-			_T('titre_connexion_ldap'),
79
-			info_progression_etape(2, 'etape_ldap', 'install/')
80
-		),  _T('info_connexion_ldap_ok');
81
-		echo generer_form_ecrire('install', (
82
-			"\n<input type='hidden' name='etape' value='ldap3' />"
83
-			. "\n<input type='hidden' name='adresse_ldap' value=\"" . spip_htmlspecialchars($adresse_ldap) . '" />'
84
-			. "\n<input type='hidden' name='port_ldap' value=\"" . spip_htmlspecialchars($port_ldap) . '" />'
85
-			. "\n<input type='hidden' name='login_ldap' value=\"" . spip_htmlspecialchars($login_ldap) . '" />'
86
-			. "\n<input type='hidden' name='pass_ldap' value=\"" . spip_htmlspecialchars($pass_ldap) . '" />'
87
-			. "\n<input type='hidden' name='protocole_ldap' value=\"" . spip_htmlspecialchars($protocole_ldap) . '" />'
88
-			. "\n<input type='hidden' name='tls_ldap' value=\"" . spip_htmlspecialchars($tls_ldap) . '" />'
89
-			. bouton_suivant()));
90
-	} else {
91
-		echo info_etape(_T('titre_connexion_ldap')), info_progression_etape(1, 'etape_ldap', 'install/', true),
92
-			"<div class='error'><p>" . _T('avis_connexion_ldap_echec_1') . '</p>',
93
-			'<p>' . _T('avis_connexion_ldap_echec_2') .
94
-			"<br />\n" . _T('avis_connexion_ldap_echec_3') .
95
-			'<br /><br />' . $erreur . '<b> ?</b></p></div>';
96
-	}
97
-
98
-	echo $minipage->installFinPage();
17
+    $minipage = new Spip\Afficher\Minipage\Installation();
18
+    echo $minipage->installDebutPage(['onload' => 'document.getElementById(\'suivant\').focus();return false;']);
19
+
20
+    $adresse_ldap = _request('adresse_ldap');
21
+
22
+    $port_ldap = _request('port_ldap');
23
+
24
+    $tls_ldap = _request('tls_ldap');
25
+
26
+    $protocole_ldap = _request('protocole_ldap');
27
+
28
+    $login_ldap = _request('login_ldap');
29
+
30
+    $pass_ldap = _request('pass_ldap');
31
+
32
+    $port_ldap = intval($port_ldap);
33
+
34
+    $tls = false;
35
+
36
+    if ($tls_ldap == 'oui') {
37
+        if ($port_ldap == 636) {
38
+            $adresse_ldap = "ldaps://$adresse_ldap";
39
+        } else {
40
+            $tls = true;
41
+        }
42
+    }
43
+    else {
44
+        $tls_ldap == 'non';
45
+    }
46
+
47
+    // Verifions que l'adresse demandee est valide
48
+    $adresse_ldap = filter_var($adresse_ldap, FILTER_SANITIZE_URL) ?: '';
49
+
50
+    $ldap_link = ldap_connect($adresse_ldap, $port_ldap);
51
+    $erreur = 'ldap_connect(' . spip_htmlspecialchars($adresse_ldap) . ', ' . spip_htmlspecialchars($port_ldap) . ')';
52
+
53
+    if ($ldap_link) {
54
+        if (!ldap_set_option($ldap_link, LDAP_OPT_PROTOCOL_VERSION, $protocole_ldap)) {
55
+            $protocole_ldap = 2;
56
+            ldap_set_option($ldap_link, LDAP_OPT_PROTOCOL_VERSION, $protocole_ldap);
57
+        }
58
+        if ($tls === true) {
59
+            if (!ldap_start_tls($ldap_link)) {
60
+                $erreur = 'ldap_start_tls(' . spip_htmlspecialchars($ldap_link)
61
+                    . ' ' . spip_htmlspecialchars($adresse_ldap)
62
+                    . ', ' . spip_htmlspecialchars($port_ldap) . ')';
63
+                $ldap_link = false;
64
+            }
65
+        }
66
+        if ($ldap_link) {
67
+            $ldap_link = ldap_bind($ldap_link, $login_ldap, $pass_ldap);
68
+            $erreur = "ldap_bind('" . spip_htmlspecialchars($ldap_link)
69
+                . "', '" . spip_htmlspecialchars($login_ldap)
70
+                . "', '" . spip_htmlspecialchars($pass_ldap)
71
+                . "'): " . spip_htmlspecialchars($adresse_ldap)
72
+                . ', ' . spip_htmlspecialchars($port_ldap);
73
+        }
74
+    }
75
+
76
+    if ($ldap_link) {
77
+        echo info_etape(
78
+            _T('titre_connexion_ldap'),
79
+            info_progression_etape(2, 'etape_ldap', 'install/')
80
+        ),  _T('info_connexion_ldap_ok');
81
+        echo generer_form_ecrire('install', (
82
+            "\n<input type='hidden' name='etape' value='ldap3' />"
83
+            . "\n<input type='hidden' name='adresse_ldap' value=\"" . spip_htmlspecialchars($adresse_ldap) . '" />'
84
+            . "\n<input type='hidden' name='port_ldap' value=\"" . spip_htmlspecialchars($port_ldap) . '" />'
85
+            . "\n<input type='hidden' name='login_ldap' value=\"" . spip_htmlspecialchars($login_ldap) . '" />'
86
+            . "\n<input type='hidden' name='pass_ldap' value=\"" . spip_htmlspecialchars($pass_ldap) . '" />'
87
+            . "\n<input type='hidden' name='protocole_ldap' value=\"" . spip_htmlspecialchars($protocole_ldap) . '" />'
88
+            . "\n<input type='hidden' name='tls_ldap' value=\"" . spip_htmlspecialchars($tls_ldap) . '" />'
89
+            . bouton_suivant()));
90
+    } else {
91
+        echo info_etape(_T('titre_connexion_ldap')), info_progression_etape(1, 'etape_ldap', 'install/', true),
92
+            "<div class='error'><p>" . _T('avis_connexion_ldap_echec_1') . '</p>',
93
+            '<p>' . _T('avis_connexion_ldap_echec_2') .
94
+            "<br />\n" . _T('avis_connexion_ldap_echec_3') .
95
+            '<br /><br />' . $erreur . '<b> ?</b></p></div>';
96
+    }
97
+
98
+    echo $minipage->installFinPage();
99 99
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 	$adresse_ldap = filter_var($adresse_ldap, FILTER_SANITIZE_URL) ?: '';
49 49
 
50 50
 	$ldap_link = ldap_connect($adresse_ldap, $port_ldap);
51
-	$erreur = 'ldap_connect(' . spip_htmlspecialchars($adresse_ldap) . ', ' . spip_htmlspecialchars($port_ldap) . ')';
51
+	$erreur = 'ldap_connect('.spip_htmlspecialchars($adresse_ldap).', '.spip_htmlspecialchars($port_ldap).')';
52 52
 
53 53
 	if ($ldap_link) {
54 54
 		if (!ldap_set_option($ldap_link, LDAP_OPT_PROTOCOL_VERSION, $protocole_ldap)) {
@@ -57,19 +57,19 @@  discard block
 block discarded – undo
57 57
 		}
58 58
 		if ($tls === true) {
59 59
 			if (!ldap_start_tls($ldap_link)) {
60
-				$erreur = 'ldap_start_tls(' . spip_htmlspecialchars($ldap_link)
61
-					. ' ' . spip_htmlspecialchars($adresse_ldap)
62
-					. ', ' . spip_htmlspecialchars($port_ldap) . ')';
60
+				$erreur = 'ldap_start_tls('.spip_htmlspecialchars($ldap_link)
61
+					. ' '.spip_htmlspecialchars($adresse_ldap)
62
+					. ', '.spip_htmlspecialchars($port_ldap).')';
63 63
 				$ldap_link = false;
64 64
 			}
65 65
 		}
66 66
 		if ($ldap_link) {
67 67
 			$ldap_link = ldap_bind($ldap_link, $login_ldap, $pass_ldap);
68
-			$erreur = "ldap_bind('" . spip_htmlspecialchars($ldap_link)
69
-				. "', '" . spip_htmlspecialchars($login_ldap)
70
-				. "', '" . spip_htmlspecialchars($pass_ldap)
71
-				. "'): " . spip_htmlspecialchars($adresse_ldap)
72
-				. ', ' . spip_htmlspecialchars($port_ldap);
68
+			$erreur = "ldap_bind('".spip_htmlspecialchars($ldap_link)
69
+				. "', '".spip_htmlspecialchars($login_ldap)
70
+				. "', '".spip_htmlspecialchars($pass_ldap)
71
+				. "'): ".spip_htmlspecialchars($adresse_ldap)
72
+				. ', '.spip_htmlspecialchars($port_ldap);
73 73
 		}
74 74
 	}
75 75
 
@@ -77,22 +77,22 @@  discard block
 block discarded – undo
77 77
 		echo info_etape(
78 78
 			_T('titre_connexion_ldap'),
79 79
 			info_progression_etape(2, 'etape_ldap', 'install/')
80
-		),  _T('info_connexion_ldap_ok');
80
+		), _T('info_connexion_ldap_ok');
81 81
 		echo generer_form_ecrire('install', (
82 82
 			"\n<input type='hidden' name='etape' value='ldap3' />"
83
-			. "\n<input type='hidden' name='adresse_ldap' value=\"" . spip_htmlspecialchars($adresse_ldap) . '" />'
84
-			. "\n<input type='hidden' name='port_ldap' value=\"" . spip_htmlspecialchars($port_ldap) . '" />'
85
-			. "\n<input type='hidden' name='login_ldap' value=\"" . spip_htmlspecialchars($login_ldap) . '" />'
86
-			. "\n<input type='hidden' name='pass_ldap' value=\"" . spip_htmlspecialchars($pass_ldap) . '" />'
87
-			. "\n<input type='hidden' name='protocole_ldap' value=\"" . spip_htmlspecialchars($protocole_ldap) . '" />'
88
-			. "\n<input type='hidden' name='tls_ldap' value=\"" . spip_htmlspecialchars($tls_ldap) . '" />'
83
+			. "\n<input type='hidden' name='adresse_ldap' value=\"".spip_htmlspecialchars($adresse_ldap).'" />'
84
+			. "\n<input type='hidden' name='port_ldap' value=\"".spip_htmlspecialchars($port_ldap).'" />'
85
+			. "\n<input type='hidden' name='login_ldap' value=\"".spip_htmlspecialchars($login_ldap).'" />'
86
+			. "\n<input type='hidden' name='pass_ldap' value=\"".spip_htmlspecialchars($pass_ldap).'" />'
87
+			. "\n<input type='hidden' name='protocole_ldap' value=\"".spip_htmlspecialchars($protocole_ldap).'" />'
88
+			. "\n<input type='hidden' name='tls_ldap' value=\"".spip_htmlspecialchars($tls_ldap).'" />'
89 89
 			. bouton_suivant()));
90 90
 	} else {
91 91
 		echo info_etape(_T('titre_connexion_ldap')), info_progression_etape(1, 'etape_ldap', 'install/', true),
92
-			"<div class='error'><p>" . _T('avis_connexion_ldap_echec_1') . '</p>',
93
-			'<p>' . _T('avis_connexion_ldap_echec_2') .
94
-			"<br />\n" . _T('avis_connexion_ldap_echec_3') .
95
-			'<br /><br />' . $erreur . '<b> ?</b></p></div>';
92
+			"<div class='error'><p>"._T('avis_connexion_ldap_echec_1').'</p>',
93
+			'<p>'._T('avis_connexion_ldap_echec_2').
94
+			"<br />\n"._T('avis_connexion_ldap_echec_3').
95
+			'<br /><br />'.$erreur.'<b> ?</b></p></div>';
96 96
 	}
97 97
 
98 98
 	echo $minipage->installFinPage();
Please login to merge, or discard this patch.
ecrire/inc/cookie.php 2 patches
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  **/
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 
@@ -52,68 +52,68 @@  discard block
 block discarded – undo
52 52
  *     cookie sécurisé ou non ?
53 53
  **/
54 54
 function spip_setcookie($name = '', $value = '', $options = []) {
55
-	static $to_secure_list = ['spip_session'];
56
-	if (defined('_COOKIE_SECURE_LIST') and is_array(_COOKIE_SECURE_LIST)) {
57
-		$to_secure_list = array_merge($to_secure_list, _COOKIE_SECURE_LIST);
58
-	}
59
-
60
-	if (!is_array($options)) {
61
-		// anciens paramètres :
62
-		# spip_setcookie($name = '', $value = '', $expire = 0, $path = 'AUTO', $domain = '', $secure = '')
63
-		$opt = func_get_args();
64
-		$opt = array_slice($opt, 2);
65
-		$options = []; # /!\ après le func_get_args (sinon $opt[0] référence la nouvelle valeur de $options !);
66
-		if (isset($opt[0])) {
67
-			$options['expires'] = $opt[0];
68
-		}
69
-		if (isset($opt[1])) {
70
-			$options['path'] = $opt[1];
71
-		}
72
-		if (isset($opt[2])) {
73
-			$options['domain'] = $opt[2];
74
-		}
75
-		if (isset($opt[3])) {
76
-			$options['secure'] = $opt[3];
77
-		}
78
-	}
79
-
80
-	// expires
81
-	if (!isset($options['expires'])) {
82
-		$options['expires'] = 0;
83
-	}
84
-	if (!isset($options['path']) or $options['path'] === 'AUTO') {
85
-		if (defined('_COOKIE_PATH')) {
86
-			$options['path'] = _COOKIE_PATH;
87
-		} else {
88
-			$options['path'] = preg_replace(',^\w+://[^/]*,', '', url_de_base());
89
-		}
90
-	}
91
-	if (empty($options['domain']) and defined('_COOKIE_DOMAIN') and _COOKIE_DOMAIN) {
92
-		$options['domain'] = _COOKIE_DOMAIN;
93
-	}
94
-	if (in_array($name, $to_secure_list)) {
95
-		if (empty($options['secure']) and defined('_COOKIE_SECURE') and _COOKIE_SECURE) {
96
-			$options['secure'] = true;
97
-		}
98
-		if (empty($options['httponly'])) {
99
-			$options['httponly'] = true;
100
-		}
101
-	}
102
-	if (empty($options['samesite'])) {
103
-		$options['samesite'] = 'Lax';
104
-	}
105
-
106
-	// in fine renommer le prefixe si besoin
107
-	if (strpos($name, 'spip_') === 0) {
108
-		$name = $GLOBALS['cookie_prefix'] . '_' . substr($name, 5);
109
-	}
110
-
111
-	#spip_log("cookie('$name', '$value', " . json_encode($options, true) . ")", "cookies");
112
-	$a = @setcookie($name, $value, $options);
113
-
114
-	spip_cookie_envoye(true);
115
-
116
-	return $a;
55
+    static $to_secure_list = ['spip_session'];
56
+    if (defined('_COOKIE_SECURE_LIST') and is_array(_COOKIE_SECURE_LIST)) {
57
+        $to_secure_list = array_merge($to_secure_list, _COOKIE_SECURE_LIST);
58
+    }
59
+
60
+    if (!is_array($options)) {
61
+        // anciens paramètres :
62
+        # spip_setcookie($name = '', $value = '', $expire = 0, $path = 'AUTO', $domain = '', $secure = '')
63
+        $opt = func_get_args();
64
+        $opt = array_slice($opt, 2);
65
+        $options = []; # /!\ après le func_get_args (sinon $opt[0] référence la nouvelle valeur de $options !);
66
+        if (isset($opt[0])) {
67
+            $options['expires'] = $opt[0];
68
+        }
69
+        if (isset($opt[1])) {
70
+            $options['path'] = $opt[1];
71
+        }
72
+        if (isset($opt[2])) {
73
+            $options['domain'] = $opt[2];
74
+        }
75
+        if (isset($opt[3])) {
76
+            $options['secure'] = $opt[3];
77
+        }
78
+    }
79
+
80
+    // expires
81
+    if (!isset($options['expires'])) {
82
+        $options['expires'] = 0;
83
+    }
84
+    if (!isset($options['path']) or $options['path'] === 'AUTO') {
85
+        if (defined('_COOKIE_PATH')) {
86
+            $options['path'] = _COOKIE_PATH;
87
+        } else {
88
+            $options['path'] = preg_replace(',^\w+://[^/]*,', '', url_de_base());
89
+        }
90
+    }
91
+    if (empty($options['domain']) and defined('_COOKIE_DOMAIN') and _COOKIE_DOMAIN) {
92
+        $options['domain'] = _COOKIE_DOMAIN;
93
+    }
94
+    if (in_array($name, $to_secure_list)) {
95
+        if (empty($options['secure']) and defined('_COOKIE_SECURE') and _COOKIE_SECURE) {
96
+            $options['secure'] = true;
97
+        }
98
+        if (empty($options['httponly'])) {
99
+            $options['httponly'] = true;
100
+        }
101
+    }
102
+    if (empty($options['samesite'])) {
103
+        $options['samesite'] = 'Lax';
104
+    }
105
+
106
+    // in fine renommer le prefixe si besoin
107
+    if (strpos($name, 'spip_') === 0) {
108
+        $name = $GLOBALS['cookie_prefix'] . '_' . substr($name, 5);
109
+    }
110
+
111
+    #spip_log("cookie('$name', '$value', " . json_encode($options, true) . ")", "cookies");
112
+    $a = @setcookie($name, $value, $options);
113
+
114
+    spip_cookie_envoye(true);
115
+
116
+    return $a;
117 117
 }
118 118
 
119 119
 /**
@@ -129,12 +129,12 @@  discard block
 block discarded – undo
129 129
  * @return bool
130 130
  **/
131 131
 function spip_cookie_envoye($set = '') {
132
-	static $envoye = false;
133
-	if ($set) {
134
-		$envoye = true;
135
-	}
132
+    static $envoye = false;
133
+    if ($set) {
134
+        $envoye = true;
135
+    }
136 136
 
137
-	return $envoye;
137
+    return $envoye;
138 138
 }
139 139
 
140 140
 /**
@@ -153,21 +153,21 @@  discard block
 block discarded – undo
153 153
  *     Préfixe des cookies de SPIP
154 154
  **/
155 155
 function recuperer_cookies_spip($cookie_prefix) {
156
-	$prefix_long = strlen($cookie_prefix);
157
-
158
-	foreach ($_COOKIE as $name => $value) {
159
-		if (substr($name, 0, 5) == 'spip_' && substr($name, 0, $prefix_long) != $cookie_prefix) {
160
-			unset($_COOKIE[$name]);
161
-			unset($GLOBALS[$name]);
162
-		}
163
-	}
164
-	foreach ($_COOKIE as $name => $value) {
165
-		if (substr($name, 0, $prefix_long) == $cookie_prefix) {
166
-			$spipname = preg_replace('/^' . $cookie_prefix . '_/', 'spip_', $name);
167
-			$_COOKIE[$spipname] = $value;
168
-			$GLOBALS[$spipname] = $value;
169
-		}
170
-	}
156
+    $prefix_long = strlen($cookie_prefix);
157
+
158
+    foreach ($_COOKIE as $name => $value) {
159
+        if (substr($name, 0, 5) == 'spip_' && substr($name, 0, $prefix_long) != $cookie_prefix) {
160
+            unset($_COOKIE[$name]);
161
+            unset($GLOBALS[$name]);
162
+        }
163
+    }
164
+    foreach ($_COOKIE as $name => $value) {
165
+        if (substr($name, 0, $prefix_long) == $cookie_prefix) {
166
+            $spipname = preg_replace('/^' . $cookie_prefix . '_/', 'spip_', $name);
167
+            $_COOKIE[$spipname] = $value;
168
+            $GLOBALS[$spipname] = $value;
169
+        }
170
+    }
171 171
 }
172 172
 
173 173
 
@@ -186,18 +186,18 @@  discard block
 block discarded – undo
186 186
  *
187 187
  **/
188 188
 function exec_test_ajax_dist() {
189
-	switch (_request('js')) {
190
-		// on est appele par <noscript>
191
-		case -1:
192
-			spip_setcookie('spip_accepte_ajax', -1);
193
-			include_spip('inc/headers');
194
-			redirige_par_entete(chemin_image('erreur-xx.svg'));
195
-			break;
196
-
197
-		// ou par ajax
198
-		case 1:
199
-		default:
200
-			spip_setcookie('spip_accepte_ajax', 1);
201
-			break;
202
-	}
189
+    switch (_request('js')) {
190
+        // on est appele par <noscript>
191
+        case -1:
192
+            spip_setcookie('spip_accepte_ajax', -1);
193
+            include_spip('inc/headers');
194
+            redirige_par_entete(chemin_image('erreur-xx.svg'));
195
+            break;
196
+
197
+        // ou par ajax
198
+        case 1:
199
+        default:
200
+            spip_setcookie('spip_accepte_ajax', 1);
201
+            break;
202
+    }
203 203
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 
106 106
 	// in fine renommer le prefixe si besoin
107 107
 	if (strpos($name, 'spip_') === 0) {
108
-		$name = $GLOBALS['cookie_prefix'] . '_' . substr($name, 5);
108
+		$name = $GLOBALS['cookie_prefix'].'_'.substr($name, 5);
109 109
 	}
110 110
 
111 111
 	#spip_log("cookie('$name', '$value', " . json_encode($options, true) . ")", "cookies");
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 	}
164 164
 	foreach ($_COOKIE as $name => $value) {
165 165
 		if (substr($name, 0, $prefix_long) == $cookie_prefix) {
166
-			$spipname = preg_replace('/^' . $cookie_prefix . '_/', 'spip_', $name);
166
+			$spipname = preg_replace('/^'.$cookie_prefix.'_/', 'spip_', $name);
167 167
 			$_COOKIE[$spipname] = $value;
168 168
 			$GLOBALS[$spipname] = $value;
169 169
 		}
Please login to merge, or discard this patch.
ecrire/inc/distant.php 3 patches
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -121,8 +121,7 @@  discard block
 block discarded – undo
121 121
 		if (!$res or (!$res['length'] and $res['status'] != 304)) {
122 122
 			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
123 123
 			@unlink($localrac_tmp);
124
-		}
125
-		else {
124
+		} else {
126 125
 			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
127 126
 		}
128 127
 		if (!$res or !$res['length']) {
@@ -240,8 +239,7 @@  discard block
 block discarded – undo
240 239
 						break;
241 240
 					}
242 241
 				}
243
-			}
244
-			else {
242
+			} else {
245 243
 				$ip = false;
246 244
 			}
247 245
 		}
Please login to merge, or discard this patch.
Indentation   +1086 added lines, -1086 removed lines patch added patch discarded remove patch
@@ -18,32 +18,32 @@  discard block
 block discarded – undo
18 18
  * @package SPIP\Core\Distant
19 19
  **/
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 
24 24
 if (!defined('_INC_DISTANT_VERSION_HTTP')) {
25
-	define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
25
+    define('_INC_DISTANT_VERSION_HTTP', 'HTTP/1.0');
26 26
 }
27 27
 if (!defined('_INC_DISTANT_CONTENT_ENCODING')) {
28
-	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
28
+    define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
29 29
 }
30 30
 if (!defined('_INC_DISTANT_USER_AGENT')) {
31
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
31
+    define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
32 32
 }
33 33
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
34
-	define('_INC_DISTANT_MAX_SIZE', 2_097_152);
34
+    define('_INC_DISTANT_MAX_SIZE', 2_097_152);
35 35
 }
36 36
 if (!defined('_INC_DISTANT_CONNECT_TIMEOUT')) {
37
-	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
37
+    define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
38 38
 }
39 39
 
40 40
 define('_REGEXP_COPIE_LOCALE', ',' 	.
41
-	preg_replace(
42
-		'@^https?:@',
43
-		'https?:',
44
-		($GLOBALS['meta']['adresse_site'] ?? '')
45
-	)
46
-	. '/?spip.php[?]action=acceder_document.*file=(.*)$,');
41
+    preg_replace(
42
+        '@^https?:@',
43
+        'https?:',
44
+        ($GLOBALS['meta']['adresse_site'] ?? '')
45
+    )
46
+    . '/?spip.php[?]action=acceder_document.*file=(.*)$,');
47 47
 
48 48
 //@define('_COPIE_LOCALE_MAX_SIZE',2097152); // poids (inc/utils l'a fait)
49 49
 
@@ -72,107 +72,107 @@  discard block
 block discarded – undo
72 72
  */
73 73
 function copie_locale($source, $mode = 'auto', $local = null, $taille_max = null, $callback_valider_url = null) {
74 74
 
75
-	// si c'est la protection de soi-meme, retourner le path
76
-	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
77
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
78
-
79
-		return @file_exists($source) ? $source : false;
80
-	}
81
-
82
-	if (is_null($local)) {
83
-		$local = fichier_copie_locale($source);
84
-	} else {
85
-		if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
86
-			$local = substr($local, strlen(_DIR_RACINE));
87
-		}
88
-	}
89
-
90
-	// si $local = '' c'est un fichier refuse par fichier_copie_locale(),
91
-	// par exemple un fichier qui ne figure pas dans nos documents ;
92
-	// dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
93
-	if (!$local) {
94
-		return false;
95
-	}
96
-
97
-	$localrac = _DIR_RACINE . $local;
98
-	$t = ($mode === 'force') ? false : @file_exists($localrac);
99
-
100
-	// test d'existence du fichier
101
-	if ($mode === 'test') {
102
-		return $t ? $local : '';
103
-	}
104
-
105
-	// sinon voir si on doit/peut le telecharger
106
-	if ($local === $source or !tester_url_absolue($source)) {
107
-		return $t ? $local : '';
108
-	}
109
-
110
-	if ($mode === 'modif' or !$t) {
111
-		// passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
112
-		// et des eventuelles recuperations concurantes
113
-		include_spip('inc/acces');
114
-		if (!$taille_max) {
115
-			$taille_max = _COPIE_LOCALE_MAX_SIZE;
116
-		}
117
-		$localrac_tmp = $localrac . '.tmp';
118
-		$res = recuperer_url(
119
-			$source,
120
-			['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
121
-		);
122
-
123
-		if (!$res or (!$res['length'] and $res['status'] != 304)) {
124
-			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
125
-			@unlink($localrac_tmp);
126
-		}
127
-		else {
128
-			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
129
-		}
130
-		if (!$res or !$res['length']) {
131
-			// si $t c'est sans doute juste un not-modified-since
132
-			return $t ? $local : false;
133
-		}
134
-
135
-		// si option valider url, verifions que l'URL finale est acceptable
136
-		if (
137
-			$callback_valider_url
138
-			and is_callable($callback_valider_url)
139
-			and !$callback_valider_url($res['url'])
140
-		) {
141
-			spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
142
-			@unlink($localrac_tmp);
143
-			return $t ? $local : false;
144
-		}
145
-
146
-		// on peut renommer le fichier tmp
147
-		@rename($localrac_tmp, $localrac);
148
-
149
-		// si on retrouve l'extension
150
-		if (
151
-			!empty($res['headers'])
152
-			and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
153
-		) {
154
-			if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
155
-				$sanitizer($localrac);
156
-			}
157
-		}
158
-
159
-		// pour une eventuelle indexation
160
-		pipeline(
161
-			'post_edition',
162
-			[
163
-				'args' => [
164
-					'operation' => 'copie_locale',
165
-					'source' => $source,
166
-					'fichier' => $local,
167
-					'http_res' => $res['length'],
168
-					'url' => $res['url'],
169
-				],
170
-				'data' => null
171
-			]
172
-		);
173
-	}
174
-
175
-	return $local;
75
+    // si c'est la protection de soi-meme, retourner le path
76
+    if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
77
+        $source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
78
+
79
+        return @file_exists($source) ? $source : false;
80
+    }
81
+
82
+    if (is_null($local)) {
83
+        $local = fichier_copie_locale($source);
84
+    } else {
85
+        if (_DIR_RACINE and strncmp(_DIR_RACINE, $local, strlen(_DIR_RACINE)) == 0) {
86
+            $local = substr($local, strlen(_DIR_RACINE));
87
+        }
88
+    }
89
+
90
+    // si $local = '' c'est un fichier refuse par fichier_copie_locale(),
91
+    // par exemple un fichier qui ne figure pas dans nos documents ;
92
+    // dans ce cas on n'essaie pas de le telecharger pour ensuite echouer
93
+    if (!$local) {
94
+        return false;
95
+    }
96
+
97
+    $localrac = _DIR_RACINE . $local;
98
+    $t = ($mode === 'force') ? false : @file_exists($localrac);
99
+
100
+    // test d'existence du fichier
101
+    if ($mode === 'test') {
102
+        return $t ? $local : '';
103
+    }
104
+
105
+    // sinon voir si on doit/peut le telecharger
106
+    if ($local === $source or !tester_url_absolue($source)) {
107
+        return $t ? $local : '';
108
+    }
109
+
110
+    if ($mode === 'modif' or !$t) {
111
+        // passer par un fichier temporaire unique pour gerer les echecs en cours de recuperation
112
+        // et des eventuelles recuperations concurantes
113
+        include_spip('inc/acces');
114
+        if (!$taille_max) {
115
+            $taille_max = _COPIE_LOCALE_MAX_SIZE;
116
+        }
117
+        $localrac_tmp = $localrac . '.tmp';
118
+        $res = recuperer_url(
119
+            $source,
120
+            ['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
121
+        );
122
+
123
+        if (!$res or (!$res['length'] and $res['status'] != 304)) {
124
+            spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
125
+            @unlink($localrac_tmp);
126
+        }
127
+        else {
128
+            spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
129
+        }
130
+        if (!$res or !$res['length']) {
131
+            // si $t c'est sans doute juste un not-modified-since
132
+            return $t ? $local : false;
133
+        }
134
+
135
+        // si option valider url, verifions que l'URL finale est acceptable
136
+        if (
137
+            $callback_valider_url
138
+            and is_callable($callback_valider_url)
139
+            and !$callback_valider_url($res['url'])
140
+        ) {
141
+            spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
142
+            @unlink($localrac_tmp);
143
+            return $t ? $local : false;
144
+        }
145
+
146
+        // on peut renommer le fichier tmp
147
+        @rename($localrac_tmp, $localrac);
148
+
149
+        // si on retrouve l'extension
150
+        if (
151
+            !empty($res['headers'])
152
+            and $extension = distant_trouver_extension_selon_headers($source, $res['headers'])
153
+        ) {
154
+            if ($sanitizer = charger_fonction($extension, 'sanitizer', true)) {
155
+                $sanitizer($localrac);
156
+            }
157
+        }
158
+
159
+        // pour une eventuelle indexation
160
+        pipeline(
161
+            'post_edition',
162
+            [
163
+                'args' => [
164
+                    'operation' => 'copie_locale',
165
+                    'source' => $source,
166
+                    'fichier' => $local,
167
+                    'http_res' => $res['length'],
168
+                    'url' => $res['url'],
169
+                ],
170
+                'data' => null
171
+            ]
172
+        );
173
+    }
174
+
175
+    return $local;
176 176
 }
177 177
 
178 178
 /**
@@ -187,99 +187,99 @@  discard block
 block discarded – undo
187 187
  *   url ou false en cas d'echec
188 188
  */
189 189
 function valider_url_distante($url, $known_hosts = []) {
190
-	if (!function_exists('protocole_verifier')) {
191
-		include_spip('inc/filtres_mini');
192
-	}
193
-
194
-	if (!protocole_verifier($url, ['http', 'https'])) {
195
-		return false;
196
-	}
197
-
198
-	$parsed_url = parse_url($url);
199
-	if (!$parsed_url or empty($parsed_url['host'])) {
200
-		return false;
201
-	}
202
-
203
-	if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
204
-		return false;
205
-	}
206
-
207
-	if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
208
-		return false;
209
-	}
210
-
211
-	if (!is_array($known_hosts)) {
212
-		$known_hosts = [$known_hosts];
213
-	}
214
-	$known_hosts[] = $GLOBALS['meta']['adresse_site'];
215
-	$known_hosts[] = url_de_base();
216
-	$known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
217
-
218
-	$is_known_host = false;
219
-	foreach ($known_hosts as $known_host) {
220
-		$parse_known = parse_url($known_host);
221
-		if (
222
-			$parse_known
223
-			and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
224
-		) {
225
-			$is_known_host = true;
226
-			break;
227
-		}
228
-	}
229
-
230
-	if (!$is_known_host) {
231
-		$host = trim($parsed_url['host'], '.');
232
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
233
-			$ip = gethostbyname($host);
234
-			if ($ip === $host) {
235
-				// Error condition for gethostbyname()
236
-				$ip = false;
237
-			}
238
-			if ($records = dns_get_record($host)) {
239
-				foreach ($records as $record) {
240
-					// il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
241
-					// se fasse sur la meme IP
242
-					if ($record['ttl'] < 10) {
243
-						$ip = false;
244
-						break;
245
-					}
246
-				}
247
-			}
248
-			else {
249
-				$ip = false;
250
-			}
251
-		}
252
-		if ($ip) {
253
-			if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
254
-				return false;
255
-			}
256
-		}
257
-	}
258
-
259
-	if (empty($parsed_url['port'])) {
260
-		return $url;
261
-	}
262
-
263
-	$port = $parsed_url['port'];
264
-	if ($port === 80  or $port === 443  or $port === 8080) {
265
-		return $url;
266
-	}
267
-
268
-	if ($is_known_host) {
269
-		foreach ($known_hosts as $known_host) {
270
-			$parse_known = parse_url($known_host);
271
-			if (
272
-				$parse_known
273
-				and !empty($parse_known['port'])
274
-				and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
275
-				and $parse_known['port'] == $port
276
-			) {
277
-				return $url;
278
-			}
279
-		}
280
-	}
281
-
282
-	return false;
190
+    if (!function_exists('protocole_verifier')) {
191
+        include_spip('inc/filtres_mini');
192
+    }
193
+
194
+    if (!protocole_verifier($url, ['http', 'https'])) {
195
+        return false;
196
+    }
197
+
198
+    $parsed_url = parse_url($url);
199
+    if (!$parsed_url or empty($parsed_url['host'])) {
200
+        return false;
201
+    }
202
+
203
+    if (isset($parsed_url['user']) or isset($parsed_url['pass'])) {
204
+        return false;
205
+    }
206
+
207
+    if (false !== strpbrk($parsed_url['host'], ':#?[]')) {
208
+        return false;
209
+    }
210
+
211
+    if (!is_array($known_hosts)) {
212
+        $known_hosts = [$known_hosts];
213
+    }
214
+    $known_hosts[] = $GLOBALS['meta']['adresse_site'];
215
+    $known_hosts[] = url_de_base();
216
+    $known_hosts = pipeline('declarer_hosts_distants', $known_hosts);
217
+
218
+    $is_known_host = false;
219
+    foreach ($known_hosts as $known_host) {
220
+        $parse_known = parse_url($known_host);
221
+        if (
222
+            $parse_known
223
+            and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
224
+        ) {
225
+            $is_known_host = true;
226
+            break;
227
+        }
228
+    }
229
+
230
+    if (!$is_known_host) {
231
+        $host = trim($parsed_url['host'], '.');
232
+        if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
233
+            $ip = gethostbyname($host);
234
+            if ($ip === $host) {
235
+                // Error condition for gethostbyname()
236
+                $ip = false;
237
+            }
238
+            if ($records = dns_get_record($host)) {
239
+                foreach ($records as $record) {
240
+                    // il faut que le TTL soit suffisant afin d'etre certain que le copie_locale eventuel qui suit
241
+                    // se fasse sur la meme IP
242
+                    if ($record['ttl'] < 10) {
243
+                        $ip = false;
244
+                        break;
245
+                    }
246
+                }
247
+            }
248
+            else {
249
+                $ip = false;
250
+            }
251
+        }
252
+        if ($ip) {
253
+            if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
254
+                return false;
255
+            }
256
+        }
257
+    }
258
+
259
+    if (empty($parsed_url['port'])) {
260
+        return $url;
261
+    }
262
+
263
+    $port = $parsed_url['port'];
264
+    if ($port === 80  or $port === 443  or $port === 8080) {
265
+        return $url;
266
+    }
267
+
268
+    if ($is_known_host) {
269
+        foreach ($known_hosts as $known_host) {
270
+            $parse_known = parse_url($known_host);
271
+            if (
272
+                $parse_known
273
+                and !empty($parse_known['port'])
274
+                and strtolower($parse_known['host']) === strtolower($parsed_url['host'])
275
+                and $parse_known['port'] == $port
276
+            ) {
277
+                return $url;
278
+            }
279
+        }
280
+    }
281
+
282
+    return false;
283 283
 }
284 284
 
285 285
 /**
@@ -299,86 +299,86 @@  discard block
 block discarded – undo
299 299
  */
300 300
 function prepare_donnees_post($donnees, $boundary = '') {
301 301
 
302
-	// permettre a la fonction qui a demande le post de formater elle meme ses donnees
303
-	// pour un appel soap par exemple
304
-	// l'entete est separe des donnees par un double retour a la ligne
305
-	// on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
306
-	if (is_string($donnees) && strlen($donnees)) {
307
-		$entete = '';
308
-		// on repasse tous les \r\n et \r en simples \n
309
-		$donnees = str_replace("\r\n", "\n", $donnees);
310
-		$donnees = str_replace("\r", "\n", $donnees);
311
-		// un double retour a la ligne signifie la fin de l'entete et le debut des donnees
312
-		$p = strpos($donnees, "\n\n");
313
-		if ($p !== false) {
314
-			$entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
315
-			$donnees = substr($donnees, $p + 2);
316
-		}
317
-		$chaine = str_replace("\n", "\r\n", $donnees);
318
-	} else {
319
-		/* boundary automatique */
320
-		// Si on a plus de 500 octects de donnees, on "boundarise"
321
-		if ($boundary === '') {
322
-			$taille = 0;
323
-			foreach ($donnees as $cle => $valeur) {
324
-				if (is_array($valeur)) {
325
-					foreach ($valeur as $val2) {
326
-						$taille += strlen($val2);
327
-					}
328
-				} else {
329
-					// faut-il utiliser spip_strlen() dans inc/charsets ?
330
-					$taille += strlen($valeur);
331
-				}
332
-			}
333
-			if ($taille > 500) {
334
-				$boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
335
-			}
336
-		}
337
-
338
-		if (is_string($boundary) and strlen($boundary)) {
339
-			// fabrique une chaine HTTP pour un POST avec boundary
340
-			$entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
341
-			$chaine = '';
342
-			if (is_array($donnees)) {
343
-				foreach ($donnees as $cle => $valeur) {
344
-					if (is_array($valeur)) {
345
-						foreach ($valeur as $val2) {
346
-							$chaine .= "\r\n--$boundary\r\n";
347
-							$chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
348
-							$chaine .= "\r\n";
349
-							$chaine .= $val2;
350
-						}
351
-					} else {
352
-						$chaine .= "\r\n--$boundary\r\n";
353
-						$chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
354
-						$chaine .= "\r\n";
355
-						$chaine .= $valeur;
356
-					}
357
-				}
358
-				$chaine .= "\r\n--$boundary\r\n";
359
-			}
360
-		} else {
361
-			// fabrique une chaine HTTP simple pour un POST
362
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
363
-			$chaine = [];
364
-			if (is_array($donnees)) {
365
-				foreach ($donnees as $cle => $valeur) {
366
-					if (is_array($valeur)) {
367
-						foreach ($valeur as $val2) {
368
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
369
-						}
370
-					} else {
371
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
372
-					}
373
-				}
374
-				$chaine = implode('&', $chaine);
375
-			} else {
376
-				$chaine = $donnees;
377
-			}
378
-		}
379
-	}
380
-
381
-	return [$entete, $chaine];
302
+    // permettre a la fonction qui a demande le post de formater elle meme ses donnees
303
+    // pour un appel soap par exemple
304
+    // l'entete est separe des donnees par un double retour a la ligne
305
+    // on s'occupe ici de passer tous les retours lignes (\r\n, \r ou \n) en \r\n
306
+    if (is_string($donnees) && strlen($donnees)) {
307
+        $entete = '';
308
+        // on repasse tous les \r\n et \r en simples \n
309
+        $donnees = str_replace("\r\n", "\n", $donnees);
310
+        $donnees = str_replace("\r", "\n", $donnees);
311
+        // un double retour a la ligne signifie la fin de l'entete et le debut des donnees
312
+        $p = strpos($donnees, "\n\n");
313
+        if ($p !== false) {
314
+            $entete = str_replace("\n", "\r\n", substr($donnees, 0, $p + 1));
315
+            $donnees = substr($donnees, $p + 2);
316
+        }
317
+        $chaine = str_replace("\n", "\r\n", $donnees);
318
+    } else {
319
+        /* boundary automatique */
320
+        // Si on a plus de 500 octects de donnees, on "boundarise"
321
+        if ($boundary === '') {
322
+            $taille = 0;
323
+            foreach ($donnees as $cle => $valeur) {
324
+                if (is_array($valeur)) {
325
+                    foreach ($valeur as $val2) {
326
+                        $taille += strlen($val2);
327
+                    }
328
+                } else {
329
+                    // faut-il utiliser spip_strlen() dans inc/charsets ?
330
+                    $taille += strlen($valeur);
331
+                }
332
+            }
333
+            if ($taille > 500) {
334
+                $boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
335
+            }
336
+        }
337
+
338
+        if (is_string($boundary) and strlen($boundary)) {
339
+            // fabrique une chaine HTTP pour un POST avec boundary
340
+            $entete = "Content-Type: multipart/form-data; boundary=$boundary\r\n";
341
+            $chaine = '';
342
+            if (is_array($donnees)) {
343
+                foreach ($donnees as $cle => $valeur) {
344
+                    if (is_array($valeur)) {
345
+                        foreach ($valeur as $val2) {
346
+                            $chaine .= "\r\n--$boundary\r\n";
347
+                            $chaine .= "Content-Disposition: form-data; name=\"{$cle}[]\"\r\n";
348
+                            $chaine .= "\r\n";
349
+                            $chaine .= $val2;
350
+                        }
351
+                    } else {
352
+                        $chaine .= "\r\n--$boundary\r\n";
353
+                        $chaine .= "Content-Disposition: form-data; name=\"$cle\"\r\n";
354
+                        $chaine .= "\r\n";
355
+                        $chaine .= $valeur;
356
+                    }
357
+                }
358
+                $chaine .= "\r\n--$boundary\r\n";
359
+            }
360
+        } else {
361
+            // fabrique une chaine HTTP simple pour un POST
362
+            $entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
363
+            $chaine = [];
364
+            if (is_array($donnees)) {
365
+                foreach ($donnees as $cle => $valeur) {
366
+                    if (is_array($valeur)) {
367
+                        foreach ($valeur as $val2) {
368
+                            $chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
369
+                        }
370
+                    } else {
371
+                        $chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
372
+                    }
373
+                }
374
+                $chaine = implode('&', $chaine);
375
+            } else {
376
+                $chaine = $donnees;
377
+            }
378
+        }
379
+    }
380
+
381
+    return [$entete, $chaine];
382 382
 }
383 383
 
384 384
 /**
@@ -389,19 +389,19 @@  discard block
 block discarded – undo
389 389
  */
390 390
 function url_to_ascii($url_idn) {
391 391
 
392
-	if ($parts = parse_url($url_idn)) {
393
-		$host = $parts['host'];
394
-		if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
395
-			$converter = new ToIdn();
396
-			$host_ascii = $converter->convert($host);
397
-			$url_idn = explode($host, $url_idn, 2);
398
-			$url_idn = implode($host_ascii, $url_idn);
399
-		}
400
-		// et on urlencode les char utf si besoin dans le path
401
-		$url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode($match[0]), $url_idn);
402
-	}
403
-
404
-	return $url_idn;
392
+    if ($parts = parse_url($url_idn)) {
393
+        $host = $parts['host'];
394
+        if (!preg_match(',^[a-z0-9_\.\-]+$,i', $host)) {
395
+            $converter = new ToIdn();
396
+            $host_ascii = $converter->convert($host);
397
+            $url_idn = explode($host, $url_idn, 2);
398
+            $url_idn = implode($host_ascii, $url_idn);
399
+        }
400
+        // et on urlencode les char utf si besoin dans le path
401
+        $url_idn = preg_replace_callback('/[^\x20-\x7f]/', fn($match) => urlencode($match[0]), $url_idn);
402
+    }
403
+
404
+    return $url_idn;
405 405
 }
406 406
 
407 407
 /**
@@ -442,209 +442,209 @@  discard block
 block discarded – undo
442 442
  *     string file : nom du fichier si enregistre dans un fichier
443 443
  */
444 444
 function recuperer_url($url, $options = []) {
445
-	// Conserve la mémoire de la méthode fournit éventuellement
446
-	$methode_demandee = $options['methode'] ?? '';
447
-	$default = [
448
-		'transcoder' => false,
449
-		'methode' => 'GET',
450
-		'taille_max' => null,
451
-		'headers' => [],
452
-		'datas' => '',
453
-		'boundary' => '',
454
-		'refuser_gz' => false,
455
-		'if_modified_since' => '',
456
-		'uri_referer' => '',
457
-		'file' => '',
458
-		'follow_location' => 10,
459
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
460
-	];
461
-	$options = array_merge($default, $options);
462
-	// copier directement dans un fichier ?
463
-	$copy = $options['file'];
464
-
465
-	if ($options['methode'] == 'HEAD') {
466
-		$options['taille_max'] = 0;
467
-	}
468
-	if (is_null($options['taille_max'])) {
469
-		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
470
-	}
471
-
472
-	spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
473
-
474
-	// Ajout des en-têtes spécifiques si besoin
475
-	$formatted_data = '';
476
-	if (!empty($options['headers'])) {
477
-		foreach ($options['headers'] as $champ => $valeur) {
478
-			$formatted_data .= $champ . ': ' . $valeur . "\r\n";
479
-		}
480
-	}
481
-
482
-	if (!empty($options['datas'])) {
483
-		[$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
484
-		$head .= $formatted_data;
485
-		if (stripos($head, 'Content-Length:') === false) {
486
-			$head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
487
-		}
488
-		$formatted_data = $head . "\r\n" . $postdata;
489
-		if (
490
-			strlen($postdata)
491
-			and !$methode_demandee
492
-		) {
493
-			$options['methode'] = 'POST';
494
-		}
495
-	} elseif ($formatted_data) {
496
-		$formatted_data .= "\r\n";
497
-	}
498
-
499
-	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
500
-	$url = preg_replace(',^feed://,i', 'http://', $url);
501
-	if (!tester_url_absolue($url)) {
502
-		$url = 'http://' . $url;
503
-	} elseif (strncmp($url, '//', 2) == 0) {
504
-		$url = 'http:' . $url;
505
-	}
506
-
507
-	$url = url_to_ascii($url);
508
-
509
-	$result = [
510
-		'status' => 0,
511
-		'headers' => '',
512
-		'page' => '',
513
-		'length' => 0,
514
-		'last_modified' => '',
515
-		'location' => '',
516
-		'url' => $url
517
-	];
518
-
519
-	// si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
520
-	$refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
521
-
522
-	// ouvrir la connexion et envoyer la requete et ses en-tetes
523
-	[$handle, $fopen] = init_http(
524
-		$options['methode'],
525
-		$url,
526
-		$refuser_gz,
527
-		$options['uri_referer'],
528
-		$formatted_data,
529
-		$options['version_http'],
530
-		$options['if_modified_since']
531
-	);
532
-	if (!$handle) {
533
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
534
-
535
-		return false;
536
-	}
537
-
538
-	// Sauf en fopen, envoyer le flux d'entree
539
-	// et recuperer les en-tetes de reponses
540
-	if (!$fopen) {
541
-		$res = recuperer_entetes_complets($handle, $options['if_modified_since']);
542
-		if (!$res) {
543
-			fclose($handle);
544
-			$t = @parse_url($url);
545
-			$host = $t['host'];
546
-			// Chinoisierie inexplicable pour contrer
547
-			// les actions liberticides de l'empire du milieu
548
-			if (
549
-				!need_proxy($host)
550
-				and $res = @file_get_contents($url)
551
-			) {
552
-				$result['length'] = strlen($res);
553
-				if ($copy) {
554
-					ecrire_fichier($copy, $res);
555
-					$result['file'] = $copy;
556
-				} else {
557
-					$result['page'] = $res;
558
-				}
559
-				$res = [
560
-					'status' => 200,
561
-				];
562
-			} else {
563
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
564
-				return false;
565
-			}
566
-		} elseif ($res['location'] and $options['follow_location']) {
567
-			$options['follow_location']--;
568
-			fclose($handle);
569
-			include_spip('inc/filtres');
570
-			$url = suivre_lien($url, $res['location']);
571
-
572
-			// une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
573
-			if ($options['methode'] !== 'GET') {
574
-				if (empty($res['status']) or !in_array($res['status'], [307, 308])) {
575
-					$options['methode'] = 'GET';
576
-					$options['datas'] = '';
577
-				}
578
-			}
579
-			spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
580
-
581
-			return recuperer_url($url, $options);
582
-		} elseif ($res['status'] !== 200) {
583
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
584
-		}
585
-		$result['status'] = $res['status'];
586
-		if (isset($res['headers'])) {
587
-			$result['headers'] = $res['headers'];
588
-		}
589
-		if (isset($res['last_modified'])) {
590
-			$result['last_modified'] = $res['last_modified'];
591
-		}
592
-		if (isset($res['location'])) {
593
-			$result['location'] = $res['location'];
594
-		}
595
-	}
596
-
597
-	// on ne veut que les entetes
598
-	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
599
-		spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result), 'distant' . _LOG_DEBUG);
600
-		return $result;
601
-	}
602
-
603
-
604
-	// s'il faut deballer, le faire via un fichier temporaire
605
-	// sinon la memoire explose pour les gros flux
606
-
607
-	$gz = false;
608
-	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
609
-		$gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
610
-	}
611
-
612
-	// si on a pas deja recuperer le contenu par une methode detournee
613
-	if (!$result['length']) {
614
-		$res = recuperer_body($handle, $options['taille_max'], $gz ?: $copy);
615
-		fclose($handle);
616
-		if ($copy) {
617
-			$result['length'] = $res;
618
-			$result['file'] = $copy;
619
-		} elseif ($res) {
620
-			$result['page'] = &$res;
621
-			$result['length'] = strlen($result['page']);
622
-		}
623
-		if (!$result['status']) {
624
-			$result['status'] = 200; // on a reussi, donc !
625
-		}
626
-	}
627
-	if (!$result['page']) {
628
-		return $result;
629
-	}
630
-
631
-	// Decompresser au besoin
632
-	if ($gz) {
633
-		$result['page'] = implode('', gzfile($gz));
634
-		supprimer_fichier($gz);
635
-	}
636
-
637
-	// Faut-il l'importer dans notre charset local ?
638
-	if ($options['transcoder']) {
639
-		include_spip('inc/charsets');
640
-		$result['page'] = transcoder_page($result['page'], $result['headers']);
641
-	}
642
-
643
-	$trace = json_decode(json_encode($result), true);
644
-	$trace['page'] = '...';
645
-	spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace), 'distant' . _LOG_DEBUG);
646
-
647
-	return $result;
445
+    // Conserve la mémoire de la méthode fournit éventuellement
446
+    $methode_demandee = $options['methode'] ?? '';
447
+    $default = [
448
+        'transcoder' => false,
449
+        'methode' => 'GET',
450
+        'taille_max' => null,
451
+        'headers' => [],
452
+        'datas' => '',
453
+        'boundary' => '',
454
+        'refuser_gz' => false,
455
+        'if_modified_since' => '',
456
+        'uri_referer' => '',
457
+        'file' => '',
458
+        'follow_location' => 10,
459
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
460
+    ];
461
+    $options = array_merge($default, $options);
462
+    // copier directement dans un fichier ?
463
+    $copy = $options['file'];
464
+
465
+    if ($options['methode'] == 'HEAD') {
466
+        $options['taille_max'] = 0;
467
+    }
468
+    if (is_null($options['taille_max'])) {
469
+        $options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
470
+    }
471
+
472
+    spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
473
+
474
+    // Ajout des en-têtes spécifiques si besoin
475
+    $formatted_data = '';
476
+    if (!empty($options['headers'])) {
477
+        foreach ($options['headers'] as $champ => $valeur) {
478
+            $formatted_data .= $champ . ': ' . $valeur . "\r\n";
479
+        }
480
+    }
481
+
482
+    if (!empty($options['datas'])) {
483
+        [$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
484
+        $head .= $formatted_data;
485
+        if (stripos($head, 'Content-Length:') === false) {
486
+            $head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
487
+        }
488
+        $formatted_data = $head . "\r\n" . $postdata;
489
+        if (
490
+            strlen($postdata)
491
+            and !$methode_demandee
492
+        ) {
493
+            $options['methode'] = 'POST';
494
+        }
495
+    } elseif ($formatted_data) {
496
+        $formatted_data .= "\r\n";
497
+    }
498
+
499
+    // Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
500
+    $url = preg_replace(',^feed://,i', 'http://', $url);
501
+    if (!tester_url_absolue($url)) {
502
+        $url = 'http://' . $url;
503
+    } elseif (strncmp($url, '//', 2) == 0) {
504
+        $url = 'http:' . $url;
505
+    }
506
+
507
+    $url = url_to_ascii($url);
508
+
509
+    $result = [
510
+        'status' => 0,
511
+        'headers' => '',
512
+        'page' => '',
513
+        'length' => 0,
514
+        'last_modified' => '',
515
+        'location' => '',
516
+        'url' => $url
517
+    ];
518
+
519
+    // si on ecrit directement dans un fichier, pour ne pas manipuler en memoire refuser gz
520
+    $refuser_gz = (($options['refuser_gz'] or $copy) ? true : false);
521
+
522
+    // ouvrir la connexion et envoyer la requete et ses en-tetes
523
+    [$handle, $fopen] = init_http(
524
+        $options['methode'],
525
+        $url,
526
+        $refuser_gz,
527
+        $options['uri_referer'],
528
+        $formatted_data,
529
+        $options['version_http'],
530
+        $options['if_modified_since']
531
+    );
532
+    if (!$handle) {
533
+        spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
534
+
535
+        return false;
536
+    }
537
+
538
+    // Sauf en fopen, envoyer le flux d'entree
539
+    // et recuperer les en-tetes de reponses
540
+    if (!$fopen) {
541
+        $res = recuperer_entetes_complets($handle, $options['if_modified_since']);
542
+        if (!$res) {
543
+            fclose($handle);
544
+            $t = @parse_url($url);
545
+            $host = $t['host'];
546
+            // Chinoisierie inexplicable pour contrer
547
+            // les actions liberticides de l'empire du milieu
548
+            if (
549
+                !need_proxy($host)
550
+                and $res = @file_get_contents($url)
551
+            ) {
552
+                $result['length'] = strlen($res);
553
+                if ($copy) {
554
+                    ecrire_fichier($copy, $res);
555
+                    $result['file'] = $copy;
556
+                } else {
557
+                    $result['page'] = $res;
558
+                }
559
+                $res = [
560
+                    'status' => 200,
561
+                ];
562
+            } else {
563
+                spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
564
+                return false;
565
+            }
566
+        } elseif ($res['location'] and $options['follow_location']) {
567
+            $options['follow_location']--;
568
+            fclose($handle);
569
+            include_spip('inc/filtres');
570
+            $url = suivre_lien($url, $res['location']);
571
+
572
+            // une redirection doit se faire en GET, sauf status explicite 307 ou 308 qui indique de garder la meme methode
573
+            if ($options['methode'] !== 'GET') {
574
+                if (empty($res['status']) or !in_array($res['status'], [307, 308])) {
575
+                    $options['methode'] = 'GET';
576
+                    $options['datas'] = '';
577
+                }
578
+            }
579
+            spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
580
+
581
+            return recuperer_url($url, $options);
582
+        } elseif ($res['status'] !== 200) {
583
+            spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
584
+        }
585
+        $result['status'] = $res['status'];
586
+        if (isset($res['headers'])) {
587
+            $result['headers'] = $res['headers'];
588
+        }
589
+        if (isset($res['last_modified'])) {
590
+            $result['last_modified'] = $res['last_modified'];
591
+        }
592
+        if (isset($res['location'])) {
593
+            $result['location'] = $res['location'];
594
+        }
595
+    }
596
+
597
+    // on ne veut que les entetes
598
+    if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
599
+        spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result), 'distant' . _LOG_DEBUG);
600
+        return $result;
601
+    }
602
+
603
+
604
+    // s'il faut deballer, le faire via un fichier temporaire
605
+    // sinon la memoire explose pour les gros flux
606
+
607
+    $gz = false;
608
+    if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
609
+        $gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
610
+    }
611
+
612
+    // si on a pas deja recuperer le contenu par une methode detournee
613
+    if (!$result['length']) {
614
+        $res = recuperer_body($handle, $options['taille_max'], $gz ?: $copy);
615
+        fclose($handle);
616
+        if ($copy) {
617
+            $result['length'] = $res;
618
+            $result['file'] = $copy;
619
+        } elseif ($res) {
620
+            $result['page'] = &$res;
621
+            $result['length'] = strlen($result['page']);
622
+        }
623
+        if (!$result['status']) {
624
+            $result['status'] = 200; // on a reussi, donc !
625
+        }
626
+    }
627
+    if (!$result['page']) {
628
+        return $result;
629
+    }
630
+
631
+    // Decompresser au besoin
632
+    if ($gz) {
633
+        $result['page'] = implode('', gzfile($gz));
634
+        supprimer_fichier($gz);
635
+    }
636
+
637
+    // Faut-il l'importer dans notre charset local ?
638
+    if ($options['transcoder']) {
639
+        include_spip('inc/charsets');
640
+        $result['page'] = transcoder_page($result['page'], $result['headers']);
641
+    }
642
+
643
+    $trace = json_decode(json_encode($result), true);
644
+    $trace['page'] = '...';
645
+    spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace), 'distant' . _LOG_DEBUG);
646
+
647
+    return $result;
648 648
 }
649 649
 
650 650
 /**
@@ -660,73 +660,73 @@  discard block
 block discarded – undo
660 660
  * @return array|bool|mixed
661 661
  */
662 662
 function recuperer_url_cache($url, $options = []) {
663
-	if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
664
-		define('_DELAI_RECUPERER_URL_CACHE', 3600);
665
-	}
666
-	$default = [
667
-		'transcoder' => false,
668
-		'methode' => 'GET',
669
-		'taille_max' => null,
670
-		'datas' => '',
671
-		'boundary' => '',
672
-		'refuser_gz' => false,
673
-		'if_modified_since' => '',
674
-		'uri_referer' => '',
675
-		'file' => '',
676
-		'follow_location' => 10,
677
-		'version_http' => _INC_DISTANT_VERSION_HTTP,
678
-		'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
679
-	];
680
-	$options = array_merge($default, $options);
681
-
682
-	// cas ou il n'est pas possible de cacher
683
-	if (!empty($options['data']) or $options['methode'] == 'POST') {
684
-		return recuperer_url($url, $options);
685
-	}
686
-
687
-	// ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
688
-	static $errors = [];
689
-	if (isset($errors[$url])) {
690
-		return $errors[$url];
691
-	}
692
-
693
-	$sig = $options;
694
-	unset($sig['if_modified_since']);
695
-	unset($sig['delai_cache']);
696
-	$sig['url'] = $url;
697
-
698
-	$dir = sous_repertoire(_DIR_CACHE, 'curl');
699
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
700
-	$sub = sous_repertoire($dir, substr($cache, 0, 2));
701
-	$cache = "$sub$cache";
702
-
703
-	$res = false;
704
-	$is_cached = file_exists($cache);
705
-	if (
706
-		$is_cached
707
-		and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
708
-	) {
709
-		lire_fichier($cache, $res);
710
-		if ($res = unserialize($res)) {
711
-			// mettre le last_modified et le status=304 ?
712
-		}
713
-	}
714
-	if (!$res) {
715
-		$res = recuperer_url($url, $options);
716
-		// ne pas recharger cette url non cachee dans le meme hit puisque non disponible
717
-		if (!$res) {
718
-			if ($is_cached) {
719
-				// on a pas reussi a recuperer mais on avait un cache : l'utiliser
720
-				lire_fichier($cache, $res);
721
-				$res = unserialize($res);
722
-			}
723
-
724
-			return $errors[$url] = $res;
725
-		}
726
-		ecrire_fichier($cache, serialize($res));
727
-	}
728
-
729
-	return $res;
663
+    if (!defined('_DELAI_RECUPERER_URL_CACHE')) {
664
+        define('_DELAI_RECUPERER_URL_CACHE', 3600);
665
+    }
666
+    $default = [
667
+        'transcoder' => false,
668
+        'methode' => 'GET',
669
+        'taille_max' => null,
670
+        'datas' => '',
671
+        'boundary' => '',
672
+        'refuser_gz' => false,
673
+        'if_modified_since' => '',
674
+        'uri_referer' => '',
675
+        'file' => '',
676
+        'follow_location' => 10,
677
+        'version_http' => _INC_DISTANT_VERSION_HTTP,
678
+        'delai_cache' => in_array(_VAR_MODE, ['preview', 'recalcul']) ? 0 : _DELAI_RECUPERER_URL_CACHE,
679
+    ];
680
+    $options = array_merge($default, $options);
681
+
682
+    // cas ou il n'est pas possible de cacher
683
+    if (!empty($options['data']) or $options['methode'] == 'POST') {
684
+        return recuperer_url($url, $options);
685
+    }
686
+
687
+    // ne pas tenter plusieurs fois la meme url en erreur (non cachee donc)
688
+    static $errors = [];
689
+    if (isset($errors[$url])) {
690
+        return $errors[$url];
691
+    }
692
+
693
+    $sig = $options;
694
+    unset($sig['if_modified_since']);
695
+    unset($sig['delai_cache']);
696
+    $sig['url'] = $url;
697
+
698
+    $dir = sous_repertoire(_DIR_CACHE, 'curl');
699
+    $cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
700
+    $sub = sous_repertoire($dir, substr($cache, 0, 2));
701
+    $cache = "$sub$cache";
702
+
703
+    $res = false;
704
+    $is_cached = file_exists($cache);
705
+    if (
706
+        $is_cached
707
+        and (filemtime($cache) > $_SERVER['REQUEST_TIME'] - $options['delai_cache'])
708
+    ) {
709
+        lire_fichier($cache, $res);
710
+        if ($res = unserialize($res)) {
711
+            // mettre le last_modified et le status=304 ?
712
+        }
713
+    }
714
+    if (!$res) {
715
+        $res = recuperer_url($url, $options);
716
+        // ne pas recharger cette url non cachee dans le meme hit puisque non disponible
717
+        if (!$res) {
718
+            if ($is_cached) {
719
+                // on a pas reussi a recuperer mais on avait un cache : l'utiliser
720
+                lire_fichier($cache, $res);
721
+                $res = unserialize($res);
722
+            }
723
+
724
+            return $errors[$url] = $res;
725
+        }
726
+        ecrire_fichier($cache, serialize($res));
727
+    }
728
+
729
+    return $res;
730 730
 }
731 731
 
732 732
 /**
@@ -744,42 +744,42 @@  discard block
 block discarded – undo
744 744
  *   string contenu de la resource
745 745
  */
746 746
 function recuperer_body($handle, $taille_max = _INC_DISTANT_MAX_SIZE, $fichier = '') {
747
-	$tmpfile = null;
748
-	$taille = 0;
749
-	$result = '';
750
-	$fp = false;
751
-	if ($fichier) {
752
-		include_spip('inc/acces');
753
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
754
-		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
755
-		if (!$fp and file_exists($fichier)) {
756
-			return filesize($fichier);
757
-		}
758
-		if (!$fp) {
759
-			return false;
760
-		}
761
-		$result = 0; // on renvoie la taille du fichier
762
-	}
763
-	while (!feof($handle) and $taille < $taille_max) {
764
-		$res = fread($handle, 16384);
765
-		$taille += strlen($res);
766
-		if ($fp) {
767
-			fwrite($fp, $res);
768
-			$result = $taille;
769
-		} else {
770
-			$result .= $res;
771
-		}
772
-	}
773
-	if ($fp) {
774
-		spip_fclose_unlock($fp);
775
-		spip_unlink($fichier);
776
-		@rename($tmpfile, $fichier);
777
-		if (!file_exists($fichier)) {
778
-			return false;
779
-		}
780
-	}
781
-
782
-	return $result;
747
+    $tmpfile = null;
748
+    $taille = 0;
749
+    $result = '';
750
+    $fp = false;
751
+    if ($fichier) {
752
+        include_spip('inc/acces');
753
+        $tmpfile = "$fichier." . creer_uniqid() . '.tmp';
754
+        $fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
755
+        if (!$fp and file_exists($fichier)) {
756
+            return filesize($fichier);
757
+        }
758
+        if (!$fp) {
759
+            return false;
760
+        }
761
+        $result = 0; // on renvoie la taille du fichier
762
+    }
763
+    while (!feof($handle) and $taille < $taille_max) {
764
+        $res = fread($handle, 16384);
765
+        $taille += strlen($res);
766
+        if ($fp) {
767
+            fwrite($fp, $res);
768
+            $result = $taille;
769
+        } else {
770
+            $result .= $res;
771
+        }
772
+    }
773
+    if ($fp) {
774
+        spip_fclose_unlock($fp);
775
+        spip_unlink($fichier);
776
+        @rename($tmpfile, $fichier);
777
+        if (!file_exists($fichier)) {
778
+            return false;
779
+        }
780
+    }
781
+
782
+    return $result;
783 783
 }
784 784
 
785 785
 /**
@@ -801,35 +801,35 @@  discard block
 block discarded – undo
801 801
  *   string location
802 802
  */
803 803
 function recuperer_entetes_complets($handle, $if_modified_since = false) {
804
-	$result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
805
-
806
-	$s = @trim(fgets($handle, 16384));
807
-	if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
808
-		return false;
809
-	}
810
-	$result['status'] = intval($r[1]);
811
-	while ($s = trim(fgets($handle, 16384))) {
812
-		$result['headers'][] = $s . "\n";
813
-		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
814
-		[, $d, $v] = $r;
815
-		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
816
-			$result['location'] = $v;
817
-		} elseif ($d == 'Last-Modified') {
818
-			$result['last_modified'] = strtotime($v);
819
-		}
820
-	}
821
-	if (
822
-		$if_modified_since
823
-		and $result['last_modified']
824
-		and $if_modified_since > $result['last_modified']
825
-		and $result['status'] == 200
826
-	) {
827
-		$result['status'] = 304;
828
-	}
829
-
830
-	$result['headers'] = implode('', $result['headers']);
831
-
832
-	return $result;
804
+    $result = ['status' => 0, 'headers' => [], 'last_modified' => 0, 'location' => ''];
805
+
806
+    $s = @trim(fgets($handle, 16384));
807
+    if (!preg_match(',^HTTP/[0-9]+\.[0-9]+ ([0-9]+),', $s, $r)) {
808
+        return false;
809
+    }
810
+    $result['status'] = intval($r[1]);
811
+    while ($s = trim(fgets($handle, 16384))) {
812
+        $result['headers'][] = $s . "\n";
813
+        preg_match(',^([^:]*): *(.*)$,i', $s, $r);
814
+        [, $d, $v] = $r;
815
+        if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
816
+            $result['location'] = $v;
817
+        } elseif ($d == 'Last-Modified') {
818
+            $result['last_modified'] = strtotime($v);
819
+        }
820
+    }
821
+    if (
822
+        $if_modified_since
823
+        and $result['last_modified']
824
+        and $if_modified_since > $result['last_modified']
825
+        and $result['status'] == 200
826
+    ) {
827
+        $result['status'] = 304;
828
+    }
829
+
830
+    $result['headers'] = implode('', $result['headers']);
831
+
832
+    return $result;
833 833
 }
834 834
 
835 835
 /**
@@ -851,22 +851,22 @@  discard block
 block discarded – undo
851 851
  *     Nom du fichier pour copie locale
852 852
  **/
853 853
 function nom_fichier_copie_locale($source, $extension) {
854
-	include_spip('inc/documents');
854
+    include_spip('inc/documents');
855 855
 
856
-	$d = creer_repertoire_documents('distant'); # IMG/distant/
857
-	$d = sous_repertoire($d, $extension); # IMG/distant/pdf/
856
+    $d = creer_repertoire_documents('distant'); # IMG/distant/
857
+    $d = sous_repertoire($d, $extension); # IMG/distant/pdf/
858 858
 
859
-	// on se place tout le temps comme si on etait a la racine
860
-	if (_DIR_RACINE) {
861
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
862
-	}
859
+    // on se place tout le temps comme si on etait a la racine
860
+    if (_DIR_RACINE) {
861
+        $d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
862
+    }
863 863
 
864
-	$m = md5($source);
864
+    $m = md5($source);
865 865
 
866
-	return $d
867
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
868
-	. substr($m, 0, 4)
869
-	. ".$extension";
866
+    return $d
867
+    . substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
868
+    . substr($m, 0, 4)
869
+    . ".$extension";
870 870
 }
871 871
 
872 872
 /**
@@ -885,72 +885,72 @@  discard block
 block discarded – undo
885 885
  *      - null: Copie locale impossible
886 886
  **/
887 887
 function fichier_copie_locale($source) {
888
-	// Si c'est deja local pas de souci
889
-	if (!tester_url_absolue($source)) {
890
-		if (_DIR_RACINE) {
891
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
892
-		}
893
-
894
-		return $source;
895
-	}
896
-
897
-	// optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
898
-	// a deja ete copie en local avec cette extension
899
-	// dans ce cas elle est fiable, pas la peine de requeter en base
900
-	$path_parts = pathinfo($source);
901
-	if (!isset($path_parts['extension'])) {
902
-		$path_parts['extension'] = '';
903
-	}
904
-	$ext = $path_parts ? $path_parts['extension'] : '';
905
-	if (
906
-		$ext
907
-		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
908
-		and $f = nom_fichier_copie_locale($source, $ext)
909
-		and file_exists(_DIR_RACINE . $f)
910
-	) {
911
-		return $f;
912
-	}
913
-
914
-
915
-	// Si c'est deja dans la table des documents,
916
-	// ramener le nom de sa copie potentielle
917
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
918
-
919
-	if ($ext) {
920
-		return nom_fichier_copie_locale($source, $ext);
921
-	}
922
-
923
-	// voir si l'extension indiquee dans le nom du fichier est ok
924
-	// et si il n'aurait pas deja ete rapatrie
925
-
926
-	$ext = $path_parts ? $path_parts['extension'] : '';
927
-
928
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
929
-		$f = nom_fichier_copie_locale($source, $ext);
930
-		if (file_exists(_DIR_RACINE . $f)) {
931
-			return $f;
932
-		}
933
-	}
934
-
935
-	// Ping  pour voir si son extension est connue et autorisee
936
-	// avec mise en cache du resultat du ping
937
-
938
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
939
-	if (
940
-		!@file_exists($cache)
941
-		or !$path_parts = @unserialize(spip_file_get_contents($cache))
942
-		or _request('var_mode') === 'recalcul'
943
-	) {
944
-		$path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
945
-		ecrire_fichier($cache, serialize($path_parts));
946
-	}
947
-	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
948
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
949
-		return nom_fichier_copie_locale($source, $ext);
950
-	}
951
-
952
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
953
-	return null;
888
+    // Si c'est deja local pas de souci
889
+    if (!tester_url_absolue($source)) {
890
+        if (_DIR_RACINE) {
891
+            $source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
892
+        }
893
+
894
+        return $source;
895
+    }
896
+
897
+    // optimisation : on regarde si on peut deviner l'extension dans l'url et si le fichier
898
+    // a deja ete copie en local avec cette extension
899
+    // dans ce cas elle est fiable, pas la peine de requeter en base
900
+    $path_parts = pathinfo($source);
901
+    if (!isset($path_parts['extension'])) {
902
+        $path_parts['extension'] = '';
903
+    }
904
+    $ext = $path_parts ? $path_parts['extension'] : '';
905
+    if (
906
+        $ext
907
+        and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
908
+        and $f = nom_fichier_copie_locale($source, $ext)
909
+        and file_exists(_DIR_RACINE . $f)
910
+    ) {
911
+        return $f;
912
+    }
913
+
914
+
915
+    // Si c'est deja dans la table des documents,
916
+    // ramener le nom de sa copie potentielle
917
+    $ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
918
+
919
+    if ($ext) {
920
+        return nom_fichier_copie_locale($source, $ext);
921
+    }
922
+
923
+    // voir si l'extension indiquee dans le nom du fichier est ok
924
+    // et si il n'aurait pas deja ete rapatrie
925
+
926
+    $ext = $path_parts ? $path_parts['extension'] : '';
927
+
928
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
929
+        $f = nom_fichier_copie_locale($source, $ext);
930
+        if (file_exists(_DIR_RACINE . $f)) {
931
+            return $f;
932
+        }
933
+    }
934
+
935
+    // Ping  pour voir si son extension est connue et autorisee
936
+    // avec mise en cache du resultat du ping
937
+
938
+    $cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
939
+    if (
940
+        !@file_exists($cache)
941
+        or !$path_parts = @unserialize(spip_file_get_contents($cache))
942
+        or _request('var_mode') === 'recalcul'
943
+    ) {
944
+        $path_parts = recuperer_infos_distantes($source, ['charger_si_petite_image' => false]);
945
+        ecrire_fichier($cache, serialize($path_parts));
946
+    }
947
+    $ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
948
+    if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
949
+        return nom_fichier_copie_locale($source, $ext);
950
+    }
951
+
952
+    spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
953
+    return null;
954 954
 }
955 955
 
956 956
 
@@ -979,110 +979,110 @@  discard block
 block discarded – undo
979 979
  **/
980 980
 function recuperer_infos_distantes($source, $options = []) {
981 981
 
982
-	// pas la peine de perdre son temps
983
-	if (!tester_url_absolue($source)) {
984
-		return false;
985
-	}
986
-
987
-	$taille_max = $options['taille_max'] ?? 0;
988
-	$charger_si_petite_image = !!($options['charger_si_petite_image'] ?? true);
989
-	$callback_valider_url = $options['callback_valider_url'] ?? null;
990
-
991
-	# charger les alias des types mime
992
-	include_spip('base/typedoc');
993
-
994
-	$a = [];
995
-	$mime_type = '';
996
-	// On va directement charger le debut des images et des fichiers html,
997
-	// de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
998
-	// ca echoue l'utilisateur devra les entrer...
999
-	$reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
1000
-	if (
1001
-		$callback_valider_url
1002
-		and is_callable($callback_valider_url)
1003
-		and !$callback_valider_url($reponse['url'])
1004
-	) {
1005
-		return false;
1006
-	}
1007
-	$headers = $reponse['headers'] ?? '';
1008
-	$a['body'] = $reponse['page'] ?? '';
1009
-	if ($headers) {
1010
-		if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1011
-			return false;
1012
-		}
1013
-
1014
-		$a['extension'] = $extension;
1015
-
1016
-		if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1017
-			$a['taille'] = intval($regs[1]);
1018
-		}
1019
-	}
1020
-
1021
-	// Echec avec HEAD, on tente avec GET
1022
-	if (!$a and !$taille_max) {
1023
-		spip_log("tenter GET $source", 'distant');
1024
-		$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1025
-		$a = recuperer_infos_distantes($source, $options);
1026
-	}
1027
-
1028
-	// si on a rien trouve pas la peine d'insister
1029
-	if (!$a) {
1030
-		return false;
1031
-	}
1032
-
1033
-	// S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1034
-	// recharger le document en GET et recuperer des donnees supplementaires...
1035
-	include_spip('inc/filtres_images_lib_mini');
1036
-	if (
1037
-		strpos($mime_type, 'image/') === 0
1038
-		and $extension = _image_trouver_extension_depuis_mime($mime_type)
1039
-	) {
1040
-		if (
1041
-			$taille_max == 0
1042
-			and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1043
-			and in_array($extension, formats_image_acceptables())
1044
-			and $charger_si_petite_image
1045
-		) {
1046
-			$options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1047
-			$a = recuperer_infos_distantes($source, $options);
1048
-		} else {
1049
-			if ($a['body']) {
1050
-				$a['extension'] = $extension;
1051
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1052
-				ecrire_fichier($a['fichier'], $a['body']);
1053
-				$size_image = @spip_getimagesize($a['fichier']);
1054
-				$a['largeur'] = intval($size_image[0]);
1055
-				$a['hauteur'] = intval($size_image[1]);
1056
-				$a['type_image'] = true;
1057
-			}
1058
-		}
1059
-	}
1060
-
1061
-	// Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1062
-	// ce sera mieux que 0x0
1063
-	// Flash is dead!
1064
-	if (
1065
-		$a and isset($a['extension']) and $a['extension'] == 'swf'
1066
-		and empty($a['largeur'])
1067
-	) {
1068
-		$a['largeur'] = 425;
1069
-		$a['hauteur'] = 350;
1070
-	}
1071
-
1072
-	if ($mime_type == 'text/html') {
1073
-		include_spip('inc/filtres');
1074
-		$page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1075
-		$page = $page['page'] ?? '';
1076
-		if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1077
-			$a['titre'] = corriger_caracteres(trim($regs[1]));
1078
-		}
1079
-		if (!isset($a['taille']) or !$a['taille']) {
1080
-			$a['taille'] = strlen($page); # a peu pres
1081
-		}
1082
-	}
1083
-	$a['mime_type'] = $mime_type;
1084
-
1085
-	return $a;
982
+    // pas la peine de perdre son temps
983
+    if (!tester_url_absolue($source)) {
984
+        return false;
985
+    }
986
+
987
+    $taille_max = $options['taille_max'] ?? 0;
988
+    $charger_si_petite_image = !!($options['charger_si_petite_image'] ?? true);
989
+    $callback_valider_url = $options['callback_valider_url'] ?? null;
990
+
991
+    # charger les alias des types mime
992
+    include_spip('base/typedoc');
993
+
994
+    $a = [];
995
+    $mime_type = '';
996
+    // On va directement charger le debut des images et des fichiers html,
997
+    // de maniere a attrapper le maximum d'infos (titre, taille, etc). Si
998
+    // ca echoue l'utilisateur devra les entrer...
999
+    $reponse = recuperer_url($source, ['taille_max' => $taille_max, 'refuser_gz' => true]);
1000
+    if (
1001
+        $callback_valider_url
1002
+        and is_callable($callback_valider_url)
1003
+        and !$callback_valider_url($reponse['url'])
1004
+    ) {
1005
+        return false;
1006
+    }
1007
+    $headers = $reponse['headers'] ?? '';
1008
+    $a['body'] = $reponse['page'] ?? '';
1009
+    if ($headers) {
1010
+        if (!$extension = distant_trouver_extension_selon_headers($source, $headers)) {
1011
+            return false;
1012
+        }
1013
+
1014
+        $a['extension'] = $extension;
1015
+
1016
+        if (preg_match(",\nContent-Length: *([^[:space:]]*),i", "\n$headers", $regs)) {
1017
+            $a['taille'] = intval($regs[1]);
1018
+        }
1019
+    }
1020
+
1021
+    // Echec avec HEAD, on tente avec GET
1022
+    if (!$a and !$taille_max) {
1023
+        spip_log("tenter GET $source", 'distant');
1024
+        $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1025
+        $a = recuperer_infos_distantes($source, $options);
1026
+    }
1027
+
1028
+    // si on a rien trouve pas la peine d'insister
1029
+    if (!$a) {
1030
+        return false;
1031
+    }
1032
+
1033
+    // S'il s'agit d'une image pas trop grosse ou d'un fichier html, on va aller
1034
+    // recharger le document en GET et recuperer des donnees supplementaires...
1035
+    include_spip('inc/filtres_images_lib_mini');
1036
+    if (
1037
+        strpos($mime_type, 'image/') === 0
1038
+        and $extension = _image_trouver_extension_depuis_mime($mime_type)
1039
+    ) {
1040
+        if (
1041
+            $taille_max == 0
1042
+            and (empty($a['taille']) or $a['taille'] < _INC_DISTANT_MAX_SIZE)
1043
+            and in_array($extension, formats_image_acceptables())
1044
+            and $charger_si_petite_image
1045
+        ) {
1046
+            $options['taille_max'] = _INC_DISTANT_MAX_SIZE;
1047
+            $a = recuperer_infos_distantes($source, $options);
1048
+        } else {
1049
+            if ($a['body']) {
1050
+                $a['extension'] = $extension;
1051
+                $a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1052
+                ecrire_fichier($a['fichier'], $a['body']);
1053
+                $size_image = @spip_getimagesize($a['fichier']);
1054
+                $a['largeur'] = intval($size_image[0]);
1055
+                $a['hauteur'] = intval($size_image[1]);
1056
+                $a['type_image'] = true;
1057
+            }
1058
+        }
1059
+    }
1060
+
1061
+    // Fichier swf, si on n'a pas la taille, on va mettre 425x350 par defaut
1062
+    // ce sera mieux que 0x0
1063
+    // Flash is dead!
1064
+    if (
1065
+        $a and isset($a['extension']) and $a['extension'] == 'swf'
1066
+        and empty($a['largeur'])
1067
+    ) {
1068
+        $a['largeur'] = 425;
1069
+        $a['hauteur'] = 350;
1070
+    }
1071
+
1072
+    if ($mime_type == 'text/html') {
1073
+        include_spip('inc/filtres');
1074
+        $page = recuperer_url($source, ['transcoder' => true, 'taille_max' => _INC_DISTANT_MAX_SIZE]);
1075
+        $page = $page['page'] ?? '';
1076
+        if (preg_match(',<title>(.*?)</title>,ims', $page, $regs)) {
1077
+            $a['titre'] = corriger_caracteres(trim($regs[1]));
1078
+        }
1079
+        if (!isset($a['taille']) or !$a['taille']) {
1080
+            $a['taille'] = strlen($page); # a peu pres
1081
+        }
1082
+    }
1083
+    $a['mime_type'] = $mime_type;
1084
+
1085
+    return $a;
1086 1086
 }
1087 1087
 
1088 1088
 /**
@@ -1091,70 +1091,70 @@  discard block
 block discarded – undo
1091 1091
  * @return false|mixed
1092 1092
  */
1093 1093
 function distant_trouver_extension_selon_headers($source, $headers) {
1094
-	if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1095
-		$mime_type = (trim($regs[1]));
1096
-	} else {
1097
-		$mime_type = '';
1098
-	} // inconnu
1099
-
1100
-	// Appliquer les alias
1101
-	while (isset($GLOBALS['mime_alias'][$mime_type])) {
1102
-		$mime_type = $GLOBALS['mime_alias'][$mime_type];
1103
-	}
1104
-
1105
-	// pour corriger_extension()
1106
-	include_spip('inc/documents');
1107
-
1108
-	// Si on a un mime-type insignifiant
1109
-	// text/plain,application/octet-stream ou vide
1110
-	// c'est peut-etre que le serveur ne sait pas
1111
-	// ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1112
-	// ou le Content-Disposition: attachment; filename=...
1113
-	$t = null;
1114
-	if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1115
-		if (
1116
-			!$t
1117
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1118
-		) {
1119
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1120
-		}
1121
-		if (
1122
-			!$t
1123
-			and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1124
-			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1125
-		) {
1126
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1127
-		}
1128
-	}
1129
-
1130
-	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1131
-	if (!$t) {
1132
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1133
-	}
1134
-
1135
-	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1136
-	// On essaie de nouveau avec l'extension
1137
-	if (
1138
-		!$t
1139
-		and $mime_type != 'text/plain'
1140
-		and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1141
-	) {
1142
-		# eviter xxx.3 => 3gp (> SPIP 3)
1143
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1144
-	}
1145
-
1146
-	if ($t) {
1147
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1148
-		return $t['extension'];
1149
-	} else {
1150
-		# par defaut on retombe sur '.bin' si c'est autorise
1151
-		spip_log("mime-type $mime_type inconnu", 'distant');
1152
-		$t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1153
-		if (!$t) {
1154
-			return false;
1155
-		}
1156
-		return $t['extension'];
1157
-	}
1094
+    if (preg_match(",\nContent-Type: *([^[:space:];]*),i", "\n$headers", $regs)) {
1095
+        $mime_type = (trim($regs[1]));
1096
+    } else {
1097
+        $mime_type = '';
1098
+    } // inconnu
1099
+
1100
+    // Appliquer les alias
1101
+    while (isset($GLOBALS['mime_alias'][$mime_type])) {
1102
+        $mime_type = $GLOBALS['mime_alias'][$mime_type];
1103
+    }
1104
+
1105
+    // pour corriger_extension()
1106
+    include_spip('inc/documents');
1107
+
1108
+    // Si on a un mime-type insignifiant
1109
+    // text/plain,application/octet-stream ou vide
1110
+    // c'est peut-etre que le serveur ne sait pas
1111
+    // ce qu'il sert ; on va tenter de detecter via l'extension de l'url
1112
+    // ou le Content-Disposition: attachment; filename=...
1113
+    $t = null;
1114
+    if (in_array($mime_type, ['text/plain', '', 'application/octet-stream'])) {
1115
+        if (
1116
+            !$t
1117
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1118
+        ) {
1119
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1120
+        }
1121
+        if (
1122
+            !$t
1123
+            and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1124
+            and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1125
+        ) {
1126
+            $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1127
+        }
1128
+    }
1129
+
1130
+    // Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1131
+    if (!$t) {
1132
+        $t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1133
+    }
1134
+
1135
+    // Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
1136
+    // On essaie de nouveau avec l'extension
1137
+    if (
1138
+        !$t
1139
+        and $mime_type != 'text/plain'
1140
+        and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1141
+    ) {
1142
+        # eviter xxx.3 => 3gp (> SPIP 3)
1143
+        $t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1144
+    }
1145
+
1146
+    if ($t) {
1147
+        spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1148
+        return $t['extension'];
1149
+    } else {
1150
+        # par defaut on retombe sur '.bin' si c'est autorise
1151
+        spip_log("mime-type $mime_type inconnu", 'distant');
1152
+        $t = sql_fetsel('extension', 'spip_types_documents', "extension='bin'");
1153
+        if (!$t) {
1154
+            return false;
1155
+        }
1156
+        return $t['extension'];
1157
+    }
1158 1158
 }
1159 1159
 
1160 1160
 /**
@@ -1170,45 +1170,45 @@  discard block
 block discarded – undo
1170 1170
  */
1171 1171
 function need_proxy($host, $http_proxy = null, $http_noproxy = null) {
1172 1172
 
1173
-	$http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1174
-
1175
-	// rien a faire si pas de proxy :)
1176
-	if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1177
-		return '';
1178
-	}
1179
-
1180
-	if (is_null($http_noproxy)) {
1181
-		$http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1182
-	}
1183
-	// si pas d'exception, on retourne le proxy
1184
-	if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1185
-		return $http_proxy;
1186
-	}
1187
-
1188
-	// si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1189
-	// $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1190
-	$http_noproxy = str_replace("\n", ' ', $http_noproxy);
1191
-	$http_noproxy = str_replace("\r", ' ', $http_noproxy);
1192
-	$http_noproxy = " $http_noproxy ";
1193
-	$domain = $host;
1194
-	// si le domaine exact www.example.org est dans les exceptions
1195
-	if (strpos($http_noproxy, (string) " $domain ") !== false) {
1196
-		return '';
1197
-	}
1198
-
1199
-	while (strpos($domain, '.') !== false) {
1200
-		$domain = explode('.', $domain);
1201
-		array_shift($domain);
1202
-		$domain = implode('.', $domain);
1203
-
1204
-		// ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1205
-		if (strpos($http_noproxy, (string) " .$domain ") !== false) {
1206
-			return '';
1207
-		}
1208
-	}
1209
-
1210
-	// ok c'est pas une exception
1211
-	return $http_proxy;
1173
+    $http_proxy ??= $GLOBALS['meta']['http_proxy'] ?? null;
1174
+
1175
+    // rien a faire si pas de proxy :)
1176
+    if (is_null($http_proxy) or !$http_proxy = trim($http_proxy)) {
1177
+        return '';
1178
+    }
1179
+
1180
+    if (is_null($http_noproxy)) {
1181
+        $http_noproxy = $GLOBALS['meta']['http_noproxy'] ?? null;
1182
+    }
1183
+    // si pas d'exception, on retourne le proxy
1184
+    if (is_null($http_noproxy) or !$http_noproxy = trim($http_noproxy)) {
1185
+        return $http_proxy;
1186
+    }
1187
+
1188
+    // si le host ou l'un des domaines parents est dans $http_noproxy on fait exception
1189
+    // $http_noproxy peut contenir plusieurs domaines separes par des espaces ou retour ligne
1190
+    $http_noproxy = str_replace("\n", ' ', $http_noproxy);
1191
+    $http_noproxy = str_replace("\r", ' ', $http_noproxy);
1192
+    $http_noproxy = " $http_noproxy ";
1193
+    $domain = $host;
1194
+    // si le domaine exact www.example.org est dans les exceptions
1195
+    if (strpos($http_noproxy, (string) " $domain ") !== false) {
1196
+        return '';
1197
+    }
1198
+
1199
+    while (strpos($domain, '.') !== false) {
1200
+        $domain = explode('.', $domain);
1201
+        array_shift($domain);
1202
+        $domain = implode('.', $domain);
1203
+
1204
+        // ou si un domaine parent commencant par un . est dans les exceptions (indiquant qu'il couvre tous les sous-domaines)
1205
+        if (strpos($http_noproxy, (string) " .$domain ") !== false) {
1206
+            return '';
1207
+        }
1208
+    }
1209
+
1210
+    // ok c'est pas une exception
1211
+    return $http_proxy;
1212 1212
 }
1213 1213
 
1214 1214
 
@@ -1231,59 +1231,59 @@  discard block
 block discarded – undo
1231 1231
  * @return array
1232 1232
  */
1233 1233
 function init_http($method, $url, $refuse_gz = false, $referer = '', $datas = '', $vers = 'HTTP/1.0', $date = '') {
1234
-	$user = $via_proxy = $proxy_user = '';
1235
-	$fopen = false;
1236
-
1237
-	$t = @parse_url($url);
1238
-	$host = $t['host'];
1239
-	if ($t['scheme'] == 'http') {
1240
-		$scheme = 'http';
1241
-		$noproxy = '';
1242
-	} elseif ($t['scheme'] == 'https') {
1243
-		$scheme = 'ssl';
1244
-		$noproxy = 'ssl://';
1245
-		if (!isset($t['port']) || !($port = $t['port'])) {
1246
-			$t['port'] = 443;
1247
-		}
1248
-	} else {
1249
-		$scheme = $t['scheme'];
1250
-		$noproxy = $scheme . '://';
1251
-	}
1252
-	if (isset($t['user'])) {
1253
-		$user = [$t['user'], $t['pass']];
1254
-	}
1255
-
1256
-	if (!isset($t['port']) || !($port = $t['port'])) {
1257
-		$port = 80;
1258
-	}
1259
-	if (!isset($t['path']) || !($path = $t['path'])) {
1260
-		$path = '/';
1261
-	}
1262
-
1263
-	if (!empty($t['query'])) {
1264
-		$path .= '?' . $t['query'];
1265
-	}
1266
-
1267
-	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1268
-	if (!$f or !is_resource($f)) {
1269
-		// fallback : fopen si on a pas fait timeout dans lance_requete
1270
-		// ce qui correspond a $f===110
1271
-		if (
1272
-			$f !== 110
1273
-			and !need_proxy($host)
1274
-			and !_request('tester_proxy')
1275
-			and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1276
-		) {
1277
-			$f = @fopen($url, 'rb');
1278
-			spip_log("connexion vers $url par simple fopen", 'distant');
1279
-			$fopen = true;
1280
-		} else {
1281
-			// echec total
1282
-			$f = false;
1283
-		}
1284
-	}
1285
-
1286
-	return [$f, $fopen];
1234
+    $user = $via_proxy = $proxy_user = '';
1235
+    $fopen = false;
1236
+
1237
+    $t = @parse_url($url);
1238
+    $host = $t['host'];
1239
+    if ($t['scheme'] == 'http') {
1240
+        $scheme = 'http';
1241
+        $noproxy = '';
1242
+    } elseif ($t['scheme'] == 'https') {
1243
+        $scheme = 'ssl';
1244
+        $noproxy = 'ssl://';
1245
+        if (!isset($t['port']) || !($port = $t['port'])) {
1246
+            $t['port'] = 443;
1247
+        }
1248
+    } else {
1249
+        $scheme = $t['scheme'];
1250
+        $noproxy = $scheme . '://';
1251
+    }
1252
+    if (isset($t['user'])) {
1253
+        $user = [$t['user'], $t['pass']];
1254
+    }
1255
+
1256
+    if (!isset($t['port']) || !($port = $t['port'])) {
1257
+        $port = 80;
1258
+    }
1259
+    if (!isset($t['path']) || !($path = $t['path'])) {
1260
+        $path = '/';
1261
+    }
1262
+
1263
+    if (!empty($t['query'])) {
1264
+        $path .= '?' . $t['query'];
1265
+    }
1266
+
1267
+    $f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
1268
+    if (!$f or !is_resource($f)) {
1269
+        // fallback : fopen si on a pas fait timeout dans lance_requete
1270
+        // ce qui correspond a $f===110
1271
+        if (
1272
+            $f !== 110
1273
+            and !need_proxy($host)
1274
+            and !_request('tester_proxy')
1275
+            and (!isset($GLOBALS['inc_distant_allow_fopen']) or $GLOBALS['inc_distant_allow_fopen'])
1276
+        ) {
1277
+            $f = @fopen($url, 'rb');
1278
+            spip_log("connexion vers $url par simple fopen", 'distant');
1279
+            $fopen = true;
1280
+        } else {
1281
+            // echec total
1282
+            $f = false;
1283
+        }
1284
+    }
1285
+
1286
+    return [$f, $fopen];
1287 1287
 }
1288 1288
 
1289 1289
 /**
@@ -1318,123 +1318,123 @@  discard block
 block discarded – undo
1318 1318
  *   resource socket vers l'url demandee
1319 1319
  */
1320 1320
 function lance_requete(
1321
-	$method,
1322
-	$scheme,
1323
-	$user,
1324
-	$host,
1325
-	$path,
1326
-	$port,
1327
-	$noproxy,
1328
-	$refuse_gz = false,
1329
-	$referer = '',
1330
-	$datas = '',
1331
-	$vers = 'HTTP/1.0',
1332
-	$date = ''
1321
+    $method,
1322
+    $scheme,
1323
+    $user,
1324
+    $host,
1325
+    $path,
1326
+    $port,
1327
+    $noproxy,
1328
+    $refuse_gz = false,
1329
+    $referer = '',
1330
+    $datas = '',
1331
+    $vers = 'HTTP/1.0',
1332
+    $date = ''
1333 1333
 ) {
1334 1334
 
1335
-	$proxy_user = '';
1336
-	$http_proxy = need_proxy($host);
1337
-	if ($user) {
1338
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1339
-	}
1340
-
1341
-	$connect = '';
1342
-	if ($http_proxy) {
1343
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1344
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1345
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1346
-				. "Host: $path_host\r\n"
1347
-				. "Proxy-Connection: Keep-Alive\r\n";
1348
-		} else {
1349
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1350
-				. (!$user ? '' : "$user@")
1351
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1352
-		}
1353
-		$t2 = @parse_url($http_proxy);
1354
-		$first_host = $t2['host'];
1355
-		$port = ($t2['port'] ?? null) ?: 80;
1356
-		if ($t2['user'] ?? null) {
1357
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1358
-		}
1359
-	} else {
1360
-		$first_host = $noproxy . $host;
1361
-	}
1362
-
1363
-	if ($connect) {
1364
-		$streamContext = stream_context_create([
1365
-			'ssl' => [
1366
-				'verify_peer' => false,
1367
-				'allow_self_signed' => true,
1368
-				'SNI_enabled' => true,
1369
-				'peer_name' => $host,
1370
-			]
1371
-		]);
1372
-		$f = @stream_socket_client(
1373
-			"tcp://$first_host:$port",
1374
-			$errno,
1375
-			$errstr,
1376
-			_INC_DISTANT_CONNECT_TIMEOUT,
1377
-			STREAM_CLIENT_CONNECT,
1378
-			$streamContext
1379
-		);
1380
-		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1381
-		if (!$f) {
1382
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1383
-			return $errno;
1384
-		}
1385
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1386
-
1387
-		fputs($f, $connect);
1388
-		fputs($f, "\r\n");
1389
-		$res = fread($f, 1024);
1390
-		if (
1391
-			!$res
1392
-			or !count($res = explode(' ', $res))
1393
-			or $res[1] !== '200'
1394
-		) {
1395
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1396
-			fclose($f);
1397
-
1398
-			return false;
1399
-		}
1400
-		// important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1401
-		stream_set_blocking($f, true);
1402
-		// envoyer le handshake
1403
-		stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1404
-		spip_log("OK CONNECT sur $first_host:$port", 'connect');
1405
-	} else {
1406
-		$ntry = 3;
1407
-		do {
1408
-			$f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1409
-		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1410
-		spip_log("Recuperer $path sur $first_host:$port par $f");
1411
-		if (!$f) {
1412
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1413
-
1414
-			return $errno;
1415
-		}
1416
-		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1417
-	}
1418
-
1419
-	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1420
-
1421
-	$host_port = $host;
1422
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1423
-		$host_port .= ":$port";
1424
-	}
1425
-	$req = "$method $path $vers\r\n"
1426
-		. "Host: $host_port\r\n"
1427
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1428
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1429
-		. (!$site ? '' : "Referer: $site/$referer\r\n")
1430
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1431
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1432
-		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1433
-		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1335
+    $proxy_user = '';
1336
+    $http_proxy = need_proxy($host);
1337
+    if ($user) {
1338
+        $user = urlencode($user[0]) . ':' . urlencode($user[1]);
1339
+    }
1340
+
1341
+    $connect = '';
1342
+    if ($http_proxy) {
1343
+        if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1344
+            $path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1345
+            $connect = 'CONNECT ' . $path_host . " $vers\r\n"
1346
+                . "Host: $path_host\r\n"
1347
+                . "Proxy-Connection: Keep-Alive\r\n";
1348
+        } else {
1349
+            $path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1350
+                . (!$user ? '' : "$user@")
1351
+                . "$host" . (($port != 80) ? ":$port" : '') . $path;
1352
+        }
1353
+        $t2 = @parse_url($http_proxy);
1354
+        $first_host = $t2['host'];
1355
+        $port = ($t2['port'] ?? null) ?: 80;
1356
+        if ($t2['user'] ?? null) {
1357
+            $proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1358
+        }
1359
+    } else {
1360
+        $first_host = $noproxy . $host;
1361
+    }
1362
+
1363
+    if ($connect) {
1364
+        $streamContext = stream_context_create([
1365
+            'ssl' => [
1366
+                'verify_peer' => false,
1367
+                'allow_self_signed' => true,
1368
+                'SNI_enabled' => true,
1369
+                'peer_name' => $host,
1370
+            ]
1371
+        ]);
1372
+        $f = @stream_socket_client(
1373
+            "tcp://$first_host:$port",
1374
+            $errno,
1375
+            $errstr,
1376
+            _INC_DISTANT_CONNECT_TIMEOUT,
1377
+            STREAM_CLIENT_CONNECT,
1378
+            $streamContext
1379
+        );
1380
+        spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1381
+        if (!$f) {
1382
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1383
+            return $errno;
1384
+        }
1385
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1386
+
1387
+        fputs($f, $connect);
1388
+        fputs($f, "\r\n");
1389
+        $res = fread($f, 1024);
1390
+        if (
1391
+            !$res
1392
+            or !count($res = explode(' ', $res))
1393
+            or $res[1] !== '200'
1394
+        ) {
1395
+            spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1396
+            fclose($f);
1397
+
1398
+            return false;
1399
+        }
1400
+        // important, car sinon on lit trop vite et les donnees ne sont pas encore dispo
1401
+        stream_set_blocking($f, true);
1402
+        // envoyer le handshake
1403
+        stream_socket_enable_crypto($f, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
1404
+        spip_log("OK CONNECT sur $first_host:$port", 'connect');
1405
+    } else {
1406
+        $ntry = 3;
1407
+        do {
1408
+            $f = @fsockopen($first_host, $port, $errno, $errstr, _INC_DISTANT_CONNECT_TIMEOUT);
1409
+        } while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1410
+        spip_log("Recuperer $path sur $first_host:$port par $f");
1411
+        if (!$f) {
1412
+            spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1413
+
1414
+            return $errno;
1415
+        }
1416
+        stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
1417
+    }
1418
+
1419
+    $site = $GLOBALS['meta']['adresse_site'] ?? '';
1420
+
1421
+    $host_port = $host;
1422
+    if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1423
+        $host_port .= ":$port";
1424
+    }
1425
+    $req = "$method $path $vers\r\n"
1426
+        . "Host: $host_port\r\n"
1427
+        . 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1428
+        . ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1429
+        . (!$site ? '' : "Referer: $site/$referer\r\n")
1430
+        . (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1431
+        . (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1432
+        . (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1433
+        . (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1434 1434
 
1435 1435
 #	spip_log("Requete\n$req", 'distant');
1436
-	fputs($f, $req);
1437
-	fputs($f, $datas ?: "\r\n");
1436
+    fputs($f, $req);
1437
+    fputs($f, $datas ?: "\r\n");
1438 1438
 
1439
-	return $f;
1439
+    return $f;
1440 1440
 }
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
 	define('_INC_DISTANT_CONTENT_ENCODING', 'gzip');
29 29
 }
30 30
 if (!defined('_INC_DISTANT_USER_AGENT')) {
31
-	define('_INC_DISTANT_USER_AGENT', 'SPIP-' . $GLOBALS['spip_version_affichee'] . ' (' . $GLOBALS['home_server'] . ')');
31
+	define('_INC_DISTANT_USER_AGENT', 'SPIP-'.$GLOBALS['spip_version_affichee'].' ('.$GLOBALS['home_server'].')');
32 32
 }
33 33
 if (!defined('_INC_DISTANT_MAX_SIZE')) {
34 34
 	define('_INC_DISTANT_MAX_SIZE', 2_097_152);
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	define('_INC_DISTANT_CONNECT_TIMEOUT', 10);
38 38
 }
39 39
 
40
-define('_REGEXP_COPIE_LOCALE', ',' 	.
40
+define('_REGEXP_COPIE_LOCALE', ','.
41 41
 	preg_replace(
42 42
 		'@^https?:@',
43 43
 		'https?:',
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 
75 75
 	// si c'est la protection de soi-meme, retourner le path
76 76
 	if ($mode !== 'force' and preg_match(_REGEXP_COPIE_LOCALE, $source, $match)) {
77
-		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)) . urldecode($match[1]);
77
+		$source = substr(_DIR_IMG, strlen(_DIR_RACINE)).urldecode($match[1]);
78 78
 
79 79
 		return @file_exists($source) ? $source : false;
80 80
 	}
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 		return false;
95 95
 	}
96 96
 
97
-	$localrac = _DIR_RACINE . $local;
97
+	$localrac = _DIR_RACINE.$local;
98 98
 	$t = ($mode === 'force') ? false : @file_exists($localrac);
99 99
 
100 100
 	// test d'existence du fichier
@@ -114,18 +114,18 @@  discard block
 block discarded – undo
114 114
 		if (!$taille_max) {
115 115
 			$taille_max = _COPIE_LOCALE_MAX_SIZE;
116 116
 		}
117
-		$localrac_tmp = $localrac . '.tmp';
117
+		$localrac_tmp = $localrac.'.tmp';
118 118
 		$res = recuperer_url(
119 119
 			$source,
120 120
 			['file' => $localrac_tmp, 'taille_max' => $taille_max, 'if_modified_since' => $t ? filemtime($localrac) : '']
121 121
 		);
122 122
 
123 123
 		if (!$res or (!$res['length'] and $res['status'] != 304)) {
124
-			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : " . ($res ? $res['status'] : '-'), 'distant' . _LOG_INFO_IMPORTANTE);
124
+			spip_log("copie_locale : Echec recuperation $source sur $localrac_tmp status : ".($res ? $res['status'] : '-'), 'distant'._LOG_INFO_IMPORTANTE);
125 125
 			@unlink($localrac_tmp);
126 126
 		}
127 127
 		else {
128
-			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille " . $res['length'] . ' status ' . $res['status'], 'distant');
128
+			spip_log("copie_locale : recuperation $source sur $localrac_tmp OK | taille ".$res['length'].' status '.$res['status'], 'distant');
129 129
 		}
130 130
 		if (!$res or !$res['length']) {
131 131
 			// si $t c'est sans doute juste un not-modified-since
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 			and is_callable($callback_valider_url)
139 139
 			and !$callback_valider_url($res['url'])
140 140
 		) {
141
-			spip_log('copie_locale : url finale ' . $res['url'] . " non valide, on refuse le fichier $localrac_tmp", 'distant' . _LOG_INFO_IMPORTANTE);
141
+			spip_log('copie_locale : url finale '.$res['url']." non valide, on refuse le fichier $localrac_tmp", 'distant'._LOG_INFO_IMPORTANTE);
142 142
 			@unlink($localrac_tmp);
143 143
 			return $t ? $local : false;
144 144
 		}
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 
230 230
 	if (!$is_known_host) {
231 231
 		$host = trim($parsed_url['host'], '.');
232
-		if (! $ip = filter_var($host, FILTER_VALIDATE_IP)) {
232
+		if (!$ip = filter_var($host, FILTER_VALIDATE_IP)) {
233 233
 			$ip = gethostbyname($host);
234 234
 			if ($ip === $host) {
235 235
 				// Error condition for gethostbyname()
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 			}
251 251
 		}
252 252
 		if ($ip) {
253
-			if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
253
+			if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
254 254
 				return false;
255 255
 			}
256 256
 		}
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	}
262 262
 
263 263
 	$port = $parsed_url['port'];
264
-	if ($port === 80  or $port === 443  or $port === 8080) {
264
+	if ($port === 80 or $port === 443 or $port === 8080) {
265 265
 		return $url;
266 266
 	}
267 267
 
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 				}
332 332
 			}
333 333
 			if ($taille > 500) {
334
-				$boundary = substr(md5(random_int(0, mt_getrandmax()) . 'spip'), 0, 8);
334
+				$boundary = substr(md5(random_int(0, mt_getrandmax()).'spip'), 0, 8);
335 335
 			}
336 336
 		}
337 337
 
@@ -359,16 +359,16 @@  discard block
 block discarded – undo
359 359
 			}
360 360
 		} else {
361 361
 			// fabrique une chaine HTTP simple pour un POST
362
-			$entete = 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
362
+			$entete = 'Content-Type: application/x-www-form-urlencoded'."\r\n";
363 363
 			$chaine = [];
364 364
 			if (is_array($donnees)) {
365 365
 				foreach ($donnees as $cle => $valeur) {
366 366
 					if (is_array($valeur)) {
367 367
 						foreach ($valeur as $val2) {
368
-							$chaine[] = rawurlencode($cle) . '[]=' . rawurlencode($val2);
368
+							$chaine[] = rawurlencode($cle).'[]='.rawurlencode($val2);
369 369
 						}
370 370
 					} else {
371
-						$chaine[] = rawurlencode($cle) . '=' . rawurlencode($valeur);
371
+						$chaine[] = rawurlencode($cle).'='.rawurlencode($valeur);
372 372
 					}
373 373
 				}
374 374
 				$chaine = implode('&', $chaine);
@@ -469,13 +469,13 @@  discard block
 block discarded – undo
469 469
 		$options['taille_max'] = $copy ? _COPIE_LOCALE_MAX_SIZE : _INC_DISTANT_MAX_SIZE;
470 470
 	}
471 471
 
472
-	spip_log('recuperer_url ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
472
+	spip_log('recuperer_url '.$options['methode']." sur $url", 'distant'._LOG_DEBUG);
473 473
 
474 474
 	// Ajout des en-têtes spécifiques si besoin
475 475
 	$formatted_data = '';
476 476
 	if (!empty($options['headers'])) {
477 477
 		foreach ($options['headers'] as $champ => $valeur) {
478
-			$formatted_data .= $champ . ': ' . $valeur . "\r\n";
478
+			$formatted_data .= $champ.': '.$valeur."\r\n";
479 479
 		}
480 480
 	}
481 481
 
@@ -483,9 +483,9 @@  discard block
 block discarded – undo
483 483
 		[$head, $postdata] = prepare_donnees_post($options['datas'], $options['boundary']);
484 484
 		$head .= $formatted_data;
485 485
 		if (stripos($head, 'Content-Length:') === false) {
486
-			$head .= 'Content-Length: ' . strlen($postdata) . "\r\n";
486
+			$head .= 'Content-Length: '.strlen($postdata)."\r\n";
487 487
 		}
488
-		$formatted_data = $head . "\r\n" . $postdata;
488
+		$formatted_data = $head."\r\n".$postdata;
489 489
 		if (
490 490
 			strlen($postdata)
491 491
 			and !$methode_demandee
@@ -499,9 +499,9 @@  discard block
 block discarded – undo
499 499
 	// Accepter les URLs au format feed:// ou qui ont oublie le http:// ou les urls relatives au protocole
500 500
 	$url = preg_replace(',^feed://,i', 'http://', $url);
501 501
 	if (!tester_url_absolue($url)) {
502
-		$url = 'http://' . $url;
502
+		$url = 'http://'.$url;
503 503
 	} elseif (strncmp($url, '//', 2) == 0) {
504
-		$url = 'http:' . $url;
504
+		$url = 'http:'.$url;
505 505
 	}
506 506
 
507 507
 	$url = url_to_ascii($url);
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 		$options['if_modified_since']
531 531
 	);
532 532
 	if (!$handle) {
533
-		spip_log("ECHEC init_http $url", 'distant' . _LOG_ERREUR);
533
+		spip_log("ECHEC init_http $url", 'distant'._LOG_ERREUR);
534 534
 
535 535
 		return false;
536 536
 	}
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
 					'status' => 200,
561 561
 				];
562 562
 			} else {
563
-				spip_log("ECHEC chinoiserie $url", 'distant' . _LOG_ERREUR);
563
+				spip_log("ECHEC chinoiserie $url", 'distant'._LOG_ERREUR);
564 564
 				return false;
565 565
 			}
566 566
 		} elseif ($res['location'] and $options['follow_location']) {
@@ -576,11 +576,11 @@  discard block
 block discarded – undo
576 576
 					$options['datas'] = '';
577 577
 				}
578 578
 			}
579
-			spip_log('recuperer_url recommence ' . $options['methode'] . " sur $url", 'distant' . _LOG_DEBUG);
579
+			spip_log('recuperer_url recommence '.$options['methode']." sur $url", 'distant'._LOG_DEBUG);
580 580
 
581 581
 			return recuperer_url($url, $options);
582 582
 		} elseif ($res['status'] !== 200) {
583
-			spip_log('HTTP status ' . $res['status'] . " pour $url", 'distant');
583
+			spip_log('HTTP status '.$res['status']." pour $url", 'distant');
584 584
 		}
585 585
 		$result['status'] = $res['status'];
586 586
 		if (isset($res['headers'])) {
@@ -596,7 +596,7 @@  discard block
 block discarded – undo
596 596
 
597 597
 	// on ne veut que les entetes
598 598
 	if (!$options['taille_max'] or $options['methode'] == 'HEAD' or $result['status'] == '304') {
599
-		spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($result), 'distant' . _LOG_DEBUG);
599
+		spip_log('RESULTAT recuperer_url '.$options['methode']." sur $url : ".json_encode($result), 'distant'._LOG_DEBUG);
600 600
 		return $result;
601 601
 	}
602 602
 
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
 
607 607
 	$gz = false;
608 608
 	if (preg_match(",\bContent-Encoding: .*gzip,is", $result['headers'])) {
609
-		$gz = (_DIR_TMP . md5(uniqid(random_int(0, mt_getrandmax()))) . '.tmp.gz');
609
+		$gz = (_DIR_TMP.md5(uniqid(random_int(0, mt_getrandmax()))).'.tmp.gz');
610 610
 	}
611 611
 
612 612
 	// si on a pas deja recuperer le contenu par une methode detournee
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
 
643 643
 	$trace = json_decode(json_encode($result), true);
644 644
 	$trace['page'] = '...';
645
-	spip_log('RESULTAT recuperer_url ' . $options['methode'] . " sur $url : " . json_encode($trace), 'distant' . _LOG_DEBUG);
645
+	spip_log('RESULTAT recuperer_url '.$options['methode']." sur $url : ".json_encode($trace), 'distant'._LOG_DEBUG);
646 646
 
647 647
 	return $result;
648 648
 }
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 	$sig['url'] = $url;
697 697
 
698 698
 	$dir = sous_repertoire(_DIR_CACHE, 'curl');
699
-	$cache = md5(serialize($sig)) . '-' . substr(preg_replace(',\W+,', '_', $url), 0, 80);
699
+	$cache = md5(serialize($sig)).'-'.substr(preg_replace(',\W+,', '_', $url), 0, 80);
700 700
 	$sub = sous_repertoire($dir, substr($cache, 0, 2));
701 701
 	$cache = "$sub$cache";
702 702
 
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 	$fp = false;
751 751
 	if ($fichier) {
752 752
 		include_spip('inc/acces');
753
-		$tmpfile = "$fichier." . creer_uniqid() . '.tmp';
753
+		$tmpfile = "$fichier.".creer_uniqid().'.tmp';
754 754
 		$fp = spip_fopen_lock($tmpfile, 'w', LOCK_EX);
755 755
 		if (!$fp and file_exists($fichier)) {
756 756
 			return filesize($fichier);
@@ -809,7 +809,7 @@  discard block
 block discarded – undo
809 809
 	}
810 810
 	$result['status'] = intval($r[1]);
811 811
 	while ($s = trim(fgets($handle, 16384))) {
812
-		$result['headers'][] = $s . "\n";
812
+		$result['headers'][] = $s."\n";
813 813
 		preg_match(',^([^:]*): *(.*)$,i', $s, $r);
814 814
 		[, $d, $v] = $r;
815 815
 		if (strtolower(trim($d)) == 'location' and $result['status'] >= 300 and $result['status'] < 400) {
@@ -858,13 +858,13 @@  discard block
 block discarded – undo
858 858
 
859 859
 	// on se place tout le temps comme si on etait a la racine
860 860
 	if (_DIR_RACINE) {
861
-		$d = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $d);
861
+		$d = preg_replace(',^'.preg_quote(_DIR_RACINE).',', '', $d);
862 862
 	}
863 863
 
864 864
 	$m = md5($source);
865 865
 
866 866
 	return $d
867
-	. substr(preg_replace(',[^\w-],', '', basename($source)) . '-' . $m, 0, 12)
867
+	. substr(preg_replace(',[^\w-],', '', basename($source)).'-'.$m, 0, 12)
868 868
 	. substr($m, 0, 4)
869 869
 	. ".$extension";
870 870
 }
@@ -888,7 +888,7 @@  discard block
 block discarded – undo
888 888
 	// Si c'est deja local pas de souci
889 889
 	if (!tester_url_absolue($source)) {
890 890
 		if (_DIR_RACINE) {
891
-			$source = preg_replace(',^' . preg_quote(_DIR_RACINE) . ',', '', $source);
891
+			$source = preg_replace(',^'.preg_quote(_DIR_RACINE).',', '', $source);
892 892
 		}
893 893
 
894 894
 		return $source;
@@ -906,7 +906,7 @@  discard block
 block discarded – undo
906 906
 		$ext
907 907
 		and preg_match(',^\w+$,', $ext) // pas de php?truc=1&...
908 908
 		and $f = nom_fichier_copie_locale($source, $ext)
909
-		and file_exists(_DIR_RACINE . $f)
909
+		and file_exists(_DIR_RACINE.$f)
910 910
 	) {
911 911
 		return $f;
912 912
 	}
@@ -914,7 +914,7 @@  discard block
 block discarded – undo
914 914
 
915 915
 	// Si c'est deja dans la table des documents,
916 916
 	// ramener le nom de sa copie potentielle
917
-	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier=' . sql_quote($source) . " AND distant='oui' AND extension <> ''");
917
+	$ext = sql_getfetsel('extension', 'spip_documents', 'fichier='.sql_quote($source)." AND distant='oui' AND extension <> ''");
918 918
 
919 919
 	if ($ext) {
920 920
 		return nom_fichier_copie_locale($source, $ext);
@@ -925,9 +925,9 @@  discard block
 block discarded – undo
925 925
 
926 926
 	$ext = $path_parts ? $path_parts['extension'] : '';
927 927
 
928
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
928
+	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
929 929
 		$f = nom_fichier_copie_locale($source, $ext);
930
-		if (file_exists(_DIR_RACINE . $f)) {
930
+		if (file_exists(_DIR_RACINE.$f)) {
931 931
 			return $f;
932 932
 		}
933 933
 	}
@@ -935,7 +935,7 @@  discard block
 block discarded – undo
935 935
 	// Ping  pour voir si son extension est connue et autorisee
936 936
 	// avec mise en cache du resultat du ping
937 937
 
938
-	$cache = sous_repertoire(_DIR_CACHE, 'rid') . md5($source);
938
+	$cache = sous_repertoire(_DIR_CACHE, 'rid').md5($source);
939 939
 	if (
940 940
 		!@file_exists($cache)
941 941
 		or !$path_parts = @unserialize(spip_file_get_contents($cache))
@@ -945,11 +945,11 @@  discard block
 block discarded – undo
945 945
 		ecrire_fichier($cache, serialize($path_parts));
946 946
 	}
947 947
 	$ext = !empty($path_parts['extension']) ? $path_parts['extension'] : '';
948
-	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension=' . sql_quote($ext))) {
948
+	if ($ext and sql_getfetsel('extension', 'spip_types_documents', 'extension='.sql_quote($ext))) {
949 949
 		return nom_fichier_copie_locale($source, $ext);
950 950
 	}
951 951
 
952
-	spip_log("pas de copie locale pour $source", 'distant' . _LOG_ERREUR);
952
+	spip_log("pas de copie locale pour $source", 'distant'._LOG_ERREUR);
953 953
 	return null;
954 954
 }
955 955
 
@@ -1048,7 +1048,7 @@  discard block
 block discarded – undo
1048 1048
 		} else {
1049 1049
 			if ($a['body']) {
1050 1050
 				$a['extension'] = $extension;
1051
-				$a['fichier'] = _DIR_RACINE . nom_fichier_copie_locale($source, $extension);
1051
+				$a['fichier'] = _DIR_RACINE.nom_fichier_copie_locale($source, $extension);
1052 1052
 				ecrire_fichier($a['fichier'], $a['body']);
1053 1053
 				$size_image = @spip_getimagesize($a['fichier']);
1054 1054
 				$a['largeur'] = intval($size_image[0]);
@@ -1116,20 +1116,20 @@  discard block
 block discarded – undo
1116 1116
 			!$t
1117 1117
 			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1118 1118
 		) {
1119
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1119
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1120 1120
 		}
1121 1121
 		if (
1122 1122
 			!$t
1123 1123
 			and preg_match(',^Content-Disposition:\s*attachment;\s*filename=(.*)$,Uims', $headers, $m)
1124 1124
 			and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $m[1], $rext)
1125 1125
 		) {
1126
-			$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1126
+			$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1127 1127
 		}
1128 1128
 	}
1129 1129
 
1130 1130
 	// Autre mime/type (ou text/plain avec fichier d'extension inconnue)
1131 1131
 	if (!$t) {
1132
-		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type=' . sql_quote($mime_type));
1132
+		$t = sql_fetsel('extension', 'spip_types_documents', 'mime_type='.sql_quote($mime_type));
1133 1133
 	}
1134 1134
 
1135 1135
 	// Toujours rien ? (ex: audio/x-ogg au lieu de application/ogg)
@@ -1140,11 +1140,11 @@  discard block
 block discarded – undo
1140 1140
 		and preg_match(',\.([a-z0-9]+)(\?.*)?$,i', $source, $rext)
1141 1141
 	) {
1142 1142
 		# eviter xxx.3 => 3gp (> SPIP 3)
1143
-		$t = sql_fetsel('extension', 'spip_types_documents', 'extension=' . sql_quote(corriger_extension($rext[1]), '', 'text'));
1143
+		$t = sql_fetsel('extension', 'spip_types_documents', 'extension='.sql_quote(corriger_extension($rext[1]), '', 'text'));
1144 1144
 	}
1145 1145
 
1146 1146
 	if ($t) {
1147
-		spip_log("mime-type $mime_type ok, extension " . $t['extension'], 'distant');
1147
+		spip_log("mime-type $mime_type ok, extension ".$t['extension'], 'distant');
1148 1148
 		return $t['extension'];
1149 1149
 	} else {
1150 1150
 		# par defaut on retombe sur '.bin' si c'est autorise
@@ -1247,7 +1247,7 @@  discard block
 block discarded – undo
1247 1247
 		}
1248 1248
 	} else {
1249 1249
 		$scheme = $t['scheme'];
1250
-		$noproxy = $scheme . '://';
1250
+		$noproxy = $scheme.'://';
1251 1251
 	}
1252 1252
 	if (isset($t['user'])) {
1253 1253
 		$user = [$t['user'], $t['pass']];
@@ -1261,7 +1261,7 @@  discard block
 block discarded – undo
1261 1261
 	}
1262 1262
 
1263 1263
 	if (!empty($t['query'])) {
1264
-		$path .= '?' . $t['query'];
1264
+		$path .= '?'.$t['query'];
1265 1265
 	}
1266 1266
 
1267 1267
 	$f = lance_requete($method, $scheme, $user, $host, $path, $port, $noproxy, $refuse_gz, $referer, $datas, $vers, $date);
@@ -1335,29 +1335,29 @@  discard block
 block discarded – undo
1335 1335
 	$proxy_user = '';
1336 1336
 	$http_proxy = need_proxy($host);
1337 1337
 	if ($user) {
1338
-		$user = urlencode($user[0]) . ':' . urlencode($user[1]);
1338
+		$user = urlencode($user[0]).':'.urlencode($user[1]);
1339 1339
 	}
1340 1340
 
1341 1341
 	$connect = '';
1342 1342
 	if ($http_proxy) {
1343
-		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls','ssl'])) {
1344
-			$path_host = (!$user ? '' : "$user@") . $host . (($port != 80) ? ":$port" : '');
1345
-			$connect = 'CONNECT ' . $path_host . " $vers\r\n"
1343
+		if (!defined('_PROXY_HTTPS_NOT_VIA_CONNECT') and in_array($scheme, ['tls', 'ssl'])) {
1344
+			$path_host = (!$user ? '' : "$user@").$host.(($port != 80) ? ":$port" : '');
1345
+			$connect = 'CONNECT '.$path_host." $vers\r\n"
1346 1346
 				. "Host: $path_host\r\n"
1347 1347
 				. "Proxy-Connection: Keep-Alive\r\n";
1348 1348
 		} else {
1349
-			$path = (in_array($scheme, ['tls','ssl']) ? 'https://' : "$scheme://")
1349
+			$path = (in_array($scheme, ['tls', 'ssl']) ? 'https://' : "$scheme://")
1350 1350
 				. (!$user ? '' : "$user@")
1351
-				. "$host" . (($port != 80) ? ":$port" : '') . $path;
1351
+				. "$host".(($port != 80) ? ":$port" : '').$path;
1352 1352
 		}
1353 1353
 		$t2 = @parse_url($http_proxy);
1354 1354
 		$first_host = $t2['host'];
1355 1355
 		$port = ($t2['port'] ?? null) ?: 80;
1356 1356
 		if ($t2['user'] ?? null) {
1357
-			$proxy_user = base64_encode($t2['user'] . ':' . $t2['pass']);
1357
+			$proxy_user = base64_encode($t2['user'].':'.$t2['pass']);
1358 1358
 		}
1359 1359
 	} else {
1360
-		$first_host = $noproxy . $host;
1360
+		$first_host = $noproxy.$host;
1361 1361
 	}
1362 1362
 
1363 1363
 	if ($connect) {
@@ -1379,7 +1379,7 @@  discard block
 block discarded – undo
1379 1379
 		);
1380 1380
 		spip_log("Recuperer $path sur $first_host:$port par $f (via CONNECT)", 'connect');
1381 1381
 		if (!$f) {
1382
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1382
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1383 1383
 			return $errno;
1384 1384
 		}
1385 1385
 		stream_set_timeout($f, _INC_DISTANT_CONNECT_TIMEOUT);
@@ -1392,7 +1392,7 @@  discard block
 block discarded – undo
1392 1392
 			or !count($res = explode(' ', $res))
1393 1393
 			or $res[1] !== '200'
1394 1394
 		) {
1395
-			spip_log("Echec CONNECT sur $first_host:$port", 'connect' . _LOG_INFO_IMPORTANTE);
1395
+			spip_log("Echec CONNECT sur $first_host:$port", 'connect'._LOG_INFO_IMPORTANTE);
1396 1396
 			fclose($f);
1397 1397
 
1398 1398
 			return false;
@@ -1409,7 +1409,7 @@  discard block
 block discarded – undo
1409 1409
 		} while (!$f and $ntry-- and $errno !== 110 and sleep(1));
1410 1410
 		spip_log("Recuperer $path sur $first_host:$port par $f");
1411 1411
 		if (!$f) {
1412
-			spip_log("Erreur connexion $errno $errstr", 'distant' . _LOG_ERREUR);
1412
+			spip_log("Erreur connexion $errno $errstr", 'distant'._LOG_ERREUR);
1413 1413
 
1414 1414
 			return $errno;
1415 1415
 		}
@@ -1419,16 +1419,16 @@  discard block
 block discarded – undo
1419 1419
 	$site = $GLOBALS['meta']['adresse_site'] ?? '';
1420 1420
 
1421 1421
 	$host_port = $host;
1422
-	if ($port != (in_array($scheme, ['tls','ssl']) ? 443 : 80)) {
1422
+	if ($port != (in_array($scheme, ['tls', 'ssl']) ? 443 : 80)) {
1423 1423
 		$host_port .= ":$port";
1424 1424
 	}
1425 1425
 	$req = "$method $path $vers\r\n"
1426 1426
 		. "Host: $host_port\r\n"
1427
-		. 'User-Agent: ' . _INC_DISTANT_USER_AGENT . "\r\n"
1428
-		. ($refuse_gz ? '' : ('Accept-Encoding: ' . _INC_DISTANT_CONTENT_ENCODING . "\r\n"))
1427
+		. 'User-Agent: '._INC_DISTANT_USER_AGENT."\r\n"
1428
+		. ($refuse_gz ? '' : ('Accept-Encoding: '._INC_DISTANT_CONTENT_ENCODING."\r\n"))
1429 1429
 		. (!$site ? '' : "Referer: $site/$referer\r\n")
1430
-		. (!$date ? '' : 'If-Modified-Since: ' . (gmdate('D, d M Y H:i:s', $date) . " GMT\r\n"))
1431
-		. (!$user ? '' : ('Authorization: Basic ' . base64_encode($user) . "\r\n"))
1430
+		. (!$date ? '' : 'If-Modified-Since: '.(gmdate('D, d M Y H:i:s', $date)." GMT\r\n"))
1431
+		. (!$user ? '' : ('Authorization: Basic '.base64_encode($user)."\r\n"))
1432 1432
 		. (!$proxy_user ? '' : "Proxy-Authorization: Basic $proxy_user\r\n")
1433 1433
 		. (!strpos($vers, '1.1') ? '' : "Keep-Alive: 300\r\nConnection: keep-alive\r\n");
1434 1434
 
Please login to merge, or discard this patch.
ecrire/action/editer_rubrique.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 			$id_rubrique,
151 151
 			[
152 152
 			'data' => $set,
153
-			'nonvide' => ['titre' => _T('titre_nouvelle_rubrique') . ' ' . _T('info_numero_abbreviation') . $id_rubrique]
153
+			'nonvide' => ['titre' => _T('titre_nouvelle_rubrique').' '._T('info_numero_abbreviation').$id_rubrique]
154 154
 			],
155 155
 			$c
156 156
 		)
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 				)
255 255
 			) {
256 256
 				if ($s['statut'] != 'prepa') {
257
-					spip_log("deplacement de $id_rubrique vers $id_parent refuse a " . $GLOBALS['visiteur_session']['id_auteur'] . ' ' . $GLOBALS['visiteur_session']['statut']);
257
+					spip_log("deplacement de $id_rubrique vers $id_parent refuse a ".$GLOBALS['visiteur_session']['id_auteur'].' '.$GLOBALS['visiteur_session']['statut']);
258 258
 				}
259 259
 			} elseif (editer_rubrique_breves($id_rubrique, $id_parent, $c)) {
260 260
 				$statut_ancien = $s['statut'];
Please login to merge, or discard this patch.
Indentation   +216 added lines, -216 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Rubriques\Edition
17 17
  */
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 include_spip('inc/rubriques');
@@ -38,34 +38,34 @@  discard block
 block discarded – undo
38 38
  */
39 39
 function action_editer_rubrique_dist($arg = null) {
40 40
 
41
-	if (is_null($arg)) {
42
-		$securiser_action = charger_fonction('securiser_action', 'inc');
43
-		$arg = $securiser_action();
44
-	}
45
-
46
-	if (!$id_rubrique = intval($arg)) {
47
-		if ($arg != 'oui') {
48
-			include_spip('inc/headers');
49
-			redirige_url_ecrire();
50
-		}
51
-		$id_rubrique = rubrique_inserer(_request('id_parent'));
52
-	}
53
-
54
-	$err = rubrique_modifier($id_rubrique);
55
-
56
-	if (_request('redirect')) {
57
-		$redirect = parametre_url(
58
-			urldecode(_request('redirect')),
59
-			'id_rubrique',
60
-			$id_rubrique,
61
-			'&'
62
-		);
63
-
64
-		include_spip('inc/headers');
65
-		redirige_par_entete($redirect);
66
-	}
67
-
68
-	return [$id_rubrique, $err];
41
+    if (is_null($arg)) {
42
+        $securiser_action = charger_fonction('securiser_action', 'inc');
43
+        $arg = $securiser_action();
44
+    }
45
+
46
+    if (!$id_rubrique = intval($arg)) {
47
+        if ($arg != 'oui') {
48
+            include_spip('inc/headers');
49
+            redirige_url_ecrire();
50
+        }
51
+        $id_rubrique = rubrique_inserer(_request('id_parent'));
52
+    }
53
+
54
+    $err = rubrique_modifier($id_rubrique);
55
+
56
+    if (_request('redirect')) {
57
+        $redirect = parametre_url(
58
+            urldecode(_request('redirect')),
59
+            'id_rubrique',
60
+            $id_rubrique,
61
+            '&'
62
+        );
63
+
64
+        include_spip('inc/headers');
65
+        redirige_par_entete($redirect);
66
+    }
67
+
68
+    return [$id_rubrique, $err];
69 69
 }
70 70
 
71 71
 
@@ -80,64 +80,64 @@  discard block
 block discarded – undo
80 80
  *     Identifiant de la rubrique crée
81 81
  */
82 82
 function rubrique_inserer($id_parent, $set = null) {
83
-	$champs = [
84
-		'titre' => _T('item_nouvelle_rubrique'),
85
-		'id_parent' => intval($id_parent),
86
-		'statut' => 'prepa'
87
-	];
88
-
89
-	if ($set) {
90
-		$champs = array_merge($champs, $set);
91
-	}
92
-
93
-	// Envoyer aux plugins
94
-	$champs = pipeline(
95
-		'pre_insertion',
96
-		[
97
-			'args' => [
98
-				'table' => 'spip_rubriques',
99
-			],
100
-			'data' => $champs
101
-		]
102
-	);
103
-
104
-	$id_rubrique = sql_insertq('spip_rubriques', $champs);
105
-	pipeline(
106
-		'post_insertion',
107
-		[
108
-			'args' => [
109
-				'table' => 'spip_rubriques',
110
-				'id_objet' => $id_rubrique
111
-			],
112
-			'data' => $champs
113
-		]
114
-	);
115
-	propager_les_secteurs();
116
-	calculer_langues_rubriques();
117
-
118
-	// Appeler une notification
119
-	if ($notifications = charger_fonction('notifications', 'inc')) {
120
-		$notifications(
121
-			'rubrique_inserer',
122
-			$id_rubrique,
123
-			[
124
-				'id_parent' => $id_parent,
125
-				'champs' => $champs,
126
-			]
127
-		);
128
-		$notifications(
129
-			'objet_inserer',
130
-			$id_rubrique,
131
-			[
132
-				'objet' => 'rubrique',
133
-				'id_objet' => $id_rubrique,
134
-				'id_parent' => $id_parent,
135
-				'champs' => $champs,
136
-			]
137
-		);
138
-	}
83
+    $champs = [
84
+        'titre' => _T('item_nouvelle_rubrique'),
85
+        'id_parent' => intval($id_parent),
86
+        'statut' => 'prepa'
87
+    ];
88
+
89
+    if ($set) {
90
+        $champs = array_merge($champs, $set);
91
+    }
92
+
93
+    // Envoyer aux plugins
94
+    $champs = pipeline(
95
+        'pre_insertion',
96
+        [
97
+            'args' => [
98
+                'table' => 'spip_rubriques',
99
+            ],
100
+            'data' => $champs
101
+        ]
102
+    );
103
+
104
+    $id_rubrique = sql_insertq('spip_rubriques', $champs);
105
+    pipeline(
106
+        'post_insertion',
107
+        [
108
+            'args' => [
109
+                'table' => 'spip_rubriques',
110
+                'id_objet' => $id_rubrique
111
+            ],
112
+            'data' => $champs
113
+        ]
114
+    );
115
+    propager_les_secteurs();
116
+    calculer_langues_rubriques();
117
+
118
+    // Appeler une notification
119
+    if ($notifications = charger_fonction('notifications', 'inc')) {
120
+        $notifications(
121
+            'rubrique_inserer',
122
+            $id_rubrique,
123
+            [
124
+                'id_parent' => $id_parent,
125
+                'champs' => $champs,
126
+            ]
127
+        );
128
+        $notifications(
129
+            'objet_inserer',
130
+            $id_rubrique,
131
+            [
132
+                'objet' => 'rubrique',
133
+                'id_objet' => $id_rubrique,
134
+                'id_parent' => $id_parent,
135
+                'champs' => $champs,
136
+            ]
137
+        );
138
+    }
139 139
 	
140
-	return $id_rubrique;
140
+    return $id_rubrique;
141 141
 }
142 142
 
143 143
 /**
@@ -153,46 +153,46 @@  discard block
 block discarded – undo
153 153
  *     - chaîne : texte d'un message d'erreur
154 154
  */
155 155
 function rubrique_modifier($id_rubrique, $set = null) {
156
-	include_spip('inc/autoriser');
157
-	include_spip('inc/filtres');
158
-
159
-	include_spip('inc/modifier');
160
-	$c = collecter_requests(
161
-		// include list
162
-		objet_info('rubrique', 'champs_editables'),
163
-		// exclude list
164
-		['id_parent', 'confirme_deplace'],
165
-		// donnees eventuellement fournies
166
-		$set
167
-	);
168
-
169
-	if (
170
-		$err = objet_modifier_champs(
171
-			'rubrique',
172
-			$id_rubrique,
173
-			[
174
-			'data' => $set,
175
-			'nonvide' => ['titre' => _T('titre_nouvelle_rubrique') . ' ' . _T('info_numero_abbreviation') . $id_rubrique]
176
-			],
177
-			$c
178
-		)
179
-	) {
180
-		return $err;
181
-	}
182
-
183
-	$c = collecter_requests(['id_parent', 'confirme_deplace'], [], $set);
184
-	// Deplacer la rubrique
185
-	if (isset($c['id_parent'])) {
186
-		$err = rubrique_instituer($id_rubrique, $c);
187
-	}
188
-
189
-	// invalider les caches marques de cette rubrique
190
-	include_spip('inc/invalideur');
191
-	suivre_invalideur("id='rubrique/$id_rubrique'");
192
-	// et celui de menu_rubriques
193
-	effacer_meta('date_calcul_rubriques');
194
-
195
-	return $err;
156
+    include_spip('inc/autoriser');
157
+    include_spip('inc/filtres');
158
+
159
+    include_spip('inc/modifier');
160
+    $c = collecter_requests(
161
+        // include list
162
+        objet_info('rubrique', 'champs_editables'),
163
+        // exclude list
164
+        ['id_parent', 'confirme_deplace'],
165
+        // donnees eventuellement fournies
166
+        $set
167
+    );
168
+
169
+    if (
170
+        $err = objet_modifier_champs(
171
+            'rubrique',
172
+            $id_rubrique,
173
+            [
174
+            'data' => $set,
175
+            'nonvide' => ['titre' => _T('titre_nouvelle_rubrique') . ' ' . _T('info_numero_abbreviation') . $id_rubrique]
176
+            ],
177
+            $c
178
+        )
179
+    ) {
180
+        return $err;
181
+    }
182
+
183
+    $c = collecter_requests(['id_parent', 'confirme_deplace'], [], $set);
184
+    // Deplacer la rubrique
185
+    if (isset($c['id_parent'])) {
186
+        $err = rubrique_instituer($id_rubrique, $c);
187
+    }
188
+
189
+    // invalider les caches marques de cette rubrique
190
+    include_spip('inc/invalideur');
191
+    suivre_invalideur("id='rubrique/$id_rubrique'");
192
+    // et celui de menu_rubriques
193
+    effacer_meta('date_calcul_rubriques');
194
+
195
+    return $err;
196 196
 }
197 197
 
198 198
 /**
@@ -215,29 +215,29 @@  discard block
 block discarded – undo
215 215
  *     false si la confirmation du déplacement n'est pas présente
216 216
  */
217 217
 function editer_rubrique_breves($id_rubrique, $id_parent, $c = []) {
218
-	if (!sql_table_exists('spip_breves')) {
219
-		return true;
220
-	}
221
-
222
-	if (!sql_countsel('spip_breves', "id_rubrique=$id_rubrique")) {
223
-		return true;
224
-	}
225
-
226
-	if (empty($c['confirme_deplace']) or $c['confirme_deplace'] != 'oui') {
227
-		return false;
228
-	}
229
-
230
-	if (
231
-		$id_secteur = sql_getfetsel(
232
-			'id_secteur',
233
-			'spip_rubriques',
234
-			"id_rubrique=$id_parent"
235
-		)
236
-	) {
237
-		sql_updateq('spip_breves', ['id_rubrique' => $id_secteur], "id_rubrique=$id_rubrique");
238
-	}
239
-
240
-	return true;
218
+    if (!sql_table_exists('spip_breves')) {
219
+        return true;
220
+    }
221
+
222
+    if (!sql_countsel('spip_breves', "id_rubrique=$id_rubrique")) {
223
+        return true;
224
+    }
225
+
226
+    if (empty($c['confirme_deplace']) or $c['confirme_deplace'] != 'oui') {
227
+        return false;
228
+    }
229
+
230
+    if (
231
+        $id_secteur = sql_getfetsel(
232
+            'id_secteur',
233
+            'spip_rubriques',
234
+            "id_rubrique=$id_parent"
235
+        )
236
+    ) {
237
+        sql_updateq('spip_breves', ['id_rubrique' => $id_secteur], "id_rubrique=$id_rubrique");
238
+    }
239
+
240
+    return true;
241 241
 }
242 242
 
243 243
 
@@ -259,72 +259,72 @@  discard block
 block discarded – undo
259 259
  *     Chaîne : texte du message d'erreur
260 260
  */
261 261
 function rubrique_instituer($id_rubrique, $c) {
262
-	// traitement de la rubrique parente
263
-	// interdiction de deplacer vers ou a partir d'une rubrique
264
-	// qu'on n'administre pas.
265
-
266
-	if (null !== ($id_parent = $c['id_parent'])) {
267
-		$id_parent = intval($id_parent);
268
-		$filles = calcul_branche_in($id_rubrique);
269
-		if (strpos(",$id_parent,", (string) ",$filles,") !== false) {
270
-			spip_log("La rubrique $id_rubrique ne peut etre fille de sa descendante $id_parent");
271
-		} else {
272
-			$s = sql_fetsel('id_parent, statut', 'spip_rubriques', "id_rubrique=$id_rubrique");
273
-			$old_parent = $s['id_parent'];
274
-
275
-			if (
276
-				!($id_parent != $old_parent
277
-				and autoriser('publierdans', 'rubrique', $id_parent)
278
-				and autoriser('creerrubriquedans', 'rubrique', $id_parent)
279
-				and autoriser('publierdans', 'rubrique', $old_parent)
280
-				)
281
-			) {
282
-				if ($s['statut'] != 'prepa') {
283
-					spip_log("deplacement de $id_rubrique vers $id_parent refuse a " . $GLOBALS['visiteur_session']['id_auteur'] . ' ' . $GLOBALS['visiteur_session']['statut']);
284
-				}
285
-			} elseif (editer_rubrique_breves($id_rubrique, $id_parent, $c)) {
286
-				$statut_ancien = $s['statut'];
287
-				sql_updateq('spip_rubriques', ['id_parent' => $id_parent], "id_rubrique=$id_rubrique");
288
-
289
-
290
-				propager_les_secteurs();
291
-
292
-				// Deplacement d'une rubrique publiee ==> chgt general de leur statut
293
-				if ($statut_ancien == 'publie') {
294
-					calculer_rubriques_if($old_parent, ['id_rubrique' => $id_parent], ['statut_ancien' => $statut_ancien]);
295
-				}
296
-				// Creation ou deplacement d'une rubrique non publiee
297
-				// invalider le cache de leur menu
298
-				elseif (!$statut_ancien || $old_parent != $id_parent) {
299
-					effacer_meta('date_calcul_rubriques');
300
-				}
301
-
302
-				calculer_langues_rubriques();
262
+    // traitement de la rubrique parente
263
+    // interdiction de deplacer vers ou a partir d'une rubrique
264
+    // qu'on n'administre pas.
265
+
266
+    if (null !== ($id_parent = $c['id_parent'])) {
267
+        $id_parent = intval($id_parent);
268
+        $filles = calcul_branche_in($id_rubrique);
269
+        if (strpos(",$id_parent,", (string) ",$filles,") !== false) {
270
+            spip_log("La rubrique $id_rubrique ne peut etre fille de sa descendante $id_parent");
271
+        } else {
272
+            $s = sql_fetsel('id_parent, statut', 'spip_rubriques', "id_rubrique=$id_rubrique");
273
+            $old_parent = $s['id_parent'];
274
+
275
+            if (
276
+                !($id_parent != $old_parent
277
+                and autoriser('publierdans', 'rubrique', $id_parent)
278
+                and autoriser('creerrubriquedans', 'rubrique', $id_parent)
279
+                and autoriser('publierdans', 'rubrique', $old_parent)
280
+                )
281
+            ) {
282
+                if ($s['statut'] != 'prepa') {
283
+                    spip_log("deplacement de $id_rubrique vers $id_parent refuse a " . $GLOBALS['visiteur_session']['id_auteur'] . ' ' . $GLOBALS['visiteur_session']['statut']);
284
+                }
285
+            } elseif (editer_rubrique_breves($id_rubrique, $id_parent, $c)) {
286
+                $statut_ancien = $s['statut'];
287
+                sql_updateq('spip_rubriques', ['id_parent' => $id_parent], "id_rubrique=$id_rubrique");
288
+
289
+
290
+                propager_les_secteurs();
291
+
292
+                // Deplacement d'une rubrique publiee ==> chgt general de leur statut
293
+                if ($statut_ancien == 'publie') {
294
+                    calculer_rubriques_if($old_parent, ['id_rubrique' => $id_parent], ['statut_ancien' => $statut_ancien]);
295
+                }
296
+                // Creation ou deplacement d'une rubrique non publiee
297
+                // invalider le cache de leur menu
298
+                elseif (!$statut_ancien || $old_parent != $id_parent) {
299
+                    effacer_meta('date_calcul_rubriques');
300
+                }
301
+
302
+                calculer_langues_rubriques();
303 303
 				
304
-				// Appeler une notification
305
-				if ($notifications = charger_fonction('notifications', 'inc')) {
306
-					$notifications(
307
-						'rubrique_instituer',
308
-						$id_rubrique,
309
-						[
310
-							'statut_ancien' => $statut_ancien,
311
-							'id_parent_ancien' => $old_parent,
312
-						]
313
-					);
314
-					$notifications(
315
-						'objet_instituer',
316
-						$id_rubrique,
317
-						[
318
-							'objet' => 'rubrique',
319
-							'id_objet' => $id_rubrique,
320
-							'statut_ancien' => $statut_ancien,
321
-							'id_parent_ancien' => $old_parent,
322
-						]
323
-					);
324
-				}
325
-			}
326
-		}
327
-	}
328
-
329
-	return ''; // pas d'erreur
304
+                // Appeler une notification
305
+                if ($notifications = charger_fonction('notifications', 'inc')) {
306
+                    $notifications(
307
+                        'rubrique_instituer',
308
+                        $id_rubrique,
309
+                        [
310
+                            'statut_ancien' => $statut_ancien,
311
+                            'id_parent_ancien' => $old_parent,
312
+                        ]
313
+                    );
314
+                    $notifications(
315
+                        'objet_instituer',
316
+                        $id_rubrique,
317
+                        [
318
+                            'objet' => 'rubrique',
319
+                            'id_objet' => $id_rubrique,
320
+                            'statut_ancien' => $statut_ancien,
321
+                            'id_parent_ancien' => $old_parent,
322
+                        ]
323
+                    );
324
+                }
325
+            }
326
+        }
327
+    }
328
+
329
+    return ''; // pas d'erreur
330 330
 }
Please login to merge, or discard this patch.
ecrire/inc/filtres_dates.php 2 patches
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
 function extraire_date($texte): string {
40 40
 	// format = 2001-08
41 41
 	if (preg_match(',([1-2][0-9]{3})[^0-9]*(1[0-2]|0?[1-9]),', $texte, $regs)) {
42
-		return $regs[1] . '-' . sprintf('%02d', $regs[2]) . '-01';
42
+		return $regs[1].'-'.sprintf('%02d', $regs[2]).'-01';
43 43
 	}
44 44
 	return '';
45 45
 }
@@ -70,11 +70,11 @@  discard block
 block discarded – undo
70 70
 		}
71 71
 		if (preg_match('#^([12][0-9]{3})([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
72 72
 			$regs = array_pad($regs, 4, null); // eviter notice php
73
-			$date = $regs[1] . '-00-00' . $regs[3];
73
+			$date = $regs[1].'-00-00'.$regs[3];
74 74
 		} else {
75 75
 			if (preg_match('#^([12][0-9]{3}[-/][01]?[0-9])([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
76 76
 				$regs = array_pad($regs, 4, null); // eviter notice php
77
-				$date = preg_replace('@/@', '-', $regs[1]) . '-00' . $regs[3];
77
+				$date = preg_replace('@/@', '-', $regs[1]).'-00'.$regs[3];
78 78
 			} else {
79 79
 				$date = date('Y-m-d H:i:s', strtotime($date));
80 80
 			}
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 	$letexte ??= '';
102 102
 	if (
103 103
 		!$verif_format_date
104
-		or (in_array(strlen($letexte), [10,19]) and
104
+		or (in_array(strlen($letexte), [10, 19]) and
105 105
 			  preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}(\s[0-9]{2}:[0-9]{2}:[0-9]{2})?$/', $letexte))
106 106
 	) {
107 107
 		if (strncmp('0000-00-00', $letexte, 10) == 0) {
@@ -388,17 +388,17 @@  discard block
 block discarded – undo
388 388
 	if ($decal > 3600 * 24 * 30) {
389 389
 		$mois = floor($decal / (3600 * 24 * 30));
390 390
 		if ($mois < 2) {
391
-			$delai = "$mois " . _T('date_un_mois');
391
+			$delai = "$mois "._T('date_un_mois');
392 392
 		} else {
393
-			$delai = "$mois " . _T('date_mois');
393
+			$delai = "$mois "._T('date_mois');
394 394
 		}
395 395
 	} else {
396 396
 		if ($decal > 3600 * 24 * 7) {
397 397
 			$semaines = floor($decal / (3600 * 24 * 7));
398 398
 			if ($semaines < 2) {
399
-				$delai = "$semaines " . _T('date_une_semaine');
399
+				$delai = "$semaines "._T('date_une_semaine');
400 400
 			} else {
401
-				$delai = "$semaines " . _T('date_semaines');
401
+				$delai = "$semaines "._T('date_semaines');
402 402
 			}
403 403
 		} else {
404 404
 			if ($decal > 3600 * 24) {
@@ -406,30 +406,30 @@  discard block
 block discarded – undo
406 406
 				if ($jours < 2) {
407 407
 					return $il_y_a == 'date_dans' ? _T('date_demain') : _T('date_hier');
408 408
 				} else {
409
-					$delai = "$jours " . _T('date_jours');
409
+					$delai = "$jours "._T('date_jours');
410 410
 				}
411 411
 			} else {
412 412
 				if ($decal >= 3600) {
413 413
 					$heures = floor($decal / 3600);
414 414
 					if ($heures < 2) {
415
-						$delai = "$heures " . _T('date_une_heure');
415
+						$delai = "$heures "._T('date_une_heure');
416 416
 					} else {
417
-						$delai = "$heures " . _T('date_heures');
417
+						$delai = "$heures "._T('date_heures');
418 418
 					}
419 419
 				} else {
420 420
 					if ($decal >= 60) {
421 421
 						$minutes = floor($decal / 60);
422 422
 						if ($minutes < 2) {
423
-							$delai = "$minutes " . _T('date_une_minute');
423
+							$delai = "$minutes "._T('date_une_minute');
424 424
 						} else {
425
-							$delai = "$minutes " . _T('date_minutes');
425
+							$delai = "$minutes "._T('date_minutes');
426 426
 						}
427 427
 					} else {
428 428
 						$secondes = ceil($decal);
429 429
 						if ($secondes < 2) {
430
-							$delai = "$secondes " . _T('date_une_seconde');
430
+							$delai = "$secondes "._T('date_une_seconde');
431 431
 						} else {
432
-							$delai = "$secondes " . _T('date_secondes');
432
+							$delai = "$secondes "._T('date_secondes');
433 433
 						}
434 434
 					}
435 435
 				}
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
 		$njour = 0;
523 523
 	} else {
524 524
 		$njour = intval($jour);
525
-		if ($jourth = _T('date_jnum' . $jour)) {
525
+		if ($jourth = _T('date_jnum'.$jour)) {
526 526
 			$jour = $jourth;
527 527
 		}
528 528
 	}
@@ -530,10 +530,10 @@  discard block
 block discarded – undo
530 530
 	$mois = intval($mois);
531 531
 	if ($mois > 0 and $mois < 13) {
532 532
 		/* Traiter le cas "abbr" pour les noms de mois */
533
-		$param = ((isset($options['param']) and $options['param'] === 'abbr') ? '_' . $options['param'] : '');
534
-		$nommois = _T('date_mois_' . $mois . $param);
533
+		$param = ((isset($options['param']) and $options['param'] === 'abbr') ? '_'.$options['param'] : '');
534
+		$nommois = _T('date_mois_'.$mois.$param);
535 535
 		if ($jour) {
536
-			$jourmois = _T('date_de_mois_' . $mois, ['j' => $jour, 'nommois' => $nommois]);
536
+			$jourmois = _T('date_de_mois_'.$mois, ['j' => $jour, 'nommois' => $nommois]);
537 537
 		} else {
538 538
 			$jourmois = $nommois;
539 539
 		}
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 	}
544 544
 
545 545
 	if ($annee < 0) {
546
-		$annee = -$annee . ' ' . _T('date_avant_jc');
546
+		$annee = -$annee.' '._T('date_avant_jc');
547 547
 		$avjc = true;
548 548
 	} else {
549 549
 		$avjc = false;
@@ -569,11 +569,11 @@  discard block
 block discarded – undo
569 569
 				}
570 570
 			}
571 571
 			if ($vue == 'saison') {
572
-				return $saison ? _T('date_saison_' . $saison) : '';
572
+				return $saison ? _T('date_saison_'.$saison) : '';
573 573
 			} else {
574 574
 				return $saison ? trim(_T(
575 575
 					'date_fmt_saison_annee',
576
-					['saison' => _T('date_saison_' . $saison), 'annee' => $annee]
576
+					['saison' => _T('date_saison_'.$saison), 'annee' => $annee]
577 577
 				)) : '';
578 578
 			}
579 579
 
@@ -650,9 +650,9 @@  discard block
 block discarded – undo
650 650
 			}
651 651
 			$nom = mktime(1, 1, 1, $mois, $njour, $annee);
652 652
 			$nom = 1 + (int) date('w', $nom);
653
-			$param = ((isset($options['param']) and $options['param']) ? '_' . $options['param'] : '');
653
+			$param = ((isset($options['param']) and $options['param']) ? '_'.$options['param'] : '');
654 654
 
655
-			return _T('date_jour_' . $nom . $param);
655
+			return _T('date_jour_'.$nom.$param);
656 656
 
657 657
 		case 'mois_annee':
658 658
 			if ($avjc) {
@@ -1047,8 +1047,8 @@  discard block
 block discarded – undo
1047 1047
 
1048 1048
 	$dtstart = $dtend = $dtabbr = '';
1049 1049
 	if (strpos($forme, 'hcal') !== false) {
1050
-		$dtstart = "<abbr class='dtstart' title='" . date_iso($date_debut) . "'>";
1051
-		$dtend = "<abbr class='dtend' title='" . date_iso($date_fin) . "'>";
1050
+		$dtstart = "<abbr class='dtstart' title='".date_iso($date_debut)."'>";
1051
+		$dtend = "<abbr class='dtend' title='".date_iso($date_fin)."'>";
1052 1052
 		$dtabbr = '</abbr>';
1053 1053
 	}
1054 1054
 
@@ -1096,7 +1096,7 @@  discard block
 block discarded – undo
1096 1096
 			}
1097 1097
 		} else {
1098 1098
 			if ($dtabbr && $dtstart) {
1099
-				$s = $dtstart . spip_ucfirst($s) . $dtabbr;
1099
+				$s = $dtstart.spip_ucfirst($s).$dtabbr;
1100 1100
 			} else {
1101 1101
 				$s = spip_ucfirst($s);
1102 1102
 			}
@@ -1119,8 +1119,8 @@  discard block
 block discarded – undo
1119 1119
 				$date_debut = _T('date_fmt_jour_heure', ['jour' => $date_debut, 'heure' => $hd]);
1120 1120
 				$date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1121 1121
 			}
1122
-			$date_debut = $dtstart . $date_debut . $dtabbr;
1123
-			$date_fin = $dtend . $date_fin . $dtabbr;
1122
+			$date_debut = $dtstart.$date_debut.$dtabbr;
1123
+			$date_fin = $dtend.$date_fin.$dtabbr;
1124 1124
 
1125 1125
 			$s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1126 1126
 		} else {
@@ -1137,8 +1137,8 @@  discard block
 block discarded – undo
1137 1137
 				$date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1138 1138
 			}
1139 1139
 
1140
-			$date_debut = $dtstart . $date_debut . $dtabbr;
1141
-			$date_fin = $dtend . $date_fin . $dtabbr;
1140
+			$date_debut = $dtstart.$date_debut.$dtabbr;
1141
+			$date_fin = $dtend.$date_fin.$dtabbr;
1142 1142
 			$s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1143 1143
 		}
1144 1144
 	}
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
 		$d = date('Y-m-d');
1243 1243
 	}
1244 1244
 
1245
-	return substr($d, 0, 4) . substr($d, 5, 2) . substr($d, 8, 2);
1245
+	return substr($d, 0, 4).substr($d, 5, 2).substr($d, 8, 2);
1246 1246
 }
1247 1247
 
1248 1248
 /**
@@ -1262,7 +1262,7 @@  discard block
 block discarded – undo
1262 1262
 		$d = date('Y-m-d');
1263 1263
 	}
1264 1264
 
1265
-	return substr($d, 0, 4) . substr($d, 5, 2);
1265
+	return substr($d, 0, 4).substr($d, 5, 2);
1266 1266
 }
1267 1267
 
1268 1268
 /**
Please login to merge, or discard this patch.
Indentation   +585 added lines, -585 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Filtres
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 
@@ -37,11 +37,11 @@  discard block
 block discarded – undo
37 37
  *    Date au format SQL tel que `2008-04-01` sinon ''
38 38
  **/
39 39
 function extraire_date($texte): string {
40
-	// format = 2001-08
41
-	if (preg_match(',([1-2][0-9]{3})[^0-9]*(1[0-2]|0?[1-9]),', $texte, $regs)) {
42
-		return $regs[1] . '-' . sprintf('%02d', $regs[2]) . '-01';
43
-	}
44
-	return '';
40
+    // format = 2001-08
41
+    if (preg_match(',([1-2][0-9]{3})[^0-9]*(1[0-2]|0?[1-9]),', $texte, $regs)) {
42
+        return $regs[1] . '-' . sprintf('%02d', $regs[2]) . '-01';
43
+    }
44
+    return '';
45 45
 }
46 46
 
47 47
 
@@ -63,29 +63,29 @@  discard block
 block discarded – undo
63 63
  *     - une chaîne vide si la date est considérée nulle
64 64
  **/
65 65
 function normaliser_date($date, $forcer_jour = false): string {
66
-	$date = vider_date($date);
67
-	if ($date) {
68
-		if (preg_match('/^[0-9]{8,10}$/', $date)) {
69
-			$date = date('Y-m-d H:i:s', $date);
70
-		}
71
-		if (preg_match('#^([12][0-9]{3})([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
72
-			$regs = array_pad($regs, 4, null); // eviter notice php
73
-			$date = $regs[1] . '-00-00' . $regs[3];
74
-		} else {
75
-			if (preg_match('#^([12][0-9]{3}[-/][01]?[0-9])([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
76
-				$regs = array_pad($regs, 4, null); // eviter notice php
77
-				$date = preg_replace('@/@', '-', $regs[1]) . '-00' . $regs[3];
78
-			} else {
79
-				$date = date('Y-m-d H:i:s', strtotime($date));
80
-			}
81
-		}
82
-
83
-		if ($forcer_jour) {
84
-			$date = str_replace('-00', '-01', $date);
85
-		}
86
-	}
87
-
88
-	return $date;
66
+    $date = vider_date($date);
67
+    if ($date) {
68
+        if (preg_match('/^[0-9]{8,10}$/', $date)) {
69
+            $date = date('Y-m-d H:i:s', $date);
70
+        }
71
+        if (preg_match('#^([12][0-9]{3})([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
72
+            $regs = array_pad($regs, 4, null); // eviter notice php
73
+            $date = $regs[1] . '-00-00' . $regs[3];
74
+        } else {
75
+            if (preg_match('#^([12][0-9]{3}[-/][01]?[0-9])([-/]00)?( [-0-9:]+)?$#', $date, $regs)) {
76
+                $regs = array_pad($regs, 4, null); // eviter notice php
77
+                $date = preg_replace('@/@', '-', $regs[1]) . '-00' . $regs[3];
78
+            } else {
79
+                $date = date('Y-m-d H:i:s', strtotime($date));
80
+            }
81
+        }
82
+
83
+        if ($forcer_jour) {
84
+            $date = str_replace('-00', '-01', $date);
85
+        }
86
+    }
87
+
88
+    return $date;
89 89
 }
90 90
 
91 91
 /**
@@ -98,23 +98,23 @@  discard block
 block discarded – undo
98 98
  *     - Une chaine vide
99 99
  **/
100 100
 function vider_date($letexte, $verif_format_date = false): string {
101
-	$letexte ??= '';
102
-	if (
103
-		!$verif_format_date
104
-		or (in_array(strlen($letexte), [10,19]) and
105
-			  preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}(\s[0-9]{2}:[0-9]{2}:[0-9]{2})?$/', $letexte))
106
-	) {
107
-		if (strncmp('0000-00-00', $letexte, 10) == 0) {
108
-			return '';
109
-		}
110
-		if (strncmp('0001-01-01', $letexte, 10) == 0) {
111
-			return '';
112
-		}
113
-		if (strncmp('1970-01-01', $letexte, 10) == 0) {
114
-			return '';
115
-		}  // eviter le bug GMT-1
116
-	}
117
-	return $letexte;
101
+    $letexte ??= '';
102
+    if (
103
+        !$verif_format_date
104
+        or (in_array(strlen($letexte), [10,19]) and
105
+              preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}(\s[0-9]{2}:[0-9]{2}:[0-9]{2})?$/', $letexte))
106
+    ) {
107
+        if (strncmp('0000-00-00', $letexte, 10) == 0) {
108
+            return '';
109
+        }
110
+        if (strncmp('0001-01-01', $letexte, 10) == 0) {
111
+            return '';
112
+        }
113
+        if (strncmp('1970-01-01', $letexte, 10) == 0) {
114
+            return '';
115
+        }  // eviter le bug GMT-1
116
+    }
117
+    return $letexte;
118 118
 }
119 119
 
120 120
 /**
@@ -130,17 +130,17 @@  discard block
 block discarded – undo
130 130
  **/
131 131
 function recup_heure($date): array {
132 132
 
133
-	if (preg_match('#([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2}))?#', $date, $elements)) {
134
-		array_shift($elements);
135
-		if (!isset($elements[2])) {
136
-			$elements[2] = 0;
137
-		}
138
-		$heure = $elements;
139
-	} else {
140
-		$heure = [0, 0, 0];
141
-	}
142
-
143
-	return $heure;
133
+    if (preg_match('#([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2}))?#', $date, $elements)) {
134
+        array_shift($elements);
135
+        if (!isset($elements[2])) {
136
+            $elements[2] = 0;
137
+        }
138
+        $heure = $elements;
139
+    } else {
140
+        $heure = [0, 0, 0];
141
+    }
142
+
143
+    return $heure;
144 144
 }
145 145
 
146 146
 /**
@@ -154,13 +154,13 @@  discard block
 block discarded – undo
154 154
  * @return string heures, sinon 0
155 155
  **/
156 156
 function heures($numdate): string {
157
-	$heures = null;
158
-	$date_array = recup_heure($numdate);
159
-	if ($date_array) {
160
-		[$heures, $minutes, $secondes] = $date_array;
161
-	}
157
+    $heures = null;
158
+    $date_array = recup_heure($numdate);
159
+    if ($date_array) {
160
+        [$heures, $minutes, $secondes] = $date_array;
161
+    }
162 162
 
163
-	return $heures;
163
+    return $heures;
164 164
 }
165 165
 
166 166
 /**
@@ -174,13 +174,13 @@  discard block
 block discarded – undo
174 174
  * @return string minutes, sinon 0
175 175
  **/
176 176
 function minutes($numdate): string {
177
-	$minutes = null;
178
-	$date_array = recup_heure($numdate);
179
-	if ($date_array) {
180
-		[$heures, $minutes, $secondes] = $date_array;
181
-	}
177
+    $minutes = null;
178
+    $date_array = recup_heure($numdate);
179
+    if ($date_array) {
180
+        [$heures, $minutes, $secondes] = $date_array;
181
+    }
182 182
 
183
-	return $minutes;
183
+    return $minutes;
184 184
 }
185 185
 
186 186
 /**
@@ -194,13 +194,13 @@  discard block
 block discarded – undo
194 194
  * @return string secondes, sinon 0
195 195
  **/
196 196
 function secondes($numdate): string {
197
-	$secondes = null;
198
-	$date_array = recup_heure($numdate);
199
-	if ($date_array) {
200
-		[$heures, $minutes, $secondes] = $date_array;
201
-	}
197
+    $secondes = null;
198
+    $date_array = recup_heure($numdate);
199
+    if ($date_array) {
200
+        [$heures, $minutes, $secondes] = $date_array;
201
+    }
202 202
 
203
-	return $secondes;
203
+    return $secondes;
204 204
 }
205 205
 
206 206
 /**
@@ -219,11 +219,11 @@  discard block
 block discarded – undo
219 219
  * @return string L'heure formatée dans la langue en cours.
220 220
  **/
221 221
 function heures_minutes($numdate, $forme = ''): string {
222
-	if ($forme !== 'abbr') {
223
-		return _T('date_fmt_heures_minutes', ['h' => heures($numdate), 'm' => minutes($numdate)]);
224
-	} else {
225
-		return _T('date_fmt_heures_minutes_court', ['h' => heures($numdate), 'm' => minutes($numdate)]);
226
-	}
222
+    if ($forme !== 'abbr') {
223
+        return _T('date_fmt_heures_minutes', ['h' => heures($numdate), 'm' => minutes($numdate)]);
224
+    } else {
225
+        return _T('date_fmt_heures_minutes_court', ['h' => heures($numdate), 'm' => minutes($numdate)]);
226
+    }
227 227
 }
228 228
 
229 229
 /**
@@ -248,57 +248,57 @@  discard block
 block discarded – undo
248 248
  * @return array [année, mois, jour, heures, minutes, secondes] ou []
249 249
  **/
250 250
 function recup_date($numdate, $forcer_jour = true): array {
251
-	if (!$numdate) {
252
-		return [];
253
-	}
254
-	$heures = $minutes = $secondes = 0;
255
-	if (preg_match('#([0-9]{1,2})/([0-9]{1,2})/([0-9]{4}|[0-9]{1,2})#', $numdate, $regs)) {
256
-		$jour = $regs[1];
257
-		$mois = $regs[2];
258
-		$annee = $regs[3];
259
-		if ($annee < 90) {
260
-			$annee = 2000 + $annee;
261
-		} elseif ($annee < 100) {
262
-			$annee = 1900 + $annee;
263
-		}
264
-		[$heures, $minutes, $secondes] = recup_heure($numdate);
265
-	} elseif (preg_match('#([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})#', $numdate, $regs)) {
266
-		$annee = $regs[1];
267
-		$mois = $regs[2];
268
-		$jour = $regs[3];
269
-		[$heures, $minutes, $secondes] = recup_heure($numdate);
270
-	} elseif (preg_match('#([0-9]{4})-([0-9]{2})#', $numdate, $regs)) {
271
-		$annee = $regs[1];
272
-		$mois = $regs[2];
273
-		$jour = '';
274
-		[$heures, $minutes, $secondes] = recup_heure($numdate);
275
-	} elseif (preg_match('#^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})$#', $numdate, $regs)) {
276
-		$annee = $regs[1];
277
-		$mois = $regs[2];
278
-		$jour = $regs[3];
279
-		$heures = $regs[4];
280
-		$minutes = $regs[5];
281
-		$secondes = $regs[6];
282
-	} else {
283
-		$annee = $mois = $jour = '';
284
-	}
285
-	if ($annee > 4000) {
286
-		$annee -= 9000;
287
-	}
288
-	if (strlen($jour) and substr($jour, 0, 1) == '0') {
289
-		$jour = substr($jour, 1);
290
-	}
291
-
292
-	if ($forcer_jour and $jour == '0') {
293
-		$jour = '1';
294
-	}
295
-	if ($forcer_jour and $mois == '0') {
296
-		$mois = '1';
297
-	}
298
-	if ($annee or $mois or $jour or $heures or $minutes or $secondes) {
299
-		return [$annee, $mois, $jour, $heures, $minutes, $secondes];
300
-	}
301
-	return [];
251
+    if (!$numdate) {
252
+        return [];
253
+    }
254
+    $heures = $minutes = $secondes = 0;
255
+    if (preg_match('#([0-9]{1,2})/([0-9]{1,2})/([0-9]{4}|[0-9]{1,2})#', $numdate, $regs)) {
256
+        $jour = $regs[1];
257
+        $mois = $regs[2];
258
+        $annee = $regs[3];
259
+        if ($annee < 90) {
260
+            $annee = 2000 + $annee;
261
+        } elseif ($annee < 100) {
262
+            $annee = 1900 + $annee;
263
+        }
264
+        [$heures, $minutes, $secondes] = recup_heure($numdate);
265
+    } elseif (preg_match('#([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})#', $numdate, $regs)) {
266
+        $annee = $regs[1];
267
+        $mois = $regs[2];
268
+        $jour = $regs[3];
269
+        [$heures, $minutes, $secondes] = recup_heure($numdate);
270
+    } elseif (preg_match('#([0-9]{4})-([0-9]{2})#', $numdate, $regs)) {
271
+        $annee = $regs[1];
272
+        $mois = $regs[2];
273
+        $jour = '';
274
+        [$heures, $minutes, $secondes] = recup_heure($numdate);
275
+    } elseif (preg_match('#^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})$#', $numdate, $regs)) {
276
+        $annee = $regs[1];
277
+        $mois = $regs[2];
278
+        $jour = $regs[3];
279
+        $heures = $regs[4];
280
+        $minutes = $regs[5];
281
+        $secondes = $regs[6];
282
+    } else {
283
+        $annee = $mois = $jour = '';
284
+    }
285
+    if ($annee > 4000) {
286
+        $annee -= 9000;
287
+    }
288
+    if (strlen($jour) and substr($jour, 0, 1) == '0') {
289
+        $jour = substr($jour, 1);
290
+    }
291
+
292
+    if ($forcer_jour and $jour == '0') {
293
+        $jour = '1';
294
+    }
295
+    if ($forcer_jour and $mois == '0') {
296
+        $mois = '1';
297
+    }
298
+    if ($annee or $mois or $jour or $heures or $minutes or $secondes) {
299
+        return [$annee, $mois, $jour, $heures, $minutes, $secondes];
300
+    }
301
+    return [];
302 302
 }
303 303
 
304 304
 /**
@@ -325,10 +325,10 @@  discard block
 block discarded – undo
325 325
  *     La date relative ou complète
326 326
  **/
327 327
 function date_interface($date, $decalage_maxi = 43200 /* 12*3600 */): string {
328
-	return sinon(
329
-		date_relative($date, $decalage_maxi),
330
-		affdate_heure($date)
331
-	);
328
+    return sinon(
329
+        date_relative($date, $decalage_maxi),
330
+        affdate_heure($date)
331
+    );
332 332
 }
333 333
 
334 334
 /**
@@ -361,86 +361,86 @@  discard block
 block discarded – undo
361 361
  **/
362 362
 function date_relative($date, $decalage_maxi = 0, $ref_date = null): string {
363 363
 
364
-	if (!$date) {
365
-		return '';
366
-	}
367
-
368
-	if (is_null($ref_date)) {
369
-		$ref_time = time();
370
-	} else {
371
-		$ref_time = strtotime($ref_date);
372
-	}
373
-
374
-	$decal = date('U', $ref_time) - date('U', strtotime($date));
375
-
376
-	if ($decalage_maxi and ($decal > $decalage_maxi or $decal < 0)) {
377
-		return '';
378
-	}
379
-
380
-	if ($decal < 0) {
381
-		$il_y_a = 'date_dans';
382
-		$decal = -1 * $decal;
383
-	} else {
384
-		$il_y_a = 'date_il_y_a';
385
-	}
386
-
387
-	if ($decal > 3600 * 24 * 30 * 6) {
388
-		return affdate_court($date);
389
-	}
390
-
391
-	if ($decal > 3600 * 24 * 30) {
392
-		$mois = floor($decal / (3600 * 24 * 30));
393
-		if ($mois < 2) {
394
-			$delai = "$mois " . _T('date_un_mois');
395
-		} else {
396
-			$delai = "$mois " . _T('date_mois');
397
-		}
398
-	} else {
399
-		if ($decal > 3600 * 24 * 7) {
400
-			$semaines = floor($decal / (3600 * 24 * 7));
401
-			if ($semaines < 2) {
402
-				$delai = "$semaines " . _T('date_une_semaine');
403
-			} else {
404
-				$delai = "$semaines " . _T('date_semaines');
405
-			}
406
-		} else {
407
-			if ($decal > 3600 * 24) {
408
-				$jours = floor($decal / (3600 * 24));
409
-				if ($jours < 2) {
410
-					return $il_y_a == 'date_dans' ? _T('date_demain') : _T('date_hier');
411
-				} else {
412
-					$delai = "$jours " . _T('date_jours');
413
-				}
414
-			} else {
415
-				if ($decal >= 3600) {
416
-					$heures = floor($decal / 3600);
417
-					if ($heures < 2) {
418
-						$delai = "$heures " . _T('date_une_heure');
419
-					} else {
420
-						$delai = "$heures " . _T('date_heures');
421
-					}
422
-				} else {
423
-					if ($decal >= 60) {
424
-						$minutes = floor($decal / 60);
425
-						if ($minutes < 2) {
426
-							$delai = "$minutes " . _T('date_une_minute');
427
-						} else {
428
-							$delai = "$minutes " . _T('date_minutes');
429
-						}
430
-					} else {
431
-						$secondes = ceil($decal);
432
-						if ($secondes < 2) {
433
-							$delai = "$secondes " . _T('date_une_seconde');
434
-						} else {
435
-							$delai = "$secondes " . _T('date_secondes');
436
-						}
437
-					}
438
-				}
439
-			}
440
-		}
441
-	}
442
-
443
-	return _T($il_y_a, ['delai' => $delai]);
364
+    if (!$date) {
365
+        return '';
366
+    }
367
+
368
+    if (is_null($ref_date)) {
369
+        $ref_time = time();
370
+    } else {
371
+        $ref_time = strtotime($ref_date);
372
+    }
373
+
374
+    $decal = date('U', $ref_time) - date('U', strtotime($date));
375
+
376
+    if ($decalage_maxi and ($decal > $decalage_maxi or $decal < 0)) {
377
+        return '';
378
+    }
379
+
380
+    if ($decal < 0) {
381
+        $il_y_a = 'date_dans';
382
+        $decal = -1 * $decal;
383
+    } else {
384
+        $il_y_a = 'date_il_y_a';
385
+    }
386
+
387
+    if ($decal > 3600 * 24 * 30 * 6) {
388
+        return affdate_court($date);
389
+    }
390
+
391
+    if ($decal > 3600 * 24 * 30) {
392
+        $mois = floor($decal / (3600 * 24 * 30));
393
+        if ($mois < 2) {
394
+            $delai = "$mois " . _T('date_un_mois');
395
+        } else {
396
+            $delai = "$mois " . _T('date_mois');
397
+        }
398
+    } else {
399
+        if ($decal > 3600 * 24 * 7) {
400
+            $semaines = floor($decal / (3600 * 24 * 7));
401
+            if ($semaines < 2) {
402
+                $delai = "$semaines " . _T('date_une_semaine');
403
+            } else {
404
+                $delai = "$semaines " . _T('date_semaines');
405
+            }
406
+        } else {
407
+            if ($decal > 3600 * 24) {
408
+                $jours = floor($decal / (3600 * 24));
409
+                if ($jours < 2) {
410
+                    return $il_y_a == 'date_dans' ? _T('date_demain') : _T('date_hier');
411
+                } else {
412
+                    $delai = "$jours " . _T('date_jours');
413
+                }
414
+            } else {
415
+                if ($decal >= 3600) {
416
+                    $heures = floor($decal / 3600);
417
+                    if ($heures < 2) {
418
+                        $delai = "$heures " . _T('date_une_heure');
419
+                    } else {
420
+                        $delai = "$heures " . _T('date_heures');
421
+                    }
422
+                } else {
423
+                    if ($decal >= 60) {
424
+                        $minutes = floor($decal / 60);
425
+                        if ($minutes < 2) {
426
+                            $delai = "$minutes " . _T('date_une_minute');
427
+                        } else {
428
+                            $delai = "$minutes " . _T('date_minutes');
429
+                        }
430
+                    } else {
431
+                        $secondes = ceil($decal);
432
+                        if ($secondes < 2) {
433
+                            $delai = "$secondes " . _T('date_une_seconde');
434
+                        } else {
435
+                            $delai = "$secondes " . _T('date_secondes');
436
+                        }
437
+                    }
438
+                }
439
+            }
440
+        }
441
+    }
442
+
443
+    return _T($il_y_a, ['delai' => $delai]);
444 444
 }
445 445
 
446 446
 
@@ -466,32 +466,32 @@  discard block
 block discarded – undo
466 466
  **/
467 467
 function date_relativecourt($date, $decalage_maxi = 0): string {
468 468
 
469
-	if (!$date) {
470
-		return '';
471
-	}
472
-	$decal = date('U', strtotime(date('Y-m-d')) - strtotime(date('Y-m-d', strtotime($date))));
473
-
474
-	if ($decalage_maxi and ($decal > $decalage_maxi or $decal < 0)) {
475
-		return '';
476
-	}
477
-
478
-	if ($decal < -24 * 3600) {
479
-		$retour = date_relative($date, $decalage_maxi);
480
-	} elseif ($decal < 0) {
481
-		$retour = _T('date_demain');
482
-	} else {
483
-		if ($decal < (3600 * 24)) {
484
-			$retour = _T('date_aujourdhui');
485
-		} else {
486
-			if ($decal < (3600 * 24 * 2)) {
487
-				$retour = _T('date_hier');
488
-			} else {
489
-				$retour = date_relative($date, $decalage_maxi);
490
-			}
491
-		}
492
-	}
493
-
494
-	return $retour;
469
+    if (!$date) {
470
+        return '';
471
+    }
472
+    $decal = date('U', strtotime(date('Y-m-d')) - strtotime(date('Y-m-d', strtotime($date))));
473
+
474
+    if ($decalage_maxi and ($decal > $decalage_maxi or $decal < 0)) {
475
+        return '';
476
+    }
477
+
478
+    if ($decal < -24 * 3600) {
479
+        $retour = date_relative($date, $decalage_maxi);
480
+    } elseif ($decal < 0) {
481
+        $retour = _T('date_demain');
482
+    } else {
483
+        if ($decal < (3600 * 24)) {
484
+            $retour = _T('date_aujourdhui');
485
+        } else {
486
+            if ($decal < (3600 * 24 * 2)) {
487
+                $retour = _T('date_hier');
488
+            } else {
489
+                $retour = date_relative($date, $decalage_maxi);
490
+            }
491
+        }
492
+    }
493
+
494
+    return $retour;
495 495
 }
496 496
 
497 497
 /**
@@ -508,174 +508,174 @@  discard block
 block discarded – undo
508 508
  * @return string
509 509
  */
510 510
 function affdate_base($numdate, $vue, $options = []): string {
511
-	if (is_string($options)) {
512
-		$options = ['param' => $options];
513
-	}
514
-	$date_array = recup_date($numdate, false);
515
-	if (!$date_array) {
516
-		return '';
517
-	}
518
-	[$annee, $mois, $jour, $heures, $minutes, $secondes] = $date_array;
519
-
520
-	// 1er, 21st, etc.
521
-	$journum = $jour;
522
-
523
-	if ($jour == 0) {
524
-		$jour = '';
525
-		$njour = 0;
526
-	} else {
527
-		$njour = intval($jour);
528
-		if ($jourth = _T('date_jnum' . $jour)) {
529
-			$jour = $jourth;
530
-		}
531
-	}
532
-
533
-	$mois = intval($mois);
534
-	if ($mois > 0 and $mois < 13) {
535
-		/* Traiter le cas "abbr" pour les noms de mois */
536
-		$param = ((isset($options['param']) and $options['param'] === 'abbr') ? '_' . $options['param'] : '');
537
-		$nommois = _T('date_mois_' . $mois . $param);
538
-		if ($jour) {
539
-			$jourmois = _T('date_de_mois_' . $mois, ['j' => $jour, 'nommois' => $nommois]);
540
-		} else {
541
-			$jourmois = $nommois;
542
-		}
543
-	} else {
544
-		$nommois = '';
545
-		$jourmois = '';
546
-	}
547
-
548
-	if ($annee < 0) {
549
-		$annee = -$annee . ' ' . _T('date_avant_jc');
550
-		$avjc = true;
551
-	} else {
552
-		$avjc = false;
553
-	}
554
-
555
-	switch ($vue) {
556
-		case 'saison':
557
-		case 'saison_annee':
558
-			$saison = '';
559
-			if ($mois > 0) {
560
-				$saison = ($options['param'] == 'sud') ? 3 : 1;
561
-				if (($mois == 3 and $jour >= 21) or $mois > 3) {
562
-					$saison = ($options['param'] == 'sud') ? 4 : 2;
563
-				}
564
-				if (($mois == 6 and $jour >= 21) or $mois > 6) {
565
-					$saison = ($options['param'] == 'sud') ? 1 : 3;
566
-				}
567
-				if (($mois == 9 and $jour >= 21) or $mois > 9) {
568
-					$saison = ($options['param'] == 'sud') ? 2 : 4;
569
-				}
570
-				if (($mois == 12 and $jour >= 21) or $mois > 12) {
571
-					$saison = ($options['param'] == 'sud') ? 3 : 1;
572
-				}
573
-			}
574
-			if ($vue == 'saison') {
575
-				return $saison ? _T('date_saison_' . $saison) : '';
576
-			} else {
577
-				return $saison ? trim(_T(
578
-					'date_fmt_saison_annee',
579
-					['saison' => _T('date_saison_' . $saison), 'annee' => $annee]
580
-				)) : '';
581
-			}
582
-
583
-		case 'court':
584
-			if ($avjc) {
585
-				return $annee;
586
-			}
587
-			$a = ((isset($options['annee_courante']) and $options['annee_courante']) ? $options['annee_courante'] : date('Y'));
588
-			if ($annee < ($a - 100) or $annee > ($a + 100)) {
589
-				return $annee;
590
-			}
591
-			if ($annee != $a) {
592
-				return _T(
593
-					'date_fmt_mois_annee',
594
-					['mois' => $mois, 'nommois' => spip_ucfirst($nommois), 'annee' => $annee]
595
-				);
596
-			}
597
-
598
-			return _T(
599
-				'date_fmt_jour_mois',
600
-				['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
601
-			);
602
-
603
-		case 'jourcourt':
604
-			if ($avjc) {
605
-				return $annee;
606
-			}
607
-			$a = ((isset($options['annee_courante']) and $options['annee_courante']) ? $options['annee_courante'] : date('Y'));
608
-			if ($annee < ($a - 100) or $annee > ($a + 100)) {
609
-				return $annee;
610
-			}
611
-			if ($annee != $a) {
612
-				return _T(
613
-					'date_fmt_jour_mois_annee',
614
-					['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
615
-				);
616
-			}
617
-
618
-			return _T(
619
-				'date_fmt_jour_mois',
620
-				['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
621
-			);
622
-
623
-		case 'entier':
624
-			if ($avjc) {
625
-				return $annee;
626
-			}
627
-			if ($jour) {
628
-				return _T(
629
-					'date_fmt_jour_mois_annee',
630
-					['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
631
-				);
632
-			} elseif ($mois) {
633
-				return trim(_T('date_fmt_mois_annee', ['mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]));
634
-			} else {
635
-				return $annee;
636
-			}
637
-
638
-		case 'nom_mois':
639
-			return $nommois;
640
-
641
-		case 'mois':
642
-			return sprintf('%02s', $mois);
643
-
644
-		case 'jour':
645
-			return $jour;
646
-
647
-		case 'journum':
648
-			return $journum;
649
-
650
-		case 'nom_jour':
651
-			if (!$mois or !$njour) {
652
-				return '';
653
-			}
654
-			$nom = mktime(1, 1, 1, $mois, $njour, $annee);
655
-			$nom = 1 + (int) date('w', $nom);
656
-			$param = ((isset($options['param']) and $options['param']) ? '_' . $options['param'] : '');
657
-
658
-			return _T('date_jour_' . $nom . $param);
659
-
660
-		case 'mois_annee':
661
-			if ($avjc) {
662
-				return $annee;
663
-			}
664
-
665
-			return trim(_T('date_fmt_mois_annee', ['mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]));
666
-
667
-		case 'annee':
668
-			return $annee;
669
-
670
-		// Cas d'une vue non definie : retomber sur le format
671
-		// de date propose par http://www.php.net/date
672
-		default:
673
-			[$annee, $mois, $jour, $heures, $minutes, $secondes] = $date_array;
674
-			if (!$time = mktime($heures, $minutes, $secondes, $mois, (int) $jour, $annee)) {
675
-				$time = strtotime($numdate);
676
-			}
677
-			return date($vue, $time);
678
-	}
511
+    if (is_string($options)) {
512
+        $options = ['param' => $options];
513
+    }
514
+    $date_array = recup_date($numdate, false);
515
+    if (!$date_array) {
516
+        return '';
517
+    }
518
+    [$annee, $mois, $jour, $heures, $minutes, $secondes] = $date_array;
519
+
520
+    // 1er, 21st, etc.
521
+    $journum = $jour;
522
+
523
+    if ($jour == 0) {
524
+        $jour = '';
525
+        $njour = 0;
526
+    } else {
527
+        $njour = intval($jour);
528
+        if ($jourth = _T('date_jnum' . $jour)) {
529
+            $jour = $jourth;
530
+        }
531
+    }
532
+
533
+    $mois = intval($mois);
534
+    if ($mois > 0 and $mois < 13) {
535
+        /* Traiter le cas "abbr" pour les noms de mois */
536
+        $param = ((isset($options['param']) and $options['param'] === 'abbr') ? '_' . $options['param'] : '');
537
+        $nommois = _T('date_mois_' . $mois . $param);
538
+        if ($jour) {
539
+            $jourmois = _T('date_de_mois_' . $mois, ['j' => $jour, 'nommois' => $nommois]);
540
+        } else {
541
+            $jourmois = $nommois;
542
+        }
543
+    } else {
544
+        $nommois = '';
545
+        $jourmois = '';
546
+    }
547
+
548
+    if ($annee < 0) {
549
+        $annee = -$annee . ' ' . _T('date_avant_jc');
550
+        $avjc = true;
551
+    } else {
552
+        $avjc = false;
553
+    }
554
+
555
+    switch ($vue) {
556
+        case 'saison':
557
+        case 'saison_annee':
558
+            $saison = '';
559
+            if ($mois > 0) {
560
+                $saison = ($options['param'] == 'sud') ? 3 : 1;
561
+                if (($mois == 3 and $jour >= 21) or $mois > 3) {
562
+                    $saison = ($options['param'] == 'sud') ? 4 : 2;
563
+                }
564
+                if (($mois == 6 and $jour >= 21) or $mois > 6) {
565
+                    $saison = ($options['param'] == 'sud') ? 1 : 3;
566
+                }
567
+                if (($mois == 9 and $jour >= 21) or $mois > 9) {
568
+                    $saison = ($options['param'] == 'sud') ? 2 : 4;
569
+                }
570
+                if (($mois == 12 and $jour >= 21) or $mois > 12) {
571
+                    $saison = ($options['param'] == 'sud') ? 3 : 1;
572
+                }
573
+            }
574
+            if ($vue == 'saison') {
575
+                return $saison ? _T('date_saison_' . $saison) : '';
576
+            } else {
577
+                return $saison ? trim(_T(
578
+                    'date_fmt_saison_annee',
579
+                    ['saison' => _T('date_saison_' . $saison), 'annee' => $annee]
580
+                )) : '';
581
+            }
582
+
583
+        case 'court':
584
+            if ($avjc) {
585
+                return $annee;
586
+            }
587
+            $a = ((isset($options['annee_courante']) and $options['annee_courante']) ? $options['annee_courante'] : date('Y'));
588
+            if ($annee < ($a - 100) or $annee > ($a + 100)) {
589
+                return $annee;
590
+            }
591
+            if ($annee != $a) {
592
+                return _T(
593
+                    'date_fmt_mois_annee',
594
+                    ['mois' => $mois, 'nommois' => spip_ucfirst($nommois), 'annee' => $annee]
595
+                );
596
+            }
597
+
598
+            return _T(
599
+                'date_fmt_jour_mois',
600
+                ['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
601
+            );
602
+
603
+        case 'jourcourt':
604
+            if ($avjc) {
605
+                return $annee;
606
+            }
607
+            $a = ((isset($options['annee_courante']) and $options['annee_courante']) ? $options['annee_courante'] : date('Y'));
608
+            if ($annee < ($a - 100) or $annee > ($a + 100)) {
609
+                return $annee;
610
+            }
611
+            if ($annee != $a) {
612
+                return _T(
613
+                    'date_fmt_jour_mois_annee',
614
+                    ['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
615
+                );
616
+            }
617
+
618
+            return _T(
619
+                'date_fmt_jour_mois',
620
+                ['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
621
+            );
622
+
623
+        case 'entier':
624
+            if ($avjc) {
625
+                return $annee;
626
+            }
627
+            if ($jour) {
628
+                return _T(
629
+                    'date_fmt_jour_mois_annee',
630
+                    ['jourmois' => $jourmois, 'jour' => $jour, 'mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]
631
+                );
632
+            } elseif ($mois) {
633
+                return trim(_T('date_fmt_mois_annee', ['mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]));
634
+            } else {
635
+                return $annee;
636
+            }
637
+
638
+        case 'nom_mois':
639
+            return $nommois;
640
+
641
+        case 'mois':
642
+            return sprintf('%02s', $mois);
643
+
644
+        case 'jour':
645
+            return $jour;
646
+
647
+        case 'journum':
648
+            return $journum;
649
+
650
+        case 'nom_jour':
651
+            if (!$mois or !$njour) {
652
+                return '';
653
+            }
654
+            $nom = mktime(1, 1, 1, $mois, $njour, $annee);
655
+            $nom = 1 + (int) date('w', $nom);
656
+            $param = ((isset($options['param']) and $options['param']) ? '_' . $options['param'] : '');
657
+
658
+            return _T('date_jour_' . $nom . $param);
659
+
660
+        case 'mois_annee':
661
+            if ($avjc) {
662
+                return $annee;
663
+            }
664
+
665
+            return trim(_T('date_fmt_mois_annee', ['mois' => $mois, 'nommois' => $nommois, 'annee' => $annee]));
666
+
667
+        case 'annee':
668
+            return $annee;
669
+
670
+        // Cas d'une vue non definie : retomber sur le format
671
+        // de date propose par http://www.php.net/date
672
+        default:
673
+            [$annee, $mois, $jour, $heures, $minutes, $secondes] = $date_array;
674
+            if (!$time = mktime($heures, $minutes, $secondes, $mois, (int) $jour, $annee)) {
675
+                $time = strtotime($numdate);
676
+            }
677
+            return date($vue, $time);
678
+    }
679 679
 }
680 680
 
681 681
 
@@ -702,11 +702,11 @@  discard block
 block discarded – undo
702 702
  *     Nom du jour
703 703
  **/
704 704
 function nom_jour($numdate, $forme = ''): string {
705
-	if (!($forme === 'abbr' or $forme === 'initiale')) {
706
-		$forme = '';
707
-	}
705
+    if (!($forme === 'abbr' or $forme === 'initiale')) {
706
+        $forme = '';
707
+    }
708 708
 
709
-	return affdate_base($numdate, 'nom_jour', ['param' => $forme]);
709
+    return affdate_base($numdate, 'nom_jour', ['param' => $forme]);
710 710
 }
711 711
 
712 712
 /**
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
  *     Numéro du jour
729 729
  **/
730 730
 function jour($numdate): string {
731
-	return affdate_base($numdate, 'jour');
731
+    return affdate_base($numdate, 'jour');
732 732
 }
733 733
 
734 734
 /**
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
  *     Numéro du jour
747 747
  **/
748 748
 function journum($numdate): string {
749
-	return affdate_base($numdate, 'journum');
749
+    return affdate_base($numdate, 'journum');
750 750
 }
751 751
 
752 752
 /**
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
  *     Numéro du mois (sur 2 chiffres)
765 765
  **/
766 766
 function mois($numdate): string {
767
-	return  affdate_base($numdate, 'mois');
767
+    return  affdate_base($numdate, 'mois');
768 768
 }
769 769
 
770 770
 /**
@@ -788,11 +788,11 @@  discard block
 block discarded – undo
788 788
  *     Nom du mois
789 789
  **/
790 790
 function nom_mois($numdate, $forme = ''): string {
791
-	if (!($forme === 'abbr')) {
792
-		$forme = '';
793
-	}
791
+    if (!($forme === 'abbr')) {
792
+        $forme = '';
793
+    }
794 794
 
795
-	return affdate_base($numdate, 'nom_mois', ['param' => $forme]);
795
+    return affdate_base($numdate, 'nom_mois', ['param' => $forme]);
796 796
 }
797 797
 
798 798
 /**
@@ -810,7 +810,7 @@  discard block
 block discarded – undo
810 810
  *     Année (sur 4 chiffres)
811 811
  **/
812 812
 function annee($numdate): string {
813
-	return affdate_base($numdate, 'annee');
813
+    return affdate_base($numdate, 'annee');
814 814
 }
815 815
 
816 816
 
@@ -840,11 +840,11 @@  discard block
 block discarded – undo
840 840
  *     La date formatée
841 841
  **/
842 842
 function saison($numdate, $hemisphere = 'nord'): string {
843
-	if ($hemisphere !== 'sud') {
844
-		$hemisphere = 'nord';
845
-	}
843
+    if ($hemisphere !== 'sud') {
844
+        $hemisphere = 'nord';
845
+    }
846 846
 
847
-	return affdate_base($numdate, 'saison', ['param' => $hemisphere]);
847
+    return affdate_base($numdate, 'saison', ['param' => $hemisphere]);
848 848
 }
849 849
 
850 850
 
@@ -873,11 +873,11 @@  discard block
 block discarded – undo
873 873
  *     La date formatée
874 874
  **/
875 875
 function saison_annee($numdate, $hemisphere = 'nord'): string {
876
-	if ($hemisphere !== 'sud') {
877
-		$hemisphere = 'nord';
878
-	}
876
+    if ($hemisphere !== 'sud') {
877
+        $hemisphere = 'nord';
878
+    }
879 879
 
880
-	return affdate_base($numdate, 'saison_annee', ['param' => $hemisphere]);
880
+    return affdate_base($numdate, 'saison_annee', ['param' => $hemisphere]);
881 881
 }
882 882
 
883 883
 /**
@@ -905,7 +905,7 @@  discard block
 block discarded – undo
905 905
  *     La date formatée
906 906
  **/
907 907
 function affdate($numdate, $format = 'entier'): string {
908
-	return affdate_base($numdate, $format);
908
+    return affdate_base($numdate, $format);
909 909
 }
910 910
 
911 911
 
@@ -932,7 +932,7 @@  discard block
 block discarded – undo
932 932
  *     La date formatée
933 933
  **/
934 934
 function affdate_court($numdate, $annee_courante = null): string {
935
-	return affdate_base($numdate, 'court', ['annee_courante' => $annee_courante]);
935
+    return affdate_base($numdate, 'court', ['annee_courante' => $annee_courante]);
936 936
 }
937 937
 
938 938
 
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
  *     La date formatée
960 960
  **/
961 961
 function affdate_jourcourt($numdate, $annee_courante = null): string {
962
-	return affdate_base($numdate, 'jourcourt', ['annee_courante' => $annee_courante]);
962
+    return affdate_base($numdate, 'jourcourt', ['annee_courante' => $annee_courante]);
963 963
 }
964 964
 
965 965
 /**
@@ -977,7 +977,7 @@  discard block
 block discarded – undo
977 977
  *     La date formatée
978 978
  **/
979 979
 function affdate_mois_annee($numdate): string {
980
-	return affdate_base($numdate, 'mois_annee');
980
+    return affdate_base($numdate, 'mois_annee');
981 981
 }
982 982
 
983 983
 /**
@@ -995,16 +995,16 @@  discard block
 block discarded – undo
995 995
  *     La date formatée, sinon ''
996 996
  **/
997 997
 function affdate_heure($numdate): string {
998
-	$date_array = recup_date($numdate);
999
-	if (!$date_array) {
1000
-		return '';
1001
-	}
1002
-	[$annee, $mois, $jour, $heures, $minutes, $sec] = $date_array;
1003
-
1004
-	return _T('date_fmt_jour_heure', [
1005
-		'jour' => affdate($numdate),
1006
-		'heure' => _T('date_fmt_heures_minutes', ['h' => $heures, 'm' => $minutes])
1007
-	]);
998
+    $date_array = recup_date($numdate);
999
+    if (!$date_array) {
1000
+        return '';
1001
+    }
1002
+    [$annee, $mois, $jour, $heures, $minutes, $sec] = $date_array;
1003
+
1004
+    return _T('date_fmt_jour_heure', [
1005
+        'jour' => affdate($numdate),
1006
+        'heure' => _T('date_fmt_heures_minutes', ['h' => $heures, 'm' => $minutes])
1007
+    ]);
1008 1008
 }
1009 1009
 
1010 1010
 /**
@@ -1036,117 +1036,117 @@  discard block
 block discarded – undo
1036 1036
  *     texte de la date
1037 1037
  */
1038 1038
 function affdate_debut_fin($date_debut, $date_fin, $horaire = 'oui', $forme = ''): string {
1039
-	$abbr = $jour = '';
1040
-	$affdate = 'affdate_jourcourt';
1041
-	if (strpos($forme, 'abbr') !== false) {
1042
-		$abbr = 'abbr';
1043
-	}
1044
-	if (strpos($forme, 'annee') !== false) {
1045
-		$affdate = 'affdate';
1046
-	}
1047
-	if (strpos($forme, 'jour') !== false) {
1048
-		$jour = 'jour';
1049
-	}
1050
-
1051
-	$dtstart = $dtend = $dtabbr = '';
1052
-	if (strpos($forme, 'hcal') !== false) {
1053
-		$dtstart = "<abbr class='dtstart' title='" . date_iso($date_debut) . "'>";
1054
-		$dtend = "<abbr class='dtend' title='" . date_iso($date_fin) . "'>";
1055
-		$dtabbr = '</abbr>';
1056
-	}
1057
-
1058
-	$date_debut = strtotime($date_debut);
1059
-	$date_fin = strtotime($date_fin);
1060
-	$d = date('Y-m-d', $date_debut);
1061
-	$f = date('Y-m-d', $date_fin);
1062
-	$h = ($horaire === 'oui' or $horaire === true);
1063
-	$hd = _T('date_fmt_heures_minutes_court', ['h' => date('H', $date_debut), 'm' => date('i', $date_debut)]);
1064
-	$hf = _T('date_fmt_heures_minutes_court', ['h' => date('H', $date_fin), 'm' => date('i', $date_fin)]);
1065
-
1066
-	if ($d == $f) { // meme jour
1067
-		$nomjour = nom_jour($d, $abbr);
1068
-		$s = $affdate($d);
1069
-		$s = _T('date_fmt_jour', ['nomjour' => $nomjour, 'jour' => $s]);
1070
-		if ($h) {
1071
-			if ($hd == $hf) {
1072
-				// Lundi 20 fevrier a 18h25
1073
-				$s = spip_ucfirst(_T('date_fmt_jour_heure', ['jour' => $s, 'heure' => $hd]));
1074
-				$s = "$dtstart$s$dtabbr";
1075
-			} else {
1076
-				// Le <abbr...>lundi 20 fevrier de 18h00</abbr> a <abbr...>20h00</abbr>
1077
-				if ($dtabbr && $dtstart && $dtend) {
1078
-					$s = _T(
1079
-						'date_fmt_jour_heure_debut_fin_abbr',
1080
-						[
1081
-						'jour' => spip_ucfirst($s),
1082
-						'heure_debut' => $hd,
1083
-						'heure_fin' => $hf,
1084
-						'dtstart' => $dtstart,
1085
-						'dtend' => $dtend,
1086
-						'dtabbr' => $dtabbr
1087
-						],
1088
-						[
1089
-							'sanitize' => false
1090
-						]
1091
-					);
1092
-				} // Le lundi 20 fevrier de 18h00 a 20h00
1093
-				else {
1094
-					$s = spip_ucfirst(_T(
1095
-						'date_fmt_jour_heure_debut_fin',
1096
-						['jour' => $s, 'heure_debut' => $hd, 'heure_fin' => $hf]
1097
-					));
1098
-				}
1099
-			}
1100
-		} else {
1101
-			if ($dtabbr && $dtstart) {
1102
-				$s = $dtstart . spip_ucfirst($s) . $dtabbr;
1103
-			} else {
1104
-				$s = spip_ucfirst($s);
1105
-			}
1106
-		}
1107
-	} else {
1108
-		if ((date('Y-m', $date_debut)) == date('Y-m', $date_fin)) { // meme annee et mois, jours differents
1109
-			if (!$h) {
1110
-				$date_debut = jour($d);
1111
-			} else {
1112
-				$date_debut = affdate_jourcourt($d, date('Y', $date_fin));
1113
-			}
1114
-			$date_fin = $affdate($f);
1115
-			if ($jour) {
1116
-				$nomjour_debut = nom_jour($d, $abbr);
1117
-				$date_debut = _T('date_fmt_jour', ['nomjour' => $nomjour_debut, 'jour' => $date_debut]);
1118
-				$nomjour_fin = nom_jour($f, $abbr);
1119
-				$date_fin = _T('date_fmt_jour', ['nomjour' => $nomjour_fin, 'jour' => $date_fin]);
1120
-			}
1121
-			if ($h) {
1122
-				$date_debut = _T('date_fmt_jour_heure', ['jour' => $date_debut, 'heure' => $hd]);
1123
-				$date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1124
-			}
1125
-			$date_debut = $dtstart . $date_debut . $dtabbr;
1126
-			$date_fin = $dtend . $date_fin . $dtabbr;
1127
-
1128
-			$s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1129
-		} else {
1130
-			$date_debut = affdate_jourcourt($d, date('Y', $date_fin));
1131
-			$date_fin = $affdate($f);
1132
-			if ($jour) {
1133
-				$nomjour_debut = nom_jour($d, $abbr);
1134
-				$date_debut = _T('date_fmt_jour', ['nomjour' => $nomjour_debut, 'jour' => $date_debut]);
1135
-				$nomjour_fin = nom_jour($f, $abbr);
1136
-				$date_fin = _T('date_fmt_jour', ['nomjour' => $nomjour_fin, 'jour' => $date_fin]);
1137
-			}
1138
-			if ($h) {
1139
-				$date_debut = _T('date_fmt_jour_heure', ['jour' => $date_debut, 'heure' => $hd]);
1140
-				$date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1141
-			}
1142
-
1143
-			$date_debut = $dtstart . $date_debut . $dtabbr;
1144
-			$date_fin = $dtend . $date_fin . $dtabbr;
1145
-			$s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1146
-		}
1147
-	}
1148
-
1149
-	return $s;
1039
+    $abbr = $jour = '';
1040
+    $affdate = 'affdate_jourcourt';
1041
+    if (strpos($forme, 'abbr') !== false) {
1042
+        $abbr = 'abbr';
1043
+    }
1044
+    if (strpos($forme, 'annee') !== false) {
1045
+        $affdate = 'affdate';
1046
+    }
1047
+    if (strpos($forme, 'jour') !== false) {
1048
+        $jour = 'jour';
1049
+    }
1050
+
1051
+    $dtstart = $dtend = $dtabbr = '';
1052
+    if (strpos($forme, 'hcal') !== false) {
1053
+        $dtstart = "<abbr class='dtstart' title='" . date_iso($date_debut) . "'>";
1054
+        $dtend = "<abbr class='dtend' title='" . date_iso($date_fin) . "'>";
1055
+        $dtabbr = '</abbr>';
1056
+    }
1057
+
1058
+    $date_debut = strtotime($date_debut);
1059
+    $date_fin = strtotime($date_fin);
1060
+    $d = date('Y-m-d', $date_debut);
1061
+    $f = date('Y-m-d', $date_fin);
1062
+    $h = ($horaire === 'oui' or $horaire === true);
1063
+    $hd = _T('date_fmt_heures_minutes_court', ['h' => date('H', $date_debut), 'm' => date('i', $date_debut)]);
1064
+    $hf = _T('date_fmt_heures_minutes_court', ['h' => date('H', $date_fin), 'm' => date('i', $date_fin)]);
1065
+
1066
+    if ($d == $f) { // meme jour
1067
+        $nomjour = nom_jour($d, $abbr);
1068
+        $s = $affdate($d);
1069
+        $s = _T('date_fmt_jour', ['nomjour' => $nomjour, 'jour' => $s]);
1070
+        if ($h) {
1071
+            if ($hd == $hf) {
1072
+                // Lundi 20 fevrier a 18h25
1073
+                $s = spip_ucfirst(_T('date_fmt_jour_heure', ['jour' => $s, 'heure' => $hd]));
1074
+                $s = "$dtstart$s$dtabbr";
1075
+            } else {
1076
+                // Le <abbr...>lundi 20 fevrier de 18h00</abbr> a <abbr...>20h00</abbr>
1077
+                if ($dtabbr && $dtstart && $dtend) {
1078
+                    $s = _T(
1079
+                        'date_fmt_jour_heure_debut_fin_abbr',
1080
+                        [
1081
+                        'jour' => spip_ucfirst($s),
1082
+                        'heure_debut' => $hd,
1083
+                        'heure_fin' => $hf,
1084
+                        'dtstart' => $dtstart,
1085
+                        'dtend' => $dtend,
1086
+                        'dtabbr' => $dtabbr
1087
+                        ],
1088
+                        [
1089
+                            'sanitize' => false
1090
+                        ]
1091
+                    );
1092
+                } // Le lundi 20 fevrier de 18h00 a 20h00
1093
+                else {
1094
+                    $s = spip_ucfirst(_T(
1095
+                        'date_fmt_jour_heure_debut_fin',
1096
+                        ['jour' => $s, 'heure_debut' => $hd, 'heure_fin' => $hf]
1097
+                    ));
1098
+                }
1099
+            }
1100
+        } else {
1101
+            if ($dtabbr && $dtstart) {
1102
+                $s = $dtstart . spip_ucfirst($s) . $dtabbr;
1103
+            } else {
1104
+                $s = spip_ucfirst($s);
1105
+            }
1106
+        }
1107
+    } else {
1108
+        if ((date('Y-m', $date_debut)) == date('Y-m', $date_fin)) { // meme annee et mois, jours differents
1109
+            if (!$h) {
1110
+                $date_debut = jour($d);
1111
+            } else {
1112
+                $date_debut = affdate_jourcourt($d, date('Y', $date_fin));
1113
+            }
1114
+            $date_fin = $affdate($f);
1115
+            if ($jour) {
1116
+                $nomjour_debut = nom_jour($d, $abbr);
1117
+                $date_debut = _T('date_fmt_jour', ['nomjour' => $nomjour_debut, 'jour' => $date_debut]);
1118
+                $nomjour_fin = nom_jour($f, $abbr);
1119
+                $date_fin = _T('date_fmt_jour', ['nomjour' => $nomjour_fin, 'jour' => $date_fin]);
1120
+            }
1121
+            if ($h) {
1122
+                $date_debut = _T('date_fmt_jour_heure', ['jour' => $date_debut, 'heure' => $hd]);
1123
+                $date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1124
+            }
1125
+            $date_debut = $dtstart . $date_debut . $dtabbr;
1126
+            $date_fin = $dtend . $date_fin . $dtabbr;
1127
+
1128
+            $s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1129
+        } else {
1130
+            $date_debut = affdate_jourcourt($d, date('Y', $date_fin));
1131
+            $date_fin = $affdate($f);
1132
+            if ($jour) {
1133
+                $nomjour_debut = nom_jour($d, $abbr);
1134
+                $date_debut = _T('date_fmt_jour', ['nomjour' => $nomjour_debut, 'jour' => $date_debut]);
1135
+                $nomjour_fin = nom_jour($f, $abbr);
1136
+                $date_fin = _T('date_fmt_jour', ['nomjour' => $nomjour_fin, 'jour' => $date_fin]);
1137
+            }
1138
+            if ($h) {
1139
+                $date_debut = _T('date_fmt_jour_heure', ['jour' => $date_debut, 'heure' => $hd]);
1140
+                $date_fin = _T('date_fmt_jour_heure', ['jour' => $date_fin, 'heure' => $hf]);
1141
+            }
1142
+
1143
+            $date_debut = $dtstart . $date_debut . $dtabbr;
1144
+            $date_fin = $dtend . $date_fin . $dtabbr;
1145
+            $s = _T('date_fmt_periode', ['date_debut' => $date_debut, 'date_fin' => $date_fin]);
1146
+        }
1147
+    }
1148
+
1149
+    return $s;
1150 1150
 }
1151 1151
 
1152 1152
 /**
@@ -1167,10 +1167,10 @@  discard block
 block discarded – undo
1167 1167
  *     Date au format ical
1168 1168
  **/
1169 1169
 function date_ical($date, $addminutes = 0): string {
1170
-	[$heures, $minutes, $secondes] = recup_heure($date);
1171
-	[$annee, $mois, $jour] = recup_date($date);
1170
+    [$heures, $minutes, $secondes] = recup_heure($date);
1171
+    [$annee, $mois, $jour] = recup_date($date);
1172 1172
 
1173
-	return gmdate('Ymd\THis\Z', mktime($heures, $minutes + $addminutes, $secondes, $mois, $jour, $annee));
1173
+    return gmdate('Ymd\THis\Z', mktime($heures, $minutes + $addminutes, $secondes, $mois, $jour, $annee));
1174 1174
 }
1175 1175
 
1176 1176
 
@@ -1194,11 +1194,11 @@  discard block
 block discarded – undo
1194 1194
  *     La date formatée
1195 1195
  **/
1196 1196
 function date_iso($date_heure): string {
1197
-	[$annee, $mois, $jour] = recup_date($date_heure);
1198
-	[$heures, $minutes, $secondes] = recup_heure($date_heure);
1199
-	$time = @mktime($heures, $minutes, $secondes, $mois, $jour, $annee);
1197
+    [$annee, $mois, $jour] = recup_date($date_heure);
1198
+    [$heures, $minutes, $secondes] = recup_heure($date_heure);
1199
+    $time = @mktime($heures, $minutes, $secondes, $mois, $jour, $annee);
1200 1200
 
1201
-	return gmdate('Y-m-d\TH:i:s\Z', $time);
1201
+    return gmdate('Y-m-d\TH:i:s\Z', $time);
1202 1202
 }
1203 1203
 
1204 1204
 /**
@@ -1221,11 +1221,11 @@  discard block
 block discarded – undo
1221 1221
  *     La date formatée
1222 1222
  **/
1223 1223
 function date_822($date_heure): string {
1224
-	[$annee, $mois, $jour] = recup_date($date_heure);
1225
-	[$heures, $minutes, $secondes] = recup_heure($date_heure);
1226
-	$time = mktime($heures, $minutes, $secondes, $mois, $jour, $annee);
1224
+    [$annee, $mois, $jour] = recup_date($date_heure);
1225
+    [$heures, $minutes, $secondes] = recup_heure($date_heure);
1226
+    $time = mktime($heures, $minutes, $secondes, $mois, $jour, $annee);
1227 1227
 
1228
-	return date('r', $time);
1228
+    return date('r', $time);
1229 1229
 }
1230 1230
 
1231 1231
 /**
@@ -1241,11 +1241,11 @@  discard block
 block discarded – undo
1241 1241
  *     Date au format `Ymd`
1242 1242
  **/
1243 1243
 function date_anneemoisjour($d): string {
1244
-	if (!$d) {
1245
-		$d = date('Y-m-d');
1246
-	}
1244
+    if (!$d) {
1245
+        $d = date('Y-m-d');
1246
+    }
1247 1247
 
1248
-	return substr($d, 0, 4) . substr($d, 5, 2) . substr($d, 8, 2);
1248
+    return substr($d, 0, 4) . substr($d, 5, 2) . substr($d, 8, 2);
1249 1249
 }
1250 1250
 
1251 1251
 /**
@@ -1261,11 +1261,11 @@  discard block
 block discarded – undo
1261 1261
  *     Date au format `Ym`
1262 1262
  **/
1263 1263
 function date_anneemois($d): string {
1264
-	if (!$d) {
1265
-		$d = date('Y-m-d');
1266
-	}
1264
+    if (!$d) {
1265
+        $d = date('Y-m-d');
1266
+    }
1267 1267
 
1268
-	return substr($d, 0, 4) . substr($d, 5, 2);
1268
+    return substr($d, 0, 4) . substr($d, 5, 2);
1269 1269
 }
1270 1270
 
1271 1271
 /**
@@ -1281,13 +1281,13 @@  discard block
 block discarded – undo
1281 1281
  *     Date au lundi de la même semaine au format `Ymd`
1282 1282
  **/
1283 1283
 function date_debut_semaine($annee, $mois, $jour): string {
1284
-	$w_day = date('w', mktime(0, 0, 0, $mois, $jour, $annee));
1285
-	if ($w_day == 0) {
1286
-		$w_day = 7;
1287
-	} // Gaffe: le dimanche est zero
1288
-	$debut = $jour - $w_day + 1;
1284
+    $w_day = date('w', mktime(0, 0, 0, $mois, $jour, $annee));
1285
+    if ($w_day == 0) {
1286
+        $w_day = 7;
1287
+    } // Gaffe: le dimanche est zero
1288
+    $debut = $jour - $w_day + 1;
1289 1289
 
1290
-	return date('Ymd', mktime(0, 0, 0, $mois, $debut, $annee));
1290
+    return date('Ymd', mktime(0, 0, 0, $mois, $debut, $annee));
1291 1291
 }
1292 1292
 
1293 1293
 /**
@@ -1303,11 +1303,11 @@  discard block
 block discarded – undo
1303 1303
  *     Date au dimanche de la même semaine au format `Ymd`
1304 1304
  **/
1305 1305
 function date_fin_semaine($annee, $mois, $jour): string {
1306
-	$w_day = date('w', mktime(0, 0, 0, $mois, $jour, $annee));
1307
-	if ($w_day == 0) {
1308
-		$w_day = 7;
1309
-	} // Gaffe: le dimanche est zero
1310
-	$debut = $jour - $w_day + 1;
1306
+    $w_day = date('w', mktime(0, 0, 0, $mois, $jour, $annee));
1307
+    if ($w_day == 0) {
1308
+        $w_day = 7;
1309
+    } // Gaffe: le dimanche est zero
1310
+    $debut = $jour - $w_day + 1;
1311 1311
 
1312
-	return date('Ymd', mktime(0, 0, 0, $mois, $debut + 6, $annee));
1312
+    return date('Ymd', mktime(0, 0, 0, $mois, $debut + 6, $annee));
1313 1313
 }
Please login to merge, or discard this patch.