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
;
25 private static $fatalErrors = true
;
27 public static function connect()
30 self
::$mysqli = new mysqli($globals->dbhost
, $globals->dbuser
, $globals->dbpwd
, $globals->dbdb
);
31 if ($globals->debug
& DEBUG_BT
) {
32 $bt = new PlBacktrace('MySQL');
33 if (mysqli_connect_errno()) {
34 $bt->newEvent("MySQLI connection", 0, mysqli_connect_error());
38 self
::$mysqli->autocommit(true
);
39 self
::$mysqli->set_charset($globals->dbcharset
);
43 public static function setNonFatalError()
45 self
::$fatalErrors = false
;
48 public static function _prepare($args)
51 $query = array_map(Array('XDB', 'escape'), $args);
52 $query[0] = preg_replace('/#([a-z0-9]+)#/', $globals->dbprefix
. '$1', $args[0]);
53 $query[0] = str_replace('%', '%%', $query[0]);
54 $query[0] = str_replace('{?}', '%s', $query[0]);
55 return call_user_func_array('sprintf', $query);
58 public static function _reformatQuery($query)
60 $query = preg_split("/\n\\s*/", trim($query));
62 foreach ($query as $key=>$line) {
64 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
65 && $matches[1] != 'AND' && $matches[1] != 'OR')
67 $local = strlen($matches[1]);
68 $line = $matches[1] . ' ' . $matches[2];
69 $length = max($length, $local);
71 $query[$key] = array($line, $local);
74 foreach ($query as $array) {
75 list($line, $local) = $array;
76 $local = max(0, $length - $local);
77 $res .= str_repeat(' ', $local) . $line . "\n";
78 $length +
= 2 * (substr_count($line, '(') - substr_count($line, ')'));
83 public static function _query($query)
87 if (!self
::$mysqli && !self
::connect()) {
88 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
89 Platal
::page()->kill('Impossible de se connecter à la base de données.');
93 if ($globals->debug
& DEBUG_BT
) {
95 if (strpos($query, 'FOUND_ROWS()') === false
) {
96 $res = self
::$mysqli->query("EXPLAIN $query");
98 while ($row = $res->fetch_assoc()) {
104 PlBacktrace
::$bt['MySQL']->start(XDB
::_reformatQuery($query));
107 $res = XDB
::$mysqli->query($query);
109 if ($globals->debug
& DEBUG_BT
) {
110 PlBacktrace
::$bt['MySQL']->stop(@$res->num_rows ?
$res->num_rows
: self
::$mysqli->affected_rows
,
111 self
::$mysqli->error
,
115 if ($res === false
) {
116 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
117 if (strpos($query, 'INSERT') === false
&& strpos($query, 'UPDATE') === false
118 && strpos($query, 'REPLACE') === false
&& strpos($query, 'DELETE') === false
) {
119 $text = 'Erreur lors de l\'interrogation de la base de données';
121 $text = 'Erreur lors de l\'écriture dans la base de données';
123 if (php_sapi_name() == 'cli') {
124 $text .= "\n" . XDB
::_reformatQuery($query)
125 . "\n" . XDB
::$mysqli->error
;
126 } else if ($globals->debug
) {
127 $text .= '<pre>' . pl_entities(XDB
::_reformatQuery($query)) . '</pre>';
129 $file = fopen($globals->spoolroot
. '/spool/tmp/query_errors', 'a');
130 fwrite($file, '<pre>' . date("Y-m-d G:i:s") . '</pre>'
131 . '<pre>' . pl_entities(XDB
::_reformatQuery($query)) . '</pre>'
132 . '<pre>' . XDB
::$mysqli->error
. '</pre>'
133 . "--------------------------------------------------------------------------------\n");
136 if (self
::$fatalErrors) {
137 Platal
::page()->kill($text);
140 throw new Exception($text . " :\n" . $query);
146 private static function queryv($query)
148 return new XOrgDBResult(self
::_prepare($query));
151 public static function query()
153 return self
::queryv(func_get_args());
156 public static function format()
158 return self
::_prepare(func_get_args());
161 // Produce the SQL statement for setting/unsetting a flag
162 public static function changeFlag($fieldname, $flagname, $state)
165 return XDB
::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
167 return XDB
::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
171 // Produce the SQL statement representing an array
172 public static function formatArray(array $array)
174 return self
::escape($array);
177 const WILDCARD_EXACT
= 0x00;
178 const WILDCARD_PREFIX
= 0x01;
179 const WILDCARD_SUFFIX
= 0x02;
180 const WILDCARD_CONTAINS
= 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
182 // Returns the SQL statement for a wildcard search.
183 public static function formatWildcards($mode, $text)
185 if ($mode == self
::WILDCARD_EXACT
) {
186 return XDB
::format(' = {?}', $text);
188 $text = str_replace(array('%', '_'), array('\%', '\_'), $text);
189 if ($mode & self
::WILDCARD_PREFIX
) {
192 if ($mode & self
::WILDCARD_SUFFIX
) {
195 return XDB
::format(" LIKE {?}", $text);
199 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
200 public static function formatCustomOrder($field, $values)
202 return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')';
205 public static function execute()
208 $args = func_get_args();
209 if ($globals->mode
!= 'rw' && !strpos($args[0], 'logger')) {
212 return self
::_query(XDB
::_prepare($args));
215 public static function iterator()
217 return new XOrgDBIterator(self
::_prepare(func_get_args()));
220 public static function iterRow()
222 return new XOrgDBIterator(self
::_prepare(func_get_args()), MYSQL_NUM
);
225 private static function findQuery($params, $default = array())
227 for ($i = 0 ; $i < count($default) ; ++
$i) {
229 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
230 if (stripos($params[0], $kwd) !== false
) {
238 $default[$i] = array_shift($params);
241 return array($default, $params);
244 /** Fetch all rows returned by the given query.
245 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllRow()).
246 * Optional arguments are given *before* the query.
248 public static function fetchAllRow()
250 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
251 return self
::queryv($query)->fetchAllRow($args[0], $args[1]);
254 /** Fetch all rows returned by the given query.
255 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllAssoc()).
256 * Optional arguments are given *before* the query.
258 public static function fetchAllAssoc()
260 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
261 return self
::queryv($query)->fetchAllAssoc($args[0], $args[1]);
264 public static function fetchOneCell()
266 list($args, $query) = self
::findQuery(func_get_args());
267 return self
::queryv($query)->fetchOneCell();
270 public static function fetchOneRow()
272 list($args, $query) = self
::findQuery(func_get_args());
273 return self
::queryv($query)->fetchOneRow();
276 public static function fetchOneAssoc()
278 list($args, $query) = self
::findQuery(func_get_args());
279 return self
::queryv($query)->fetchOneAssoc();
282 /** Fetch a column from the result of the given query.
283 * This functions can take 1 optional arguments (cf XOrgDBResult::fetchColumn()).
284 * Optional arguments are given *before* the query.
286 public static function fetchColumn()
288 list($args, $query) = self
::findQuery(func_get_args(), array(0));
289 return self
::queryv($query)->fetchColumn();
292 public static function insertId()
294 return self
::$mysqli->insert_id
;
297 public static function errno()
299 return self
::$mysqli->errno
;
302 public static function error()
304 return self
::$mysqli->error
;
307 public static function affectedRows()
309 return self
::$mysqli->affected_rows
;
312 public static function escape($var)
314 switch (gettype($var)) {
324 return "'".addslashes($var)."'";
330 if ($var instanceof PlFlagSet
) {
331 return "'" . addslashes($var->flags()) . "'";
333 return "'".addslashes(serialize($var))."'";
337 return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')';
340 die(var_export($var, true
).' is not a valid for a database entry');
350 public function __construct($query)
352 $this->_res
= XDB
::_query($query);
355 public function free()
363 protected function _fetchRow()
365 return $this->_res ?
$this->_res
->fetch_row() : null
;
368 protected function _fetchAssoc()
370 return $this->_res ?
$this->_res
->fetch_assoc() : null
;
373 public function fetchAllRow($id = false
, $keep_array = false
)
379 while (($data = $this->_res
->fetch_row())) {
383 if (!$keep_array && count($data) == 1) {
385 $result[$key] = current($data);
387 $result[$key] = $data;
397 public function fetchAllAssoc($id = false
, $keep_array = false
)
403 while (($data = $this->_res
->fetch_assoc())) {
407 if (!$keep_array && count($data) == 1) {
409 $result[$key] = current($data);
411 $result[$key] = $data;
421 public function fetchOneAssoc()
423 $tmp = $this->_fetchAssoc();
428 public function fetchOneRow()
430 $tmp = $this->_fetchRow();
435 public function fetchOneCell()
437 $tmp = $this->_fetchRow();
442 public function fetchColumn($key = 0)
445 if (is_numeric($key)) {
446 while($tmp = $this->_fetchRow()) {
450 while($tmp = $this->_fetchAssoc()) {
458 public function fetchOneField()
460 return $this->_res ?
$this->_res
->fetch_field() : null
;
463 public function fetchFields()
466 while ($res[] = $this->fetchOneField());
470 public function numRows()
472 return $this->_res ?
$this->_res
->num_rows
: 0;
475 public function fieldCount()
477 return $this->_res ?
$this->_res
->field_count
: 0;
481 require_once dirname(__FILE__
) . '/pliterator.php';
483 class XOrgDBIterator
extends XOrgDBResult
implements PlIterator
490 private $_mode = MYSQL_ASSOC
;
492 public function __construct($query, $mode = MYSQL_ASSOC
)
494 parent
::__construct($query);
496 $this->_total
= $this->numRows();
498 $this->_fields
= $this->fieldCount();
499 $this->_mode
= $mode;
502 public function next()
505 if ($this->_pos
> $this->_total
) {
510 return $this->_mode
!= MYSQL_ASSOC ?
$this->_fetchRow() : $this->_fetchAssoc();
513 public function first()
515 return $this->_pos
== 1;
518 public function last()
520 return $this->_pos
== $this->_total
;
523 public function total()
525 return $this->_total
;
528 public function nextField()
531 if ($this->_fpos
> $this->_fields
) {
534 return $this->fetchOneField();
537 public function firstField()
539 return $this->_fpos
== 1;
542 public function lastField()
544 return $this->_fpos
== $this->_fields
;
547 public function totalFields()
549 return $this->_fields
;
553 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: