Prevents notice in skin templates.
[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
7f6d1063
FB
22class XDBException extends PlException {
23 public function __construct($query, $error) {
24 if (strpos($query, 'INSERT') === false && strpos($query, 'UPDATE') === false
25 && strpos($query, 'REPLACE') === false && strpos($query, 'DELETE') === false) {
26 $text = 'Erreur lors de l\'interrogation de la base de données';
27 } else {
28 $text = 'Erreur lors de l\'écriture dans la base de données';
29 }
30 parent::__construct($text, $query . "\n" . $error);
31 }
32}
33
08cce2ff 34class XDB
0337d704 35{
32d9ae72 36 private static $mysqli = null;
37
821744e0 38 public static function connect()
32d9ae72 39 {
821744e0 40 global $globals;
e4f6c7d0 41 self::$mysqli = new mysqli($globals->dbhost, $globals->dbuser, $globals->dbpwd, $globals->dbdb);
81e9c63f 42 if ($globals->debug & DEBUG_BT) {
d3f26be9 43 $bt = new PlBacktrace('MySQL');
44 if (mysqli_connect_errno()) {
45 $bt->newEvent("MySQLI connection", 0, mysqli_connect_error());
46 return false;
47 }
32d9ae72 48 }
e4f6c7d0
FB
49 self::$mysqli->autocommit(true);
50 self::$mysqli->set_charset($globals->dbcharset);
32d9ae72 51 return true;
52 }
f1ca33de 53
ed3f4d3e 54 public static function _prepare($args)
55 {
4d6eeacc 56 global $globals;
f62bd784 57 $query = array_map(Array('XDB', 'escape'), $args);
f3e3cab8 58 $query[0] = preg_replace('/#([a-z0-9]+)#/', $globals->dbprefix . '$1', $args[0]);
4d6eeacc
VZ
59 $query[0] = str_replace('%', '%%', $query[0]);
60 $query[0] = str_replace('{?}', '%s', $query[0]);
0337d704 61 return call_user_func_array('sprintf', $query);
62 }
13a25546 63
6995a9b9 64 public static function _reformatQuery($query)
7c571120 65 {
a4f89886 66 $query = preg_split("/\n\\s*/", trim($query));
7c571120 67 $length = 0;
d3c52d30 68 foreach ($query as $key=>$line) {
69 $local = -2;
a14159bf 70 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
85d3b330 71 && $matches[1] != 'AND' && $matches[1] != 'OR')
72 {
d3c52d30 73 $local = strlen($matches[1]);
74 $line = $matches[1] . ' ' . $matches[2];
75 $length = max($length, $local);
7c571120 76 }
d3c52d30 77 $query[$key] = array($line, $local);
7c571120 78 }
79 $res = '';
d3c52d30 80 foreach ($query as $array) {
81 list($line, $local) = $array;
9630c649 82 $local = max(0, $length - $local);
7c571120 83 $res .= str_repeat(' ', $local) . $line . "\n";
84 $length += 2 * (substr_count($line, '(') - substr_count($line, ')'));
85 }
86 return $res;
87 }
88
ed3f4d3e 89 public static function _query($query)
90 {
f1ca33de 91 global $globals;
92
e4f6c7d0 93 if (!self::$mysqli && !self::connect()) {
12ccfec7 94 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
084a60da
FB
95 Platal::page()->kill('Impossible de se connecter à la base de données.');
96 exit;
821744e0 97 }
98
81e9c63f 99 if ($globals->debug & DEBUG_BT) {
f1ca33de 100 $explain = array();
5fb22b39 101 if (strpos($query, 'FOUND_ROWS()') === false) {
e4f6c7d0 102 $res = self::$mysqli->query("EXPLAIN $query");
32d9ae72 103 if ($res) {
104 while ($row = $res->fetch_assoc()) {
5fb22b39 105 $explain[] = $row;
106 }
32d9ae72 107 $res->free();
5fb22b39 108 }
f1ca33de 109 }
d3f26be9 110 PlBacktrace::$bt['MySQL']->start(XDB::_reformatQuery($query));
f1ca33de 111 }
112
32d9ae72 113 $res = XDB::$mysqli->query($query);
0381e170 114
81e9c63f 115 if ($globals->debug & DEBUG_BT) {
e4f6c7d0
FB
116 PlBacktrace::$bt['MySQL']->stop(@$res->num_rows ? $res->num_rows : self::$mysqli->affected_rows,
117 self::$mysqli->error,
d3f26be9 118 $explain);
f1ca33de 119 }
084a60da
FB
120
121 if ($res === false) {
7f6d1063 122 throw new XDBException(XDB::_reformatQuery($query), XDB::$mysqli->error);
084a60da 123 }
f1ca33de 124 return $res;
125 }
126
e4f6c7d0
FB
127 private static function queryv($query)
128 {
129 return new XOrgDBResult(self::_prepare($query));
130 }
131
6995a9b9 132 public static function query()
0337d704 133 {
e4f6c7d0 134 return self::queryv(func_get_args());
0337d704 135 }
136
20973bf8
FB
137 public static function format()
138 {
e4f6c7d0 139 return self::_prepare(func_get_args());
20973bf8
FB
140 }
141
0ef5bd4b
FB
142 // Produce the SQL statement for setting/unsetting a flag
143 public static function changeFlag($fieldname, $flagname, $state)
144 {
145 if ($state) {
146 return XDB::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
147 } else {
148 return XDB::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
149 }
150 }
151
152 // Produce the SQL statement representing an array
153 public static function formatArray(array $array)
154 {
e677bc13 155 return self::escape($array);
0ef5bd4b
FB
156 }
157
adf947ff
RB
158 const WILDCARD_EXACT = 0x00;
159 const WILDCARD_PREFIX = 0x01;
160 const WILDCARD_SUFFIX = 0x02;
161 const WILDCARD_CONTAINS = 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
162
163 // Returns the SQL statement for a wildcard search.
164 public static function formatWildcards($mode, $text)
165 {
166 if ($mode == self::WILDCARD_EXACT) {
167 return XDB::format(' = {?}', $text);
168 } else {
169 $text = str_replace(array('%', '_'), array('\%', '\_'), $text);
170 if ($mode & self::WILDCARD_PREFIX) {
171 $text = $text . '%';
172 }
173 if ($mode & self::WILDCARD_SUFFIX) {
174 $text = '%' . $text;
175 }
176 return XDB::format(" LIKE {?}", $text);
177 }
178 }
179
47595f9a
RB
180 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
181 public static function formatCustomOrder($field, $values)
182 {
29bd16df 183 return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')';
47595f9a
RB
184 }
185
6995a9b9 186 public static function execute()
f1ca33de 187 {
fe556813
FB
188 global $globals;
189 $args = func_get_args();
190 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
191 return;
192 }
e4f6c7d0 193 return self::_query(XDB::_prepare($args));
0337d704 194 }
13a25546 195
6995a9b9 196 public static function iterator()
0337d704 197 {
e4f6c7d0 198 return new XOrgDBIterator(self::_prepare(func_get_args()));
0337d704 199 }
13a25546 200
6995a9b9 201 public static function iterRow()
0337d704 202 {
e4f6c7d0
FB
203 return new XOrgDBIterator(self::_prepare(func_get_args()), MYSQL_NUM);
204 }
205
206 private static function findQuery($params, $default = array())
207 {
208 for ($i = 0 ; $i < count($default) ; ++$i) {
209 $is_query = false;
210 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
211 if (stripos($params[0], $kwd) !== false) {
212 $is_query = true;
213 break;
214 }
215 }
216 if ($is_query) {
217 break;
218 } else {
219 $default[$i] = array_shift($params);
220 }
221 }
222 return array($default, $params);
223 }
224
225 /** Fetch all rows returned by the given query.
226 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllRow()).
227 * Optional arguments are given *before* the query.
228 */
229 public static function fetchAllRow()
230 {
231 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
232 return self::queryv($query)->fetchAllRow($args[0], $args[1]);
233 }
234
235 /** Fetch all rows returned by the given query.
236 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllAssoc()).
237 * Optional arguments are given *before* the query.
238 */
239 public static function fetchAllAssoc()
240 {
241 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
242 return self::queryv($query)->fetchAllAssoc($args[0], $args[1]);
243 }
244
245 public static function fetchOneCell()
246 {
247 list($args, $query) = self::findQuery(func_get_args());
248 return self::queryv($query)->fetchOneCell();
249 }
250
251 public static function fetchOneRow()
252 {
253 list($args, $query) = self::findQuery(func_get_args());
254 return self::queryv($query)->fetchOneRow();
255 }
256
257 public static function fetchOneAssoc()
258 {
259 list($args, $query) = self::findQuery(func_get_args());
260 return self::queryv($query)->fetchOneAssoc();
261 }
262
263 /** Fetch a column from the result of the given query.
264 * This functions can take 1 optional arguments (cf XOrgDBResult::fetchColumn()).
265 * Optional arguments are given *before* the query.
266 */
267 public static function fetchColumn()
268 {
269 list($args, $query) = self::findQuery(func_get_args(), array(0));
270 return self::queryv($query)->fetchColumn();
0337d704 271 }
13a25546 272
6995a9b9 273 public static function insertId()
13a25546 274 {
e4f6c7d0 275 return self::$mysqli->insert_id;
13a25546 276 }
277
0380bf85 278 public static function errno()
279 {
e4f6c7d0 280 return self::$mysqli->errno;
0380bf85 281 }
282
283 public static function error()
834fd0f6 284 {
e4f6c7d0 285 return self::$mysqli->error;
0380bf85 286 }
287
288 public static function affectedRows()
289 {
e4f6c7d0 290 return self::$mysqli->affected_rows;
0380bf85 291 }
292
f62bd784 293 public static function escape($var)
0337d704 294 {
295 switch (gettype($var)) {
13a25546 296 case 'boolean':
297 return $var ? 1 : 0;
298
299 case 'integer':
300 case 'double':
301 case 'float':
302 return $var;
303
304 case 'string':
305 return "'".addslashes($var)."'";
306
307 case 'NULL':
308 return 'NULL';
309
310 case 'object':
113f6de8 311 if ($var instanceof PlFlagSet) {
04c1b2eb 312 return "'" . addslashes($var->flags()) . "'";
e677bc13
FB
313 } else {
314 return "'".addslashes(serialize($var))."'";
04c1b2eb 315 }
e677bc13 316
13a25546 317 case 'array':
e677bc13 318 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
13a25546 319
320 default:
321 die(var_export($var, true).' is not a valid for a database entry');
0337d704 322 }
323 }
0337d704 324}
325
0337d704 326class XOrgDBResult
327{
0337d704 328
32d9ae72 329 private $_res;
0337d704 330
0381e170 331 public function __construct($query)
0337d704 332 {
755abda6 333 $this->_res = XDB::_query($query);
0337d704 334 }
335
0381e170 336 public function free()
0337d704 337 {
0381e170 338 if ($this->_res) {
339 $this->_res->free();
340 }
0337d704 341 unset($this);
342 }
343
0381e170 344 protected function _fetchRow()
0337d704 345 {
0381e170 346 return $this->_res ? $this->_res->fetch_row() : null;
0337d704 347 }
348
0381e170 349 protected function _fetchAssoc()
0337d704 350 {
0381e170 351 return $this->_res ? $this->_res->fetch_assoc() : null;
0337d704 352 }
353
e4f6c7d0 354 public function fetchAllRow($id = false, $keep_array = false)
0337d704 355 {
356 $result = Array();
0381e170 357 if (!$this->_res) {
358 return $result;
359 }
e4f6c7d0
FB
360 while (($data = $this->_res->fetch_row())) {
361 if ($id !== false) {
362 $key = $data[$id];
363 unset($data[$id]);
364 if (!$keep_array && count($data) == 1) {
365 reset($data);
366 $result[$key] = current($data);
367 } else {
368 $result[$key] = $data;
369 }
370 } else {
371 $result[] = $data;
372 }
373 }
0337d704 374 $this->free();
375 return $result;
376 }
377
e4f6c7d0 378 public function fetchAllAssoc($id = false, $keep_array = false)
0337d704 379 {
380 $result = Array();
0381e170 381 if (!$this->_res) {
382 return $result;
383 }
e4f6c7d0
FB
384 while (($data = $this->_res->fetch_assoc())) {
385 if ($id !== false) {
386 $key = $data[$id];
387 unset($data[$id]);
388 if (!$keep_array && count($data) == 1) {
389 reset($data);
390 $result[$key] = current($data);
391 } else {
392 $result[$key] = $data;
393 }
394 } else {
395 $result[] = $data;
396 }
397 }
0337d704 398 $this->free();
399 return $result;
400 }
401
0381e170 402 public function fetchOneAssoc()
0337d704 403 {
404 $tmp = $this->_fetchAssoc();
405 $this->free();
406 return $tmp;
407 }
408
0381e170 409 public function fetchOneRow()
0337d704 410 {
411 $tmp = $this->_fetchRow();
412 $this->free();
413 return $tmp;
414 }
415
0381e170 416 public function fetchOneCell()
0337d704 417 {
418 $tmp = $this->_fetchRow();
419 $this->free();
420 return $tmp[0];
421 }
422
0381e170 423 public function fetchColumn($key = 0)
0337d704 424 {
425 $res = Array();
426 if (is_numeric($key)) {
427 while($tmp = $this->_fetchRow()) {
428 $res[] = $tmp[$key];
429 }
430 } else {
431 while($tmp = $this->_fetchAssoc()) {
432 $res[] = $tmp[$key];
433 }
434 }
435 $this->free();
436 return $res;
437 }
438
0381e170 439 public function fetchOneField()
0380bf85 440 {
0381e170 441 return $this->_res ? $this->_res->fetch_field() : null;
0380bf85 442 }
443
0381e170 444 public function fetchFields()
0380bf85 445 {
446 $res = array();
447 while ($res[] = $this->fetchOneField());
448 return $res;
449 }
450
0381e170 451 public function numRows()
0337d704 452 {
0381e170 453 return $this->_res ? $this->_res->num_rows : 0;
0337d704 454 }
0380bf85 455
0381e170 456 public function fieldCount()
0380bf85 457 {
0381e170 458 return $this->_res ? $this->_res->field_count : 0;
0380bf85 459 }
0337d704 460}
461
2b1ee50b 462require_once dirname(__FILE__) . '/pliterator.php';
463
0381e170 464class XOrgDBIterator extends XOrgDBResult implements PlIterator
0337d704 465{
85d3b330 466 private $_result;
467 private $_pos;
468 private $_total;
0380bf85 469 private $_fpos;
470 private $_fields;
85d3b330 471 private $_mode = MYSQL_ASSOC;
0337d704 472
0381e170 473 public function __construct($query, $mode = MYSQL_ASSOC)
0337d704 474 {
0381e170 475 parent::__construct($query);
0337d704 476 $this->_pos = 0;
0381e170 477 $this->_total = $this->numRows();
0380bf85 478 $this->_fpost = 0;
0381e170 479 $this->_fields = $this->fieldCount();
0337d704 480 $this->_mode = $mode;
481 }
482
0381e170 483 public function next()
0337d704 484 {
485 $this->_pos ++;
486 if ($this->_pos > $this->_total) {
0381e170 487 $this->free();
0337d704 488 unset($this);
489 return null;
490 }
0381e170 491 return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc();
0337d704 492 }
493
0381e170 494 public function first()
0337d704 495 {
496 return $this->_pos == 1;
497 }
498
0381e170 499 public function last()
0337d704 500 {
0380bf85 501 return $this->_pos == $this->_total;
0337d704 502 }
503
0381e170 504 public function total()
0337d704 505 {
506 return $this->_total;
507 }
0380bf85 508
0381e170 509 public function nextField()
0380bf85 510 {
511 $this->_fpos++;
512 if ($this->_fpos > $this->_fields) {
513 return null;
514 }
0381e170 515 return $this->fetchOneField();
0380bf85 516 }
517
0381e170 518 public function firstField()
0380bf85 519 {
520 return $this->_fpos == 1;
521 }
522
0381e170 523 public function lastField()
0380bf85 524 {
525 return $this->_fpos == $this->_fields;
526 }
527
0381e170 528 public function totalFields()
0380bf85 529 {
530 return $this->_fields;
531 }
0337d704 532}
533
a7de4ef7 534// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
0337d704 535?>