Mercurial > hg > rc2
annotate program/lib/Roundcube/rcube_db.php @ 14:abddb304201f
continue slowly cleaning up after move to 8.3
| author | Charlie Root |
|---|---|
| date | Sat, 06 Sep 2025 08:16:01 -0400 |
| parents | aff04b06b685 |
| children | b6a96bdd6b29 |
| rev | line source |
|---|---|
| 0 | 1 <?php |
| 2 | |
| 3 /** | |
| 4 +-----------------------------------------------------------------------+ | |
| 5 | This file is part of the Roundcube Webmail client | | |
| 6 | Copyright (C) 2005-2012, The Roundcube Dev Team | | |
| 7 | | | |
| 8 | Licensed under the GNU General Public License version 3 or | | |
| 9 | any later version with exceptions for skins & plugins. | | |
| 10 | See the README file for a full license statement. | | |
| 11 | | | |
| 12 | PURPOSE: | | |
| 13 | Database wrapper class that implements PHP PDO functions | | |
| 14 +-----------------------------------------------------------------------+ | |
| 15 | Author: Aleksander Machniak <alec@alec.pl> | | |
| 16 +-----------------------------------------------------------------------+ | |
| 17 */ | |
| 18 | |
| 19 /** | |
| 20 * Database independent query interface. | |
| 21 * This is a wrapper for the PHP PDO. | |
| 22 * | |
| 23 * @package Framework | |
| 24 * @subpackage Database | |
| 25 */ | |
| 26 class rcube_db | |
| 27 { | |
| 28 public $db_provider; | |
| 14 | 29 |
| 30 protected $db_pconn; | |
| 0 | 31 |
| 32 protected $db_dsnw; // DSN for write operations | |
| 33 protected $db_dsnr; // DSN for read operations | |
| 14 | 34 protected $db_dsnr_array; |
| 35 protected $db_dsnw_array; | |
| 0 | 36 protected $db_connected = false; // Already connected ? |
| 37 protected $db_mode; // Connection mode | |
| 38 protected $dbh; // Connection handle | |
| 39 protected $dbhs = array(); | |
| 40 protected $table_connections = array(); | |
| 41 | |
| 42 protected $db_error = false; | |
| 43 protected $db_error_msg = ''; | |
| 44 protected $conn_failure = false; | |
| 45 protected $db_index = 0; | |
| 46 protected $last_result; | |
| 47 protected $tables; | |
| 48 protected $variables; | |
| 49 | |
| 50 protected $options = array( | |
| 51 // column/table quotes | |
| 52 'identifier_start' => '"', | |
| 53 'identifier_end' => '"', | |
| 54 // date/time input format | |
| 55 'datetime_format' => 'Y-m-d H:i:s', | |
| 56 ); | |
| 57 | |
| 58 const DEBUG_LINE_LENGTH = 4096; | |
| 59 const DEFAULT_QUOTE = '`'; | |
| 60 | |
| 61 /** | |
| 62 * Factory, returns driver-specific instance of the class | |
| 63 * | |
| 64 * @param string $db_dsnw DSN for read/write operations | |
| 65 * @param string $db_dsnr Optional DSN for read only operations | |
| 66 * @param bool $pconn Enables persistent connections | |
| 67 * | |
| 68 * @return rcube_db Object instance | |
| 69 */ | |
| 70 public static function factory($db_dsnw, $db_dsnr = '', $pconn = false) | |
| 71 { | |
| 72 $driver = strtolower(substr($db_dsnw, 0, strpos($db_dsnw, ':'))); | |
| 73 $driver_map = array( | |
| 74 'sqlite2' => 'sqlite', | |
| 75 'sybase' => 'mssql', | |
| 76 'dblib' => 'mssql', | |
| 77 'mysqli' => 'mysql', | |
| 78 'oci' => 'oracle', | |
| 79 'oci8' => 'oracle', | |
| 80 ); | |
| 81 | |
| 82 $driver = isset($driver_map[$driver]) ? $driver_map[$driver] : $driver; | |
| 83 $class = "rcube_db_$driver"; | |
| 84 | |
| 85 if (!$driver || !class_exists($class)) { | |
| 86 rcube::raise_error(array('code' => 600, 'type' => 'db', | |
| 87 'line' => __LINE__, 'file' => __FILE__, | |
| 88 'message' => "Configuration error. Unsupported database driver: $driver"), | |
| 89 true, true); | |
| 90 } | |
| 91 | |
| 92 return new $class($db_dsnw, $db_dsnr, $pconn); | |
| 93 } | |
| 94 | |
| 95 /** | |
| 96 * Object constructor | |
| 97 * | |
| 98 * @param string $db_dsnw DSN for read/write operations | |
| 99 * @param string $db_dsnr Optional DSN for read only operations | |
| 100 * @param bool $pconn Enables persistent connections | |
| 101 */ | |
| 102 public function __construct($db_dsnw, $db_dsnr = '', $pconn = false) | |
| 103 { | |
| 104 if (empty($db_dsnr)) { | |
| 105 $db_dsnr = $db_dsnw; | |
| 106 } | |
| 107 | |
| 108 $this->db_dsnw = $db_dsnw; | |
| 109 $this->db_dsnr = $db_dsnr; | |
| 110 $this->db_pconn = $pconn; | |
| 111 | |
| 112 $this->db_dsnw_array = self::parse_dsn($db_dsnw); | |
| 113 $this->db_dsnr_array = self::parse_dsn($db_dsnr); | |
| 114 | |
| 115 $config = rcube::get_instance()->config; | |
| 116 | |
| 117 $this->options['table_prefix'] = $config->get('db_prefix'); | |
| 118 $this->options['dsnw_noread'] = $config->get('db_dsnw_noread', false); | |
| 119 $this->options['table_dsn_map'] = array_map(array($this, 'table_name'), $config->get('db_table_dsn', array())); | |
| 120 } | |
| 121 | |
| 122 /** | |
| 123 * Connect to specific database | |
| 124 * | |
| 125 * @param array $dsn DSN for DB connections | |
| 126 * @param string $mode Connection mode (r|w) | |
| 127 */ | |
| 128 protected function dsn_connect($dsn, $mode) | |
| 129 { | |
| 130 $this->db_error = false; | |
| 131 $this->db_error_msg = null; | |
| 132 | |
| 133 // return existing handle | |
| 134 if ($this->dbhs[$mode]) { | |
| 135 $this->dbh = $this->dbhs[$mode]; | |
| 136 $this->db_mode = $mode; | |
| 137 return $this->dbh; | |
| 138 } | |
| 139 | |
| 140 // connect to database | |
| 141 if ($dbh = $this->conn_create($dsn)) { | |
| 142 $this->dbh = $dbh; | |
| 143 $this->dbhs[$mode] = $dbh; | |
| 144 $this->db_mode = $mode; | |
| 145 $this->db_connected = true; | |
| 146 } | |
| 147 } | |
| 148 | |
| 149 /** | |
| 150 * Create PDO connection | |
| 151 */ | |
| 152 protected function conn_create($dsn) | |
| 153 { | |
| 154 // Get database specific connection options | |
| 155 $dsn_string = $this->dsn_string($dsn); | |
| 156 $dsn_options = $this->dsn_options($dsn); | |
| 157 | |
| 158 // Connect | |
| 159 try { | |
| 160 // with this check we skip fatal error on PDO object creation | |
| 161 if (!class_exists('PDO', false)) { | |
| 162 throw new Exception('PDO extension not loaded. See http://php.net/manual/en/intro.pdo.php'); | |
| 163 } | |
| 164 | |
| 165 $this->conn_prepare($dsn); | |
| 166 | |
| 167 $dbh = new PDO($dsn_string, $dsn['username'], $dsn['password'], $dsn_options); | |
| 168 | |
| 169 // don't throw exceptions or warnings | |
| 170 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); | |
| 171 | |
| 172 $this->conn_configure($dsn, $dbh); | |
| 173 } | |
| 174 catch (Exception $e) { | |
| 175 $this->db_error = true; | |
| 176 $this->db_error_msg = $e->getMessage(); | |
| 177 | |
| 178 rcube::raise_error(array('code' => 500, 'type' => 'db', | |
| 179 'line' => __LINE__, 'file' => __FILE__, | |
| 180 'message' => $this->db_error_msg), true, false); | |
| 181 | |
| 182 return null; | |
| 183 } | |
| 184 | |
| 185 return $dbh; | |
| 186 } | |
| 187 | |
| 188 /** | |
| 189 * Driver-specific preparation of database connection | |
| 190 * | |
| 191 * @param array $dsn DSN for DB connections | |
| 192 */ | |
| 193 protected function conn_prepare($dsn) | |
| 194 { | |
| 195 } | |
| 196 | |
| 197 /** | |
| 198 * Driver-specific configuration of database connection | |
| 199 * | |
| 200 * @param array $dsn DSN for DB connections | |
| 201 * @param PDO $dbh Connection handler | |
| 202 */ | |
| 203 protected function conn_configure($dsn, $dbh) | |
| 204 { | |
| 205 } | |
| 206 | |
| 207 /** | |
| 208 * Connect to appropriate database depending on the operation | |
| 209 * | |
| 210 * @param string $mode Connection mode (r|w) | |
| 211 * @param boolean $force Enforce using the given mode | |
| 212 */ | |
| 213 public function db_connect($mode, $force = false) | |
| 214 { | |
| 215 // previous connection failed, don't attempt to connect again | |
| 216 if ($this->conn_failure) { | |
| 217 return; | |
| 218 } | |
| 219 | |
| 220 // no replication | |
| 221 if ($this->db_dsnw == $this->db_dsnr) { | |
| 222 $mode = 'w'; | |
| 223 } | |
| 224 | |
| 225 // Already connected | |
| 226 if ($this->db_connected) { | |
| 227 // connected to db with the same or "higher" mode (if allowed) | |
| 228 if ($this->db_mode == $mode || $this->db_mode == 'w' && !$force && !$this->options['dsnw_noread']) { | |
| 229 return; | |
| 230 } | |
| 231 } | |
| 232 | |
| 233 $dsn = ($mode == 'r') ? $this->db_dsnr_array : $this->db_dsnw_array; | |
| 234 $this->dsn_connect($dsn, $mode); | |
| 235 | |
| 236 // use write-master when read-only fails | |
| 237 if (!$this->db_connected && $mode == 'r' && $this->is_replicated()) { | |
| 238 $this->dsn_connect($this->db_dsnw_array, 'w'); | |
| 239 } | |
| 240 | |
| 241 $this->conn_failure = !$this->db_connected; | |
| 242 } | |
| 243 | |
| 244 /** | |
| 245 * Analyze the given SQL statement and select the appropriate connection to use | |
| 246 */ | |
| 247 protected function dsn_select($query) | |
| 248 { | |
| 249 // no replication | |
| 250 if ($this->db_dsnw == $this->db_dsnr) { | |
| 251 return 'w'; | |
| 252 } | |
| 253 | |
| 254 // Read or write ? | |
| 255 $mode = preg_match('/^(select|show|set)/i', $query) ? 'r' : 'w'; | |
| 256 | |
| 257 $start = '[' . $this->options['identifier_start'] . self::DEFAULT_QUOTE . ']'; | |
| 258 $end = '[' . $this->options['identifier_end'] . self::DEFAULT_QUOTE . ']'; | |
| 259 $regex = '/(?:^|\s)(from|update|into|join)\s+'.$start.'?([a-z0-9._]+)'.$end.'?\s+/i'; | |
| 260 | |
| 261 // find tables involved in this query | |
| 262 if (preg_match_all($regex, $query, $matches, PREG_SET_ORDER)) { | |
| 263 foreach ($matches as $m) { | |
| 264 $table = $m[2]; | |
| 265 | |
| 266 // always use direct mapping | |
| 267 if ($this->options['table_dsn_map'][$table]) { | |
| 268 $mode = $this->options['table_dsn_map'][$table]; | |
| 269 break; // primary table rules | |
| 270 } | |
| 271 else if ($mode == 'r') { | |
| 272 // connected to db with the same or "higher" mode for this table | |
| 273 $db_mode = $this->table_connections[$table]; | |
| 274 if ($db_mode == 'w' && !$this->options['dsnw_noread']) { | |
| 275 $mode = $db_mode; | |
| 276 } | |
| 277 } | |
| 278 } | |
| 279 | |
| 280 // remember mode chosen (for primary table) | |
| 281 $table = $matches[0][2]; | |
| 282 $this->table_connections[$table] = $mode; | |
| 283 } | |
| 284 | |
| 285 return $mode; | |
| 286 } | |
| 287 | |
| 288 /** | |
| 289 * Activate/deactivate debug mode | |
| 290 * | |
| 291 * @param boolean $dbg True if SQL queries should be logged | |
| 292 */ | |
| 293 public function set_debug($dbg = true) | |
| 294 { | |
| 295 $this->options['debug_mode'] = $dbg; | |
| 296 } | |
| 297 | |
| 298 /** | |
| 299 * Writes debug information/query to 'sql' log file | |
| 300 * | |
| 301 * @param string $query SQL query | |
| 302 */ | |
| 303 protected function debug($query) | |
| 304 { | |
| 305 if ($this->options['debug_mode']) { | |
| 306 if (($len = strlen($query)) > self::DEBUG_LINE_LENGTH) { | |
| 307 $diff = $len - self::DEBUG_LINE_LENGTH; | |
| 308 $query = substr($query, 0, self::DEBUG_LINE_LENGTH) | |
| 309 . "... [truncated $diff bytes]"; | |
| 310 } | |
| 311 rcube::write_log('sql', '[' . (++$this->db_index) . '] ' . $query . ';'); | |
| 312 } | |
| 313 } | |
| 314 | |
| 315 /** | |
| 316 * Getter for error state | |
| 317 * | |
| 318 * @param mixed $result Optional query result | |
| 319 * | |
| 320 * @return string Error message | |
| 321 */ | |
| 322 public function is_error($result = null) | |
| 323 { | |
| 324 if ($result !== null) { | |
| 325 return $result === false ? $this->db_error_msg : null; | |
| 326 } | |
| 327 | |
| 328 return $this->db_error ? $this->db_error_msg : null; | |
| 329 } | |
| 330 | |
| 331 /** | |
| 332 * Connection state checker | |
| 333 * | |
| 334 * @return boolean True if in connected state | |
| 335 */ | |
| 336 public function is_connected() | |
| 337 { | |
| 338 return !is_object($this->dbh) ? false : $this->db_connected; | |
| 339 } | |
| 340 | |
| 341 /** | |
| 342 * Is database replication configured? | |
| 343 * | |
| 344 * @return bool Returns true if dsnw != dsnr | |
| 345 */ | |
| 346 public function is_replicated() | |
| 347 { | |
| 348 return !empty($this->db_dsnr) && $this->db_dsnw != $this->db_dsnr; | |
| 349 } | |
| 350 | |
| 351 /** | |
| 352 * Get database runtime variables | |
| 353 * | |
| 354 * @param string $varname Variable name | |
| 355 * @param mixed $default Default value if variable is not set | |
| 356 * | |
| 357 * @return mixed Variable value or default | |
| 358 */ | |
| 359 public function get_variable($varname, $default = null) | |
| 360 { | |
| 361 // to be implemented by driver class | |
| 362 return rcube::get_instance()->config->get('db_' . $varname, $default); | |
| 363 } | |
| 364 | |
| 365 /** | |
| 366 * Execute a SQL query | |
| 367 * | |
| 368 * @param string SQL query to execute | |
| 369 * @param mixed Values to be inserted in query | |
| 370 * | |
| 371 * @return number Query handle identifier | |
| 372 */ | |
| 373 public function query() | |
| 374 { | |
| 375 $params = func_get_args(); | |
| 376 $query = array_shift($params); | |
| 377 | |
| 378 // Support one argument of type array, instead of n arguments | |
| 379 if (count($params) == 1 && is_array($params[0])) { | |
| 380 $params = $params[0]; | |
| 381 } | |
| 382 | |
| 383 return $this->_query($query, 0, 0, $params); | |
| 384 } | |
| 385 | |
| 386 /** | |
| 387 * Execute a SQL query with limits | |
| 388 * | |
| 389 * @param string SQL query to execute | |
| 390 * @param int Offset for LIMIT statement | |
| 391 * @param int Number of rows for LIMIT statement | |
| 392 * @param mixed Values to be inserted in query | |
| 393 * | |
| 394 * @return PDOStatement|bool Query handle or False on error | |
| 395 */ | |
| 396 public function limitquery() | |
| 397 { | |
| 398 $params = func_get_args(); | |
| 399 $query = array_shift($params); | |
| 400 $offset = array_shift($params); | |
| 401 $numrows = array_shift($params); | |
| 402 | |
| 403 return $this->_query($query, $offset, $numrows, $params); | |
| 404 } | |
| 405 | |
| 406 /** | |
| 407 * Execute a SQL query with limits | |
| 408 * | |
| 409 * @param string $query SQL query to execute | |
| 410 * @param int $offset Offset for LIMIT statement | |
| 411 * @param int $numrows Number of rows for LIMIT statement | |
| 412 * @param array $params Values to be inserted in query | |
| 413 * | |
| 414 * @return PDOStatement|bool Query handle or False on error | |
| 415 */ | |
| 416 protected function _query($query, $offset, $numrows, $params) | |
| 417 { | |
| 418 $query = ltrim($query); | |
| 419 | |
| 420 $this->db_connect($this->dsn_select($query), true); | |
| 421 | |
| 422 // check connection before proceeding | |
| 423 if (!$this->is_connected()) { | |
| 424 return $this->last_result = false; | |
| 425 } | |
| 426 | |
| 427 if ($numrows || $offset) { | |
| 428 $query = $this->set_limit($query, $numrows, $offset); | |
| 429 } | |
| 430 | |
| 431 // replace self::DEFAULT_QUOTE with driver-specific quoting | |
| 432 $query = $this->query_parse($query); | |
| 433 | |
| 434 // Because in Roundcube we mostly use queries that are | |
| 435 // executed only once, we will not use prepared queries | |
| 436 $pos = 0; | |
| 437 $idx = 0; | |
| 438 | |
| 439 if (count($params)) { | |
| 440 while ($pos = strpos($query, '?', $pos)) { | |
| 441 if ($query[$pos+1] == '?') { // skip escaped '?' | |
| 442 $pos += 2; | |
| 443 } | |
| 444 else { | |
| 445 $val = $this->quote($params[$idx++]); | |
| 446 unset($params[$idx-1]); | |
| 447 $query = substr_replace($query, $val, $pos, 1); | |
| 448 $pos += strlen($val); | |
| 449 } | |
| 450 } | |
| 451 } | |
| 452 | |
| 453 $query = rtrim($query, " \t\n\r\0\x0B;"); | |
| 454 | |
| 455 // replace escaped '?' and quotes back to normal, see self::quote() | |
| 456 $query = str_replace( | |
| 457 array('??', self::DEFAULT_QUOTE.self::DEFAULT_QUOTE), | |
| 458 array('?', self::DEFAULT_QUOTE), | |
| 459 $query | |
| 460 ); | |
| 461 | |
| 462 // log query | |
| 463 $this->debug($query); | |
| 464 | |
| 465 return $this->query_execute($query); | |
| 466 } | |
| 467 | |
| 468 /** | |
| 469 * Query execution | |
| 470 */ | |
| 471 protected function query_execute($query) | |
| 472 { | |
| 473 // destroy reference to previous result, required for SQLite driver (#1488874) | |
| 474 $this->last_result = null; | |
| 475 $this->db_error_msg = null; | |
| 476 | |
| 477 // send query | |
| 478 $result = $this->dbh->query($query); | |
| 479 | |
| 480 if ($result === false) { | |
| 481 $result = $this->handle_error($query); | |
| 482 } | |
| 483 | |
| 484 return $this->last_result = $result; | |
| 485 } | |
| 486 | |
| 487 /** | |
| 488 * Parse SQL query and replace identifier quoting | |
| 489 * | |
| 490 * @param string $query SQL query | |
| 491 * | |
| 492 * @return string SQL query | |
| 493 */ | |
| 494 protected function query_parse($query) | |
| 495 { | |
| 496 $start = $this->options['identifier_start']; | |
| 497 $end = $this->options['identifier_end']; | |
| 498 $quote = self::DEFAULT_QUOTE; | |
| 499 | |
| 500 if ($start == $quote) { | |
| 501 return $query; | |
| 502 } | |
| 503 | |
| 504 $pos = 0; | |
| 505 $in = false; | |
| 506 | |
| 507 while ($pos = strpos($query, $quote, $pos)) { | |
| 508 if ($query[$pos+1] == $quote) { // skip escaped quote | |
| 509 $pos += 2; | |
| 510 } | |
| 511 else { | |
| 512 if ($in) { | |
| 513 $q = $end; | |
| 514 $in = false; | |
| 515 } | |
| 516 else { | |
| 517 $q = $start; | |
| 518 $in = true; | |
| 519 } | |
| 520 | |
| 521 $query = substr_replace($query, $q, $pos, 1); | |
| 522 $pos++; | |
| 523 } | |
| 524 } | |
| 525 | |
| 526 return $query; | |
| 527 } | |
| 528 | |
| 529 /** | |
| 530 * Helper method to handle DB errors. | |
| 531 * This by default logs the error but could be overridden by a driver implementation | |
| 532 * | |
| 533 * @param string $query Query that triggered the error | |
| 534 * | |
| 535 * @return mixed Result to be stored and returned | |
| 536 */ | |
| 537 protected function handle_error($query) | |
| 538 { | |
| 539 $error = $this->dbh->errorInfo(); | |
| 540 | |
| 541 if (empty($this->options['ignore_key_errors']) || !in_array($error[0], array('23000', '23505'))) { | |
| 542 $this->db_error = true; | |
| 543 $this->db_error_msg = sprintf('[%s] %s', $error[1], $error[2]); | |
| 544 | |
| 545 if (empty($this->options['ignore_errors'])) { | |
| 546 rcube::raise_error(array( | |
| 547 'code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__, | |
| 548 'message' => $this->db_error_msg . " (SQL Query: $query)" | |
| 549 ), true, false); | |
| 550 } | |
| 551 } | |
| 552 | |
| 553 return false; | |
| 554 } | |
| 555 | |
| 556 /** | |
| 557 * Get number of affected rows for the last query | |
| 558 * | |
| 559 * @param mixed $result Optional query handle | |
| 560 * | |
| 561 * @return int Number of (matching) rows | |
| 562 */ | |
| 563 public function affected_rows($result = null) | |
| 564 { | |
| 565 if ($result || ($result === null && ($result = $this->last_result))) { | |
| 566 if ($result !== true) { | |
| 567 return $result->rowCount(); | |
| 568 } | |
| 569 } | |
| 570 | |
| 571 return 0; | |
| 572 } | |
| 573 | |
| 574 /** | |
| 575 * Get number of rows for a SQL query | |
| 576 * If no query handle is specified, the last query will be taken as reference | |
| 577 * | |
| 578 * @param mixed $result Optional query handle | |
| 579 * | |
| 580 * @return mixed Number of rows or false on failure | |
| 581 * @deprecated This method shows very poor performance and should be avoided. | |
| 582 */ | |
| 583 public function num_rows($result = null) | |
| 584 { | |
| 585 if (($result || ($result === null && ($result = $this->last_result))) && $result !== true) { | |
| 586 // repeat query with SELECT COUNT(*) ... | |
| 587 if (preg_match('/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/ims', $result->queryString, $m)) { | |
| 588 $query = $this->dbh->query('SELECT COUNT(*) FROM ' . $m[1], PDO::FETCH_NUM); | |
| 589 return $query ? intval($query->fetchColumn(0)) : false; | |
| 590 } | |
| 591 else { | |
| 592 $num = count($result->fetchAll()); | |
| 593 $result->execute(); // re-execute query because there's no seek(0) | |
| 594 return $num; | |
| 595 } | |
| 596 } | |
| 597 | |
| 598 return false; | |
| 599 } | |
| 600 | |
| 601 /** | |
| 602 * Get last inserted record ID | |
| 603 * | |
| 604 * @param string $table Table name (to find the incremented sequence) | |
| 605 * | |
| 606 * @return mixed ID or false on failure | |
| 607 */ | |
| 608 public function insert_id($table = '') | |
| 609 { | |
| 610 if (!$this->db_connected || $this->db_mode == 'r') { | |
| 611 return false; | |
| 612 } | |
| 613 | |
| 614 if ($table) { | |
| 615 // resolve table name | |
| 616 $table = $this->table_name($table); | |
| 617 } | |
| 618 | |
| 619 $id = $this->dbh->lastInsertId($table); | |
| 620 | |
| 621 return $id; | |
| 622 } | |
| 623 | |
| 624 /** | |
| 625 * Get an associative array for one row | |
| 626 * If no query handle is specified, the last query will be taken as reference | |
| 627 * | |
| 628 * @param mixed $result Optional query handle | |
| 629 * | |
| 630 * @return mixed Array with col values or false on failure | |
| 631 */ | |
| 632 public function fetch_assoc($result = null) | |
| 633 { | |
| 634 return $this->_fetch_row($result, PDO::FETCH_ASSOC); | |
| 635 } | |
| 636 | |
| 637 /** | |
| 638 * Get an index array for one row | |
| 639 * If no query handle is specified, the last query will be taken as reference | |
| 640 * | |
| 641 * @param mixed $result Optional query handle | |
| 642 * | |
| 643 * @return mixed Array with col values or false on failure | |
| 644 */ | |
| 645 public function fetch_array($result = null) | |
| 646 { | |
| 647 return $this->_fetch_row($result, PDO::FETCH_NUM); | |
| 648 } | |
| 649 | |
| 650 /** | |
| 651 * Get col values for a result row | |
| 652 * | |
| 653 * @param mixed $result Optional query handle | |
| 654 * @param int $mode Fetch mode identifier | |
| 655 * | |
| 656 * @return mixed Array with col values or false on failure | |
| 657 */ | |
| 658 protected function _fetch_row($result, $mode) | |
| 659 { | |
| 660 if ($result || ($result === null && ($result = $this->last_result))) { | |
| 661 if ($result !== true) { | |
| 662 return $result->fetch($mode); | |
| 663 } | |
| 664 } | |
| 665 | |
| 666 return false; | |
| 667 } | |
| 668 | |
| 669 /** | |
| 670 * Adds LIMIT,OFFSET clauses to the query | |
| 671 * | |
| 672 * @param string $query SQL query | |
| 673 * @param int $limit Number of rows | |
| 674 * @param int $offset Offset | |
| 675 * | |
| 676 * @return string SQL query | |
| 677 */ | |
| 678 protected function set_limit($query, $limit = 0, $offset = 0) | |
| 679 { | |
| 680 if ($limit) { | |
| 681 $query .= ' LIMIT ' . intval($limit); | |
| 682 } | |
| 683 | |
| 684 if ($offset) { | |
| 685 $query .= ' OFFSET ' . intval($offset); | |
| 686 } | |
| 687 | |
| 688 return $query; | |
| 689 } | |
| 690 | |
| 691 /** | |
| 692 * Returns list of tables in a database | |
| 693 * | |
| 694 * @return array List of all tables of the current database | |
| 695 */ | |
| 696 public function list_tables() | |
| 697 { | |
| 698 // get tables if not cached | |
| 699 if ($this->tables === null) { | |
| 700 $q = $this->query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES" | |
| 701 . " WHERE TABLE_TYPE = 'BASE TABLE'" | |
| 702 . " ORDER BY TABLE_NAME"); | |
| 703 | |
| 704 $this->tables = $q ? $q->fetchAll(PDO::FETCH_COLUMN, 0) : array(); | |
| 705 } | |
| 706 | |
| 707 return $this->tables; | |
| 708 } | |
| 709 | |
| 710 /** | |
| 711 * Returns list of columns in database table | |
| 712 * | |
| 713 * @param string $table Table name | |
| 714 * | |
| 715 * @return array List of table cols | |
| 716 */ | |
| 717 public function list_cols($table) | |
| 718 { | |
| 719 $q = $this->query('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?', | |
| 720 array($table)); | |
| 721 | |
| 722 if ($q) { | |
| 723 return $q->fetchAll(PDO::FETCH_COLUMN, 0); | |
| 724 } | |
| 725 | |
| 726 return array(); | |
| 727 } | |
| 728 | |
| 729 /** | |
| 730 * Start transaction | |
| 731 * | |
| 732 * @return bool True on success, False on failure | |
| 733 */ | |
| 734 public function startTransaction() | |
| 735 { | |
| 736 $this->db_connect('w', true); | |
| 737 | |
| 738 // check connection before proceeding | |
| 739 if (!$this->is_connected()) { | |
| 740 return $this->last_result = false; | |
| 741 } | |
| 742 | |
| 743 $this->debug('BEGIN TRANSACTION'); | |
| 744 | |
| 745 return $this->last_result = $this->dbh->beginTransaction(); | |
| 746 } | |
| 747 | |
| 748 /** | |
| 749 * Commit transaction | |
| 750 * | |
| 751 * @return bool True on success, False on failure | |
| 752 */ | |
| 753 public function endTransaction() | |
| 754 { | |
| 755 $this->db_connect('w', true); | |
| 756 | |
| 757 // check connection before proceeding | |
| 758 if (!$this->is_connected()) { | |
| 759 return $this->last_result = false; | |
| 760 } | |
| 761 | |
| 762 $this->debug('COMMIT TRANSACTION'); | |
| 763 | |
| 764 return $this->last_result = $this->dbh->commit(); | |
| 765 } | |
| 766 | |
| 767 /** | |
| 768 * Rollback transaction | |
| 769 * | |
| 770 * @return bool True on success, False on failure | |
| 771 */ | |
| 772 public function rollbackTransaction() | |
| 773 { | |
| 774 $this->db_connect('w', true); | |
| 775 | |
| 776 // check connection before proceeding | |
| 777 if (!$this->is_connected()) { | |
| 778 return $this->last_result = false; | |
| 779 } | |
| 780 | |
| 781 $this->debug('ROLLBACK TRANSACTION'); | |
| 782 | |
| 783 return $this->last_result = $this->dbh->rollBack(); | |
| 784 } | |
| 785 | |
| 786 /** | |
| 787 * Release resources related to the last query result. | |
| 788 * When we know we don't need to access the last query result we can destroy it | |
| 789 * and release memory. Useful especially if the query returned big chunk of data. | |
| 790 */ | |
| 791 public function reset() | |
| 792 { | |
| 793 $this->last_result = null; | |
| 794 } | |
| 795 | |
| 796 /** | |
| 797 * Terminate database connection. | |
| 798 */ | |
| 799 public function closeConnection() | |
| 800 { | |
| 801 $this->db_connected = false; | |
| 802 $this->db_index = 0; | |
| 803 | |
| 804 // release statement and connection resources | |
| 805 $this->last_result = null; | |
| 806 $this->dbh = null; | |
| 807 $this->dbhs = array(); | |
| 808 } | |
| 809 | |
| 810 /** | |
| 811 * Formats input so it can be safely used in a query | |
| 812 * | |
| 813 * @param mixed $input Value to quote | |
| 814 * @param string $type Type of data (integer, bool, ident) | |
| 815 * | |
| 816 * @return string Quoted/converted string for use in query | |
| 817 */ | |
| 818 public function quote($input, $type = null) | |
| 819 { | |
| 820 // handle int directly for better performance | |
| 821 if ($type == 'integer' || $type == 'int') { | |
| 822 return intval($input); | |
| 823 } | |
| 824 | |
| 825 if (is_null($input)) { | |
| 826 return 'NULL'; | |
| 827 } | |
| 828 | |
| 829 if ($input instanceof DateTime) { | |
| 830 return $this->quote($input->format($this->options['datetime_format'])); | |
| 831 } | |
| 832 | |
| 833 if ($type == 'ident') { | |
| 834 return $this->quote_identifier($input); | |
| 835 } | |
| 836 | |
| 837 // create DB handle if not available | |
| 838 if (!$this->dbh) { | |
| 839 $this->db_connect('r'); | |
| 840 } | |
| 841 | |
| 842 if ($this->dbh) { | |
| 843 $map = array( | |
| 844 'bool' => PDO::PARAM_BOOL, | |
| 845 'integer' => PDO::PARAM_INT, | |
| 846 ); | |
| 847 | |
| 848 $type = isset($map[$type]) ? $map[$type] : PDO::PARAM_STR; | |
| 849 | |
| 850 return strtr($this->dbh->quote($input, $type), | |
| 851 // escape ? and ` | |
| 852 array('?' => '??', self::DEFAULT_QUOTE => self::DEFAULT_QUOTE.self::DEFAULT_QUOTE) | |
| 853 ); | |
| 854 } | |
| 855 | |
| 856 return 'NULL'; | |
| 857 } | |
| 858 | |
| 859 /** | |
| 860 * Escapes a string so it can be safely used in a query | |
| 861 * | |
| 862 * @param string $str A string to escape | |
| 863 * | |
| 864 * @return string Escaped string for use in a query | |
| 865 */ | |
| 866 public function escape($str) | |
| 867 { | |
| 868 if (is_null($str)) { | |
| 869 return 'NULL'; | |
| 870 } | |
| 871 | |
| 872 return substr($this->quote($str), 1, -1); | |
| 873 } | |
| 874 | |
| 875 /** | |
| 876 * Quotes a string so it can be safely used as a table or column name | |
| 877 * | |
| 878 * @param string $str Value to quote | |
| 879 * | |
| 880 * @return string Quoted string for use in query | |
| 881 * @deprecated Replaced by rcube_db::quote_identifier | |
| 882 * @see rcube_db::quote_identifier | |
| 883 */ | |
| 884 public function quoteIdentifier($str) | |
| 885 { | |
| 886 return $this->quote_identifier($str); | |
| 887 } | |
| 888 | |
| 889 /** | |
| 890 * Escapes a string so it can be safely used in a query | |
| 891 * | |
| 892 * @param string $str A string to escape | |
| 893 * | |
| 894 * @return string Escaped string for use in a query | |
| 895 * @deprecated Replaced by rcube_db::escape | |
| 896 * @see rcube_db::escape | |
| 897 */ | |
| 898 public function escapeSimple($str) | |
| 899 { | |
| 900 return $this->escape($str); | |
| 901 } | |
| 902 | |
| 903 /** | |
| 904 * Quotes a string so it can be safely used as a table or column name | |
| 905 * | |
| 906 * @param string $str Value to quote | |
| 907 * | |
| 908 * @return string Quoted string for use in query | |
| 909 */ | |
| 910 public function quote_identifier($str) | |
| 911 { | |
| 912 $start = $this->options['identifier_start']; | |
| 913 $end = $this->options['identifier_end']; | |
| 914 $name = array(); | |
| 915 | |
| 916 foreach (explode('.', $str) as $elem) { | |
| 917 $elem = str_replace(array($start, $end), '', $elem); | |
| 918 $name[] = $start . $elem . $end; | |
| 919 } | |
| 920 | |
|
11
aff04b06b685
various small fixes from upgrades to PHP and/or hangover from fix to apt-get overwrite at beginning of the year somehow
Charlie Root
parents:
0
diff
changeset
|
921 return implode('.',$name); |
| 0 | 922 } |
| 923 | |
| 924 /** | |
| 925 * Return SQL function for current time and date | |
| 926 * | |
| 927 * @param int $interval Optional interval (in seconds) to add/subtract | |
| 928 * | |
| 929 * @return string SQL function to use in query | |
| 930 */ | |
| 931 public function now($interval = 0) | |
| 932 { | |
| 933 if ($interval) { | |
| 934 $add = ' ' . ($interval > 0 ? '+' : '-') . ' INTERVAL '; | |
| 935 $add .= $interval > 0 ? intval($interval) : intval($interval) * -1; | |
| 936 $add .= ' SECOND'; | |
| 937 } | |
| 938 | |
| 939 return "now()" . $add; | |
| 940 } | |
| 941 | |
| 942 /** | |
| 943 * Return list of elements for use with SQL's IN clause | |
| 944 * | |
| 945 * @param array $arr Input array | |
| 946 * @param string $type Type of data (integer, bool, ident) | |
| 947 * | |
| 948 * @return string Comma-separated list of quoted values for use in query | |
| 949 */ | |
| 950 public function array2list($arr, $type = null) | |
| 951 { | |
| 952 if (!is_array($arr)) { | |
| 953 return $this->quote($arr, $type); | |
| 954 } | |
| 955 | |
| 956 foreach ($arr as $idx => $item) { | |
| 957 $arr[$idx] = $this->quote($item, $type); | |
| 958 } | |
| 959 | |
| 960 return implode(',', $arr); | |
| 961 } | |
| 962 | |
| 963 /** | |
| 964 * Return SQL statement to convert a field value into a unix timestamp | |
| 965 * | |
| 966 * This method is deprecated and should not be used anymore due to limitations | |
| 967 * of timestamp functions in Mysql (year 2038 problem) | |
| 968 * | |
| 969 * @param string $field Field name | |
| 970 * | |
| 971 * @return string SQL statement to use in query | |
| 972 * @deprecated | |
| 973 */ | |
| 974 public function unixtimestamp($field) | |
| 975 { | |
| 976 return "UNIX_TIMESTAMP($field)"; | |
| 977 } | |
| 978 | |
| 979 /** | |
| 980 * Return SQL statement to convert from a unix timestamp | |
| 981 * | |
| 982 * @param int $timestamp Unix timestamp | |
| 983 * | |
| 984 * @return string Date string in db-specific format | |
| 985 * @deprecated | |
| 986 */ | |
| 987 public function fromunixtime($timestamp) | |
| 988 { | |
| 989 return $this->quote(date($this->options['datetime_format'], $timestamp)); | |
| 990 } | |
| 991 | |
| 992 /** | |
| 993 * Return SQL statement for case insensitive LIKE | |
| 994 * | |
| 995 * @param string $column Field name | |
| 996 * @param string $value Search value | |
| 997 * | |
| 998 * @return string SQL statement to use in query | |
| 999 */ | |
| 1000 public function ilike($column, $value) | |
| 1001 { | |
| 1002 return $this->quote_identifier($column).' LIKE '.$this->quote($value); | |
| 1003 } | |
| 1004 | |
| 1005 /** | |
| 1006 * Abstract SQL statement for value concatenation | |
| 1007 * | |
| 1008 * @return string SQL statement to be used in query | |
| 1009 */ | |
| 1010 public function concat(/* col1, col2, ... */) | |
| 1011 { | |
| 1012 $args = func_get_args(); | |
| 1013 if (is_array($args[0])) { | |
| 1014 $args = $args[0]; | |
| 1015 } | |
| 1016 | |
| 1017 return '(' . join(' || ', $args) . ')'; | |
| 1018 } | |
| 1019 | |
| 1020 /** | |
| 1021 * Encodes non-UTF-8 characters in string/array/object (recursive) | |
| 1022 * | |
| 1023 * @param mixed $input Data to fix | |
| 1024 * @param bool $serialized Enable serialization | |
| 1025 * | |
| 1026 * @return mixed Properly UTF-8 encoded data | |
| 1027 */ | |
| 1028 public static function encode($input, $serialized = false) | |
| 1029 { | |
| 1030 // use Base64 encoding to workaround issues with invalid | |
| 1031 // or null characters in serialized string (#1489142) | |
| 1032 if ($serialized) { | |
| 1033 return base64_encode(serialize($input)); | |
| 1034 } | |
| 1035 | |
| 1036 if (is_object($input)) { | |
| 1037 foreach (get_object_vars($input) as $idx => $value) { | |
| 1038 $input->$idx = self::encode($value); | |
| 1039 } | |
| 1040 return $input; | |
| 1041 } | |
| 1042 else if (is_array($input)) { | |
| 1043 foreach ($input as $idx => $value) { | |
| 1044 $input[$idx] = self::encode($value); | |
| 1045 } | |
| 1046 | |
| 1047 return $input; | |
| 1048 } | |
| 1049 | |
| 1050 return utf8_encode($input); | |
| 1051 } | |
| 1052 | |
| 1053 /** | |
| 1054 * Decodes encoded UTF-8 string/object/array (recursive) | |
| 1055 * | |
| 1056 * @param mixed $input Input data | |
| 1057 * @param bool $serialized Enable serialization | |
| 1058 * | |
| 1059 * @return mixed Decoded data | |
| 1060 */ | |
| 1061 public static function decode($input, $serialized = false) | |
| 1062 { | |
| 1063 // use Base64 encoding to workaround issues with invalid | |
| 1064 // or null characters in serialized string (#1489142) | |
| 1065 if ($serialized) { | |
| 1066 // Keep backward compatybility where base64 wasn't used | |
| 1067 if (strpos(substr($input, 0, 16), ':') !== false) { | |
| 1068 return self::decode(@unserialize($input)); | |
| 1069 } | |
| 1070 | |
| 1071 return @unserialize(base64_decode($input)); | |
| 1072 } | |
| 1073 | |
| 1074 if (is_object($input)) { | |
| 1075 foreach (get_object_vars($input) as $idx => $value) { | |
| 1076 $input->$idx = self::decode($value); | |
| 1077 } | |
| 1078 return $input; | |
| 1079 } | |
| 1080 else if (is_array($input)) { | |
| 1081 foreach ($input as $idx => $value) { | |
| 1082 $input[$idx] = self::decode($value); | |
| 1083 } | |
| 1084 return $input; | |
| 1085 } | |
| 1086 | |
| 1087 return utf8_decode($input); | |
| 1088 } | |
| 1089 | |
| 1090 /** | |
| 1091 * Return correct name for a specific database table | |
| 1092 * | |
| 1093 * @param string $table Table name | |
| 1094 * @param bool $quoted Quote table identifier | |
| 1095 * | |
| 1096 * @return string Translated table name | |
| 1097 */ | |
| 1098 public function table_name($table, $quoted = false) | |
| 1099 { | |
| 1100 // let plugins alter the table name (#1489837) | |
| 1101 $plugin = rcube::get_instance()->plugins->exec_hook('db_table_name', array('table' => $table)); | |
| 1102 $table = $plugin['table']; | |
| 1103 | |
| 1104 // add prefix to the table name if configured | |
| 1105 if (($prefix = $this->options['table_prefix']) && strpos($table, $prefix) !== 0) { | |
| 1106 $table = $prefix . $table; | |
| 1107 } | |
| 1108 | |
| 1109 if ($quoted) { | |
| 1110 $table = $this->quote_identifier($table); | |
| 1111 } | |
| 1112 | |
| 1113 return $table; | |
| 1114 } | |
| 1115 | |
| 1116 /** | |
| 1117 * Set class option value | |
| 1118 * | |
| 1119 * @param string $name Option name | |
| 1120 * @param mixed $value Option value | |
| 1121 */ | |
| 1122 public function set_option($name, $value) | |
| 1123 { | |
| 1124 $this->options[$name] = $value; | |
| 1125 } | |
| 1126 | |
| 1127 /** | |
| 1128 * Set DSN connection to be used for the given table | |
| 1129 * | |
| 1130 * @param string $table Table name | |
| 1131 * @param string $mode DSN connection ('r' or 'w') to be used | |
| 1132 */ | |
| 1133 public function set_table_dsn($table, $mode) | |
| 1134 { | |
| 1135 $this->options['table_dsn_map'][$this->table_name($table)] = $mode; | |
| 1136 } | |
| 1137 | |
| 1138 /** | |
| 1139 * MDB2 DSN string parser | |
| 1140 * | |
| 1141 * @param string $sequence Secuence name | |
| 1142 * | |
| 1143 * @return array DSN parameters | |
| 1144 */ | |
| 1145 public static function parse_dsn($dsn) | |
| 1146 { | |
| 14 | 1147 $proto = null; |
| 1148 | |
| 0 | 1149 if (empty($dsn)) { |
| 1150 return null; | |
| 1151 } | |
| 1152 | |
| 1153 // Find phptype and dbsyntax | |
| 1154 if (($pos = strpos($dsn, '://')) !== false) { | |
| 1155 $str = substr($dsn, 0, $pos); | |
| 1156 $dsn = substr($dsn, $pos + 3); | |
| 1157 } | |
| 1158 else { | |
| 1159 $str = $dsn; | |
| 1160 $dsn = null; | |
| 1161 } | |
| 1162 | |
| 1163 // Get phptype and dbsyntax | |
| 1164 // $str => phptype(dbsyntax) | |
| 1165 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { | |
| 1166 $parsed['phptype'] = $arr[1]; | |
| 1167 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2]; | |
| 1168 } | |
| 1169 else { | |
| 1170 $parsed['phptype'] = $str; | |
| 1171 $parsed['dbsyntax'] = $str; | |
| 1172 } | |
| 1173 | |
| 1174 if (empty($dsn)) { | |
| 1175 return $parsed; | |
| 1176 } | |
| 1177 | |
| 1178 // Get (if found): username and password | |
| 1179 // $dsn => username:password@protocol+hostspec/database | |
| 1180 if (($at = strrpos($dsn,'@')) !== false) { | |
| 1181 $str = substr($dsn, 0, $at); | |
| 1182 $dsn = substr($dsn, $at + 1); | |
| 1183 if (($pos = strpos($str, ':')) !== false) { | |
| 1184 $parsed['username'] = rawurldecode(substr($str, 0, $pos)); | |
| 1185 $parsed['password'] = rawurldecode(substr($str, $pos + 1)); | |
| 1186 } | |
| 1187 else { | |
| 1188 $parsed['username'] = rawurldecode($str); | |
| 1189 } | |
| 1190 } | |
| 1191 | |
| 1192 // Find protocol and hostspec | |
| 1193 | |
| 1194 // $dsn => proto(proto_opts)/database | |
| 1195 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) { | |
| 1196 $proto = $match[1]; | |
| 1197 $proto_opts = $match[2] ? $match[2] : false; | |
| 1198 $dsn = $match[3]; | |
| 1199 } | |
| 1200 // $dsn => protocol+hostspec/database (old format) | |
| 1201 else { | |
| 1202 if (strpos($dsn, '+') !== false) { | |
| 1203 list($proto, $dsn) = explode('+', $dsn, 2); | |
| 1204 } | |
| 1205 if ( strpos($dsn, '//') === 0 | |
| 1206 && strpos($dsn, '/', 2) !== false | |
| 1207 && $parsed['phptype'] == 'oci8' | |
| 1208 ) { | |
| 1209 //oracle's "Easy Connect" syntax: | |
| 1210 //"username/password@[//]host[:port][/service_name]" | |
| 1211 //e.g. "scott/tiger@//mymachine:1521/oracle" | |
| 1212 $proto_opts = $dsn; | |
| 1213 $pos = strrpos($proto_opts, '/'); | |
| 1214 $dsn = substr($proto_opts, $pos + 1); | |
| 1215 $proto_opts = substr($proto_opts, 0, $pos); | |
| 1216 } | |
| 1217 else if (strpos($dsn, '/') !== false) { | |
| 1218 list($proto_opts, $dsn) = explode('/', $dsn, 2); | |
| 1219 } | |
| 1220 else { | |
| 1221 $proto_opts = $dsn; | |
| 1222 $dsn = null; | |
| 1223 } | |
| 1224 } | |
| 1225 | |
| 1226 // process the different protocol options | |
| 1227 $parsed['protocol'] = $proto ?: 'tcp'; | |
| 1228 $proto_opts = rawurldecode($proto_opts); | |
| 1229 if (strpos($proto_opts, ':') !== false) { | |
| 1230 list($proto_opts, $parsed['port']) = explode(':', $proto_opts); | |
| 1231 } | |
| 1232 if ($parsed['protocol'] == 'tcp') { | |
| 1233 $parsed['hostspec'] = $proto_opts; | |
| 1234 } | |
| 1235 else if ($parsed['protocol'] == 'unix') { | |
| 1236 $parsed['socket'] = $proto_opts; | |
| 1237 } | |
| 1238 | |
| 1239 // Get dabase if any | |
| 1240 // $dsn => database | |
| 1241 if ($dsn) { | |
| 1242 // /database | |
| 1243 if (($pos = strpos($dsn, '?')) === false) { | |
| 1244 $parsed['database'] = rawurldecode($dsn); | |
| 1245 // /database?param1=value1¶m2=value2 | |
| 1246 } | |
| 1247 else { | |
| 1248 $parsed['database'] = rawurldecode(substr($dsn, 0, $pos)); | |
| 1249 $dsn = substr($dsn, $pos + 1); | |
| 1250 if (strpos($dsn, '&') !== false) { | |
| 1251 $opts = explode('&', $dsn); | |
| 1252 } | |
| 1253 else { // database?param1=value1 | |
| 1254 $opts = array($dsn); | |
| 1255 } | |
| 1256 foreach ($opts as $opt) { | |
| 1257 list($key, $value) = explode('=', $opt); | |
| 1258 if (!array_key_exists($key, $parsed) || false === $parsed[$key]) { | |
| 1259 // don't allow params overwrite | |
| 1260 $parsed[$key] = rawurldecode($value); | |
| 1261 } | |
| 1262 } | |
| 1263 } | |
| 1264 } | |
| 1265 | |
| 1266 return $parsed; | |
| 1267 } | |
| 1268 | |
| 1269 /** | |
| 1270 * Returns PDO DSN string from DSN array | |
| 1271 * | |
| 1272 * @param array $dsn DSN parameters | |
| 1273 * | |
| 1274 * @return string DSN string | |
| 1275 */ | |
| 1276 protected function dsn_string($dsn) | |
| 1277 { | |
| 1278 $params = array(); | |
| 1279 $result = $dsn['phptype'] . ':'; | |
| 1280 | |
| 1281 if ($dsn['hostspec']) { | |
| 1282 $params[] = 'host=' . $dsn['hostspec']; | |
| 1283 } | |
| 1284 | |
| 1285 if ($dsn['port']) { | |
| 1286 $params[] = 'port=' . $dsn['port']; | |
| 1287 } | |
| 1288 | |
| 1289 if ($dsn['database']) { | |
| 1290 $params[] = 'dbname=' . $dsn['database']; | |
| 1291 } | |
| 1292 | |
| 1293 if (!empty($params)) { | |
| 1294 $result .= implode(';', $params); | |
| 1295 } | |
| 1296 | |
| 1297 return $result; | |
| 1298 } | |
| 1299 | |
| 1300 /** | |
| 1301 * Returns driver-specific connection options | |
| 1302 * | |
| 1303 * @param array $dsn DSN parameters | |
| 1304 * | |
| 1305 * @return array Connection options | |
| 1306 */ | |
| 1307 protected function dsn_options($dsn) | |
| 1308 { | |
| 1309 $result = array(); | |
| 1310 | |
| 1311 if ($this->db_pconn) { | |
| 1312 $result[PDO::ATTR_PERSISTENT] = true; | |
| 1313 } | |
| 1314 | |
| 1315 if (!empty($dsn['prefetch'])) { | |
| 1316 $result[PDO::ATTR_PREFETCH] = (int) $dsn['prefetch']; | |
| 1317 } | |
| 1318 | |
| 1319 if (!empty($dsn['timeout'])) { | |
| 1320 $result[PDO::ATTR_TIMEOUT] = (int) $dsn['timeout']; | |
| 1321 } | |
| 1322 | |
| 1323 return $result; | |
| 1324 } | |
| 1325 | |
| 1326 /** | |
| 1327 * Execute the given SQL script | |
| 1328 * | |
| 1329 * @param string $sql SQL queries to execute | |
| 1330 * | |
| 1331 * @return boolen True on success, False on error | |
| 1332 */ | |
| 1333 public function exec_script($sql) | |
| 1334 { | |
| 1335 $sql = $this->fix_table_names($sql); | |
| 1336 $buff = ''; | |
| 1337 $exec = ''; | |
| 1338 | |
| 1339 foreach (explode("\n", $sql) as $line) { | |
| 1340 $trimmed = trim($line); | |
| 1341 if ($trimmed == '' || preg_match('/^--/', $trimmed)) { | |
| 1342 continue; | |
| 1343 } | |
| 1344 | |
| 1345 if ($trimmed == 'GO') { | |
| 1346 $exec = $buff; | |
| 1347 } | |
| 1348 else if ($trimmed[strlen($trimmed)-1] == ';') { | |
| 1349 $exec = $buff . substr(rtrim($line), 0, -1); | |
| 1350 } | |
| 1351 | |
| 1352 if ($exec) { | |
| 1353 $this->query($exec); | |
| 1354 $buff = ''; | |
| 1355 $exec = ''; | |
| 1356 if ($this->db_error) { | |
| 1357 break; | |
| 1358 } | |
| 1359 } | |
| 1360 else { | |
| 1361 $buff .= $line . "\n"; | |
| 1362 } | |
| 1363 } | |
| 1364 | |
| 1365 return !$this->db_error; | |
| 1366 } | |
| 1367 | |
| 1368 /** | |
| 1369 * Parse SQL file and fix table names according to table prefix | |
| 1370 */ | |
| 1371 protected function fix_table_names($sql) | |
| 1372 { | |
| 1373 if (!$this->options['table_prefix']) { | |
| 1374 return $sql; | |
| 1375 } | |
| 1376 | |
| 1377 $sql = preg_replace_callback( | |
| 1378 '/((TABLE|TRUNCATE|(?<!ON )UPDATE|INSERT INTO|FROM' | |
| 1379 . '| ON(?! (DELETE|UPDATE))|REFERENCES|CONSTRAINT|FOREIGN KEY|INDEX)' | |
| 1380 . '\s+(IF (NOT )?EXISTS )?[`"]*)([^`"\( \r\n]+)/', | |
| 1381 array($this, 'fix_table_names_callback'), | |
| 1382 $sql | |
| 1383 ); | |
| 1384 | |
| 1385 return $sql; | |
| 1386 } | |
| 1387 | |
| 1388 /** | |
| 1389 * Preg_replace callback for fix_table_names() | |
| 1390 */ | |
| 1391 protected function fix_table_names_callback($matches) | |
| 1392 { | |
| 1393 return $matches[1] . $this->options['table_prefix'] . $matches[count($matches)-1]; | |
| 1394 } | |
| 1395 } |
