Completed
Push — master ( 0288ab...6b3284 )
by cam
02:21
created
ecrire/src/Chiffrer/SpipCles.php 1 patch
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -14,171 +14,171 @@
 block discarded – undo
14 14
 
15 15
 /** Gestion des clés d’authentification / chiffrement de SPIP */
16 16
 final class SpipCles {
17
-	private static array $instances = [];
18
-
19
-	private string $file = _DIR_ETC . 'cles.php';
20
-	private Cles $cles;
21
-
22
-	public static function instance(string $file = ''): self {
23
-		if (empty(self::$instances[$file])) {
24
-			self::$instances[$file] = new self($file);
25
-		}
26
-		return self::$instances[$file];
27
-	}
28
-
29
-	/**
30
-	 * Retourne le secret du site (shorthand)
31
-	 * @uses self::getSecretSite()
32
-	 */
33
-	public static function secret_du_site(): ?string {
34
-		return (self::instance())->getSecretSite();
35
-	}
36
-
37
-	private function __construct(string $file = '') {
38
-		if ($file) {
39
-			$this->file = $file;
40
-		}
41
-		$this->cles = new Cles($this->read());
42
-	}
43
-
44
-	/**
45
-	 * Renvoyer le secret du site
46
-	 *
47
-	 * Le secret du site doit rester aussi secret que possible, et est eternel
48
-	 * On ne doit pas l'exporter
49
-	 *
50
-	 * Le secret est partagé entre une clé disque et une clé bdd
51
-	 *
52
-	 * @return string
53
-	 */
54
-	public function getSecretSite(bool $autoInit = true): ?string {
55
-		$key = $this->getKey('secret_du_site', $autoInit);
56
-		$meta = $this->getMetaKey('secret_du_site', $autoInit);
57
-		// conserve la même longeur.
58
-		return $key ^ $meta;
59
-	}
60
-
61
-	/** Renvoyer le secret des authentifications */
62
-	public function getSecretAuth(bool $autoInit = false): ?string {
63
-		return $this->getKey('secret_des_auth', $autoInit);
64
-	}
65
-	public function save(): bool {
66
-		return ecrire_fichier_securise($this->file, $this->cles->toJson());
67
-	}
68
-
69
-	/**
70
-	 * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
71
-	 *
72
-	 * @param string $withKey Clé de chiffrage de la sauvegarde
73
-	 * @return string Contenu de la sauvegarde chiffrée générée
74
-	 */
75
-	public function backup(
76
-		#[\SensitiveParameter]
77
-		string $withKey
78
-	): string {
79
-		if (count($this->cles)) {
80
-			return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
81
-		}
82
-		return '';
83
-	}
84
-
85
-	/**
86
-	 * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
87
-	 * (si la sauvegarde est bien valide)
88
-	 *
89
-	 * @param string $backup Sauvegarde chiffrée (générée par backup())
90
-	 * @param int $id_auteur
91
-	 * @param string $pass
92
-	 * @return void
93
-	 */
94
-	public function restore(
95
-		string $backup,
96
-		#[\SensitiveParameter]
97
-		string $password_clair,
98
-		#[\SensitiveParameter]
99
-		string $password_hash,
100
-		int $id_auteur
101
-	): bool {
102
-		if (empty($backup)) {
103
-			return false;
104
-		}
105
-
106
-		$sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
107
-		$json = json_decode($sauvegarde, true);
108
-		if (!$json) {
109
-			return false;
110
-		}
111
-
112
-		// cela semble une sauvegarde valide
113
-		$cles_potentielles = array_map('base64_decode', $json);
114
-
115
-		// il faut faire une double verif sur secret_des_auth
116
-		// pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
117
-		// et par extension tous les passwords
118
-		if (!empty($cles_potentielles['secret_des_auth'])) {
119
-			if (!Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])) {
120
-				spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
121
-				unset($cles_potentielles['secret_des_auth']);
122
-			}
123
-		}
124
-
125
-		// on merge les cles pour recuperer les cles manquantes
126
-		$restauration = false;
127
-		foreach ($cles_potentielles as $name => $key) {
128
-			if (!$this->cles->has($name)) {
129
-				$this->cles->set($name, $key);
130
-				spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
131
-				$restauration = true;
132
-			}
133
-		}
134
-		return $restauration;
135
-	}
136
-
137
-	private function getKey(string $name, bool $autoInit): ?string {
138
-		if ($this->cles->has($name)) {
139
-			return $this->cles->get($name);
140
-		}
141
-		if ($autoInit) {
142
-			$this->cles->generate($name);
143
-			// si l'ecriture de fichier a bien marche on peut utiliser la cle
144
-			if ($this->save()) {
145
-				return $this->cles->get($name);
146
-			}
147
-			// sinon loger et annule la cle generee car il ne faut pas l'utiliser
148
-			spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
149
-			$this->cles->delete($name);
150
-		}
151
-		return null;
152
-	}
153
-
154
-	private function getMetaKey(string $name, bool $autoInit = true): ?string {
155
-		if (!isset($GLOBALS['meta'][$name])) {
156
-			include_spip('base/abstract_sql');
157
-			$GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
158
-		}
159
-		$key = base64_decode($GLOBALS['meta'][$name] ?? '');
160
-		if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
161
-			return $key;
162
-		}
163
-		if (!$autoInit) {
164
-			return null;
165
-		}
166
-		$key = Chiffrement::keygen();
167
-		ecrire_meta($name, base64_encode($key), 'non');
168
-		lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
169
-
170
-		return $key;
171
-	}
172
-
173
-	private function read(): array {
174
-		lire_fichier_securise($this->file, $json);
175
-		if (
176
-			$json
177
-			and $json = \json_decode($json, true)
178
-			and is_array($json)
179
-		) {
180
-			return array_map('base64_decode', $json);
181
-		}
182
-		return [];
183
-	}
17
+    private static array $instances = [];
18
+
19
+    private string $file = _DIR_ETC . 'cles.php';
20
+    private Cles $cles;
21
+
22
+    public static function instance(string $file = ''): self {
23
+        if (empty(self::$instances[$file])) {
24
+            self::$instances[$file] = new self($file);
25
+        }
26
+        return self::$instances[$file];
27
+    }
28
+
29
+    /**
30
+     * Retourne le secret du site (shorthand)
31
+     * @uses self::getSecretSite()
32
+     */
33
+    public static function secret_du_site(): ?string {
34
+        return (self::instance())->getSecretSite();
35
+    }
36
+
37
+    private function __construct(string $file = '') {
38
+        if ($file) {
39
+            $this->file = $file;
40
+        }
41
+        $this->cles = new Cles($this->read());
42
+    }
43
+
44
+    /**
45
+     * Renvoyer le secret du site
46
+     *
47
+     * Le secret du site doit rester aussi secret que possible, et est eternel
48
+     * On ne doit pas l'exporter
49
+     *
50
+     * Le secret est partagé entre une clé disque et une clé bdd
51
+     *
52
+     * @return string
53
+     */
54
+    public function getSecretSite(bool $autoInit = true): ?string {
55
+        $key = $this->getKey('secret_du_site', $autoInit);
56
+        $meta = $this->getMetaKey('secret_du_site', $autoInit);
57
+        // conserve la même longeur.
58
+        return $key ^ $meta;
59
+    }
60
+
61
+    /** Renvoyer le secret des authentifications */
62
+    public function getSecretAuth(bool $autoInit = false): ?string {
63
+        return $this->getKey('secret_des_auth', $autoInit);
64
+    }
65
+    public function save(): bool {
66
+        return ecrire_fichier_securise($this->file, $this->cles->toJson());
67
+    }
68
+
69
+    /**
70
+     * Fournir une sauvegarde chiffree des cles (a l'aide d'une autre clé, comme le pass d'un auteur)
71
+     *
72
+     * @param string $withKey Clé de chiffrage de la sauvegarde
73
+     * @return string Contenu de la sauvegarde chiffrée générée
74
+     */
75
+    public function backup(
76
+        #[\SensitiveParameter]
77
+        string $withKey
78
+    ): string {
79
+        if (count($this->cles)) {
80
+            return Chiffrement::chiffrer($this->cles->toJson(), $withKey);
81
+        }
82
+        return '';
83
+    }
84
+
85
+    /**
86
+     * Restaurer les cles manquantes depuis une sauvegarde chiffree des cles
87
+     * (si la sauvegarde est bien valide)
88
+     *
89
+     * @param string $backup Sauvegarde chiffrée (générée par backup())
90
+     * @param int $id_auteur
91
+     * @param string $pass
92
+     * @return void
93
+     */
94
+    public function restore(
95
+        string $backup,
96
+        #[\SensitiveParameter]
97
+        string $password_clair,
98
+        #[\SensitiveParameter]
99
+        string $password_hash,
100
+        int $id_auteur
101
+    ): bool {
102
+        if (empty($backup)) {
103
+            return false;
104
+        }
105
+
106
+        $sauvegarde = Chiffrement::dechiffrer($backup, $password_clair);
107
+        $json = json_decode($sauvegarde, true);
108
+        if (!$json) {
109
+            return false;
110
+        }
111
+
112
+        // cela semble une sauvegarde valide
113
+        $cles_potentielles = array_map('base64_decode', $json);
114
+
115
+        // il faut faire une double verif sur secret_des_auth
116
+        // pour s'assurer qu'elle permet bien de decrypter le pass de l'auteur qui fournit la sauvegarde
117
+        // et par extension tous les passwords
118
+        if (!empty($cles_potentielles['secret_des_auth'])) {
119
+            if (!Password::verifier($password_clair, $password_hash, $cles_potentielles['secret_des_auth'])) {
120
+                spip_log("Restauration de la cle `secret_des_auth` par id_auteur $id_auteur erronnee, on ignore", 'chiffrer' . _LOG_INFO_IMPORTANTE);
121
+                unset($cles_potentielles['secret_des_auth']);
122
+            }
123
+        }
124
+
125
+        // on merge les cles pour recuperer les cles manquantes
126
+        $restauration = false;
127
+        foreach ($cles_potentielles as $name => $key) {
128
+            if (!$this->cles->has($name)) {
129
+                $this->cles->set($name, $key);
130
+                spip_log("Restauration de la cle $name par id_auteur $id_auteur", 'chiffrer' . _LOG_INFO_IMPORTANTE);
131
+                $restauration = true;
132
+            }
133
+        }
134
+        return $restauration;
135
+    }
136
+
137
+    private function getKey(string $name, bool $autoInit): ?string {
138
+        if ($this->cles->has($name)) {
139
+            return $this->cles->get($name);
140
+        }
141
+        if ($autoInit) {
142
+            $this->cles->generate($name);
143
+            // si l'ecriture de fichier a bien marche on peut utiliser la cle
144
+            if ($this->save()) {
145
+                return $this->cles->get($name);
146
+            }
147
+            // sinon loger et annule la cle generee car il ne faut pas l'utiliser
148
+            spip_log('Echec ecriture du fichier cle ' . $this->file . " ; impossible de generer une cle $name", 'chiffrer' . _LOG_ERREUR);
149
+            $this->cles->delete($name);
150
+        }
151
+        return null;
152
+    }
153
+
154
+    private function getMetaKey(string $name, bool $autoInit = true): ?string {
155
+        if (!isset($GLOBALS['meta'][$name])) {
156
+            include_spip('base/abstract_sql');
157
+            $GLOBALS['meta'][$name] = sql_getfetsel('valeur', 'spip_meta', 'nom = ' . sql_quote($name, '', 'string'));
158
+        }
159
+        $key = base64_decode($GLOBALS['meta'][$name] ?? '');
160
+        if (strlen($key) === \SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
161
+            return $key;
162
+        }
163
+        if (!$autoInit) {
164
+            return null;
165
+        }
166
+        $key = Chiffrement::keygen();
167
+        ecrire_meta($name, base64_encode($key), 'non');
168
+        lire_metas(); // au cas ou ecrire_meta() ne fonctionne pas
169
+
170
+        return $key;
171
+    }
172
+
173
+    private function read(): array {
174
+        lire_fichier_securise($this->file, $json);
175
+        if (
176
+            $json
177
+            and $json = \json_decode($json, true)
178
+            and is_array($json)
179
+        ) {
180
+            return array_map('base64_decode', $json);
181
+        }
182
+        return [];
183
+    }
184 184
 }
Please login to merge, or discard this patch.
prive/formulaires/configurer_preferences.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
  **/
22 22
 
23 23
 if (!defined('_ECRIRE_INC_VERSION')) {
24
-	return;
24
+    return;
25 25
 }
26 26
 
27 27
 /**
@@ -31,27 +31,27 @@  discard block
 block discarded – undo
31 31
  *     Environnement du formulaire
32 32
  **/
33 33
 function formulaires_configurer_preferences_charger_dist() {
34
-	// travailler sur des meta fraiches
35
-	include_spip('inc/meta');
36
-	lire_metas();
34
+    // travailler sur des meta fraiches
35
+    include_spip('inc/meta');
36
+    lire_metas();
37 37
 
38
-	$valeurs = [];
39
-	$valeurs['display_navigation'] = $GLOBALS['visiteur_session']['prefs']['display_navigation'] ?? 'navigation_avec_icones';
40
-	$valeurs['display'] = (isset($GLOBALS['visiteur_session']['prefs']['display']) and $GLOBALS['visiteur_session']['prefs']['display'] > 0) ? $GLOBALS['visiteur_session']['prefs']['display'] : 2;
41
-	$valeurs['couleur'] = (isset($GLOBALS['visiteur_session']['prefs']['couleur']) and $GLOBALS['visiteur_session']['prefs']['couleur'] > 0) ? $GLOBALS['visiteur_session']['prefs']['couleur'] : 1;
38
+    $valeurs = [];
39
+    $valeurs['display_navigation'] = $GLOBALS['visiteur_session']['prefs']['display_navigation'] ?? 'navigation_avec_icones';
40
+    $valeurs['display'] = (isset($GLOBALS['visiteur_session']['prefs']['display']) and $GLOBALS['visiteur_session']['prefs']['display'] > 0) ? $GLOBALS['visiteur_session']['prefs']['display'] : 2;
41
+    $valeurs['couleur'] = (isset($GLOBALS['visiteur_session']['prefs']['couleur']) and $GLOBALS['visiteur_session']['prefs']['couleur'] > 0) ? $GLOBALS['visiteur_session']['prefs']['couleur'] : 1;
42 42
 
43
-	$couleurs = charger_fonction('couleurs', 'inc');
44
-	$les_couleurs = $couleurs();
45
-	foreach ($les_couleurs as $k => $c) {
46
-		$valeurs['_couleurs_url'][$k] = generer_url_public('style_prive.css', 'ltr='
47
-			. $GLOBALS['spip_lang_left'] . '&'
48
-			. $couleurs($k));
49
-		$valeurs['couleurs'][$k] = $c;
50
-	}
43
+    $couleurs = charger_fonction('couleurs', 'inc');
44
+    $les_couleurs = $couleurs();
45
+    foreach ($les_couleurs as $k => $c) {
46
+        $valeurs['_couleurs_url'][$k] = generer_url_public('style_prive.css', 'ltr='
47
+            . $GLOBALS['spip_lang_left'] . '&'
48
+            . $couleurs($k));
49
+        $valeurs['couleurs'][$k] = $c;
50
+    }
51 51
 
52
-	$valeurs['imessage'] = $GLOBALS['visiteur_session']['imessage'];
52
+    $valeurs['imessage'] = $GLOBALS['visiteur_session']['imessage'];
53 53
 
54
-	return $valeurs;
54
+    return $valeurs;
55 55
 }
56 56
 
57 57
 /**
@@ -62,33 +62,33 @@  discard block
 block discarded – undo
62 62
  **/
63 63
 function formulaires_configurer_preferences_traiter_dist() {
64 64
 
65
-	if ($couleur = _request('couleur')) {
66
-		$couleurs = charger_fonction('couleurs', 'inc');
67
-		$les_couleurs = $couleurs([], true);
68
-		if (isset($les_couleurs[$couleur])) {
69
-			$GLOBALS['visiteur_session']['prefs']['couleur'] = $couleur;
70
-		}
71
-	}
72
-	if ($display = intval(_request('display'))) {
73
-		$GLOBALS['visiteur_session']['prefs']['display'] = $display;
74
-	}
75
-	if (
76
-		$display_navigation = _request('display_navigation')
77
-		and in_array($display_navigation, ['navigation_sans_icone', 'navigation_avec_icones'])
78
-	) {
79
-		$GLOBALS['visiteur_session']['prefs']['display_navigation'] = $display_navigation;
80
-	}
65
+    if ($couleur = _request('couleur')) {
66
+        $couleurs = charger_fonction('couleurs', 'inc');
67
+        $les_couleurs = $couleurs([], true);
68
+        if (isset($les_couleurs[$couleur])) {
69
+            $GLOBALS['visiteur_session']['prefs']['couleur'] = $couleur;
70
+        }
71
+    }
72
+    if ($display = intval(_request('display'))) {
73
+        $GLOBALS['visiteur_session']['prefs']['display'] = $display;
74
+    }
75
+    if (
76
+        $display_navigation = _request('display_navigation')
77
+        and in_array($display_navigation, ['navigation_sans_icone', 'navigation_avec_icones'])
78
+    ) {
79
+        $GLOBALS['visiteur_session']['prefs']['display_navigation'] = $display_navigation;
80
+    }
81 81
 
82
-	if (intval($GLOBALS['visiteur_session']['id_auteur'])) {
83
-		include_spip('action/editer_auteur');
84
-		$c = ['prefs' => serialize($GLOBALS['visiteur_session']['prefs'])];
82
+    if (intval($GLOBALS['visiteur_session']['id_auteur'])) {
83
+        include_spip('action/editer_auteur');
84
+        $c = ['prefs' => serialize($GLOBALS['visiteur_session']['prefs'])];
85 85
 
86
-		if ($imessage = _request('imessage') and in_array($imessage, ['oui', 'non'])) {
87
-			$c['imessage'] = $imessage;
88
-		}
86
+        if ($imessage = _request('imessage') and in_array($imessage, ['oui', 'non'])) {
87
+            $c['imessage'] = $imessage;
88
+        }
89 89
 
90
-		auteur_modifier($GLOBALS['visiteur_session']['id_auteur'], $c);
91
-	}
90
+        auteur_modifier($GLOBALS['visiteur_session']['id_auteur'], $c);
91
+    }
92 92
 
93
-	return ['message_ok' => _T('config_info_enregistree'), 'editable' => true];
93
+    return ['message_ok' => _T('config_info_enregistree'), 'editable' => true];
94 94
 }
Please login to merge, or discard this patch.
ecrire/inc/informer.php 1 patch
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -11,77 +11,77 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 # Les information d'une rubrique selectionnee dans le mini navigateur
18 18
 
19 19
 function inc_informer_dist($id, $col, $exclus, $rac, $type, $do = 'aff') {
20
-	include_spip('inc/texte');
21
-	$titre = $descriptif = '';
22
-	if ($type === 'rubrique') {
23
-		$row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . intval($id));
24
-		if ($row) {
25
-			$titre = typo($row['titre']);
26
-			$descriptif = propre($row['descriptif']);
27
-		} else {
28
-			$titre = _T('info_racine_site');
29
-		}
30
-	}
20
+    include_spip('inc/texte');
21
+    $titre = $descriptif = '';
22
+    if ($type === 'rubrique') {
23
+        $row = sql_fetsel('titre, descriptif', 'spip_rubriques', 'id_rubrique = ' . intval($id));
24
+        if ($row) {
25
+            $titre = typo($row['titre']);
26
+            $descriptif = propre($row['descriptif']);
27
+        } else {
28
+            $titre = _T('info_racine_site');
29
+        }
30
+    }
31 31
 
32
-	$res = '';
33
-	if (
34
-		$type === 'rubrique'
35
-		and intval($GLOBALS['visiteur_session']['prefs']['display'] ?? 0) !== 1
36
-		and isset($GLOBALS['meta']['image_process'])
37
-	) {
38
-		if ($GLOBALS['meta']['image_process'] !== 'non') {
39
-			$chercher_logo = charger_fonction('chercher_logo', 'inc');
40
-			if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
41
-				[$fid, $dir, $nom, $format] = $res;
42
-				include_spip('inc/filtres_images_mini');
43
-				$res = image_reduire("<img src='$fid' alt='' />", 100, 48);
44
-				if ($res) {
45
-					$res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
46
-				}
47
-			}
48
-		}
49
-	}
32
+    $res = '';
33
+    if (
34
+        $type === 'rubrique'
35
+        and intval($GLOBALS['visiteur_session']['prefs']['display'] ?? 0) !== 1
36
+        and isset($GLOBALS['meta']['image_process'])
37
+    ) {
38
+        if ($GLOBALS['meta']['image_process'] !== 'non') {
39
+            $chercher_logo = charger_fonction('chercher_logo', 'inc');
40
+            if ($res = $chercher_logo($id, 'id_rubrique', 'on')) {
41
+                [$fid, $dir, $nom, $format] = $res;
42
+                include_spip('inc/filtres_images_mini');
43
+                $res = image_reduire("<img src='$fid' alt='' />", 100, 48);
44
+                if ($res) {
45
+                    $res = "<div class='informer__media' style='float: " . $GLOBALS['spip_lang_right'] . '; margin-' . $GLOBALS['spip_lang_right'] . ": -5px; margin-top: -5px;'>$res</div>";
46
+                }
47
+            }
48
+        }
49
+    }
50 50
 
51
-	$rac = spip_htmlentities($rac, ENT_QUOTES);
52
-	$do = spip_htmlentities($do, ENT_QUOTES);
53
-	$id = intval($id);
51
+    $rac = spip_htmlentities($rac, ENT_QUOTES);
52
+    $do = spip_htmlentities($do, ENT_QUOTES);
53
+    $id = intval($id);
54 54
 
55 55
 # ce lien provoque la selection (directe) de la rubrique cliquee
56 56
 # et l'affichage de son titre dans le bandeau
57
-	$titre = strtr(
58
-		str_replace(
59
-			"'",
60
-			'&#8217;',
61
-			str_replace('"', '&#34;', textebrut($titre))
62
-		),
63
-		"\n\r",
64
-		'  '
65
-	);
57
+    $titre = strtr(
58
+        str_replace(
59
+            "'",
60
+            '&#8217;',
61
+            str_replace('"', '&#34;', textebrut($titre))
62
+        ),
63
+        "\n\r",
64
+        '  '
65
+    );
66 66
 
67
-	$js_func = $do . '_selection_titre';
67
+    $js_func = $do . '_selection_titre';
68 68
 
69
-	return "<div style='display: none;'>"
70
-	. "<input type='text' id='" . $rac . "_sel' value='$id' />"
71
-	. "<input type='text' id='" . $rac . "_sel2' value=\""
72
-	. entites_html($titre)
73
-	. '" />'
74
-	. '</div>'
75
-	. "<div class='informer' style='padding: 5px; border-top: 0px;'>"
76
-	. '<div class="informer__item">'
77
-	. (!$res ? '' : $res)
78
-	. "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
79
-	. (!$descriptif ? '' : "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>')
80
-	. '</div>'
81
-	. "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
82
-	. "<input type='submit' class='fondo btn submit' value='"
83
-	. _T('bouton_choisir')
84
-	. "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
85
-	. '</div>'
86
-	. '</div>';
69
+    return "<div style='display: none;'>"
70
+    . "<input type='text' id='" . $rac . "_sel' value='$id' />"
71
+    . "<input type='text' id='" . $rac . "_sel2' value=\""
72
+    . entites_html($titre)
73
+    . '" />'
74
+    . '</div>'
75
+    . "<div class='informer' style='padding: 5px; border-top: 0px;'>"
76
+    . '<div class="informer__item">'
77
+    . (!$res ? '' : $res)
78
+    . "<p class='informer__titre'><b>" . safehtml($titre) . '</b></p>'
79
+    . (!$descriptif ? '' : "<div class='informer__descriptif'>" . safehtml($descriptif) . '</div>')
80
+    . '</div>'
81
+    . "<div class='informer__action' style='clear:both; text-align: " . $GLOBALS['spip_lang_right'] . ";'>"
82
+    . "<input type='submit' class='fondo btn submit' value='"
83
+    . _T('bouton_choisir')
84
+    . "'\nonclick=\"$js_func('$titre',$id,'selection_rubrique','id_parent'); return false;\" />"
85
+    . '</div>'
86
+    . '</div>';
87 87
 }
Please login to merge, or discard this patch.
ecrire/inc/commencer_page.php 1 patch
Indentation   +56 added lines, -56 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
 /**
@@ -43,25 +43,25 @@  discard block
 block discarded – undo
43 43
  * @return string Code HTML
44 44
  **/
45 45
 function inc_commencer_page_dist(
46
-	$titre = '',
47
-	$rubrique = 'accueil',
48
-	$sous_rubrique = 'accueil',
49
-	$id_rubrique = '',
50
-	$menu = true,
51
-	$minipres = false,
52
-	$alertes = true
46
+    $titre = '',
47
+    $rubrique = 'accueil',
48
+    $sous_rubrique = 'accueil',
49
+    $id_rubrique = '',
50
+    $menu = true,
51
+    $minipres = false,
52
+    $alertes = true
53 53
 ) {
54 54
 
55
-	include_spip('inc/headers');
55
+    include_spip('inc/headers');
56 56
 
57
-	http_no_cache();
57
+    http_no_cache();
58 58
 
59
-	return init_entete($titre, $id_rubrique, $minipres)
60
-	. init_body($rubrique, $sous_rubrique, $id_rubrique, $menu)
61
-	. "<div id='page'>"
62
-	. auteurs_recemment_connectes($GLOBALS['connect_id_auteur'])
63
-	. ($alertes ? alertes_auteur($GLOBALS['connect_id_auteur']) : '')
64
-	. '<div class="largeur">';
59
+    return init_entete($titre, $id_rubrique, $minipres)
60
+    . init_body($rubrique, $sous_rubrique, $id_rubrique, $menu)
61
+    . "<div id='page'>"
62
+    . auteurs_recemment_connectes($GLOBALS['connect_id_auteur'])
63
+    . ($alertes ? alertes_auteur($GLOBALS['connect_id_auteur']) : '')
64
+    . '<div class="largeur">';
65 65
 }
66 66
 
67 67
 /**
@@ -82,21 +82,21 @@  discard block
 block discarded – undo
82 82
  *     Entête du fichier HTML avec le DOCTYPE
83 83
  */
84 84
 function init_entete($titre = '', $dummy = 0, $minipres = false) {
85
-	include_spip('inc/texte');
86
-	if (!$nom_site_spip = textebrut(typo($GLOBALS['meta']['nom_site']))) {
87
-		$nom_site_spip = _T('info_mon_site_spip');
88
-	}
89
-
90
-	$titre = '['
91
-		. $nom_site_spip
92
-		. ']'
93
-		. ($titre ? ' ' . textebrut(typo($titre)) : '');
94
-
95
-	return _DOCTYPE_ECRIRE
96
-	. html_lang_attributes()
97
-	. "<head>\n"
98
-	. init_head($titre, $dummy, $minipres)
99
-	. "</head>\n";
85
+    include_spip('inc/texte');
86
+    if (!$nom_site_spip = textebrut(typo($GLOBALS['meta']['nom_site']))) {
87
+        $nom_site_spip = _T('info_mon_site_spip');
88
+    }
89
+
90
+    $titre = '['
91
+        . $nom_site_spip
92
+        . ']'
93
+        . ($titre ? ' ' . textebrut(typo($titre)) : '');
94
+
95
+    return _DOCTYPE_ECRIRE
96
+    . html_lang_attributes()
97
+    . "<head>\n"
98
+    . init_head($titre, $dummy, $minipres)
99
+    . "</head>\n";
100 100
 }
101 101
 
102 102
 /**
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
  * @return string
111 111
  */
112 112
 function init_head($titre = '', $dummy = 0, $minipres = false) {
113
-	return recuperer_fond('prive/squelettes/head/dist', ['titre' => $titre, 'minipres' => $minipres ? ' ' : '']);
113
+    return recuperer_fond('prive/squelettes/head/dist', ['titre' => $titre, 'minipres' => $minipres ? ' ' : '']);
114 114
 }
115 115
 
116 116
 /**
@@ -132,20 +132,20 @@  discard block
 block discarded – undo
132 132
  */
133 133
 function init_body($rubrique = 'accueil', $sous_rubrique = 'accueil', $id_rubrique = '', $menu = true) {
134 134
 
135
-	$res = pipeline('body_prive', "<body class='"
136
-		. init_body_class() . ' ' . _request('exec') . "'"
137
-		. ($GLOBALS['spip_lang_rtl'] ? " dir='rtl'" : '')
138
-		. '>');
135
+    $res = pipeline('body_prive', "<body class='"
136
+        . init_body_class() . ' ' . _request('exec') . "'"
137
+        . ($GLOBALS['spip_lang_rtl'] ? " dir='rtl'" : '')
138
+        . '>');
139 139
 
140
-	if (!$menu) {
141
-		return $res;
142
-	}
140
+    if (!$menu) {
141
+        return $res;
142
+    }
143 143
 
144 144
 
145
-	$bandeau = charger_fonction('bandeau', 'inc');
145
+    $bandeau = charger_fonction('bandeau', 'inc');
146 146
 
147
-	return $res
148
-	. $bandeau();
147
+    return $res
148
+    . $bandeau();
149 149
 }
150 150
 
151 151
 /**
@@ -157,23 +157,23 @@  discard block
 block discarded – undo
157 157
  * @return string Classes CSS (séparées par des espaces)
158 158
  */
159 159
 function init_body_class() {
160
-	$display_modes = [
161
-		0 => 'icones_img_texte' // défaut.
162
-		/*init*/,
163
-		1 => 'icones_texte',
164
-		2 => 'icones_img_texte',
165
-		3 => 'icones_img'
166
-	];
160
+    $display_modes = [
161
+        0 => 'icones_img_texte' // défaut.
162
+        /*init*/,
163
+        1 => 'icones_texte',
164
+        2 => 'icones_img_texte',
165
+        3 => 'icones_img'
166
+    ];
167 167
 
168
-	$prefs = $GLOBALS['visiteur_session']['prefs'] ?? [];
168
+    $prefs = $GLOBALS['visiteur_session']['prefs'] ?? [];
169 169
 
170
-	$display_mode = $display_modes[intval($prefs['display'] ?? 0)] ?? $display_modes[0];
171
-	$spip_display_navigation = isset($prefs['display_navigation']) ? spip_sanitize_classname($prefs['display_navigation']) : 'navigation_avec_icones';
170
+    $display_mode = $display_modes[intval($prefs['display'] ?? 0)] ?? $display_modes[0];
171
+    $spip_display_navigation = isset($prefs['display_navigation']) ? spip_sanitize_classname($prefs['display_navigation']) : 'navigation_avec_icones';
172 172
 
173
-	$couleur = intval($prefs['couleur'] ?? 2);
173
+    $couleur = intval($prefs['couleur'] ?? 2);
174 174
 
175
-	$classes = "spip-theme-colors-$couleur $spip_display_navigation $display_mode";
176
-	return spip_sanitize_classname($classes);
175
+    $classes = "spip-theme-colors-$couleur $spip_display_navigation $display_mode";
176
+    return spip_sanitize_classname($classes);
177 177
 }
178 178
 
179 179
 
@@ -184,5 +184,5 @@  discard block
 block discarded – undo
184 184
  * @return string
185 185
  */
186 186
 function auteurs_recemment_connectes($id_auteur) {
187
-	return recuperer_fond('prive/objets/liste/auteurs_enligne');
187
+    return recuperer_fond('prive/objets/liste/auteurs_enligne');
188 188
 }
Please login to merge, or discard this patch.
ecrire/index.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
 /** Drapeau indiquant que l'on est dans l'espace privé */
20 20
 define('_ESPACE_PRIVE', true);
21 21
 if (!defined('_ECRIRE_INC_VERSION')) {
22
-	include 'inc_version.php';
22
+    include 'inc_version.php';
23 23
 }
24 24
 
25 25
 include_spip('inc/cookie');
@@ -35,18 +35,18 @@  discard block
 block discarded – undo
35 35
 // alors il faut blinder les variables d'URL
36 36
 //
37 37
 if (autoriser_sans_cookie($exec, false)) {
38
-	if (!isset($reinstall)) {
39
-		$reinstall = 'non';
40
-	}
41
-	$var_auth = true;
38
+    if (!isset($reinstall)) {
39
+        $reinstall = 'non';
40
+    }
41
+    $var_auth = true;
42 42
 } else {
43
-	// Authentification, redefinissable
44
-	$auth = charger_fonction('auth', 'inc');
45
-	$var_auth = $auth();
46
-	if ($var_auth) {
47
-		echo auth_echec($var_auth);
48
-		exit;
49
-	}
43
+    // Authentification, redefinissable
44
+    $auth = charger_fonction('auth', 'inc');
45
+    $var_auth = $auth();
46
+    if ($var_auth) {
47
+        echo auth_echec($var_auth);
48
+        exit;
49
+    }
50 50
 }
51 51
 
52 52
 // initialiser a la langue par defaut
@@ -57,29 +57,29 @@  discard block
 block discarded – undo
57 57
 
58 58
 
59 59
 if (_request('action') or _request('var_ajax') or _request('formulaire_action')) {
60
-	if (!autoriser_sans_cookie($exec)) {
61
-		// Charger l'aiguilleur qui va mettre sur la bonne voie les traitements derogatoires
62
-		include_spip('public/aiguiller');
63
-		if (
64
-			// cas des appels actions ?action=xxx
65
-			traiter_appels_actions()
66
-			or
67
-			// cas des hits ajax sur les inclusions ajax
68
-			traiter_appels_inclusions_ajax()
69
-			or
70
-			// cas des formulaires charger/verifier/traiter
71
-			traiter_formulaires_dynamiques()
72
-		) {
73
-			exit;
74
-		} // le hit est fini !
75
-	}
60
+    if (!autoriser_sans_cookie($exec)) {
61
+        // Charger l'aiguilleur qui va mettre sur la bonne voie les traitements derogatoires
62
+        include_spip('public/aiguiller');
63
+        if (
64
+            // cas des appels actions ?action=xxx
65
+            traiter_appels_actions()
66
+            or
67
+            // cas des hits ajax sur les inclusions ajax
68
+            traiter_appels_inclusions_ajax()
69
+            or
70
+            // cas des formulaires charger/verifier/traiter
71
+            traiter_formulaires_dynamiques()
72
+        ) {
73
+            exit;
74
+        } // le hit est fini !
75
+    }
76 76
 }
77 77
 // securiser les redirect du back-office
78 78
 if (_request('redirect')) {
79
-	if (!function_exists('securiser_redirect_action')) {
80
-		include_spip('public/aiguiller');
81
-	}
82
-	set_request('redirect', securiser_redirect_action(_request('redirect')));
79
+    if (!function_exists('securiser_redirect_action')) {
80
+        include_spip('public/aiguiller');
81
+    }
82
+    set_request('redirect', securiser_redirect_action(_request('redirect')));
83 83
 }
84 84
 
85 85
 
@@ -89,12 +89,12 @@  discard block
 block discarded – undo
89 89
 
90 90
 // Controle de la version, sauf si on est deja en train de s'en occuper
91 91
 if (
92
-	!$reinstall == 'oui'
93
-	and !_AJAX
94
-	and isset($GLOBALS['meta']['version_installee'])
95
-	and ($GLOBALS['spip_version_base'] != (str_replace(',', '.', $GLOBALS['meta']['version_installee'])))
92
+    !$reinstall == 'oui'
93
+    and !_AJAX
94
+    and isset($GLOBALS['meta']['version_installee'])
95
+    and ($GLOBALS['spip_version_base'] != (str_replace(',', '.', $GLOBALS['meta']['version_installee'])))
96 96
 ) {
97
-	$exec = 'demande_mise_a_jour';
97
+    $exec = 'demande_mise_a_jour';
98 98
 }
99 99
 
100 100
 // Quand une action d'administration est en cours (meta "admin"),
@@ -104,39 +104,39 @@  discard block
 block discarded – undo
104 104
 // sinon c'est qu'elle a ete interrompue et il faut la reprendre
105 105
 
106 106
 elseif (isset($GLOBALS['meta']['admin'])) {
107
-	if (preg_match('/^(.*)_(\d+)_/', $GLOBALS['meta']['admin'], $l)) {
108
-		[, $var_f, $n] = $l;
109
-	}
110
-	if (
111
-		_AJAX
112
-		or !(
113
-			isset($_COOKIE['spip_admin'])
114
-			or (isset($GLOBALS['visiteur_session']) and $GLOBALS['visiteur_session']['statut'] == '0minirezo')
115
-		)
116
-	) {
117
-		spip_log('Quand la meta admin vaut ' .
118
-			$GLOBALS['meta']['admin'] .
119
-			' seul un admin peut se connecter et sans AJAX.' .
120
-			' En cas de probleme, detruire cette meta.');
121
-		die(_T('info_travaux_texte'));
122
-	}
123
-	if ($n) {
124
-		[, $var_f, $n] = $l;
125
-		if (tester_url_ecrire("base_$var_f")) {
126
-			$var_f = "base_$var_f";
127
-		}
128
-		if ($var_f != $exec) {
129
-			spip_log("Le script $var_f lance par auteur$n se substitue a l'exec $exec");
130
-			$exec = $var_f;
131
-			set_request('exec', $exec);
132
-		}
133
-	}
107
+    if (preg_match('/^(.*)_(\d+)_/', $GLOBALS['meta']['admin'], $l)) {
108
+        [, $var_f, $n] = $l;
109
+    }
110
+    if (
111
+        _AJAX
112
+        or !(
113
+            isset($_COOKIE['spip_admin'])
114
+            or (isset($GLOBALS['visiteur_session']) and $GLOBALS['visiteur_session']['statut'] == '0minirezo')
115
+        )
116
+    ) {
117
+        spip_log('Quand la meta admin vaut ' .
118
+            $GLOBALS['meta']['admin'] .
119
+            ' seul un admin peut se connecter et sans AJAX.' .
120
+            ' En cas de probleme, detruire cette meta.');
121
+        die(_T('info_travaux_texte'));
122
+    }
123
+    if ($n) {
124
+        [, $var_f, $n] = $l;
125
+        if (tester_url_ecrire("base_$var_f")) {
126
+            $var_f = "base_$var_f";
127
+        }
128
+        if ($var_f != $exec) {
129
+            spip_log("Le script $var_f lance par auteur$n se substitue a l'exec $exec");
130
+            $exec = $var_f;
131
+            set_request('exec', $exec);
132
+        }
133
+    }
134 134
 }
135 135
 // si nom pas plausible, prendre le script par defaut
136 136
 // attention aux deux cas 404/403 qui commencent par un 4 !
137 137
 elseif (!preg_match(',^[a-z4_][0-9a-z_-]*$,i', $exec)) {
138
-	$exec = 'accueil';
139
-	set_request('exec', $exec);
138
+    $exec = 'accueil';
139
+    set_request('exec', $exec);
140 140
 }
141 141
 
142 142
 //  si la langue est specifiee par cookie et ne correspond pas
@@ -144,19 +144,19 @@  discard block
 block discarded – undo
144 144
 // on appelle directement la fonction, car un appel d'action peut conduire a une boucle infinie
145 145
 // si le cookie n'est pas pose correctement dans l'action
146 146
 if (
147
-	!$var_auth and isset($_COOKIE['spip_lang_ecrire'])
148
-	and $_COOKIE['spip_lang_ecrire'] <> $GLOBALS['visiteur_session']['lang']
147
+    !$var_auth and isset($_COOKIE['spip_lang_ecrire'])
148
+    and $_COOKIE['spip_lang_ecrire'] <> $GLOBALS['visiteur_session']['lang']
149 149
 ) {
150
-	include_spip('action/converser');
151
-	action_converser_post($GLOBALS['visiteur_session']['lang'], true);
150
+    include_spip('action/converser');
151
+    action_converser_post($GLOBALS['visiteur_session']['lang'], true);
152 152
 }
153 153
 
154 154
 if ($var_f = tester_url_ecrire($exec)) {
155
-	$var_f = charger_fonction($var_f);
156
-	$var_f(); // at last
155
+    $var_f = charger_fonction($var_f);
156
+    $var_f(); // at last
157 157
 } else {
158
-	// Rien de connu: rerouter vers exec=404 au lieu d'echouer
159
-	// ce qui permet de laisser la main a un plugin
160
-	$var_f = charger_fonction('404');
161
-	$var_f($exec);
158
+    // Rien de connu: rerouter vers exec=404 au lieu d'echouer
159
+    // ce qui permet de laisser la main a un plugin
160
+    $var_f = charger_fonction('404');
161
+    $var_f($exec);
162 162
 }
Please login to merge, or discard this patch.
ecrire/action/editer_objet.php 1 patch
Indentation   +513 added lines, -513 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
 /**
@@ -33,36 +33,36 @@  discard block
 block discarded – undo
33 33
  */
34 34
 function action_editer_objet_dist($id = null, $objet = null, $set = null) {
35 35
 
36
-	// appel direct depuis une url avec arg = "objet/id"
37
-	if (is_null($id) or is_null($objet)) {
38
-		$securiser_action = charger_fonction('securiser_action', 'inc');
39
-		$arg = $securiser_action();
40
-		[$objet, $id] = array_pad(explode('/', $arg, 2), 2, null);
41
-	}
42
-
43
-	// appel incorrect ou depuis une url erronnée interdit
44
-	if (is_null($id) or is_null($objet)) {
45
-		include_spip('inc/minipres');
46
-		echo minipres(_T('info_acces_interdit'));
47
-		die();
48
-	}
49
-
50
-	// si id n'est pas un nombre, c'est une creation
51
-	// mais on verifie qu'on a toutes les donnees qu'il faut.
52
-	if (!$id = intval($id)) {
53
-		// on ne sait pas si un parent existe mais on essaye
54
-		$id_parent = _request('id_parent');
55
-		$id = objet_inserer($objet, $id_parent);
56
-	}
57
-
58
-	if (!($id = intval($id)) > 0) {
59
-		return [$id, _L('echec enregistrement en base')];
60
-	}
61
-
62
-	// Enregistre l'envoi dans la BD
63
-	$err = objet_modifier($objet, $id, $set);
64
-
65
-	return [$id, $err];
36
+    // appel direct depuis une url avec arg = "objet/id"
37
+    if (is_null($id) or is_null($objet)) {
38
+        $securiser_action = charger_fonction('securiser_action', 'inc');
39
+        $arg = $securiser_action();
40
+        [$objet, $id] = array_pad(explode('/', $arg, 2), 2, null);
41
+    }
42
+
43
+    // appel incorrect ou depuis une url erronnée interdit
44
+    if (is_null($id) or is_null($objet)) {
45
+        include_spip('inc/minipres');
46
+        echo minipres(_T('info_acces_interdit'));
47
+        die();
48
+    }
49
+
50
+    // si id n'est pas un nombre, c'est une creation
51
+    // mais on verifie qu'on a toutes les donnees qu'il faut.
52
+    if (!$id = intval($id)) {
53
+        // on ne sait pas si un parent existe mais on essaye
54
+        $id_parent = _request('id_parent');
55
+        $id = objet_inserer($objet, $id_parent);
56
+    }
57
+
58
+    if (!($id = intval($id)) > 0) {
59
+        return [$id, _L('echec enregistrement en base')];
60
+    }
61
+
62
+    // Enregistre l'envoi dans la BD
63
+    $err = objet_modifier($objet, $id, $set);
64
+
65
+    return [$id, $err];
66 66
 }
67 67
 
68 68
 /**
@@ -75,85 +75,85 @@  discard block
 block discarded – undo
75 75
  * @return mixed|string
76 76
  */
77 77
 function objet_modifier($objet, $id, $set = null) {
78
-	if (($t = objet_type($objet)) !== $objet) {
79
-		spip_log("objet_modifier: appel avec type $objet invalide au lieu de $t", 'editer' . _LOG_INFO_IMPORTANTE);
80
-		$objet = $t;
81
-	}
82
-	if (
83
-		include_spip('action/editer_' . $objet)
84
-		and function_exists($modifier = $objet . '_modifier')
85
-	) {
86
-		return $modifier($id, $set);
87
-	}
88
-
89
-	$table_sql = table_objet_sql($objet);
90
-	$trouver_table = charger_fonction('trouver_table', 'base');
91
-	$desc = $trouver_table($table_sql);
92
-	if (!$desc or !isset($desc['field'])) {
93
-		spip_log("Objet $objet inconnu dans objet_modifier", 'editer' . _LOG_ERREUR);
94
-
95
-		return _L("Erreur objet $objet inconnu");
96
-	}
97
-	include_spip('inc/modifier');
98
-
99
-	$champ_date = '';
100
-	if (isset($desc['date']) and $desc['date']) {
101
-		$champ_date = $desc['date'];
102
-	} elseif (isset($desc['field']['date'])) {
103
-		$champ_date = 'date';
104
-	}
105
-
106
-	$include_list = array_keys($desc['field']);
107
-	// on ne traite pas la cle primaire par defaut, notamment car
108
-	// sur une creation, id_x vaut 'oui', et serait enregistre en id_x=0 dans la base
109
-	$include_list = array_diff($include_list, [$desc['key']['PRIMARY KEY']]);
110
-
111
-	if (isset($desc['champs_editables']) and is_array($desc['champs_editables'])) {
112
-		$include_list = $desc['champs_editables'];
113
-	}
114
-	$c = collecter_requests(
115
-		// include list
116
-		$include_list,
117
-		// exclude list
118
-		[$champ_date, 'statut', 'id_parent', 'id_secteur'],
119
-		// donnees eventuellement fournies
120
-		$set
121
-	);
122
-
123
-	// Si l'objet est publie, invalider les caches et demander sa reindexation
124
-	if (objet_test_si_publie($objet, $id)) {
125
-		$invalideur = "id='$objet/$id'";
126
-		$indexation = true;
127
-	} else {
128
-		$invalideur = '';
129
-		$indexation = false;
130
-	}
131
-
132
-	if (
133
-		$err = objet_modifier_champs(
134
-			$objet,
135
-			$id,
136
-			[
137
-			'data' => $set,
138
-			'nonvide' => '',
139
-			'invalideur' => $invalideur,
140
-			'indexation' => $indexation,
141
-			// champ a mettre a date('Y-m-d H:i:s') s'il y a modif
142
-			'date_modif' => (isset($desc['field']['date_modif']) ? 'date_modif' : '')
143
-			],
144
-			$c
145
-		)
146
-	) {
147
-		return $err;
148
-	}
149
-
150
-	// Modification de statut, changement de rubrique ?
151
-	// FIXME: Ici lorsqu'un $set est passé, la fonction collecter_requests() retourne tout
152
-	//         le tableau $set hors liste d’exclusion, mais du coup on a possiblement des champs en trop.
153
-	$c = collecter_requests([$champ_date, 'statut', 'id_parent'], [], $set);
154
-	$err = objet_instituer($objet, $id, $c);
155
-
156
-	return $err;
78
+    if (($t = objet_type($objet)) !== $objet) {
79
+        spip_log("objet_modifier: appel avec type $objet invalide au lieu de $t", 'editer' . _LOG_INFO_IMPORTANTE);
80
+        $objet = $t;
81
+    }
82
+    if (
83
+        include_spip('action/editer_' . $objet)
84
+        and function_exists($modifier = $objet . '_modifier')
85
+    ) {
86
+        return $modifier($id, $set);
87
+    }
88
+
89
+    $table_sql = table_objet_sql($objet);
90
+    $trouver_table = charger_fonction('trouver_table', 'base');
91
+    $desc = $trouver_table($table_sql);
92
+    if (!$desc or !isset($desc['field'])) {
93
+        spip_log("Objet $objet inconnu dans objet_modifier", 'editer' . _LOG_ERREUR);
94
+
95
+        return _L("Erreur objet $objet inconnu");
96
+    }
97
+    include_spip('inc/modifier');
98
+
99
+    $champ_date = '';
100
+    if (isset($desc['date']) and $desc['date']) {
101
+        $champ_date = $desc['date'];
102
+    } elseif (isset($desc['field']['date'])) {
103
+        $champ_date = 'date';
104
+    }
105
+
106
+    $include_list = array_keys($desc['field']);
107
+    // on ne traite pas la cle primaire par defaut, notamment car
108
+    // sur une creation, id_x vaut 'oui', et serait enregistre en id_x=0 dans la base
109
+    $include_list = array_diff($include_list, [$desc['key']['PRIMARY KEY']]);
110
+
111
+    if (isset($desc['champs_editables']) and is_array($desc['champs_editables'])) {
112
+        $include_list = $desc['champs_editables'];
113
+    }
114
+    $c = collecter_requests(
115
+        // include list
116
+        $include_list,
117
+        // exclude list
118
+        [$champ_date, 'statut', 'id_parent', 'id_secteur'],
119
+        // donnees eventuellement fournies
120
+        $set
121
+    );
122
+
123
+    // Si l'objet est publie, invalider les caches et demander sa reindexation
124
+    if (objet_test_si_publie($objet, $id)) {
125
+        $invalideur = "id='$objet/$id'";
126
+        $indexation = true;
127
+    } else {
128
+        $invalideur = '';
129
+        $indexation = false;
130
+    }
131
+
132
+    if (
133
+        $err = objet_modifier_champs(
134
+            $objet,
135
+            $id,
136
+            [
137
+            'data' => $set,
138
+            'nonvide' => '',
139
+            'invalideur' => $invalideur,
140
+            'indexation' => $indexation,
141
+            // champ a mettre a date('Y-m-d H:i:s') s'il y a modif
142
+            'date_modif' => (isset($desc['field']['date_modif']) ? 'date_modif' : '')
143
+            ],
144
+            $c
145
+        )
146
+    ) {
147
+        return $err;
148
+    }
149
+
150
+    // Modification de statut, changement de rubrique ?
151
+    // FIXME: Ici lorsqu'un $set est passé, la fonction collecter_requests() retourne tout
152
+    //         le tableau $set hors liste d’exclusion, mais du coup on a possiblement des champs en trop.
153
+    $c = collecter_requests([$champ_date, 'statut', 'id_parent'], [], $set);
154
+    $err = objet_instituer($objet, $id, $c);
155
+
156
+    return $err;
157 157
 }
158 158
 
159 159
 /**
@@ -168,135 +168,135 @@  discard block
 block discarded – undo
168 168
  * @return bool|int
169 169
  */
170 170
 function objet_inserer($objet, $id_parent = null, $set = null) {
171
-	$d = null;
172
-	if (($t = objet_type($objet)) !== $objet) {
173
-		spip_log("objet_inserer: appel avec type $objet invalide au lieu de $t", 'editer' . _LOG_INFO_IMPORTANTE);
174
-		$objet = $t;
175
-	}
176
-	if (
177
-		include_spip('action/editer_' . $objet)
178
-		and function_exists($inserer = $objet . '_inserer')
179
-	) {
180
-		return $inserer($id_parent, $set);
181
-	}
182
-
183
-	$table_sql = table_objet_sql($objet);
184
-	$trouver_table = charger_fonction('trouver_table', 'base');
185
-	$desc = $trouver_table($table_sql);
186
-	if (!$desc or !isset($desc['field'])) {
187
-		return 0;
188
-	}
189
-
190
-	$lang_rub = '';
191
-	$champs = [];
192
-	if (isset($desc['field']['id_rubrique'])) {
193
-		// Si id_rubrique vaut 0 ou n'est pas definie, creer l'objet
194
-		// dans la premiere rubrique racine
195
-		if (!$id_rubrique = intval($id_parent)) {
196
-			$row = sql_fetsel('id_rubrique, id_secteur, lang', 'spip_rubriques', 'id_parent=0', '', '0+titre,titre', '1');
197
-			$id_rubrique = $row['id_rubrique'];
198
-		} else {
199
-			$row = sql_fetsel('lang, id_secteur', 'spip_rubriques', 'id_rubrique=' . intval($id_rubrique));
200
-		}
201
-
202
-		$champs['id_rubrique'] = $id_rubrique;
203
-		if (isset($desc['field']['id_secteur'])) {
204
-			$champs['id_secteur'] = $row['id_secteur'];
205
-		}
206
-		$lang_rub = $row['lang'];
207
-	}
208
-
209
-	// La langue a la creation : si les liens de traduction sont autorises
210
-	// dans les rubriques, on essaie avec la langue de l'auteur,
211
-	// ou a defaut celle de la rubrique
212
-	// Sinon c'est la langue de la rubrique qui est choisie + heritee
213
-	if (
214
-		isset($desc['field']['lang']) and !empty($GLOBALS['meta']['multi_objets']) and in_array(
215
-			$table_sql,
216
-			explode(',', $GLOBALS['meta']['multi_objets'])
217
-		)
218
-	) {
219
-		lang_select($GLOBALS['visiteur_session']['lang']);
220
-		if (
221
-			in_array(
222
-				$GLOBALS['spip_lang'],
223
-				explode(',', $GLOBALS['meta']['langues_multilingue'])
224
-			)
225
-		) {
226
-			$champs['lang'] = $GLOBALS['spip_lang'];
227
-			if (isset($desc['field']['langue_choisie'])) {
228
-				$champs['langue_choisie'] = 'oui';
229
-			}
230
-		}
231
-	} elseif (isset($desc['field']['lang']) and isset($desc['field']['langue_choisie'])) {
232
-		$champs['lang'] = ($lang_rub ?: $GLOBALS['meta']['langue_site']);
233
-		$champs['langue_choisie'] = 'non';
234
-	}
235
-
236
-	if (isset($desc['field']['statut'])) {
237
-		if (isset($desc['statut_textes_instituer'])) {
238
-			$cles_statut = array_keys($desc['statut_textes_instituer']);
239
-			$champs['statut'] = reset($cles_statut);
240
-		} else {
241
-			$champs['statut'] = 'prepa';
242
-		}
243
-	}
244
-
245
-
246
-	if ((isset($desc['date']) and $d = $desc['date']) or isset($desc['field'][$d = 'date'])) {
247
-		$champs[$d] = date('Y-m-d H:i:s');
248
-	}
249
-
250
-	if ($set) {
251
-		$champs = array_merge($champs, $set);
252
-	}
253
-
254
-	// Envoyer aux plugins
255
-	$champs = pipeline(
256
-		'pre_insertion',
257
-		[
258
-			'args' => [
259
-				'table' => $table_sql,
260
-				'id_parent' => $id_parent,
261
-			],
262
-			'data' => $champs
263
-		]
264
-	);
265
-
266
-	$id = sql_insertq($table_sql, $champs);
267
-
268
-	if ($id) {
269
-		// controler si le serveur n'a pas renvoye une erreur
270
-		// et associer l'auteur sinon
271
-		// si la table n'a pas deja un champ id_auteur
272
-		// et si le form n'a pas poste un id_auteur (meme vide, ce qui sert a annuler cette auto association)
273
-		if (
274
-			$id > 0
275
-			and !isset($desc['field']['id_auteur'])
276
-		) {
277
-			$id_auteur = ((is_null(_request('id_auteur')) and isset($GLOBALS['visiteur_session']['id_auteur'])) ?
278
-				$GLOBALS['visiteur_session']['id_auteur']
279
-				: _request('id_auteur'));
280
-			if ($id_auteur) {
281
-				include_spip('action/editer_auteur');
282
-				auteur_associer($id_auteur, [$objet => $id]);
283
-			}
284
-		}
285
-
286
-		pipeline(
287
-			'post_insertion',
288
-			[
289
-				'args' => [
290
-					'table' => $table_sql,
291
-					'id_parent' => $id_parent,
292
-					'id_objet' => $id,
293
-				],
294
-				'data' => $champs
295
-			]
296
-		);
297
-	}
298
-
299
-	return $id;
171
+    $d = null;
172
+    if (($t = objet_type($objet)) !== $objet) {
173
+        spip_log("objet_inserer: appel avec type $objet invalide au lieu de $t", 'editer' . _LOG_INFO_IMPORTANTE);
174
+        $objet = $t;
175
+    }
176
+    if (
177
+        include_spip('action/editer_' . $objet)
178
+        and function_exists($inserer = $objet . '_inserer')
179
+    ) {
180
+        return $inserer($id_parent, $set);
181
+    }
182
+
183
+    $table_sql = table_objet_sql($objet);
184
+    $trouver_table = charger_fonction('trouver_table', 'base');
185
+    $desc = $trouver_table($table_sql);
186
+    if (!$desc or !isset($desc['field'])) {
187
+        return 0;
188
+    }
189
+
190
+    $lang_rub = '';
191
+    $champs = [];
192
+    if (isset($desc['field']['id_rubrique'])) {
193
+        // Si id_rubrique vaut 0 ou n'est pas definie, creer l'objet
194
+        // dans la premiere rubrique racine
195
+        if (!$id_rubrique = intval($id_parent)) {
196
+            $row = sql_fetsel('id_rubrique, id_secteur, lang', 'spip_rubriques', 'id_parent=0', '', '0+titre,titre', '1');
197
+            $id_rubrique = $row['id_rubrique'];
198
+        } else {
199
+            $row = sql_fetsel('lang, id_secteur', 'spip_rubriques', 'id_rubrique=' . intval($id_rubrique));
200
+        }
201
+
202
+        $champs['id_rubrique'] = $id_rubrique;
203
+        if (isset($desc['field']['id_secteur'])) {
204
+            $champs['id_secteur'] = $row['id_secteur'];
205
+        }
206
+        $lang_rub = $row['lang'];
207
+    }
208
+
209
+    // La langue a la creation : si les liens de traduction sont autorises
210
+    // dans les rubriques, on essaie avec la langue de l'auteur,
211
+    // ou a defaut celle de la rubrique
212
+    // Sinon c'est la langue de la rubrique qui est choisie + heritee
213
+    if (
214
+        isset($desc['field']['lang']) and !empty($GLOBALS['meta']['multi_objets']) and in_array(
215
+            $table_sql,
216
+            explode(',', $GLOBALS['meta']['multi_objets'])
217
+        )
218
+    ) {
219
+        lang_select($GLOBALS['visiteur_session']['lang']);
220
+        if (
221
+            in_array(
222
+                $GLOBALS['spip_lang'],
223
+                explode(',', $GLOBALS['meta']['langues_multilingue'])
224
+            )
225
+        ) {
226
+            $champs['lang'] = $GLOBALS['spip_lang'];
227
+            if (isset($desc['field']['langue_choisie'])) {
228
+                $champs['langue_choisie'] = 'oui';
229
+            }
230
+        }
231
+    } elseif (isset($desc['field']['lang']) and isset($desc['field']['langue_choisie'])) {
232
+        $champs['lang'] = ($lang_rub ?: $GLOBALS['meta']['langue_site']);
233
+        $champs['langue_choisie'] = 'non';
234
+    }
235
+
236
+    if (isset($desc['field']['statut'])) {
237
+        if (isset($desc['statut_textes_instituer'])) {
238
+            $cles_statut = array_keys($desc['statut_textes_instituer']);
239
+            $champs['statut'] = reset($cles_statut);
240
+        } else {
241
+            $champs['statut'] = 'prepa';
242
+        }
243
+    }
244
+
245
+
246
+    if ((isset($desc['date']) and $d = $desc['date']) or isset($desc['field'][$d = 'date'])) {
247
+        $champs[$d] = date('Y-m-d H:i:s');
248
+    }
249
+
250
+    if ($set) {
251
+        $champs = array_merge($champs, $set);
252
+    }
253
+
254
+    // Envoyer aux plugins
255
+    $champs = pipeline(
256
+        'pre_insertion',
257
+        [
258
+            'args' => [
259
+                'table' => $table_sql,
260
+                'id_parent' => $id_parent,
261
+            ],
262
+            'data' => $champs
263
+        ]
264
+    );
265
+
266
+    $id = sql_insertq($table_sql, $champs);
267
+
268
+    if ($id) {
269
+        // controler si le serveur n'a pas renvoye une erreur
270
+        // et associer l'auteur sinon
271
+        // si la table n'a pas deja un champ id_auteur
272
+        // et si le form n'a pas poste un id_auteur (meme vide, ce qui sert a annuler cette auto association)
273
+        if (
274
+            $id > 0
275
+            and !isset($desc['field']['id_auteur'])
276
+        ) {
277
+            $id_auteur = ((is_null(_request('id_auteur')) and isset($GLOBALS['visiteur_session']['id_auteur'])) ?
278
+                $GLOBALS['visiteur_session']['id_auteur']
279
+                : _request('id_auteur'));
280
+            if ($id_auteur) {
281
+                include_spip('action/editer_auteur');
282
+                auteur_associer($id_auteur, [$objet => $id]);
283
+            }
284
+        }
285
+
286
+        pipeline(
287
+            'post_insertion',
288
+            [
289
+                'args' => [
290
+                    'table' => $table_sql,
291
+                    'id_parent' => $id_parent,
292
+                    'id_objet' => $id,
293
+                ],
294
+                'data' => $champs
295
+            ]
296
+        );
297
+    }
298
+
299
+    return $id;
300 300
 }
