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/codebase/> |
---|
5 | * Copyright 2001-2012 Strangecode, LLC |
---|
6 | * |
---|
7 | * This file is part of The Strangecode Codebase. |
---|
8 | * |
---|
9 | * The Strangecode Codebase is free software: you can redistribute it and/or |
---|
10 | * modify it under the terms of the GNU General Public License as published by the |
---|
11 | * Free Software Foundation, either version 3 of the License, or (at your option) |
---|
12 | * any later version. |
---|
13 | * |
---|
14 | * The Strangecode Codebase is distributed in the hope that it will be useful, but |
---|
15 | * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
---|
16 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
---|
17 | * details. |
---|
18 | * |
---|
19 | * You should have received a copy of the GNU General Public License along with |
---|
20 | * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>. |
---|
21 | */ |
---|
22 | |
---|
23 | /** |
---|
24 | * DB.inc.php |
---|
25 | * |
---|
26 | * Very lightweight DB semi-abstraction layer. Mainly to catch errors with mysql_query, with some goodies. |
---|
27 | * |
---|
28 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
29 | * @version 2.1 |
---|
30 | */ |
---|
31 | |
---|
32 | class DB |
---|
33 | { |
---|
34 | |
---|
35 | // A place to keep an object instance for the singleton pattern. |
---|
36 | protected static $instance = null; |
---|
37 | |
---|
38 | // If $db->connect has successfully opened a db connection. |
---|
39 | protected $_connected = false; |
---|
40 | |
---|
41 | // Database handle. |
---|
42 | public $dbh; |
---|
43 | |
---|
44 | // Count how many queries run during the whole instance. |
---|
45 | protected $_query_count = 0; |
---|
46 | |
---|
47 | // Hash of DB parameters. |
---|
48 | protected $_params = array(); |
---|
49 | |
---|
50 | // Default parameters. |
---|
51 | protected $_param_defaults = array( |
---|
52 | |
---|
53 | // DB passwords should be set as apache environment variables in httpd.conf, readable only by root. |
---|
54 | 'db_server' => 'localhost', |
---|
55 | 'db_name' => null, |
---|
56 | 'db_user' => null, |
---|
57 | 'db_pass' => null, |
---|
58 | |
---|
59 | // Display all SQL queries. FALSE recommended for production sites. |
---|
60 | 'db_always_debug' => false, |
---|
61 | |
---|
62 | // Display db errors. FALSE recommended for production sites. |
---|
63 | 'db_debug' => false, |
---|
64 | |
---|
65 | // Script stops on db error. TRUE recommended for production sites. |
---|
66 | 'db_die_on_failure' => true, |
---|
67 | |
---|
68 | // Special date settings. These will dynamically changes depending on MySQL version or settings. |
---|
69 | 'zero_date' => '0000-00-00', |
---|
70 | 'infinity_date' => '9999-12-31', |
---|
71 | ); |
---|
72 | |
---|
73 | // Translate between HTML and MySQL character set names. |
---|
74 | public $mysql_character_sets = array( |
---|
75 | 'utf-8' => 'utf8', |
---|
76 | 'iso-8859-1' => 'latin1', |
---|
77 | ); |
---|
78 | |
---|
79 | // Caches. |
---|
80 | protected static $existing_tables = null; |
---|
81 | protected static $table_columns = null; |
---|
82 | |
---|
83 | /** |
---|
84 | * Constructor. |
---|
85 | */ |
---|
86 | public function __construct() |
---|
87 | { |
---|
88 | // Initialize default parameters. |
---|
89 | $this->_params = array_merge($this->_params, $this->_param_defaults); |
---|
90 | } |
---|
91 | |
---|
92 | /** |
---|
93 | * This method enforces the singleton pattern for this class. |
---|
94 | * |
---|
95 | * @return object Reference to the global DB object. |
---|
96 | * @access public |
---|
97 | * @static |
---|
98 | */ |
---|
99 | public static function &getInstance() |
---|
100 | { |
---|
101 | if (self::$instance === null) { |
---|
102 | self::$instance = new self(); |
---|
103 | } |
---|
104 | |
---|
105 | return self::$instance; |
---|
106 | } |
---|
107 | |
---|
108 | /** |
---|
109 | * Set (or overwrite existing) parameters by passing an array of new parameters. |
---|
110 | * |
---|
111 | * @access public |
---|
112 | * |
---|
113 | * @param array $params Array of parameters (key => val pairs). |
---|
114 | */ |
---|
115 | public function setParam($params) |
---|
116 | { |
---|
117 | $app =& App::getInstance(); |
---|
118 | |
---|
119 | if (isset($params) && is_array($params)) { |
---|
120 | // Merge new parameters with old overriding only those passed. |
---|
121 | $this->_params = array_merge($this->_params, $params); |
---|
122 | } else { |
---|
123 | $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__); |
---|
124 | } |
---|
125 | } |
---|
126 | |
---|
127 | /** |
---|
128 | * Return the value of a parameter, if it exists. |
---|
129 | * |
---|
130 | * @access public |
---|
131 | * @param string $param Which parameter to return. |
---|
132 | * @return mixed Configured parameter value. |
---|
133 | */ |
---|
134 | public function getParam($param) |
---|
135 | { |
---|
136 | $app =& App::getInstance(); |
---|
137 | |
---|
138 | if (array_key_exists($param, $this->_params)) { |
---|
139 | return $this->_params[$param]; |
---|
140 | } else { |
---|
141 | $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__); |
---|
142 | return null; |
---|
143 | } |
---|
144 | } |
---|
145 | |
---|
146 | /** |
---|
147 | * Connect to database with credentials in params. |
---|
148 | * |
---|
149 | * @access public |
---|
150 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
151 | * @since 28 Aug 2005 14:02:49 |
---|
152 | */ |
---|
153 | public function connect() |
---|
154 | { |
---|
155 | $app =& App::getInstance(); |
---|
156 | |
---|
157 | if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) { |
---|
158 | $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__); |
---|
159 | return false; |
---|
160 | } |
---|
161 | |
---|
162 | if (!$this->getParam('db_server')) { |
---|
163 | // If db_server not specified, assume localhost. |
---|
164 | $this->setParam(array('db_server' => 'localhost')); |
---|
165 | } |
---|
166 | |
---|
167 | // Connect to database. Always create a new link to the server. |
---|
168 | // Connection errors are suppressed so we can do our own error management below. |
---|
169 | if ($this->dbh = @mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) { |
---|
170 | // Select database |
---|
171 | mysql_select_db($this->getParam('db_name'), $this->dbh); |
---|
172 | } |
---|
173 | |
---|
174 | // Test for connection errors. |
---|
175 | if (!$this->dbh || mysql_error($this->dbh)) { |
---|
176 | $mysql_error_msg = $this->dbh ? 'Codebase MySQL error: (' . mysql_errno($this->dbh) . ') ' . mysql_error($this->dbh) : sprintf('Codebase MySQL 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')); |
---|
177 | $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__); |
---|
178 | |
---|
179 | // Print helpful or pretty error? |
---|
180 | if ($this->getParam('db_debug')) { |
---|
181 | echo $mysql_error_msg . "\n"; |
---|
182 | } |
---|
183 | |
---|
184 | // Die if db_die_on_failure = true, or just continue without connection. |
---|
185 | return $this->_fail(); |
---|
186 | } |
---|
187 | |
---|
188 | // DB connection success! |
---|
189 | $this->_connected = true; |
---|
190 | |
---|
191 | // Tell MySQL what character set we're using. Available only on MySQL versions > 4.01.01. |
---|
192 | if ('' != $app->getParam('character_set') && isset($this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))])) { |
---|
193 | $this->query("/*!40101 SET NAMES '" . $this->mysql_character_sets[mb_strtolower($app->getParam('character_set'))] . "' */"); |
---|
194 | } else { |
---|
195 | $app->logMsg(sprintf('%s is not a known character_set.', $app->getParam('character_set')), LOG_ERR, __FILE__, __LINE__); |
---|
196 | } |
---|
197 | |
---|
198 | // Update config for this version of MySQL. |
---|
199 | if (version_compare(mysql_get_server_info(), '5.7.4', '>=')) { |
---|
200 | $this->setParam(array('zero_date' => '1000-01-01')); |
---|
201 | } |
---|
202 | |
---|
203 | return true; |
---|
204 | } |
---|
205 | |
---|
206 | /** |
---|
207 | * Close db connection. |
---|
208 | * |
---|
209 | * @access public |
---|
210 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
211 | * @since 28 Aug 2005 14:32:01 |
---|
212 | */ |
---|
213 | public function close() |
---|
214 | { |
---|
215 | if (!$this->_connected) { |
---|
216 | return false; |
---|
217 | } |
---|
218 | $this->_connected = false; |
---|
219 | return mysql_close($this->dbh); |
---|
220 | } |
---|
221 | |
---|
222 | /* |
---|
223 | * |
---|
224 | * |
---|
225 | * @access public |
---|
226 | * @param |
---|
227 | * @return |
---|
228 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
229 | * @version 1.0 |
---|
230 | * @since 03 Jul 2013 14:50:23 |
---|
231 | */ |
---|
232 | public function reconnect() |
---|
233 | { |
---|
234 | $this->close(); |
---|
235 | $this->connect(); |
---|
236 | } |
---|
237 | |
---|
238 | /* |
---|
239 | * Die only if db_die_on_failure is true. This will be set to false for some cases |
---|
240 | * when a database is not required for web app functionality. |
---|
241 | * |
---|
242 | * @access public |
---|
243 | * @param string $msg Print $msg when dying. |
---|
244 | * @return bool false If we don't die. |
---|
245 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
246 | * @version 1.0 |
---|
247 | * @since 15 Jan 2007 15:59:00 |
---|
248 | */ |
---|
249 | protected function _fail() |
---|
250 | { |
---|
251 | $app =& App::getInstance(); |
---|
252 | |
---|
253 | if ($this->getParam('db_die_on_failure')) { |
---|
254 | if (!$app->cli) { |
---|
255 | // For http requests, send a Service Unavailable header. |
---|
256 | header(' ', true, 503); |
---|
257 | echo _("This page is temporarily unavailable. Please try again in a few minutes."); |
---|
258 | } |
---|
259 | die; |
---|
260 | } else { |
---|
261 | return false; |
---|
262 | } |
---|
263 | } |
---|
264 | |
---|
265 | /** |
---|
266 | * Return the current database handler. |
---|
267 | * |
---|
268 | * @access public |
---|
269 | * @return resource Current value of $this->dbh. |
---|
270 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
271 | * @since 20 Aug 2005 13:50:36 |
---|
272 | */ |
---|
273 | public function getDBH() |
---|
274 | { |
---|
275 | if (!$this->_connected) { |
---|
276 | return false; |
---|
277 | } |
---|
278 | |
---|
279 | return $this->dbh; |
---|
280 | } |
---|
281 | |
---|
282 | /** |
---|
283 | * Returns connection status |
---|
284 | * |
---|
285 | * @access public |
---|
286 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
287 | * @since 28 Aug 2005 14:58:09 |
---|
288 | */ |
---|
289 | public function isConnected() |
---|
290 | { |
---|
291 | return (true === $this->_connected); |
---|
292 | } |
---|
293 | |
---|
294 | /** |
---|
295 | * Returns a properly escaped string using mysql_real_escape_string() with the current connection's charset. |
---|
296 | * |
---|
297 | * @access public |
---|
298 | * @param string $string Input string to be sent as SQL query. |
---|
299 | * @return string Escaped string from mysql_real_escape_string() |
---|
300 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
301 | * @since 06 Mar 2006 16:41:32 |
---|
302 | */ |
---|
303 | public function escapeString($string) |
---|
304 | { |
---|
305 | if (!$this->_connected) { |
---|
306 | return false; |
---|
307 | } |
---|
308 | |
---|
309 | return mysql_real_escape_string($string, $this->dbh); |
---|
310 | } |
---|
311 | |
---|
312 | /** |
---|
313 | * A wrapper for mysql_query. Allows us to set the database link_identifier, |
---|
314 | * to trap errors and ease debugging. |
---|
315 | * |
---|
316 | * @param string $query The SQL query to execute |
---|
317 | * @param bool $debug If true, prints debugging info |
---|
318 | * @return resource Query identifier |
---|
319 | */ |
---|
320 | public function query($query, $debug=false) |
---|
321 | { |
---|
322 | $app =& App::getInstance(); |
---|
323 | |
---|
324 | if (!$this->_connected) { |
---|
325 | return false; |
---|
326 | } |
---|
327 | |
---|
328 | $this->_query_count++; |
---|
329 | |
---|
330 | $debugqry = preg_replace("/\n[\t ]+/", "\n", $query); |
---|
331 | if ($this->getParam('db_always_debug') || $debug) { |
---|
332 | echo "<!-- ----------------- Query $this->_query_count ---------------------\n$debugqry\n-->\n"; |
---|
333 | } |
---|
334 | |
---|
335 | // Ensure we have an active connection. |
---|
336 | // If we continue on a dead connection we might experience a "MySQL server has gone away" error. |
---|
337 | // http://dev.mysql.com/doc/refman/5.0/en/gone-away.html |
---|
338 | if (!mysql_ping($this->dbh)) { |
---|
339 | $app->logMsg(sprintf('MySQL ping failed; reconnecting⊠("%s")', truncate(trim($debugqry), 150)), LOG_DEBUG, __FILE__, __LINE__); |
---|
340 | $this->reconnect(); |
---|
341 | } |
---|
342 | |
---|
343 | // Execute! |
---|
344 | $qid = mysql_query($query, $this->dbh); |
---|
345 | |
---|
346 | // Error checking. |
---|
347 | if (!$qid || mysql_error($this->dbh)) { |
---|
348 | $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__); |
---|
349 | if ($this->getParam('db_debug')) { |
---|
350 | if (!$app->cli) { |
---|
351 | echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>'; |
---|
352 | } |
---|
353 | } |
---|
354 | // Die if db_die_on_failure = true, or just continue without connection |
---|
355 | return $this->_fail(); |
---|
356 | } |
---|
357 | |
---|
358 | return $qid; |
---|
359 | } |
---|
360 | |
---|
361 | /** |
---|
362 | * Loads a list of tables in the current database into an array, and returns |
---|
363 | * true if the requested table is found. Use this function to enable/disable |
---|
364 | * functionality based upon the current available db tables or to dynamically |
---|
365 | * create tables if missing. |
---|
366 | * |
---|
367 | * @param string $table The name of the table to search. |
---|
368 | * @param bool $use_cached_results Get fresh table info (in case DB changed). |
---|
369 | * @return bool true if given $table exists. |
---|
370 | */ |
---|
371 | public function tableExists($table, $use_cached_results=true) |
---|
372 | { |
---|
373 | $app =& App::getInstance(); |
---|
374 | |
---|
375 | if (!$this->_connected) { |
---|
376 | return false; |
---|
377 | } |
---|
378 | |
---|
379 | if (is_null(self::$existing_tables) || !$use_cached_results) { |
---|
380 | self::$existing_tables = array(); |
---|
381 | $qid = $this->query("SHOW TABLES"); |
---|
382 | while (list($row) = mysql_fetch_row($qid)) { |
---|
383 | self::$existing_tables[] = $row; |
---|
384 | } |
---|
385 | } |
---|
386 | |
---|
387 | if (in_array($table, self::$existing_tables)) { |
---|
388 | return true; |
---|
389 | } else { |
---|
390 | $app->logMsg(sprintf('Nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_INFO, __FILE__, __LINE__); |
---|
391 | return false; |
---|
392 | } |
---|
393 | } |
---|
394 | |
---|
395 | /** |
---|
396 | * Tests if the given array of columns exists in the specified table. |
---|
397 | * |
---|
398 | * @param string $table The name of the table to search. |
---|
399 | * @param array $columns An array of column names. |
---|
400 | * @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). |
---|
401 | * @param bool $use_cached_results Get fresh table info (in case DB changed). |
---|
402 | * @return bool true if column(s) exist. |
---|
403 | */ |
---|
404 | public function columnExists($table, $columns, $strict=true, $use_cached_results=true) |
---|
405 | { |
---|
406 | $app =& App::getInstance(); |
---|
407 | |
---|
408 | if (!$this->_connected) { |
---|
409 | $app->logMsg(sprintf('No DB connection to run %s', __METHOD__), LOG_NOTICE, __FILE__, __LINE__); |
---|
410 | return false; |
---|
411 | } |
---|
412 | |
---|
413 | // Ensure the table exists. |
---|
414 | if (!$this->tableExists($table, $use_cached_results)) { |
---|
415 | $app->logMsg(sprintf('Table does not exist: %s', $table), LOG_NOTICE, __FILE__, __LINE__); |
---|
416 | return false; |
---|
417 | } |
---|
418 | |
---|
419 | // For single-value columns. |
---|
420 | if (!is_array($columns)) { |
---|
421 | $columns = array($columns); |
---|
422 | } |
---|
423 | |
---|
424 | if (!isset(self::$table_columns[$table]) || !$use_cached_results) { |
---|
425 | // Populate and cache array of current columns for this table. |
---|
426 | self::$table_columns[$table] = array(); |
---|
427 | $qid = $this->query("DESCRIBE $table"); |
---|
428 | while ($row = mysql_fetch_row($qid)) { |
---|
429 | self::$table_columns[$table][] = $row[0]; |
---|
430 | } |
---|
431 | } |
---|
432 | |
---|
433 | if ($strict) { |
---|
434 | // Do an exact comparison of table schemas. |
---|
435 | sort($columns); |
---|
436 | sort(self::$table_columns[$table]); |
---|
437 | return self::$table_columns[$table] == $columns; |
---|
438 | } else { |
---|
439 | // Only check that the specified columns are available in the table. |
---|
440 | $match_columns = array_intersect(self::$table_columns[$table], $columns); |
---|
441 | sort($columns); |
---|
442 | sort($match_columns); |
---|
443 | return $match_columns == $columns; |
---|
444 | } |
---|
445 | } |
---|
446 | |
---|
447 | /* |
---|
448 | * Return the total number of queries executed thus far. |
---|
449 | * |
---|
450 | * @access public |
---|
451 | * @return int Number of queries |
---|
452 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
453 | * @version 1.0 |
---|
454 | * @since 15 Jun 2006 11:46:05 |
---|
455 | */ |
---|
456 | public function numQueries() |
---|
457 | { |
---|
458 | return $this->_query_count; |
---|
459 | } |
---|
460 | |
---|
461 | /** |
---|
462 | * Reset cached items. |
---|
463 | * |
---|
464 | * @access public |
---|
465 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
466 | * @since 28 Aug 2005 22:10:50 |
---|
467 | */ |
---|
468 | public function resetCache() |
---|
469 | { |
---|
470 | self::$existing_tables = null; |
---|
471 | self::$table_columns = null; |
---|
472 | } |
---|
473 | |
---|
474 | /** |
---|
475 | * Returns the values of an ENUM or SET column, returning them as an array. |
---|
476 | * |
---|
477 | * @param string $db_table database table to lookup |
---|
478 | * @param string $db_col database column to lookup |
---|
479 | * @param bool $sort Sort the output. |
---|
480 | * @return array Array of the set/enum values on success, false on failure. |
---|
481 | */ |
---|
482 | public function getEnumValues($db_table, $db_col, $sort=false) |
---|
483 | { |
---|
484 | $app =& App::getInstance(); |
---|
485 | |
---|
486 | $qid = $this->query("SHOW COLUMNS FROM " . $this->escapeString($db_table) . " LIKE '" . $this->escapeString($db_col) . "'", false); |
---|
487 | |
---|
488 | $row = mysql_fetch_row($qid); |
---|
489 | if (preg_match('/^enum|^set/i', $row[1]) && preg_match_all("/'([^']*)'/", $row[1], $matches)) { |
---|
490 | if ($sort) { |
---|
491 | natsort($matches[1]); |
---|
492 | } |
---|
493 | return $matches[1]; |
---|
494 | } else { |
---|
495 | $app->logMsg(sprintf('No set or enum fields found in %s.%s', $db_table, $db_col), LOG_ERR, __FILE__, __LINE__); |
---|
496 | return false; |
---|
497 | } |
---|
498 | } |
---|
499 | |
---|
500 | |
---|
501 | } // End. |
---|
502 | |
---|