1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 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 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
22 
23 #include "php.h"
24 #include "php_ini.h"
25 #include "ext/standard/info.h"
26 #include "php_sqlite3.h"
27 #include "php_sqlite3_structs.h"
28 #include "main/SAPI.h"
29 
30 #include <sqlite3.h>
31 
32 #include "zend_exceptions.h"
33 #include "zend_interfaces.h"
34 #include "SAPI.h"
35 
36 ZEND_DECLARE_MODULE_GLOBALS(sqlite3)
37 
38 static PHP_GINIT_FUNCTION(sqlite3);
39 static int php_sqlite3_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4, const char *arg5, const char *arg6);
40 static void sqlite3_param_dtor(zval *data);
41 static int php_sqlite3_compare_stmt_zval_free(php_sqlite3_free_list **free_list, zval *statement);
42 
43 /* {{{ Error Handler
44 */
php_sqlite3_error(php_sqlite3_db_object *db_obj, char *format, ...)45 static void php_sqlite3_error(php_sqlite3_db_object *db_obj, char *format, ...)
46 {
47 	va_list arg;
48 	char 	*message;
49 
50 	va_start(arg, format);
51 	vspprintf(&message, 0, format, arg);
52 	va_end(arg);
53 
54 	if (db_obj && db_obj->exception) {
55 		zend_throw_exception(zend_ce_exception, message, 0);
56 	} else {
57 		php_error_docref(NULL, E_WARNING, "%s", message);
58 	}
59 
60 	if (message) {
61 		efree(message);
62 	}
63 }
64 /* }}} */
65 
66 #define SQLITE3_CHECK_INITIALIZED(db_obj, member, class_name) \
67 	if (!(db_obj) || !(member)) { \
68 		php_sqlite3_error(db_obj, "The " #class_name " object has not been correctly initialised"); \
69 		RETURN_FALSE; \
70 	}
71 
72 #define SQLITE3_CHECK_INITIALIZED_STMT(member, class_name) \
73 	if (!(member)) { \
74 		php_error_docref(NULL, E_WARNING, "The " #class_name " object has not been correctly initialised"); \
75 		RETURN_FALSE; \
76 	}
77 
78 /* {{{ PHP_INI
79 */
80 PHP_INI_BEGIN()
81 	STD_PHP_INI_ENTRY("sqlite3.extension_dir",  NULL, PHP_INI_SYSTEM, OnUpdateString, extension_dir, zend_sqlite3_globals, sqlite3_globals)
82 #if SQLITE_VERSION_NUMBER >= 3026000
83 	STD_PHP_INI_ENTRY("sqlite3.defensive",  "1", PHP_INI_SYSTEM, OnUpdateBool, dbconfig_defensive, zend_sqlite3_globals, sqlite3_globals)
84 #endif
85 PHP_INI_END()
86 /* }}} */
87 
88 /* Handlers */
89 static zend_object_handlers sqlite3_object_handlers;
90 static zend_object_handlers sqlite3_stmt_object_handlers;
91 static zend_object_handlers sqlite3_result_object_handlers;
92 
93 /* Class entries */
94 zend_class_entry *php_sqlite3_sc_entry;
95 zend_class_entry *php_sqlite3_stmt_entry;
96 zend_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. */
PHP_METHODnull100 PHP_METHOD(sqlite3, open)
101 {
102 	php_sqlite3_db_object *db_obj;
103 	zval *object = ZEND_THIS;
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 	int rc;
108 
109 	db_obj = Z_SQLITE3_DB_P(object);
110 
111 	if (FAILURE == zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p|ls", &filename, &filename_len, &flags, &encryption_key, &encryption_key_len)) {
112 		return;
113 	}
114 
115 	if (db_obj->initialised) {
116 		zend_throw_exception(zend_ce_exception, "Already initialised DB Object", 0);
117 		return;
118 	}
119 
120 	if (filename_len != 0 && (filename_len != sizeof(":memory:")-1 ||
121 			memcmp(filename, ":memory:", sizeof(":memory:")-1) != 0)) {
122 		if (!(fullpath = expand_filepath(filename, NULL))) {
123 			zend_throw_exception(zend_ce_exception, "Unable to expand filepath", 0);
124 			return;
125 		}
126 
127 		if (php_check_open_basedir(fullpath)) {
128 			zend_throw_exception_ex(zend_ce_exception, 0, "open_basedir prohibits opening %s", fullpath);
129 			efree(fullpath);
130 			return;
131 		}
132 	} else {
133 		/* filename equals "" or ":memory:" */
134 		fullpath = filename;
135 	}
136 
137 	rc = sqlite3_open_v2(fullpath, &(db_obj->db), flags, NULL);
138 	if (rc != SQLITE_OK) {
139 		zend_throw_exception_ex(zend_ce_exception, 0, "Unable to open database: %s",
140 #ifdef HAVE_SQLITE3_ERRSTR
141 				db_obj->db ? sqlite3_errmsg(db_obj->db) : sqlite3_errstr(rc));
142 #else
143 				db_obj->db ? sqlite3_errmsg(db_obj->db) : "");
144 #endif
145 		sqlite3_close(db_obj->db);
146 		if (fullpath != filename) {
147 			efree(fullpath);
148 		}
149 		return;
150 	}
151 
152 #if SQLITE_HAS_CODEC
153 	if (encryption_key_len > 0) {
154 		if (sqlite3_key(db_obj->db, encryption_key, encryption_key_len) != SQLITE_OK) {
155 			zend_throw_exception_ex(zend_ce_exception, 0, "Unable to open database: %s", sqlite3_errmsg(db_obj->db));
156 			sqlite3_close(db_obj->db);
157 			return;
158 		}
159 	}
160 #endif
161 
162 	db_obj->initialised = 1;
163 
164 	if (PG(open_basedir) && *PG(open_basedir)) {
165 		sqlite3_set_authorizer(db_obj->db, php_sqlite3_authorizer, NULL);
166 	}
167 
168 #if SQLITE_VERSION_NUMBER >= 3026000
169 	if (SQLITE3G(dbconfig_defensive)) {
170 		sqlite3_db_config(db_obj->db, SQLITE_DBCONFIG_DEFENSIVE, 1, NULL);
171 	}
172 #endif
173 
174 	if (fullpath != filename) {
175 		efree(fullpath);
176 	}
177 }
178 /* }}} */
179 
180 /* {{{ proto bool SQLite3::close()
181    Close a SQLite 3 Database. */
PHP_METHODnull182 PHP_METHOD(sqlite3, close)
183 {
184 	php_sqlite3_db_object *db_obj;
185 	zval *object = ZEND_THIS;
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. */
PHP_METHODnull211 PHP_METHOD(sqlite3, exec)
212 {
213 	php_sqlite3_db_object *db_obj;
214 	zval *object = ZEND_THIS;
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. */
PHP_METHODnull237 PHP_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. */
PHP_METHODnull254 PHP_METHOD(sqlite3, lastInsertRowID)
255 {
256 	php_sqlite3_db_object *db_obj;
257 	zval *object = ZEND_THIS;
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((zend_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. */
PHP_METHODnull272 PHP_METHOD(sqlite3, lastErrorCode)
273 {
274 	php_sqlite3_db_object *db_obj;
275 	zval *object = ZEND_THIS;
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 int SQLite3::lastExtendedErrorCode()
293    Returns the numeric extended result code of the most recent failed sqlite API call for the database connection. */
PHP_METHODnull294 PHP_METHOD(sqlite3, lastExtendedErrorCode)
295 {
296 	php_sqlite3_db_object *db_obj;
297 	zval *object = ZEND_THIS;
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_LONG(sqlite3_extended_errcode(db_obj->db));
308 	} else {
309 		RETURN_LONG(0);
310 	}
311 }
312 /* }}} */
313 
314 /* {{{ proto bool SQLite3::enableExtendedResultCodes([bool enable = true])
315     Turns on or off the extended result codes feature of SQLite. */
PHP_METHODnull316 PHP_METHOD(sqlite3, enableExtendedResultCodes)
317 {
318 	php_sqlite3_db_object *db_obj;
319 	zval *object = ZEND_THIS;
320 	zend_bool enable = 1;
321 	db_obj = Z_SQLITE3_DB_P(object);
322 	int ret;
323 
324 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->db, SQLite3)
325 
326 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &enable) == FAILURE) {
327 		return;
328 	}
329 
330 	if (db_obj->initialised) {
331 		ret = sqlite3_extended_result_codes(db_obj->db, enable ? 1 : 0);
332 		if (ret == SQLITE_OK)
333 		{
334 			RETURN_TRUE;
335 		}
336 	}
337 
338 	RETURN_FALSE;
339 }
340 /* }}} */
341 
342 /* {{{ proto string SQLite3::lastErrorMsg()
343    Returns english text describing the most recent failed sqlite API call for the database connection. */
PHP_METHODnull344 PHP_METHOD(sqlite3, lastErrorMsg)
345 {
346 	php_sqlite3_db_object *db_obj;
347 	zval *object = ZEND_THIS;
348 	db_obj = Z_SQLITE3_DB_P(object);
349 
350 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->db, SQLite3)
351 
352 	if (zend_parse_parameters_none() == FAILURE) {
353 		return;
354 	}
355 
356 	if (db_obj->initialised) {
357 		RETURN_STRING((char *)sqlite3_errmsg(db_obj->db));
358 	} else {
359 		RETURN_EMPTY_STRING();
360 	}
361 }
362 /* }}} */
363 
364 /* {{{ proto bool SQLite3::busyTimeout(int msecs)
365    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. */
PHP_METHODnull366 PHP_METHOD(sqlite3, busyTimeout)
367 {
368 	php_sqlite3_db_object *db_obj;
369 	zval *object = ZEND_THIS;
370 	zend_long ms;
371 #ifdef SQLITE_ENABLE_API_ARMOR
372 	int return_code;
373 #endif
374 	db_obj = Z_SQLITE3_DB_P(object);
375 
376 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
377 
378 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "l", &ms)) {
379 		return;
380 	}
381 
382 #ifdef SQLITE_ENABLE_API_ARMOR
383 	return_code = sqlite3_busy_timeout(db_obj->db, ms);
384 	if (return_code != SQLITE_OK) {
385 		php_sqlite3_error(db_obj, "Unable to set busy timeout: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
386 		RETURN_FALSE;
387 	}
388 #else
389 	php_ignore_value(sqlite3_busy_timeout(db_obj->db, ms));
390 #endif
391 
392 	RETURN_TRUE;
393 }
394 /* }}} */
395 
396 
397 #ifndef SQLITE_OMIT_LOAD_EXTENSION
398 /* {{{ proto bool SQLite3::loadExtension(String Shared Library)
399    Attempts to load an SQLite extension library. */
PHP_METHODnull400 PHP_METHOD(sqlite3, loadExtension)
401 {
402 	php_sqlite3_db_object *db_obj;
403 	zval *object = ZEND_THIS;
404 	char *extension, *lib_path, *extension_dir, *errtext = NULL;
405 	char fullpath[MAXPATHLEN];
406 	size_t extension_len, extension_dir_len;
407 	db_obj = Z_SQLITE3_DB_P(object);
408 
409 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
410 
411 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s", &extension, &extension_len)) {
412 		return;
413 	}
414 
415 #ifdef ZTS
416 	if ((strncmp(sapi_module.name, "cgi", 3) != 0) &&
417 		(strcmp(sapi_module.name, "cli") != 0) &&
418 		(strncmp(sapi_module.name, "embed", 5) != 0)
419 	) {		php_sqlite3_error(db_obj, "Not supported in multithreaded Web servers");
420 		RETURN_FALSE;
421 	}
422 #endif
423 
424 	if (!SQLITE3G(extension_dir)) {
425 		php_sqlite3_error(db_obj, "SQLite Extension are disabled");
426 		RETURN_FALSE;
427 	}
428 
429 	if (extension_len == 0) {
430 		php_sqlite3_error(db_obj, "Empty string as an extension");
431 		RETURN_FALSE;
432 	}
433 
434 	extension_dir = SQLITE3G(extension_dir);
435 	extension_dir_len = strlen(SQLITE3G(extension_dir));
436 
437 	if (IS_SLASH(extension_dir[extension_dir_len-1])) {
438 		spprintf(&lib_path, 0, "%s%s", extension_dir, extension);
439 	} else {
440 		spprintf(&lib_path, 0, "%s%c%s", extension_dir, DEFAULT_SLASH, extension);
441 	}
442 
443 	if (!VCWD_REALPATH(lib_path, fullpath)) {
444 		php_sqlite3_error(db_obj, "Unable to load extension at '%s'", lib_path);
445 		efree(lib_path);
446 		RETURN_FALSE;
447 	}
448 
449 	efree(lib_path);
450 
451 	if (strncmp(fullpath, extension_dir, extension_dir_len) != 0) {
452 		php_sqlite3_error(db_obj, "Unable to open extensions outside the defined directory");
453 		RETURN_FALSE;
454 	}
455 
456 	/* Extension loading should only be enabled for when we attempt to load */
457 	sqlite3_enable_load_extension(db_obj->db, 1);
458 	if (sqlite3_load_extension(db_obj->db, fullpath, 0, &errtext) != SQLITE_OK) {
459 		php_sqlite3_error(db_obj, "%s", errtext);
460 		sqlite3_free(errtext);
461 		sqlite3_enable_load_extension(db_obj->db, 0);
462 		RETURN_FALSE;
463 	}
464 	sqlite3_enable_load_extension(db_obj->db, 0);
465 
466 	RETURN_TRUE;
467 }
468 /* }}} */
469 #endif
470 
471 /* {{{ proto int SQLite3::changes()
472   Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement. */
PHP_METHODnull473 PHP_METHOD(sqlite3, changes)
474 {
475 	php_sqlite3_db_object *db_obj;
476 	zval *object = ZEND_THIS;
477 	db_obj = Z_SQLITE3_DB_P(object);
478 
479 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
480 
481 	if (zend_parse_parameters_none() == FAILURE) {
482 		return;
483 	}
484 
485 	RETURN_LONG(sqlite3_changes(db_obj->db));
486 }
487 /* }}} */
488 
489 /* {{{ proto String SQLite3::escapeString(String value)
490    Returns a string that has been properly escaped. */
PHP_METHODnull491 PHP_METHOD(sqlite3, escapeString)
492 {
493 	zend_string *sql;
494 	char *ret;
495 
496 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
497 		return;
498 	}
499 
500 	if (ZSTR_LEN(sql)) {
501 		ret = sqlite3_mprintf("%q", ZSTR_VAL(sql));
502 		if (ret) {
503 			RETVAL_STRING(ret);
504 			sqlite3_free(ret);
505 		}
506 	} else {
507 		RETURN_EMPTY_STRING();
508 	}
509 }
510 /* }}} */
511 
512 /* {{{ proto SQLite3Stmt SQLite3::prepare(String Query)
513    Returns a prepared SQL statement for execution. */
PHP_METHODnull514 PHP_METHOD(sqlite3, prepare)
515 {
516 	php_sqlite3_db_object *db_obj;
517 	php_sqlite3_stmt *stmt_obj;
518 	zval *object = ZEND_THIS;
519 	zend_string *sql;
520 	int errcode;
521 	php_sqlite3_free_list *free_item;
522 
523 	db_obj = Z_SQLITE3_DB_P(object);
524 
525 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
526 
527 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
528 		return;
529 	}
530 
531 	if (!ZSTR_LEN(sql)) {
532 		RETURN_FALSE;
533 	}
534 
535 	object_init_ex(return_value, php_sqlite3_stmt_entry);
536 	stmt_obj = Z_SQLITE3_STMT_P(return_value);
537 	stmt_obj->db_obj = db_obj;
538 	Z_ADDREF_P(object);
539 	ZVAL_OBJ(&stmt_obj->db_obj_zval, Z_OBJ_P(object));
540 
541 	errcode = sqlite3_prepare_v2(db_obj->db, ZSTR_VAL(sql), ZSTR_LEN(sql), &(stmt_obj->stmt), NULL);
542 	if (errcode != SQLITE_OK) {
543 		php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
544 		zval_ptr_dtor(return_value);
545 		RETURN_FALSE;
546 	}
547 
548 	stmt_obj->initialised = 1;
549 
550 	free_item = emalloc(sizeof(php_sqlite3_free_list));
551 	free_item->stmt_obj = stmt_obj;
552 	ZVAL_OBJ(&free_item->stmt_obj_zval, Z_OBJ_P(return_value));
553 
554 	zend_llist_add_element(&(db_obj->free_list), &free_item);
555 }
556 /* }}} */
557 
558 /* {{{ proto SQLite3Result SQLite3::query(String Query)
559    Returns true or false, for queries that return data it will return a SQLite3Result object. */
PHP_METHODnull560 PHP_METHOD(sqlite3, query)
561 {
562 	php_sqlite3_db_object *db_obj;
563 	php_sqlite3_result *result;
564 	php_sqlite3_stmt *stmt_obj;
565 	zval *object = ZEND_THIS;
566 	zval stmt;
567 	zend_string *sql;
568 	char *errtext = NULL;
569 	int return_code;
570 	db_obj = Z_SQLITE3_DB_P(object);
571 
572 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
573 
574 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
575 		return;
576 	}
577 
578 	if (!ZSTR_LEN(sql)) {
579 		RETURN_FALSE;
580 	}
581 
582 	/* If there was no return value then just execute the query */
583 	if (!USED_RET()) {
584 		if (sqlite3_exec(db_obj->db, ZSTR_VAL(sql), NULL, NULL, &errtext) != SQLITE_OK) {
585 			php_sqlite3_error(db_obj, "%s", errtext);
586 			sqlite3_free(errtext);
587 		}
588 		return;
589 	}
590 
591 	object_init_ex(&stmt, php_sqlite3_stmt_entry);
592 	stmt_obj = Z_SQLITE3_STMT_P(&stmt);
593 	stmt_obj->db_obj = db_obj;
594 	Z_ADDREF_P(object);
595 	ZVAL_OBJ(&stmt_obj->db_obj_zval, Z_OBJ_P(object));
596 
597 	return_code = sqlite3_prepare_v2(db_obj->db, ZSTR_VAL(sql), ZSTR_LEN(sql), &(stmt_obj->stmt), NULL);
598 	if (return_code != SQLITE_OK) {
599 		php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
600 		zval_ptr_dtor(&stmt);
601 		RETURN_FALSE;
602 	}
603 
604 	stmt_obj->initialised = 1;
605 
606 	object_init_ex(return_value, php_sqlite3_result_entry);
607 	result = Z_SQLITE3_RESULT_P(return_value);
608 	result->db_obj = db_obj;
609 	result->stmt_obj = stmt_obj;
610 	ZVAL_OBJ(&result->stmt_obj_zval, Z_OBJ(stmt));
611 
612 	return_code = sqlite3_step(result->stmt_obj->stmt);
613 
614 	switch (return_code) {
615 		case SQLITE_ROW: /* Valid Row */
616 		case SQLITE_DONE: /* Valid but no results */
617 		{
618 			php_sqlite3_free_list *free_item;
619 			free_item = emalloc(sizeof(php_sqlite3_free_list));
620 			free_item->stmt_obj = stmt_obj;
621 			free_item->stmt_obj_zval = stmt;
622 			zend_llist_add_element(&(db_obj->free_list), &free_item);
623 			sqlite3_reset(result->stmt_obj->stmt);
624 			break;
625 		}
626 		default:
627 			if (!EG(exception)) {
628 				php_sqlite3_error(db_obj, "Unable to execute statement: %s", sqlite3_errmsg(db_obj->db));
629 			}
630 			sqlite3_finalize(stmt_obj->stmt);
631 			stmt_obj->initialised = 0;
632 			zval_ptr_dtor(return_value);
633 			RETURN_FALSE;
634 	}
635 }
636 /* }}} */
637 
sqlite_value_to_zval(sqlite3_stmt *stmt, int column, zval *data)638 static void sqlite_value_to_zval(sqlite3_stmt *stmt, int column, zval *data) /* {{{ */
639 {
640 	sqlite3_int64 val;
641 
642 	switch (sqlite3_column_type(stmt, column)) {
643 		case SQLITE_INTEGER:
644 			val = sqlite3_column_int64(stmt, column);
645 #if LONG_MAX <= 2147483647
646 			if (val > ZEND_LONG_MAX || val < ZEND_LONG_MIN) {
647 				ZVAL_STRINGL(data, (char *)sqlite3_column_text(stmt, column), sqlite3_column_bytes(stmt, column));
648 			} else {
649 #endif
650 				ZVAL_LONG(data, (zend_long) val);
651 #if LONG_MAX <= 2147483647
652 			}
653 #endif
654 			break;
655 
656 		case SQLITE_FLOAT:
657 			ZVAL_DOUBLE(data, sqlite3_column_double(stmt, column));
658 			break;
659 
660 		case SQLITE_NULL:
661 			ZVAL_NULL(data);
662 			break;
663 
664 		case SQLITE3_TEXT:
665 			ZVAL_STRING(data, (char*)sqlite3_column_text(stmt, column));
666 			break;
667 
668 		case SQLITE_BLOB:
669 		default:
670 			ZVAL_STRINGL(data, (char*)sqlite3_column_blob(stmt, column), sqlite3_column_bytes(stmt, column));
671 	}
672 }
673 /* }}} */
674 
675 /* {{{ proto SQLite3Result SQLite3::querySingle(String Query [, bool entire_row = false])
676    Returns a string of the first column, or an array of the entire row. */
PHP_METHODnull677 PHP_METHOD(sqlite3, querySingle)
678 {
679 	php_sqlite3_db_object *db_obj;
680 	zval *object = ZEND_THIS;
681 	zend_string *sql;
682 	char *errtext = NULL;
683 	int return_code;
684 	zend_bool entire_row = 0;
685 	sqlite3_stmt *stmt;
686 	db_obj = Z_SQLITE3_DB_P(object);
687 
688 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
689 
690 	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S|b", &sql, &entire_row)) {
691 		return;
692 	}
693 
694 	if (!ZSTR_LEN(sql)) {
695 		RETURN_FALSE;
696 	}
697 
698 	/* If there was no return value then just execute the query */
699 	if (!USED_RET()) {
700 		if (sqlite3_exec(db_obj->db, ZSTR_VAL(sql), NULL, NULL, &errtext) != SQLITE_OK) {
701 			php_sqlite3_error(db_obj, "%s", errtext);
702 			sqlite3_free(errtext);
703 		}
704 		return;
705 	}
706 
707 	return_code = sqlite3_prepare_v2(db_obj->db, ZSTR_VAL(sql), ZSTR_LEN(sql), &stmt, NULL);
708 	if (return_code != SQLITE_OK) {
709 		php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
710 		RETURN_FALSE;
711 	}
712 
713 	return_code = sqlite3_step(stmt);
714 
715 	switch (return_code) {
716 		case SQLITE_ROW: /* Valid Row */
717 		{
718 			if (!entire_row) {
719 				sqlite_value_to_zval(stmt, 0, return_value);
720 			} else {
721 				int i = 0;
722 				array_init(return_value);
723 				for (i = 0; i < sqlite3_data_count(stmt); i++) {
724 					zval data;
725 					sqlite_value_to_zval(stmt, i, &data);
726 					add_assoc_zval(return_value, (char*)sqlite3_column_name(stmt, i), &data);
727 				}
728 			}
729 			break;
730 		}
731 		case SQLITE_DONE: /* Valid but no results */
732 		{
733 			if (!entire_row) {
734 				RETVAL_NULL();
735 			} else {
736 				RETVAL_EMPTY_ARRAY();
737 			}
738 			break;
739 		}
740 		default:
741 		if (!EG(exception)) {
742 			php_sqlite3_error(db_obj, "Unable to execute statement: %s", sqlite3_errmsg(db_obj->db));
743 		}
744 		RETVAL_FALSE;
745 	}
746 	sqlite3_finalize(stmt);
747 }
748 /* }}} */
749 
sqlite3_do_callback(struct php_sqlite3_fci *fc, zval *cb, int argc, sqlite3_value **argv, sqlite3_context *context, int is_agg)750 static int sqlite3_do_callback(struct php_sqlite3_fci *fc, zval *cb, int argc, sqlite3_value **argv, sqlite3_context *context, int is_agg) /* {{{ */
751 {
752 	zval *zargs = NULL;
753 	zval retval;
754 	int i;
755 	int ret;
756 	int fake_argc;
757 	php_sqlite3_agg_context *agg_context = NULL;
758 
759 	if (is_agg) {
760 		is_agg = 2;
761 	}
762 
763 	fake_argc = argc + is_agg;
764 
765 	fc->fci.size = sizeof(fc->fci);
766 	ZVAL_COPY_VALUE(&fc->fci.function_name, cb);
767 	fc->fci.object = NULL;
768 	fc->fci.retval = &retval;
769 	fc->fci.param_count = fake_argc;
770 
771 	/* build up the params */
772 
773 	if (fake_argc) {
774 		zargs = (zval *)safe_emalloc(fake_argc, sizeof(zval), 0);
775 	}
776 
777 	if (is_agg) {
778 		/* summon the aggregation context */
779 		agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
780 
781 		if (Z_ISUNDEF(agg_context->zval_context)) {
782 			ZVAL_NULL(&agg_context->zval_context);
783 		}
784 		ZVAL_COPY(&zargs[0], &agg_context->zval_context);
785 		ZVAL_LONG(&zargs[1], agg_context->row_count);
786 	}
787 
788 	for (i = 0; i < argc; i++) {
789 		switch (sqlite3_value_type(argv[i])) {
790 			case SQLITE_INTEGER:
791 #if ZEND_LONG_MAX > 2147483647
792 				ZVAL_LONG(&zargs[i + is_agg], sqlite3_value_int64(argv[i]));
793 #else
794 				ZVAL_LONG(&zargs[i + is_agg], sqlite3_value_int(argv[i]));
795 #endif
796 				break;
797 
798 			case SQLITE_FLOAT:
799 				ZVAL_DOUBLE(&zargs[i + is_agg], sqlite3_value_double(argv[i]));
800 				break;
801 
802 			case SQLITE_NULL:
803 				ZVAL_NULL(&zargs[i + is_agg]);
804 				break;
805 
806 			case SQLITE_BLOB:
807 			case SQLITE3_TEXT:
808 			default:
809 				ZVAL_STRINGL(&zargs[i + is_agg], (char*)sqlite3_value_text(argv[i]), sqlite3_value_bytes(argv[i]));
810 				break;
811 		}
812 	}
813 
814 	fc->fci.params = zargs;
815 
816 	if ((ret = zend_call_function(&fc->fci, &fc->fcc)) == FAILURE) {
817 		php_error_docref(NULL, E_WARNING, "An error occurred while invoking the callback");
818 	}
819 
820 	if (is_agg) {
821 		zval_ptr_dtor(&zargs[0]);
822 	}
823 
824 	/* clean up the params */
825 	if (fake_argc) {
826 		for (i = is_agg; i < argc + is_agg; i++) {
827 			zval_ptr_dtor(&zargs[i]);
828 		}
829 		if (is_agg) {
830 			zval_ptr_dtor(&zargs[1]);
831 		}
832 		efree(zargs);
833 	}
834 
835 	if (!is_agg || !argv) {
836 		/* only set the sqlite return value if we are a scalar function,
837 		 * or if we are finalizing an aggregate */
838 		if (!Z_ISUNDEF(retval)) {
839 			switch (Z_TYPE(retval)) {
840 				case IS_LONG:
841 #if ZEND_LONG_MAX > 2147483647
842 					sqlite3_result_int64(context, Z_LVAL(retval));
843 #else
844 					sqlite3_result_int(context, Z_LVAL(retval));
845 #endif
846 					break;
847 
848 				case IS_NULL:
849 					sqlite3_result_null(context);
850 					break;
851 
852 				case IS_DOUBLE:
853 					sqlite3_result_double(context, Z_DVAL(retval));
854 					break;
855 
856 				default: {
857 					zend_string *str = zval_try_get_string(&retval);
858 					if (UNEXPECTED(!str)) {
859 						ret = FAILURE;
860 						break;
861 					}
862 					sqlite3_result_text(context, ZSTR_VAL(str), ZSTR_LEN(str), SQLITE_TRANSIENT);
863 					zend_string_release(str);
864 					break;
865 				}
866 			}
867 		} else {
868 			sqlite3_result_error(context, "failed to invoke callback", 0);
869 		}
870 
871 		if (agg_context && !Z_ISUNDEF(agg_context->zval_context)) {
872 			zval_ptr_dtor(&agg_context->zval_context);
873 		}
874 	} else {
875 		/* we're stepping in an aggregate; the return value goes into
876 		 * the context */
877 		if (agg_context && !Z_ISUNDEF(agg_context->zval_context)) {
878 			zval_ptr_dtor(&agg_context->zval_context);
879 		}
880 		ZVAL_COPY_VALUE(&agg_context->zval_context, &retval);
881 		ZVAL_UNDEF(&retval);
882 	}
883 
884 	if (!Z_ISUNDEF(retval)) {
885 		zval_ptr_dtor(&retval);
886 	}
887 	return ret;
888 }
889 /* }}}*/
890 
php_sqlite3_callback_func(sqlite3_context *context, int argc, sqlite3_value **argv)891 static void php_sqlite3_callback_func(sqlite3_context *context, int argc, sqlite3_value **argv) /* {{{ */
892 {
893 	php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
894 
895 	sqlite3_do_callback(&func->afunc, &func->func, argc, argv, context, 0);
896 }
897 /* }}}*/
898 
php_sqlite3_callback_step(sqlite3_context *context, int argc, sqlite3_value **argv)899 static void php_sqlite3_callback_step(sqlite3_context *context, int argc, sqlite3_value **argv) /* {{{ */
900 {
901 	php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
902 	php_sqlite3_agg_context *agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
903 
904 	agg_context->row_count++;
905 
906 	sqlite3_do_callback(&func->astep, &func->step, argc, argv, context, 1);
907 }
908 /* }}} */
909 
php_sqlite3_callback_final(sqlite3_context *context)910 static void php_sqlite3_callback_final(sqlite3_context *context) /* {{{ */
911 {
912 	php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
913 	php_sqlite3_agg_context *agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
914 
915 	agg_context->row_count = 0;
916 
917 	sqlite3_do_callback(&func->afini, &func->fini, 0, NULL, context, 1);
918 }
919 /* }}} */
920 
php_sqlite3_callback_compare(void *coll, int a_len, const void *a, int b_len, const void* b)921 static int php_sqlite3_callback_compare(void *coll, int a_len, const void *a, int b_len, const void* b) /* {{{ */
922 {
923 	php_sqlite3_collation *collation = (php_sqlite3_collation*)coll;
924 	zval zargs[2];
925 	zval retval;
926 	int ret;
927 
928 	// Exception occurred on previous callback. Don't attempt to call function.
929 	if (EG(exception)) {
930 		return 0;
931 	}
932 
933 	collation->fci.fci.size = (sizeof(collation->fci.fci));
934 	ZVAL_COPY_VALUE(&collation->fci.fci.function_name, &collation->cmp_func);
935 	collation->fci.fci.object = NULL;
936 	collation->fci.fci.retval = &retval;
937 	collation->fci.fci.param_count = 2;
938 
939 	ZVAL_STRINGL(&zargs[0], a, a_len);
940 	ZVAL_STRINGL(&zargs[1], b, b_len);
941 
942 	collation->fci.fci.params = zargs;
943 
944 	if ((ret = zend_call_function(&collation->fci.fci, &collation->fci.fcc)) == FAILURE) {
945 		php_error_docref(NULL, E_WARNING, "An error occurred while invoking the compare callback");
946 	}
947 
948 	zval_ptr_dtor(&zargs[0]);
949 	zval_ptr_dtor(&zargs[1]);
950 
951 	if (EG(exception)) {
952 		ret = 0;
953 	} else if (Z_TYPE(retval) != IS_LONG){
954 		//retval ought to contain a ZVAL_LONG by now
955 		// (the result of a comparison, i.e. most likely -1, 0, or 1)
956 		//I suppose we could accept any scalar return type, though.
957 		php_error_docref(NULL, E_WARNING, "An error occurred while invoking the compare callback (invalid return type).  Collation behaviour is undefined.");
958 	} else {
959 		ret = Z_LVAL(retval);
960 	}
961 
962 	zval_ptr_dtor(&retval);
963 
964 	return ret;
965 }
966 /* }}} */
967 
968 /* {{{ proto bool SQLite3::createFunction(string name, mixed callback [, int argcount, int flags])
969    Allows registration of a PHP function as a SQLite UDF that can be called within SQL statements. */
PHP_METHODnull970 PHP_METHOD(sqlite3, createFunction)
971 {
972 	php_sqlite3_db_object *db_obj;
973 	zval *object = ZEND_THIS;
974 	php_sqlite3_func *func;
975 	char *sql_func;
976 	size_t sql_func_len;
977 	zval *callback_func;
978 	zend_long sql_func_num_args = -1;
979 	zend_long flags = 0;
980 	db_obj = Z_SQLITE3_DB_P(object);
981 
982 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
983 
984 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz|ll", &sql_func, &sql_func_len, &callback_func, &sql_func_num_args, &flags) == FAILURE) {
985 		return;
986 	}
987 
988 	if (!sql_func_len) {
989 		RETURN_FALSE;
990 	}
991 
992 	if (!zend_is_callable(callback_func, 0, NULL)) {
993 		zend_string *callback_name = zend_get_callable_name(callback_func);
994 		php_sqlite3_error(db_obj, "Not a valid callback function %s", ZSTR_VAL(callback_name));
995 		zend_string_release_ex(callback_name, 0);
996 		RETURN_FALSE;
997 	}
998 
999 	func = (php_sqlite3_func *)ecalloc(1, sizeof(*func));
1000 
1001 	if (sqlite3_create_function(db_obj->db, sql_func, sql_func_num_args, flags | SQLITE_UTF8, func, php_sqlite3_callback_func, NULL, NULL) == SQLITE_OK) {
1002 		func->func_name = estrdup(sql_func);
1003 
1004 		ZVAL_COPY(&func->func, callback_func);
1005 
1006 		func->argc = sql_func_num_args;
1007 		func->next = db_obj->funcs;
1008 		db_obj->funcs = func;
1009 
1010 		RETURN_TRUE;
1011 	}
1012 	efree(func);
1013 
1014 	RETURN_FALSE;
1015 }
1016 /* }}} */
1017 
1018 /* {{{ proto bool SQLite3::createAggregate(string name, mixed step, mixed final [, int argcount])
1019    Allows registration of a PHP function for use as an aggregate. */
PHP_METHODnull1020 PHP_METHOD(sqlite3, createAggregate)
1021 {
1022 	php_sqlite3_db_object *db_obj;
1023 	zval *object = ZEND_THIS;
1024 	php_sqlite3_func *func;
1025 	char *sql_func;
1026 	size_t sql_func_len;
1027 	zval *step_callback, *fini_callback;
1028 	zend_long sql_func_num_args = -1;
1029 	db_obj = Z_SQLITE3_DB_P(object);
1030 
1031 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1032 
1033 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &sql_func, &sql_func_len, &step_callback, &fini_callback, &sql_func_num_args) == FAILURE) {
1034 		return;
1035 	}
1036 
1037 	if (!sql_func_len) {
1038 		RETURN_FALSE;
1039 	}
1040 
1041 	if (!zend_is_callable(step_callback, 0, NULL)) {
1042 		zend_string *callback_name = zend_get_callable_name(step_callback);
1043 		php_sqlite3_error(db_obj, "Not a valid callback function %s", ZSTR_VAL(callback_name));
1044 		zend_string_release_ex(callback_name, 0);
1045 		RETURN_FALSE;
1046 	}
1047 
1048 	if (!zend_is_callable(fini_callback, 0, NULL)) {
1049 		zend_string *callback_name = zend_get_callable_name(fini_callback);
1050 		php_sqlite3_error(db_obj, "Not a valid callback function %s", ZSTR_VAL(callback_name));
1051 		zend_string_release_ex(callback_name, 0);
1052 		RETURN_FALSE;
1053 	}
1054 
1055 	func = (php_sqlite3_func *)ecalloc(1, sizeof(*func));
1056 
1057 	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) {
1058 		func->func_name = estrdup(sql_func);
1059 
1060 		ZVAL_COPY(&func->step, step_callback);
1061 		ZVAL_COPY(&func->fini, fini_callback);
1062 
1063 		func->argc = sql_func_num_args;
1064 		func->next = db_obj->funcs;
1065 		db_obj->funcs = func;
1066 
1067 		RETURN_TRUE;
1068 	}
1069 	efree(func);
1070 
1071 	RETURN_FALSE;
1072 }
1073 /* }}} */
1074 
1075 /* {{{ proto bool SQLite3::createCollation(string name, mixed callback)
1076    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()). */
PHP_METHODnull1077 PHP_METHOD(sqlite3, createCollation)
1078 {
1079 	php_sqlite3_db_object *db_obj;
1080 	zval *object = ZEND_THIS;
1081 	php_sqlite3_collation *collation;
1082 	char *collation_name;
1083 	size_t collation_name_len;
1084 	zval *callback_func;
1085 	db_obj = Z_SQLITE3_DB_P(object);
1086 
1087 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1088 
1089 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz", &collation_name, &collation_name_len, &callback_func) == FAILURE) {
1090 		RETURN_FALSE;
1091 	}
1092 
1093 	if (!collation_name_len) {
1094 		RETURN_FALSE;
1095 	}
1096 
1097 	if (!zend_is_callable(callback_func, 0, NULL)) {
1098 		zend_string *callback_name = zend_get_callable_name(callback_func);
1099 		php_sqlite3_error(db_obj, "Not a valid callback function %s", ZSTR_VAL(callback_name));
1100 		zend_string_release_ex(callback_name, 0);
1101 		RETURN_FALSE;
1102 	}
1103 
1104 	collation = (php_sqlite3_collation *)ecalloc(1, sizeof(*collation));
1105 	if (sqlite3_create_collation(db_obj->db, collation_name, SQLITE_UTF8, collation, php_sqlite3_callback_compare) == SQLITE_OK) {
1106 		collation->collation_name = estrdup(collation_name);
1107 
1108 		ZVAL_COPY(&collation->cmp_func, callback_func);
1109 
1110 		collation->next = db_obj->collations;
1111 		db_obj->collations = collation;
1112 
1113 		RETURN_TRUE;
1114 	}
1115 	efree(collation);
1116 
1117 	RETURN_FALSE;
1118 }
1119 /* }}} */
1120 
1121 typedef struct {
1122 	sqlite3_blob *blob;
1123 	size_t		 position;
1124 	size_t       size;
1125 	int          flags;
1126 } php_stream_sqlite3_data;
1127 
php_sqlite3_stream_write(php_stream *stream, const char *buf, size_t count)1128 static ssize_t php_sqlite3_stream_write(php_stream *stream, const char *buf, size_t count)
1129 {
1130 	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1131 
1132 	if (sqlite3_stream->flags & SQLITE_OPEN_READONLY) {
1133 		php_error_docref(NULL, E_WARNING, "Can't write to blob stream: is open as read only");
1134 		return -1;
1135 	}
1136 
1137 	if (sqlite3_stream->position + count > sqlite3_stream->size) {
1138 		php_error_docref(NULL, E_WARNING, "It is not possible to increase the size of a BLOB");
1139 		return -1;
1140 	}
1141 
1142 	if (sqlite3_blob_write(sqlite3_stream->blob, buf, count, sqlite3_stream->position) != SQLITE_OK) {
1143 		return -1;
1144 	}
1145 
1146 	if (sqlite3_stream->position + count >= sqlite3_stream->size) {
1147 		stream->eof = 1;
1148 		sqlite3_stream->position = sqlite3_stream->size;
1149 	}
1150 	else {
1151 		sqlite3_stream->position += count;
1152 	}
1153 
1154 	return count;
1155 }
1156 
php_sqlite3_stream_read(php_stream *stream, char *buf, size_t count)1157 static ssize_t php_sqlite3_stream_read(php_stream *stream, char *buf, size_t count)
1158 {
1159 	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1160 
1161 	if (sqlite3_stream->position + count >= sqlite3_stream->size) {
1162 		count = sqlite3_stream->size - sqlite3_stream->position;
1163 		stream->eof = 1;
1164 	}
1165 	if (count) {
1166 		if (sqlite3_blob_read(sqlite3_stream->blob, buf, count, sqlite3_stream->position) != SQLITE_OK) {
1167 			return -1;
1168 		}
1169 		sqlite3_stream->position += count;
1170 	}
1171 	return count;
1172 }
1173 
php_sqlite3_stream_close(php_stream *stream, int close_handle)1174 static int php_sqlite3_stream_close(php_stream *stream, int close_handle)
1175 {
1176 	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1177 
1178 	if (sqlite3_blob_close(sqlite3_stream->blob) != SQLITE_OK) {
1179 		/* Error occurred, but it still closed */
1180 	}
1181 
1182 	efree(sqlite3_stream);
1183 
1184 	return 0;
1185 }
1186 
php_sqlite3_stream_flush(php_stream *stream)1187 static int php_sqlite3_stream_flush(php_stream *stream)
1188 {
1189 	/* do nothing */
1190 	return 0;
1191 }
1192 
1193 /* {{{ */
php_sqlite3_stream_seek(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffs)1194 static int php_sqlite3_stream_seek(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffs)
1195 {
1196 	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1197 
1198 	switch(whence) {
1199 		case SEEK_CUR:
1200 			if (offset < 0) {
1201 				if (sqlite3_stream->position < (size_t)(-offset)) {
1202 					sqlite3_stream->position = 0;
1203 					*newoffs = -1;
1204 					return -1;
1205 				} else {
1206 					sqlite3_stream->position = sqlite3_stream->position + offset;
1207 					*newoffs = sqlite3_stream->position;
1208 					stream->eof = 0;
1209 					return 0;
1210 				}
1211 			} else {
1212 				if (sqlite3_stream->position + (size_t)(offset) > sqlite3_stream->size) {
1213 					sqlite3_stream->position = sqlite3_stream->size;
1214 					*newoffs = -1;
1215 					return -1;
1216 				} else {
1217 					sqlite3_stream->position = sqlite3_stream->position + offset;
1218 					*newoffs = sqlite3_stream->position;
1219 					stream->eof = 0;
1220 					return 0;
1221 				}
1222 			}
1223 		case SEEK_SET:
1224 			if (sqlite3_stream->size < (size_t)(offset)) {
1225 				sqlite3_stream->position = sqlite3_stream->size;
1226 				*newoffs = -1;
1227 				return -1;
1228 			} else {
1229 				sqlite3_stream->position = offset;
1230 				*newoffs = sqlite3_stream->position;
1231 				stream->eof = 0;
1232 				return 0;
1233 			}
1234 		case SEEK_END:
1235 			if (offset > 0) {
1236 				sqlite3_stream->position = sqlite3_stream->size;
1237 				*newoffs = -1;
1238 				return -1;
1239 			} else if (sqlite3_stream->size < (size_t)(-offset)) {
1240 				sqlite3_stream->position = 0;
1241 				*newoffs = -1;
1242 				return -1;
1243 			} else {
1244 				sqlite3_stream->position = sqlite3_stream->size + offset;
1245 				*newoffs = sqlite3_stream->position;
1246 				stream->eof = 0;
1247 				return 0;
1248 			}
1249 		default:
1250 			*newoffs = sqlite3_stream->position;
1251 			return -1;
1252 	}
1253 }
1254 /* }}} */
1255 
1256 
php_sqlite3_stream_cast(php_stream *stream, int castas, void **ret)1257 static int php_sqlite3_stream_cast(php_stream *stream, int castas, void **ret)
1258 {
1259 	return FAILURE;
1260 }
1261 
php_sqlite3_stream_stat(php_stream *stream, php_stream_statbuf *ssb)1262 static int php_sqlite3_stream_stat(php_stream *stream, php_stream_statbuf *ssb)
1263 {
1264 	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1265 	ssb->sb.st_size = sqlite3_stream->size;
1266 	return 0;
1267 }
1268 
1269 static const php_stream_ops php_stream_sqlite3_ops = {
1270 	php_sqlite3_stream_write,
1271 	php_sqlite3_stream_read,
1272 	php_sqlite3_stream_close,
1273 	php_sqlite3_stream_flush,
1274 	"SQLite3",
1275 	php_sqlite3_stream_seek,
1276 	php_sqlite3_stream_cast,
1277 	php_sqlite3_stream_stat,
1278 	NULL
1279 };
1280 
1281 /* {{{ proto resource SQLite3::openBlob(string table, string column, int rowid [, string dbname [, int flags]])
1282    Open a blob as a stream which we can read / write to. */
PHP_METHODnull1283 PHP_METHOD(sqlite3, openBlob)
1284 {
1285 	php_sqlite3_db_object *db_obj;
1286 	zval *object = ZEND_THIS;
1287 	char *table, *column, *dbname = "main", *mode = "rb";
1288 	size_t table_len, column_len, dbname_len;
1289 	zend_long rowid, flags = SQLITE_OPEN_READONLY, sqlite_flags = 0;
1290 	sqlite3_blob *blob = NULL;
1291 	php_stream_sqlite3_data *sqlite3_stream;
1292 	php_stream *stream;
1293 
1294 	db_obj = Z_SQLITE3_DB_P(object);
1295 
1296 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1297 
1298 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssl|sl", &table, &table_len, &column, &column_len, &rowid, &dbname, &dbname_len, &flags) == FAILURE) {
1299 		return;
1300 	}
1301 
1302 	sqlite_flags = (flags & SQLITE_OPEN_READWRITE) ? 1 : 0;
1303 
1304 	if (sqlite3_blob_open(db_obj->db, dbname, table, column, rowid, sqlite_flags, &blob) != SQLITE_OK) {
1305 		php_sqlite3_error(db_obj, "Unable to open blob: %s", sqlite3_errmsg(db_obj->db));
1306 		RETURN_FALSE;
1307 	}
1308 
1309 	sqlite3_stream = emalloc(sizeof(php_stream_sqlite3_data));
1310 	sqlite3_stream->blob = blob;
1311 	sqlite3_stream->flags = flags;
1312 	sqlite3_stream->position = 0;
1313 	sqlite3_stream->size = sqlite3_blob_bytes(blob);
1314 
1315 	if (sqlite_flags != 0) {
1316 		mode = "r+b";
1317 	}
1318 
1319 	stream = php_stream_alloc(&php_stream_sqlite3_ops, sqlite3_stream, 0, mode);
1320 
1321 	if (stream) {
1322 		php_stream_to_zval(stream, return_value);
1323 	} else {
1324 		RETURN_FALSE;
1325 	}
1326 }
1327 /* }}} */
1328 
1329 /* {{{ proto bool SQLite3::enableExceptions([bool enableExceptions = false])
1330    Enables an exception error mode. */
PHP_METHODnull1331 PHP_METHOD(sqlite3, enableExceptions)
1332 {
1333 	php_sqlite3_db_object *db_obj;
1334 	zval *object = ZEND_THIS;
1335 	zend_bool enableExceptions = 0;
1336 
1337 	db_obj = Z_SQLITE3_DB_P(object);
1338 
1339 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &enableExceptions) == FAILURE) {
1340 		return;
1341 	}
1342 
1343 	RETVAL_BOOL(db_obj->exception);
1344 
1345 	db_obj->exception = enableExceptions;
1346 }
1347 /* }}} */
1348 
1349 #if SQLITE_VERSION_NUMBER >= 3006011
1350 /* {{{ proto bool SQLite3::backup(SQLite3 destination_db[, string source_dbname = "main"[, string destination_dbname = "main"]])
1351    Backups the current database to another one. */
PHP_METHODnull1352 PHP_METHOD(sqlite3, backup)
1353 {
1354 	php_sqlite3_db_object *source_obj;
1355 	php_sqlite3_db_object *destination_obj;
1356 	char *source_dbname = "main", *destination_dbname = "main";
1357 	size_t source_dbname_length, destination_dbname_length;
1358 	zval *source_zval = ZEND_THIS;
1359 	zval *destination_zval;
1360 	sqlite3_backup *dbBackup;
1361 	int rc; // Return code
1362 
1363 	source_obj = Z_SQLITE3_DB_P(source_zval);
1364 	SQLITE3_CHECK_INITIALIZED(source_obj, source_obj->initialised, SQLite3)
1365 
1366 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|ss", &destination_zval, php_sqlite3_sc_entry, &source_dbname, &source_dbname_length, &destination_dbname, &destination_dbname_length) == FAILURE) {
1367 		return;
1368 	}
1369 
1370 	destination_obj = Z_SQLITE3_DB_P(destination_zval);
1371 
1372 	SQLITE3_CHECK_INITIALIZED(destination_obj, destination_obj->initialised, SQLite3)
1373 
1374 	dbBackup = sqlite3_backup_init(destination_obj->db, destination_dbname, source_obj->db, source_dbname);
1375 
1376 	if (dbBackup) {
1377 		do {
1378 			rc = sqlite3_backup_step(dbBackup, -1);
1379 		} while (rc == SQLITE_OK);
1380 
1381 		/* Release resources allocated by backup_init(). */
1382 		rc = sqlite3_backup_finish(dbBackup);
1383 	}
1384 	else {
1385 		rc = sqlite3_errcode(source_obj->db);
1386 	}
1387 
1388 	if (rc != SQLITE_OK) {
1389 		if (rc == SQLITE_BUSY) {
1390 			php_sqlite3_error(source_obj, "Backup failed: source database is busy");
1391 		}
1392 		else if (rc == SQLITE_LOCKED) {
1393 			php_sqlite3_error(source_obj, "Backup failed: source database is locked");
1394 		}
1395 		else {
1396 			php_sqlite3_error(source_obj, "Backup failed: %d, %s", rc, sqlite3_errmsg(source_obj->db));
1397 		}
1398 		RETURN_FALSE;
1399 	}
1400 
1401 	RETURN_TRUE;
1402 }
1403 /* }}} */
1404 #endif
1405 
1406 /* {{{ proto int SQLite3Stmt::paramCount()
1407    Returns the number of parameters within the prepared statement. */
PHP_METHODnull1408 PHP_METHOD(sqlite3stmt, paramCount)
1409 {
1410 	php_sqlite3_stmt *stmt_obj;
1411 	zval *object = ZEND_THIS;
1412 	stmt_obj = Z_SQLITE3_STMT_P(object);
1413 
1414 	if (zend_parse_parameters_none() == FAILURE) {
1415 		return;
1416 	}
1417 
1418 	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1419 	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1420 
1421 	RETURN_LONG(sqlite3_bind_parameter_count(stmt_obj->stmt));
1422 }
1423 /* }}} */
1424 
1425 /* {{{ proto bool SQLite3Stmt::close()
1426    Closes the prepared statement. */
PHP_METHODnull1427 PHP_METHOD(sqlite3stmt, close)
1428 {
1429 	php_sqlite3_stmt *stmt_obj;
1430 	zval *object = ZEND_THIS;
1431 	stmt_obj = Z_SQLITE3_STMT_P(object);
1432 
1433 	if (zend_parse_parameters_none() == FAILURE) {
1434 		return;
1435 	}
1436 
1437 	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1438 
1439 	if(stmt_obj->db_obj) {
1440         	zend_llist_del_element(&(stmt_obj->db_obj->free_list), object, (int (*)(void *, void *)) php_sqlite3_compare_stmt_zval_free);
1441 	}
1442 
1443 	RETURN_TRUE;
1444 }
1445 /* }}} */
1446 
1447 /* {{{ proto bool SQLite3Stmt::reset()
1448    Reset the prepared statement to the state before it was executed, bindings still remain. */
PHP_METHODnull1449 PHP_METHOD(sqlite3stmt, reset)
1450 {
1451 	php_sqlite3_stmt *stmt_obj;
1452 	zval *object = ZEND_THIS;
1453 	stmt_obj = Z_SQLITE3_STMT_P(object);
1454 
1455 	if (zend_parse_parameters_none() == FAILURE) {
1456 		return;
1457 	}
1458 
1459 	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1460 	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1461 
1462 	if (sqlite3_reset(stmt_obj->stmt) != SQLITE_OK) {
1463 		php_sqlite3_error(stmt_obj->db_obj, "Unable to reset statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1464 		RETURN_FALSE;
1465 	}
1466 	RETURN_TRUE;
1467 }
1468 /* }}} */
1469 
1470 /* {{{ proto bool SQLite3Stmt::clear()
1471    Clear all current bound parameters. */
PHP_METHODnull1472 PHP_METHOD(sqlite3stmt, clear)
1473 {
1474 	php_sqlite3_stmt *stmt_obj;
1475 	zval *object = ZEND_THIS;
1476 	stmt_obj = Z_SQLITE3_STMT_P(object);
1477 
1478 	if (zend_parse_parameters_none() == FAILURE) {
1479 		return;
1480 	}
1481 
1482 	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1483 	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1484 
1485 	if (sqlite3_clear_bindings(stmt_obj->stmt) != SQLITE_OK) {
1486 		php_sqlite3_error(stmt_obj->db_obj, "Unable to clear statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1487 		RETURN_FALSE;
1488 	}
1489 
1490 	if (stmt_obj->bound_params) {
1491 		zend_hash_destroy(stmt_obj->bound_params);
1492 		FREE_HASHTABLE(stmt_obj->bound_params);
1493 		stmt_obj->bound_params = NULL;
1494 	}
1495 
1496 	RETURN_TRUE;
1497 }
1498 /* }}} */
1499 
1500 /* {{{ proto bool SQLite3Stmt::readOnly()
1501    Returns true if a statement is definitely read only */
PHP_METHODnull1502 PHP_METHOD(sqlite3stmt, readOnly)
1503 {
1504 	php_sqlite3_stmt *stmt_obj;
1505 	zval *object = ZEND_THIS;
1506 	stmt_obj = Z_SQLITE3_STMT_P(object);
1507 
1508 	if (zend_parse_parameters_none() == FAILURE) {
1509 		return;
1510 	}
1511 
1512 	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1513 	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1514 
1515 	if (sqlite3_stmt_readonly(stmt_obj->stmt)) {
1516 		RETURN_TRUE;
1517 	}
1518 	RETURN_FALSE;
1519 }
1520 /* }}} */
1521 
1522 /* bind parameters to a statement before execution */
php_sqlite3_bind_params(php_sqlite3_stmt *stmt_obj)1523 static int php_sqlite3_bind_params(php_sqlite3_stmt *stmt_obj) /* {{{ */
1524 {
1525 	struct php_sqlite3_bound_param *param;
1526 	int return_code;
1527 
1528 	if (stmt_obj->bound_params) {
1529 		ZEND_HASH_FOREACH_PTR(stmt_obj->bound_params, param) {
1530 			zval *parameter;
1531 			/* parameter must be a reference? */
1532 			if (Z_ISREF(param->parameter)) {
1533 				parameter = Z_REFVAL(param->parameter);
1534 			} else {
1535 				parameter = &param->parameter;
1536 			}
1537 
1538 			/* If the ZVAL is null then it should be bound as that */
1539 			if (Z_TYPE_P(parameter) == IS_NULL) {
1540 				return_code = sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1541 				if (return_code != SQLITE_OK) {
1542 					php_sqlite3_error(stmt_obj->db_obj, "Unable to bind parameter number " ZEND_LONG_FMT " (%d)", param->param_number, return_code);
1543 				}
1544 				continue;
1545 			}
1546 
1547 			switch (param->type) {
1548 				case SQLITE_INTEGER:
1549 					convert_to_long(parameter);
1550 #if ZEND_LONG_MAX > 2147483647
1551 					return_code = sqlite3_bind_int64(stmt_obj->stmt, param->param_number, Z_LVAL_P(parameter));
1552 #else
1553 					return_code = sqlite3_bind_int(stmt_obj->stmt, param->param_number, Z_LVAL_P(parameter));
1554 #endif
1555 					if (return_code != SQLITE_OK) {
1556 						php_sqlite3_error(stmt_obj->db_obj, "Unable to bind parameter number " ZEND_LONG_FMT " (%d)", param->param_number, return_code);
1557 					}
1558 					break;
1559 
1560 				case SQLITE_FLOAT:
1561 					convert_to_double(parameter);
1562 					return_code = sqlite3_bind_double(stmt_obj->stmt, param->param_number, Z_DVAL_P(parameter));
1563 					if (return_code != SQLITE_OK) {
1564 						php_sqlite3_error(stmt_obj->db_obj, "Unable to bind parameter number " ZEND_LONG_FMT " (%d)", param->param_number, return_code);
1565 					}
1566 					break;
1567 
1568 				case SQLITE_BLOB:
1569 				{
1570 					php_stream *stream = NULL;
1571 					zend_string *buffer = NULL;
1572 					if (Z_TYPE_P(parameter) == IS_RESOURCE) {
1573 						php_stream_from_zval_no_verify(stream, parameter);
1574 						if (stream == NULL) {
1575 							php_sqlite3_error(stmt_obj->db_obj, "Unable to read stream for parameter %ld", param->param_number);
1576 							return FAILURE;
1577 						}
1578 						buffer = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0);
1579 					} else {
1580 						buffer = zval_get_string(parameter);
1581 					}
1582 
1583 					if (buffer) {
1584 						return_code = sqlite3_bind_blob(stmt_obj->stmt, param->param_number, ZSTR_VAL(buffer), ZSTR_LEN(buffer), SQLITE_TRANSIENT);
1585 						zend_string_release_ex(buffer, 0);
1586 						if (return_code != SQLITE_OK) {
1587 							php_sqlite3_error(stmt_obj->db_obj, "Unable to bind parameter number " ZEND_LONG_FMT " (%d)", param->param_number, return_code);
1588 						}
1589 					} else {
1590 						return_code = sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1591 						if (return_code != SQLITE_OK) {
1592 							php_sqlite3_error(stmt_obj->db_obj, "Unable to bind parameter number " ZEND_LONG_FMT " (%d)", param->param_number, return_code);
1593 						}
1594 					}
1595 					break;
1596 				}
1597 
1598 				case SQLITE3_TEXT: {
1599 					zend_string *str = zval_try_get_string(parameter);
1600 					if (UNEXPECTED(!str)) {
1601 						return FAILURE;
1602 					}
1603 					return_code = sqlite3_bind_text(stmt_obj->stmt, param->param_number, ZSTR_VAL(str), ZSTR_LEN(str), SQLITE_TRANSIENT);
1604 					if (return_code != SQLITE_OK) {
1605 						php_sqlite3_error(stmt_obj->db_obj, "Unable to bind parameter number " ZEND_LONG_FMT " (%d)", param->param_number, return_code);
1606 					}
1607 					zend_string_release(str);
1608 					break;
1609 				}
1610 
1611 				case SQLITE_NULL:
1612 					return_code = sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1613 					if (return_code != SQLITE_OK) {
1614 						php_sqlite3_error(stmt_obj->db_obj, "Unable to bind parameter number " ZEND_LONG_FMT " (%d)", param->param_number, return_code);
1615 					}
1616 					break;
1617 
1618 				default:
1619 					php_sqlite3_error(stmt_obj->db_obj, "Unknown parameter type: %pd for parameter %pd", param->type, param->param_number);
1620 					return FAILURE;
1621 			}
1622 		} ZEND_HASH_FOREACH_END();
1623 	}
1624 
1625 	return SUCCESS;
1626 }
1627 /* }}} */
1628 
1629 
1630 /* {{{ proto string SQLite3Stmt::getSQL([expanded = false])
1631    Returns the SQL statement used to prepare the query. If expanded is true, binded parameters and values will be expanded. */
PHP_METHODnull1632 PHP_METHOD(sqlite3stmt, getSQL)
1633 {
1634 	php_sqlite3_stmt *stmt_obj;
1635 	zend_bool expanded = 0;
1636 	zval *object = getThis();
1637 	stmt_obj = Z_SQLITE3_STMT_P(object);
1638 	int bind_rc;
1639 
1640 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &expanded) == FAILURE) {
1641 		return;
1642 	}
1643 
1644 	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1645 	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1646 
1647 	bind_rc = php_sqlite3_bind_params(stmt_obj);
1648 
1649 	if (bind_rc == FAILURE || EG(exception)) {
1650 		RETURN_FALSE;
1651 	}
1652 
1653 	if (expanded) {
1654 #ifdef HAVE_SQLITE3_EXPANDED_SQL
1655 		char *sql = sqlite3_expanded_sql(stmt_obj->stmt);
1656 		RETVAL_STRING(sql);
1657 		sqlite3_free(sql);
1658 #else
1659 		php_sqlite3_error(stmt_obj->db_obj, "The expanded parameter requires SQLite3 >= 3.14 and %s is installed", sqlite3_libversion());
1660 		RETURN_FALSE;
1661 #endif
1662 	} else {
1663 		const char *sql = sqlite3_sql(stmt_obj->stmt);
1664 		RETVAL_STRING(sql);
1665 	}
1666 }
1667 /* }}} */
1668 
1669 
register_bound_parameter_to_sqlite(struct php_sqlite3_bound_param *param, php_sqlite3_stmt *stmt)1670 static int register_bound_parameter_to_sqlite(struct php_sqlite3_bound_param *param, php_sqlite3_stmt *stmt) /* {{{ */
1671 {
1672 	HashTable *hash;
1673 	hash = stmt->bound_params;
1674 
1675 	if (!hash) {
1676 		ALLOC_HASHTABLE(hash);
1677 		zend_hash_init(hash, 13, NULL, sqlite3_param_dtor, 0);
1678 		stmt->bound_params = hash;
1679 	}
1680 
1681 	/* We need a : prefix to resolve a name to a parameter number */
1682 	if (param->name) {
1683 		if (ZSTR_VAL(param->name)[0] != ':' && ZSTR_VAL(param->name)[0] != '@') {
1684 			/* pre-increment for character + 1 for null */
1685 			zend_string *temp = zend_string_alloc(ZSTR_LEN(param->name) + 1, 0);
1686 			ZSTR_VAL(temp)[0] = ':';
1687 			memmove(ZSTR_VAL(temp) + 1, ZSTR_VAL(param->name), ZSTR_LEN(param->name) + 1);
1688 			param->name = temp;
1689 		} else {
1690 			param->name = zend_string_copy(param->name);
1691 		}
1692 		/* do lookup*/
1693 		param->param_number = sqlite3_bind_parameter_index(stmt->stmt, ZSTR_VAL(param->name));
1694 	}
1695 
1696 	if (param->param_number < 1) {
1697 		if (param->name) {
1698 			zend_string_release_ex(param->name, 0);
1699 		}
1700 		return 0;
1701 	}
1702 
1703 	if (param->param_number >= 1) {
1704 		zend_hash_index_del(hash, param->param_number);
1705 	}
1706 
1707 	if (param->name) {
1708 		zend_hash_update_mem(hash, param->name, param, sizeof(struct php_sqlite3_bound_param));
1709 	} else {
1710 		zend_hash_index_update_mem(hash, param->param_number, param, sizeof(struct php_sqlite3_bound_param));
1711 	}
1712 
1713 	return 1;
1714 }
1715 /* }}} */
1716 
1717 /* {{{ Best try to map between PHP and SQLite. Default is still text. */
1718 #define PHP_SQLITE3_SET_TYPE(z, p) \
1719 	switch (Z_TYPE_P(z)) { \
1720 		default: \
1721 			(p).type = SQLITE_TEXT; \
1722 			break; \
1723 		case IS_LONG: \
1724 		case IS_TRUE: \
1725 		case IS_FALSE: \
1726 			(p).type = SQLITE_INTEGER; \
1727 			break; \
1728 		case IS_DOUBLE: \
1729 			(p).type = SQLITE_FLOAT; \
1730 			break; \
1731 		case IS_NULL: \
1732 			(p).type = SQLITE_NULL; \
1733 			break; \
1734 	}
1735 /* }}} */
1736 
1737 /* {{{ proto bool SQLite3Stmt::bindParam(int parameter_number, mixed parameter [, int type])
1738    Bind Parameter to a stmt variable. */
PHP_METHODnull1739 PHP_METHOD(sqlite3stmt, bindParam)
1740 {
1741 	php_sqlite3_stmt *stmt_obj;
1742 	zval *object = ZEND_THIS;
1743 	struct php_sqlite3_bound_param param = {0};
1744 	zval *parameter;
1745 	stmt_obj = Z_SQLITE3_STMT_P(object);
1746 
1747 	param.param_number = -1;
1748 	param.type = SQLITE3_TEXT;
1749 
1750 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "lz|l", &param.param_number, &parameter, &param.type) == FAILURE) {
1751 		if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz|l", &param.name, &parameter, &param.type) == FAILURE) {
1752 			return;
1753 		}
1754 	}
1755 
1756 	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1757 	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1758 
1759 	ZVAL_COPY(&param.parameter, parameter);
1760 
1761 	if (ZEND_NUM_ARGS() < 3) {
1762 		PHP_SQLITE3_SET_TYPE(parameter, param);
1763 	}
1764 
1765 	if (!register_bound_parameter_to_sqlite(&param, stmt_obj)) {
1766 		if (!Z_ISUNDEF(param.parameter)) {
1767 			zval_ptr_dtor(&(param.parameter));
1768 			ZVAL_UNDEF(&param.parameter);
1769 		}
1770 		RETURN_FALSE;
1771 	}
1772 	RETURN_TRUE;
1773 }
1774 /* }}} */
1775 
1776 /* {{{ proto bool SQLite3Stmt::bindValue(int parameter_number, mixed parameter [, int type])
1777    Bind Value of a parameter to a stmt variable. */
PHP_METHODnull1778 PHP_METHOD(sqlite3stmt, bindValue)
1779 {
1780 	php_sqlite3_stmt *stmt_obj;
1781 	zval *object = ZEND_THIS;
1782 	struct php_sqlite3_bound_param param = {0};
1783 	zval *parameter;
1784 	stmt_obj = Z_SQLITE3_STMT_P(object);
1785 
1786 	param.param_number = -1;
1787 	param.type = SQLITE3_TEXT;
1788 
1789 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "lz|l", &param.param_number, &parameter, &param.type) == FAILURE) {
1790 		if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz|l", &param.name, &parameter, &param.type) == FAILURE) {
1791 			return;
1792 		}
1793 	}
1794 
1795 	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1796 	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1797 
1798 	ZVAL_COPY(&param.parameter, parameter);
1799 
1800 	if (ZEND_NUM_ARGS() < 3) {
1801 		PHP_SQLITE3_SET_TYPE(parameter, param);
1802 	}
1803 
1804 	if (!register_bound_parameter_to_sqlite(&param, stmt_obj)) {
1805 		if (!Z_ISUNDEF(param.parameter)) {
1806 			zval_ptr_dtor(&(param.parameter));
1807 			ZVAL_UNDEF(&param.parameter);
1808 		}
1809 		RETURN_FALSE;
1810 	}
1811 	RETURN_TRUE;
1812 }
1813 /* }}} */
1814 
1815 #undef PHP_SQLITE3_SET_TYPE
1816 
1817 /* {{{ proto SQLite3Result SQLite3Stmt::execute()
1818    Executes a prepared statement and returns a result set object. */
PHP_METHODnull1819 PHP_METHOD(sqlite3stmt, execute)
1820 {
1821 	php_sqlite3_stmt *stmt_obj;
1822 	php_sqlite3_result *result;
1823 	zval *object = ZEND_THIS;
1824 	int return_code = 0;
1825 	int bind_rc = 0;
1826 
1827 	stmt_obj = Z_SQLITE3_STMT_P(object);
1828 
1829 	if (zend_parse_parameters_none() == FAILURE) {
1830 		return;
1831 	}
1832 
1833 	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1834 
1835 	/* Always reset statement before execution, see bug #77051 */
1836 	sqlite3_reset(stmt_obj->stmt);
1837 
1838 	/* Bind parameters to the statement */
1839 	bind_rc = php_sqlite3_bind_params(stmt_obj);
1840 
1841 	if (bind_rc == FAILURE || EG(exception)) {
1842 		RETURN_FALSE;
1843 	}
1844 
1845 	return_code = sqlite3_step(stmt_obj->stmt);
1846 
1847 	switch (return_code) {
1848 		case SQLITE_ROW: /* Valid Row */
1849 		case SQLITE_DONE: /* Valid but no results */
1850 		{
1851 			sqlite3_reset(stmt_obj->stmt);
1852 			object_init_ex(return_value, php_sqlite3_result_entry);
1853 			result = Z_SQLITE3_RESULT_P(return_value);
1854 
1855 			result->is_prepared_statement = 1;
1856 			result->db_obj = stmt_obj->db_obj;
1857 			result->stmt_obj = stmt_obj;
1858 			Z_ADDREF_P(object);
1859 			ZVAL_OBJ(&result->stmt_obj_zval, Z_OBJ_P(object));
1860 
1861 			break;
1862 		}
1863 		case SQLITE_ERROR:
1864 			sqlite3_reset(stmt_obj->stmt);
1865 
1866 		default:
1867 			if (!EG(exception)) {
1868 				php_sqlite3_error(stmt_obj->db_obj, "Unable to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1869 			}
1870 			zval_ptr_dtor(return_value);
1871 			RETURN_FALSE;
1872 	}
1873 
1874 	return;
1875 }
1876 /* }}} */
1877 
1878 /* {{{ proto SQLite3Stmt::__construct(SQLite3 dbobject, String Statement)
1879    __constructor for SQLite3Stmt. */
PHP_METHODnull1880 PHP_METHOD(sqlite3stmt, __construct)
1881 {
1882 	php_sqlite3_stmt *stmt_obj;
1883 	php_sqlite3_db_object *db_obj;
1884 	zval *object = ZEND_THIS;
1885 	zval *db_zval;
1886 	zend_string *sql;
1887 	int errcode;
1888 	zend_error_handling error_handling;
1889 	php_sqlite3_free_list *free_item;
1890 
1891 	stmt_obj = Z_SQLITE3_STMT_P(object);
1892 
1893 	if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "OS", &db_zval, php_sqlite3_sc_entry, &sql) == FAILURE) {
1894 		return;
1895 	}
1896 
1897 	db_obj = Z_SQLITE3_DB_P(db_zval);
1898 
1899 	zend_replace_error_handling(EH_THROW, NULL, &error_handling);
1900 	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1901 	zend_restore_error_handling(&error_handling);
1902 
1903 	if (!ZSTR_LEN(sql)) {
1904 		RETURN_FALSE;
1905 	}
1906 
1907 	stmt_obj->db_obj = db_obj;
1908 	Z_ADDREF_P(db_zval);
1909 	ZVAL_OBJ(&stmt_obj->db_obj_zval, Z_OBJ_P(db_zval));
1910 
1911 	errcode = sqlite3_prepare_v2(db_obj->db, ZSTR_VAL(sql), ZSTR_LEN(sql), &(stmt_obj->stmt), NULL);
1912 	if (errcode != SQLITE_OK) {
1913 		php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
1914 		zval_ptr_dtor(return_value);
1915 		RETURN_FALSE;
1916 	}
1917 	stmt_obj->initialised = 1;
1918 
1919 	free_item = emalloc(sizeof(php_sqlite3_free_list));
1920 	free_item->stmt_obj = stmt_obj;
1921 	//??  free_item->stmt_obj_zval = ZEND_THIS;
1922 	ZVAL_OBJ(&free_item->stmt_obj_zval, Z_OBJ_P(object));
1923 
1924 	zend_llist_add_element(&(db_obj->free_list), &free_item);
1925 }
1926 /* }}} */
1927 
1928 /* {{{ proto int SQLite3Result::numColumns()
1929    Number of columns in the result set. */
PHP_METHODnull1930 PHP_METHOD(sqlite3result, numColumns)
1931 {
1932 	php_sqlite3_result *result_obj;
1933 	zval *object = ZEND_THIS;
1934 	result_obj = Z_SQLITE3_RESULT_P(object);
1935 
1936 	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1937 
1938 	if (zend_parse_parameters_none() == FAILURE) {
1939 		return;
1940 	}
1941 
1942 	RETURN_LONG(sqlite3_column_count(result_obj->stmt_obj->stmt));
1943 }
1944 /* }}} */
1945 
1946 /* {{{ proto string SQLite3Result::columnName(int column)
1947    Returns the name of the nth column. */
PHP_METHODnull1948 PHP_METHOD(sqlite3result, columnName)
1949 {
1950 	php_sqlite3_result *result_obj;
1951 	zval *object = ZEND_THIS;
1952 	zend_long column = 0;
1953 	char *column_name;
1954 	result_obj = Z_SQLITE3_RESULT_P(object);
1955 
1956 	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1957 
1958 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &column) == FAILURE) {
1959 		return;
1960 	}
1961 	column_name = (char*) sqlite3_column_name(result_obj->stmt_obj->stmt, column);
1962 
1963 	if (column_name == NULL) {
1964 		RETURN_FALSE;
1965 	}
1966 
1967 	RETVAL_STRING(column_name);
1968 }
1969 /* }}} */
1970 
1971 /* {{{ proto int SQLite3Result::columnType(int column)
1972    Returns the type of the nth column. */
PHP_METHODnull1973 PHP_METHOD(sqlite3result, columnType)
1974 {
1975 	php_sqlite3_result *result_obj;
1976 	zval *object = ZEND_THIS;
1977 	zend_long column = 0;
1978 	result_obj = Z_SQLITE3_RESULT_P(object);
1979 
1980 	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1981 
1982 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &column) == FAILURE) {
1983 		return;
1984 	}
1985 
1986 	if (!sqlite3_data_count(result_obj->stmt_obj->stmt)) {
1987 		RETURN_FALSE;
1988 	}
1989 
1990 	RETURN_LONG(sqlite3_column_type(result_obj->stmt_obj->stmt, column));
1991 }
1992 /* }}} */
1993 
1994 /* {{{ proto array SQLite3Result::fetchArray([int mode])
1995    Fetch a result row as both an associative or numerically indexed array or both. */
PHP_METHODnull1996 PHP_METHOD(sqlite3result, fetchArray)
1997 {
1998 	php_sqlite3_result *result_obj;
1999 	zval *object = ZEND_THIS;
2000 	int i, ret;
2001 	zend_long mode = PHP_SQLITE3_BOTH;
2002 	result_obj = Z_SQLITE3_RESULT_P(object);
2003 
2004 	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
2005 
2006 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &mode) == FAILURE) {
2007 		return;
2008 	}
2009 
2010 	ret = sqlite3_step(result_obj->stmt_obj->stmt);
2011 	switch (ret) {
2012 		case SQLITE_ROW:
2013 			/* If there was no return value then just skip fetching */
2014 			if (!USED_RET()) {
2015 				return;
2016 			}
2017 
2018 			array_init(return_value);
2019 
2020 			for (i = 0; i < sqlite3_data_count(result_obj->stmt_obj->stmt); i++) {
2021 				zval data;
2022 
2023 				sqlite_value_to_zval(result_obj->stmt_obj->stmt, i, &data);
2024 
2025 				if (mode & PHP_SQLITE3_NUM) {
2026 					add_index_zval(return_value, i, &data);
2027 				}
2028 
2029 				if (mode & PHP_SQLITE3_ASSOC) {
2030 					if (mode & PHP_SQLITE3_NUM) {
2031 						if (Z_REFCOUNTED(data)) {
2032 							Z_ADDREF(data);
2033 						}
2034 					}
2035 					add_assoc_zval(return_value, (char*)sqlite3_column_name(result_obj->stmt_obj->stmt, i), &data);
2036 				}
2037 			}
2038 			break;
2039 
2040 		case SQLITE_DONE:
2041 			RETURN_FALSE;
2042 			break;
2043 
2044 		default:
2045 			php_sqlite3_error(result_obj->db_obj, "Unable to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(result_obj->stmt_obj->stmt)));
2046 	}
2047 }
2048 /* }}} */
2049 
2050 /* {{{ proto bool SQLite3Result::reset()
2051    Resets the result set back to the first row. */
PHP_METHODnull2052 PHP_METHOD(sqlite3result, reset)
2053 {
2054 	php_sqlite3_result *result_obj;
2055 	zval *object = ZEND_THIS;
2056 	result_obj = Z_SQLITE3_RESULT_P(object);
2057 
2058 	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
2059 
2060 	if (zend_parse_parameters_none() == FAILURE) {
2061 		return;
2062 	}
2063 
2064 	if (sqlite3_reset(result_obj->stmt_obj->stmt) != SQLITE_OK) {
2065 		RETURN_FALSE;
2066 	}
2067 
2068 	RETURN_TRUE;
2069 }
2070 /* }}} */
2071 
2072 /* {{{ proto bool SQLite3Result::finalize()
2073    Closes the result set. */
PHP_METHODnull2074 PHP_METHOD(sqlite3result, finalize)
2075 {
2076 	php_sqlite3_result *result_obj;
2077 	zval *object = ZEND_THIS;
2078 	result_obj = Z_SQLITE3_RESULT_P(object);
2079 
2080 	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
2081 
2082 	if (zend_parse_parameters_none() == FAILURE) {
2083 		return;
2084 	}
2085 
2086 	/* We need to finalize an internal statement */
2087 	if (result_obj->is_prepared_statement == 0) {
2088 		zend_llist_del_element(&(result_obj->db_obj->free_list), &result_obj->stmt_obj_zval,
2089 			(int (*)(void *, void *)) php_sqlite3_compare_stmt_zval_free);
2090 	} else {
2091 		sqlite3_reset(result_obj->stmt_obj->stmt);
2092 	}
2093 
2094 	RETURN_TRUE;
2095 }
2096 /* }}} */
2097 
2098 /* {{{ proto SQLite3Result::__construct()
2099    __constructor for SQLite3Result. */
PHP_METHODnull2100 PHP_METHOD(sqlite3result, __construct)
2101 {
2102 	zend_throw_exception(zend_ce_exception, "SQLite3Result cannot be directly instantiated", 0);
2103 }
2104 /* }}} */
2105 
2106 /* {{{ arginfo */
2107 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_open, 0, 0, 1)
2108 	ZEND_ARG_INFO(0, filename)
2109 	ZEND_ARG_INFO(0, flags)
2110 	ZEND_ARG_INFO(0, encryption_key)
2111 ZEND_END_ARG_INFO()
2112 
2113 ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_busytimeout, 0)
2114 	ZEND_ARG_INFO(0, ms)
2115 ZEND_END_ARG_INFO()
2116 
2117 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2118 ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_loadextension, 0)
2119 	ZEND_ARG_INFO(0, shared_library)
2120 ZEND_END_ARG_INFO()
2121 #endif
2122 
2123 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_escapestring, 0, 0, 1)
2124 	ZEND_ARG_INFO(0, value)
2125 ZEND_END_ARG_INFO()
2126 
2127 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_query, 0, 0, 1)
2128 	ZEND_ARG_INFO(0, query)
2129 ZEND_END_ARG_INFO()
2130 
2131 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_querysingle, 0, 0, 1)
2132 	ZEND_ARG_INFO(0, query)
2133 	ZEND_ARG_INFO(0, entire_row)
2134 ZEND_END_ARG_INFO()
2135 
2136 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createfunction, 0, 0, 2)
2137 	ZEND_ARG_INFO(0, name)
2138 	ZEND_ARG_INFO(0, callback)
2139 	ZEND_ARG_INFO(0, argument_count)
2140 	ZEND_ARG_INFO(0, flags)
2141 ZEND_END_ARG_INFO()
2142 
2143 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createaggregate, 0, 0, 3)
2144 	ZEND_ARG_INFO(0, name)
2145 	ZEND_ARG_INFO(0, step_callback)
2146 	ZEND_ARG_INFO(0, final_callback)
2147 	ZEND_ARG_INFO(0, argument_count)
2148 ZEND_END_ARG_INFO()
2149 
2150 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createcollation, 0, 0, 2)
2151 	ZEND_ARG_INFO(0, name)
2152 	ZEND_ARG_INFO(0, callback)
2153 ZEND_END_ARG_INFO()
2154 
2155 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_openblob, 0, 0, 3)
2156 	ZEND_ARG_INFO(0, table)
2157 	ZEND_ARG_INFO(0, column)
2158 	ZEND_ARG_INFO(0, rowid)
2159 	ZEND_ARG_INFO(0, dbname)
2160 	ZEND_ARG_INFO(0, flags)
2161 ZEND_END_ARG_INFO()
2162 
2163 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_enableexceptions, 0, 0, 0)
2164 	ZEND_ARG_INFO(0, enableExceptions)
2165 ZEND_END_ARG_INFO()
2166 
2167 #if SQLITE_VERSION_NUMBER >= 3006011
2168 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_backup, 0, 0, 1)
2169 	ZEND_ARG_INFO(0, destination_db)
2170 	ZEND_ARG_INFO(0, source_dbname)
2171 	ZEND_ARG_INFO(0, destination_dbname)
2172 ZEND_END_ARG_INFO()
2173 #endif
2174 
2175 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_bindparam, 0, 0, 2)
2176 	ZEND_ARG_INFO(0, param_number)
2177 	ZEND_ARG_INFO(1, param)
2178 	ZEND_ARG_INFO(0, type)
2179 ZEND_END_ARG_INFO()
2180 
2181 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_bindvalue, 0, 0, 2)
2182 	ZEND_ARG_INFO(0, param_number)
2183 	ZEND_ARG_INFO(0, param)
2184 	ZEND_ARG_INFO(0, type)
2185 ZEND_END_ARG_INFO()
2186 
2187 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_construct, 0, 0, 1)
2188 	ZEND_ARG_INFO(0, sqlite3)
2189 ZEND_END_ARG_INFO()
2190 
2191 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_getsql, 0, 0, 0)
2192 	ZEND_ARG_INFO(0, expanded)
2193 ZEND_END_ARG_INFO()
2194 
2195 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_columnname, 0, 0, 1)
2196 	ZEND_ARG_INFO(0, column_number)
2197 ZEND_END_ARG_INFO()
2198 
2199 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_columntype, 0, 0, 1)
2200 	ZEND_ARG_INFO(0, column_number)
2201 ZEND_END_ARG_INFO()
2202 
2203 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_fetcharray, 0, 0, 0)
2204 	ZEND_ARG_INFO(0, mode)
2205 ZEND_END_ARG_INFO()
2206 
2207 ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_enableextended, 0, 0, 1)
2208 	ZEND_ARG_INFO(0, enable)
2209 ZEND_END_ARG_INFO()
2210 
2211 ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_void, 0)
2212 ZEND_END_ARG_INFO()
2213 /* }}} */
2214 
2215 /* {{{ php_sqlite3_class_methods */
2216 static const zend_function_entry php_sqlite3_class_methods[] = {
2217 	PHP_ME(sqlite3,		open,						arginfo_sqlite3_open, ZEND_ACC_PUBLIC)
2218 	PHP_ME(sqlite3,		close,						arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2219 	PHP_ME(sqlite3,		exec,						arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
2220 	PHP_ME(sqlite3,		version,					arginfo_sqlite3_void, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
2221 	PHP_ME(sqlite3,		lastInsertRowID,			arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2222 	PHP_ME(sqlite3,		lastErrorCode,				arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2223 	PHP_ME(sqlite3,		lastExtendedErrorCode,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2224 	PHP_ME(sqlite3,		enableExtendedResultCodes,	arginfo_sqlite3_enableextended, ZEND_ACC_PUBLIC)
2225 	PHP_ME(sqlite3,		lastErrorMsg,				arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2226 	PHP_ME(sqlite3,		busyTimeout,				arginfo_sqlite3_busytimeout, ZEND_ACC_PUBLIC)
2227 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2228 	PHP_ME(sqlite3,		loadExtension,				arginfo_sqlite3_loadextension, ZEND_ACC_PUBLIC)
2229 #endif
2230 	PHP_ME(sqlite3,		changes,					arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2231 	PHP_ME(sqlite3,		escapeString,				arginfo_sqlite3_escapestring, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
2232 	PHP_ME(sqlite3,		prepare,					arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
2233 	PHP_ME(sqlite3,		query,						arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
2234 	PHP_ME(sqlite3,		querySingle,				arginfo_sqlite3_querysingle, ZEND_ACC_PUBLIC)
2235 	PHP_ME(sqlite3,		createFunction,				arginfo_sqlite3_createfunction, ZEND_ACC_PUBLIC)
2236 	PHP_ME(sqlite3,		createAggregate,			arginfo_sqlite3_createaggregate, ZEND_ACC_PUBLIC)
2237 	PHP_ME(sqlite3,		createCollation,			arginfo_sqlite3_createcollation, ZEND_ACC_PUBLIC)
2238 	PHP_ME(sqlite3,		openBlob,					arginfo_sqlite3_openblob, ZEND_ACC_PUBLIC)
2239 	PHP_ME(sqlite3,		enableExceptions,			arginfo_sqlite3_enableexceptions, ZEND_ACC_PUBLIC)
2240 #if SQLITE_VERSION_NUMBER >= 3006011
2241 	PHP_ME(sqlite3,		backup,						arginfo_sqlite3_backup, ZEND_ACC_PUBLIC)
2242 #endif
2243 	/* Aliases */
2244 	PHP_MALIAS(sqlite3,	__construct, open, arginfo_sqlite3_open, ZEND_ACC_PUBLIC)
2245 	PHP_FE_END
2246 };
2247 /* }}} */
2248 
2249 /* {{{ php_sqlite3_stmt_class_methods */
2250 static const zend_function_entry php_sqlite3_stmt_class_methods[] = {
2251 	PHP_ME(sqlite3stmt, paramCount,	arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2252 	PHP_ME(sqlite3stmt, close,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2253 	PHP_ME(sqlite3stmt, reset,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2254 	PHP_ME(sqlite3stmt, clear,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2255 	PHP_ME(sqlite3stmt, execute,	arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2256 	PHP_ME(sqlite3stmt, bindParam,	arginfo_sqlite3stmt_bindparam, ZEND_ACC_PUBLIC)
2257 	PHP_ME(sqlite3stmt, bindValue,	arginfo_sqlite3stmt_bindvalue, ZEND_ACC_PUBLIC)
2258 	PHP_ME(sqlite3stmt, readOnly,	arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2259 	PHP_ME(sqlite3stmt, getSQL,		arginfo_sqlite3stmt_getsql, ZEND_ACC_PUBLIC)
2260 	PHP_ME(sqlite3stmt, __construct, arginfo_sqlite3stmt_construct, ZEND_ACC_PRIVATE)
2261 	PHP_FE_END
2262 };
2263 /* }}} */
2264 
2265 /* {{{ php_sqlite3_result_class_methods */
2266 static const zend_function_entry php_sqlite3_result_class_methods[] = {
2267 	PHP_ME(sqlite3result, numColumns,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2268 	PHP_ME(sqlite3result, columnName,		arginfo_sqlite3result_columnname, ZEND_ACC_PUBLIC)
2269 	PHP_ME(sqlite3result, columnType,		arginfo_sqlite3result_columntype, ZEND_ACC_PUBLIC)
2270 	PHP_ME(sqlite3result, fetchArray,		arginfo_sqlite3result_fetcharray, ZEND_ACC_PUBLIC)
2271 	PHP_ME(sqlite3result, reset,			arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2272 	PHP_ME(sqlite3result, finalize,			arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
2273 	PHP_ME(sqlite3result, __construct, 		arginfo_sqlite3_void, ZEND_ACC_PRIVATE)
2274 	PHP_FE_END
2275 };
2276 /* }}} */
2277 
2278 /* {{{ Authorization Callback
2279 */
php_sqlite3_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4, const char *arg5, const char *arg6)2280 static int php_sqlite3_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4, const char *arg5, const char *arg6)
2281 {
2282 	switch (access_type) {
2283 		case SQLITE_ATTACH:
2284 		{
2285 			if (memcmp(arg3, ":memory:", sizeof(":memory:")) && *arg3) {
2286 				if (strncmp(arg3, "file:", 5) == 0) {
2287 					/* starts with "file:" */
2288 					if (!arg3[5]) {
2289 						return SQLITE_DENY;
2290 					}
2291 					if (php_check_open_basedir(arg3 + 5)) {
2292 						return SQLITE_DENY;
2293 					}
2294 				}
2295 				if (php_check_open_basedir(arg3)) {
2296 					return SQLITE_DENY;
2297 				}
2298 			}
2299 			return SQLITE_OK;
2300 		}
2301 
2302 		default:
2303 			/* access allowed */
2304 			return SQLITE_OK;
2305 	}
2306 }
2307 /* }}} */
2308 
2309 /* {{{ php_sqlite3_free_list_dtor
2310 */
php_sqlite3_free_list_dtor(void **item)2311 static void php_sqlite3_free_list_dtor(void **item)
2312 {
2313 	php_sqlite3_free_list *free_item = (php_sqlite3_free_list *)*item;
2314 
2315 	if (free_item->stmt_obj && free_item->stmt_obj->initialised) {
2316 		sqlite3_finalize(free_item->stmt_obj->stmt);
2317 		free_item->stmt_obj->initialised = 0;
2318 	}
2319 	efree(*item);
2320 }
2321 /* }}} */
2322 
php_sqlite3_compare_stmt_zval_free(php_sqlite3_free_list **free_list, zval *statement )2323 static int php_sqlite3_compare_stmt_zval_free(php_sqlite3_free_list **free_list, zval *statement ) /* {{{ */
2324 {
2325 	return  ((*free_list)->stmt_obj->initialised && Z_PTR_P(statement) == Z_PTR((*free_list)->stmt_obj_zval));
2326 }
2327 /* }}} */
2328 
php_sqlite3_compare_stmt_free( php_sqlite3_free_list **free_list, sqlite3_stmt *statement )2329 static int php_sqlite3_compare_stmt_free( php_sqlite3_free_list **free_list, sqlite3_stmt *statement ) /* {{{ */
2330 {
2331 	return ((*free_list)->stmt_obj->initialised && statement == (*free_list)->stmt_obj->stmt);
2332 }
2333 /* }}} */
2334 
php_sqlite3_object_free_storage(zend_object *object)2335 static void php_sqlite3_object_free_storage(zend_object *object) /* {{{ */
2336 {
2337 	php_sqlite3_db_object *intern = php_sqlite3_db_from_obj(object);
2338 	php_sqlite3_func *func;
2339 	php_sqlite3_collation *collation;
2340 
2341 	if (!intern) {
2342 		return;
2343 	}
2344 
2345 	while (intern->funcs) {
2346 		func = intern->funcs;
2347 		intern->funcs = func->next;
2348 		if (intern->initialised && intern->db) {
2349 			sqlite3_create_function(intern->db, func->func_name, func->argc, SQLITE_UTF8, func, NULL, NULL, NULL);
2350 		}
2351 
2352 		efree((char*)func->func_name);
2353 
2354 		if (!Z_ISUNDEF(func->func)) {
2355 			zval_ptr_dtor(&func->func);
2356 		}
2357 		if (!Z_ISUNDEF(func->step)) {
2358 			zval_ptr_dtor(&func->step);
2359 		}
2360 		if (!Z_ISUNDEF(func->fini)) {
2361 			zval_ptr_dtor(&func->fini);
2362 		}
2363 		efree(func);
2364 	}
2365 
2366 	while (intern->collations){
2367 		collation = intern->collations;
2368 		intern->collations = collation->next;
2369 		if (intern->initialised && intern->db){
2370 			sqlite3_create_collation(intern->db, collation->collation_name, SQLITE_UTF8, NULL, NULL);
2371 		}
2372 		efree((char*)collation->collation_name);
2373 		if (!Z_ISUNDEF(collation->cmp_func)) {
2374 			zval_ptr_dtor(&collation->cmp_func);
2375 		}
2376 		efree(collation);
2377 	}
2378 
2379 	if (intern->initialised && intern->db) {
2380 		sqlite3_close(intern->db);
2381 		intern->initialised = 0;
2382 	}
2383 
2384 	zend_object_std_dtor(&intern->zo);
2385 }
2386 /* }}} */
2387 
php_sqlite3_stmt_object_free_storage(zend_object *object)2388 static void php_sqlite3_stmt_object_free_storage(zend_object *object) /* {{{ */
2389 {
2390 	php_sqlite3_stmt *intern = php_sqlite3_stmt_from_obj(object);
2391 
2392 	if (!intern) {
2393 		return;
2394 	}
2395 
2396 	if (intern->bound_params) {
2397 		zend_hash_destroy(intern->bound_params);
2398 		FREE_HASHTABLE(intern->bound_params);
2399 		intern->bound_params = NULL;
2400 	}
2401 
2402 	if (intern->initialised) {
2403 		zend_llist_del_element(&(intern->db_obj->free_list), intern->stmt,
2404 			(int (*)(void *, void *)) php_sqlite3_compare_stmt_free);
2405 	}
2406 
2407 	if (!Z_ISUNDEF(intern->db_obj_zval)) {
2408 		zval_ptr_dtor(&intern->db_obj_zval);
2409 	}
2410 
2411 	zend_object_std_dtor(&intern->zo);
2412 }
2413 /* }}} */
2414 
php_sqlite3_result_object_free_storage(zend_object *object)2415 static void php_sqlite3_result_object_free_storage(zend_object *object) /* {{{ */
2416 {
2417 	php_sqlite3_result *intern = php_sqlite3_result_from_obj(object);
2418 
2419 	if (!intern) {
2420 		return;
2421 	}
2422 
2423 	if (!Z_ISNULL(intern->stmt_obj_zval)) {
2424 		if (intern->stmt_obj && intern->stmt_obj->initialised) {
2425 			sqlite3_reset(intern->stmt_obj->stmt);
2426 		}
2427 
2428 		zval_ptr_dtor(&intern->stmt_obj_zval);
2429 	}
2430 
2431 	zend_object_std_dtor(&intern->zo);
2432 }
2433 /* }}} */
2434 
php_sqlite3_object_new(zend_class_entry *class_type)2435 static zend_object *php_sqlite3_object_new(zend_class_entry *class_type) /* {{{ */
2436 {
2437 	php_sqlite3_db_object *intern;
2438 
2439 	/* Allocate memory for it */
2440 	intern = zend_object_alloc(sizeof(php_sqlite3_db_object), class_type);
2441 
2442 	/* Need to keep track of things to free */
2443 	zend_llist_init(&(intern->free_list),  sizeof(php_sqlite3_free_list *), (llist_dtor_func_t)php_sqlite3_free_list_dtor, 0);
2444 
2445 	zend_object_std_init(&intern->zo, class_type);
2446 	object_properties_init(&intern->zo, class_type);
2447 
2448 	intern->zo.handlers = &sqlite3_object_handlers;
2449 
2450 	return &intern->zo;
2451 }
2452 /* }}} */
2453 
php_sqlite3_stmt_object_new(zend_class_entry *class_type)2454 static zend_object *php_sqlite3_stmt_object_new(zend_class_entry *class_type) /* {{{ */
2455 {
2456 	php_sqlite3_stmt *intern;
2457 
2458 	/* Allocate memory for it */
2459 	intern = zend_object_alloc(sizeof(php_sqlite3_stmt), class_type);
2460 
2461 	zend_object_std_init(&intern->zo, class_type);
2462 	object_properties_init(&intern->zo, class_type);
2463 
2464 	intern->zo.handlers = &sqlite3_stmt_object_handlers;
2465 
2466 	return &intern->zo;
2467 }
2468 /* }}} */
2469 
php_sqlite3_result_object_new(zend_class_entry *class_type)2470 static zend_object *php_sqlite3_result_object_new(zend_class_entry *class_type) /* {{{ */
2471 {
2472 	php_sqlite3_result *intern;
2473 
2474 	/* Allocate memory for it */
2475 	intern = zend_object_alloc(sizeof(php_sqlite3_result), class_type);
2476 
2477 	zend_object_std_init(&intern->zo, class_type);
2478 	object_properties_init(&intern->zo, class_type);
2479 
2480 	intern->zo.handlers = &sqlite3_result_object_handlers;
2481 
2482 	return &intern->zo;
2483 }
2484 /* }}} */
2485 
sqlite3_param_dtor(zval *data)2486 static void sqlite3_param_dtor(zval *data) /* {{{ */
2487 {
2488 	struct php_sqlite3_bound_param *param = (struct php_sqlite3_bound_param*)Z_PTR_P(data);
2489 
2490 	if (param->name) {
2491 		zend_string_release_ex(param->name, 0);
2492 	}
2493 
2494 	if (!Z_ISNULL(param->parameter)) {
2495 		zval_ptr_dtor(&(param->parameter));
2496 		ZVAL_UNDEF(&param->parameter);
2497 	}
2498 	efree(param);
2499 }
2500 /* }}} */
2501 
2502 /* {{{ PHP_MINIT_FUNCTION
2503 */
PHP_MINIT_FUNCTIONnull2504 PHP_MINIT_FUNCTION(sqlite3)
2505 {
2506 	zend_class_entry ce;
2507 
2508 #if defined(ZTS)
2509 	/* Refuse to load if this wasn't a threasafe library loaded */
2510 	if (!sqlite3_threadsafe()) {
2511 		php_error_docref(NULL, E_WARNING, "A thread safe version of SQLite is required when using a thread safe version of PHP.");
2512 		return FAILURE;
2513 	}
2514 #endif
2515 
2516 	memcpy(&sqlite3_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
2517 	memcpy(&sqlite3_stmt_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
2518 	memcpy(&sqlite3_result_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
2519 
2520 	/* Register SQLite 3 Class */
2521 	INIT_CLASS_ENTRY(ce, "SQLite3", php_sqlite3_class_methods);
2522 	ce.create_object = php_sqlite3_object_new;
2523 	sqlite3_object_handlers.offset = XtOffsetOf(php_sqlite3_db_object, zo);
2524 	sqlite3_object_handlers.clone_obj = NULL;
2525 	sqlite3_object_handlers.free_obj = php_sqlite3_object_free_storage;
2526 	php_sqlite3_sc_entry = zend_register_internal_class(&ce);
2527 	php_sqlite3_sc_entry->serialize = zend_class_serialize_deny;
2528 	php_sqlite3_sc_entry->unserialize = zend_class_unserialize_deny;
2529 
2530 	/* Register SQLite 3 Prepared Statement Class */
2531 	INIT_CLASS_ENTRY(ce, "SQLite3Stmt", php_sqlite3_stmt_class_methods);
2532 	ce.create_object = php_sqlite3_stmt_object_new;
2533 	sqlite3_stmt_object_handlers.offset = XtOffsetOf(php_sqlite3_stmt, zo);
2534 	sqlite3_stmt_object_handlers.clone_obj = NULL;
2535 	sqlite3_stmt_object_handlers.free_obj = php_sqlite3_stmt_object_free_storage;
2536 	php_sqlite3_stmt_entry = zend_register_internal_class(&ce);
2537 	php_sqlite3_stmt_entry->serialize = zend_class_serialize_deny;
2538 	php_sqlite3_stmt_entry->unserialize = zend_class_unserialize_deny;
2539 
2540 	/* Register SQLite 3 Result Class */
2541 	INIT_CLASS_ENTRY(ce, "SQLite3Result", php_sqlite3_result_class_methods);
2542 	ce.create_object = php_sqlite3_result_object_new;
2543 	sqlite3_result_object_handlers.offset = XtOffsetOf(php_sqlite3_result, zo);
2544 	sqlite3_result_object_handlers.clone_obj = NULL;
2545 	sqlite3_result_object_handlers.free_obj = php_sqlite3_result_object_free_storage;
2546 	php_sqlite3_result_entry = zend_register_internal_class(&ce);
2547 	php_sqlite3_result_entry->serialize = zend_class_serialize_deny;
2548 	php_sqlite3_result_entry->unserialize = zend_class_unserialize_deny;
2549 
2550 	REGISTER_INI_ENTRIES();
2551 
2552 	REGISTER_LONG_CONSTANT("SQLITE3_ASSOC", PHP_SQLITE3_ASSOC, CONST_CS | CONST_PERSISTENT);
2553 	REGISTER_LONG_CONSTANT("SQLITE3_NUM", PHP_SQLITE3_NUM, CONST_CS | CONST_PERSISTENT);
2554 	REGISTER_LONG_CONSTANT("SQLITE3_BOTH", PHP_SQLITE3_BOTH, CONST_CS | CONST_PERSISTENT);
2555 
2556 	REGISTER_LONG_CONSTANT("SQLITE3_INTEGER", SQLITE_INTEGER, CONST_CS | CONST_PERSISTENT);
2557 	REGISTER_LONG_CONSTANT("SQLITE3_FLOAT", SQLITE_FLOAT, CONST_CS | CONST_PERSISTENT);
2558 	REGISTER_LONG_CONSTANT("SQLITE3_TEXT", SQLITE3_TEXT, CONST_CS | CONST_PERSISTENT);
2559 	REGISTER_LONG_CONSTANT("SQLITE3_BLOB", SQLITE_BLOB, CONST_CS | CONST_PERSISTENT);
2560 	REGISTER_LONG_CONSTANT("SQLITE3_NULL", SQLITE_NULL, CONST_CS | CONST_PERSISTENT);
2561 
2562 	REGISTER_LONG_CONSTANT("SQLITE3_OPEN_READONLY", SQLITE_OPEN_READONLY, CONST_CS | CONST_PERSISTENT);
2563 	REGISTER_LONG_CONSTANT("SQLITE3_OPEN_READWRITE", SQLITE_OPEN_READWRITE, CONST_CS | CONST_PERSISTENT);
2564 	REGISTER_LONG_CONSTANT("SQLITE3_OPEN_CREATE", SQLITE_OPEN_CREATE, CONST_CS | CONST_PERSISTENT);
2565 
2566 #ifdef SQLITE_DETERMINISTIC
2567 	REGISTER_LONG_CONSTANT("SQLITE3_DETERMINISTIC", SQLITE_DETERMINISTIC, CONST_CS | CONST_PERSISTENT);
2568 #endif
2569 
2570 	return SUCCESS;
2571 }
2572 /* }}} */
2573 
2574 /* {{{ PHP_MSHUTDOWN_FUNCTION
2575 */
PHP_MSHUTDOWN_FUNCTIONnull2576 PHP_MSHUTDOWN_FUNCTION(sqlite3)
2577 {
2578 	UNREGISTER_INI_ENTRIES();
2579 
2580 	return SUCCESS;
2581 }
2582 /* }}} */
2583 
2584 /* {{{ PHP_MINFO_FUNCTION
2585 */
PHP_MINFO_FUNCTIONnull2586 PHP_MINFO_FUNCTION(sqlite3)
2587 {
2588 	php_info_print_table_start();
2589 	php_info_print_table_header(2, "SQLite3 support", "enabled");
2590 	php_info_print_table_row(2, "SQLite Library", sqlite3_libversion());
2591 	php_info_print_table_end();
2592 
2593 	DISPLAY_INI_ENTRIES();
2594 }
2595 /* }}} */
2596 
2597 /* {{{ PHP_GINIT_FUNCTION
2598 */
PHP_GINIT_FUNCTIONnull2599 static PHP_GINIT_FUNCTION(sqlite3)
2600 {
2601 #if defined(COMPILE_DL_SQLITE3) && defined(ZTS)
2602 	ZEND_TSRMLS_CACHE_UPDATE();
2603 #endif
2604 	memset(sqlite3_globals, 0, sizeof(*sqlite3_globals));
2605 }
2606 /* }}} */
2607 
2608 /* {{{ sqlite3_module_entry
2609 */
2610 zend_module_entry sqlite3_module_entry = {
2611 	STANDARD_MODULE_HEADER,
2612 	"sqlite3",
2613 	NULL,
2614 	PHP_MINIT(sqlite3),
2615 	PHP_MSHUTDOWN(sqlite3),
2616 	NULL,
2617 	NULL,
2618 	PHP_MINFO(sqlite3),
2619 	PHP_SQLITE3_VERSION,
2620 	PHP_MODULE_GLOBALS(sqlite3),
2621 	PHP_GINIT(sqlite3),
2622 	NULL,
2623 	NULL,
2624 	STANDARD_MODULE_PROPERTIES_EX
2625 };
2626 /* }}} */
2627 
2628 #ifdef COMPILE_DL_SQLITE3
2629 #ifdef ZTS
2630 ZEND_TSRMLS_CACHE_DEFINE()
2631 #endif
2632 ZEND_GET_MODULE(sqlite3)
2633 #endif
2634