Add interface PlIteraface and the corresponding abstract class
[platal.git] / classes / xdb.php
CommitLineData
0337d704 1<?php
2/***************************************************************************
2ab75571 3 * Copyright (C) 2003-2010 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
cd1d4b4f 42 public static function prepare($args)
ed3f4d3e 43 {
4d6eeacc 44 global $globals;
f62bd784 45 $query = array_map(Array('XDB', 'escape'), $args);
f3e3cab8 46 $query[0] = preg_replace('/#([a-z0-9]+)#/', $globals->dbprefix . '$1', $args[0]);
4d6eeacc
VZ
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
cd1d4b4f 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
cd1d4b4f 77 public static function run($query)
ed3f4d3e 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 }
cd1d4b4f 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) {
cd1d4b4f 110 throw new XDBException(XDB::reformatQuery($query), XDB::$mysqli->error);
084a60da 111 }
f1ca33de 112 return $res;
113 }
114
e4f6c7d0
FB
115 private static function queryv($query)
116 {
cd1d4b4f 117 return new XDBResult(self::prepare($query));
e4f6c7d0
FB
118 }
119
6995a9b9 120 public static function query()
0337d704 121 {
e4f6c7d0 122 return self::queryv(func_get_args());
0337d704 123 }
124
20973bf8
FB
125 public static function format()
126 {
cd1d4b4f 127 return self::prepare(func_get_args());
20973bf8
FB
128 }
129
0ef5bd4b
FB
130 // Produce the SQL statement for setting/unsetting a flag
131 public static function changeFlag($fieldname, $flagname, $state)
132 {
133 if ($state) {
134 return XDB::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
135 } else {
136 return XDB::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
137 }
138 }
139
140 // Produce the SQL statement representing an array
141 public static function formatArray(array $array)
142 {
e677bc13 143 return self::escape($array);
0ef5bd4b
FB
144 }
145
adf947ff
RB
146 const WILDCARD_EXACT = 0x00;
147 const WILDCARD_PREFIX = 0x01;
148 const WILDCARD_SUFFIX = 0x02;
149 const WILDCARD_CONTAINS = 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
150
cd1d4b4f
FB
151 // Produce a valid XDB argument that get formatted as a wildcard
152 // according to the given mode.
153 //
154 // Example:
155 // XDB::query("SELECT * FROM table WHERE field {?}", XDB::wildcard($text, WILDCARD_EXACT));
156 public static function wildcard($mode, $value)
157 {
158 return new XDBWildcard($value, $mode);
159 }
160
adf947ff
RB
161 // Returns the SQL statement for a wildcard search.
162 public static function formatWildcards($mode, $text)
163 {
cd1d4b4f 164 return XDB::wildcard($mode, $text)->format();
adf947ff
RB
165 }
166
47595f9a
RB
167 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
168 public static function formatCustomOrder($field, $values)
169 {
29bd16df 170 return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')';
47595f9a
RB
171 }
172
6995a9b9 173 public static function execute()
f1ca33de 174 {
fe556813
FB
175 global $globals;
176 $args = func_get_args();
177 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
178 return;
179 }
cd1d4b4f 180 return self::run(XDB::prepare($args));
0337d704 181 }
13a25546 182
6995a9b9 183 public static function iterator()
0337d704 184 {
cd1d4b4f 185 return new XDBIterator(self::prepare(func_get_args()));
0337d704 186 }
13a25546 187
6995a9b9 188 public static function iterRow()
0337d704 189 {
cd1d4b4f 190 return new XDBIterator(self::prepare(func_get_args()), MYSQL_NUM);
e4f6c7d0
FB
191 }
192
193 private static function findQuery($params, $default = array())
194 {
195 for ($i = 0 ; $i < count($default) ; ++$i) {
196 $is_query = false;
197 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
198 if (stripos($params[0], $kwd) !== false) {
199 $is_query = true;
200 break;
201 }
202 }
203 if ($is_query) {
204 break;
205 } else {
206 $default[$i] = array_shift($params);
207 }
208 }
209 return array($default, $params);
210 }
211
212 /** Fetch all rows returned by the given query.
cd1d4b4f 213 * This functions can take 2 optional arguments (cf XDBResult::fetchAllRow()).
e4f6c7d0
FB
214 * Optional arguments are given *before* the query.
215 */
216 public static function fetchAllRow()
217 {
218 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
219 return self::queryv($query)->fetchAllRow($args[0], $args[1]);
220 }
221
222 /** Fetch all rows returned by the given query.
cd1d4b4f 223 * This functions can take 2 optional arguments (cf XDBResult::fetchAllAssoc()).
e4f6c7d0
FB
224 * Optional arguments are given *before* the query.
225 */
226 public static function fetchAllAssoc()
227 {
228 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
229 return self::queryv($query)->fetchAllAssoc($args[0], $args[1]);
230 }
231
232 public static function fetchOneCell()
233 {
234 list($args, $query) = self::findQuery(func_get_args());
235 return self::queryv($query)->fetchOneCell();
236 }
237
238 public static function fetchOneRow()
239 {
240 list($args, $query) = self::findQuery(func_get_args());
241 return self::queryv($query)->fetchOneRow();
242 }
243
244 public static function fetchOneAssoc()
245 {
246 list($args, $query) = self::findQuery(func_get_args());
247 return self::queryv($query)->fetchOneAssoc();
248 }
249
250 /** Fetch a column from the result of the given query.
cd1d4b4f 251 * This functions can take 1 optional arguments (cf XDBResult::fetchColumn()).
e4f6c7d0
FB
252 * Optional arguments are given *before* the query.
253 */
254 public static function fetchColumn()
255 {
256 list($args, $query) = self::findQuery(func_get_args(), array(0));
257 return self::queryv($query)->fetchColumn();
0337d704 258 }
13a25546 259
6995a9b9 260 public static function insertId()
13a25546 261 {
e4f6c7d0 262 return self::$mysqli->insert_id;
13a25546 263 }
264
0380bf85 265 public static function errno()
266 {
e4f6c7d0 267 return self::$mysqli->errno;
0380bf85 268 }
269
270 public static function error()
834fd0f6 271 {
e4f6c7d0 272 return self::$mysqli->error;
0380bf85 273 }
274
275 public static function affectedRows()
276 {
e4f6c7d0 277 return self::$mysqli->affected_rows;
0380bf85 278 }
279
f62bd784 280 public static function escape($var)
0337d704 281 {
282 switch (gettype($var)) {
13a25546 283 case 'boolean':
284 return $var ? 1 : 0;
285
286 case 'integer':
287 case 'double':
288 case 'float':
289 return $var;
290
291 case 'string':
292 return "'".addslashes($var)."'";
293
294 case 'NULL':
295 return 'NULL';
296
297 case 'object':
cd1d4b4f
FB
298 if ($var instanceof XDBFormat) {
299 return $var->format();
e677bc13
FB
300 } else {
301 return "'".addslashes(serialize($var))."'";
04c1b2eb 302 }
e677bc13 303
13a25546 304 case 'array':
e677bc13 305 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
13a25546 306
307 default:
308 die(var_export($var, true).' is not a valid for a database entry');
0337d704 309 }
310 }
0337d704 311}
312
cd1d4b4f 313class XDBException extends PlException
0337d704 314{
cd1d4b4f
FB
315 public function __construct($query, $error)
316 {
317 if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
318 && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
319 $text = 'Erreur lors de l\'interrogation de la base de données';
320 } else {
321 $text = 'Erreur lors de l\'écriture dans la base de données';
322 }
323 parent::__construct($text, $query . "\n" . $error);
324 }
325}
326
327interface XDBFormat
328{
329 public function format();
330}
0337d704 331
cd1d4b4f
FB
332class XDBWildcard implements XDBFormat
333{
334 private $value;
335 private $mode;
336
337 public function __construct($value, $mode)
338 {
339 $this->value = $value;
340 $this->mode = $mode;
341 }
342
343 public function format()
344 {
345 if ($this->mode == XDB::WILDCARD_EXACT) {
346 return XDB::format(' = {?}', $this->value);
347 } else {
348 $text = str_replace(array('%', '_'), array('\%', '\_'), $this->value);
349 if ($this->mode & XDB::WILDCARD_PREFIX) {
350 $text = $text . '%';
351 }
352 if ($this->mode & XDB::WILDCARD_SUFFIX) {
353 $text = '%' . $text;
354 }
355 return XDB::format(" LIKE {?}", $text);
356 }
357 }
358}
359
360
361class XDBResult
362{
363 private $res;
0337d704 364
0381e170 365 public function __construct($query)
0337d704 366 {
cd1d4b4f 367 $this->res = XDB::run($query);
0337d704 368 }
369
0381e170 370 public function free()
0337d704 371 {
cd1d4b4f
FB
372 if ($this->res) {
373 $this->res->free();
0381e170 374 }
0337d704 375 unset($this);
376 }
377
cd1d4b4f 378 protected function fetchRow()
0337d704 379 {
cd1d4b4f 380 return $this->res ? $this->res->fetch_row() : null;
0337d704 381 }
382
cd1d4b4f 383 protected function fetchAssoc()
0337d704 384 {
cd1d4b4f 385 return $this->res ? $this->res->fetch_assoc() : null;
0337d704 386 }
387
e4f6c7d0 388 public function fetchAllRow($id = false, $keep_array = false)
0337d704 389 {
390 $result = Array();
cd1d4b4f 391 if (!$this->res) {
0381e170 392 return $result;
393 }
cd1d4b4f 394 while (($data = $this->res->fetch_row())) {
e4f6c7d0
FB
395 if ($id !== false) {
396 $key = $data[$id];
397 unset($data[$id]);
398 if (!$keep_array && count($data) == 1) {
399 reset($data);
400 $result[$key] = current($data);
401 } else {
402 $result[$key] = $data;
403 }
404 } else {
405 $result[] = $data;
406 }
407 }
0337d704 408 $this->free();
409 return $result;
410 }
411
e4f6c7d0 412 public function fetchAllAssoc($id = false, $keep_array = false)
0337d704 413 {
414 $result = Array();
cd1d4b4f 415 if (!$this->res) {
0381e170 416 return $result;
417 }
cd1d4b4f 418 while (($data = $this->res->fetch_assoc())) {
e4f6c7d0
FB
419 if ($id !== false) {
420 $key = $data[$id];
421 unset($data[$id]);
422 if (!$keep_array && count($data) == 1) {
423 reset($data);
424 $result[$key] = current($data);
425 } else {
426 $result[$key] = $data;
427 }
428 } else {
429 $result[] = $data;
430 }
431 }
0337d704 432 $this->free();
433 return $result;
434 }
435
0381e170 436 public function fetchOneAssoc()
0337d704 437 {
cd1d4b4f 438 $tmp = $this->fetchAssoc();
0337d704 439 $this->free();
440 return $tmp;
441 }
442
0381e170 443 public function fetchOneRow()
0337d704 444 {
cd1d4b4f 445 $tmp = $this->fetchRow();
0337d704 446 $this->free();
447 return $tmp;
448 }
449
0381e170 450 public function fetchOneCell()
0337d704 451 {
cd1d4b4f 452 $tmp = $this->fetchRow();
0337d704 453 $this->free();
454 return $tmp[0];
455 }
456
0381e170 457 public function fetchColumn($key = 0)
0337d704 458 {
459 $res = Array();
460 if (is_numeric($key)) {
cd1d4b4f 461 while($tmp = $this->fetchRow()) {
0337d704 462 $res[] = $tmp[$key];
463 }
464 } else {
cd1d4b4f 465 while($tmp = $this->fetchAssoc()) {
0337d704 466 $res[] = $tmp[$key];
467 }
468 }
469 $this->free();
470 return $res;
471 }
472
0381e170 473 public function fetchOneField()
0380bf85 474 {
cd1d4b4f 475 return $this->res ? $this->res->fetch_field() : null;
0380bf85 476 }
477
0381e170 478 public function fetchFields()
0380bf85 479 {
480 $res = array();
481 while ($res[] = $this->fetchOneField());
482 return $res;
483 }
484
0381e170 485 public function numRows()
0337d704 486 {
cd1d4b4f 487 return $this->res ? $this->res->num_rows : 0;
0337d704 488 }
0380bf85 489
0381e170 490 public function fieldCount()
0380bf85 491 {
cd1d4b4f 492 return $this->res ? $this->res->field_count : 0;
0380bf85 493 }
0337d704 494}
495
2b1ee50b 496
cd1d4b4f 497class XDBIterator extends XDBResult implements PlIterator
0337d704 498{
cd1d4b4f
FB
499 private $result;
500 private $pos;
501 private $total;
502 private $fpos;
503 private $fields;
504 private $mode = MYSQL_ASSOC;
0337d704 505
0381e170 506 public function __construct($query, $mode = MYSQL_ASSOC)
0337d704 507 {
0381e170 508 parent::__construct($query);
cd1d4b4f
FB
509 $this->pos = 0;
510 $this->total = $this->numRows();
511 $this->fpost = 0;
512 $this->fields = $this->fieldCount();
513 $this->mode = $mode;
0337d704 514 }
515
0381e170 516 public function next()
0337d704 517 {
cd1d4b4f
FB
518 $this->pos ++;
519 if ($this->pos > $this->total) {
0381e170 520 $this->free();
0337d704 521 unset($this);
522 return null;
523 }
cd1d4b4f 524 return $this->mode != MYSQL_ASSOC ? $this->fetchRow() : $this->fetchAssoc();
0337d704 525 }
526
0381e170 527 public function first()
0337d704 528 {
cd1d4b4f 529 return $this->pos == 1;
0337d704 530 }
531
0381e170 532 public function last()
0337d704 533 {
cd1d4b4f 534 return $this->pos == $this->total;
0337d704 535 }
536
0381e170 537 public function total()
0337d704 538 {
cd1d4b4f 539 return $this->total;
0337d704 540 }
0380bf85 541
0381e170 542 public function nextField()
0380bf85 543 {
cd1d4b4f
FB
544 $this->fpos++;
545 if ($this->fpos > $this->fields) {
0380bf85 546 return null;
547 }
0381e170 548 return $this->fetchOneField();
0380bf85 549 }
550
0381e170 551 public function firstField()
0380bf85 552 {
cd1d4b4f 553 return $this->fpos == 1;
0380bf85 554 }
555
0381e170 556 public function lastField()
0380bf85 557 {
cd1d4b4f 558 return $this->fpos == $this->fields;
0380bf85 559 }
560
0381e170 561 public function totalFields()
0380bf85 562 {
cd1d4b4f 563 return $this->fields;
0380bf85 564 }
0337d704 565}
566
a7de4ef7 567// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 568?>