Fix empty arrays parsing
[m6w6/ext-pq] / src / php_pq_misc.c
1 /*
2 +--------------------------------------------------------------------+
3 | PECL :: pq |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted provided that the conditions mentioned |
7 | in the accompanying LICENSE file are met. |
8 +--------------------------------------------------------------------+
9 | Copyright (c) 2013, Michael Wallner <mike@php.net> |
10 +--------------------------------------------------------------------+
11 */
12
13 #ifdef HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #include <php.h>
18 #include <ext/date/php_date.h>
19 #include <ext/standard/php_string.h>
20
21 #include <Zend/zend_interfaces.h>
22
23 #include <libpq/libpq-fs.h>
24
25 #include "php_pq.h"
26 #include "php_pqexc.h"
27 #include "php_pq_misc.h"
28 #include "php_pqconn_event.h"
29 #undef PHP_PQ_TYPE
30 #include "php_pq_type.h"
31
32
33 /* clear result object associated with a result handle */
34 void php_pqres_clear(PGresult *r) {
35 php_pq_object_t *o = PQresultInstanceData(r, php_pqconn_event);
36
37 if (o) {
38 php_pq_object_delref(o);
39 } else {
40 PQclear(r);
41 }
42 }
43
44 /* clear any asynchronous results */
45 void php_pqconn_clear(PGconn *conn) {
46 PGresult *r;
47 php_pqconn_event_data_t *evdata = PQinstanceData(conn, php_pqconn_event);
48
49 while ((r = PQgetResult(conn))) {
50 php_pqres_clear(r);
51 }
52
53 if (evdata && evdata->obj) {
54 if (php_pq_callback_is_enabled(&evdata->obj->intern->onevent)) {
55 if (php_pq_callback_is_locked(&evdata->obj->intern->onevent)) {
56 php_pq_callback_disable(&evdata->obj->intern->onevent);
57 } else {
58 php_pq_callback_dtor(&evdata->obj->intern->onevent);
59 }
60 }
61 }
62 }
63
64 /* safe wrappers to clear any asynchronous wrappers before querying synchronously */
65 PGresult *php_pq_exec(PGconn *conn, const char *query) {
66 php_pqconn_clear(conn);
67 return PQexec(conn, query);
68 }
69 PGresult *php_pq_exec_params(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const * paramValues, const int *paramLengths, const int *paramFormats, int resultFormat) {
70 php_pqconn_clear(conn);
71 return PQexecParams(conn, command, nParams, paramTypes, paramValues, paramLengths, paramFormats, resultFormat);
72 }
73 PGresult *php_pq_prepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes) {
74 php_pqconn_clear(conn);
75 return PQprepare(conn, stmtName, query, nParams, paramTypes);
76 }
77 PGresult *php_pq_exec_prepared(PGconn *conn, const char *stmtName, int nParams, const char *const * paramValues, const int *paramLengths, const int *paramFormats, int resultFormat) {
78 php_pqconn_clear(conn);
79 return PQexecPrepared(conn, stmtName, nParams, paramValues, paramLengths, paramFormats, resultFormat);
80 }
81
82 char *php_pq_rtrim(char *e)
83 {
84 size_t l = strlen(e);
85
86 while (l-- > 0 && e[l] == '\n') {
87 e[l] = '\0';
88 }
89 return e;
90 }
91
92 const char *php_pq_strmode(long mode)
93 {
94 switch (mode & (INV_READ|INV_WRITE)) {
95 case INV_READ|INV_WRITE:
96 return "rw";
97 case INV_READ:
98 return "r";
99 case INV_WRITE:
100 return "w";
101 default:
102 return "-";
103 }
104 }
105
106 int php_pq_compare_index(const void *lptr, const void *rptr)
107 {
108 zend_ulong l = ((const Bucket *) lptr)->h;
109 zend_ulong r = ((const Bucket *) rptr)->h;
110
111 if (l < r) {
112 return -1;
113 }
114 if (l > r) {
115 return 1;
116 }
117 return 0;
118 }
119
120 void php_pq_hash_ptr_dtor(zval *p)
121 {
122 efree(Z_PTR_P(p));
123 }
124
125 zend_class_entry *php_pqdt_class_entry;
126
127 ZEND_BEGIN_ARG_INFO_EX(ai_pqdt_to_string, 0, 0, 0)
128 ZEND_END_ARG_INFO();
129 static PHP_METHOD(pqdt, __toString)
130 {
131 zval rv, tmp;
132
133 ZVAL_NULL(&rv);
134 zend_call_method_with_1_params(getThis(), php_pqdt_class_entry, NULL, "format", &rv,
135 zend_read_property(php_pqdt_class_entry, getThis(), ZEND_STRL("format"), 0, &tmp));
136 RETVAL_ZVAL(&rv, 1, 1);
137 }
138
139 ZEND_BEGIN_ARG_INFO_EX(ai_pqdt_create_from_format, 0, 0, 2)
140 ZEND_ARG_INFO(0, format)
141 ZEND_ARG_INFO(0, datetime)
142 #if PHP_VERSION_ID >= 70200
143 ZEND_ARG_OBJ_INFO(0, object, DateTimeZone, 1)
144 #else
145 ZEND_ARG_INFO(0, timezone)
146 #endif
147 ZEND_END_ARG_INFO();
148 static PHP_METHOD(pqdt, createFromFormat)
149 {
150 zend_error_handling zeh;
151 char *fmt_str, *dt_str;
152 size_t fmt_len, dt_len;
153 zval *ztz = NULL;
154 ZEND_RESULT_CODE rv;
155
156 zend_replace_error_handling(EH_THROW, exce(EX_INVALID_ARGUMENT), &zeh);
157 rv = zend_parse_parameters(ZEND_NUM_ARGS(), "ss|O", &fmt_str, &fmt_len, &dt_str, &dt_len, &ztz, php_date_get_timezone_ce());
158 zend_restore_error_handling(&zeh);
159
160 if (SUCCESS == rv) {
161 php_pqdt_from_string(return_value, fmt_str, dt_str, dt_len, "Y-m-d H:i:s.uO", ztz);
162 }
163 }
164
165 static zend_function_entry php_pqdt_methods[] = {
166 PHP_ME(pqdt, createFromFormat, ai_pqdt_create_from_format, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
167 PHP_ME(pqdt, __toString, ai_pqdt_to_string, ZEND_ACC_PUBLIC)
168 PHP_MALIAS(pqdt, jsonSerialize, __toString, ai_pqdt_to_string, ZEND_ACC_PUBLIC)
169 {0}
170 };
171
172 zval *php_pqdt_from_string(zval *zv, char *input_fmt, char *dt_str, size_t dt_len, char *output_fmt, zval *ztimezone)
173 {
174 php_date_obj *dobj;
175
176 php_date_instantiate(php_pqdt_class_entry, zv);
177 dobj = php_date_obj_from_obj(Z_OBJ_P(zv));
178 if (!php_date_initialize(dobj, dt_str, dt_len, input_fmt, ztimezone, 1)) {
179 zval_dtor(zv);
180 ZVAL_NULL(zv);
181 } else if (output_fmt) {
182 zend_update_property_string(php_pqdt_class_entry, zv, ZEND_STRL("format"), output_fmt);
183 }
184
185 return zv;
186 }
187
188 zend_string *php_pqdt_to_string(zval *zdt, const char *format)
189 {
190 zval rv;
191
192 ZVAL_NULL(&rv);
193
194 if (Z_OBJ_HT_P(zdt)->cast_object
195 && SUCCESS == Z_OBJ_HT_P(zdt)->cast_object(zdt, &rv, IS_STRING)
196 ) {
197 return Z_STR(rv);
198 } else if (instanceof_function(Z_OBJCE_P(zdt), php_date_get_date_ce())) {
199 zval rv, zfmt;
200
201 ZVAL_NULL(&rv);
202 ZVAL_STRING(&zfmt, format);
203 zend_call_method_with_1_params(zdt, Z_OBJCE_P(zdt), NULL, "format", &rv, &zfmt);
204 zval_ptr_dtor(&zfmt);
205
206 if (Z_TYPE(rv) == IS_STRING) {
207 return Z_STR(rv);
208 }
209 zval_ptr_dtor(&rv);
210 }
211
212 return NULL;
213 }
214
215 zend_class_entry *php_pqconv_class_entry;
216
217 ZEND_BEGIN_ARG_INFO_EX(ai_pqconv_convert_types, 0, 0, 0)
218 ZEND_END_ARG_INFO();
219
220 ZEND_BEGIN_ARG_INFO_EX(ai_pqconv_convert_from_string, 0, 0, 2)
221 ZEND_ARG_INFO(0, data)
222 ZEND_ARG_INFO(0, type)
223 ZEND_END_ARG_INFO();
224
225 ZEND_BEGIN_ARG_INFO_EX(ai_pqconv_convert_to_string, 0, 0, 2)
226 ZEND_ARG_INFO(0, data)
227 ZEND_ARG_INFO(0, type)
228 ZEND_END_ARG_INFO();
229
230 zend_function_entry php_pqconv_methods[] = {
231 PHP_ABSTRACT_ME(pqconv, convertTypes, ai_pqconv_convert_types)
232 PHP_ABSTRACT_ME(pqconv, convertFromString, ai_pqconv_convert_from_string)
233 PHP_ABSTRACT_ME(pqconv, convertToString, ai_pqconv_convert_to_string)
234 {0}
235 };
236
237
238 PHP_MINIT_FUNCTION(pq_misc)
239 {
240 zend_class_entry *json, ce = {0};
241
242 INIT_NS_CLASS_ENTRY(ce, "pq", "Converter", php_pqconv_methods);
243 php_pqconv_class_entry = zend_register_internal_interface(&ce);
244
245 memset(&ce, 0, sizeof(ce));
246 INIT_NS_CLASS_ENTRY(ce ,"pq", "DateTime", php_pqdt_methods);
247 php_pqdt_class_entry = zend_register_internal_class_ex(&ce, php_date_get_date_ce());
248
249 zend_declare_property_stringl(php_pqdt_class_entry, ZEND_STRL("format"), ZEND_STRL("Y-m-d H:i:s.uO"), ZEND_ACC_PUBLIC);
250
251 /* stop reading this file right here! */
252 if ((json = zend_hash_str_find_ptr(CG(class_table), ZEND_STRL("jsonserializable")))) {
253 zend_class_implements(php_pqdt_class_entry, 1, json);
254 }
255
256 return SUCCESS;
257 }
258
259 typedef struct _HashTableList {
260 zval arr;
261 struct _HashTableList *parent;
262 } HashTableList;
263
264 typedef struct _ArrayParserState {
265 const char *ptr, *end;
266 HashTableList *list;
267 php_pqres_t *res;
268 Oid typ;
269 unsigned quotes:1;
270 unsigned escaped:1;
271 } ArrayParserState;
272
273 static char caa(ArrayParserState *a, const char *any, unsigned advance)
274 {
275 const char *p = any;
276
277 do {
278 if (*p == *a->ptr) {
279 a->ptr += advance;
280 return *p;
281 }
282 } while (*++p);
283
284 php_error_docref(NULL, E_WARNING, "Failed to parse array: expected one of '%s', got '%c'", any, *a->ptr); \
285 return 0;
286 }
287
288 static ZEND_RESULT_CODE add_element(ArrayParserState *a, const char *start)
289 {
290 zval zelem;
291 zend_string *zstr = zend_string_init(start, a->ptr - start, 0);
292
293 if (a->quotes) {
294 php_stripslashes(zstr);
295 ZVAL_STR(&zelem, zstr);
296 } else if (!zend_string_equals_literal(zstr, "NULL")) {
297 ZVAL_STR(&zelem, zstr);
298 } else {
299 zend_string_release(zstr);
300 ZVAL_NULL(&zelem);
301 }
302
303 if (!ZVAL_IS_NULL(&zelem)) {
304 php_pqres_typed_zval(a->res, a->typ, &zelem);
305 }
306
307 add_next_index_zval(&a->list->arr, &zelem);
308 return SUCCESS;
309 }
310
311 static ZEND_RESULT_CODE parse_array(ArrayParserState *a);
312
313 static ZEND_RESULT_CODE parse_element(ArrayParserState *a, char delim)
314 {
315 const char *el;
316
317 switch (*a->ptr) {
318 case '{':
319 return parse_array(a);
320
321 case '}':
322 return SUCCESS;
323
324 case '"':
325 a->quotes = 1;
326 ++a->ptr;
327 break;
328 }
329
330 for (el = a->ptr; a->ptr < a->end; ++a->ptr) {
331 switch (*a->ptr) {
332 case '\\':
333 a->escaped = !a->escaped;
334 break;
335
336 case '"':
337 if (a->escaped) {
338 a->escaped = 0;
339 } else if (a->quotes) {
340 if (SUCCESS != add_element(a, el)) {
341 return FAILURE;
342 }
343 a->quotes = 0;
344 ++a->ptr;
345 return SUCCESS;
346 } else {
347 php_error_docref(NULL, E_WARNING, "Failed to parse element, unexpected quote: '%.*s'", (int) (a->ptr - el), el);
348 return FAILURE;
349 }
350 break;
351
352 default:
353 if (delim != *a->ptr) {
354 a->escaped = 0;
355 break;
356 }
357 /* no break */
358 case '}':
359 if (!a->quotes) {
360 return add_element(a, el);
361 }
362 break;
363
364 }
365 }
366
367 php_error_docref(NULL, E_WARNING, "Failed to parse element, reached end of input");
368 return FAILURE;
369 }
370
371 static ZEND_RESULT_CODE parse_elements(ArrayParserState *a)
372 {
373 char delims[] = {'}', (char) PHP_PQ_DELIM_OF_ARRAY(a->typ), 0};
374
375 while (SUCCESS == parse_element(a, delims[1])) {
376 switch (caa(a, delims, 0)) {
377 case 0:
378 return FAILURE;
379
380 case '}':
381 return SUCCESS;
382
383 default:
384 if (!*++a->ptr) {
385 php_error_docref(NULL, E_WARNING, "Failed to parse elements, reached end of input");
386 return FAILURE;
387 }
388 break;
389 }
390 }
391
392 return FAILURE;
393 }
394
395 static ZEND_RESULT_CODE parse_array(ArrayParserState *a)
396 {
397 HashTableList *list;
398
399 if (!caa(a, "{", 1)) {
400 return FAILURE;
401 }
402
403 list = ecalloc(1, sizeof(*list));
404 array_init(&list->arr);
405
406 if (a->list) {
407 add_next_index_zval(&a->list->arr, &list->arr);
408 list->parent = a->list;
409 }
410 a->list = list;
411
412 if (SUCCESS != parse_elements(a)) {
413 return FAILURE;
414 }
415
416 if (!caa(a, "}", 1)) {
417 return FAILURE;
418 }
419
420 /* step one level back up */
421 if (a->list->parent) {
422 HashTableList *l = a->list->parent;
423
424 efree(a->list);
425 a->list = l;
426 }
427
428 return SUCCESS;
429 }
430
431 HashTable *php_pq_parse_array(php_pqres_t *res, const char *val_str, size_t val_len, Oid typ)
432 {
433 HashTable *ht = NULL;
434 ArrayParserState a = {0};
435
436 a.typ = typ;
437 a.ptr = val_str;
438 a.end = val_str + val_len;
439 a.res = res;
440
441 if (SUCCESS != parse_array(&a)) {
442 while (a.list) {
443 HashTableList *l = a.list->parent;
444
445 zval_dtor(&a.list->arr);
446 efree(a.list);
447 a.list = l;
448 }
449 return ht;
450 }
451
452 if (*a.ptr) {
453 php_error_docref(NULL, E_NOTICE, "Trailing input: '%s'", a.ptr);
454 }
455
456 while (a.list) {
457 HashTableList *l = a.list->parent;
458
459 ht = Z_ARRVAL(a.list->arr);
460 efree(a.list);
461 a.list = l;
462 }
463
464 return ht;
465 }
466
467
468 /*
469 * Local variables:
470 * tab-width: 4
471 * c-basic-offset: 4
472 * End:
473 * vim600: noet sw=4 ts=4 fdm=marker
474 * vim<600: noet sw=4 ts=4
475 */