Completed
Push — master ( 89cac1...7b34bc )
by cam
01:10
created
ecrire/action/logout.php 1 patch
Indentation   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  */
18 18
 
19 19
 if (!defined('_ECRIRE_INC_VERSION')) {
20
-	return;
20
+    return;
21 21
 }
22 22
 
23 23
 include_spip('inc/cookie');
@@ -34,70 +34,70 @@  discard block
 block discarded – undo
34 34
  *
35 35
  */
36 36
 function action_logout_dist() {
37
-	$logout = _request('logout');
38
-	$url = securiser_redirect_action(_request('url'));
39
-	// cas particulier, logout dans l'espace public
40
-	if ($logout == 'public' and !$url) {
41
-		$url = url_de_base();
42
-	}
43
-
44
-	// seul le loge peut se deloger (mais id_auteur peut valoir 0 apres une restauration avortee)
45
-	if (isset($GLOBALS['visiteur_session']['id_auteur'])
46
-		and is_numeric($GLOBALS['visiteur_session']['id_auteur'])
47
-		// des sessions anonymes avec id_auteur=0 existent, mais elle n'ont pas de statut : double check
48
-		and isset($GLOBALS['visiteur_session']['statut'])
49
-	) {
50
-
51
-		// il faut un jeton pour fermer la session (eviter les CSRF)
52
-		if (!$jeton = _request('jeton')
53
-			or !verifier_jeton_logout($jeton, $GLOBALS['visiteur_session'])
54
-		) {
55
-			$jeton = generer_jeton_logout($GLOBALS['visiteur_session']);
56
-			$action = generer_url_action("logout", "jeton=$jeton");
57
-			$action = parametre_url($action, 'logout', _request('logout'));
58
-			$action = parametre_url($action, 'url', _request('url'));
59
-			include_spip("inc/minipres");
60
-			include_spip("inc/filtres");
61
-			$texte = bouton_action(_T('spip:icone_deconnecter'), $action);
62
-			$texte = "<div class='boutons'>$texte</div>";
63
-			$texte .= '<script type="text/javascript">document.write("<style>body{visibility:hidden;}</style>");window.document.forms[0].submit();</script>';
64
-			$res = minipres(_T('spip:icone_deconnecter'), $texte, '', true);
65
-			echo $res;
66
-
67
-			return;
68
-		}
69
-
70
-		include_spip('inc/auth');
71
-		auth_trace($GLOBALS['visiteur_session'], '0000-00-00 00:00:00');
72
-		// le logout explicite vaut destruction de toutes les sessions
73
-		if (isset($_COOKIE['spip_session'])) {
74
-			$session = charger_fonction('session', 'inc');
75
-			$session($GLOBALS['visiteur_session']['id_auteur']);
76
-			spip_setcookie('spip_session', $_COOKIE['spip_session'], [
77
-				'expires' => time() - 3600
78
-			]);
79
-		}
80
-		// si authentification http, et que la personne est loge,
81
-		// pour se deconnecter, il faut proposer un nouveau formulaire de connexion http
82
-		if (isset($_SERVER['PHP_AUTH_USER'])
83
-			and !$GLOBALS['ignore_auth_http']
84
-			and $GLOBALS['auth_can_disconnect']
85
-		) {
86
-			ask_php_auth(_T('login_deconnexion_ok'),
87
-				_T('login_verifiez_navigateur'),
88
-				_T('login_retour_public'),
89
-				"redirect=" . _DIR_RESTREINT_ABS,
90
-				_T('login_test_navigateur'),
91
-				true);
92
-
93
-		}
94
-	}
95
-
96
-	// Rediriger en contrant le cache navigateur (Safari3)
97
-	include_spip('inc/headers');
98
-	redirige_par_entete($url
99
-		? parametre_url($url, 'var_hasard', uniqid(rand()), '&')
100
-		: generer_url_public('login'));
37
+    $logout = _request('logout');
38
+    $url = securiser_redirect_action(_request('url'));
39
+    // cas particulier, logout dans l'espace public
40
+    if ($logout == 'public' and !$url) {
41
+        $url = url_de_base();
42
+    }
43
+
44
+    // seul le loge peut se deloger (mais id_auteur peut valoir 0 apres une restauration avortee)
45
+    if (isset($GLOBALS['visiteur_session']['id_auteur'])
46
+        and is_numeric($GLOBALS['visiteur_session']['id_auteur'])
47
+        // des sessions anonymes avec id_auteur=0 existent, mais elle n'ont pas de statut : double check
48
+        and isset($GLOBALS['visiteur_session']['statut'])
49
+    ) {
50
+
51
+        // il faut un jeton pour fermer la session (eviter les CSRF)
52
+        if (!$jeton = _request('jeton')
53
+            or !verifier_jeton_logout($jeton, $GLOBALS['visiteur_session'])
54
+        ) {
55
+            $jeton = generer_jeton_logout($GLOBALS['visiteur_session']);
56
+            $action = generer_url_action("logout", "jeton=$jeton");
57
+            $action = parametre_url($action, 'logout', _request('logout'));
58
+            $action = parametre_url($action, 'url', _request('url'));
59
+            include_spip("inc/minipres");
60
+            include_spip("inc/filtres");
61
+            $texte = bouton_action(_T('spip:icone_deconnecter'), $action);
62
+            $texte = "<div class='boutons'>$texte</div>";
63
+            $texte .= '<script type="text/javascript">document.write("<style>body{visibility:hidden;}</style>");window.document.forms[0].submit();</script>';
64
+            $res = minipres(_T('spip:icone_deconnecter'), $texte, '', true);
65
+            echo $res;
66
+
67
+            return;
68
+        }
69
+
70
+        include_spip('inc/auth');
71
+        auth_trace($GLOBALS['visiteur_session'], '0000-00-00 00:00:00');
72
+        // le logout explicite vaut destruction de toutes les sessions
73
+        if (isset($_COOKIE['spip_session'])) {
74
+            $session = charger_fonction('session', 'inc');
75
+            $session($GLOBALS['visiteur_session']['id_auteur']);
76
+            spip_setcookie('spip_session', $_COOKIE['spip_session'], [
77
+                'expires' => time() - 3600
78
+            ]);
79
+        }
80
+        // si authentification http, et que la personne est loge,
81
+        // pour se deconnecter, il faut proposer un nouveau formulaire de connexion http
82
+        if (isset($_SERVER['PHP_AUTH_USER'])
83
+            and !$GLOBALS['ignore_auth_http']
84
+            and $GLOBALS['auth_can_disconnect']
85
+        ) {
86
+            ask_php_auth(_T('login_deconnexion_ok'),
87
+                _T('login_verifiez_navigateur'),
88
+                _T('login_retour_public'),
89
+                "redirect=" . _DIR_RESTREINT_ABS,
90
+                _T('login_test_navigateur'),
91
+                true);
92
+
93
+        }
94
+    }
95
+
96
+    // Rediriger en contrant le cache navigateur (Safari3)
97
+    include_spip('inc/headers');
98
+    redirige_par_entete($url
99
+        ? parametre_url($url, 'var_hasard', uniqid(rand()), '&')
100
+        : generer_url_public('login'));
101 101
 }
102 102
 
103 103
 /**
@@ -108,18 +108,18 @@  discard block
 block discarded – undo
108 108
  * @return string
109 109
  */
110 110
 function generer_jeton_logout($session, $alea = null) {
111
-	if (is_null($alea)) {
112
-		include_spip('inc/acces');
113
-		$alea = charger_aleas();
114
-	}
115
-
116
-	$jeton = md5($session['date_session']
117
-		. $session['id_auteur']
118
-		. $session['statut']
119
-		. $alea
120
-	);
121
-
122
-	return $jeton;
111
+    if (is_null($alea)) {
112
+        include_spip('inc/acces');
113
+        $alea = charger_aleas();
114
+    }
115
+
116
+    $jeton = md5($session['date_session']
117
+        . $session['id_auteur']
118
+        . $session['statut']
119
+        . $alea
120
+    );
121
+
122
+    return $jeton;
123 123
 }
124 124
 
125 125
 /**
@@ -133,13 +133,13 @@  discard block
 block discarded – undo
133 133
  * @return bool
134 134
  */
135 135
 function verifier_jeton_logout($jeton, $session) {
136
-	if (generer_jeton_logout($session) === $jeton) {
137
-		return true;
138
-	}
136
+    if (generer_jeton_logout($session) === $jeton) {
137
+        return true;
138
+    }
139 139
 
140
-	if (generer_jeton_logout($session, $GLOBALS['meta']['alea_ephemere_ancien']) === $jeton) {
141
-		return true;
142
-	}
140
+    if (generer_jeton_logout($session, $GLOBALS['meta']['alea_ephemere_ancien']) === $jeton) {
141
+        return true;
142
+    }
143 143
 
144
-	return false;
144
+    return false;
145 145
 }
Please login to merge, or discard this patch.
prive/images/index.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -9,13 +9,13 @@
 block discarded – undo
9 9
 	<h1>Index des icones de <a href='https://www.spip.net'>Spip</a></h1>
10 10
 	<table>
11 11
 		<?php
12
-		$myDir = opendir('.');
13
-		while ($file = readdir($myDir)) {
14
-			if (preg_match(',\.(png|gif)$,i', $file)) {
15
-				echo "		<tr><td>$file</td><td><img src='$file' alt='$file' /></td></tr>\n";
16
-			}
17
-		}
18
-		?>
12
+        $myDir = opendir('.');
13
+        while ($file = readdir($myDir)) {
14
+            if (preg_match(',\.(png|gif)$,i', $file)) {
15
+                echo "		<tr><td>$file</td><td><img src='$file' alt='$file' /></td></tr>\n";
16
+            }
17
+        }
18
+        ?>
19 19
 	</table>
20 20
 </center>
21 21
 </body>
Please login to merge, or discard this patch.
ecrire/req/sqlite3.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 
@@ -22,19 +22,19 @@  discard block
 block discarded – undo
22 22
 
23 23
 // https://code.spip.net/@req_sqlite3_dist
24 24
 function req_sqlite3_dist($addr, $port, $login, $pass, $db = '', $prefixe = '') {
25
-	return req_sqlite_dist($addr, $port, $login, $pass, $db, $prefixe, $sqlite_version = 3);
25
+    return req_sqlite_dist($addr, $port, $login, $pass, $db, $prefixe, $sqlite_version = 3);
26 26
 }
27 27
 
28 28
 
29 29
 // https://code.spip.net/@spip_sqlite3_constantes
30 30
 function spip_sqlite3_constantes() {
31
-	if (!defined('SPIP_SQLITE3_ASSOC')) {
32
-		define('SPIP_SQLITE3_ASSOC', PDO::FETCH_ASSOC);
33
-		define('SPIP_SQLITE3_NUM', PDO::FETCH_NUM);
34
-		define('SPIP_SQLITE3_BOTH', PDO::FETCH_BOTH);
35
-	}
31
+    if (!defined('SPIP_SQLITE3_ASSOC')) {
32
+        define('SPIP_SQLITE3_ASSOC', PDO::FETCH_ASSOC);
33
+        define('SPIP_SQLITE3_NUM', PDO::FETCH_NUM);
34
+        define('SPIP_SQLITE3_BOTH', PDO::FETCH_BOTH);
35
+    }
36 36
 }
37 37
 
38 38
 function spip_versions_sqlite3() {
39
-	return _sqlite_charger_version(3) ? 3 : false;
39
+    return _sqlite_charger_version(3) ? 3 : false;
40 40
 }
Please login to merge, or discard this patch.
ecrire/req/pg.exp.php 1 patch
Indentation   +1112 added lines, -1112 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
 define('_DEFAULT_DB', 'spip');
@@ -32,128 +32,128 @@  discard block
 block discarded – undo
32 32
 
33 33
 // https://code.spip.net/@req_pg_dist
