Add XDB::rawXXXX($query) that runs the given query without formatting.
[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) {
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 iterator()
198 {
199 return new XDBIterator(self::prepare(func_get_args()));
200 }
201
202 public static function rawIterator($query)
203 {
204 return new XDBIterator($query);
205 }
206
207 public static function iterRow()
208 {
209 return new XDBIterator(self::prepare(func_get_args()), MYSQL_NUM);
210 }
211
212 public static function rawIterRow($query)
213 {
214 return new XDBIterator($query, MYSQL_NUM);
215 }
216
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.
237 * This functions can take 2 optional arguments (cf XDBResult::fetchAllRow()).
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.
247 * This functions can take 2 optional arguments (cf XDBResult::fetchAllAssoc()).
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.
275 * This functions can take 1 optional arguments (cf XDBResult::fetchColumn()).
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();
282 }
283
284 public static function insertId()
285 {
286 return self::$mysqli->insert_id;
287 }
288
289 public static function errno()
290 {
291 return self::$mysqli->errno;
292 }
293
294 public static function error()
295 {
296 return self::$mysqli->error;
297 }
298
299 public static function affectedRows()
300 {
301 return self::$mysqli->affected_rows;
302 }
303
304 public static function escape($var)
305 {
306 switch (gettype($var)) {
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':
322 if ($var instanceof XDBFormat) {
323 return $var->format();
324 } else {
325 return "'".addslashes(serialize($var))."'";
326 }
327
328 case 'array':
329 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
330
331 default:
332 die(var_export($var, true).' is not a valid for a database entry');
333 }
334 }
335 }
336
337 class XDBException extends PlException
338 {
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
351 interface XDBFormat
352 {
353 public function format();
354 }
355
356 class 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
385 class XDBResult
386 {
387 private $res;
388
389 public function __construct($query)
390 {
391 $this->res = XDB::run($query);
392 }
393
394 public function free()
395 {
396 if ($this->res) {
397 $this->res->free();
398 }
399 unset($this);
400 }
401
402 protected function fetchRow()
403 {
404 return $this->res ? $this->res->fetch_row() : null;
405 }
406
407 protected function fetchAssoc()
408 {
409 return $this->res ? $this->res->fetch_assoc() : null;
410 }
411
412 public function fetchAllRow($id = false, $keep_array = false)
413 {
414 $result = Array();
415 if (!$this->res) {
416 return $result;
417 }
418 while (($data = $this->res->fetch_row())) {
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 }
432 $this->free();
433 return $result;
434 }
435
436 public function fetchAllAssoc($id = false, $keep_array = false)
437 {
438 $result = Array();
439 if (!$this->res) {
440 return $result;
441 }
442 while (($data = $this->res->fetch_assoc())) {
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 }
456 $this->free();
457 return $result;
458 }
459
460 public function fetchOneAssoc()
461 {
462 $tmp = $this->fetchAssoc();
463 $this->free();
464 return $tmp;
465 }
466
467 public function fetchOneRow()
468 {
469 $tmp = $this->fetchRow();
470 $this->free();
471 return $tmp;
472 }
473
474 public function fetchOneCell()
475 {
476 $tmp = $this->fetchRow();
477 $this->free();
478 return $tmp[0];
479 }
480
481 public function fetchColumn($key = 0)
482 {
483 $res = Array();
484 if (is_numeric($key)) {
485 while($tmp = $this->fetchRow()) {
486 $res[] = $tmp[$key];
487 }
488 } else {
489 while($tmp = $this->fetchAssoc()) {
490 $res[] = $tmp[$key];
491 }
492 }
493 $this->free();
494 return $res;
495 }
496
497 public function fetchOneField()
498 {
499 return $this->res ? $this->res->fetch_field() : null;
500 }
501
502 public function fetchFields()
503 {
504 $res = array();
505 while ($res[] = $this->fetchOneField());
506 return $res;
507 }
508
509 public function numRows()
510 {
511 return $this->res ? $this->res->num_rows : 0;
512 }
513
514 public function fieldCount()
515 {
516 return $this->res ? $this->res->field_count : 0;
517 }
518 }
519
520
521 class XDBIterator extends XDBResult implements PlIterator
522 {
523 private $result;
524 private $pos;
525 private $total;
526 private $fpos;
527 private $fields;
528 private $mode = MYSQL_ASSOC;
529
530 public function __construct($query, $mode = MYSQL_ASSOC)
531 {
532 parent::__construct($query);
533 $this->pos = 0;
534 $this->total = $this->numRows();
535 $this->fpost = 0;
536 $this->fields = $this->fieldCount();
537 $this->mode = $mode;
538 }
539
540 public function next()
541 {
542 $this->pos ++;
543 if ($this->pos > $this->total) {
544 $this->free();
545 unset($this);
546 return null;
547 }
548 return $this->mode != MYSQL_ASSOC ? $this->fetchRow() : $this->fetchAssoc();
549 }
550
551 public function first()
552 {
553 return $this->pos == 1;
554 }
555
556 public function last()
557 {
558 return $this->pos == $this->total;
559 }
560
561 public function total()
562 {
563 return $this->total;
564 }
565
566 public function nextField()
567 {
568 $this->fpos++;
569 if ($this->fpos > $this->fields) {
570 return null;
571 }
572 return $this->fetchOneField();
573 }
574
575 public function firstField()
576 {
577 return $this->fpos == 1;
578 }
579
580 public function lastField()
581 {
582 return $this->fpos == $this->fields;
583 }
584
585 public function totalFields()
586 {
587 return $this->fields;
588 }
589 }
590
591 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
592 ?>