Add XDB::runTransaction($callback, $arg1, $arg2, $arg2...) to run a
[platal.git] / classes / xdb.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
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
22 class XDB
23 {
24 private static $mysqli = null;
25
26 public static function connect()
27 {
28 global $globals;
29 self::$mysqli = new mysqli($globals->dbhost, $globals->dbuser, $globals->dbpwd, $globals->dbdb);
30 if ($globals->debug & DEBUG_BT) {
31 $bt = new PlBacktrace('MySQL');
32 if (mysqli_connect_errno()) {
33 $bt->newEvent("MySQLI connection", 0, mysqli_connect_error());
34 return false;
35 }
36 }
37 self::$mysqli->autocommit(true);
38 self::$mysqli->set_charset($globals->dbcharset);
39 return true;
40 }
41
42 public static function prepare($args)
43 {
44 global $globals;
45 $query = array_map(Array('XDB', 'escape'), $args);
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]);
49 return call_user_func_array('sprintf', $query);
50 }
51
52 public static function reformatQuery($query)
53 {
54 $query = preg_split("/\n\\s*/", trim($query));
55 $length = 0;
56 foreach ($query as $key=>$line) {
57 $local = -2;
58 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
59 && $matches[1] != 'AND' && $matches[1] != 'OR')
60 {
61 $local = strlen($matches[1]);
62 $line = $matches[1] . ' ' . $matches[2];
63 $length = max($length, $local);
64 }
65 $query[$key] = array($line, $local);
66 }
67 $res = '';
68 foreach ($query as $array) {
69 list($line, $local) = $array;
70 $local = max(0, $length - $local);
71 $res .= str_repeat(' ', $local) . $line . "\n";
72 $length += 2 * (substr_count($line, '(') - substr_count($line, ')'));
73 }
74 return $res;
75 }
76
77 public static function run($query)
78 {
79 global $globals;
80
81 if (!self::$mysqli && !self::connect()) {
82 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
83 Platal::page()->kill('Impossible de se connecter à la base de données.');
84 exit;
85 }
86
87 if ($globals->debug & DEBUG_BT) {
88 $explain = array();
89 if (strpos($query, 'FOUND_ROWS()') === false && strpos($query, 'AUTOCOMMIT') === false) {
90 $res = self::$mysqli->query("EXPLAIN $query");
91 if ($res) {
92 while ($row = $res->fetch_assoc()) {
93 $explain[] = $row;
94 }
95 $res->free();
96 }
97 }
98 PlBacktrace::$bt['MySQL']->start(XDB::reformatQuery($query));
99 }
100
101 $res = XDB::$mysqli->query($query);
102
103 if ($globals->debug & DEBUG_BT) {
104 PlBacktrace::$bt['MySQL']->stop(@$res->num_rows ? $res->num_rows : self::$mysqli->affected_rows,
105 self::$mysqli->error,
106 $explain);
107 }
108
109 if ($res === false) {
110 throw new XDBException(XDB::reformatQuery($query), XDB::$mysqli->error);
111 }
112 return $res;
113 }
114
115 private static function queryv($query)
116 {
117 return new XDBResult(self::prepare($query));
118 }
119
120 public static function query()
121 {
122 return self::queryv(func_get_args());
123 }
124
125 public static function rawQuery($query)
126 {
127 return new XDBResult($query);
128 }
129
130 public static function format()
131 {
132 return self::prepare(func_get_args());
133 }
134
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 {
148 return self::escape($array);
149 }
150
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
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
166 // Returns the SQL statement for a wildcard search.
167 public static function formatWildcards($mode, $text)
168 {
169 return XDB::wildcard($mode, $text)->format();
170 }
171
172 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
173 public static function formatCustomOrder($field, $values)
174 {
175 return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')';
176 }
177
178 public static function execute()
179 {
180 global $globals;
181 $args = func_get_args();
182 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
183 return;
184 }
185 return self::run(XDB::prepare($args));
186 }
187
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
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
215 public static function runTransactionV($callback, array $args)
216 {
217 self::startTransaction();
218 try {
219 if (call_user_func_array($callback, $args)) {
220 self::commit();
221 return true;
222 } else {
223 self::rollback();
224 return false;
225 }
226 } catch (Exception $e) {
227 self::rollback();
228 throw $e;
229 }
230 }
231
232 /** This function takes a callback followed by the arguments to be passed to the callback
233 * as arguments. It starts a transaction and execute the callback. If the callback fails
234 * (return false or raise an exception), the transaction is rollbacked, if the callback
235 * succeeds (return true), the transaction is committed.
236 */
237 public static function runTransaction()
238 {
239 $args = func_get_args();
240 $cb = array_shift($args);
241 self::runTransactionV($cb, $args);
242 }
243
244 public static function iterator()
245 {
246 return new XDBIterator(self::prepare(func_get_args()));
247 }
248
249 public static function rawIterator($query)
250 {
251 return new XDBIterator($query);
252 }
253
254 public static function iterRow()
255 {
256 return new XDBIterator(self::prepare(func_get_args()), MYSQL_NUM);
257 }
258
259 public static function rawIterRow($query)
260 {
261 return new XDBIterator($query, MYSQL_NUM);
262 }
263
264 private static function findQuery($params, $default = array())
265 {
266 for ($i = 0 ; $i < count($default) ; ++$i) {
267 $is_query = false;
268 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
269 if (stripos($params[0], $kwd) !== false) {
270 $is_query = true;
271 break;
272 }
273 }
274 if ($is_query) {
275 break;
276 } else {
277 $default[$i] = array_shift($params);
278 }
279 }
280 return array($default, $params);
281 }
282
283 /** Fetch all rows returned by the given query.
284 * This functions can take 2 optional arguments (cf XDBResult::fetchAllRow()).
285 * Optional arguments are given *before* the query.
286 */
287 public static function fetchAllRow()
288 {
289 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
290 return self::queryv($query)->fetchAllRow($args[0], $args[1]);
291 }
292
293 public static function rawFetchAllRow($query, $id = false, $keep_array = false)
294 {
295 return self::rawQuery($query)->fetchAllRow($id, $keep_array);
296 }
297
298 /** Fetch all rows returned by the given query.
299 * This functions can take 2 optional arguments (cf XDBResult::fetchAllAssoc()).
300 * Optional arguments are given *before* the query.
301 */
302 public static function fetchAllAssoc()
303 {
304 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
305 return self::queryv($query)->fetchAllAssoc($args[0], $args[1]);
306 }
307
308 public static function rawFetchAllAssoc($query, $id = false, $keep_array = false)
309 {
310 return self::rawQuery($query)->fetchAllAssoc($id, $keep_array);
311 }
312
313 public static function fetchOneCell()
314 {
315 list($args, $query) = self::findQuery(func_get_args());
316 return self::queryv($query)->fetchOneCell();
317 }
318
319 public static function rawFetchOneCell($query)
320 {
321 return self::rawQuery($query)->fetchOneCell();
322 }
323
324 public static function fetchOneRow()
325 {
326 list($args, $query) = self::findQuery(func_get_args());
327 return self::queryv($query)->fetchOneRow();
328 }
329
330 public static function rawFetchOneRow($query)
331 {
332 return self::rawQuery($query)->fetchOneRow();
333 }
334
335 public static function fetchOneAssoc()
336 {
337 list($args, $query) = self::findQuery(func_get_args());
338 return self::queryv($query)->fetchOneAssoc();
339 }
340
341 public static function rawFetchOneAssoc($query)
342 {
343 return self::rawQuery($query)->fetchOneAssoc();
344 }
345
346 /** Fetch a column from the result of the given query.
347 * This functions can take 1 optional arguments (cf XDBResult::fetchColumn()).
348 * Optional arguments are given *before* the query.
349 */
350 public static function fetchColumn()
351 {
352 list($args, $query) = self::findQuery(func_get_args(), array(0));
353 return self::queryv($query)->fetchColumn($args[0]);
354 }
355
356 public static function rawFetchColumn($query, $key = 0)
357 {
358 return self::rawQuery($query)->fetchColumn($key);
359 }
360
361 public static function insertId()
362 {
363 return self::$mysqli->insert_id;
364 }
365
366 public static function errno()
367 {
368 return self::$mysqli->errno;
369 }
370
371 public static function error()
372 {
373 return self::$mysqli->error;
374 }
375
376 public static function affectedRows()
377 {
378 return self::$mysqli->affected_rows;
379 }
380
381 public static function escape($var)
382 {
383 switch (gettype($var)) {
384 case 'boolean':
385 return $var ? 1 : 0;
386
387 case 'integer':
388 case 'double':
389 case 'float':
390 return $var;
391
392 case 'string':
393 return "'".addslashes($var)."'";
394
395 case 'NULL':
396 return 'NULL';
397
398 case 'object':
399 if ($var instanceof XDBFormat) {
400 return $var->format();
401 } else {
402 return "'".addslashes(serialize($var))."'";
403 }
404
405 case 'array':
406 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
407
408 default:
409 die(var_export($var, true).' is not a valid for a database entry');
410 }
411 }
412 }
413
414 class XDBException extends PlException
415 {
416 public function __construct($query, $error)
417 {
418 if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
419 && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
420 $text = 'Erreur lors de l\'interrogation de la base de données';
421 } else {
422 $text = 'Erreur lors de l\'écriture dans la base de données';
423 }
424 parent::__construct($text, $query . "\n" . $error);
425 }
426 }
427
428 interface XDBFormat
429 {
430 public function format();
431 }
432
433 class XDBWildcard implements XDBFormat
434 {
435 private $value;
436 private $mode;
437
438 public function __construct($value, $mode)
439 {
440 $this->value = $value;
441 $this->mode = $mode;
442 }
443
444 public function format()
445 {
446 if ($this->mode == XDB::WILDCARD_EXACT) {
447 return XDB::format(' = {?}', $this->value);
448 } else {
449 $text = str_replace(array('%', '_'), array('\%', '\_'), $this->value);
450 if ($this->mode & XDB::WILDCARD_PREFIX) {
451 $text = $text . '%';
452 }
453 if ($this->mode & XDB::WILDCARD_SUFFIX) {
454 $text = '%' . $text;
455 }
456 return XDB::format(" LIKE {?}", $text);
457 }
458 }
459 }
460
461
462 class XDBResult
463 {
464 private $res;
465
466 public function __construct($query)
467 {
468 $this->res = XDB::run($query);
469 }
470
471 public function free()
472 {
473 if ($this->res) {
474 $this->res->free();
475 }
476 unset($this);
477 }
478
479 protected function fetchRow()
480 {
481 return $this->res ? $this->res->fetch_row() : null;
482 }
483
484 protected function fetchAssoc()
485 {
486 return $this->res ? $this->res->fetch_assoc() : null;
487 }
488
489 public function fetchAllRow($id = false, $keep_array = false)
490 {
491 $result = Array();
492 if (!$this->res) {
493 return $result;
494 }
495 while (($data = $this->res->fetch_row())) {
496 if ($id !== false) {
497 $key = $data[$id];
498 unset($data[$id]);
499 if (!$keep_array && count($data) == 1) {
500 reset($data);
501 $result[$key] = current($data);
502 } else {
503 $result[$key] = $data;
504 }
505 } else {
506 $result[] = $data;
507 }
508 }
509 $this->free();
510 return $result;
511 }
512
513 public function fetchAllAssoc($id = false, $keep_array = false)
514 {
515 $result = Array();
516 if (!$this->res) {
517 return $result;
518 }
519 while (($data = $this->res->fetch_assoc())) {
520 if ($id !== false) {
521 $key = $data[$id];
522 unset($data[$id]);
523 if (!$keep_array && count($data) == 1) {
524 reset($data);
525 $result[$key] = current($data);
526 } else {
527 $result[$key] = $data;
528 }
529 } else {
530 $result[] = $data;
531 }
532 }
533 $this->free();
534 return $result;
535 }
536
537 public function fetchOneAssoc()
538 {
539 $tmp = $this->fetchAssoc();
540 $this->free();
541 return $tmp;
542 }
543
544 public function fetchOneRow()
545 {
546 $tmp = $this->fetchRow();
547 $this->free();
548 return $tmp;
549 }
550
551 public function fetchOneCell()
552 {
553 $tmp = $this->fetchRow();
554 $this->free();
555 return $tmp[0];
556 }
557
558 public function fetchColumn($key = 0)
559 {
560 $res = Array();
561 if (is_numeric($key)) {
562 while($tmp = $this->fetchRow()) {
563 $res[] = $tmp[$key];
564 }
565 } else {
566 while($tmp = $this->fetchAssoc()) {
567 $res[] = $tmp[$key];
568 }
569 }
570 $this->free();
571 return $res;
572 }
573
574 public function fetchOneField()
575 {
576 return $this->res ? $this->res->fetch_field() : null;
577 }
578
579 public function fetchFields()
580 {
581 $res = array();
582 while ($res[] = $this->fetchOneField());
583 return $res;
584 }
585
586 public function numRows()
587 {
588 return $this->res ? $this->res->num_rows : 0;
589 }
590
591 public function fieldCount()
592 {
593 return $this->res ? $this->res->field_count : 0;
594 }
595 }
596
597
598 class XDBIterator extends XDBResult implements PlIterator
599 {
600 private $result;
601 private $pos;
602 private $total;
603 private $fpos;
604 private $fields;
605 private $mode = MYSQL_ASSOC;
606
607 public function __construct($query, $mode = MYSQL_ASSOC)
608 {
609 parent::__construct($query);
610 $this->pos = 0;
611 $this->total = $this->numRows();
612 $this->fpost = 0;
613 $this->fields = $this->fieldCount();
614 $this->mode = $mode;
615 }
616
617 public function next()
618 {
619 $this->pos ++;
620 if ($this->pos > $this->total) {
621 $this->free();
622 unset($this);
623 return null;
624 }
625 return $this->mode != MYSQL_ASSOC ? $this->fetchRow() : $this->fetchAssoc();
626 }
627
628 public function first()
629 {
630 return $this->pos == 1;
631 }
632
633 public function last()
634 {
635 return $this->pos == $this->total;
636 }
637
638 public function total()
639 {
640 return $this->total;
641 }
642
643 public function nextField()
644 {
645 $this->fpos++;
646 if ($this->fpos > $this->fields) {
647 return null;
648 }
649 return $this->fetchOneField();
650 }
651
652 public function firstField()
653 {
654 return $this->fpos == 1;
655 }
656
657 public function lastField()
658 {
659 return $this->fpos == $this->fields;
660 }
661
662 public function totalFields()
663 {
664 return $this->fields;
665 }
666 }
667
668 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
669 ?>