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