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