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