File: MDB.php

package info (click to toggle)
irm 1.5.3.1-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,436 kB
  • ctags: 3,308
  • sloc: php: 16,796; sh: 127; perl: 97; pascal: 56; makefile: 48
file content (733 lines) | stat: -rw-r--r-- 26,620 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox,                 |
// | Stig. S. Bakken, Lukas Smith                                         |
// | All rights reserved.                                                 |
// +----------------------------------------------------------------------+
// | MDB is a merge of PEAR DB and Metabases that provides a unified DB   |
// | API as well as database abstraction for PHP applications.            |
// | This LICENSE is in the BSD license style.                            |
// |                                                                      |
// | Redistribution and use in source and binary forms, with or without   |
// | modification, are permitted provided that the following conditions   |
// | are met:                                                             |
// |                                                                      |
// | Redistributions of source code must retain the above copyright       |
// | notice, this list of conditions and the following disclaimer.        |
// |                                                                      |
// | Redistributions in binary form must reproduce the above copyright    |
// | notice, this list of conditions and the following disclaimer in the  |
// | documentation and/or other materials provided with the distribution. |
// |                                                                      |
// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
// | Lukas Smith nor the names of his contributors may be used to endorse |
// | or promote products derived from this software without specific prior|
// | written permission.                                                  |
// |                                                                      |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
// | POSSIBILITY OF SUCH DAMAGE.                                          |
// +----------------------------------------------------------------------+
// | Author: Lukas Smith <smith@backendmedia.com>                         |
// +----------------------------------------------------------------------+
//
// $Id: MDB.php,v 1.59.4.12 2004/02/28 10:37:54 quipo Exp $
//
require_once('PEAR.php');

/**
 * The method mapErrorCode in each MDB_dbtype implementation maps
 * native error codes to one of these.
 *
 * If you add an error code here, make sure you also add a textual
 * version of it in MDB::errorMessage().
 */

define('MDB_OK',                         1);
define('MDB_ERROR',                     -1);
define('MDB_ERROR_SYNTAX',              -2);
define('MDB_ERROR_CONSTRAINT',          -3);
define('MDB_ERROR_NOT_FOUND',           -4);
define('MDB_ERROR_ALREADY_EXISTS',      -5);
define('MDB_ERROR_UNSUPPORTED',         -6);
define('MDB_ERROR_MISMATCH',            -7);
define('MDB_ERROR_INVALID',             -8);
define('MDB_ERROR_NOT_CAPABLE',         -9);
define('MDB_ERROR_TRUNCATED',          -10);
define('MDB_ERROR_INVALID_NUMBER',     -11);
define('MDB_ERROR_INVALID_DATE',       -12);
define('MDB_ERROR_DIVZERO',            -13);
define('MDB_ERROR_NODBSELECTED',       -14);
define('MDB_ERROR_CANNOT_CREATE',      -15);
define('MDB_ERROR_CANNOT_DELETE',      -16);
define('MDB_ERROR_CANNOT_DROP',        -17);
define('MDB_ERROR_NOSUCHTABLE',        -18);
define('MDB_ERROR_NOSUCHFIELD',        -19);
define('MDB_ERROR_NEED_MORE_DATA',     -20);
define('MDB_ERROR_NOT_LOCKED',         -21);
define('MDB_ERROR_VALUE_COUNT_ON_ROW', -22);
define('MDB_ERROR_INVALID_DSN',        -23);
define('MDB_ERROR_CONNECT_FAILED',     -24);
define('MDB_ERROR_EXTENSION_NOT_FOUND',-25);
define('MDB_ERROR_NOSUCHDB',           -26);
define('MDB_ERROR_ACCESS_VIOLATION',   -27);
define('MDB_ERROR_CANNOT_REPLACE',     -28);
define('MDB_ERROR_CONSTRAINT_NOT_NULL',-29);
define('MDB_ERROR_DEADLOCK',           -30);
define('MDB_ERROR_CANNOT_ALTER',       -31);
define('MDB_ERROR_MANAGER',            -32);
define('MDB_ERROR_MANAGER_PARSE',      -33);
define('MDB_ERROR_LOADMODULE',         -34);
define('MDB_ERROR_INSUFFICIENT_DATA',  -35);
/**
 * This is a special constant that tells DB the user hasn't specified
 * any particular get mode, so the default should be used.
 */

