[693] | 1 | <?php |
---|
| 2 | /* |
---|
| 3 | * The Strangecode Codebase - a general application development framework for PHP |
---|
| 4 | * For details visit the project site: <http://trac.strangecode.com/> |
---|
| 5 | * Copyright © 2019 Strangecode, LLC |
---|
| 6 | * |
---|
| 7 | * This program is free software: you can redistribute it and/or modify |
---|
| 8 | * it under the terms of the GNU General Public License as published by |
---|
| 9 | * the Free Software Foundation, either version 3 of the License, or |
---|
| 10 | * (at your option) any later version. |
---|
| 11 | * |
---|
| 12 | * This program is distributed in the hope that it will be useful, |
---|
| 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
| 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
| 15 | * GNU General Public License for more details. |
---|
| 16 | * |
---|
| 17 | * You should have received a copy of the GNU General Public License |
---|
| 18 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
---|
| 19 | */ |
---|
| 20 | |
---|
| 21 | /* |
---|
| 22 | * PDO.inc.php |
---|
| 23 | * |
---|
| 24 | * |
---|
| 25 | * |
---|
| 26 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 27 | * @version 1.0 |
---|
| 28 | * @since 09 Jul 2019 08:11:03 |
---|
| 29 | * |
---|
| 30 | * Example of use: |
---|
| 31 | --------------------------------------------------------------------- |
---|
| 32 | $x = new PDO(); |
---|
| 33 | $x->setParam(array('foo' => 'bar')); |
---|
| 34 | $x->doIt(); |
---|
| 35 | echo $x->getIt(); |
---|
| 36 | --------------------------------------------------------------------- |
---|
| 37 | */ |
---|
| 38 | namespace Strangecode\Codebase; |
---|
| 39 | use \App; |
---|
| 40 | |
---|
| 41 | class PDO |
---|
| 42 | { |
---|
| 43 | // A place to keep an object instance for the singleton pattern. |
---|
| 44 | protected static $instance = null; |
---|
| 45 | |
---|
| 46 | // If $db->connect has successfully opened a db connection. |
---|
| 47 | protected $_connected = false; |
---|
| 48 | |
---|
| 49 | // Database handle. |
---|
| 50 | public $dbh; |
---|
| 51 | |
---|
| 52 | // Count how many queries run during the whole instance. |
---|
| 53 | protected $_query_count = 0; |
---|
| 54 | |
---|
| 55 | // Hash of DB parameters. |
---|
| 56 | protected $_params = array( |
---|
| 57 | |
---|
| 58 | // DB passwords should be set as apache environment variables in httpd.conf, readable only by root. |
---|
| 59 | 'db_server' => 'localhost', |
---|
| 60 | 'db_name' => null, |
---|
| 61 | 'db_user' => null, |
---|
| 62 | 'db_pass' => null, |
---|
| 63 | |
---|
| 64 | // Display all SQL queries. FALSE recommended for production sites. |
---|
| 65 | 'db_always_debug' => false, |
---|
| 66 | |
---|
| 67 | // Display db errors. FALSE recommended for production sites. |
---|
| 68 | 'db_debug' => false, |
---|
| 69 | |
---|
| 70 | // Script stops on db error. TRUE recommended for production sites. |
---|
| 71 | 'db_die_on_failure' => true, |
---|
| 72 | |
---|
| 73 | // Special date settings. These will dynamically changes depending on MySQL version or settings. |
---|
| 74 | 'zero_date' => '0000-00-00', |
---|
| 75 | 'infinity_date' => '9999-12-31', |
---|
| 76 | |
---|
| 77 | // Timezone for MySQL. |
---|
| 78 | 'timezone' => 'UTC', |
---|
| 79 | |
---|
| 80 | // MySQL character set and collation. |
---|
| 81 | 'character_set' => '', |
---|
| 82 | 'collation' => '', |
---|
| 83 | ); |
---|
| 84 | |
---|
| 85 | // Translate between HTML and MySQL character set names. |
---|
| 86 | public $mysql_character_sets = array( |
---|
| 87 | 'utf-8' => 'utf8', |
---|
| 88 | 'iso-8859-1' => 'latin1', |
---|
| 89 | ); |
---|
| 90 | |
---|
| 91 | // Caches. |
---|
| 92 | protected static $existing_tables = null; |
---|
| 93 | protected static $table_columns = []; |
---|
| 94 | |
---|
| 95 | /** |
---|
| 96 | * PDO constructor. |
---|
| 97 | * |
---|
| 98 | * @access public |
---|
| 99 | * @param string $namespace Namespace for this object, used to avoid collisions in global contexts. |
---|
| 100 | * @param string $params Configuration parameters for this object. |
---|
| 101 | */ |
---|
| 102 | public function __construct($params=null) |
---|
| 103 | { |
---|
| 104 | // Set custom parameters. |
---|
| 105 | $this->setParam($params); |
---|
| 106 | } |
---|
| 107 | |
---|
| 108 | /** |
---|
| 109 | * This method enforces the singleton pattern for this class. |
---|
| 110 | * |
---|
| 111 | * @return object Reference to the global DB object. |
---|
| 112 | * @access public |
---|
| 113 | * @static |
---|
| 114 | */ |
---|
| 115 | public static function &getInstance() |
---|
| 116 | { |
---|
| 117 | if (self::$instance === null) { |
---|
| 118 | self::$instance = new self(); |
---|
| 119 | } |
---|
| 120 | |
---|
| 121 | return self::$instance; |
---|
| 122 | } |
---|
| 123 | |
---|
| 124 | /** |
---|
| 125 | * Set the params of this object. |
---|
| 126 | * |
---|
| 127 | * @access public |
---|
| 128 | * @param array $params Array of param keys and values to set. |
---|
| 129 | */ |
---|
| 130 | public function setParam($params=null) |
---|
| 131 | { |
---|
| 132 | if (isset($params) && is_array($params)) { |
---|
| 133 | // Merge new parameters with old overriding only those passed. |
---|
| 134 | $this->_params = array_merge($this->_params, $params); |
---|
| 135 | } |
---|
| 136 | } |
---|
| 137 | |
---|
| 138 | /** |
---|
| 139 | * Return the value of a parameter, if it exists. |
---|
| 140 | * |
---|
| 141 | * @access public |
---|
| 142 | * @param string $param Which parameter to return. |
---|
| 143 | * @return mixed Configured parameter value. |
---|
| 144 | */ |
---|
| 145 | public function getParam($param) |
---|
| 146 | { |
---|
| 147 | $app =& App::getInstance(); |
---|
| 148 | |
---|
| 149 | if (isset($this->_params[$param])) { |
---|
| 150 | return $this->_params[$param]; |
---|
| 151 | } else { |
---|
| 152 | $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 153 | return null; |
---|
| 154 | } |
---|
| 155 | } |
---|
| 156 | |
---|
| 157 | /* |
---|
| 158 | * Connect to database with credentials in params. |
---|
| 159 | * |
---|
| 160 | * @access public |
---|
| 161 | * @param |
---|
| 162 | * @return |
---|
| 163 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 164 | * @since 09 Jul 2019 08:16:42 |
---|
| 165 | */ |
---|
| 166 | public function connect() |
---|
| 167 | { |
---|
| 168 | $app =& App::getInstance(); |
---|
| 169 | |
---|
| 170 | if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) { |
---|
| 171 | $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__); |
---|
| 172 | return false; |
---|
| 173 | } |
---|
| 174 | |
---|
| 175 | // If db_server not specified, assume localhost. |
---|
| 176 | if (!$this->getParam('db_server')) { |
---|
| 177 | $this->setParam(array('db_server' => 'localhost')); |
---|
| 178 | } |
---|
| 179 | |
---|
| 180 | // If the mysql charset is not defined, try to determine a mysql charset from the app charset. |
---|
| 181 | if ('' == $this->getParam('character_set') && '' != $app->getParam('character_set') && isset($this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])) { |
---|
| 182 | $this->setParam(array('character_set' => $this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])); |
---|
| 183 | } |
---|
| 184 | |
---|
| 185 | try { |
---|
| 186 | $dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', $this->getParam('db_server'), $this->getParam('db_name'), $this->getParam('character_set')); |
---|
| 187 | $options = [ |
---|
| 188 | \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, |
---|
| 189 | \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, |
---|
| 190 | \PDO::ATTR_EMULATE_PREPARES => false, |
---|
| 191 | ]; |
---|
| 192 | $this->dbh = new \PDO($dsn, $this->getParam('db_user'), $this->getParam('db_pass'), $options); |
---|
| 193 | } catch (\PDOException $e) { |
---|
[698] | 194 | $mysql_error_msg = sprintf('PDO connect %s: %s (db_server=%s, db_name=%s, db_user=%s, db_pass=%s)', |
---|
| 195 | get_class($e), |
---|
| 196 | $e->getMessage(), |
---|
| 197 | $this->getParam('db_server'), |
---|
| 198 | $this->getParam('db_name'), |
---|
| 199 | $this->getParam('db_user'), |
---|
| 200 | ('' == $this->getParam('db_pass') ? 'NO' : 'YES') |
---|
| 201 | ); |
---|
[693] | 202 | $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__); |
---|
| 203 | |
---|
| 204 | // Print helpful or pretty error? |
---|
[698] | 205 | if ($this->getParam('db_debug') && $app->getParam('display_errors')) { |
---|
| 206 | if (!$app->isCLI()) { |
---|
| 207 | printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s</pre>', $mysql_error_msg); |
---|
| 208 | } |
---|
[693] | 209 | } |
---|
| 210 | |
---|
| 211 | // Die if db_die_on_failure = true, or just continue without connection. |
---|
| 212 | return $this->_fail(); |
---|
| 213 | } |
---|
| 214 | |
---|
| 215 | // DB connection success! |
---|
| 216 | $this->_connected = true; |
---|
| 217 | |
---|
| 218 | // Update config for this version of MySQL. |
---|
| 219 | if (version_compare($this->dbh->getAttribute(\PDO::ATTR_SERVER_VERSION), '5.7.4', '>=')) { |
---|
| 220 | $this->setParam(array('zero_date' => '1000-01-01')); |
---|
| 221 | } |
---|
| 222 | |
---|
| 223 | // Set MySQL session timezone. |
---|
| 224 | if ($this->getParam('timezone')) { |
---|
| 225 | // https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html |
---|
| 226 | $this->dbh->query(sprintf("SET time_zone = '%s'", $this->getParam('timezone'))); |
---|
| 227 | } |
---|
| 228 | |
---|
| 229 | return true; |
---|
| 230 | } |
---|
| 231 | |
---|
| 232 | /** |
---|
| 233 | * Close db connection. |
---|
| 234 | * |
---|
| 235 | * @access public |
---|
| 236 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 237 | * @since 28 Aug 2005 14:32:01 |
---|
| 238 | */ |
---|
| 239 | public function close() |
---|
| 240 | { |
---|
[698] | 241 | $app =& App::getInstance(); |
---|
| 242 | |
---|
[693] | 243 | if (!$this->_connected) { |
---|
[719] | 244 | throw new \Exception(sprintf('No DB connection to run %s', __METHOD__)); |
---|
[693] | 245 | } |
---|
[719] | 246 | |
---|
[693] | 247 | $this->_connected = false; |
---|
| 248 | $this->dbh = null; |
---|
[719] | 249 | |
---|
[693] | 250 | return true; |
---|
| 251 | } |
---|
| 252 | |
---|
| 253 | /* |
---|
| 254 | * |
---|
| 255 | * |
---|
| 256 | * @access public |
---|
| 257 | * @param |
---|
| 258 | * @return |
---|
| 259 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 260 | * @version 1.0 |
---|
| 261 | * @since 03 Jul 2013 14:50:23 |
---|
| 262 | */ |
---|
| 263 | public function reconnect() |
---|
| 264 | { |
---|
| 265 | $this->close(); |
---|
| 266 | $this->connect(); |
---|
| 267 | } |
---|
| 268 | |
---|
| 269 | /* |
---|
| 270 | * |
---|
| 271 | * |
---|
| 272 | * @access public |
---|
| 273 | * @param |
---|
| 274 | * @return |
---|
| 275 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 276 | * @since 09 Jul 2019 10:05:34 |
---|
| 277 | */ |
---|
| 278 | public function ping() |
---|
| 279 | { |
---|
[698] | 280 | $app =& App::getInstance(); |
---|
| 281 | |
---|
[693] | 282 | if (!$this->_connected) { |
---|
[719] | 283 | throw new \Exception(sprintf('No DB connection to run %s', __METHOD__)); |
---|
[693] | 284 | } |
---|
| 285 | |
---|
| 286 | try { |
---|
| 287 | $this->dbh->query('SELECT 1'); |
---|
| 288 | } catch (\PDOException $e) { |
---|
| 289 | return false; |
---|
| 290 | } |
---|
| 291 | |
---|
| 292 | return true; |
---|
| 293 | } |
---|
| 294 | |
---|
| 295 | /* |
---|
| 296 | * Die only if db_die_on_failure is true. This will be set to false for some cases |
---|
| 297 | * when a database is not required for web app functionality. |
---|
| 298 | * |
---|
| 299 | * @access public |
---|
| 300 | * @param string $msg Print $msg when dying. |
---|
| 301 | * @return bool false If we don't die. |
---|
| 302 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 303 | * @version 1.0 |
---|
| 304 | * @since 15 Jan 2007 15:59:00 |
---|
| 305 | */ |
---|
| 306 | protected function _fail() |
---|
| 307 | { |
---|
| 308 | $app =& App::getInstance(); |
---|
| 309 | |
---|
| 310 | if ($this->getParam('db_die_on_failure')) { |
---|
| 311 | if (!$app->isCLI()) { |
---|
| 312 | // For http requests, send a Service Unavailable header. |
---|
| 313 | header(' ', true, 503); |
---|
| 314 | echo _("This page is temporarily unavailable. Please try again in a few minutes."); |
---|
| 315 | } |
---|
| 316 | die; |
---|
| 317 | } else { |
---|
| 318 | return false; |
---|
| 319 | } |
---|
| 320 | } |
---|
| 321 | |
---|
| 322 | /** |
---|
| 323 | * Returns connection status |
---|
| 324 | * |
---|
| 325 | * @access public |
---|
| 326 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 327 | * @since 28 Aug 2005 14:58:09 |
---|
| 328 | */ |
---|
| 329 | public function isConnected() |
---|
| 330 | { |
---|
| 331 | return (true === $this->_connected); |
---|
| 332 | } |
---|
| 333 | |
---|
| 334 | /* |
---|
| 335 | * Return the total number of queries executed thus far. |
---|
| 336 | * |
---|
| 337 | * @access public |
---|
| 338 | * @return int Number of queries |
---|
| 339 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 340 | * @version 1.0 |
---|
| 341 | * @since 15 Jun 2006 11:46:05 |
---|
| 342 | */ |
---|
| 343 | public function numQueries() |
---|
| 344 | { |
---|
| 345 | return $this->_query_count; |
---|
| 346 | } |
---|
| 347 | |
---|
| 348 | /** |
---|
| 349 | * Reset cached items. |
---|
| 350 | * |
---|
| 351 | * @access public |
---|
| 352 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 353 | * @since 28 Aug 2005 22:10:50 |
---|
| 354 | */ |
---|
| 355 | public function resetCache() |
---|
| 356 | { |
---|
| 357 | self::$existing_tables = null; |
---|
| 358 | self::$table_columns = []; |
---|
| 359 | } |
---|
| 360 | |
---|
| 361 | /* |
---|
| 362 | * |
---|
| 363 | * |
---|
| 364 | * @access public |
---|
| 365 | * @param string $query The SQL query to execute |
---|
| 366 | * @param bool $debug If true, prints debugging info |
---|
| 367 | * @return resource PDOStatement |
---|
| 368 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 369 | * @since 09 Jul 2019 10:00:00 |
---|
| 370 | */ |
---|
| 371 | public function query($query, $debug=false) |
---|
| 372 | { |
---|
| 373 | $app =& App::getInstance(); |
---|
| 374 | |
---|
| 375 | if (!$this->_connected) { |
---|
[719] | 376 | throw new \Exception(sprintf('No DB connection to run %s', __METHOD__)); |
---|
[693] | 377 | } |
---|
| 378 | |
---|
| 379 | $this->_query_count++; |
---|
| 380 | |
---|
| 381 | $debugqry = preg_replace("/\n[\t ]+/u", "\n", $query); |
---|
| 382 | if ($this->getParam('db_always_debug') || $debug) { |
---|
| 383 | if ($debug > 1) { |
---|
| 384 | dump($debugqry, true, SC_DUMP_PRINT_R, __FILE__, __LINE__); |
---|
| 385 | } else { |
---|
[698] | 386 | echo "<!-- ----------------- PDO query $this->_query_count ---------------------\n$debugqry\n-->\n"; |
---|
[693] | 387 | } |
---|
| 388 | } |
---|
| 389 | |
---|
| 390 | // Ensure we have an active connection. |
---|
| 391 | // If we continue on a dead connection we might experience a "MySQL server has gone away" error. |
---|
| 392 | // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html |
---|
| 393 | if (!$this->ping()) { |
---|
| 394 | $app->logMsg(sprintf('MySQL ping failed; reconnecting⊠("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 395 | $this->reconnect(); |
---|
| 396 | } |
---|
| 397 | |
---|
| 398 | // Execute! |
---|
| 399 | try { |
---|
| 400 | $stmt = $this->dbh->query($query); |
---|
[698] | 401 | if (!$stmt) { |
---|
[718] | 402 | throw new \Exception('PDO::query returned false'); |
---|
[698] | 403 | } |
---|
| 404 | } catch (\Exception $e) { |
---|
| 405 | $app->logMsg(sprintf('PDO query %s (%s): %s in query: %s', get_class($e), $e->getCode(), $e->getMessage(), $debugqry), LOG_EMERG, __FILE__, __LINE__); |
---|
| 406 | if ($this->getParam('db_debug') && $app->getParam('display_errors')) { |
---|
[693] | 407 | if (!$app->isCLI()) { |
---|
[698] | 408 | printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s<hr>%s</pre>', wordwrap($e->getMessage()), htmlspecialchars($debugqry)); |
---|
[693] | 409 | } |
---|
| 410 | } |
---|
| 411 | // Die if db_die_on_failure = true, or just continue without connection |
---|
| 412 | return $this->_fail(); |
---|
| 413 | } |
---|
| 414 | |
---|
| 415 | return $stmt; |
---|
| 416 | } |
---|
| 417 | |
---|
| 418 | /* |
---|
| 419 | * |
---|
| 420 | * |
---|
| 421 | * @access public |
---|
| 422 | * @param |
---|
| 423 | * @return |
---|
| 424 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 425 | * @since 09 Jul 2019 19:26:37 |
---|
| 426 | */ |
---|
| 427 | public function prepare($query, ...$params) |
---|
| 428 | { |
---|
| 429 | $app =& App::getInstance(); |
---|
| 430 | |
---|
| 431 | if (!$this->_connected) { |
---|
[719] | 432 | throw new \Exception(sprintf('No DB connection to run %s', __METHOD__)); |
---|
[693] | 433 | } |
---|
| 434 | |
---|
| 435 | $this->_query_count++; |
---|
| 436 | |
---|
| 437 | $debugqry = preg_replace("/\n[\t ]+/u", "\n", $query); |
---|
| 438 | if ($this->getParam('db_always_debug')) { |
---|
[698] | 439 | echo "<!-- ----------------- PDO prepare $this->_query_count ---------------------\n$debugqry\n-->\n"; |
---|
[693] | 440 | } |
---|
| 441 | |
---|
| 442 | // Ensure we have an active connection. |
---|
| 443 | // If we continue on a dead connection we might experience a "MySQL server has gone away" error. |
---|
| 444 | // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html |
---|
| 445 | if (!$this->ping()) { |
---|
| 446 | $app->logMsg(sprintf('MySQL ping failed; reconnecting⊠("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__); |
---|
| 447 | $this->reconnect(); |
---|
| 448 | } |
---|
| 449 | |
---|
| 450 | // Execute! |
---|
| 451 | try { |
---|
| 452 | $stmt = $this->dbh->prepare($query, ...$params); |
---|
[698] | 453 | if (!$stmt) { |
---|
[718] | 454 | throw new \Exception('PDO::prepare returned false'); |
---|
[698] | 455 | } |
---|
[693] | 456 | } catch (\PDOException $e) { |
---|
[698] | 457 | $app->logMsg(sprintf('PDO prepare %s (%s): %s in query: %s', get_class($e), $e->getCode(), $e->getMessage(), $debugqry), LOG_EMERG, __FILE__, __LINE__); |
---|
| 458 | if ($this->getParam('db_debug') && $app->getParam('display_errors')) { |
---|
[693] | 459 | if (!$app->isCLI()) { |
---|
[698] | 460 | printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s<hr>%s</pre>', wordwrap($e->getMessage()), htmlspecialchars($debugqry)); |
---|
[693] | 461 | } |
---|
| 462 | } |
---|
| 463 | // Die if db_die_on_failure = true, or just continue without connection |
---|
| 464 | return $this->_fail(); |
---|
| 465 | } |
---|
| 466 | |
---|
| 467 | return $stmt; |
---|
| 468 | } |
---|
| 469 | |
---|
| 470 | /* |
---|
| 471 | * |
---|
| 472 | * |
---|
| 473 | * @access public |
---|
| 474 | * @param |
---|
| 475 | * @return |
---|
| 476 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 477 | * @since 09 Jul 2019 19:42:48 |
---|
| 478 | */ |
---|
| 479 | public function lastInsertId($name=null) |
---|
| 480 | { |
---|
| 481 | return $this->dbh->lastInsertId($name); |
---|
| 482 | } |
---|
| 483 | |
---|
| 484 | /* |
---|
| 485 | * |
---|
| 486 | * |
---|
| 487 | * @access public |
---|
| 488 | * @param |
---|
| 489 | * @return |
---|
| 490 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 491 | * @since 09 Jul 2019 18:32:55 |
---|
| 492 | */ |
---|
| 493 | public function quote(...$params) |
---|
| 494 | { |
---|
| 495 | return $this->dbh->quote(...$params); |
---|
| 496 | } |
---|
| 497 | |
---|
| 498 | /* |
---|
[718] | 499 | * Remove unsafe characters from SQL identifiers (tables, views, indexes, columns, and constraints). |
---|
[693] | 500 | * |
---|
| 501 | * @access public |
---|
[718] | 502 | * @param string $idname Identifier name. |
---|
| 503 | * @return string Clean string. |
---|
[693] | 504 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
| 505 | * @since 09 Jul 2019 18:32:55 |
---|
| 506 | */ |
---|
[718] | 507 | static function sanitizeIdentifier($idname) |
---|
[693] | 508 | { |
---|
[718] | 509 | return preg_replace('/\W/u', '', $idname); |
---|
[693] | 510 | } |
---|
| 511 | |
---|
| 512 | /** |
---|
| 513 | * Loads a list of tables in the current database into an array, and returns |
---|
| 514 | * true if the requested table is found. Use this function to enable/disable |
---|
| 515 | * functionality based upon the current available db tables or to dynamically |
---|
| 516 | * create tables if missing. |
---|
| 517 | * |
---|
| 518 | * @param string $table The name of the table to search. |
---|
| 519 | * @param bool $use_cached_results Get fresh table info (in case DB changed). |
---|
| 520 | * @return bool true if given $table exists. |
---|
| 521 | */ |
---|
| 522 | public function tableExists($table, $use_cached_results=true) |
---|
| 523 | { |
---|
| 524 | $app =& App::getInstance(); |
---|
| 525 | |
---|
| 526 | if (!$this->_connected) { |
---|
[719] | 527 | throw new \Exception(sprintf('No DB connection to run %s', __METHOD__)); |
---|
[693] | 528 | } |
---|
| 529 | |
---|
| 530 | if (null === self::$existing_tables || !$use_cached_results) { |
---|
| 531 | $stmt = $this->query('SHOW TABLES'); |
---|
| 532 | self::$existing_tables = $stmt->fetchAll(\PDO::FETCH_COLUMN); |
---|
| 533 | } |
---|
| 534 | |
---|
| 535 | if (in_array($table, self::$existing_tables)) { |
---|
| 536 | return true; |
---|
| 537 | } else { |
---|
| 538 | $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__); |
---|
| 539 | return false; |
---|
| 540 | } |
---|
| 541 | } |
---|
| 542 | |
---|
| 543 | /** |
---|
| 544 | * Tests if the given array of columns exists in the specified table. |
---|
| 545 | * |
---|
| 546 | * @param string $table The name of the table to search. |
---|
| 547 | * @param array $columns An array of column names. |
---|
| 548 | * @param bool $strict Exact schema match. If TRUE, test if *only* the given columns exist. If FALSE, test if given columns exist (possibly amongst others). |
---|
| 549 | * @param bool $use_cached_results Get fresh table info (in case DB changed). |
---|
| 550 | * @return bool true if column(s) exist. |
---|
| 551 | */ |
---|
| 552 | public function columnExists($table, $columns, $strict=true, $use_cached_results=true) |
---|
| 553 | { |
---|
| 554 | $app =& App::getInstance(); |
---|
| 555 | |
---|
| 556 | if (!$this->_connected) { |
---|
[719] | 557 | throw new \Exception(sprintf('No DB connection to run %s', __METHOD__)); |
---|
[693] | 558 | } |
---|
| 559 | |
---|
| 560 | // Ensure the table exists. |
---|
| 561 | if (!$this->tableExists($table, $use_cached_results)) { |
---|
| 562 | $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__); |
---|
| 563 | return false; |
---|
| 564 | } |
---|
| 565 | |
---|
| 566 | // For single-value columns. |
---|
| 567 | if (!is_array($columns)) { |
---|
| 568 | $columns = array($columns); |
---|
| 569 | } |
---|
| 570 | |
---|
| 571 | if (!isset(self::$table_columns[$table]) || !$use_cached_results) { |
---|
| 572 | // Populate and cache array of current columns for this table. |
---|
| 573 | $stmt = $this->query(sprintf('DESCRIBE `%s`', $this->sanitizeIdentifier($table))); |
---|
| 574 | self::$table_columns[$table] = $stmt->fetchAll(\PDO::FETCH_COLUMN); |
---|
| 575 | } |
---|
| 576 | |
---|
| 577 | if ($strict) { |
---|
| 578 | // Do an exact comparison of table schemas. |
---|
| 579 | sort($columns); |
---|
| 580 | sort(self::$table_columns[$table]); |
---|
| 581 | return self::$table_columns[$table] == $columns; |
---|
| 582 | } else { |
---|
| 583 | // Only check that the specified columns are available in the table. |
---|
| 584 | $match_columns = array_intersect(self::$table_columns[$table], $columns); |
---|
| 585 | sort($columns); |
---|
| 586 | sort($match_columns); |
---|
| 587 | return $match_columns == $columns; |
---|
| 588 | } |
---|
| 589 | } |
---|
| 590 | |
---|
| 591 | /** |
---|
| 592 | * Returns the values of an ENUM or SET column, returning them as an array. |
---|
| 593 | * |
---|
| 594 | * @param string $db_table database table to lookup |
---|
| 595 | * @param string $db_col database column to lookup |
---|
| 596 | * @param bool $sort Sort the output. |
---|
| 597 | * @return array Array of the set/enum values on success, false on failure. |
---|
| 598 | */ |
---|
| 599 | public function getEnumValues($db_table, $db_col, $sort=false) |
---|
| 600 | { |
---|
| 601 | $app =& App::getInstance(); |
---|
| 602 | |
---|
| 603 | $stmt = $this->query(sprintf("SHOW COLUMNS FROM `%s` LIKE %s", $this->sanitizeIdentifier($db_table), $this->dbh->quote($db_col)), false); |
---|
| 604 | $row = $stmt->fetch(\PDO::FETCH_ASSOC); |
---|
| 605 | if (isset($row['Type']) && preg_match('/^(?:enum|set)\((.*)\)$/i', $row['Type'], $matches) && isset($matches[1]) && '' != $matches[1]) { |
---|
| 606 | $enum = str_getcsv($matches[1], ",", "'"); |
---|
| 607 | if ($sort) { |
---|
| 608 | natsort($enum); |
---|
| 609 | } |
---|
| 610 | return $enum; |
---|
| 611 | } else { |
---|
| 612 | $app->logMsg(sprintf('No set or enum fields found in %s.%s', $db_table, $db_col), LOG_ERR, __FILE__, __LINE__); |
---|
| 613 | return false; |
---|
| 614 | } |
---|
| 615 | } |
---|
| 616 | } |
---|