301 301
 
302 302
 
@@ -313,138 +313,138 @@  discard block
 block discarded – undo
313 313
  * @return string
314 314
  */
315 315
 function objet_instituer($objet, $id, $c, $calcul_rub = true) {
316
-	if (($t = objet_type($objet)) !== $objet) {
317
-		spip_log("objet_instituer: appel avec type $objet invalide au lieu de $t", 'editer' . _LOG_INFO_IMPORTANTE);
318
-		$objet = $t;
319
-	}
320
-	if (
321
-		include_spip('action/editer_' . $objet)
322
-		and function_exists($instituer = $objet . '_instituer')
323
-	) {
324
-		return $instituer($id, $c, $calcul_rub);
325
-	}
326
-
327
-	$table_sql = table_objet_sql($objet);
328
-	$trouver_table = charger_fonction('trouver_table', 'base');
329
-	$desc = $trouver_table($table_sql);
330
-	if (!$desc or !isset($desc['field'])) {
331
-		return _L("Impossible d'instituer $objet : non connu en base");
332
-	}
333
-
334
-	include_spip('inc/autoriser');
335
-	include_spip('inc/rubriques');
336
-	include_spip('inc/modifier');
337
-
338
-	$sel = [];
339
-	$sel[] = (isset($desc['field']['statut']) ? 'statut' : "'' as statut");
340
-
341
-	$champ_date = '';
342
-	if (isset($desc['date']) and $desc['date']) {
343
-		$champ_date = $desc['date'];
344
-	} elseif (isset($desc['field']['date'])) {
345
-		$champ_date = 'date';
346
-	}
347
-
348
-	$sel[] = ($champ_date ? "$champ_date as date" : "'' as date");
349
-	$sel[] = (isset($desc['field']['id_rubrique']) ? 'id_rubrique' : '0 as id_rubrique');
350
-
351
-	$row = sql_fetsel($sel, $table_sql, id_table_objet($objet) . '=' . intval($id));
352
-
353
-	$id_rubrique = $row['id_rubrique'];
354
-	$statut_ancien = $statut = $row['statut'];
355
-	$date_ancienne = $date = $row['date'];
356
-	$champs = [];
357
-
358
-	$d = ($date and isset($c[$champ_date])) ? $c[$champ_date] : null;
359
-	$s = (isset($desc['field']['statut']) and isset($c['statut'])) ? $c['statut'] : $statut;
360
-
361
-	// cf autorisations dans inc/instituer_objet
362
-	if ($s != $statut or ($d and $d != $date)) {
363
-		if (
364
-			$id_rubrique ?
365
-			autoriser('publierdans', 'rubrique', $id_rubrique)
366
-			:
367
-			autoriser('instituer', $objet, $id, null, ['statut' => $s])
368
-		) {
369
-			$statut = $champs['statut'] = $s;
370
-		} else {
371
-			if ($s != 'publie' and autoriser('modifier', $objet, $id)) {
372
-				$statut = $champs['statut'] = $s;
373
-			} else {
374
-				spip_log("editer_objet $objet #$id refus " . json_encode($c, JSON_THROW_ON_ERROR), 'editer' . _LOG_INFO_IMPORTANTE);
375
-			}
376
-		}
377
-
378
-		// En cas de publication, fixer la date a "maintenant"
379
-		// sauf si $c commande autre chose
380
-		// ou si l'objet est deja date dans le futur
381
-		// En cas de proposition d'un objet (mais pas depublication), idem
382
-		if ($champ_date) {
383
-			if (
384
-				$champs['statut'] == 'publie'
385
-				or ($champs['statut'] == 'prop' and !in_array($statut_ancien, ['publie', 'prop']))
386
-				or $d
387
-			) {
388
-				if ($d or strtotime($d = $date) > time()) {
389
-					$champs[$champ_date] = $date = $d;
390
-				} else {
391
-					$champs[$champ_date] = $date = date('Y-m-d H:i:s');
392
-				}
393
-			}
394
-		}
395
-	}
396
-
397
-	// Verifier que la rubrique demandee existe et est differente
398
-	// de la rubrique actuelle
399
-	if (
400
-		$id_rubrique
401
-		and isset($c['id_parent'])
402
-		and $id_parent = $c['id_parent']
403
-		and $id_parent != $id_rubrique
404
-		and (sql_fetsel('1', 'spip_rubriques', 'id_rubrique=' . intval($id_parent)))
405
-	) {
406
-		$champs['id_rubrique'] = $id_parent;
407
-
408
-		// si l'objet etait publie
409
-		// et que le demandeur n'est pas admin de la rubrique
410
-		// repasser l'objet en statut 'propose'.
411
-		if (
412
-			$statut == 'publie'
413
-			and !autoriser('publierdans', 'rubrique', $id_rubrique)
414
-		) {
415
-			$champs['statut'] = 'prop';
416
-		}
417
-	}
418
-
419
-
420
-	// Envoyer aux plugins
421
-	$champs = pipeline(
422
-		'pre_edition',
423
-		[
424
-			'args' => [
425
-				'table' => $table_sql,
426
-				'id_objet' => $id,
427
-				'action' => 'instituer',
428
-				'statut_ancien' => $statut_ancien,
429
-				'date_ancienne' => $date_ancienne,
430
-				'id_parent_ancien' => $id_rubrique,
431
-			],
432
-			'data' => $champs
433
-		]
434
-	);
435
-
436
-	if (!(is_countable($champs) ? count($champs) : 0)) {
437
-		return '';
438
-	}
439
-
440
-	// Envoyer les modifs.
441
-	objet_editer_heritage($objet, $id, $id_rubrique, $statut_ancien, $champs, $calcul_rub);
442
-
443
-	// Invalider les caches
444
-	include_spip('inc/invalideur');
445
-	suivre_invalideur("id='$objet/$id'");
446
-
447
-	/*
316
+    if (($t = objet_type($objet)) !== $objet) {
317
+        spip_log("objet_instituer: appel avec type $objet invalide au lieu de $t", 'editer' . _LOG_INFO_IMPORTANTE);
318
+        $objet = $t;
319
+    }
320
+    if (
321
+        include_spip('action/editer_' . $objet)
322
+        and function_exists($instituer = $objet . '_instituer')
323
+    ) {
324
+        return $instituer($id, $c, $calcul_rub);
325
+    }
326
+
327
+    $table_sql = table_objet_sql($objet);
328
+    $trouver_table = charger_fonction('trouver_table', 'base');
329
+    $desc = $trouver_table($table_sql);
330
+    if (!$desc or !isset($desc['field'])) {
331
+        return _L("Impossible d'instituer $objet : non connu en base");
332
+    }
333
+
334
+    include_spip('inc/autoriser');
335
+    include_spip('inc/rubriques');
336
+    include_spip('inc/modifier');
337
+
338
+    $sel = [];
339
+    $sel[] = (isset($desc['field']['statut']) ? 'statut' : "'' as statut");
340
+
341
+    $champ_date = '';
342
+    if (isset($desc['date']) and $desc['date']) {
343
+        $champ_date = $desc['date'];
344
+    } elseif (isset($desc['field']['date'])) {
345
+        $champ_date = 'date';
346
+    }
347
+
348
+    $sel[] = ($champ_date ? "$champ_date as date" : "'' as date");
349
+    $sel[] = (isset($desc['field']['id_rubrique']) ? 'id_rubrique' : '0 as id_rubrique');
350
+
351
+    $row = sql_fetsel($sel, $table_sql, id_table_objet($objet) . '=' . intval($id));
352
+
353
+    $id_rubrique = $row['id_rubrique'];
354
+    $statut_ancien = $statut = $row['statut'];
355
+    $date_ancienne = $date = $row['date'];
356
+    $champs = [];
357
+
358
+    $d = ($date and isset($c[$champ_date])) ? $c[$champ_date] : null;
359
+    $s = (isset($desc['field']['statut']) and isset($c['statut'])) ? $c['statut'] : $statut;
360
+
361
+    // cf autorisations dans inc/instituer_objet
362
+    if ($s != $statut or ($d and $d != $date)) {
363
+        if (
364
+            $id_rubrique ?
365
+            autoriser('publierdans', 'rubrique', $id_rubrique)
366
+            :
367
+            autoriser('instituer', $objet, $id, null, ['statut' => $s])
368
+        ) {
369
+            $statut = $champs['statut'] = $s;
370
+        } else {
371
+            if ($s != 'publie' and autoriser('modifier', $objet, $id)) {
372
+                $statut = $champs['statut'] = $s;
373
+            } else {
374
+                spip_log("editer_objet $objet #$id refus " . json_encode($c, JSON_THROW_ON_ERROR), 'editer' . _LOG_INFO_IMPORTANTE);
375
+            }
376
+        }
377
+
378
+        // En cas de publication, fixer la date a "maintenant"
379
+        // sauf si $c commande autre chose
380
+        // ou si l'objet est deja date dans le futur
381
+        // En cas de proposition d'un objet (mais pas depublication), idem
382
+        if ($champ_date) {
383
+            if (
384
+                $champs['statut'] == 'publie'
385
+                or ($champs['statut'] == 'prop' and !in_array($statut_ancien, ['publie', 'prop']))
386
+                or $d
387
+            ) {
388
+                if ($d or strtotime($d = $date) > time()) {
389
+                    $champs[$champ_date] = $date = $d;
390
+                } else {
391
+                    $champs[$champ_date] = $date = date('Y-m-d H:i:s');
392
+                }
393
+            }
394
+        }
395
+    }
396
+
397
+    // Verifier que la rubrique demandee existe et est differente
398
+    // de la rubrique actuelle
399
+    if (
400
+        $id_rubrique
401
+        and isset($c['id_parent'])
402
+        and $id_parent = $c['id_parent']
403
+        and $id_parent != $id_rubrique
404
+        and (sql_fetsel('1', 'spip_rubriques', 'id_rubrique=' . intval($id_parent)))
405
+    ) {
406
+        $champs['id_rubrique'] = $id_parent;
407
+
408
+        // si l'objet etait publie
409
+        // et que le demandeur n'est pas admin de la rubrique
410
+        // repasser l'objet en statut 'propose'.
411
+        if (
412
+            $statut == 'publie'
413
+            and !autoriser('publierdans', 'rubrique', $id_rubrique)
414
+        ) {
415
+            $champs['statut'] = 'prop';
416
+        }
417
+    }
418
+
419
+
420
+    // Envoyer aux plugins
421
+    $champs = pipeline(
422
+        'pre_edition',
423
+        [
424
+            'args' => [
425
+                'table' => $table_sql,
426
+                'id_objet' => $id,
427
+                'action' => 'instituer',
428
+                'statut_ancien' => $statut_ancien,
429
+                'date_ancienne' => $date_ancienne,
430
+                'id_parent_ancien' => $id_rubrique,
431
+            ],
432
+            'data' => $champs
433
+        ]
434
+    );
435
+
436
+    if (!(is_countable($champs) ? count($champs) : 0)) {
437
+        return '';
438
+    }
439
+
440
+    // Envoyer les modifs.
441
+    objet_editer_heritage($objet, $id, $id_rubrique, $statut_ancien, $champs, $calcul_rub);
442
+
443
+    // Invalider les caches
444
+    include_spip('inc/invalideur');
445
+    suivre_invalideur("id='$objet/$id'");
446
+
447
+    /*
448 448
 	if ($date) {
449 449
 		$t = strtotime($date);
450 450
 		$p = @$GLOBALS['meta']['date_prochain_postdate'];
@@ -453,32 +453,32 @@  discard block
 block discarded – undo
453 453
 		}
454 454
 	}*/
455 455
 
456
-	// Pipeline
457
-	pipeline(
458
-		'post_edition',
459
-		[
460
-			'args' => [
461
-				'table' => $table_sql,
462
-				'id_objet' => $id,
463
-				'action' => 'instituer',
464
-				'statut_ancien' => $statut_ancien,
465
-				'date_ancienne' => $date_ancienne,
466
-				'id_parent_ancien' => $id_rubrique,
467
-			],
468
-			'data' => $champs
469
-		]
470
-	);
471
-
472
-	// Notifications
473
-	if ($notifications = charger_fonction('notifications', 'inc')) {
474
-		$notifications(
475
-			"instituer$objet",
476
-			$id,
477
-			['statut' => $statut, 'statut_ancien' => $statut_ancien, 'date' => $date, 'date_ancienne' => $date_ancienne]
478
-		);
479
-	}
480
-
481
-	return ''; // pas d'erreur
456
+    // Pipeline
457
+    pipeline(
458
+        'post_edition',
459
+        [
460
+            'args' => [
461
+                'table' => $table_sql,
462
+                'id_objet' => $id,
463
+                'action' => 'instituer',
464
+                'statut_ancien' => $statut_ancien,
465
+                'date_ancienne' => $date_ancienne,
466
+                'id_parent_ancien' => $id_rubrique,
467
+            ],
468
+            'data' => $champs
469
+        ]
470
+    );
471
+
472
+    // Notifications
473
+    if ($notifications = charger_fonction('notifications', 'inc')) {
474
+        $notifications(
475
+            "instituer$objet",
476
+            $id,
477
+            ['statut' => $statut, 'statut_ancien' => $statut_ancien, 'date' => $date, 'date_ancienne' => $date_ancienne]
478
+        );
479
+    }
480
+
481
+    return ''; // pas d'erreur
482 482
 }
483 483
 
484 484
 /**
@@ -493,51 +493,51 @@  discard block
 block discarded – undo
493 493
  * @return void
494 494
  */
495 495
 function objet_editer_heritage($objet, $id, $id_rubrique, $statut, $champs, $cond = true) {
496
-	$table_sql = table_objet_sql($objet);
497
-	$trouver_table = charger_fonction('trouver_table', 'base');
498
-	$desc = $trouver_table($table_sql);
499
-
500
-	// Si on deplace l'objet
501
-	// changer aussi son secteur et sa langue (si heritee)
502
-	if (isset($champs['id_rubrique'])) {
503
-		$row_rub = sql_fetsel('id_secteur, lang', 'spip_rubriques', 'id_rubrique=' . sql_quote($champs['id_rubrique']));
504
-		$langue = $row_rub['lang'];
505
-
506
-		if (isset($desc['field']['id_secteur'])) {
507
-			$champs['id_secteur'] = $row_rub['id_secteur'];
508
-		}
509
-
510
-		if (isset($desc['field']['lang']) and isset($desc['field']['langue_choisie'])) {
511
-			if (
512
-				sql_fetsel(
513
-					'1',
514
-					$table_sql,
515
-					id_table_objet($objet) . '=' . intval($id) . " AND langue_choisie<>'oui' AND lang<>" . sql_quote($langue)
516
-				)
517
-			) {
518
-				$champs['lang'] = $langue;
519
-			}
520
-		}
521
-	}
522
-
523
-	if (!$champs) {
524
-		return;
525
-	}
526
-	sql_updateq($table_sql, $champs, id_table_objet($objet) . '=' . intval($id));
527
-
528
-	// Changer le statut des rubriques concernees
529
-	if ($cond) {
530
-		include_spip('inc/rubriques');
531
-		//$postdate = ($GLOBALS['meta']["post_dates"] == "non" AND isset($champs['date']) AND (strtotime($champs['date']) < time()))?$champs['date']:false;
532
-		$postdate = false;
533
-		// On rajoute les infos de l'objet
534
-		$infos = [
535
-			'objet' => $objet,
536
-			'id_objet' => $id,
537
-			'statut_ancien' => $statut,
538
-		];
539
-		calculer_rubriques_if($id_rubrique, $champs, $infos, $postdate);
540
-	}
496
+    $table_sql = table_objet_sql($objet);
497
+    $trouver_table = charger_fonction('trouver_table', 'base');
498
+    $desc = $trouver_table($table_sql);
499
+
500
+    // Si on deplace l'objet
501
+    // changer aussi son secteur et sa langue (si heritee)
502
+    if (isset($champs['id_rubrique'])) {
503
+        $row_rub = sql_fetsel('id_secteur, lang', 'spip_rubriques', 'id_rubrique=' . sql_quote($champs['id_rubrique']));
504
+        $langue = $row_rub['lang'];
505
+
506
+        if (isset($desc['field']['id_secteur'])) {
507
+            $champs['id_secteur'] = $row_rub['id_secteur'];
508
+        }
509
+
510
+        if (isset($desc['field']['lang']) and isset($desc['field']['langue_choisie'])) {
511
+            if (
512
+                sql_fetsel(
513
+                    '1',
514
+                    $table_sql,
515
+                    id_table_objet($objet) . '=' . intval($id) . " AND langue_choisie<>'oui' AND lang<>" . sql_quote($langue)
516
+                )
517
+            ) {
518
+                $champs['lang'] = $langue;
519
+            }
520
+        }
521
+    }
522
+
523
+    if (!$champs) {
524
+        return;
525
+    }
526
+    sql_updateq($table_sql, $champs, id_table_objet($objet) . '=' . intval($id));
527
+
528
+    // Changer le statut des rubriques concernees
529
+    if ($cond) {
530
+        include_spip('inc/rubriques');
531
+        //$postdate = ($GLOBALS['meta']["post_dates"] == "non" AND isset($champs['date']) AND (strtotime($champs['date']) < time()))?$champs['date']:false;
532
+        $postdate = false;
533
+        // On rajoute les infos de l'objet
534
+        $infos = [
535
+            'objet' => $objet,
536
+            'id_objet' => $id,
537
+            'statut_ancien' => $statut,
538
+        ];
539
+        calculer_rubriques_if($id_rubrique, $champs, $infos, $postdate);
540
+    }
541 541
 }