define('MDB_FETCHMODE_DEFAULT', 0);

/**
 * Column data indexed by numbers, ordered from 0 and up
 */

define('MDB_FETCHMODE_ORDERED',  1);

/**
 * Column data indexed by column names
 */

define('MDB_FETCHMODE_ASSOC',    2);

/**
 * For multi-dimensional results: normally the first level of arrays
 * is the row number, and the second level indexed by column number or name.
 * MDB_FETCHMODE_FLIPPED switches this order, so the first level of arrays
 * is the column name, and the second level the row number.
 */

define('MDB_FETCHMODE_FLIPPED',  4);

/**
 * These are constants for the tableInfo-function
 * they are bitwised or'ed. so if there are more constants to be defined
 * in the future, adjust MDB_TABLEINFO_FULL accordingly
 */

define('MDB_TABLEINFO_ORDER',      1);
define('MDB_TABLEINFO_ORDERTABLE', 2);
define('MDB_TABLEINFO_FULL',       3);

/**
 * These are constants for each of the supported datatypes
 */

define('MDB_TYPE_TEXT'      , 0);
define('MDB_TYPE_BOOLEAN'   , 1);
define('MDB_TYPE_INTEGER'   , 2);
define('MDB_TYPE_DECIMAL'   , 3);
define('MDB_TYPE_FLOAT'     , 4);
define('MDB_TYPE_DATE'      , 5);
define('MDB_TYPE_TIME'      , 6);
define('MDB_TYPE_TIMESTAMP' , 7);
define('MDB_TYPE_CLOB'      , 8);
define('MDB_TYPE_BLOB'      , 9);

/**
 * These are global variables that are used to track the various class instances
 */

$GLOBALS['_MDB_lobs'] = array();
$GLOBALS['_MDB_databases'] = array();

/**
 * The main 'MDB' class is simply a container class with some static
 * methods for creating DB objects as well as some utility functions
 * common to all parts of DB.
 *
 * The object model of DB is as follows (indentation means inheritance):
 *
 * MDB          The main DB class.  This is simply a utility class
 *              with some 'static' methods for creating MDB objects as
 *              well as common utility functions for other MDB classes.
 *
 * MDB_common   The base for each DB implementation.  Provides default
 * |            implementations (in OO lingo virtual methods) for
 * |            the actual DB implementations as well as a bunch of
 * |            query utility functions.
 * |
 * +-MDB_mysql  The DB implementation for MySQL. Inherits MDB_Common.
 *              When calling MDB::factory or MDB::connect for MySQL
 *              connections, the object returned is an instance of this
 *              class.
 * +-MDB_pgsql  The DB implementation for PostGreSQL. Inherits MDB_Common.
 *              When calling MDB::factory or MDB::connect for PostGreSQL
 *              connections, the object returned is an instance of this
 *              class.
 *
 * MDB_Date     This class provides several method to convert from and to
 *              MDB timestamps.
 *
 * MDB_Manager  This class handles the xml schema management.
 *
 * @package  MDB
 * @version  $Id: MDB.php,v 1.59.4.12 2004/02/28 10:37:54 quipo Exp $
 * @category Database
 * @author   Lukas Smith <smith@backendmedia.com>
 */
class MDB
{
    // }}}
    // {{{ setOptions()

    /**
     * set option array in an exiting database object
     *
     * @param   object  $db       MDB object
     * @param   mixed   $options  An associative array of option names and
     *                            their values.
     * @access  public
     */
    function setOptions(&$db, $options)
    {
        if(is_array($options)) {
            foreach($options as $option => $value) {
                $test = $db->setOption($option, $value);
                if(MDB::isError($test)) {
                    return $test;
                }
            }
        } else {
            $db->setOption('persistent', $options);
        }
        $include_lob = $db->getOption('includelob');
        if(!MDB::isError($include_lob) && $include_lob) {
            $db->loadLob('load at start');
        }
        $includemanager = $db->getOption('includemanager');
        if(!MDB::isError($includemanager) && $includemanager) {
            $db->loadManager('load at start');
        }
        $debug = $db->getOption('debug');
        if(!MDB::isError($debug) && $debug) {
            $db->captureDebugOutput(TRUE);
        }
    }

