| 1 | <?php |
| 2 | /*************************************************************************** |
| 3 | * Copyright (C) 2003-2010 Polytechnique.org * |
| 4 | * http://opensource.polytechnique.org/ * |
| 5 | * * |
| 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. * |
| 10 | * * |
| 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. * |
| 15 | * * |
| 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 * |
| 18 | * Foundation, Inc., * |
| 19 | * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * |
| 20 | **************************************************************************/ |
| 21 | |
| 22 | class XDB |
| 23 | { |
| 24 | private static $mysqli = null; |
| 25 | |
| 26 | public static function connect() |
| 27 | { |
| 28 | global $globals; |
| 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()); |
| 34 | return false; |
| 35 | } |
| 36 | } |
| 37 | self::$mysqli->autocommit(true); |
| 38 | self::$mysqli->set_charset($globals->dbcharset); |
| 39 | return true; |
| 40 | } |
| 41 | |
| 42 | public static function _prepare($args) |
| 43 | { |
| 44 | global $globals; |
| 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); |
| 50 | } |
| 51 | |
| 52 | public static function _reformatQuery($query) |
| 53 | { |
| 54 | $query = preg_split("/\n\\s*/", trim($query)); |
| 55 | $length = 0; |
| 56 | foreach ($query as $key=>$line) { |
| 57 | $local = -2; |
| 58 | if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches) |
| 59 | && $matches[1] != 'AND' && $matches[1] != 'OR') |
| 60 | { |
| 61 | $local = strlen($matches[1]); |
| 62 | $line = $matches[1] . ' ' . $matches[2]; |
| 63 | $length = max($length, $local); |
| 64 | } |
| 65 | $query[$key] = array($line, $local); |
| 66 | } |
| 67 | $res = ''; |
| 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, ')')); |
| 73 | } |
| 74 | return $res; |
| 75 | } |
| 76 | |
| 77 | public static function _query($query) |
| 78 | { |
| 79 | global $globals; |
| 80 | |
| 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.'); |
| 84 | exit; |
| 85 | } |
| 86 | |
| 87 | if ($globals->debug & DEBUG_BT) { |
| 88 | $explain = array(); |
| 89 | if (strpos($query, 'FOUND_ROWS()') === false) { |
| 90 | $res = self::$mysqli->query("EXPLAIN $query"); |
| 91 | if ($res) { |
| 92 | while ($row = $res->fetch_assoc()) { |
| 93 | $explain[] = $row; |
| 94 | } |
| 95 | $res->free(); |
| 96 | } |
| 97 | } |
| 98 | PlBacktrace::$bt['MySQL']->start(XDB::_reformatQuery($query)); |
| 99 | } |
| 100 | |
| 101 | $res = XDB::$mysqli->query($query); |
| 102 | |
| 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, |
| 106 | $explain); |
| 107 | } |
| 108 | |
| 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'; |
| 114 | } else { |
| 115 | $text = 'Erreur lors de l\'écriture dans la base de données'; |
| 116 | } |
| 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>'; |
| 122 | } else { |
| 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"); |
| 126 | fclose($file); |
| 127 | } |
| 128 | Platal::page()->kill($text); |
| 129 | exit; |
| 130 | } |
| 131 | return $res; |
| 132 | } |
| 133 | |
| 134 | private static function queryv($query) |
| 135 | { |
| 136 | return new XOrgDBResult(self::_prepare($query)); |
| 137 | } |
| 138 | |
| 139 | public static function query() |
| 140 | { |
| 141 | return self::queryv(func_get_args()); |
| 142 | } |
| 143 | |
| 144 | public static function format() |
| 145 | { |
| 146 | return self::_prepare(func_get_args()); |
| 147 | } |
| 148 | |
| 149 | // Produce the SQL statement for setting/unsetting a flag |
| 150 | public static function changeFlag($fieldname, $flagname, $state) |
| 151 | { |
| 152 | if ($state) { |
| 153 | return XDB::format($fieldname . ' = CONCAT({?}, \',\', ' . $fieldname . ')', $flagname); |
| 154 | } else { |
| 155 | return XDB::format($fieldname . ' = REPLACE(' . $fieldname . ', {?}, \'\')', $flagname); |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // Produce the SQL statement representing an array |
| 160 | public static function formatArray(array $array) |
| 161 | { |
| 162 | return self::escape($array); |
| 163 | } |
| 164 | |
| 165 | const WILDCARD_EXACT = 0x00; |
| 166 | const WILDCARD_PREFIX = 0x01; |
| 167 | const WILDCARD_SUFFIX = 0x02; |
| 168 | const WILDCARD_CONTAINS = 0x03; // WILDCARD_PREFIX | WILDCARD_SUFFIX |
| 169 | |
| 170 | // Returns the SQL statement for a wildcard search. |
| 171 | public static function formatWildcards($mode, $text) |
| 172 | { |
| 173 | if ($mode == self::WILDCARD_EXACT) { |
| 174 | return XDB::format(' = {?}', $text); |
| 175 | } else { |
| 176 | $text = str_replace(array('%', '_'), array('\%', '\_'), $text); |
| 177 | if ($mode & self::WILDCARD_PREFIX) { |
| 178 | $text = $text . '%'; |
| 179 | } |
| 180 | if ($mode & self::WILDCARD_SUFFIX) { |
| 181 | $text = '%' . $text; |
| 182 | } |
| 183 | return XDB::format(" LIKE {?}", $text); |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | // Returns a FIELD(blah, 3, 1, 2) for use in an order with custom orders |
| 188 | public static function formatCustomOrder($field, $values) |
| 189 | { |
| 190 | return 'FIELD( ' . $field . ', ' . implode(', ', array_map(array('XDB', 'escape'), $values)) . ')'; |
| 191 | } |
| 192 | |
| 193 | public static function execute() |
| 194 | { |
| 195 | global $globals; |
| 196 | $args = func_get_args(); |
| 197 | if ($globals->mode != 'rw' && !strpos($args[0], 'logger')) { |
| 198 | return; |
| 199 | } |
| 200 | return self::_query(XDB::_prepare($args)); |
| 201 | } |
| 202 | |
| 203 | public static function iterator() |
| 204 | { |
| 205 | return new XOrgDBIterator(self::_prepare(func_get_args())); |
| 206 | } |
| 207 | |
| 208 | public static function iterRow() |
| 209 | { |
| 210 | return new XOrgDBIterator(self::_prepare(func_get_args()), MYSQL_NUM); |
| 211 | } |
| 212 | |
| 213 | private static function findQuery($params, $default = array()) |
| 214 | { |
| 215 | for ($i = 0 ; $i < count($default) ; ++$i) { |
| 216 | $is_query = false; |
| 217 | foreach (array('insert', 'select', 'replace', 'delete', 'update') as $kwd) { |
| 218 | if (stripos($params[0], $kwd) !== false) { |
| 219 | $is_query = true; |
| 220 | break; |
| 221 | } |
| 222 | } |
| 223 | if ($is_query) { |
| 224 | break; |
| 225 | } else { |
| 226 | $default[$i] = array_shift($params); |
| 227 | } |
| 228 | } |
| 229 | return array($default, $params); |
| 230 | } |
| 231 | |
| 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. |
| 235 | */ |
| 236 | public static function fetchAllRow() |
| 237 | { |
| 238 | list($args, $query) = self::findQuery(func_get_args(), array(false, false)); |
| 239 | return self::queryv($query)->fetchAllRow($args[0], $args[1]); |
| 240 | } |
| 241 | |
| 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. |
| 245 | */ |
| 246 | public static function fetchAllAssoc() |
| 247 | { |
| 248 | list($args, $query) = self::findQuery(func_get_args(), array(false, false)); |
| 249 | return self::queryv($query)->fetchAllAssoc($args[0], $args[1]); |
| 250 | } |
| 251 | |
| 252 | public static function fetchOneCell() |
| 253 | { |
| 254 | list($args, $query) = self::findQuery(func_get_args()); |
| 255 | return self::queryv($query)->fetchOneCell(); |
| 256 | } |
| 257 | |
| 258 | public static function fetchOneRow() |
| 259 | { |
| 260 | list($args, $query) = self::findQuery(func_get_args()); |
| 261 | return self::queryv($query)->fetchOneRow(); |
| 262 | } |
| 263 | |
| 264 | public static function fetchOneAssoc() |
| 265 | { |
| 266 | list($args, $query) = self::findQuery(func_get_args()); |
| 267 | return self::queryv($query)->fetchOneAssoc(); |
| 268 | } |
| 269 | |
| 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. |
| 273 | */ |
| 274 | public static function fetchColumn() |
| 275 | { |
| 276 | list($args, $query) = self::findQuery(func_get_args(), array(0)); |
| 277 | return self::queryv($query)->fetchColumn(); |
| 278 | } |
| 279 | |
| 280 | public static function insertId() |
| 281 | { |
| 282 | return self::$mysqli->insert_id; |
| 283 | } |
| 284 | |
| 285 | public static function errno() |
| 286 | { |
| 287 | return self::$mysqli->errno; |
| 288 | } |
| 289 | |
| 290 | public static function error() |
| 291 | { |
| 292 | return self::$mysqli->error; |
| 293 | } |
| 294 | |
| 295 | public static function affectedRows() |
| 296 | { |
| 297 | return self::$mysqli->affected_rows; |
| 298 | } |
| 299 | |
| 300 | public static function escape($var) |
| 301 | { |
| 302 | switch (gettype($var)) { |
| 303 | case 'boolean': |
| 304 | return $var ? 1 : 0; |
| 305 | |
| 306 | case 'integer': |
| 307 | case 'double': |
| 308 | case 'float': |
| 309 | return $var; |
| 310 | |
| 311 | case 'string': |
| 312 | return "'".addslashes($var)."'"; |
| 313 | |
| 314 | case 'NULL': |
| 315 | return 'NULL'; |
| 316 | |
| 317 | case 'object': |
| 318 | if ($var instanceof PlFlagSet) { |
| 319 | return "'" . addslashes($var->flags()) . "'"; |
| 320 | } else { |
| 321 | return "'".addslashes(serialize($var))."'"; |
| 322 | } |
| 323 | |
| 324 | case 'array': |
| 325 | return '(' . implode(', ', array_map(array('XDB', 'escape'), $var)) . ')'; |
| 326 | |
| 327 | default: |
| 328 | die(var_export($var, true).' is not a valid for a database entry'); |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | class XOrgDBResult |
| 334 | { |
| 335 | |
| 336 | private $_res; |
| 337 | |
| 338 | public function __construct($query) |
| 339 | { |
| 340 | $this->_res = XDB::_query($query); |
| 341 | } |
| 342 | |
| 343 | public function free() |
| 344 | { |
| 345 | if ($this->_res) { |
| 346 | $this->_res->free(); |
| 347 | } |
| 348 | unset($this); |
| 349 | } |
| 350 | |
| 351 | protected function _fetchRow() |
| 352 | { |
| 353 | return $this->_res ? $this->_res->fetch_row() : null; |
| 354 | } |
| 355 | |
| 356 | protected function _fetchAssoc() |
| 357 | { |
| 358 | return $this->_res ? $this->_res->fetch_assoc() : null; |
| 359 | } |
| 360 | |
| 361 | public function fetchAllRow($id = false, $keep_array = false) |
| 362 | { |
| 363 | $result = Array(); |
| 364 | if (!$this->_res) { |
| 365 | return $result; |
| 366 | } |
| 367 | while (($data = $this->_res->fetch_row())) { |
| 368 | if ($id !== false) { |
| 369 | $key = $data[$id]; |
| 370 | unset($data[$id]); |
| 371 | if (!$keep_array && count($data) == 1) { |
| 372 | reset($data); |
| 373 | $result[$key] = current($data); |
| 374 | } else { |
| 375 | $result[$key] = $data; |
| 376 | } |
| 377 | } else { |
| 378 | $result[] = $data; |
| 379 | } |
| 380 | } |
| 381 | $this->free(); |
| 382 | return $result; |
| 383 | } |
| 384 | |
| 385 | public function fetchAllAssoc($id = false, $keep_array = false) |
| 386 | { |
| 387 | $result = Array(); |
| 388 | if (!$this->_res) { |
| 389 | return $result; |
| 390 | } |
| 391 | while (($data = $this->_res->fetch_assoc())) { |
| 392 | if ($id !== false) { |
| 393 | $key = $data[$id]; |
| 394 | unset($data[$id]); |
| 395 | if (!$keep_array && count($data) == 1) { |
| 396 | reset($data); |
| 397 | $result[$key] = current($data); |
| 398 | } else { |
| 399 | $result[$key] = $data; |
| 400 | } |
| 401 | } else { |
| 402 | $result[] = $data; |
| 403 | } |
| 404 | } |
| 405 | $this->free(); |
| 406 | return $result; |
| 407 | } |
| 408 | |
| 409 | public function fetchOneAssoc() |
| 410 | { |
| 411 | $tmp = $this->_fetchAssoc(); |
| 412 | $this->free(); |
| 413 | return $tmp; |
| 414 | } |
| 415 | |
| 416 | public function fetchOneRow() |
| 417 | { |
| 418 | $tmp = $this->_fetchRow(); |
| 419 | $this->free(); |
| 420 | return $tmp; |
| 421 | } |
| 422 | |
| 423 | public function fetchOneCell() |
| 424 | { |
| 425 | $tmp = $this->_fetchRow(); |
| 426 | $this->free(); |
| 427 | return $tmp[0]; |
| 428 | } |
| 429 | |
| 430 | public function fetchColumn($key = 0) |
| 431 | { |
| 432 | $res = Array(); |
| 433 | if (is_numeric($key)) { |
| 434 | while($tmp = $this->_fetchRow()) { |
| 435 | $res[] = $tmp[$key]; |
| 436 | } |
| 437 | } else { |
| 438 | while($tmp = $this->_fetchAssoc()) { |
| 439 | $res[] = $tmp[$key]; |
| 440 | } |
| 441 | } |
| 442 | $this->free(); |
| 443 | return $res; |
| 444 | } |
| 445 | |
| 446 | public function fetchOneField() |
| 447 | { |
| 448 | return $this->_res ? $this->_res->fetch_field() : null; |
| 449 | } |
| 450 | |
| 451 | public function fetchFields() |
| 452 | { |
| 453 | $res = array(); |
| 454 | while ($res[] = $this->fetchOneField()); |
| 455 | return $res; |
| 456 | } |
| 457 | |
| 458 | public function numRows() |
| 459 | { |
| 460 | return $this->_res ? $this->_res->num_rows : 0; |
| 461 | } |
| 462 | |
| 463 | public function fieldCount() |
| 464 | { |
| 465 | return $this->_res ? $this->_res->field_count : 0; |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | require_once dirname(__FILE__) . '/pliterator.php'; |
| 470 | |
| 471 | class XOrgDBIterator extends XOrgDBResult implements PlIterator |
| 472 | { |
| 473 | private $_result; |
| 474 | private $_pos; |
| 475 | private $_total; |
| 476 | private $_fpos; |
| 477 | private $_fields; |
| 478 | private $_mode = MYSQL_ASSOC; |
| 479 | |
| 480 | public function __construct($query, $mode = MYSQL_ASSOC) |
| 481 | { |
| 482 | parent::__construct($query); |
| 483 | $this->_pos = 0; |
| 484 | $this->_total = $this->numRows(); |
| 485 | $this->_fpost = 0; |
| 486 | $this->_fields = $this->fieldCount(); |
| 487 | $this->_mode = $mode; |
| 488 | } |
| 489 | |
| 490 | public function next() |
| 491 | { |
| 492 | $this->_pos ++; |
| 493 | if ($this->_pos > $this->_total) { |
| 494 | $this->free(); |
| 495 | unset($this); |
| 496 | return null; |
| 497 | } |
| 498 | return $this->_mode != MYSQL_ASSOC ? $this->_fetchRow() : $this->_fetchAssoc(); |
| 499 | } |
| 500 | |
| 501 | public function first() |
| 502 | { |
| 503 | return $this->_pos == 1; |
| 504 | } |
| 505 | |
| 506 | public function last() |
| 507 | { |
| 508 | return $this->_pos == $this->_total; |
| 509 | } |
| 510 | |
| 511 | public function total() |
| 512 | { |
| 513 | return $this->_total; |
| 514 | } |
| 515 | |
| 516 | public function nextField() |
| 517 | { |
| 518 | $this->_fpos++; |
| 519 | if ($this->_fpos > $this->_fields) { |
| 520 | return null; |
| 521 | } |
| 522 | return $this->fetchOneField(); |
| 523 | } |
| 524 | |
| 525 | public function firstField() |
| 526 | { |
| 527 | return $this->_fpos == 1; |
| 528 | } |
| 529 | |
| 530 | public function lastField() |
| 531 | { |
| 532 | return $this->_fpos == $this->_fields; |
| 533 | } |
| 534 | |
| 535 | public function totalFields() |
| 536 | { |
| 537 | return $this->_fields; |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: |
| 542 | ?> |