34 34
 function req_pg_dist($addr, $port, $login, $pass, $db = '', $prefixe = '') {
35
-	static $last_connect = array();
36
-	if (!extension_loaded('pgsql')) {
37
-		return false;
38
-	}
39
-
40
-	// si provient de selectdb
41
-	if (empty($addr) && empty($port) && empty($login) && empty($pass)) {
42
-		foreach (array('addr', 'port', 'login', 'pass', 'prefixe') as $a) {
43
-			$$a = $last_connect[$a];
44
-		}
45
-	}
46
-	@list($host, $p) = explode(';', $addr);
47
-	if ($p > 0) {
48
-		$port = " port=$p";
49
-	} else {
50
-		$port = '';
51
-	}
52
-	$erreurs = array();
53
-	if ($db) {
54
-		@$link = pg_connect("host=$host$port dbname=$db user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW);
55
-	} elseif (!@$link = pg_connect("host=$host$port user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW)) {
56
-		$erreurs[] = pg_last_error();
57
-		if (@$link = pg_connect("host=$host$port dbname=$login user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW)) {
58
-			$db = $login;
59
-		} else {
60
-			$erreurs[] = pg_last_error();
61
-			$db = _DEFAULT_DB;
62
-			$link = pg_connect("host=$host$port dbname=$db user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW);
63
-		}
64
-	}
65
-	if (!$link) {
66
-		$erreurs[] = pg_last_error();
67
-		foreach ($erreurs as $e) {
68
-			spip_log('Echec pg_connect. Erreur : ' . $e, 'pg.' . _LOG_HS);
69
-		}
70
-
71
-		return false;
72
-	}
73
-
74
-	if ($link) {
75
-		$last_connect = array(
76
-			'addr' => $addr,
77
-			'port' => $port,
78
-			'login' => $login,
79
-			'pass' => $pass,
80
-			'db' => $db,
81
-			'prefixe' => $prefixe,
82
-		);
83
-	}
84
-
85
-	spip_log("Connexion vers $host, base $db, prefixe $prefixe " . ($link ? 'operationnelle' : 'impossible'),
86
-		'pg.' . _LOG_DEBUG);
87
-
88
-	return !$link ? false : array(
89
-		'db' => $db,
90
-		'prefixe' => $prefixe ? $prefixe : $db,
91
-		'link' => $link,
92
-	);
35
+    static $last_connect = array();
36
+    if (!extension_loaded('pgsql')) {
37
+        return false;
38
+    }
39
+
40
+    // si provient de selectdb
41
+    if (empty($addr) && empty($port) && empty($login) && empty($pass)) {
42
+        foreach (array('addr', 'port', 'login', 'pass', 'prefixe') as $a) {
43
+            $$a = $last_connect[$a];
44
+        }
45
+    }
46
+    @list($host, $p) = explode(';', $addr);
47
+    if ($p > 0) {
48
+        $port = " port=$p";
49
+    } else {
50
+        $port = '';
51
+    }
52
+    $erreurs = array();
53
+    if ($db) {
54
+        @$link = pg_connect("host=$host$port dbname=$db user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW);
55
+    } elseif (!@$link = pg_connect("host=$host$port user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW)) {
56
+        $erreurs[] = pg_last_error();
57
+        if (@$link = pg_connect("host=$host$port dbname=$login user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW)) {
58
+            $db = $login;
59
+        } else {
60
+            $erreurs[] = pg_last_error();
61
+            $db = _DEFAULT_DB;
62
+            $link = pg_connect("host=$host$port dbname=$db user=$login password='$pass'", PGSQL_CONNECT_FORCE_NEW);
63
+        }
64
+    }
65
+    if (!$link) {
66
+        $erreurs[] = pg_last_error();
67
+        foreach ($erreurs as $e) {
68
+            spip_log('Echec pg_connect. Erreur : ' . $e, 'pg.' . _LOG_HS);
69
+        }
70
+
71
+        return false;
72
+    }
73
+
74
+    if ($link) {
75
+        $last_connect = array(
76
+            'addr' => $addr,
77
+            'port' => $port,
78
+            'login' => $login,
79
+            'pass' => $pass,
80
+            'db' => $db,
81
+            'prefixe' => $prefixe,
82
+        );
83
+    }
84
+
85
+    spip_log("Connexion vers $host, base $db, prefixe $prefixe " . ($link ? 'operationnelle' : 'impossible'),
86
+        'pg.' . _LOG_DEBUG);
87
+
88
+    return !$link ? false : array(
89
+        'db' => $db,
90
+        'prefixe' => $prefixe ? $prefixe : $db,
91
+        'link' => $link,
92
+    );
93 93
 }
94 94
 
95 95
 $GLOBALS['spip_pg_functions_1'] = array(
96
-	'alter' => 'spip_pg_alter',
97
-	'count' => 'spip_pg_count',
98
-	'countsel' => 'spip_pg_countsel',
99
-	'create' => 'spip_pg_create',
100
-	'create_base' => 'spip_pg_create_base',
101
-	'create_view' => 'spip_pg_create_view',
102
-	'date_proche' => 'spip_pg_date_proche',
103
-	'delete' => 'spip_pg_delete',
104
-	'drop_table' => 'spip_pg_drop_table',
105
-	'drop_view' => 'spip_pg_drop_view',
106
-	'errno' => 'spip_pg_errno',
107
-	'error' => 'spip_pg_error',
108
-	'explain' => 'spip_pg_explain',
109
-	'fetch' => 'spip_pg_fetch',
110
-	'seek' => 'spip_pg_seek',
111
-	'free' => 'spip_pg_free',
112
-	'hex' => 'spip_pg_hex',
113
-	'in' => 'spip_pg_in',
114
-	'insert' => 'spip_pg_insert',
115
-	'insertq' => 'spip_pg_insertq',
116
-	'insertq_multi' => 'spip_pg_insertq_multi',
117
-	'listdbs' => 'spip_pg_listdbs',
118
-	'multi' => 'spip_pg_multi',
119
-	'optimize' => 'spip_pg_optimize',
120
-	'query' => 'spip_pg_query',
121
-	'quote' => 'spip_pg_quote',
122
-	'replace' => 'spip_pg_replace',
123
-	'replace_multi' => 'spip_pg_replace_multi',
124
-	'select' => 'spip_pg_select',
125
-	'selectdb' => 'spip_pg_selectdb',
126
-	'set_connect_charset' => 'spip_pg_set_connect_charset',
127
-	'showbase' => 'spip_pg_showbase',
128
-	'showtable' => 'spip_pg_showtable',
129
-	'update' => 'spip_pg_update',
130
-	'updateq' => 'spip_pg_updateq',
96
+    'alter' => 'spip_pg_alter',
97
+    'count' => 'spip_pg_count',
98
+    'countsel' => 'spip_pg_countsel',
99
+    'create' => 'spip_pg_create',
100
+    'create_base' => 'spip_pg_create_base',
101
+    'create_view' => 'spip_pg_create_view',
102
+    'date_proche' => 'spip_pg_date_proche',
103
+    'delete' => 'spip_pg_delete',
104
+    'drop_table' => 'spip_pg_drop_table',
105
+    'drop_view' => 'spip_pg_drop_view',
106
+    'errno' => 'spip_pg_errno',
107
+    'error' => 'spip_pg_error',
108
+    'explain' => 'spip_pg_explain',
109
+    'fetch' => 'spip_pg_fetch',
110
+    'seek' => 'spip_pg_seek',
111
+    'free' => 'spip_pg_free',
112
+    'hex' => 'spip_pg_hex',
113
+    'in' => 'spip_pg_in',
114
+    'insert' => 'spip_pg_insert',
115
+    'insertq' => 'spip_pg_insertq',
116
+    'insertq_multi' => 'spip_pg_insertq_multi',
117
+    'listdbs' => 'spip_pg_listdbs',
118
+    'multi' => 'spip_pg_multi',
119
+    'optimize' => 'spip_pg_optimize',
120
+    'query' => 'spip_pg_query',
121
+    'quote' => 'spip_pg_quote',
122
+    'replace' => 'spip_pg_replace',
123
+    'replace_multi' => 'spip_pg_replace_multi',
124
+    'select' => 'spip_pg_select',
125
+    'selectdb' => 'spip_pg_selectdb',
126
+    'set_connect_charset' => 'spip_pg_set_connect_charset',
127
+    'showbase' => 'spip_pg_showbase',
128
+    'showtable' => 'spip_pg_showtable',
129
+    'update' => 'spip_pg_update',
130
+    'updateq' => 'spip_pg_updateq',
131 131
 );
132 132
 
133 133
 // Par ou ca passe une fois les traductions faites
134 134
 // https://code.spip.net/@spip_pg_trace_query
135 135
 function spip_pg_trace_query($query, $serveur = '') {
136
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
137
-	$prefixe = $connexion['prefixe'];
138
-	$link = $connexion['link'];
139
-	$db = $connexion['db'];
140
-
141
-	if (isset($_GET['var_profile'])) {
142
-		include_spip('public/tracer');
143
-		$t = trace_query_start();
144
-		$e = '';
145
-	} else {
146
-		$t = 0;
147
-	}
148
-
149
-	$connexion['last'] = $query;
150
-	$r = spip_pg_query_simple($link, $query);
151
-
152
-	// Log de l'erreur eventuelle
153
-	if ($e = spip_pg_errno($serveur)) {
154
-		$e .= spip_pg_error($query, $serveur);
155
-	} // et du fautif
156
-	return $t ? trace_query_end($query, $t, $r, $e, $serveur) : $r;
136
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
137
+    $prefixe = $connexion['prefixe'];
138
+    $link = $connexion['link'];
139
+    $db = $connexion['db'];
140
+
141
+    if (isset($_GET['var_profile'])) {
142
+        include_spip('public/tracer');
143
+        $t = trace_query_start();
144
+        $e = '';
145
+    } else {
146
+        $t = 0;
147
+    }
148
+
149
+    $connexion['last'] = $query;
150
+    $r = spip_pg_query_simple($link, $query);
151
+
152
+    // Log de l'erreur eventuelle
153
+    if ($e = spip_pg_errno($serveur)) {
154
+        $e .= spip_pg_error($query, $serveur);
155
+    } // et du fautif
156
+    return $t ? trace_query_end($query, $t, $r, $e, $serveur) : $r;
157 157
 }
158 158
 
159 159
 // Fonction de requete generale quand on est sur que c'est SQL standard.
@@ -161,30 +161,30 @@  discard block
 block discarded – undo
161 161
 
162 162
 // https://code.spip.net/@spip_pg_query
163 163
 function spip_pg_query($query, $serveur = '', $requeter = true) {
164
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
165
-	$prefixe = $connexion['prefixe'];
166
-	$link = $connexion['link'];
167
-	$db = $connexion['db'];
168
-
169
-	if (preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/i', $query, $regs)) {
170
-		$suite = strstr($query, $regs[0]);
171
-		$query = substr($query, 0, -strlen($suite));
172
-	} else {
173
-		$suite = '';
174
-	}
175
-	$query = preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
176
-
177
-	// renvoyer la requete inerte si demandee
178
-	if (!$requeter) {
179
-		return $query;
180
-	}
181
-
182
-	return spip_pg_trace_query($query, $serveur);
164
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
165
+    $prefixe = $connexion['prefixe'];
166
+    $link = $connexion['link'];
167
+    $db = $connexion['db'];
168
+
169
+    if (preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/i', $query, $regs)) {
170
+        $suite = strstr($query, $regs[0]);
171
+        $query = substr($query, 0, -strlen($suite));
172
+    } else {
173
+        $suite = '';
174
+    }
175
+    $query = preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
176
+
177
+    // renvoyer la requete inerte si demandee
178
+    if (!$requeter) {
179
+        return $query;
180
+    }
181
+
182
+    return spip_pg_trace_query($query, $serveur);
183 183
 }
184 184
 
185 185
 function spip_pg_query_simple($link, $query) {
186
-	#spip_log(var_export($query,true), 'pg.'._LOG_DEBUG);
187
-	return pg_query($link, $query);
186
+    #spip_log(var_export($query,true), 'pg.'._LOG_DEBUG);
187
+    return pg_query($link, $query);
188 188
 }
189 189
 
190 190
 /*
@@ -196,198 +196,198 @@  discard block
 block discarded – undo
196 196
  * de requetes showtable intempestives
197 197
  */
198 198
 function spip_pg_ajouter_champs_timestamp($table, $couples, $desc = '', $serveur = '') {
199
-	static $tables = array();
200
-
201
-	if (!isset($tables[$table])) {
202
-
203
-		if (!$desc) {
204
-			$trouver_table = charger_fonction('trouver_table', 'base');
205
-			$desc = $trouver_table($table, $serveur);
206
-			// si pas de description, on ne fait rien, ou on die() ?
207
-			if (!$desc) {
208
-				return $couples;
209
-			}
210
-		}
211
-
212
-		// recherche des champs avec simplement 'TIMESTAMP'
213
-		// cependant, il faudra peut etre etendre
214
-		// avec la gestion de DEFAULT et ON UPDATE
215
-		// mais ceux-ci ne sont pas utilises dans le core
216
-		$tables[$table] = array();
217
-		foreach ($desc['field'] as $k => $v) {
218
-			$v = strtolower(ltrim($v));
219
-			// ne pas ajouter de timestamp now() si un default est specifie
220
-			if (strpos($v, 'timestamp') === 0 and strpos($v, 'default') === false) {
221
-				$tables[$table][] = $k;
222
-			}
223
-		}
224
-	}
225
-
226
-	// ajout des champs type 'timestamp' absents
227
-	foreach ($tables[$table] as $maj) {
228
-		if (!array_key_exists($maj, $couples)) {
229
-			$couples[$maj] = "NOW()";
230
-		}
231
-	}
232
-
233
-	return $couples;
199
+    static $tables = array();
200
+
201
+    if (!isset($tables[$table])) {
202
+
203
+        if (!$desc) {
204
+            $trouver_table = charger_fonction('trouver_table', 'base');
205
+            $desc = $trouver_table($table, $serveur);
206
+            // si pas de description, on ne fait rien, ou on die() ?
207
+            if (!$desc) {
208
+                return $couples;
209
+            }
210
+        }
211
+
212
+        // recherche des champs avec simplement 'TIMESTAMP'
213
+        // cependant, il faudra peut etre etendre
214
+        // avec la gestion de DEFAULT et ON UPDATE
215
+        // mais ceux-ci ne sont pas utilises dans le core
216
+        $tables[$table] = array();
217
+        foreach ($desc['field'] as $k => $v) {
218
+            $v = strtolower(ltrim($v));
219
+            // ne pas ajouter de timestamp now() si un default est specifie
220
+            if (strpos($v, 'timestamp') === 0 and strpos($v, 'default') === false) {
221
+                $tables[$table][] = $k;
222
+            }
223
+        }
224
+    }
225
+
226
+    // ajout des champs type 'timestamp' absents
227
+    foreach ($tables[$table] as $maj) {
228
+        if (!array_key_exists($maj, $couples)) {
229
+            $couples[$maj] = "NOW()";
230
+        }
231
+    }
232
+
233
+    return $couples;
234 234
 }
235 235
 
236 236
 
237 237
 // Alter en PG ne traite pas les index
238 238
 // https://code.spip.net/@spip_pg_alter
239 239
 function spip_pg_alter($query, $serveur = '', $requeter = true) {
240
-	// il faudrait une regexp pour eviter de spliter ADD PRIMARY KEY (colA, colB)
241
-	// tout en cassant en deux alter distincts "ADD PRIMARY KEY (colA, colB), ADD INDEX (chose)"... 
242
-	// ou revoir l'api de sql_alter en creant un 
243
-	// sql_alter_table($table,array($actions));
244
-	if (!preg_match("/\s*((\s*IGNORE)?\s*TABLE\s*([^\s]*))\s*(.*)?/is", $query, $regs)) {
245
-		spip_log("$query mal comprise", 'pg.' . _LOG_ERREUR);
246
-
247
-		return false;
248
-	}
249
-	$debut = $regs[1];
250
-	$table = $regs[3];
251
-	$suite = $regs[4];
252
-	$todo = explode(',', $suite);
253
-	// on remet les morceaux dechires ensembles... que c'est laid !
254
-	$todo2 = array();
255
-	$i = 0;
256
-	$ouverte = false;
257
-	while ($do = array_shift($todo)) {
258
-		$todo2[$i] = isset($todo2[$i]) ? $todo2[$i] . "," . $do : $do;
259
-		$o = (false !== strpos($do, "("));
260
-		$f = (false !== strpos($do, ")"));
261
-		if ($o and !$f) {
262
-			$ouverte = true;
263
-		} elseif ($f) {
264
-			$ouverte = false;
265
-		}
266
-		if (!$ouverte) {
267
-			$i++;
268
-		}
269
-	}
270
-	$todo = $todo2;
271
-	$query = $debut . ' ' . array_shift($todo);
272
-
273
-	if (!preg_match('/^\s*(IGNORE\s*)?TABLE\s+(\w+)\s+(ADD|DROP|CHANGE|MODIFY|RENAME)\s*(.*)$/is', $query, $r)) {
274
-		spip_log("$query incompris", 'pg.' . _LOG_ERREUR);
275
-	} else {
276
-		if ($r[1]) {
277
-			spip_log("j'ignore IGNORE dans $query", 'pg.' . _LOG_AVERTISSEMENT);
278
-		}
279
-		$f = 'spip_pg_alter_' . strtolower($r[3]);
280
-		if (function_exists($f)) {
281
-			$f($r[2], $r[4], $serveur, $requeter);
282
-		} else {
283
-			spip_log("$query non prevu", 'pg.' . _LOG_ERREUR);
284
-		}
285
-	}
286
-	// Alter a plusieurs args. Faudrait optimiser.
287
-	if ($todo) {
288
-		spip_pg_alter("TABLE $table " . join(',', $todo));
289
-	}
240
+    // il faudrait une regexp pour eviter de spliter ADD PRIMARY KEY (colA, colB)
241
+    // tout en cassant en deux alter distincts "ADD PRIMARY KEY (colA, colB), ADD INDEX (chose)"... 
242
+    // ou revoir l'api de sql_alter en creant un 
243
+    // sql_alter_table($table,array($actions));
244
+    if (!preg_match("/\s*((\s*IGNORE)?\s*TABLE\s*([^\s]*))\s*(.*)?/is", $query, $regs)) {
245
+        spip_log("$query mal comprise", 'pg.' . _LOG_ERREUR);
246
+
247
+        return false;
248
+    }
249
+    $debut = $regs[1];
250
+    $table = $regs[3];
251
+    $suite = $regs[4];
252
+    $todo = explode(',', $suite);
253
+    // on remet les morceaux dechires ensembles... que c'est laid !
254
+    $todo2 = array();
255
+    $i = 0;
256
+    $ouverte = false;
257
+    while ($do = array_shift($todo)) {
258
+        $todo2[$i] = isset($todo2[$i]) ? $todo2[$i] . "," . $do : $do;
259
+        $o = (false !== strpos($do, "("));
260
+        $f = (false !== strpos($do, ")"));
261
+        if ($o and !$f) {
262
+            $ouverte = true;
263
+        } elseif ($f) {
264
+            $ouverte = false;
265
+        }
266
+        if (!$ouverte) {
267
+            $i++;
268
+        }
269
+    }
270
+    $todo = $todo2;
271
+    $query = $debut . ' ' . array_shift($todo);
272
+
273
+    if (!preg_match('/^\s*(IGNORE\s*)?TABLE\s+(\w+)\s+(ADD|DROP|CHANGE|MODIFY|RENAME)\s*(.*)$/is', $query, $r)) {
274
+        spip_log("$query incompris", 'pg.' . _LOG_ERREUR);
275
+    } else {
276
+        if ($r[1]) {
277
+            spip_log("j'ignore IGNORE dans $query", 'pg.' . _LOG_AVERTISSEMENT);
278
+        }
279
+        $f = 'spip_pg_alter_' . strtolower($r[3]);
280
+        if (function_exists($f)) {
281
+            $f($r[2], $r[4], $serveur, $requeter);
282
+        } else {
283
+            spip_log("$query non prevu", 'pg.' . _LOG_ERREUR);
284
+        }
285
+    }
286
+    // Alter a plusieurs args. Faudrait optimiser.
287
+    if ($todo) {
288
+        spip_pg_alter("TABLE $table " . join(',', $todo));
289
+    }
290 290
 
291 291
 }
292 292
 
293 293
 // https://code.spip.net/@spip_pg_alter_change
294 294
 function spip_pg_alter_change($table, $arg, $serveur = '', $requeter = true) {
295
-	if (!preg_match('/^`?(\w+)`?\s+`?(\w+)`?\s+(.*?)\s*(DEFAULT .*?)?(NOT\s+NULL)?\s*(DEFAULT .*?)?$/i', $arg, $r)) {
296
-		spip_log("alter change: $arg  incompris", 'pg.' . _LOG_ERREUR);
297
-	} else {
298
-		list(, $old, $new, $type, $default, $null, $def2) = $r;
299
-		$actions = array("ALTER $old TYPE " . mysql2pg_type($type));
300
-		if ($null) {
301
-			$actions[] = "ALTER $old SET NOT NULL";
302
-		} else {
303
-			$actions[] = "ALTER $old DROP NOT NULL";
304
-		}
305
-
306
-		if ($d = ($default ? $default : $def2)) {
307
-			$actions[] = "ALTER $old SET $d";
308
-		} else {
309
-			$actions[] = "ALTER $old DROP DEFAULT";
310
-		}
311
-
312
-		spip_pg_query("ALTER TABLE $table " . join(', ', $actions));
313
-
314
-		if ($old != $new) {
315
-			spip_pg_query("ALTER TABLE $table RENAME $old TO $new", $serveur);
316
-		}
317
-	}
295
+    if (!preg_match('/^`?(\w+)`?\s+`?(\w+)`?\s+(.*?)\s*(DEFAULT .*?)?(NOT\s+NULL)?\s*(DEFAULT .*?)?$/i', $arg, $r)) {
296
+        spip_log("alter change: $arg  incompris", 'pg.' . _LOG_ERREUR);
297
+    } else {
298
+        list(, $old, $new, $type, $default, $null, $def2) = $r;
299
+        $actions = array("ALTER $old TYPE " . mysql2pg_type($type));
300
+        if ($null) {
301
+            $actions[] = "ALTER $old SET NOT NULL";
302
+        } else {
303
+            $actions[] = "ALTER $old DROP NOT NULL";
304
+        }
305
+
306
+        if ($d = ($default ? $default : $def2)) {
307
+            $actions[] = "ALTER $old SET $d";
308
+        } else {
309
+            $actions[] = "ALTER $old DROP DEFAULT";
310
+        }
311
+
312
+        spip_pg_query("ALTER TABLE $table " . join(', ', $actions));
313
+
314
+        if ($old != $new) {
315
+            spip_pg_query("ALTER TABLE $table RENAME $old TO $new", $serveur);
316
+        }
317
+    }
318 318
 }
319 319
 
320 320
 // https://code.spip.net/@spip_pg_alter_add
321 321
 function spip_pg_alter_add($table, $arg, $serveur = '', $requeter = true) {
322
-	if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*(.*)$/', $arg, $r)) {
323
-		spip_log("alter add $arg  incompris", 'pg.' . _LOG_ERREUR);
324
-
325
-		return null;
326
-	}
327
-	if (!$r[1] or $r[1] == 'COLUMN') {
328
-		preg_match('/`?(\w+)`?(.*)/', $r[2], $m);
329
-		if (preg_match('/^(.*)(BEFORE|AFTER|FIRST)(.*)$/is', $m[2], $n)) {
330
-			$m[2] = $n[1];
331
-		}
332
-
333
-		return spip_pg_query("ALTER TABLE $table ADD " . $m[1] . ' ' . mysql2pg_type($m[2]), $serveur, $requeter);
334
-	} elseif ($r[1][0] == 'P') {
335
-		// la primary peut etre sur plusieurs champs
336
-		$r[2] = trim(str_replace('`', '', $r[2]));
337
-		$m = ($r[2][0] == '(') ? substr($r[2], 1, -1) : $r[2];
338
-
339
-		return spip_pg_query("ALTER TABLE $table ADD CONSTRAINT $table" . '_pkey PRIMARY KEY (' . $m . ')', $serveur,
340
-			$requeter);
341
-	} else {
342
-		preg_match('/([^\s,]*)\s*(.*)?/', $r[2], $m);
343
-		// peut etre "(colonne)" ou "nom_index (colonnes)"
344
-		// bug potentiel si qqn met "(colonne, colonne)"
345
-		//
346
-		// nom_index (colonnes)
347
-		if ($m[2]) {
348
-			$colonnes = substr($m[2], 1, -1);
349
-			$nom_index = $m[1];
350
-		} else {
351
-			// (colonne)
352
-			if ($m[1][0] == "(") {
353
-				$colonnes = substr($m[1], 1, -1);
354
-				if (false !== strpos(",", $colonnes)) {
355
-					spip_log("PG : Erreur, impossible de creer un index sur plusieurs colonnes"
356
-						. " sans qu'il ait de nom ($table, ($colonnes))", 'pg.' . _LOG_ERREUR);
357
-				} else {
358
-					$nom_index = $colonnes;
359
-				}
360
-			} // nom_index
361
-			else {
362
-				$nom_index = $colonnes = $m[1];
363
-			}
364
-		}
365
-
366
-		return spip_pg_create_index($nom_index, $table, $colonnes, $serveur, $requeter);
367
-	}
322
+    if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*(.*)$/', $arg, $r)) {
323
+        spip_log("alter add $arg  incompris", 'pg.' . _LOG_ERREUR);
324
+
325
+        return null;
326
+    }
327
+    if (!$r[1] or $r[1] == 'COLUMN') {
328
+        preg_match('/`?(\w+)`?(.*)/', $r[2], $m);
329
+        if (preg_match('/^(.*)(BEFORE|AFTER|FIRST)(.*)$/is', $m[2], $n)) {
330
+            $m[2] = $n[1];
331
+        }
332
+
333
+        return spip_pg_query("ALTER TABLE $table ADD " . $m[1] . ' ' . mysql2pg_type($m[2]), $serveur, $requeter);
334
+    } elseif ($r[1][0] == 'P') {
335
+        // la primary peut etre sur plusieurs champs
336
+        $r[2] = trim(str_replace('`', '', $r[2]));
337
+        $m = ($r[2][0] == '(') ? substr($r[2], 1, -1) : $r[2];
338
+
339
+        return spip_pg_query("ALTER TABLE $table ADD CONSTRAINT $table" . '_pkey PRIMARY KEY (' . $m . ')', $serveur,
340
+            $requeter);
341
+    } else {
342
+        preg_match('/([^\s,]*)\s*(.*)?/', $r[2], $m);
343
+        // peut etre "(colonne)" ou "nom_index (colonnes)"
344
+        // bug potentiel si qqn met "(colonne, colonne)"
345
+        //
346
+        // nom_index (colonnes)
347
+        if ($m[2]) {
348
+            $colonnes = substr($m[2], 1, -1);
349
+            $nom_index = $m[1];
350
+        } else {
351
+            // (colonne)
352
+            if ($m[1][0] == "(") {
353
+                $colonnes = substr($m[1], 1, -1);
354
+                if (false !== strpos(",", $colonnes)) {
355
+                    spip_log("PG : Erreur, impossible de creer un index sur plusieurs colonnes"
356
+                        . " sans qu'il ait de nom ($table, ($colonnes))", 'pg.' . _LOG_ERREUR);
357
+                } else {
358
+                    $nom_index = $colonnes;
359
+                }
360
+            } // nom_index
361
+            else {
362
+                $nom_index = $colonnes = $m[1];
363
+            }
364
+        }
365
+
366
+        return spip_pg_create_index($nom_index, $table, $colonnes, $serveur, $requeter);
367
+    }
368 368
 }
369 369
 
370 370
 // https://code.spip.net/@spip_pg_alter_drop
371 371
 function spip_pg_alter_drop($table, $arg, $serveur = '', $requeter = true) {
372
-	if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*`?(\w*)`?/', $arg, $r)) {
373
-		spip_log("alter drop: $arg  incompris", 'pg.' . _LOG_ERREUR);
374
-	} else {
375
-		if (!$r[1] or $r[1] == 'COLUMN') {
376
-			return spip_pg_query("ALTER TABLE $table DROP " . $r[2], $serveur);
377
-		} elseif ($r[1][0] == 'P') {
378
-			return spip_pg_query("ALTER TABLE $table DROP CONSTRAINT $table" . '_pkey', $serveur);
379
-		} else {
380
-			return spip_pg_query("DROP INDEX " . $table . '_' . $r[2], $serveur);
381
-		}
382
-	}
372
+    if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*`?(\w*)`?/', $arg, $r)) {
373
+        spip_log("alter drop: $arg  incompris", 'pg.' . _LOG_ERREUR);
374
+    } else {
375
+        if (!$r[1] or $r[1] == 'COLUMN') {
376
+            return spip_pg_query("ALTER TABLE $table DROP " . $r[2], $serveur);
377
+        } elseif ($r[1][0] == 'P') {
378
+            return spip_pg_query("ALTER TABLE $table DROP CONSTRAINT $table" . '_pkey', $serveur);
379
+        } else {
380
+            return spip_pg_query("DROP INDEX " . $table . '_' . $r[2], $serveur);
381
+        }
382
+    }
383 383
 }
384 384
 
385 385
 function spip_pg_alter_modify($table, $arg, $serveur = '', $requeter = true) {
386
-	if (!preg_match('/^`?(\w+)`?\s+(.*)$/', $arg, $r)) {
387
-		spip_log("alter modify: $arg  incompris", 'pg.' . _LOG_ERREUR);
388
-	} else {
389
-		return spip_pg_alter_change($table, $r[1] . ' ' . $arg, $serveur = '', $requeter = true);
390
-	}
386
+    if (!preg_match('/^`?(\w+)`?\s+(.*)$/', $arg, $r)) {
387
+        spip_log("alter modify: $arg  incompris", 'pg.' . _LOG_ERREUR);
388
+    } else {
389
+        return spip_pg_alter_change($table, $r[1] . ' ' . $arg, $serveur = '', $requeter = true);
390
+    }
391 391
 }
392 392
 
393 393
 // attention (en pg) : 
@@ -395,17 +395,17 @@  discard block
 block discarded – undo
395 395
 // - alter table A rename X to Y = changer le nom de la colonne X en Y 
396 396
 // pour l'instant, traiter simplement RENAME TO X
397 397
 function spip_pg_alter_rename($table, $arg, $serveur = '', $requeter = true) {
398
-	$rename = "";
399
-	// si TO, mais pas au debut
400
-	if (!stripos($arg, 'TO ')) {
401
-		$rename = $arg;
402
-	} elseif (preg_match('/^(TO)\s*`?(\w*)`?/', $arg, $r)) {
403
-		$rename = $r[2];
404
-	} else {
405
-		spip_log("alter rename: $arg  incompris", 'pg.' . _LOG_ERREUR);
406
-	}
407
-
408
-	return $rename ? spip_pg_query("ALTER TABLE $table RENAME TO $rename") : false;
398
+    $rename = "";
399
+    // si TO, mais pas au debut
400
+    if (!stripos($arg, 'TO ')) {
401
+        $rename = $arg;
402
+    } elseif (preg_match('/^(TO)\s*`?(\w*)`?/', $arg, $r)) {
403
+        $rename = $r[2];
404
+    } else {
405
+        spip_log("alter rename: $arg  incompris", 'pg.' . _LOG_ERREUR);
406
+    }
407
+
408
+    return $rename ? spip_pg_query("ALTER TABLE $table RENAME TO $rename") : false;
409 409
 }
410 410
 
411 411
 
@@ -421,58 +421,58 @@  discard block
 block discarded – undo
421 421
  * @return bool ou requete
422 422
  */
423 423
 function spip_pg_create_index($nom, $table, $champs, $serveur = '', $requeter = true) {
424
-	if (!($nom or $table or $champs)) {
425
-		spip_log("Champ manquant pour creer un index pg ($nom, $table, (" . @join(',', $champs) . "))",
426
-			'pg.' . _LOG_ERREUR);
427
-
428
-		return false;
429
-	}
430
-
431
-	$nom = str_replace("`", "", $nom);
432
-	$champs = str_replace("`", "", $champs);
433
-
434
-	// PG ne differentie pas noms des index en fonction des tables
435
-	// il faut donc creer des noms uniques d'index pour une base pg
436
-	$nom = $table . '_' . $nom;
437
-	// enlever d'eventuelles parentheses deja presentes sur champs
438
-	if (!is_array($champs)) {
439
-		if ($champs[0] == "(") {
440
-			$champs = substr($champs, 1, -1);
441
-		}
442
-		$champs = array($champs);
443
-	}
444
-	$query = "CREATE INDEX $nom ON $table (" . join(',', $champs) . ")";
445
-	if (!$requeter) {
446
-		return $query;
447
-	}
448
-	$res = spip_pg_query($query, $serveur, $requeter);
449
-
450
-	return $res;
424
+    if (!($nom or $table or $champs)) {
425
+        spip_log("Champ manquant pour creer un index pg ($nom, $table, (" . @join(',', $champs) . "))",
426
+            'pg.' . _LOG_ERREUR);
427
+
428
+        return false;
429
+    }
430
+
431
+    $nom = str_replace("`", "", $nom);
432
+    $champs = str_replace("`", "", $champs);
433
+
434
+    // PG ne differentie pas noms des index en fonction des tables
435
+    // il faut donc creer des noms uniques d'index pour une base pg
436
+    $nom = $table . '_' . $nom;
437
+    // enlever d'eventuelles parentheses deja presentes sur champs
438
+    if (!is_array($champs)) {
439
+        if ($champs[0] == "(") {
440
+            $champs = substr($champs, 1, -1);
441
+        }
442
+        $champs = array($champs);
443
+    }
444
+    $query = "CREATE INDEX $nom ON $table (" . join(',', $champs) . ")";
445
+    if (!$requeter) {
446
+        return $query;
447
+    }
448
+    $res = spip_pg_query($query, $serveur, $requeter);
449
+
450
+    return $res;
451 451
 }
452 452
 
453 453
 
454 454
 // https://code.spip.net/@spip_pg_explain
455 455
 function spip_pg_explain($query, $serveur = '', $requeter = true) {
456
-	if (strpos(ltrim($query), 'SELECT') !== 0) {
457
-		return array();
458
-	}
459
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
460
-	$prefixe = $connexion['prefixe'];
461
-	$link = $connexion['link'];
462
-	if (preg_match('/\s(SET|VALUES|WHERE)\s/i', $query, $regs)) {
463
-		$suite = strstr($query, $regs[0]);
464
-		$query = substr($query, 0, -strlen($suite));
465
-	} else {
466
-		$suite = '';
467
-	}
468
-	$query = 'EXPLAIN ' . preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
469
-
470
-	if (!$requeter) {
471
-		return $query;
472
-	}
473
-	$r = spip_pg_query_simple($link, $query);
474
-
475
-	return spip_pg_fetch($r, null, $serveur);
456
+    if (strpos(ltrim($query), 'SELECT') !== 0) {
457
+        return array();
458
+    }
459
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
460
+    $prefixe = $connexion['prefixe'];
461
+    $link = $connexion['link'];
462
+    if (preg_match('/\s(SET|VALUES|WHERE)\s/i', $query, $regs)) {
463
+        $suite = strstr($query, $regs[0]);
464
+        $query = substr($query, 0, -strlen($suite));
465
+    } else {
466
+        $suite = '';
467
+    }
468
+    $query = 'EXPLAIN ' . preg_replace('/([,\s])spip_/', '\1' . $prefixe . '_', $query) . $suite;
469
+
470
+    if (!$requeter) {
471
+        return $query;
472
+    }
473
+    $r = spip_pg_query_simple($link, $query);
474
+
475
+    return spip_pg_fetch($r, null, $serveur);
476 476
 }
477 477
 
478 478
 
@@ -491,92 +491,92 @@  discard block
 block discarded – undo
491 491
  *     - False en cas d'erreur.
492 492
  **/
493 493
 function spip_pg_selectdb($db, $serveur = '', $requeter = true) {
494
-	// se connecter a la base indiquee
495
-	// avec les identifiants connus
496
-	$index = $serveur ? strtolower($serveur) : 0;
497
-
498
-	if ($link = spip_connect_db('', '', '', '', $db, 'pg', '', '')) {
499
-		if (($db == $link['db']) && $GLOBALS['connexions'][$index] = $link) {
500
-			return $db;
501
-		}
502
-	} else {
503
-		return false;
504
-	}
494
+    // se connecter a la base indiquee
495
+    // avec les identifiants connus
496
+    $index = $serveur ? strtolower($serveur) : 0;
497
+
498
+    if ($link = spip_connect_db('', '', '', '', $db, 'pg', '', '')) {
499
+        if (($db == $link['db']) && $GLOBALS['connexions'][$index] = $link) {
500
+            return $db;
501
+        }
502
+    } else {
503
+        return false;
504
+    }
505 505
 }
506 506
 
507 507
 // Qu'une seule base pour le moment
508 508
 
509 509
 // https://code.spip.net/@spip_pg_listdbs
510 510
 function spip_pg_listdbs($serveur) {
511
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
512
-	$link = $connexion['link'];
513
-	$dbs = array();
514
-	$res = spip_pg_query_simple($link, "select * From pg_database");
515
-	while ($row = pg_fetch_array($res, null, PGSQL_NUM)) {
516
-		$dbs[] = reset($row);
517
-	}
518
-
519
-	return $dbs;
511
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
512
+    $link = $connexion['link'];
513
+    $dbs = array();
514
+    $res = spip_pg_query_simple($link, "select * From pg_database");
515
+    while ($row = pg_fetch_array($res, null, PGSQL_NUM)) {
516
+        $dbs[] = reset($row);
517
+    }
518
+
519
+    return $dbs;
520 520
 }
521 521
 
522 522
 // https://code.spip.net/@spip_pg_select
523 523
 function spip_pg_select(
524
-	$select,
525
-	$from,
526
-	$where = '',
527
-	$groupby = array(),
528
-	$orderby = '',
529
-	$limit = '',
530
-	$having = '',
531
-	$serveur = '',
532
-	$requeter = true
524
+    $select,
525
+    $from,
526
+    $where = '',
527
+    $groupby = array(),
528
+    $orderby = '',
529
+    $limit = '',
530
+    $having = '',
531
+    $serveur = '',
532
+    $requeter = true
533 533
 ) {
534 534
 
535
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
536
-	$prefixe = $connexion['prefixe'];
537
-	$link = $connexion['link'];
538
-	$db = $connexion['db'];
539
-
540
-	$limit = preg_match("/^\s*(([0-9]+),)?\s*([0-9]+)\s*$/", $limit, $limatch);
541
-	if ($limit) {
542
-		$offset = $limatch[2];
543
-		$count = $limatch[3];
544
-	}
545
-
546
-	$select = spip_pg_frommysql($select);
547
-
548
-	// si pas de tri explicitement demande, le GROUP BY ne
549
-	// contient que la clef primaire.
550
-	// lui ajouter alors le champ de tri par defaut
551
-	if (preg_match("/FIELD\(([a-z]+\.[a-z]+),/i", $orderby[0], $groupbyplus)) {
552
-		$groupby[] = $groupbyplus[1];
553
-	}
554
-
555
-	$orderby = spip_pg_orderby($orderby, $select);
556
-
557
-	if ($having) {
558
-		if (is_array($having)) {
559
-			$having = join("\n\tAND ", array_map('calculer_pg_where', $having));
560
-		}
561
-	}
562
-	$from = spip_pg_from($from, $prefixe);
563
-	$query = "SELECT " . $select
564
-		. (!$from ? '' : "\nFROM $from")
565
-		. (!$where ? '' : ("\nWHERE " . (!is_array($where) ? calculer_pg_where($where) : (join("\n\tAND ",
566
-				array_map('calculer_pg_where', $where))))))
567
-		. spip_pg_groupby($groupby, $from, $select)
568
-		. (!$having ? '' : "\nHAVING $having")
569
-		. ($orderby ? ("\nORDER BY $orderby") : '')
570
-		. (!$limit ? '' : (" LIMIT $count" . (!$offset ? '' : " OFFSET $offset")));
571
-
572
-	// renvoyer la requete inerte si demandee
573
-	if ($requeter === false) {
574
-		return $query;
575
-	}
576
-
577
-	$r = spip_pg_trace_query($query, $serveur);
578
-
579
-	return $r ? $r : $query;;
535
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
536
+    $prefixe = $connexion['prefixe'];
537
+    $link = $connexion['link'];
538
+    $db = $connexion['db'];
539
+
540
+    $limit = preg_match("/^\s*(([0-9]+),)?\s*([0-9]+)\s*$/", $limit, $limatch);
541
+    if ($limit) {
542
+        $offset = $limatch[2];
543
+        $count = $limatch[3];
544
+    }
545
+
546
+    $select = spip_pg_frommysql($select);
547
+
548
+    // si pas de tri explicitement demande, le GROUP BY ne
549
+    // contient que la clef primaire.
550
+    // lui ajouter alors le champ de tri par defaut
551
+    if (preg_match("/FIELD\(([a-z]+\.[a-z]+),/i", $orderby[0], $groupbyplus)) {
552
+        $groupby[] = $groupbyplus[1];
553
+    }
554
+
555
+    $orderby = spip_pg_orderby($orderby, $select);
556
+
557
+    if ($having) {
558
+        if (is_array($having)) {
559
+            $having = join("\n\tAND ", array_map('calculer_pg_where', $having));
560
+        }
561
+    }
562
+    $from = spip_pg_from($from, $prefixe);
563
+    $query = "SELECT " . $select
564
+        . (!$from ? '' : "\nFROM $from")
565
+        . (!$where ? '' : ("\nWHERE " . (!is_array($where) ? calculer_pg_where($where) : (join("\n\tAND ",
566
+                array_map('calculer_pg_where', $where))))))
567
+        . spip_pg_groupby($groupby, $from, $select)
568
+        . (!$having ? '' : "\nHAVING $having")
569
+        . ($orderby ? ("\nORDER BY $orderby") : '')
570
+        . (!$limit ? '' : (" LIMIT $count" . (!$offset ? '' : " OFFSET $offset")));
571
+
572
+    // renvoyer la requete inerte si demandee
573
+    if ($requeter === false) {
574
+        return $query;
575
+    }
576
+
577
+    $r = spip_pg_trace_query($query, $serveur);
578
+
579
+    return $r ? $r : $query;;
580 580
 }
581 581
 
582 582
 // Le traitement des prefixes de table dans un Select se limite au FROM
@@ -584,28 +584,28 @@  discard block
 block discarded – undo
584 584
 
585 585
 // https://code.spip.net/@spip_pg_from
586 586
 function spip_pg_from($from, $prefixe) {
587
-	if (is_array($from)) {
588
-		$from = spip_pg_select_as($from);
589
-	}
587
+    if (is_array($from)) {
588
+        $from = spip_pg_select_as($from);
589
+    }
590 590
 
591
-	return !$prefixe ? $from : preg_replace('/(\b)spip_/', '\1' . $prefixe . '_', $from);
591
+    return !$prefixe ? $from : preg_replace('/(\b)spip_/', '\1' . $prefixe . '_', $from);
592 592
 }
593 593
 
594 594
 // https://code.spip.net/@spip_pg_orderby
595 595
 function spip_pg_orderby($order, $select) {
596
-	$res = array();
597
-	$arg = (is_array($order) ? $order : preg_split('/\s*,\s*/', $order));
596
+    $res = array();
597
+    $arg = (is_array($order) ? $order : preg_split('/\s*,\s*/', $order));
598 598
 
599
-	foreach ($arg as $v) {
600
-		if (preg_match('/(case\s+.*?else\s+0\s+end)\s*AS\s+' . $v . '/', $select, $m)) {
599
+    foreach ($arg as $v) {
600
+        if (preg_match('/(case\s+.*?else\s+0\s+end)\s*AS\s+' . $v . '/', $select, $m)) {
601 601
 
602
-			$res[] = $m[1];
603
-		} else {
604
-			$res[] = $v;
605
-		}
606
-	}
602
+            $res[] = $m[1];
603
+        } else {
604
+            $res[] = $v;
605
+        }
606
+    }
607 607
 
608
-	return spip_pg_frommysql(join(',', $res));
608
+    return spip_pg_frommysql(join(',', $res));
609 609
 }
610 610
 
611 611
 // Conversion a l'arrach' des jointures MySQL en jointures PG
@@ -614,57 +614,57 @@  discard block
 block discarded – undo
614 614
 
615 615
 // https://code.spip.net/@spip_pg_groupby
616 616
 function spip_pg_groupby($groupby, $from, $select) {
617
-	$join = strpos($from, ",");
618
-	// ismplifier avant de decouper
619
-	if (is_string($select)) // fct SQL sur colonne et constante apostrophee ==> la colonne
620
-	{
621
-		$select = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/', '\\1', $select);
622
-	}
623
-
624
-	if ($join or $groupby) {
625
-		$join = is_array($select) ? $select : explode(", ", $select);
626
-	}
627
-	if ($join) {
628
-		// enlever les 0 as points, '', ...
629
-		foreach ($join as $k => $v) {
630
-			$v = str_replace('DISTINCT ', '', $v);
631
-			// fct SQL sur colonne et constante apostrophee ==> la colonne
632
-			$v = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/', '\\1', $v);
633
-			$v = preg_replace('/CAST\(\s*([^(),\' ]*\s+)as\s*\w+\)/', '\\1', $v);
634
-			// resultat d'agregat ne sont pas a mettre dans le groupby
635
-			$v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)(\s*AS\s+\w+)\s*,?/i', '', $v);
636
-			// idem sans AS (fetch numerique)
637
-			$v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)\s*,?/i', '', $v);
638
-			// des AS simples : on garde le cote droit du AS
639
-			$v = preg_replace('/^.*\sAS\s+(\w+)\s*$/i', '\\1', $v);
640
-			// ne reste plus que les vrais colonnes, ou des constantes a virer
641
-			if (preg_match(',^[\'"],', $v) or is_numeric($v)) {
642
-				unset($join[$k]);
643
-			} else {
644
-				$join[$k] = trim($v);
645
-			}
646
-		}
647
-		$join = array_diff($join, array(''));
648
-		$join = implode(',', $join);
649
-	}
650
-	if (is_array($groupby)) {
651
-		$groupby = join(',', $groupby);
652
-	}
653
-	if ($join) {
654
-		$groupby = $groupby ? "$groupby, $join" : $join;
655
-	}
656
-	if (!$groupby) {
657
-		return '';
658
-	}
659
-
660
-	$groupby = spip_pg_frommysql($groupby);
661
-	// Ne pas mettre dans le Group-By des valeurs numeriques
662
-	// issue de prepare_recherche
663
-	$groupby = preg_replace('/^\s*\d+\s+AS\s+\w+\s*,?\s*/i', '', $groupby);
664
-	$groupby = preg_replace('/,\s*\d+\s+AS\s+\w+\s*/i', '', $groupby);
665
-	$groupby = preg_replace('/\s+AS\s+\w+\s*/i', '', $groupby);
666
-
667
-	return "\nGROUP BY $groupby";
617
+    $join = strpos($from, ",");
618
+    // ismplifier avant de decouper
619
+    if (is_string($select)) // fct SQL sur colonne et constante apostrophee ==> la colonne
620
+    {
621
+        $select = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/', '\\1', $select);
622
+    }
623
+
624
+    if ($join or $groupby) {
625
+        $join = is_array($select) ? $select : explode(", ", $select);
626
+    }
627
+    if ($join) {
628
+        // enlever les 0 as points, '', ...
629
+        foreach ($join as $k => $v) {
630
+            $v = str_replace('DISTINCT ', '', $v);
631
+            // fct SQL sur colonne et constante apostrophee ==> la colonne
632
+            $v = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/', '\\1', $v);
633
+            $v = preg_replace('/CAST\(\s*([^(),\' ]*\s+)as\s*\w+\)/', '\\1', $v);
634
+            // resultat d'agregat ne sont pas a mettre dans le groupby
635
+            $v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)(\s*AS\s+\w+)\s*,?/i', '', $v);
636
+            // idem sans AS (fetch numerique)
637
+            $v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)\s*,?/i', '', $v);
638
+            // des AS simples : on garde le cote droit du AS
639
+            $v = preg_replace('/^.*\sAS\s+(\w+)\s*$/i', '\\1', $v);
640
+            // ne reste plus que les vrais colonnes, ou des constantes a virer
641
+            if (preg_match(',^[\'"],', $v) or is_numeric($v)) {
642
+                unset($join[$k]);
643
+            } else {
644
+                $join[$k] = trim($v);
645
+            }
646
+        }
647
+        $join = array_diff($join, array(''));
648
+        $join = implode(',', $join);
649
+    }
650
+    if (is_array($groupby)) {
651
+        $groupby = join(',', $groupby);
652
+    }
653
+    if ($join) {
654
+        $groupby = $groupby ? "$groupby, $join" : $join;
655
+    }
656
+    if (!$groupby) {
657
+        return '';
658
+    }
659
+
660
+    $groupby = spip_pg_frommysql($groupby);
661
+    // Ne pas mettre dans le Group-By des valeurs numeriques
662
+    // issue de prepare_recherche
663
+    $groupby = preg_replace('/^\s*\d+\s+AS\s+\w+\s*,?\s*/i', '', $groupby);
664
+    $groupby = preg_replace('/,\s*\d+\s+AS\s+\w+\s*/i', '', $groupby);
665
+    $groupby = preg_replace('/\s+AS\s+\w+\s*/i', '', $groupby);
666
+
667
+    return "\nGROUP BY $groupby";
668 668
 }
669 669
 
670 670
 // Conversion des operateurs MySQL en PG
@@ -676,472 +676,472 @@  discard block
 block discarded – undo
676 676
 
677 677
 // https://code.spip.net/@spip_pg_frommysql
678 678
 function spip_pg_frommysql($arg) {
679
-	if (is_array($arg)) {
680
-		$arg = join(", ", $arg);
681
-	}
679
+    if (is_array($arg)) {
680
+        $arg = join(", ", $arg);
681
+    }
682 682
 
683
-	$res = spip_pg_fromfield($arg);
683
+    $res = spip_pg_fromfield($arg);
684 684
 
685
-	$res = preg_replace('/\brand[(][)]/i', 'random()', $res);
685
+    $res = preg_replace('/\brand[(][)]/i', 'random()', $res);
686 686
 
687
-	$res = preg_replace('/\b0\.0[+]([a-zA-Z0-9_.]+)\s*/',
688
-		'CAST(substring(\1, \'^ *[0-9.]+\') as float)',
689
-		$res);
690
-	$res = preg_replace('/\b0[+]([a-zA-Z0-9_.]+)\s*/',
691
-		'CAST(substring(\1, \'^ *[0-9]+\') as int)',
692
-		$res);
693
-	$res = preg_replace('/\bconv[(]([^,]*)[^)]*[)]/i',
694
-		'CAST(substring(\1, \'^ *[0-9]+\') as int)',
695
-		$res);
687
+    $res = preg_replace('/\b0\.0[+]([a-zA-Z0-9_.]+)\s*/',
688
+        'CAST(substring(\1, \'^ *[0-9.]+\') as float)',
689
+        $res);
690
+    $res = preg_replace('/\b0[+]([a-zA-Z0-9_.]+)\s*/',
691
+        'CAST(substring(\1, \'^ *[0-9]+\') as int)',
692
+        $res);
693
+    $res = preg_replace('/\bconv[(]([^,]*)[^)]*[)]/i',
694
+        'CAST(substring(\1, \'^ *[0-9]+\') as int)',
695
+        $res);
696 696
 
697
-	$res = preg_replace('/UNIX_TIMESTAMP\s*[(]\s*[)]/',
698
-		' EXTRACT(epoch FROM NOW())', $res);
697
+    $res = preg_replace('/UNIX_TIMESTAMP\s*[(]\s*[)]/',
698
+        ' EXTRACT(epoch FROM NOW())', $res);
699 699
 
700
-	// la fonction md5(integer) n'est pas connu en pg
701
-	// il faut donc forcer les types en text (cas de md5(id_article))
702
-	$res = preg_replace('/md5\s*[(]([^)]*)[)]/i',
703
-		'MD5(CAST(\1 AS text))', $res);
700
+    // la fonction md5(integer) n'est pas connu en pg
701
+    // il faut donc forcer les types en text (cas de md5(id_article))
702
+    $res = preg_replace('/md5\s*[(]([^)]*)[)]/i',
703
+        'MD5(CAST(\1 AS text))', $res);
704 704
 
705
-	$res = preg_replace('/UNIX_TIMESTAMP\s*[(]([^)]*)[)]/',
706
-		' EXTRACT(epoch FROM \1)', $res);
705
+    $res = preg_replace('/UNIX_TIMESTAMP\s*[(]([^)]*)[)]/',
706
+        ' EXTRACT(epoch FROM \1)', $res);
707 707
 
708
-	$res = preg_replace('/\bDAYOFMONTH\s*[(]([^()]*([(][^()]*[)][^()]*)*[^)]*)[)]/',
709
-		' EXTRACT(day FROM \1)',
710
-		$res);
708
+    $res = preg_replace('/\bDAYOFMONTH\s*[(]([^()]*([(][^()]*[)][^()]*)*[^)]*)[)]/',
709
+        ' EXTRACT(day FROM \1)',
710
+        $res);
711 711
 
712
-	$res = preg_replace('/\bMONTH\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/',
713
-		' EXTRACT(month FROM \1)',
714
-		$res);
712
+    $res = preg_replace('/\bMONTH\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/',
713
+        ' EXTRACT(month FROM \1)',
714
+        $res);
715 715
 
716
-	$res = preg_replace('/\bYEAR\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/',
717
-		' EXTRACT(year FROM \1)',
718
-		$res);
716
+    $res = preg_replace('/\bYEAR\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/',
717
+        ' EXTRACT(year FROM \1)',
718
+        $res);
719 719
 
720
-	$res = preg_replace('/TO_DAYS\s*[(]([^()]*([(][^)]*[)][()]*)*)[)]/',
721
-		' EXTRACT(day FROM \1 - \'0001-01-01\')',
722
-		$res);
720
+    $res = preg_replace('/TO_DAYS\s*[(]([^()]*([(][^)]*[)][()]*)*)[)]/',
721
+        ' EXTRACT(day FROM \1 - \'0001-01-01\')',
722
+        $res);
723 723
 
724
-	$res = preg_replace("/(EXTRACT[(][^ ]* FROM *)\"([^\"]*)\"/", '\1\'\2\'', $res);
724
+    $res = preg_replace("/(EXTRACT[(][^ ]* FROM *)\"([^\"]*)\"/", '\1\'\2\'', $res);
725 725
 
726
-	$res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m%d\'[)]/', 'to_char(\1, \'YYYYMMDD\')', $res);
726
+    $res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m%d\'[)]/', 'to_char(\1, \'YYYYMMDD\')', $res);
727 727
 
728
-	$res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m\'[)]/', 'to_char(\1, \'YYYYMM\')', $res);
728
+    $res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m\'[)]/', 'to_char(\1, \'YYYYMM\')', $res);
729 729
 
730
-	$res = preg_replace('/DATE_SUB\s*[(]([^,]*),/', '(\1 -', $res);
731
-	$res = preg_replace('/DATE_ADD\s*[(]([^,]*),/', '(\1 +', $res);
732
-	$res = preg_replace('/INTERVAL\s+(\d+\s+\w+)/', 'INTERVAL \'\1\'', $res);
733
-	$res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\s+\d+:\d+(:\d+)\')/', '\1 timestamp \2', $res);
734
-	$res = preg_replace('/(\'\d+-\d+-\d+\s+\d+:\d+:\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res);
730
+    $res = preg_replace('/DATE_SUB\s*[(]([^,]*),/', '(\1 -', $res);
731
+    $res = preg_replace('/DATE_ADD\s*[(]([^,]*),/', '(\1 +', $res);
732
+    $res = preg_replace('/INTERVAL\s+(\d+\s+\w+)/', 'INTERVAL \'\1\'', $res);
733
+    $res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\s+\d+:\d+(:\d+)\')/', '\1 timestamp \2', $res);
734
+    $res = preg_replace('/(\'\d+-\d+-\d+\s+\d+:\d+:\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res);
735 735
 
736
-	$res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\')/', '\1 timestamp \2', $res);
737
-	$res = preg_replace('/(\'\d+-\d+-\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res);
736
+    $res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\')/', '\1 timestamp \2', $res);
737
+    $res = preg_replace('/(\'\d+-\d+-\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res);
738 738
 
739
-	$res = preg_replace('/(timestamp .\d+)-00-/', '\1-01-', $res);
740
-	$res = preg_replace('/(timestamp .\d+-\d+)-00/', '\1-01', $res);
739
+    $res = preg_replace('/(timestamp .\d+)-00-/', '\1-01-', $res);
740
+    $res = preg_replace('/(timestamp .\d+-\d+)-00/', '\1-01', $res);
741 741
 # correct en theorie mais produit des debordements arithmetiques
742 742
 #	$res = preg_replace("/(EXTRACT[(][^ ]* FROM *)(timestamp *'[^']*' *[+-] *timestamp *'[^']*') *[)]/", '\2', $res);
743
-	$res = preg_replace("/(EXTRACT[(][^ ]* FROM *)('[^']*')/", '\1 timestamp \2', $res);
744
-	$res = preg_replace("/\sLIKE\s+/", ' ILIKE ', $res);
743
+    $res = preg_replace("/(EXTRACT[(][^ ]* FROM *)('[^']*')/", '\1 timestamp \2', $res);
744
+    $res = preg_replace("/\sLIKE\s+/", ' ILIKE ', $res);
745 745
 
746
-	return str_replace('REGEXP', '~', $res);
746
+    return str_replace('REGEXP', '~', $res);
747 747
 }
748 748
 
749 749
 // https://code.spip.net/@spip_pg_fromfield
750 750
 function spip_pg_fromfield($arg) {
751
-	while (preg_match('/^(.*?)FIELD\s*\(([^,]*)((,[^,)]*)*)\)/', $arg, $m)) {
752
-
753
-		preg_match_all('/,([^,]*)/', $m[3], $r, PREG_PATTERN_ORDER);
754
-		$res = '';
755
-		$n = 0;
756
-		$index = $m[2];
757
-		foreach ($r[1] as $v) {
758
-			$n++;
759
-			$res .= "\nwhen $index=$v then $n";
760
-		}
761
-		$arg = $m[1] . "case $res else 0 end "
762
-			. substr($arg, strlen($m[0]));
763
-	}
764
-
765
-	return $arg;
751
+    while (preg_match('/^(.*?)FIELD\s*\(([^,]*)((,[^,)]*)*)\)/', $arg, $m)) {
752
+
753
+        preg_match_all('/,([^,]*)/', $m[3], $r, PREG_PATTERN_ORDER);
754
+        $res = '';
755
+        $n = 0;
756
+        $index = $m[2];
757
+        foreach ($r[1] as $v) {
758
+            $n++;
759
+            $res .= "\nwhen $index=$v then $n";
760
+        }
761
+        $arg = $m[1] . "case $res else 0 end "
762
+            . substr($arg, strlen($m[0]));
763
+    }
764
+
765
+    return $arg;
766 766
 }
767 767
 
768 768
 // https://code.spip.net/@calculer_pg_where
769 769
 function calculer_pg_where($v) {
770
-	if (!is_array($v)) {
771
-		return spip_pg_frommysql($v);
772
-	}
773
-
774
-	$op = str_replace('REGEXP', '~', array_shift($v));
775
-	if (!($n = count($v))) {
776
-		return $op;
777
-	} else {
778
-		$arg = calculer_pg_where(array_shift($v));
779
-		if ($n == 1) {
780
-			return "$op($arg)";
781
-		} else {
782
-			$arg2 = calculer_pg_where(array_shift($v));
783
-			if ($n == 2) {
784
-				return "($arg $op $arg2)";
785
-			} else {
786
-				return "($arg $op ($arg2) : $v[0])";
787
-			}
788
-		}
789
-	}
770
+    if (!is_array($v)) {
771
+        return spip_pg_frommysql($v);
772
+    }
773
+
774
+    $op = str_replace('REGEXP', '~', array_shift($v));
775
+    if (!($n = count($v))) {
776
+        return $op;
777
+    } else {
778
+        $arg = calculer_pg_where(array_shift($v));
779
+        if ($n == 1) {
780
+            return "$op($arg)";
781
+        } else {
782
+            $arg2 = calculer_pg_where(array_shift($v));
783
+            if ($n == 2) {
784
+                return "($arg $op $arg2)";
785
+            } else {
786
+                return "($arg $op ($arg2) : $v[0])";
787
+            }
788
+        }
789
+    }
790 790
 }
791 791
 
792 792
 
793 793
 // https://code.spip.net/@calculer_pg_expression
794 794
 function calculer_pg_expression($expression, $v, $join = 'AND') {
795
-	if (empty($v)) {
796
-		return '';
797
-	}
795
+    if (empty($v)) {
796
+        return '';
797
+    }
798 798
 
799
-	$exp = "\n$expression ";
799
+    $exp = "\n$expression ";
800 800
 
801
-	if (!is_array($v)) {
802
-		$v = array($v);
803
-	}
801
+    if (!is_array($v)) {
802
+        $v = array($v);
803
+    }
804 804
 
805
-	if (strtoupper($join) === 'AND') {
806
-		return $exp . join("\n\t$join ", array_map('calculer_pg_where', $v));
807
-	} else {
808
-		return $exp . join($join, $v);
809
-	}
805
+    if (strtoupper($join) === 'AND') {
806
+        return $exp . join("\n\t$join ", array_map('calculer_pg_where', $v));
807
+    } else {
808
+        return $exp . join($join, $v);
809
+    }
810 810
 }
811 811
 
812 812
 // https://code.spip.net/@spip_pg_select_as
813 813
 function spip_pg_select_as($args) {
814
-	$argsas = "";
815
-	foreach ($args as $k => $v) {
816
-		if (substr($k, -1) == '@') {
817
-			// c'est une jointure qui se refere au from precedent
818
-			// pas de virgule
819
-			$argsas .= '  ' . $v;
820
-		} else {
821
-			$as = '';
822
-			//  spip_log("$k : $v", _LOG_DEBUG);
823
-			if (!is_numeric($k)) {
824
-				if (preg_match('/\.(.*)$/', $k, $r)) {
825
-					$v = $k;
826
-				} elseif ($v != $k) {
827
-					$p = strpos($v, " ");
828
-					if ($p) {
829
-						$v = substr($v, 0, $p) . " AS $k" . substr($v, $p);
830
-					} else {
831
-						$as = " AS $k";
832
-					}
833
-				}
834
-			}
835
-			// spip_log("subs $k : $v avec $as", _LOG_DEBUG);
836
-			// if (strpos($v, 'JOIN') === false)  $argsas .= ', ';
837
-			$argsas .= ', ' . $v . $as;
838
-		}
839
-	}
840
-
841
-	return substr($argsas, 2);
814
+    $argsas = "";
815
+    foreach ($args as $k => $v) {
816
+        if (substr($k, -1) == '@') {
817
+            // c'est une jointure qui se refere au from precedent
818
+            // pas de virgule
819
+            $argsas .= '  ' . $v;
820
+        } else {
821
+            $as = '';
822
+            //  spip_log("$k : $v", _LOG_DEBUG);
823
+            if (!is_numeric($k)) {
824
+                if (preg_match('/\.(.*)$/', $k, $r)) {
825
+                    $v = $k;
826
+                } elseif ($v != $k) {
827
+                    $p = strpos($v, " ");
828
+                    if ($p) {
829
+                        $v = substr($v, 0, $p) . " AS $k" . substr($v, $p);
830
+                    } else {
831
+                        $as = " AS $k";
832
+                    }
833
+                }
834
+            }
835
+            // spip_log("subs $k : $v avec $as", _LOG_DEBUG);
836
+            // if (strpos($v, 'JOIN') === false)  $argsas .= ', ';
837
+            $argsas .= ', ' . $v . $as;
838
+        }
839
+    }
840
+
841
+    return substr($argsas, 2);
842 842
 }
843 843
 
844 844
 // https://code.spip.net/@spip_pg_fetch
845 845
 function spip_pg_fetch($res, $t = '', $serveur = '', $requeter = true) {
846 846
 
847
-	if ($res) {
848
-		$res = pg_fetch_array($res, null, PGSQL_ASSOC);
849
-	}
847
+    if ($res) {
848
+        $res = pg_fetch_array($res, null, PGSQL_ASSOC);
849
+    }
850 850
 
851
-	return $res;
851
+    return $res;
852 852
 }
853 853
 
854 854
 function spip_pg_seek($r, $row_number, $serveur = '', $requeter = true) {
855
-	if ($r) {
856
-		return pg_result_seek($r, $row_number);
857
-	}
855
+    if ($r) {
856
+        return pg_result_seek($r, $row_number);
857
+    }
858 858
 }
859 859
 
860 860
 
861 861
 // https://code.spip.net/@spip_pg_countsel
862 862
 function spip_pg_countsel(
863
-	$from = array(),
864
-	$where = array(),
865
-	$groupby = array(),
866
-	$having = array(),
867
-	$serveur = '',
868
-	$requeter = true
863
+    $from = array(),
864
+    $where = array(),
865
+    $groupby = array(),
866
+    $having = array(),
867
+    $serveur = '',
868
+    $requeter = true
869 869
 ) {
870
-	$c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
871
-	$r = spip_pg_select("COUNT($c)", $from, $where, '', '', '', $having, $serveur, $requeter);
872
-	if (!$requeter) {
873
-		return $r;
874
-	}
875
-	if (!is_resource($r)) {
876
-		return 0;
877
-	}
878
-	list($c) = pg_fetch_array($r, null, PGSQL_NUM);
879
-
880
-	return $c;
870
+    $c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby)));
871
+    $r = spip_pg_select("COUNT($c)", $from, $where, '', '', '', $having, $serveur, $requeter);
872
+    if (!$requeter) {
873
+        return $r;
874
+    }
875
+    if (!is_resource($r)) {
876
+        return 0;
877
+    }
878
+    list($c) = pg_fetch_array($r, null, PGSQL_NUM);
879
+
880
+    return $c;
881 881
 }
882 882
 
883 883
 // https://code.spip.net/@spip_pg_count
884 884
 function spip_pg_count($res, $serveur = '', $requeter = true) {
885
-	return !$res ? 0 : pg_numrows($res);
885
+    return !$res ? 0 : pg_numrows($res);
886 886
 }
887 887
 
888 888
 // https://code.spip.net/@spip_pg_free
889 889
 function spip_pg_free($res, $serveur = '', $requeter = true) {
890
-	// rien a faire en postgres
890
+    // rien a faire en postgres
891 891
 }
892 892
 
893 893
 // https://code.spip.net/@spip_pg_delete
894 894
 function spip_pg_delete($table, $where = '', $serveur = '', $requeter = true) {
895 895
 
896
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
897
-	$table = prefixer_table_spip($table, $connexion['prefixe']);
896
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
897
+    $table = prefixer_table_spip($table, $connexion['prefixe']);
898 898
 
899
-	$query = calculer_pg_expression('DELETE FROM', $table, ',')
900
-		. calculer_pg_expression('WHERE', $where, 'AND');
899
+    $query = calculer_pg_expression('DELETE FROM', $table, ',')
900
+        . calculer_pg_expression('WHERE', $where, 'AND');
901 901
 
902
-	// renvoyer la requete inerte si demandee
903
-	if (!$requeter) {
904
-		return $query;
905
-	}
902
+    // renvoyer la requete inerte si demandee
903
+    if (!$requeter) {
904
+        return $query;
905
+    }
906 906
 
907
-	$res = spip_pg_trace_query($query, $serveur);
908
-	if ($res) {
909
-		return pg_affected_rows($res);
910
-	} else {
911
-		return false;
912
-	}
907
+    $res = spip_pg_trace_query($query, $serveur);
908
+    if ($res) {
909
+        return pg_affected_rows($res);
910
+    } else {
911
+        return false;
912
+    }
913 913
 }
914 914
 
915 915
 // https://code.spip.net/@spip_pg_insert
916 916
 function spip_pg_insert($table, $champs, $valeurs, $desc = array(), $serveur = '', $requeter = true) {
917
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
918
-	$prefixe = $connexion['prefixe'];
919
-	$link = $connexion['link'];
920
-
921
-	if (!$desc) {
922
-		$desc = description_table($table, $serveur);
923
-	}
924
-	$seq = spip_pg_sequence($table, true);
925
-	// si pas de cle primaire dans l'insertion, renvoyer curval
926
-	if (!preg_match(",\b$seq\b,", $champs)) {
927
-		$seq = spip_pg_sequence($table);
928
-		$seq = prefixer_table_spip($seq, $prefixe);
929
-		$seq = "currval('$seq')";
930
-	}
931
-
932
-	$table = prefixer_table_spip($table, $prefixe);
933
-	$ret = !$seq ? '' : (" RETURNING $seq");
934
-	$ins = (strlen($champs) < 3)
935
-		? " DEFAULT VALUES"
936
-		: "$champs VALUES $valeurs";
937
-	$q = "INSERT INTO $table $ins $ret";
938
-	if (!$requeter) {
939
-		return $q;
940
-	}
941
-	$connexion['last'] = $q;
942
-	$r = spip_pg_query_simple($link, $q);
917
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
918
+    $prefixe = $connexion['prefixe'];
919
+    $link = $connexion['link'];
920
+
921
+    if (!$desc) {
922
+        $desc = description_table($table, $serveur);
923
+    }
924
+    $seq = spip_pg_sequence($table, true);
925
+    // si pas de cle primaire dans l'insertion, renvoyer curval
926
+    if (!preg_match(",\b$seq\b,", $champs)) {
927
+        $seq = spip_pg_sequence($table);
928
+        $seq = prefixer_table_spip($seq, $prefixe);
929
+        $seq = "currval('$seq')";
930
+    }
931
+
932
+    $table = prefixer_table_spip($table, $prefixe);
933
+    $ret = !$seq ? '' : (" RETURNING $seq");
934
+    $ins = (strlen($champs) < 3)
935
+        ? " DEFAULT VALUES"
936
+        : "$champs VALUES $valeurs";
937
+    $q = "INSERT INTO $table $ins $ret";
938
+    if (!$requeter) {
939
+        return $q;
940
+    }
941
+    $connexion['last'] = $q;
942
+    $r = spip_pg_query_simple($link, $q);
943 943
 #	spip_log($q,'pg.'._LOG_DEBUG);
944
-	if ($r) {
945
-		if (!$ret) {
946
-			return 0;
947
-		}
948
-		if ($r2 = pg_fetch_array($r, null, PGSQL_NUM)) {
949
-			return $r2[0];
950
-		}
951
-	}
952
-
953
-	return false;
944
+    if ($r) {
945
+        if (!$ret) {
946
+            return 0;
947
+        }
948
+        if ($r2 = pg_fetch_array($r, null, PGSQL_NUM)) {
949
+            return $r2[0];
950
+        }
951
+    }
952
+
953
+    return false;
954 954
 }
955 955
 
956 956
 // https://code.spip.net/@spip_pg_insertq
957 957
 function spip_pg_insertq($table, $couples = array(), $desc = array(), $serveur = '', $requeter = true) {
958 958
 
959
-	if (!$desc) {
960
-		$desc = description_table($table, $serveur);
961
-	}
962
-	if (!$desc) {
963
-		die("$table insertion sans description");
964
-	}
965
-	$fields = $desc['field'];
959
+    if (!$desc) {
960
+        $desc = description_table($table, $serveur);
961
+    }
962
+    if (!$desc) {
963
+        die("$table insertion sans description");
964
+    }
965
+    $fields = $desc['field'];
966 966
 
967
-	foreach ($couples as $champ => $val) {
968
-		$couples[$champ] = spip_pg_cite($val, $fields[$champ]);
969
-	}
967
+    foreach ($couples as $champ => $val) {
968
+        $couples[$champ] = spip_pg_cite($val, $fields[$champ]);
969
+    }
970 970
 
971
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
972
-	$couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
971
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
972
+    $couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
973 973
 
974
-	return spip_pg_insert($table, "(" . join(',', array_keys($couples)) . ")", "(" . join(',', $couples) . ")", $desc,
975
-		$serveur, $requeter);
974
+    return spip_pg_insert($table, "(" . join(',', array_keys($couples)) . ")", "(" . join(',', $couples) . ")", $desc,
975
+        $serveur, $requeter);
976 976
 }
977 977
 
978 978
 
979 979
 // https://code.spip.net/@spip_pg_insertq_multi
980 980
 function spip_pg_insertq_multi($table, $tab_couples = array(), $desc = array(), $serveur = '', $requeter = true) {
981 981
 
982
-	if (!$desc) {
983
-		$desc = description_table($table, $serveur);
984
-	}
985
-	if (!$desc) {
986
-		die("$table insertion sans description");
987
-	}
988
-	$fields = isset($desc['field']) ? $desc['field'] : array();
989
-
990
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
991
-	// une premiere fois pour ajouter maj dans les cles
992
-	$c = isset($tab_couples[0]) ? $tab_couples[0] : array();
993
-	$les_cles = spip_pg_ajouter_champs_timestamp($table, $c, $desc, $serveur);
994
-
995
-	$cles = "(" . join(',', array_keys($les_cles)) . ')';
996
-	$valeurs = array();
997
-	foreach ($tab_couples as $couples) {
998
-		foreach ($couples as $champ => $val) {
999
-			$couples[$champ] = spip_pg_cite($val, $fields[$champ]);
1000
-		}
1001
-		// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1002
-		$couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1003
-
1004
-		$valeurs[] = '(' . join(',', $couples) . ')';
1005
-	}
1006
-	$valeurs = implode(', ', $valeurs);
1007
-
1008
-	return spip_pg_insert($table, $cles, $valeurs, $desc, $serveur, $requeter);
982
+    if (!$desc) {
983
+        $desc = description_table($table, $serveur);
984
+    }
985
+    if (!$desc) {
986
+        die("$table insertion sans description");
987
+    }
988
+    $fields = isset($desc['field']) ? $desc['field'] : array();
989
+
990
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
991
+    // une premiere fois pour ajouter maj dans les cles
992
+    $c = isset($tab_couples[0]) ? $tab_couples[0] : array();
993
+    $les_cles = spip_pg_ajouter_champs_timestamp($table, $c, $desc, $serveur);
994
+
995
+    $cles = "(" . join(',', array_keys($les_cles)) . ')';
996
+    $valeurs = array();
997
+    foreach ($tab_couples as $couples) {
998
+        foreach ($couples as $champ => $val) {
999
+            $couples[$champ] = spip_pg_cite($val, $fields[$champ]);
1000
+        }
1001
+        // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1002
+        $couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1003
+
1004
+        $valeurs[] = '(' . join(',', $couples) . ')';
1005
+    }
1006
+    $valeurs = implode(', ', $valeurs);
1007
+
1008
+    return spip_pg_insert($table, $cles, $valeurs, $desc, $serveur, $requeter);
1009 1009
 }
1010 1010
 
1011 1011
 
1012 1012
 // https://code.spip.net/@spip_pg_update
1013 1013
 function spip_pg_update($table, $couples, $where = '', $desc = '', $serveur = '', $requeter = true) {
1014 1014
 
1015
-	if (!$couples) {
1016
-		return;
1017
-	}
1018
-	$connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1019
-	$table = prefixer_table_spip($table, $connexion['prefixe']);
1015
+    if (!$couples) {
1016
+        return;
1017
+    }
1018
+    $connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1019
+    $table = prefixer_table_spip($table, $connexion['prefixe']);
1020 1020
 
1021
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1022
-	$couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1021
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1022
+    $couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur);
1023 1023
 
1024
-	$set = array();
1025
-	foreach ($couples as $champ => $val) {
1026
-		$set[] = $champ . '=' . $val;
1027
-	}
1024
+    $set = array();
1025
+    foreach ($couples as $champ => $val) {
1026
+        $set[] = $champ . '=' . $val;
1027
+    }
1028 1028
 
1029
-	$query = calculer_pg_expression('UPDATE', $table, ',')
1030
-		. calculer_pg_expression('SET', $set, ',')
1031
-		. calculer_pg_expression('WHERE', $where, 'AND');
1029
+    $query = calculer_pg_expression('UPDATE', $table, ',')
1030
+        . calculer_pg_expression('SET', $set, ',')
1031
+        . calculer_pg_expression('WHERE', $where, 'AND');
1032 1032
 
1033
-	// renvoyer la requete inerte si demandee
1034
-	if (!$requeter) {
1035
-		return $query;
1036
-	}
1033
+    // renvoyer la requete inerte si demandee
1034
+    if (!$requeter) {
1035
+        return $query;
1036
+    }
1037 1037
 
1038
-	return spip_pg_trace_query($query, $serveur);
1038
+    return spip_pg_trace_query($query, $serveur);
1039 1039
 }
1040 1040
 
1041 1041
 // idem, mais les valeurs sont des constantes a mettre entre apostrophes
1042 1042
 // sauf les expressions de date lorsqu'il s'agit de fonctions SQL (NOW etc)
1043 1043
 // https://code.spip.net/@spip_pg_updateq
1044 1044
 function spip_pg_updateq($table, $couples, $where = '', $desc = array(), $serveur = '', $requeter = true) {
1045
-	if (!$couples) {
1046
-		return;
1047
-	}
1048
-	if (!$desc) {
1049
-		$desc = description_table($table, $serveur);
1050
-	}
1051
-	$fields = $desc['field'];
1052
-	foreach ($couples as $k => $val) {
1053
-		$couples[$k] = spip_pg_cite($val, $fields[$k]);
1054
-	}
1055
-
1056
-	return spip_pg_update($table, $couples, $where, $desc, $serveur, $requeter);
1045
+    if (!$couples) {
1046
+        return;
1047
+    }
1048
+    if (!$desc) {
1049
+        $desc = description_table($table, $serveur);
1050
+    }
1051
+    $fields = $desc['field'];
1052
+    foreach ($couples as $k => $val) {
1053
+        $couples[$k] = spip_pg_cite($val, $fields[$k]);
1054
+    }
1055
+
1056
+    return spip_pg_update($table, $couples, $where, $desc, $serveur, $requeter);
1057 1057
 }
1058 1058
 
1059 1059
 
1060 1060
 // https://code.spip.net/@spip_pg_replace
1061 1061
 function spip_pg_replace($table, $values, $desc, $serveur = '', $requeter = true) {
1062
-	if (!$values) {
1063
-		spip_log("replace vide $table", 'pg.' . _LOG_AVERTISSEMENT);
1064
-
1065
-		return 0;
1066
-	}
1067
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1068
-	$prefixe = $connexion['prefixe'];
1069
-	$link = $connexion['link'];
1070
-
1071
-	if (!$desc) {
1072
-		$desc = description_table($table, $serveur);
1073
-	}
1074
-	if (!$desc) {
1075
-		die("$table insertion sans description");
1076
-	}
1077
-	$prim = $desc['key']['PRIMARY KEY'];
1078
-	$ids = preg_split('/,\s*/', $prim);
1079
-	$noprims = $prims = array();
1080
-	foreach ($values as $k => $v) {
1081
-		$values[$k] = $v = spip_pg_cite($v, $desc['field'][$k]);
1082
-
1083
-		if (!in_array($k, $ids)) {
1084
-			$noprims[$k] = "$k=$v";
1085
-		} else {
1086
-			$prims[$k] = "$k=$v";
1087
-		}
1088
-	}
1089
-
1090
-	// recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1091
-	$values = spip_pg_ajouter_champs_timestamp($table, $values, $desc, $serveur);
1092
-
1093
-	$where = join(' AND ', $prims);
1094
-	if (!$where) {
1095
-		return spip_pg_insert($table, "(" . join(',', array_keys($values)) . ")", "(" . join(',', $values) . ")", $desc,
1096
-			$serveur);
1097
-	}
1098
-	$couples = join(',', $noprims);
1099
-
1100
-	$seq = spip_pg_sequence($table);
1101
-	$table = prefixer_table_spip($table, $prefixe);
1102
-	$seq = prefixer_table_spip($seq, $prefixe);
1103
-
1104
-	$connexion['last'] = $q = "UPDATE $table SET $couples WHERE $where";
1105
-	if ($couples) {
1106
-		$couples = spip_pg_query_simple($link, $q);
1062
+    if (!$values) {
1063
+        spip_log("replace vide $table", 'pg.' . _LOG_AVERTISSEMENT);
1064
+
1065
+        return 0;
1066
+    }
1067
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1068
+    $prefixe = $connexion['prefixe'];
1069
+    $link = $connexion['link'];
1070
+
1071
+    if (!$desc) {
1072
+        $desc = description_table($table, $serveur);
1073
+    }
1074
+    if (!$desc) {
1075
+        die("$table insertion sans description");
1076
+    }
1077
+    $prim = $desc['key']['PRIMARY KEY'];
1078
+    $ids = preg_split('/,\s*/', $prim);
1079
+    $noprims = $prims = array();
1080
+    foreach ($values as $k => $v) {
1081
+        $values[$k] = $v = spip_pg_cite($v, $desc['field'][$k]);
1082
+
1083
+        if (!in_array($k, $ids)) {
1084
+            $noprims[$k] = "$k=$v";
1085
+        } else {
1086
+            $prims[$k] = "$k=$v";
1087
+        }
1088
+    }
1089
+
1090
+    // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci
1091
+    $values = spip_pg_ajouter_champs_timestamp($table, $values, $desc, $serveur);
1092
+
1093
+    $where = join(' AND ', $prims);
1094
+    if (!$where) {
1095
+        return spip_pg_insert($table, "(" . join(',', array_keys($values)) . ")", "(" . join(',', $values) . ")", $desc,
1096
+            $serveur);
1097
+    }
1098
+    $couples = join(',', $noprims);
1099
+
1100
+    $seq = spip_pg_sequence($table);
1101
+    $table = prefixer_table_spip($table, $prefixe);
1102
+    $seq = prefixer_table_spip($seq, $prefixe);
1103
+
1104
+    $connexion['last'] = $q = "UPDATE $table SET $couples WHERE $where";
1105
+    if ($couples) {
1106
+        $couples = spip_pg_query_simple($link, $q);
1107 1107
 #	  spip_log($q,'pg.'._LOG_DEBUG);
1108
-		if (!$couples) {
1109
-			return false;
1110
-		}
1111
-		$couples = pg_affected_rows($couples);
1112
-	}
1113
-	if (!$couples) {
1114
-		$ret = !$seq ? '' :
1115
-			(" RETURNING nextval('$seq') < $prim");
1116
-		$connexion['last'] = $q = "INSERT INTO $table (" . join(',', array_keys($values)) . ') VALUES (' . join(',',
1117
-				$values) . ")$ret";
1118
-		$couples = spip_pg_query_simple($link, $q);
1119
-		if (!$couples) {
1120
-			return false;
1121
-		} elseif ($ret) {
1122
-			$r = pg_fetch_array($couples, null, PGSQL_NUM);
1123
-			if ($r[0]) {
1124
-				$connexion['last'] = $q = "SELECT setval('$seq', $prim) from $table";
1125
-				// Le code de SPIP met parfois la sequence a 0 (dans l'import)
1126
-				// MySQL n'en dit rien, on fait pareil pour PG
1127
-				$r = @pg_query($link, $q);
1128
-			}
1129
-		}
1130
-	}
1131
-
1132
-	return $couples;
1108
+        if (!$couples) {
1109
+            return false;
1110
+        }
1111
+        $couples = pg_affected_rows($couples);
1112
+    }
1113
+    if (!$couples) {
1114
+        $ret = !$seq ? '' :
1115
+            (" RETURNING nextval('$seq') < $prim");
1116
+        $connexion['last'] = $q = "INSERT INTO $table (" . join(',', array_keys($values)) . ') VALUES (' . join(',',
1117
+                $values) . ")$ret";
1118
+        $couples = spip_pg_query_simple($link, $q);
1119
+        if (!$couples) {
1120
+            return false;
1121
+        } elseif ($ret) {
1122
+            $r = pg_fetch_array($couples, null, PGSQL_NUM);
1123
+            if ($r[0]) {
1124
+                $connexion['last'] = $q = "SELECT setval('$seq', $prim) from $table";
1125
+                // Le code de SPIP met parfois la sequence a 0 (dans l'import)
1126
+                // MySQL n'en dit rien, on fait pareil pour PG
1127
+                $r = @pg_query($link, $q);
1128
+            }
1129
+        }
1130
+    }
1131
+
1132
+    return $couples;
1133 1133
 }
1134 1134
 
1135 1135
 
1136 1136
 // https://code.spip.net/@spip_pg_replace_multi
