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

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

Add PDO class. (And add a few /u unicode flags to preg functions in App - more of those coming in the next commit).

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