2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 **************************************************************************/
24 private static $mysqli = null
;
26 public static function connect()
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());
37 self
::$mysqli->autocommit(true
);
38 self
::$mysqli->set_charset($globals->dbcharset
);
42 public static function prepare($args)
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);
52 public static function reformatQuery($query)
54 $query = preg_split("/\n\\s*/", trim($query));
56 foreach ($query as $key=>$line) {
58 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
59 && $matches[1] != 'AND' && $matches[1] != 'OR')
61 $local = strlen($matches[1]);
62 $line = $matches[1] . ' ' . $matches[2];
63 $length = max($length, $local);
65 $query[$key] = array($line, $local);
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, ')'));
77 public static function run($query)
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.');
87 if ($globals->debug
& DEBUG_BT
) {
89 if (strpos($query, 'FOUND_ROWS()') === false
) {
90 $res = self
::$mysqli->query("EXPLAIN $query");
92 while ($row = $res->fetch_assoc()) {
98 PlBacktrace
::$bt['MySQL']->start(XDB
::reformatQuery($query));
101 $res = XDB
::$mysqli->query($query);
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
,
109 if ($res === false
) {
110 throw new XDBException(XDB
::reformatQuery($query), XDB
::$mysqli->error
);
115 private static function queryv($query)
117 return new XDBResult(self
::prepare($query));
120 public static function query()
122 return self
::queryv(func_get_args());
125 public static function rawQuery($query)
127 return new XDBResult($query);
130 public static function format()
132 return self
::prepare(func_get_args());
135 // Produce the SQL statement for setting/unsetting a flag
136 public static function changeFlag($fieldname, $flagname, $state)
139 return XDB
::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
141 return XDB
::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
145 // Produce the SQL statement representing an array
146 public static function formatArray(array $array)
148 return self
::escape($array);
151 const WILDCARD_EXACT
= 0x00;
152 const WILDCARD_PREFIX
= 0x01;
153 const WILDCARD_SUFFIX
= 0x02;
154 const WILDCARD_CONTAINS
= 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
156 // Produce a valid XDB argument that get formatted as a wildcard
157 // according to the given mode.
160 // XDB::query("SELECT * FROM table WHERE field {?}", XDB::wildcard($text, WILDCARD_EXACT));
161 public static function wildcard($mode, $value)
163 return new XDBWildcard($value, $mode);
166 // Returns the SQL statement for a wildcard search.
167 public static function formatWildcards($mode, $text)
169 return XDB
::wildcard($mode, $text)->format();
172 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
173 public static function formatCustomOrder($field, $values)
175 return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')';
178 public static function execute()
181 $args = func_get_args();
182 if ($globals->mode
!= 'rw' && !strpos($args[0], 'logger')) {
185 return self
::run(XDB
::prepare($args));
188 public static function rawExecute($query)
191 if ($globals->mode
!= 'rw') {
194 return self
::run($query);
197 public static function iterator()
199 return new XDBIterator(self
::prepare(func_get_args()));
202 public static function rawIterator($query)
204 return new XDBIterator($query);
207 public static function iterRow()
209 return new XDBIterator(self
::prepare(func_get_args()), MYSQL_NUM
);
212 public static function rawIterRow($query)
214 return new XDBIterator($query, MYSQL_NUM
);
217 private static function findQuery($params, $default = array())
219 for ($i = 0 ; $i < count($default) ; ++
$i) {
221 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
222 if (stripos($params[0], $kwd) !== false
) {
230 $default[$i] = array_shift($params);
233 return array($default, $params);
236 /** Fetch all rows returned by the given query.
237 * This functions can take 2 optional arguments (cf XDBResult::fetchAllRow()).
238 * Optional arguments are given *before* the query.
240 public static function fetchAllRow()
242 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
243 return self
::queryv($query)->fetchAllRow($args[0], $args[1]);
246 public static function rawFetchAllRow($query, $id = false
, $keep_array = false
)
248 return self
::rawQuery($query)->fetchAllRow($id, $keep_array);
251 /** Fetch all rows returned by the given query.
252 * This functions can take 2 optional arguments (cf XDBResult::fetchAllAssoc()).
253 * Optional arguments are given *before* the query.
255 public static function fetchAllAssoc()
257 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
258 return self
::queryv($query)->fetchAllAssoc($args[0], $args[1]);
261 public static function rawFetchAllAssoc($query, $id = false
, $keep_array = false
)
263 return self
::rawQuery($query)->fetchAllAssoc($id, $keep_array);
266 public static function fetchOneCell()
268 list($args, $query) = self
::findQuery(func_get_args());
269 return self
::queryv($query)->fetchOneCell();
272 public static function rawFetchOneCell($query)
274 return self
::rawQuery($query)->fetchOneCell();
277 public static function fetchOneRow()
279 list($args, $query) = self
::findQuery(func_get_args());
280 return self
::queryv($query)->fetchOneRow();
283 public static function rawFetchOneRow($query)
285 return self
::rawQuery($query)->fetchOneRow();
288 public static function fetchOneAssoc()
290 list($args, $query) = self
::findQuery(func_get_args());
291 return self
::queryv($query)->fetchOneAssoc();
294 public static function rawFetchOneAssoc($query)
296 return self
::rawQuery($query)->fetchOneAssoc();
299 /** Fetch a column from the result of the given query.
300 * This functions can take 1 optional arguments (cf XDBResult::fetchColumn()).
301 * Optional arguments are given *before* the query.
303 public static function fetchColumn()
305 list($args, $query) = self
::findQuery(func_get_args(), array(0));
306 return self
::queryv($query)->fetchColumn($args[0]);
309 public static function rawFetchColumn($query, $key = 0)
311 return self
::rawQuery($query)->fetchColumn($key);
314 public static function insertId()
316 return self
::$mysqli->insert_id
;
319 public static function errno()
321 return self
::$mysqli->errno
;
324 public static function error()
326 return self
::$mysqli->error
;
329 public static function affectedRows()
331 return self
::$mysqli->affected_rows
;
334 public static function escape($var)
336 switch (gettype($var)) {
346 return "'".addslashes($var)."'";
352 if ($var instanceof XDBFormat
) {
353 return $var->format();
355 return "'".addslashes(serialize($var))."'";
359 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
362 die(var_export($var, true
).' is not a valid for a database entry');
367 class XDBException
extends PlException
369 public function __construct($query, $error)
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';
375 $text = 'Erreur lors de l\'écriture dans la base de données';
377 parent
::__construct($text, $query . "\n" . $error);
383 public function format();
386 class XDBWildcard
implements XDBFormat
391 public function __construct($value, $mode)
393 $this->value
= $value;
397 public function format()
399 if ($this->mode
== XDB
::WILDCARD_EXACT
) {
400 return XDB
::format(' = {?}', $this->value
);
402 $text = str_replace(array('%', '_'), array('\%', '\_'), $this->value
);
403 if ($this->mode
& XDB
::WILDCARD_PREFIX
) {
406 if ($this->mode
& XDB
::WILDCARD_SUFFIX
) {
409 return XDB
::format(" LIKE {?}", $text);
419 public function __construct($query)
421 $this->res
= XDB
::run($query);
424 public function free()
432 protected function fetchRow()
434 return $this->res ?
$this->res
->fetch_row() : null
;
437 protected function fetchAssoc()
439 return $this->res ?
$this->res
->fetch_assoc() : null
;
442 public function fetchAllRow($id = false
, $keep_array = false
)
448 while (($data = $this->res
->fetch_row())) {
452 if (!$keep_array && count($data) == 1) {
454 $result[$key] = current($data);
456 $result[$key] = $data;
466 public function fetchAllAssoc($id = false
, $keep_array = false
)
472 while (($data = $this->res
->fetch_assoc())) {
476 if (!$keep_array && count($data) == 1) {
478 $result[$key] = current($data);
480 $result[$key] = $data;
490 public function fetchOneAssoc()
492 $tmp = $this->fetchAssoc();
497 public function fetchOneRow()
499 $tmp = $this->fetchRow();
504 public function fetchOneCell()
506 $tmp = $this->fetchRow();
511 public function fetchColumn($key = 0)
514 if (is_numeric($key)) {
515 while($tmp = $this->fetchRow()) {
519 while($tmp = $this->fetchAssoc()) {
527 public function fetchOneField()
529 return $this->res ?
$this->res
->fetch_field() : null
;
532 public function fetchFields()
535 while ($res[] = $this->fetchOneField());
539 public function numRows()
541 return $this->res ?
$this->res
->num_rows
: 0;
544 public function fieldCount()
546 return $this->res ?
$this->res
->field_count
: 0;
551 class XDBIterator
extends XDBResult
implements PlIterator
558 private $mode = MYSQL_ASSOC
;
560 public function __construct($query, $mode = MYSQL_ASSOC
)
562 parent
::__construct($query);
564 $this->total
= $this->numRows();
566 $this->fields
= $this->fieldCount();
570 public function next()
573 if ($this->pos
> $this->total
) {
578 return $this->mode
!= MYSQL_ASSOC ?
$this->fetchRow() : $this->fetchAssoc();
581 public function first()
583 return $this->pos
== 1;
586 public function last()
588 return $this->pos
== $this->total
;
591 public function total()
596 public function nextField()
599 if ($this->fpos
> $this->fields
) {
602 return $this->fetchOneField();
605 public function firstField()
607 return $this->fpos
== 1;
610 public function lastField()
612 return $this->fpos
== $this->fields
;
615 public function totalFields()
617 return $this->fields
;
621 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: