Merge branch 'core-1.0.0' into core
[platal.git] / classes / xdb.php
CommitLineData
0337d704 1<?php
2/***************************************************************************
179afa7f 3 * Copyright (C) 2003-2008 Polytechnique.org *
0337d704 4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 **************************************************************************/
21
08cce2ff 22class XDB
0337d704 23{
32d9ae72 24 private static $mysqli = null;
25
821744e0 26 public static function connect()
32d9ae72 27 {
821744e0 28 global $globals;
29 XDB::$mysqli = new mysqli($globals->dbhost, $globals->dbuser, $globals->dbpwd, $globals->dbdb);
81e9c63f 30 if ($globals->debug & DEBUG_BT) {
d3f26be9 31 $bt = new PlBacktrace('MySQL');
32 if (mysqli_connect_errno()) {
33 $bt->newEvent("MySQLI connection", 0, mysqli_connect_error());
34 return false;
35 }
32d9ae72 36 }
37 XDB::$mysqli->autocommit(true);
821744e0 38 XDB::$mysqli->set_charset($globals->dbcharset);
32d9ae72 39 return true;
40 }
f1ca33de 41
ed3f4d3e 42 public static function _prepare($args)
43 {
f62bd784 44 $query = array_map(Array('XDB', 'escape'), $args);
0337d704 45 $query[0] = str_replace('{?}', '%s', str_replace('%', '%%', $args[0]));
46 return call_user_func_array('sprintf', $query);
47 }
13a25546 48
6995a9b9 49 public static function _reformatQuery($query)
7c571120 50 {
a4f89886 51 $query = preg_split("/\n\\s*/", trim($query));
7c571120 52 $length = 0;
d3c52d30 53 foreach ($query as $key=>$line) {
54 $local = -2;
a14159bf 55 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
85d3b330 56 && $matches[1] != 'AND' && $matches[1] != 'OR')
57 {
d3c52d30 58 $local = strlen($matches[1]);
59 $line = $matches[1] . ' ' . $matches[2];
60 $length = max($length, $local);
7c571120 61 }
d3c52d30 62 $query[$key] = array($line, $local);
7c571120 63 }
64 $res = '';
d3c52d30 65 foreach ($query as $array) {
66 list($line, $local) = $array;
9630c649 67 $local = max(0, $length - $local);
7c571120 68 $res .= str_repeat(' ', $local) . $line . "\n";
69 $length += 2 * (substr_count($line, '(') - substr_count($line, ')'));
70 }
71 return $res;
72 }
73
ed3f4d3e 74 public static function _query($query)
75 {
f1ca33de 76 global $globals;
77
821744e0 78 if (!XDB::$mysqli && !XDB::connect()) {
12ccfec7 79 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
084a60da
FB
80 Platal::page()->kill('Impossible de se connecter à la base de données.');
81 exit;
821744e0 82 }
83
81e9c63f 84 if ($globals->debug & DEBUG_BT) {
f1ca33de 85 $explain = array();
5fb22b39 86 if (strpos($query, 'FOUND_ROWS()') === false) {
32d9ae72 87 $res = XDB::$mysqli->query("EXPLAIN $query");
88 if ($res) {
89 while ($row = $res->fetch_assoc()) {
5fb22b39 90 $explain[] = $row;
91 }
32d9ae72 92 $res->free();
5fb22b39 93 }
f1ca33de 94 }
d3f26be9 95 PlBacktrace::$bt['MySQL']->start(XDB::_reformatQuery($query));
f1ca33de 96 }
97
32d9ae72 98 $res = XDB::$mysqli->query($query);
0381e170 99
81e9c63f 100 if ($globals->debug & DEBUG_BT) {
d3f26be9 101 PlBacktrace::$bt['MySQL']->stop(@$res->num_rows ? $res->num_rows : XDB::$mysqli->affected_rows,
102 XDB::$mysqli->error,
103 $explain);
f1ca33de 104 }
084a60da
FB
105
106 if ($res === false) {
12ccfec7 107 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
084a60da
FB
108 if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
109 && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
7f10bc61 110 $text = 'Erreur lors de l\'interrogation de la base de données';
084a60da 111 } else {
7f10bc61 112 $text = 'Erreur lors de l\'écriture dans la base de données';
084a60da 113 }
7f10bc61
FB
114 if ($globals->debug) {
115 $text .= '<pre>' . pl_entities(XDB::_reformatQuery($query)) . '</pre>';
116 }
117 Platal::page()->kill($text);
084a60da
FB
118 exit;
119 }
f1ca33de 120 return $res;
121 }
122
6995a9b9 123 public static function query()
0337d704 124 {
08cce2ff 125 return new XOrgDBResult(XDB::_prepare(func_get_args()));
0337d704 126 }
127
6995a9b9 128 public static function execute()
f1ca33de 129 {
fe556813
FB
130 global $globals;
131 $args = func_get_args();
132 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
133 return;
134 }
135 return XDB::_query(XDB::_prepare($args));
0337d704 136 }
13a25546 137
6995a9b9 138 public static function iterator()
0337d704 139 {
08cce2ff 140 return new XOrgDBIterator(XDB::_prepare(func_get_args()));
0337d704 141 }
13a25546 142
6995a9b9 143 public static function iterRow()
0337d704 144 {
08cce2ff 145 return new XOrgDBIterator(XDB::_prepare(func_get_args()), MYSQL_NUM);
0337d704 146 }
13a25546 147
6995a9b9 148 public static function insertId()
13a25546 149 {
32d9ae72 150 return XDB::$mysqli->insert_id;
13a25546 151 }
152
0380bf85 153 public static function errno()
154 {
0380bf85 155 return XDB::$mysqli->errno;
156 }
157
158 public static function error()
834fd0f6 159 {
0380bf85 160 return XDB::$mysqli->error;
161 }
162
163 public static function affectedRows()
164 {
165 return XDB::$mysqli->affected_rows;
166 }
167
f62bd784 168 public static function escape($var)
0337d704 169 {
170 switch (gettype($var)) {
13a25546 171 case 'boolean':
172 return $var ? 1 : 0;
173
174 case 'integer':
175 case 'double':
176 case 'float':
177 return $var;
178
179 case 'string':
180 return "'".addslashes($var)."'";
181
182 case 'NULL':
183 return 'NULL';
184
185 case 'object':
113f6de8 186 if ($var instanceof PlFlagSet) {
04c1b2eb
FB
187 return "'" . addslashes($var->flags()) . "'";
188 }
13a25546 189 case 'array':
190 return "'".addslashes(serialize($var))."'";
191
192 default:
193 die(var_export($var, true).' is not a valid for a database entry');
0337d704 194 }
195 }
0337d704 196}
197
0337d704 198class XOrgDBResult
199{
0337d704 200
32d9ae72 201 private $_res;
0337d704 202
0381e170 203 public function __construct($query)
0337d704 204 {
755abda6 205 $this->_res = XDB::_query($query);
0337d704 206 }
207
0381e170 208 public function free()
0337d704 209 {
0381e170 210 if ($this->_res) {
211 $this->_res->free();
212 }
0337d704 213 unset($this);
214 }
215
0381e170 216 protected function _fetchRow()
0337d704 217 {
0381e170 218 return $this->_res ? $this->_res->fetch_row() : null;
0337d704 219 }
220
0381e170 221 protected function _fetchAssoc()
0337d704 222 {
0381e170 223 return $this->_res ? $this->_res->fetch_assoc() : null;
0337d704 224 }
225
0381e170 226 public function fetchAllRow()
0337d704 227 {
228 $result = Array();
0381e170 229 if (!$this->_res) {
230 return $result;
231 }
32d9ae72 232 while ($result[] = $this->_res->fetch_row());
0337d704 233 array_pop($result);
234 $this->free();
235 return $result;
236 }
237
0381e170 238 public function fetchAllAssoc()
0337d704 239 {
240 $result = Array();
0381e170 241 if (!$this->_res) {
242 return $result;
243 }
32d9ae72 244 while ($result[] = $this->_res->fetch_assoc());
0337d704 245 array_pop($result);
246 $this->free();
247 return $result;
248 }
249
0381e170 250 public function fetchOneAssoc()
0337d704 251 {
252 $tmp = $this->_fetchAssoc();
253 $this->free();
254 return $tmp;
255 }
256
0381e170 257 public function fetchOneRow()
0337d704 258 {
259 $tmp = $this->_fetchRow();
260 $this->free();
261 return $tmp;
262 }
263
0381e170 264 public function fetchOneCell()
0337d704 265 {
266 $tmp = $this->_fetchRow();
267 $this->free();
268 return $tmp[0];
269 }
270
0381e170 271 public function fetchColumn($key = 0)
0337d704 272 {
273 $res = Array();
274 if (is_numeric($key)) {
275 while($tmp = $this->_fetchRow()) {
276 $res[] = $tmp[$key];
277 }
278 } else {
279 while($tmp = $this->_fetchAssoc()) {
280 $res[] = $tmp[$key];
281 }
282 }
283 $this->free();
284 return $res;
285 }
286
0381e170 287 public function fetchOneField()
0380bf85 288 {
0381e170 289 return $this->_res ? $this->_res->fetch_field() : null;
0380bf85 290 }
291
0381e170 292 public function fetchFields()
0380bf85 293 {
294 $res = array();
295 while ($res[] = $this->fetchOneField());
296 return $res;
297 }
298
0381e170 299 public function numRows()
0337d704 300 {
0381e170 301 return $this->_res ? $this->_res->num_rows : 0;
0337d704 302 }
0380bf85 303
0381e170 304 public function fieldCount()
0380bf85 305 {
0381e170 306 return $this->_res ? $this->_res->field_count : 0;
0380bf85 307 }
0337d704 308}
309
2b1ee50b 310require_once dirname(__FILE__) . '/pliterator.php';
311
0381e170 312class XOrgDBIterator extends XOrgDBResult implements PlIterator
0337d704 313{
85d3b330 314 private $_result;
315 private $_pos;
316 private $_total;
0380bf85 317 private $_fpos;
318 private $_fields;
85d3b330 319 private $_mode = MYSQL_ASSOC;
0337d704 320
0381e170 321 public function __construct($query, $mode = MYSQL_ASSOC)
0337d704 322 {
0381e170 323 parent::__construct($query);
0337d704 324 $this->_pos = 0;
0381e170 325 $this->_total = $this->numRows();
0380bf85 326 $this->_fpost = 0;
0381e170 327 $this->_fields = $this->fieldCount();
0337d704 328 $this->_mode = $mode;
329 }
330
0381e170 331 public function next()
0337d704 332 {
333 $this->_pos ++;
334 if ($this->_pos > $this->_total) {
0381e170 335 $this->free();
0337d704 336 unset($this);
337 return null;
338 }
0381e170 339 return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc();
0337d704 340 }
341
0381e170 342 public function first()
0337d704 343 {
344 return $this->_pos == 1;
345 }
346
0381e170 347 public function last()
0337d704 348 {
0380bf85 349 return $this->_pos == $this->_total;
0337d704 350 }
351
0381e170 352 public function total()
0337d704 353 {
354 return $this->_total;
355 }
0380bf85 356
0381e170 357 public function nextField()
0380bf85 358 {
359 $this->_fpos++;
360 if ($this->_fpos > $this->_fields) {
361 return null;
362 }
0381e170 363 return $this->fetchOneField();
0380bf85 364 }
365
0381e170 366 public function firstField()
0380bf85 367 {
368 return $this->_fpos == 1;
369 }
370
0381e170 371 public function lastField()
0380bf85 372 {
373 return $this->_fpos == $this->_fields;
374 }
375
0381e170 376 public function totalFields()
0380bf85 377 {
378 return $this->_fields;
379 }
0337d704 380}
381
a7de4ef7 382// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 383?>