542 542
 
543 543
 
@@ -566,75 +566,75 @@  discard block
 block discarded – undo
566 566
  *     string|int : valeur du champ demande pour l'objet demande
567 567
  */
568 568
 function objet_lire($objet, $valeur_id, $options = []) {
569
-	if (($t = objet_type($objet)) !== $objet) {
570
-		spip_log("objet_lire: appel avec type $objet invalide au lieu de $t", 'editer' . _LOG_INFO_IMPORTANTE);
571
-		$objet = $t;
572
-	}
573
-
574
-	// tableau du cache des descriptions et des id d'objet (au sens id_xxx).
575
-	// Les tableaux sont toujours indexés par le trio [objet][cle][valeur_cle]
576
-	static $descriptions = [];
577
-
578
-	// On détermine le nom du champ id de la table.
579
-	include_spip('base/objets');
580
-	$primary = id_table_objet($objet);
581
-
582
-	// On détermine l'id à utiliser.
583
-	$champ_id = (!empty($options['champ_id']) ? $options['champ_id'] : $primary);
584
-
585
-	// Si l'objet n'a pas encore été stocké, il faut récupérer sa description complète.
586
-	if (
587
-		!isset($descriptions[$objet][$champ_id][$valeur_id])
588
-		or (isset($options['force']) and $options['force'])
589
-	) {
590
-		// Il est possible pour un type d'objet de fournir une fonction de lecture de tous les champs d'un objet.
591
-		if (
592
-			include_spip('action/editer_' . $objet)
593
-			and function_exists($lire = "{$objet}_lire_champs")
594
-		) {
595
-			$valeurs = $lire($objet, $valeur_id, $champ_id);
596
-		} else {
597
-			// On récupère la table SQL à partir du type d'objet.
598
-			$table = table_objet_sql($objet);
599
-
600
-			// La condition est appliquée sur le champ désigné par l'utilisateur.
601
-			$where = [
602
-				$champ_id . '=' . sql_quote($valeur_id)
603
-			];
604
-
605
-			// Acquisition de tous les champs de l'objet : si l'accès SQL retourne une erreur on renvoie un tableau vide.
606
-			$valeurs = sql_fetsel('*', $table, $where);
607
-		}
608
-
609
-		if (!$valeurs) {
610
-			$valeurs = false;
611
-		}
612
-
613
-		$descriptions[$objet][$champ_id][$valeur_id] = $valeurs;
614
-
615
-		if ($champ_id !== $primary and isset($valeurs[$primary])) {
616
-			$descriptions[$objet][$primary][$valeurs[$primary]] = $valeurs;
617
-			$descriptions[$objet][$champ_id][$valeur_id] = &$descriptions[$objet][$primary][$valeurs[$primary]];
618
-		}
619
-	}
620
-
621
-	$retour = $descriptions[$objet][$champ_id][$valeur_id];
622
-
623
-	// On ne retourne maintenant que les champs demandés.
624
-	// - on détermine les informations à renvoyer.
625
-	if ($retour and !empty($options['champs'])) {
626
-		$champs = $options['champs'];
627
-		// Extraction des seules informations demandées.
628
-		// -- si on demande une information unique on renvoie la valeur simple, sinon on renvoie un tableau.
629
-		// -- si une information n'est pas un champ valide elle n'est pas renvoyée sans renvoyer d'erreur.
630
-		if (is_array($champs)) {
631
-			// Tableau des informations valides
632
-			$retour = array_intersect_key($retour, array_flip($champs));
633
-		} else {
634
-			// Valeur unique demandée.
635
-			$retour = ($retour[$champs] ?? false);
636
-		}
637
-	}
638
-
639
-	return $retour;
569
+    if (($t = objet_type($objet)) !== $objet) {
570
+        spip_log("objet_lire: appel avec type $objet invalide au lieu de $t", 'editer' . _LOG_INFO_IMPORTANTE);
571
+        $objet = $t;
572
+    }
573
+
574
+    // tableau du cache des descriptions et des id d'objet (au sens id_xxx).
575
+    // Les tableaux sont toujours indexés par le trio [objet][cle][valeur_cle]
576
+    static $descriptions = [];
577
+
578
+    // On détermine le nom du champ id de la table.
579
+    include_spip('base/objets');
580
+    $primary = id_table_objet($objet);
581
+
582
+    // On détermine l'id à utiliser.
583
+    $champ_id = (!empty($options['champ_id']) ? $options['champ_id'] : $primary);
584
+
585
+    // Si l'objet n'a pas encore été stocké, il faut récupérer sa description complète.
586
+    if (
587
+        !isset($descriptions[$objet][$champ_id][$valeur_id])
588
+        or (isset($options['force']) and $options['force'])
589
+    ) {
590
+        // Il est possible pour un type d'objet de fournir une fonction de lecture de tous les champs d'un objet.
591
+        if (
592
+            include_spip('action/editer_' . $objet)
593
+            and function_exists($lire = "{$objet}_lire_champs")
594
+        ) {
595
+            $valeurs = $lire($objet, $valeur_id, $champ_id);
596
+        } else {
597
+            // On récupère la table SQL à partir du type d'objet.
598
+            $table = table_objet_sql($objet);
599
+
600
+            // La condition est appliquée sur le champ désigné par l'utilisateur.
601
+            $where = [
602
+                $champ_id . '=' . sql_quote($valeur_id)
603
+            ];
604
+
605
+            // Acquisition de tous les champs de l'objet : si l'accès SQL retourne une erreur on renvoie un tableau vide.
606
+            $valeurs = sql_fetsel('*', $table, $where);
607
+        }
608
+
609
+        if (!$valeurs) {
610
+            $valeurs = false;
611
+        }
612
+
613
+        $descriptions[$objet][$champ_id][$valeur_id] = $valeurs;
614
+
615
+        if ($champ_id !== $primary and isset($valeurs[$primary])) {
616
+            $descriptions[$objet][$primary][$valeurs[$primary]] = $valeurs;
617
+            $descriptions[$objet][$champ_id][$valeur_id] = &$descriptions[$objet][$primary][$valeurs[$primary]];
618
+        }
619
+    }
620
+
621
+    $retour = $descriptions[$objet][$champ_id][$valeur_id];
622
+
623
+    // On ne retourne maintenant que les champs demandés.
624
+    // - on détermine les informations à renvoyer.
625
+    if ($retour and !empty($options['champs'])) {
626
+        $champs = $options['champs'];
627
+        // Extraction des seules informations demandées.
628
+        // -- si on demande une information unique on renvoie la valeur simple, sinon on renvoie un tableau.
629
+        // -- si une information n'est pas un champ valide elle n'est pas renvoyée sans renvoyer d'erreur.
630
+        if (is_array($champs)) {
631
+            // Tableau des informations valides
632
+            $retour = array_intersect_key($retour, array_flip($champs));
633
+        } else {
634
+            // Valeur unique demandée.
635
+            $retour = ($retour[$champs] ?? false);
636
+        }
637
+    }
638
+
639
+    return $retour;
640 640
 }
Please login to merge, or discard this patch.
ecrire/inc/flock.php 1 patch
Indentation   +407 added lines, -407 removed lines patch added patch discarded remove patch
@@ -17,12 +17,12 @@  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
 if (!defined('_TEST_FILE_EXISTS')) {
24
-	/** Permettre d'éviter des tests file_exists sur certains hébergeurs */
25
-	define('_TEST_FILE_EXISTS', preg_match(',(online|free)[.]fr$,', $_ENV['HTTP_HOST'] ?? ''));
24
+    /** Permettre d'éviter des tests file_exists sur certains hébergeurs */
25
+    define('_TEST_FILE_EXISTS', preg_match(',(online|free)[.]fr$,', $_ENV['HTTP_HOST'] ?? ''));
26 26
 }
27 27
 
28 28
 #define('_SPIP_LOCK_MODE',0); // ne pas utiliser de lock (deconseille)
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
 #define('_SPIP_LOCK_MODE',2); // utiliser le nfslock de spip
31 31
 
32 32
 if (_SPIP_LOCK_MODE == 2) {
33
-	include_spip('inc/nfslock');
33
+    include_spip('inc/nfslock');
34 34
 }
35 35
 
36 36
 $GLOBALS['liste_verrous'] = [];
@@ -53,24 +53,24 @@  discard block
 block discarded – undo
53 53
  *     Ressource sur le fichier ouvert, sinon false.
54 54
  **/
55 55
 function spip_fopen_lock($fichier, $mode, $verrou) {
56
-	if (_SPIP_LOCK_MODE == 1) {
57
-		if ($fl = @fopen($fichier, $mode)) {
58
-			// verrou
59
-			@flock($fl, $verrou);
60
-		}
61
-
62
-		return $fl;
63
-	} elseif (_SPIP_LOCK_MODE == 2) {
64
-		if (($verrou = spip_nfslock($fichier)) && ($fl = @fopen($fichier, $mode))) {
65
-			$GLOBALS['liste_verrous'][$fl] = [$fichier, $verrou];
66
-
67
-			return $fl;
68
-		} else {
69
-			return false;
70
-		}
71
-	}
72
-
73
-	return @fopen($fichier, $mode);
56
+    if (_SPIP_LOCK_MODE == 1) {
57
+        if ($fl = @fopen($fichier, $mode)) {
58
+            // verrou
59
+            @flock($fl, $verrou);
60
+        }
61
+
62
+        return $fl;
63
+    } elseif (_SPIP_LOCK_MODE == 2) {
64
+        if (($verrou = spip_nfslock($fichier)) && ($fl = @fopen($fichier, $mode))) {
65
+            $GLOBALS['liste_verrous'][$fl] = [$fichier, $verrou];
66
+
67
+            return $fl;
68
+        } else {
69
+            return false;
70
+        }
71
+    }
72
+
73
+    return @fopen($fichier, $mode);
74 74
 }
75 75
 
76 76
 /**
@@ -85,14 +85,14 @@  discard block
 block discarded – undo
85 85
  *     true si succès, false sinon.
86 86
  **/
87 87
 function spip_fclose_unlock($handle) {
88
-	if (_SPIP_LOCK_MODE == 1) {
89
-		@flock($handle, LOCK_UN);
90
-	} elseif (_SPIP_LOCK_MODE == 2) {
91
-		spip_nfsunlock(reset($GLOBALS['liste_verrous'][$handle]), end($GLOBALS['liste_verrous'][$handle]));
92
-		unset($GLOBALS['liste_verrous'][$handle]);
93
-	}
94
-
95
-	return @fclose($handle);
88
+    if (_SPIP_LOCK_MODE == 1) {
89
+        @flock($handle, LOCK_UN);
90
+    } elseif (_SPIP_LOCK_MODE == 2) {
91
+        spip_nfsunlock(reset($GLOBALS['liste_verrous'][$handle]), end($GLOBALS['liste_verrous'][$handle]));
92
+        unset($GLOBALS['liste_verrous'][$handle]);
93
+    }
94
+
95
+    return @fclose($handle);
96 96
 }
97 97
 
98 98
 
@@ -106,23 +106,23 @@  discard block
 block discarded – undo
106 106
  *     Contenu du fichier
107 107
  **/
108 108
 function spip_file_get_contents($fichier) {
109
-	if (substr($fichier, -3) != '.gz') {
110
-		if (function_exists('file_get_contents')) {
111
-			// quand on est sous windows on ne sait pas si file_get_contents marche
112
-			// on essaye : si ca retourne du contenu alors c'est bon
113
-			// sinon on fait un file() pour avoir le coeur net
114
-			$contenu = @file_get_contents($fichier);
115
-			if (!$contenu and _OS_SERVEUR == 'windows') {
116
-				$contenu = @file($fichier);
117
-			}
118
-		} else {
119
-			$contenu = @file($fichier);
120
-		}
121
-	} else {
122
-		$contenu = @gzfile($fichier);
123
-	}
124
-
125
-	return is_array($contenu) ? join('', $contenu) : (string)$contenu;
109
+    if (substr($fichier, -3) != '.gz') {
110
+        if (function_exists('file_get_contents')) {
111
+            // quand on est sous windows on ne sait pas si file_get_contents marche
112
+            // on essaye : si ca retourne du contenu alors c'est bon
113
+            // sinon on fait un file() pour avoir le coeur net
114
+            $contenu = @file_get_contents($fichier);
115
+            if (!$contenu and _OS_SERVEUR == 'windows') {
116
+                $contenu = @file($fichier);
117
+            }
118
+        } else {
119
+            $contenu = @file($fichier);
120
+        }
121
+    } else {
122
+        $contenu = @gzfile($fichier);
123
+    }
124
+
125
+    return is_array($contenu) ? join('', $contenu) : (string)$contenu;
126 126
 }
127 127
 
128 128
 
@@ -147,48 +147,48 @@  discard block
 block discarded – undo
147 147
  *     true si l'opération a réussie, false sinon.
148 148
  **/
149 149
 function lire_fichier($fichier, &$contenu, $options = []) {
150
-	$contenu = '';
151
-	// inutile car si le fichier n'existe pas, le lock va renvoyer false juste apres
152
-	// economisons donc les acces disque, sauf chez free qui rale pour un rien
153
-	if (_TEST_FILE_EXISTS and !@file_exists($fichier)) {
154
-		return false;
155
-	}
156
-
157
-	#spip_timer('lire_fichier');
158
-
159
-	// pas de @ sur spip_fopen_lock qui est silencieux de toute facon
160
-	if ($fl = spip_fopen_lock($fichier, 'r', LOCK_SH)) {
161
-		// lire le fichier avant tout
162
-		$contenu = spip_file_get_contents($fichier);
163
-
164
-		// le fichier a-t-il ete supprime par le locker ?
165
-		// on ne verifie que si la tentative de lecture a echoue
166
-		// pour discriminer un contenu vide d'un fichier absent
167
-		// et eviter un acces disque
168
-		if (!$contenu and !@file_exists($fichier)) {
169
-			spip_fclose_unlock($fl);
170
-
171
-			return false;
172
-		}
173
-
174
-		// liberer le verrou
175
-		spip_fclose_unlock($fl);
176
-
177
-		// Verifications
178
-		$ok = true;
179
-		if (isset($options['phpcheck']) and $options['phpcheck'] == 'oui') {
180
-			$ok &= (preg_match(",[?]>\n?$,", $contenu));
181
-		}
182
-
183
-		#spip_log("$fread $fichier ".spip_timer('lire_fichier'));
184
-		if (!$ok) {
185
-			spip_log("echec lecture $fichier");
186
-		}
187
-
188
-		return $ok;
189
-	}
190
-
191
-	return false;
150
+    $contenu = '';
151
+    // inutile car si le fichier n'existe pas, le lock va renvoyer false juste apres
152
+    // economisons donc les acces disque, sauf chez free qui rale pour un rien
153
+    if (_TEST_FILE_EXISTS and !@file_exists($fichier)) {
154
+        return false;
155
+    }
156
+
157
+    #spip_timer('lire_fichier');
158
+
159
+    // pas de @ sur spip_fopen_lock qui est silencieux de toute facon
160
+    if ($fl = spip_fopen_lock($fichier, 'r', LOCK_SH)) {
161
+        // lire le fichier avant tout
162
+        $contenu = spip_file_get_contents($fichier);
163
+
164
+        // le fichier a-t-il ete supprime par le locker ?
165
+        // on ne verifie que si la tentative de lecture a echoue
166
+        // pour discriminer un contenu vide d'un fichier absent
167
+        // et eviter un acces disque
168
+        if (!$contenu and !@file_exists($fichier)) {
169
+            spip_fclose_unlock($fl);
170
+
171
+            return false;
172
+        }
173
+
174
+        // liberer le verrou
175
+        spip_fclose_unlock($fl);
176
+
177
+        // Verifications
178
+        $ok = true;
179
+        if (isset($options['phpcheck']) and $options['phpcheck'] == 'oui') {
180
+            $ok &= (preg_match(",[?]>\n?$,", $contenu));
181
+        }
182
+
183
+        #spip_log("$fread $fichier ".spip_timer('lire_fichier'));
184
+        if (!$ok) {
185
+            spip_log("echec lecture $fichier");
186
+        }
187
+
188
+        return $ok;
189
+    }
190
+
191
+    return false;
192 192
 }
193 193
 
194 194
 
@@ -216,85 +216,85 @@  discard block
 block discarded – undo
216 216
  **/
217 217
 function ecrire_fichier($fichier, $contenu, $ignorer_echec = false, $truncate = true) {
218 218
 
219
-	#spip_timer('ecrire_fichier');
220
-
221
-	// verrouiller le fichier destination
222
-	if ($fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
223
-		// ecrire les donnees, compressees le cas echeant
224
-		// (on ouvre un nouveau pointeur sur le fichier, ce qui a l'avantage
225
-		// de le recreer si le locker qui nous precede l'avait supprime...)
226
-		if (substr($fichier, -3) == '.gz') {
227
-			$contenu = gzencode($contenu);
228
-		}
229
-		// si c'est une ecriture avec troncation , on fait plutot une ecriture complete a cote suivie unlink+rename
230
-		// pour etre sur d'avoir une operation atomique
231
-		// y compris en NFS : http://www.ietf.org/rfc/rfc1094.txt
232
-		// sauf sous wintruc ou ca ne marche pas
233
-		$ok = false;
234
-		if ($truncate and _OS_SERVEUR != 'windows') {
235
-			if (!function_exists('creer_uniqid')) {
236
-				include_spip('inc/acces');
237
-			}
238
-			$id = creer_uniqid();
239
-			// on ouvre un pointeur sur un fichier temporaire en ecriture +raz
240
-			if ($fp2 = spip_fopen_lock("$fichier.$id", 'w', LOCK_EX)) {
241
-				$s = @fputs($fp2, $contenu, $a = strlen($contenu));
242
-				$ok = ($s == $a);
243
-				spip_fclose_unlock($fp2);
244
-				spip_fclose_unlock($fp);
245
-				// unlink direct et pas spip_unlink car on avait deja le verrou
246
-				// a priori pas besoin car rename ecrase la cible
247
-				// @unlink($fichier);
248
-				// le rename aussitot, atomique quand on est pas sous windows
249
-				// au pire on arrive en second en cas de concourance, et le rename echoue
250
-				// --> on a la version de l'autre process qui doit etre identique
251
-				@rename("$fichier.$id", $fichier);
252
-				// precaution en cas d'echec du rename
253
-				if (!_TEST_FILE_EXISTS or @file_exists("$fichier.$id")) {
254
-					@unlink("$fichier.$id");
255
-				}
256
-				if ($ok) {
257
-					$ok = file_exists($fichier);
258
-				}
259
-			} else // echec mais penser a fermer ..
260
-			{
261
-				spip_fclose_unlock($fp);
262
-			}
263
-		}
264
-		// sinon ou si methode precedente a echoueee
265
-		// on se rabat sur la methode ancienne
266
-		if (!$ok) {
267
-			// ici on est en ajout ou sous windows, cas desespere
268
-			if ($truncate) {
269
-				@ftruncate($fp, 0);
270
-			}
271
-			$s = @fputs($fp, $contenu, $a = strlen($contenu));
272
-
273
-			$ok = ($s == $a);
274
-			spip_fclose_unlock($fp);
275
-		}
276
-
277
-		// liberer le verrou et fermer le fichier
278
-		@chmod($fichier, _SPIP_CHMOD & 0666);
279
-		if ($ok) {
280
-			if (strpos($fichier, '.php') !== false) {
281
-				spip_clear_opcode_cache(realpath($fichier));
282
-			}
283
-
284
-			return $ok;
285
-		}
286
-	}
287
-
288
-	if (!$ignorer_echec) {
289
-		include_spip('inc/autoriser');
290
-		if (autoriser('chargerftp')) {
291
-			raler_fichier($fichier);
292
-		}
293
-		spip_unlink($fichier);
294
-	}
295
-	spip_log("Ecriture fichier $fichier impossible", _LOG_INFO_IMPORTANTE);
296
-
297
-	return false;
219
+    #spip_timer('ecrire_fichier');
220
+
221
+    // verrouiller le fichier destination
222
+    if ($fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
223
+        // ecrire les donnees, compressees le cas echeant
224
+        // (on ouvre un nouveau pointeur sur le fichier, ce qui a l'avantage
225
+        // de le recreer si le locker qui nous precede l'avait supprime...)
226
+        if (substr($fichier, -3) == '.gz') {
227
+            $contenu = gzencode($contenu);
228
+        }
229
+        // si c'est une ecriture avec troncation , on fait plutot une ecriture complete a cote suivie unlink+rename
230
+        // pour etre sur d'avoir une operation atomique
231
+        // y compris en NFS : http://www.ietf.org/rfc/rfc1094.txt
232
+        // sauf sous wintruc ou ca ne marche pas
233
+        $ok = false;
234
+        if ($truncate and _OS_SERVEUR != 'windows') {
235
+            if (!function_exists('creer_uniqid')) {
236
+                include_spip('inc/acces');
237
+            }
238
+            $id = creer_uniqid();
239
+            // on ouvre un pointeur sur un fichier temporaire en ecriture +raz
240
+            if ($fp2 = spip_fopen_lock("$fichier.$id", 'w', LOCK_EX)) {
241
+                $s = @fputs($fp2, $contenu, $a = strlen($contenu));
242
+                $ok = ($s == $a);
243
+                spip_fclose_unlock($fp2);
244
+                spip_fclose_unlock($fp);
245
+                // unlink direct et pas spip_unlink car on avait deja le verrou
246
+                // a priori pas besoin car rename ecrase la cible
247
+                // @unlink($fichier);
248
+                // le rename aussitot, atomique quand on est pas sous windows
249
+                // au pire on arrive en second en cas de concourance, et le rename echoue
250
+                // --> on a la version de l'autre process qui doit etre identique
251
+                @rename("$fichier.$id", $fichier);
252
+                // precaution en cas d'echec du rename
253
+                if (!_TEST_FILE_EXISTS or @file_exists("$fichier.$id")) {
254
+                    @unlink("$fichier.$id");
255
+                }
256
+                if ($ok) {
257
+                    $ok = file_exists($fichier);
258
+                }
259
+            } else // echec mais penser a fermer ..
260
+            {
261
+                spip_fclose_unlock($fp);
262
+            }
263
+        }
264
+        // sinon ou si methode precedente a echoueee
265
+        // on se rabat sur la methode ancienne
266
+        if (!$ok) {
267
+            // ici on est en ajout ou sous windows, cas desespere
268
+            if ($truncate) {
269
+                @ftruncate($fp, 0);
270
+            }
271
+            $s = @fputs($fp, $contenu, $a = strlen($contenu));
272
+
273
+            $ok = ($s == $a);
274
+            spip_fclose_unlock($fp);
275
+        }
276
+
277
+        // liberer le verrou et fermer le fichier
278
+        @chmod($fichier, _SPIP_CHMOD & 0666);
279
+        if ($ok) {
280
+            if (strpos($fichier, '.php') !== false) {
281
+                spip_clear_opcode_cache(realpath($fichier));
282
+            }
283
+
284
+            return $ok;
285
+        }
286
+    }
287
+
288
+    if (!$ignorer_echec) {
289
+        include_spip('inc/autoriser');
290
+        if (autoriser('chargerftp')) {
291
+            raler_fichier($fichier);
292
+        }
293
+        spip_unlink($fichier);
294
+    }
295
+    spip_log("Ecriture fichier $fichier impossible", _LOG_INFO_IMPORTANTE);
296
+
297
+    return false;
298 298
 }
299 299
 
300 300
 /**
@@ -314,12 +314,12 @@  discard block
 block discarded – undo
314 314
  *     Écriture avec troncation ?
315 315
  */
316 316
 function ecrire_fichier_securise($fichier, $contenu, $ecrire_quand_meme = false, $truncate = true) {
317
-	if (substr($fichier, -4) !== '.php') {
318
-		spip_log('Erreur de programmation: ' . $fichier . ' doit finir par .php');
319
-	}
320
-	$contenu = '<' . "?php die ('Acces interdit'); ?" . ">\n" . $contenu;
317
+    if (substr($fichier, -4) !== '.php') {
318
+        spip_log('Erreur de programmation: ' . $fichier . ' doit finir par .php');
319
+    }
320
+    $contenu = '<' . "?php die ('Acces interdit'); ?" . ">\n" . $contenu;
321 321
 
322
-	return ecrire_fichier($fichier, $contenu, $ecrire_quand_meme, $truncate);
322
+    return ecrire_fichier($fichier, $contenu, $ecrire_quand_meme, $truncate);
323 323
 }
324 324
 
325 325
 
@@ -330,25 +330,25 @@  discard block
 block discarded – undo
330 330
  * @return bool
331 331
  */
332 332
 function ecrire_fichier_calcule_si_modifie($fichier, $contenu, $force = false, $use_copy = false) {
333
-	$fichier_tmp = $fichier . '.last';
334
-	if (!ecrire_fichier($fichier_tmp, $contenu, true)) {
335
-		return false;
336
-	}
337
-	if (
338
-		$force
339
-		or !file_exists($fichier)
340
-		or md5_file($fichier) != md5_file($fichier_tmp)
341
-	) {
342
-		if ($use_copy) {
343
-			@copy($fichier_tmp, $fichier);
344
-		}
345
-		else {
346
-			@rename($fichier_tmp, $fichier);
347
-		}
348
-		// eviter que PHP ne reserve le vieux timestamp
349
-		clearstatcache(true, $fichier);
350
-	}
351
-	return true;
333
+    $fichier_tmp = $fichier . '.last';
334
+    if (!ecrire_fichier($fichier_tmp, $contenu, true)) {
335
+        return false;
336
+    }
337
+    if (
338
+        $force
339
+        or !file_exists($fichier)
340
+        or md5_file($fichier) != md5_file($fichier_tmp)
341
+    ) {
342
+        if ($use_copy) {
343
+            @copy($fichier_tmp, $fichier);
344
+        }
345
+        else {
346
+            @rename($fichier_tmp, $fichier);
347
+        }
348
+        // eviter que PHP ne reserve le vieux timestamp
349
+        clearstatcache(true, $fichier);
350
+    }
351
+    return true;
352 352
 }
353 353
 
354 354
 
@@ -369,11 +369,11 @@  discard block
 block discarded – undo
369 369
  *     true si l'opération a réussie, false sinon.
370 370
  */
371 371
 function lire_fichier_securise($fichier, &$contenu, $options = []) {
372
-	if ($res = lire_fichier($fichier, $contenu, $options)) {
373
-		$contenu = substr($contenu, strlen('<' . "?php die ('Acces interdit'); ?" . ">\n"));
374
-	}
372
+    if ($res = lire_fichier($fichier, $contenu, $options)) {
373
+        $contenu = substr($contenu, strlen('<' . "?php die ('Acces interdit'); ?" . ">\n"));
374
+    }
375 375
 
376
-	return $res;
376
+    return $res;
377 377
 }
378 378
 
379 379
 /**
@@ -388,25 +388,25 @@  discard block
 block discarded – undo
388 388
  *     Chemin du fichier
389 389
  **/
390 390
 function raler_fichier($fichier) {
391
-	if (!defined('_SPIP_ECRIRE_SCRIPT')) {
392
-		spip_initialisation_suite();
393
-	}
394
-	include_spip('inc/minipres');
395
-	$dir = dirname($fichier);
396
-	http_response_code(401);
397
-	echo minipres(_T('texte_inc_meta_2'), "<h4 style='color: red'>"
398
-		. _T('texte_inc_meta_1', ['fichier' => $fichier])
399
-		. " <a href='"
400
-		. generer_url_ecrire('install', "etape=chmod&test_dir=$dir")
401
-		. "'>"
402
-		. _T('texte_inc_meta_2')
403
-		. '</a> '
404
-		. _T(
405
-			'texte_inc_meta_3',
406
-			['repertoire' => joli_repertoire($dir)]
407
-		)
408
-		. "</h4>\n");
409
-	exit;
391
+    if (!defined('_SPIP_ECRIRE_SCRIPT')) {
392
+        spip_initialisation_suite();
393
+    }
394
+    include_spip('inc/minipres');
395
+    $dir = dirname($fichier);
396
+    http_response_code(401);
397
+    echo minipres(_T('texte_inc_meta_2'), "<h4 style='color: red'>"
398
+        . _T('texte_inc_meta_1', ['fichier' => $fichier])
399
+        . " <a href='"
400
+        . generer_url_ecrire('install', "etape=chmod&test_dir=$dir")
401
+        . "'>"
402
+        . _T('texte_inc_meta_2')
403
+        . '</a> '
404
+        . _T(
405
+            'texte_inc_meta_3',
406
+            ['repertoire' => joli_repertoire($dir)]
407
+        )
408
+        . "</h4>\n");
409
+    exit;
410 410
 }
411 411
 
412 412
 
@@ -421,14 +421,14 @@  discard block
 block discarded – undo
421 421
  *     - true si récent, false sinon
422 422
  */
423 423
 function jeune_fichier($fichier, $n) {
424
-	if (!file_exists($fichier)) {
425
-		return false;
426
-	}
427
-	if (!$c = @filemtime($fichier)) {
428
-		return false;
429
-	}
430
-
431
-	return (time() - $n <= $c);
424
+    if (!file_exists($fichier)) {
425
+        return false;
426
+    }
427
+    if (!$c = @filemtime($fichier)) {
428
+        return false;
429
+    }
430
+
431
+    return (time() - $n <= $c);
432 432
 }
433 433
 
434 434
 /**
@@ -443,22 +443,22 @@  discard block
 block discarded – undo
443 443
  *     - false si on n'arrive pas poser le verrou ou si la suppression échoue
444 444
  */
445 445
 function supprimer_fichier($fichier, $lock = true) {
446
-	if (!@file_exists($fichier)) {
447
-		return true;
448
-	}
449
-
450
-	if ($lock) {
451
-		// verrouiller le fichier destination
452
-		if (!$fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
453
-			return false;
454
-		}
455
-
456
-		// liberer le verrou
457
-		spip_fclose_unlock($fp);
458
-	}
459
-
460
-	// supprimer
461
-	return @unlink($fichier);
446
+    if (!@file_exists($fichier)) {
447
+        return true;
448
+    }
449
+
450
+    if ($lock) {
451
+        // verrouiller le fichier destination
452
+        if (!$fp = spip_fopen_lock($fichier, 'a', LOCK_EX)) {
453
+            return false;
454
+        }
455
+
456
+        // liberer le verrou
457
+        spip_fclose_unlock($fp);
458
+    }
459
+
460
+    // supprimer
461
+    return @unlink($fichier);
462 462
 }
463 463
 
464 464
 /**
@@ -468,12 +468,12 @@  discard block
 block discarded – undo
468 468
  *     Chemin du fichier
469 469
  */
470 470
 function spip_unlink($f) {
471
-	if (!is_dir($f)) {
472
-		supprimer_fichier($f, false);
473
-	} else {
474
-		@unlink("$f/.ok");
475
-		@rmdir($f);
476
-	}
471
+    if (!is_dir($f)) {
472
+        supprimer_fichier($f, false);
473
+    } else {
474
+        @unlink("$f/.ok");
475
+        @rmdir($f);
476
+    }
477 477
 }
478 478
 
479 479
 /**
@@ -487,26 +487,26 @@  discard block
 block discarded – undo
487 487
  *   The absolute path of the PHP file to invalidate.
488 488
  */
489 489
 function spip_clear_opcode_cache($filepath) {
490
-	clearstatcache(true, $filepath);
491
-
492
-	// Zend OPcache
493
-	if (function_exists('opcache_invalidate')) {
494
-		$invalidate = @opcache_invalidate($filepath, true);
495
-		// si l'invalidation a echoue lever un flag
496
-		if (!$invalidate and !defined('_spip_attend_invalidation_opcode_cache')) {
497
-			define('_spip_attend_invalidation_opcode_cache', true);
498
-		}
499
-	} elseif (!defined('_spip_attend_invalidation_opcode_cache')) {
500
-		// n'agira que si opcache est effectivement actif (il semble qu'on a pas toujours la fonction opcache_invalidate)
501
-		define('_spip_attend_invalidation_opcode_cache', true);
502
-	}
503
-	// APC.
504
-	if (function_exists('apc_delete_file')) {
505
-		// apc_delete_file() throws a PHP warning in case the specified file was
506
-		// not compiled yet.
507
-		// @see http://php.net/apc-delete-file
508
-		@apc_delete_file($filepath);
509
-	}
490
+    clearstatcache(true, $filepath);
491
+
492
+    // Zend OPcache
493
+    if (function_exists('opcache_invalidate')) {
494
+        $invalidate = @opcache_invalidate($filepath, true);
495
+        // si l'invalidation a echoue lever un flag
496
+        if (!$invalidate and !defined('_spip_attend_invalidation_opcode_cache')) {
497
+            define('_spip_attend_invalidation_opcode_cache', true);
498
+        }
499
+    } elseif (!defined('_spip_attend_invalidation_opcode_cache')) {
500
+        // n'agira que si opcache est effectivement actif (il semble qu'on a pas toujours la fonction opcache_invalidate)
501
+        define('_spip_attend_invalidation_opcode_cache', true);
502
+    }
503
+    // APC.
504
+    if (function_exists('apc_delete_file')) {
505
+        // apc_delete_file() throws a PHP warning in case the specified file was
506
+        // not compiled yet.
507
+        // @see http://php.net/apc-delete-file
508
+        @apc_delete_file($filepath);
509
+    }
510 510
 }
511 511
 
512 512
 /**
@@ -529,25 +529,25 @@  discard block
 block discarded – undo
529 529
  *
530 530
  */
531 531
 function spip_attend_invalidation_opcode_cache($timestamp = null) {
532
-	if (
533
-		function_exists('opcache_get_configuration')
534
-		and @ini_get('opcache.enable')
535
-		and @ini_get('opcache.validate_timestamps')
536
-		and ($duree = intval(@ini_get('opcache.revalidate_freq')) or $duree = 2)
537
-		and defined('_spip_attend_invalidation_opcode_cache') // des invalidations ont echouees
538
-	) {
539
-		$wait = $duree + 1;
540
-		if ($timestamp) {
541
-			$wait -= (time() - $timestamp);
542
-			if ($wait < 0) {
543
-				$wait = 0;
544
-			}
545
-		}
546
-		spip_log('Probleme de configuration opcache.revalidate_freq ' . $duree . 's : on attend ' . $wait . 's', _LOG_INFO_IMPORTANTE);
547
-		if ($wait) {
548
-			sleep($duree + 1);
549
-		}
550
-	}
532
+    if (
533
+        function_exists('opcache_get_configuration')
534
+        and @ini_get('opcache.enable')
535
+        and @ini_get('opcache.validate_timestamps')
536
+        and ($duree = intval(@ini_get('opcache.revalidate_freq')) or $duree = 2)
537
+        and defined('_spip_attend_invalidation_opcode_cache') // des invalidations ont echouees
538
+    ) {
539
+        $wait = $duree + 1;
540
+        if ($timestamp) {
541
+            $wait -= (time() - $timestamp);
542
+            if ($wait < 0) {
543
+                $wait = 0;
544
+            }
545
+        }
546
+        spip_log('Probleme de configuration opcache.revalidate_freq ' . $duree . 's : on attend ' . $wait . 's', _LOG_INFO_IMPORTANTE);
547
+        if ($wait) {
548
+            sleep($duree + 1);
549
+        }
550
+    }
551 551
 }
552 552
 
553 553
 
@@ -560,26 +560,26 @@  discard block
 block discarded – undo
560 560
  * @return bool Suppression reussie.
561 561
  */
562 562
 function supprimer_repertoire($dir) {
563
-	if (!file_exists($dir)) {
564
-		return true;
565
-	}
566
-	if (!is_dir($dir) || is_link($dir)) {
567
-		return @unlink($dir);
568
-	}
569
-
570
-	foreach (scandir($dir) as $item) {
571
-		if ($item == '.' || $item == '..') {
572
-			continue;
573
-		}
574
-		if (!supprimer_repertoire($dir . '/' . $item)) {
575
-			@chmod($dir . '/' . $item, 0777);
576
-			if (!supprimer_repertoire($dir . '/' . $item)) {
577
-				return false;
578
-			}
579
-		};
580
-	}
581
-
582
-	return @rmdir($dir);
563
+    if (!file_exists($dir)) {
564
+        return true;
565
+    }
566
+    if (!is_dir($dir) || is_link($dir)) {
567
+        return @unlink($dir);
568
+    }
569
+
570
+    foreach (scandir($dir) as $item) {
571
+        if ($item == '.' || $item == '..') {
572
+            continue;
573
+        }
574
+        if (!supprimer_repertoire($dir . '/' . $item)) {
575
+            @chmod($dir . '/' . $item, 0777);
576
+            if (!supprimer_repertoire($dir . '/' . $item)) {
577
+                return false;
578
+            }
579
+        };
580
+    }
581
+
582
+    return @rmdir($dir);
583 583
 }
584 584
 
585 585
 
@@ -608,57 +608,57 @@  discard block
 block discarded – undo
608 608
  *     Chemin du répertoire créé.
609 609
  **/
