Added a parameter in API->delete() to optionally stop the running of API->set_existin...
[isso.git] / db.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]issoversion[#]
5 || # Copyright ©2002-[#]year[#] Iris Studios, Inc.
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 Iris Studios, Inc.
41 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
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 $this->registry->check_isso_fields(get_class($this));
190
191 if ($this->dblink == false)
192 {
193 $this->dblink = call_user_func(($pconnect ? $this->commands['pconnect'] : $this->commands['connect']), $server, $user, $password, $database);
194
195 if ($this->dblink == false)
196 {
197 $this->error('DB-Link == false, cannot connect');
198 return false;
199 }
200
201 return true;
202 }
203 }
204
205 // ###################################################################
206 /**
207 * Send a query to the open database link
208 *
209 * @access public
210 *
211 * @param string Query string
212 *
213 * @return integer Result
214 */
215 function query($string)
216 {
217 $time = microtime();
218
219 $this->querystr = $string;
220 $this->result = @call_user_func($this->commands['query'], $this->dblink, $string);
221
222 if (!$this->result)
223 {
224 $this->error('Invalid SQL query');
225 }
226
227 $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()));
228
229 if (defined('ISSO_SHOW_QUERIES_LIVE'))
230 {
231 if (constant('ISSO_SHOW_QUERIES_LIVE'))
232 {
233 print($this->construct_query_debug($history));
234 }
235 }
236
237 return $this->result;
238 }
239
240 // ###################################################################
241 /**
242 * Escape a string (depending on character set, if supported)
243 *
244 * @access public
245 *
246 * @param string String to be escaped
247 *
248 * @return string Escaped string
249 */
250 function escape_string($string)
251 {
252 return call_user_func($this->commands['escape_string'], $this->dblink, $string);
253 }
254
255 // ###################################################################
256 /**
257 * Escapes a binary string for insertion into the database
258 *
259 * @access public
260 *
261 * @param string Unescaped data
262 *
263 * @return string Escaped binary data
264 */
265 function escape_binary($binary)
266 {
267 return call_user_func($this->commands['escape_binary'], $binary);
268 }
269
270 // ###################################################################
271 /**
272 * Unescapes a binary string that was fetched from the database
273 *
274 * @access public
275 *
276 * @param string Escaped data
277 *
278 * @return string Unescaped binary data
279 */
280 function unescape_binary($binary)
281 {
282 return call_user_func($this->commands['unescape_binary'], $binary);
283 }
284
285 // ###################################################################
286 /**
287 * Fetch the query result as an array
288 *
289 * @access public
290 *
291 * @param integer Result
292 * @param bool Return an associative array?
293 *
294 * @return array A row of the query result
295 */
296 function fetch_array($result, $assoc = true)
297 {
298 return call_user_func($this->commands[ ($assoc ? 'fetch_assoc' : 'fetch_row') ], $result);
299 }
300
301 // ###################################################################
302 /**
303 * Fetch the query result as an object
304 *
305 * @access public
306 *
307 * @param integer Result
308 *
309 * @return object An object with the query result
310 */
311 function fetch_object($result)
312 {
313 return call_user_func($this->commands['fetch_object'], $result);
314 }
315
316 // ###################################################################
317 /**
318 * Send a query and return the first row of the results
319 *
320 * @access public
321 *
322 * @param string Query string
323 * @param string Result return function (in the database layer)
324 *
325 * @return mixed Results in variable formats
326 */
327 function query_first($string, $callback = 'fetch_array')
328 {
329 $resource = $this->query($string);
330 if ($resource)
331 {
332 $return = $this->$callback($resource);
333 $this->free_result($resource);
334 return $return;
335 }
336 else
337 {
338 return false;
339 }
340 }
341
342 // ###################################################################
343 /**
344 * Free the current query result
345 *
346 * @access public
347 *
348 * @param integer Result
349 */
350 function free_result($result)
351 {
352 call_user_func($this->commands['free_result'], $result);
353 $this->result = null;
354 $this->querystr = '';
355 }
356
357 // ###################################################################
358 /**
359 * Fetch the unique ID of the record just inserted
360 *
361 * @access public
362 *
363 * @return integer Insert-ID
364 */
365 function insert_id()
366 {
367 return call_user_func($this->commands['insert_id'], $this->dblink);
368 }
369
370 // ###################################################################
371 /**
372 * Fetch the number of rows in the result
373 *
374 * @access public
375 *
376 * @param integer Result
377 *
378 * @return integer Number of rows
379 */
380 function num_rows($result)
381 {
382 return call_user_func($this->commands['num_rows'], $result);
383 }
384
385 // ###################################################################
386 /**
387 * Fetch the number of rows affected by the query
388 *
389 * @access public
390 *
391 * @param integer Result
392 *
393 * @return integer Number of affected rows
394 */
395 function affected_rows($result)
396 {
397 return call_user_func($this->commands['affected_rows'], $result);
398 }
399
400 // ###################################################################
401 /**
402 * Sends the command to start a transaction. This command should never
403 * be reached as it's always overridden
404 *
405 * @access public
406 */
407 function transaction_start()
408 {
409 trigger_error('DB_Abstract::transaction_start() needs to be overridden when subclassed', E_USER_ERROR);
410 }
411
412 // ###################################################################
413 /**
414 * Sends the command to set this as a savepoint. This command should never
415 * be reached as it's always overridden
416 *
417 * @access public
418 *
419 * @param string Named savepoint
420 */
421 function transaction_savepoint($name)
422 {
423 trigger_error('DB_Abstract::transaction_savepoint() needs to be overridden when subclassed', E_USER_ERROR);
424 }
425
426 // ###################################################################
427 /**
428 * Sends the command to rollback to a given savepoint. This command
429 * should never be reached as it's always overridden
430 *
431 * @access public
432 *
433 * @param string Named savepoint
434 */
435 function transaction_rollback($name)
436 {
437 trigger_error('DB_Abstract::transaction_rollback() needs to be overridden when subclassed', E_USER_ERROR);
438 }
439
440 // ###################################################################
441 /**
442 * Sends the command to commit the entire transaction. This command
443 * should never be reached as it's always overridden
444 *
445 * @access public
446 */
447 function transaction_commit($name)
448 {
449 trigger_error('DB_Abstract::transaction_commit() needs to be overridden when subclassed', E_USER_ERROR);
450 }
451
452 // ###################################################################
453 /**
454 * Constructs a table of query information output that is used in some
455 * other modules to display a list of queries. This merely formats
456 * a DB->history array entry nicely
457 *
458 * @access public
459 *
460 * @param array An entry from DB->history
461 *
462 * @return string A formatted table block
463 */
464 function construct_query_debug($query)
465 {
466 $block = "<strong>Query:</strong>\n\n<div>" . $this->registry->entity_encode($query['query']) . "</div>\n";
467 $block .= "<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>\n\t\t";
468 $block .= "<strong>Time:</strong> $query[time]<br />\n\t\t<br />\n\t\t";
469 $block .= "<strong>Backtrace:</strong>\n\t\t<div>" . implode("<br />\n", $query['trace']) . "</div>\n\t</td>\n</tr>";
470
471 return $this->registry->message('Query Debug', $block, 1, true, false, 0);
472 }
473
474 // ###################################################################
475 /**
476 * Error wrapper for ISSO->message()
477 *
478 * @access protected
479 *
480 * @param string User defined error message
481 */
482 function error($message)
483 {
484 if ($this->showerrors)
485 {
486 if ($this->dblink)
487 {
488 $this->errnum = call_user_func($this->commands['error_num'], $this->dblink);
489 $this->errstr = call_user_func($this->commands['error_str'], $this->dblink);
490 }
491
492 $style['code'] = 'font-family: \'Courier New\', Courier, mono; font-size: 11px;';
493
494 $message_prepped = "<blockquote>\n<p>";
495 $message_prepped .= "\n\t&raquo; <strong>Query:</strong>\n<br /> <pre style=\"$style[code]\">" . htmlspecialchars($this->querystr) ."</pre>\n<br />";
496 $message_prepped .= "\n\t&raquo; <strong>Error Number:</strong> <span style=\"$style[code]\">" . $this->errnum . "</span>\n<br />";
497 $message_prepped .= "\n\t&raquo; <strong>Error Message:</strong> <span style=\"$style[code]\">" . $this->errstr . "</span>\n<br />";
498 $message_prepped .= "\n\t&raquo; <strong>Additional Notes:</strong> <span style=\"$style[code]\">" . $message . "</span>\n<br />";
499 $message_prepped .= "\n\t&raquo; <strong>File:</strong> <span style=\"$style[code]\">" . $_SERVER['PHP_SELF'] . "</span>\n";
500 $message_prepped .= "\n</p>\n</blockquote>";
501
502 $this->registry->message('Database Error in `<em>' . $this->registry->application . '</em>`', $message_prepped, 3);
503 exit;
504 }
505 }
506 }
507
508 /*=====================================================================*\
509 || ###################################################################
510 || # $HeadURL$
511 || # $Id$
512 || ###################################################################
513 \*=====================================================================*/
514 ?>