    // }}}
    // {{{ factory()

    /**
     * Create a new DB connection object for the specified database
     * type
     * IMPORTANT: In order for MDB to work properly it is necessary that
     * you make sure that you work with a reference of the original
     * object instead of a copy (this is a PHP4 quirk).
     *
     * For example:
     *     $mdb =& MDB::factory($dsn);
     *          ^^
     * And not:
     *     $mdb = MDB::factory($dsn);
     *          ^^
     *
     * @param   string  $type   database type, for example 'mysql'
     * @return  mixed   a newly created MDB connection object, or a MDB
     *                  error object on error
     * @access  public
     */
    function &factory($type)
    {
        $class_name = "MDB_$type";

        @include_once("MDB/${type}.php");

        @$db =& new $class_name;

        return($db);
    }

    // }}}
    // {{{ connect()

    /**
     * Create a new MDB connection object and connect to the specified
     * database
     *
     * IMPORTANT: In order for MDB to work properly it is necessary that
     * you make sure that you work with a reference of the original
     * object instead of a copy (this is a PHP4 quirk).
     *
     * For example:
     *     $mdb =& MDB::connect($dsn);
     *          ^^
     * And not:
     *     $mdb = MDB::connect($dsn);
     *          ^^
     *
     * @param   mixed   $dsn      'data source name', see the MDB::parseDSN
     *                            method for a description of the dsn format.
     *                            Can also be specified as an array of the
     *                            format returned by MDB::parseDSN.
     * @param   mixed   $options  An associative array of option names and
     *                            their values.
     * @return  mixed   a newly created MDB connection object, or a MDB
     *                  error object on error
     * @access  public
     * @see     MDB::parseDSN
     */
    function &connect($dsn, $options = FALSE)
    {
        $dsninfo = MDB::parseDSN($dsn);
        if(isset($dsninfo['phptype'])) {
            $type          = $dsninfo['phptype'];
            $class_name    = 'MDB_'.$type;
            $include       = 'MDB/'.$type.'.php';
        } else {
            return(PEAR::raiseError(NULL, MDB_ERROR_NOT_FOUND,
                NULL, NULL, 'no RDBMS driver specified',
                'MDB_Error', TRUE));
        }

        if(is_array($options)
            && isset($options['debug'])
            && $options['debug'] >= 2
        ) {
            // expose php errors with sufficient debug level
            @include_once($include);
        } else {
            include_once($include);
        }

        if(!class_exists($class_name)) {
            $error = PEAR::raiseError(NULL, MDB_ERROR_NOT_FOUND, NULL, NULL,
                'Unable to include the '.$include.' file', 'MDB_Error', TRUE);
            return($error);
        }

        @$db =& new $class_name();

        $db->setDSN($dsninfo);

        MDB::setOptions($db, $options);

        if(isset($dsninfo['database'])) {
            $err = $db->connect();
            if (MDB::isError($err)) {
                $dsn = $db->getDSN();
                $err->addUserInfo($dsn);
                return($err);
            }
        }
        return($db);
    }

    // }}}
    // {{{ connect()

