1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2015 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Scott MacVicar <scottmac@php.net>                           |
16   +----------------------------------------------------------------------+
17*/
18
19/* $Id$ */
20
21#ifdef HAVE_CONFIG_H
22#include "config.h"
23#endif
24
25#include "php.h"
26#include "php_ini.h"
27#include "ext/standard/info.h"
28#include "php_sqlite3.h"
29#include "php_sqlite3_structs.h"
30#include "main/SAPI.h"
31
32#include <sqlite3.h>
33
34#include "zend_exceptions.h"
35#include "zend_interfaces.h"
36#include "SAPI.h"
37
38ZEND_DECLARE_MODULE_GLOBALS(sqlite3)
39
40static PHP_GINIT_FUNCTION(sqlite3);
41static int php_sqlite3_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4, const char *arg5, const char *arg6);
42static void sqlite3_param_dtor(zval *data);
43static int php_sqlite3_compare_stmt_zval_free(php_sqlite3_free_list **free_list, zval *statement);
44
45/* {{{ Error Handler
46*/
47static void php_sqlite3_error(php_sqlite3_db_object *db_obj, char *format, ...)
48{
49    va_list arg;
50    char    *message;
51
52    va_start(arg, format);
53    vspprintf(&message, 0, format, arg);
54    va_end(arg);
55
56    if (db_obj && db_obj->exception) {
57        zend_throw_exception(zend_exception_get_default(), message, 0);
58    } else {
59        php_error_docref(NULL, E_WARNING, "%s", message);
60    }
61
62    if (message) {
63        efree(message);
64    }
65}
66/* }}} */
67
68#define SQLITE3_CHECK_INITIALIZED(db_obj, member, class_name) \
69    if (!(db_obj) || !(member)) { \
70        php_sqlite3_error(db_obj, "The " #class_name " object has not been correctly initialised"); \
71        RETURN_FALSE; \
72    }
73
74#define SQLITE3_CHECK_INITIALIZED_STMT(member, class_name) \
75    if (!(member)) { \
76        php_error_docref(NULL, E_WARNING, "The " #class_name " object has not been correctly initialised"); \
77        RETURN_FALSE; \
78    }
79
80/* {{{ PHP_INI
81*/
82PHP_INI_BEGIN()
83    STD_PHP_INI_ENTRY("sqlite3.extension_dir",  NULL, PHP_INI_SYSTEM, OnUpdateString, extension_dir, zend_sqlite3_globals, sqlite3_globals)
84PHP_INI_END()
85/* }}} */
86
87/* Handlers */
88static zend_object_handlers sqlite3_object_handlers;
89static zend_object_handlers sqlite3_stmt_object_handlers;
90static zend_object_handlers sqlite3_result_object_handlers;
91
92/* Class entries */
93zend_class_entry *php_sqlite3_sc_entry;
94zend_class_entry *php_sqlite3_stmt_entry;
95zend_class_entry *php_sqlite3_result_entry;
96
97/* {{{ proto void SQLite3::open(String filename [, int Flags [, string Encryption Key]])
98   Opens a SQLite 3 Database, if the build includes encryption then it will attempt to use the key. */
99PHP_METHOD(sqlite3, open)
100{
101    php_sqlite3_db_object *db_obj;
102    zval *object = getThis();
103    char *filename, *encryption_key, *fullpath;
104    size_t filename_len, encryption_key_len = 0;
105    zend_long flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
106
107    db_obj = Z_SQLITE3_DB_P(object);
108
109    if (FAILURE == zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p|ls", &filename, &filename_len, &flags, &encryption_key, &encryption_key_len)) {
110        return;
111    }
112
113    if (db_obj->initialised) {
114        zend_throw_exception(zend_exception_get_default(), "Already initialised DB Object", 0);
115    }
116
117    if (strlen(filename) != filename_len) {
118        return;
119    }
120    if (memcmp(filename, ":memory:", sizeof(":memory:")) != 0) {
121        if (!(fullpath = expand_filepath(filename, NULL))) {
122            zend_throw_exception(zend_exception_get_default(), "Unable to expand filepath", 0);
123            return;
124        }
125
126#if PHP_API_VERSION < 20100412
127        if (PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
128            zend_throw_exception_ex(zend_exception_get_default(), 0, "safe_mode prohibits opening %s", fullpath);
129            efree(fullpath);
130            return;
131        }
132#endif
133
134        if (php_check_open_basedir(fullpath)) {
135            zend_throw_exception_ex(zend_exception_get_default(), 0, "open_basedir prohibits opening %s", fullpath);
136            efree(fullpath);
137            return;
138        }
139    } else {
140        fullpath = estrdup(filename);
141    }
142
143#if SQLITE_VERSION_NUMBER >= 3005000
144    if (sqlite3_open_v2(fullpath, &(db_obj->db), flags, NULL) != SQLITE_OK) {
145#else
146    if (sqlite3_open(fullpath, &(db_obj->db)) != SQLITE_OK) {
147#endif
148        zend_throw_exception_ex(zend_exception_get_default(), 0, "Unable to open database: %s", sqlite3_errmsg(db_obj->db));
149        if (fullpath) {
150            efree(fullpath);
151        }
152        return;
153    }
154
155#if SQLITE_HAS_CODEC
156    if (encryption_key_len > 0) {
157        if (sqlite3_key(db_obj->db, encryption_key, encryption_key_len) != SQLITE_OK) {
158            zend_throw_exception_ex(zend_exception_get_default(), 0, "Unable to open database: %s", sqlite3_errmsg(db_obj->db));
159            return;
160        }
161    }
162#endif
163
164    db_obj->initialised = 1;
165
166#if PHP_API_VERSION < 20100412
167    if (PG(safe_mode) || (PG(open_basedir) && *PG(open_basedir))) {
168#else
169    if (PG(open_basedir) && *PG(open_basedir)) {
170#endif
171        sqlite3_set_authorizer(db_obj->db, php_sqlite3_authorizer, NULL);
172    }
173
174    if (fullpath) {
175        efree(fullpath);
176    }
177}
178/* }}} */
179
180/* {{{ proto bool SQLite3::close()
181   Close a SQLite 3 Database. */
182PHP_METHOD(sqlite3, close)
183{
184    php_sqlite3_db_object *db_obj;
185    zval *object = getThis();
186    int errcode;
187    db_obj = Z_SQLITE3_DB_P(object);
188
189    if (zend_parse_parameters_none() == FAILURE) {
190        return;
191    }
192
193    if (db_obj->initialised) {
194        zend_llist_clean(&(db_obj->free_list));
195        if(db_obj->db) {
196            errcode = sqlite3_close(db_obj->db);
197            if (errcode != SQLITE_OK) {
198                php_sqlite3_error(db_obj, "Unable to close database: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
199                RETURN_FALSE;
200            }
201        }
202        db_obj->initialised = 0;
203    }
204
205    RETURN_TRUE;
206}
207/* }}} */
208
209/* {{{ proto bool SQLite3::exec(String Query)
210   Executes a result-less query against a given database. */
211PHP_METHOD(sqlite3, exec)
212{
213    php_sqlite3_db_object *db_obj;
214    zval *object = getThis();
215    zend_string *sql;
216    char *errtext = NULL;
217    db_obj = Z_SQLITE3_DB_P(object);
218
219    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
220
221    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
222        return;
223    }
224
225    if (sqlite3_exec(db_obj->db, sql->val, NULL, NULL, &errtext) != SQLITE_OK) {
226        php_sqlite3_error(db_obj, "%s", errtext);
227        sqlite3_free(errtext);
228        RETURN_FALSE;
229    }
230
231    RETURN_TRUE;
232}
233/* }}} */
234
235/* {{{ proto Array SQLite3::version()
236   Returns the SQLite3 Library version as a string constant and as a number. */
237PHP_METHOD(sqlite3, version)
238{
239    if (zend_parse_parameters_none() == FAILURE) {
240        return;
241    }
242
243    array_init(return_value);
244
245    add_assoc_string(return_value, "versionString", (char*)sqlite3_libversion());
246    add_assoc_long(return_value, "versionNumber", sqlite3_libversion_number());
247
248    return;
249}
250/* }}} */
251
252/* {{{ proto int SQLite3::lastInsertRowID()
253   Returns the rowid of the most recent INSERT into the database from the database connection. */
254PHP_METHOD(sqlite3, lastInsertRowID)
255{
256    php_sqlite3_db_object *db_obj;
257    zval *object = getThis();
258    db_obj = Z_SQLITE3_DB_P(object);
259
260    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
261
262    if (zend_parse_parameters_none() == FAILURE) {
263        return;
264    }
265
266    RETURN_LONG(sqlite3_last_insert_rowid(db_obj->db));
267}
268/* }}} */
269
270/* {{{ proto int SQLite3::lastErrorCode()
271   Returns the numeric result code of the most recent failed sqlite API call for the database connection. */
272PHP_METHOD(sqlite3, lastErrorCode)
273{
274    php_sqlite3_db_object *db_obj;
275    zval *object = getThis();
276    db_obj = Z_SQLITE3_DB_P(object);
277
278    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->db, SQLite3)
279
280    if (zend_parse_parameters_none() == FAILURE) {
281        return;
282    }
283
284    RETURN_LONG(sqlite3_errcode(db_obj->db));
285}
286/* }}} */
287
288/* {{{ proto string SQLite3::lastErrorMsg()
289   Returns english text describing the most recent failed sqlite API call for the database connection. */
290PHP_METHOD(sqlite3, lastErrorMsg)
291{
292    php_sqlite3_db_object *db_obj;
293    zval *object = getThis();
294    db_obj = Z_SQLITE3_DB_P(object);
295
296    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->db, SQLite3)
297
298    if (zend_parse_parameters_none() == FAILURE) {
299        return;
300    }
301
302    RETVAL_STRING((char *)sqlite3_errmsg(db_obj->db));
303}
304/* }}} */
305
306/* {{{ proto bool SQLite3::busyTimeout(int msecs)
307   Sets a busy handler that will sleep until database is not locked or timeout is reached. Passing a value less than or equal to zero turns off all busy handlers. */
308PHP_METHOD(sqlite3, busyTimeout)
309{
310    php_sqlite3_db_object *db_obj;
311    zval *object = getThis();
312    zend_long ms;
313    int return_code;
314    db_obj = Z_SQLITE3_DB_P(object);
315
316    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
317
318    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "l", &ms)) {
319        return;
320    }
321
322    return_code = sqlite3_busy_timeout(db_obj->db, ms);
323    if (return_code != SQLITE_OK) {
324        php_sqlite3_error(db_obj, "Unable to set busy timeout: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
325        RETURN_FALSE;
326    }
327
328    RETURN_TRUE;
329}
330/* }}} */
331
332
333#ifndef SQLITE_OMIT_LOAD_EXTENSION
334/* {{{ proto bool SQLite3::loadExtension(String Shared Library)
335   Attempts to load an SQLite extension library. */
336PHP_METHOD(sqlite3, loadExtension)
337{
338    php_sqlite3_db_object *db_obj;
339    zval *object = getThis();
340    char *extension, *lib_path, *extension_dir, *errtext = NULL;
341    char fullpath[MAXPATHLEN];
342    size_t extension_len, extension_dir_len;
343    db_obj = Z_SQLITE3_DB_P(object);
344
345    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
346
347    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s", &extension, &extension_len)) {
348        return;
349    }
350
351#ifdef ZTS
352    if ((strncmp(sapi_module.name, "cgi", 3) != 0) &&
353        (strcmp(sapi_module.name, "cli") != 0) &&
354        (strncmp(sapi_module.name, "embed", 5) != 0)
355    ) {     php_sqlite3_error(db_obj, "Not supported in multithreaded Web servers");
356        RETURN_FALSE;
357    }
358#endif
359
360    if (!SQLITE3G(extension_dir)) {
361        php_sqlite3_error(db_obj, "SQLite Extension are disabled");
362        RETURN_FALSE;
363    }
364
365    if (extension_len == 0) {
366        php_sqlite3_error(db_obj, "Empty string as an extension");
367        RETURN_FALSE;
368    }
369
370    extension_dir = SQLITE3G(extension_dir);
371    extension_dir_len = strlen(SQLITE3G(extension_dir));
372
373    if (IS_SLASH(extension_dir[extension_dir_len-1])) {
374        spprintf(&lib_path, 0, "%s%s", extension_dir, extension);
375    } else {
376        spprintf(&lib_path, 0, "%s%c%s", extension_dir, DEFAULT_SLASH, extension);
377    }
378
379    if (!VCWD_REALPATH(lib_path, fullpath)) {
380        php_sqlite3_error(db_obj, "Unable to load extension at '%s'", lib_path);
381        efree(lib_path);
382        RETURN_FALSE;
383    }
384
385    efree(lib_path);
386
387    if (strncmp(fullpath, extension_dir, extension_dir_len) != 0) {
388        php_sqlite3_error(db_obj, "Unable to open extensions outside the defined directory");
389        RETURN_FALSE;
390    }
391
392    /* Extension loading should only be enabled for when we attempt to load */
393    sqlite3_enable_load_extension(db_obj->db, 1);
394    if (sqlite3_load_extension(db_obj->db, fullpath, 0, &errtext) != SQLITE_OK) {
395        php_sqlite3_error(db_obj, "%s", errtext);
396        sqlite3_free(errtext);
397        sqlite3_enable_load_extension(db_obj->db, 0);
398        RETURN_FALSE;
399    }
400    sqlite3_enable_load_extension(db_obj->db, 0);
401
402    RETURN_TRUE;
403}
404/* }}} */
405#endif
406
407/* {{{ proto int SQLite3::changes()
408  Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement. */
409PHP_METHOD(sqlite3, changes)
410{
411    php_sqlite3_db_object *db_obj;
412    zval *object = getThis();
413    db_obj = Z_SQLITE3_DB_P(object);
414
415    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
416
417    if (zend_parse_parameters_none() == FAILURE) {
418        return;
419    }
420
421    RETURN_LONG(sqlite3_changes(db_obj->db));
422}
423/* }}} */
424
425/* {{{ proto String SQLite3::escapeString(String value)
426   Returns a string that has been properly escaped. */
427PHP_METHOD(sqlite3, escapeString)
428{
429    zend_string *sql;
430    char *ret;
431
432    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
433        return;
434    }
435
436    if (sql->len) {
437        ret = sqlite3_mprintf("%q", sql->val);
438        if (ret) {
439            RETVAL_STRING(ret);
440            sqlite3_free(ret);
441        }
442    } else {
443        RETURN_EMPTY_STRING();
444    }
445}
446/* }}} */
447
448/* {{{ proto SQLite3Stmt SQLite3::prepare(String Query)
449   Returns a prepared SQL statement for execution. */
450PHP_METHOD(sqlite3, prepare)
451{
452    php_sqlite3_db_object *db_obj;
453    php_sqlite3_stmt *stmt_obj;
454    zval *object = getThis();
455    zend_string *sql;
456    int errcode;
457    php_sqlite3_free_list *free_item;
458
459    db_obj = Z_SQLITE3_DB_P(object);
460
461    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
462
463    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
464        return;
465    }
466
467    if (!sql->len) {
468        RETURN_FALSE;
469    }
470
471    object_init_ex(return_value, php_sqlite3_stmt_entry);
472    stmt_obj = Z_SQLITE3_STMT_P(return_value);
473    stmt_obj->db_obj = db_obj;
474    ZVAL_COPY(&stmt_obj->db_obj_zval, object);
475
476    errcode = sqlite3_prepare_v2(db_obj->db, sql->val, sql->len, &(stmt_obj->stmt), NULL);
477    if (errcode != SQLITE_OK) {
478        php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
479        zval_dtor(return_value);
480        RETURN_FALSE;
481    }
482
483    stmt_obj->initialised = 1;
484
485    free_item = emalloc(sizeof(php_sqlite3_free_list));
486    free_item->stmt_obj = stmt_obj;
487    ZVAL_COPY_VALUE(&free_item->stmt_obj_zval, return_value);
488
489    zend_llist_add_element(&(db_obj->free_list), &free_item);
490}
491/* }}} */
492
493/* {{{ proto SQLite3Result SQLite3::query(String Query)
494   Returns true or false, for queries that return data it will return a SQLite3Result object. */
495PHP_METHOD(sqlite3, query)
496{
497    php_sqlite3_db_object *db_obj;
498    php_sqlite3_result *result;
499    php_sqlite3_stmt *stmt_obj;
500    zval *object = getThis();
501    zval stmt;
502    zend_string *sql;
503    char *errtext = NULL;
504    int return_code;
505    db_obj = Z_SQLITE3_DB_P(object);
506
507    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
508
509    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
510        return;
511    }
512
513    if (!sql->len) {
514        RETURN_FALSE;
515    }
516
517    /* If there was no return value then just execute the query */
518    if (!USED_RET()) {
519        if (sqlite3_exec(db_obj->db, sql->val, NULL, NULL, &errtext) != SQLITE_OK) {
520            php_sqlite3_error(db_obj, "%s", errtext);
521            sqlite3_free(errtext);
522        }
523        return;
524    }
525
526    object_init_ex(&stmt, php_sqlite3_stmt_entry);
527    stmt_obj = Z_SQLITE3_STMT_P(&stmt);
528    stmt_obj->db_obj = db_obj;
529    ZVAL_COPY(&stmt_obj->db_obj_zval, object);
530
531    return_code = sqlite3_prepare_v2(db_obj->db, sql->val, sql->len, &(stmt_obj->stmt), NULL);
532    if (return_code != SQLITE_OK) {
533        php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
534        zval_ptr_dtor(&stmt);
535        RETURN_FALSE;
536    }
537
538    stmt_obj->initialised = 1;
539
540    object_init_ex(return_value, php_sqlite3_result_entry);
541    result = Z_SQLITE3_RESULT_P(return_value);
542    result->db_obj = db_obj;
543    result->stmt_obj = stmt_obj;
544    ZVAL_COPY_VALUE(&result->stmt_obj_zval, &stmt);
545
546    return_code = sqlite3_step(result->stmt_obj->stmt);
547
548    switch (return_code) {
549        case SQLITE_ROW: /* Valid Row */
550        case SQLITE_DONE: /* Valid but no results */
551        {
552            php_sqlite3_free_list *free_item;
553            free_item = emalloc(sizeof(php_sqlite3_free_list));
554            free_item->stmt_obj = stmt_obj;
555            free_item->stmt_obj_zval = stmt;
556            zend_llist_add_element(&(db_obj->free_list), &free_item);
557            sqlite3_reset(result->stmt_obj->stmt);
558            break;
559        }
560        default:
561            php_sqlite3_error(db_obj, "Unable to execute statement: %s", sqlite3_errmsg(db_obj->db));
562            sqlite3_finalize(stmt_obj->stmt);
563            stmt_obj->initialised = 0;
564            zval_dtor(return_value);
565            RETURN_FALSE;
566    }
567}
568/* }}} */
569
570static void sqlite_value_to_zval(sqlite3_stmt *stmt, int column, zval *data) /* {{{ */
571{
572    switch (sqlite3_column_type(stmt, column)) {
573        case SQLITE_INTEGER:
574            if ((sqlite3_column_int64(stmt, column)) >= INT_MAX || sqlite3_column_int64(stmt, column) <= INT_MIN) {
575                ZVAL_STRINGL(data, (char *)sqlite3_column_text(stmt, column), sqlite3_column_bytes(stmt, column));
576            } else {
577                ZVAL_LONG(data, sqlite3_column_int64(stmt, column));
578            }
579            break;
580
581        case SQLITE_FLOAT:
582            ZVAL_DOUBLE(data, sqlite3_column_double(stmt, column));
583            break;
584
585        case SQLITE_NULL:
586            ZVAL_NULL(data);
587            break;
588
589        case SQLITE3_TEXT:
590            ZVAL_STRING(data, (char*)sqlite3_column_text(stmt, column));
591            break;
592
593        case SQLITE_BLOB:
594        default:
595            ZVAL_STRINGL(data, (char*)sqlite3_column_blob(stmt, column), sqlite3_column_bytes(stmt, column));
596    }
597}
598/* }}} */
599
600/* {{{ proto SQLite3Result SQLite3::querySingle(String Query [, bool entire_row = false])
601   Returns a string of the first column, or an array of the entire row. */
602PHP_METHOD(sqlite3, querySingle)
603{
604    php_sqlite3_db_object *db_obj;
605    zval *object = getThis();
606    zend_string *sql;
607    char *errtext = NULL;
608    int return_code;
609    zend_bool entire_row = 0;
610    sqlite3_stmt *stmt;
611    db_obj = Z_SQLITE3_DB_P(object);
612
613    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
614
615    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S|b", &sql, &entire_row)) {
616        return;
617    }
618
619    if (!sql->len) {
620        RETURN_FALSE;
621    }
622
623    /* If there was no return value then just execute the query */
624    if (!USED_RET()) {
625        if (sqlite3_exec(db_obj->db, sql->val, NULL, NULL, &errtext) != SQLITE_OK) {
626            php_sqlite3_error(db_obj, "%s", errtext);
627            sqlite3_free(errtext);
628        }
629        return;
630    }
631
632    return_code = sqlite3_prepare_v2(db_obj->db, sql->val, sql->len, &stmt, NULL);
633    if (return_code != SQLITE_OK) {
634        php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
635        RETURN_FALSE;
636    }
637
638    return_code = sqlite3_step(stmt);
639
640    switch (return_code) {
641        case SQLITE_ROW: /* Valid Row */
642        {
643            if (!entire_row) {
644                sqlite_value_to_zval(stmt, 0, return_value);
645            } else {
646                int i = 0;
647                array_init(return_value);
648                for (i = 0; i < sqlite3_data_count(stmt); i++) {
649                    zval data;
650                    sqlite_value_to_zval(stmt, i, &data);
651                    add_assoc_zval(return_value, (char*)sqlite3_column_name(stmt, i), &data);
652                }
653            }
654            break;
655        }
656        case SQLITE_DONE: /* Valid but no results */
657        {
658            if (!entire_row) {
659                RETVAL_NULL();
660            } else {
661                array_init(return_value);
662            }
663            break;
664        }
665        default:
666            php_sqlite3_error(db_obj, "Unable to execute statement: %s", sqlite3_errmsg(db_obj->db));
667            RETVAL_FALSE;
668    }
669    sqlite3_finalize(stmt);
670}
671/* }}} */
672
673static int sqlite3_do_callback(struct php_sqlite3_fci *fc, zval *cb, int argc, sqlite3_value **argv, sqlite3_context *context, int is_agg) /* {{{ */
674{
675    zval *zargs = NULL;
676    zval retval;
677    int i;
678    int ret;
679    int fake_argc;
680    php_sqlite3_agg_context *agg_context = NULL;
681
682    if (is_agg) {
683        is_agg = 2;
684    }
685
686    fake_argc = argc + is_agg;
687
688    fc->fci.size = sizeof(fc->fci);
689    fc->fci.function_table = EG(function_table);
690    ZVAL_COPY_VALUE(&fc->fci.function_name, cb);
691    fc->fci.symbol_table = NULL;
692    fc->fci.object = NULL;
693    fc->fci.retval = &retval;
694    fc->fci.param_count = fake_argc;
695
696    /* build up the params */
697
698    if (fake_argc) {
699        zargs = (zval *)safe_emalloc(fake_argc, sizeof(zval), 0);
700    }
701
702    if (is_agg) {
703        /* summon the aggregation context */
704        agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
705
706        if (Z_ISUNDEF(agg_context->zval_context)) {
707            ZVAL_NULL(&agg_context->zval_context);
708        }
709        ZVAL_COPY_VALUE(&zargs[0], &agg_context->zval_context);
710        ZVAL_LONG(&zargs[1], agg_context->row_count);
711    }
712
713    for (i = 0; i < argc; i++) {
714        switch (sqlite3_value_type(argv[i])) {
715            case SQLITE_INTEGER:
716#if ZEND_LONG_MAX > 2147483647
717                ZVAL_LONG(&zargs[i + is_agg], sqlite3_value_int64(argv[i]));
718#else
719                ZVAL_LONG(&zargs[i + is_agg], sqlite3_value_int(argv[i]));
720#endif
721                break;
722
723            case SQLITE_FLOAT:
724                ZVAL_DOUBLE(&zargs[i + is_agg], sqlite3_value_double(argv[i]));
725                break;
726
727            case SQLITE_NULL:
728                ZVAL_NULL(&zargs[i + is_agg]);
729                break;
730
731            case SQLITE_BLOB:
732            case SQLITE3_TEXT:
733            default:
734                ZVAL_STRINGL(&zargs[i + is_agg], (char*)sqlite3_value_text(argv[i]), sqlite3_value_bytes(argv[i]));
735                break;
736        }
737    }
738
739    fc->fci.params = zargs;
740
741    if ((ret = zend_call_function(&fc->fci, &fc->fcc)) == FAILURE) {
742        php_error_docref(NULL, E_WARNING, "An error occurred while invoking the callback");
743    }
744
745    /* clean up the params */
746    if (fake_argc) {
747        for (i = is_agg; i < argc + is_agg; i++) {
748            zval_ptr_dtor(&zargs[i]);
749        }
750        if (is_agg) {
751            zval_ptr_dtor(&zargs[1]);
752        }
753        efree(zargs);
754    }
755
756    if (!is_agg || !argv) {
757        /* only set the sqlite return value if we are a scalar function,
758         * or if we are finalizing an aggregate */
759        if (!Z_ISUNDEF(retval)) {
760            switch (Z_TYPE(retval)) {
761                case IS_LONG:
762#if ZEND_LONG_MAX > 2147483647
763                    sqlite3_result_int64(context, Z_LVAL(retval));
764#else
765                    sqlite3_result_int(context, Z_LVAL(retval));
766#endif
767                    break;
768
769                case IS_NULL:
770                    sqlite3_result_null(context);
771                    break;
772
773                case IS_DOUBLE:
774                    sqlite3_result_double(context, Z_DVAL(retval));
775                    break;
776
777                default:
778                    convert_to_string_ex(&retval);
779                    sqlite3_result_text(context, Z_STRVAL(retval), Z_STRLEN(retval), SQLITE_TRANSIENT);
780                    break;
781            }
782        } else {
783            sqlite3_result_error(context, "failed to invoke callback", 0);
784        }
785
786        if (agg_context && !Z_ISUNDEF(agg_context->zval_context)) {
787            zval_ptr_dtor(&agg_context->zval_context);
788        }
789    } else {
790        /* we're stepping in an aggregate; the return value goes into
791         * the context */
792        if (agg_context && !Z_ISUNDEF(agg_context->zval_context)) {
793            zval_ptr_dtor(&agg_context->zval_context);
794        }
795        ZVAL_COPY_VALUE(&agg_context->zval_context, &retval);
796        ZVAL_UNDEF(&retval);
797    }
798
799    if (!Z_ISUNDEF(retval)) {
800        zval_ptr_dtor(&retval);
801    }
802    return ret;
803}
804/* }}}*/
805
806static void php_sqlite3_callback_func(sqlite3_context *context, int argc, sqlite3_value **argv) /* {{{ */
807{
808    php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
809
810    sqlite3_do_callback(&func->afunc, &func->func, argc, argv, context, 0);
811}
812/* }}}*/
813
814static void php_sqlite3_callback_step(sqlite3_context *context, int argc, sqlite3_value **argv) /* {{{ */
815{
816    php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
817    php_sqlite3_agg_context *agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
818
819    agg_context->row_count++;
820
821    sqlite3_do_callback(&func->astep, &func->step, argc, argv, context, 1);
822}
823/* }}} */
824
825static void php_sqlite3_callback_final(sqlite3_context *context) /* {{{ */
826{
827    php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
828    php_sqlite3_agg_context *agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
829
830    agg_context->row_count = 0;
831
832    sqlite3_do_callback(&func->afini, &func->fini, 0, NULL, context, 1);
833}
834/* }}} */
835
836static int php_sqlite3_callback_compare(void *coll, int a_len, const void *a, int b_len, const void* b) /* {{{ */
837{
838    php_sqlite3_collation *collation = (php_sqlite3_collation*)coll;
839    zval *zargs = NULL;
840    zval retval;
841    int ret;
842
843    ZVAL_UNDEF(&retval);
844    collation->fci.fci.size = (sizeof(collation->fci.fci));
845    collation->fci.fci.function_table = EG(function_table);
846    ZVAL_COPY_VALUE(&collation->fci.fci.function_name, &collation->cmp_func);
847    collation->fci.fci.symbol_table = NULL;
848    collation->fci.fci.object = NULL;
849    collation->fci.fci.retval = &retval;
850    collation->fci.fci.param_count = 2;
851
852    zargs = safe_emalloc(2, sizeof(zval), 0);
853    ZVAL_STRINGL(&zargs[0], a, a_len);
854    ZVAL_STRINGL(&zargs[1], b, b_len);
855
856    collation->fci.fci.params = zargs;
857
858    if (!EG(exception)) {
859        //Exception occurred on previous callback. Don't attempt to call function
860        if ((ret = zend_call_function(&collation->fci.fci, &collation->fci.fcc)) == FAILURE) {
861            php_error_docref(NULL, E_WARNING, "An error occurred while invoking the compare callback");
862        }
863    }
864
865    zval_ptr_dtor(&zargs[0]);
866    zval_ptr_dtor(&zargs[1]);
867    efree(zargs);
868
869    if (EG(exception)) {
870        ret = 0;
871    } else if (Z_TYPE(retval) != IS_LONG){
872        //retval ought to contain a ZVAL_LONG by now
873        // (the result of a comparison, i.e. most likely -1, 0, or 1)
874        //I suppose we could accept any scalar return type, though.
875        php_error_docref(NULL, E_WARNING, "An error occurred while invoking the compare callback (invalid return type).  Collation behaviour is undefined.");
876    }else{
877        ret = Z_LVAL(retval);
878    }
879
880    zval_ptr_dtor(&retval);
881
882    return ret;
883}
884/* }}} */
885
886/* {{{ proto bool SQLite3::createFunction(string name, mixed callback [, int argcount])
887   Allows registration of a PHP function as a SQLite UDF that can be called within SQL statements. */
888PHP_METHOD(sqlite3, createFunction)
889{
890    php_sqlite3_db_object *db_obj;
891    zval *object = getThis();
892    php_sqlite3_func *func;
893    char *sql_func;
894    size_t sql_func_len;
895    zval *callback_func;
896    zend_string *callback_name;
897    zend_long sql_func_num_args = -1;
898    db_obj = Z_SQLITE3_DB_P(object);
899
900    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
901
902    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz|l", &sql_func, &sql_func_len, &callback_func, &sql_func_num_args) == FAILURE) {
903        return;
904    }
905
906    if (!sql_func_len) {
907        RETURN_FALSE;
908    }
909
910    if (!zend_is_callable(callback_func, 0, &callback_name)) {
911        php_sqlite3_error(db_obj, "Not a valid callback function %s", callback_name->val);
912        zend_string_release(callback_name);
913        RETURN_FALSE;
914    }
915    zend_string_release(callback_name);
916
917    func = (php_sqlite3_func *)ecalloc(1, sizeof(*func));
918
919    if (sqlite3_create_function(db_obj->db, sql_func, sql_func_num_args, SQLITE_UTF8, func, php_sqlite3_callback_func, NULL, NULL) == SQLITE_OK) {
920        func->func_name = estrdup(sql_func);
921
922        ZVAL_COPY(&func->func, callback_func);
923
924        func->argc = sql_func_num_args;
925        func->next = db_obj->funcs;
926        db_obj->funcs = func;
927
928        RETURN_TRUE;
929    }
930    efree(func);
931
932    RETURN_FALSE;
933}
934/* }}} */
935
936/* {{{ proto bool SQLite3::createAggregate(string name, mixed step, mixed final [, int argcount])
937   Allows registration of a PHP function for use as an aggregate. */
938PHP_METHOD(sqlite3, createAggregate)
939{
940    php_sqlite3_db_object *db_obj;
941    zval *object = getThis();
942    php_sqlite3_func *func;
943    char *sql_func;
944    zend_string *callback_name;
945    size_t sql_func_len;
946    zval *step_callback, *fini_callback;
947    zend_long sql_func_num_args = -1;
948    db_obj = Z_SQLITE3_DB_P(object);
949
950    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
951
952    if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &sql_func, &sql_func_len, &step_callback, &fini_callback, &sql_func_num_args) == FAILURE) {
953        return;
954    }
955
956    if (!sql_func_len) {
957        RETURN_FALSE;
958    }
959
960    if (!zend_is_callable(step_callback, 0, &callback_name)) {
961        php_sqlite3_error(db_obj, "Not a valid callback function %s", callback_name->val);
962        zend_string_release(callback_name);
963        RETURN_FALSE;
964    }
965    zend_string_release(callback_name);
966
967    if (!zend_is_callable(fini_callback, 0, &callback_name)) {
968        php_sqlite3_error(db_obj, "Not a valid callback function %s", callback_name->val);
969        zend_string_release(callback_name);
970        RETURN_FALSE;
971    }
972    zend_string_release(callback_name);
973
974    func = (php_sqlite3_func *)ecalloc(1, sizeof(*func));
975
976    if (sqlite3_create_function(db_obj->db, sql_func, sql_func_num_args, SQLITE_UTF8, func, NULL, php_sqlite3_callback_step, php_sqlite3_callback_final) == SQLITE_OK) {
977        func->func_name = estrdup(sql_func);
978
979        ZVAL_COPY(&func->step, step_callback);
980        ZVAL_COPY(&func->fini, fini_callback);
981
982        func->argc = sql_func_num_args;
983        func->next = db_obj->funcs;
984        db_obj->funcs = func;
985
986        RETURN_TRUE;
987    }
988    efree(func);
989
990    RETURN_FALSE;
991}
992/* }}} */
993
994/* {{{ proto bool SQLite3::createCollation(string name, mixed callback)
995   Registers a PHP function as a comparator that can be used with the SQL COLLATE operator. Callback must accept two strings and return an integer (as strcmp()). */
996PHP_METHOD(sqlite3, createCollation)
997{
998    php_sqlite3_db_object *db_obj;
999    zval *object = getThis();
1000    php_sqlite3_collation *collation;
1001    char *collation_name;
1002    zend_string *callback_name;
1003    size_t collation_name_len;
1004    zval *callback_func;
1005    db_obj = Z_SQLITE3_DB_P(object);
1006
1007    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1008
1009    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz", &collation_name, &collation_name_len, &callback_func) == FAILURE) {
1010        RETURN_FALSE;
1011    }
1012
1013    if (!collation_name_len) {
1014        RETURN_FALSE;
1015    }
1016
1017    if (!zend_is_callable(callback_func, 0, &callback_name)) {
1018        php_sqlite3_error(db_obj, "Not a valid callback function %s", callback_name->val);
1019        zend_string_release(callback_name);
1020        RETURN_FALSE;
1021    }
1022    zend_string_release(callback_name);
1023
1024    collation = (php_sqlite3_collation *)ecalloc(1, sizeof(*collation));
1025    if (sqlite3_create_collation(db_obj->db, collation_name, SQLITE_UTF8, collation, php_sqlite3_callback_compare) == SQLITE_OK) {
1026        collation->collation_name = estrdup(collation_name);
1027
1028        ZVAL_COPY(&collation->cmp_func, callback_func);
1029
1030        collation->next = db_obj->collations;
1031        db_obj->collations = collation;
1032
1033        RETURN_TRUE;
1034    }
1035    efree(collation);
1036
1037    RETURN_FALSE;
1038}
1039/* }}} */
1040
1041typedef struct {
1042    sqlite3_blob *blob;
1043    size_t       position;
1044    size_t       size;
1045} php_stream_sqlite3_data;
1046
1047static size_t php_sqlite3_stream_write(php_stream *stream, const char *buf, size_t count)
1048{
1049/*  php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract; */
1050
1051    return 0;
1052}
1053
1054static size_t php_sqlite3_stream_read(php_stream *stream, char *buf, size_t count)
1055{
1056    php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1057
1058    if (sqlite3_stream->position + count >= sqlite3_stream->size) {
1059        count = sqlite3_stream->size - sqlite3_stream->position;
1060        stream->eof = 1;
1061    }
1062    if (count) {
1063        if (sqlite3_blob_read(sqlite3_stream->blob, buf, count, sqlite3_stream->position) != SQLITE_OK) {
1064            return 0;
1065        }
1066        sqlite3_stream->position += count;
1067    }
1068    return count;
1069}
1070
1071static int php_sqlite3_stream_close(php_stream *stream, int close_handle)
1072{
1073    php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1074
1075    if (sqlite3_blob_close(sqlite3_stream->blob) != SQLITE_OK) {
1076        /* Error occurred, but it still closed */
1077    }
1078
1079    efree(sqlite3_stream);
1080
1081    return 0;
1082}
1083
1084static int php_sqlite3_stream_flush(php_stream *stream)
1085{
1086    /* do nothing */
1087    return 0;
1088}
1089
1090/* {{{ */
1091static int php_sqlite3_stream_seek(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffs)
1092{
1093    php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1094
1095    switch(whence) {
1096        case SEEK_CUR:
1097            if (offset < 0) {
1098                if (sqlite3_stream->position < (size_t)(-offset)) {
1099                    sqlite3_stream->position = 0;
1100                    *newoffs = -1;
1101                    return -1;
1102                } else {
1103                    sqlite3_stream->position = sqlite3_stream->position + offset;
1104                    *newoffs = sqlite3_stream->position;
1105                    stream->eof = 0;
1106                    return 0;
1107                }
1108            } else {
1109                if (sqlite3_stream->position + (size_t)(offset) > sqlite3_stream->size) {
1110                    sqlite3_stream->position = sqlite3_stream->size;
1111                    *newoffs = -1;
1112                    return -1;
1113                } else {
1114                    sqlite3_stream->position = sqlite3_stream->position + offset;
1115                    *newoffs = sqlite3_stream->position;
1116                    stream->eof = 0;
1117                    return 0;
1118                }
1119            }
1120        case SEEK_SET:
1121            if (sqlite3_stream->size < (size_t)(offset)) {
1122                sqlite3_stream->position = sqlite3_stream->size;
1123                *newoffs = -1;
1124                return -1;
1125            } else {
1126                sqlite3_stream->position = offset;
1127                *newoffs = sqlite3_stream->position;
1128                stream->eof = 0;
1129                return 0;
1130            }
1131        case SEEK_END:
1132            if (offset > 0) {
1133                sqlite3_stream->position = sqlite3_stream->size;
1134                *newoffs = -1;
1135                return -1;
1136            } else if (sqlite3_stream->size < (size_t)(-offset)) {
1137                sqlite3_stream->position = 0;
1138                *newoffs = -1;
1139                return -1;
1140            } else {
1141                sqlite3_stream->position = sqlite3_stream->size + offset;
1142                *newoffs = sqlite3_stream->position;
1143                stream->eof = 0;
1144                return 0;
1145            }
1146        default:
1147            *newoffs = sqlite3_stream->position;
1148            return -1;
1149    }
1150}
1151/* }}} */
1152
1153
1154static int php_sqlite3_stream_cast(php_stream *stream, int castas, void **ret)
1155{
1156    return FAILURE;
1157}
1158
1159static int php_sqlite3_stream_stat(php_stream *stream, php_stream_statbuf *ssb)
1160{
1161    php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1162    ssb->sb.st_size = sqlite3_stream->size;
1163    return 0;
1164}
1165
1166static php_stream_ops php_stream_sqlite3_ops = {
1167    php_sqlite3_stream_write,
1168    php_sqlite3_stream_read,
1169    php_sqlite3_stream_close,
1170    php_sqlite3_stream_flush,
1171    "SQLite3",
1172    php_sqlite3_stream_seek,
1173    php_sqlite3_stream_cast,
1174    php_sqlite3_stream_stat
1175};
1176
1177/* {{{ proto resource SQLite3::openBlob(string table, string column, int rowid [, string dbname])
1178   Open a blob as a stream which we can read / write to. */
1179PHP_METHOD(sqlite3, openBlob)
1180{
1181    php_sqlite3_db_object *db_obj;
1182    zval *object = getThis();
1183    char *table, *column, *dbname = "main";
1184    size_t table_len, column_len, dbname_len;
1185    zend_long rowid, flags = 0;
1186    sqlite3_blob *blob = NULL;
1187    php_stream_sqlite3_data *sqlite3_stream;
1188    php_stream *stream;
1189
1190    db_obj = Z_SQLITE3_DB_P(object);
1191
1192    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1193
1194    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssl|s", &table, &table_len, &column, &column_len, &rowid, &dbname, &dbname_len) == FAILURE) {
1195        return;
1196    }
1197
1198    if (sqlite3_blob_open(db_obj->db, dbname, table, column, rowid, flags, &blob) != SQLITE_OK) {
1199        php_sqlite3_error(db_obj, "Unable to open blob: %s", sqlite3_errmsg(db_obj->db));
1200        RETURN_FALSE;
1201    }
1202
1203    sqlite3_stream = emalloc(sizeof(php_stream_sqlite3_data));
1204    sqlite3_stream->blob = blob;
1205    sqlite3_stream->position = 0;
1206    sqlite3_stream->size = sqlite3_blob_bytes(blob);
1207
1208    stream = php_stream_alloc(&php_stream_sqlite3_ops, sqlite3_stream, 0, "rb");
1209
1210    if (stream) {
1211        php_stream_to_zval(stream, return_value);
1212    } else {
1213        RETURN_FALSE;
1214    }
1215}
1216/* }}} */
1217
1218/* {{{ proto bool SQLite3::enableExceptions([bool enableExceptions = false])
1219   Enables an exception error mode. */
1220PHP_METHOD(sqlite3, enableExceptions)
1221{
1222    php_sqlite3_db_object *db_obj;
1223    zval *object = getThis();
1224    zend_bool enableExceptions = 0;
1225
1226    db_obj = Z_SQLITE3_DB_P(object);
1227
1228    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &enableExceptions) == FAILURE) {
1229        return;
1230    }
1231
1232    RETVAL_BOOL(db_obj->exception);
1233
1234    db_obj->exception = enableExceptions;
1235}
1236/* }}} */
1237
1238/* {{{ proto int SQLite3Stmt::paramCount()
1239   Returns the number of parameters within the prepared statement. */
1240PHP_METHOD(sqlite3stmt, paramCount)
1241{
1242    php_sqlite3_stmt *stmt_obj;
1243    zval *object = getThis();
1244    stmt_obj = Z_SQLITE3_STMT_P(object);
1245
1246    if (zend_parse_parameters_none() == FAILURE) {
1247        return;
1248    }
1249
1250    SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1251    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1252
1253    RETURN_LONG(sqlite3_bind_parameter_count(stmt_obj->stmt));
1254}
1255/* }}} */
1256
1257/* {{{ proto bool SQLite3Stmt::close()
1258   Closes the prepared statement. */
1259PHP_METHOD(sqlite3stmt, close)
1260{
1261    php_sqlite3_stmt *stmt_obj;
1262    zval *object = getThis();
1263    stmt_obj = Z_SQLITE3_STMT_P(object);
1264
1265    if (zend_parse_parameters_none() == FAILURE) {
1266        return;
1267    }
1268
1269    SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1270
1271    if(stmt_obj->db_obj) {
1272            zend_llist_del_element(&(stmt_obj->db_obj->free_list), object, (int (*)(void *, void *)) php_sqlite3_compare_stmt_zval_free);
1273    }
1274
1275    RETURN_TRUE;
1276}
1277/* }}} */
1278
1279/* {{{ proto bool SQLite3Stmt::reset()
1280   Reset the prepared statement to the state before it was executed, bindings still remain. */
1281PHP_METHOD(sqlite3stmt, reset)
1282{
1283    php_sqlite3_stmt *stmt_obj;
1284    zval *object = getThis();
1285    stmt_obj = Z_SQLITE3_STMT_P(object);
1286
1287    if (zend_parse_parameters_none() == FAILURE) {
1288        return;
1289    }
1290
1291    SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1292    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1293
1294    if (sqlite3_reset(stmt_obj->stmt) != SQLITE_OK) {
1295        php_sqlite3_error(stmt_obj->db_obj, "Unable to reset statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1296        RETURN_FALSE;
1297    }
1298    RETURN_TRUE;
1299}
1300/* }}} */
1301
1302/* {{{ proto bool SQLite3Stmt::clear()
1303   Clear all current bound parameters. */
1304PHP_METHOD(sqlite3stmt, clear)
1305{
1306    php_sqlite3_stmt *stmt_obj;
1307    zval *object = getThis();
1308    stmt_obj = Z_SQLITE3_STMT_P(object);
1309
1310    if (zend_parse_parameters_none() == FAILURE) {
1311        return;
1312    }
1313
1314    SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1315    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1316
1317    if (sqlite3_clear_bindings(stmt_obj->stmt) != SQLITE_OK) {
1318        php_sqlite3_error(stmt_obj->db_obj, "Unable to clear statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1319        RETURN_FALSE;
1320    }
1321
1322    RETURN_TRUE;
1323}
1324/* }}} */
1325
1326/* {{{ proto bool SQLite3Stmt::readOnly()
1327   Returns true if a statement is definitely read only */
1328PHP_METHOD(sqlite3stmt, readOnly)
1329{
1330    php_sqlite3_stmt *stmt_obj;
1331    zval *object = getThis();
1332    stmt_obj = Z_SQLITE3_STMT_P(object);
1333
1334    if (zend_parse_parameters_none() == FAILURE) {
1335        return;
1336    }
1337
1338    SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1339    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1340
1341#if SQLITE_VERSION_NUMBER >= 3007004
1342    if (sqlite3_stmt_readonly(stmt_obj->stmt)) {
1343        RETURN_TRUE;
1344    }
1345#endif
1346    RETURN_FALSE;
1347}
1348/* }}} */
1349
1350static int register_bound_parameter_to_sqlite(struct php_sqlite3_bound_param *param, php_sqlite3_stmt *stmt) /* {{{ */
1351{
1352    HashTable *hash;
1353    hash = stmt->bound_params;
1354
1355    if (!hash) {
1356        ALLOC_HASHTABLE(hash);
1357        zend_hash_init(hash, 13, NULL, sqlite3_param_dtor, 0);
1358        stmt->bound_params = hash;
1359    }
1360
1361    /* We need a : prefix to resolve a name to a parameter number */
1362    if (param->name) {
1363        if (param->name->val[0] != ':') {
1364            /* pre-increment for character + 1 for null */
1365            zend_string *temp = zend_string_alloc(param->name->len + 1, 0);
1366            temp->val[0] = ':';
1367            memmove(temp->val + 1, param->name->val, param->name->len + 1);
1368            param->name = temp;
1369        } else {
1370            param->name = zend_string_init(param->name->val, param->name->len, 0);
1371        }
1372        /* do lookup*/
1373        param->param_number = sqlite3_bind_parameter_index(stmt->stmt, param->name->val);
1374    }
1375
1376    if (param->param_number < 1) {
1377        zend_string_release(param->name);
1378        return 0;
1379    }
1380
1381    if (param->param_number >= 1) {
1382        zend_hash_index_del(hash, param->param_number);
1383    }
1384
1385    if (param->name) {
1386        zend_hash_update_mem(hash, param->name, param, sizeof(struct php_sqlite3_bound_param));
1387    } else {
1388        zend_hash_index_update_mem(hash, param->param_number, param, sizeof(struct php_sqlite3_bound_param));
1389    }
1390
1391    return 1;
1392}
1393/* }}} */
1394
1395/* {{{ proto bool SQLite3Stmt::bindParam(int parameter_number, mixed parameter [, int type])
1396   Bind Parameter to a stmt variable. */
1397PHP_METHOD(sqlite3stmt, bindParam)
1398{
1399    php_sqlite3_stmt *stmt_obj;
1400    zval *object = getThis();
1401    struct php_sqlite3_bound_param param = {0};
1402    zval *parameter;
1403    stmt_obj = Z_SQLITE3_STMT_P(object);
1404
1405    param.param_number = -1;
1406    param.type = SQLITE3_TEXT;
1407
1408    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "lz|l", &param.param_number, &parameter, &param.type) == FAILURE) {
1409        if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz|l", &param.name, &parameter, &param.type) == FAILURE) {
1410            return;
1411        }
1412    }
1413
1414    SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1415    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1416
1417    ZVAL_COPY(&param.parameter, parameter);
1418
1419    if (!register_bound_parameter_to_sqlite(&param, stmt_obj)) {
1420        if (!Z_ISUNDEF(param.parameter)) {
1421            zval_ptr_dtor(&(param.parameter));
1422            ZVAL_UNDEF(&param.parameter);
1423        }
1424        RETURN_FALSE;
1425    }
1426    RETURN_TRUE;
1427}
1428/* }}} */
1429
1430/* {{{ proto bool SQLite3Stmt::bindValue(int parameter_number, mixed parameter [, int type])
1431   Bind Value of a parameter to a stmt variable. */
1432PHP_METHOD(sqlite3stmt, bindValue)
1433{
1434    php_sqlite3_stmt *stmt_obj;
1435    zval *object = getThis();
1436    struct php_sqlite3_bound_param param = {0};
1437    zval *parameter;
1438    stmt_obj = Z_SQLITE3_STMT_P(object);
1439
1440    param.param_number = -1;
1441    param.type = SQLITE3_TEXT;
1442
1443    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "lz/|l", &param.param_number, &parameter, &param.type) == FAILURE) {
1444        if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz/|l", &param.name, &parameter, &param.type) == FAILURE) {
1445            return;
1446        }
1447    }
1448
1449    SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1450    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1451
1452    ZVAL_COPY(&param.parameter, parameter);
1453
1454    if (!register_bound_parameter_to_sqlite(&param, stmt_obj)) {
1455        if (!Z_ISUNDEF(param.parameter)) {
1456            zval_ptr_dtor(&(param.parameter));
1457            ZVAL_UNDEF(&param.parameter);
1458        }
1459        RETURN_FALSE;
1460    }
1461    RETURN_TRUE;
1462}
1463/* }}} */
1464
1465/* {{{ proto SQLite3Result SQLite3Stmt::execute()
1466   Executes a prepared statement and returns a result set object. */
1467PHP_METHOD(sqlite3stmt, execute)
1468{
1469    php_sqlite3_stmt *stmt_obj;
1470    php_sqlite3_result *result;
1471    zval *object = getThis();
1472    int return_code = 0;
1473    struct php_sqlite3_bound_param *param;
1474
1475    stmt_obj = Z_SQLITE3_STMT_P(object);
1476
1477    if (zend_parse_parameters_none() == FAILURE) {
1478        return;
1479    }
1480
1481    SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1482
1483    if (stmt_obj->bound_params) {
1484        ZEND_HASH_FOREACH_PTR(stmt_obj->bound_params, param) {
1485            zval *parameter;
1486            /* parameter must be a reference? */
1487            if (Z_ISREF(param->parameter)) {
1488                parameter = Z_REFVAL(param->parameter);
1489            } else {
1490                parameter = &param->parameter;
1491            }
1492
1493            /* If the ZVAL is null then it should be bound as that */
1494            if (Z_TYPE_P(parameter) == IS_NULL) {
1495                sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1496                continue;
1497            }
1498
1499            switch (param->type) {
1500                case SQLITE_INTEGER:
1501                    convert_to_long(parameter);
1502#if ZEND_LONG_MAX > 2147483647
1503                    sqlite3_bind_int64(stmt_obj->stmt, param->param_number, Z_LVAL_P(parameter));
1504#else
1505                    sqlite3_bind_int(stmt_obj->stmt, param->param_number, Z_LVAL_P(parameter));
1506#endif
1507                    break;
1508
1509                case SQLITE_FLOAT:
1510                    /* convert_to_double(parameter);*/
1511                    sqlite3_bind_double(stmt_obj->stmt, param->param_number, Z_DVAL_P(parameter));
1512                    break;
1513
1514                case SQLITE_BLOB:
1515                {
1516                    php_stream *stream = NULL;
1517                    zend_string *buffer;
1518                    if (Z_TYPE_P(parameter) == IS_RESOURCE) {
1519                        php_stream_from_zval_no_verify(stream, parameter);
1520                        if (stream == NULL) {
1521                            php_sqlite3_error(stmt_obj->db_obj, "Unable to read stream for parameter %ld", param->param_number);
1522                            RETURN_FALSE;
1523                        }
1524                        buffer = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0);
1525                    } else {
1526                        convert_to_string(parameter);
1527                        buffer = Z_STR_P(parameter);
1528                    }
1529
1530                    sqlite3_bind_blob(stmt_obj->stmt, param->param_number, buffer->val, buffer->len, SQLITE_TRANSIENT);
1531
1532                    if (stream) {
1533                        zend_string_release(buffer);
1534                    }
1535                    break;
1536                }
1537
1538                case SQLITE3_TEXT:
1539                    convert_to_string(parameter);
1540                    sqlite3_bind_text(stmt_obj->stmt, param->param_number, Z_STRVAL_P(parameter), Z_STRLEN_P(parameter), SQLITE_STATIC);
1541                    break;
1542
1543                case SQLITE_NULL:
1544                    sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1545                    break;
1546
1547                default:
1548                    php_sqlite3_error(stmt_obj->db_obj, "Unknown parameter type: %pd for parameter %pd", param->type, param->param_number);
1549                    RETURN_FALSE;
1550            }
1551        } ZEND_HASH_FOREACH_END();
1552    }
1553
1554    return_code = sqlite3_step(stmt_obj->stmt);
1555
1556    switch (return_code) {
1557        case SQLITE_ROW: /* Valid Row */
1558        case SQLITE_DONE: /* Valid but no results */
1559        {
1560            sqlite3_reset(stmt_obj->stmt);
1561            object_init_ex(return_value, php_sqlite3_result_entry);
1562            result = Z_SQLITE3_RESULT_P(return_value);
1563
1564            result->is_prepared_statement = 1;
1565            result->db_obj = stmt_obj->db_obj;
1566            result->stmt_obj = stmt_obj;
1567            ZVAL_COPY(&result->stmt_obj_zval, object);
1568
1569            break;
1570        }
1571        case SQLITE_ERROR:
1572            sqlite3_reset(stmt_obj->stmt);
1573
1574        default:
1575            php_sqlite3_error(stmt_obj->db_obj, "Unable to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1576            zval_dtor(return_value);
1577            RETURN_FALSE;
1578    }
1579
1580    return;
1581}
1582/* }}} */
1583
1584/* {{{ proto int SQLite3Stmt::__construct(SQLite3 dbobject, String Statement)
1585   __constructor for SQLite3Stmt. */
1586PHP_METHOD(sqlite3stmt, __construct)
1587{
1588    php_sqlite3_stmt *stmt_obj;
1589    php_sqlite3_db_object *db_obj;
1590    zval *object = getThis();
1591    zval *db_zval;
1592    zend_string *sql;
1593    int errcode;
1594    zend_error_handling error_handling;
1595    php_sqlite3_free_list *free_item;
1596
1597    stmt_obj = Z_SQLITE3_STMT_P(object);
1598
1599    if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "OS", &db_zval, php_sqlite3_sc_entry, &sql) == FAILURE) {
1600        return;
1601    }
1602
1603    db_obj = Z_SQLITE3_DB_P(db_zval);
1604
1605    zend_replace_error_handling(EH_THROW, NULL, &error_handling);
1606    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1607    zend_restore_error_handling(&error_handling);
1608
1609    if (!sql->len) {
1610        RETURN_FALSE;
1611    }
1612
1613    stmt_obj->db_obj = db_obj;
1614    ZVAL_COPY(&stmt_obj->db_obj_zval, db_zval);
1615
1616    errcode = sqlite3_prepare_v2(db_obj->db, sql->val, sql->len, &(stmt_obj->stmt), NULL);
1617    if (errcode != SQLITE_OK) {
1618        php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
1619        zval_dtor(return_value);
1620        RETURN_FALSE;
1621    }
1622    stmt_obj->initialised = 1;
1623
1624    free_item = emalloc(sizeof(php_sqlite3_free_list));
1625    free_item->stmt_obj = stmt_obj;
1626    //??  free_item->stmt_obj_zval = getThis();
1627    ZVAL_COPY_VALUE(&free_item->stmt_obj_zval, object);
1628
1629    zend_llist_add_element(&(db_obj->free_list), &free_item);
1630}
1631/* }}} */
1632
1633/* {{{ proto int SQLite3Result::numColumns()
1634   Number of columns in the result set. */
1635PHP_METHOD(sqlite3result, numColumns)
1636{
1637    php_sqlite3_result *result_obj;
1638    zval *object = getThis();
1639    result_obj = Z_SQLITE3_RESULT_P(object);
1640
1641    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1642
1643    if (zend_parse_parameters_none() == FAILURE) {
1644        return;
1645    }
1646
1647    RETURN_LONG(sqlite3_column_count(result_obj->stmt_obj->stmt));
1648}
1649/* }}} */
1650
1651/* {{{ proto string SQLite3Result::columnName(int column)
1652   Returns the name of the nth column. */
1653PHP_METHOD(sqlite3result, columnName)
1654{
1655    php_sqlite3_result *result_obj;
1656    zval *object = getThis();
1657    zend_long column = 0;
1658    char *column_name;
1659    result_obj = Z_SQLITE3_RESULT_P(object);
1660
1661    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1662
1663    if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &column) == FAILURE) {
1664        return;
1665    }
1666    column_name = (char*) sqlite3_column_name(result_obj->stmt_obj->stmt, column);
1667
1668    if (column_name == NULL) {
1669        RETURN_FALSE;
1670    }
1671
1672    RETVAL_STRING(column_name);
1673}
1674/* }}} */
1675
1676/* {{{ proto int SQLite3Result::columnType(int column)
1677   Returns the type of the nth column. */
1678PHP_METHOD(sqlite3result, columnType)
1679{
1680    php_sqlite3_result *result_obj;
1681    zval *object = getThis();
1682    zend_long column = 0;
1683    result_obj = Z_SQLITE3_RESULT_P(object);
1684
1685    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1686
1687    if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &column) == FAILURE) {
1688        return;
1689    }
1690
1691    if (result_obj->complete) {
1692        RETURN_FALSE;
1693    }
1694
1695    RETURN_LONG(sqlite3_column_type(result_obj->stmt_obj->stmt, column));
1696}
1697/* }}} */
1698
1699/* {{{ proto array SQLite3Result::fetchArray([int mode])
1700   Fetch a result row as both an associative or numerically indexed array or both. */
1701PHP_METHOD(sqlite3result, fetchArray)
1702{
1703    php_sqlite3_result *result_obj;
1704    zval *object = getThis();
1705    int i, ret;
1706    zend_long mode = PHP_SQLITE3_BOTH;
1707    result_obj = Z_SQLITE3_RESULT_P(object);
1708
1709    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1710
1711    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &mode) == FAILURE) {
1712        return;
1713    }
1714
1715    ret = sqlite3_step(result_obj->stmt_obj->stmt);
1716    switch (ret) {
1717        case SQLITE_ROW:
1718            /* If there was no return value then just skip fetching */
1719            if (!USED_RET()) {
1720                return;
1721            }
1722
1723            array_init(return_value);
1724
1725            for (i = 0; i < sqlite3_data_count(result_obj->stmt_obj->stmt); i++) {
1726                zval data;
1727
1728                sqlite_value_to_zval(result_obj->stmt_obj->stmt, i, &data);
1729
1730                if (mode & PHP_SQLITE3_NUM) {
1731                    add_index_zval(return_value, i, &data);
1732                }
1733
1734                if (mode & PHP_SQLITE3_ASSOC) {
1735                    if (mode & PHP_SQLITE3_NUM) {
1736                        if (Z_REFCOUNTED(data)) {
1737                            Z_ADDREF(data);
1738                        }
1739                    }
1740                    add_assoc_zval(return_value, (char*)sqlite3_column_name(result_obj->stmt_obj->stmt, i), &data);
1741                }
1742            }
1743            break;
1744
1745        case SQLITE_DONE:
1746            result_obj->complete = 1;
1747            RETURN_FALSE;
1748            break;
1749
1750        default:
1751            php_sqlite3_error(result_obj->db_obj, "Unable to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(result_obj->stmt_obj->stmt)));
1752    }
1753}
1754/* }}} */
1755
1756/* {{{ proto bool SQLite3Result::reset()
1757   Resets the result set back to the first row. */
1758PHP_METHOD(sqlite3result, reset)
1759{
1760    php_sqlite3_result *result_obj;
1761    zval *object = getThis();
1762    result_obj = Z_SQLITE3_RESULT_P(object);
1763
1764    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1765
1766    if (zend_parse_parameters_none() == FAILURE) {
1767        return;
1768    }
1769
1770    if (sqlite3_reset(result_obj->stmt_obj->stmt) != SQLITE_OK) {
1771        RETURN_FALSE;
1772    }
1773
1774    result_obj->complete = 0;
1775
1776    RETURN_TRUE;
1777}
1778/* }}} */
1779
1780/* {{{ proto bool SQLite3Result::finalize()
1781   Closes the result set. */
1782PHP_METHOD(sqlite3result, finalize)
1783{
1784    php_sqlite3_result *result_obj;
1785    zval *object = getThis();
1786    result_obj = Z_SQLITE3_RESULT_P(object);
1787
1788    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1789
1790    if (zend_parse_parameters_none() == FAILURE) {
1791        return;
1792    }
1793
1794    /* We need to finalize an internal statement */
1795    if (result_obj->is_prepared_statement == 0) {
1796        zend_llist_del_element(&(result_obj->db_obj->free_list), &result_obj->stmt_obj_zval,
1797            (int (*)(void *, void *)) php_sqlite3_compare_stmt_zval_free);
1798    } else {
1799        sqlite3_reset(result_obj->stmt_obj->stmt);
1800    }
1801
1802    RETURN_TRUE;
1803}
1804/* }}} */
1805
1806/* {{{ proto int SQLite3Result::__construct()
1807   __constructor for SQLite3Result. */
1808PHP_METHOD(sqlite3result, __construct)
1809{
1810    zend_throw_exception(zend_exception_get_default(), "SQLite3Result cannot be directly instantiated", 0);
1811}
1812/* }}} */
1813
1814/* {{{ arginfo */
1815ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_open, 0)
1816    ZEND_ARG_INFO(0, filename)
1817    ZEND_ARG_INFO(0, flags)
1818    ZEND_ARG_INFO(0, encryption_key)
1819ZEND_END_ARG_INFO()
1820
1821ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_busytimeout, 0)
1822    ZEND_ARG_INFO(0, ms)
1823ZEND_END_ARG_INFO()
1824
1825#ifndef SQLITE_OMIT_LOAD_EXTENSION
1826ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_loadextension, 0)
1827    ZEND_ARG_INFO(0, shared_library)
1828ZEND_END_ARG_INFO()
1829#endif
1830
1831ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_escapestring, 0, 0, 1)
1832    ZEND_ARG_INFO(0, value)
1833ZEND_END_ARG_INFO()
1834
1835ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_query, 0, 0, 1)
1836    ZEND_ARG_INFO(0, query)
1837ZEND_END_ARG_INFO()
1838
1839ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_querysingle, 0, 0, 1)
1840    ZEND_ARG_INFO(0, query)
1841    ZEND_ARG_INFO(0, entire_row)
1842ZEND_END_ARG_INFO()
1843
1844ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createfunction, 0, 0, 2)
1845    ZEND_ARG_INFO(0, name)
1846    ZEND_ARG_INFO(0, callback)
1847    ZEND_ARG_INFO(0, argument_count)
1848ZEND_END_ARG_INFO()
1849
1850ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createaggregate, 0, 0, 3)
1851    ZEND_ARG_INFO(0, name)
1852    ZEND_ARG_INFO(0, step_callback)
1853    ZEND_ARG_INFO(0, final_callback)
1854    ZEND_ARG_INFO(0, argument_count)
1855ZEND_END_ARG_INFO()
1856
1857ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createcollation, 0, 0, 2)
1858    ZEND_ARG_INFO(0, name)
1859    ZEND_ARG_INFO(0, callback)
1860ZEND_END_ARG_INFO()
1861
1862ZEND_BEGIN_ARG_INFO_EX(argingo_sqlite3_openblob, 0, 0, 3)
1863    ZEND_ARG_INFO(0, table)
1864    ZEND_ARG_INFO(0, column)
1865    ZEND_ARG_INFO(0, rowid)
1866    ZEND_ARG_INFO(0, dbname)
1867ZEND_END_ARG_INFO()
1868
1869ZEND_BEGIN_ARG_INFO_EX(argingo_sqlite3_enableexceptions, 0, 0, 1)
1870    ZEND_ARG_INFO(0, enableExceptions)
1871ZEND_END_ARG_INFO()
1872
1873ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_bindparam, 0, 0, 2)
1874    ZEND_ARG_INFO(0, param_number)
1875    ZEND_ARG_INFO(1, param)
1876    ZEND_ARG_INFO(0, type)
1877ZEND_END_ARG_INFO()
1878
1879ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_bindvalue, 0, 0, 2)
1880    ZEND_ARG_INFO(0, param_number)
1881    ZEND_ARG_INFO(0, param)
1882    ZEND_ARG_INFO(0, type)
1883ZEND_END_ARG_INFO()
1884
1885ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_construct, 0, 0, 1)
1886    ZEND_ARG_INFO(0, sqlite3)
1887ZEND_END_ARG_INFO()
1888
1889ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_columnname, 0, 0, 1)
1890    ZEND_ARG_INFO(0, column_number)
1891ZEND_END_ARG_INFO()
1892
1893ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_columntype, 0, 0, 1)
1894    ZEND_ARG_INFO(0, column_number)
1895ZEND_END_ARG_INFO()
1896
1897ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_fetcharray, 0, 0, 0)
1898    ZEND_ARG_INFO(0, mode)
1899ZEND_END_ARG_INFO()
1900
1901ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_void, 0)
1902ZEND_END_ARG_INFO()
1903/* }}} */
1904
1905/* {{{ php_sqlite3_class_methods */
1906static zend_function_entry php_sqlite3_class_methods[] = {
1907    PHP_ME(sqlite3,     open,               arginfo_sqlite3_open, ZEND_ACC_PUBLIC)
1908    PHP_ME(sqlite3,     close,              arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1909    PHP_ME(sqlite3,     exec,               arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
1910    PHP_ME(sqlite3,     version,            arginfo_sqlite3_void, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
1911    PHP_ME(sqlite3,     lastInsertRowID,    arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1912    PHP_ME(sqlite3,     lastErrorCode,      arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1913    PHP_ME(sqlite3,     lastErrorMsg,       arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1914    PHP_ME(sqlite3,     busyTimeout,        arginfo_sqlite3_busytimeout, ZEND_ACC_PUBLIC)
1915#ifndef SQLITE_OMIT_LOAD_EXTENSION
1916    PHP_ME(sqlite3,     loadExtension,      arginfo_sqlite3_loadextension, ZEND_ACC_PUBLIC)
1917#endif
1918    PHP_ME(sqlite3,     changes,            arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1919    PHP_ME(sqlite3,     escapeString,       arginfo_sqlite3_escapestring, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
1920    PHP_ME(sqlite3,     prepare,            arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
1921    PHP_ME(sqlite3,     query,              arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
1922    PHP_ME(sqlite3,     querySingle,        arginfo_sqlite3_querysingle, ZEND_ACC_PUBLIC)
1923    PHP_ME(sqlite3,     createFunction,     arginfo_sqlite3_createfunction, ZEND_ACC_PUBLIC)
1924    PHP_ME(sqlite3,     createAggregate,    arginfo_sqlite3_createaggregate, ZEND_ACC_PUBLIC)
1925    PHP_ME(sqlite3,     createCollation,    arginfo_sqlite3_createcollation, ZEND_ACC_PUBLIC)
1926    PHP_ME(sqlite3,     openBlob,           argingo_sqlite3_openblob, ZEND_ACC_PUBLIC)
1927    PHP_ME(sqlite3,     enableExceptions,   argingo_sqlite3_enableexceptions, ZEND_ACC_PUBLIC)
1928    /* Aliases */
1929    PHP_MALIAS(sqlite3, __construct, open, arginfo_sqlite3_open, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
1930    PHP_FE_END
1931};
1932/* }}} */
1933
1934/* {{{ php_sqlite3_stmt_class_methods */
1935static zend_function_entry php_sqlite3_stmt_class_methods[] = {
1936    PHP_ME(sqlite3stmt, paramCount, arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1937    PHP_ME(sqlite3stmt, close,      arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1938    PHP_ME(sqlite3stmt, reset,      arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1939    PHP_ME(sqlite3stmt, clear,      arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1940    PHP_ME(sqlite3stmt, execute,    arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1941    PHP_ME(sqlite3stmt, bindParam,  arginfo_sqlite3stmt_bindparam, ZEND_ACC_PUBLIC)
1942    PHP_ME(sqlite3stmt, bindValue,  arginfo_sqlite3stmt_bindvalue, ZEND_ACC_PUBLIC)
1943    PHP_ME(sqlite3stmt, readOnly,   arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1944    PHP_ME(sqlite3stmt, __construct, arginfo_sqlite3stmt_construct, ZEND_ACC_PRIVATE|ZEND_ACC_CTOR)
1945    PHP_FE_END
1946};
1947/* }}} */
1948
1949/* {{{ php_sqlite3_result_class_methods */
1950static zend_function_entry php_sqlite3_result_class_methods[] = {
1951    PHP_ME(sqlite3result, numColumns,       arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1952    PHP_ME(sqlite3result, columnName,       arginfo_sqlite3result_columnname, ZEND_ACC_PUBLIC)
1953    PHP_ME(sqlite3result, columnType,       arginfo_sqlite3result_columntype, ZEND_ACC_PUBLIC)
1954    PHP_ME(sqlite3result, fetchArray,       arginfo_sqlite3result_fetcharray, ZEND_ACC_PUBLIC)
1955    PHP_ME(sqlite3result, reset,            arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1956    PHP_ME(sqlite3result, finalize,         arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1957    PHP_ME(sqlite3result, __construct,      arginfo_sqlite3_void, ZEND_ACC_PRIVATE|ZEND_ACC_CTOR)
1958    PHP_FE_END
1959};
1960/* }}} */
1961
1962/* {{{ Authorization Callback
1963*/
1964static int php_sqlite3_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4, const char *arg5, const char *arg6)
1965{
1966    switch (access_type) {
1967        case SQLITE_ATTACH:
1968        {
1969            if (memcmp(arg3, ":memory:", sizeof(":memory:")) && *arg3) {
1970
1971#if PHP_API_VERSION < 20100412
1972                if (PG(safe_mode) && (!php_checkuid(arg3, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
1973                    return SQLITE_DENY;
1974                }
1975#endif
1976
1977                if (php_check_open_basedir(arg3)) {
1978                    return SQLITE_DENY;
1979                }
1980            }
1981            return SQLITE_OK;
1982        }
1983
1984        default:
1985            /* access allowed */
1986            return SQLITE_OK;
1987    }
1988}
1989/* }}} */
1990
1991/* {{{ php_sqlite3_free_list_dtor
1992*/
1993static void php_sqlite3_free_list_dtor(void **item)
1994{
1995    php_sqlite3_free_list *free_item = (php_sqlite3_free_list *)*item;
1996
1997    if (free_item->stmt_obj && free_item->stmt_obj->initialised) {
1998        sqlite3_finalize(free_item->stmt_obj->stmt);
1999        free_item->stmt_obj->initialised = 0;
2000    }
2001    efree(*item);
2002}
2003/* }}} */
2004
2005static int php_sqlite3_compare_stmt_zval_free(php_sqlite3_free_list **free_list, zval *statement ) /* {{{ */
2006{
2007    return  ((*free_list)->stmt_obj->initialised && Z_PTR_P(statement) == Z_PTR((*free_list)->stmt_obj_zval));
2008}
2009/* }}} */
2010
2011static int php_sqlite3_compare_stmt_free( php_sqlite3_free_list **free_list, sqlite3_stmt *statement ) /* {{{ */
2012{
2013    return ((*free_list)->stmt_obj->initialised && statement == (*free_list)->stmt_obj->stmt);
2014}
2015/* }}} */
2016
2017static void php_sqlite3_object_free_storage(zend_object *object) /* {{{ */
2018{
2019    php_sqlite3_db_object *intern = php_sqlite3_db_from_obj(object);
2020    php_sqlite3_func *func;
2021    php_sqlite3_collation *collation;
2022
2023    if (!intern) {
2024        return;
2025    }
2026
2027    while (intern->funcs) {
2028        func = intern->funcs;
2029        intern->funcs = func->next;
2030        if (intern->initialised && intern->db) {
2031            sqlite3_create_function(intern->db, func->func_name, func->argc, SQLITE_UTF8, func, NULL, NULL, NULL);
2032        }
2033
2034        efree((char*)func->func_name);
2035
2036        if (!Z_ISUNDEF(func->func)) {
2037            zval_ptr_dtor(&func->func);
2038        }
2039        if (!Z_ISUNDEF(func->step)) {
2040            zval_ptr_dtor(&func->step);
2041        }
2042        if (!Z_ISUNDEF(func->fini)) {
2043            zval_ptr_dtor(&func->fini);
2044        }
2045        efree(func);
2046    }
2047
2048    while (intern->collations){
2049        collation = intern->collations;
2050        intern->collations = collation->next;
2051        if (intern->initialised && intern->db){
2052            sqlite3_create_collation(intern->db, collation->collation_name, SQLITE_UTF8, NULL, NULL);
2053        }
2054        efree((char*)collation->collation_name);
2055        if (!Z_ISUNDEF(collation->cmp_func)) {
2056            zval_ptr_dtor(&collation->cmp_func);
2057        }
2058        efree(collation);
2059    }
2060
2061    if (intern->initialised && intern->db) {
2062        sqlite3_close(intern->db);
2063        intern->initialised = 0;
2064    }
2065
2066    zend_object_std_dtor(&intern->zo);
2067}
2068/* }}} */
2069
2070static void php_sqlite3_stmt_object_free_storage(zend_object *object) /* {{{ */
2071{
2072    php_sqlite3_stmt *intern = php_sqlite3_stmt_from_obj(object);
2073
2074    if (!intern) {
2075        return;
2076    }
2077
2078    if (intern->bound_params) {
2079        zend_hash_destroy(intern->bound_params);
2080        FREE_HASHTABLE(intern->bound_params);
2081        intern->bound_params = NULL;
2082    }
2083
2084    if (intern->initialised) {
2085        zend_llist_del_element(&(intern->db_obj->free_list), intern->stmt,
2086            (int (*)(void *, void *)) php_sqlite3_compare_stmt_free);
2087    }
2088
2089    if (!Z_ISUNDEF(intern->db_obj_zval)) {
2090        zval_ptr_dtor(&intern->db_obj_zval);
2091    }
2092
2093    zend_object_std_dtor(&intern->zo);
2094}
2095/* }}} */
2096
2097static void php_sqlite3_result_object_free_storage(zend_object *object) /* {{{ */
2098{
2099    php_sqlite3_result *intern = php_sqlite3_result_from_obj(object);
2100
2101    if (!intern) {
2102        return;
2103    }
2104
2105    if (!Z_ISNULL(intern->stmt_obj_zval)) {
2106        if (intern->stmt_obj->initialised) {
2107            sqlite3_reset(intern->stmt_obj->stmt);
2108        }
2109
2110        zval_ptr_dtor(&intern->stmt_obj_zval);
2111    }
2112
2113    zend_object_std_dtor(&intern->zo);
2114}
2115/* }}} */
2116
2117static zend_object *php_sqlite3_object_new(zend_class_entry *class_type) /* {{{ */
2118{
2119    php_sqlite3_db_object *intern;
2120
2121    /* Allocate memory for it */
2122    intern = ecalloc(1, sizeof(php_sqlite3_db_object) + zend_object_properties_size(class_type));
2123
2124    /* Need to keep track of things to free */
2125    zend_llist_init(&(intern->free_list),  sizeof(php_sqlite3_free_list *), (llist_dtor_func_t)php_sqlite3_free_list_dtor, 0);
2126
2127    zend_object_std_init(&intern->zo, class_type);
2128    object_properties_init(&intern->zo, class_type);
2129
2130    intern->zo.handlers = &sqlite3_object_handlers;
2131
2132    return &intern->zo;
2133}
2134/* }}} */
2135
2136static zend_object *php_sqlite3_stmt_object_new(zend_class_entry *class_type) /* {{{ */
2137{
2138    php_sqlite3_stmt *intern;
2139
2140    /* Allocate memory for it */
2141    intern = ecalloc(1, sizeof(php_sqlite3_stmt) + zend_object_properties_size(class_type));
2142
2143    zend_object_std_init(&intern->zo, class_type);
2144    object_properties_init(&intern->zo, class_type);
2145
2146    intern->zo.handlers = &sqlite3_stmt_object_handlers;
2147
2148    return &intern->zo;
2149}
2150/* }}} */
2151
2152static zend_object *php_sqlite3_result_object_new(zend_class_entry *class_type) /* {{{ */
2153{
2154    php_sqlite3_result *intern;
2155
2156    /* Allocate memory for it */
2157    intern = ecalloc(1, sizeof(php_sqlite3_result) + zend_object_properties_size(class_type));
2158
2159    zend_object_std_init(&intern->zo, class_type);
2160    object_properties_init(&intern->zo, class_type);
2161
2162    intern->zo.handlers = &sqlite3_result_object_handlers;
2163
2164    return &intern->zo;
2165}
2166/* }}} */
2167
2168static void sqlite3_param_dtor(zval *data) /* {{{ */
2169{
2170    struct php_sqlite3_bound_param *param = (struct php_sqlite3_bound_param*)Z_PTR_P(data);
2171
2172    if (param->name) {
2173        zend_string_release(param->name);
2174    }
2175
2176    if (!Z_ISNULL(param->parameter)) {
2177        zval_ptr_dtor(&(param->parameter));
2178        ZVAL_UNDEF(&param->parameter);
2179    }
2180    efree(param);
2181}
2182/* }}} */
2183
2184/* {{{ PHP_MINIT_FUNCTION
2185*/
2186PHP_MINIT_FUNCTION(sqlite3)
2187{
2188    zend_class_entry ce;
2189
2190#if defined(ZTS)
2191    /* Refuse to load if this wasn't a threasafe library loaded */
2192    if (!sqlite3_threadsafe()) {
2193        php_error_docref(NULL, E_WARNING, "A thread safe version of SQLite is required when using a thread safe version of PHP.");
2194        return FAILURE;
2195    }
2196#endif
2197
2198    memcpy(&sqlite3_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
2199    memcpy(&sqlite3_stmt_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
2200    memcpy(&sqlite3_result_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
2201
2202    /* Register SQLite 3 Class */
2203    INIT_CLASS_ENTRY(ce, "SQLite3", php_sqlite3_class_methods);
2204    ce.create_object = php_sqlite3_object_new;
2205    sqlite3_object_handlers.offset = XtOffsetOf(php_sqlite3_db_object, zo);
2206    sqlite3_object_handlers.clone_obj = NULL;
2207    sqlite3_object_handlers.free_obj = php_sqlite3_object_free_storage;
2208    php_sqlite3_sc_entry = zend_register_internal_class(&ce);
2209
2210    /* Register SQLite 3 Prepared Statement Class */
2211    INIT_CLASS_ENTRY(ce, "SQLite3Stmt", php_sqlite3_stmt_class_methods);
2212    ce.create_object = php_sqlite3_stmt_object_new;
2213    sqlite3_stmt_object_handlers.offset = XtOffsetOf(php_sqlite3_stmt, zo);
2214    sqlite3_stmt_object_handlers.clone_obj = NULL;
2215    sqlite3_stmt_object_handlers.free_obj = php_sqlite3_stmt_object_free_storage;
2216    php_sqlite3_stmt_entry = zend_register_internal_class(&ce);
2217
2218    /* Register SQLite 3 Result Class */
2219    INIT_CLASS_ENTRY(ce, "SQLite3Result", php_sqlite3_result_class_methods);
2220    ce.create_object = php_sqlite3_result_object_new;
2221    sqlite3_result_object_handlers.offset = XtOffsetOf(php_sqlite3_result, zo);
2222    sqlite3_result_object_handlers.clone_obj = NULL;
2223    sqlite3_result_object_handlers.free_obj = php_sqlite3_result_object_free_storage;
2224    php_sqlite3_result_entry = zend_register_internal_class(&ce);
2225
2226    REGISTER_INI_ENTRIES();
2227
2228    REGISTER_LONG_CONSTANT("SQLITE3_ASSOC", PHP_SQLITE3_ASSOC, CONST_CS | CONST_PERSISTENT);
2229    REGISTER_LONG_CONSTANT("SQLITE3_NUM", PHP_SQLITE3_NUM, CONST_CS | CONST_PERSISTENT);
2230    REGISTER_LONG_CONSTANT("SQLITE3_BOTH", PHP_SQLITE3_BOTH, CONST_CS | CONST_PERSISTENT);
2231
2232    REGISTER_LONG_CONSTANT("SQLITE3_INTEGER", SQLITE_INTEGER, CONST_CS | CONST_PERSISTENT);
2233    REGISTER_LONG_CONSTANT("SQLITE3_FLOAT", SQLITE_FLOAT, CONST_CS | CONST_PERSISTENT);
2234    REGISTER_LONG_CONSTANT("SQLITE3_TEXT", SQLITE3_TEXT, CONST_CS | CONST_PERSISTENT);
2235    REGISTER_LONG_CONSTANT("SQLITE3_BLOB", SQLITE_BLOB, CONST_CS | CONST_PERSISTENT);
2236    REGISTER_LONG_CONSTANT("SQLITE3_NULL", SQLITE_NULL, CONST_CS | CONST_PERSISTENT);
2237
2238    REGISTER_LONG_CONSTANT("SQLITE3_OPEN_READONLY", SQLITE_OPEN_READONLY, CONST_CS | CONST_PERSISTENT);
2239    REGISTER_LONG_CONSTANT("SQLITE3_OPEN_READWRITE", SQLITE_OPEN_READWRITE, CONST_CS | CONST_PERSISTENT);
2240    REGISTER_LONG_CONSTANT("SQLITE3_OPEN_CREATE", SQLITE_OPEN_CREATE, CONST_CS | CONST_PERSISTENT);
2241
2242    return SUCCESS;
2243}
2244/* }}} */
2245
2246/* {{{ PHP_MSHUTDOWN_FUNCTION
2247*/
2248PHP_MSHUTDOWN_FUNCTION(sqlite3)
2249{
2250    UNREGISTER_INI_ENTRIES();
2251
2252    return SUCCESS;
2253}
2254/* }}} */
2255
2256/* {{{ PHP_MINFO_FUNCTION
2257*/
2258PHP_MINFO_FUNCTION(sqlite3)
2259{
2260    php_info_print_table_start();
2261    php_info_print_table_header(2, "SQLite3 support", "enabled");
2262    php_info_print_table_row(2, "SQLite3 module version", PHP_SQLITE3_VERSION);
2263    php_info_print_table_row(2, "SQLite Library", sqlite3_libversion());
2264    php_info_print_table_end();
2265
2266    DISPLAY_INI_ENTRIES();
2267}
2268/* }}} */
2269
2270/* {{{ PHP_GINIT_FUNCTION
2271*/
2272static PHP_GINIT_FUNCTION(sqlite3)
2273{
2274#if defined(COMPILE_DL_SQLITE3) && defined(ZTS)
2275    ZEND_TSRMLS_CACHE_UPDATE();
2276#endif
2277    memset(sqlite3_globals, 0, sizeof(*sqlite3_globals));
2278}
2279/* }}} */
2280
2281/* {{{ sqlite3_module_entry
2282*/
2283zend_module_entry sqlite3_module_entry = {
2284    STANDARD_MODULE_HEADER,
2285    "sqlite3",
2286    NULL,
2287    PHP_MINIT(sqlite3),
2288    PHP_MSHUTDOWN(sqlite3),
2289    NULL,
2290    NULL,
2291    PHP_MINFO(sqlite3),
2292    PHP_SQLITE3_VERSION,
2293    PHP_MODULE_GLOBALS(sqlite3),
2294    PHP_GINIT(sqlite3),
2295    NULL,
2296    NULL,
2297    STANDARD_MODULE_PROPERTIES_EX
2298};
2299/* }}} */
2300
2301#ifdef COMPILE_DL_SQLITE3
2302#ifdef ZTS
2303ZEND_TSRMLS_CACHE_DEFINE();
2304#endif
2305ZEND_GET_MODULE(sqlite3)
2306#endif
2307
2308/*
2309 * Local variables:
2310 * tab-width: 4
2311 * c-basic-offset: 4
2312 * End:
2313 * vim600: sw=4 ts=4 fdm=marker
2314 * vim<600: sw=4 ts=4
2315 */
2316