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