    /**
     * Returns a MDB connection with the requested DSN.
     * A newnew MDB connection object is only created if no object with the
     * reuested DSN exists yet.
     *
     * IMPORTANT: In order for MDB to work properly it is necessary that
     * you make sure that you work with a reference of the original
     * object instead of a copy (this is a PHP4 quirk).
     *
     * For example:
     *     $mdb =& MDB::sngleton($dsn);
     *          ^^
     * And not:
     *     $mdb = MDB::singleton($dsn);
     *          ^^
     *
     * @param   mixed   $dsn      'data source name', see the MDB::parseDSN
     *                            method for a description of the dsn format.
     *                            Can also be specified as an array of the
     *                            format returned by MDB::parseDSN.
     * @param   mixed   $options  An associative array of option names and
     *                            their values.
     * @return  mixed   a newly created MDB connection object, or a MDB
     *                  error object on error
     * @access  public
     * @see     MDB::parseDSN
     */
    function &singleton($dsn = NULL, $options = FALSE)
    {
        if ($dsn) {
            $dsninfo = MDB::parseDSN($dsn);
            $dsninfo_default = array(
                'phptype' => NULL,
                'username' => NULL,
                'password' => NULL,
                'hostspec' => NULL,
                'database' => NULL,
            );
            $dsninfo = array_merge($dsninfo_default, $dsninfo);
            $keys = array_keys($GLOBALS['_MDB_databases']);
            for ($i=0, $j=count($keys); $i<$j; ++$i) {
                $tmp_dsn = $GLOBALS['_MDB_databases'][$keys[$i]]->getDSN('array');
                if ($dsninfo['phptype'] == $tmp_dsn['phptype']
                    && $dsninfo['username'] == $tmp_dsn['username']
                    && $dsninfo['password'] == $tmp_dsn['password']
                    && $dsninfo['hostspec'] == $tmp_dsn['hostspec']
                    && $dsninfo['database'] == $tmp_dsn['database'])
                {
                    MDB::setOptions($GLOBALS['_MDB_databases'][$keys[$i]], $options);
                    return $GLOBALS['_MDB_databases'][$keys[$i]];
                }
            }
        } else {
            if (is_array($GLOBALS['_MDB_databases'])
                && reset($GLOBALS['_MDB_databases'])
            ) {
                $db =& $GLOBALS['_MDB_databases'][key($GLOBALS['_MDB_databases'])];
                return $db;
            }
        }
        $db =& MDB::connect($dsn, $options);
        return $db;
    }

    // }}}
    // {{{ loadFile()

    /**
     * load a file (like 'Date.php' or 'Manager.php')
     *
     * @return $file    name of the file to be included from the MDB dir without
     *                  the '.php' extension (like 'Date' or 'Manager')
     * @access public
     */
    function loadFile($file)
    {
        @include_once('MDB/'.$file.'.php');
    }

    // }}}
    // {{{ apiVersion()

    /**
     * Return the MDB API version
     *
     * @return int     the MDB API version number
     * @access public
     */
    function apiVersion()
    {
        return(1);
    }

    // }}}
    // {{{ isError()

    /**
     * Tell whether a result code from a MDB method is an error
     *
     * @param   int       $value  result code
     * @return  boolean   whether $value is an MDB_Error
     * @access public
     */
    function isError($value)
    {
        return is_a($value, 'MDB_Error');
    }

    // }}}
    // {{{ isConnection()
    /**
     * Tell whether a value is a MDB connection
     *
     * @param mixed $value value to test
     *
     * @return bool whether $value is a MDB connection
     *
     * @access public
     */
    function isConnection($value)
    {
        return is_a($value, 'MDB_Common');
    }

    // }}}
    // {{{ isManip()

    /**
     * Tell whether a query is a data manipulation query (insert,
     * update or delete) or a data definition query (create, drop,
     * alter, grant, revoke).
     *
     * @param   string   $query the query
     * @return  boolean  whether $query is a data manipulation query
     * @access public
     */
    function isManip($query)
    {
        $manips = 'INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|
                  ALTER|GRANT|REVOKE|LOCK|UNLOCK|ROLLBACK|COMMIT';
        if (preg_match('/^\s*"?('.$manips.')\s+/i', $query)) {
            return(TRUE);
        }
        return(FALSE);
    }

    // }}}
    // {{{ errorMessage()

    /**
     * Return a textual error message for a MDB error code
     *
     * @param   int     $value error code
     * @return  string  error message, or false if the error code was
     *                  not recognized
     * @access public
     */
    function errorMessage($value)
    {
        static $errorMessages;
        if (!isset($errorMessages)) {
            $errorMessages = array(
                MDB_ERROR                    => 'unknown error',
                MDB_ERROR_ALREADY_EXISTS     => 'already exists',
                MDB_ERROR_CANNOT_CREATE      => 'can not create',
                MDB_ERROR_CANNOT_ALTER       => 'can not alter',
                MDB_ERROR_CANNOT_REPLACE     => 'can not replace',
                MDB_ERROR_CANNOT_DELETE      => 'can not delete',
                MDB_ERROR_CANNOT_DROP        => 'can not drop',
                MDB_ERROR_CONSTRAINT         => 'constraint violation',
                MDB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
                MDB_ERROR_DIVZERO            => 'division by zero',
                MDB_ERROR_INVALID            => 'invalid',
                MDB_ERROR_INVALID_DATE       => 'invalid date or time',
                MDB_ERROR_INVALID_NUMBER     => 'invalid number',
                MDB_ERROR_MISMATCH           => 'mismatch',
                MDB_ERROR_NODBSELECTED       => 'no database selected',
                MDB_ERROR_NOSUCHFIELD        => 'no such field',
                MDB_ERROR_NOSUCHTABLE        => 'no such table',
                MDB_ERROR_NOT_CAPABLE        => 'MDB backend not capable',
                MDB_ERROR_NOT_FOUND          => 'not found',
                MDB_ERROR_NOT_LOCKED         => 'not locked',
                MDB_ERROR_SYNTAX             => 'syntax error',
                MDB_ERROR_UNSUPPORTED        => 'not supported',
                MDB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
                MDB_ERROR_INVALID_DSN        => 'invalid DSN',
                MDB_ERROR_CONNECT_FAILED     => 'connect failed',
                MDB_OK                       => 'no error',
                MDB_ERROR_NEED_MORE_DATA     => 'insufficient data supplied',
                MDB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
                MDB_ERROR_NOSUCHDB           => 'no such database',
                MDB_ERROR_ACCESS_VIOLATION   => 'insufficient permissions',
                MDB_ERROR_MANAGER            => 'MDB_manager error',
                MDB_ERROR_MANAGER_PARSE      => 'MDB_manager schema parse error',
                MDB_ERROR_LOADMODULE         => 'Error while including on demand module',
                MDB_ERROR_TRUNCATED          => 'truncated',
                MDB_ERROR_DEADLOCK           => 'deadlock detected',
            );
        }

        if (MDB::isError($value)) {
            $value = $value->getCode();
        }

        return(isset($errorMessages[$value]) ?
           $errorMessages[$value] : $errorMessages[MDB_ERROR]);
    }

    // }}}
    // {{{ parseDSN()

    /**
     * Parse a data source name
     *
     * A array with the following keys will be returned:
     *  phptype: Database backend used in PHP (mysql, odbc etc.)
     *  dbsyntax: Database used with regards to SQL syntax etc.
     *  protocol: Communication protocol to use (tcp, unix etc.)
     *  hostspec: Host specification (hostname[:port])
     *  database: Database to use on the DBMS server
     *  username: User name for login
     *  password: Password for login
     *
     * The format of the supplied DSN is in its fullest form:
     *
     *  phptype(dbsyntax)://username:password@protocol+hostspec/database
     *
     * Most variations are allowed:
     *
     *  phptype://username:password@protocol+hostspec:110//usr/db_file.db
     *  phptype://username:password@hostspec/database_name
     *  phptype://username:password@hostspec
     *  phptype://username@hostspec
     *  phptype://hostspec/database
     *  phptype://hostspec
     *  phptype(dbsyntax)
     *  phptype
     *
     * @param   string  $dsn Data Source Name to be parsed
     * @return  array   an associative array
     * @access public
     * @author Tomas V.V.Cox <cox@idecnet.com>
     */
    function parseDSN($dsn)
    {
        if (is_array($dsn)) {
            return($dsn);
        }

        $parsed = array(
            'phptype'  => FALSE,
            'dbsyntax' => FALSE,
            'username' => FALSE,
            'password' => FALSE,
            'protocol' => FALSE,
            'hostspec' => FALSE,
            'port'     => FALSE,
            'socket'   => FALSE,
            'database' => FALSE
        );

        // Find phptype and dbsyntax
        if (($pos = strpos($dsn, '://')) !== FALSE) {
            $str = substr($dsn, 0, $pos);
            $dsn = substr($dsn, $pos + 3);
        } else {
            $str = $dsn;
            $dsn = NULL;
        }

        // Get phptype and dbsyntax
        // $str => phptype(dbsyntax)
        if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
            $parsed['phptype']  = $arr[1];
            $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
        } else {
            $parsed['phptype']  = $str;
            $parsed['dbsyntax'] = $str;
        }

