In mail.php, we don't want to double encode fields so in send() create local variable...
[isso.git] / db.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright ©2002-[#]year[#] Blue Static
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; version [#]gpl[#] of the License.
10 || #
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 || # more details.
15 || #
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
21
22 /**
23 * Abstract Database Layer
24 * db.php
25 *
26 * @package ISSO
27 */
28
29 /**
30 * Abstract Database Layer
31 *
32 * This class provides an abstract template for all RDBMS layers. All
33 * ISSO abstraction layers should inherit this class. It provides error
34 * reporting, SQL analysis, and general connection functionality.
35 *
36 * Constants:
37 * [required] ISSO_DB_LAYER - The name of the DB layer module used in the application
38 * ISSO_SHOW_QUERIES_LIVE - Show queries in page output as they are sent
39 *
40 * @author Blue Static
41 * @copyright Copyright ©2002 - [#]year[#], Blue Static
42 * @version $Revision$
43 * @package ISSO
44 *
45 */
46 class DB_Abstract
47 {
48 /**
49 * Framework registry object
50 * @var object
51 * @access protected
52 */
53 var $registry = null;
54
55 /**
56 * Determines whether or not errors should be shown
57 * @var bool
58 * @access public
59 */
60 var $showerrors = true;
61
62 /**
63 * Current error number
64 * @var integer
65 * @access protected
66 */
67 var $errnum = 0;
68
69 /**
70 * Description of current error
71 * @var string
72 * @access protected
73 */
74 var $errstr = '';
75
76 /**
77 * Currend open MySQL connexion
78 * @var resource
79 * @access protected
80 */
81 var $dblink = null;
82
83 /**
84 * Current query ID
85 * @var integer
86 * @access protected
87 */
88 var $result = null;
89
90 /**
91 * Current query string
92 * @var string
93 * @access protected
94 */
95 var $querystr = '';
96
97 /**
98 * History of all executed queryies
99 * @var array
100 * @access protected
101 */
102 var $history = array();
103
104 /**
105 * Command mapping list
106 * @var array
107 * @access protected
108 */
109 var $commands = array(
110 'pconnect' => '%server %user %password %database',
111 'connect' => '%server %user %password %database',
112 'query' => '%link %query',
113 'error_num' => '%link',
114 'error_str' => '%link',
115 'escape_string' => '%link %string',
116 'escape_binary' => '%string',
117 'unescape_binary' => '%string',
118 'fetch_assoc' => '%result',
119 'fetch_row' => '%result',
120 'fetch_object' => '%result',
121 'free_result' => '%result',
122 'insert_id' => '%link',
123 'num_rows' => '%result',
124 'affected_rows' => '%result'
125 );
126
127 // ###################################################################
128 /**
129 * Constructor
130 */
131 function __construct(&$registry)
132 {
133 $this->registry =& $registry;
134
135 // because ivars and call_user_func() are conspiring against us...
136 foreach ($this->commands AS $key => $string)
137 {
138 if (strpos($string, '$this->') !== false)
139 {
140 $this->commands["$key"] = array($this, str_replace('$this->', '', $string));
141 }
142 }
143 }
144
145 // ###################################################################
146 /**
147 * (PHP 4) Constructor
148 */
149 function DB_Abstract(&$registry)
150 {
151 $this->__construct($registry);
152 }
153
154 // ###################################################################
155 /**
156 * Initializes the class and all subclasses under a common package name
157 *
158 * @access protected
159 *
160 * @return string The package name
161 */
162 function init_as_package()
163 {
164 if (!defined('ISSO_DB_LAYER'))
165 {
166 define('ISSO_DB_LAYER', get_class($this));
167 trigger_error('ISSO_DB_LAYER was defined automatically by DB::init_as_package(). Define the constant yourself to remove this warning', E_USER_WARNING);
168 }
169
170 return 'db';
171 }
172
173 // ###################################################################
174 /**
175 * Connect to a the specified database
176 *
177 * @access public
178 *
179 * @param string Server name
180 * @param string User name
181 * @param string Password
182 * @param string Database name
183 * @param bool Use p-connect?
184 *
185 * @return bool Result of connect
186 */
187 function connect($server, $user, $password, $database, $pconnect)
188 {
189 if ($this->dblink == false)
190 {
191 $this->dblink = call_user_func(($pconnect ? $this->commands['pconnect'] : $this->commands['connect']), $server, $user, $password, $database);
192
193 if ($this->dblink == false)
194 {
195 $this->error('DB-Link == false, cannot connect');
196 return false;
197 }
198
199 return true;
200 }
201 }
202
203 // ###################################################################
204 /**
205 * Send a query to the open database link
206 *
207 * @access public
208 *
209 * @param string Query string
210 *
211 * @return integer Result
212 */
213 function query($string)
214 {
215 $time = microtime();
216
217 $this->querystr = $string;
218 $this->result = @call_user_func($this->commands['query'], $this->dblink, $string);
219
220 if (!$this->result)
221 {
222 $this->error('Invalid SQL query');
223 }
224
225 $this->history[] = $history = array('query' => $string, 'time' => ($this->registry->is_loaded('functions') ? $this->registry->modules['functions']->fetch_microtime_diff($time) : 0), 'trace' => $this->registry->format_debug_trace(debug_backtrace()));
226
227 if (defined('ISSO_SHOW_QUERIES_LIVE'))
228 {
229 if (constant('ISSO_SHOW_QUERIES_LIVE'))
230 {
231 print($this->construct_query_debug($history));
232 }
233 }
234
235 return $this->result;
236 }
237
238 // ###################################################################
239 /**
240 * Escape a string (depending on character set, if supported)
241 *
242 * @access public
243 *
244 * @param string String to be escaped
245 *
246 * @return string Escaped string
247 */
248 function escape_string($string)
249 {
250 return call_user_func($this->commands['escape_string'], $this->dblink, $string);
251 }
252
253 // ###################################################################
254 /**
255 * Escapes a binary string for insertion into the database
256 *
257 * @access public
258 *
259 * @param string Unescaped data
260 *
261 * @return string Escaped binary data
262 */
263 function escape_binary($binary)
264 {
265 return call_user_func($this->commands['escape_binary'], $binary);
266 }
267
268 // ###################################################################
269 /**
270 * Unescapes a binary string that was fetched from the database
271 *
272 * @access public
273 *
274 * @param string Escaped data
275 *
276 * @return string Unescaped binary data
277 */
278 function unescape_binary($binary)
279 {
280 return call_user_func($this->commands['unescape_binary'], $binary);
281 }
282
283 // ###################################################################
284 /**
285 * Fetch the query result as an array
286 *
287 * @access public
288 *
289 * @param integer Result
290 * @param bool Return an associative array?
291 *
292 * @return array A row of the query result
293 */
294 function fetch_array($result, $assoc = true)
295 {
296 return call_user_func($this->commands[ ($assoc ? 'fetch_assoc' : 'fetch_row') ], $result);
297 }
298
299 // ###################################################################
300 /**
301 * Fetch the query result as an object
302 *
303 * @access public
304 *
305 * @param integer Result
306 *
307 * @return object An object with the query result
308 */
309 function fetch_object($result)
310 {
311 return call_user_func($this->commands['fetch_object'], $result);
312 }
313
314 // ###################################################################
315 /**
316 * Send a query and return the first row of the results
317 *
318 * @access public
319 *
320 * @param string Query string
321 * @param string Result return function (in the database layer)
322 *
323 * @return mixed Results in variable formats
324 */
325 function query_first($string, $callback = 'fetch_array')
326 {
327 $resource = $this->query($string);
328 if ($resource)
329 {
330 $return = $this->$callback($resource);
331 $this->free_result($resource);
332 return $return;
333 }
334 else
335 {
336 return false;
337 }
338 }
339
340 // ###################################################################
341 /**
342 * Free the current query result
343 *
344 * @access public
345 *
346 * @param integer Result
347 */
348 function free_result($result)
349 {
350 call_user_func($this->commands['free_result'], $result);
351 $this->result = null;
352 $this->querystr = '';
353 }
354
355 // ###################################################################
356 /**
357 * Fetch the unique ID of the record just inserted
358 *
359 * @access public
360 *
361 * @return integer Insert-ID
362 */
363 function insert_id()
364 {
365 return call_user_func($this->commands['insert_id'], $this->dblink);
366 }
367
368 // ###################################################################
369 /**
370 * Fetch the number of rows in the result
371 *
372 * @access public
373 *
374 * @param integer Result
375 *
376 * @return integer Number of rows
377 */
378 function num_rows($result)
379 {
380 return call_user_func($this->commands['num_rows'], $result);
381 }
382
383 // ###################################################################
384 /**
385 * Fetch the number of rows affected by the query
386 *
387 * @access public
388 *
389 * @param integer Result
390 *
391 * @return integer Number of affected rows
392 */
393 function affected_rows($result)
394 {
395 return call_user_func($this->commands['affected_rows'], $result);
396 }
397
398 // ###################################################################
399 /**
400 * Sends the command to start a transaction. This command should never
401 * be reached as it's always overridden
402 *
403 * @access public
404 */
405 function transaction_start()
406 {
407 trigger_error('DB_Abstract::transaction_start() needs to be overridden when subclassed', E_USER_ERROR);
408 }
409
410 // ###################################################################
411 /**
412 * Sends the command to set this as a savepoint. This command should never
413 * be reached as it's always overridden
414 *
415 * @access public
416 *
417 * @param string Named savepoint
418 */
419 function transaction_savepoint($name)
420 {
421 trigger_error('DB_Abstract::transaction_savepoint() needs to be overridden when subclassed', E_USER_ERROR);
422 }
423
424 // ###################################################################
425 /**
426 * Sends the command to rollback to a given savepoint. This command
427 * should never be reached as it's always overridden
428 *
429 * @access public
430 *
431 * @param string Named savepoint
432 */
433 function transaction_rollback($name)
434 {
435 trigger_error('DB_Abstract::transaction_rollback() needs to be overridden when subclassed', E_USER_ERROR);
436 }
437
438 // ###################################################################
439 /**
440 * Sends the command to commit the entire transaction. This command
441 * should never be reached as it's always overridden
442 *
443 * @access public
444 */
445 function transaction_commit($name)
446 {
447 trigger_error('DB_Abstract::transaction_commit() needs to be overridden when subclassed', E_USER_ERROR);
448 }
449
450 // ###################################################################
451 /**
452 * Constructs a table of query information output that is used in some
453 * other modules to display a list of queries. This merely formats
454 * a DB->history array entry nicely
455 *
456 * @access public
457 *
458 * @param array An entry from DB->history
459 *
460 * @return string A formatted table block
461 */
462 function construct_query_debug($query)
463 {
464 $block = "<strong>Query:</strong>\n\n<div>" . $this->registry->entity_encode($query['query']) . "</div>\n";
465 $block .= "<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>\n\t\t";
466 $block .= "<strong>Time:</strong> $query[time]<br />\n\t\t<br />\n\t\t";
467 $block .= "<strong>Backtrace:</strong>\n\t\t<div>" . implode("<br />\n", $query['trace']) . "</div>\n\t</td>\n</tr>";
468
469 return $this->registry->message('Query Debug', $block, 1, true, false, 0);
470 }
471
472 // ###################################################################
473 /**
474 * Error wrapper for ISSO->message()
475 *
476 * @access protected
477 *
478 * @param string User defined error message
479 */
480 function error($message)
481 {
482 if ($this->showerrors)
483 {
484 if ($this->dblink)
485 {
486 $this->errnum = call_user_func($this->commands['error_num'], $this->dblink);
487 $this->errstr = call_user_func($this->commands['error_str'], $this->dblink);
488 }
489
490 $style['code'] = 'font-family: \'Courier New\', Courier, mono; font-size: 11px;';
491
492 $message_prepped = "<blockquote>\n<p>";
493 $message_prepped .= "\n\t&raquo; <strong>Query:</strong>\n<br /> <pre style=\"$style[code]\">" . htmlspecialchars($this->querystr) ."</pre>\n<br />";
494 $message_prepped .= "\n\t&raquo; <strong>Error Number:</strong> <span style=\"$style[code]\">" . $this->errnum . "</span>\n<br />";
495 $message_prepped .= "\n\t&raquo; <strong>Error Message:</strong> <span style=\"$style[code]\">" . $this->errstr . "</span>\n<br />";
496 $message_prepped .= "\n\t&raquo; <strong>Additional Notes:</strong> <span style=\"$style[code]\">" . $message . "</span>\n<br />";
497 $message_prepped .= "\n\t&raquo; <strong>File:</strong> <span style=\"$style[code]\">" . $_SERVER['PHP_SELF'] . "</span>\n";
498 $message_prepped .= "\n</p>\n</blockquote>";
499
500 $this->registry->message('Database Error in `<em>' . $this->registry->application . '</em>`', $message_prepped, 3);
501 exit;
502 }
503 }
504 }
505
506 /*=====================================================================*\
507 || ###################################################################
508 || # $HeadURL$
509 || # $Id$
510 || ###################################################################
511 \*=====================================================================*/
512 ?>