610 610
 function sous_repertoire($base, $subdir = '', $nobase = false, $tantpis = false) {
611
-	static $dirs = [];
612
-
613
-	$base = str_replace('//', '/', $base);
614
-
615
-	# suppr le dernier caractere si c'est un /
616
-	$base = rtrim($base, '/');
617
-
618
-	if (!strlen($subdir)) {
619
-		$n = strrpos($base, '/');
620
-		if ($n === false) {
621
-			return $nobase ? '' : ($base . '/');
622
-		}
623
-		$subdir = substr($base, $n + 1);
624
-		$base = substr($base, 0, $n + 1);
625
-	} else {
626
-		$base .= '/';
627
-		$subdir = str_replace('/', '', $subdir);
628
-	}
629
-
630
-	$baseaff = $nobase ? '' : $base;
631
-	if (isset($dirs[$base . $subdir])) {
632
-		return $baseaff . $dirs[$base . $subdir];
633
-	}
634
-
635
-	$path = $base . $subdir; # $path = 'IMG/distant/pdf' ou 'IMG/distant_pdf'
636
-
637
-	if (file_exists("$path/.ok")) {
638
-		return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
639
-	}
640
-
641
-	@mkdir($path, _SPIP_CHMOD);
642
-	@chmod($path, _SPIP_CHMOD);
643
-
644
-	if (is_dir($path) && is_writable($path)) {
645
-		@touch("$path/.ok");
646
-		spip_log("creation $base$subdir/");
647
-
648
-		return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
649
-	}
650
-
651
-	// en cas d'echec c'est peut etre tout simplement que le disque est plein :
652
-	// l'inode du fichier dir_test existe, mais impossible d'y mettre du contenu
653
-	spip_log("echec creation $base{$subdir}");
654
-	if ($tantpis) {
655
-		return '';
656
-	}
657
-	if (!_DIR_RESTREINT) {
658
-		$base = preg_replace(',^' . _DIR_RACINE . ',', '', $base);
659
-	}
660
-	$base .= $subdir;
661
-	raler_fichier($base . '/.ok');
611
+    static $dirs = [];
612
+
613
+    $base = str_replace('//', '/', $base);
614
+
615
+    # suppr le dernier caractere si c'est un /
616
+    $base = rtrim($base, '/');
617
+
618
+    if (!strlen($subdir)) {
619
+        $n = strrpos($base, '/');
620
+        if ($n === false) {
621
+            return $nobase ? '' : ($base . '/');
622
+        }
623
+        $subdir = substr($base, $n + 1);
624
+        $base = substr($base, 0, $n + 1);
625
+    } else {
626
+        $base .= '/';
627
+        $subdir = str_replace('/', '', $subdir);
628
+    }
629
+
630
+    $baseaff = $nobase ? '' : $base;
631
+    if (isset($dirs[$base . $subdir])) {
632
+        return $baseaff . $dirs[$base . $subdir];
633
+    }
634
+
635
+    $path = $base . $subdir; # $path = 'IMG/distant/pdf' ou 'IMG/distant_pdf'
636
+
637
+    if (file_exists("$path/.ok")) {
638
+        return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
639
+    }
640
+
641
+    @mkdir($path, _SPIP_CHMOD);
642
+    @chmod($path, _SPIP_CHMOD);
643
+
644
+    if (is_dir($path) && is_writable($path)) {
645
+        @touch("$path/.ok");
646
+        spip_log("creation $base$subdir/");
647
+
648
+        return $baseaff . ($dirs[$base . $subdir] = "$subdir/");
649
+    }
650
+
651
+    // en cas d'echec c'est peut etre tout simplement que le disque est plein :
652
+    // l'inode du fichier dir_test existe, mais impossible d'y mettre du contenu
653
+    spip_log("echec creation $base{$subdir}");
654
+    if ($tantpis) {
655
+        return '';
656
+    }
657
+    if (!_DIR_RESTREINT) {
658
+        $base = preg_replace(',^' . _DIR_RACINE . ',', '', $base);
659
+    }
660
+    $base .= $subdir;
661
+    raler_fichier($base . '/.ok');
662 662
 }
663 663
 
664 664
 
@@ -691,56 +691,56 @@  discard block
 block discarded – undo
691 691
  *     Chemins des fichiers trouvés.
692 692
  **/
693 693
 function preg_files($dir, $pattern = -1 /* AUTO */, $maxfiles = 10000, $recurs = []) {
694
-	$nbfiles = 0;
695
-	if ($pattern == -1) {
696
-		$pattern = '';
697
-	}
698
-	$fichiers = [];
699
-	// revenir au repertoire racine si on a recu dossier/truc
700
-	// pour regarder dossier/truc/ ne pas oublier le / final
701
-	$dir = preg_replace(',/[^/]*$,', '', $dir);
702
-	if ($dir == '') {
703
-		$dir = '.';
704
-	}
705
-
706
-	if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
707
-		while (($f = readdir($d)) !== false && ($nbfiles < $maxfiles)) {
708
-			if (
709
-				$f[0] != '.' # ignorer . .. .svn etc
710
-				and $f != 'CVS'
711
-				and $f != 'remove.txt'
712
-				and is_readable($f = "$dir/$f")
713
-			) {
714
-				if (is_file($f)) {
715
-					if (!$pattern or preg_match(";$pattern;iS", $f)) {
716
-						$fichiers[] = $f;
717
-						$nbfiles++;
718
-					}
719
-				} else {
720
-					if (is_dir($f) and is_array($recurs)) {
721
-						$rp = @realpath($f);
722
-						if (!is_string($rp) or !strlen($rp)) {
723
-							$rp = $f;
724
-						} # realpath n'est peut etre pas autorise
725
-						if (!isset($recurs[$rp])) {
726
-							$recurs[$rp] = true;
727
-							$beginning = $fichiers;
728
-							$end = preg_files(
729
-								"$f/",
730
-								$pattern,
731
-								$maxfiles - $nbfiles,
732
-								$recurs
733
-							);
734
-							$fichiers = array_merge((array)$beginning, (array)$end);
735
-							$nbfiles = count($fichiers);
736
-						}
737
-					}
738
-				}
739
-			}
740
-		}
741
-		closedir($d);
742
-	}
743
-	sort($fichiers);
744
-
745
-	return $fichiers;
694
+    $nbfiles = 0;
695
+    if ($pattern == -1) {
696
+        $pattern = '';
697
+    }
698
+    $fichiers = [];
699
+    // revenir au repertoire racine si on a recu dossier/truc
700
+    // pour regarder dossier/truc/ ne pas oublier le / final
701
+    $dir = preg_replace(',/[^/]*$,', '', $dir);
702
+    if ($dir == '') {
703
+        $dir = '.';
704
+    }
705
+
706
+    if (@is_dir($dir) and is_readable($dir) and $d = opendir($dir)) {
707
+        while (($f = readdir($d)) !== false && ($nbfiles < $maxfiles)) {
708
+            if (
709
+                $f[0] != '.' # ignorer . .. .svn etc
710
+                and $f != 'CVS'
711
+                and $f != 'remove.txt'
712
+                and is_readable($f = "$dir/$f")
713
+            ) {
714
+                if (is_file($f)) {
715
+                    if (!$pattern or preg_match(";$pattern;iS", $f)) {
716
+                        $fichiers[] = $f;
717
+                        $nbfiles++;
718
+                    }
719
+                } else {
720
+                    if (is_dir($f) and is_array($recurs)) {
721
+                        $rp = @realpath($f);
722
+                        if (!is_string($rp) or !strlen($rp)) {
723
+                            $rp = $f;
724
+                        } # realpath n'est peut etre pas autorise
725
+                        if (!isset($recurs[$rp])) {
726
+                            $recurs[$rp] = true;
727
+                            $beginning = $fichiers;
728
+                            $end = preg_files(
729
+                                "$f/",
730
+                                $pattern,
731
+                                $maxfiles - $nbfiles,
732
+                                $recurs
733
+                            );
734
+                            $fichiers = array_merge((array)$beginning, (array)$end);
735
+                            $nbfiles = count($fichiers);
736
+                        }
737
+                    }
738
+                }
739
+            }
740
+        }
741
+        closedir($d);
742
+    }
743
+    sort($fichiers);
744
+
745
+    return $fichiers;
746 746
 }
Please login to merge, or discard this patch.
ecrire/inc/filtres_alertes.php 1 patch
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  **/
19 19
 
20 20
 if (!defined('_ECRIRE_INC_VERSION')) {
21
-	return;
21
+    return;
22 22
 }
23 23
 
24 24
 /**
@@ -43,22 +43,22 @@  discard block
 block discarded – undo
43 43
  *     Pile complétée par le code à générer
44 44
  */
45 45
 function balise_ALERTE_MESSAGE_dist($p) {
46
-	$_texte = interprete_argument_balise(1, $p);
47
-	$_titre = interprete_argument_balise(2, $p);
48
-	$_class = interprete_argument_balise(3, $p);
49
-	$_role  = interprete_argument_balise(4, $p);
50
-	$_id    = interprete_argument_balise(5, $p);
51
-	$_texte = ($_texte ?: "''");
52
-	$_titre = ($_titre ? ", $_titre" : ', null');
53
-	$_class = ($_class ? ", $_class" : ', null');
54
-	$_role  = ($_role  ? ", $_role"  : ', null');
55
-	$_id    = ($_id    ? ", $_id"    : ', null');
46
+    $_texte = interprete_argument_balise(1, $p);
47
+    $_titre = interprete_argument_balise(2, $p);
48
+    $_class = interprete_argument_balise(3, $p);
49
+    $_role  = interprete_argument_balise(4, $p);
50
+    $_id    = interprete_argument_balise(5, $p);
51
+    $_texte = ($_texte ?: "''");
52
+    $_titre = ($_titre ? ", $_titre" : ', null');
53
+    $_class = ($_class ? ", $_class" : ', null');
54
+    $_role  = ($_role  ? ", $_role"  : ', null');
55
+    $_id    = ($_id    ? ", $_id"    : ', null');
56 56
 
57
-	$f = chercher_filtre('message_alerte');
58
-	$p->code = "$f($_texte$_titre$_class$_role$_id)";
59
-	$p->interdire_scripts = false;
57
+    $f = chercher_filtre('message_alerte');
58
+    $p->code = "$f($_texte$_titre$_class$_role$_id)";
59
+    $p->interdire_scripts = false;
60 60
 
61
-	return $p;
61
+    return $p;
62 62
 }
63 63
 
64 64
 /**
@@ -86,20 +86,20 @@  discard block
 block discarded – undo
86 86
  *     Pile complétée par le code à générer
87 87
  */
88 88
 function balise_ALERTE_OUVRIR_dist($p) {
89
-	$_titre = interprete_argument_balise(1, $p);
90
-	$_class = interprete_argument_balise(2, $p);
91
-	$_role  = interprete_argument_balise(3, $p);
92
-	$_id    = interprete_argument_balise(4, $p);
93
-	$_titre = ($_titre ? "$_titre"   : 'null');
94
-	$_class = ($_class ? ", $_class" : ', null');
95
-	$_role  = ($_role  ? ", $_role"  : ', null');
96
-	$_id    = ($_id    ? ", $_id"    : ', null');
89
+    $_titre = interprete_argument_balise(1, $p);
90
+    $_class = interprete_argument_balise(2, $p);
91
+    $_role  = interprete_argument_balise(3, $p);
92
+    $_id    = interprete_argument_balise(4, $p);
93
+    $_titre = ($_titre ? "$_titre"   : 'null');
94
+    $_class = ($_class ? ", $_class" : ', null');
95
+    $_role  = ($_role  ? ", $_role"  : ', null');
96
+    $_id    = ($_id    ? ", $_id"    : ', null');
97 97
 
98
-	$f = chercher_filtre('message_alerte_ouvrir');
99
-	$p->code = "$f($_titre$_class$_role$_id)";
100
-	$p->interdire_scripts = false;
98
+    $f = chercher_filtre('message_alerte_ouvrir');
99
+    $p->code = "$f($_titre$_class$_role$_id)";
100
+    $p->interdire_scripts = false;
101 101
 
102
-	return $p;
102
+    return $p;
103 103
 }
104 104
 
105 105
 /**
@@ -121,11 +121,11 @@  discard block
 block discarded – undo
121 121
  *     Pile complétée par le code à générer
122 122
  */
123 123
 function balise_ALERTE_FERMER_dist($p) {
124
-	$f = chercher_filtre('message_alerte_fermer');
125
-	$p->code = "$f()";
126
-	$p->interdire_scripts = false;
124
+    $f = chercher_filtre('message_alerte_fermer');
125
+    $p->code = "$f()";
126
+    $p->interdire_scripts = false;
127 127
 
128
-	return $p;
128
+    return $p;
129 129
 }
130 130
 
131 131
 /**
@@ -160,14 +160,14 @@  discard block
 block discarded – undo
160 160
  */
161 161
 function message_alerte(string $texte, ?string $titre = null, ?string $class = null, ?string $role = null, ?string $id = null): string {
162 162
 
163
-	$message_alerte_ouvrir = chercher_filtre('message_alerte_ouvrir');
164
-	$message_alerte_fermer = chercher_filtre('message_alerte_fermer');
165
-	$message =
166
-		$message_alerte_ouvrir($titre, $class, $role, $id) .
167
-		$texte .
168
-		$message_alerte_fermer();
163
+    $message_alerte_ouvrir = chercher_filtre('message_alerte_ouvrir');
164
+    $message_alerte_fermer = chercher_filtre('message_alerte_fermer');
165
+    $message =
166
+        $message_alerte_ouvrir($titre, $class, $role, $id) .
167
+        $texte .
168
+        $message_alerte_fermer();
169 169
 
170
-	return $message;
170
+    return $message;
171 171
 }
172 172
 
173 173
 /**
@@ -198,56 +198,56 @@  discard block
 block discarded – undo
198 198
  */
199 199
 function message_alerte_ouvrir(?string $titre = null, ?string $class = null, ?string $role = null, ?string $id = null): string {
200 200
 
201
-	$prive = test_espace_prive();
201
+    $prive = test_espace_prive();
202 202
 
203
-	// Valeurs par défaut
204
-	$titre = trim($titre ?? '');
205
-	$role ??= 'alert'; // fallback uniquement si null
206
-	$class ??= 'notice'; // fallback uniquement si null
203
+    // Valeurs par défaut
204
+    $titre = trim($titre ?? '');
205
+    $role ??= 'alert'; // fallback uniquement si null
206
+    $class ??= 'notice'; // fallback uniquement si null
207 207
 
208
-	// Type d'alerte : le chercher dans les classes, nettoyer celles-ci, puis le réinjecter
209
-	$types = [
210
-		'notice',
211
-		'error',
212
-		'success',
213
-		'info',
214
-	];
215
-	$type  = array_intersect(explode(' ', $class), $types);
216
-	$type  = reset($type);
217
-	$class = trim(str_replace($types, '', $class) . " $type");
208
+    // Type d'alerte : le chercher dans les classes, nettoyer celles-ci, puis le réinjecter
209
+    $types = [
210
+        'notice',
211
+        'error',
212
+        'success',
213
+        'info',
214
+    ];
215
+    $type  = array_intersect(explode(' ', $class), $types);
216
+    $type  = reset($type);
217
+    $class = trim(str_replace($types, '', $class) . " $type");
218 218
 
219
-	// Classes
220
-	$class_racine = 'msg-alert';
221
-	$clearfix     = ($prive ? 'clearfix' : '');
222
-	$class_alerte = "$class_racine $class";
223
-	$class_texte  = "{$class_racine}__text $clearfix";
224
-	$class_titre  = "{$class_racine}__heading";
219
+    // Classes
220
+    $class_racine = 'msg-alert';
221
+    $clearfix     = ($prive ? 'clearfix' : '');
222
+    $class_alerte = "$class_racine $class";
223
+    $class_texte  = "{$class_racine}__text $clearfix";
224
+    $class_titre  = "{$class_racine}__heading";
225 225
 
226
-	// Titre : markup
227
-	$titre = trim($titre);
228
-	if (strlen($titre)) {
229
-		include_spip('inc/filtres');
230
-		// Si besoin on encapsule le titre : un h3 dans le privé, un simple div sinon.
231
-		$cherche_tag = ($prive ? '<h' : '<');
232
-		$wrap_tag    = ($prive ? '<h3>' : '<div>');
233
-		if (strpos($titre, $cherche_tag) !== 0) {
234
-			$titre = wrap($titre, $wrap_tag);
235
-		}
236
-		// puis on ajoute la classe
237
-		$titre = ajouter_class($titre, $class_titre);
238
-	}
226
+    // Titre : markup
227
+    $titre = trim($titre);
228
+    if (strlen($titre)) {
229
+        include_spip('inc/filtres');
230
+        // Si besoin on encapsule le titre : un h3 dans le privé, un simple div sinon.
231
+        $cherche_tag = ($prive ? '<h' : '<');
232
+        $wrap_tag    = ($prive ? '<h3>' : '<div>');
233
+        if (strpos($titre, $cherche_tag) !== 0) {
234
+            $titre = wrap($titre, $wrap_tag);
235
+        }
236
+        // puis on ajoute la classe
237
+        $titre = ajouter_class($titre, $class_titre);
238
+    }
239 239
 
240
-	// Attributs
241
-	$attr_role = ($role ? "role=\"$role\"" : '');
242
-	$attr_id   = ($id   ? "id=\"$id\"" : '');
243
-	$attr_data = ($type ? "data-alert=\"$type\"" : '');
240
+    // Attributs
241
+    $attr_role = ($role ? "role=\"$role\"" : '');
242
+    $attr_id   = ($id   ? "id=\"$id\"" : '');
243
+    $attr_data = ($type ? "data-alert=\"$type\"" : '');
244 244
 
245
-	$message =
246
-		"<div class=\"$class_alerte\" $attr_role $attr_id $attr_data>"
247
-			. $titre
248
-			. "<div class=\"$class_texte\">";
245
+    $message =
246
+        "<div class=\"$class_alerte\" $attr_role $attr_id $attr_data>"
247
+            . $titre
248
+            . "<div class=\"$class_texte\">";
249 249
 
250
-	return $message;
250
+    return $message;
251 251
 }
252 252
 
253 253
 /**
@@ -261,5 +261,5 @@  discard block
 block discarded – undo
261 261
  *     HTML de fin de l'alerte
262 262
  */
263 263
 function message_alerte_fermer(): string {
264
-	return '</div></div>';
264
+    return '</div></div>';
265 265
 }
Please login to merge, or discard this patch.
ecrire/inc/recherche_to_array.php 1 patch
Indentation   +267 added lines, -267 removed lines patch added patch discarded remove patch
@@ -11,298 +11,298 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 
18 18
 // methodes sql