1137 1137
 function spip_pg_replace_multi($table, $tab_couples, $desc = array(), $serveur = '', $requeter = true) {
1138
-	// boucler pour traiter chaque requete independemment
1139
-	foreach ($tab_couples as $couples) {
1140
-		$retour = spip_pg_replace($table, $couples, $desc, $serveur, $requeter);
1141
-	}
1138
+    // boucler pour traiter chaque requete independemment
1139
+    foreach ($tab_couples as $couples) {
1140
+        $retour = spip_pg_replace($table, $couples, $desc, $serveur, $requeter);
1141
+    }
1142 1142
 
1143
-	// renvoie le dernier id
1144
-	return $retour;
1143
+    // renvoie le dernier id
1144
+    return $retour;
1145 1145
 }
1146 1146
 
1147 1147
 
@@ -1151,19 +1151,19 @@  discard block
 block discarded – undo
1151 1151
 // https://code.spip.net/@spip_pg_sequence
1152 1152
 function spip_pg_sequence($table, $raw = false) {
1153 1153
 
1154
-	include_spip('base/serial');
1155
-	if (!isset($GLOBALS['tables_principales'][$table])) {
1156
-		return false;
1157
-	}
1158
-	$desc = $GLOBALS['tables_principales'][$table];
1159
-	$prim = @$desc['key']['PRIMARY KEY'];
1160
-	if (!preg_match('/^\w+$/', $prim)
1161
-		or strpos($desc['field'][$prim], 'int') === false
1162
-	) {
1163
-		return '';
1164
-	} else {
1165
-		return $raw ? $prim : $table . '_' . $prim . "_seq";
1166
-	}
1154
+    include_spip('base/serial');
1155
+    if (!isset($GLOBALS['tables_principales'][$table])) {
1156
+        return false;
1157
+    }
1158
+    $desc = $GLOBALS['tables_principales'][$table];
1159
+    $prim = @$desc['key']['PRIMARY KEY'];
1160
+    if (!preg_match('/^\w+$/', $prim)
1161
+        or strpos($desc['field'][$prim], 'int') === false
1162
+    ) {
1163
+        return '';
1164
+    } else {
1165
+        return $raw ? $prim : $table . '_' . $prim . "_seq";
1166
+    }
1167 1167
 }
1168 1168
 
1169 1169
 // Explicite les conversions de Mysql d'une valeur $v de type $t
@@ -1171,65 +1171,65 @@  discard block
 block discarded – undo
1171 1171
 
1172 1172
 // https://code.spip.net/@spip_pg_cite
1173 1173
 function spip_pg_cite($v, $t) {
1174
-	if (is_null($v)) {
1175
-		return 'NULL';
1176
-	} // null php se traduit en NULL SQL
1177
-
1178
-	if (sql_test_date($t)) {
1179
-		if ($v and (strpos("0123456789", $v[0]) === false)) {
1180
-			return spip_pg_frommysql($v);
1181
-		} else {
1182
-			if (strncmp($v, '0000', 4) == 0) {
1183
-				$v = "0001" . substr($v, 4);
1184
-			}
1185
-			if (strpos($v, "-00-00") === 4) {
1186
-				$v = substr($v, 0, 4) . "-01-01" . substr($v, 10);
1187
-			}
1188
-
1189
-			return "timestamp '$v'";
1190
-		}
1191
-	} elseif (!sql_test_int($t)) {
1192
-		return ("'" . pg_escape_string($v) . "'");
1193
-	} elseif (is_numeric($v) or (strpos($v, 'CAST(') === 0)) {
1194
-		return $v;
1195
-	} elseif ($v[0] == '0' and $v[1] !== 'x' and ctype_xdigit(substr($v, 1))) {
1196
-		return substr($v, 1);
1197
-	} else {
1198
-		spip_log("Warning: '$v'  n'est pas de type $t", 'pg.' . _LOG_AVERTISSEMENT);
1199
-
1200
-		return intval($v);
1201
-	}
1174
+    if (is_null($v)) {
1175
+        return 'NULL';
1176
+    } // null php se traduit en NULL SQL
1177
+
1178
+    if (sql_test_date($t)) {
1179
+        if ($v and (strpos("0123456789", $v[0]) === false)) {
1180
+            return spip_pg_frommysql($v);
1181
+        } else {
1182
+            if (strncmp($v, '0000', 4) == 0) {
1183
+                $v = "0001" . substr($v, 4);
1184
+            }
1185
+            if (strpos($v, "-00-00") === 4) {
1186
+                $v = substr($v, 0, 4) . "-01-01" . substr($v, 10);
1187
+            }
1188
+
1189
+            return "timestamp '$v'";
1190
+        }
1191
+    } elseif (!sql_test_int($t)) {
1192
+        return ("'" . pg_escape_string($v) . "'");
1193
+    } elseif (is_numeric($v) or (strpos($v, 'CAST(') === 0)) {
1194
+        return $v;
1195
+    } elseif ($v[0] == '0' and $v[1] !== 'x' and ctype_xdigit(substr($v, 1))) {
1196
+        return substr($v, 1);
1197
+    } else {
1198
+        spip_log("Warning: '$v'  n'est pas de type $t", 'pg.' . _LOG_AVERTISSEMENT);
1199
+
1200
+        return intval($v);
1201
+    }
1202 1202
 }
1203 1203
 
1204 1204
 // https://code.spip.net/@spip_pg_hex
1205 1205
 function spip_pg_hex($v) {
1206
-	return "CAST(x'" . $v . "' as bigint)";
1206
+    return "CAST(x'" . $v . "' as bigint)";
1207 1207
 }
1208 1208
 
1209 1209
 function spip_pg_quote($v, $type = '') {
1210
-	if (!is_array($v)) {
1211
-		return spip_pg_cite($v, $type);
1212
-	}
1213
-	// si c'est un tableau, le parcourir en propageant le type
1214
-	foreach ($v as $k => $r) {
1215
-		$v[$k] = spip_pg_quote($r, $type);
1216
-	}
1217
-
1218
-	return join(",", $v);
1210
+    if (!is_array($v)) {
1211
+        return spip_pg_cite($v, $type);
1212
+    }
1213
+    // si c'est un tableau, le parcourir en propageant le type
1214
+    foreach ($v as $k => $r) {
1215
+        $v[$k] = spip_pg_quote($r, $type);
1216
+    }
1217
+
1218
+    return join(",", $v);
1219 1219
 }
1220 1220
 
1221 1221
 function spip_pg_date_proche($champ, $interval, $unite) {
1222
-	return '('
1223
-	. $champ
1224
-	. (($interval <= 0) ? '>' : '<')
1225
-	. (($interval <= 0) ? 'DATE_SUB' : 'DATE_ADD')
1226
-	. '('
1227
-	. sql_quote(date('Y-m-d H:i:s'))
1228
-	. ', INTERVAL '
1229
-	. (($interval > 0) ? $interval : (0 - $interval))
1230
-	. ' '
1231
-	. $unite
1232
-	. '))';
1222
+    return '('
1223
+    . $champ
1224
+    . (($interval <= 0) ? '>' : '<')
1225
+    . (($interval <= 0) ? 'DATE_SUB' : 'DATE_ADD')
1226
+    . '('
1227
+    . sql_quote(date('Y-m-d H:i:s'))
1228
+    . ', INTERVAL '
1229
+    . (($interval > 0) ? $interval : (0 - $interval))
1230
+    . ' '
1231
+    . $unite
1232
+    . '))';
1233 1233
 }
1234 1234
 
1235 1235
 // https://code.spip.net/@spip_pg_in
@@ -1237,69 +1237,69 @@  discard block
 block discarded – undo
1237 1237
 //
1238 1238
 // IN (...) souvent limite a 255  elements, d'ou cette fonction assistante
1239 1239
 //
1240
-	// s'il n'y a pas de valeur, eviter de produire un IN vide: PG rale.
1241
-	if (!$valeurs) {
1242
-		return $not ? '0=0' : '0=1';
1243
-	}
1244
-	if (strpos($valeurs, "CAST(x'") !== false) {
1245
-		return "($val=" . join("OR $val=", explode(',', $valeurs)) . ')';
1246
-	}
1247
-	$n = $i = 0;
1248
-	$in_sql = "";
1249
-	while ($n = strpos($valeurs, ',', $n + 1)) {
1250
-		if ((++$i) >= 255) {
1251
-			$in_sql .= "($val $not IN (" .
1252
-				substr($valeurs, 0, $n) .
1253
-				"))\n" .
1254
-				($not ? "AND\t" : "OR\t");
1255
-			$valeurs = substr($valeurs, $n + 1);
1256
-			$i = $n = 0;
1257
-		}
1258
-	}
1259
-	$in_sql .= "($val $not IN ($valeurs))";
1260
-
1261
-	return "($in_sql)";
1240
+    // s'il n'y a pas de valeur, eviter de produire un IN vide: PG rale.
1241
+    if (!$valeurs) {
1242
+        return $not ? '0=0' : '0=1';
1243
+    }
1244
+    if (strpos($valeurs, "CAST(x'") !== false) {
1245
+        return "($val=" . join("OR $val=", explode(',', $valeurs)) . ')';
1246
+    }
1247
+    $n = $i = 0;
1248
+    $in_sql = "";
1249
+    while ($n = strpos($valeurs, ',', $n + 1)) {
1250
+        if ((++$i) >= 255) {
1251
+            $in_sql .= "($val $not IN (" .
1252
+                substr($valeurs, 0, $n) .
1253
+                "))\n" .
1254
+                ($not ? "AND\t" : "OR\t");
1255
+            $valeurs = substr($valeurs, $n + 1);
1256
+            $i = $n = 0;
1257
+        }
1258
+    }
1259
+    $in_sql .= "($val $not IN ($valeurs))";
1260
+
1261
+    return "($in_sql)";
1262 1262
 }
1263 1263
 
1264 1264
 // https://code.spip.net/@spip_pg_error
1265 1265
 function spip_pg_error($query = '', $serveur = '', $requeter = true) {
1266
-	$link = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]['link'];
1267
-	$s = $link ? pg_last_error($link) : pg_last_error();
1268
-	if ($s) {
1269
-		$s = str_replace('ERROR', 'errcode: 1000 ', $s);
1270
-		spip_log("$s - $query", 'pg.' . _LOG_ERREUR);
1271
-	}
1272
-
1273
-	return $s;
1266
+    $link = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]['link'];
1267
+    $s = $link ? pg_last_error($link) : pg_last_error();
1268
+    if ($s) {
1269
+        $s = str_replace('ERROR', 'errcode: 1000 ', $s);
1270
+        spip_log("$s - $query", 'pg.' . _LOG_ERREUR);
1271
+    }
1272
+
1273
+    return $s;
1274 1274
 }
1275 1275
 
1276 1276
 // https://code.spip.net/@spip_pg_errno
1277 1277
 function spip_pg_errno($serveur = '') {
1278
-	// il faudrait avoir la derniere ressource retournee et utiliser
1279
-	// http://fr2.php.net/manual/fr/function.pg-result-error.php
1280
-	return 0;
1278
+    // il faudrait avoir la derniere ressource retournee et utiliser
1279
+    // http://fr2.php.net/manual/fr/function.pg-result-error.php
1280
+    return 0;
1281 1281
 }
1282 1282
 
1283 1283
 // https://code.spip.net/@spip_pg_drop_table
1284 1284
 function spip_pg_drop_table($table, $exist = '', $serveur = '', $requeter = true) {
1285
-	if ($exist) {
1286
-		$exist = " IF EXISTS";
1287
-	}
1288
-	if (spip_pg_query("DROP TABLE$exist $table", $serveur, $requeter)) {
1289
-		return true;
1290
-	} else {
1291
-		return false;
1292
-	}
1285
+    if ($exist) {
1286
+        $exist = " IF EXISTS";
1287
+    }
1288
+    if (spip_pg_query("DROP TABLE$exist $table", $serveur, $requeter)) {
1289
+        return true;
1290
+    } else {
1291
+        return false;
1292
+    }
1293 1293
 }
1294 1294
 
1295 1295
 // supprime une vue 
1296 1296
 // https://code.spip.net/@spip_pg_drop_view
1297 1297
 function spip_pg_drop_view($view, $exist = '', $serveur = '', $requeter = true) {
1298
-	if ($exist) {
1299
-		$exist = " IF EXISTS";
1300
-	}
1298
+    if ($exist) {
1299
+        $exist = " IF EXISTS";
1300
+    }
1301 1301
 
1302
-	return spip_pg_query("DROP VIEW$exist $view", $serveur, $requeter);
1302
+    return spip_pg_query("DROP VIEW$exist $view", $serveur, $requeter);
1303 1303
 }
1304 1304
 
1305 1305
 /**
@@ -1316,41 +1316,41 @@  discard block
 block discarded – undo
1316 1316
  *     Ressource à utiliser avec sql_fetch()
1317 1317
  **/
1318 1318
 function spip_pg_showbase($match, $serveur = '', $requeter = true) {
1319
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1320
-	$link = $connexion['link'];
1321
-	$connexion['last'] = $q = "SELECT tablename FROM pg_tables WHERE tablename ILIKE " . _q($match);
1319
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1320
+    $link = $connexion['link'];
1321
+    $connexion['last'] = $q = "SELECT tablename FROM pg_tables WHERE tablename ILIKE " . _q($match);
1322 1322
 
1323
-	return spip_pg_query_simple($link, $q);
1323
+    return spip_pg_query_simple($link, $q);
1324 1324
 }
1325 1325
 
1326 1326
 // https://code.spip.net/@spip_pg_showtable
1327 1327
 function spip_pg_showtable($nom_table, $serveur = '', $requeter = true) {
1328
-	$connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1329
-	$link = $connexion['link'];
1330
-	$connexion['last'] = $q = "SELECT column_name, column_default, data_type FROM information_schema.columns WHERE table_name ILIKE " . _q($nom_table);
1331
-
1332
-	$res = spip_pg_query_simple($link, $q);
1333
-	if (!$res) {
1334
-		return false;
1335
-	}
1336
-
1337
-	// etrangement, $res peut ne rien contenir, mais arriver ici...
1338
-	// il faut en tenir compte dans le return
1339
-	$fields = array();
1340
-	while ($field = pg_fetch_array($res, null, PGSQL_NUM)) {
1341
-		$fields[$field[0]] = $field[2] . (!$field[1] ? '' : (" DEFAULT " . $field[1]));
1342
-	}
1343
-	$connexion['last'] = $q = "SELECT indexdef FROM pg_indexes WHERE tablename ILIKE " . _q($nom_table);
1344
-	$res = spip_pg_query_simple($link, $q);
1345
-	$keys = array();
1346
-	while ($index = pg_fetch_array($res, null, PGSQL_NUM)) {
1347
-		if (preg_match('/CREATE\s+(UNIQUE\s+)?INDEX\s([^\s]+).*\((.*)\)$/', $index[0], $r)) {
1348
-			$nom = str_replace($nom_table . '_', '', $r[2]);
1349
-			$keys[($r[1] ? "PRIMARY KEY" : ("KEY " . $nom))] = $r[3];
1350
-		}
1351
-	}
1352
-
1353
-	return count($fields) ? array('field' => $fields, 'key' => $keys) : false;
1328
+    $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1329
+    $link = $connexion['link'];
1330
+    $connexion['last'] = $q = "SELECT column_name, column_default, data_type FROM information_schema.columns WHERE table_name ILIKE " . _q($nom_table);
1331
+
1332
+    $res = spip_pg_query_simple($link, $q);
1333
+    if (!$res) {
1334
+        return false;
1335
+    }
1336
+
1337
+    // etrangement, $res peut ne rien contenir, mais arriver ici...
1338
+    // il faut en tenir compte dans le return
1339
+    $fields = array();
1340
+    while ($field = pg_fetch_array($res, null, PGSQL_NUM)) {
1341
+        $fields[$field[0]] = $field[2] . (!$field[1] ? '' : (" DEFAULT " . $field[1]));
1342
+    }
1343
+    $connexion['last'] = $q = "SELECT indexdef FROM pg_indexes WHERE tablename ILIKE " . _q($nom_table);
1344
+    $res = spip_pg_query_simple($link, $q);
1345
+    $keys = array();
1346
+    while ($index = pg_fetch_array($res, null, PGSQL_NUM)) {
1347
+        if (preg_match('/CREATE\s+(UNIQUE\s+)?INDEX\s([^\s]+).*\((.*)\)$/', $index[0], $r)) {
1348
+            $nom = str_replace($nom_table . '_', '', $r[2]);
1349
+            $keys[($r[1] ? "PRIMARY KEY" : ("KEY " . $nom))] = $r[3];
1350
+        }
1351
+    }
1352
+
1353
+    return count($fields) ? array('field' => $fields, 'key' => $keys) : false;
1354 1354
 }
1355 1355
 
1356 1356
 // Fonction de creation d'une table SQL nommee $nom
@@ -1362,118 +1362,118 @@  discard block
 block discarded – undo
1362 1362
 // https://code.spip.net/@spip_pg_create
1363 1363
 function spip_pg_create($nom, $champs, $cles, $autoinc = false, $temporary = false, $serveur = '', $requeter = true) {
1364 1364
 
1365
-	$connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1366
-	$link = $connexion['link'];
1367
-	$nom = prefixer_table_spip($nom, $connexion['prefixe']);
1368
-
1369
-	$query = $prim = $prim_name = $v = $s = $p = '';
1370
-	$keys = array();
1371
-
1372
-	// certains plugins declarent les tables  (permet leur inclusion dans le dump)
1373
-	// sans les renseigner (laisse le compilo recuperer la description)
1374
-	if (!is_array($champs) || !is_array($cles)) {
1375
-		return;
1376
-	}
1377
-
1378
-	foreach ($cles as $k => $v) {
1379
-		if (strpos($k, "KEY ") === 0) {
1380
-			$n = str_replace('`', '', $k);
1381
-			$v = str_replace('`', '"', $v);
1382
-			$i = $nom . preg_replace("/KEY +/", '_', $n);
1383
-			if ($k != $n) {
1384
-				$i = "\"$i\"";
1385
-			}
1386
-			$keys[] = "CREATE INDEX $i ON $nom ($v);";
1387
-		} elseif (strpos($k, "UNIQUE ") === 0) {
1388
-			$k = preg_replace("/^UNIQUE +/", '', $k);
1389
-			$prim .= "$s\n\t\tCONSTRAINT " . str_replace('`', '"', $k) . " UNIQUE ($v)";
1390
-		} else {
1391
-			$prim .= "$s\n\t\t" . str_replace('`', '"', $k) . " ($v)";
1392
-		}
1393
-		if ($k == "PRIMARY KEY") {
1394
-			$prim_name = $v;
1395
-		}
1396
-		$s = ",";
1397
-	}
1398
-	$s = '';
1399
-
1400
-	$character_set = "";
1401
-	if (@$GLOBALS['meta']['charset_sql_base']) {
1402
-		$character_set .= " CHARACTER SET " . $GLOBALS['meta']['charset_sql_base'];
1403
-	}
1404
-	if (@$GLOBALS['meta']['charset_collation_sql_base']) {
1405
-		$character_set .= " COLLATE " . $GLOBALS['meta']['charset_collation_sql_base'];
1406
-	}
1407
-
1408
-	foreach ($champs as $k => $v) {
1409
-		$k = str_replace('`', '"', $k);
1410
-		if (preg_match(',([a-z]*\s*(\(\s*[0-9]*\s*\))?(\s*binary)?),i', $v, $defs)) {
1411
-			if (preg_match(',(char|text),i', $defs[1]) and !preg_match(',binary,i', $defs[1])) {
1412
-				$v = $defs[1] . $character_set . ' ' . substr($v, strlen($defs[1]));
1413
-			}
1414
-		}
1415
-
1416
-		$query .= "$s\n\t\t$k "
1417
-			. (($autoinc && ($prim_name == $k) && preg_match(',\b(big|small|medium|tiny)?int\b,i', $v))
1418
-				? " bigserial"
1419
-				: mysql2pg_type($v)
1420
-			);
1421
-		$s = ",";
1422
-	}
1423
-	$temporary = $temporary ? 'TEMPORARY' : '';
1424
-
1425
-	// En l'absence de "if not exists" en PG, on neutralise les erreurs
1426
-
1427
-	$q = "CREATE $temporary TABLE $nom ($query" . ($prim ? ",$prim" : '') . ")" .
1428
-		($character_set ? " DEFAULT $character_set" : "")
1429
-		. "\n";
1430
-
1431
-	if (!$requeter) {
1432
-		return $q;
1433
-	}
1434
-	$connexion['last'] = $q;
1435
-	$r = @pg_query($link, $q);
1436
-
1437
-	if (!$r) {
1438
-		spip_log("Impossible de creer cette table: $q", 'pg.' . _LOG_ERREUR);
1439
-	} else {
1440
-		foreach ($keys as $index) {
1441
-			pg_query($link, $index);
1442
-		}
1443
-	}
1444
-
1445
-	return $r;
1365
+    $connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0];
1366
+    $link = $connexion['link'];
1367
+    $nom = prefixer_table_spip($nom, $connexion['prefixe']);
1368
+
1369
+    $query = $prim = $prim_name = $v = $s = $p = '';
1370
+    $keys = array();
1371
+
1372
+    // certains plugins declarent les tables  (permet leur inclusion dans le dump)
1373
+    // sans les renseigner (laisse le compilo recuperer la description)
1374
+    if (!is_array($champs) || !is_array($cles)) {
1375
+        return;
1376
+    }
1377
+
1378
+    foreach ($cles as $k => $v) {
1379
+        if (strpos($k, "KEY ") === 0) {
1380
+            $n = str_replace('`', '', $k);
1381
+            $v = str_replace('`', '"', $v);
1382
+            $i = $nom . preg_replace("/KEY +/", '_', $n);
1383
+            if ($k != $n) {
1384
+                $i = "\"$i\"";
1385
+            }
1386
+            $keys[] = "CREATE INDEX $i ON $nom ($v);";
1387
+        } elseif (strpos($k, "UNIQUE ") === 0) {
1388
+            $k = preg_replace("/^UNIQUE +/", '', $k);
1389
+            $prim .= "$s\n\t\tCONSTRAINT " . str_replace('`', '"', $k) . " UNIQUE ($v)";
1390
+        } else {
1391
+            $prim .= "$s\n\t\t" . str_replace('`', '"', $k) . " ($v)";
1392
+        }
1393
+        if ($k == "PRIMARY KEY") {
1394
+            $prim_name = $v;
1395
+        }
1396
+        $s = ",";
1397
+    }
1398
+    $s = '';
1399
+
1400
+    $character_set = "";
1401
+    if (@$GLOBALS['meta']['charset_sql_base']) {
1402
+        $character_set .= " CHARACTER SET " . $GLOBALS['meta']['charset_sql_base'];
1403
+    }
1404
+    if (@$GLOBALS['meta']['charset_collation_sql_base']) {
1405
+        $character_set .= " COLLATE " . $GLOBALS['meta']['charset_collation_sql_base'];
1406
+    }
1407
+
1408
+    foreach ($champs as $k => $v) {
1409
+        $k = str_replace('`', '"', $k);
1410
+        if (preg_match(',([a-z]*\s*(\(\s*[0-9]*\s*\))?(\s*binary)?),i', $v, $defs)) {
1411
+            if (preg_match(',(char|text),i', $defs[1]) and !preg_match(',binary,i', $defs[1])) {
1412
+                $v = $defs[1] . $character_set . ' ' . substr($v, strlen($defs[1]));
1413
+            }
1414
+        }
1415
+
1416
+        $query .= "$s\n\t\t$k "
1417
+            . (($autoinc && ($prim_name == $k) && preg_match(',\b(big|small|medium|tiny)?int\b,i', $v))
1418
+                ? " bigserial"
1419
+                : mysql2pg_type($v)
1420
+            );
1421
+        $s = ",";
1422
+    }
1423
+    $temporary = $temporary ? 'TEMPORARY' : '';
1424
+
1425
+    // En l'absence de "if not exists" en PG, on neutralise les erreurs
1426
+
1427
+    $q = "CREATE $temporary TABLE $nom ($query" . ($prim ? ",$prim" : '') . ")" .
1428
+        ($character_set ? " DEFAULT $character_set" : "")
1429
+        . "\n";
1430
+
1431
+    if (!$requeter) {
1432
+        return $q;
1433
+    }
1434
+    $connexion['last'] = $q;
1435
+    $r = @pg_query($link, $q);
1436
+
1437
+    if (!$r) {
1438
+        spip_log("Impossible de creer cette table: $q", 'pg.' . _LOG_ERREUR);
1439
+    } else {
1440
+        foreach ($keys as $index) {
1441
+            pg_query($link, $index);
1442
+        }
1443
+    }
1444
+
1445
+    return $r;
1446 1446
 }
1447 1447
 
1448 1448
 
1449 1449
 function spip_pg_create_base($nom, $serveur = '', $requeter = true) {
1450
-	return spip_pg_query("CREATE DATABASE $nom", $serveur, $requeter);
1450
+    return spip_pg_query("CREATE DATABASE $nom", $serveur, $requeter);
1451 1451
 }
1452 1452
 
1453 1453
 // Fonction de creation d'une vue SQL nommee $nom
1454 1454
 // https://code.spip.net/@spip_pg_create_view
1455 1455
 function spip_pg_create_view($nom, $query_select, $serveur = '', $requeter = true) {
1456
-	if (!$query_select) {
1457
-		return false;
1458
-	}
1459
-	// vue deja presente
1460
-	if (sql_showtable($nom, false, $serveur)) {
1461
-		if ($requeter) {
1462
-			spip_log("Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)", 'pg.' . _LOG_ERREUR);
1463
-		}
1456
+    if (!$query_select) {
1457
+        return false;
1458
+    }
1459
+    // vue deja presente
1460
+    if (sql_showtable($nom, false, $serveur)) {
1461
+        if ($requeter) {
1462
+            spip_log("Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)", 'pg.' . _LOG_ERREUR);
1463
+        }
1464 1464
 
1465
-		return false;
1466
-	}
1465
+        return false;
1466
+    }
1467 1467
 
1468
-	$query = "CREATE VIEW $nom AS " . $query_select;
1468
+    $query = "CREATE VIEW $nom AS " . $query_select;
1469 1469
 
1470
-	return spip_pg_query($query, $serveur, $requeter);
1470
+    return spip_pg_query($query, $serveur, $requeter);
1471 1471
 }
1472 1472
 
1473 1473
 
1474 1474
 // https://code.spip.net/@spip_pg_set_connect_charset
1475 1475
 function spip_pg_set_connect_charset($charset, $serveur = '', $requeter = true) {
1476
-	spip_log("changement de charset sql a ecrire en PG", 'pg.' . _LOG_ERREUR);
1476
+    spip_log("changement de charset sql a ecrire en PG", 'pg.' . _LOG_ERREUR);
1477 1477
 }
1478 1478
 
1479 1479
 
@@ -1487,7 +1487,7 @@  discard block
 block discarded – undo
1487 1487
  **/
1488 1488
 // https://code.spip.net/@spip_sqlite_optimize
1489 1489
 function spip_pg_optimize($table, $serveur = '', $requeter = true) {
1490
-	return spip_pg_query("VACUUM " . $table, $serveur, $requeter);
1490
+    return spip_pg_query("VACUUM " . $table, $serveur, $requeter);
1491 1491
 }
1492 1492
 
1493 1493
 // Selectionner la sous-chaine dans $objet
@@ -1495,13 +1495,13 @@  discard block
 block discarded – undo
1495 1495
 
1496 1496
 // https://code.spip.net/@spip_pg_multi
1497 1497
 function spip_pg_multi($objet, $lang) {
1498
-	$r = "regexp_replace("
1499
-		. $objet
1500
-		. ",'<multi>.*[[]"
1501
-		. $lang
1502
-		. "[]]([^[]*).*</multi>', E'\\\\1') AS multi";
1498
+    $r = "regexp_replace("
1499
+        . $objet
1500
+        . ",'<multi>.*[[]"
1501
+        . $lang
1502
+        . "[]]([^[]*).*</multi>', E'\\\\1') AS multi";
1503 1503
 
1504
-	return $r;
1504
+    return $r;
1505 1505
 }
1506 1506
 
1507 1507
 // Palanquee d'idiosyncrasies MySQL dans les creations de table
@@ -1509,31 +1509,31 @@  discard block
 block discarded – undo
1509 1509
 
1510 1510
 // https://code.spip.net/@mysql2pg_type
1511 1511
 function mysql2pg_type($v) {
1512
-	$remplace = array(
1513
-		'/auto_increment/i' => '', // non reconnu
1514
-		'/bigint/i' => 'bigint',
1515
-		'/mediumint/i' => 'mediumint',
1516
-		'/smallint/i' => 'smallint',
1517
-		"/tinyint/i" => 'int',
1518
-		'/int\s*[(]\s*\d+\s*[)]/i' => 'int',
1519
-		"/longtext/i" => 'text',
1520
-		"/mediumtext/i" => 'text',
1521
-		"/tinytext/i" => 'text',
1522
-		"/longblob/i" => 'text',
1523
-		"/0000-00-00/" => '0001-01-01',
1524
-		"/datetime/i" => 'timestamp',
1525
-		"/unsigned/i" => '',
1526
-		"/double/i" => 'double precision',
1527
-		'/VARCHAR\((\d+)\)\s+BINARY/i' => 'varchar(\1)',
1528
-		"/ENUM *[(][^)]*[)]/i" => "varchar(255)",
1529
-		'/(timestamp .* )ON .*$/is' => '\\1',
1530
-	);
1531
-
1532
-	return preg_replace(array_keys($remplace), array_values($remplace), $v);
1512
+    $remplace = array(
1513
+        '/auto_increment/i' => '', // non reconnu
1514
+        '/bigint/i' => 'bigint',
1515
+        '/mediumint/i' => 'mediumint',
1516
+        '/smallint/i' => 'smallint',
1517
+        "/tinyint/i" => 'int',
1518
+        '/int\s*[(]\s*\d+\s*[)]/i' => 'int',
1519
+        "/longtext/i" => 'text',
1520
+        "/mediumtext/i" => 'text',
1521
+        "/tinytext/i" => 'text',
1522
+        "/longblob/i" => 'text',
1523
+        "/0000-00-00/" => '0001-01-01',
1524
+        "/datetime/i" => 'timestamp',
1525
+        "/unsigned/i" => '',
1526
+        "/double/i" => 'double precision',
1527
+        '/VARCHAR\((\d+)\)\s+BINARY/i' => 'varchar(\1)',
1528
+        "/ENUM *[(][^)]*[)]/i" => "varchar(255)",
1529
+        '/(timestamp .* )ON .*$/is' => '\\1',
1530
+    );
1531
+
1532
+    return preg_replace(array_keys($remplace), array_values($remplace), $v);
1533 1533
 }
1534 1534
 
1535 1535
 // Renvoie false si on n'a pas les fonctions pg (pour l'install)
1536 1536
 // https://code.spip.net/@spip_versions_pg
1537 1537
 function spip_versions_pg() {
1538
-	return function_exists('pg_connect');
1538
+    return function_exists('pg_connect');
1539 1539
 }
Please login to merge, or discard this patch.
ecrire/urls/page.php 1 patch
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 define('URLS_PAGE_EXEMPLE', 'spip.php?article12');
@@ -30,74 +30,74 @@  discard block
 block discarded – undo
30 30
 // https://code.spip.net/@_generer_url_page
31 31
 function _generer_url_page($type, $id, $args = '', $ancre = '') {
32 32
 
33
-	if ($generer_url_externe = charger_fonction("generer_url_$type", 'urls', true)) {
34
-		$url = $generer_url_externe($id, $args, $ancre);
35
-		if (null != $url) {
36
-			return $url;
37
-		}
38
-	}
33
+    if ($generer_url_externe = charger_fonction("generer_url_$type", 'urls', true)) {
34
+        $url = $generer_url_externe($id, $args, $ancre);
35
+        if (null != $url) {
36
+            return $url;
37
+        }
38
+    }
39 39
 
40
-	$url = _debut_urls_page . $type . _separateur_urls_page
41
-		. $id . _terminaison_urls_page;
40
+    $url = _debut_urls_page . $type . _separateur_urls_page
41
+        . $id . _terminaison_urls_page;
42 42
 
43
-	if ($args) {
44
-		$args = strpos($url, '?') ? "&$args" : "?$args";
45
-	}
43
+    if ($args) {
44
+        $args = strpos($url, '?') ? "&$args" : "?$args";
45
+    }
46 46
 
47
-	return _DIR_RACINE . $url . $args . ($ancre ? "#$ancre" : '');
47
+    return _DIR_RACINE . $url . $args . ($ancre ? "#$ancre" : '');
48 48
 }
49 49
 
50 50
 // retrouve le fond et les parametres d'une URL abregee
51 51
 // le contexte deja existant est fourni dans args sous forme de tableau ou query string
52 52
 // https://code.spip.net/@urls_page_dist
53 53
 function urls_page_dist($i, &$entite, $args = '', $ancre = '') {
54
-	if (is_numeric($i)) {
55
-		return _generer_url_page($entite, $i, $args, $ancre);
56
-	}
54
+    if (is_numeric($i)) {
55
+        return _generer_url_page($entite, $i, $args, $ancre);
56
+    }
57 57
 
58
-	// traiter les injections du type domaine.org/spip.php/cestnimportequoi/ou/encore/plus/rubrique23
59
-	if ($GLOBALS['profondeur_url'] > 0 and $entite == 'sommaire') {
60
-		return array(array(), '404');
61
-	}
58
+    // traiter les injections du type domaine.org/spip.php/cestnimportequoi/ou/encore/plus/rubrique23
59
+    if ($GLOBALS['profondeur_url'] > 0 and $entite == 'sommaire') {
60
+        return array(array(), '404');
61
+    }
62 62
 
63
-	// voir s'il faut recuperer le id_* implicite et les &debut_xx;
64
-	if (is_array($args)) {
65
-		$contexte = $args;
66
-	} else {
67
-		parse_str($args, $contexte);
68
-	}
69
-	include_spip('inc/urls');
70
-	$r = nettoyer_url_page($i, $contexte);
71
-	if ($r) {
72
-		array_pop($r); // nettoyer_url_page renvoie un argument de plus inutile ici
73
-		return $r;
74
-	}
63
+    // voir s'il faut recuperer le id_* implicite et les &debut_xx;
64
+    if (is_array($args)) {
65
+        $contexte = $args;
66
+    } else {
67
+        parse_str($args, $contexte);
68
+    }
69
+    include_spip('inc/urls');
70
+    $r = nettoyer_url_page($i, $contexte);
71
+    if ($r) {
72
+        array_pop($r); // nettoyer_url_page renvoie un argument de plus inutile ici
73
+        return $r;
74
+    }
75 75
 
76
-	/*
76
+    /*
77 77
 	 * Le bloc qui suit sert a faciliter les transitions depuis
78 78
 	 * le mode 'urls-propres' vers les modes 'urls-standard' et 'url-html'
79 79
 	 * Il est inutile de le recopier si vous personnalisez vos URLs
80 80
 	 * et votre .htaccess
81 81
 	 */
82
-	// Si on est revenu en mode html, mais c'est une ancienne url_propre
83
-	// on ne redirige pas, on assume le nouveau contexte (si possible)
84
-	$url = $i;
85
-	$url_propre = isset($url)
86
-		? $url
87
-		: (isset($_SERVER['REDIRECT_url_propre'])
88
-			? $_SERVER['REDIRECT_url_propre']
89
-			: (isset($_ENV['url_propre'])
90
-				? $_ENV['url_propre']
91
-				: ''
92
-			));
93
-	if ($url_propre) {
94
-		if ($GLOBALS['profondeur_url'] <= 0) {
95
-			$urls_anciennes = charger_fonction('propres', 'urls', true);
96
-		} else {
97
-			$urls_anciennes = charger_fonction('arbo', 'urls', true);
98
-		}
82
+    // Si on est revenu en mode html, mais c'est une ancienne url_propre
83
+    // on ne redirige pas, on assume le nouveau contexte (si possible)
84
+    $url = $i;
85
+    $url_propre = isset($url)
86
+        ? $url
87
+        : (isset($_SERVER['REDIRECT_url_propre'])
88
+            ? $_SERVER['REDIRECT_url_propre']
89
+            : (isset($_ENV['url_propre'])
90
+                ? $_ENV['url_propre']
91
+                : ''
92
+            ));
93
+    if ($url_propre) {
94
+        if ($GLOBALS['profondeur_url'] <= 0) {
95
+            $urls_anciennes = charger_fonction('propres', 'urls', true);
96
+        } else {
97
+            $urls_anciennes = charger_fonction('arbo', 'urls', true);
98
+        }
99 99
 
100
-		return $urls_anciennes ? $urls_anciennes($url_propre, $entite, $contexte) : '';
101
-	}
102
-	/* Fin du bloc compatibilite url-propres */
100
+        return $urls_anciennes ? $urls_anciennes($url_propre, $entite, $contexte) : '';
101
+    }
102
+    /* Fin du bloc compatibilite url-propres */
103 103
 }
Please login to merge, or discard this patch.
ecrire/action/purger.php 1 patch
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  * @package SPIP\Core\Cache
17 17
  **/
18 18
 if (!defined('_ECRIRE_INC_VERSION')) {
19
-	return;
19
+    return;
20 20
 }
21 21
 
22 22
 /**
@@ -39,57 +39,57 @@  discard block
 block discarded – undo
39 39
  *     de l'action sécurisée.
40 40
  */
41 41
 function action_purger_dist($arg = null) {
42
-	if (is_null($arg)) {
43
-		$securiser_action = charger_fonction('securiser_action', 'inc');
44
-		$arg = $securiser_action();
45
-	}
42
+    if (is_null($arg)) {
43
+        $securiser_action = charger_fonction('securiser_action', 'inc');
44
+        $arg = $securiser_action();
45
+    }
46 46
 
47
-	include_spip('inc/invalideur');
47
+    include_spip('inc/invalideur');
48 48
 
49
-	spip_log("purger $arg");
49
+    spip_log("purger $arg");
50 50
 
51
-	switch ($arg) {
52
-		case 'inhibe_cache':
53
-			// inhiber le cache pendant 24h
54
-			ecrire_meta('cache_inhib', $_SERVER['REQUEST_TIME'] + 24 * 3600);
55
-			break;
56
-		case 'reactive_cache':
57
-			effacer_meta('cache_inhib');
58
-			break;
51
+    switch ($arg) {
52
+        case 'inhibe_cache':
53
+            // inhiber le cache pendant 24h
54
+            ecrire_meta('cache_inhib', $_SERVER['REQUEST_TIME'] + 24 * 3600);
55
+            break;
56
+        case 'reactive_cache':
57
+            effacer_meta('cache_inhib');
58
+            break;
59 59
 
60
-		case 'cache':
61
-			supprime_invalideurs();
62
-			@spip_unlink(_CACHE_RUBRIQUES);
63
-			@spip_unlink(_CACHE_CHEMIN);
64
-			@spip_unlink(_DIR_TMP . "plugin_xml_cache.gz");
65
-			// on ne supprime que _CACHE_PLUGINS_OPT qui declenche la reconstruction des 3
66
-			// _CACHE_PIPELINES _CACHE_PLUGINS_PATH et _CACHE_PLUGINS_FCT
67
-			// pour eviter des problemes de concurence
68
-			// cf https://core.spip.net/issues/2989
69
-			//@spip_unlink(_CACHE_PIPELINES);
70
-			//@spip_unlink(_CACHE_PLUGINS_PATH);
71
-			//@spip_unlink(_CACHE_PLUGINS_FCT);
72
-			@spip_unlink(_CACHE_PLUGINS_OPT);
73
-			purger_repertoire(_DIR_CACHE, array('subdir' => true));
74
-			purger_repertoire(_DIR_AIDE);
75
-			purger_repertoire(_DIR_VAR . 'cache-css');
76
-			purger_repertoire(_DIR_VAR . 'cache-js');
77
-			break;
60
+        case 'cache':
61
+            supprime_invalideurs();
62
+            @spip_unlink(_CACHE_RUBRIQUES);
63
+            @spip_unlink(_CACHE_CHEMIN);
64
+            @spip_unlink(_DIR_TMP . "plugin_xml_cache.gz");
65
+            // on ne supprime que _CACHE_PLUGINS_OPT qui declenche la reconstruction des 3
66
+            // _CACHE_PIPELINES _CACHE_PLUGINS_PATH et _CACHE_PLUGINS_FCT
67
+            // pour eviter des problemes de concurence
68
+            // cf https://core.spip.net/issues/2989
69
+            //@spip_unlink(_CACHE_PIPELINES);
70
+            //@spip_unlink(_CACHE_PLUGINS_PATH);
71
+            //@spip_unlink(_CACHE_PLUGINS_FCT);
72
+            @spip_unlink(_CACHE_PLUGINS_OPT);
73
+            purger_repertoire(_DIR_CACHE, array('subdir' => true));
74
+            purger_repertoire(_DIR_AIDE);
75
+            purger_repertoire(_DIR_VAR . 'cache-css');
76
+            purger_repertoire(_DIR_VAR . 'cache-js');
77
+            break;
78 78
 
79
-		case 'squelettes':
80
-			purger_repertoire(_DIR_SKELS);
81
-			break;
79
+        case 'squelettes':
80
+            purger_repertoire(_DIR_SKELS);
81
+            break;
82 82
 
83
-		case 'vignettes':
84
-			purger_repertoire(_DIR_VAR . 'cache-gd2', array('subdir' => true));
85
-			purger_repertoire(_DIR_VAR . 'cache-texte', array('subdir' => true));
86
-			purger_repertoire(_DIR_VAR . 'cache-vignettes', array('subdir' => true));
87
-			purger_repertoire(_DIR_VAR . 'cache-TeX', array('subdir' => true));
88
-			supprime_invalideurs();
89
-			purger_repertoire(_DIR_CACHE, array('subdir' => true));
90
-			break;
91
-	}
83
+        case 'vignettes':
84
+            purger_repertoire(_DIR_VAR . 'cache-gd2', array('subdir' => true));
85
+            purger_repertoire(_DIR_VAR . 'cache-texte', array('subdir' => true));
86
+            purger_repertoire(_DIR_VAR . 'cache-vignettes', array('subdir' => true));
87
+            purger_repertoire(_DIR_VAR . 'cache-TeX', array('subdir' => true));
88
+            supprime_invalideurs();
89
+            purger_repertoire(_DIR_CACHE, array('subdir' => true));
90
+            break;
91
+    }
92 92
 
93
-	// le faire savoir aux plugins
94
-	pipeline('trig_purger', $arg);
93
+    // le faire savoir aux plugins
94
+    pipeline('trig_purger', $arg);
95 95
 }
Please login to merge, or discard this patch.
ecrire/xml/sax.php 1 patch
Indentation   +246 added lines, -246 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 include_spip('inc/charsets');
@@ -24,218 +24,218 @@  discard block
 block discarded – undo
24 24
  * @return string
25 25
  */
26 26
 function xml_entites_html($texte) {
27
-	if (!is_string($texte) or !$texte
28
-		or strpbrk($texte, "&\"'<>") == false
29
-	) {
30
-		return $texte;
31
-	}
32
-
33
-	if (!function_exists('spip_htmlspecialchars')) {
34
-		include_spip("inc/filtres_mini");
35
-	}
36
-	$texte = spip_htmlspecialchars($texte, ENT_QUOTES);
37
-
38
-	return $texte;
27
+    if (!is_string($texte) or !$texte
28
+        or strpbrk($texte, "&\"'<>") == false
29
+    ) {
30
+        return $texte;
31
+    }
32
+
33
+    if (!function_exists('spip_htmlspecialchars')) {
34
+        include_spip("inc/filtres_mini");
35
+    }
36
+    $texte = spip_htmlspecialchars($texte, ENT_QUOTES);
37
+
38
+    return $texte;
39 39
 }
40 40
 
41 41
 // https://code.spip.net/@xml_debutElement
42 42
 function xml_debutElement($phraseur, $name, $attrs) {
43
-	$depth = $phraseur->depth;
44
-
45
-	$t = isset($phraseur->ouvrant[$depth]) ? $phraseur->ouvrant[$depth] : ' ';
46
-	// espace initial signifie: deja integree au resultat
47
-	if ($t[0] != ' ') {
48
-		$phraseur->res .= '<' . $t . '>';
49
-		$phraseur->ouvrant[$depth] = ' ' . $t;
50
-	}
51
-	$t = $phraseur->contenu[$depth];
52
-	// n'indenter que s'il y a un separateur avant
53
-	$phraseur->res .= preg_replace("/[\n\t ]+$/", "\n$depth", $t);
54
-	$phraseur->contenu[$depth] = "";
55
-	$att = '';
56
-	$sep = ' ';
57
-	foreach ($attrs as $k => $v) {
58
-		$delim = strpos($v, "'") === false ? "'" : '"';
59
-		$val = xml_entites_html($v);
60
-		$att .= $sep . $k . "=" . $delim
61
-			. ($delim !== '"' ? str_replace('&quot;', '"', $val) : $val)
62
-			. $delim;
63
-		$sep = "\n $depth";
64
-	}
65
-	$phraseur->depth .= '  ';
66
-	$phraseur->contenu[$phraseur->depth] = "";
67
-	$phraseur->ouvrant[$phraseur->depth] = $name . $att;
68
-	$phraseur->reperes[$phraseur->depth] = xml_get_current_line_number($phraseur->sax);
43
+    $depth = $phraseur->depth;
44
+
45
+    $t = isset($phraseur->ouvrant[$depth]) ? $phraseur->ouvrant[$depth] : ' ';
46
+    // espace initial signifie: deja integree au resultat
47
+    if ($t[0] != ' ') {
48
+        $phraseur->res .= '<' . $t . '>';
49
+        $phraseur->ouvrant[$depth] = ' ' . $t;
50
+    }
51
+    $t = $phraseur->contenu[$depth];
52
+    // n'indenter que s'il y a un separateur avant
53
+    $phraseur->res .= preg_replace("/[\n\t ]+$/", "\n$depth", $t);
54
+    $phraseur->contenu[$depth] = "";
55
+    $att = '';
56
+    $sep = ' ';
57
+    foreach ($attrs as $k => $v) {
58
+        $delim = strpos($v, "'") === false ? "'" : '"';
59
+        $val = xml_entites_html($v);
60
+        $att .= $sep . $k . "=" . $delim
61
+            . ($delim !== '"' ? str_replace('&quot;', '"', $val) : $val)
62
+            . $delim;
63
+        $sep = "\n $depth";
64
+    }
65
+    $phraseur->depth .= '  ';
66
+    $phraseur->contenu[$phraseur->depth] = "";
67
+    $phraseur->ouvrant[$phraseur->depth] = $name . $att;
68
+    $phraseur->reperes[$phraseur->depth] = xml_get_current_line_number($phraseur->sax);
69 69
 }
70 70
 
71 71
 // https://code.spip.net/@xml_finElement
72 72
 function xml_finElement($phraseur, $name, $fusion_bal = false) {
73
-	$ouv = $phraseur->ouvrant[$phraseur->depth];
74
-
75
-	if ($ouv[0] != ' ') {
76
-		$phraseur->ouvrant[$phraseur->depth] = ' ' . $ouv;
77
-	} else {
78
-		$ouv = "";
79
-	}
80
-	$t = $phraseur->contenu[$phraseur->depth];
81
-	$phraseur->depth = substr($phraseur->depth, 2);
82
-	$t = preg_replace("/[\n\t ]+$/", "\n" . $phraseur->depth, $t);
83
-
84
-	// fusion <balise></balise> en <balise />.
85
-	// ATTENTION,  certains clients http croient que fusion ==> pas d'atttributs
86
-	// en particulier pour les balises Script et A.
87
-	// en presence d'attributs ne le faire que si la DTD est dispo et d'accord
88
-	// (param fusion_bal)
89
-
90
-	if ($t || (($ouv != $name) and !$fusion_bal)) {
91
-		$phraseur->res .= ($ouv ? ('<' . $ouv . '>') : '') . $t . "</" . $name . ">";
92
-	} else {
93
-		$phraseur->res .= ($ouv ? ('<' . $ouv . ' />') : ("</" . $name . ">"));
94
-	}
73
+    $ouv = $phraseur->ouvrant[$phraseur->depth];
74
+
75
+    if ($ouv[0] != ' ') {
76
+        $phraseur->ouvrant[$phraseur->depth] = ' ' . $ouv;
77
+    } else {
78
+        $ouv = "";
79
+    }
80
+    $t = $phraseur->contenu[$phraseur->depth];
81
+    $phraseur->depth = substr($phraseur->depth, 2);
82
+    $t = preg_replace("/[\n\t ]+$/", "\n" . $phraseur->depth, $t);
83
+
84
+    // fusion <balise></balise> en <balise />.
85
+    // ATTENTION,  certains clients http croient que fusion ==> pas d'atttributs
86
+    // en particulier pour les balises Script et A.
87
+    // en presence d'attributs ne le faire que si la DTD est dispo et d'accord
88
+    // (param fusion_bal)
89
+
90
+    if ($t || (($ouv != $name) and !$fusion_bal)) {
91
+        $phraseur->res .= ($ouv ? ('<' . $ouv . '>') : '') . $t . "</" . $name . ">";
92
+    } else {
93
+        $phraseur->res .= ($ouv ? ('<' . $ouv . ' />') : ("</" . $name . ">"));
94
+    }
95 95
 }