        if (empty($dsn)) {
            return($parsed);
        }

        // Get (if found): username and password
        // $dsn => username:password@protocol+hostspec/database
        if (($at = strrpos($dsn,'@')) !== FALSE) {
            $str = substr($dsn, 0, $at);
            $dsn = substr($dsn, $at + 1);
            if (($pos = strpos($str, ':')) !== FALSE) {
                $parsed['username'] = rawurldecode(substr($str, 0, $pos));
                $parsed['password'] = rawurldecode(substr($str, $pos + 1));
            } else {
                $parsed['username'] = rawurldecode($str);
            }
        }

        // Find protocol and hostspec

        // $dsn => proto(proto_opts)/database
        if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
            $proto       = $match[1];
            $proto_opts  = (!empty($match[2])) ? $match[2] : FALSE;
            $dsn         = $match[3];

        // $dsn => protocol+hostspec/database (old format)
        } else {
            if (strpos($dsn, '+') !== FALSE) {
                list($proto, $dsn) = explode('+', $dsn, 2);
            }
            if (strpos($dsn, '/') !== FALSE) {
                list($proto_opts, $dsn) = explode('/', $dsn, 2);
            } else {
                $proto_opts = $dsn;
                $dsn = NULL;
            }
        }

        // process the different protocol options
        $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
        $proto_opts = rawurldecode($proto_opts);
        if ($parsed['protocol'] == 'tcp') {
            if (strpos($proto_opts, ':') !== FALSE) {
                list($parsed['hostspec'], $parsed['port']) =
                                                     explode(':', $proto_opts);
            } else {
                $parsed['hostspec'] = $proto_opts;
            }
        } elseif ($parsed['protocol'] == 'unix') {
            $parsed['socket'] = $proto_opts;
        }

        // Get dabase if any
        // $dsn => database
        if (!empty($dsn)) {
            // /database
            if (($pos = strpos($dsn, '?')) === FALSE) {
                $parsed['database'] = $dsn;
            // /database?param1=value1&param2=value2
            } else {
                $parsed['database'] = substr($dsn, 0, $pos);
                $dsn = substr($dsn, $pos + 1);
                if (strpos($dsn, '&') !== FALSE) {
                    $opts = explode('&', $dsn);
                } else { // database?param1=value1
                    $opts = array($dsn);
                }
                foreach ($opts as $opt) {
                    list($key, $value) = explode('=', $opt);
                    if (!isset($parsed[$key])) { // don't allow params overwrite
                        $parsed[$key] = rawurldecode($value);
                    }
                }
            }
        }

        return($parsed);
    }
}

/**
 * MDB_Error implements a class for reporting portable database error
 * messages.
 *
 * @package MDB
 * @category Database
 * @author  Stig Bakken <ssb@fast.no>
 */
class MDB_Error extends PEAR_Error
{

    // }}}
    // {{{ constructor

    /**
     * MDB_Error constructor.
     *
     * @param mixed   $code      MDB error code, or string with error message.
     * @param integer $mode      what 'error mode' to operate in
     * @param integer $level     what error level to use for
     *                           $mode & PEAR_ERROR_TRIGGER
     * @param smixed  $debuginfo additional debug info, such as the last query
     */
    function MDB_Error($code = MDB_ERROR, $mode = PEAR_ERROR_RETURN,
              $level = E_USER_NOTICE, $debuginfo = NULL)
    {
        if (is_int($code)) {
            $this->PEAR_Error('MDB Error: '.MDB::errorMessage($code), $code,
                $mode, $level, $debuginfo);
        } else {
            $this->PEAR_Error("MDB Error: $code", MDB_ERROR, $mode, $level,
                $debuginfo);
        }
    }
}
?>