Add XDB::formatCustomOrder (to create a custom order in an SQL query)
[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 _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 const WILDCARD_EXACT = 0x00;
163 const WILDCARD_PREFIX = 0x01;
164 const WILDCARD_SUFFIX = 0x02;
165 const WILDCARD_CONTAINS = 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
166
167 // Returns the SQL statement for a wildcard search.
168 public static function formatWildcards($mode, $text)
169 {
170 if ($mode == self::WILDCARD_EXACT) {
171 return XDB::format(' = {?}', $text);
172 } else {
173 $text = str_replace(array('%', '_'), array('\%', '\_'), $text);
174 if ($mode & self::WILDCARD_PREFIX) {
175 $text = $text . '%';
176 }
177 if ($mode & self::WILDCARD_SUFFIX) {
178 $text = '%' . $text;
179 }
180 return XDB::format(" LIKE {?}", $text);
181 }
182 }
183
184 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
185 public static function formatCustomOrder($field, $values)
186 {
187 return 'FIELD( ' . $field . ', ' . XDB::formatArray($values) . ')';
188 }
189
190 public static function execute()
191 {
192 global $globals;
193 $args = func_get_args();
194 if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) {
195 return;
196 }
197 return self::_query(XDB::_prepare($args));
198 }
199
200 public static function iterator()
201 {
202 return new XOrgDBIterator(self::_prepare(func_get_args()));
203 }
204
205 public static function iterRow()
206 {
207 return new XOrgDBIterator(self::_prepare(func_get_args()), MYSQL_NUM);
208 }
209
210 private static function findQuery($params, $default = array())
211 {
212 for ($i = 0 ; $i < count($default) ; ++$i) {
213 $is_query = false;
214 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
215 if (stripos($params[0], $kwd) !== false) {
216 $is_query = true;
217 break;
218 }
219 }
220 if ($is_query) {
221 break;
222 } else {
223 $default[$i] = array_shift($params);
224 }
225 }
226 return array($default, $params);
227 }
228
229 /** Fetch all rows returned by the given query.
230 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllRow()).
231 * Optional arguments are given *before* the query.
232 */
233 public static function fetchAllRow()
234 {
235 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
236 return self::queryv($query)->fetchAllRow($args[0], $args[1]);
237 }
238
239 /** Fetch all rows returned by the given query.
240 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllAssoc()).
241 * Optional arguments are given *before* the query.
242 */
243 public static function fetchAllAssoc()
244 {
245 list($args, $query) = self::findQuery(func_get_args(), array(false, false));
246 return self::queryv($query)->fetchAllAssoc($args[0], $args[1]);
247 }
248
249 public static function fetchOneCell()
250 {
251 list($args, $query) = self::findQuery(func_get_args());
252 return self::queryv($query)->fetchOneCell();
253 }
254
255 public static function fetchOneRow()
256 {
257 list($args, $query) = self::findQuery(func_get_args());
258 return self::queryv($query)->fetchOneRow();
259 }
260
261 public static function fetchOneAssoc()
262 {
263 list($args, $query) = self::findQuery(func_get_args());
264 return self::queryv($query)->fetchOneAssoc();
265 }
266
267 /** Fetch a column from the result of the given query.
268 * This functions can take 1 optional arguments (cf XOrgDBResult::fetchColumn()).
269 * Optional arguments are given *before* the query.
270 */
271 public static function fetchColumn()
272 {
273 list($args, $query) = self::findQuery(func_get_args(), array(0));
274 return self::queryv($query)->fetchColumn();
275 }
276
277 public static function insertId()
278 {
279 return self::$mysqli->insert_id;
280 }
281
282 public static function errno()
283 {
284 return self::$mysqli->errno;
285 }
286
287 public static function error()
288 {
289 return self::$mysqli->error;
290 }
291
292 public static function affectedRows()
293 {
294 return self::$mysqli->affected_rows;
295 }
296
297 public static function escape($var)
298 {
299 switch (gettype($var)) {
300 case 'boolean':
301 return $var ? 1 : 0;
302
303 case 'integer':
304 case 'double':
305 case 'float':
306 return $var;
307
308 case 'string':
309 return "'".addslashes($var)."'";
310
311 case 'NULL':
312 return 'NULL';
313
314 case 'object':
315 if ($var instanceof PlFlagSet) {
316 return "'" . addslashes($var->flags()) . "'";
317 }
318 case 'array':
319 return "'".addslashes(serialize($var))."'";
320
321 default:
322 die(var_export($var, true).' is not a valid for a database entry');
323 }
324 }
325 }
326
327 class XOrgDBResult
328 {
329
330 private $_res;
331
332 public function __construct($query)
333 {
334 $this->_res = XDB::_query($query);
335 }
336
337 public function free()
338 {
339 if ($this->_res) {
340 $this->_res->free();
341 }
342 unset($this);
343 }
344
345 protected function _fetchRow()
346 {
347 return $this->_res ? $this->_res->fetch_row() : null;
348 }
349
350 protected function _fetchAssoc()
351 {
352 return $this->_res ? $this->_res->fetch_assoc() : null;
353 }
354
355 public function fetchAllRow($id = false, $keep_array = false)
356 {
357 $result = Array();
358 if (!$this->_res) {
359 return $result;
360 }
361 while (($data = $this->_res->fetch_row())) {
362 if ($id !== false) {
363 $key = $data[$id];
364 unset($data[$id]);
365 if (!$keep_array && count($data) == 1) {
366 reset($data);
367 $result[$key] = current($data);
368 } else {
369 $result[$key] = $data;
370 }
371 } else {
372 $result[] = $data;
373 }
374 }
375 $this->free();
376 return $result;
377 }
378
379 public function fetchAllAssoc($id = false, $keep_array = false)
380 {
381 $result = Array();
382 if (!$this->_res) {
383 return $result;
384 }
385 while (($data = $this->_res->fetch_assoc())) {
386 if ($id !== false) {
387 $key = $data[$id];
388 unset($data[$id]);
389 if (!$keep_array && count($data) == 1) {
390 reset($data);
391 $result[$key] = current($data);
392 } else {
393 $result[$key] = $data;
394 }
395 } else {
396 $result[] = $data;
397 }
398 }
399 $this->free();
400 return $result;
401 }
402
403 public function fetchOneAssoc()
404 {
405 $tmp = $this->_fetchAssoc();
406 $this->free();
407 return $tmp;
408 }
409
410 public function fetchOneRow()
411 {
412 $tmp = $this->_fetchRow();
413 $this->free();
414 return $tmp;
415 }
416
417 public function fetchOneCell()
418 {
419 $tmp = $this->_fetchRow();
420 $this->free();
421 return $tmp[0];
422 }
423
424 public function fetchColumn($key = 0)
425 {
426 $res = Array();
427 if (is_numeric($key)) {
428 while($tmp = $this->_fetchRow()) {
429 $res[] = $tmp[$key];
430 }
431 } else {
432 while($tmp = $this->_fetchAssoc()) {
433 $res[] = $tmp[$key];
434 }
435 }
436 $this->free();
437 return $res;
438 }
439
440 public function fetchOneField()
441 {
442 return $this->_res ? $this->_res->fetch_field() : null;
443 }
444
445 public function fetchFields()
446 {
447 $res = array();
448 while ($res[] = $this->fetchOneField());
449 return $res;
450 }
451
452 public function numRows()
453 {
454 return $this->_res ? $this->_res->num_rows : 0;
455 }
456
457 public function fieldCount()
458 {
459 return $this->_res ? $this->_res->field_count : 0;
460 }
461 }
462
463 require_once dirname(__FILE__) . '/pliterator.php';
464
465 class XOrgDBIterator extends XOrgDBResult implements PlIterator
466 {
467 private $_result;
468 private $_pos;
469 private $_total;
470 private $_fpos;
471 private $_fields;
472 private $_mode = MYSQL_ASSOC;
473
474 public function __construct($query, $mode = MYSQL_ASSOC)
475 {
476 parent::__construct($query);
477 $this->_pos = 0;
478 $this->_total = $this->numRows();
479 $this->_fpost = 0;
480 $this->_fields = $this->fieldCount();
481 $this->_mode = $mode;
482 }
483
484 public function next()
485 {
486 $this->_pos ++;
487 if ($this->_pos > $this->_total) {
488 $this->free();
489 unset($this);
490 return null;
491 }
492 return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc();
493 }
494
495 public function first()
496 {
497 return $this->_pos == 1;
498 }
499
500 public function last()
501 {
502 return $this->_pos == $this->_total;
503 }
504
505 public function total()
506 {
507 return $this->_total;
508 }
509
510 public function nextField()
511 {
512 $this->_fpos++;
513 if ($this->_fpos > $this->_fields) {
514 return null;
515 }
516 return $this->fetchOneField();
517 }
518
519 public function firstField()
520 {
521 return $this->_fpos == 1;
522 }
523
524 public function lastField()
525 {
526 return $this->_fpos == $this->_fields;
527 }
528
529 public function totalFields()
530 {
531 return $this->_fields;
532 }
533 }
534
535 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
536 ?>