96 96
 
97 97
 // https://code.spip.net/@xml_textElement
98 98
 function xml_textElement($phraseur, $data) {
99
-	$depth = $phraseur->depth;
100
-	$phraseur->contenu[$depth] .= preg_match('/^script/', $phraseur->ouvrant[$depth])
101
-		? $data
102
-		: xml_entites_html($data);
99
+    $depth = $phraseur->depth;
100
+    $phraseur->contenu[$depth] .= preg_match('/^script/', $phraseur->ouvrant[$depth])
101
+        ? $data
102
+        : xml_entites_html($data);
103 103
 }
104 104
 
105 105
 function xml_piElement($phraseur, $target, $data) {
106
-	$depth = $phraseur->depth;
107
-
108
-	if (strtolower($target) != "php") {
109
-		$phraseur->contenu[$depth] .= $data;
110
-	} else {
111
-		ob_start();
112
-		eval($data);
113
-		$data = ob_get_contents();
114
-		ob_end_clean();
115
-		$phraseur->contenu[$depth] .= $data;
116
-	}
106
+    $depth = $phraseur->depth;
107
+
108
+    if (strtolower($target) != "php") {
109
+        $phraseur->contenu[$depth] .= $data;
110
+    } else {
111
+        ob_start();
112
+        eval($data);
113
+        $data = ob_get_contents();
114
+        ob_end_clean();
115
+        $phraseur->contenu[$depth] .= $data;
116
+    }
117 117
 }
118 118
 
119 119
 
120 120
 // https://code.spip.net/@xml_defautElement
121 121
 function xml_defaultElement($phraseur, $data) {
122
-	$depth = $phraseur->depth;
122
+    $depth = $phraseur->depth;
123 123
 
124
-	if (!isset($phraseur->contenu[$depth])) {
125
-		$phraseur->contenu[$depth] = '';
126
-	}
127
-	$phraseur->contenu[$depth] .= $data;
124
+    if (!isset($phraseur->contenu[$depth])) {
125
+        $phraseur->contenu[$depth] = '';
126
+    }
127
+    $phraseur->contenu[$depth] .= $data;
128 128
 }
129 129
 
130 130
 // https://code.spip.net/@xml_parsestring
131 131
 function xml_parsestring($phraseur, $data) {
132
-	$phraseur->contenu[$phraseur->depth] = '';
133
-
134
-	if (!xml_parse($phraseur->sax, $data, true)) {
135
-		coordonnees_erreur($phraseur,
136
-			xml_error_string(xml_get_error_code($phraseur->sax))
137
-			. "<br />\n" .
138
-			(!$phraseur->depth ? '' :
139
-				('(' .
140
-					_T('erreur_balise_non_fermee') .
141
-					" <tt>" .
142
-					$phraseur->ouvrant[$phraseur->depth] .
143
-					"</tt> " .
144
-					_T('ligne') .
145
-					" " .
146
-					$phraseur->reperes[$phraseur->depth] .
147
-					") <br />\n")));
148
-	}
132
+    $phraseur->contenu[$phraseur->depth] = '';
133
+
134
+    if (!xml_parse($phraseur->sax, $data, true)) {
135
+        coordonnees_erreur($phraseur,
136
+            xml_error_string(xml_get_error_code($phraseur->sax))
137
+            . "<br />\n" .
138
+            (!$phraseur->depth ? '' :
139
+                ('(' .
140
+                    _T('erreur_balise_non_fermee') .
141
+                    " <tt>" .
142
+                    $phraseur->ouvrant[$phraseur->depth] .
143
+                    "</tt> " .
144
+                    _T('ligne') .
145
+                    " " .
146
+                    $phraseur->reperes[$phraseur->depth] .
147
+                    ") <br />\n")));
148
+    }
149 149
 }
150 150
 
151 151
 // https://code.spip.net/@coordonnees_erreur
152 152
 function coordonnees_erreur($phraseur, $msg) {
153
-	$entete_length = substr_count($phraseur->entete, "\n");
154
-	$phraseur->err[] = array(
155
-		$msg,
156
-		xml_get_current_line_number($phraseur->sax) + $entete_length,
157
-		xml_get_current_column_number($phraseur->sax)
158
-	);
153
+    $entete_length = substr_count($phraseur->entete, "\n");
154
+    $phraseur->err[] = array(
155
+        $msg,
156
+        xml_get_current_line_number($phraseur->sax) + $entete_length,
157
+        xml_get_current_column_number($phraseur->sax)
158
+    );
159 159
 }
160 160
 
161 161
 // https://code.spip.net/@xml_sax_dist
162 162
 function xml_sax_dist($page, $apply = false, $phraseur = null, $doctype = '', $charset = null) {
163
-	if (is_null($charset)) {
164
-		$charset = $GLOBALS['meta']['charset'];
165
-	}
166
-	if ($apply) {
167
-		ob_start();
168
-		if (is_array($apply)) {
169
-			$r = call_user_func_array($page, $apply);
170
-		} else {
171
-			$r = $page();
172
-		}
173
-		$page = ob_get_contents();
174
-		ob_end_clean();
175
-		// fonction sans aucun "echo", ca doit etre le resultat
176
-		if (!$page) {
177
-			$page = $r;
178
-		}
179
-	}
180
-
181
-	if (!$page) {
182
-		return '';
183
-	}
184
-	// charger la DTD et transcoder les entites,
185
-	// et escamoter le doctype que sax mange en php5 mais pas en  php4
186
-	if (!$doctype) {
187
-		if (!$r = analyser_doctype($page)) {
188
-			$page = _MESSAGE_DOCTYPE . _DOCTYPE_ECRIRE
189
-				. preg_replace(_REGEXP_DOCTYPE, '', $page);
190
-			$r = analyser_doctype($page);
191
-		}
192
-		list($entete, $avail, $grammaire, $rotlvl) = array_pad($r, 4, null);
193
-		$page = substr($page, strlen($entete));
194
-	} else {
195
-		$avail = 'SYSTEM';
196
-		$grammaire = $doctype;
197
-		$rotlvl = basename($grammaire);
198
-	}
199
-
200
-	include_spip('xml/analyser_dtd');
201
-	$dtc = charger_dtd($grammaire, $avail, $rotlvl);
202
-	$page = sax_bug($page, $dtc, $charset);
203
-
204
-	// compatibilite Tidy espace public
205
-	if (!$phraseur) {
206
-		$indenter_xml = charger_fonction('indenter', 'xml');
207
-
208
-		return $indenter_xml($page, $apply);
209
-	}
210
-
211
-	$xml_parser = xml_parser_create($charset);
212
-
213
-	xml_set_element_handler($xml_parser,
214
-		array($phraseur, "debutElement"),
215
-		array($phraseur, "finElement"));
216
-
217
-	xml_set_character_data_handler($xml_parser,
218
-		array($phraseur, "textElement"));
219
-
220
-	xml_set_processing_instruction_handler($xml_parser,
221
-		array($phraseur, 'piElement'));
222
-
223
-	xml_set_default_handler($xml_parser,
224
-		array($phraseur, "defaultElement"));
225
-
226
-	xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
227
-
228
-	$phraseur->sax = $xml_parser;
229
-	if (isset($entete)) {
230
-		$phraseur->entete = $entete;
231
-	}
232
-	$phraseur->page = $page;
233
-	$phraseur->dtc = $dtc;
234
-	$phraseur->phraserTout($xml_parser, $page);
235
-	xml_parser_free($xml_parser);
236
-	$phraseur->sax = '';
237
-
238
-	return $phraseur;
163
+    if (is_null($charset)) {
164
+        $charset = $GLOBALS['meta']['charset'];
165
+    }
166
+    if ($apply) {
167
+        ob_start();
168
+        if (is_array($apply)) {
169
+            $r = call_user_func_array($page, $apply);
170
+        } else {
171
+            $r = $page();
172
+        }
173
+        $page = ob_get_contents();
174
+        ob_end_clean();
175
+        // fonction sans aucun "echo", ca doit etre le resultat
176
+        if (!$page) {
177
+            $page = $r;
178
+        }
179
+    }
180
+
181
+    if (!$page) {
182
+        return '';
183
+    }
184
+    // charger la DTD et transcoder les entites,
185
+    // et escamoter le doctype que sax mange en php5 mais pas en  php4
186
+    if (!$doctype) {
187
+        if (!$r = analyser_doctype($page)) {
188
+            $page = _MESSAGE_DOCTYPE . _DOCTYPE_ECRIRE
189
+                . preg_replace(_REGEXP_DOCTYPE, '', $page);
190
+            $r = analyser_doctype($page);
191
+        }
192
+        list($entete, $avail, $grammaire, $rotlvl) = array_pad($r, 4, null);
193
+        $page = substr($page, strlen($entete));
194
+    } else {
195
+        $avail = 'SYSTEM';
196
+        $grammaire = $doctype;
197
+        $rotlvl = basename($grammaire);
198
+    }
199
+
200
+    include_spip('xml/analyser_dtd');
201
+    $dtc = charger_dtd($grammaire, $avail, $rotlvl);
202
+    $page = sax_bug($page, $dtc, $charset);
203
+
204
+    // compatibilite Tidy espace public
205
+    if (!$phraseur) {
206
+        $indenter_xml = charger_fonction('indenter', 'xml');
207
+
208
+        return $indenter_xml($page, $apply);
209
+    }
210
+
211
+    $xml_parser = xml_parser_create($charset);
212
+
213
+    xml_set_element_handler($xml_parser,
214
+        array($phraseur, "debutElement"),
215
+        array($phraseur, "finElement"));
216
+
217
+    xml_set_character_data_handler($xml_parser,
218
+        array($phraseur, "textElement"));
219
+
220
+    xml_set_processing_instruction_handler($xml_parser,
221
+        array($phraseur, 'piElement'));
222
+
223
+    xml_set_default_handler($xml_parser,
224
+        array($phraseur, "defaultElement"));
225
+
226
+    xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
227
+
228
+    $phraseur->sax = $xml_parser;
229
+    if (isset($entete)) {
230
+        $phraseur->entete = $entete;
231
+    }
232
+    $phraseur->page = $page;
233
+    $phraseur->dtc = $dtc;
234
+    $phraseur->phraserTout($xml_parser, $page);
235
+    xml_parser_free($xml_parser);
236
+    $phraseur->sax = '';
237
+
238
+    return $phraseur;
239 239
 }
240 240
 
241 241
 // SAX ne dit pas si une Entite est dans un attribut ou non.
@@ -247,24 +247,24 @@  discard block
 block discarded – undo
247 247
 
248 248
 // https://code.spip.net/@sax_bug
249 249
 function sax_bug($data, $dtc, $charset = null) {
250
-	if (is_null($charset)) {
251
-		$charset = $GLOBALS['meta']['charset'];
252
-	}
253
-
254
-	if ($dtc) {
255
-		$trans = array();
256
-
257
-		foreach ($dtc->entites as $k => $v) {
258
-			if (!strpos(" amp lt gt quot ", $k)) {
259
-				$trans["&$k;"] = $v;
260
-			}
261
-		}
262
-		$data = strtr($data, $trans);
263
-	} else {
264
-		$data = html2unicode($data, true);
265
-	}
266
-
267
-	return unicode2charset($data, $charset);
250
+    if (is_null($charset)) {
251
+        $charset = $GLOBALS['meta']['charset'];
252
+    }
253
+
254
+    if ($dtc) {
255
+        $trans = array();
256
+
257
+        foreach ($dtc->entites as $k => $v) {
258
+            if (!strpos(" amp lt gt quot ", $k)) {
259
+                $trans["&$k;"] = $v;
260
+            }
261
+        }
262
+        $data = strtr($data, $trans);
263
+    } else {
264
+        $data = html2unicode($data, true);
265
+    }
266
+
267
+    return unicode2charset($data, $charset);
268 268
 }
269 269
 
270 270
 // Retirer < ? xml... ? > et autre PI, ainsi que les commentaires en debut
@@ -275,52 +275,52 @@  discard block
 block discarded – undo
275 275
 // mais un XML Schema que SPIP ne fait pas encore lire.
276 276
 // https://code.spip.net/@analyser_doctype
277 277
 function analyser_doctype($data) {
278
-	if (!preg_match(_REGEXP_DOCTYPE, $data, $page)) {
279
-		if (preg_match(_REGEXP_XML, $data, $page)) {
280
-			list(, $entete, $topelement) = $page;
281
-			if ($topelement == 'rss') {
282
-				return array(
283
-					$entete,
284
-					'PUBLIC',
285
-					_DOCTYPE_RSS,
286
-					'rss-0.91.dtd'
287
-				);
288
-			} else {
289
-				$dtd = $topelement . '.dtd';
290
-				$f = find_in_path($dtd);
291
-				if (file_exists($f)) {
292
-					return array($entete, 'SYSTEM', $f, $dtd);
293
-				}
294
-			}
295
-		}
296
-		spip_log("Dtd pas vu pour " . substr($data, 0, 100));
297
-
298
-		return array();
299
-	}
300
-	list($entete, , $topelement, $avail, $suite) = $page;
301
-
302
-	if (!preg_match('/^"([^"]*)"\s*(.*)$/', $suite, $r)) {
303
-		if (!preg_match("/^'([^']*)'\s*(.*)$/", $suite, $r)) {
304
-			return array();
305
-		}
306
-	}
307
-	list(, $rotlvl, $suite) = $r;
308
-
309
-	if (!$suite) {
310
-		if ($avail != 'SYSTEM') {
311
-			return array();
312
-		}
313
-		$grammaire = $rotlvl;
314
-		$rotlvl = '';
315
-	} else {
316
-		if (!preg_match('/^"([^"]*)"\s*$/', $suite, $r)) {
317
-			if (!preg_match("/^'([^']*)'\s*$/", $suite, $r)) {
318
-				return array();
319
-			}
320
-		}
321
-
322
-		$grammaire = $r[1];
323
-	}
324
-
325
-	return array($entete, $avail, $grammaire, $rotlvl);
278
+    if (!preg_match(_REGEXP_DOCTYPE, $data, $page)) {
279
+        if (preg_match(_REGEXP_XML, $data, $page)) {
280
+            list(, $entete, $topelement) = $page;
281
+            if ($topelement == 'rss') {
282
+                return array(
283
+                    $entete,
284
+                    'PUBLIC',
285
+                    _DOCTYPE_RSS,
286
+                    'rss-0.91.dtd'
287
+                );
288
+            } else {
289
+                $dtd = $topelement . '.dtd';
290
+                $f = find_in_path($dtd);
291
+                if (file_exists($f)) {
292
+                    return array($entete, 'SYSTEM', $f, $dtd);
293
+                }
294
+            }
295
+        }
296
+        spip_log("Dtd pas vu pour " . substr($data, 0, 100));
297
+
298
+        return array();
299
+    }
300
+    list($entete, , $topelement, $avail, $suite) = $page;
301
+
302
+    if (!preg_match('/^"([^"]*)"\s*(.*)$/', $suite, $r)) {
303
+        if (!preg_match("/^'([^']*)'\s*(.*)$/", $suite, $r)) {
304
+            return array();
305
+        }
306
+    }
307
+    list(, $rotlvl, $suite) = $r;
308
+
309
+    if (!$suite) {
310
+        if ($avail != 'SYSTEM') {
311
+            return array();
312
+        }
313
+        $grammaire = $rotlvl;
314
+        $rotlvl = '';
315
+    } else {
316
+        if (!preg_match('/^"([^"]*)"\s*$/', $suite, $r)) {
317
+            if (!preg_match("/^'([^']*)'\s*$/", $suite, $r)) {
318
+                return array();
319
+            }
320
+        }
321
+
322
+        $grammaire = $r[1];
323
+    }
324
+
325
+    return array($entete, $avail, $grammaire, $rotlvl);
326 326
 }
Please login to merge, or discard this patch.
ecrire/xml/indenter.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -11,61 +11,61 @@
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 class IndenteurXML {
18 18
 
19
-	// https://code.spip.net/@debutElement
20
-	public function debutElement($phraseur, $name, $attrs) {
21
-		xml_debutElement($this, $name, $attrs);
22
-	}
19
+    // https://code.spip.net/@debutElement
20
+    public function debutElement($phraseur, $name, $attrs) {
21
+        xml_debutElement($this, $name, $attrs);
22
+    }
23 23
 
24
-	// https://code.spip.net/@finElement
25
-	public function finElement($phraseur, $name) {
26
-		xml_finElement($this, $name);
27
-	}
24
+    // https://code.spip.net/@finElement
25
+    public function finElement($phraseur, $name) {
26
+        xml_finElement($this, $name);
27
+    }
28 28
 
29
-	// https://code.spip.net/@textElement
30
-	public function textElement($phraseur, $data) {
31
-		xml_textElement($this, $data);
32
-	}
29
+    // https://code.spip.net/@textElement
30
+    public function textElement($phraseur, $data) {
31
+        xml_textElement($this, $data);
32
+    }
33 33
 
34
-	public function piElement($phraseur, $target, $data) {
35
-		xml_PiElement($this, $target, $data);
36
-	}
34
+    public function piElement($phraseur, $target, $data) {
35
+        xml_PiElement($this, $target, $data);
36
+    }
37 37
 
38
-	// https://code.spip.net/@defautElement
39
-	public function defaultElement($phraseur, $data) {
40
-		xml_defaultElement($this, $data);
41
-	}
38
+    // https://code.spip.net/@defautElement
39
+    public function defaultElement($phraseur, $data) {
40
+        xml_defaultElement($this, $data);
41
+    }
42 42
 
43
-	// https://code.spip.net/@phraserTout
44
-	public function phraserTout($phraseur, $data) {
45
-		xml_parsestring($this, $data);
46
-	}
43
+    // https://code.spip.net/@phraserTout
44
+    public function phraserTout($phraseur, $data) {
45
+        xml_parsestring($this, $data);
46
+    }
47 47
 
48
-	public $depth = "";
49
-	public $res = "";
50
-	public $err = array();
51
-	public $contenu = array();
52
-	public $ouvrant = array();
53
-	public $reperes = array();
54
-	public $entete = '';
55
-	public $page = '';
56
-	public $dtc = null;
57
-	public $sax = null;
48
+    public $depth = "";
49
+    public $res = "";
50
+    public $err = array();
51
+    public $contenu = array();
52
+    public $ouvrant = array();
53
+    public $reperes = array();
54
+    public $entete = '';
55
+    public $page = '';
56
+    public $dtc = null;
57
+    public $sax = null;
58 58
 }
59 59
 
60 60
 // https://code.spip.net/@xml_indenter_dist
61 61
 function xml_indenter_dist($page, $apply = false) {
62
-	$sax = charger_fonction('sax', 'xml');
63
-	$f = new IndenteurXML();
64
-	$sax($page, $apply, $f);
65
-	if (!$f->err) {
66
-		return $f->entete . $f->res;
67
-	}
68
-	spip_log("indentation impossible " . count($f->err) . " erreurs de validation");
62
+    $sax = charger_fonction('sax', 'xml');
63
+    $f = new IndenteurXML();
64
+    $sax($page, $apply, $f);
65
+    if (!$f->err) {
66
+        return $f->entete . $f->res;
67
+    }
68
+    spip_log("indentation impossible " . count($f->err) . " erreurs de validation");
69 69
 
70
-	return $f->entete . $f->page;
70
+    return $f->entete . $f->page;
71 71
 }
Please login to merge, or discard this patch.
ecrire/xml/valider.php 1 patch
Indentation   +331 added lines, -331 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 \***************************************************************************/
12 12
 
13 13
 if (!defined('_ECRIRE_INC_VERSION')) {
14
-	return;
14
+    return;
15 15
 }
16 16
 
17 17
 /**
@@ -23,333 +23,333 @@  discard block
 block discarded – undo
23 23
  **/