19 19
 function inc_recherche_to_array_dist($recherche, $options = []) {
20 20
 
21
-	// options par defaut
22
-	$options = array_merge(
23
-		[
24
-			'score' => true,
25
-			'champs' => false,
26
-			'toutvoir' => false,
27
-			'matches' => false,
28
-			'jointures' => false
29
-		],
30
-		$options
31
-	);
21
+    // options par defaut
22
+    $options = array_merge(
23
+        [
24
+            'score' => true,
25
+            'champs' => false,
26
+            'toutvoir' => false,
27
+            'matches' => false,
28
+            'jointures' => false
29
+        ],
30
+        $options
31
+    );
32 32
 
33
-	include_spip('inc/rechercher');
34
-	include_spip('inc/autoriser');
33
+    include_spip('inc/rechercher');
34
+    include_spip('inc/autoriser');
35 35
 
36
-	$requete = [
37
-		'SELECT' => [],
38
-		'FROM' => [],
39
-		'WHERE' => [],
40
-		'GROUPBY' => [],
41
-		'ORDERBY' => [],
42
-		'LIMIT' => '',
43
-		'HAVING' => []
44
-	];
36
+    $requete = [
37
+        'SELECT' => [],
38
+        'FROM' => [],
39
+        'WHERE' => [],
40
+        'GROUPBY' => [],
41
+        'ORDERBY' => [],
42
+        'LIMIT' => '',
43
+        'HAVING' => []
44
+    ];
45 45
 
46
-	$table = sinon($options['table'], 'article');
47
-	if ($options['champs']) {
48
-		$champs = $options['champs'];
49
-	} else {
50
-		$l = liste_des_champs();
51
-		$champs = $l['article'];
52
-	}
53
-	$serveur = $options['serveur'];
46
+    $table = sinon($options['table'], 'article');
47
+    if ($options['champs']) {
48
+        $champs = $options['champs'];
49
+    } else {
50
+        $l = liste_des_champs();
51
+        $champs = $l['article'];
52
+    }
53
+    $serveur = $options['serveur'];
54 54
 
55
-	[$methode, $q, $preg] = expression_recherche($recherche, $options);
55
+    [$methode, $q, $preg] = expression_recherche($recherche, $options);
56 56
 
57
-	$jointures = $options['jointures']
58
-		? liste_des_jointures()
59
-		: [];
57
+    $jointures = $options['jointures']
58
+        ? liste_des_jointures()
59
+        : [];
60 60
 
61
-	$_id_table = id_table_objet($table);
61
+    $_id_table = id_table_objet($table);
62 62
 
63
-	// c'est un pis-aller : ca a peu de chance de marcher, mais mieux quand meme que en conservant la ','
64
-	// (aka ca marche au moins dans certains cas comme avec spip_formulaires_reponses_champs)
65
-	if (strpos($_id_table, ',') !== false) {
66
-		$_id_table = explode(',', $_id_table);
67
-		$_id_table = reset($_id_table);
68
-	}
63
+    // c'est un pis-aller : ca a peu de chance de marcher, mais mieux quand meme que en conservant la ','
64
+    // (aka ca marche au moins dans certains cas comme avec spip_formulaires_reponses_champs)
65
+    if (strpos($_id_table, ',') !== false) {
66
+        $_id_table = explode(',', $_id_table);
67
+        $_id_table = reset($_id_table);
68
+    }
69 69
 
70
-	$requete['SELECT'][] = 't.' . $_id_table;
71
-	$a = [];
72
-	// Recherche fulltext
73
-	foreach ($champs as $champ => $poids) {
74
-		if (is_array($champ)) {
75
-			spip_log('requetes imbriquees interdites');
76
-		} else {
77
-			if (strpos($champ, '.') === false) {
78
-				$champ = "t.$champ";
79
-			}
80
-			$requete['SELECT'][] = $champ;
81
-			$a[] = $champ . ' ' . $methode . ' ' . $q;
82
-		}
83
-	}
84
-	if ($a) {
85
-		$requete['WHERE'][] = join(' OR ', $a);
86
-	}
87
-	$requete['FROM'][] = table_objet_sql($table) . ' AS t';
70
+    $requete['SELECT'][] = 't.' . $_id_table;
71
+    $a = [];
72
+    // Recherche fulltext
73
+    foreach ($champs as $champ => $poids) {
74
+        if (is_array($champ)) {
75
+            spip_log('requetes imbriquees interdites');
76
+        } else {
77
+            if (strpos($champ, '.') === false) {
78
+                $champ = "t.$champ";
79
+            }
80
+            $requete['SELECT'][] = $champ;
81
+            $a[] = $champ . ' ' . $methode . ' ' . $q;
82
+        }
83
+    }
84
+    if ($a) {
85
+        $requete['WHERE'][] = join(' OR ', $a);
86
+    }
87
+    $requete['FROM'][] = table_objet_sql($table) . ' AS t';
88 88
 
89
-	$results = [];
89
+    $results = [];
90 90
 
91
-	$s = sql_select(
92
-		$requete['SELECT'],
93
-		$requete['FROM'],
94
-		$requete['WHERE'],
95
-		implode(' ', $requete['GROUPBY']),
96
-		$requete['ORDERBY'],
97
-		$requete['LIMIT'],
98
-		$requete['HAVING'],
99
-		$serveur
100
-	);
91
+    $s = sql_select(
92
+        $requete['SELECT'],
93
+        $requete['FROM'],
94
+        $requete['WHERE'],
95
+        implode(' ', $requete['GROUPBY']),
96
+        $requete['ORDERBY'],
97
+        $requete['LIMIT'],
98
+        $requete['HAVING'],
99
+        $serveur
100
+    );
101 101
 
102
-	while (
103
-		$t = sql_fetch($s, $serveur)
104
-		and (!isset($t['score']) or $t['score'] > 0)
105
-	) {
106
-		$id = intval($t[$_id_table]);
102
+    while (
103
+        $t = sql_fetch($s, $serveur)
104
+        and (!isset($t['score']) or $t['score'] > 0)
105
+    ) {
106
+        $id = intval($t[$_id_table]);
107 107
 
108
-		if (
109
-			$options['toutvoir']
110
-			or autoriser('voir', $table, $id)
111
-		) {
112
-			// indiquer les champs concernes
113
-			$champs_vus = [];
114
-			$score = 0;
115
-			$matches = [];
108
+        if (
109
+            $options['toutvoir']
110
+            or autoriser('voir', $table, $id)
111
+        ) {
112
+            // indiquer les champs concernes
113
+            $champs_vus = [];
114
+            $score = 0;
115
+            $matches = [];
116 116
 
117
-			$vu = false;
118
-			foreach ($champs as $champ => $poids) {
119
-				$champ = explode('.', $champ);
120
-				$champ = end($champ);
121
-				// translitteration_rapide uniquement si on est deja en utf-8
122
-				$value = ($GLOBALS['meta']['charset'] == 'utf-8' ? translitteration_rapide($t[$champ]) : translitteration($t[$champ]));
123
-				if (
124
-					$n =
125
-					($options['score'] || $options['matches'])
126
-						? preg_match_all($preg, $value, $regs, PREG_SET_ORDER)
127
-						: preg_match($preg, $value)
128
-				) {
129
-					$vu = true;
117
+            $vu = false;
118
+            foreach ($champs as $champ => $poids) {
119
+                $champ = explode('.', $champ);
120
+                $champ = end($champ);
121
+                // translitteration_rapide uniquement si on est deja en utf-8
122
+                $value = ($GLOBALS['meta']['charset'] == 'utf-8' ? translitteration_rapide($t[$champ]) : translitteration($t[$champ]));
123
+                if (
124
+                    $n =
125
+                    ($options['score'] || $options['matches'])
126
+                        ? preg_match_all($preg, $value, $regs, PREG_SET_ORDER)
127
+                        : preg_match($preg, $value)
128
+                ) {
129
+                    $vu = true;
130 130
 
131
-					if ($options['champs']) {
132
-						$champs_vus[$champ] = $t[$champ];
133
-					}
134
-					if ($options['score']) {
135
-						// compter les points avec un peu de discernement : on pondere par la longueur du match compte en chars
136
-						$score += $poids * strlen(implode('', array_column($regs, 0)));
137
-					}
131
+                    if ($options['champs']) {
132
+                        $champs_vus[$champ] = $t[$champ];
133
+                    }
134
+                    if ($options['score']) {
135
+                        // compter les points avec un peu de discernement : on pondere par la longueur du match compte en chars
136
+                        $score += $poids * strlen(implode('', array_column($regs, 0)));
137
+                    }
138 138
 
139
-					if ($options['matches']) {
140
-						$matches[$champ] = $regs;
141
-					}
139
+                    if ($options['matches']) {
140
+                        $matches[$champ] = $regs;
141
+                    }
142 142
 
143
-					if (
144
-						!$options['champs']
145
-						and !$options['score']
146
-						and !$options['matches']
147
-					) {
148
-						break;
149
-					}
150
-				}
151
-			}
143
+                    if (
144
+                        !$options['champs']
145
+                        and !$options['score']
146
+                        and !$options['matches']
147
+                    ) {
148
+                        break;
149
+                    }
150
+                }
151
+            }
152 152
 
153
-			if ($vu) {
154
-				if (!isset($results)) {
155
-					$results = [];
156
-				}
157
-				$results[$id] = [];
158
-				if ($champs_vus) {
159
-					$results[$id]['champs'] = $champs_vus;
160
-				}
161
-				if ($score) {
162
-					$results[$id]['score'] = $score;
163
-				}
164
-				if ($matches) {
165
-					$results[$id]['matches'] = $matches;
166
-				}
167
-			}
168
-		}
169
-	}
153
+            if ($vu) {
154
+                if (!isset($results)) {
155
+                    $results = [];
156
+                }
157
+                $results[$id] = [];
158
+                if ($champs_vus) {
159
+                    $results[$id]['champs'] = $champs_vus;
160
+                }
161
+                if ($score) {
162
+                    $results[$id]['score'] = $score;
163
+                }
164
+                if ($matches) {
165
+                    $results[$id]['matches'] = $matches;
166
+                }
167
+            }
168
+        }
169
+    }
170 170
 
171 171
 
172
-	// Gerer les donnees associees
173
-	// ici on est un peu naze : pas capables de reconstruire une jointure complexe
174
-	// on ne sait passer que par table de laison en 1 coup
175
-	if (
176
-		isset($jointures[$table])
177
-		and $joints = recherche_en_base(
178
-			$recherche,
179
-			$jointures[$table],
180
-			array_merge($options, ['jointures' => false])
181
-		)
182
-	) {
183
-		include_spip('action/editer_liens');
184
-		$trouver_table = charger_fonction('trouver_table', 'base');
185
-		$cle_depart = id_table_objet($table);
186
-		$table_depart = table_objet($table, $serveur);
187
-		$desc_depart = $trouver_table($table_depart, $serveur);
188
-		$depart_associable = objet_associable($table);
189
-		foreach ($joints as $table_liee => $ids_trouves) {
190
-			// on peut definir une fonction de recherche jointe pour regler les cas particuliers
191
-			if (
192
-				!(
193
-				$rechercher_joints = charger_fonction("rechercher_joints_{$table}_{$table_liee}", 'inc', true)
194
-				or $rechercher_joints = charger_fonction("rechercher_joints_objet_{$table_liee}", 'inc', true)
195
-				or $rechercher_joints = charger_fonction("rechercher_joints_{$table}_objet_lie", 'inc', true)
196
-				)
197
-			) {
198
-				$cle_arrivee = id_table_objet($table_liee);
199
-				$table_arrivee = table_objet($table_liee, $serveur);
200
-				$desc_arrivee = $trouver_table($table_arrivee, $serveur);
201
-				// cas simple : $cle_depart dans la table_liee
202
-				if (isset($desc_arrivee['field'][$cle_depart])) {
203
-					$s = sql_select(
204
-						"$cle_depart, $cle_arrivee",
205
-						$desc_arrivee['table_sql'],
206
-						sql_in($cle_arrivee, array_keys($ids_trouves)),
207
-						'',
208
-						'',
209
-						'',
210
-						'',
211
-						$serveur
212
-					);
213
-				} // cas simple : $cle_arrivee dans la table
214
-				elseif (isset($desc_depart['field'][$cle_arrivee])) {
215
-					$s = sql_select(
216
-						"$cle_depart, $cle_arrivee",
217
-						$desc_depart['table_sql'],
218
-						sql_in($cle_arrivee, array_keys($ids_trouves)),
219
-						'',
220
-						'',
221
-						'',
222
-						'',
223
-						$serveur
224
-					);
225
-				}
226
-				// sinon cherchons une table de liaison
227
-				// cas recherche principale article, objet lie document : passer par spip_documents_liens
228
-				elseif ($l = objet_associable($table_liee)) {
229
-					[$primary, $table_liens] = $l;
230
-					$s = sql_select(
231
-						"id_objet as $cle_depart, $primary as $cle_arrivee",
232
-						$table_liens,
233
-						["objet='$table'", sql_in($primary, array_keys($ids_trouves))],
234
-						'',
235
-						'',
236
-						'',
237
-						'',
238
-						$serveur
239
-					);
240
-				} // cas recherche principale auteur, objet lie article: passer par spip_auteurs_liens
241
-				elseif ($l = $depart_associable) {
242
-					[$primary, $table_liens] = $l;
243
-					$s = sql_select(
244
-						"$primary as $cle_depart, id_objet as $cle_arrivee",
245
-						$table_liens,
246
-						["objet='$table_liee'", sql_in('id_objet', array_keys($ids_trouves))],
247
-						'',
248
-						'',
249
-						'',
250
-						'',
251
-						$serveur
252
-					);
253
-				} // cas table de liaison generique spip_xxx_yyy
254
-				elseif (
255
-					$t = $trouver_table($table_arrivee . '_' . $table_depart, $serveur)
256
-					or $t = $trouver_table($table_depart . '_' . $table_arrivee, $serveur)
257
-				) {
258
-					$s = sql_select(
259
-						"$cle_depart,$cle_arrivee",
260
-						$t['table_sql'],
261
-						sql_in($cle_arrivee, array_keys($ids_trouves)),
262
-						'',
263
-						'',
264
-						'',
265
-						'',
266
-						$serveur
267
-					);
268
-				}
269
-			} else {
270
-				[$cle_depart, $cle_arrivee, $s] = $rechercher_joints(
271
-					$table,
272
-					$table_liee,
273
-					array_keys($ids_trouves),
274
-					$serveur
275
-				);
276
-			}
172
+    // Gerer les donnees associees
173
+    // ici on est un peu naze : pas capables de reconstruire une jointure complexe
174
+    // on ne sait passer que par table de laison en 1 coup
175
+    if (
176
+        isset($jointures[$table])
177
+        and $joints = recherche_en_base(
178
+            $recherche,
179
+            $jointures[$table],
180
+            array_merge($options, ['jointures' => false])
181
+        )
182
+    ) {
183
+        include_spip('action/editer_liens');
184
+        $trouver_table = charger_fonction('trouver_table', 'base');
185
+        $cle_depart = id_table_objet($table);
186
+        $table_depart = table_objet($table, $serveur);
187
+        $desc_depart = $trouver_table($table_depart, $serveur);
188
+        $depart_associable = objet_associable($table);
189
+        foreach ($joints as $table_liee => $ids_trouves) {
190
+            // on peut definir une fonction de recherche jointe pour regler les cas particuliers
191
+            if (
192
+                !(
193
+                $rechercher_joints = charger_fonction("rechercher_joints_{$table}_{$table_liee}", 'inc', true)
194
+                or $rechercher_joints = charger_fonction("rechercher_joints_objet_{$table_liee}", 'inc', true)
195
+                or $rechercher_joints = charger_fonction("rechercher_joints_{$table}_objet_lie", 'inc', true)
196
+                )
197
+            ) {
198
+                $cle_arrivee = id_table_objet($table_liee);
199
+                $table_arrivee = table_objet($table_liee, $serveur);
200
+                $desc_arrivee = $trouver_table($table_arrivee, $serveur);
201
+                // cas simple : $cle_depart dans la table_liee
202
+                if (isset($desc_arrivee['field'][$cle_depart])) {
203
+                    $s = sql_select(
204
+                        "$cle_depart, $cle_arrivee",
205
+                        $desc_arrivee['table_sql'],
206
+                        sql_in($cle_arrivee, array_keys($ids_trouves)),
207
+                        '',
208
+                        '',
209
+                        '',
210
+                        '',
211
+                        $serveur
212
+                    );
213
+                } // cas simple : $cle_arrivee dans la table
214
+                elseif (isset($desc_depart['field'][$cle_arrivee])) {
215
+                    $s = sql_select(
216
+                        "$cle_depart, $cle_arrivee",
217
+                        $desc_depart['table_sql'],
218
+                        sql_in($cle_arrivee, array_keys($ids_trouves)),
219
+                        '',
220
+                        '',
221
+                        '',
222
+                        '',
223
+                        $serveur
224
+                    );
225
+                }
226
+                // sinon cherchons une table de liaison
227
+                // cas recherche principale article, objet lie document : passer par spip_documents_liens
228
+                elseif ($l = objet_associable($table_liee)) {
229
+                    [$primary, $table_liens] = $l;
230
+                    $s = sql_select(
231
+                        "id_objet as $cle_depart, $primary as $cle_arrivee",
232
+                        $table_liens,
233
+                        ["objet='$table'", sql_in($primary, array_keys($ids_trouves))],
234
+                        '',
235
+                        '',
236
+                        '',
237
+                        '',
238
+                        $serveur
239
+                    );
240
+                } // cas recherche principale auteur, objet lie article: passer par spip_auteurs_liens
241
+                elseif ($l = $depart_associable) {
242
+                    [$primary, $table_liens] = $l;
243
+                    $s = sql_select(
244
+                        "$primary as $cle_depart, id_objet as $cle_arrivee",
245
+                        $table_liens,
246
+                        ["objet='$table_liee'", sql_in('id_objet', array_keys($ids_trouves))],
247
+                        '',
248
+                        '',
249
+                        '',
250
+                        '',
251
+                        $serveur
252
+                    );
253
+                } // cas table de liaison generique spip_xxx_yyy
254
+                elseif (
255
+                    $t = $trouver_table($table_arrivee . '_' . $table_depart, $serveur)
256
+                    or $t = $trouver_table($table_depart . '_' . $table_arrivee, $serveur)
257
+                ) {
258
+                    $s = sql_select(
259
+                        "$cle_depart,$cle_arrivee",
260
+                        $t['table_sql'],
261
+                        sql_in($cle_arrivee, array_keys($ids_trouves)),
262
+                        '',
263
+                        '',
264
+                        '',
265
+                        '',
266
+                        $serveur
267
+                    );
268
+                }
269
+            } else {
270
+                [$cle_depart, $cle_arrivee, $s] = $rechercher_joints(
271
+                    $table,
272
+                    $table_liee,
273
+                    array_keys($ids_trouves),
274
+                    $serveur
275
+                );
276
+            }
277 277
 
278
-			while ($t = is_array($s) ? array_shift($s) : sql_fetch($s)) {
279
-				$id = $t[$cle_depart];
280
-				$joint = $ids_trouves[$t[$cle_arrivee]];
281
-				if (!isset($results)) {
282
-					$results = [];
283
-				}
284
-				if (!isset($results[$id])) {
285
-					$results[$id] = [];
286
-				}
287
-				if (isset($joint['score']) and $joint['score']) {
288
-					if (!isset($results[$id]['score'])) {
289
-						$results[$id]['score'] = 0;
290
-					}
291
-					$results[$id]['score'] += $joint['score'];
292
-				}
293
-				if (isset($joint['champs']) and $joint['champs']) {
294
-					foreach ($joint['champs'] as $c => $val) {
295
-						$results[$id]['champs'][$table_liee . '.' . $c] = $val;
296
-					}
297
-				}
298
-				if (isset($joint['matches']) and $joint['matches']) {
299
-					foreach ($joint['matches'] as $c => $val) {
300
-						$results[$id]['matches'][$table_liee . '.' . $c] = $val;
301
-					}
302
-				}
303
-			}
304
-		}
305
-	}
278
+            while ($t = is_array($s) ? array_shift($s) : sql_fetch($s)) {
279
+                $id = $t[$cle_depart];
280
+                $joint = $ids_trouves[$t[$cle_arrivee]];
281
+                if (!isset($results)) {
282
+                    $results = [];
283
+                }
284
+                if (!isset($results[$id])) {
285
+                    $results[$id] = [];
286
+                }
287
+                if (isset($joint['score']) and $joint['score']) {
288
+                    if (!isset($results[$id]['score'])) {
289
+                        $results[$id]['score'] = 0;
290
+                    }
291
+                    $results[$id]['score'] += $joint['score'];
292
+                }
293
+                if (isset($joint['champs']) and $joint['champs']) {
294
+                    foreach ($joint['champs'] as $c => $val) {
295
+                        $results[$id]['champs'][$table_liee . '.' . $c] = $val;
296
+                    }
297
+                }
298
+                if (isset($joint['matches']) and $joint['matches']) {
299
+                    foreach ($joint['matches'] as $c => $val) {
300
+                        $results[$id]['matches'][$table_liee . '.' . $c] = $val;
301
+                    }
302
+                }
303
+            }
304
+        }
305
+    }
306 306
 
307
-	return $results;
307
+    return $results;
308 308
 }
Please login to merge, or discard this patch.