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