2 /***************************************************************************
3 * Copyright (C) 2003-2008 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 XDB
::$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 XDB
::$mysqli->autocommit(true
);
38 XDB
::$mysqli->set_charset($globals->dbcharset
);
42 public static function _prepare($args)
44 $query = array_map(Array('XDB', 'escape'), $args);
45 $query[0] = str_replace('{?}', '%s', str_replace('%', '%%', $args[0]));
46 return call_user_func_array('sprintf', $query);
49 public static function _reformatQuery($query)
51 $query = preg_split("/\n\\s*/", trim($query));
53 foreach ($query as $key=>$line) {
55 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
56 && $matches[1] != 'AND' && $matches[1] != 'OR')
58 $local = strlen($matches[1]);
59 $line = $matches[1] . ' ' . $matches[2];
60 $length = max($length, $local);
62 $query[$key] = array($line, $local);
65 foreach ($query as $array) {
66 list($line, $local) = $array;
67 $local = max(0, $length - $local);
68 $res .= str_repeat(' ', $local) . $line . "\n";
69 $length +
= 2 * (substr_count($line, '(') - substr_count($line, ')'));
74 public static function _query($query)
78 if (!XDB
::$mysqli && !XDB
::connect()) {
79 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
80 Platal
::page()->kill('Impossible de se connecter à la base de données.');
84 if ($globals->debug
& DEBUG_BT
) {
86 if (strpos($query, 'FOUND_ROWS()') === false
) {
87 $res = XDB
::$mysqli->query("EXPLAIN $query");
89 while ($row = $res->fetch_assoc()) {
95 PlBacktrace
::$bt['MySQL']->start(XDB
::_reformatQuery($query));
98 $res = XDB
::$mysqli->query($query);
100 if ($globals->debug
& DEBUG_BT
) {
101 PlBacktrace
::$bt['MySQL']->stop(@$res->num_rows ?
$res->num_rows
: XDB
::$mysqli->affected_rows
,
106 if ($res === false
) {
107 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
108 if (strpos($query, 'INSERT') === false
&& strpos($query, 'UPDATE') === false
109 && strpos($query, 'REPLACE') === false
&& strpos($query, 'DELETE') === false
) {
110 Platal
::page()->kill('Erreur lors de l\'interrogation de la base de données');
112 Platal
::page()->kill('Erreur lors de l\'écriture dans la base de données');
119 public static function query()
121 return new XOrgDBResult(XDB
::_prepare(func_get_args()));
124 public static function execute()
127 $args = func_get_args();
128 if ($globals->mode
!= 'rw' && !strpos($args[0], 'logger')) {
131 return XDB
::_query(XDB
::_prepare($args));
134 public static function iterator()
136 return new XOrgDBIterator(XDB
::_prepare(func_get_args()));
139 public static function iterRow()
141 return new XOrgDBIterator(XDB
::_prepare(func_get_args()), MYSQL_NUM
);
144 public static function insertId()
146 return XDB
::$mysqli->insert_id
;
149 public static function errno()
151 return XDB
::$mysqli->errno
;
154 public static function error()
156 return XDB
::$mysqli->error
;
159 public static function affectedRows()
161 return XDB
::$mysqli->affected_rows
;
164 public static function escape($var)
166 switch (gettype($var)) {
176 return "'".addslashes($var)."'";
182 if ($var instanceof PlFlagSet
) {
183 return "'" . addslashes($var->flags()) . "'";
186 return "'".addslashes(serialize($var))."'";
189 die(var_export($var, true
).' is not a valid for a database entry');
199 public function __construct($query)
201 $this->_res
= XDB
::_query($query);
204 public function free()
212 protected function _fetchRow()
214 return $this->_res ?
$this->_res
->fetch_row() : null
;
217 protected function _fetchAssoc()
219 return $this->_res ?
$this->_res
->fetch_assoc() : null
;
222 public function fetchAllRow()
228 while ($result[] = $this->_res
->fetch_row());
234 public function fetchAllAssoc()
240 while ($result[] = $this->_res
->fetch_assoc());
246 public function fetchOneAssoc()
248 $tmp = $this->_fetchAssoc();
253 public function fetchOneRow()
255 $tmp = $this->_fetchRow();
260 public function fetchOneCell()
262 $tmp = $this->_fetchRow();
267 public function fetchColumn($key = 0)
270 if (is_numeric($key)) {
271 while($tmp = $this->_fetchRow()) {
275 while($tmp = $this->_fetchAssoc()) {
283 public function fetchOneField()
285 return $this->_res ?
$this->_res
->fetch_field() : null
;
288 public function fetchFields()
291 while ($res[] = $this->fetchOneField());
295 public function numRows()
297 return $this->_res ?
$this->_res
->num_rows
: 0;
300 public function fieldCount()
302 return $this->_res ?
$this->_res
->field_count
: 0;
306 require_once dirname(__FILE__
) . '/pliterator.php';
308 class XOrgDBIterator
extends XOrgDBResult
implements PlIterator
315 private $_mode = MYSQL_ASSOC
;
317 public function __construct($query, $mode = MYSQL_ASSOC
)
319 parent
::__construct($query);
321 $this->_total
= $this->numRows();
323 $this->_fields
= $this->fieldCount();
324 $this->_mode
= $mode;
327 public function next()
330 if ($this->_pos
> $this->_total
) {
335 return $this->_mode
!= MYSQL_ASSOC ?
$this->_fetchRow() : $this->_fetchAssoc();
338 public function first()
340 return $this->_pos
== 1;
343 public function last()
345 return $this->_pos
== $this->_total
;
348 public function total()
350 return $this->_total
;
353 public function nextField()
356 if ($this->_fpos
> $this->_fields
) {
359 return $this->fetchOneField();
362 public function firstField()
364 return $this->_fpos
== 1;
367 public function lastField()
369 return $this->_fpos
== $this->_fields
;
372 public function totalFields()
374 return $this->_fields
;
378 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: