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 _query($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 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';
115 $text = 'Erreur lors de l\'écriture dans la base de données';
117 if (php_sapi_name() == 'cli') {
118 $text .= "\n" . XDB
::_reformatQuery($query)
119 . "\n" . XDB
::$mysqli->error
;
120 } else if ($globals->debug
) {
121 $text .= '<pre>' . pl_entities(XDB
::_reformatQuery($query)) . '</pre>';
123 $file = fopen($globals->spoolroot
. '/spool/tmp/query_errors', 'a');
124 fwrite($file, '<pre>' . pl_entities(XDB
::_reformatQuery($query)) . '</pre>'
125 . '<pre>' . XDB
::$mysqli->error
. '</pre>' . "\n");
128 Platal
::page()->kill($text);
134 private static function queryv($query)
136 return new XOrgDBResult(self
::_prepare($query));
139 public static function query()
141 return self
::queryv(func_get_args());
144 public static function format()
146 return self
::_prepare(func_get_args());
149 // Produce the SQL statement for setting/unsetting a flag
150 public static function changeFlag($fieldname, $flagname, $state)
153 return XDB
::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname);
155 return XDB
::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname);
159 // Produce the SQL statement representing an array
160 public static function formatArray(array $array)
162 return '(' . implode(', ', array_map(array('XDB', 'escape'), $array)) . ')';
165 const WILDCARD_EXACT
= 0x00;
166 const WILDCARD_PREFIX
= 0x01;
167 const WILDCARD_SUFFIX
= 0x02;
168 const WILDCARD_CONTAINS
= 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX
170 // Returns the SQL statement for a wildcard search.
171 public static function formatWildcards($mode, $text)
173 if ($mode == self
::WILDCARD_EXACT
) {
174 return XDB
::format(' = {?}', $text);
176 $text = str_replace(array('%', '_'), array('\%', '\_'), $text);
177 if ($mode & self
::WILDCARD_PREFIX
) {
180 if ($mode & self
::WILDCARD_SUFFIX
) {
183 return XDB
::format(" LIKE {?}", $text);
187 // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders
188 public static function formatCustomOrder($field, $values)
190 return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')';
193 public static function execute()
196 $args = func_get_args();
197 if ($globals->mode
!= 'rw' && !strpos($args[0], 'logger')) {
200 return self
::_query(XDB
::_prepare($args));
203 public static function iterator()
205 return new XOrgDBIterator(self
::_prepare(func_get_args()));
208 public static function iterRow()
210 return new XOrgDBIterator(self
::_prepare(func_get_args()), MYSQL_NUM
);
213 private static function findQuery($params, $default = array())
215 for ($i = 0 ; $i < count($default) ; ++
$i) {
217 foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) {
218 if (stripos($params[0], $kwd) !== false
) {
226 $default[$i] = array_shift($params);
229 return array($default, $params);
232 /** Fetch all rows returned by the given query.
233 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllRow()).
234 * Optional arguments are given *before* the query.
236 public static function fetchAllRow()
238 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
239 return self
::queryv($query)->fetchAllRow($args[0], $args[1]);
242 /** Fetch all rows returned by the given query.
243 * This functions can take 2 optional arguments (cf XOrgDBResult::fetchAllAssoc()).
244 * Optional arguments are given *before* the query.
246 public static function fetchAllAssoc()
248 list($args, $query) = self
::findQuery(func_get_args(), array(false
, false
));
249 return self
::queryv($query)->fetchAllAssoc($args[0], $args[1]);
252 public static function fetchOneCell()
254 list($args, $query) = self
::findQuery(func_get_args());
255 return self
::queryv($query)->fetchOneCell();
258 public static function fetchOneRow()
260 list($args, $query) = self
::findQuery(func_get_args());
261 return self
::queryv($query)->fetchOneRow();
264 public static function fetchOneAssoc()
266 list($args, $query) = self
::findQuery(func_get_args());
267 return self
::queryv($query)->fetchOneAssoc();
270 /** Fetch a column from the result of the given query.
271 * This functions can take 1 optional arguments (cf XOrgDBResult::fetchColumn()).
272 * Optional arguments are given *before* the query.
274 public static function fetchColumn()
276 list($args, $query) = self
::findQuery(func_get_args(), array(0));
277 return self
::queryv($query)->fetchColumn();
280 public static function insertId()
282 return self
::$mysqli->insert_id
;
285 public static function errno()
287 return self
::$mysqli->errno
;
290 public static function error()
292 return self
::$mysqli->error
;
295 public static function affectedRows()
297 return self
::$mysqli->affected_rows
;
300 public static function escape($var)
302 switch (gettype($var)) {
312 return "'".addslashes($var)."'";
318 if ($var instanceof PlFlagSet
) {
319 return "'" . addslashes($var->flags()) . "'";
322 return "'".addslashes(serialize($var))."'";
325 die(var_export($var, true
).' is not a valid for a database entry');
335 public function __construct($query)
337 $this->_res
= XDB
::_query($query);
340 public function free()
348 protected function _fetchRow()
350 return $this->_res ?
$this->_res
->fetch_row() : null
;
353 protected function _fetchAssoc()
355 return $this->_res ?
$this->_res
->fetch_assoc() : null
;
358 public function fetchAllRow($id = false
, $keep_array = false
)
364 while (($data = $this->_res
->fetch_row())) {
368 if (!$keep_array && count($data) == 1) {
370 $result[$key] = current($data);
372 $result[$key] = $data;
382 public function fetchAllAssoc($id = false
, $keep_array = false
)
388 while (($data = $this->_res
->fetch_assoc())) {
392 if (!$keep_array && count($data) == 1) {
394 $result[$key] = current($data);
396 $result[$key] = $data;
406 public function fetchOneAssoc()
408 $tmp = $this->_fetchAssoc();
413 public function fetchOneRow()
415 $tmp = $this->_fetchRow();
420 public function fetchOneCell()
422 $tmp = $this->_fetchRow();
427 public function fetchColumn($key = 0)
430 if (is_numeric($key)) {
431 while($tmp = $this->_fetchRow()) {
435 while($tmp = $this->_fetchAssoc()) {
443 public function fetchOneField()
445 return $this->_res ?
$this->_res
->fetch_field() : null
;
448 public function fetchFields()
451 while ($res[] = $this->fetchOneField());
455 public function numRows()
457 return $this->_res ?
$this->_res
->num_rows
: 0;
460 public function fieldCount()
462 return $this->_res ?
$this->_res
->field_count
: 0;
466 require_once dirname(__FILE__
) . '/pliterator.php';
468 class XOrgDBIterator
extends XOrgDBResult
implements PlIterator
475 private $_mode = MYSQL_ASSOC
;
477 public function __construct($query, $mode = MYSQL_ASSOC
)
479 parent
::__construct($query);
481 $this->_total
= $this->numRows();
483 $this->_fields
= $this->fieldCount();
484 $this->_mode
= $mode;
487 public function next()
490 if ($this->_pos
> $this->_total
) {
495 return $this->_mode
!= MYSQL_ASSOC ?
$this->_fetchRow() : $this->_fetchAssoc();
498 public function first()
500 return $this->_pos
== 1;
503 public function last()
505 return $this->_pos
== $this->_total
;
508 public function total()
510 return $this->_total
;
513 public function nextField()
516 if ($this->_fpos
> $this->_fields
) {
519 return $this->fetchOneField();
522 public function firstField()
524 return $this->_fpos
== 1;
527 public function lastField()
529 return $this->_fpos
== $this->_fields
;
532 public function totalFields()
534 return $this->_fields
;
538 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: