]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/DB/msql.php
[ROUTES] Allow accept-header specification during router creation
[quix0rs-gnu-social.git] / extlib / DB / msql.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6  * The PEAR DB driver for PHP's msql extension
7  * for interacting with Mini SQL databases
8  *
9  * PHP's mSQL extension did weird things with NULL values prior to PHP
10  * 4.3.11 and 5.0.4.  Make sure your version of PHP meets or exceeds
11  * those versions.
12  *
13  * PHP version 5
14  *
15  * LICENSE: This source file is subject to version 3.0 of the PHP license
16  * that is available through the world-wide-web at the following URI:
17  * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
18  * the PHP License and are unable to obtain it through the web, please
19  * send a note to license@php.net so we can mail you a copy immediately.
20  *
21  * @category   Database
22  * @package    DB
23  * @author     Daniel Convissor <danielc@php.net>
24  * @copyright  1997-2007 The PHP Group
25  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
26  * @version    CVS: $Id$
27  * @link       http://pear.php.net/package/DB
28  */
29
30 /**
31  * Obtain the DB_common class so it can be extended from
32  */
33 //require_once 'DB/common.php';
34 require_once 'common.php';
35
36 /**
37  * The methods PEAR DB uses to interact with PHP's msql extension
38  * for interacting with Mini SQL databases
39  *
40  * These methods overload the ones declared in DB_common.
41  *
42  * PHP's mSQL extension did weird things with NULL values prior to PHP
43  * 4.3.11 and 5.0.4.  Make sure your version of PHP meets or exceeds
44  * those versions.
45  *
46  * @category   Database
47  * @package    DB
48  * @author     Daniel Convissor <danielc@php.net>
49  * @copyright  1997-2007 The PHP Group
50  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
51  * @version    Release: 1.9.2
52  * @link       http://pear.php.net/package/DB
53  * @since      Class not functional until Release 1.7.0
54  */
55 class DB_msql extends DB_common
56 {
57     // {{{ properties
58
59     /**
60      * The DB driver type (mysql, oci8, odbc, etc.)
61      * @var string
62      */
63     public $phptype = 'msql';
64
65     /**
66      * The database syntax variant to be used (db2, access, etc.), if any
67      * @var string
68      */
69     public $dbsyntax = 'msql';
70
71     /**
72      * The capabilities of this DB implementation
73      *
74      * The 'new_link' element contains the PHP version that first provided
75      * new_link support for this DBMS.  Contains false if it's unsupported.
76      *
77      * Meaning of the 'limit' element:
78      *   + 'emulate' = emulate with fetch row by number
79      *   + 'alter'   = alter the query
80      *   + false     = skip rows
81      *
82      * @var array
83      */
84     public $features = array(
85         'limit' => 'emulate',
86         'new_link' => false,
87         'numrows' => true,
88         'pconnect' => true,
89         'prepare' => false,
90         'ssl' => false,
91         'transactions' => false,
92     );
93
94     /**
95      * A mapping of native error codes to DB error codes
96      * @var array
97      */
98     public $errorcode_map = array();
99
100     /**
101      * The raw database connection created by PHP
102      * @var resource
103      */
104     public $connection;
105
106     /**
107      * The DSN information for connecting to a database
108      * @var array
109      */
110     public $dsn = array();
111
112
113     /**
114      * The query result resource created by PHP
115      *
116      * Used to make affectedRows() work.  Only contains the result for
117      * data manipulation queries.  Contains false for other queries.
118      *
119      * @var resource
120      * @access private
121      */
122     public $_result;
123
124
125     // }}}
126     // {{{ constructor
127
128     /**
129      * This constructor calls <kbd>parent::__construct()</kbd>
130      *
131      * @return void
132      */
133     public function __construct()
134     {
135         parent::__construct();
136     }
137
138     // }}}
139     // {{{ connect()
140
141     /**
142      * Connect to the database server, log in and open the database
143      *
144      * Don't call this method directly.  Use DB::connect() instead.
145      *
146      * Example of how to connect:
147      * <code>
148      * require_once 'DB.php';
149      *
150      * // $dsn = 'msql://hostname/dbname';  // use a TCP connection
151      * $dsn = 'msql:///dbname';             // use a socket
152      * $options = array(
153      *     'portability' => DB_PORTABILITY_ALL,
154      * );
155      *
156      * $db = DB::connect($dsn, $options);
157      * if ((new PEAR)->isError($db)) {
158      *     die($db->getMessage());
159      * }
160      * </code>
161      *
162      * @param array $dsn the data source name
163      * @param bool $persistent should the connection be persistent?
164      *
165      * @return int|object
166      */
167     public function connect($dsn, $persistent = false)
168     {
169         if (!PEAR::loadExtension('msql')) {
170             return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
171         }
172
173         $this->dsn = $dsn;
174         if ($dsn['dbsyntax']) {
175             $this->dbsyntax = $dsn['dbsyntax'];
176         }
177
178         $params = array();
179         if ($dsn['hostspec']) {
180             $params[] = $dsn['port']
181                 ? $dsn['hostspec'] . ',' . $dsn['port']
182                 : $dsn['hostspec'];
183         }
184
185         $connect_function = $persistent ? 'msql_pconnect' : 'msql_connect';
186
187         $ini = ini_get('track_errors');
188         $php_errormsg = '';
189         if ($ini) {
190             $this->connection = @call_user_func_array(
191                 $connect_function,
192                 $params
193             );
194         } else {
195             @ini_set('track_errors', 1);
196             $this->connection = @call_user_func_array(
197                 $connect_function,
198                 $params
199             );
200             @ini_set('track_errors', $ini);
201         }
202
203         if (!$this->connection) {
204             if (($err = @msql_error()) != '') {
205                 return $this->raiseError(
206                     DB_ERROR_CONNECT_FAILED,
207                     null,
208                     null,
209                     null,
210                     $err
211                 );
212             } else {
213                 return $this->raiseError(
214                     DB_ERROR_CONNECT_FAILED,
215                     null,
216                     null,
217                     null,
218                     $php_errormsg
219                 );
220             }
221         }
222
223         if (!@msql_select_db($dsn['database'], $this->connection)) {
224             return $this->msqlRaiseError();
225         }
226         return DB_OK;
227     }
228
229     // }}}
230     // {{{ disconnect()
231
232     /**
233      * Produces a DB_Error object regarding the current problem
234      *
235      * @param int $errno if the error is being manually raised pass a
236      *                     DB_ERROR* constant here.  If this isn't passed
237      *                     the error information gathered from the DBMS.
238      *
239      * @return object  the DB_Error object
240      *
241      * @see DB_common::raiseError(),
242      *      DB_msql::errorNative(), DB_msql::errorCode()
243      */
244     public function msqlRaiseError($errno = null)
245     {
246         $native = $this->errorNative();
247         if ($errno === null) {
248             $errno = $this->errorCode($native);
249         }
250         return $this->raiseError($errno, null, null, null, $native);
251     }
252
253     // }}}
254     // {{{ simpleQuery()
255
256     /**
257      * Gets the DBMS' native error message produced by the last query
258      *
259      * @return string  the DBMS' error message
260      */
261     public function errorNative()
262     {
263         return @msql_error();
264     }
265
266
267     // }}}
268     // {{{ nextResult()
269
270     /**
271      * Determines PEAR::DB error code from the database's text error message
272      *
273      * @param string $errormsg the error message returned from the database
274      *
275      * @return integer  the error number from a DB_ERROR* constant
276      */
277     public function errorCode($errormsg)
278     {
279         static $error_regexps;
280
281         // PHP 5.2+ prepends the function name to $php_errormsg, so we need
282         // this hack to work around it, per bug #9599.
283         $errormsg = preg_replace('/^msql[a-z_]+\(\): /', '', $errormsg);
284
285         if (!isset($error_regexps)) {
286             $error_regexps = array(
287                 '/^Access to database denied/i'
288                 => DB_ERROR_ACCESS_VIOLATION,
289                 '/^Bad index name/i'
290                 => DB_ERROR_ALREADY_EXISTS,
291                 '/^Bad order field/i'
292                 => DB_ERROR_SYNTAX,
293                 '/^Bad type for comparison/i'
294                 => DB_ERROR_SYNTAX,
295                 '/^Can\'t perform LIKE on/i'
296                 => DB_ERROR_SYNTAX,
297                 '/^Can\'t use TEXT fields in LIKE comparison/i'
298                 => DB_ERROR_SYNTAX,
299                 '/^Couldn\'t create temporary table/i'
300                 => DB_ERROR_CANNOT_CREATE,
301                 '/^Error creating table file/i'
302                 => DB_ERROR_CANNOT_CREATE,
303                 '/^Field .* cannot be null$/i'
304                 => DB_ERROR_CONSTRAINT_NOT_NULL,
305                 '/^Index (field|condition) .* cannot be null$/i'
306                 => DB_ERROR_SYNTAX,
307                 '/^Invalid date format/i'
308                 => DB_ERROR_INVALID_DATE,
309                 '/^Invalid time format/i'
310                 => DB_ERROR_INVALID,
311                 '/^Literal value for .* is wrong type$/i'
312                 => DB_ERROR_INVALID_NUMBER,
313                 '/^No Database Selected/i'
314                 => DB_ERROR_NODBSELECTED,
315                 '/^No value specified for field/i'
316                 => DB_ERROR_VALUE_COUNT_ON_ROW,
317                 '/^Non unique value for unique index/i'
318                 => DB_ERROR_CONSTRAINT,
319                 '/^Out of memory for temporary table/i'
320                 => DB_ERROR_CANNOT_CREATE,
321                 '/^Permission denied/i'
322                 => DB_ERROR_ACCESS_VIOLATION,
323                 '/^Reference to un-selected table/i'
324                 => DB_ERROR_SYNTAX,
325                 '/^syntax error/i'
326                 => DB_ERROR_SYNTAX,
327                 '/^Table .* exists$/i'
328                 => DB_ERROR_ALREADY_EXISTS,
329                 '/^Unknown database/i'
330                 => DB_ERROR_NOSUCHDB,
331                 '/^Unknown field/i'
332                 => DB_ERROR_NOSUCHFIELD,
333                 '/^Unknown (index|system variable)/i'
334                 => DB_ERROR_NOT_FOUND,
335                 '/^Unknown table/i'
336                 => DB_ERROR_NOSUCHTABLE,
337                 '/^Unqualified field/i'
338                 => DB_ERROR_SYNTAX,
339             );
340         }
341
342         foreach ($error_regexps as $regexp => $code) {
343             if (preg_match($regexp, $errormsg)) {
344                 return $code;
345             }
346         }
347         return DB_ERROR;
348     }
349
350     // }}}
351     // {{{ fetchInto()
352
353     /**
354      * Disconnects from the database server
355      *
356      * @return bool  TRUE on success, FALSE on failure
357      */
358     public function disconnect()
359     {
360         $ret = @msql_close($this->connection);
361         $this->connection = null;
362         return $ret;
363     }
364
365     // }}}
366     // {{{ freeResult()
367
368     /**
369      * Sends a query to the database server
370      *
371      * @param string  the SQL query string
372      *
373      * @return mixed  + a PHP result resrouce for successful SELECT queries
374      *                + the DB_OK constant for other successful queries
375      *                + a DB_Error object on failure
376      */
377     public function simpleQuery($query)
378     {
379         $this->last_query = $query;
380         $query = $this->modifyQuery($query);
381         $result = @msql_query($query, $this->connection);
382         if (!$result) {
383             return $this->msqlRaiseError();
384         }
385         // Determine which queries that should return data, and which
386         // should return an error code only.
387         if ($this->_checkManip($query)) {
388             $this->_result = $result;
389             return DB_OK;
390         } else {
391             $this->_result = false;
392             return $result;
393         }
394     }
395
396     // }}}
397     // {{{ numCols()
398
399     /**
400      * Move the internal msql result pointer to the next available result
401      *
402      * @param a valid fbsql result resource
403      *
404      * @access public
405      *
406      * @return true if a result is available otherwise return false
407      */
408     public function nextResult($result)
409     {
410         return false;
411     }
412
413     // }}}
414     // {{{ numRows()
415
416     /**
417      * Places a row from the result set into the given array
418      *
419      * Formating of the array and the data therein are configurable.
420      * See DB_result::fetchInto() for more information.
421      *
422      * This method is not meant to be called directly.  Use
423      * DB_result::fetchInto() instead.  It can't be declared "protected"
424      * because DB_result is a separate object.
425      *
426      * PHP's mSQL extension did weird things with NULL values prior to PHP
427      * 4.3.11 and 5.0.4.  Make sure your version of PHP meets or exceeds
428      * those versions.
429      *
430      * @param resource $result the query result resource
431      * @param array $arr the referenced array to put the data in
432      * @param int $fetchmode how the resulting array should be indexed
433      * @param int $rownum the row number to fetch (0 = first row)
434      *
435      * @return mixed  DB_OK on success, NULL when the end of a result set is
436      *                 reached or on failure
437      *
438      * @see DB_result::fetchInto()
439      */
440     public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
441     {
442         if ($rownum !== null) {
443             if (!@msql_data_seek($result, $rownum)) {
444                 return null;
445             }
446         }
447         if ($fetchmode & DB_FETCHMODE_ASSOC) {
448             $arr = @msql_fetch_array($result, MSQL_ASSOC);
449             if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
450                 $arr = array_change_key_case($arr, CASE_LOWER);
451             }
452         } else {
453             $arr = @msql_fetch_row($result);
454         }
455         if (!$arr) {
456             return null;
457         }
458         if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
459             $this->_rtrimArrayValues($arr);
460         }
461         if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
462             $this->_convertNullArrayValuesToEmpty($arr);
463         }
464         return DB_OK;
465     }
466
467     // }}}
468     // {{{ affected()
469
470     /**
471      * Deletes the result set and frees the memory occupied by the result set
472      *
473      * This method is not meant to be called directly.  Use
474      * DB_result::free() instead.  It can't be declared "protected"
475      * because DB_result is a separate object.
476      *
477      * @param resource $result PHP's query result resource
478      *
479      * @return bool  TRUE on success, FALSE if $result is invalid
480      *
481      * @see DB_result::free()
482      */
483     public function freeResult($result)
484     {
485         return is_resource($result) ? msql_free_result($result) : false;
486     }
487
488     // }}}
489     // {{{ nextId()
490
491     /**
492      * Gets the number of columns in a result set
493      *
494      * This method is not meant to be called directly.  Use
495      * DB_result::numCols() instead.  It can't be declared "protected"
496      * because DB_result is a separate object.
497      *
498      * @param resource $result PHP's query result resource
499      *
500      * @return int|object
501      *
502      * @see DB_result::numCols()
503      */
504     public function numCols($result)
505     {
506         $cols = @msql_num_fields($result);
507         if (!$cols) {
508             return $this->msqlRaiseError();
509         }
510         return $cols;
511     }
512
513     // }}}
514     // {{{ createSequence()
515
516     /**
517      * Gets the number of rows in a result set
518      *
519      * This method is not meant to be called directly.  Use
520      * DB_result::numRows() instead.  It can't be declared "protected"
521      * because DB_result is a separate object.
522      *
523      * @param resource $result PHP's query result resource
524      *
525      * @return int|object
526      *
527      * @see DB_result::numRows()
528      */
529     public function numRows($result)
530     {
531         $rows = @msql_num_rows($result);
532         if ($rows === false) {
533             return $this->msqlRaiseError();
534         }
535         return $rows;
536     }
537
538     // }}}
539     // {{{ dropSequence()
540
541     /**
542      * Determines the number of rows affected by a data maniuplation query
543      *
544      * 0 is returned for queries that don't manipulate data.
545      *
546      * @return int  the number of rows.  A DB_Error object on failure.
547      */
548     public function affectedRows()
549     {
550         if (!$this->_result) {
551             return 0;
552         }
553         return msql_affected_rows($this->_result);
554     }
555
556     // }}}
557     // {{{ quoteIdentifier()
558
559     /**
560      * Returns the next free id in a sequence
561      *
562      * @param string $seq_name name of the sequence
563      * @param boolean $ondemand when true, the seqence is automatically
564      *                            created if it does not exist
565      *
566      * @return int|object
567      *               A DB_Error object on failure.
568      *
569      * @see DB_common::nextID(), DB_common::getSequenceName(),
570      *      DB_msql::createSequence(), DB_msql::dropSequence()
571      */
572     public function nextId($seq_name, $ondemand = true)
573     {
574         $seqname = $this->getSequenceName($seq_name);
575         $repeat = false;
576         do {
577             $this->pushErrorHandling(PEAR_ERROR_RETURN);
578             $result = $this->query("SELECT _seq FROM ${seqname}");
579             $this->popErrorHandling();
580             if ($ondemand && DB::isError($result) &&
581                 $result->getCode() == DB_ERROR_NOSUCHTABLE) {
582                 $repeat = true;
583                 $this->pushErrorHandling(PEAR_ERROR_RETURN);
584                 $result = $this->createSequence($seq_name);
585                 $this->popErrorHandling();
586                 if (DB::isError($result)) {
587                     return $this->raiseError($result);
588                 }
589             } else {
590                 $repeat = false;
591             }
592         } while ($repeat);
593         if (DB::isError($result)) {
594             return $this->raiseError($result);
595         }
596         $arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
597         $result->free();
598         return $arr[0];
599     }
600
601     // }}}
602     // {{{ quoteFloat()
603
604     /**
605      * Creates a new sequence
606      *
607      * Also creates a new table to associate the sequence with.  Uses
608      * a separate table to ensure portability with other drivers.
609      *
610      * @param string $seq_name name of the new sequence
611      *
612      * @return int  DB_OK on success.  A DB_Error object on failure.
613      *
614      * @see DB_common::createSequence(), DB_common::getSequenceName(),
615      *      DB_msql::nextID(), DB_msql::dropSequence()
616      */
617     public function createSequence($seq_name)
618     {
619         $seqname = $this->getSequenceName($seq_name);
620         $res = $this->query('CREATE TABLE ' . $seqname
621             . ' (id INTEGER NOT NULL)');
622         if (DB::isError($res)) {
623             return $res;
624         }
625         $res = $this->query("CREATE SEQUENCE ON ${seqname}");
626         return $res;
627     }
628
629     // }}}
630     // {{{ escapeSimple()
631
632     /**
633      * Deletes a sequence
634      *
635      * @param string $seq_name name of the sequence to be deleted
636      *
637      * @return int  DB_OK on success.  A DB_Error object on failure.
638      *
639      * @see DB_common::dropSequence(), DB_common::getSequenceName(),
640      *      DB_msql::nextID(), DB_msql::createSequence()
641      */
642     public function dropSequence($seq_name)
643     {
644         return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
645     }
646
647     // }}}
648     // {{{ msqlRaiseError()
649
650     /**
651      * mSQL does not support delimited identifiers
652      *
653      * @param string $str the identifier name to be quoted
654      *
655      * @return object  a DB_Error object
656      *
657      * @see DB_common::quoteIdentifier()
658      * @since Method available since Release 1.7.0
659      */
660     public function quoteIdentifier($str)
661     {
662         return $this->raiseError(DB_ERROR_UNSUPPORTED);
663     }
664
665     // }}}
666     // {{{ errorNative()
667
668     /**
669      * Formats a float value for use within a query in a locale-independent
670      * manner.
671      *
672      * @param float the float value to be quoted.
673      * @return string the quoted string.
674      * @see DB_common::quoteSmart()
675      * @since Method available since release 1.7.8.
676      */
677     public function quoteFloat($float)
678     {
679         return $this->escapeSimple(str_replace(',', '.', strval(floatval($float))));
680     }
681
682     // }}}
683     // {{{ errorCode()
684
685     /**
686      * Escapes a string according to the current DBMS's standards
687      *
688      * @param string $str the string to be escaped
689      *
690      * @return string  the escaped string
691      *
692      * @see DB_common::quoteSmart()
693      * @since Method available since Release 1.7.0
694      */
695     public function escapeSimple($str)
696     {
697         return addslashes($str);
698     }
699
700     // }}}
701     // {{{ tableInfo()
702
703     /**
704      * Returns information about a table or a result set
705      *
706      * @param object|string $result DB_result object from a query or a
707      *                                 string containing the name of a table.
708      *                                 While this also accepts a query result
709      *                                 resource identifier, this behavior is
710      *                                 deprecated.
711      * @param int $mode a valid tableInfo mode
712      *
713      * @return array|object
714      *                 A DB_Error object on failure.
715      *
716      * @see DB_common::setOption()
717      */
718     public function tableInfo($result, $mode = null)
719     {
720         if (is_string($result)) {
721             /*
722              * Probably received a table name.
723              * Create a result resource identifier.
724              */
725             $id = @msql_query(
726                 "SELECT * FROM $result",
727                 $this->connection
728             );
729             $got_string = true;
730         } elseif (isset($result->result)) {
731             /*
732              * Probably received a result object.
733              * Extract the result resource identifier.
734              */
735             $id = $result->result;
736             $got_string = false;
737         } else {
738             /*
739              * Probably received a result resource identifier.
740              * Copy it.
741              * Deprecated.  Here for compatibility only.
742              */
743             $id = $result;
744             $got_string = false;
745         }
746
747         if (!is_resource($id)) {
748             return $this->raiseError(DB_ERROR_NEED_MORE_DATA);
749         }
750
751         if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
752             $case_func = 'strtolower';
753         } else {
754             $case_func = 'strval';
755         }
756
757         $count = @msql_num_fields($id);
758         $res = array();
759
760         if ($mode) {
761             $res['num_fields'] = $count;
762         }
763
764         for ($i = 0; $i < $count; $i++) {
765             $tmp = @msql_fetch_field($id);
766
767             $flags = '';
768             if ($tmp->not_null) {
769                 $flags .= 'not_null ';
770             }
771             if ($tmp->unique) {
772                 $flags .= 'unique_key ';
773             }
774             $flags = trim($flags);
775
776             $res[$i] = array(
777                 'table' => $case_func($tmp->table),
778                 'name' => $case_func($tmp->name),
779                 'type' => $tmp->type,
780                 'len' => msql_field_len($id, $i),
781                 'flags' => $flags,
782             );
783
784             if ($mode & DB_TABLEINFO_ORDER) {
785                 $res['order'][$res[$i]['name']] = $i;
786             }
787             if ($mode & DB_TABLEINFO_ORDERTABLE) {
788                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
789             }
790         }
791
792         // free the result only if we were called on a table
793         if ($got_string) {
794             @msql_free_result($id);
795         }
796         return $res;
797     }
798
799     // }}}
800     // {{{ getSpecialQuery()
801
802     /**
803      * Obtain a list of a given type of objects
804      *
805      * @param string $type the kind of objects you want to retrieve
806      *
807      * @return array|object
808      *
809      * @access protected
810      * @see DB_common::getListOf()
811      */
812     public function getSpecialQuery($type)
813     {
814         switch ($type) {
815             case 'databases':
816                 $id = @msql_list_dbs($this->connection);
817                 break;
818             case 'tables':
819                 $id = @msql_list_tables(
820                     $this->dsn['database'],
821                     $this->connection
822                 );
823                 break;
824             default:
825                 return null;
826         }
827         if (!$id) {
828             return $this->msqlRaiseError();
829         }
830         $out = array();
831         while ($row = @msql_fetch_row($id)) {
832             $out[] = $row[0];
833         }
834         return $out;
835     }
836
837     // }}}
838 }
839
840 /*
841  * Local variables:
842  * tab-width: 4
843  * c-basic-offset: 4
844  * End:
845  */