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

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