root/cherokee/trunk/dbslayer/mysql_wrap.php

Revision 4141, 33.0 kB (checked in by alo, 2 months ago)

New year, new copyright notice: 's/2009/2010/g'.

Line 
1 <?
2 /* Cherokee's DBSlayer Wrapper for MySQL built-in functions
3  *
4  * Authors:
5  *      Taher Shihadeh <taher@unixwars.com>
6  *
7  * Copyright (C) 2001-2010 Alvaro Lopez Ortega <alvaro@alobbs.com>
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * * Redistributions of source code must retain the above copyright
15  *   notice, this list of conditions and the following disclaimer.
16  * * Redistributions in binary form must reproduce the above copyright
17  *   notice, this list of conditions and the following disclaimer in
18  *   the documentation and/or other materials provided with the
19  *   distribution.
20  * * The name "Alvaro Lopez Ortega" may not be used to endorse or
21  *   promote products derived from this software without specific prior
22  *   written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28  * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37
38 /* NOTE:
39  *
40  * To override the mysql_* builtin functions, you need to provide
41  * phpize (php5-dev) and: `pecl install apd`.
42  *
43  * If you do not, you can still use the wrapper initializing it with a
44  * FALSE value as optional second parameter: cherokee_init($host, FALSE)
45  *
46  * runkit_function_redefine could be another approach. Remains to be seen.
47  *
48  */
49
50 define("DEFAULT_ERRNO", 3000);
51 define("DEFAULT_ERROR", "DBSlayer: undefined MySQL error");
52 define("SERVER_INFO",   "Cherokee DBSlayer MySQL bridge");
53 define("CLIENT_INFO",   "DBSlayer MySQL Wrapper v1.0");
54 define("DEFAULT_LINK""DBSLAYER_LINK");
55 define("DEFAULT_HOST""http://localhost:8888");
56
57 $_dbslayer = NULL;
58
59 function cherokee_init ($host, $map = TRUE)
60 {
61     global $_dbslayer;
62
63     $curl = curl_init();
64     if (!$curl)
65        throw new Exception("DBSlayer MySQL Wrapper could not be created.");
66
67     $_dbslayer = array (
68            'db_host' => ($host) ? $host : ini_get('mysql.default_host'),
69            'db_user' => ini_get('mysql.default_user'),
70            'db_pass' => ini_get('mysql.default_password'),
71            'db_link' => DEFAULT_LINK,
72            'db_name' => NULL,
73            'encoding'=> ini_get('mysql.character_set'),
74            'curl'    => $curl,
75            'success' => NULL,
76            'errno'   => NULL,
77            'error'   => NULL,
78            'insert_id'=> 0,
79            'affected_rows'=> 0);
80
81     if ($map == TRUE)
82        return _dbslayer_map();
83     return TRUE;
84 }
85
86 /* Debug */
87 function _dbslayer_print()
88 {
89     global $_dbslayer;
90         echo 'db_host: '. $_dbslayer['db_host']."\n";
91         echo 'db_user: '. $_dbslayer['db_user']."\n";
92         echo 'db_pass: '. $_dbslayer['db_pass']."\n";
93         echo 'db_link: '. $_dbslayer['db_link']."\n";
94         echo 'db_name: '. $_dbslayer['db_name']."\n";
95         echo 'success: '. $_dbslayer['success']."\n";
96         echo 'errno: '. $_dbslayer['errno']."\n";
97         echo 'error: '. $_dbslayer['error']."\n";
98         echo 'insert_id: '. $_dbslayer['insert_id']."\n";
99         echo 'affected_rows: '. $_dbslayer['affected_rows']."\n";
100 }
101
102 /* Transparently use DBSLAYER when approriate
103  */
104 function _dbslayer_map()
105 {
106     $substs = array(
107         'is_resource'        => 'cherokee_is_resource($link)',
108         'mysql_affected_rows'    => 'cherokee_mysql_affected_rows($link)',
109         'mysql_client_encoding'    => 'cherokee_mysql_client_encoding ($link)',
110         'mysql_close'        => 'cherokee_mysql_close($link)',
111         'mysql_connect'            => 'cherokee_mysql_connect($host, $user, $pass, $new_link, $client_flags)',
112         'mysql_create_db'        => 'cherokee_mysql_create_db($database_name, $link)',
113         'mysql_data_seek'         => 'cherokee_mysql_data_seek($result, $row_number)',
114         'mysql_db_name'        => 'cherokee_mysql_db_name($result, $row, $field)',
115         'mysql_db_query'        => 'cherokee_mysql_db_query($database, $query, $link)',
116         'mysql_drop_db'        => 'cherokee_mysql_drop_db($database_name, $link)',
117         'mysql_errno'         => 'cherokee_mysql_errno($link)',
118         'mysql_error'         => 'cherokee_mysql_error($link)',
119         'mysql_escape_string'    => 'cherokee_mysql_escape_string($unescaped_string)',
120         'mysql_fetch_array'     => 'cherokee_mysql_fetch_array($result, $result_type)',
121         'mysql_fetch_assoc'     => 'cherokee_mysql_fetch_assoc($result)',
122         'mysql_fetch_field'     => 'cherokee_mysql_fetch_field($result, $field_offset)',
123         'mysql_fetch_lengths'    => 'cherokee_mysql_fetch_lengths($result)',
124         'mysql_fetch_num'        => 'cherokee_mysql_fetch_num($result)',
125         'mysql_fetch_object'    => 'cherokee_mysql_fetch_object (&$result, $class_name, $params)',
126         'mysql_field_flags'        => 'cherokee_mysql_field_flags ($result, $field_offset)',
127         'mysql_field_name'        => 'cherokee_mysql_field_name ($result, $field_offset)',
128         'mysql_field_seek'        => 'cherokee_mysql_field_seek (&$result, $field_offset)',
129         'mysql_field_type'        => 'cherokee_mysql_field_type ($result, $field_offset)',
130         'mysql_free_result'     => 'cherokee_mysql_free_result($result)',
131         'mysql_get_client_info'       => 'cherokee_mysql_get_client_info()',
132         'mysql_get_host_info'    => 'cherokee_mysql_get_host_info ($link)',
133         'mysql_get_proto_info'    => 'cherokee_mysql_get_proto_info ($link)',
134         'mysql_get_server_info'       => 'cherokee_mysql_get_server_info($link)',
135         'mysql_info'        => 'cherokee_mysql_info ($link)',
136         'mysql_insert_id'        => 'cherokee_mysql_insert_id($link)',
137         'mysql_list_dbs'         => 'cherokee_mysql_list_dbs($link)',
138         'mysql_list_fields'        => 'cherokee_mysql_list_fields ($database, $table_name, $link)',
139         'mysql_list_processes'    => 'cherokee_mysql_list_processes ($link)',
140         'mysql_list_tables'        => 'cherokee_mysql_list_tables  ($database, $link)',
141         'mysql_num_fields'        => 'cherokee_mysql_num_fields ($result)',
142         'mysql_num_rows'            => 'cherokee_mysql_num_rows($result)',
143         'mysql_pconnect'            => 'cherokee_mysql_pconnect($host, $user, $pass, $client_flags)',
144         'mysql_ping'        => 'cherokee_mysql_ping ($link)',
145         'mysql_query'            => 'cherokee_mysql_query($query, $link)',
146         'mysql_real_escape_string'    => 'cherokee_mysql_real_escape_string($unescaped_string, $link)',
147         'mysql_result'         => 'cherokee_mysql_result($result, $row, $field)',
148         'mysql_select_db'        => 'cherokee_mysql_select_db($database_name, &$link)',
149         'mysql_set_charset'        => 'cherokee_mysql_set_charset($charset, $link)',
150         'mysql_stat'        => 'cherokee_mysql_stat($link)',
151         'mysql_tablename'         => 'cherokee_mysql_tablename($result, $i)',
152         'mysql_thread_id'        => 'cherokee_mysql_thread_id ($link)',
153         'mysql_unbuffered_query'    => 'cherokee_mysql_unbuffered_query($query, $link)',
154             );
155
156     $args = array(
157             'is_resource'        => '$link',
158         'mysql_affected_rows'    => '$link = NULL',
159         'mysql_client_encoding'    => '$link = NULL',
160             'mysql_close'        => '$link = NULL',
161         'mysql_connect'            => '$host = NULL, $user = NULL, $pass = NULL, $new_link = false, $client_flags = 0',
162         'mysql_create_db'        => '$database_name, $link = NULL',
163         'mysql_data_seek'         => '&$result, $row_number',
164         'mysql_db_name'        => '$result, $row, $field = NULL',
165         'mysql_db_query'        => '$database, $query, $link = NULL',
166         'mysql_drop_db'        => '$database_name, $link = NULL',
167         'mysql_errno'         => '$link = NULL',
168         'mysql_error'         => '$link = NULL',
169         'mysql_escape_string'    => '$unescaped_string',
170         'mysql_fetch_array'     => '&$result, $result_type = MYSQL_BOTH',
171         'mysql_fetch_assoc'     => '&$result',
172         'mysql_fetch_field'     => '&$result, $field_offset = -1',
173         'mysql_fetch_lengths'    => '$result',
174         'mysql_fetch_num'        => '&$result',
175         'mysql_fetch_object'    => '&$result, $class_name = "stdClass", $params = NULL',
176         'mysql_field_flags'        => '$result, $field_offset',
177         'mysql_field_name'        => '$result, $field_offset',
178         'mysql_field_seek'        => '&$result, $field_offset',
179         'mysql_field_type'        => '$result, $field_offset',
180         'mysql_free_result'     => '&$result',
181         'mysql_get_client_info'       => '',
182         'mysql_get_host_info'    => '$link = NULL',
183         'mysql_get_proto_info'    => '$link = NULL',
184         'mysql_get_server_info'       => '$link = NULL',
185         'mysql_info'        => '$link = NULL',
186         'mysql_insert_id'        => '$link = NULL',
187         'mysql_list_dbs'        => '$link = NULL',
188         'mysql_list_fields'        => '$database, $table_name, $link = NULL',
189         'mysql_list_processes'    => '$link = NULL',
190         'mysql_list_tables'        => '$database, $link = NULL',
191         'mysql_num_fields'        => '$result',
192         'mysql_num_rows'            => '$result',
193         'mysql_pconnect'            => '$host = NULL, $user = NULL, $pass = NULL, $client_flags = 0',
194         'mysql_ping'        => '$link = NULL',
195         'mysql_query'            => '$query, $link = NULL',
196         'mysql_real_escape_string'    => '$unescaped_string, $link = NULL',
197         'mysql_result'         => '&$result, $row, $field = 0',
198         'mysql_select_db'        => '$database_name, $link = NULL',
199         'mysql_set_charset'        => '$charset , $link = NULL',
200         'mysql_stat'        => '$link = NULL',
201         'mysql_tablename'        => '$result, $i',
202         'mysql_thread_id'        => '$link = NULL',
203         'mysql_unbuffered_query'    => '$query, $link = NULL',
204             );
205
206     foreach ($substs as $func => $ren_func) {
207         $ret  = override_function($func, $args[$func], "return $substs[$func];");
208               $ret &= rename_function("__overridden__", "_$ren_func");
209         if ($ret == FALSE) return FALSE;
210       }
211
212     return TRUE;
213 }
214
215
216 /* Wrap DEFAULT_LINK checks and assignations */
217 function _dbslayer(&$link)
218 {
219     global $_dbslayer;
220     if ($link == NULL)
221        $link = $_dbslayer;
222
223     if (isset($link['db_link']) && $link['db_link'] == DEFAULT_LINK)
224        return TRUE;
225     return FALSE;
226 }
227
228
229 /* Delete NULL parameters before calling the wrapped functions */
230 function _call()
231 {
232     $args_in  = func_get_args();
233     $args_num = func_num_args();
234     $args_out = array();
235     $func      = $args_in[0];
236
237     for ($i=1; $i < $args_num ; $i++) {
238         if ($args_in[$i])
239            array_push($args_out, $args_in[$i]);
240     }
241     return call_user_func_array($func, $args_out);
242 }
243
244
245 /* Check if it is a DBSlayer result */
246 function _is_result($result)
247 {
248     if (isset($result["_dbslayer"]))
249        return TRUE;
250     return FALSE;
251 }
252
253
254 /* Fetch the RESULT entry */
255 function & _get_result (&$result)
256 {
257     if (!_is_result($result))
258        return NULL;
259
260     $idx = $result["_dbslayer"]["_idxres"];
261     $tmp = &$result[$idx]["RESULT"];
262     return $tmp;
263 }
264
265 /* Fetch the ROWS entry */
266 function & _get_rows (&$result)
267 {
268     if (!_is_result($result))
269        return NULL;
270
271     $idx = $result["_dbslayer"]["_idxres"];
272     $tmp = &$result[$idx]["RESULT"]["ROWS"];
273     return $tmp;
274 }
275
276
277 /* Fetch the HEADER entry */
278 function & _get_header (&$result)
279 {
280     if (!_is_result($result))
281        return NULL;
282
283     $idx = $result["_dbslayer"]["_idxres"];
284     $tmp = &$result[$idx]["RESULT"]["HEADER"];
285     return $tmp;
286 }
287
288 /* Fetch the [_dbslayer] private parameters */
289 function & _get_params (&$result)
290 {
291     if (!_is_result($result))
292        return NULL;
293
294     $tmp  = &$result["_dbslayer"];
295     return $tmp;
296 }
297
298
299 /**********************************************************************
300  * Wrapped functions from now on
301  **********************************************************************/
302
303
304 /* is_resource - Finds whether a variable is a resource */
305 function cherokee_is_resource ($link)
306 {
307     if (_dbslayer($link))
308        return TRUE;
309
310     return _is_resource($link);
311 }
312
313
314 /* mysql_affected_rows - Get number of affected rows in previous MySQL operation */
315 function cherokee_mysql_affected_rows ($link = NULL)
316 {
317     if (!_dbslayer($link)) {
318        return _call('_mysql_affected_rows', $link);
319     }
320
321     return $link['affected_rows'];
322 }
323
324
325 /* mysql_client_encoding - Returns the name of the character set */
326 function cherokee_mysql_client_encoding ($link = NULL)
327 {
328     if (!_dbslayer($link)) {
329        return _call('_mysql_client_encoding', $link);
330     }
331
332     $query  = "SHOW VARIABLES WHERE Variable_name='character_set_connection';";
333     $result = cherokee_mysql_query($query, $link);
334     $result = cherokee_mysql_fetch_array($result);
335     return $result['Value'];
336 }
337
338
339 /* mysql_close - Close MySQL connection */
340 function cherokee_mysql_close ($link = NULL)
341 {
342     if (!_dbslayer($link)) {
343        return _call('_mysql_close', $link);
344     }
345
346     return TRUE;
347 }
348
349
350 /* mysql_connect - Open a connection to a MySQL Server */
351 function cherokee_mysql_connect ($host = NULL, $user = NULL,
352                          $pass = NULL, $new_link = false,
353                     $client_flags = 0)
354 {
355     global $_dbslayer;
356     $host = ($host) ? $host:$_dbslayer['db_host'];
357
358     if ($host != $_dbslayer['db_host'])
359        return _mysql_connect($host, $user, $pass, $new_link, $client_flags);
360
361     return cherokee_mysql_pconnect ($host, $user, $pass, $client_flags);
362 }
363
364
365 /* mysql_create_db - Create a MySQL database */
366 function cherokee_mysql_create_db ($database_name, $link = NULL)
367 {
368     if (!_dbslayer($link)) {
369        return _call('_mysql_create_db', $database_name, $link);
370     }
371
372     $query = "CREATE DATABASE $database_name";
373     $result = cherokee_mysql_query($query, $link);
374     return $result;
375 }
376
377
378 /* mysql_data_seek - Move internal result pointer */
379 function cherokee_mysql_data_seek  (&$result, $row_number)
380 {
381     if (!_is_result($result))
382        return _mysql_data_seek ($result, $row_number);
383
384     if ($row_number >= $result["_dbslayer"]["_rows"])
385        return FALSE;
386
387     $result["_dbslayer"]["_idxrow"] = $row_number;
388     return TRUE;
389 }
390
391
392 /* mysql_db_query - Send a MySQL query (and select a database). Deprecated */
393 function cherokee_mysql_db_query ($database, $query, $link = NULL)
394 {
395     if (!_dbslayer($link)) {
396        return _call('_mysql_db_query', $database, $query, $link);
397     }
398
399     cherokee_mysql_select_db($database);
400     return cherokee_mysql_query($query, $link);
401 }
402
403
404 /* mysql_db_name - Get result data */
405 /* Deprecated alias: mysql_dbname */
406 function cherokee_mysql_db_name ($result, $row, $field = NULL)
407 {
408     if (!_is_result($result))
409        return _mysql_db_name ($result, $row, $field);
410
411     // I have no idea what $field is used for
412
413     $tmp = _get_rows($result);
414
415     if (isset($tmp[$row][0]))
416        return $tmp[$row][0];
417     return FALSE;   
418 }
419
420
421 /* mysql_drop_db - Drop (delete) a MySQL database */
422 /* Deprecated alias: mysql_dropdb */
423 function cherokee_mysql_drop_db ($database_name, $link = NULL)
424 {
425     if (!_dbslayer($link)) {
426        return _call('_mysql_drop_db', $database_name, $link);
427     }
428
429     $query = "DROP  $database_name";
430     $result = cherokee_mysql_query($query, $link);
431     return $result;
432 }
433
434
435 /* mysql_errno - Returns the numerical value of the error message from previous MySQL operation */
436 function cherokee_mysql_errno ($link = NULL)
437 {
438     if (!_dbslayer($link)) {
439        return _call('_mysql_errno', $link);
440     }
441
442     return $link['errno'];
443 }   
444
445
446 /* mysql_error - Returns the text of the error message from previous MySQL operation */
447 function cherokee_mysql_error ($link = NULL)
448 {
449     if (!_dbslayer($link)) {
450        return _call('_mysql_error', $link);
451     }
452
453     return $link['error'];
454 }
455
456
457 /* mysql_fetch_array - Fetch a result row as an associative array, a numeric array, or both */
458 function cherokee_mysql_fetch_array  (&$result, $result_type = MYSQL_BOTH)
459 {
460     if (!_is_result($result))
461        return _mysql_fetch_array (&$result, $result_type);
462
463     // No RESULT field present
464     if ($result["_dbslayer"]["_idxres"] < 0)
465        return FALSE;
466
467     $idx = $result["_dbslayer"]["_idxres"];
468     $tmp = &$result[$idx];
469     // reset internal index
470     if ($result["_dbslayer"]["_idxrow"] >= $result["_dbslayer"]["_rows"]) {
471        $result["_dbslayer"]["_last_access"] = -1;
472        $result["_dbslayer"]["_idxrow"] = 0;
473        return FALSE;
474     }
475
476     $idx = $result["_dbslayer"]["_idxrow"];
477     $result["_dbslayer"]["_last_access"] = $result["_dbslayer"]["_idxrow"];
478     $result["_dbslayer"]["_idxrow"]++;
479
480     $num = $tmp["RESULT"]["ROWS"][$idx];
481     if ($result_type == MYSQL_NUM) {
482        return $num;
483     }
484
485     $keys = $tmp["RESULT"]["HEADER"];
486     $vals = $tmp["RESULT"]["ROWS"][$idx];
487
488     $assoc = array_combine($keys, $vals);
489     if ($result_type == MYSQL_ASSOC) {
490        return $assoc;
491     }
492     return array_merge($num, $assoc);
493 }
494
495
496 /* mysql_fetch_assoc - Fetch a result row as an associative array */
497 function cherokee_mysql_fetch_assoc (&$result)
498 {
499     return cherokee_mysql_fetch_array(&$result, MYSQL_ASSOC);
500 }
501
502
503 /* PARTIAL: mysql_fetch_field - Get column information from a result and return as an object */
504 function cherokee_mysql_fetch_field (&$result, $field_offset = -1)
505 {
506     if (!_is_result($result)) {
507        if ($field_offset == -1)
508           return _mysql_fetch_field ($result);
509        return _mysql_fetch_field ($result, $field_offset);
510     }
511
512     if ($field_offset == -1) {
513        $field_offset = $result["_dbslayer"][_field_offset]+1;
514     }
515
516     $obj = _get_result($result);
517     $fo = $field_offset;
518     if ($fo >= count($obj["HEADER"])) {
519        $result["_dbslayer"][_field_offset] = 0;
520        return NULL;
521     }
522
523     $meta = new Mysql_fetch_field_object();
524     $meta->name          = $obj["HEADER"][$fo];
525     $meta->type          = $obj["TYPES"][$fo];
526     $meta->blob          = 0; // 1 if the column is a BLOB
527     $meta->numeric       = 0; // 1 if the column is numeric
528
529     /* Many $meta-> fields remain UNIMPLEMENTED
530     $meta->table         = $obj[""][$fo]; // name of the table the column belongs to
531     $meta->def           = $obj[""][$fo]; // default value of the column
532     $meta->max_length    = $obj[""][$fo]; // maximum length of the column
533     $meta->not_null      = $obj[""][$fo]; // 1 if the column cannot be NULL
534     $meta->primary_key   = $obj[""][$fo]; // 1 if the column is a primary key
535     $meta->unique_key    = $obj[""][$fo]; // 1 if the column is a unique key
536     $meta->multiple_key  = $obj[""][$fo]; // 1 if the column is a non-unique key
537     $meta->unsigned      = $obj[""][$fo]; // 1 if the column is unsigned
538     $meta->zerofill      = $obj[""][$fo]; // 1 if the column is zero-filled
539     */
540
541     switch ($obj["TYPES"][$fo]) {
542            case MYSQL_TYPE_BLOB:
543            case MYSQL_TYPE_TINY_BLOB:
544            case MYSQL_TYPE_MEDIUM_BLOB:
545            case MYSQL_TYPE_LONG_BLOB:               
546                    $meta->blob = 1;
547             break;
548
549            case MYSQL_TYPE_TINY:
550            case MYSQL_TYPE_SHORT:
551            case MYSQL_TYPE_LONG:
552            case MYSQL_TYPE_INT24:
553            case MYSQL_TYPE_DECIMAL:
554            case MYSQL_TYPE_NEWDECIMAL:
555            case MYSQL_TYPE_DOUBLE:
556            case MYSQL_TYPE_FLOAT:
557            case MYSQL_TYPE_LONGLONG:
558                    $meta->numeric = 1;
559
560     }
561     $result["_dbslayer"][_field_offset]++;
562     return $meta;
563 }
564
565
566 /* mysql_fetch_lengths - Get the length of each output in a result */
567 function cherokee_mysql_fetch_lengths ($result)
568 {
569     if (!_is_result($result))
570        return _mysql_fetch_lengths ($result);
571
572     $idx_last = $result["_dbslayer"]["_last_access"];
573     if ($idx_last <0)
574        return FALSE;
575
576     $rows    = _get_rows($result);
577     $num     = $rows[$idx_last];
578     $lengths = array();
579
580     foreach ($num as $field) {
581        array_push ($lengths, strlen($field));
582     }
583     return $lengths;
584 }
585
586
587 /* mysql_fetch_object - Fetch a result row as an object */
588 function cherokee_mysql_fetch_object (&$result, $class_name = 'stdClass', $params = NULL)
589 {
590     if (!_is_result($result)) {
591        return _call('_mysql_fetch_object', $result, $class_name, $params);
592     }
593
594     $obj = array();
595     $row = cherokee_mysql_fetch_assoc (&$result);
596     if (!$row)
597        return FALSE;
598
599     foreach ($row as $key=>$value) {
600         $obj[$key] = $value;
601     }
602
603     $obj = (object) $obj;
604     return $obj;
605 }
606
607
608 /* mysql_fetch_row - Get a result row as an enumerated array */
609 function cherokee_mysql_fetch_row (&$result)
610 {
611     return cherokee_mysql_fetch_array(&$result, MYSQL_NUM);
612 }
613
614
615 /* PARTIAL: mysql_field_flags - Get the flags associated with the specified field in a result */
616 /* Deprecated alias: mysql_fieldflags */
617 function cherokee_mysql_field_flags ($result, $field_offset)
618 {
619     if (!_is_result($result)) {
620        return _call('_mysql_field_flags', $result, $field_offset);
621     }
622
623     $field_num = count(_get_header($result));
624     if ($field_offset < 0 || $field_offset >= $field_num) {
625        trigger_error('field_offset does not exist', E_WARNING);
626        return FALSE;
627     }
628
629     // The rest of the functionality cannot currently be
630     // implemented. So fail:
631     throw new Exception("cherokee_mysql_field_flags not functional!");
632 }
633
634
635 /* UNIMPLEMENTED: mysql_field_len - Returns the length of the specified field */
636 function cherokee_mysql_field_len ($result, $field_offset) {}
637
638
639 /* mysql_field_name - Get the name of the specified field in a result */
640 /* Deprecated alias: mysql_fieldname */
641 function cherokee_mysql_field_name ($result, $field_offset) {
642     if (!_is_result($result)) {
643        return _call('_mysql_field_name', $result, $field_offset);
644     }
645
646     $header = _get_header($result);
647     $field_num = count($header);
648     if ($field_offset < 0 || $field_offset >= $field_num) {
649        trigger_error('field_offset does not exist', E_WARNING);
650        return FALSE;
651     }
652
653     return $header[$field_offset];
654 }
655
656
657 /* mysql_field_seek - Set result pointer to a specified field offset */
658 function cherokee_mysql_field_seek (&$result, $field_offset)
659 {
660     if (!_is_result($result)) {
661        return _call('_mysql_field_seek', $result, $field_offset);
662     }
663
664     $params = _get_params($result);
665     $field_num = $params["_fields"];
666
667     if ($field_offset < 0 || $field_offset >= $field_num) {
668        trigger_error('field_offset does not exist', E_WARNING);
669        return FALSE;
670     }
671
672     $result['_dbslayer']['_field_offset'] = $field_offset;
673     return TRUE;
674 }
675
676
677 /* UNIMPLEMENTED: mysql_field_table - Get name of the table the specified field is in */
678 function cherokee_mysql_field_table ($result, $field_offset) {}
679
680
681 /* mysql_field_type - Get the type of the specified field in a result */
682 function cherokee_mysql_field_type ($result, $field_offset)
683 {
684     if (!_is_result($result)) {
685        return _call('_mysql_field_type', $result, $field_offset);
686     }
687
688     $res = _get_result($result);
689     $tmp = $res['TYPES'];
690     $field_num = count($tmp);
691     if ($field_offset < 0 || $field_offset >= $field_num) {
692        trigger_error('field_offset does not exist', E_WARNING);
693        return FALSE;
694     }
695
696     return $tmp[$field_offset];
697 }
698
699
700 /* mysql_free_result - Free result memory */
701 function cherokee_mysql_free_result (&$result)
702 {
703     if (!_is_result($result))
704        return _mysql_free_result ($result);
705     return TRUE;
706 }
707
708
709 /* mysql_get_client_info - Get MySQL client info */
710 function cherokee_mysql_get_client_info ()
711 {
712     $info = _mysql_get_client_info();
713     return $info . ' ' . CLIENT_INFO;
714 }
715
716
717 /* mysql_get_host_info - Get MySQL host info */
718 function cherokee_mysql_get_host_info ($link = NULL)
719 {
720     if (!_dbslayer($link)) {
721        return _call('_mysql_get_host_info', $link);
722     }
723
724     $info = $link['db_host'] . 'via HTTP';
725     return $info;
726 }
727
728
729 /* mysql_get_proto_info - Get MySQL protocol info */
730 function cherokee_mysql_get_proto_info ($link = NULL)
731 {
732     if (_dbslayer($link))
733        $link = NULL;
734     return _call('_mysql_get_proto_info', $link);
735 }
736
737
738 /* mysql_get_server_info - Get MySQL server info */
739 function cherokee_mysql_get_server_info ($link = NULL)
740 {
741     if (!_dbslayer($link)) {
742        return _call('_mysql_get_server_info', $link);
743     }
744     
745     return SERVER_INFO;
746 }
747
748
749 /* UNIMPLEMENTED: mysql_info - Get information about the most recent query */
750 function cherokee_mysql_info ($link = NULL)
751 {
752     if (!_dbslayer($link)) {
753        return _call('_mysql_info', $link);
754     }
755 }
756
757
758 /* mysql_insert_id - Get the ID generated from the previous INSERT operation */
759 function cherokee_mysql_insert_id ($link = NULL)
760 {
761     if (!_dbslayer($link)) {
762        return _call('_mysql_insert_id', $link);
763     }
764
765     if ($link['success'] != FALSE)
766        return $link['insert_id'];
767     return FALSE;
768 }
769
770
771 /* mysql_list_dbs - List databases available on a MySQL server */
772 /* Deprecated alias: mysql_listdbs */
773 function cherokee_mysql_list_dbs ($link = NULL)
774 {
775     if (!_dbslayer($link)) {
776        return _call('_mysql_list_dbs', $link);
777     }
778
779     $query = "SHOW DATABASES;";
780     $result = cherokee_mysql_query($query, $link);
781
782     if ($link['success'])
783        return $result;
784     return FALSE;
785 }
786
787
788 /* mysql_list_fields - List MySQL table fields */
789 /* Deprecated alias: mysql_listfields */
790 function cherokee_mysql_list_fields ($database, $table_name, $link = NULL)
791 {
792     if (!_dbslayer($link)) {
793        return _call('_mysql_list_fields', $database_name, $table_name, $link);
794     }
795
796     cherokee_mysql_select_db($database);
797     $query = "SHOW COLUMNS FROM $table_name";
798     $result = cherokee_mysql_query($query, $link);
799     $result['_dbslayer']['_generator'] = 'list_fields';
800
801     return $result;
802     // to use with: cherokee_mysql_field_flags(), cherokee_mysql_field_len(),
803     //          cherokee_mysql_field_name(),  cherokee_mysql_field_type()
804 }
805
806
807 /* mysql_list_processes - List MySQL processes */
808 function cherokee_mysql_list_processes ($link = NULL) {
809     if (!_dbslayer($link)) {
810        return _call('_mysql_list_fields', $database_name, $table_name, $link);
811     }
812
813     cherokee_mysql_select_db($database);
814     $query = "SHOW PROCESSLIST";
815     $result = cherokee_mysql_query($query, $link);
816
817     $params = _get_params($result);
818
819     if ($params['_idxres'] < 0)
820           return FALSE;
821
822     return $result;
823 }
824
825
826 /* mysql_list_tables - List tables in a MySQL database */
827 function cherokee_mysql_list_tables  ($database, $link = NULL)
828 {
829     if (!_dbslayer($link)) {
830        return _call('_mysql_list_tables', $database, $link);
831     }
832
833     $query = "SHOW TABLES FROM $database";
834     $result = cherokee_mysql_query($query, $link);
835     $result['_dbslayer']['_generator'] = 'list_tables';
836
837     return $result;
838     // to use with: cherokee_mysql_tablename()
839 }
840
841
842 /* mysql_num_fields - Get number of fields in result */
843 function cherokee_mysql_num_fields ($result)
844 {
845     if (!_is_result($result))
846        return _mysql_num_fields ($result);
847
848     if (!isset($result["_dbslayer"]["_fields"]))
849        return FALSE;
850
851     return $result["_dbslayer"]["_fields"];
852 }
853
854
855 /* mysql_num_rows - Get number of rows in result */
856 function cherokee_mysql_num_rows ($result)
857 {
858     if (!_is_result($result))
859        return _mysql_num_rows ($result);
860     if (!isset($result["_dbslayer"]["_rows"]))
861        return FALSE;
862     return $result["_dbslayer"]["_rows"];
863 }
864
865
866 /* mysql_ping - Ping a server connection  */
867 function cherokee_mysql_ping ($link = NULL)
868 {
869     if (!_dbslayer($link)) {
870        return _call('_mysql_ping', $link);
871     }
872
873     $proc = cherokee_mysql_list_processe($link);
874     if ($proc)
875        return TRUE;
876
877     return FALSE;
878 }
879
880
881 /* mysql_pconnect - Open a persistent connection to a MySQL server */
882 function &cherokee_mysql_pconnect ($host = NULL, $user = NULL,
883                  $pass = NULL, $client_flags = 0)
884 {
885     global $_dbslayer;
886
887     $host = ($host) ? $host:$_dbslayer['db_host'];
888         $user = ($user) ? $user:$_dbslayer['db_user'];
889         $pass = ($pass) ? $pass:$_dbslayer['db_pass'];
890
891     if ($host != $_dbslayer['db_host'])
892        return _mysql_pconnect($host, $user, $pass, $client_flags);
893
894     $_dbslayer['db_host'] = $host;
895         $_dbslayer['db_user'] = $user;
896         $_dbslayer['db_pass'] = $pass;
897
898     return $_dbslayer;
899 }
900
901
902 /* mysql_query - Send a MySQL query */
903 function cherokee_mysql_query ($query, $link = NULL)
904 {
905     if (!_dbslayer($link)) {
906        return _call('_mysql_query', $query, $link);
907     }
908
909     global $_dbslayer;
910
911     if ($_dbslayer['db_name'])
912        $query = "use " . $_dbslayer['db_name'] . "; " . $query;
913
914     $url = $_dbslayer['db_host'] . "/" . rawurlencode($query);
915     if (!curl_setopt ($_dbslayer['curl'], CURLOPT_URL, $url)||
916         !curl_setopt ($_dbslayer['curl'], CURLOPT_RETURNTRANSFER, 1)) {
917        $err = "cannot set cURL CURLOPT_URL to " . $_dbslayer['db_host'].":" .
918               curl_error() . "(" . curl_errno() . ")";
919        throw new Exception($err);
920     }
921
922     $result = curl_exec ($_dbslayer['curl']);
923     if (!$result) {
924        $err = "curl_exec() failed for url " . $_dbslayer['db_host'] . ":" .
925               curl_error() . "(" . curl_errno() . ")";
926        throw new Exception($err);
927     }
928
929     eval("\$obj = $result;");
930
931     $dbs = array(
932         "_idxres" => count($obj) - 1, // points to the result field
933         "_idxrow" => 0,                     // row pointer
934         "_field_offset" => 0,         // field_offset for mysql_fetch_field
935         "_last_access" => -1,          // last accessed row
936         "_generator"   => 'query');   // mysql originating function
937     $obj["_dbslayer"] = $dbs;
938     $_dbslayer['success'] = TRUE;
939
940     // Map results or errors
941     do {
942        $idx = $obj["_dbslayer"]["_idxres"];
943        $tmp = $obj[$idx];
944
945        if (isset($tmp["RESULT"])){
946           $obj["_dbslayer"]["_rows"]   = count ($tmp["RESULT"]["ROWS"]);
947           $obj["_dbslayer"]["_fields"] = count ($tmp["RESULT"]["HEADER"]);
948           return $obj;
949        }
950
951        if (isset($tmp["SUCCESS"]) && $tmp["SUCCESS"] == 0) {
952           $_dbslayer['success'] = FALSE;
953           $_dbslayer['errno'] = $tmp["MYSQL_ERRNO"];
954           $_dbslayer['error'] = $tmp["MYSQL_ERROR"];
955           $_dbslayer['affected_rows'] = -1;
956           break;
957         }
958
959        if (isset($tmp["AFFECTED_ROWS"])) {
960           $_dbslayer['affected_rows'] = $tmp["AFFECTED_ROWS"];
961        }
962
963        if (isset($tmp["INSERT_ID"])) {
964           $_dbslayer['insert_id'] = $tmp["INSERT_ID"];
965         }
966
967        $obj["_dbslayer"]["_idxres"]--;
968     } while ($obj["_dbslayer"]["_idxres"] >=0);
969
970     // Statements returning resultset return a resource on success, or FALSE.
971     // Other type of SQL statements return TRUE on success or FALSE on error.
972     return $_dbslayer['success'];
973 }
974
975
976 /* mysql_real_escape_string - Escapes characters for use in a SQL statement */
977 /* Prepend backslashes to the : \x00, \n, \r, \, ', " and \x1a.             */
978 function cherokee_mysql_real_escape_string ($unescaped_string, $link = NULL)
979 {
980     if (!_dbslayer($link)) {
981        return _call('_mysql_real_escape_string', $unescaped_string, $link);
982     }
983     return _mysql_escape_string($unescaped_string);
984 }
985
986
987 /* mysql_result - Get result data. Fields can be numbers or
988  * names. table.name notation not yet supported
989  */
990 function cherokee_mysql_result (&$result, $row, $field = 0)
991 {
992     if (!_is_result($result))
993            return _mysql_result ($result, $row, $field);
994     if ($row < 0 || $row >= $result["_dbslayer"]["_rows"])
995        return NULL;
996     
997     $idx = $result["_dbslayer"]["_idxres"];
998     $tmp = $result[$idx];
999     if (!is_numeric($field)) {
1000        $i=0;
1001        foreach ($tmp["RESULT"]["HEADER"] as $value) {
1002             if ($value == $field) break;
1003             $i++;
1004        }
1005        if ($i < count($tmp["RESULT"]["HEADER"]))
1006           $field = $i;
1007        else
1008           return NULL;
1009     }
1010
1011     return $tmp["RESULT"]["ROWS"][$row][$field];
1012 }
1013
1014
1015 /* mysql_select_db - Select a MySQL database */
1016 function cherokee_mysql_select_db ($database_name, $link = NULL)
1017 {
1018     if (!_dbslayer($link)) {
1019        return _call('_mysql_select_db', $database_name, $link);
1020     }
1021
1022     global $_dbslayer;
1023     $_dbslayer['db_name'] = $database_name;
1024     $link['db_name']      = $database_name;
1025     
1026     return TRUE;
1027 }
1028
1029
1030 /* mysql_set_charset - Sets the client character set */
1031 function cherokee_mysql_set_charset ($charset , $link = NULL)
1032 {
1033     if (!_dbslayer($link)) {
1034        return _call('_mysql_set_charset', $charset, $link);
1035     }
1036
1037     $query = "SET character_set_results = '"  . $charset .
1038              "', character_set_client = '"    . $charset .
1039          "', character_set_connection = '". $charset .
1040          "', character_set_database = '"  . $charset .
1041          "', character_set_server = '"    . $charset .
1042          "'";
1043
1044     $result = cherokee_mysql_query($query, $link);
1045     $params = _get_params($result);
1046
1047     if ($params['success'])
1048        return TRUE;
1049     return FALSE;
1050 }
1051
1052
1053 /* mysql_stat - Get current system status */
1054 function cherokee_mysql_stat ($link = NULL)
1055 {
1056     if (!_dbslayer($link)) {
1057        return _call('_mysql_stat', $link);
1058     }
1059
1060     $query  = "SHOW STATUS WHERE Variable_name = 'Uptime' OR "
1061                             ."Variable_name = 'Questions' OR "
1062                             ."Variable_name = 'Slow_queries' OR "
1063                             ."Variable_name LIKE 'Threads%' OR "
1064                             ."Variable_name LIKE 'Open%' OR "
1065                             ."Variable_name LIKE 'Flu%'";
1066
1067     $result = cherokee_mysql_query($query, $link);
1068
1069     $params = _get_params($result);
1070
1071     if ($params['_idxres'] < 0)
1072        return NULL;
1073
1074
1075     $info = "";
1076     while ($row = cherokee_mysql_fetch_assoc($result)) {
1077           $info .= $row['Variable_name'] . ": " . $row['Value'] . "  ";
1078     }
1079
1080     return trim($info);
1081 }
1082
1083
1084 /* mysql_tablename - Get table name of field */
1085 function cherokee_mysql_tablename ($result, $i)
1086 {
1087     if (!_dbslayer($link)) {
1088        return _call('_mysql_tablename', $result, $i);
1089     }
1090
1091     $params = _get_params($result);
1092     if ($params['_generator'] != 'list_tables')
1093        return FALSE;
1094
1095     if ($i < 0 || $i >= $params['_rows'])
1096        return FALSE;
1097     
1098     $rows = _get_rows($result);
1099
1100     return $rows[$i][0];
1101 }
1102
1103
1104 /* UNIMPLEMENTED: mysql_thread_id - Return the current thread ID */
1105 function cherokee_mysql_thread_id ($link = NULL)
1106 {
1107     if (!_dbslayer($link)) {
1108        return _call('_mysql_mysql_thread_id', $link);
1109     }
1110
1111     return FALSE;
1112 }
1113
1114
1115 /* mysql_unbuffered_query - Send an SQL query to MySQL, without fetching and buffering the result rows */
1116 function cherokee_mysql_unbuffered_query ($query, $link = NULL)
1117 {
1118     if (!_dbslayer($link)) {
1119        return _call('_mysql_unbuffered_query', $query, $link);
1120     }
1121
1122     return cherokee_mysql_query($query, $link);
1123 }
1124
1125
1126 class Mysql_fetch_field_object
1127 {
1128       public $name;         // column name
1129       public $type;         // the type of the column
1130       public $blob;         // 1 if the column is a BLOB
1131       public $numeric;      // 1 if the column is numeric
1132
1133       /* These not yet provided:
1134       public $table;        // name of the table the column belongs to
1135       public $def;          // default value of the column
1136       public $max_length;   // maximum length of the column
1137       public $not_null;     // 1 if the column cannot be NULL
1138       public $primary_key;  // 1 if the column is a primary key
1139       public $unique_key;   // 1 if the column is a unique key
1140       public $multiple_key; // 1 if the column is a non-unique key
1141       public $unsigned;     // 1 if the column is unsigned
1142       public $zerofill;     // 1 if the column is zero-filled
1143      */
1144 }
1145
1146 ?>
1147
Note: See TracBrowser for help on using the browser.