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