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 **************************************************************************/
22 class 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';
28 $text = 'Erreur lors de l\'écriture dans la base de données';
30 parent
::__construct($text, $query . "\n" . $error);
36 private static $mysqli = null
;
38 public static function connect()
41 self
::$mysqli = new mysqli($globals->dbhost
, $globals->dbuser
, $globals->dbpwd
, $globals->dbdb
);
42 if ($globals->debug
& DEBUG_BT
) {
43 $bt = new PlBacktrace('MySQL');
44 if (mysqli_connect_errno()) {
45 $bt->newEvent("MySQLI connection", 0, mysqli_connect_error());
49 self
::$mysqli->autocommit(true
);
50 self
::$mysqli->set_charset($globals->dbcharset
);
54 public static function _prepare($args)
57 $query = array_map(Array('XDB', 'escape'), $args);
58 $query[0] = preg_replace('/#([a-z0-9]+)#/', $globals->dbprefix
. '$1', $args[0]);
59 $query[0] = str_replace('%', '%%', $query[0]);
60 $query[0] = str_replace('{?}', '%s', $query[0]);
61 return call_user_func_array('sprintf', $query);
64 public static function _reformatQuery($query)
66 $query = preg_split("/\n\\s*/", trim($query));
68 foreach ($query as $key=>$line) {
70 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
71 && $matches[1] != 'AND' && $matches[1] != 'OR')
73 $local = strlen($matches[1]);
74 $line = $matches[1] . ' ' . $matches[2];
75 $length = max($length, $local);
77 $query[$key] = array($line, $local);
80 foreach ($query as $array) {
81 list($line, $local) = $array;
82 $local = max(0, $length - $local);
83 $res .= str_repeat(' ', $local) . $line . "\n";
84 $length +
= 2 * (substr_count($line, '(') - substr_count($line, ')'));
89 public static function _query($query)
93 if (!self
::$mysqli && !self
::connect()) {
94 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
95 Platal
::page()->kill('Impossible de se connecter à la base de données.');
99 if ($globals->debug
& DEBUG_BT
) {
101 if (strpos($query, 'FOUND_ROWS()') === false
) {
102 $res = self
::$mysqli->query("EXPLAIN $query");
104 while ($row = $res->fetch_assoc()) {
110 PlBacktrace
::$bt['MySQL']->start(XDB
::_reformatQuery($query));
113 $res = XDB
::$mysqli->query($query);
115 if ($globals->debug
& DEBUG_BT
) {
116 PlBacktrace
::$bt['MySQL']->stop(@$res->num_rows ?
$res->num_rows
: self
::$mysqli->affected_rows
,
117 self
::$mysqli->error
,
121 if ($res === false
) {
122 throw new XDBException(XDB
::_reformatQuery($query), XDB
::$mysqli->error
);
127 private static function queryv($query)
129 return new XOrgDBResult(self
::_prepare($query));
132 public static function query()
134 return self
::queryv(func_get_args());
137 public static function format()
139 return self
::_prepare(func_get_args());
142 // Produce the SQL statement for setting/unsetting a flag
143 public static function changeFlag($fieldname, $flagname, $state)
146 return XDB
::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
148 return XDB
::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
152 // Produce the SQL statement representing an array
153 public static function formatArray(array $array)
155 return self
::escape($array);
158 const WILDCARD_EXACT
= 0x00;
159 const WILDCARD_PREFIX
= 0x01;
160 const WILDCARD_SUFFIX
= 0x02;
161 const WILDCARD_CONTAINS
= 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
163 // Returns the SQL statement for a wildcard search.
164 public static function formatWildcards($mode, $text)
166 if ($mode == self
::WILDCARD_EXACT
) {
167 return XDB
::format(' = {?}', $text);
169 $text = str_replace(array('%', '_'), array('\%', '\_'), $text);
170 if ($mode & self
::WILDCARD_PREFIX
) {
173 if ($mode & self
::WILDCARD_SUFFIX
) {
176 return XDB
::format(" LIKE {?}", $text);
180 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
181 public static function formatCustomOrder($field, $values)
183 return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')';
186 public static function execute()
189 $args = func_get_args();
190 if ($globals->mode
!= 'rw' && !strpos($args[0], 'logger')) {
193 return self
::_query(XDB
::_prepare($args));
196 public static function iterator()
198 return new XOrgDBIterator(self
::_prepare(func_get_args()));
201 public static function iterRow()
203 return new XOrgDBIterator(self
::_prepare(func_get_args()), MYSQL_NUM
);
206 private static function findQuery($params, $default = array())
208 for ($i = 0 ; $i < count($default) ; ++
$i) {
210 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
211 if (stripos($params[0], $kwd) !== false
) {
219 $default[$i] = array_shift($params);
222 return array($default, $params);
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.
229 public static function fetchAllRow()
231 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
232 return self
::queryv($query)->fetchAllRow($args[0], $args[1]);
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.
239 public static function fetchAllAssoc()
241 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
242 return self
::queryv($query)->fetchAllAssoc($args[0], $args[1]);
245 public static function fetchOneCell()
247 list($args, $query) = self
::findQuery(func_get_args());
248 return self
::queryv($query)->fetchOneCell();
251 public static function fetchOneRow()
253 list($args, $query) = self
::findQuery(func_get_args());
254 return self
::queryv($query)->fetchOneRow();
257 public static function fetchOneAssoc()
259 list($args, $query) = self
::findQuery(func_get_args());
260 return self
::queryv($query)->fetchOneAssoc();
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.
267 public static function fetchColumn()
269 list($args, $query) = self
::findQuery(func_get_args(), array(0));
270 return self
::queryv($query)->fetchColumn();
273 public static function insertId()
275 return self
::$mysqli->insert_id
;
278 public static function errno()
280 return self
::$mysqli->errno
;
283 public static function error()
285 return self
::$mysqli->error
;
288 public static function affectedRows()
290 return self
::$mysqli->affected_rows
;
293 public static function escape($var)
295 switch (gettype($var)) {
305 return "'".addslashes($var)."'";
311 if ($var instanceof PlFlagSet
) {
312 return "'" . addslashes($var->flags()) . "'";
314 return "'".addslashes(serialize($var))."'";
318 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
321 die(var_export($var, true
).' is not a valid for a database entry');
331 public function __construct($query)
333 $this->_res
= XDB
::_query($query);
336 public function free()
344 protected function _fetchRow()
346 return $this->_res ?
$this->_res
->fetch_row() : null
;
349 protected function _fetchAssoc()
351 return $this->_res ?
$this->_res
->fetch_assoc() : null
;
354 public function fetchAllRow($id = false
, $keep_array = false
)
360 while (($data = $this->_res
->fetch_row())) {
364 if (!$keep_array && count($data) == 1) {
366 $result[$key] = current($data);
368 $result[$key] = $data;
378 public function fetchAllAssoc($id = false
, $keep_array = false
)
384 while (($data = $this->_res
->fetch_assoc())) {
388 if (!$keep_array && count($data) == 1) {
390 $result[$key] = current($data);
392 $result[$key] = $data;
402 public function fetchOneAssoc()
404 $tmp = $this->_fetchAssoc();
409 public function fetchOneRow()
411 $tmp = $this->_fetchRow();
416 public function fetchOneCell()
418 $tmp = $this->_fetchRow();
423 public function fetchColumn($key = 0)
426 if (is_numeric($key)) {
427 while($tmp = $this->_fetchRow()) {
431 while($tmp = $this->_fetchAssoc()) {
439 public function fetchOneField()
441 return $this->_res ?
$this->_res
->fetch_field() : null
;
444 public function fetchFields()
447 while ($res[] = $this->fetchOneField());
451 public function numRows()
453 return $this->_res ?
$this->_res
->num_rows
: 0;
456 public function fieldCount()
458 return $this->_res ?
$this->_res
->field_count
: 0;
462 require_once dirname(__FILE__
) . '/pliterator.php';
464 class XOrgDBIterator
extends XOrgDBResult
implements PlIterator
471 private $_mode = MYSQL_ASSOC
;
473 public function __construct($query, $mode = MYSQL_ASSOC
)
475 parent
::__construct($query);
477 $this->_total
= $this->numRows();
479 $this->_fields
= $this->fieldCount();
480 $this->_mode
= $mode;
483 public function next()
486 if ($this->_pos
> $this->_total
) {
491 return $this->_mode
!= MYSQL_ASSOC ?
$this->_fetchRow() : $this->_fetchAssoc();
494 public function first()
496 return $this->_pos
== 1;
499 public function last()
501 return $this->_pos
== $this->_total
;
504 public function total()
506 return $this->_total
;
509 public function nextField()
512 if ($this->_fpos
> $this->_fields
) {
515 return $this->fetchOneField();
518 public function firstField()
520 return $this->_fpos
== 1;
523 public function lastField()
525 return $this->_fpos
== $this->_fields
;
528 public function totalFields()
530 return $this->_fields
;
534 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: