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