Makes the $limit argument optional.
[platal.git] / classes / xdb.php
CommitLineData
0337d704 1<?php
2/***************************************************************************
a7f778a5 3 * Copyright (C) 2003-2009 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;
e4f6c7d0 29 self::$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 }
e4f6c7d0
FB
37 self::$mysqli->autocommit(true);
38 self::$mysqli->set_charset($globals->dbcharset);
32d9ae72 39 return true;
40 }
f1ca33de 41
ed3f4d3e 42 public static function _prepare($args)
43 {
4d6eeacc 44 global $globals;
f62bd784 45 $query = array_map(Array('XDB', 'escape'), $args);
4d6eeacc
VZ
46 $query[0] = preg_replace('/#([a-z0-9]*)#/', $globals->dbprefix . '$1', $args[0]);
47 $query[0] = str_replace('%', '%%', $query[0]);
48 $query[0] = str_replace('{?}', '%s', $query[0]);
0337d704 49 return call_user_func_array('sprintf', $query);
50 }
13a25546 51
6995a9b9 52 public static function _reformatQuery($query)
7c571120 53 {
a4f89886 54 $query = preg_split("/\n\\s*/", trim($query));
7c571120 55 $length = 0;
d3c52d30 56 foreach ($query as $key=>$line) {
57 $local = -2;
a14159bf 58 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
85d3b330 59 && $matches[1] != 'AND' && $matches[1] != 'OR')
60 {
d3c52d30 61 $local = strlen($matches[1]);
62 $line = $matches[1] . ' ' . $matches[2];
63 $length = max($length, $local);
7c571120 64 }
d3c52d30 65 $query[$key] = array($line, $local);
7c571120 66 }
67 $res = '';
d3c52d30 68 foreach ($query as $array) {
69 list($line, $local) = $array;
9630c649 70 $local = max(0, $length - $local);
7c571120 71 $res .= str_repeat(' ', $local) . $line . "\n";
72 $length += 2 * (substr_count($line, '(') - substr_count($line, ')'));
73 }
74 return $res;
75 }
76
ed3f4d3e 77 public static function _query($query)
78 {
f1ca33de 79 global $globals;
80
e4f6c7d0 81 if (!self::$mysqli && !self::connect()) {
12ccfec7 82 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
084a60da
FB
83 Platal::page()->kill('Impossible de se connecter à la base de données.');
84 exit;
821744e0 85 }
86
81e9c63f 87 if ($globals->debug & DEBUG_BT) {
f1ca33de 88 $explain = array();
5fb22b39 89 if (strpos($query, 'FOUND_ROWS()') === false) {
e4f6c7d0 90 $res = self::$mysqli->query("EXPLAIN $query");
32d9ae72 91 if ($res) {
92 while ($row = $res->fetch_assoc()) {
5fb22b39 93 $explain[] = $row;
94 }
32d9ae72 95 $res->free();
5fb22b39 96 }
f1ca33de 97 }
d3f26be9 98 PlBacktrace::$bt['MySQL']->start(XDB::_reformatQuery($query));
f1ca33de 99 }
100
32d9ae72 101 $res = XDB::$mysqli->query($query);
0381e170 102
81e9c63f 103 if ($globals->debug & DEBUG_BT) {
e4f6c7d0
FB
104 PlBacktrace::$bt['MySQL']->stop(@$res->num_rows ? $res->num_rows : self::$mysqli->affected_rows,
105 self::$mysqli->error,
d3f26be9 106 $explain);
f1ca33de 107 }
084a60da
FB
108
109 if ($res === false) {
12ccfec7 110 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
084a60da
FB
111 if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
112 && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
7f10bc61 113 $text = 'Erreur lors de l\'interrogation de la base de données';
084a60da 114 } else {
7f10bc61 115 $text = 'Erreur lors de l\'écriture dans la base de données';
084a60da 116 }
7f10bc61
FB
117 if ($globals->debug) {
118 $text .= '<pre>' . pl_entities(XDB::_reformatQuery($query)) . '</pre>';
f8eaef22
FB
119 } else {
120 $file = fopen($globals->spoolroot . '/spool/tmp/query_errors', 'a');
121 fwrite($file, '<pre>' . pl_entities(XDB::_reformatQuery($query)) . '</pre>'
122 . '<pre>' . XDB::$mysqli->error . '</pre>' . "\n");
123 fclose($file);
7f10bc61
FB
124 }
125 Platal::page()->kill($text);
084a60da
FB
126 exit;
127 }
f1ca33de 128 return $res;
129 }
130
e4f6c7d0
FB
131 private static function queryv($query)
132 {
133 return new XOrgDBResult(self::_prepare($query));
134 }
135
6995a9b9 136 public static function query()
0337d704 137 {
e4f6c7d0 138 return self::queryv(func_get_args());
0337d704 139 }
140
20973bf8
FB
141 public static function format()
142 {
e4f6c7d0 143 return self::_prepare(func_get_args());
20973bf8
FB
144 }
145
0ef5bd4b
FB
146 // Produce the SQL statement for setting/unsetting a flag
147 public static function changeFlag($fieldname, $flagname, $state)
148 {
149 if ($state) {
150 return XDB::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
151 } else {
152 return XDB::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
153 }
154 }
155
156 // Produce the SQL statement representing an array
157 public static function formatArray(array $array)
158 {
159 return '(' . implode(', ', array_map(array('XDB', 'escape'), $array)) . ')';
160 }
161
adf947ff
RB
162 const WILDCARD_EXACT = 0x00;
163 const WILDCARD_PREFIX = 0x01;
164 const WILDCARD_SUFFIX = 0x02;
165 const WILDCARD_CONTAINS = 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
166
167 // Returns the SQL statement for a wildcard search.
168 public static function formatWildcards($mode, $text)
169 {
170 if ($mode == self::WILDCARD_EXACT) {
171 return XDB::format(' = {?}', $text);
172 } else {
173 $text = str_replace(array('%', '_'), array('\%', '\_'), $text);
174 if ($mode & self::WILDCARD_PREFIX) {
175 $text = $text . '%';
176 }
177 if ($mode & self::WILDCARD_SUFFIX) {
178 $text = '%' . $text;
179 }
180 return XDB::format(" LIKE {?}", $text);
181 }
182 }
183
6995a9b9 184 public static function execute()
f1ca33de 185 {
fe556813
FB
186 global $globals;
187 $args = func_get_args();
188 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
189 return;
190 }
e4f6c7d0 191 return self::_query(XDB::_prepare($args));
0337d704 192 }
13a25546 193
6995a9b9 194 public static function iterator()
0337d704 195 {
e4f6c7d0 196 return new XOrgDBIterator(self::_prepare(func_get_args()));
0337d704 197 }
13a25546 198
6995a9b9 199 public static function iterRow()
0337d704 200 {
e4f6c7d0
FB
201 return new XOrgDBIterator(self::_prepare(func_get_args()), MYSQL_NUM);
202 }
203
204 private static function findQuery($params, $default = array())
205 {
206 for ($i = 0 ; $i < count($default) ; ++$i) {
207 $is_query = false;
208 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
209 if (stripos($params[0], $kwd) !== false) {
210 $is_query = true;
211 break;
212 }
213 }
214 if ($is_query) {
215 break;
216 } else {
217 $default[$i] = array_shift($params);
218 }
219 }
220 return array($default, $params);
221 }
222
223 /** Fetch all rows returned by the given query.
224 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllRow()).
225 * Optional arguments are given *before* the query.
226 */
227 public static function fetchAllRow()
228 {
229 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
230 return self::queryv($query)->fetchAllRow($args[0], $args[1]);
231 }
232
233 /** Fetch all rows returned by the given query.
234 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllAssoc()).
235 * Optional arguments are given *before* the query.
236 */
237 public static function fetchAllAssoc()
238 {
239 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
240 return self::queryv($query)->fetchAllAssoc($args[0], $args[1]);
241 }
242
243 public static function fetchOneCell()
244 {
245 list($args, $query) = self::findQuery(func_get_args());
246 return self::queryv($query)->fetchOneCell();
247 }
248
249 public static function fetchOneRow()
250 {
251 list($args, $query) = self::findQuery(func_get_args());
252 return self::queryv($query)->fetchOneRow();
253 }
254
255 public static function fetchOneAssoc()
256 {
257 list($args, $query) = self::findQuery(func_get_args());
258 return self::queryv($query)->fetchOneAssoc();
259 }
260
261 /** Fetch a column from the result of the given query.
262 * This functions can take 1 optional arguments (cf XOrgDBResult::fetchColumn()).
263 * Optional arguments are given *before* the query.
264 */
265 public static function fetchColumn()
266 {
267 list($args, $query) = self::findQuery(func_get_args(), array(0));
268 return self::queryv($query)->fetchColumn();
0337d704 269 }
13a25546 270
6995a9b9 271 public static function insertId()
13a25546 272 {
e4f6c7d0 273 return self::$mysqli->insert_id;
13a25546 274 }
275
0380bf85 276 public static function errno()
277 {
e4f6c7d0 278 return self::$mysqli->errno;
0380bf85 279 }
280
281 public static function error()
834fd0f6 282 {
e4f6c7d0 283 return self::$mysqli->error;
0380bf85 284 }
285
286 public static function affectedRows()
287 {
e4f6c7d0 288 return self::$mysqli->affected_rows;
0380bf85 289 }
290
f62bd784 291 public static function escape($var)
0337d704 292 {
293 switch (gettype($var)) {
13a25546 294 case 'boolean':
295 return $var ? 1 : 0;
296
297 case 'integer':
298 case 'double':
299 case 'float':
300 return $var;
301
302 case 'string':
303 return "'".addslashes($var)."'";
304
305 case 'NULL':
306 return 'NULL';
307
308 case 'object':
113f6de8 309 if ($var instanceof PlFlagSet) {
04c1b2eb
FB
310 return "'" . addslashes($var->flags()) . "'";
311 }
13a25546 312 case 'array':
313 return "'".addslashes(serialize($var))."'";
314
315 default:
316 die(var_export($var, true).' is not a valid for a database entry');
0337d704 317 }
318 }
0337d704 319}
320
0337d704 321class XOrgDBResult
322{
0337d704 323
32d9ae72 324 private $_res;
0337d704 325
0381e170 326 public function __construct($query)
0337d704 327 {
755abda6 328 $this->_res = XDB::_query($query);
0337d704 329 }
330
0381e170 331 public function free()
0337d704 332 {
0381e170 333 if ($this->_res) {
334 $this->_res->free();
335 }
0337d704 336 unset($this);
337 }
338
0381e170 339 protected function _fetchRow()
0337d704 340 {
0381e170 341 return $this->_res ? $this->_res->fetch_row() : null;
0337d704 342 }
343
0381e170 344 protected function _fetchAssoc()
0337d704 345 {
0381e170 346 return $this->_res ? $this->_res->fetch_assoc() : null;
0337d704 347 }
348
e4f6c7d0 349 public function fetchAllRow($id = false, $keep_array = false)
0337d704 350 {
351 $result = Array();
0381e170 352 if (!$this->_res) {
353 return $result;
354 }
e4f6c7d0
FB
355 while (($data = $this->_res->fetch_row())) {
356 if ($id !== false) {
357 $key = $data[$id];
358 unset($data[$id]);
359 if (!$keep_array && count($data) == 1) {
360 reset($data);
361 $result[$key] = current($data);
362 } else {
363 $result[$key] = $data;
364 }
365 } else {
366 $result[] = $data;
367 }
368 }
0337d704 369 $this->free();
370 return $result;
371 }
372
e4f6c7d0 373 public function fetchAllAssoc($id = false, $keep_array = false)
0337d704 374 {
375 $result = Array();
0381e170 376 if (!$this->_res) {
377 return $result;
378 }
e4f6c7d0
FB
379 while (($data = $this->_res->fetch_assoc())) {
380 if ($id !== false) {
381 $key = $data[$id];
382 unset($data[$id]);
383 if (!$keep_array && count($data) == 1) {
384 reset($data);
385 $result[$key] = current($data);
386 } else {
387 $result[$key] = $data;
388 }
389 } else {
390 $result[] = $data;
391 }
392 }
0337d704 393 $this->free();
394 return $result;
395 }
396
0381e170 397 public function fetchOneAssoc()
0337d704 398 {
399 $tmp = $this->_fetchAssoc();
400 $this->free();
401 return $tmp;
402 }
403
0381e170 404 public function fetchOneRow()
0337d704 405 {
406 $tmp = $this->_fetchRow();
407 $this->free();
408 return $tmp;
409 }
410
0381e170 411 public function fetchOneCell()
0337d704 412 {
413 $tmp = $this->_fetchRow();
414 $this->free();
415 return $tmp[0];
416 }
417
0381e170 418 public function fetchColumn($key = 0)
0337d704 419 {
420 $res = Array();
421 if (is_numeric($key)) {
422 while($tmp = $this->_fetchRow()) {
423 $res[] = $tmp[$key];
424 }
425 } else {
426 while($tmp = $this->_fetchAssoc()) {
427 $res[] = $tmp[$key];
428 }
429 }
430 $this->free();
431 return $res;
432 }
433
0381e170 434 public function fetchOneField()
0380bf85 435 {
0381e170 436 return $this->_res ? $this->_res->fetch_field() : null;
0380bf85 437 }
438
0381e170 439 public function fetchFields()
0380bf85 440 {
441 $res = array();
442 while ($res[] = $this->fetchOneField());
443 return $res;
444 }
445
0381e170 446 public function numRows()
0337d704 447 {
0381e170 448 return $this->_res ? $this->_res->num_rows : 0;
0337d704 449 }
0380bf85 450
0381e170 451 public function fieldCount()
0380bf85 452 {
0381e170 453 return $this->_res ? $this->_res->field_count : 0;
0380bf85 454 }
0337d704 455}
456
2b1ee50b 457require_once dirname(__FILE__) . '/pliterator.php';
458
0381e170 459class XOrgDBIterator extends XOrgDBResult implements PlIterator
0337d704 460{
85d3b330 461 private $_result;
462 private $_pos;
463 private $_total;
0380bf85 464 private $_fpos;
465 private $_fields;
85d3b330 466 private $_mode = MYSQL_ASSOC;
0337d704 467
0381e170 468 public function __construct($query, $mode = MYSQL_ASSOC)
0337d704 469 {
0381e170 470 parent::__construct($query);
0337d704 471 $this->_pos = 0;
0381e170 472 $this->_total = $this->numRows();
0380bf85 473 $this->_fpost = 0;
0381e170 474 $this->_fields = $this->fieldCount();
0337d704 475 $this->_mode = $mode;
476 }
477
0381e170 478 public function next()
0337d704 479 {
480 $this->_pos ++;
481 if ($this->_pos > $this->_total) {
0381e170 482 $this->free();
0337d704 483 unset($this);
484 return null;
485 }
0381e170 486 return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc();
0337d704 487 }
488
0381e170 489 public function first()
0337d704 490 {
491 return $this->_pos == 1;
492 }
493
0381e170 494 public function last()
0337d704 495 {
0380bf85 496 return $this->_pos == $this->_total;
0337d704 497 }
498
0381e170 499 public function total()
0337d704 500 {
501 return $this->_total;
502 }
0380bf85 503
0381e170 504 public function nextField()
0380bf85 505 {
506 $this->_fpos++;
507 if ($this->_fpos > $this->_fields) {
508 return null;
509 }
0381e170 510 return $this->fetchOneField();
0380bf85 511 }
512
0381e170 513 public function firstField()
0380bf85 514 {
515 return $this->_fpos == 1;
516 }
517
0381e170 518 public function lastField()
0380bf85 519 {
520 return $this->_fpos == $this->_fields;
521 }
522
0381e170 523 public function totalFields()
0380bf85 524 {
525 return $this->_fields;
526 }
0337d704 527}
528
a7de4ef7 529// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 530?>