ISSO is no longer a product regularly released so we'll remove the issoversion tag...
[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 (Db.php)
24 *
25 * @package ISSO
26 */
27
28 require_once('ISSO/Functions.php');
29
30 /**
31 * Abstract Database Layer
32 *
33 * This class provides an abstract template for all RDBMS layers. All
34 * ISSO abstraction layers should inherit this class. It provides error
35 * reporting, SQL analysis, and general connection functionality.
36 *
37 * Constants:
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 abstract class BSDb
47 {
48 /**
49 * Determines whether or not errors should be shown
50 * @var bool
51 */
52 public $showerrors = true;
53
54 /**
55 * Current error number
56 * @var integer
57 */
58 protected $errnum = 0;
59
60 /**
61 * Description of current error
62 * @var string
63 */
64 protected $errstr = '';
65
66 /**
67 * Currend open database connection
68 * @var integer
69 */
70 protected $dblink = null;
71
72 /**
73 * Current query ID
74 * @var integer
75 */
76 protected $result = null;
77
78 /**
79 * Current query string
80 * @var string
81 */
82 protected $querystr = '';
83
84 /**
85 * History of all executed queryies
86 * @var array
87 */
88 protected $history = array();
89
90 // ###################################################################
91 /**
92 * Connect to a the specified database
93 *
94 * @param string Server name
95 * @param string User name
96 * @param string Password
97 * @param string Database name
98 * @param bool Use p-connect?
99 *
100 * @return bool Result of connect
101 */
102 public function connect($server, $user, $password, $database, $pconnect)
103 {
104 if ($this->dblink == false)
105 {
106 $this->dblink = $this->{($pconnect ? '_connect' : '_pConnect')}($server, $user, $password, $database);
107
108 if ($this->dblink == false)
109 {
110 $this->_error('DB-Link == false, cannot connect');
111 return false;
112 }
113
114 return true;
115 }
116 }
117
118 /**
119 * Abstract function that returns a database link after establishing a connection. This just
120 * calls the function and does not do any checking
121 *
122 * @param string Server name
123 * @param string User name
124 * @param string Password
125 * @param string Database name
126 *
127 * @return integer Database link
128 */
129 protected abstract function _connect($server, $user, $password, $database);
130
131 /**
132 * Abstract function that returns a database link after establishing a connection. This just
133 * calls the function and does not do any checking
134 *
135 * @param string Server name
136 * @param string User name
137 * @param string Password
138 * @param string Database name
139 *
140 * @return resource Database link
141 */
142 protected abstract function _pConnect($server, $user, $password, $database);
143
144 // ###################################################################
145 /**
146 * Send a query to the open database link
147 *
148 * @param string Query string
149 *
150 * @return integer Result
151 */
152 public function query($string)
153 {
154 $time = microtime();
155
156 $this->querystr = $string;
157 $this->result = $this->_query($this->dblink, $string);
158
159 if (!$this->result)
160 {
161 $this->_error('Invalid SQL query');
162 }
163
164 $this->history[] = $history = array('query' => $string, 'time' => BSFunctions::FetchMicrotimeDiff($time), 'trace' => $this->registry->format_debug_trace(debug_backtrace()));
165
166 if (defined('ISSO_SHOW_QUERIES_LIVE'))
167 {
168 if (constant('ISSO_SHOW_QUERIES_LIVE'))
169 {
170 print($this->_constructDebugQuery($history));
171 }
172 }
173
174 return $this->result;
175 }
176
177 /**
178 * Abstract function that executes the query command on the database
179 *
180 * @param string Query string
181 *
182 * @return integer Result ID
183 */
184 protected abstract function _query($query);
185
186 // ###################################################################
187 /**
188 * Escape a string (depending on character set, if supported)
189 *
190 * @param string String to be escaped
191 *
192 * @return string Escaped string
193 */
194 public function escapeString($string)
195 {
196 return $this->_escapeString($string);
197 }
198
199 /**
200 * Abstract function that calls the escape_string() method
201 *
202 * @param string String to escape
203 *
204 * @return string Escaped string
205 */
206 protected abstract function _escapeString($string);
207
208 // ###################################################################
209 /**
210 * Escapes a binary string for insertion into the database
211 *
212 * @param string Unescaped data
213 *
214 * @return string Escaped binary data
215 */
216 public function escapeBinary($binary)
217 {
218 return $this->_escapeBinary($binary);
219 }
220
221 /**
222 * Abstract function that calls escape_binary()
223 *
224 * @param string Binary to escape
225 *
226 * @return string Escaped binary
227 */
228 protected abstract function _escapeBinary($string);
229
230 // ###################################################################
231 /**
232 * Unescapes a binary string that was fetched from the database
233 *
234 * @param string Escaped data
235 *
236 * @return string Unescaped binary data
237 */
238 public function unescapeBinary($binary)
239 {
240 return $this->_unescapeBinary($binary);
241 }
242
243 /**
244 * Abstract function that calls unescape_binary()
245 *
246 * @param string Escaped data
247 *
248 * @return string Data that has been unescaped
249 */
250 protected abstract function _unescapeBinary($string);
251
252 // ###################################################################
253 /**
254 * Fetch the query result as an array
255 *
256 * @param integer Result
257 * @param bool Return an associative array?
258 *
259 * @return array A row of the query result
260 */
261 public function fetchArray($result, $assoc = true)
262 {
263 return $this->{($assoc ? '_fetchAssocArray' : '_fetchRowArray')}($result);
264 }
265
266 /**
267 * Abstract function that returns an associative array of given result
268 *
269 * @param integer Result
270 *
271 * @return array Result array
272 */
273 protected abstract function _fetchAssocArray($result);
274
275 /**
276 * Abstract function that returns a row array of given result
277 *
278 * @param integer Result
279 *
280 * @return array Result array
281 */
282 protected abstract function _fetchRowArray($result);
283
284 // ###################################################################
285 /**
286 * Fetch the query result as an object
287 *
288 * @param integer Result
289 *
290 * @return object An object with the query result
291 */
292 public function fetchObject($result)
293 {
294 return $this->_fetchObject($result);
295 }
296
297 /**
298 * Abstract function that returns an object for a given result
299 *
300 * @param integer Result
301 *
302 * @return object Row object
303 */
304 public abstract function _fetchObject($result);
305
306 // ###################################################################
307 /**
308 * Send a query and return the first row of the results
309 *
310 * @param string Query string
311 * @param string Result return function (in the database layer)
312 *
313 * @return mixed Results in variable formats
314 */
315 public function queryFirst($string, $callback = 'fetchArray')
316 {
317 $resource = $this->query($string);
318 if ($resource)
319 {
320 $return = $this->$callback($resource);
321 $this->_freeResult($resource);
322 return $return;
323 }
324 else
325 {
326 return false;
327 }
328 }
329
330 // ###################################################################
331 /**
332 * Free the current query result
333 *
334 * @param integer Result
335 */
336 public function freeResult($result)
337 {
338 $this->_freeResult($result);
339 $this->result = null;
340 $this->querystr = '';
341 }
342
343 /**
344 * Abstract function that frees a given result
345 *
346 * @param integer Result ID
347 */
348 protected abstract function _freeResult($result);
349
350 // ###################################################################
351 /**
352 * Fetch the unique ID of the record just inserted
353 *
354 * @return integer Insert-ID
355 */
356 public function insertId()
357 {
358 return $this->_insertID();
359 }
360
361 /**
362 * Abstract function that returns the ID of the most recently-inserted
363 * record
364 *
365 * @return integer Insertion ID
366 */
367 protected abstract function _insertId();
368
369 // ###################################################################
370 /**
371 * Fetch the number of rows in the result
372 *
373 * @param integer Result
374 *
375 * @return integer Number of rows
376 */
377 public function numRows($result)
378 {
379 return $this->_numRows($result);
380 }
381
382 /**
383 * Abstract function that returns the number of rows in the result
384 *
385 * @param integer Result ID
386 *
387 * @return integer Number of rows
388 */
389 protected abstract function _numRows($result);
390
391 // ###################################################################
392 /**
393 * Fetch the number of rows affected by the query
394 *
395 * @param integer Result
396 *
397 * @return integer Number of affected rows
398 */
399 public function affectedRows($result)
400 {
401 return $this->_affectedRows($result);
402 }
403
404 /**
405 * Abstract function that returns the number of affected rows in the result
406 *
407 * @param integer Result ID
408 *
409 * @return integer Number of rows
410 */
411 protected abstract function _affectedRows($result);
412
413 // ###################################################################
414 /**
415 * Sends the command to start a transaction. This command should never
416 * be reached as it's always overridden
417 */
418 public abstract function transactionStart();
419
420 // ###################################################################
421 /**
422 * Sends the command to set this as a savepoint. This command should never
423 * be reached as it's always overridden
424 *
425 * @param string Named savepoint
426 */
427 public abstract function transactionSavepoint($name);
428
429 // ###################################################################
430 /**
431 * Sends the command to rollback to a given savepoint. This command
432 * should never be reached as it's always overridden
433 *
434 * @param string Named savepoint
435 */
436 public abstract function transactionRollback($name = null);
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 public abstract function transactionCommit();
444
445 // ###################################################################
446 /**
447 * Constructs a table of query information output that is used in some
448 * other modules to display a list of queries. This merely formats
449 * a DB->history array entry nicely
450 *
451 * @param array An entry from DB->history
452 *
453 * @return string A formatted table block
454 */
455 protected function _constructDebugQuery($query)
456 {
457 $block = "<strong>Query:</strong>\n\n<div>" . htmlspecialchars($query['query']) . "</div>\n";
458 $block .= "<tr style=\"background-color: #FFFFFF; text-align: left\">\n\t<td>\n\t\t";
459 $block .= "<strong>Time:</strong> $query[time]<br />\n\t\t<br />\n\t\t";
460 $block .= "<strong>Backtrace:</strong>\n\t\t<div>" . implode("<br />\n", $query['trace']) . "</div>\n\t</td>\n</tr>";
461
462 return BSRegister::Message('Query Debug', $block, 1, true, false, 0);
463 }
464
465 // ###################################################################
466 /**
467 * Error wrapper for ISSO->message()
468 *
469 * @param string User defined error message
470 */
471 protected function _error($message)
472 {
473 if ($this->showerrors)
474 {
475 if ($this->dblink)
476 {
477 $this->errnum = call_user_func($this->commands['error_num'], $this->dblink);
478 $this->errstr = call_user_func($this->commands['error_str'], $this->dblink);
479 }
480
481 $style['code'] = 'font-family: \'Courier New\', Courier, mono; font-size: 11px;';
482
483 $message_prepped = "<blockquote>\n<p>";
484 $message_prepped .= "\n\t&raquo; <strong>Query:</strong>\n<br /> <pre style=\"$style[code]\">" . htmlspecialchars($this->querystr) ."</pre>\n<br />";
485 $message_prepped .= "\n\t&raquo; <strong>Error Number:</strong> <span style=\"$style[code]\">" . $this->errnum . "</span>\n<br />";
486 $message_prepped .= "\n\t&raquo; <strong>Error Message:</strong> <span style=\"$style[code]\">" . $this->errstr . "</span>\n<br />";
487 $message_prepped .= "\n\t&raquo; <strong>Additional Notes:</strong> <span style=\"$style[code]\">" . $message . "</span>\n<br />";
488 $message_prepped .= "\n\t&raquo; <strong>File:</strong> <span style=\"$style[code]\">" . $_SERVER['PHP_SELF'] . "</span>\n";
489 $message_prepped .= "\n</p>\n</blockquote>";
490
491 BSRegister::Message('Database Error in `<em>' . BSRegister::GetApplication() . '</em>`', $message_prepped, 3);
492 exit;
493 }
494 }
495 }
496
497 /*=====================================================================*\
498 || ###################################################################
499 || # $HeadURL$
500 || # $Id$
501 || ###################################################################
502 \*=====================================================================*/
503 ?>