source: trunk/lib/PDO.inc.php

Last change on this file was 810, checked in by anonymous, 2 months ago

Enable setting db_timezone during runtime. Refactor setParam() in App, DB, and PDO.

File size: 21.6 KB
Line 
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();
35echo $x->getIt();
36---------------------------------------------------------------------
37*/
38namespace Strangecode\Codebase;
39use \App;
40
41class 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        // Reconnection attempt limit. Set to 0 to disable retries, i.e., only the first connect will be attempted.
85        'retry_limit' => 8,
86    );
87
88    // Translate between HTML and MySQL character set names.
89    public $mysql_character_sets = array(
90        'utf-8' => 'utf8mb4',
91        'iso-8859-1' => 'latin1',
92    );
93
94    // Caches.
95    protected static $existing_tables = null;
96    protected static $table_columns = [];
97
98    /**
99     * PDO constructor.
100     *
101     * @access public
102     * @param string $namespace Namespace for this object, used to avoid collisions in global contexts.
103     * @param string $params    Configuration parameters for this object.
104     */
105    public function __construct(Array $params=[])
106    {
107        // Set custom parameters.
108        $this->setParam($params);
109    }
110
111    /**
112     * This method enforces the singleton pattern for this class.
113     *
114     * @return  object  Reference to the global DB object.
115     * @access  public
116     * @static
117     */
118    public static function &getInstance()
119    {
120        if (self::$instance === null) {
121            self::$instance = new self();
122        }
123
124        return self::$instance;
125    }
126
127    /**
128     * Set the params of this object.
129     *
130     * @access public
131     * @param  array $params   Array of param keys and values to set.
132     */
133    public function setParam(Array $params)
134    {
135        if (!isset($params) || !is_array($params)) {
136            trigger_error(sprintf('%s failed; not an array: %s', __METHOD__, getDump($params, false, SC_DUMP_PRINT_R)), E_USER_ERROR);
137        }
138
139        // Merge new parameters with old overriding only those passed.
140        $this->_params = array_merge($this->_params, $params);
141
142        if ($this->isConnected()) {
143            // Params that require additional processing if set during runtime.
144            foreach ($params as $key => $val) {
145                switch ($key) {
146                case 'timezone':
147                    // Set timezone used by MySQL.
148                    $this->query(sprintf("SET time_zone = %s;", $this->quote($val)));
149                    break;
150                }
151            }
152        }
153    }
154
155    /**
156     * Return the value of a parameter, if it exists.
157     *
158     * @access public
159     * @param string $param        Which parameter to return.
160     * @return mixed               Configured parameter value.
161     */
162    public function getParam($param)
163    {
164        $app =& App::getInstance();
165
166        if (isset($this->_params[$param])) {
167            return $this->_params[$param];
168        } else {
169            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
170            return null;
171        }
172    }
173
174    /*
175    * Connect to database with credentials in params.
176    *
177    * @access   public
178    * @param
179    * @return
180    * @author   Quinn Comendant <quinn@strangecode.com>
181    * @since    09 Jul 2019 08:16:42
182    */
183    public function connect($retry_num=0)
184    {
185        $app =& App::getInstance();
186
187        if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) {
188            $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
189            return false;
190        }
191
192        // If db_server not specified, assume localhost.
193        if (null === $this->_params['db_server']) {
194            $this->setParam(array('db_server' => 'localhost'));
195        }
196
197        // If the mysql charset is not defined, try to determine a mysql charset from the app charset.
198        if ('' == $this->getParam('character_set') && '' != $app->getParam('character_set') && isset($this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])) {
199            $this->setParam(array('character_set' => $this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))]));
200        }
201
202        try {
203            // Set charset in DSN and disable emulated prepares as per https://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection/12202218
204            $dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', $this->getParam('db_server'), $this->getParam('db_name'), $this->getParam('character_set'));
205            $options = [
206                \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
207                \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
208                \PDO::ATTR_EMULATE_PREPARES   => false,
209            ];
210            $this->dbh = new \PDO($dsn, $this->getParam('db_user'), $this->getParam('db_pass'), $options);
211        } catch (\PDOException $e) {
212            $mysql_error_msg = sprintf('PDO connect %s: %s (db_server=%s, db_name=%s, db_user=%s, db_pass=%s)%s',
213                get_class($e),
214                $e->getMessage(),
215                $this->getParam('db_server'),
216                $this->getParam('db_name'),
217                $this->getParam('db_user'),
218                ('' == $this->getParam('db_pass') ? 'NO' : 'YES'),
219                ($retry_num > 0 ? ' retry ' . $retry_num : '')
220            );
221            // Use LOG_NOTICE for first connection attempts, and LOG_EMERG for the last one.
222            $app->logMsg($mysql_error_msg, ($retry_num >= $this->getParam('retry_limit') ? LOG_EMERG : LOG_NOTICE), __FILE__, __LINE__);
223
224            // These are probably transient errors:
225            // SQLSTATE[HY000] [2002] Connection refused
226            // SQLSTATE[HY000] [2002] No such file or directory
227            // SQLSTATE[HY000] [2006] MySQL server has gone away
228            if ($retry_num < $this->getParam('retry_limit') && (strpos($e->getMessage(), '[2002]') !== false || strpos($e->getMessage(), '[2006]') !== false)) {
229                // Try again after a delay:
230                usleep(500000);
231                return $this->connect(++$retry_num);
232            }
233
234            // Print helpful or pretty error?
235            if ($this->getParam('db_debug') && $app->getParam('display_errors')) {
236                if (!$app->isCLI()) {
237                    printf('<pre style="padding:1em;background:#ddd;font:10px monospace;">%s</pre>', $mysql_error_msg);
238                }
239            }
240
241            // Die if db_die_on_failure = true, or just continue without connection.
242            return $this->_fail();
243        }
244
245        // DB connection success!
246        $this->_connected = true;
247
248        // Update config for this version of MySQL.
249        if (version_compare($this->dbh->getAttribute(\PDO::ATTR_SERVER_VERSION), '5.7.4', '>=')) {
250            $this->setParam(array('zero_date' => '1000-01-01'));
251        }
252
253        // Set MySQL session timezone.
254        if ($this->getParam('timezone')) {
255            // https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
256            $this->dbh->query(sprintf("SET time_zone = '%s'", $this->getParam('timezone')));
257        }
258
259        return true;
260    }
261
262    /**
263     * Close db connection.
264     *
265     * @access  public
266     * @author  Quinn Comendant <quinn@strangecode.com>
267     * @since   28 Aug 2005 14:32:01
268     */
269    public function close()
270    {
271        $this->_connected = false;
272        $this->dbh = null;
273
274        return true;
275    }
276
277    /*
278    *
279    *
280    * @access   public
281    * @param
282    * @return
283    * @author   Quinn Comendant <quinn@strangecode.com>
284    * @version  1.0
285    * @since    03 Jul 2013 14:50:23
286    */
287    public function reconnect()
288    {
289        $this->close();
290        $this->connect();
291    }
292
293    /*
294    *
295    *
296    * @access   public
297    * @param
298    * @return
299    * @author   Quinn Comendant <quinn@strangecode.com>
300    * @since    09 Jul 2019 10:05:34
301    */
302    public function ping()
303    {
304        $app =& App::getInstance();
305
306        if (!$this->_connected) {
307            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
308        }
309
310        try {
311            $this->dbh->query('SELECT 1');
312        } catch (\PDOException $e) {
313            return false;
314        }
315
316        return true;
317    }
318
319    /*
320    * Die only if db_die_on_failure is true. This will be set to false for some cases
321    * when a database is not required for web app functionality.
322    *
323    * @access   public
324    * @param    string  $msg Print $msg when dying.
325    * @return   bool    false If we don't die.
326    * @author   Quinn Comendant <quinn@strangecode.com>
327    * @version  1.0
328    * @since    15 Jan 2007 15:59:00
329    */
330    protected function _fail()
331    {
332        $app =& App::getInstance();
333
334        if ($this->getParam('db_die_on_failure')) {
335            if (!$app->isCLI()) {
336                // For http requests, send a Service Unavailable header.
337                header(' ', true, 503);
338                echo _("This page is temporarily unavailable. Please try again in a few minutes.");
339            }
340            die;
341        } else {
342            return false;
343        }
344    }
345
346    /**
347     * Returns connection status
348     *
349     * @access  public
350     * @author  Quinn Comendant <quinn@strangecode.com>
351     * @since   28 Aug 2005 14:58:09
352     */
353    public function isConnected()
354    {
355        return (true === $this->_connected);
356    }
357
358    /*
359    * Return the total number of queries executed thus far.
360    *
361    * @access   public
362    * @return   int Number of queries
363    * @author   Quinn Comendant <quinn@strangecode.com>
364    * @version  1.0
365    * @since    15 Jun 2006 11:46:05
366    */
367    public function numQueries()
368    {
369        return $this->_query_count;
370    }
371
372    /**
373     * Reset cached items.
374     *
375     * @access  public
376     * @author  Quinn Comendant <quinn@strangecode.com>
377     * @since   28 Aug 2005 22:10:50
378     */
379    public function resetCache()
380    {
381        self::$existing_tables = null;
382        self::$table_columns = [];
383    }
384
385    /*
386    *
387    *
388    * @access   public
389    * @param    string  $query   The SQL query to execute
390    * @param    bool    $debug   If true, prints debugging info
391    * @return   resource         PDOStatement
392    * @author   Quinn Comendant <quinn@strangecode.com>
393    * @since    09 Jul 2019 10:00:00
394    */
395    public function query($query, $debug=false)
396    {
397        $app =& App::getInstance();
398
399        if (!$this->_connected) {
400            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
401        }
402
403        $this->_query_count++;
404
405        $debugqry = preg_replace('/\n[\t ]+/' . $app->getParam('preg_u'), "\n", $query);
406        if ($this->getParam('db_always_debug') || $debug) {
407            if ($debug > 1) {
408                dump($debugqry, true, SC_DUMP_PRINT_R, __FILE__, __LINE__);
409            } else {
410                echo "<!-- ----------------- PDO query $this->_query_count ---------------------\n$debugqry\n-->\n";
411            }
412        }
413
414        // Ensure we have an active connection.
415        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
416        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
417        if (!$this->ping()) {
418            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
419            $this->reconnect();
420        }
421
422        // Execute!
423        try {
424            $stmt = $this->dbh->query($query);
425            if (!$stmt) {
426                throw new \Exception('PDO::query returned false');
427            }
428        } catch (\Exception $e) {
429            $app->logMsg(sprintf('PDO query %s (%s): %s in query: %s', get_class($e), $e->getCode(), $e->getMessage(), $debugqry), LOG_EMERG, __FILE__, __LINE__);
430            if ($this->getParam('db_debug') && $app->getParam('display_errors')) {
431                if (!$app->isCLI()) {
432                    printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s<hr>%s</pre>', wordwrap($e->getMessage()), htmlspecialchars($debugqry));
433                }
434            }
435            // Die if db_die_on_failure = true, or just continue without connection
436            return $this->_fail();
437        }
438
439        return $stmt;
440    }
441
442    /*
443    *
444    *
445    * @access   public
446    * @param
447    * @return
448    * @author   Quinn Comendant <quinn@strangecode.com>
449    * @since    09 Jul 2019 19:26:37
450    */
451    public function prepare($query, ...$params)
452    {
453        $app =& App::getInstance();
454
455        if (!$this->_connected) {
456            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
457        }
458
459        $this->_query_count++;
460
461        $debugqry = preg_replace('/\n[\t ]+/' . $app->getParam('preg_u'), "\n", $query);
462        if ($this->getParam('db_always_debug')) {
463            echo "<!-- ----------------- PDO prepare $this->_query_count ---------------------\n$debugqry\n-->\n";
464        }
465
466        // Ensure we have an active connection.
467        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
468        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
469        if (!$this->ping()) {
470            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
471            $this->reconnect();
472        }
473
474        // Execute!
475        try {
476            $stmt = $this->dbh->prepare($query, ...$params);
477            if (!$stmt) {
478                throw new \Exception('PDO::prepare returned false');
479            }
480        } catch (\PDOException $e) {
481            $app->logMsg(sprintf('PDO prepare %s (%s): %s in query: %s', get_class($e), $e->getCode(), $e->getMessage(), $debugqry), LOG_EMERG, __FILE__, __LINE__);
482            if ($this->getParam('db_debug') && $app->getParam('display_errors')) {
483                if (!$app->isCLI()) {
484                    printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s<hr>%s</pre>', wordwrap($e->getMessage()), htmlspecialchars($debugqry));
485                }
486            }
487            // Die if db_die_on_failure = true, or just continue without connection
488            return $this->_fail();
489        }
490
491        return $stmt;
492    }
493
494    /*
495    *
496    *
497    * @access   public
498    * @param
499    * @return
500    * @author   Quinn Comendant <quinn@strangecode.com>
501    * @since    09 Jul 2019 19:42:48
502    */
503    public function lastInsertId($name=null)
504    {
505        return $this->dbh->lastInsertId($name);
506    }
507
508    /*
509    *
510    *
511    * @access   public
512    * @param
513    * @return
514    * @author   Quinn Comendant <quinn@strangecode.com>
515    * @since    09 Jul 2019 18:32:55
516    */
517    public function quote(...$params)
518    {
519        return $this->dbh->quote(...$params);
520    }
521
522    /*
523    * Remove unsafe characters from SQL identifiers (tables, views, indexes, columns, and constraints).
524    *
525    * @access   public
526    * @param    string  $idname     Identifier name.
527    * @return   string              Clean string.
528    * @author   Quinn Comendant <quinn@strangecode.com>
529    * @since    09 Jul 2019 18:32:55
530    */
531    static function sanitizeIdentifier($idname)
532    {
533        $app =& App::getInstance();
534
535        return preg_replace('/\W/' . $app->getParam('preg_u'), '', $idname);
536    }
537
538    /**
539     * Loads a list of tables in the current database into an array, and returns
540     * true if the requested table is found. Use this function to enable/disable
541     * functionality based upon the current available db tables or to dynamically
542     * create tables if missing.
543     *
544     * @param  string $table                The name of the table to search.
545     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
546     * @return bool                         true if given $table exists.
547     */
548    public function tableExists($table, $use_cached_results=true)
549    {
550        $app =& App::getInstance();
551
552        if (!$this->_connected) {
553            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
554        }
555
556        if (null === self::$existing_tables || !$use_cached_results) {
557            $stmt = $this->query('SHOW TABLES');
558            self::$existing_tables = $stmt->fetchAll(\PDO::FETCH_COLUMN);
559        }
560
561        if (in_array($table, self::$existing_tables)) {
562            return true;
563        } else {
564            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__);
565            return false;
566        }
567    }
568
569    /**
570     * Tests if the given array of columns exists in the specified table.
571     *
572     * @param  string $table                The name of the table to search.
573     * @param  array  $columns              An array of column names.
574     * @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).
575     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
576     * @return bool                         true if column(s) exist.
577     */
578    public function columnExists($table, $columns, $strict=true, $use_cached_results=true)
579    {
580        $app =& App::getInstance();
581
582        if (!$this->_connected) {
583            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
584        }
585
586        // Ensure the table exists.
587        if (!$this->tableExists($table, $use_cached_results)) {
588            $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__);
589            return false;
590        }
591
592        // For single-value columns.
593        if (!is_array($columns)) {
594            $columns = array($columns);
595        }
596
597        if (!isset(self::$table_columns[$table]) || !$use_cached_results) {
598            // Populate and cache array of current columns for this table.
599            $stmt = $this->query(sprintf('DESCRIBE `%s`', $this->sanitizeIdentifier($table)));
600            self::$table_columns[$table] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
601        }
602
603        if ($strict) {
604            // Do an exact comparison of table schemas.
605            sort($columns);
606            sort(self::$table_columns[$table]);
607            return self::$table_columns[$table] == $columns;
608        } else {
609            // Only check that the specified columns are available in the table.
610            $match_columns = array_intersect(self::$table_columns[$table], $columns);
611            sort($columns);
612            sort($match_columns);
613            return $match_columns == $columns;
614        }
615    }
616
617    /**
618     * Returns the values of an ENUM or SET column, returning them as an array.
619     *
620     * @param  string $db_table   database table to lookup
621     * @param  string $db_col     database column to lookup
622     * @param  bool   $sort          Sort the output.
623     * @return array    Array of the set/enum values on success, false on failure.
624     */
625    public function getEnumValues($db_table, $db_col, $sort=false)
626    {
627        $app =& App::getInstance();
628
629        $stmt = $this->query(sprintf("SHOW COLUMNS FROM `%s` LIKE %s", $this->sanitizeIdentifier($db_table), $this->dbh->quote($db_col)), false);
630        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
631        if (isset($row['Type']) && preg_match('/^(?:enum|set)\((.*)\)$/i', $row['Type'], $matches) && isset($matches[1]) && '' != $matches[1]) {
632            $enum = str_getcsv($matches[1], ",", "'");
633            if ($sort) {
634                natsort($enum);
635            }
636            return $enum;
637        } else {
638            $app->logMsg(sprintf('No set or enum fields found in %s.%s', $db_table, $db_col), LOG_ERR, __FILE__, __LINE__);
639            return false;
640        }
641    }
642}
Note: See TracBrowser for help on using the repository browser.