source: trunk/lib/PDO.inc.php @ 733

Last change on this file since 733 was 733, checked in by anonymous, 4 years ago

Add PDO connect retries. Minor fixes related to DB env vars.

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