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