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

Last change on this file since 710 was 698, checked in by anonymous, 5 years ago

Improve error handling and display

File size: 20.1 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
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) {
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            );
202            $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
203
204            // Print helpful or pretty error?
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                }
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    {
241        $app =& App::getInstance();
242
243        if (!$this->_connected) {
244            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
245            return false;
246        }
247        $this->_connected = false;
248        $this->dbh = null;
249        return true;
250    }
251
252    /*
253    *
254    *
255    * @access   public
256    * @param
257    * @return
258    * @author   Quinn Comendant <quinn@strangecode.com>
259    * @version  1.0
260    * @since    03 Jul 2013 14:50:23
261    */
262    public function reconnect()
263    {
264        $this->close();
265        $this->connect();
266    }
267
268    /*
269    *
270    *
271    * @access   public
272    * @param
273    * @return
274    * @author   Quinn Comendant <quinn@strangecode.com>
275    * @since    09 Jul 2019 10:05:34
276    */
277    public function ping()
278    {
279        $app =& App::getInstance();
280
281        if (!$this->_connected) {
282            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
283            return false;
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) {
376            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
377            return false;
378        }
379
380        $this->_query_count++;
381
382        $debugqry = preg_replace("/\n[\t ]+/u", "\n", $query);
383        if ($this->getParam('db_always_debug') || $debug) {
384            if ($debug > 1) {
385                dump($debugqry, true, SC_DUMP_PRINT_R, __FILE__, __LINE__);
386            } else {
387                echo "<!-- ----------------- PDO query $this->_query_count ---------------------\n$debugqry\n-->\n";
388            }
389        }
390
391        // Ensure we have an active connection.
392        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
393        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
394        if (!$this->ping()) {
395            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
396            $this->reconnect();
397        }
398
399        // Execute!
400        try {
401            $stmt = $this->dbh->query($query);
402            if (!$stmt) {
403                throw new Exception('PDO::query returned false');
404            }
405        } catch (\Exception $e) {
406            $app->logMsg(sprintf('PDO query %s (%s): %s in query: %s', get_class($e), $e->getCode(), $e->getMessage(), $debugqry), LOG_EMERG, __FILE__, __LINE__);
407            if ($this->getParam('db_debug') && $app->getParam('display_errors')) {
408                if (!$app->isCLI()) {
409                    printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s<hr>%s</pre>', wordwrap($e->getMessage()), htmlspecialchars($debugqry));
410                }
411            }
412            // Die if db_die_on_failure = true, or just continue without connection
413            return $this->_fail();
414        }
415
416        return $stmt;
417    }
418
419    /*
420    *
421    *
422    * @access   public
423    * @param
424    * @return
425    * @author   Quinn Comendant <quinn@strangecode.com>
426    * @since    09 Jul 2019 19:26:37
427    */
428    public function prepare($query, ...$params)
429    {
430        $app =& App::getInstance();
431
432        if (!$this->_connected) {
433            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
434            return false;
435        }
436
437        $this->_query_count++;
438
439        $debugqry = preg_replace("/\n[\t ]+/u", "\n", $query);
440        if ($this->getParam('db_always_debug')) {
441            echo "<!-- ----------------- PDO prepare $this->_query_count ---------------------\n$debugqry\n-->\n";
442        }
443
444        // Ensure we have an active connection.
445        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
446        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
447        if (!$this->ping()) {
448            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
449            $this->reconnect();
450        }
451
452        // Execute!
453        try {
454            $stmt = $this->dbh->prepare($query, ...$params);
455            if (!$stmt) {
456                throw new Exception('PDO::query returned false');
457            }
458        } catch (\PDOException $e) {
459            $app->logMsg(sprintf('PDO prepare %s (%s): %s in query: %s', get_class($e), $e->getCode(), $e->getMessage(), $debugqry), LOG_EMERG, __FILE__, __LINE__);
460            if ($this->getParam('db_debug') && $app->getParam('display_errors')) {
461                if (!$app->isCLI()) {
462                    printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s<hr>%s</pre>', wordwrap($e->getMessage()), htmlspecialchars($debugqry));
463                }
464            }
465            // Die if db_die_on_failure = true, or just continue without connection
466            return $this->_fail();
467        }
468
469        return $stmt;
470    }
471
472    /*
473    *
474    *
475    * @access   public
476    * @param
477    * @return
478    * @author   Quinn Comendant <quinn@strangecode.com>
479    * @since    09 Jul 2019 19:42:48
480    */
481    public function lastInsertId($name=null)
482    {
483        return $this->dbh->lastInsertId($name);
484    }
485
486    /*
487    *
488    *
489    * @access   public
490    * @param
491    * @return
492    * @author   Quinn Comendant <quinn@strangecode.com>
493    * @since    09 Jul 2019 18:32:55
494    */
495    public function quote(...$params)
496    {
497        return $this->dbh->quote(...$params);
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    static function sanitizeIdentifier($str)
510    {
511        return preg_replace('/\W/u', '', $str);
512    }
513
514    /**
515     * Loads a list of tables in the current database into an array, and returns
516     * true if the requested table is found. Use this function to enable/disable
517     * functionality based upon the current available db tables or to dynamically
518     * create tables if missing.
519     *
520     * @param  string $table                The name of the table to search.
521     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
522     * @return bool                         true if given $table exists.
523     */
524    public function tableExists($table, $use_cached_results=true)
525    {
526        $app =& App::getInstance();
527
528        if (!$this->_connected) {
529            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
530            return false;
531        }
532
533        if (null === self::$existing_tables || !$use_cached_results) {
534            $stmt = $this->query('SHOW TABLES');
535            self::$existing_tables = $stmt->fetchAll(\PDO::FETCH_COLUMN);
536        }
537
538        if (in_array($table, self::$existing_tables)) {
539            return true;
540        } else {
541            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__);
542            return false;
543        }
544    }
545
546    /**
547     * Tests if the given array of columns exists in the specified table.
548     *
549     * @param  string $table                The name of the table to search.
550     * @param  array  $columns              An array of column names.
551     * @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).
552     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
553     * @return bool                         true if column(s) exist.
554     */
555    public function columnExists($table, $columns, $strict=true, $use_cached_results=true)
556    {
557        $app =& App::getInstance();
558
559        if (!$this->_connected) {
560            $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__);
561            return false;
562        }
563
564        // Ensure the table exists.
565        if (!$this->tableExists($table, $use_cached_results)) {
566            $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__);
567            return false;
568        }
569
570        // For single-value columns.
571        if (!is_array($columns)) {
572            $columns = array($columns);
573        }
574
575        if (!isset(self::$table_columns[$table]) || !$use_cached_results) {
576            // Populate and cache array of current columns for this table.
577            $stmt = $this->query(sprintf('DESCRIBE `%s`', $this->sanitizeIdentifier($table)));
578            self::$table_columns[$table] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
579        }
580
581        if ($strict) {
582            // Do an exact comparison of table schemas.
583            sort($columns);
584            sort(self::$table_columns[$table]);
585            return self::$table_columns[$table] == $columns;
586        } else {
587            // Only check that the specified columns are available in the table.
588            $match_columns = array_intersect(self::$table_columns[$table], $columns);
589            sort($columns);
590            sort($match_columns);
591            return $match_columns == $columns;
592        }
593    }
594
595    /**
596     * Returns the values of an ENUM or SET column, returning them as an array.
597     *
598     * @param  string $db_table   database table to lookup
599     * @param  string $db_col     database column to lookup
600     * @param  bool   $sort          Sort the output.
601     * @return array    Array of the set/enum values on success, false on failure.
602     */
603    public function getEnumValues($db_table, $db_col, $sort=false)
604    {
605        $app =& App::getInstance();
606
607        $stmt = $this->query(sprintf("SHOW COLUMNS FROM `%s` LIKE %s", $this->sanitizeIdentifier($db_table), $this->dbh->quote($db_col)), false);
608        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
609        if (isset($row['Type']) && preg_match('/^(?:enum|set)\((.*)\)$/i', $row['Type'], $matches) && isset($matches[1]) && '' != $matches[1]) {
610            $enum = str_getcsv($matches[1], ",", "'");
611            if ($sort) {
612                natsort($enum);
613            }
614            return $enum;
615        } else {
616            $app->logMsg(sprintf('No set or enum fields found in %s.%s', $db_table, $db_col), LOG_ERR, __FILE__, __LINE__);
617            return false;
618        }
619    }
620}
Note: See TracBrowser for help on using the repository browser.