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

Last change on this file since 747 was 747, checked in by anonymous, 3 years ago

Set default mysql connection charset to utf8mb4

File size: 21.0 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($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        $this->_connected = false;
258        $this->dbh = null;
259
260        return true;
261    }
262
263    /*
264    *
265    *
266    * @access   public
267    * @param
268    * @return
269    * @author   Quinn Comendant <quinn@strangecode.com>
270    * @version  1.0
271    * @since    03 Jul 2013 14:50:23
272    */
273    public function reconnect()
274    {
275        $this->close();
276        $this->connect();
277    }
278
279    /*
280    *
281    *
282    * @access   public
283    * @param
284    * @return
285    * @author   Quinn Comendant <quinn@strangecode.com>
286    * @since    09 Jul 2019 10:05:34
287    */
288    public function ping()
289    {
290        $app =& App::getInstance();
291
292        if (!$this->_connected) {
293            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
294        }
295
296        try {
297            $this->dbh->query('SELECT 1');
298        } catch (\PDOException $e) {
299            return false;
300        }
301
302        return true;
303    }
304
305    /*
306    * Die only if db_die_on_failure is true. This will be set to false for some cases
307    * when a database is not required for web app functionality.
308    *
309    * @access   public
310    * @param    string  $msg Print $msg when dying.
311    * @return   bool    false If we don't die.
312    * @author   Quinn Comendant <quinn@strangecode.com>
313    * @version  1.0
314    * @since    15 Jan 2007 15:59:00
315    */
316    protected function _fail()
317    {
318        $app =& App::getInstance();
319
320        if ($this->getParam('db_die_on_failure')) {
321            if (!$app->isCLI()) {
322                // For http requests, send a Service Unavailable header.
323                header(' ', true, 503);
324                echo _("This page is temporarily unavailable. Please try again in a few minutes.");
325            }
326            die;
327        } else {
328            return false;
329        }
330    }
331
332    /**
333     * Returns connection status
334     *
335     * @access  public
336     * @author  Quinn Comendant <quinn@strangecode.com>
337     * @since   28 Aug 2005 14:58:09
338     */
339    public function isConnected()
340    {
341        return (true === $this->_connected);
342    }
343
344    /*
345    * Return the total number of queries executed thus far.
346    *
347    * @access   public
348    * @return   int Number of queries
349    * @author   Quinn Comendant <quinn@strangecode.com>
350    * @version  1.0
351    * @since    15 Jun 2006 11:46:05
352    */
353    public function numQueries()
354    {
355        return $this->_query_count;
356    }
357
358    /**
359     * Reset cached items.
360     *
361     * @access  public
362     * @author  Quinn Comendant <quinn@strangecode.com>
363     * @since   28 Aug 2005 22:10:50
364     */
365    public function resetCache()
366    {
367        self::$existing_tables = null;
368        self::$table_columns = [];
369    }
370
371    /*
372    *
373    *
374    * @access   public
375    * @param    string  $query   The SQL query to execute
376    * @param    bool    $debug   If true, prints debugging info
377    * @return   resource         PDOStatement
378    * @author   Quinn Comendant <quinn@strangecode.com>
379    * @since    09 Jul 2019 10:00:00
380    */
381    public function query($query, $debug=false)
382    {
383        $app =& App::getInstance();
384
385        if (!$this->_connected) {
386            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
387        }
388
389        $this->_query_count++;
390
391        $debugqry = preg_replace('/\n[\t ]+/' . $app->getParam('preg_u'), "\n", $query);
392        if ($this->getParam('db_always_debug') || $debug) {
393            if ($debug > 1) {
394                dump($debugqry, true, SC_DUMP_PRINT_R, __FILE__, __LINE__);
395            } else {
396                echo "<!-- ----------------- PDO query $this->_query_count ---------------------\n$debugqry\n-->\n";
397            }
398        }
399
400        // Ensure we have an active connection.
401        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
402        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
403        if (!$this->ping()) {
404            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
405            $this->reconnect();
406        }
407
408        // Execute!
409        try {
410            $stmt = $this->dbh->query($query);
411            if (!$stmt) {
412                throw new \Exception('PDO::query returned false');
413            }
414        } catch (\Exception $e) {
415            $app->logMsg(sprintf('PDO query %s (%s): %s in query: %s', get_class($e), $e->getCode(), $e->getMessage(), $debugqry), LOG_EMERG, __FILE__, __LINE__);
416            if ($this->getParam('db_debug') && $app->getParam('display_errors')) {
417                if (!$app->isCLI()) {
418                    printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s<hr>%s</pre>', wordwrap($e->getMessage()), htmlspecialchars($debugqry));
419                }
420            }
421            // Die if db_die_on_failure = true, or just continue without connection
422            return $this->_fail();
423        }
424
425        return $stmt;
426    }
427
428    /*
429    *
430    *
431    * @access   public
432    * @param
433    * @return
434    * @author   Quinn Comendant <quinn@strangecode.com>
435    * @since    09 Jul 2019 19:26:37
436    */
437    public function prepare($query, ...$params)
438    {
439        $app =& App::getInstance();
440
441        if (!$this->_connected) {
442            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
443        }
444
445        $this->_query_count++;
446
447        $debugqry = preg_replace('/\n[\t ]+/' . $app->getParam('preg_u'), "\n", $query);
448        if ($this->getParam('db_always_debug')) {
449            echo "<!-- ----------------- PDO prepare $this->_query_count ---------------------\n$debugqry\n-->\n";
450        }
451
452        // Ensure we have an active connection.
453        // If we continue on a dead connection we might experience a "MySQL server has gone away" error.
454        // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
455        if (!$this->ping()) {
456            $app->logMsg(sprintf('MySQL ping failed; reconnecting
 ("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__);
457            $this->reconnect();
458        }
459
460        // Execute!
461        try {
462            $stmt = $this->dbh->prepare($query, ...$params);
463            if (!$stmt) {
464                throw new \Exception('PDO::prepare returned false');
465            }
466        } catch (\PDOException $e) {
467            $app->logMsg(sprintf('PDO prepare %s (%s): %s in query: %s', get_class($e), $e->getCode(), $e->getMessage(), $debugqry), LOG_EMERG, __FILE__, __LINE__);
468            if ($this->getParam('db_debug') && $app->getParam('display_errors')) {
469                if (!$app->isCLI()) {
470                    printf('<pre style="padding:1em;background:#ddd;font:0.9rem monospace;">%s<hr>%s</pre>', wordwrap($e->getMessage()), htmlspecialchars($debugqry));
471                }
472            }
473            // Die if db_die_on_failure = true, or just continue without connection
474            return $this->_fail();
475        }
476
477        return $stmt;
478    }
479
480    /*
481    *
482    *
483    * @access   public
484    * @param
485    * @return
486    * @author   Quinn Comendant <quinn@strangecode.com>
487    * @since    09 Jul 2019 19:42:48
488    */
489    public function lastInsertId($name=null)
490    {
491        return $this->dbh->lastInsertId($name);
492    }
493
494    /*
495    *
496    *
497    * @access   public
498    * @param
499    * @return
500    * @author   Quinn Comendant <quinn@strangecode.com>
501    * @since    09 Jul 2019 18:32:55
502    */
503    public function quote(...$params)
504    {
505        return $this->dbh->quote(...$params);
506    }
507
508    /*
509    * Remove unsafe characters from SQL identifiers (tables, views, indexes, columns, and constraints).
510    *
511    * @access   public
512    * @param    string  $idname     Identifier name.
513    * @return   string              Clean string.
514    * @author   Quinn Comendant <quinn@strangecode.com>
515    * @since    09 Jul 2019 18:32:55
516    */
517    static function sanitizeIdentifier($idname)
518    {
519        $app =& App::getInstance();
520
521        return preg_replace('/\W/' . $app->getParam('preg_u'), '', $idname);
522    }
523
524    /**
525     * Loads a list of tables in the current database into an array, and returns
526     * true if the requested table is found. Use this function to enable/disable
527     * functionality based upon the current available db tables or to dynamically
528     * create tables if missing.
529     *
530     * @param  string $table                The name of the table to search.
531     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
532     * @return bool                         true if given $table exists.
533     */
534    public function tableExists($table, $use_cached_results=true)
535    {
536        $app =& App::getInstance();
537
538        if (!$this->_connected) {
539            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
540        }
541
542        if (null === self::$existing_tables || !$use_cached_results) {
543            $stmt = $this->query('SHOW TABLES');
544            self::$existing_tables = $stmt->fetchAll(\PDO::FETCH_COLUMN);
545        }
546
547        if (in_array($table, self::$existing_tables)) {
548            return true;
549        } else {
550            $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__);
551            return false;
552        }
553    }
554
555    /**
556     * Tests if the given array of columns exists in the specified table.
557     *
558     * @param  string $table                The name of the table to search.
559     * @param  array  $columns              An array of column names.
560     * @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).
561     * @param  bool   $use_cached_results   Get fresh table info (in case DB changed).
562     * @return bool                         true if column(s) exist.
563     */
564    public function columnExists($table, $columns, $strict=true, $use_cached_results=true)
565    {
566        $app =& App::getInstance();
567
568        if (!$this->_connected) {
569            throw new \Exception(sprintf('No DB connection to run %s', __METHOD__));
570        }
571
572        // Ensure the table exists.
573        if (!$this->tableExists($table, $use_cached_results)) {
574            $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__);
575            return false;
576        }
577
578        // For single-value columns.
579        if (!is_array($columns)) {
580            $columns = array($columns);
581        }
582
583        if (!isset(self::$table_columns[$table]) || !$use_cached_results) {
584            // Populate and cache array of current columns for this table.
585            $stmt = $this->query(sprintf('DESCRIBE `%s`', $this->sanitizeIdentifier($table)));
586            self::$table_columns[$table] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
587        }
588
589        if ($strict) {
590            // Do an exact comparison of table schemas.
591            sort($columns);
592            sort(self::$table_columns[$table]);
593            return self::$table_columns[$table] == $columns;
594        } else {
595            // Only check that the specified columns are available in the table.
596            $match_columns = array_intersect(self::$table_columns[$table], $columns);
597            sort($columns);
598            sort($match_columns);
599            return $match_columns == $columns;
600        }
601    }
602
603    /**
604     * Returns the values of an ENUM or SET column, returning them as an array.
605     *
606     * @param  string $db_table   database table to lookup
607     * @param  string $db_col     database column to lookup
608     * @param  bool   $sort          Sort the output.
609     * @return array    Array of the set/enum values on success, false on failure.
610     */
611    public function getEnumValues($db_table, $db_col, $sort=false)
612    {
613        $app =& App::getInstance();
614
615        $stmt = $this->query(sprintf("SHOW COLUMNS FROM `%s` LIKE %s", $this->sanitizeIdentifier($db_table), $this->dbh->quote($db_col)), false);
616        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
617        if (isset($row['Type']) && preg_match('/^(?:enum|set)\((.*)\)$/i', $row['Type'], $matches) && isset($matches[1]) && '' != $matches[1]) {
618            $enum = str_getcsv($matches[1], ",", "'");
619            if ($sort) {
620                natsort($enum);
621            }
622            return $enum;
623        } else {
624            $app->logMsg(sprintf('No set or enum fields found in %s.%s', $db_table, $db_col), LOG_ERR, __FILE__, __LINE__);
625            return false;
626        }
627    }
628}
Note: See TracBrowser for help on using the repository browser.