Fix SUID.
[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
dec6c3bd
FB
246 public static function rawFetchAllRow($query, $id = false, $keep_array = false)
247 {
248 return self::rawQuery($query)->fetchAllRow($id, $keep_array);
249 }
250
e4f6c7d0 251 /** Fetch all rows returned by the given query.
cd1d4b4f 252 * This functions can take 2 optional arguments (cf XDBResult::fetchAllAssoc()).
e4f6c7d0
FB
253 * Optional arguments are given *before* the query.
254 */
255 public static function fetchAllAssoc()
256 {
257 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
258 return self::queryv($query)->fetchAllAssoc($args[0], $args[1]);
259 }
260
dec6c3bd
FB
261 public static function rawFetchAllAssoc($query, $id = false, $keep_array = false)
262 {
263 return self::rawQuery($query)->fetchAllAssoc($id, $keep_array);
264 }
265
e4f6c7d0
FB
266 public static function fetchOneCell()
267 {
268 list($args, $query) = self::findQuery(func_get_args());
269 return self::queryv($query)->fetchOneCell();
270 }
271
dec6c3bd
FB
272 public static function rawFetchOneCell($query)
273 {
274 return self::rawQuery($query)->fetchOneCell();
275 }
276
e4f6c7d0
FB
277 public static function fetchOneRow()
278 {
279 list($args, $query) = self::findQuery(func_get_args());
280 return self::queryv($query)->fetchOneRow();
281 }
282
dec6c3bd
FB
283 public static function rawFetchOneRow($query)
284 {
285 return self::rawQuery($query)->fetchOneRow();
286 }
287
e4f6c7d0
FB
288 public static function fetchOneAssoc()
289 {
290 list($args, $query) = self::findQuery(func_get_args());
291 return self::queryv($query)->fetchOneAssoc();
292 }
293
dec6c3bd
FB
294 public static function rawFetchOneAssoc($query)
295 {
296 return self::rawQuery($query)->fetchOneAssoc();
297 }
298
e4f6c7d0 299 /** Fetch a column from the result of the given query.
cd1d4b4f 300 * This functions can take 1 optional arguments (cf XDBResult::fetchColumn()).
e4f6c7d0
FB
301 * Optional arguments are given *before* the query.
302 */
303 public static function fetchColumn()
304 {
305 list($args, $query) = self::findQuery(func_get_args(), array(0));
dec6c3bd
FB
306 return self::queryv($query)->fetchColumn($args[0]);
307 }
308
309 public static function rawFetchColumn($query, $key = 0)
310 {
311 return self::rawQuery($query)->fetchColumn($key);
0337d704 312 }
13a25546 313
6995a9b9 314 public static function insertId()
13a25546 315 {
e4f6c7d0 316 return self::$mysqli->insert_id;
13a25546 317 }
318
0380bf85 319 public static function errno()
320 {
e4f6c7d0 321 return self::$mysqli->errno;
0380bf85 322 }
323
324 public static function error()
834fd0f6 325 {
e4f6c7d0 326 return self::$mysqli->error;
0380bf85 327 }
328
329 public static function affectedRows()
330 {
e4f6c7d0 331 return self::$mysqli->affected_rows;
0380bf85 332 }
333
f62bd784 334 public static function escape($var)
0337d704 335 {
336 switch (gettype($var)) {
13a25546 337 case 'boolean':
338 return $var ? 1 : 0;
339
340 case 'integer':
341 case 'double':
342 case 'float':
343 return $var;
344
345 case 'string':
346 return "'".addslashes($var)."'";
347
348 case 'NULL':
349 return 'NULL';
350
351 case 'object':
cd1d4b4f
FB
352 if ($var instanceof XDBFormat) {
353 return $var->format();
e677bc13
FB
354 } else {
355 return "'".addslashes(serialize($var))."'";
04c1b2eb 356 }
e677bc13 357
13a25546 358 case 'array':
e677bc13 359 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
13a25546 360
361 default:
362 die(var_export($var, true).' is not a valid for a database entry');
0337d704 363 }
364 }
0337d704 365}
366
cd1d4b4f 367class XDBException extends PlException
0337d704 368{
cd1d4b4f
FB
369 public function __construct($query, $error)
370 {
371 if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
372 && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
373 $text = 'Erreur lors de l\'interrogation de la base de données';
374 } else {
375 $text = 'Erreur lors de l\'écriture dans la base de données';
376 }
377 parent::__construct($text, $query . "\n" . $error);
378 }
379}
380
381interface XDBFormat
382{
383 public function format();
384}
0337d704 385
cd1d4b4f
FB
386class XDBWildcard implements XDBFormat
387{
388 private $value;
389 private $mode;
390
391 public function __construct($value, $mode)
392 {
393 $this->value = $value;
394 $this->mode = $mode;
395 }
396
397 public function format()
398 {
399 if ($this->mode == XDB::WILDCARD_EXACT) {
400 return XDB::format(' = {?}', $this->value);
401 } else {
402 $text = str_replace(array('%', '_'), array('\%', '\_'), $this->value);
403 if ($this->mode & XDB::WILDCARD_PREFIX) {
404 $text = $text . '%';
405 }
406 if ($this->mode & XDB::WILDCARD_SUFFIX) {
407 $text = '%' . $text;
408 }
409 return XDB::format(" LIKE {?}", $text);
410 }
411 }
412}
413
414
415class XDBResult
416{
417 private $res;
0337d704 418
0381e170 419 public function __construct($query)
0337d704 420 {
cd1d4b4f 421 $this->res = XDB::run($query);
0337d704 422 }
423
0381e170 424 public function free()
0337d704 425 {
cd1d4b4f
FB
426 if ($this->res) {
427 $this->res->free();
0381e170 428 }
0337d704 429 unset($this);
430 }
431
cd1d4b4f 432 protected function fetchRow()
0337d704 433 {
cd1d4b4f 434 return $this->res ? $this->res->fetch_row() : null;
0337d704 435 }
436
cd1d4b4f 437 protected function fetchAssoc()
0337d704 438 {
cd1d4b4f 439 return $this->res ? $this->res->fetch_assoc() : null;
0337d704 440 }
441
e4f6c7d0 442 public function fetchAllRow($id = false, $keep_array = false)
0337d704 443 {
444 $result = Array();
cd1d4b4f 445 if (!$this->res) {
0381e170 446 return $result;
447 }
cd1d4b4f 448 while (($data = $this->res->fetch_row())) {
e4f6c7d0
FB
449 if ($id !== false) {
450 $key = $data[$id];
451 unset($data[$id]);
452 if (!$keep_array && count($data) == 1) {
453 reset($data);
454 $result[$key] = current($data);
455 } else {
456 $result[$key] = $data;
457 }
458 } else {
459 $result[] = $data;
460 }
461 }
0337d704 462 $this->free();
463 return $result;
464 }
465
e4f6c7d0 466 public function fetchAllAssoc($id = false, $keep_array = false)
0337d704 467 {
468 $result = Array();
cd1d4b4f 469 if (!$this->res) {
0381e170 470 return $result;
471 }
cd1d4b4f 472 while (($data = $this->res->fetch_assoc())) {
e4f6c7d0
FB
473 if ($id !== false) {
474 $key = $data[$id];
475 unset($data[$id]);
476 if (!$keep_array && count($data) == 1) {
477 reset($data);
478 $result[$key] = current($data);
479 } else {
480 $result[$key] = $data;
481 }
482 } else {
483 $result[] = $data;
484 }
485 }
0337d704 486 $this->free();
487 return $result;
488 }
489
0381e170 490 public function fetchOneAssoc()
0337d704 491 {
cd1d4b4f 492 $tmp = $this->fetchAssoc();
0337d704 493 $this->free();
494 return $tmp;
495 }
496
0381e170 497 public function fetchOneRow()
0337d704 498 {
cd1d4b4f 499 $tmp = $this->fetchRow();
0337d704 500 $this->free();
501 return $tmp;
502 }
503
0381e170 504 public function fetchOneCell()
0337d704 505 {
cd1d4b4f 506 $tmp = $this->fetchRow();
0337d704 507 $this->free();
508 return $tmp[0];
509 }
510
0381e170 511 public function fetchColumn($key = 0)
0337d704 512 {
513 $res = Array();
514 if (is_numeric($key)) {
cd1d4b4f 515 while($tmp = $this->fetchRow()) {
0337d704 516 $res[] = $tmp[$key];
517 }
518 } else {
cd1d4b4f 519 while($tmp = $this->fetchAssoc()) {
0337d704 520 $res[] = $tmp[$key];
521 }
522 }
523 $this->free();
524 return $res;
525 }
526
0381e170 527 public function fetchOneField()
0380bf85 528 {
cd1d4b4f 529 return $this->res ? $this->res->fetch_field() : null;
0380bf85 530 }
531
0381e170 532 public function fetchFields()
0380bf85 533 {
534 $res = array();
535 while ($res[] = $this->fetchOneField());
536 return $res;
537 }
538
0381e170 539 public function numRows()
0337d704 540 {
cd1d4b4f 541 return $this->res ? $this->res->num_rows : 0;
0337d704 542 }
0380bf85 543
0381e170 544 public function fieldCount()
0380bf85 545 {
cd1d4b4f 546 return $this->res ? $this->res->field_count : 0;
0380bf85 547 }
0337d704 548}
549
2b1ee50b 550
cd1d4b4f 551class XDBIterator extends XDBResult implements PlIterator
0337d704 552{
cd1d4b4f
FB
553 private $result;
554 private $pos;
555 private $total;
556 private $fpos;
557 private $fields;
558 private $mode = MYSQL_ASSOC;
0337d704 559
0381e170 560 public function __construct($query, $mode = MYSQL_ASSOC)
0337d704 561 {
0381e170 562 parent::__construct($query);
cd1d4b4f
FB
563 $this->pos = 0;
564 $this->total = $this->numRows();
565 $this->fpost = 0;
566 $this->fields = $this->fieldCount();
567 $this->mode = $mode;
0337d704 568 }
569
0381e170 570 public function next()
0337d704 571 {
cd1d4b4f
FB
572 $this->pos ++;
573 if ($this->pos > $this->total) {
0381e170 574 $this->free();
0337d704 575 unset($this);
576 return null;
577 }
cd1d4b4f 578 return $this->mode != MYSQL_ASSOC ? $this->fetchRow() : $this->fetchAssoc();
0337d704 579 }
580
0381e170 581 public function first()
0337d704 582 {
cd1d4b4f 583 return $this->pos == 1;
0337d704 584 }
585
0381e170 586 public function last()
0337d704 587 {
cd1d4b4f 588 return $this->pos == $this->total;
0337d704 589 }
590
0381e170 591 public function total()
0337d704 592 {
cd1d4b4f 593 return $this->total;
0337d704 594 }
0380bf85 595
0381e170 596 public function nextField()
0380bf85 597 {
cd1d4b4f
FB
598 $this->fpos++;
599 if ($this->fpos > $this->fields) {
0380bf85 600 return null;
601 }
0381e170 602 return $this->fetchOneField();
0380bf85 603 }
604
0381e170 605 public function firstField()
0380bf85 606 {
cd1d4b4f 607 return $this->fpos == 1;
0380bf85 608 }
609
0381e170 610 public function lastField()
0380bf85 611 {
cd1d4b4f 612 return $this->fpos == $this->fields;
0380bf85 613 }
614
0381e170 615 public function totalFields()
0380bf85 616 {
cd1d4b4f 617 return $this->fields;
0380bf85 618 }
0337d704 619}
620
a7de4ef7 621// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 622?>