Add XDB::rawXXXX($query) that runs the given query without formatting.
[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
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
6995a9b9 197 public static function iterator()
0337d704 198 {
cd1d4b4f 199 return new XDBIterator(self::prepare(func_get_args()));
0337d704 200 }
13a25546 201
4c455d70
FB
202 public static function rawIterator($query)
203 {
204 return new XDBIterator($query);
205 }
206
6995a9b9 207 public static function iterRow()
0337d704 208 {
cd1d4b4f 209 return new XDBIterator(self::prepare(func_get_args()), MYSQL_NUM);
e4f6c7d0
FB
210 }
211
4c455d70
FB
212 public static function rawIterRow($query)
213 {
214 return new XDBIterator($query, MYSQL_NUM);
215 }
216
e4f6c7d0
FB
217 private static function findQuery($params, $default = array())
218 {
219 for ($i = 0 ; $i < count($default) ; ++$i) {
220 $is_query = false;
221 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
222 if (stripos($params[0], $kwd) !== false) {
223 $is_query = true;
224 break;
225 }
226 }
227 if ($is_query) {
228 break;
229 } else {
230 $default[$i] = array_shift($params);
231 }
232 }
233 return array($default, $params);
234 }
235
236 /** Fetch all rows returned by the given query.
cd1d4b4f 237 * This functions can take 2 optional arguments (cf XDBResult::fetchAllRow()).
e4f6c7d0
FB
238 * Optional arguments are given *before* the query.
239 */
240 public static function fetchAllRow()
241 {
242 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
243 return self::queryv($query)->fetchAllRow($args[0], $args[1]);
244 }
245
246 /** Fetch all rows returned by the given query.
cd1d4b4f 247 * This functions can take 2 optional arguments (cf XDBResult::fetchAllAssoc()).
e4f6c7d0
FB
248 * Optional arguments are given *before* the query.
249 */
250 public static function fetchAllAssoc()
251 {
252 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
253 return self::queryv($query)->fetchAllAssoc($args[0], $args[1]);
254 }
255
256 public static function fetchOneCell()
257 {
258 list($args, $query) = self::findQuery(func_get_args());
259 return self::queryv($query)->fetchOneCell();
260 }
261
262 public static function fetchOneRow()
263 {
264 list($args, $query) = self::findQuery(func_get_args());
265 return self::queryv($query)->fetchOneRow();
266 }
267
268 public static function fetchOneAssoc()
269 {
270 list($args, $query) = self::findQuery(func_get_args());
271 return self::queryv($query)->fetchOneAssoc();
272 }
273
274 /** Fetch a column from the result of the given query.
cd1d4b4f 275 * This functions can take 1 optional arguments (cf XDBResult::fetchColumn()).
e4f6c7d0
FB
276 * Optional arguments are given *before* the query.
277 */
278 public static function fetchColumn()
279 {
280 list($args, $query) = self::findQuery(func_get_args(), array(0));
281 return self::queryv($query)->fetchColumn();
0337d704 282 }
13a25546 283
6995a9b9 284 public static function insertId()
13a25546 285 {
e4f6c7d0 286 return self::$mysqli->insert_id;
13a25546 287 }
288
0380bf85 289 public static function errno()
290 {
e4f6c7d0 291 return self::$mysqli->errno;
0380bf85 292 }
293
294 public static function error()
834fd0f6 295 {
e4f6c7d0 296 return self::$mysqli->error;
0380bf85 297 }
298
299 public static function affectedRows()
300 {
e4f6c7d0 301 return self::$mysqli->affected_rows;
0380bf85 302 }
303
f62bd784 304 public static function escape($var)
0337d704 305 {
306 switch (gettype($var)) {
13a25546 307 case 'boolean':
308 return $var ? 1 : 0;
309
310 case 'integer':
311 case 'double':
312 case 'float':
313 return $var;
314
315 case 'string':
316 return "'".addslashes($var)."'";
317
318 case 'NULL':
319 return 'NULL';
320
321 case 'object':
cd1d4b4f
FB
322 if ($var instanceof XDBFormat) {
323 return $var->format();
e677bc13
FB
324 } else {
325 return "'".addslashes(serialize($var))."'";
04c1b2eb 326 }
e677bc13 327
13a25546 328 case 'array':
e677bc13 329 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
13a25546 330
331 default:
332 die(var_export($var, true).' is not a valid for a database entry');
0337d704 333 }
334 }
0337d704 335}
336
cd1d4b4f 337class XDBException extends PlException
0337d704 338{
cd1d4b4f
FB
339 public function __construct($query, $error)
340 {
341 if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
342 && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
343 $text = 'Erreur lors de l\'interrogation de la base de données';
344 } else {
345 $text = 'Erreur lors de l\'écriture dans la base de données';
346 }
347 parent::__construct($text, $query . "\n" . $error);
348 }
349}
350
351interface XDBFormat
352{
353 public function format();
354}
0337d704 355
cd1d4b4f
FB
356class XDBWildcard implements XDBFormat
357{
358 private $value;
359 private $mode;
360
361 public function __construct($value, $mode)
362 {
363 $this->value = $value;
364 $this->mode = $mode;
365 }
366
367 public function format()
368 {
369 if ($this->mode == XDB::WILDCARD_EXACT) {
370 return XDB::format(' = {?}', $this->value);
371 } else {
372 $text = str_replace(array('%', '_'), array('\%', '\_'), $this->value);
373 if ($this->mode & XDB::WILDCARD_PREFIX) {
374 $text = $text . '%';
375 }
376 if ($this->mode & XDB::WILDCARD_SUFFIX) {
377 $text = '%' . $text;
378 }
379 return XDB::format(" LIKE {?}", $text);
380 }
381 }
382}
383
384
385class XDBResult
386{
387 private $res;
0337d704 388
0381e170 389 public function __construct($query)
0337d704 390 {
cd1d4b4f 391 $this->res = XDB::run($query);
0337d704 392 }
393
0381e170 394 public function free()
0337d704 395 {
cd1d4b4f
FB
396 if ($this->res) {
397 $this->res->free();
0381e170 398 }
0337d704 399 unset($this);
400 }
401
cd1d4b4f 402 protected function fetchRow()
0337d704 403 {
cd1d4b4f 404 return $this->res ? $this->res->fetch_row() : null;
0337d704 405 }
406
cd1d4b4f 407 protected function fetchAssoc()
0337d704 408 {
cd1d4b4f 409 return $this->res ? $this->res->fetch_assoc() : null;
0337d704 410 }
411
e4f6c7d0 412 public function fetchAllRow($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_row())) {
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
e4f6c7d0 436 public function fetchAllAssoc($id = false, $keep_array = false)
0337d704 437 {
438 $result = Array();
cd1d4b4f 439 if (!$this->res) {
0381e170 440 return $result;
441 }
cd1d4b4f 442 while (($data = $this->res->fetch_assoc())) {
e4f6c7d0
FB
443 if ($id !== false) {
444 $key = $data[$id];
445 unset($data[$id]);
446 if (!$keep_array && count($data) == 1) {
447 reset($data);
448 $result[$key] = current($data);
449 } else {
450 $result[$key] = $data;
451 }
452 } else {
453 $result[] = $data;
454 }
455 }
0337d704 456 $this->free();
457 return $result;
458 }
459
0381e170 460 public function fetchOneAssoc()
0337d704 461 {
cd1d4b4f 462 $tmp = $this->fetchAssoc();
0337d704 463 $this->free();
464 return $tmp;
465 }
466
0381e170 467 public function fetchOneRow()
0337d704 468 {
cd1d4b4f 469 $tmp = $this->fetchRow();
0337d704 470 $this->free();
471 return $tmp;
472 }
473
0381e170 474 public function fetchOneCell()
0337d704 475 {
cd1d4b4f 476 $tmp = $this->fetchRow();
0337d704 477 $this->free();
478 return $tmp[0];
479 }
480
0381e170 481 public function fetchColumn($key = 0)
0337d704 482 {
483 $res = Array();
484 if (is_numeric($key)) {
cd1d4b4f 485 while($tmp = $this->fetchRow()) {
0337d704 486 $res[] = $tmp[$key];
487 }
488 } else {
cd1d4b4f 489 while($tmp = $this->fetchAssoc()) {
0337d704 490 $res[] = $tmp[$key];
491 }
492 }
493 $this->free();
494 return $res;
495 }
496
0381e170 497 public function fetchOneField()
0380bf85 498 {
cd1d4b4f 499 return $this->res ? $this->res->fetch_field() : null;
0380bf85 500 }
501
0381e170 502 public function fetchFields()
0380bf85 503 {
504 $res = array();
505 while ($res[] = $this->fetchOneField());
506 return $res;
507 }
508
0381e170 509 public function numRows()
0337d704 510 {
cd1d4b4f 511 return $this->res ? $this->res->num_rows : 0;
0337d704 512 }
0380bf85 513
0381e170 514 public function fieldCount()
0380bf85 515 {
cd1d4b4f 516 return $this->res ? $this->res->field_count : 0;
0380bf85 517 }
0337d704 518}
519
2b1ee50b 520
cd1d4b4f 521class XDBIterator extends XDBResult implements PlIterator
0337d704 522{
cd1d4b4f
FB
523 private $result;
524 private $pos;
525 private $total;
526 private $fpos;
527 private $fields;
528 private $mode = MYSQL_ASSOC;
0337d704 529
0381e170 530 public function __construct($query, $mode = MYSQL_ASSOC)
0337d704 531 {
0381e170 532 parent::__construct($query);
cd1d4b4f
FB
533 $this->pos = 0;
534 $this->total = $this->numRows();
535 $this->fpost = 0;
536 $this->fields = $this->fieldCount();
537 $this->mode = $mode;
0337d704 538 }
539
0381e170 540 public function next()
0337d704 541 {
cd1d4b4f
FB
542 $this->pos ++;
543 if ($this->pos > $this->total) {
0381e170 544 $this->free();
0337d704 545 unset($this);
546 return null;
547 }
cd1d4b4f 548 return $this->mode != MYSQL_ASSOC ? $this->fetchRow() : $this->fetchAssoc();
0337d704 549 }
550
0381e170 551 public function first()
0337d704 552 {
cd1d4b4f 553 return $this->pos == 1;
0337d704 554 }
555
0381e170 556 public function last()
0337d704 557 {
cd1d4b4f 558 return $this->pos == $this->total;
0337d704 559 }
560
0381e170 561 public function total()
0337d704 562 {
cd1d4b4f 563 return $this->total;
0337d704 564 }
0380bf85 565
0381e170 566 public function nextField()
0380bf85 567 {
cd1d4b4f
FB
568 $this->fpos++;
569 if ($this->fpos > $this->fields) {
0380bf85 570 return null;
571 }
0381e170 572 return $this->fetchOneField();
0380bf85 573 }
574
0381e170 575 public function firstField()
0380bf85 576 {
cd1d4b4f 577 return $this->fpos == 1;
0380bf85 578 }
579
0381e170 580 public function lastField()
0380bf85 581 {
cd1d4b4f 582 return $this->fpos == $this->fields;
0380bf85 583 }
584
0381e170 585 public function totalFields()
0380bf85 586 {
cd1d4b4f 587 return $this->fields;
0380bf85 588 }
0337d704 589}
590
a7de4ef7 591// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 592?>