]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/DB.php
[DOCUMENTATION] Convert INSTALL to markdown and update the requirements
[quix0rs-gnu-social.git] / extlib / DB.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6  * Database independent query interface
7  *
8  * PHP version 5
9  *
10  * LICENSE: This source file is subject to version 3.0 of the PHP license
11  * that is available through the world-wide-web at the following URI:
12  * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
13  * the PHP License and are unable to obtain it through the web, please
14  * send a note to license@php.net so we can mail you a copy immediately.
15  *
16  * @category   Database
17  * @package    DB
18  * @author     Stig Bakken <ssb@php.net>
19  * @author     Tomas V.V.Cox <cox@idecnet.com>
20  * @author     Daniel Convissor <danielc@php.net>
21  * @copyright  1997-2007 The PHP Group
22  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
23  * @version    CVS: $Id$
24  * @link       http://pear.php.net/package/DB
25  */
26
27 /**
28  * Obtain the PEAR class so it can be extended from
29  */
30 require_once 'PEAR.php';
31
32
33 // {{{ constants
34 // {{{ error codes
35
36 /**#@+
37  * One of PEAR DB's portable error codes.
38  * @see DB_common::errorCode(), DB::errorMessage()
39  *
40  * {@internal If you add an error code here, make sure you also add a textual
41  * version of it in DB::errorMessage().}}
42  */
43
44 /**
45  * The code returned by many methods upon success
46  */
47 define('DB_OK', 1);
48
49 /**
50  * Unkown error
51  */
52 define('DB_ERROR', -1);
53
54 /**
55  * Syntax error
56  */
57 define('DB_ERROR_SYNTAX', -2);
58
59 /**
60  * Tried to insert a duplicate value into a primary or unique index
61  */
62 define('DB_ERROR_CONSTRAINT', -3);
63
64 /**
65  * An identifier in the query refers to a non-existant object
66  */
67 define('DB_ERROR_NOT_FOUND', -4);
68
69 /**
70  * Tried to create a duplicate object
71  */
72 define('DB_ERROR_ALREADY_EXISTS', -5);
73
74 /**
75  * The current driver does not support the action you attempted
76  */
77 define('DB_ERROR_UNSUPPORTED', -6);
78
79 /**
80  * The number of parameters does not match the number of placeholders
81  */
82 define('DB_ERROR_MISMATCH', -7);
83
84 /**
85  * A literal submitted did not match the data type expected
86  */
87 define('DB_ERROR_INVALID', -8);
88
89 /**
90  * The current DBMS does not support the action you attempted
91  */
92 define('DB_ERROR_NOT_CAPABLE', -9);
93
94 /**
95  * A literal submitted was too long so the end of it was removed
96  */
97 define('DB_ERROR_TRUNCATED', -10);
98
99 /**
100  * A literal number submitted did not match the data type expected
101  */
102 define('DB_ERROR_INVALID_NUMBER', -11);
103
104 /**
105  * A literal date submitted did not match the data type expected
106  */
107 define('DB_ERROR_INVALID_DATE', -12);
108
109 /**
110  * Attempt to divide something by zero
111  */
112 define('DB_ERROR_DIVZERO', -13);
113
114 /**
115  * A database needs to be selected
116  */
117 define('DB_ERROR_NODBSELECTED', -14);
118
119 /**
120  * Could not create the object requested
121  */
122 define('DB_ERROR_CANNOT_CREATE', -15);
123
124 /**
125  * Could not drop the database requested because it does not exist
126  */
127 define('DB_ERROR_CANNOT_DROP', -17);
128
129 /**
130  * An identifier in the query refers to a non-existant table
131  */
132 define('DB_ERROR_NOSUCHTABLE', -18);
133
134 /**
135  * An identifier in the query refers to a non-existant column
136  */
137 define('DB_ERROR_NOSUCHFIELD', -19);
138
139 /**
140  * The data submitted to the method was inappropriate
141  */
142 define('DB_ERROR_NEED_MORE_DATA', -20);
143
144 /**
145  * The attempt to lock the table failed
146  */
147 define('DB_ERROR_NOT_LOCKED', -21);
148
149 /**
150  * The number of columns doesn't match the number of values
151  */
152 define('DB_ERROR_VALUE_COUNT_ON_ROW', -22);
153
154 /**
155  * The DSN submitted has problems
156  */
157 define('DB_ERROR_INVALID_DSN', -23);
158
159 /**
160  * Could not connect to the database
161  */
162 define('DB_ERROR_CONNECT_FAILED', -24);
163
164 /**
165  * The PHP extension needed for this DBMS could not be found
166  */
167 define('DB_ERROR_EXTENSION_NOT_FOUND', -25);
168
169 /**
170  * The present user has inadequate permissions to perform the task requestd
171  */
172 define('DB_ERROR_ACCESS_VIOLATION', -26);
173
174 /**
175  * The database requested does not exist
176  */
177 define('DB_ERROR_NOSUCHDB', -27);
178
179 /**
180  * Tried to insert a null value into a column that doesn't allow nulls
181  */
182 define('DB_ERROR_CONSTRAINT_NOT_NULL', -29);
183 /**#@-*/
184
185
186 // }}}
187 // {{{ prepared statement-related
188
189
190 /**#@+
191  * Identifiers for the placeholders used in prepared statements.
192  * @see DB_common::prepare()
193  */
194
195 /**
196  * Indicates a scalar (<kbd>?</kbd>) placeholder was used
197  *
198  * Quote and escape the value as necessary.
199  */
200 define('DB_PARAM_SCALAR', 1);
201
202 /**
203  * Indicates an opaque (<kbd>&</kbd>) placeholder was used
204  *
205  * The value presented is a file name.  Extract the contents of that file
206  * and place them in this column.
207  */
208 define('DB_PARAM_OPAQUE', 2);
209
210 /**
211  * Indicates a misc (<kbd>!</kbd>) placeholder was used
212  *
213  * The value should not be quoted or escaped.
214  */
215 define('DB_PARAM_MISC', 3);
216 /**#@-*/
217
218
219 // }}}
220 // {{{ binary data-related
221
222
223 /**#@+
224  * The different ways of returning binary data from queries.
225  */
226
227 /**
228  * Sends the fetched data straight through to output
229  */
230 define('DB_BINMODE_PASSTHRU', 1);
231
232 /**
233  * Lets you return data as usual
234  */
235 define('DB_BINMODE_RETURN', 2);
236
237 /**
238  * Converts the data to hex format before returning it
239  *
240  * For example the string "123" would become "313233".
241  */
242 define('DB_BINMODE_CONVERT', 3);
243 /**#@-*/
244
245
246 // }}}
247 // {{{ fetch modes
248
249
250 /**#@+
251  * Fetch Modes.
252  * @see DB_common::setFetchMode()
253  */
254
255 /**
256  * Indicates the current default fetch mode should be used
257  * @see DB_common::$fetchmode
258  */
259 define('DB_FETCHMODE_DEFAULT', 0);
260
261 /**
262  * Column data indexed by numbers, ordered from 0 and up
263  */
264 define('DB_FETCHMODE_ORDERED', 1);
265
266 /**
267  * Column data indexed by column names
268  */
269 define('DB_FETCHMODE_ASSOC', 2);
270
271 /**
272  * Column data as object properties
273  */
274 define('DB_FETCHMODE_OBJECT', 3);
275
276 /**
277  * For multi-dimensional results, make the column name the first level
278  * of the array and put the row number in the second level of the array
279  *
280  * This is flipped from the normal behavior, which puts the row numbers
281  * in the first level of the array and the column names in the second level.
282  */
283 define('DB_FETCHMODE_FLIPPED', 4);
284 /**#@-*/
285
286 /**#@+
287  * Old fetch modes.  Left here for compatibility.
288  */
289 define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
290 define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
291 define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
292 /**#@-*/
293
294
295 // }}}
296 // {{{ tableInfo() && autoPrepare()-related
297
298
299 /**#@+
300  * The type of information to return from the tableInfo() method.
301  *
302  * Bitwised constants, so they can be combined using <kbd>|</kbd>
303  * and removed using <kbd>^</kbd>.
304  *
305  * @see DB_common::tableInfo()
306  *
307  * {@internal Since the TABLEINFO constants are bitwised, if more of them are
308  * added in the future, make sure to adjust DB_TABLEINFO_FULL accordingly.}}
309  */
310 define('DB_TABLEINFO_ORDER', 1);
311 define('DB_TABLEINFO_ORDERTABLE', 2);
312 define('DB_TABLEINFO_FULL', 3);
313 /**#@-*/
314
315
316 /**#@+
317  * The type of query to create with the automatic query building methods.
318  * @see DB_common::autoPrepare(), DB_common::autoExecute()
319  */
320 define('DB_AUTOQUERY_INSERT', 1);
321 define('DB_AUTOQUERY_UPDATE', 2);
322 /**#@-*/
323
324
325 // }}}
326 // {{{ portability modes
327
328
329 /**#@+
330  * Portability Modes.
331  *
332  * Bitwised constants, so they can be combined using <kbd>|</kbd>
333  * and removed using <kbd>^</kbd>.
334  *
335  * @see DB_common::setOption()
336  *
337  * {@internal Since the PORTABILITY constants are bitwised, if more of them are
338  * added in the future, make sure to adjust DB_PORTABILITY_ALL accordingly.}}
339  */
340
341 /**
342  * Turn off all portability features
343  */
344 define('DB_PORTABILITY_NONE', 0);
345
346 /**
347  * Convert names of tables and fields to lower case
348  * when using the get*(), fetch*() and tableInfo() methods
349  */
350 define('DB_PORTABILITY_LOWERCASE', 1);
351
352 /**
353  * Right trim the data output by get*() and fetch*()
354  */
355 define('DB_PORTABILITY_RTRIM', 2);
356
357 /**
358  * Force reporting the number of rows deleted
359  */
360 define('DB_PORTABILITY_DELETE_COUNT', 4);
361
362 /**
363  * Enable hack that makes numRows() work in Oracle
364  */
365 define('DB_PORTABILITY_NUMROWS', 8);
366
367 /**
368  * Makes certain error messages in certain drivers compatible
369  * with those from other DBMS's
370  *
371  * + mysql, mysqli:  change unique/primary key constraints
372  *   DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
373  *
374  * + odbc(access):  MS's ODBC driver reports 'no such field' as code
375  *   07001, which means 'too few parameters.'  When this option is on
376  *   that code gets mapped to DB_ERROR_NOSUCHFIELD.
377  */
378 define('DB_PORTABILITY_ERRORS', 16);
379
380 /**
381  * Convert null values to empty strings in data output by
382  * get*() and fetch*()
383  */
384 define('DB_PORTABILITY_NULL_TO_EMPTY', 32);
385
386 /**
387  * Turn on all portability features
388  */
389 define('DB_PORTABILITY_ALL', 63);
390 /**#@-*/
391
392 // }}}
393
394
395 // }}}
396 // {{{ class DB
397
398 /**
399  * Database independent query interface
400  *
401  * The main "DB" class is simply a container class with some static
402  * methods for creating DB objects as well as some utility functions
403  * common to all parts of DB.
404  *
405  * The object model of DB is as follows (indentation means inheritance):
406  * <pre>
407  * DB           The main DB class.  This is simply a utility class
408  *              with some "static" methods for creating DB objects as
409  *              well as common utility functions for other DB classes.
410  *
411  * DB_common    The base for each DB implementation.  Provides default
412  * |            implementations (in OO lingo virtual methods) for
413  * |            the actual DB implementations as well as a bunch of
414  * |            query utility functions.
415  * |
416  * +-DB_mysql   The DB implementation for MySQL.  Inherits DB_common.
417  *              When calling DB::factory or DB::connect for MySQL
418  *              connections, the object returned is an instance of this
419  *              class.
420  * </pre>
421  *
422  * @category   Database
423  * @package    DB
424  * @author     Stig Bakken <ssb@php.net>
425  * @author     Tomas V.V.Cox <cox@idecnet.com>
426  * @author     Daniel Convissor <danielc@php.net>
427  * @copyright  1997-2007 The PHP Group
428  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
429  * @version    Release: 1.9.2
430  * @link       http://pear.php.net/package/DB
431  */
432 class DB
433 {
434     // {{{ factory()
435
436     /**
437      * Create a new DB object for the specified database type but don't
438      * connect to the database
439      *
440      * @param string $type the database type (eg "mysql")
441      * @param array $options an associative array of option names and values
442      *
443      * @return object  a new DB object.  A DB_Error object on failure.
444      *
445      * @see DB_common::setOption()
446      */
447     public static function factory($type, $options = [])
448     {
449         if (!is_array($options)) {
450             $options = array('persistent' => $options);
451         }
452
453         if (isset($options['debug']) && $options['debug'] >= 2) {
454             // expose php errors with sufficient debug level
455             include_once "DB/{$type}.php";
456         } else {
457             @include_once "DB/{$type}.php";
458         }
459
460         $classname = "DB_${type}";
461
462         if (!class_exists($classname)) {
463             $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
464                 "Unable to include the DB/{$type}.php"
465                 . " file for '$dsn'",
466                 'DB_Error', true);
467             return $tmp;
468         }
469
470         @$obj = new $classname;
471
472         foreach ($options as $option => $value) {
473             $test = $obj->setOption($option, $value);
474             if (DB::isError($test)) {
475                 return $test;
476             }
477         }
478
479         return $obj;
480     }
481
482     // }}}
483     // {{{ connect()
484
485     /**
486      * Determines if a variable is a DB_Error object
487      *
488      * @param mixed $value the variable to check
489      *
490      * @return bool  whether $value is DB_Error object
491      */
492     public static function isError($value)
493     {
494         return is_object($value) && is_a($value, 'DB_Error');
495     }
496
497     // }}}
498     // {{{ apiVersion()
499
500     /**
501      * Create a new DB object including a connection to the specified database
502      *
503      * Example 1.
504      * <code>
505      * require_once 'DB.php';
506      *
507      * $dsn = 'pgsql://user:password@host/database';
508      * $options = array(
509      *     'debug'       => 2,
510      *     'portability' => DB_PORTABILITY_ALL,
511      * );
512      *
513      * $db = DB::connect($dsn, $options);
514      * if (PEAR::isError($db)) {
515      *     die($db->getMessage());
516      * }
517      * </code>
518      *
519      * @param mixed $dsn the string "data source name" or array in the
520      *                         format returned by DB::parseDSN()
521      * @param array $options an associative array of option names and values
522      *
523      * @return object  a new DB object.  A DB_Error object on failure.
524      *
525      * @uses DB_dbase::connect(), DB_fbsql::connect(), DB_ibase::connect(),
526      *       DB_ifx::connect(), DB_msql::connect(), DB_mssql::connect(),
527      *       DB_mysql::connect(), DB_mysqli::connect(), DB_oci8::connect(),
528      *       DB_odbc::connect(), DB_pgsql::connect(), DB_sqlite::connect(),
529      *       DB_sybase::connect()
530      *
531      * @uses DB::parseDSN(), DB_common::setOption(), PEAR::isError()
532      */
533     public static function connect($dsn, $options = array())
534     {
535         $dsninfo = DB::parseDSN($dsn);
536         $type = $dsninfo['phptype'];
537
538         if (!is_array($options)) {
539             /*
540              * For backwards compatibility.  $options used to be boolean,
541              * indicating whether the connection should be persistent.
542              */
543             $options = array('persistent' => $options);
544         }
545
546         if (isset($options['debug']) && $options['debug'] >= 2) {
547             // expose php errors with sufficient debug level
548             include_once "DB/${type}.php";
549         } else {
550             @include_once "DB/${type}.php";
551         }
552
553         $classname = "DB_${type}";
554         if (!class_exists($classname)) {
555             $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
556                 "Unable to include the DB/{$type}.php"
557                 . " file for '"
558                 . DB::getDSNString($dsn, true) . "'",
559                 'DB_Error', true);
560             return $tmp;
561         }
562
563         @$obj = new $classname;
564
565         foreach ($options as $option => $value) {
566             $test = $obj->setOption($option, $value);
567             if (DB::isError($test)) {
568                 return $test;
569             }
570         }
571
572         $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
573         if (DB::isError($err)) {
574             if (is_array($dsn)) {
575                 $err->addUserInfo(DB::getDSNString($dsn, true));
576             } else {
577                 $err->addUserInfo($dsn);
578             }
579             return $err;
580         }
581
582         return $obj;
583     }
584
585     // }}}
586     // {{{ isError()
587
588     /**
589      * Parse a data source name
590      *
591      * Additional keys can be added by appending a URI query string to the
592      * end of the DSN.
593      *
594      * The format of the supplied DSN is in its fullest form:
595      * <code>
596      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
597      * </code>
598      *
599      * Most variations are allowed:
600      * <code>
601      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
602      *  phptype://username:password@hostspec/database_name
603      *  phptype://username:password@hostspec
604      *  phptype://username@hostspec
605      *  phptype://hostspec/database
606      *  phptype://hostspec
607      *  phptype(dbsyntax)
608      *  phptype
609      * </code>
610      *
611      * @param string $dsn Data Source Name to be parsed
612      *
613      * @return array an associative array with the following keys:
614      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
615      *  + dbsyntax: Database used with regards to SQL syntax etc.
616      *  + protocol: Communication protocol to use (tcp, unix etc.)
617      *  + hostspec: Host specification (hostname[:port])
618      *  + database: Database to use on the DBMS server
619      *  + username: User name for login
620      *  + password: Password for login
621      */
622     public static function parseDSN($dsn)
623     {
624         $parsed = array(
625             'phptype' => false,
626             'dbsyntax' => false,
627             'username' => false,
628             'password' => false,
629             'protocol' => false,
630             'hostspec' => false,
631             'port' => false,
632             'socket' => false,
633             'database' => false,
634         );
635
636         if (is_array($dsn)) {
637             $dsn = array_merge($parsed, $dsn);
638             if (!$dsn['dbsyntax']) {
639                 $dsn['dbsyntax'] = $dsn['phptype'];
640             }
641             return $dsn;
642         }
643
644         // Find phptype and dbsyntax
645         if (($pos = strpos($dsn, '://')) !== false) {
646             $str = substr($dsn, 0, $pos);
647             $dsn = substr($dsn, $pos + 3);
648         } else {
649             $str = $dsn;
650             $dsn = null;
651         }
652
653         // Get phptype and dbsyntax
654         // $str => phptype(dbsyntax)
655         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
656             $parsed['phptype'] = $arr[1];
657             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
658         } else {
659             $parsed['phptype'] = $str;
660             $parsed['dbsyntax'] = $str;
661         }
662
663         if (!strlen($dsn)) {
664             return $parsed;
665         }
666
667         // Get (if found): username and password
668         // $dsn => username:password@protocol+hostspec/database
669         if (($at = strrpos($dsn, '@')) !== false) {
670             $str = substr($dsn, 0, $at);
671             $dsn = substr($dsn, $at + 1);
672             if (($pos = strpos($str, ':')) !== false) {
673                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
674                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
675             } else {
676                 $parsed['username'] = rawurldecode($str);
677             }
678         }
679
680         // Find protocol and hostspec
681
682         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
683             // $dsn => proto(proto_opts)/database
684             $proto = $match[1];
685             $proto_opts = $match[2] ? $match[2] : false;
686             $dsn = $match[3];
687
688         } else {
689             // $dsn => protocol+hostspec/database (old format)
690             if (strpos($dsn, '+') !== false) {
691                 list($proto, $dsn) = explode('+', $dsn, 2);
692             }
693             if (strpos($dsn, '/') !== false) {
694                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
695             } else {
696                 $proto_opts = $dsn;
697                 $dsn = null;
698             }
699         }
700
701         // process the different protocol options
702         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
703         $proto_opts = rawurldecode($proto_opts);
704         if (strpos($proto_opts, ':') !== false) {
705             list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
706         }
707         if ($parsed['protocol'] == 'tcp') {
708             $parsed['hostspec'] = $proto_opts;
709         } elseif ($parsed['protocol'] == 'unix') {
710             $parsed['socket'] = $proto_opts;
711         }
712
713         // Get dabase if any
714         // $dsn => database
715         if ($dsn) {
716             if (($pos = strpos($dsn, '?')) === false) {
717                 // /database
718                 $parsed['database'] = rawurldecode($dsn);
719             } else {
720                 // /database?param1=value1&param2=value2
721                 $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
722                 $dsn = substr($dsn, $pos + 1);
723                 if (strpos($dsn, '&') !== false) {
724                     $opts = explode('&', $dsn);
725                 } else { // database?param1=value1
726                     $opts = array($dsn);
727                 }
728                 foreach ($opts as $opt) {
729                     list($key, $value) = explode('=', $opt);
730                     if (!isset($parsed[$key])) {
731                         // don't allow params overwrite
732                         $parsed[$key] = rawurldecode($value);
733                     }
734                 }
735             }
736         }
737
738         return $parsed;
739     }
740
741     // }}}
742     // {{{ isConnection()
743
744     /**
745      * Returns the given DSN in a string format suitable for output.
746      *
747      * @param array|string the DSN to parse and format
748      * @param boolean true to hide the password, false to include it
749      * @return string
750      */
751     public static function getDSNString($dsn, $hidePassword)
752     {
753         /* Calling parseDSN will ensure that we have all the array elements
754          * defined, and means that we deal with strings and array in the same
755          * manner. */
756         $dsnArray = DB::parseDSN($dsn);
757
758         if ($hidePassword) {
759             $dsnArray['password'] = 'PASSWORD';
760         }
761
762         /* Protocol is special-cased, as using the default "tcp" along with an
763          * Oracle TNS connection string fails. */
764         if (is_string($dsn) && strpos($dsn, 'tcp') === false && $dsnArray['protocol'] == 'tcp') {
765             $dsnArray['protocol'] = false;
766         }
767
768         // Now we just have to construct the actual string. This is ugly.
769         $dsnString = $dsnArray['phptype'];
770         if ($dsnArray['dbsyntax']) {
771             $dsnString .= '(' . $dsnArray['dbsyntax'] . ')';
772         }
773         $dsnString .= '://'
774             . $dsnArray['username']
775             . ':'
776             . $dsnArray['password']
777             . '@'
778             . $dsnArray['protocol'];
779         if ($dsnArray['socket']) {
780             $dsnString .= '(' . $dsnArray['socket'] . ')';
781         }
782         if ($dsnArray['protocol'] && $dsnArray['hostspec']) {
783             $dsnString .= '+';
784         }
785         $dsnString .= $dsnArray['hostspec'];
786         if ($dsnArray['port']) {
787             $dsnString .= ':' . $dsnArray['port'];
788         }
789         $dsnString .= '/' . $dsnArray['database'];
790
791         /* Option handling. Unfortunately, parseDSN simply places options into
792          * the top-level array, so we'll first get rid of the fields defined by
793          * DB and see what's left. */
794         unset($dsnArray['phptype'],
795             $dsnArray['dbsyntax'],
796             $dsnArray['username'],
797             $dsnArray['password'],
798             $dsnArray['protocol'],
799             $dsnArray['socket'],
800             $dsnArray['hostspec'],
801             $dsnArray['port'],
802             $dsnArray['database']
803         );
804         if (count($dsnArray) > 0) {
805             $dsnString .= '?';
806             $i = 0;
807             foreach ($dsnArray as $key => $value) {
808                 if (++$i > 1) {
809                     $dsnString .= '&';
810                 }
811                 $dsnString .= $key . '=' . $value;
812             }
813         }
814
815         return $dsnString;
816     }
817
818     // }}}
819     // {{{ isManip()
820
821     /**
822      * Determines if a value is a DB_<driver> object
823      *
824      * @param mixed $value the value to test
825      *
826      * @return bool  whether $value is a DB_<driver> object
827      */
828     public static function isConnection($value)
829     {
830         return (is_object($value) &&
831             is_subclass_of($value, 'db_common') &&
832             method_exists($value, 'simpleQuery'));
833     }
834
835     // }}}
836     // {{{ errorMessage()
837
838     /**
839      * Tell whether a query is a data manipulation or data definition query
840      *
841      * Examples of data manipulation queries are INSERT, UPDATE and DELETE.
842      * Examples of data definition queries are CREATE, DROP, ALTER, GRANT,
843      * REVOKE.
844      *
845      * @param string $query the query
846      *
847      * @return boolean  whether $query is a data manipulation query
848      */
849     public static function isManip($query)
850     {
851         $manips = 'INSERT|UPDATE|DELETE|REPLACE|'
852             . 'CREATE|DROP|'
853             . 'LOAD DATA|SELECT .* INTO .* FROM|COPY|'
854             . 'ALTER|GRANT|REVOKE|'
855             . 'LOCK|UNLOCK';
856         if (preg_match('/^\s*"?(' . $manips . ')\s+/i', $query)) {
857             return true;
858         }
859         return false;
860     }
861
862     // }}}
863     // {{{ parseDSN()
864
865     /**
866      * Return a textual error message for a DB error code
867      *
868      * @param integer $value the DB error code
869      *
870      * @return string  the error message or false if the error code was
871      *                  not recognized
872      */
873     public static function errorMessage($value)
874     {
875         static $errorMessages;
876         if (!isset($errorMessages)) {
877             $errorMessages = array(
878                 DB_ERROR => 'unknown error',
879                 DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
880                 DB_ERROR_ALREADY_EXISTS => 'already exists',
881                 DB_ERROR_CANNOT_CREATE => 'can not create',
882                 DB_ERROR_CANNOT_DROP => 'can not drop',
883                 DB_ERROR_CONNECT_FAILED => 'connect failed',
884                 DB_ERROR_CONSTRAINT => 'constraint violation',
885                 DB_ERROR_CONSTRAINT_NOT_NULL => 'null value violates not-null constraint',
886                 DB_ERROR_DIVZERO => 'division by zero',
887                 DB_ERROR_EXTENSION_NOT_FOUND => 'extension not found',
888                 DB_ERROR_INVALID => 'invalid',
889                 DB_ERROR_INVALID_DATE => 'invalid date or time',
890                 DB_ERROR_INVALID_DSN => 'invalid DSN',
891                 DB_ERROR_INVALID_NUMBER => 'invalid number',
892                 DB_ERROR_MISMATCH => 'mismatch',
893                 DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
894                 DB_ERROR_NODBSELECTED => 'no database selected',
895                 DB_ERROR_NOSUCHDB => 'no such database',
896                 DB_ERROR_NOSUCHFIELD => 'no such field',
897                 DB_ERROR_NOSUCHTABLE => 'no such table',
898                 DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
899                 DB_ERROR_NOT_FOUND => 'not found',
900                 DB_ERROR_NOT_LOCKED => 'not locked',
901                 DB_ERROR_SYNTAX => 'syntax error',
902                 DB_ERROR_UNSUPPORTED => 'not supported',
903                 DB_ERROR_TRUNCATED => 'truncated',
904                 DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
905                 DB_OK => 'no error',
906             );
907         }
908
909         if (DB::isError($value)) {
910             $value = $value->getCode();
911         }
912
913         return isset($errorMessages[$value]) ? $errorMessages[$value]
914             : $errorMessages[DB_ERROR];
915     }
916
917     // }}}
918     // {{{ getDSNString()
919
920     /**
921      * Return the DB API version
922      *
923      * @return string  the DB API version number
924      */
925     function apiVersion()
926     {
927         return '1.9.2';
928     }
929
930     // }}}
931 }
932
933 // }}}
934 // {{{ class DB_Error
935
936 /**
937  * DB_Error implements a class for reporting portable database error
938  * messages
939  *
940  * @category   Database
941  * @package    DB
942  * @author     Stig Bakken <ssb@php.net>
943  * @copyright  1997-2007 The PHP Group
944  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
945  * @version    Release: 1.9.2
946  * @link       http://pear.php.net/package/DB
947  */
948 class DB_Error extends PEAR_Error
949 {
950     // {{{ constructor
951
952     /**
953      * DB_Error constructor
954      *
955      * @param mixed $code DB error code, or string with error message
956      * @param int $mode what "error mode" to operate in
957      * @param int $level what error level to use for $mode &
958      *                           PEAR_ERROR_TRIGGER
959      * @param mixed $debuginfo additional debug info, such as the last query
960      *
961      * @see PEAR_Error
962      */
963     function __construct($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
964                          $level = E_USER_NOTICE, $debuginfo = null)
965     {
966         if (is_int($code)) {
967             parent::__construct('DB Error: ' . DB::errorMessage($code), $code,
968                 $mode, $level, $debuginfo);
969         } else {
970             parent::__construct("DB Error: $code", DB_ERROR,
971                 $mode, $level, $debuginfo);
972         }
973     }
974
975     /**
976      * Workaround to both avoid the "Redefining already defined constructor"
977      * PHP error and provide backward compatibility in case someone is calling
978      * DB_Error() dynamically
979      * @param $method
980      * @param $arguments
981      * @return bool|mixed
982      */
983     public function __call($method, $arguments)
984     {
985         if ($method == 'DB_Error') {
986             return call_user_func_array(array($this, '__construct'), $arguments);
987         }
988         trigger_error(
989             'Call to undefined method DB_Error::' . $method . '()', E_USER_ERROR
990         );
991         return false;
992     }
993     // }}}
994 }
995
996 // }}}
997 // {{{ class DB_result
998
999 /**
1000  * This class implements a wrapper for a DB result set
1001  *
1002  * A new instance of this class will be returned by the DB implementation
1003  * after processing a query that returns data.
1004  *
1005  * @category   Database
1006  * @package    DB
1007  * @author     Stig Bakken <ssb@php.net>
1008  * @copyright  1997-2007 The PHP Group
1009  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
1010  * @version    Release: 1.9.2
1011  * @link       http://pear.php.net/package/DB
1012  */
1013 class DB_result
1014 {
1015     // {{{ properties
1016
1017     /**
1018      * Should results be freed automatically when there are no more rows?
1019      * @var boolean
1020      * @see DB_common::$options
1021      */
1022     var $autofree;
1023
1024     /**
1025      * A reference to the DB_<driver> object
1026      * @var object
1027      */
1028     var $dbh;
1029
1030     /**
1031      * The current default fetch mode
1032      * @var integer
1033      * @see DB_common::$fetchmode
1034      */
1035     var $fetchmode;
1036
1037     /**
1038      * The name of the class into which results should be fetched when
1039      * DB_FETCHMODE_OBJECT is in effect
1040      *
1041      * @var string
1042      * @see DB_common::$fetchmode_object_class
1043      */
1044     var $fetchmode_object_class;
1045
1046     /**
1047      * The number of rows to fetch from a limit query
1048      * @var integer
1049      */
1050     var $limit_count = null;
1051
1052     /**
1053      * The row to start fetching from in limit queries
1054      * @var integer
1055      */
1056     var $limit_from = null;
1057
1058     /**
1059      * The execute parameters that created this result
1060      * @var array
1061      * @since Property available since Release 1.7.0
1062      */
1063     var $parameters;
1064
1065     /**
1066      * The query string that created this result
1067      *
1068      * Copied here incase it changes in $dbh, which is referenced
1069      *
1070      * @var string
1071      * @since Property available since Release 1.7.0
1072      */
1073     var $query;
1074
1075     /**
1076      * The query result resource id created by PHP
1077      * @var resource
1078      */
1079     var $result;
1080
1081     /**
1082      * The present row being dealt with
1083      * @var integer
1084      */
1085     var $row_counter = null;
1086
1087     /**
1088      * The prepared statement resource id created by PHP in $dbh
1089      *
1090      * This resource is only available when the result set was created using
1091      * a driver's native execute() method, not PEAR DB's emulated one.
1092      *
1093      * Copied here incase it changes in $dbh, which is referenced
1094      *
1095      * {@internal  Mainly here because the InterBase/Firebird API is only
1096      * able to retrieve data from result sets if the statemnt handle is
1097      * still in scope.}}
1098      *
1099      * @var resource
1100      * @since Property available since Release 1.7.0
1101      */
1102     var $statement;
1103
1104
1105     // }}}
1106     // {{{ constructor
1107
1108     /**
1109      * This constructor sets the object's properties
1110      *
1111      * @param object   &$dbh the DB object reference
1112      * @param resource $result the result resource id
1113      * @param array $options an associative array with result options
1114      *
1115      * @return void
1116      */
1117     function __construct(&$dbh, $result, $options = array())
1118     {
1119         $this->autofree = $dbh->options['autofree'];
1120         $this->dbh = &$dbh;
1121         $this->fetchmode = $dbh->fetchmode;
1122         $this->fetchmode_object_class = $dbh->fetchmode_object_class;
1123         $this->parameters = $dbh->last_parameters;
1124         $this->query = $dbh->last_query;
1125         $this->result = $result;
1126         $this->statement = empty($dbh->last_stmt) ? null : $dbh->last_stmt;
1127         foreach ($options as $key => $value) {
1128             $this->setOption($key, $value);
1129         }
1130     }
1131
1132     /**
1133      * Set options for the DB_result object
1134      *
1135      * @param string $key the option to set
1136      * @param mixed $value the value to set the option to
1137      *
1138      * @return void
1139      */
1140     function setOption($key, $value = null)
1141     {
1142         switch ($key) {
1143             case 'limit_from':
1144                 $this->limit_from = $value;
1145                 break;
1146             case 'limit_count':
1147                 $this->limit_count = $value;
1148         }
1149     }
1150
1151     // }}}
1152     // {{{ fetchRow()
1153
1154     /**
1155      * Fetch a row of data and return it by reference into an array
1156      *
1157      * The type of array returned can be controlled either by setting this
1158      * method's <var>$fetchmode</var> parameter or by changing the default
1159      * fetch mode setFetchMode() before calling this method.
1160      *
1161      * There are two options for standardizing the information returned
1162      * from databases, ensuring their values are consistent when changing
1163      * DBMS's.  These portability options can be turned on when creating a
1164      * new DB object or by using setOption().
1165      *
1166      *   + <var>DB_PORTABILITY_LOWERCASE</var>
1167      *     convert names of fields to lower case
1168      *
1169      *   + <var>DB_PORTABILITY_RTRIM</var>
1170      *     right trim the data
1171      *
1172      * @param int $fetchmode the constant indicating how to format the data
1173      * @param int $rownum the row number to fetch (index starts at 0)
1174      *
1175      * @return mixed  an array or object containing the row's data,
1176      *                 NULL when the end of the result set is reached
1177      *                 or a DB_Error object on failure.
1178      *
1179      * @see DB_common::setOption(), DB_common::setFetchMode()
1180      */
1181     function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1182     {
1183         if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1184             $fetchmode = $this->fetchmode;
1185         }
1186         if ($fetchmode === DB_FETCHMODE_OBJECT) {
1187             $fetchmode = DB_FETCHMODE_ASSOC;
1188             $object_class = $this->fetchmode_object_class;
1189         }
1190         if (is_null($rownum) && $this->limit_from !== null) {
1191             if ($this->row_counter === null) {
1192                 $this->row_counter = $this->limit_from;
1193                 // Skip rows
1194                 if ($this->dbh->features['limit'] === false) {
1195                     $i = 0;
1196                     while ($i++ < $this->limit_from) {
1197                         $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1198                     }
1199                 }
1200             }
1201             if ($this->row_counter >= ($this->limit_from + $this->limit_count)) {
1202                 if ($this->autofree) {
1203                     $this->free();
1204                 }
1205                 $tmp = null;
1206                 return $tmp;
1207             }
1208             if ($this->dbh->features['limit'] === 'emulate') {
1209                 $rownum = $this->row_counter;
1210             }
1211             $this->row_counter++;
1212         }
1213         $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1214         if ($res === DB_OK) {
1215             if (isset($object_class)) {
1216                 // The default mode is specified in the
1217                 // DB_common::fetchmode_object_class property
1218                 if ($object_class == 'stdClass') {
1219                     $arr = (object)$arr;
1220                 } else {
1221                     $arr = new $object_class($arr);
1222                 }
1223             }
1224             return $arr;
1225         }
1226         if ($res == null && $this->autofree) {
1227             $this->free();
1228         }
1229         return $res;
1230     }
1231
1232     // }}}
1233     // {{{ fetchInto()
1234
1235     /**
1236      * Frees the resources allocated for this result set
1237      *
1238      * @return bool  true on success.  A DB_Error object on failure.
1239      */
1240     function free()
1241     {
1242         $err = $this->dbh->freeResult($this->result);
1243         if (DB::isError($err)) {
1244             return $err;
1245         }
1246         $this->result = false;
1247         $this->statement = false;
1248         return true;
1249     }
1250
1251     // }}}
1252     // {{{ numCols()
1253
1254     /**
1255      * Fetch a row of data into an array which is passed by reference
1256      *
1257      * The type of array returned can be controlled either by setting this
1258      * method's <var>$fetchmode</var> parameter or by changing the default
1259      * fetch mode setFetchMode() before calling this method.
1260      *
1261      * There are two options for standardizing the information returned
1262      * from databases, ensuring their values are consistent when changing
1263      * DBMS's.  These portability options can be turned on when creating a
1264      * new DB object or by using setOption().
1265      *
1266      *   + <var>DB_PORTABILITY_LOWERCASE</var>
1267      *     convert names of fields to lower case
1268      *
1269      *   + <var>DB_PORTABILITY_RTRIM</var>
1270      *     right trim the data
1271      *
1272      * @param array &$arr the variable where the data should be placed
1273      * @param int $fetchmode the constant indicating how to format the data
1274      * @param int $rownum the row number to fetch (index starts at 0)
1275      *
1276      * @return mixed  DB_OK if a row is processed, NULL when the end of the
1277      *                 result set is reached or a DB_Error object on failure
1278      *
1279      * @see DB_common::setOption(), DB_common::setFetchMode()
1280      */
1281     function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
1282     {
1283         if ($fetchmode === DB_FETCHMODE_DEFAULT) {
1284             $fetchmode = $this->fetchmode;
1285         }
1286         if ($fetchmode === DB_FETCHMODE_OBJECT) {
1287             $fetchmode = DB_FETCHMODE_ASSOC;
1288             $object_class = $this->fetchmode_object_class;
1289         }
1290         if (is_null($rownum) && $this->limit_from !== null) {
1291             if ($this->row_counter === null) {
1292                 $this->row_counter = $this->limit_from;
1293                 // Skip rows
1294                 if ($this->dbh->features['limit'] === false) {
1295                     $i = 0;
1296                     while ($i++ < $this->limit_from) {
1297                         $this->dbh->fetchInto($this->result, $arr, $fetchmode);
1298                     }
1299                 }
1300             }
1301             if ($this->row_counter >= (
1302                     $this->limit_from + $this->limit_count)) {
1303                 if ($this->autofree) {
1304                     $this->free();
1305                 }
1306                 return null;
1307             }
1308             if ($this->dbh->features['limit'] === 'emulate') {
1309                 $rownum = $this->row_counter;
1310             }
1311
1312             $this->row_counter++;
1313         }
1314         $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
1315         if ($res === DB_OK) {
1316             if (isset($object_class)) {
1317                 // default mode specified in the
1318                 // DB_common::fetchmode_object_class property
1319                 if ($object_class == 'stdClass') {
1320                     $arr = (object)$arr;
1321                 } else {
1322                     $arr = new $object_class($arr);
1323                 }
1324             }
1325             return DB_OK;
1326         }
1327         if ($res == null && $this->autofree) {
1328             $this->free();
1329         }
1330         return $res;
1331     }
1332
1333     // }}}
1334     // {{{ numRows()
1335
1336     /**
1337      * Get the the number of columns in a result set
1338      *
1339      * @return int  the number of columns.  A DB_Error object on failure.
1340      */
1341     function numCols()
1342     {
1343         return $this->dbh->numCols($this->result);
1344     }
1345
1346     // }}}
1347     // {{{ nextResult()
1348
1349     /**
1350      * Get the number of rows in a result set
1351      *
1352      * @return int  the number of rows.  A DB_Error object on failure.
1353      */
1354     function numRows()
1355     {
1356         if ($this->dbh->features['numrows'] === 'emulate'
1357             && $this->dbh->options['portability'] & DB_PORTABILITY_NUMROWS) {
1358             if ($this->dbh->features['prepare']) {
1359                 $res = $this->dbh->query($this->query, $this->parameters);
1360             } else {
1361                 $res = $this->dbh->query($this->query);
1362             }
1363             if (DB::isError($res)) {
1364                 return $res;
1365             }
1366             $i = 0;
1367             while ($res->fetchInto($tmp, DB_FETCHMODE_ORDERED)) {
1368                 $i++;
1369             }
1370             $count = $i;
1371         } else {
1372             $count = $this->dbh->numRows($this->result);
1373         }
1374
1375         /* fbsql is checked for here because limit queries are implemented
1376          * using a TOP() function, which results in fbsql_num_rows still
1377          * returning the total number of rows that would have been returned,
1378          * rather than the real number. As a result, we'll just do the limit
1379          * calculations for fbsql in the same way as a database with emulated
1380          * limits. Unfortunately, we can't just do this in DB_fbsql::numRows()
1381          * because that only gets the result resource, rather than the full
1382          * DB_Result object. */
1383         if (($this->dbh->features['limit'] === 'emulate'
1384                 && $this->limit_from !== null)
1385             || $this->dbh->phptype == 'fbsql') {
1386             $limit_count = is_null($this->limit_count) ? $count : $this->limit_count;
1387             if ($count < $this->limit_from) {
1388                 $count = 0;
1389             } elseif ($count < ($this->limit_from + $limit_count)) {
1390                 $count -= $this->limit_from;
1391             } else {
1392                 $count = $limit_count;
1393             }
1394         }
1395
1396         return $count;
1397     }
1398
1399     // }}}
1400     // {{{ free()
1401
1402     /**
1403      * Get the next result if a batch of queries was executed
1404      *
1405      * @return bool  true if a new result is available or false if not
1406      */
1407     function nextResult()
1408     {
1409         return $this->dbh->nextResult($this->result);
1410     }
1411
1412     // }}}
1413     // {{{ tableInfo()
1414
1415     /**
1416      * @param null $mode
1417      * @return
1418      * @see DB_common::tableInfo()
1419      * @deprecated Method deprecated some time before Release 1.2
1420      */
1421     function tableInfo($mode = null)
1422     {
1423         if (is_string($mode)) {
1424             return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
1425         }
1426         return $this->dbh->tableInfo($this, $mode);
1427     }
1428
1429     // }}}
1430     // {{{ getQuery()
1431
1432     /**
1433      * Determine the query string that created this result
1434      *
1435      * @return string  the query string
1436      *
1437      * @since Method available since Release 1.7.0
1438      */
1439     function getQuery()
1440     {
1441         return $this->query;
1442     }
1443
1444     // }}}
1445     // {{{ getRowCounter()
1446
1447     /**
1448      * Tells which row number is currently being processed
1449      *
1450      * @return integer  the current row being looked at.  Starts at 1.
1451      */
1452     function getRowCounter()
1453     {
1454         return $this->row_counter;
1455     }
1456
1457     // }}}
1458 }
1459
1460 // }}}
1461 // {{{ class DB_row
1462
1463 /**
1464  * PEAR DB Row Object
1465  *
1466  * The object contains a row of data from a result set.  Each column's data
1467  * is placed in a property named for the column.
1468  *
1469  * @category   Database
1470  * @package    DB
1471  * @author     Stig Bakken <ssb@php.net>
1472  * @copyright  1997-2007 The PHP Group
1473  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
1474  * @version    Release: 1.9.2
1475  * @link       http://pear.php.net/package/DB
1476  * @see        DB_common::setFetchMode()
1477  */
1478 class DB_row
1479 {
1480     // {{{ constructor
1481
1482     /**
1483      * The constructor places a row's data into properties of this object
1484      *
1485      * @param array  the array containing the row's data
1486      *
1487      * @return void
1488      */
1489     function __construct(&$arr)
1490     {
1491         foreach ($arr as $key => $value) {
1492             $this->$key = &$arr[$key];
1493         }
1494     }
1495
1496     // }}}
1497 }
1498
1499 // }}}
1500
1501 /*
1502  * Local variables:
1503  * tab-width: 4
1504  * c-basic-offset: 4
1505  * End:
1506  */