24 24
 class ValidateurXML {
25 25
 
26
-	// https://code.spip.net/@validerElement
27
-	public function validerElement($phraseur, $name, $attrs) {
28
-		if (!($p = isset($this->dtc->elements[$name]))) {
29
-			if ($p = strpos($name, ':')) {
30
-				$name = substr($name, $p + 1);
31
-				$p = isset($this->dtc->elements[$name]);
32
-			}
33
-			if (!$p) {
34
-				coordonnees_erreur($this, " <b>$name</b>&nbsp;: "
35
-					. _T('zxml_inconnu_balise'));
36
-
37
-				return;
38
-			}
39
-		}
40
-		// controler les filles illegitimes, ca suffit 
41
-		$depth = $this->depth;
42
-		$ouvrant = $this->ouvrant;
43
-		#spip_log("trouve $name apres " . $ouvrant[$depth]);
44
-		if (isset($ouvrant[$depth])) {
45
-			if (preg_match('/^\s*(\w+)/', $ouvrant[$depth], $r)) {
46
-				$pere = $r[1];
47
-				#spip_log("pere $pere");
48
-				if (isset($this->dtc->elements[$pere])) {
49
-					$fils = $this->dtc->elements[$pere];
50
-					#spip_log("rejeton $name fils " . @join(',',$fils));
51
-					if (!($p = @in_array($name, $fils))) {
52
-						if ($p = strpos($name, ':')) {
53
-							$p = substr($name, $p + 1);
54
-							$p = @in_array($p, $fils);
55
-						}
56
-					}
57
-					if (!$p) {
58
-						$bons_peres = @join('</b>, <b>', $this->dtc->peres[$name]);
59
-						coordonnees_erreur($this, " <b>$name</b> "
60
-							. _T('zxml_non_fils')
61
-							. ' <b>'
62
-							. $pere
63
-							. '</b>'
64
-							. (!$bons_peres ? ''
65
-								: ('<p style="font-size: 80%"> ' . _T('zxml_mais_de') . ' <b>' . $bons_peres . '</b></p>')));
66
-					} elseif ($this->dtc->regles[$pere][0] == '/') {
67
-						$frat = substr($depth, 2);
68
-						if (!isset($this->fratrie[$frat])) {
69
-							$this->fratrie[$frat] = '';
70
-						}
71
-						$this->fratrie[$frat] .= "$name ";
72
-					}
73
-				}
74
-			}
75
-		}
76
-		// Init de la suite des balises a memoriser si regle difficile
77
-		if ($this->dtc->regles[$name] and $this->dtc->regles[$name][0] == '/') {
78
-			$this->fratrie[$depth] = '';
79
-		}
80
-		if (isset($this->dtc->attributs[$name])) {
81
-			foreach ($this->dtc->attributs[$name] as $n => $v) {
82
-				if (($v[1] == '#REQUIRED') and (!isset($attrs[$n]))) {
83
-					coordonnees_erreur($this, " <b>$n</b>"
84
-						. '&nbsp;:&nbsp;'
85
-						. _T('zxml_obligatoire_attribut')
86
-						. " <b>$name</b>");
87
-				}
88
-			}
89
-		}
90
-	}
91
-
92
-	// https://code.spip.net/@validerAttribut
93
-	public function validerAttribut($phraseur, $name, $val, $bal) {
94
-		// Si la balise est inconnue, eviter d'insister
95
-		if (!isset($this->dtc->attributs[$bal])) {
96
-			return;
97
-		}
98
-
99
-		$a = $this->dtc->attributs[$bal];
100
-		if (!isset($a[$name])) {
101
-			$bons = join(', ', array_keys($a));
102
-			if ($bons) {
103
-				$bons = " title=' " .
104
-					_T('zxml_connus_attributs') .
105
-					'&nbsp;: ' .
106
-					$bons .
107
-					"'";
108
-			}
109
-			$bons .= " style='font-weight: bold'";
110
-			coordonnees_erreur($this, " <b>$name</b> "
111
-				. _T('zxml_inconnu_attribut') . ' ' . _T('zxml_de')
112
-				. " <a$bons>$bal</a> ("
113
-				. _T('zxml_survoler')
114
-				. ")");
115
-		} else {
116
-			$type = $a[$name][0];
117
-			if (!preg_match('/^\w+$/', $type)) {
118
-				$this->valider_motif($phraseur, $name, $val, $bal, $type);
119
-			} else {
120
-				if (method_exists($this, $f = 'validerAttribut_' . $type)) {
121
-					$this->$f($phraseur, $name, $val, $bal);
122
-				}
123
-			}
124
-			#		else spip_log("$type type d'attribut inconnu");
125
-		}
126
-	}
127
-
128
-	public function validerAttribut_NMTOKEN($phraseur, $name, $val, $bal) {
129
-		$this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_NMTOKEN);
130
-	}
131
-
132
-	public function validerAttribut_NMTOKENS($phraseur, $name, $val, $bal) {
133
-		$this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_NMTOKENS);
134
-	}
135
-
136
-	// https://code.spip.net/@validerAttribut_ID
137
-	public function validerAttribut_ID($phraseur, $name, $val, $bal) {
138
-		if (isset($this->ids[$val])) {
139
-			list($l, $c) = $this->ids[$val];
140
-			coordonnees_erreur($this, " <p><b>$val</b> "
141
-				. _T('zxml_valeur_attribut')
142
-				. " <b>$name</b> "
143
-				. _T('zxml_de')
144
-				. " <b>$bal</b> "
145
-				. _T('zxml_vu')
146
-				. " (L$l,C$c)");
147
-		} else {
148
-			$this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_ID);
149
-			$this->ids[$val] = array(xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur));
150
-		}
151
-	}
152
-
153
-	// https://code.spip.net/@validerAttribut_IDREF
154
-	public function validerAttribut_IDREF($phraseur, $name, $val, $bal) {
155
-		$this->idrefs[] = array($val, xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur));
156
-	}
157
-
158
-	// https://code.spip.net/@validerAttribut_IDREFS
159
-	public function validerAttribut_IDREFS($phraseur, $name, $val, $bal) {
160
-		$this->idrefss[] = array($val, xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur));
161
-	}
162
-
163
-	// https://code.spip.net/@valider_motif
164
-	public function valider_motif($phraseur, $name, $val, $bal, $motif) {
165
-		if (!preg_match($motif, $val)) {
166
-			coordonnees_erreur($this, "<b>$val</b> "
167
-				. _T('zxml_valeur_attribut')
168
-				. " <b>$name</b> "
169
-				. _T('zxml_de')
170
-				. " <b>$bal</b> "
171
-				. _T('zxml_non_conforme')
172
-				. "</p><p>"
173
-				. "<b>" . $motif . "</b>");
174
-		}
175
-	}
176
-
177
-	// https://code.spip.net/@valider_idref
178
-	public function valider_idref($nom, $ligne, $col) {
179
-		if (!isset($this->ids[$nom])) {
180
-			$this->err[] = array(" <p><b>$nom</b> " . _T('zxml_inconnu_id'), $ligne, $col);
181
-		}
182
-	}
183
-
184
-	// https://code.spip.net/@valider_passe2
185
-	public function valider_passe2() {
186
-		if (!$this->err) {
187
-			foreach ($this->idrefs as $idref) {
188
-				list($nom, $ligne, $col) = $idref;
189
-				$this->valider_idref($nom, $ligne, $col);
190
-			}
191
-			foreach ($this->idrefss as $idref) {
192
-				list($noms, $ligne, $col) = $idref;
193
-				foreach (preg_split('/\s+/', $noms) as $nom) {
194
-					$this->valider_idref($nom, $ligne, $col);
195
-				}
196
-			}
197
-		}
198
-	}
199
-
200
-	// https://code.spip.net/@debutElement
201
-	public function debutElement($phraseur, $name, $attrs) {
202
-		if ($this->dtc->elements) {
203
-			$this->validerElement($phraseur, $name, $attrs);
204
-		}
205
-
206
-		if ($f = $this->process['debut']) {
207
-			$f($this, $name, $attrs);
208
-		}
209
-		$depth = $this->depth;
210
-		$this->debuts[$depth] = strlen($this->res);
211
-		foreach ($attrs as $k => $v) {
212
-			$this->validerAttribut($phraseur, $k, $v, $name);
213
-		}
214
-	}
215
-
216
-	// https://code.spip.net/@finElement
217
-	public function finElement($phraseur, $name) {
218
-		$depth = $this->depth;
219
-		$contenu = $this->contenu;
220
-
221
-		$n = strlen($this->res);
222
-		$c = strlen(trim($contenu[$depth]));
223
-		$k = $this->debuts[$depth];
224
-
225
-		$regle = isset($this->dtc->regles[$name]) ? $this->dtc->regles[$name] : false;
226
-		$vide = ($regle == 'EMPTY');
227
-		// controler que les balises devant etre vides le sont 
228
-		if ($vide) {
229
-			if ($n <> ($k + $c)) {
230
-				coordonnees_erreur($this, " <p><b>$name</b> " . _T('zxml_nonvide_balise'));
231
-			}
232
-			// pour les regles PCDATA ou iteration de disjonction, tout est fait
233
-		} elseif ($regle and ($regle != '*')) {
234
-			if ($regle == '+') {
235
-				// iteration de disjonction non vide: 1 balise au -
236
-				if ($n == $k) {
237
-					coordonnees_erreur($this, "<p>\n<b>$name</b> "
238
-						. _T('zxml_vide_balise'));
239
-				}
240
-			} else {
241
-				$f = isset($this->fratrie[substr($depth, 2)]) ? $this->fratrie[substr($depth, 2)] : null;
242
-				if (is_null($f) or !preg_match($regle, $f)) {
243
-					coordonnees_erreur($this,
244
-						" <p>\n<b>$name</b> "
245
-						. _T('zxml_succession_fils_incorrecte')
246
-						. '&nbsp;: <b>'
247
-						. $f
248
-						. '</b>');
249
-				}
250
-			}
251
-
252
-		}
253
-		if ($f = $this->process['fin']) {
254
-			$f($this, $name, $vide);
255
-		}
256
-	}
257
-
258
-	// https://code.spip.net/@textElement
259
-	public function textElement($phraseur, $data) {
260
-		if (trim($data)) {
261
-			$d = $this->depth;
262
-			$d = $this->ouvrant[$d];
263
-			preg_match('/^\s*(\S+)/', $d, $m);
264
-			if (isset($this->dtc->pcdata[$m[1]]) and ($this->dtc->pcdata[$m[1]])) {
265
-				coordonnees_erreur($this, " <p><b>" . $m[1] . "</b> "
266
-					. _T('zxml_nonvide_balise') // message a affiner
267
-				);
268
-			}
269
-		}
270
-		if ($f = $this->process['text']) {
271
-			$f($this, $data);
272
-		}
273
-	}
274
-
275
-	public function piElement($phraseur, $target, $data) {
276
-		if ($f = $this->process['pi']) {
277
-			$f($this, $target, $data);
278
-		}
279
-	}
280
-
281
-	// Denonciation des entitees XML inconnues
282
-	// Pour contourner le bug de conception de SAX qui ne signale pas si elles
283
-	// sont dans un attribut, les  entites les plus frequentes ont ete
284
-	// transcodees au prealable  (sauf & < > " que SAX traite correctement).
285
-	// On ne les verra donc pas passer a cette etape, contrairement a ce que 
286
-	// le source de la page laisse legitimement supposer. 
287
-
288
-	// https://code.spip.net/@defautElement
289
-	public function defaultElement($phraseur, $data) {
290
-		if (!preg_match('/^<!--/', $data)
291
-			and (preg_match_all('/&([^;]*)?/', $data, $r, PREG_SET_ORDER))
292
-		) {
293
-			foreach ($r as $m) {
294
-				list($t, $e) = $m;
295
-				if (!isset($this->dtc->entites[$e])) {
296
-					coordonnees_erreur($this, " <b>$e</b> "
297
-						. _T('zxml_inconnu_entite')
298
-						. ' '
299
-					);
300
-				}
301
-			}
302
-		}
303
-		if (isset($this->process['default']) and ($f = $this->process['default'])) {
304
-			$f($this, $data);
305
-		}
306
-	}
307
-
308
-	// https://code.spip.net/@phraserTout
309
-	public function phraserTout($phraseur, $data) {
310
-		xml_parsestring($this, $data);
311
-
312
-		if (!$this->dtc or preg_match(',^' . _MESSAGE_DOCTYPE . ',', $data)) {
313
-			$this->err[] = array('DOCTYPE ?', 0, 0);
314
-		} else {
315
-			$this->valider_passe2($this);
316
-		}
317
-	}
318
-
319
-	/**
320
-	 * Constructeur
321
-	 *
322
-	 * @param array $process ?
323
-	 **/
324
-	public function __construct($process = array()) {
325
-		if (is_array($process)) {
326
-			$this->process = $process;
327
-		}
328
-	}
329
-
330
-	public $ids = array();
331
-	public $idrefs = array();
332
-	public $idrefss = array();
333
-	public $debuts = array();
334
-	public $fratrie = array();
335
-
336
-	public $dtc = null;
337
-	public $sax = null;
338
-	public $depth = "";
339
-	public $entete = '';
340
-	public $page = '';
341
-	public $res = "";
342
-	public $err = array();
343
-	public $contenu = array();
344
-	public $ouvrant = array();
345
-	public $reperes = array();
346
-	public $process = array(
347
-		'debut' => 'xml_debutElement',
348
-		'fin' => 'xml_finElement',
349
-		'text' => 'xml_textElement',
350
-		'pi' => 'xml_piElement',
351
-		'default' => 'xml_defaultElement'
352
-	);
26
+    // https://code.spip.net/@validerElement
27
+    public function validerElement($phraseur, $name, $attrs) {
28
+        if (!($p = isset($this->dtc->elements[$name]))) {
29
+            if ($p = strpos($name, ':')) {
30
+                $name = substr($name, $p + 1);
31
+                $p = isset($this->dtc->elements[$name]);
32
+            }
33
+            if (!$p) {
34
+                coordonnees_erreur($this, " <b>$name</b>&nbsp;: "
35
+                    . _T('zxml_inconnu_balise'));
36
+
37
+                return;
38
+            }
39
+        }
40
+        // controler les filles illegitimes, ca suffit 
41
+        $depth = $this->depth;
42
+        $ouvrant = $this->ouvrant;
43
+        #spip_log("trouve $name apres " . $ouvrant[$depth]);
44
+        if (isset($ouvrant[$depth])) {
45
+            if (preg_match('/^\s*(\w+)/', $ouvrant[$depth], $r)) {
46
+                $pere = $r[1];
47
+                #spip_log("pere $pere");
48
+                if (isset($this->dtc->elements[$pere])) {
49
+                    $fils = $this->dtc->elements[$pere];
50
+                    #spip_log("rejeton $name fils " . @join(',',$fils));
51
+                    if (!($p = @in_array($name, $fils))) {
52
+                        if ($p = strpos($name, ':')) {
53
+                            $p = substr($name, $p + 1);
54
+                            $p = @in_array($p, $fils);
55
+                        }
56
+                    }
57
+                    if (!$p) {
58
+                        $bons_peres = @join('</b>, <b>', $this->dtc->peres[$name]);
59
+                        coordonnees_erreur($this, " <b>$name</b> "
60
+                            . _T('zxml_non_fils')
61
+                            . ' <b>'
62
+                            . $pere
63
+                            . '</b>'
64
+                            . (!$bons_peres ? ''
65
+                                : ('<p style="font-size: 80%"> ' . _T('zxml_mais_de') . ' <b>' . $bons_peres . '</b></p>')));
66
+                    } elseif ($this->dtc->regles[$pere][0] == '/') {
67
+                        $frat = substr($depth, 2);
68
+                        if (!isset($this->fratrie[$frat])) {
69
+                            $this->fratrie[$frat] = '';
70
+                        }
71
+                        $this->fratrie[$frat] .= "$name ";
72
+                    }
73
+                }
74
+            }
75
+        }
76
+        // Init de la suite des balises a memoriser si regle difficile
77
+        if ($this->dtc->regles[$name] and $this->dtc->regles[$name][0] == '/') {
78
+            $this->fratrie[$depth] = '';
79
+        }
80
+        if (isset($this->dtc->attributs[$name])) {
81
+            foreach ($this->dtc->attributs[$name] as $n => $v) {
82
+                if (($v[1] == '#REQUIRED') and (!isset($attrs[$n]))) {
83
+                    coordonnees_erreur($this, " <b>$n</b>"
84
+                        . '&nbsp;:&nbsp;'
85
+                        . _T('zxml_obligatoire_attribut')
86
+                        . " <b>$name</b>");
87
+                }
88
+            }
89
+        }
90
+    }
91
+
92
+    // https://code.spip.net/@validerAttribut
93
+    public function validerAttribut($phraseur, $name, $val, $bal) {
94
+        // Si la balise est inconnue, eviter d'insister
95
+        if (!isset($this->dtc->attributs[$bal])) {
96
+            return;
97
+        }
98
+
99
+        $a = $this->dtc->attributs[$bal];
100
+        if (!isset($a[$name])) {
101
+            $bons = join(', ', array_keys($a));
102
+            if ($bons) {
103
+                $bons = " title=' " .
104
+                    _T('zxml_connus_attributs') .
105
+                    '&nbsp;: ' .
106
+                    $bons .
107
+                    "'";
108
+            }
109
+            $bons .= " style='font-weight: bold'";
110
+            coordonnees_erreur($this, " <b>$name</b> "
111
+                . _T('zxml_inconnu_attribut') . ' ' . _T('zxml_de')
112
+                . " <a$bons>$bal</a> ("
113
+                . _T('zxml_survoler')
114
+                . ")");
115
+        } else {
116
+            $type = $a[$name][0];
117
+            if (!preg_match('/^\w+$/', $type)) {
118
+                $this->valider_motif($phraseur, $name, $val, $bal, $type);
119
+            } else {
120
+                if (method_exists($this, $f = 'validerAttribut_' . $type)) {
121
+                    $this->$f($phraseur, $name, $val, $bal);
122
+                }
123
+            }
124
+            #		else spip_log("$type type d'attribut inconnu");
125
+        }
126
+    }
127
+
128
+    public function validerAttribut_NMTOKEN($phraseur, $name, $val, $bal) {
129
+        $this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_NMTOKEN);
130
+    }
131
+
132
+    public function validerAttribut_NMTOKENS($phraseur, $name, $val, $bal) {
133
+        $this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_NMTOKENS);
134
+    }
135
+
136
+    // https://code.spip.net/@validerAttribut_ID
137
+    public function validerAttribut_ID($phraseur, $name, $val, $bal) {
138
+        if (isset($this->ids[$val])) {
139
+            list($l, $c) = $this->ids[$val];
140
+            coordonnees_erreur($this, " <p><b>$val</b> "
141
+                . _T('zxml_valeur_attribut')
142
+                . " <b>$name</b> "
143
+                . _T('zxml_de')
144
+                . " <b>$bal</b> "
145
+                . _T('zxml_vu')
146
+                . " (L$l,C$c)");
147
+        } else {
148
+            $this->valider_motif($phraseur, $name, $val, $bal, _REGEXP_ID);
149
+            $this->ids[$val] = array(xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur));
150
+        }
151
+    }
152
+
153
+    // https://code.spip.net/@validerAttribut_IDREF
154
+    public function validerAttribut_IDREF($phraseur, $name, $val, $bal) {
155
+        $this->idrefs[] = array($val, xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur));
156
+    }
157
+
158
+    // https://code.spip.net/@validerAttribut_IDREFS
159
+    public function validerAttribut_IDREFS($phraseur, $name, $val, $bal) {
160
+        $this->idrefss[] = array($val, xml_get_current_line_number($phraseur), xml_get_current_column_number($phraseur));
161
+    }
162
+
163
+    // https://code.spip.net/@valider_motif
164
+    public function valider_motif($phraseur, $name, $val, $bal, $motif) {
165
+        if (!preg_match($motif, $val)) {
166
+            coordonnees_erreur($this, "<b>$val</b> "
167
+                . _T('zxml_valeur_attribut')
168
+                . " <b>$name</b> "
169
+                . _T('zxml_de')
170
+                . " <b>$bal</b> "
171
+                . _T('zxml_non_conforme')
172
+                . "</p><p>"
173
+                . "<b>" . $motif . "</b>");
174
+        }
175
+    }
176
+
177
+    // https://code.spip.net/@valider_idref
178
+    public function valider_idref($nom, $ligne, $col) {
179
+        if (!isset($this->ids[$nom])) {
180
+            $this->err[] = array(" <p><b>$nom</b> " . _T('zxml_inconnu_id'), $ligne, $col);
181
+        }
182
+    }
183
+
184
+    // https://code.spip.net/@valider_passe2
185
+    public function valider_passe2() {
186
+        if (!$this->err) {
187
+            foreach ($this->idrefs as $idref) {
188
+                list($nom, $ligne, $col) = $idref;
189
+                $this->valider_idref($nom, $ligne, $col);
190
+            }
191
+            foreach ($this->idrefss as $idref) {
192
+                list($noms, $ligne, $col) = $idref;
193
+                foreach (preg_split('/\s+/', $noms) as $nom) {
194
+                    $this->valider_idref($nom, $ligne, $col);
195
+                }
196
+            }
197
+        }
198
+    }
199
+
200
+    // https://code.spip.net/@debutElement
201
+    public function debutElement($phraseur, $name, $attrs) {
202
+        if ($this->dtc->elements) {
203
+            $this->validerElement($phraseur, $name, $attrs);
204
+        }
205
+
206
+        if ($f = $this->process['debut']) {
207
+            $f($this, $name, $attrs);
208
+        }
209
+        $depth = $this->depth;
210
+        $this->debuts[$depth] = strlen($this->res);
211
+        foreach ($attrs as $k => $v) {
212
+            $this->validerAttribut($phraseur, $k, $v, $name);
213
+        }
214
+    }
215
+
216
+    // https://code.spip.net/@finElement
217
+    public function finElement($phraseur, $name) {
218
+        $depth = $this->depth;
219
+        $contenu = $this->contenu;
220
+
221
+        $n = strlen($this->res);
222
+        $c = strlen(trim($contenu[$depth]));
223
+        $k = $this->debuts[$depth];
224
+
225
+        $regle = isset($this->dtc->regles[$name]) ? $this->dtc->regles[$name] : false;
226
+        $vide = ($regle == 'EMPTY');
227
+        // controler que les balises devant etre vides le sont 
228
+        if ($vide) {
229
+            if ($n <> ($k + $c)) {
230
+                coordonnees_erreur($this, " <p><b>$name</b> " . _T('zxml_nonvide_balise'));
231
+            }
232
+            // pour les regles PCDATA ou iteration de disjonction, tout est fait
233
+        } elseif ($regle and ($regle != '*')) {
234
+            if ($regle == '+') {
235
+                // iteration de disjonction non vide: 1 balise au -
236
+                if ($n == $k) {
237
+                    coordonnees_erreur($this, "<p>\n<b>$name</b> "
238
+                        . _T('zxml_vide_balise'));
239
+                }
240
+            } else {
241
+                $f = isset($this->fratrie[substr($depth, 2)]) ? $this->fratrie[substr($depth, 2)] : null;
242
+                if (is_null($f) or !preg_match($regle, $f)) {
243
+                    coordonnees_erreur($this,
244
+                        " <p>\n<b>$name</b> "
245
+                        . _T('zxml_succession_fils_incorrecte')
246
+                        . '&nbsp;: <b>'
247
+                        . $f
248
+                        . '</b>');
249
+                }
250
+            }
251
+
252
+        }
253
+        if ($f = $this->process['fin']) {
254
+            $f($this, $name, $vide);
255
+        }
256
+    }
257
+
258
+    // https://code.spip.net/@textElement
259
+    public function textElement($phraseur, $data) {
260
+        if (trim($data)) {
261
+            $d = $this->depth;
262
+            $d = $this->ouvrant[$d];
263
+            preg_match('/^\s*(\S+)/', $d, $m);
264
+            if (isset($this->dtc->pcdata[$m[1]]) and ($this->dtc->pcdata[$m[1]])) {
265
+                coordonnees_erreur($this, " <p><b>" . $m[1] . "</b> "
266
+                    . _T('zxml_nonvide_balise') // message a affiner
267
+                );
268
+            }
269
+        }
270
+        if ($f = $this->process['text']) {
271
+            $f($this, $data);
272
+        }
273
+    }
274
+
275
+    public function piElement($phraseur, $target, $data) {
276
+        if ($f = $this->process['pi']) {
277
+            $f($this, $target, $data);
278
+        }
279
+    }
280
+
281
+    // Denonciation des entitees XML inconnues
282
+    // Pour contourner le bug de conception de SAX qui ne signale pas si elles
283
+    // sont dans un attribut, les  entites les plus frequentes ont ete
284
+    // transcodees au prealable  (sauf & < > " que SAX traite correctement).
285
+    // On ne les verra donc pas passer a cette etape, contrairement a ce que 
286
+    // le source de la page laisse legitimement supposer. 
287
+
288
+    // https://code.spip.net/@defautElement
289
+    public function defaultElement($phraseur, $data) {
290
+        if (!preg_match('/^<!--/', $data)
291
+            and (preg_match_all('/&([^;]*)?/', $data, $r, PREG_SET_ORDER))
292
+        ) {
293
+            foreach ($r as $m) {
294
+                list($t, $e) = $m;
295
+                if (!isset($this->dtc->entites[$e])) {
296
+                    coordonnees_erreur($this, " <b>$e</b> "
297
+                        . _T('zxml_inconnu_entite')
298
+                        . ' '
299
+                    );
300
+                }
301
+            }
302
+        }
303
+        if (isset($this->process['default']) and ($f = $this->process['default'])) {
304
+            $f($this, $data);
305
+        }
306
+    }
307
+
308
+    // https://code.spip.net/@phraserTout
309
+    public function phraserTout($phraseur, $data) {
310
+        xml_parsestring($this, $data);
311
+
312
+        if (!$this->dtc or preg_match(',^' . _MESSAGE_DOCTYPE . ',', $data)) {
313
+            $this->err[] = array('DOCTYPE ?', 0, 0);
314
+        } else {
315
+            $this->valider_passe2($this);
316
+        }
317
+    }
318
+
319
+    /**
320
+     * Constructeur
321
+     *
322
+     * @param array $process ?
323
+     **/
324
+    public function __construct($process = array()) {
325
+        if (is_array($process)) {
326
+            $this->process = $process;
327
+        }
328
+    }
329
+
330
+    public $ids = array();
331
+    public $idrefs = array();
332
+    public $idrefss = array();
333
+    public $debuts = array();
334
+    public $fratrie = array();
335
+
336
+    public $dtc = null;
337
+    public $sax = null;
338
+    public $depth = "";
339
+    public $entete = '';
340
+    public $page = '';
341
+    public $res = "";
342
+    public $err = array();
343
+    public $contenu = array();
344
+    public $ouvrant = array();
345
+    public $reperes = array();
346
+    public $process = array(
347
+        'debut' => 'xml_debutElement',
348
+        'fin' => 'xml_finElement',
349
+        'text' => 'xml_textElement',
350
+        'pi' => 'xml_piElement',
351
+        'default' => 'xml_defaultElement'
352
+    );
353 353
 }
354 354
 
355 355
 
@@ -359,8 +359,8 @@  discard block
 block discarded – undo
359 359
  *
360 360
  **/
361 361
 function xml_valider_dist($page, $apply = false, $process = false, $doctype = '', $charset = null) {
362
-	$f = new ValidateurXML($process);
363
-	$sax = charger_fonction('sax', 'xml');
362
+    $f = new ValidateurXML($process);
363
+    $sax = charger_fonction('sax', 'xml');
364 364
 
365
-	return $sax($page, $apply, $f, $doctype, $charset);
365
+    return $sax($page, $apply, $f, $doctype, $charset);
366 366
 }
Please login to merge, or discard this patch.