xref: /PHP-8.2/ext/date/php_date.c (revision 0016b308)
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: Derick Rethans <derick@derickrethans.nl>                    |
14    +----------------------------------------------------------------------+
15  */
16 
17 #include "php.h"
18 #include "php_streams.h"
19 #include "php_main.h"
20 #include "php_globals.h"
21 #include "php_ini.h"
22 #include "ext/standard/info.h"
23 #include "ext/standard/php_versioning.h"
24 #include "ext/standard/php_math.h"
25 #include "php_date.h"
26 #include "zend_interfaces.h"
27 #include "zend_exceptions.h"
28 #include "lib/timelib.h"
29 #include "lib/timelib_private.h"
30 #ifndef PHP_WIN32
31 #include <time.h>
32 #else
33 #include "win32/time.h"
34 #endif
35 
36 #ifdef PHP_WIN32
php_date_llabs(__int64 i)37 static __inline __int64 php_date_llabs( __int64 i ) { return i >= 0? i: -i; }
38 #elif defined(__GNUC__) && __GNUC__ < 3
php_date_llabs(__int64_t i)39 static __inline __int64_t php_date_llabs( __int64_t i ) { return i >= 0 ? i : -i; }
40 #else
php_date_llabs(long long i)41 static inline long long php_date_llabs( long long i ) { return i >= 0 ? i : -i; }
42 #endif
43 
44 #ifdef PHP_WIN32
45 #define DATE_I64_BUF_LEN 65
46 # define DATE_I64A(i, s, len) _i64toa_s(i, s, len, 10)
47 # define DATE_A64I(i, s) i = _atoi64(s)
48 #else
49 #define DATE_I64_BUF_LEN 65
50 # define DATE_I64A(i, s, len) \
51 	do { \
52 		int st = snprintf(s, len, "%lld", i); \
53 		s[st] = '\0'; \
54 	} while (0);
55 #define DATE_A64I(i, s) i = strtoll(s, NULL, 10)
56 #endif
57 
php_time(void)58 PHPAPI time_t php_time(void)
59 {
60 #ifdef HAVE_GETTIMEOFDAY
61 	struct timeval tm;
62 
63 	if (UNEXPECTED(gettimeofday(&tm, NULL) != SUCCESS)) {
64 		/* fallback, can't reasonably happen */
65 		return time(NULL);
66 	}
67 
68 	return tm.tv_sec;
69 #else
70 	return time(NULL);
71 #endif
72 }
73 
74 /*
75  * RFC822, Section 5.1: http://www.ietf.org/rfc/rfc822.txt
76  *  date-time   =  [ day "," ] date time        ; dd mm yy hh:mm:ss zzz
77  *  day         =  "Mon"  / "Tue" /  "Wed"  / "Thu"  /  "Fri"  / "Sat" /  "Sun"
78  *  date        =  1*2DIGIT month 2DIGIT        ; day month year e.g. 20 Jun 82
79  *  month       =  "Jan"  /  "Feb" /  "Mar"  /  "Apr"  /  "May"  /  "Jun" /  "Jul"  /  "Aug"  /  "Sep"  /  "Oct" /  "Nov"  /  "Dec"
80  *  time        =  hour zone                    ; ANSI and Military
81  *  hour        =  2DIGIT ":" 2DIGIT [":" 2DIGIT] ; 00:00:00 - 23:59:59
82  *  zone        =  "UT"  / "GMT"  /  "EST" / "EDT"  /  "CST" / "CDT"  /  "MST" / "MDT"  /  "PST" / "PDT"  /  1ALPHA  / ( ("+" / "-") 4DIGIT )
83  */
84 #define DATE_FORMAT_RFC822   "D, d M y H:i:s O"
85 
86 /*
87  * RFC850, Section 2.1.4: http://www.ietf.org/rfc/rfc850.txt
88  *  Format must be acceptable both to the ARPANET and to the getdate routine.
89  *  One format that is acceptable to both is Weekday, DD-Mon-YY HH:MM:SS TIMEZONE
90  *  TIMEZONE can be any timezone name (3 or more letters)
91  */
92 #define DATE_FORMAT_RFC850   "l, d-M-y H:i:s T"
93 
94 /*
95  * RFC1036, Section 2.1.2: http://www.ietf.org/rfc/rfc1036.txt
96  *  Its format must be acceptable both in RFC-822 and to the getdate(3)
97  *  Wdy, DD Mon YY HH:MM:SS TIMEZONE
98  *  There is no hope of having a complete list of timezones.  Universal
99  *  Time (GMT), the North American timezones (PST, PDT, MST, MDT, CST,
100  *  CDT, EST, EDT) and the +/-hhmm offset specified in RFC-822 should be supported.
101  */
102 #define DATE_FORMAT_RFC1036  "D, d M y H:i:s O"
103 
104 /*
105  * RFC1123, Section 5.2.14: http://www.ietf.org/rfc/rfc1123.txt
106  *  RFC-822 Date and Time Specification: RFC-822 Section 5
107  *  The syntax for the date is hereby changed to: date = 1*2DIGIT month 2*4DIGIT
108  */
109 #define DATE_FORMAT_RFC1123  "D, d M Y H:i:s O"
110 
111 /*
112  * RFC7231, Section 7.1.1: http://tools.ietf.org/html/rfc7231
113  */
114 #define DATE_FORMAT_RFC7231  "D, d M Y H:i:s \\G\\M\\T"
115 
116 /*
117  * RFC2822, Section 3.3: http://www.ietf.org/rfc/rfc2822.txt
118  *  FWS             =       ([*WSP CRLF] 1*WSP) /   ; Folding white space
119  *  CFWS            =       *([FWS] comment) (([FWS] comment) / FWS)
120  *
121  *  date-time       =       [ day-of-week "," ] date FWS time [CFWS]
122  *  day-of-week     =       ([FWS] day-name)
123  *  day-name        =       "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun"
124  *  date            =       day month year
125  *  year            =       4*DIGIT
126  *  month           =       (FWS month-name FWS)
127  *  month-name      =       "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
128  *  day             =       ([FWS] 1*2DIGIT)
129  *  time            =       time-of-day FWS zone
130  *  time-of-day     =       hour ":" minute [ ":" second ]
131  *  hour            =       2DIGIT
132  *  minute          =       2DIGIT
133  *  second          =       2DIGIT
134  *  zone            =       (( "+" / "-" ) 4DIGIT)
135  */
136 #define DATE_FORMAT_RFC2822  "D, d M Y H:i:s O"
137 
138 /*
139  * RFC3339, Section 5.6: http://www.ietf.org/rfc/rfc3339.txt
140  *  date-fullyear   = 4DIGIT
141  *  date-month      = 2DIGIT  ; 01-12
142  *  date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on month/year
143  *
144  *  time-hour       = 2DIGIT  ; 00-23
145  *  time-minute     = 2DIGIT  ; 00-59
146  *  time-second     = 2DIGIT  ; 00-58, 00-59, 00-60 based on leap second rules
147  *
148  *  time-secfrac    = "." 1*DIGIT
149  *  time-numoffset  = ("+" / "-") time-hour ":" time-minute
150  *  time-offset     = "Z" / time-numoffset
151  *
152  *  partial-time    = time-hour ":" time-minute ":" time-second [time-secfrac]
153  *  full-date       = date-fullyear "-" date-month "-" date-mday
154  *  full-time       = partial-time time-offset
155  *
156  *  date-time       = full-date "T" full-time
157  */
158 #define DATE_FORMAT_RFC3339  "Y-m-d\\TH:i:sP"
159 
160 /*
161  * This format does not technically match the ISO 8601 standard, as it does not
162  * use : in the UTC offset format specifier. This is kept for BC reasons. The
163  * DATE_FORMAT_ISO8601_EXPANDED format does correct this, as well as adding
164  * support for years out side of the traditional 0000-9999 range.
165  */
166 #define DATE_FORMAT_ISO8601  "Y-m-d\\TH:i:sO"
167 
168 /* ISO 8601:2004(E)
169  *
170  * Section 3.5 Expansion:
171  * By mutual agreement of the partners in information interchange, it is
172  * permitted to expand the component identifying the calendar year, which is
173  * otherwise limited to four digits. This enables reference to dates and times
174  * in calendar years outside the range supported by complete representations,
175  * i.e. before the start of the year [0000] or after the end of the year
176  * [9999]."
177  *
178  * Section 4.1.2.4 Expanded representations:
179  * If, by agreement, expanded representations are used, the formats shall be as
180  * specified below. The interchange parties shall agree the additional number of
181  * digits in the time element year. In the examples below it has been agreed to
182  * expand the time element year with two digits.
183  * Extended format: ±YYYYY-MM-DD
184  * Example: +001985-04-12
185  *
186  * PHP's year expansion digits are variable.
187  */
188 #define DATE_FORMAT_ISO8601_EXPANDED    "X-m-d\\TH:i:sP"
189 
190 /* Internal Only
191  * This format only extends the year when needed, keeping the 'P' format with
192  * colon for UTC offsets
193  */
194 #define DATE_FORMAT_ISO8601_LARGE_YEAR  "x-m-d\\TH:i:sP"
195 
196 /*
197  * RFC3339, Appendix A: http://www.ietf.org/rfc/rfc3339.txt
198  *  ISO 8601 also requires (in section 5.3.1.3) that a decimal fraction
199  *  be proceeded by a "0" if less than unity.  Annex B.2 of ISO 8601
200  *  gives examples where the decimal fractions are not preceded by a "0".
201  *  This grammar assumes section 5.3.1.3 is correct and that Annex B.2 is
202  *  in error.
203  */
204 #define DATE_FORMAT_RFC3339_EXTENDED  "Y-m-d\\TH:i:s.vP"
205 
206 /*
207  * This comes from various sources that like to contradict. I'm going with the
208  * format here because of:
209  * http://msdn.microsoft.com/en-us/library/windows/desktop/aa384321%28v=vs.85%29.aspx
210  * and http://curl.haxx.se/rfc/cookie_spec.html
211  */
212 #define DATE_FORMAT_COOKIE   "l, d-M-Y H:i:s T"
213 
214 #define SUNFUNCS_RET_TIMESTAMP 0
215 #define SUNFUNCS_RET_STRING    1
216 #define SUNFUNCS_RET_DOUBLE    2
217 
218 #define PHP_DATE_TIMEZONE_GROUP_AFRICA     0x0001
219 #define PHP_DATE_TIMEZONE_GROUP_AMERICA    0x0002
220 #define PHP_DATE_TIMEZONE_GROUP_ANTARCTICA 0x0004
221 #define PHP_DATE_TIMEZONE_GROUP_ARCTIC     0x0008
222 #define PHP_DATE_TIMEZONE_GROUP_ASIA       0x0010
223 #define PHP_DATE_TIMEZONE_GROUP_ATLANTIC   0x0020
224 #define PHP_DATE_TIMEZONE_GROUP_AUSTRALIA  0x0040
225 #define PHP_DATE_TIMEZONE_GROUP_EUROPE     0x0080
226 #define PHP_DATE_TIMEZONE_GROUP_INDIAN     0x0100
227 #define PHP_DATE_TIMEZONE_GROUP_PACIFIC    0x0200
228 #define PHP_DATE_TIMEZONE_GROUP_UTC        0x0400
229 #define PHP_DATE_TIMEZONE_GROUP_ALL        0x07FF
230 #define PHP_DATE_TIMEZONE_GROUP_ALL_W_BC   0x0FFF
231 #define PHP_DATE_TIMEZONE_PER_COUNTRY      0x1000
232 
233 #define PHP_DATE_PERIOD_EXCLUDE_START_DATE 0x0001
234 #define PHP_DATE_PERIOD_INCLUDE_END_DATE   0x0002
235 
236 #include "php_date_arginfo.h"
237 
238 static const char* guess_timezone(const timelib_tzdb *tzdb);
239 static void date_register_classes(void);
240 /* }}} */
241 
242 ZEND_DECLARE_MODULE_GLOBALS(date)
243 static PHP_GINIT_FUNCTION(date);
244 
245 /* True global */
246 timelib_tzdb *php_date_global_timezone_db;
247 int php_date_global_timezone_db_enabled;
248 
249 #define DATE_DEFAULT_LATITUDE "31.7667"
250 #define DATE_DEFAULT_LONGITUDE "35.2333"
251 
252 /* on 90'50; common sunset declaration (start of sun body appear) */
253 #define DATE_SUNSET_ZENITH "90.833333"
254 
255 /* on 90'50; common sunrise declaration (sun body disappeared) */
256 #define DATE_SUNRISE_ZENITH "90.833333"
257 
258 static PHP_INI_MH(OnUpdate_date_timezone);
259 
260 /* {{{ INI Settings */
261 PHP_INI_BEGIN()
262 	STD_PHP_INI_ENTRY("date.timezone", "UTC", PHP_INI_ALL, OnUpdate_date_timezone, default_timezone, zend_date_globals, date_globals)
263 	PHP_INI_ENTRY("date.default_latitude",           DATE_DEFAULT_LATITUDE,        PHP_INI_ALL, NULL)
264 	PHP_INI_ENTRY("date.default_longitude",          DATE_DEFAULT_LONGITUDE,       PHP_INI_ALL, NULL)
265 	PHP_INI_ENTRY("date.sunset_zenith",              DATE_SUNSET_ZENITH,           PHP_INI_ALL, NULL)
266 	PHP_INI_ENTRY("date.sunrise_zenith",             DATE_SUNRISE_ZENITH,          PHP_INI_ALL, NULL)
267 PHP_INI_END()
268 /* }}} */
269 
270 zend_class_entry *date_ce_date, *date_ce_timezone, *date_ce_interval, *date_ce_period;
271 zend_class_entry *date_ce_immutable, *date_ce_interface;
272 zend_class_entry *date_ce_date_error, *date_ce_date_object_error, *date_ce_date_range_error;
273 zend_class_entry *date_ce_date_exception, *date_ce_date_invalid_timezone_exception, *date_ce_date_invalid_operation_exception, *date_ce_date_malformed_string_exception, *date_ce_date_malformed_interval_string_exception, *date_ce_date_malformed_period_string_exception;
274 
275 
php_date_get_date_ce(void)276 PHPAPI zend_class_entry *php_date_get_date_ce(void)
277 {
278 	return date_ce_date;
279 }
280 
php_date_get_immutable_ce(void)281 PHPAPI zend_class_entry *php_date_get_immutable_ce(void)
282 {
283 	return date_ce_immutable;
284 }
285 
php_date_get_interface_ce(void)286 PHPAPI zend_class_entry *php_date_get_interface_ce(void)
287 {
288 	return date_ce_interface;
289 }
290 
php_date_get_timezone_ce(void)291 PHPAPI zend_class_entry *php_date_get_timezone_ce(void)
292 {
293 	return date_ce_timezone;
294 }
295 
php_date_get_interval_ce(void)296 PHPAPI zend_class_entry *php_date_get_interval_ce(void)
297 {
298 	return date_ce_interval;
299 }
300 
php_date_get_period_ce(void)301 PHPAPI zend_class_entry *php_date_get_period_ce(void)
302 {
303 	return date_ce_period;
304 }
305 
306 static zend_object_handlers date_object_handlers_date;
307 static zend_object_handlers date_object_handlers_immutable;
308 static zend_object_handlers date_object_handlers_timezone;
309 static zend_object_handlers date_object_handlers_interval;
310 static zend_object_handlers date_object_handlers_period;
311 
date_throw_uninitialized_error(zend_class_entry * ce)312 static void date_throw_uninitialized_error(zend_class_entry *ce)
313 {
314 	if (ce->type == ZEND_INTERNAL_CLASS) {
315 		zend_throw_error(date_ce_date_object_error, "Object of type %s has not been correctly initialized by calling parent::__construct() in its constructor", ZSTR_VAL(ce->name));
316 	} else {
317 		zend_class_entry *ce_ptr = ce;
318 		while (ce_ptr && ce_ptr->parent && ce_ptr->type == ZEND_USER_CLASS) {
319 			ce_ptr = ce_ptr->parent;
320 		}
321 		if (ce_ptr->type != ZEND_INTERNAL_CLASS) {
322 			zend_throw_error(date_ce_date_object_error, "Object of type %s not been correctly initialized by calling parent::__construct() in its constructor", ZSTR_VAL(ce->name));
323 		}
324 		zend_throw_error(date_ce_date_object_error, "Object of type %s (inheriting %s) has not been correctly initialized by calling parent::__construct() in its constructor", ZSTR_VAL(ce->name), ZSTR_VAL(ce_ptr->name));
325 	}
326 }
327 
328 #define DATE_CHECK_INITIALIZED(member, ce) \
329 	if (!(member)) { \
330 		date_throw_uninitialized_error(ce); \
331 		RETURN_THROWS(); \
332 	}
333 
334 static void date_object_free_storage_date(zend_object *object);
335 static void date_object_free_storage_timezone(zend_object *object);
336 static void date_object_free_storage_interval(zend_object *object);
337 static void date_object_free_storage_period(zend_object *object);
338 
339 static zend_object *date_object_new_date(zend_class_entry *class_type);
340 static zend_object *date_object_new_timezone(zend_class_entry *class_type);
341 static zend_object *date_object_new_interval(zend_class_entry *class_type);
342 static zend_object *date_object_new_period(zend_class_entry *class_type);
343 
344 static zend_object *date_object_clone_date(zend_object *this_ptr);
345 static zend_object *date_object_clone_timezone(zend_object *this_ptr);
346 static zend_object *date_object_clone_interval(zend_object *this_ptr);
347 static zend_object *date_object_clone_period(zend_object *this_ptr);
348 
349 static int date_object_compare_date(zval *d1, zval *d2);
350 static HashTable *date_object_get_gc(zend_object *object, zval **table, int *n);
351 static HashTable *date_object_get_properties_for(zend_object *object, zend_prop_purpose purpose);
352 static HashTable *date_object_get_gc_interval(zend_object *object, zval **table, int *n);
353 static HashTable *date_object_get_properties_interval(zend_object *object);
354 static HashTable *date_object_get_gc_period(zend_object *object, zval **table, int *n);
355 static HashTable *date_object_get_properties_for_timezone(zend_object *object, zend_prop_purpose purpose);
356 static HashTable *date_object_get_gc_timezone(zend_object *object, zval **table, int *n);
357 static HashTable *date_object_get_debug_info_timezone(zend_object *object, int *is_temp);
358 static void php_timezone_to_string(php_timezone_obj *tzobj, zval *zv);
359 
360 static int date_interval_compare_objects(zval *o1, zval *o2);
361 static zval *date_interval_read_property(zend_object *object, zend_string *member, int type, void **cache_slot, zval *rv);
362 static zval *date_interval_write_property(zend_object *object, zend_string *member, zval *value, void **cache_slot);
363 static zval *date_interval_get_property_ptr_ptr(zend_object *object, zend_string *member, int type, void **cache_slot);
364 static zval *date_period_read_property(zend_object *object, zend_string *name, int type, void **cache_slot, zval *rv);
365 static zval *date_period_write_property(zend_object *object, zend_string *name, zval *value, void **cache_slot);
366 static zval *date_period_get_property_ptr_ptr(zend_object *object, zend_string *name, int type, void **cache_slot);
367 
368 static int date_object_compare_timezone(zval *tz1, zval *tz2);
369 
370 /* {{{ Module struct */
371 zend_module_entry date_module_entry = {
372 	STANDARD_MODULE_HEADER_EX,
373 	NULL,
374 	NULL,
375 	"date",                     /* extension name */
376 	ext_functions,              /* function list */
377 	PHP_MINIT(date),            /* process startup */
378 	PHP_MSHUTDOWN(date),        /* process shutdown */
379 	PHP_RINIT(date),            /* request startup */
380 	PHP_RSHUTDOWN(date),        /* request shutdown */
381 	PHP_MINFO(date),            /* extension info */
382 	PHP_DATE_VERSION,                /* extension version */
383 	PHP_MODULE_GLOBALS(date),   /* globals descriptor */
384 	PHP_GINIT(date),            /* globals ctor */
385 	NULL,                       /* globals dtor */
386 	ZEND_MODULE_POST_ZEND_DEACTIVATE_N(date), /* post deactivate */
387 	STANDARD_MODULE_PROPERTIES_EX
388 };
389 /* }}} */
390 
391 
392 /* {{{ PHP_GINIT_FUNCTION */
PHP_GINIT_FUNCTION(date)393 static PHP_GINIT_FUNCTION(date)
394 {
395 	date_globals->default_timezone = NULL;
396 	date_globals->timezone = NULL;
397 	date_globals->tzcache = NULL;
398 }
399 /* }}} */
400 
401 
_php_date_tzinfo_dtor(zval * zv)402 static void _php_date_tzinfo_dtor(zval *zv) /* {{{ */
403 {
404 	timelib_tzinfo *tzi = (timelib_tzinfo*)Z_PTR_P(zv);
405 
406 	timelib_tzinfo_dtor(tzi);
407 } /* }}} */
408 
409 /* {{{ PHP_RINIT_FUNCTION */
PHP_RINIT_FUNCTION(date)410 PHP_RINIT_FUNCTION(date)
411 {
412 	if (DATEG(timezone)) {
413 		efree(DATEG(timezone));
414 	}
415 	DATEG(timezone) = NULL;
416 	DATEG(tzcache) = NULL;
417 	DATEG(last_errors) = NULL;
418 
419 	return SUCCESS;
420 }
421 /* }}} */
422 
423 /* {{{ PHP_RSHUTDOWN_FUNCTION */
PHP_RSHUTDOWN_FUNCTION(date)424 PHP_RSHUTDOWN_FUNCTION(date)
425 {
426 	if (DATEG(timezone)) {
427 		efree(DATEG(timezone));
428 	}
429 	DATEG(timezone) = NULL;
430 
431 	return SUCCESS;
432 }
433 /* }}} */
434 
ZEND_MODULE_POST_ZEND_DEACTIVATE_D(date)435 ZEND_MODULE_POST_ZEND_DEACTIVATE_D(date)
436 {
437 	if (DATEG(tzcache)) {
438 		zend_hash_destroy(DATEG(tzcache));
439 		FREE_HASHTABLE(DATEG(tzcache));
440 		DATEG(tzcache) = NULL;
441 	}
442 
443 	if (DATEG(last_errors)) {
444 		timelib_error_container_dtor(DATEG(last_errors));
445 		DATEG(last_errors) = NULL;
446 	}
447 
448 	return SUCCESS;
449 }
450 
451 #define DATE_TIMEZONEDB      php_date_global_timezone_db ? php_date_global_timezone_db : timelib_builtin_db()
452 
453 /* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(date)454 PHP_MINIT_FUNCTION(date)
455 {
456 	REGISTER_INI_ENTRIES();
457 	date_register_classes();
458 	register_php_date_symbols(module_number);
459 
460 	php_date_global_timezone_db = NULL;
461 	php_date_global_timezone_db_enabled = 0;
462 	DATEG(last_errors) = NULL;
463 	return SUCCESS;
464 }
465 /* }}} */
466 
467 /* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(date)468 PHP_MSHUTDOWN_FUNCTION(date)
469 {
470 	UNREGISTER_INI_ENTRIES();
471 
472 	if (DATEG(last_errors)) {
473 		timelib_error_container_dtor(DATEG(last_errors));
474 	}
475 
476 #ifndef ZTS
477 	DATEG(default_timezone) = NULL;
478 #endif
479 
480 	return SUCCESS;
481 }
482 /* }}} */
483 
484 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(date)485 PHP_MINFO_FUNCTION(date)
486 {
487 	const timelib_tzdb *tzdb = DATE_TIMEZONEDB;
488 
489 	php_info_print_table_start();
490 	php_info_print_table_row(2, "date/time support", "enabled");
491 	php_info_print_table_row(2, "timelib version", TIMELIB_ASCII_VERSION);
492 	php_info_print_table_row(2, "\"Olson\" Timezone Database Version", tzdb->version);
493 	php_info_print_table_row(2, "Timezone Database", php_date_global_timezone_db_enabled ? "external" : "internal");
494 	php_info_print_table_row(2, "Default timezone", guess_timezone(tzdb));
495 	php_info_print_table_end();
496 
497 	DISPLAY_INI_ENTRIES();
498 }
499 /* }}} */
500 
501 /* {{{ Timezone Cache functions */
php_date_parse_tzfile(const char * formal_tzname,const timelib_tzdb * tzdb)502 static timelib_tzinfo *php_date_parse_tzfile(const char *formal_tzname, const timelib_tzdb *tzdb)
503 {
504 	timelib_tzinfo *tzi;
505 	int dummy_error_code;
506 
507 	if(!DATEG(tzcache)) {
508 		ALLOC_HASHTABLE(DATEG(tzcache));
509 		zend_hash_init(DATEG(tzcache), 4, NULL, _php_date_tzinfo_dtor, 0);
510 	}
511 
512 	if ((tzi = zend_hash_str_find_ptr(DATEG(tzcache), formal_tzname, strlen(formal_tzname))) != NULL) {
513 		return tzi;
514 	}
515 
516 	tzi = timelib_parse_tzfile(formal_tzname, tzdb, &dummy_error_code);
517 	if (tzi) {
518 		zend_hash_str_add_ptr(DATEG(tzcache), formal_tzname, strlen(formal_tzname), tzi);
519 	}
520 	return tzi;
521 }
522 
php_date_parse_tzfile_wrapper(const char * formal_tzname,const timelib_tzdb * tzdb,int * dummy_error_code)523 static timelib_tzinfo *php_date_parse_tzfile_wrapper(const char *formal_tzname, const timelib_tzdb *tzdb, int *dummy_error_code)
524 {
525 	return php_date_parse_tzfile(formal_tzname, tzdb);
526 }
527 /* }}} */
528 
529 /* Callback to check the date.timezone only when changed increases performance */
530 /* {{{ static PHP_INI_MH(OnUpdate_date_timezone) */
PHP_INI_MH(OnUpdate_date_timezone)531 static PHP_INI_MH(OnUpdate_date_timezone)
532 {
533 	if (new_value && !timelib_timezone_id_is_valid(ZSTR_VAL(new_value), DATE_TIMEZONEDB)) {
534 		php_error_docref(
535 			NULL, E_WARNING,
536 			"Invalid date.timezone value '%s', using '%s' instead",
537 			ZSTR_VAL(new_value),
538 			DATEG(default_timezone) ? DATEG(default_timezone) : "UTC"
539 		);
540 		return FAILURE;
541 	}
542 
543 	if (OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage) == FAILURE) {
544 		return FAILURE;
545 	}
546 
547 	return SUCCESS;
548 }
549 /* }}} */
550 
551 /* {{{ Helper functions */
guess_timezone(const timelib_tzdb * tzdb)552 static const char* guess_timezone(const timelib_tzdb *tzdb)
553 {
554 	/* Checking whether timezone has been set with date_default_timezone_set() */
555 	if (DATEG(timezone) && (strlen(DATEG(timezone))) > 0) {
556 		return DATEG(timezone);
557 	}
558 	/* Check config setting for default timezone */
559 	if (!DATEG(default_timezone)) {
560 		/* Special case: ext/date wasn't initialized yet */
561 		zval *ztz;
562 
563 		if (NULL != (ztz = cfg_get_entry("date.timezone", sizeof("date.timezone")))
564 			&& Z_TYPE_P(ztz) == IS_STRING && Z_STRLEN_P(ztz) > 0 && timelib_timezone_id_is_valid(Z_STRVAL_P(ztz), tzdb)) {
565 			return Z_STRVAL_P(ztz);
566 		}
567 	} else if (*DATEG(default_timezone)) {
568 		return DATEG(default_timezone);
569 	}
570 	/* Fallback to UTC */
571 	return "UTC";
572 }
573 
get_timezone_info(void)574 PHPAPI timelib_tzinfo *get_timezone_info(void)
575 {
576 	timelib_tzinfo *tzi;
577 
578 	const char *tz = guess_timezone(DATE_TIMEZONEDB);
579 	tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB);
580 	if (! tzi) {
581 		zend_throw_error(date_ce_date_error, "Timezone database is corrupt. Please file a bug report as this should never happen");
582 	}
583 	return tzi;
584 }
585 
update_property(zend_object * object,zend_string * key,zval * prop_val)586 static void update_property(zend_object *object, zend_string *key, zval *prop_val)
587 {
588 	if (ZSTR_LEN(key) > 0 && ZSTR_VAL(key)[0] == '\0') { // not public
589 		const char *class_name, *prop_name;
590 		size_t prop_name_len;
591 
592 		if (zend_unmangle_property_name_ex(key, &class_name, &prop_name, &prop_name_len) == SUCCESS) {
593 			if (class_name[0] != '*') { // private
594 				zend_string *cname;
595 				zend_class_entry *ce;
596 
597 				cname = zend_string_init(class_name, strlen(class_name), 0);
598 				ce = zend_lookup_class(cname);
599 
600 				if (ce) {
601 					zend_update_property(ce, object, prop_name, prop_name_len, prop_val);
602 				}
603 
604 				zend_string_release_ex(cname, 0);
605 			} else { // protected
606 				zend_update_property(object->ce, object, prop_name, prop_name_len, prop_val);
607 			}
608 		}
609 		return;
610 	}
611 
612 	// public
613 	zend_update_property(object->ce, object, ZSTR_VAL(key), ZSTR_LEN(key), prop_val);
614 }
615 /* }}} */
616 
617 
618 /* {{{ date() and gmdate() data */
619 #include "zend_smart_str.h"
620 
621 static const char * const mon_full_names[] = {
622 	"January", "February", "March", "April",
623 	"May", "June", "July", "August",
624 	"September", "October", "November", "December"
625 };
626 
627 static const char * const mon_short_names[] = {
628 	"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
629 };
630 
631 static const char * const day_full_names[] = {
632 	"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
633 };
634 
635 static const char * const day_short_names[] = {
636 	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
637 };
638 
english_suffix(timelib_sll number)639 static const char *english_suffix(timelib_sll number)
640 {
641 	if (number >= 10 && number <= 19) {
642 		return "th";
643 	} else {
644 		switch (number % 10) {
645 			case 1: return "st";
646 			case 2: return "nd";
647 			case 3: return "rd";
648 		}
649 	}
650 	return "th";
651 }
652 /* }}} */
653 
654 /* {{{ day of week helpers */
php_date_full_day_name(timelib_sll y,timelib_sll m,timelib_sll d)655 static const char *php_date_full_day_name(timelib_sll y, timelib_sll m, timelib_sll d)
656 {
657 	timelib_sll day_of_week = timelib_day_of_week(y, m, d);
658 	if (day_of_week < 0) {
659 		return "Unknown";
660 	}
661 	return day_full_names[day_of_week];
662 }
663 
php_date_short_day_name(timelib_sll y,timelib_sll m,timelib_sll d)664 static const char *php_date_short_day_name(timelib_sll y, timelib_sll m, timelib_sll d)
665 {
666 	timelib_sll day_of_week = timelib_day_of_week(y, m, d);
667 	if (day_of_week < 0) {
668 		return "Unknown";
669 	}
670 	return day_short_names[day_of_week];
671 }
672 /* }}} */
673 
674 /* {{{ date_format - (gm)date helper */
date_format(const char * format,size_t format_len,timelib_time * t,bool localtime)675 static zend_string *date_format(const char *format, size_t format_len, timelib_time *t, bool localtime)
676 {
677 	smart_str            string = {0};
678 	size_t               i;
679 	int                  length = 0;
680 	char                 buffer[97];
681 	timelib_time_offset *offset = NULL;
682 	timelib_sll          isoweek, isoyear;
683 	bool                 rfc_colon;
684 	int                  weekYearSet = 0;
685 
686 	if (!format_len) {
687 		return ZSTR_EMPTY_ALLOC();
688 	}
689 
690 	if (localtime) {
691 		if (t->zone_type == TIMELIB_ZONETYPE_ABBR) {
692 			offset = timelib_time_offset_ctor();
693 			offset->offset = (t->z + (t->dst * 3600));
694 			offset->leap_secs = 0;
695 			offset->is_dst = t->dst;
696 			offset->abbr = timelib_strdup(t->tz_abbr);
697 		} else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) {
698 			offset = timelib_time_offset_ctor();
699 			offset->offset = (t->z);
700 			offset->leap_secs = 0;
701 			offset->is_dst = 0;
702 			offset->abbr = timelib_malloc(9); /* GMT±xxxx\0 */
703 			snprintf(offset->abbr, 9, "GMT%c%02d%02d",
704 			                          (offset->offset < 0) ? '-' : '+',
705 			                          abs(offset->offset / 3600),
706 			                          abs((offset->offset % 3600) / 60));
707 		} else {
708 			offset = timelib_get_time_zone_info(t->sse, t->tz_info);
709 		}
710 	}
711 
712 	for (i = 0; i < format_len; i++) {
713 		rfc_colon = 0;
714 		switch (format[i]) {
715 			/* day */
716 			case 'd': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->d); break;
717 			case 'D': length = slprintf(buffer, sizeof(buffer), "%s", php_date_short_day_name(t->y, t->m, t->d)); break;
718 			case 'j': length = slprintf(buffer, sizeof(buffer), "%d", (int) t->d); break;
719 			case 'l': length = slprintf(buffer, sizeof(buffer), "%s", php_date_full_day_name(t->y, t->m, t->d)); break;
720 			case 'S': length = slprintf(buffer, sizeof(buffer), "%s", english_suffix(t->d)); break;
721 			case 'w': length = slprintf(buffer, sizeof(buffer), "%d", (int) timelib_day_of_week(t->y, t->m, t->d)); break;
722 			case 'N': length = slprintf(buffer, sizeof(buffer), "%d", (int) timelib_iso_day_of_week(t->y, t->m, t->d)); break;
723 			case 'z': length = slprintf(buffer, sizeof(buffer), "%d", (int) timelib_day_of_year(t->y, t->m, t->d)); break;
724 
725 			/* week */
726 			case 'W':
727 				if(!weekYearSet) { timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); weekYearSet = 1; }
728 				length = slprintf(buffer, sizeof(buffer), "%02d", (int) isoweek); break; /* iso weeknr */
729 			case 'o':
730 				if(!weekYearSet) { timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); weekYearSet = 1; }
731 				length = slprintf(buffer, sizeof(buffer), ZEND_LONG_FMT, (zend_long) isoyear); break; /* iso year */
732 
733 			/* month */
734 			case 'F': length = slprintf(buffer, sizeof(buffer), "%s", mon_full_names[t->m - 1]); break;
735 			case 'm': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->m); break;
736 			case 'M': length = slprintf(buffer, sizeof(buffer), "%s", mon_short_names[t->m - 1]); break;
737 			case 'n': length = slprintf(buffer, sizeof(buffer), "%d", (int) t->m); break;
738 			case 't': length = slprintf(buffer, sizeof(buffer), "%d", (int) timelib_days_in_month(t->y, t->m)); break;
739 
740 			/* year */
741 			case 'L': length = slprintf(buffer, sizeof(buffer), "%d", timelib_is_leap((int) t->y)); break;
742 			case 'y': length = slprintf(buffer, sizeof(buffer), "%02d", (int) (t->y % 100)); break;
743 			case 'Y': length = slprintf(buffer, sizeof(buffer), "%s%04lld", t->y < 0 ? "-" : "", php_date_llabs((timelib_sll) t->y)); break;
744 			case 'x': length = slprintf(buffer, sizeof(buffer), "%s%04lld", t->y < 0 ? "-" : (t->y >= 10000 ? "+" : ""), php_date_llabs((timelib_sll) t->y)); break;
745 			case 'X': length = slprintf(buffer, sizeof(buffer), "%s%04lld", t->y < 0 ? "-" : "+", php_date_llabs((timelib_sll) t->y)); break;
746 
747 			/* time */
748 			case 'a': length = slprintf(buffer, sizeof(buffer), "%s", t->h >= 12 ? "pm" : "am"); break;
749 			case 'A': length = slprintf(buffer, sizeof(buffer), "%s", t->h >= 12 ? "PM" : "AM"); break;
750 			case 'B': {
751 				int retval = ((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10);
752 				if (retval < 0) {
753 					retval += 864000;
754 				}
755 				/* Make sure to do this on a positive int to avoid rounding errors */
756 				retval = (retval / 864)  % 1000;
757 				length = slprintf(buffer, sizeof(buffer), "%03d", retval);
758 				break;
759 			}
760 			case 'g': length = slprintf(buffer, sizeof(buffer), "%d", (t->h % 12) ? (int) t->h % 12 : 12); break;
761 			case 'G': length = slprintf(buffer, sizeof(buffer), "%d", (int) t->h); break;
762 			case 'h': length = slprintf(buffer, sizeof(buffer), "%02d", (t->h % 12) ? (int) t->h % 12 : 12); break;
763 			case 'H': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->h); break;
764 			case 'i': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->i); break;
765 			case 's': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->s); break;
766 			case 'u': length = slprintf(buffer, sizeof(buffer), "%06d", (int) floor(t->us)); break;
767 			case 'v': length = slprintf(buffer, sizeof(buffer), "%03d", (int) floor(t->us / 1000)); break;
768 
769 			/* timezone */
770 			case 'I': length = slprintf(buffer, sizeof(buffer), "%d", localtime ? offset->is_dst : 0); break;
771 			case 'p':
772 				if (!localtime || strcmp(offset->abbr, "UTC") == 0 || strcmp(offset->abbr, "Z") == 0 || strcmp(offset->abbr, "GMT+0000") == 0) {
773 					length = slprintf(buffer, sizeof(buffer), "%s", "Z");
774 					break;
775 				}
776 				ZEND_FALLTHROUGH;
777 			case 'P': rfc_colon = 1; ZEND_FALLTHROUGH;
778 			case 'O': length = slprintf(buffer, sizeof(buffer), "%c%02d%s%02d",
779 											localtime ? ((offset->offset < 0) ? '-' : '+') : '+',
780 											localtime ? abs(offset->offset / 3600) : 0,
781 											rfc_colon ? ":" : "",
782 											localtime ? abs((offset->offset % 3600) / 60) : 0
783 							  );
784 					  break;
785 			case 'T': length = slprintf(buffer, sizeof(buffer), "%s", localtime ? offset->abbr : "GMT"); break;
786 			case 'e': if (!localtime) {
787 					      length = slprintf(buffer, sizeof(buffer), "%s", "UTC");
788 					  } else {
789 						  switch (t->zone_type) {
790 							  case TIMELIB_ZONETYPE_ID:
791 								  length = slprintf(buffer, sizeof(buffer), "%s", t->tz_info->name);
792 								  break;
793 							  case TIMELIB_ZONETYPE_ABBR:
794 								  length = slprintf(buffer, sizeof(buffer), "%s", offset->abbr);
795 								  break;
796 							  case TIMELIB_ZONETYPE_OFFSET:
797 								  length = slprintf(buffer, sizeof(buffer), "%c%02d:%02d",
798 												((offset->offset < 0) ? '-' : '+'),
799 												abs(offset->offset / 3600),
800 												abs((offset->offset % 3600) / 60)
801 										   );
802 								  break;
803 						  }
804 					  }
805 					  break;
806 			case 'Z': length = slprintf(buffer, sizeof(buffer), "%d", localtime ? offset->offset : 0); break;
807 
808 			/* full date/time */
809 			case 'c': length = slprintf(buffer, sizeof(buffer), "%04" ZEND_LONG_FMT_SPEC "-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
810 							                (zend_long) t->y, (int) t->m, (int) t->d,
811 											(int) t->h, (int) t->i, (int) t->s,
812 											localtime ? ((offset->offset < 0) ? '-' : '+') : '+',
813 											localtime ? abs(offset->offset / 3600) : 0,
814 											localtime ? abs((offset->offset % 3600) / 60) : 0
815 							  );
816 					  break;
817 			case 'r': length = slprintf(buffer, sizeof(buffer), "%3s, %02d %3s %04" ZEND_LONG_FMT_SPEC " %02d:%02d:%02d %c%02d%02d",
818 							                php_date_short_day_name(t->y, t->m, t->d),
819 											(int) t->d, mon_short_names[t->m - 1],
820 											(zend_long) t->y, (int) t->h, (int) t->i, (int) t->s,
821 											localtime ? ((offset->offset < 0) ? '-' : '+') : '+',
822 											localtime ? abs(offset->offset / 3600) : 0,
823 											localtime ? abs((offset->offset % 3600) / 60) : 0
824 							  );
825 					  break;
826 			case 'U': length = slprintf(buffer, sizeof(buffer), "%lld", (timelib_sll) t->sse); break;
827 
828 			case '\\': if (i < format_len) i++; ZEND_FALLTHROUGH;
829 
830 			default: buffer[0] = format[i]; buffer[1] = '\0'; length = 1; break;
831 		}
832 		smart_str_appendl(&string, buffer, length);
833 	}
834 
835 	smart_str_0(&string);
836 
837 	if (localtime) {
838 		timelib_time_offset_dtor(offset);
839 	}
840 
841 	return string.s;
842 }
843 
php_format_date_obj(const char * format,size_t format_len,php_date_obj * date_obj)844 PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, php_date_obj *date_obj)
845 {
846 	if (!date_obj->time) {
847 		return NULL;
848 	}
849 
850 	return date_format(format, format_len, date_obj->time, date_obj->time->is_localtime);
851 }
852 
php_date(INTERNAL_FUNCTION_PARAMETERS,bool localtime)853 static void php_date(INTERNAL_FUNCTION_PARAMETERS, bool localtime)
854 {
855 	zend_string *format;
856 	zend_long    ts;
857 	bool    ts_is_null = 1;
858 
859 	ZEND_PARSE_PARAMETERS_START(1, 2)
860 		Z_PARAM_STR(format)
861 		Z_PARAM_OPTIONAL
862 		Z_PARAM_LONG_OR_NULL(ts, ts_is_null)
863 	ZEND_PARSE_PARAMETERS_END();
864 
865 	if (ts_is_null) {
866 		ts = php_time();
867 	}
868 
869 	RETURN_STR(php_format_date(ZSTR_VAL(format), ZSTR_LEN(format), ts, localtime));
870 }
871 /* }}} */
872 
php_format_date(const char * format,size_t format_len,time_t ts,bool localtime)873 PHPAPI zend_string *php_format_date(const char *format, size_t format_len, time_t ts, bool localtime) /* {{{ */
874 {
875 	timelib_time   *t;
876 	timelib_tzinfo *tzi;
877 	zend_string *string;
878 
879 	t = timelib_time_ctor();
880 
881 	if (localtime) {
882 		tzi = get_timezone_info();
883 		t->tz_info = tzi;
884 		t->zone_type = TIMELIB_ZONETYPE_ID;
885 		timelib_unixtime2local(t, ts);
886 	} else {
887 		tzi = NULL;
888 		timelib_unixtime2gmt(t, ts);
889 	}
890 
891 	string = date_format(format, format_len, t, localtime);
892 
893 	timelib_time_dtor(t);
894 	return string;
895 }
896 /* }}} */
897 
898 /* {{{ php_idate */
php_idate(char format,time_t ts,bool localtime)899 PHPAPI int php_idate(char format, time_t ts, bool localtime)
900 {
901 	timelib_time   *t;
902 	timelib_tzinfo *tzi;
903 	int retval = -1;
904 	timelib_time_offset *offset = NULL;
905 	timelib_sll isoweek, isoyear;
906 
907 	t = timelib_time_ctor();
908 
909 	if (!localtime) {
910 		tzi = get_timezone_info();
911 		t->tz_info = tzi;
912 		t->zone_type = TIMELIB_ZONETYPE_ID;
913 		timelib_unixtime2local(t, ts);
914 	} else {
915 		tzi = NULL;
916 		timelib_unixtime2gmt(t, ts);
917 	}
918 
919 	if (!localtime) {
920 		if (t->zone_type == TIMELIB_ZONETYPE_ABBR) {
921 			offset = timelib_time_offset_ctor();
922 			offset->offset = (t->z + (t->dst * 3600));
923 			offset->leap_secs = 0;
924 			offset->is_dst = t->dst;
925 			offset->abbr = timelib_strdup(t->tz_abbr);
926 		} else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) {
927 			offset = timelib_time_offset_ctor();
928 			offset->offset = (t->z + (t->dst * 3600));
929 			offset->leap_secs = 0;
930 			offset->is_dst = t->dst;
931 			offset->abbr = timelib_malloc(9); /* GMT±xxxx\0 */
932 			snprintf(offset->abbr, 9, "GMT%c%02d%02d",
933 			                          (offset->offset < 0) ? '-' : '+',
934 			                          abs(offset->offset / 3600),
935 			                          abs((offset->offset % 3600) / 60));
936 		} else {
937 			offset = timelib_get_time_zone_info(t->sse, t->tz_info);
938 		}
939 	}
940 
941 	timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear);
942 
943 	switch (format) {
944 		/* day */
945 		case 'd': case 'j': retval = (int) t->d; break;
946 
947 		case 'N': retval = (int) timelib_iso_day_of_week(t->y, t->m, t->d); break;
948 		case 'w': retval = (int) timelib_day_of_week(t->y, t->m, t->d); break;
949 		case 'z': retval = (int) timelib_day_of_year(t->y, t->m, t->d); break;
950 
951 		/* week */
952 		case 'W': retval = (int) isoweek; break; /* iso weeknr */
953 
954 		/* month */
955 		case 'm': case 'n': retval = (int) t->m; break;
956 		case 't': retval = (int) timelib_days_in_month(t->y, t->m); break;
957 
958 		/* year */
959 		case 'L': retval = (int) timelib_is_leap((int) t->y); break;
960 		case 'y': retval = (int) (t->y % 100); break;
961 		case 'Y': retval = (int) t->y; break;
962 		case 'o': retval = (int) isoyear; break; /* iso year */
963 
964 		/* Swatch Beat a.k.a. Internet Time */
965 		case 'B':
966 			retval = ((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10);
967 			if (retval < 0) {
968 				retval += 864000;
969 			}
970 			/* Make sure to do this on a positive int to avoid rounding errors */
971 			retval = (retval / 864) % 1000;
972 			break;
973 
974 		/* time */
975 		case 'g': case 'h': retval = (int) ((t->h % 12) ? (int) t->h % 12 : 12); break;
976 		case 'H': case 'G': retval = (int) t->h; break;
977 		case 'i': retval = (int) t->i; break;
978 		case 's': retval = (int) t->s; break;
979 
980 		/* timezone */
981 		case 'I': retval = (int) (!localtime ? offset->is_dst : 0); break;
982 		case 'Z': retval = (int) (!localtime ? offset->offset : 0); break;
983 
984 		case 'U': retval = (int) t->sse; break;
985 	}
986 
987 	if (!localtime) {
988 		timelib_time_offset_dtor(offset);
989 	}
990 	timelib_time_dtor(t);
991 
992 	return retval;
993 }
994 /* }}} */
995 
996 /* {{{ Format a local date/time */
PHP_FUNCTION(date)997 PHP_FUNCTION(date)
998 {
999 	php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1000 }
1001 /* }}} */
1002 
1003 /* {{{ Format a GMT date/time */
PHP_FUNCTION(gmdate)1004 PHP_FUNCTION(gmdate)
1005 {
1006 	php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1007 }
1008 /* }}} */
1009 
1010 /* {{{ Format a local time/date as integer */
PHP_FUNCTION(idate)1011 PHP_FUNCTION(idate)
1012 {
1013 	zend_string *format;
1014 	zend_long    ts;
1015 	bool    ts_is_null = 1;
1016 	int ret;
1017 
1018 	ZEND_PARSE_PARAMETERS_START(1, 2)
1019 		Z_PARAM_STR(format)
1020 		Z_PARAM_OPTIONAL
1021 		Z_PARAM_LONG_OR_NULL(ts, ts_is_null)
1022 	ZEND_PARSE_PARAMETERS_END();
1023 
1024 	if (ZSTR_LEN(format) != 1) {
1025 		php_error_docref(NULL, E_WARNING, "idate format is one char");
1026 		RETURN_FALSE;
1027 	}
1028 
1029 	if (ts_is_null) {
1030 		ts = php_time();
1031 	}
1032 
1033 	ret = php_idate(ZSTR_VAL(format)[0], ts, 0);
1034 	if (ret == -1) {
1035 		php_error_docref(NULL, E_WARNING, "Unrecognized date format token");
1036 		RETURN_FALSE;
1037 	}
1038 	RETURN_LONG(ret);
1039 }
1040 /* }}} */
1041 
1042 /* {{{ php_date_set_tzdb - NOT THREADSAFE */
php_date_set_tzdb(timelib_tzdb * tzdb)1043 PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb)
1044 {
1045 	const timelib_tzdb *builtin = timelib_builtin_db();
1046 
1047 	if (php_version_compare(tzdb->version, builtin->version) > 0) {
1048 		php_date_global_timezone_db = tzdb;
1049 		php_date_global_timezone_db_enabled = 1;
1050 	}
1051 }
1052 /* }}} */
1053 
1054 /* {{{ php_parse_date: Backwards compatibility function */
php_parse_date(const char * string,zend_long * now)1055 PHPAPI zend_long php_parse_date(const char *string, zend_long *now)
1056 {
1057 	timelib_time *parsed_time;
1058 	timelib_error_container *error = NULL;
1059 	int           error2;
1060 	zend_long   retval;
1061 
1062 	parsed_time = timelib_strtotime(string, strlen(string), &error, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
1063 	if (error->error_count) {
1064 		timelib_time_dtor(parsed_time);
1065 		timelib_error_container_dtor(error);
1066 		return -1;
1067 	}
1068 	timelib_error_container_dtor(error);
1069 	timelib_update_ts(parsed_time, NULL);
1070 	retval = timelib_date_to_int(parsed_time, &error2);
1071 	timelib_time_dtor(parsed_time);
1072 	if (error2) {
1073 		return -1;
1074 	}
1075 	return retval;
1076 }
1077 /* }}} */
1078 
1079 /* {{{ Convert string representation of date and time to a timestamp */
PHP_FUNCTION(strtotime)1080 PHP_FUNCTION(strtotime)
1081 {
1082 	zend_string *times;
1083 	int parse_error, epoch_does_not_fit_in_zend_long;
1084 	timelib_error_container *error;
1085 	zend_long preset_ts, ts;
1086 	bool preset_ts_is_null = 1;
1087 	timelib_time *t, *now;
1088 	timelib_tzinfo *tzi;
1089 
1090 	ZEND_PARSE_PARAMETERS_START(1, 2)
1091 		Z_PARAM_STR(times)
1092 		Z_PARAM_OPTIONAL
1093 		Z_PARAM_LONG_OR_NULL(preset_ts, preset_ts_is_null)
1094 	ZEND_PARSE_PARAMETERS_END();
1095 
1096 	/* timelib_strtotime() expects the string to not be empty */
1097 	if (ZSTR_LEN(times) == 0) {
1098 		RETURN_FALSE;
1099 	}
1100 
1101 	tzi = get_timezone_info();
1102 	if (!tzi) {
1103 		return;
1104 	}
1105 
1106 	now = timelib_time_ctor();
1107 	now->tz_info = tzi;
1108 	now->zone_type = TIMELIB_ZONETYPE_ID;
1109 	timelib_unixtime2local(now,
1110 		!preset_ts_is_null ? (timelib_sll) preset_ts : (timelib_sll) php_time());
1111 
1112 	t = timelib_strtotime(ZSTR_VAL(times), ZSTR_LEN(times), &error,
1113 		DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
1114 	parse_error = error->error_count;
1115 	timelib_error_container_dtor(error);
1116 	if (parse_error) {
1117 		timelib_time_dtor(now);
1118 		timelib_time_dtor(t);
1119 		RETURN_FALSE;
1120 	}
1121 
1122 	timelib_fill_holes(t, now, TIMELIB_NO_CLONE);
1123 	timelib_update_ts(t, tzi);
1124 	ts = timelib_date_to_int(t, &epoch_does_not_fit_in_zend_long);
1125 
1126 	timelib_time_dtor(now);
1127 	timelib_time_dtor(t);
1128 
1129 	if (epoch_does_not_fit_in_zend_long) {
1130 		php_error_docref(NULL, E_WARNING, "Epoch doesn't fit in a PHP integer");
1131 		RETURN_FALSE;
1132 	}
1133 
1134 	RETURN_LONG(ts);
1135 }
1136 /* }}} */
1137 
1138 /* {{{ php_mktime - (gm)mktime helper */
php_mktime(INTERNAL_FUNCTION_PARAMETERS,bool gmt)1139 PHPAPI void php_mktime(INTERNAL_FUNCTION_PARAMETERS, bool gmt)
1140 {
1141 	zend_long hou, min, sec, mon, day, yea;
1142 	bool min_is_null = 1, sec_is_null = 1, mon_is_null = 1, day_is_null = 1, yea_is_null = 1;
1143 	timelib_time *now;
1144 	timelib_tzinfo *tzi = NULL;
1145 	zend_long ts, adjust_seconds = 0;
1146 	int epoch_does_not_fit_in_zend_long;
1147 
1148 	ZEND_PARSE_PARAMETERS_START(1, 6)
1149 		Z_PARAM_LONG(hou)
1150 		Z_PARAM_OPTIONAL
1151 		Z_PARAM_LONG_OR_NULL(min, min_is_null)
1152 		Z_PARAM_LONG_OR_NULL(sec, sec_is_null)
1153 		Z_PARAM_LONG_OR_NULL(mon, mon_is_null)
1154 		Z_PARAM_LONG_OR_NULL(day, day_is_null)
1155 		Z_PARAM_LONG_OR_NULL(yea, yea_is_null)
1156 	ZEND_PARSE_PARAMETERS_END();
1157 
1158 	/* Initialize structure with current time */
1159 	now = timelib_time_ctor();
1160 	if (gmt) {
1161 		timelib_unixtime2gmt(now, (timelib_sll) php_time());
1162 	} else {
1163 		tzi = get_timezone_info();
1164 		if (!tzi) {
1165 			return;
1166 		}
1167 		now->tz_info = tzi;
1168 		now->zone_type = TIMELIB_ZONETYPE_ID;
1169 		timelib_unixtime2local(now, (timelib_sll) php_time());
1170 	}
1171 
1172 	now->h = hou;
1173 
1174 	if (!min_is_null) {
1175 		now->i = min;
1176 	}
1177 
1178 	if (!sec_is_null) {
1179 		now->s = sec;
1180 	}
1181 
1182 	if (!mon_is_null) {
1183 		now->m = mon;
1184 	}
1185 
1186 	if (!day_is_null) {
1187 		now->d = day;
1188 	}
1189 
1190 	if (!yea_is_null) {
1191 		if (yea >= 0 && yea < 70) {
1192 			yea += 2000;
1193 		} else if (yea >= 70 && yea <= 100) {
1194 			yea += 1900;
1195 		}
1196 		now->y = yea;
1197 	}
1198 
1199 	/* Update the timestamp */
1200 	if (gmt) {
1201 		timelib_update_ts(now, NULL);
1202 	} else {
1203 		timelib_update_ts(now, tzi);
1204 	}
1205 
1206 	/* Clean up and return */
1207 	ts = timelib_date_to_int(now, &epoch_does_not_fit_in_zend_long);
1208 
1209 	if (epoch_does_not_fit_in_zend_long) {
1210 		timelib_time_dtor(now);
1211 		php_error_docref(NULL, E_WARNING, "Epoch doesn't fit in a PHP integer");
1212 		RETURN_FALSE;
1213 	}
1214 
1215 	ts += adjust_seconds;
1216 	timelib_time_dtor(now);
1217 
1218 	RETURN_LONG(ts);
1219 }
1220 /* }}} */
1221 
1222 /* {{{ Get UNIX timestamp for a date */
PHP_FUNCTION(mktime)1223 PHP_FUNCTION(mktime)
1224 {
1225 	php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1226 }
1227 /* }}} */
1228 
1229 /* {{{ Get UNIX timestamp for a GMT date */
PHP_FUNCTION(gmmktime)1230 PHP_FUNCTION(gmmktime)
1231 {
1232 	php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1233 }
1234 /* }}} */
1235 
1236 /* {{{ Returns true(1) if it is a valid date in gregorian calendar */
PHP_FUNCTION(checkdate)1237 PHP_FUNCTION(checkdate)
1238 {
1239 	zend_long m, d, y;
1240 
1241 	ZEND_PARSE_PARAMETERS_START(3, 3)
1242 		Z_PARAM_LONG(m)
1243 		Z_PARAM_LONG(d)
1244 		Z_PARAM_LONG(y)
1245 	ZEND_PARSE_PARAMETERS_END();
1246 
1247 	if (y < 1 || y > 32767 || !timelib_valid_date(y, m, d)) {
1248 		RETURN_FALSE;
1249 	}
1250 	RETURN_TRUE;	/* True : This month, day, year arguments are valid */
1251 }
1252 /* }}} */
1253 
1254 /* {{{ php_strftime - (gm)strftime helper */
php_strftime(INTERNAL_FUNCTION_PARAMETERS,bool gmt)1255 PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, bool gmt)
1256 {
1257 	zend_string         *format;
1258 	zend_long            timestamp;
1259 	bool            timestamp_is_null = 1;
1260 	struct tm            ta;
1261 	int                  max_reallocs = 5;
1262 	size_t               buf_len = 256, real_len;
1263 	timelib_time        *ts;
1264 	timelib_tzinfo      *tzi;
1265 	timelib_time_offset *offset = NULL;
1266 	zend_string 		*buf;
1267 
1268 	ZEND_PARSE_PARAMETERS_START(1, 2)
1269 		Z_PARAM_STR(format)
1270 		Z_PARAM_OPTIONAL
1271 		Z_PARAM_LONG_OR_NULL(timestamp, timestamp_is_null)
1272 	ZEND_PARSE_PARAMETERS_END();
1273 
1274 	if (ZSTR_LEN(format) == 0) {
1275 		RETURN_FALSE;
1276 	}
1277 
1278 	if (timestamp_is_null) {
1279 		timestamp = (zend_long) php_time();
1280 	}
1281 
1282 	ts = timelib_time_ctor();
1283 	if (gmt) {
1284 		tzi = NULL;
1285 		timelib_unixtime2gmt(ts, (timelib_sll) timestamp);
1286 	} else {
1287 		tzi = get_timezone_info();
1288 		if (!tzi) {
1289 			return;
1290 		}
1291 		ts->tz_info = tzi;
1292 		ts->zone_type = TIMELIB_ZONETYPE_ID;
1293 		timelib_unixtime2local(ts, (timelib_sll) timestamp);
1294 	}
1295 	ta.tm_sec   = ts->s;
1296 	ta.tm_min   = ts->i;
1297 	ta.tm_hour  = ts->h;
1298 	ta.tm_mday  = ts->d;
1299 	ta.tm_mon   = ts->m - 1;
1300 	ta.tm_year  = ts->y - 1900;
1301 	ta.tm_wday  = timelib_day_of_week(ts->y, ts->m, ts->d);
1302 	ta.tm_yday  = timelib_day_of_year(ts->y, ts->m, ts->d);
1303 	if (gmt) {
1304 		ta.tm_isdst = 0;
1305 #if HAVE_STRUCT_TM_TM_GMTOFF
1306 		ta.tm_gmtoff = 0;
1307 #endif
1308 #if HAVE_STRUCT_TM_TM_ZONE
1309 		ta.tm_zone = "GMT";
1310 #endif
1311 	} else {
1312 		offset = timelib_get_time_zone_info(timestamp, tzi);
1313 
1314 		ta.tm_isdst = offset->is_dst;
1315 #if HAVE_STRUCT_TM_TM_GMTOFF
1316 		ta.tm_gmtoff = offset->offset;
1317 #endif
1318 #if HAVE_STRUCT_TM_TM_ZONE
1319 		ta.tm_zone = offset->abbr;
1320 #endif
1321 	}
1322 
1323 	/* VS2012 crt has a bug where strftime crash with %z and %Z format when the
1324 	   initial buffer is too small. See
1325 	   http://connect.microsoft.com/VisualStudio/feedback/details/759720/vs2012-strftime-crash-with-z-formatting-code */
1326 	buf = zend_string_alloc(buf_len, 0);
1327 	while ((real_len = strftime(ZSTR_VAL(buf), buf_len, ZSTR_VAL(format), &ta)) == buf_len || real_len == 0) {
1328 		buf_len *= 2;
1329 		buf = zend_string_extend(buf, buf_len, 0);
1330 		if (!--max_reallocs) {
1331 			break;
1332 		}
1333 	}
1334 #ifdef PHP_WIN32
1335 	/* VS2012 strftime() returns number of characters, not bytes.
1336 		See VC++11 bug id 766205. */
1337 	if (real_len > 0) {
1338 		real_len = strlen(buf->val);
1339 	}
1340 #endif
1341 
1342 	timelib_time_dtor(ts);
1343 	if (!gmt) {
1344 		timelib_time_offset_dtor(offset);
1345 	}
1346 
1347 	if (real_len && real_len != buf_len) {
1348 		buf = zend_string_truncate(buf, real_len, 0);
1349 		RETURN_NEW_STR(buf);
1350 	}
1351 	zend_string_efree(buf);
1352 	RETURN_FALSE;
1353 }
1354 /* }}} */
1355 
1356 /* {{{ Format a local time/date according to locale settings */
PHP_FUNCTION(strftime)1357 PHP_FUNCTION(strftime)
1358 {
1359 	php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1360 }
1361 /* }}} */
1362 
1363 /* {{{ Format a GMT/UCT time/date according to locale settings */
PHP_FUNCTION(gmstrftime)1364 PHP_FUNCTION(gmstrftime)
1365 {
1366 	php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1367 }
1368 /* }}} */
1369 
1370 /* {{{ Return current UNIX timestamp */
PHP_FUNCTION(time)1371 PHP_FUNCTION(time)
1372 {
1373 	ZEND_PARSE_PARAMETERS_NONE();
1374 
1375 	RETURN_LONG((zend_long)php_time());
1376 }
1377 /* }}} */
1378 
1379 /* {{{ Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array */
PHP_FUNCTION(localtime)1380 PHP_FUNCTION(localtime)
1381 {
1382 	zend_long timestamp;
1383 	bool timestamp_is_null = 1;
1384 	bool associative = 0;
1385 	timelib_tzinfo *tzi;
1386 	timelib_time   *ts;
1387 
1388 	ZEND_PARSE_PARAMETERS_START(0, 2)
1389 		Z_PARAM_OPTIONAL
1390 		Z_PARAM_LONG_OR_NULL(timestamp, timestamp_is_null)
1391 		Z_PARAM_BOOL(associative)
1392 	ZEND_PARSE_PARAMETERS_END();
1393 
1394 	if (timestamp_is_null) {
1395 		timestamp = (zend_long) php_time();
1396 	}
1397 
1398 	tzi = get_timezone_info();
1399 	if (!tzi) {
1400 		RETURN_THROWS();
1401 	}
1402 	ts = timelib_time_ctor();
1403 	ts->tz_info = tzi;
1404 	ts->zone_type = TIMELIB_ZONETYPE_ID;
1405 	timelib_unixtime2local(ts, (timelib_sll) timestamp);
1406 
1407 	array_init(return_value);
1408 
1409 	if (associative) {
1410 		add_assoc_long(return_value, "tm_sec",   ts->s);
1411 		add_assoc_long(return_value, "tm_min",   ts->i);
1412 		add_assoc_long(return_value, "tm_hour",  ts->h);
1413 		add_assoc_long(return_value, "tm_mday",  ts->d);
1414 		add_assoc_long(return_value, "tm_mon",   ts->m - 1);
1415 		add_assoc_long(return_value, "tm_year",  ts->y - 1900);
1416 		add_assoc_long(return_value, "tm_wday",  timelib_day_of_week(ts->y, ts->m, ts->d));
1417 		add_assoc_long(return_value, "tm_yday",  timelib_day_of_year(ts->y, ts->m, ts->d));
1418 		add_assoc_long(return_value, "tm_isdst", ts->dst);
1419 	} else {
1420 		add_next_index_long(return_value, ts->s);
1421 		add_next_index_long(return_value, ts->i);
1422 		add_next_index_long(return_value, ts->h);
1423 		add_next_index_long(return_value, ts->d);
1424 		add_next_index_long(return_value, ts->m - 1);
1425 		add_next_index_long(return_value, ts->y- 1900);
1426 		add_next_index_long(return_value, timelib_day_of_week(ts->y, ts->m, ts->d));
1427 		add_next_index_long(return_value, timelib_day_of_year(ts->y, ts->m, ts->d));
1428 		add_next_index_long(return_value, ts->dst);
1429 	}
1430 
1431 	timelib_time_dtor(ts);
1432 }
1433 /* }}} */
1434 
1435 /* {{{ Get date/time information */
PHP_FUNCTION(getdate)1436 PHP_FUNCTION(getdate)
1437 {
1438 	zend_long timestamp;
1439 	bool timestamp_is_null = 1;
1440 	timelib_tzinfo *tzi;
1441 	timelib_time   *ts;
1442 
1443 	ZEND_PARSE_PARAMETERS_START(0, 1)
1444 		Z_PARAM_OPTIONAL
1445 		Z_PARAM_LONG_OR_NULL(timestamp, timestamp_is_null)
1446 	ZEND_PARSE_PARAMETERS_END();
1447 
1448 	if (timestamp_is_null) {
1449 		timestamp = (zend_long) php_time();
1450 	}
1451 
1452 	tzi = get_timezone_info();
1453 	if (!tzi) {
1454 		RETURN_THROWS();
1455 	}
1456 	ts = timelib_time_ctor();
1457 	ts->tz_info = tzi;
1458 	ts->zone_type = TIMELIB_ZONETYPE_ID;
1459 	timelib_unixtime2local(ts, (timelib_sll) timestamp);
1460 
1461 	array_init(return_value);
1462 
1463 	add_assoc_long(return_value, "seconds", ts->s);
1464 	add_assoc_long(return_value, "minutes", ts->i);
1465 	add_assoc_long(return_value, "hours", ts->h);
1466 	add_assoc_long(return_value, "mday", ts->d);
1467 	add_assoc_long(return_value, "wday", timelib_day_of_week(ts->y, ts->m, ts->d));
1468 	add_assoc_long(return_value, "mon", ts->m);
1469 	add_assoc_long(return_value, "year", ts->y);
1470 	add_assoc_long(return_value, "yday", timelib_day_of_year(ts->y, ts->m, ts->d));
1471 	add_assoc_string(return_value, "weekday", php_date_full_day_name(ts->y, ts->m, ts->d));
1472 	add_assoc_string(return_value, "month", mon_full_names[ts->m - 1]);
1473 	add_index_long(return_value, 0, timestamp);
1474 
1475 	timelib_time_dtor(ts);
1476 }
1477 /* }}} */
1478 
create_date_period_datetime(timelib_time * datetime,zend_class_entry * ce,zval * zv)1479 static void create_date_period_datetime(timelib_time *datetime, zend_class_entry *ce, zval *zv)
1480 {
1481 	if (datetime) {
1482 		php_date_obj *date_obj;
1483 
1484 		object_init_ex(zv, ce);
1485 		date_obj = Z_PHPDATE_P(zv);
1486 		date_obj->time = timelib_time_clone(datetime);
1487 	} else {
1488 		ZVAL_NULL(zv);
1489 	}
1490 }
1491 
create_date_period_interval(timelib_rel_time * interval,zval * zv)1492 static void create_date_period_interval(timelib_rel_time *interval, zval *zv)
1493 {
1494 	if (interval) {
1495 		php_interval_obj *interval_obj;
1496 
1497 		object_init_ex(zv, date_ce_interval);
1498 		interval_obj = Z_PHPINTERVAL_P(zv);
1499 		interval_obj->diff = timelib_rel_time_clone(interval);
1500 		interval_obj->initialized = 1;
1501 	} else {
1502 		ZVAL_NULL(zv);
1503 	}
1504 }
1505 
write_date_period_property(zend_object * obj,const char * name,const size_t name_len,zval * zv)1506 static void write_date_period_property(zend_object *obj, const char *name, const size_t name_len, zval *zv)
1507 {
1508 	zend_string *property_name = zend_string_init(name, name_len, 0);
1509 
1510 	zend_std_write_property(obj, property_name, zv, NULL);
1511 
1512 	zval_ptr_dtor(zv);
1513 	zend_string_release(property_name);
1514 }
1515 
initialize_date_period_properties(php_period_obj * period_obj)1516 static void initialize_date_period_properties(php_period_obj *period_obj)
1517 {
1518 	zval zv;
1519 
1520 	if (UNEXPECTED(!period_obj->std.properties)) {
1521 		rebuild_object_properties(&period_obj->std);
1522 	}
1523 
1524 	create_date_period_datetime(period_obj->start, period_obj->start_ce, &zv);
1525 	write_date_period_property(&period_obj->std, "start", sizeof("start") - 1, &zv);
1526 
1527 	create_date_period_datetime(period_obj->current, period_obj->start_ce, &zv);
1528 	write_date_period_property(&period_obj->std, "current", sizeof("current") - 1, &zv);
1529 
1530 	create_date_period_datetime(period_obj->end, period_obj->start_ce, &zv);
1531 	write_date_period_property(&period_obj->std, "end", sizeof("end") - 1, &zv);
1532 
1533 	create_date_period_interval(period_obj->interval, &zv);
1534 	write_date_period_property(&period_obj->std, "interval", sizeof("interval") - 1, &zv);
1535 
1536 	ZVAL_LONG(&zv, (zend_long) period_obj->recurrences);
1537 	write_date_period_property(&period_obj->std, "recurrences", sizeof("recurrences") - 1, &zv);
1538 
1539 	ZVAL_BOOL(&zv, period_obj->include_start_date);
1540 	write_date_period_property(&period_obj->std, "include_start_date", sizeof("include_start_date") - 1, &zv);
1541 
1542 	ZVAL_BOOL(&zv, period_obj->include_end_date);
1543 	write_date_period_property(&period_obj->std, "include_end_date", sizeof("include_end_date") - 1, &zv);
1544 }
1545 
1546 /* define an overloaded iterator structure */
1547 typedef struct {
1548 	zend_object_iterator  intern;
1549 	zval                  current;
1550 	php_period_obj       *object;
1551 	int                   current_index;
1552 } date_period_it;
1553 
1554 /* {{{ date_period_it_invalidate_current */
date_period_it_invalidate_current(zend_object_iterator * iter)1555 static void date_period_it_invalidate_current(zend_object_iterator *iter)
1556 {
1557 	date_period_it *iterator = (date_period_it *)iter;
1558 
1559 	if (Z_TYPE(iterator->current) != IS_UNDEF) {
1560 		zval_ptr_dtor(&iterator->current);
1561 		ZVAL_UNDEF(&iterator->current);
1562 	}
1563 }
1564 /* }}} */
1565 
1566 /* {{{ date_period_it_dtor */
date_period_it_dtor(zend_object_iterator * iter)1567 static void date_period_it_dtor(zend_object_iterator *iter)
1568 {
1569 	date_period_it *iterator = (date_period_it *)iter;
1570 
1571 	date_period_it_invalidate_current(iter);
1572 
1573 	zval_ptr_dtor(&iterator->intern.data);
1574 }
1575 /* }}} */
1576 
1577 /* {{{ date_period_it_has_more */
date_period_it_has_more(zend_object_iterator * iter)1578 static zend_result date_period_it_has_more(zend_object_iterator *iter)
1579 {
1580 	date_period_it *iterator = (date_period_it *)iter;
1581 	php_period_obj *object   = Z_PHPPERIOD_P(&iterator->intern.data);
1582 
1583 	if (object->end) {
1584 		if (object->include_end_date) {
1585 			return object->current->sse <= object->end->sse ? SUCCESS : FAILURE;
1586 		} else {
1587 			return object->current->sse < object->end->sse ? SUCCESS : FAILURE;
1588 		}
1589 	} else {
1590 		return (iterator->current_index < object->recurrences) ? SUCCESS : FAILURE;
1591 	}
1592 }
1593 /* }}} */
1594 
get_base_date_class(zend_class_entry * start_ce)1595 static zend_class_entry *get_base_date_class(zend_class_entry *start_ce)
1596 {
1597 	zend_class_entry *tmp = start_ce;
1598 
1599 	while (tmp != date_ce_date && tmp != date_ce_immutable && tmp->parent) {
1600 		tmp = tmp->parent;
1601 	}
1602 
1603 	return tmp;
1604 }
1605 
1606 /* {{{ date_period_it_current_data */
date_period_it_current_data(zend_object_iterator * iter)1607 static zval *date_period_it_current_data(zend_object_iterator *iter)
1608 {
1609 	date_period_it *iterator = (date_period_it *)iter;
1610 	php_period_obj *object   = Z_PHPPERIOD_P(&iterator->intern.data);
1611 	timelib_time   *it_time = object->current;
1612 	php_date_obj   *newdateobj;
1613 
1614 	/* Create new object */
1615 	php_date_instantiate(get_base_date_class(object->start_ce), &iterator->current);
1616 	newdateobj = Z_PHPDATE_P(&iterator->current);
1617 	newdateobj->time = timelib_time_ctor();
1618 	*newdateobj->time = *it_time;
1619 	if (it_time->tz_abbr) {
1620 		newdateobj->time->tz_abbr = timelib_strdup(it_time->tz_abbr);
1621 	}
1622 	if (it_time->tz_info) {
1623 		newdateobj->time->tz_info = it_time->tz_info;
1624 	}
1625 
1626 	return &iterator->current;
1627 }
1628 /* }}} */
1629 
1630 /* {{{ date_period_it_current_key */
date_period_it_current_key(zend_object_iterator * iter,zval * key)1631 static void date_period_it_current_key(zend_object_iterator *iter, zval *key)
1632 {
1633 	date_period_it *iterator = (date_period_it *)iter;
1634 	ZVAL_LONG(key, iterator->current_index);
1635 }
1636 /* }}} */
1637 
date_period_advance(timelib_time * it_time,timelib_rel_time * interval)1638 static void date_period_advance(timelib_time *it_time, timelib_rel_time *interval)
1639 {
1640 	it_time->have_relative = 1;
1641 	it_time->relative = *interval;
1642 	it_time->sse_uptodate = 0;
1643 	timelib_update_ts(it_time, NULL);
1644 	timelib_update_from_sse(it_time);
1645 }
1646 
1647 /* {{{ date_period_it_move_forward */
date_period_it_move_forward(zend_object_iterator * iter)1648 static void date_period_it_move_forward(zend_object_iterator *iter)
1649 {
1650 	date_period_it *iterator = (date_period_it *)iter;
1651 	php_period_obj *object   = Z_PHPPERIOD_P(&iterator->intern.data);
1652 	timelib_time   *it_time  = object->current;
1653 	zval current_zv;
1654 
1655 	date_period_advance(it_time, object->interval);
1656 
1657 	if (UNEXPECTED(!object->std.properties)) {
1658 		rebuild_object_properties(&object->std);
1659 	}
1660 
1661 	create_date_period_datetime(object->current, object->start_ce, &current_zv);
1662 	zend_string *property_name = ZSTR_INIT_LITERAL("current", 0);
1663 	zend_std_write_property(&object->std, property_name, &current_zv, NULL);
1664 	zval_ptr_dtor(&current_zv);
1665 	zend_string_release(property_name);
1666 
1667 	iterator->current_index++;
1668 	date_period_it_invalidate_current(iter);
1669 }
1670 /* }}} */
1671 
1672 /* {{{ date_period_it_rewind */
date_period_it_rewind(zend_object_iterator * iter)1673 static void date_period_it_rewind(zend_object_iterator *iter)
1674 {
1675 	date_period_it *iterator = (date_period_it *)iter;
1676 
1677 	iterator->current_index = 0;
1678 	if (iterator->object->current) {
1679 		timelib_time_dtor(iterator->object->current);
1680 	}
1681 	if (!iterator->object->start) {
1682 		date_throw_uninitialized_error(date_ce_period);
1683 		return;
1684 	}
1685 
1686 	iterator->object->current = timelib_time_clone(iterator->object->start);
1687 
1688 	if (!iterator->object->include_start_date) {
1689 		date_period_advance(iterator->object->current, iterator->object->interval);
1690 	}
1691 
1692 	date_period_it_invalidate_current(iter);
1693 }
1694 /* }}} */
1695 
1696 /* iterator handler table */
1697 static const zend_object_iterator_funcs date_period_it_funcs = {
1698 	date_period_it_dtor,
1699 	date_period_it_has_more,
1700 	date_period_it_current_data,
1701 	date_period_it_current_key,
1702 	date_period_it_move_forward,
1703 	date_period_it_rewind,
1704 	date_period_it_invalidate_current,
1705 	NULL, /* get_gc */
1706 };
1707 
date_object_period_get_iterator(zend_class_entry * ce,zval * object,int by_ref)1708 static zend_object_iterator *date_object_period_get_iterator(zend_class_entry *ce, zval *object, int by_ref) /* {{{ */
1709 {
1710 	date_period_it *iterator;
1711 
1712 	if (by_ref) {
1713 		zend_throw_error(NULL, "An iterator cannot be used with foreach by reference");
1714 		return NULL;
1715 	}
1716 
1717 	iterator = emalloc(sizeof(date_period_it));
1718 
1719 	zend_iterator_init((zend_object_iterator*)iterator);
1720 
1721 	ZVAL_OBJ_COPY(&iterator->intern.data, Z_OBJ_P(object));
1722 	iterator->intern.funcs = &date_period_it_funcs;
1723 	iterator->object = Z_PHPPERIOD_P(object);
1724 	ZVAL_UNDEF(&iterator->current);
1725 
1726 	return (zend_object_iterator*)iterator;
1727 } /* }}} */
1728 
implement_date_interface_handler(zend_class_entry * interface,zend_class_entry * implementor)1729 static int implement_date_interface_handler(zend_class_entry *interface, zend_class_entry *implementor) /* {{{ */
1730 {
1731 	if (implementor->type == ZEND_USER_CLASS &&
1732 		!instanceof_function(implementor, date_ce_date) &&
1733 		!instanceof_function(implementor, date_ce_immutable)
1734 	) {
1735 		zend_error_noreturn(E_ERROR, "DateTimeInterface can't be implemented by user classes");
1736 	}
1737 
1738 	return SUCCESS;
1739 } /* }}} */
1740 
date_interval_has_property(zend_object * object,zend_string * name,int type,void ** cache_slot)1741 static int date_interval_has_property(zend_object *object, zend_string *name, int type, void **cache_slot) /* {{{ */
1742 {
1743 	php_interval_obj *obj;
1744 	zval rv;
1745 	zval *prop;
1746 	int retval = 0;
1747 
1748 	obj = php_interval_obj_from_obj(object);
1749 
1750 	if (!obj->initialized) {
1751 		retval = zend_std_has_property(object, name, type, cache_slot);
1752 		return retval;
1753 	}
1754 
1755 	prop = date_interval_read_property(object, name, BP_VAR_IS, cache_slot, &rv);
1756 
1757 	if (prop != &EG(uninitialized_zval)) {
1758 		if (type == 2) {
1759 			retval = 1;
1760 		} else if (type == 1) {
1761 			retval = zend_is_true(prop);
1762 		} else if (type == 0) {
1763 			retval = (Z_TYPE_P(prop) != IS_NULL);
1764 		}
1765 	} else {
1766 		retval = zend_std_has_property(object, name, type, cache_slot);
1767 	}
1768 
1769 	return retval;
1770 
1771 }
1772 /* }}} */
1773 
date_register_classes(void)1774 static void date_register_classes(void) /* {{{ */
1775 {
1776 	date_ce_interface = register_class_DateTimeInterface();
1777 	date_ce_interface->interface_gets_implemented = implement_date_interface_handler;
1778 
1779 	date_ce_date = register_class_DateTime(date_ce_interface);
1780 	date_ce_date->create_object = date_object_new_date;
1781 	date_ce_date->default_object_handlers = &date_object_handlers_date;
1782 	memcpy(&date_object_handlers_date, &std_object_handlers, sizeof(zend_object_handlers));
1783 	date_object_handlers_date.offset = XtOffsetOf(php_date_obj, std);
1784 	date_object_handlers_date.free_obj = date_object_free_storage_date;
1785 	date_object_handlers_date.clone_obj = date_object_clone_date;
1786 	date_object_handlers_date.compare = date_object_compare_date;
1787 	date_object_handlers_date.get_properties_for = date_object_get_properties_for;
1788 	date_object_handlers_date.get_gc = date_object_get_gc;
1789 
1790 	date_ce_immutable = register_class_DateTimeImmutable(date_ce_interface);
1791 	date_ce_immutable->create_object = date_object_new_date;
1792 	date_ce_immutable->default_object_handlers = &date_object_handlers_date;
1793 	memcpy(&date_object_handlers_immutable, &std_object_handlers, sizeof(zend_object_handlers));
1794 	date_object_handlers_immutable.clone_obj = date_object_clone_date;
1795 	date_object_handlers_immutable.compare = date_object_compare_date;
1796 	date_object_handlers_immutable.get_properties_for = date_object_get_properties_for;
1797 	date_object_handlers_immutable.get_gc = date_object_get_gc;
1798 
1799 	date_ce_timezone = register_class_DateTimeZone();
1800 	date_ce_timezone->create_object = date_object_new_timezone;
1801 	date_ce_timezone->default_object_handlers = &date_object_handlers_timezone;
1802 	memcpy(&date_object_handlers_timezone, &std_object_handlers, sizeof(zend_object_handlers));
1803 	date_object_handlers_timezone.offset = XtOffsetOf(php_timezone_obj, std);
1804 	date_object_handlers_timezone.free_obj = date_object_free_storage_timezone;
1805 	date_object_handlers_timezone.clone_obj = date_object_clone_timezone;
1806 	date_object_handlers_timezone.get_properties_for = date_object_get_properties_for_timezone;
1807 	date_object_handlers_timezone.get_gc = date_object_get_gc_timezone;
1808 	date_object_handlers_timezone.get_debug_info = date_object_get_debug_info_timezone;
1809 	date_object_handlers_timezone.compare = date_object_compare_timezone;
1810 
1811 	date_ce_interval = register_class_DateInterval();
1812 	date_ce_interval->create_object = date_object_new_interval;
1813 	date_ce_interval->default_object_handlers = &date_object_handlers_interval;
1814 	memcpy(&date_object_handlers_interval, &std_object_handlers, sizeof(zend_object_handlers));
1815 	date_object_handlers_interval.offset = XtOffsetOf(php_interval_obj, std);
1816 	date_object_handlers_interval.free_obj = date_object_free_storage_interval;
1817 	date_object_handlers_interval.clone_obj = date_object_clone_interval;
1818 	date_object_handlers_interval.has_property = date_interval_has_property;
1819 	date_object_handlers_interval.read_property = date_interval_read_property;
1820 	date_object_handlers_interval.write_property = date_interval_write_property;
1821 	date_object_handlers_interval.get_properties = date_object_get_properties_interval;
1822 	date_object_handlers_interval.get_property_ptr_ptr = date_interval_get_property_ptr_ptr;
1823 	date_object_handlers_interval.get_gc = date_object_get_gc_interval;
1824 	date_object_handlers_interval.compare = date_interval_compare_objects;
1825 
1826 	date_ce_period = register_class_DatePeriod(zend_ce_aggregate);
1827 	date_ce_period->create_object = date_object_new_period;
1828 	date_ce_period->default_object_handlers = &date_object_handlers_period;
1829 	date_ce_period->get_iterator = date_object_period_get_iterator;
1830 	memcpy(&date_object_handlers_period, &std_object_handlers, sizeof(zend_object_handlers));
1831 	date_object_handlers_period.offset = XtOffsetOf(php_period_obj, std);
1832 	date_object_handlers_period.free_obj = date_object_free_storage_period;
1833 	date_object_handlers_period.clone_obj = date_object_clone_period;
1834 	date_object_handlers_period.get_gc = date_object_get_gc_period;
1835 	date_object_handlers_period.get_property_ptr_ptr = date_period_get_property_ptr_ptr;
1836 	date_object_handlers_period.read_property = date_period_read_property;
1837 	date_object_handlers_period.write_property = date_period_write_property;
1838 
1839 	date_ce_date_error = register_class_DateError(zend_ce_error);
1840 	date_ce_date_object_error = register_class_DateObjectError(date_ce_date_error);
1841 	date_ce_date_range_error = register_class_DateRangeError(date_ce_date_error);
1842 
1843 	date_ce_date_exception = register_class_DateException(zend_ce_exception);
1844 	date_ce_date_invalid_timezone_exception = register_class_DateInvalidTimeZoneException(date_ce_date_exception);
1845 	date_ce_date_invalid_operation_exception = register_class_DateInvalidOperationException(date_ce_date_exception);
1846 	date_ce_date_malformed_string_exception = register_class_DateMalformedStringException(date_ce_date_exception);
1847 	date_ce_date_malformed_interval_string_exception = register_class_DateMalformedIntervalStringException(date_ce_date_exception);
1848 	date_ce_date_malformed_period_string_exception = register_class_DateMalformedPeriodStringException(date_ce_date_exception);
1849 } /* }}} */
1850 
date_object_new_date(zend_class_entry * class_type)1851 static zend_object *date_object_new_date(zend_class_entry *class_type) /* {{{ */
1852 {
1853 	php_date_obj *intern = zend_object_alloc(sizeof(php_date_obj), class_type);
1854 
1855 	zend_object_std_init(&intern->std, class_type);
1856 	object_properties_init(&intern->std, class_type);
1857 
1858 	return &intern->std;
1859 } /* }}} */
1860 
date_object_clone_date(zend_object * this_ptr)1861 static zend_object *date_object_clone_date(zend_object *this_ptr) /* {{{ */
1862 {
1863 	php_date_obj *old_obj = php_date_obj_from_obj(this_ptr);
1864 	php_date_obj *new_obj = php_date_obj_from_obj(date_object_new_date(old_obj->std.ce));
1865 
1866 	zend_objects_clone_members(&new_obj->std, &old_obj->std);
1867 	if (!old_obj->time) {
1868 		return &new_obj->std;
1869 	}
1870 
1871 	/* this should probably moved to a new `timelib_time *timelime_time_clone(timelib_time *)` */
1872 	new_obj->time = timelib_time_ctor();
1873 	*new_obj->time = *old_obj->time;
1874 	if (old_obj->time->tz_abbr) {
1875 		new_obj->time->tz_abbr = timelib_strdup(old_obj->time->tz_abbr);
1876 	}
1877 	if (old_obj->time->tz_info) {
1878 		new_obj->time->tz_info = old_obj->time->tz_info;
1879 	}
1880 
1881 	return &new_obj->std;
1882 } /* }}} */
1883 
date_clone_immutable(zval * object,zval * new_object)1884 static void date_clone_immutable(zval *object, zval *new_object) /* {{{ */
1885 {
1886 	ZVAL_OBJ(new_object, date_object_clone_date(Z_OBJ_P(object)));
1887 } /* }}} */
1888 
date_object_compare_date(zval * d1,zval * d2)1889 static int date_object_compare_date(zval *d1, zval *d2) /* {{{ */
1890 {
1891 	php_date_obj *o1;
1892 	php_date_obj *o2;
1893 
1894 	ZEND_COMPARE_OBJECTS_FALLBACK(d1, d2);
1895 
1896 	o1 = Z_PHPDATE_P(d1);
1897 	o2 = Z_PHPDATE_P(d2);
1898 
1899 	if (!o1->time || !o2->time) {
1900 		zend_throw_error(date_ce_date_object_error, "Trying to compare an incomplete DateTime or DateTimeImmutable object");
1901 		return ZEND_UNCOMPARABLE;
1902 	}
1903 	if (!o1->time->sse_uptodate) {
1904 		timelib_update_ts(o1->time, o1->time->tz_info);
1905 	}
1906 	if (!o2->time->sse_uptodate) {
1907 		timelib_update_ts(o2->time, o2->time->tz_info);
1908 	}
1909 
1910 	return timelib_time_compare(o1->time, o2->time);
1911 } /* }}} */
1912 
date_object_get_gc(zend_object * object,zval ** table,int * n)1913 static HashTable *date_object_get_gc(zend_object *object, zval **table, int *n) /* {{{ */
1914 {
1915 	*table = NULL;
1916 	*n = 0;
1917 	return zend_std_get_properties(object);
1918 } /* }}} */
1919 
date_object_get_gc_timezone(zend_object * object,zval ** table,int * n)1920 static HashTable *date_object_get_gc_timezone(zend_object *object, zval **table, int *n) /* {{{ */
1921 {
1922 	*table = NULL;
1923 	*n = 0;
1924 	return zend_std_get_properties(object);
1925 } /* }}} */
1926 
date_object_to_hash(php_date_obj * dateobj,HashTable * props)1927 static void date_object_to_hash(php_date_obj *dateobj, HashTable *props)
1928 {
1929 	zval zv;
1930 
1931 	/* first we add the date and time in ISO format */
1932 	ZVAL_STR(&zv, date_format("x-m-d H:i:s.u", sizeof("x-m-d H:i:s.u")-1, dateobj->time, 1));
1933 	zend_hash_str_update(props, "date", sizeof("date")-1, &zv);
1934 
1935 	/* then we add the timezone name (or similar) */
1936 	if (dateobj->time->is_localtime) {
1937 		ZVAL_LONG(&zv, dateobj->time->zone_type);
1938 		zend_hash_str_update(props, "timezone_type", sizeof("timezone_type")-1, &zv);
1939 
1940 		switch (dateobj->time->zone_type) {
1941 			case TIMELIB_ZONETYPE_ID:
1942 				ZVAL_STRING(&zv, dateobj->time->tz_info->name);
1943 				break;
1944 			case TIMELIB_ZONETYPE_OFFSET: {
1945 				zend_string *tmpstr = zend_string_alloc(sizeof("UTC+05:00")-1, 0);
1946 				int utc_offset = dateobj->time->z;
1947 
1948 				ZSTR_LEN(tmpstr) = snprintf(ZSTR_VAL(tmpstr), sizeof("+05:00"), "%c%02d:%02d",
1949 					utc_offset < 0 ? '-' : '+',
1950 					abs(utc_offset / 3600),
1951 					abs(((utc_offset % 3600) / 60)));
1952 
1953 				ZVAL_NEW_STR(&zv, tmpstr);
1954 				}
1955 				break;
1956 			case TIMELIB_ZONETYPE_ABBR:
1957 				ZVAL_STRING(&zv, dateobj->time->tz_abbr);
1958 				break;
1959 		}
1960 		zend_hash_str_update(props, "timezone", sizeof("timezone")-1, &zv);
1961 	}
1962 }
1963 
date_object_get_properties_for(zend_object * object,zend_prop_purpose purpose)1964 static HashTable *date_object_get_properties_for(zend_object *object, zend_prop_purpose purpose) /* {{{ */
1965 {
1966 	HashTable *props;
1967 	php_date_obj *dateobj;
1968 
1969 	switch (purpose) {
1970 		case ZEND_PROP_PURPOSE_DEBUG:
1971 		case ZEND_PROP_PURPOSE_SERIALIZE:
1972 		case ZEND_PROP_PURPOSE_VAR_EXPORT:
1973 		case ZEND_PROP_PURPOSE_JSON:
1974 		case ZEND_PROP_PURPOSE_ARRAY_CAST:
1975 			break;
1976 		default:
1977 			return zend_std_get_properties_for(object, purpose);
1978 	}
1979 
1980 	dateobj = php_date_obj_from_obj(object);
1981 	props = zend_array_dup(zend_std_get_properties(object));
1982 	if (!dateobj->time) {
1983 		return props;
1984 	}
1985 
1986 	date_object_to_hash(dateobj, props);
1987 
1988 	return props;
1989 } /* }}} */
1990 
date_object_new_timezone(zend_class_entry * class_type)1991 static zend_object *date_object_new_timezone(zend_class_entry *class_type) /* {{{ */
1992 {
1993 	php_timezone_obj *intern = zend_object_alloc(sizeof(php_timezone_obj), class_type);
1994 
1995 	zend_object_std_init(&intern->std, class_type);
1996 	object_properties_init(&intern->std, class_type);
1997 
1998 	return &intern->std;
1999 } /* }}} */
2000 
date_object_clone_timezone(zend_object * this_ptr)2001 static zend_object *date_object_clone_timezone(zend_object *this_ptr) /* {{{ */
2002 {
2003 	php_timezone_obj *old_obj = php_timezone_obj_from_obj(this_ptr);
2004 	php_timezone_obj *new_obj = php_timezone_obj_from_obj(date_object_new_timezone(old_obj->std.ce));
2005 
2006 	zend_objects_clone_members(&new_obj->std, &old_obj->std);
2007 	if (!old_obj->initialized) {
2008 		return &new_obj->std;
2009 	}
2010 
2011 	new_obj->type = old_obj->type;
2012 	new_obj->initialized = 1;
2013 	switch (new_obj->type) {
2014 		case TIMELIB_ZONETYPE_ID:
2015 			new_obj->tzi.tz = old_obj->tzi.tz;
2016 			break;
2017 		case TIMELIB_ZONETYPE_OFFSET:
2018 			new_obj->tzi.utc_offset = old_obj->tzi.utc_offset;
2019 			break;
2020 		case TIMELIB_ZONETYPE_ABBR:
2021 			new_obj->tzi.z.utc_offset = old_obj->tzi.z.utc_offset;
2022 			new_obj->tzi.z.dst        = old_obj->tzi.z.dst;
2023 			new_obj->tzi.z.abbr       = timelib_strdup(old_obj->tzi.z.abbr);
2024 			break;
2025 	}
2026 
2027 	return &new_obj->std;
2028 } /* }}} */
2029 
date_object_compare_timezone(zval * tz1,zval * tz2)2030 static int date_object_compare_timezone(zval *tz1, zval *tz2) /* {{{ */
2031 {
2032 	php_timezone_obj *o1, *o2;
2033 
2034 	ZEND_COMPARE_OBJECTS_FALLBACK(tz1, tz2);
2035 
2036 	o1 = Z_PHPTIMEZONE_P(tz1);
2037 	o2 = Z_PHPTIMEZONE_P(tz2);
2038 
2039 	if (!o1->initialized || !o2->initialized) {
2040 		zend_throw_error(date_ce_date_object_error, "Trying to compare uninitialized DateTimeZone objects");
2041 		return 1;
2042 	}
2043 
2044 	if (o1->type != o2->type) {
2045 		zend_throw_error(date_ce_date_exception, "Cannot compare two different kinds of DateTimeZone objects");
2046 		return ZEND_UNCOMPARABLE;
2047 	}
2048 
2049 	switch (o1->type) {
2050 		case TIMELIB_ZONETYPE_OFFSET:
2051 			return o1->tzi.utc_offset == o2->tzi.utc_offset ? 0 : 1;
2052 		case TIMELIB_ZONETYPE_ABBR:
2053 			return strcmp(o1->tzi.z.abbr, o2->tzi.z.abbr) ? 1 : 0;
2054 		case TIMELIB_ZONETYPE_ID:
2055 			return strcmp(o1->tzi.tz->name, o2->tzi.tz->name) ? 1 : 0;
2056 		EMPTY_SWITCH_DEFAULT_CASE();
2057 	}
2058 } /* }}} */
2059 
php_timezone_to_string(php_timezone_obj * tzobj,zval * zv)2060 static void php_timezone_to_string(php_timezone_obj *tzobj, zval *zv)
2061 {
2062 	switch (tzobj->type) {
2063 		case TIMELIB_ZONETYPE_ID:
2064 			ZVAL_STRING(zv, tzobj->tzi.tz->name);
2065 			break;
2066 		case TIMELIB_ZONETYPE_OFFSET: {
2067 			timelib_sll utc_offset = tzobj->tzi.utc_offset;
2068 			int seconds = utc_offset % 60;
2069 			size_t size;
2070 			const char *format;
2071 			if (seconds == 0) {
2072 				size = sizeof("+05:00");
2073 				format = "%c%02d:%02d";
2074 			} else {
2075 				size = sizeof("+05:00:01");
2076 				format = "%c%02d:%02d:%02d";
2077 			}
2078 			zend_string *tmpstr = zend_string_alloc(size - 1, 0);
2079 
2080 			/* Note: if seconds == 0, the seconds argument will be excessive and therefore ignored. */
2081 			ZSTR_LEN(tmpstr) = snprintf(ZSTR_VAL(tmpstr), size, format,
2082 				utc_offset < 0 ? '-' : '+',
2083 				abs((int)(utc_offset / 3600)),
2084 				abs((int)(utc_offset % 3600) / 60),
2085 				abs(seconds));
2086 
2087 			ZVAL_NEW_STR(zv, tmpstr);
2088 			}
2089 			break;
2090 		case TIMELIB_ZONETYPE_ABBR:
2091 			ZVAL_STRING(zv, tzobj->tzi.z.abbr);
2092 			break;
2093 	}
2094 }
2095 
date_timezone_object_to_hash(php_timezone_obj * tzobj,HashTable * props)2096 static void date_timezone_object_to_hash(php_timezone_obj *tzobj, HashTable *props)
2097 {
2098 	zval zv;
2099 
2100 	ZVAL_LONG(&zv, tzobj->type);
2101 	zend_hash_str_update(props, "timezone_type", strlen("timezone_type"), &zv);
2102 
2103 	php_timezone_to_string(tzobj, &zv);
2104 	zend_hash_str_update(props, "timezone", strlen("timezone"), &zv);
2105 }
2106 
date_object_get_properties_for_timezone(zend_object * object,zend_prop_purpose purpose)2107 static HashTable *date_object_get_properties_for_timezone(zend_object *object, zend_prop_purpose purpose) /* {{{ */
2108 {
2109 	HashTable *props;
2110 	php_timezone_obj *tzobj;
2111 
2112 	switch (purpose) {
2113 		case ZEND_PROP_PURPOSE_DEBUG:
2114 		case ZEND_PROP_PURPOSE_SERIALIZE:
2115 		case ZEND_PROP_PURPOSE_VAR_EXPORT:
2116 		case ZEND_PROP_PURPOSE_JSON:
2117 		case ZEND_PROP_PURPOSE_ARRAY_CAST:
2118 			break;
2119 		default:
2120 			return zend_std_get_properties_for(object, purpose);
2121 	}
2122 
2123 	tzobj = php_timezone_obj_from_obj(object);
2124 	props = zend_array_dup(zend_std_get_properties(object));
2125 	if (!tzobj->initialized) {
2126 		return props;
2127 	}
2128 
2129 	date_timezone_object_to_hash(tzobj, props);
2130 
2131 	return props;
2132 } /* }}} */
2133 
date_object_get_debug_info_timezone(zend_object * object,int * is_temp)2134 static HashTable *date_object_get_debug_info_timezone(zend_object *object, int *is_temp) /* {{{ */
2135 {
2136 	HashTable *ht, *props;
2137 	zval zv;
2138 	php_timezone_obj *tzobj;
2139 
2140 	tzobj = php_timezone_obj_from_obj(object);
2141 	props = zend_std_get_properties(object);
2142 
2143 	*is_temp = 1;
2144 	ht = zend_array_dup(props);
2145 
2146 	ZVAL_LONG(&zv, tzobj->type);
2147 	zend_hash_str_update(ht, "timezone_type", sizeof("timezone_type")-1, &zv);
2148 
2149 	php_timezone_to_string(tzobj, &zv);
2150 	zend_hash_str_update(ht, "timezone", sizeof("timezone")-1, &zv);
2151 
2152 	return ht;
2153 } /* }}} */
2154 
date_object_new_interval(zend_class_entry * class_type)2155 static zend_object *date_object_new_interval(zend_class_entry *class_type) /* {{{ */
2156 {
2157 	php_interval_obj *intern = zend_object_alloc(sizeof(php_interval_obj), class_type);
2158 
2159 	zend_object_std_init(&intern->std, class_type);
2160 	object_properties_init(&intern->std, class_type);
2161 
2162 	return &intern->std;
2163 } /* }}} */
2164 
date_object_clone_interval(zend_object * this_ptr)2165 static zend_object *date_object_clone_interval(zend_object *this_ptr) /* {{{ */
2166 {
2167 	php_interval_obj *old_obj = php_interval_obj_from_obj(this_ptr);
2168 	php_interval_obj *new_obj = php_interval_obj_from_obj(date_object_new_interval(old_obj->std.ce));
2169 
2170 	zend_objects_clone_members(&new_obj->std, &old_obj->std);
2171 	new_obj->civil_or_wall = old_obj->civil_or_wall;
2172 	new_obj->from_string = old_obj->from_string;
2173 	if (old_obj->date_string) {
2174 		new_obj->date_string = zend_string_copy(old_obj->date_string);
2175 	}
2176 	new_obj->initialized = old_obj->initialized;
2177 	if (old_obj->diff) {
2178 		new_obj->diff = timelib_rel_time_clone(old_obj->diff);
2179 	}
2180 
2181 	return &new_obj->std;
2182 } /* }}} */
2183 
date_object_get_gc_interval(zend_object * object,zval ** table,int * n)2184 static HashTable *date_object_get_gc_interval(zend_object *object, zval **table, int *n) /* {{{ */
2185 {
2186 
2187 	*table = NULL;
2188 	*n = 0;
2189 	return zend_std_get_properties(object);
2190 } /* }}} */
2191 
date_interval_object_to_hash(php_interval_obj * intervalobj,HashTable * props)2192 static void date_interval_object_to_hash(php_interval_obj *intervalobj, HashTable *props)
2193 {
2194 	zval zv;
2195 
2196 	/* Records whether this is a special relative interval that needs to be recreated from a string */
2197 	if (intervalobj->from_string) {
2198 		ZVAL_BOOL(&zv, (bool)intervalobj->from_string);
2199 		zend_hash_str_update(props, "from_string", strlen("from_string"), &zv);
2200 		ZVAL_STR_COPY(&zv, intervalobj->date_string);
2201 		zend_hash_str_update(props, "date_string", strlen("date_string"), &zv);
2202 		return;
2203 	}
2204 
2205 #define PHP_DATE_INTERVAL_ADD_PROPERTY(n,f) \
2206 	ZVAL_LONG(&zv, (zend_long)intervalobj->diff->f); \
2207 	zend_hash_str_update(props, n, sizeof(n)-1, &zv);
2208 
2209 	PHP_DATE_INTERVAL_ADD_PROPERTY("y", y);
2210 	PHP_DATE_INTERVAL_ADD_PROPERTY("m", m);
2211 	PHP_DATE_INTERVAL_ADD_PROPERTY("d", d);
2212 	PHP_DATE_INTERVAL_ADD_PROPERTY("h", h);
2213 	PHP_DATE_INTERVAL_ADD_PROPERTY("i", i);
2214 	PHP_DATE_INTERVAL_ADD_PROPERTY("s", s);
2215 	ZVAL_DOUBLE(&zv, (double)intervalobj->diff->us / 1000000.0);
2216 	zend_hash_str_update(props, "f", sizeof("f") - 1, &zv);
2217 	PHP_DATE_INTERVAL_ADD_PROPERTY("invert", invert);
2218 	if (intervalobj->diff->days != TIMELIB_UNSET) {
2219 		PHP_DATE_INTERVAL_ADD_PROPERTY("days", days);
2220 	} else {
2221 		ZVAL_FALSE(&zv);
2222 		zend_hash_str_update(props, "days", sizeof("days")-1, &zv);
2223 	}
2224 	ZVAL_BOOL(&zv, (bool)intervalobj->from_string);
2225 	zend_hash_str_update(props, "from_string", strlen("from_string"), &zv);
2226 
2227 #undef PHP_DATE_INTERVAL_ADD_PROPERTY
2228 }
2229 
date_object_get_properties_interval(zend_object * object)2230 static HashTable *date_object_get_properties_interval(zend_object *object) /* {{{ */
2231 {
2232 	HashTable *props;
2233 	php_interval_obj *intervalobj;
2234 
2235 	intervalobj = php_interval_obj_from_obj(object);
2236 	props = zend_std_get_properties(object);
2237 	if (!intervalobj->initialized) {
2238 		return props;
2239 	}
2240 
2241 	date_interval_object_to_hash(intervalobj, props);
2242 
2243 	return props;
2244 } /* }}} */
2245 
date_object_new_period(zend_class_entry * class_type)2246 static zend_object *date_object_new_period(zend_class_entry *class_type) /* {{{ */
2247 {
2248 	php_period_obj *intern = zend_object_alloc(sizeof(php_period_obj), class_type);
2249 
2250 	zend_object_std_init(&intern->std, class_type);
2251 	object_properties_init(&intern->std, class_type);
2252 
2253 	return &intern->std;
2254 } /* }}} */
2255 
date_object_clone_period(zend_object * this_ptr)2256 static zend_object *date_object_clone_period(zend_object *this_ptr) /* {{{ */
2257 {
2258 	php_period_obj *old_obj = php_period_obj_from_obj(this_ptr);
2259 	php_period_obj *new_obj = php_period_obj_from_obj(date_object_new_period(old_obj->std.ce));
2260 
2261 	zend_objects_clone_members(&new_obj->std, &old_obj->std);
2262 	new_obj->initialized = old_obj->initialized;
2263 	new_obj->recurrences = old_obj->recurrences;
2264 	new_obj->include_start_date = old_obj->include_start_date;
2265 	new_obj->include_end_date = old_obj->include_end_date;
2266 	new_obj->start_ce = old_obj->start_ce;
2267 
2268 	if (old_obj->start) {
2269 		new_obj->start = timelib_time_clone(old_obj->start);
2270 	}
2271 	if (old_obj->current) {
2272 		new_obj->current = timelib_time_clone(old_obj->current);
2273 	}
2274 	if (old_obj->end) {
2275 		new_obj->end = timelib_time_clone(old_obj->end);
2276 	}
2277 	if (old_obj->interval) {
2278 		new_obj->interval = timelib_rel_time_clone(old_obj->interval);
2279 	}
2280 	return &new_obj->std;
2281 } /* }}} */
2282 
date_object_free_storage_date(zend_object * object)2283 static void date_object_free_storage_date(zend_object *object) /* {{{ */
2284 {
2285 	php_date_obj *intern = php_date_obj_from_obj(object);
2286 
2287 	if (intern->time) {
2288 		timelib_time_dtor(intern->time);
2289 	}
2290 
2291 	zend_object_std_dtor(&intern->std);
2292 } /* }}} */
2293 
date_object_free_storage_timezone(zend_object * object)2294 static void date_object_free_storage_timezone(zend_object *object) /* {{{ */
2295 {
2296 	php_timezone_obj *intern = php_timezone_obj_from_obj(object);
2297 
2298 	if (intern->type == TIMELIB_ZONETYPE_ABBR) {
2299 		timelib_free(intern->tzi.z.abbr);
2300 	}
2301 	zend_object_std_dtor(&intern->std);
2302 } /* }}} */
2303 
date_object_free_storage_interval(zend_object * object)2304 static void date_object_free_storage_interval(zend_object *object) /* {{{ */
2305 {
2306 	php_interval_obj *intern = php_interval_obj_from_obj(object);
2307 
2308 	if (intern->date_string) {
2309 		zend_string_release(intern->date_string);
2310 		intern->date_string = NULL;
2311 	}
2312 	timelib_rel_time_dtor(intern->diff);
2313 	zend_object_std_dtor(&intern->std);
2314 } /* }}} */
2315 
date_object_free_storage_period(zend_object * object)2316 static void date_object_free_storage_period(zend_object *object) /* {{{ */
2317 {
2318 	php_period_obj *intern = php_period_obj_from_obj(object);
2319 
2320 	if (intern->start) {
2321 		timelib_time_dtor(intern->start);
2322 	}
2323 
2324 	if (intern->current) {
2325 		timelib_time_dtor(intern->current);
2326 	}
2327 
2328 	if (intern->end) {
2329 		timelib_time_dtor(intern->end);
2330 	}
2331 
2332 	timelib_rel_time_dtor(intern->interval);
2333 	zend_object_std_dtor(&intern->std);
2334 } /* }}} */
2335 
add_common_properties(HashTable * myht,zend_object * zobj)2336 static void add_common_properties(HashTable *myht, zend_object *zobj)
2337 {
2338 	HashTable *common;
2339 	zend_string *name;
2340 	zval *prop;
2341 
2342 	common = zend_std_get_properties(zobj);
2343 
2344 	ZEND_HASH_MAP_FOREACH_STR_KEY_VAL_IND(common, name, prop) {
2345 		if (zend_hash_add(myht, name, prop) != NULL) {
2346 			Z_TRY_ADDREF_P(prop);
2347 		}
2348 	} ZEND_HASH_FOREACH_END();
2349 }
2350 
2351 /* Advanced Interface */
php_date_instantiate(zend_class_entry * pce,zval * object)2352 PHPAPI zval *php_date_instantiate(zend_class_entry *pce, zval *object) /* {{{ */
2353 {
2354 	object_init_ex(object, pce);
2355 	return object;
2356 } /* }}} */
2357 
2358 /* Helper function used to store the latest found warnings and errors while
2359  * parsing, from either strtotime or parse_from_format. */
update_errors_warnings(timelib_error_container ** last_errors)2360 static void update_errors_warnings(timelib_error_container **last_errors) /* {{{ */
2361 {
2362 	if (DATEG(last_errors)) {
2363 		timelib_error_container_dtor(DATEG(last_errors));
2364 		DATEG(last_errors) = NULL;
2365 	}
2366 
2367 	if (last_errors == NULL || (*last_errors) == NULL) {
2368 		return;
2369 	}
2370 
2371 	if ((*last_errors)->warning_count || (*last_errors)->error_count) {
2372 		DATEG(last_errors) = *last_errors;
2373 		return;
2374 	}
2375 
2376 	timelib_error_container_dtor(*last_errors);
2377 	*last_errors = NULL;
2378 } /* }}} */
2379 
php_date_set_time_fraction(timelib_time * time,int microseconds)2380 static void php_date_set_time_fraction(timelib_time *time, int microseconds)
2381 {
2382 	time->us = microseconds;
2383 }
2384 
php_date_get_current_time_with_fraction(time_t * sec,suseconds_t * usec)2385 static void php_date_get_current_time_with_fraction(time_t *sec, suseconds_t *usec)
2386 {
2387 #if HAVE_GETTIMEOFDAY
2388 	struct timeval tp = {0}; /* For setting microseconds */
2389 
2390 	gettimeofday(&tp, NULL);
2391 	*sec = tp.tv_sec;
2392 	*usec = tp.tv_usec;
2393 #else
2394 	*sec = time(NULL);
2395 	*usec = 0;
2396 #endif
2397 }
2398 
php_date_initialize(php_date_obj * dateobj,const char * time_str,size_t time_str_len,const char * format,zval * timezone_object,int flags)2399 PHPAPI bool php_date_initialize(php_date_obj *dateobj, const char *time_str, size_t time_str_len, const char *format, zval *timezone_object, int flags) /* {{{ */
2400 {
2401 	timelib_time   *now;
2402 	timelib_tzinfo *tzi = NULL;
2403 	timelib_error_container *err = NULL;
2404 	int type = TIMELIB_ZONETYPE_ID, new_dst = 0;
2405 	char *new_abbr = NULL;
2406 	timelib_sll new_offset = 0;
2407 	time_t sec;
2408 	suseconds_t usec;
2409 	int options = 0;
2410 
2411 	if (dateobj->time) {
2412 		timelib_time_dtor(dateobj->time);
2413 	}
2414 	if (format) {
2415 		if (time_str_len == 0) {
2416 			time_str = "";
2417 		}
2418 		dateobj->time = timelib_parse_from_format(format, time_str, time_str_len, &err, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
2419 	} else {
2420 		if (time_str_len == 0) {
2421 			time_str = "now";
2422 			time_str_len = sizeof("now") - 1;
2423 		}
2424 		dateobj->time = timelib_strtotime(time_str, time_str_len, &err, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
2425 	}
2426 
2427 	/* update last errors and warnings */
2428 	update_errors_warnings(&err);
2429 
2430 	/* If called from a constructor throw an exception */
2431 	if ((flags & PHP_DATE_INIT_CTOR) && err && err->error_count) {
2432 		/* spit out the first library error message, at least */
2433 		zend_throw_exception_ex(date_ce_date_malformed_string_exception, 0, "Failed to parse time string (%s) at position %d (%c): %s", time_str,
2434 			err->error_messages[0].position, err->error_messages[0].character ? err->error_messages[0].character : ' ', err->error_messages[0].message);
2435 	}
2436 	if (err && err->error_count) {
2437 		timelib_time_dtor(dateobj->time);
2438 		dateobj->time = 0;
2439 		return 0;
2440 	}
2441 
2442 	if (timezone_object) {
2443 		php_timezone_obj *tzobj;
2444 
2445 		tzobj = Z_PHPTIMEZONE_P(timezone_object);
2446 		switch (tzobj->type) {
2447 			case TIMELIB_ZONETYPE_ID:
2448 				tzi = tzobj->tzi.tz;
2449 				break;
2450 			case TIMELIB_ZONETYPE_OFFSET:
2451 				new_offset = tzobj->tzi.utc_offset;
2452 				break;
2453 			case TIMELIB_ZONETYPE_ABBR:
2454 				new_offset = tzobj->tzi.z.utc_offset;
2455 				new_dst    = tzobj->tzi.z.dst;
2456 				new_abbr   = timelib_strdup(tzobj->tzi.z.abbr);
2457 				break;
2458 		}
2459 		type = tzobj->type;
2460 	} else if (dateobj->time->tz_info) {
2461 		tzi = dateobj->time->tz_info;
2462 	} else {
2463 		tzi = get_timezone_info();
2464 		if (!tzi) {
2465 			return 0;
2466 		}
2467 	}
2468 
2469 	now = timelib_time_ctor();
2470 	now->zone_type = type;
2471 	switch (type) {
2472 		case TIMELIB_ZONETYPE_ID:
2473 			now->tz_info = tzi;
2474 			break;
2475 		case TIMELIB_ZONETYPE_OFFSET:
2476 			now->z = new_offset;
2477 			break;
2478 		case TIMELIB_ZONETYPE_ABBR:
2479 			now->z = new_offset;
2480 			now->dst = new_dst;
2481 			now->tz_abbr = new_abbr;
2482 			break;
2483 	}
2484 	php_date_get_current_time_with_fraction(&sec, &usec);
2485 	timelib_unixtime2local(now, (timelib_sll) sec);
2486 	php_date_set_time_fraction(now, usec);
2487 
2488 	if (!format
2489 	 && time_str_len == sizeof("now") - 1
2490 	 && memcmp(time_str, "now", sizeof("now") - 1) == 0) {
2491 		timelib_time_dtor(dateobj->time);
2492 		dateobj->time = now;
2493 		return 1;
2494 	}
2495 
2496 	options = TIMELIB_NO_CLONE;
2497 	if (flags & PHP_DATE_INIT_FORMAT) {
2498 		options |= TIMELIB_OVERRIDE_TIME;
2499 	}
2500 	timelib_fill_holes(dateobj->time, now, options);
2501 
2502 	timelib_update_ts(dateobj->time, tzi);
2503 	timelib_update_from_sse(dateobj->time);
2504 
2505 	dateobj->time->have_relative = 0;
2506 
2507 	timelib_time_dtor(now);
2508 
2509 	return 1;
2510 } /* }}} */
2511 
php_date_initialize_from_ts_long(php_date_obj * dateobj,zend_long sec,int usec)2512 PHPAPI void php_date_initialize_from_ts_long(php_date_obj *dateobj, zend_long sec, int usec) /* {{{ */
2513 {
2514 	dateobj->time = timelib_time_ctor();
2515 	dateobj->time->zone_type = TIMELIB_ZONETYPE_OFFSET;
2516 
2517 	timelib_unixtime2gmt(dateobj->time, (timelib_sll)sec);
2518 	timelib_update_ts(dateobj->time, NULL);
2519 	php_date_set_time_fraction(dateobj->time, usec);
2520 } /* }}} */
2521 
php_date_initialize_from_ts_double(php_date_obj * dateobj,double ts)2522 PHPAPI bool php_date_initialize_from_ts_double(php_date_obj *dateobj, double ts) /* {{{ */
2523 {
2524 	double sec_dval = trunc(ts);
2525 	zend_long sec;
2526 	int usec;
2527 
2528 	if (UNEXPECTED(isnan(sec_dval)
2529 		|| sec_dval >= (double)TIMELIB_LONG_MAX
2530 		|| sec_dval < (double)TIMELIB_LONG_MIN
2531 	)) {
2532 		zend_throw_error(
2533 			date_ce_date_range_error,
2534 			"Seconds must be a finite number between " TIMELIB_LONG_FMT " and " TIMELIB_LONG_FMT ", %g given",
2535 			TIMELIB_LONG_MIN,
2536 			TIMELIB_LONG_MAX,
2537 			sec_dval
2538 		);
2539 		return false;
2540 	}
2541 
2542 	sec = (zend_long)sec_dval;
2543 	usec = (int)(fmod(ts, 1) * 1000000);
2544 
2545 	if (UNEXPECTED(usec < 0)) {
2546 		sec = sec - 1;
2547 		usec = 1000000 + usec;
2548 	}
2549 
2550 	php_date_initialize_from_ts_long(dateobj, sec, usec);
2551 
2552 	return true;
2553 } /* }}} */
2554 
2555 /* {{{ Returns new DateTime object */
PHP_FUNCTION(date_create)2556 PHP_FUNCTION(date_create)
2557 {
2558 	zval           *timezone_object = NULL;
2559 	char           *time_str = NULL;
2560 	size_t          time_str_len = 0;
2561 
2562 	ZEND_PARSE_PARAMETERS_START(0, 2)
2563 		Z_PARAM_OPTIONAL
2564 		Z_PARAM_STRING(time_str, time_str_len)
2565 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2566 	ZEND_PARSE_PARAMETERS_END();
2567 
2568 	php_date_instantiate(date_ce_date, return_value);
2569 	if (!php_date_initialize(Z_PHPDATE_P(return_value), time_str, time_str_len, NULL, timezone_object, 0)) {
2570 		zval_ptr_dtor(return_value);
2571 		RETURN_FALSE;
2572 	}
2573 }
2574 /* }}} */
2575 
2576 /* {{{ Returns new DateTimeImmutable object */
PHP_FUNCTION(date_create_immutable)2577 PHP_FUNCTION(date_create_immutable)
2578 {
2579 	zval           *timezone_object = NULL;
2580 	char           *time_str = NULL;
2581 	size_t          time_str_len = 0;
2582 
2583 	ZEND_PARSE_PARAMETERS_START(0, 2)
2584 		Z_PARAM_OPTIONAL
2585 		Z_PARAM_STRING(time_str, time_str_len)
2586 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2587 	ZEND_PARSE_PARAMETERS_END();
2588 
2589 	php_date_instantiate(date_ce_immutable, return_value);
2590 	if (!php_date_initialize(Z_PHPDATE_P(return_value), time_str, time_str_len, NULL, timezone_object, 0)) {
2591 		zval_ptr_dtor(return_value);
2592 		RETURN_FALSE;
2593 	}
2594 }
2595 /* }}} */
2596 
2597 /* {{{ Returns new DateTime object formatted according to the specified format */
PHP_FUNCTION(date_create_from_format)2598 PHP_FUNCTION(date_create_from_format)
2599 {
2600 	zval           *timezone_object = NULL;
2601 	char           *time_str = NULL, *format_str = NULL;
2602 	size_t          time_str_len = 0, format_str_len = 0;
2603 
2604 	ZEND_PARSE_PARAMETERS_START(2, 3)
2605 		Z_PARAM_STRING(format_str, format_str_len)
2606 		Z_PARAM_PATH(time_str, time_str_len)
2607 		Z_PARAM_OPTIONAL
2608 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2609 	ZEND_PARSE_PARAMETERS_END();
2610 
2611 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_date, return_value);
2612 	if (!php_date_initialize(Z_PHPDATE_P(return_value), time_str, time_str_len, format_str, timezone_object, PHP_DATE_INIT_FORMAT)) {
2613 		zval_ptr_dtor(return_value);
2614 		RETURN_FALSE;
2615 	}
2616 }
2617 /* }}} */
2618 
2619 /* {{{ Returns new DateTimeImmutable object formatted according to the specified format */
PHP_FUNCTION(date_create_immutable_from_format)2620 PHP_FUNCTION(date_create_immutable_from_format)
2621 {
2622 	zval           *timezone_object = NULL;
2623 	char           *time_str = NULL, *format_str = NULL;
2624 	size_t          time_str_len = 0, format_str_len = 0;
2625 
2626 	ZEND_PARSE_PARAMETERS_START(2, 3)
2627 		Z_PARAM_STRING(format_str, format_str_len)
2628 		Z_PARAM_PATH(time_str, time_str_len)
2629 		Z_PARAM_OPTIONAL
2630 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2631 	ZEND_PARSE_PARAMETERS_END();
2632 
2633 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_immutable, return_value);
2634 	if (!php_date_initialize(Z_PHPDATE_P(return_value), time_str, time_str_len, format_str, timezone_object, PHP_DATE_INIT_FORMAT)) {
2635 		zval_ptr_dtor(return_value);
2636 		RETURN_FALSE;
2637 	}
2638 }
2639 /* }}} */
2640 
2641 /* {{{ Creates new DateTime object */
PHP_METHOD(DateTime,__construct)2642 PHP_METHOD(DateTime, __construct)
2643 {
2644 	zval *timezone_object = NULL;
2645 	char *time_str = NULL;
2646 	size_t time_str_len = 0;
2647 
2648 	ZEND_PARSE_PARAMETERS_START(0, 2)
2649 		Z_PARAM_OPTIONAL
2650 		Z_PARAM_STRING(time_str, time_str_len)
2651 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2652 	ZEND_PARSE_PARAMETERS_END();
2653 
2654 	php_date_initialize(Z_PHPDATE_P(ZEND_THIS), time_str, time_str_len, NULL, timezone_object, PHP_DATE_INIT_CTOR);
2655 }
2656 /* }}} */
2657 
2658 /* {{{ Creates new DateTimeImmutable object */
PHP_METHOD(DateTimeImmutable,__construct)2659 PHP_METHOD(DateTimeImmutable, __construct)
2660 {
2661 	zval *timezone_object = NULL;
2662 	char *time_str = NULL;
2663 	size_t time_str_len = 0;
2664 
2665 	ZEND_PARSE_PARAMETERS_START(0, 2)
2666 		Z_PARAM_OPTIONAL
2667 		Z_PARAM_STRING(time_str, time_str_len)
2668 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2669 	ZEND_PARSE_PARAMETERS_END();
2670 
2671 	php_date_initialize(Z_PHPDATE_P(ZEND_THIS), time_str, time_str_len, NULL, timezone_object, PHP_DATE_INIT_CTOR);
2672 }
2673 /* }}} */
2674 
2675 /* {{{ Creates new DateTime object from an existing immutable DateTimeImmutable object. */
PHP_METHOD(DateTime,createFromImmutable)2676 PHP_METHOD(DateTime, createFromImmutable)
2677 {
2678 	zval *datetimeimmutable_object = NULL;
2679 	php_date_obj *new_obj = NULL;
2680 	php_date_obj *old_obj = NULL;
2681 
2682 	ZEND_PARSE_PARAMETERS_START(1, 1)
2683 		Z_PARAM_OBJECT_OF_CLASS(datetimeimmutable_object, date_ce_immutable)
2684 	ZEND_PARSE_PARAMETERS_END();
2685 
2686 	old_obj = Z_PHPDATE_P(datetimeimmutable_object);
2687 	DATE_CHECK_INITIALIZED(old_obj->time, Z_OBJCE_P(datetimeimmutable_object));
2688 
2689 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_date, return_value);
2690 	new_obj = Z_PHPDATE_P(return_value);
2691 
2692 	new_obj->time = timelib_time_clone(old_obj->time);
2693 }
2694 /* }}} */
2695 
2696 /* {{{ Creates new DateTime object from an existing DateTimeInterface object. */
PHP_METHOD(DateTime,createFromInterface)2697 PHP_METHOD(DateTime, createFromInterface)
2698 {
2699 	zval *datetimeinterface_object = NULL;
2700 	php_date_obj *new_obj = NULL;
2701 	php_date_obj *old_obj = NULL;
2702 
2703 	ZEND_PARSE_PARAMETERS_START(1, 1)
2704 		Z_PARAM_OBJECT_OF_CLASS(datetimeinterface_object, date_ce_interface)
2705 	ZEND_PARSE_PARAMETERS_END();
2706 
2707 	old_obj = Z_PHPDATE_P(datetimeinterface_object);
2708 	DATE_CHECK_INITIALIZED(old_obj->time, Z_OBJCE_P(datetimeinterface_object));
2709 
2710 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_date, return_value);
2711 	new_obj = Z_PHPDATE_P(return_value);
2712 
2713 	new_obj->time = timelib_time_clone(old_obj->time);
2714 }
2715 /* }}} */
2716 
2717 /* {{{ Creates new DateTime object from given unix timetamp */
PHP_METHOD(DateTime,createFromTimestamp)2718 PHP_METHOD(DateTime, createFromTimestamp)
2719 {
2720 	zval         *value;
2721 	zval         new_object;
2722 	php_date_obj *new_dateobj;
2723 
2724 	ZEND_PARSE_PARAMETERS_START(1, 1)
2725 		Z_PARAM_NUMBER(value)
2726 	ZEND_PARSE_PARAMETERS_END();
2727 
2728 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_date, &new_object);
2729 	new_dateobj = Z_PHPDATE_P(&new_object);
2730 
2731 	switch (Z_TYPE_P(value)) {
2732 		case IS_LONG:
2733 			php_date_initialize_from_ts_long(new_dateobj, Z_LVAL_P(value), 0);
2734 			break;
2735 
2736 		case IS_DOUBLE:
2737 			if (!php_date_initialize_from_ts_double(new_dateobj, Z_DVAL_P(value))) {
2738 				zval_ptr_dtor(&new_object);
2739 				RETURN_THROWS();
2740 			}
2741 			break;
2742 
2743 		EMPTY_SWITCH_DEFAULT_CASE();
2744 	}
2745 
2746 	RETURN_OBJ(Z_OBJ(new_object));
2747 }
2748 /* }}} */
2749 
2750 /* {{{ Creates new DateTimeImmutable object from an existing mutable DateTime object. */
PHP_METHOD(DateTimeImmutable,createFromMutable)2751 PHP_METHOD(DateTimeImmutable, createFromMutable)
2752 {
2753 	zval *datetime_object = NULL;
2754 	php_date_obj *new_obj = NULL;
2755 	php_date_obj *old_obj = NULL;
2756 
2757 	ZEND_PARSE_PARAMETERS_START(1, 1)
2758 		Z_PARAM_OBJECT_OF_CLASS(datetime_object, date_ce_date)
2759 	ZEND_PARSE_PARAMETERS_END();
2760 
2761 	old_obj = Z_PHPDATE_P(datetime_object);
2762 	DATE_CHECK_INITIALIZED(old_obj->time, Z_OBJCE_P(datetime_object));
2763 
2764 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_immutable, return_value);
2765 	new_obj = Z_PHPDATE_P(return_value);
2766 
2767 	new_obj->time = timelib_time_clone(old_obj->time);
2768 }
2769 /* }}} */
2770 
2771 /* {{{ Creates new DateTimeImmutable object from an existing DateTimeInterface object. */
PHP_METHOD(DateTimeImmutable,createFromInterface)2772 PHP_METHOD(DateTimeImmutable, createFromInterface)
2773 {
2774 	zval *datetimeinterface_object = NULL;
2775 	php_date_obj *new_obj = NULL;
2776 	php_date_obj *old_obj = NULL;
2777 
2778 	ZEND_PARSE_PARAMETERS_START(1, 1)
2779 		Z_PARAM_OBJECT_OF_CLASS(datetimeinterface_object, date_ce_interface)
2780 	ZEND_PARSE_PARAMETERS_END();
2781 
2782 	old_obj = Z_PHPDATE_P(datetimeinterface_object);
2783 	DATE_CHECK_INITIALIZED(old_obj->time, Z_OBJCE_P(datetimeinterface_object));
2784 
2785 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_immutable, return_value);
2786 	new_obj = Z_PHPDATE_P(return_value);
2787 
2788 	new_obj->time = timelib_time_clone(old_obj->time);
2789 }
2790 /* }}} */
2791 
2792 /* {{{ Creates new DateTimeImmutable object from given unix timestamp */
PHP_METHOD(DateTimeImmutable,createFromTimestamp)2793 PHP_METHOD(DateTimeImmutable, createFromTimestamp)
2794 {
2795 	zval         *value;
2796 	zval         new_object;
2797 	php_date_obj *new_dateobj;
2798 
2799 	ZEND_PARSE_PARAMETERS_START(1, 1)
2800 		Z_PARAM_NUMBER(value)
2801 	ZEND_PARSE_PARAMETERS_END();
2802 
2803 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_immutable, &new_object);
2804 	new_dateobj = Z_PHPDATE_P(&new_object);
2805 
2806 	switch (Z_TYPE_P(value)) {
2807 		case IS_LONG:
2808 			php_date_initialize_from_ts_long(new_dateobj, Z_LVAL_P(value), 0);
2809 			break;
2810 
2811 		case IS_DOUBLE:
2812 			if (!php_date_initialize_from_ts_double(new_dateobj, Z_DVAL_P(value))) {
2813 				zval_ptr_dtor(&new_object);
2814 				RETURN_THROWS();
2815 			}
2816 			break;
2817 
2818 		EMPTY_SWITCH_DEFAULT_CASE();
2819 	}
2820 
2821 	RETURN_OBJ(Z_OBJ(new_object));
2822 }
2823 /* }}} */
2824 
php_date_initialize_from_hash(php_date_obj ** dateobj,HashTable * myht)2825 static bool php_date_initialize_from_hash(php_date_obj **dateobj, HashTable *myht)
2826 {
2827 	zval             *z_date;
2828 	zval             *z_timezone_type;
2829 	zval             *z_timezone;
2830 	zval              tmp_obj;
2831 	timelib_tzinfo   *tzi;
2832 
2833 	z_date = zend_hash_str_find(myht, "date", sizeof("date")-1);
2834 	if (!z_date || Z_TYPE_P(z_date) != IS_STRING) {
2835 		return false;
2836 	}
2837 
2838 	z_timezone_type = zend_hash_str_find(myht, "timezone_type", sizeof("timezone_type")-1);
2839 	if (!z_timezone_type || Z_TYPE_P(z_timezone_type) != IS_LONG) {
2840 		return false;
2841 	}
2842 
2843 	z_timezone = zend_hash_str_find(myht, "timezone", sizeof("timezone")-1);
2844 	if (!z_timezone || Z_TYPE_P(z_timezone) != IS_STRING) {
2845 		return false;
2846 	}
2847 
2848 	switch (Z_LVAL_P(z_timezone_type)) {
2849 		case TIMELIB_ZONETYPE_OFFSET:
2850 		case TIMELIB_ZONETYPE_ABBR: {
2851 			zend_string *tmp = zend_string_concat3(
2852 				Z_STRVAL_P(z_date), Z_STRLEN_P(z_date), " ", 1,
2853 				Z_STRVAL_P(z_timezone), Z_STRLEN_P(z_timezone));
2854 			bool ret = php_date_initialize(*dateobj, ZSTR_VAL(tmp), ZSTR_LEN(tmp), NULL, NULL, 0);
2855 			zend_string_release(tmp);
2856 			return ret;
2857 		}
2858 
2859 		case TIMELIB_ZONETYPE_ID: {
2860 			bool ret;
2861 			php_timezone_obj *tzobj;
2862 
2863 			tzi = php_date_parse_tzfile(Z_STRVAL_P(z_timezone), DATE_TIMEZONEDB);
2864 
2865 			if (tzi == NULL) {
2866 				return false;
2867 			}
2868 
2869 			tzobj = Z_PHPTIMEZONE_P(php_date_instantiate(date_ce_timezone, &tmp_obj));
2870 			tzobj->type = TIMELIB_ZONETYPE_ID;
2871 			tzobj->tzi.tz = tzi;
2872 			tzobj->initialized = 1;
2873 
2874 			ret = php_date_initialize(*dateobj, Z_STRVAL_P(z_date), Z_STRLEN_P(z_date), NULL, &tmp_obj, 0);
2875 			zval_ptr_dtor(&tmp_obj);
2876 			return ret;
2877 		}
2878 	}
2879 	return false;
2880 } /* }}} */
2881 
2882 /* {{{ */
PHP_METHOD(DateTime,__set_state)2883 PHP_METHOD(DateTime, __set_state)
2884 {
2885 	php_date_obj     *dateobj;
2886 	zval             *array;
2887 	HashTable        *myht;
2888 
2889 	ZEND_PARSE_PARAMETERS_START(1, 1)
2890 		Z_PARAM_ARRAY(array)
2891 	ZEND_PARSE_PARAMETERS_END();
2892 
2893 	myht = Z_ARRVAL_P(array);
2894 
2895 	php_date_instantiate(date_ce_date, return_value);
2896 	dateobj = Z_PHPDATE_P(return_value);
2897 	if (!php_date_initialize_from_hash(&dateobj, myht)) {
2898 		zend_throw_error(NULL, "Invalid serialization data for DateTime object");
2899 		RETURN_THROWS();
2900 	}
2901 }
2902 /* }}} */
2903 
2904 /* {{{ */
PHP_METHOD(DateTimeImmutable,__set_state)2905 PHP_METHOD(DateTimeImmutable, __set_state)
2906 {
2907 	php_date_obj     *dateobj;
2908 	zval             *array;
2909 	HashTable        *myht;
2910 
2911 	ZEND_PARSE_PARAMETERS_START(1, 1)
2912 		Z_PARAM_ARRAY(array)
2913 	ZEND_PARSE_PARAMETERS_END();
2914 
2915 	myht = Z_ARRVAL_P(array);
2916 
2917 	php_date_instantiate(date_ce_immutable, return_value);
2918 	dateobj = Z_PHPDATE_P(return_value);
2919 	if (!php_date_initialize_from_hash(&dateobj, myht)) {
2920 		zend_throw_error(NULL, "Invalid serialization data for DateTimeImmutable object");
2921 		RETURN_THROWS();
2922 	}
2923 }
2924 /* }}} */
2925 
2926 /* {{{ */
PHP_METHOD(DateTime,__serialize)2927 PHP_METHOD(DateTime, __serialize)
2928 {
2929 	zval             *object = ZEND_THIS;
2930 	php_date_obj     *dateobj;
2931 	HashTable        *myht;
2932 
2933 	ZEND_PARSE_PARAMETERS_NONE();
2934 
2935 	dateobj = Z_PHPDATE_P(object);
2936 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
2937 
2938 	array_init(return_value);
2939 	myht = Z_ARRVAL_P(return_value);
2940 	date_object_to_hash(dateobj, myht);
2941 
2942 	add_common_properties(myht, &dateobj->std);
2943 }
2944 /* }}} */
2945 
2946 /* {{{ */
PHP_METHOD(DateTimeImmutable,__serialize)2947 PHP_METHOD(DateTimeImmutable, __serialize)
2948 {
2949 	zval             *object = ZEND_THIS;
2950 	php_date_obj     *dateobj;
2951 	HashTable        *myht;
2952 
2953 	ZEND_PARSE_PARAMETERS_NONE();
2954 
2955 	dateobj = Z_PHPDATE_P(object);
2956 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
2957 
2958 	array_init(return_value);
2959 	myht = Z_ARRVAL_P(return_value);
2960 	date_object_to_hash(dateobj, myht);
2961 
2962 	add_common_properties(myht, &dateobj->std);
2963 }
2964 /* }}} */
2965 
date_time_is_internal_property(zend_string * name)2966 static bool date_time_is_internal_property(zend_string *name)
2967 {
2968 	if (
2969 		zend_string_equals_literal(name, "date") ||
2970 		zend_string_equals_literal(name, "timezone_type") ||
2971 		zend_string_equals_literal(name, "timezone")
2972 	) {
2973 		return 1;
2974 	}
2975 	return 0;
2976 }
2977 
restore_custom_datetime_properties(zval * object,HashTable * myht)2978 static void restore_custom_datetime_properties(zval *object, HashTable *myht)
2979 {
2980 	zend_string      *prop_name;
2981 	zval             *prop_val;
2982 
2983 	ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(myht, prop_name, prop_val) {
2984 		if (!prop_name || (Z_TYPE_P(prop_val) == IS_REFERENCE) || date_time_is_internal_property(prop_name)) {
2985 			continue;
2986 		}
2987 		update_property(Z_OBJ_P(object), prop_name, prop_val);
2988 	} ZEND_HASH_FOREACH_END();
2989 }
2990 
2991 /* {{{ */
PHP_METHOD(DateTime,__unserialize)2992 PHP_METHOD(DateTime, __unserialize)
2993 {
2994 	zval             *object = ZEND_THIS;
2995 	php_date_obj     *dateobj;
2996 	zval             *array;
2997 	HashTable        *myht;
2998 
2999 	ZEND_PARSE_PARAMETERS_START(1, 1)
3000 		Z_PARAM_ARRAY(array)
3001 	ZEND_PARSE_PARAMETERS_END();
3002 
3003 	dateobj = Z_PHPDATE_P(object);
3004 	myht = Z_ARRVAL_P(array);
3005 
3006 	if (!php_date_initialize_from_hash(&dateobj, myht)) {
3007 		zend_throw_error(NULL, "Invalid serialization data for DateTime object");
3008 		RETURN_THROWS();
3009 	}
3010 
3011 	restore_custom_datetime_properties(object, myht);
3012 }
3013 /* }}} */
3014 
3015 /* {{{ */
PHP_METHOD(DateTimeImmutable,__unserialize)3016 PHP_METHOD(DateTimeImmutable, __unserialize)
3017 {
3018 	zval             *object = ZEND_THIS;
3019 	php_date_obj     *dateobj;
3020 	zval             *array;
3021 	HashTable        *myht;
3022 
3023 	ZEND_PARSE_PARAMETERS_START(1, 1)
3024 		Z_PARAM_ARRAY(array)
3025 	ZEND_PARSE_PARAMETERS_END();
3026 
3027 	dateobj = Z_PHPDATE_P(object);
3028 	myht = Z_ARRVAL_P(array);
3029 
3030 	if (!php_date_initialize_from_hash(&dateobj, myht)) {
3031 		zend_throw_error(NULL, "Invalid serialization data for DateTimeImmutable object");
3032 		RETURN_THROWS();
3033 	}
3034 
3035 	restore_custom_datetime_properties(object, myht);
3036 }
3037 /* }}} */
3038 
3039 /* {{{ */
PHP_METHOD(DateTime,__wakeup)3040 PHP_METHOD(DateTime, __wakeup)
3041 {
3042 	zval             *object = ZEND_THIS;
3043 	php_date_obj     *dateobj;
3044 	HashTable        *myht;
3045 
3046 	ZEND_PARSE_PARAMETERS_NONE();
3047 
3048 	dateobj = Z_PHPDATE_P(object);
3049 
3050 	myht = Z_OBJPROP_P(object);
3051 
3052 	if (!php_date_initialize_from_hash(&dateobj, myht)) {
3053 		zend_throw_error(NULL, "Invalid serialization data for DateTime object");
3054 	}
3055 }
3056 /* }}} */
3057 
3058 /* {{{ */
PHP_METHOD(DateTimeImmutable,__wakeup)3059 PHP_METHOD(DateTimeImmutable, __wakeup)
3060 {
3061 	zval             *object = ZEND_THIS;
3062 	php_date_obj     *dateobj;
3063 	HashTable        *myht;
3064 
3065 	ZEND_PARSE_PARAMETERS_NONE();
3066 
3067 	dateobj = Z_PHPDATE_P(object);
3068 
3069 	myht = Z_OBJPROP_P(object);
3070 
3071 	if (!php_date_initialize_from_hash(&dateobj, myht)) {
3072 		zend_throw_error(NULL, "Invalid serialization data for DateTimeImmutable object");
3073 	}
3074 }
3075 /* }}} */
3076 
3077 /* Helper function used to add an associative array of warnings and errors to a zval */
zval_from_error_container(zval * z,timelib_error_container * error)3078 static void zval_from_error_container(zval *z, timelib_error_container *error) /* {{{ */
3079 {
3080 	int   i;
3081 	zval element;
3082 
3083 	add_assoc_long(z, "warning_count", error->warning_count);
3084 	array_init(&element);
3085 	for (i = 0; i < error->warning_count; i++) {
3086 		add_index_string(&element, error->warning_messages[i].position, error->warning_messages[i].message);
3087 	}
3088 	add_assoc_zval(z, "warnings", &element);
3089 
3090 	add_assoc_long(z, "error_count", error->error_count);
3091 	array_init(&element);
3092 	for (i = 0; i < error->error_count; i++) {
3093 		add_index_string(&element, error->error_messages[i].position, error->error_messages[i].message);
3094 	}
3095 	add_assoc_zval(z, "errors", &element);
3096 } /* }}} */
3097 
3098 /* {{{ Returns the warnings and errors found while parsing a date/time string. */
PHP_FUNCTION(date_get_last_errors)3099 PHP_FUNCTION(date_get_last_errors)
3100 {
3101 	ZEND_PARSE_PARAMETERS_NONE();
3102 
3103 	if (DATEG(last_errors)) {
3104 		array_init(return_value);
3105 		zval_from_error_container(return_value, DATEG(last_errors));
3106 	} else {
3107 		RETURN_FALSE;
3108 	}
3109 }
3110 /* }}} */
3111 
php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAMETERS,timelib_time * parsed_time,timelib_error_container * error)3112 static void php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAMETERS, timelib_time *parsed_time, timelib_error_container *error) /* {{{ */
3113 {
3114 	zval element;
3115 
3116 	array_init(return_value);
3117 #define PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(name, elem) \
3118 	if (parsed_time->elem == TIMELIB_UNSET) {               \
3119 		add_assoc_bool(return_value, #name, 0); \
3120 	} else {                                       \
3121 		add_assoc_long(return_value, #name, parsed_time->elem); \
3122 	}
3123 	PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(year,      y);
3124 	PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(month,     m);
3125 	PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(day,       d);
3126 	PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(hour,      h);
3127 	PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(minute,    i);
3128 	PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(second,    s);
3129 
3130 	if (parsed_time->us == TIMELIB_UNSET) {
3131 		add_assoc_bool(return_value, "fraction", 0);
3132 	} else {
3133 		add_assoc_double(return_value, "fraction", (double)parsed_time->us / 1000000.0);
3134 	}
3135 
3136 	zval_from_error_container(return_value, error);
3137 
3138 	timelib_error_container_dtor(error);
3139 
3140 	add_assoc_bool(return_value, "is_localtime", parsed_time->is_localtime);
3141 
3142 	if (parsed_time->is_localtime) {
3143 		PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone_type, zone_type);
3144 		switch (parsed_time->zone_type) {
3145 			case TIMELIB_ZONETYPE_OFFSET:
3146 				PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z);
3147 				add_assoc_bool(return_value, "is_dst", parsed_time->dst);
3148 				break;
3149 			case TIMELIB_ZONETYPE_ID:
3150 				if (parsed_time->tz_abbr) {
3151 					add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr);
3152 				}
3153 				if (parsed_time->tz_info) {
3154 					add_assoc_string(return_value, "tz_id", parsed_time->tz_info->name);
3155 				}
3156 				break;
3157 			case TIMELIB_ZONETYPE_ABBR:
3158 				PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z);
3159 				add_assoc_bool(return_value, "is_dst", parsed_time->dst);
3160 				add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr);
3161 				break;
3162 		}
3163 	}
3164 	if (parsed_time->have_relative) {
3165 		array_init(&element);
3166 		add_assoc_long(&element, "year",   parsed_time->relative.y);
3167 		add_assoc_long(&element, "month",  parsed_time->relative.m);
3168 		add_assoc_long(&element, "day",    parsed_time->relative.d);
3169 		add_assoc_long(&element, "hour",   parsed_time->relative.h);
3170 		add_assoc_long(&element, "minute", parsed_time->relative.i);
3171 		add_assoc_long(&element, "second", parsed_time->relative.s);
3172 		if (parsed_time->relative.have_weekday_relative) {
3173 			add_assoc_long(&element, "weekday", parsed_time->relative.weekday);
3174 		}
3175 		if (parsed_time->relative.have_special_relative && (parsed_time->relative.special.type == TIMELIB_SPECIAL_WEEKDAY)) {
3176 			add_assoc_long(&element, "weekdays", parsed_time->relative.special.amount);
3177 		}
3178 		if (parsed_time->relative.first_last_day_of) {
3179 			add_assoc_bool(&element, parsed_time->relative.first_last_day_of == TIMELIB_SPECIAL_FIRST_DAY_OF_MONTH ? "first_day_of_month" : "last_day_of_month", 1);
3180 		}
3181 		add_assoc_zval(return_value, "relative", &element);
3182 	}
3183 	timelib_time_dtor(parsed_time);
3184 } /* }}} */
3185 
3186 /* {{{ Returns associative array with detailed info about given date */
PHP_FUNCTION(date_parse)3187 PHP_FUNCTION(date_parse)
3188 {
3189 	zend_string                    *date;
3190 	timelib_error_container *error;
3191 	timelib_time                   *parsed_time;
3192 
3193 	ZEND_PARSE_PARAMETERS_START(1, 1)
3194 		Z_PARAM_STR(date)
3195 	ZEND_PARSE_PARAMETERS_END();
3196 
3197 	parsed_time = timelib_strtotime(ZSTR_VAL(date), ZSTR_LEN(date), &error, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
3198 	php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error);
3199 }
3200 /* }}} */
3201 
3202 /* {{{ Returns associative array with detailed info about given date */
PHP_FUNCTION(date_parse_from_format)3203 PHP_FUNCTION(date_parse_from_format)
3204 {
3205 	zend_string                    *date, *format;
3206 	timelib_error_container *error;
3207 	timelib_time                   *parsed_time;
3208 
3209 	ZEND_PARSE_PARAMETERS_START(2, 2)
3210 		Z_PARAM_STR(format)
3211 		Z_PARAM_PATH_STR(date)
3212 	ZEND_PARSE_PARAMETERS_END();
3213 
3214 	parsed_time = timelib_parse_from_format(ZSTR_VAL(format), ZSTR_VAL(date), ZSTR_LEN(date), &error, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
3215 	php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error);
3216 }
3217 /* }}} */
3218 
3219 /* {{{ Returns date formatted according to given format */
PHP_FUNCTION(date_format)3220 PHP_FUNCTION(date_format)
3221 {
3222 	zval         *object;
3223 	php_date_obj *dateobj;
3224 	char         *format;
3225 	size_t       format_len;
3226 
3227 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Os", &object, date_ce_interface, &format, &format_len) == FAILURE) {
3228 		RETURN_THROWS();
3229 	}
3230 	dateobj = Z_PHPDATE_P(object);
3231 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3232 	RETURN_STR(date_format(format, format_len, dateobj->time, dateobj->time->is_localtime));
3233 }
3234 /* }}} */
3235 
php_date_modify(zval * object,char * modify,size_t modify_len)3236 static bool php_date_modify(zval *object, char *modify, size_t modify_len) /* {{{ */
3237 {
3238 	php_date_obj *dateobj;
3239 	timelib_time *tmp_time;
3240 	timelib_error_container *err = NULL;
3241 
3242 	dateobj = Z_PHPDATE_P(object);
3243 
3244 	if (!(dateobj->time)) {
3245 		date_throw_uninitialized_error(Z_OBJCE_P(object));
3246 		return 0;
3247 	}
3248 
3249 	tmp_time = timelib_strtotime(modify, modify_len, &err, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
3250 
3251 	/* update last errors and warnings */
3252 	update_errors_warnings(&err);
3253 
3254 	if (err && err->error_count) {
3255 		/* spit out the first library error message, at least */
3256 		php_error_docref(NULL, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", modify,
3257 			err->error_messages[0].position,
3258 			err->error_messages[0].character ? err->error_messages[0].character : ' ',
3259 			err->error_messages[0].message);
3260 		timelib_time_dtor(tmp_time);
3261 		return 0;
3262 	}
3263 
3264 	memcpy(&dateobj->time->relative, &tmp_time->relative, sizeof(timelib_rel_time));
3265 	dateobj->time->have_relative = tmp_time->have_relative;
3266 	dateobj->time->sse_uptodate = 0;
3267 
3268 	if (tmp_time->y != TIMELIB_UNSET) {
3269 		dateobj->time->y = tmp_time->y;
3270 	}
3271 	if (tmp_time->m != TIMELIB_UNSET) {
3272 		dateobj->time->m = tmp_time->m;
3273 	}
3274 	if (tmp_time->d != TIMELIB_UNSET) {
3275 		dateobj->time->d = tmp_time->d;
3276 	}
3277 
3278 	if (tmp_time->h != TIMELIB_UNSET) {
3279 		dateobj->time->h = tmp_time->h;
3280 		if (tmp_time->i != TIMELIB_UNSET) {
3281 			dateobj->time->i = tmp_time->i;
3282 			if (tmp_time->s != TIMELIB_UNSET) {
3283 				dateobj->time->s = tmp_time->s;
3284 			} else {
3285 				dateobj->time->s = 0;
3286 			}
3287 		} else {
3288 			dateobj->time->i = 0;
3289 			dateobj->time->s = 0;
3290 		}
3291 	}
3292 
3293 	if (tmp_time->us != TIMELIB_UNSET) {
3294 		dateobj->time->us = tmp_time->us;
3295 	}
3296 
3297 	/* Reset timezone to UTC if we detect a "@<ts>" modification */
3298 	if (
3299 		tmp_time->y == 1970 && tmp_time->m == 1 && tmp_time->d == 1 &&
3300 		tmp_time->h == 0 && tmp_time->i == 0 && tmp_time->s == 0 && tmp_time->us == 0 &&
3301 		tmp_time->have_zone && tmp_time->zone_type == TIMELIB_ZONETYPE_OFFSET &&
3302 		tmp_time->z == 0 && tmp_time->dst == 0
3303 	) {
3304 		timelib_set_timezone_from_offset(dateobj->time, 0);
3305 	}
3306 
3307 	timelib_time_dtor(tmp_time);
3308 
3309 	timelib_update_ts(dateobj->time, NULL);
3310 	timelib_update_from_sse(dateobj->time);
3311 	dateobj->time->have_relative = 0;
3312 	memset(&dateobj->time->relative, 0, sizeof(dateobj->time->relative));
3313 
3314 	return 1;
3315 } /* }}} */
3316 
3317 /* {{{ Alters the timestamp. */
PHP_FUNCTION(date_modify)3318 PHP_FUNCTION(date_modify)
3319 {
3320 	zval         *object;
3321 	char         *modify;
3322 	size_t        modify_len;
3323 
3324 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Os", &object, date_ce_date, &modify, &modify_len) == FAILURE) {
3325 		RETURN_THROWS();
3326 	}
3327 
3328 	if (!php_date_modify(object, modify, modify_len)) {
3329 		RETURN_FALSE;
3330 	}
3331 
3332 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3333 }
3334 /* }}} */
3335 
3336 /* {{{ */
PHP_METHOD(DateTime,modify)3337 PHP_METHOD(DateTime, modify)
3338 {
3339 	zval                *object;
3340 	char                *modify;
3341 	size_t               modify_len;
3342 	zend_error_handling  zeh;
3343 
3344 	object = ZEND_THIS;
3345 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &modify, &modify_len) == FAILURE) {
3346 		RETURN_THROWS();
3347 	}
3348 
3349 	zend_replace_error_handling(EH_THROW, date_ce_date_malformed_string_exception, &zeh);
3350 	if (!php_date_modify(object, modify, modify_len)) {
3351 		zend_restore_error_handling(&zeh);
3352 		RETURN_THROWS();
3353 	}
3354 
3355 	zend_restore_error_handling(&zeh);
3356 
3357 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3358 }
3359 /* }}} */
3360 
3361 /* {{{ */
PHP_METHOD(DateTimeImmutable,modify)3362 PHP_METHOD(DateTimeImmutable, modify)
3363 {
3364 	zval *object, new_object;
3365 	char *modify;
3366 	size_t   modify_len;
3367 	zend_error_handling zeh;
3368 
3369 	object = ZEND_THIS;
3370 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &modify, &modify_len) == FAILURE) {
3371 		RETURN_THROWS();
3372 	}
3373 
3374 	date_clone_immutable(object, &new_object);
3375 
3376 	zend_replace_error_handling(EH_THROW, date_ce_date_malformed_string_exception, &zeh);
3377 	if (!php_date_modify(&new_object, modify, modify_len)) {
3378 		zval_ptr_dtor(&new_object);
3379 		zend_restore_error_handling(&zeh);
3380 		RETURN_THROWS();
3381 	}
3382 
3383 	zend_restore_error_handling(&zeh);
3384 
3385 	RETURN_OBJ(Z_OBJ(new_object));
3386 }
3387 /* }}} */
3388 
php_date_add(zval * object,zval * interval,zval * return_value)3389 static void php_date_add(zval *object, zval *interval, zval *return_value) /* {{{ */
3390 {
3391 	php_date_obj     *dateobj;
3392 	php_interval_obj *intobj;
3393 	timelib_time     *new_time;
3394 
3395 	dateobj = Z_PHPDATE_P(object);
3396 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3397 	intobj = Z_PHPINTERVAL_P(interval);
3398 	DATE_CHECK_INITIALIZED(intobj->initialized, Z_OBJCE_P(interval));
3399 
3400 	if (intobj->civil_or_wall == PHP_DATE_WALL) {
3401 		new_time = timelib_add_wall(dateobj->time, intobj->diff);
3402 	} else {
3403 		new_time = timelib_add(dateobj->time, intobj->diff);
3404 	}
3405 	timelib_time_dtor(dateobj->time);
3406 	dateobj->time = new_time;
3407 } /* }}} */
3408 
3409 /* {{{ Adds an interval to the current date in object. */
PHP_FUNCTION(date_add)3410 PHP_FUNCTION(date_add)
3411 {
3412 	zval *object, *interval;
3413 
3414 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) {
3415 		RETURN_THROWS();
3416 	}
3417 
3418 	php_date_add(object, interval, return_value);
3419 
3420 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3421 }
3422 /* }}} */
3423 
3424 /* {{{ */
PHP_METHOD(DateTimeImmutable,add)3425 PHP_METHOD(DateTimeImmutable, add)
3426 {
3427 	zval *object, *interval, new_object;
3428 
3429 	object = ZEND_THIS;
3430 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &interval, date_ce_interval) == FAILURE) {
3431 		RETURN_THROWS();
3432 	}
3433 
3434 	date_clone_immutable(object, &new_object);
3435 	php_date_add(&new_object, interval, return_value);
3436 
3437 	RETURN_OBJ(Z_OBJ(new_object));
3438 }
3439 /* }}} */
3440 
php_date_sub(zval * object,zval * interval,zval * return_value)3441 static void php_date_sub(zval *object, zval *interval, zval *return_value) /* {{{ */
3442 {
3443 	php_date_obj     *dateobj;
3444 	php_interval_obj *intobj;
3445 	timelib_time     *new_time;
3446 
3447 	dateobj = Z_PHPDATE_P(object);
3448 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3449 	intobj = Z_PHPINTERVAL_P(interval);
3450 	DATE_CHECK_INITIALIZED(intobj->initialized, Z_OBJCE_P(interval));
3451 
3452 	if (intobj->diff->have_weekday_relative || intobj->diff->have_special_relative) {
3453 		php_error_docref(NULL, E_WARNING, "Only non-special relative time specifications are supported for subtraction");
3454 		return;
3455 	}
3456 
3457 	if (intobj->civil_or_wall == PHP_DATE_WALL) {
3458 		new_time = timelib_sub_wall(dateobj->time, intobj->diff);
3459 	} else {
3460 		new_time = timelib_sub(dateobj->time, intobj->diff);
3461 	}
3462 	timelib_time_dtor(dateobj->time);
3463 	dateobj->time = new_time;
3464 } /* }}} */
3465 
3466 /* {{{ Subtracts an interval to the current date in object. */
PHP_FUNCTION(date_sub)3467 PHP_FUNCTION(date_sub)
3468 {
3469 	zval *object, *interval;
3470 
3471 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) {
3472 		RETURN_THROWS();
3473 	}
3474 
3475 	php_date_sub(object, interval, return_value);
3476 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3477 }
3478 /* }}} */
3479 
3480 /* {{{ Subtracts an interval to the current date in object. */
PHP_METHOD(DateTime,sub)3481 PHP_METHOD(DateTime, sub)
3482 {
3483 	zval *object, *interval;
3484 	zend_error_handling zeh;
3485 
3486 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) {
3487 		RETURN_THROWS();
3488 	}
3489 
3490 	zend_replace_error_handling(EH_THROW, date_ce_date_invalid_operation_exception, &zeh);
3491 	php_date_sub(object, interval, return_value);
3492 	zend_restore_error_handling(&zeh);
3493 
3494 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3495 }
3496 /* }}} */
3497 
3498 /* {{{ */
PHP_METHOD(DateTimeImmutable,sub)3499 PHP_METHOD(DateTimeImmutable, sub)
3500 {
3501 	zval *object, *interval, new_object;
3502 	zend_error_handling zeh;
3503 
3504 	object = ZEND_THIS;
3505 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &interval, date_ce_interval) == FAILURE) {
3506 		RETURN_THROWS();
3507 	}
3508 
3509 	date_clone_immutable(object, &new_object);
3510 
3511 	zend_replace_error_handling(EH_THROW, date_ce_date_invalid_operation_exception, &zeh);
3512 	php_date_sub(&new_object, interval, return_value);
3513 	zend_restore_error_handling(&zeh);
3514 
3515 	RETURN_OBJ(Z_OBJ(new_object));
3516 }
3517 /* }}} */
3518 
set_timezone_from_timelib_time(php_timezone_obj * tzobj,timelib_time * t)3519 static void set_timezone_from_timelib_time(php_timezone_obj *tzobj, timelib_time *t)
3520 {
3521 	/* Free abbreviation if already set */
3522 	if (tzobj->initialized && tzobj->type == TIMELIB_ZONETYPE_ABBR) {
3523 		timelib_free(tzobj->tzi.z.abbr);
3524 	}
3525 
3526 	/* Set new values */
3527 	tzobj->initialized = 1;
3528 	tzobj->type = t->zone_type;
3529 
3530 	switch (t->zone_type) {
3531 		case TIMELIB_ZONETYPE_ID:
3532 			tzobj->tzi.tz = t->tz_info;
3533 			break;
3534 		case TIMELIB_ZONETYPE_OFFSET:
3535 			tzobj->tzi.utc_offset = t->z;
3536 			break;
3537 		case TIMELIB_ZONETYPE_ABBR:
3538 			tzobj->tzi.z.utc_offset = t->z;
3539 			tzobj->tzi.z.dst = t->dst;
3540 			tzobj->tzi.z.abbr = timelib_strdup(t->tz_abbr);
3541 			break;
3542 	}
3543 }
3544 
3545 
3546 /* {{{ Return new DateTimeZone object relative to give DateTime */
PHP_FUNCTION(date_timezone_get)3547 PHP_FUNCTION(date_timezone_get)
3548 {
3549 	zval             *object;
3550 	php_date_obj     *dateobj;
3551 
3552 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &object, date_ce_interface) == FAILURE) {
3553 		RETURN_THROWS();
3554 	}
3555 	dateobj = Z_PHPDATE_P(object);
3556 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3557 	if (dateobj->time->is_localtime) {
3558 		php_timezone_obj *tzobj;
3559 		php_date_instantiate(date_ce_timezone, return_value);
3560 		tzobj = Z_PHPTIMEZONE_P(return_value);
3561 		set_timezone_from_timelib_time(tzobj, dateobj->time);
3562 	} else {
3563 		RETURN_FALSE;
3564 	}
3565 }
3566 /* }}} */
3567 
php_date_timezone_set(zval * object,zval * timezone_object,zval * return_value)3568 static void php_date_timezone_set(zval *object, zval *timezone_object, zval *return_value) /* {{{ */
3569 {
3570 	php_date_obj     *dateobj;
3571 	php_timezone_obj *tzobj;
3572 
3573 	dateobj = Z_PHPDATE_P(object);
3574 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3575 	tzobj = Z_PHPTIMEZONE_P(timezone_object);
3576 
3577 	switch (tzobj->type) {
3578 		case TIMELIB_ZONETYPE_OFFSET:
3579 			timelib_set_timezone_from_offset(dateobj->time, tzobj->tzi.utc_offset);
3580 			break;
3581 		case TIMELIB_ZONETYPE_ABBR:
3582 			timelib_set_timezone_from_abbr(dateobj->time, tzobj->tzi.z);
3583 			break;
3584 		case TIMELIB_ZONETYPE_ID:
3585 			timelib_set_timezone(dateobj->time, tzobj->tzi.tz);
3586 			break;
3587 	}
3588 	timelib_unixtime2local(dateobj->time, dateobj->time->sse);
3589 } /* }}} */
3590 
3591 /* {{{ Sets the timezone for the DateTime object. */
PHP_FUNCTION(date_timezone_set)3592 PHP_FUNCTION(date_timezone_set)
3593 {
3594 	zval *object;
3595 	zval *timezone_object;
3596 
3597 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OO", &object, date_ce_date, &timezone_object, date_ce_timezone) == FAILURE) {
3598 		RETURN_THROWS();
3599 	}
3600 
3601 	php_date_timezone_set(object, timezone_object, return_value);
3602 
3603 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3604 }
3605 /* }}} */
3606 
3607 /* {{{ */
PHP_METHOD(DateTimeImmutable,setTimezone)3608 PHP_METHOD(DateTimeImmutable, setTimezone)
3609 {
3610 	zval *object, new_object;
3611 	zval *timezone_object;
3612 
3613 	object = ZEND_THIS;
3614 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &timezone_object, date_ce_timezone) == FAILURE) {
3615 		RETURN_THROWS();
3616 	}
3617 
3618 	date_clone_immutable(object, &new_object);
3619 	php_date_timezone_set(&new_object, timezone_object, return_value);
3620 
3621 	RETURN_OBJ(Z_OBJ(new_object));
3622 }
3623 /* }}} */
3624 
3625 /* {{{ Returns the DST offset. */
PHP_FUNCTION(date_offset_get)3626 PHP_FUNCTION(date_offset_get)
3627 {
3628 	zval                *object;
3629 	php_date_obj        *dateobj;
3630 	timelib_time_offset *offset;
3631 
3632 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &object, date_ce_interface) == FAILURE) {
3633 		RETURN_THROWS();
3634 	}
3635 	dateobj = Z_PHPDATE_P(object);
3636 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3637 	if (dateobj->time->is_localtime) {
3638 		switch (dateobj->time->zone_type) {
3639 			case TIMELIB_ZONETYPE_ID:
3640 				offset = timelib_get_time_zone_info(dateobj->time->sse, dateobj->time->tz_info);
3641 				RETVAL_LONG(offset->offset);
3642 				timelib_time_offset_dtor(offset);
3643 				break;
3644 			case TIMELIB_ZONETYPE_OFFSET:
3645 				RETVAL_LONG(dateobj->time->z);
3646 				break;
3647 			case TIMELIB_ZONETYPE_ABBR:
3648 				RETVAL_LONG((dateobj->time->z + (3600 * dateobj->time->dst)));
3649 				break;
3650 		}
3651 		return;
3652 	} else {
3653 		RETURN_LONG(0);
3654 	}
3655 }
3656 /* }}} */
3657 
php_date_time_set(zval * object,zend_long h,zend_long i,zend_long s,zend_long ms,zval * return_value)3658 static void php_date_time_set(zval *object, zend_long h, zend_long i, zend_long s, zend_long ms, zval *return_value) /* {{{ */
3659 {
3660 	php_date_obj *dateobj;
3661 
3662 	dateobj = Z_PHPDATE_P(object);
3663 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3664 	dateobj->time->h = h;
3665 	dateobj->time->i = i;
3666 	dateobj->time->s = s;
3667 	dateobj->time->us = ms;
3668 	timelib_update_ts(dateobj->time, NULL);
3669 	timelib_update_from_sse(dateobj->time);
3670 } /* }}} */
3671 
3672 /* {{{ Sets the time. */
PHP_FUNCTION(date_time_set)3673 PHP_FUNCTION(date_time_set)
3674 {
3675 	zval *object;
3676 	zend_long  h, i, s = 0, ms = 0;
3677 
3678 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Oll|ll", &object, date_ce_date, &h, &i, &s, &ms) == FAILURE) {
3679 		RETURN_THROWS();
3680 	}
3681 
3682 	php_date_time_set(object, h, i, s, ms, return_value);
3683 
3684 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3685 }
3686 /* }}} */
3687 
3688 /* {{{ */
PHP_METHOD(DateTimeImmutable,setTime)3689 PHP_METHOD(DateTimeImmutable, setTime)
3690 {
3691 	zval *object, new_object;
3692 	zend_long  h, i, s = 0, ms = 0;
3693 
3694 	object = ZEND_THIS;
3695 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ll|ll", &h, &i, &s, &ms) == FAILURE) {
3696 		RETURN_THROWS();
3697 	}
3698 
3699 	date_clone_immutable(object, &new_object);
3700 	php_date_time_set(&new_object, h, i, s, ms, return_value);
3701 
3702 	RETURN_OBJ(Z_OBJ(new_object));
3703 }
3704 /* }}} */
3705 
php_date_date_set(zval * object,zend_long y,zend_long m,zend_long d,zval * return_value)3706 static void php_date_date_set(zval *object, zend_long y, zend_long m, zend_long d, zval *return_value) /* {{{ */
3707 {
3708 	php_date_obj *dateobj;
3709 
3710 	dateobj = Z_PHPDATE_P(object);
3711 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3712 	dateobj->time->y = y;
3713 	dateobj->time->m = m;
3714 	dateobj->time->d = d;
3715 	timelib_update_ts(dateobj->time, NULL);
3716 } /* }}} */
3717 
3718 /* {{{ Sets the date. */
PHP_FUNCTION(date_date_set)3719 PHP_FUNCTION(date_date_set)
3720 {
3721 	zval *object;
3722 	zend_long  y, m, d;
3723 
3724 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Olll", &object, date_ce_date, &y, &m, &d) == FAILURE) {
3725 		RETURN_THROWS();
3726 	}
3727 
3728 	php_date_date_set(object, y, m, d, return_value);
3729 
3730 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3731 }
3732 /* }}} */
3733 
3734 /* {{{ */
PHP_METHOD(DateTimeImmutable,setDate)3735 PHP_METHOD(DateTimeImmutable, setDate)
3736 {
3737 	zval *object, new_object;
3738 	zend_long  y, m, d;
3739 
3740 	object = ZEND_THIS;
3741 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "lll", &y, &m, &d) == FAILURE) {
3742 		RETURN_THROWS();
3743 	}
3744 
3745 	date_clone_immutable(object, &new_object);
3746 	php_date_date_set(&new_object, y, m, d, return_value);
3747 
3748 	RETURN_OBJ(Z_OBJ(new_object));
3749 }
3750 /* }}} */
3751 
php_date_isodate_set(zval * object,zend_long y,zend_long w,zend_long d,zval * return_value)3752 static void php_date_isodate_set(zval *object, zend_long y, zend_long w, zend_long d, zval *return_value) /* {{{ */
3753 {
3754 	php_date_obj *dateobj;
3755 
3756 	dateobj = Z_PHPDATE_P(object);
3757 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3758 	dateobj->time->y = y;
3759 	dateobj->time->m = 1;
3760 	dateobj->time->d = 1;
3761 	memset(&dateobj->time->relative, 0, sizeof(dateobj->time->relative));
3762 	dateobj->time->relative.d = timelib_daynr_from_weeknr(y, w, d);
3763 	dateobj->time->have_relative = 1;
3764 
3765 	timelib_update_ts(dateobj->time, NULL);
3766 } /* }}} */
3767 
3768 /* {{{ Sets the ISO date. */
PHP_FUNCTION(date_isodate_set)3769 PHP_FUNCTION(date_isodate_set)
3770 {
3771 	zval *object;
3772 	zend_long  y, w, d = 1;
3773 
3774 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Oll|l", &object, date_ce_date, &y, &w, &d) == FAILURE) {
3775 		RETURN_THROWS();
3776 	}
3777 
3778 	php_date_isodate_set(object, y, w, d, return_value);
3779 
3780 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3781 }
3782 /* }}} */
3783 
3784 /* {{{ */
PHP_METHOD(DateTimeImmutable,setISODate)3785 PHP_METHOD(DateTimeImmutable, setISODate)
3786 {
3787 	zval *object, new_object;
3788 	zend_long  y, w, d = 1;
3789 
3790 	object = ZEND_THIS;
3791 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ll|l", &y, &w, &d) == FAILURE) {
3792 		RETURN_THROWS();
3793 	}
3794 
3795 	date_clone_immutable(object, &new_object);
3796 	php_date_isodate_set(&new_object, y, w, d, return_value);
3797 
3798 	RETURN_OBJ(Z_OBJ(new_object));
3799 }
3800 /* }}} */
3801 
php_date_timestamp_set(zval * object,zend_long timestamp,zval * return_value)3802 static void php_date_timestamp_set(zval *object, zend_long timestamp, zval *return_value) /* {{{ */
3803 {
3804 	php_date_obj *dateobj;
3805 
3806 	dateobj = Z_PHPDATE_P(object);
3807 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3808 	timelib_unixtime2local(dateobj->time, (timelib_sll)timestamp);
3809 	timelib_update_ts(dateobj->time, NULL);
3810 	php_date_set_time_fraction(dateobj->time, 0);
3811 } /* }}} */
3812 
3813 /* {{{ Sets the date and time based on an Unix timestamp. */
PHP_FUNCTION(date_timestamp_set)3814 PHP_FUNCTION(date_timestamp_set)
3815 {
3816 	zval *object;
3817 	zend_long  timestamp;
3818 
3819 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Ol", &object, date_ce_date, &timestamp) == FAILURE) {
3820 		RETURN_THROWS();
3821 	}
3822 
3823 	php_date_timestamp_set(object, timestamp, return_value);
3824 
3825 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3826 }
3827 /* }}} */
3828 
3829 /* {{{ */
PHP_METHOD(DateTimeImmutable,setTimestamp)3830 PHP_METHOD(DateTimeImmutable, setTimestamp)
3831 {
3832 	zval *object, new_object;
3833 	zend_long  timestamp;
3834 
3835 	object = ZEND_THIS;
3836 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &timestamp) == FAILURE) {
3837 		RETURN_THROWS();
3838 	}
3839 
3840 	date_clone_immutable(object, &new_object);
3841 	php_date_timestamp_set(&new_object, timestamp, return_value);
3842 
3843 	RETURN_OBJ(Z_OBJ(new_object));
3844 }
3845 /* }}} */
3846 
3847 /* {{{ */
PHP_METHOD(DateTimeImmutable,setMicroseconds)3848 PHP_METHOD(DateTimeImmutable, setMicroseconds)
3849 {
3850 	zval *object, new_object;
3851 	php_date_obj *dateobj, *new_dateobj;
3852 	zend_long us;
3853 
3854 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &us) == FAILURE) {
3855 		RETURN_THROWS();
3856 	}
3857 
3858 	if (UNEXPECTED(us < 0 || us > 999999)) {
3859 		zend_argument_error(
3860 			date_ce_date_range_error,
3861 			1,
3862 			"must be between 0 and 999999, " ZEND_LONG_FMT " given",
3863 			us
3864 		);
3865 		RETURN_THROWS();
3866 	}
3867 
3868 	object = ZEND_THIS;
3869 	dateobj = Z_PHPDATE_P(object);
3870 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3871 
3872 	date_clone_immutable(object, &new_object);
3873 	new_dateobj = Z_PHPDATE_P(&new_object);
3874 
3875 	php_date_set_time_fraction(new_dateobj->time, (int)us);
3876 
3877 	RETURN_OBJ(Z_OBJ(new_object));
3878 }
3879 /* }}} */
3880 
3881 /* {{{ */
PHP_METHOD(DateTime,setMicroseconds)3882 PHP_METHOD(DateTime, setMicroseconds)
3883 {
3884 	zval *object;
3885 	php_date_obj *dateobj;
3886 	zend_long us;
3887 
3888 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &us) == FAILURE) {
3889 		RETURN_THROWS();
3890 	}
3891 
3892 	if (UNEXPECTED(us < 0 || us > 999999)) {
3893 		zend_argument_error(
3894 			date_ce_date_range_error,
3895 			1,
3896 			"must be between 0 and 999999, " ZEND_LONG_FMT " given",
3897 			us
3898 		);
3899 		RETURN_THROWS();
3900 	}
3901 
3902 	object = ZEND_THIS;
3903 	dateobj = Z_PHPDATE_P(object);
3904 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3905 	php_date_set_time_fraction(dateobj->time, (int)us);
3906 
3907 	RETURN_OBJ_COPY(Z_OBJ_P(object));
3908 }
3909 /* }}} */
3910 
3911 /* {{{ Gets the Unix timestamp. */
PHP_FUNCTION(date_timestamp_get)3912 PHP_FUNCTION(date_timestamp_get)
3913 {
3914 	zval         *object;
3915 	php_date_obj *dateobj;
3916 	zend_long     timestamp;
3917 	int           epoch_does_not_fit_in_zend_long;
3918 
3919 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &object, date_ce_interface) == FAILURE) {
3920 		RETURN_THROWS();
3921 	}
3922 	dateobj = Z_PHPDATE_P(object);
3923 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3924 
3925 	if (!dateobj->time->sse_uptodate) {
3926 		timelib_update_ts(dateobj->time, NULL);
3927 	}
3928 
3929 	timestamp = timelib_date_to_int(dateobj->time, &epoch_does_not_fit_in_zend_long);
3930 
3931 	if (epoch_does_not_fit_in_zend_long) {
3932 		zend_throw_error(date_ce_date_range_error, "Epoch doesn't fit in a PHP integer");
3933 		RETURN_THROWS();
3934 	}
3935 
3936 	RETURN_LONG(timestamp);
3937 }
3938 /* }}} */
3939 
PHP_METHOD(DateTime,getMicroseconds)3940 PHP_METHOD(DateTime, getMicroseconds) /* {{{ */
3941 {
3942 	zval *object;
3943 	php_date_obj *dateobj;
3944 
3945 	ZEND_PARSE_PARAMETERS_NONE();
3946 
3947 	object = ZEND_THIS;
3948 	dateobj = Z_PHPDATE_P(object);
3949 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
3950 
3951 	RETURN_LONG((zend_long)dateobj->time->us);
3952 }
3953 /* }}} */
3954 
3955 /* {{{ Returns the difference between two DateTime objects. */
PHP_FUNCTION(date_diff)3956 PHP_FUNCTION(date_diff)
3957 {
3958 	zval         *object1, *object2;
3959 	php_date_obj *dateobj1, *dateobj2;
3960 	php_interval_obj *interval;
3961 	bool      absolute = 0;
3962 
3963 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OO|b", &object1, date_ce_interface, &object2, date_ce_interface, &absolute) == FAILURE) {
3964 		RETURN_THROWS();
3965 	}
3966 	dateobj1 = Z_PHPDATE_P(object1);
3967 	dateobj2 = Z_PHPDATE_P(object2);
3968 	DATE_CHECK_INITIALIZED(dateobj1->time, Z_OBJCE_P(object1));
3969 	DATE_CHECK_INITIALIZED(dateobj2->time, Z_OBJCE_P(object2));
3970 
3971 	php_date_instantiate(date_ce_interval, return_value);
3972 	interval = Z_PHPINTERVAL_P(return_value);
3973 	interval->diff = timelib_diff(dateobj1->time, dateobj2->time);
3974 	if (absolute) {
3975 		interval->diff->invert = 0;
3976 	}
3977 	interval->initialized = 1;
3978 	interval->civil_or_wall = PHP_DATE_CIVIL;
3979 }
3980 /* }}} */
3981 
timezone_initialize(php_timezone_obj * tzobj,const char * tz,size_t tz_len,char ** warning_message)3982 static bool timezone_initialize(php_timezone_obj *tzobj, const char *tz, size_t tz_len, char **warning_message) /* {{{ */
3983 {
3984 	timelib_time *dummy_t = ecalloc(1, sizeof(timelib_time));
3985 	int           dst, not_found;
3986 	const char   *orig_tz = tz;
3987 
3988 	if (strlen(tz) != tz_len) {
3989 		if (warning_message) {
3990 			spprintf(warning_message, 0, "Timezone must not contain null bytes");
3991 		}
3992 		efree(dummy_t);
3993 		return false;
3994 	}
3995 
3996 	dummy_t->z = timelib_parse_zone(&tz, &dst, dummy_t, &not_found, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
3997 	if ((dummy_t->z >= (100 * 60 * 60)) || (dummy_t->z <= (-100 * 60 * 60))) {
3998 		if (warning_message) {
3999 			spprintf(warning_message, 0, "Timezone offset is out of range (%s)", orig_tz);
4000 		}
4001 		timelib_free(dummy_t->tz_abbr);
4002 		efree(dummy_t);
4003 		return false;
4004 	}
4005 	dummy_t->dst = dst;
4006 	if (!not_found && (*tz != '\0')) {
4007 		if (warning_message) {
4008 			spprintf(warning_message, 0, "Unknown or bad timezone (%s)", orig_tz);
4009 		}
4010 		timelib_free(dummy_t->tz_abbr);
4011 		efree(dummy_t);
4012 		return false;
4013 	}
4014 	if (not_found) {
4015 		if (warning_message) {
4016 			spprintf(warning_message, 0, "Unknown or bad timezone (%s)", orig_tz);
4017 		}
4018 		efree(dummy_t);
4019 		return false;
4020 	} else {
4021 		set_timezone_from_timelib_time(tzobj, dummy_t);
4022 		timelib_free(dummy_t->tz_abbr);
4023 		efree(dummy_t);
4024 		return true;
4025 	}
4026 } /* }}} */
4027 
4028 /* {{{ Returns new DateTimeZone object */
PHP_FUNCTION(timezone_open)4029 PHP_FUNCTION(timezone_open)
4030 {
4031 	zend_string *tz;
4032 	php_timezone_obj *tzobj;
4033 	char *warning_message;
4034 
4035 	ZEND_PARSE_PARAMETERS_START(1, 1)
4036 		Z_PARAM_PATH_STR(tz) /* To prevent null bytes */
4037 	ZEND_PARSE_PARAMETERS_END();
4038 
4039 	tzobj = Z_PHPTIMEZONE_P(php_date_instantiate(date_ce_timezone, return_value));
4040 	if (!timezone_initialize(tzobj, ZSTR_VAL(tz), ZSTR_LEN(tz), &warning_message)) {
4041 		php_error_docref(NULL, E_WARNING, "%s", warning_message);
4042 		efree(warning_message);
4043 		zval_ptr_dtor(return_value);
4044 		RETURN_FALSE;
4045 	}
4046 }
4047 /* }}} */
4048 
4049 /* {{{ Creates new DateTimeZone object. */
PHP_METHOD(DateTimeZone,__construct)4050 PHP_METHOD(DateTimeZone, __construct)
4051 {
4052 	zend_string *tz;
4053 	php_timezone_obj *tzobj;
4054 	char *exception_message;
4055 
4056 	ZEND_PARSE_PARAMETERS_START(1, 1)
4057 		Z_PARAM_PATH_STR(tz) /* To prevent null bytes */
4058 	ZEND_PARSE_PARAMETERS_END();
4059 
4060 	tzobj = Z_PHPTIMEZONE_P(ZEND_THIS);
4061 	if (!timezone_initialize(tzobj, ZSTR_VAL(tz), ZSTR_LEN(tz), &exception_message)) {
4062 		zend_throw_exception_ex(date_ce_date_invalid_timezone_exception, 0, "DateTimeZone::__construct(): %s", exception_message);
4063 		efree(exception_message);
4064 	}
4065 }
4066 /* }}} */
4067 
php_date_timezone_initialize_from_hash(zval ** return_value,php_timezone_obj ** tzobj,HashTable * myht)4068 static bool php_date_timezone_initialize_from_hash(zval **return_value, php_timezone_obj **tzobj, HashTable *myht) /* {{{ */
4069 {
4070 	zval            *z_timezone_type;
4071 
4072 	if ((z_timezone_type = zend_hash_str_find(myht, "timezone_type", sizeof("timezone_type") - 1)) == NULL) {
4073 		return false;
4074 	}
4075 
4076 	zval *z_timezone;
4077 
4078 	if ((z_timezone = zend_hash_str_find(myht, "timezone", sizeof("timezone") - 1)) == NULL) {
4079 		return false;
4080 	}
4081 
4082 	if (Z_TYPE_P(z_timezone_type) != IS_LONG) {
4083 		return false;
4084 	}
4085 	if (Z_LVAL_P(z_timezone_type) < TIMELIB_ZONETYPE_OFFSET || Z_LVAL_P(z_timezone_type) > TIMELIB_ZONETYPE_ID) {
4086 		return false;
4087 	}
4088 	if (Z_TYPE_P(z_timezone) != IS_STRING) {
4089 		return false;
4090 	}
4091 	return timezone_initialize(*tzobj, Z_STRVAL_P(z_timezone), Z_STRLEN_P(z_timezone), NULL);
4092 } /* }}} */
4093 
4094 /* {{{  */
PHP_METHOD(DateTimeZone,__set_state)4095 PHP_METHOD(DateTimeZone, __set_state)
4096 {
4097 	php_timezone_obj *tzobj;
4098 	zval             *array;
4099 	HashTable        *myht;
4100 
4101 	ZEND_PARSE_PARAMETERS_START(1, 1)
4102 		Z_PARAM_ARRAY(array)
4103 	ZEND_PARSE_PARAMETERS_END();
4104 
4105 	myht = Z_ARRVAL_P(array);
4106 
4107 	php_date_instantiate(date_ce_timezone, return_value);
4108 	tzobj = Z_PHPTIMEZONE_P(return_value);
4109 	if (!php_date_timezone_initialize_from_hash(&return_value, &tzobj, myht)) {
4110 		zend_throw_error(NULL, "Invalid serialization data for DateTimeZone object");
4111 	}
4112 }
4113 /* }}} */
4114 
4115 /* {{{  */
PHP_METHOD(DateTimeZone,__wakeup)4116 PHP_METHOD(DateTimeZone, __wakeup)
4117 {
4118 	zval             *object = ZEND_THIS;
4119 	php_timezone_obj *tzobj;
4120 	HashTable        *myht;
4121 
4122 	ZEND_PARSE_PARAMETERS_NONE();
4123 
4124 	tzobj = Z_PHPTIMEZONE_P(object);
4125 
4126 	myht = Z_OBJPROP_P(object);
4127 
4128 	if (!php_date_timezone_initialize_from_hash(&return_value, &tzobj, myht)) {
4129 		zend_throw_error(NULL, "Invalid serialization data for DateTimeZone object");
4130 	}
4131 }
4132 /* }}} */
4133 
4134 /* {{{ */
PHP_METHOD(DateTimeZone,__serialize)4135 PHP_METHOD(DateTimeZone, __serialize)
4136 {
4137 	zval             *object = ZEND_THIS;
4138 	php_timezone_obj *tzobj;
4139 	HashTable        *myht;
4140 
4141 	ZEND_PARSE_PARAMETERS_NONE();
4142 
4143 	tzobj = Z_PHPTIMEZONE_P(object);
4144 	DATE_CHECK_INITIALIZED(tzobj->initialized, Z_OBJCE_P(object));
4145 
4146 	array_init(return_value);
4147 	myht = Z_ARRVAL_P(return_value);
4148 	date_timezone_object_to_hash(tzobj, myht);
4149 
4150 	add_common_properties(myht, &tzobj->std);
4151 }
4152 /* }}} */
4153 
date_timezone_is_internal_property(zend_string * name)4154 static bool date_timezone_is_internal_property(zend_string *name)
4155 {
4156 	if (
4157 		zend_string_equals_literal(name, "timezone_type") ||
4158 		zend_string_equals_literal(name, "timezone")
4159 	) {
4160 		return 1;
4161 	}
4162 	return 0;
4163 }
4164 
restore_custom_datetimezone_properties(zval * object,HashTable * myht)4165 static void restore_custom_datetimezone_properties(zval *object, HashTable *myht)
4166 {
4167 	zend_string      *prop_name;
4168 	zval             *prop_val;
4169 
4170 	ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(myht, prop_name, prop_val) {
4171 		if (!prop_name || (Z_TYPE_P(prop_val) == IS_REFERENCE) || date_timezone_is_internal_property(prop_name)) {
4172 			continue;
4173 		}
4174 		update_property(Z_OBJ_P(object), prop_name, prop_val);
4175 	} ZEND_HASH_FOREACH_END();
4176 }
4177 
4178 /* {{{ */
PHP_METHOD(DateTimeZone,__unserialize)4179 PHP_METHOD(DateTimeZone, __unserialize)
4180 {
4181 	zval             *object = ZEND_THIS;
4182 	php_timezone_obj *tzobj;
4183 	zval             *array;
4184 	HashTable        *myht;
4185 
4186 	ZEND_PARSE_PARAMETERS_START(1, 1)
4187 		Z_PARAM_ARRAY(array)
4188 	ZEND_PARSE_PARAMETERS_END();
4189 
4190 	tzobj = Z_PHPTIMEZONE_P(object);
4191 	myht = Z_ARRVAL_P(array);
4192 
4193 	if (!php_date_timezone_initialize_from_hash(&object, &tzobj, myht)) {
4194 		zend_throw_error(NULL, "Invalid serialization data for DateTimeZone object");
4195 	}
4196 
4197 	restore_custom_datetimezone_properties(object, myht);
4198 }
4199 /* }}} */
4200 
4201 /* {{{ Returns the name of the timezone. */
PHP_FUNCTION(timezone_name_get)4202 PHP_FUNCTION(timezone_name_get)
4203 {
4204 	zval             *object;
4205 	php_timezone_obj *tzobj;
4206 
4207 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &object, date_ce_timezone) == FAILURE) {
4208 		RETURN_THROWS();
4209 	}
4210 	tzobj = Z_PHPTIMEZONE_P(object);
4211 	DATE_CHECK_INITIALIZED(tzobj->initialized, Z_OBJCE_P(object));
4212 	php_timezone_to_string(tzobj, return_value);
4213 }
4214 /* }}} */
4215 
4216 /* {{{ Returns the timezone name from abbreviation */
PHP_FUNCTION(timezone_name_from_abbr)4217 PHP_FUNCTION(timezone_name_from_abbr)
4218 {
4219 	zend_string  *abbr;
4220 	const char   *tzid;
4221 	zend_long     gmtoffset = -1;
4222 	zend_long     isdst = -1;
4223 
4224 	ZEND_PARSE_PARAMETERS_START(1, 3)
4225 		Z_PARAM_STR(abbr)
4226 		Z_PARAM_OPTIONAL
4227 		Z_PARAM_LONG(gmtoffset)
4228 		Z_PARAM_LONG(isdst)
4229 	ZEND_PARSE_PARAMETERS_END();
4230 
4231 	tzid = timelib_timezone_id_from_abbr(ZSTR_VAL(abbr), gmtoffset, isdst);
4232 
4233 	if (tzid) {
4234 		RETURN_STRING(tzid);
4235 	} else {
4236 		RETURN_FALSE;
4237 	}
4238 }
4239 /* }}} */
4240 
4241 /* {{{ Returns the timezone offset. */
PHP_FUNCTION(timezone_offset_get)4242 PHP_FUNCTION(timezone_offset_get)
4243 {
4244 	zval                *object, *dateobject;
4245 	php_timezone_obj    *tzobj;
4246 	php_date_obj        *dateobj;
4247 	timelib_time_offset *offset;
4248 
4249 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "OO", &object, date_ce_timezone, &dateobject, date_ce_interface) == FAILURE) {
4250 		RETURN_THROWS();
4251 	}
4252 	tzobj = Z_PHPTIMEZONE_P(object);
4253 	DATE_CHECK_INITIALIZED(tzobj->initialized, Z_OBJCE_P(object));
4254 	dateobj = Z_PHPDATE_P(dateobject);
4255 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(dateobject));
4256 
4257 	switch (tzobj->type) {
4258 		case TIMELIB_ZONETYPE_ID:
4259 			offset = timelib_get_time_zone_info(dateobj->time->sse, tzobj->tzi.tz);
4260 			RETVAL_LONG(offset->offset);
4261 			timelib_time_offset_dtor(offset);
4262 			break;
4263 		case TIMELIB_ZONETYPE_OFFSET:
4264 			RETURN_LONG(tzobj->tzi.utc_offset);
4265 			break;
4266 		case TIMELIB_ZONETYPE_ABBR:
4267 			RETURN_LONG(tzobj->tzi.z.utc_offset + (tzobj->tzi.z.dst * 3600));
4268 			break;
4269 	}
4270 }
4271 /* }}} */
4272 
4273 /* {{{ Returns numerically indexed array containing associative array for all transitions in the specified range for the timezone. */
PHP_FUNCTION(timezone_transitions_get)4274 PHP_FUNCTION(timezone_transitions_get)
4275 {
4276 	zval                *object, element;
4277 	php_timezone_obj    *tzobj;
4278 	int                  begin = 0;
4279 	bool                 found;
4280 	zend_long            timestamp_begin = ZEND_LONG_MIN, timestamp_end = INT32_MAX;
4281 
4282 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O|ll", &object, date_ce_timezone, &timestamp_begin, &timestamp_end) == FAILURE) {
4283 		RETURN_THROWS();
4284 	}
4285 	tzobj = Z_PHPTIMEZONE_P(object);
4286 	DATE_CHECK_INITIALIZED(tzobj->initialized, Z_OBJCE_P(object));
4287 	if (tzobj->type != TIMELIB_ZONETYPE_ID) {
4288 		RETURN_FALSE;
4289 	}
4290 
4291 #define add_nominal() \
4292 		array_init(&element); \
4293 		add_assoc_long(&element, "ts",     timestamp_begin); \
4294 		add_assoc_str(&element, "time", php_format_date(DATE_FORMAT_ISO8601_LARGE_YEAR, 13, timestamp_begin, 0)); \
4295 		add_assoc_long(&element, "offset", tzobj->tzi.tz->type[0].offset); \
4296 		add_assoc_bool(&element, "isdst",  tzobj->tzi.tz->type[0].isdst); \
4297 		add_assoc_string(&element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[0].abbr_idx]); \
4298 		add_next_index_zval(return_value, &element);
4299 
4300 #define add(i,ts) \
4301 		array_init(&element); \
4302 		add_assoc_long(&element, "ts",     ts); \
4303 		add_assoc_str(&element, "time", php_format_date(DATE_FORMAT_ISO8601_LARGE_YEAR, 13, ts, 0)); \
4304 		add_assoc_long(&element, "offset", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].offset); \
4305 		add_assoc_bool(&element, "isdst",  tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].isdst); \
4306 		add_assoc_string(&element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].abbr_idx]); \
4307 		add_next_index_zval(return_value, &element);
4308 
4309 #define add_by_index(i,ts) \
4310 		array_init(&element); \
4311 		add_assoc_long(&element, "ts",     ts); \
4312 		add_assoc_str(&element, "time", php_format_date(DATE_FORMAT_ISO8601_LARGE_YEAR, 13, ts, 0)); \
4313 		add_assoc_long(&element, "offset", tzobj->tzi.tz->type[i].offset); \
4314 		add_assoc_bool(&element, "isdst",  tzobj->tzi.tz->type[i].isdst); \
4315 		add_assoc_string(&element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[i].abbr_idx]); \
4316 		add_next_index_zval(return_value, &element);
4317 
4318 #define add_from_tto(to,ts) \
4319 		array_init(&element); \
4320 		add_assoc_long(&element, "ts",     ts); \
4321 		add_assoc_str(&element, "time", php_format_date(DATE_FORMAT_ISO8601_LARGE_YEAR, 13, ts, 0)); \
4322 		add_assoc_long(&element, "offset", (to)->offset); \
4323 		add_assoc_bool(&element, "isdst",  (to)->is_dst); \
4324 		add_assoc_string(&element, "abbr", (to)->abbr); \
4325 		add_next_index_zval(return_value, &element);
4326 
4327 #define add_last() add(tzobj->tzi.tz->bit64.timecnt - 1, timestamp_begin)
4328 
4329 	array_init(return_value);
4330 
4331 	if (timestamp_begin == ZEND_LONG_MIN) {
4332 		add_nominal();
4333 		begin = 0;
4334 		found = 1;
4335 	} else {
4336 		begin = 0;
4337 		found = 0;
4338 		if (tzobj->tzi.tz->bit64.timecnt > 0) {
4339 			do {
4340 				if (tzobj->tzi.tz->trans[begin] > timestamp_begin) {
4341 					if (begin > 0) {
4342 						add(begin - 1, timestamp_begin);
4343 					} else {
4344 						add_nominal();
4345 					}
4346 					found = 1;
4347 					break;
4348 				}
4349 				begin++;
4350 			} while (begin < tzobj->tzi.tz->bit64.timecnt);
4351 		}
4352 	}
4353 
4354 	if (!found) {
4355 		if (tzobj->tzi.tz->bit64.timecnt > 0) {
4356 			if (tzobj->tzi.tz->posix_info && tzobj->tzi.tz->posix_info->dst_end) {
4357 				timelib_time_offset *tto = timelib_get_time_zone_info(timestamp_begin, tzobj->tzi.tz);
4358 				add_from_tto(tto, timestamp_begin);
4359 				timelib_time_offset_dtor(tto);
4360 			} else {
4361 				add_last();
4362 			}
4363 		} else {
4364 			add_nominal();
4365 		}
4366 	} else {
4367 		unsigned int i;
4368 		for (i = begin; i < tzobj->tzi.tz->bit64.timecnt; ++i) {
4369 			if (tzobj->tzi.tz->trans[i] < timestamp_end) {
4370 				add(i, tzobj->tzi.tz->trans[i]);
4371 			} else {
4372 				return;
4373 			}
4374 		}
4375 	}
4376 	if (tzobj->tzi.tz->posix_info && tzobj->tzi.tz->posix_info->dst_end) {
4377 		int i, j;
4378 		timelib_sll start_y, end_y, dummy_m, dummy_d;
4379 		timelib_sll last_transition_ts = tzobj->tzi.tz->trans[tzobj->tzi.tz->bit64.timecnt - 1];
4380 
4381 		/* Find out year for last transition */
4382 		timelib_unixtime2date(last_transition_ts, &start_y, &dummy_m, &dummy_d);
4383 
4384 		/* Find out year for final boundary timestamp */
4385 		timelib_unixtime2date(timestamp_end, &end_y, &dummy_m, &dummy_d);
4386 
4387 		for (i = start_y; i <= end_y; i++) {
4388 			timelib_posix_transitions transitions = { 0 };
4389 
4390 			timelib_get_transitions_for_year(tzobj->tzi.tz, i, &transitions);
4391 
4392 			for (j = 0; j < transitions.count; j++) {
4393 				if (transitions.times[j] <= last_transition_ts) {
4394 					continue;
4395 				}
4396 				if (transitions.times[j] < timestamp_begin) {
4397 					continue;
4398 				}
4399 				if (transitions.times[j] > timestamp_end) {
4400 					return;
4401 				}
4402 				add_by_index(transitions.types[j], transitions.times[j]);
4403 			}
4404 		}
4405 	}
4406 }
4407 /* }}} */
4408 
4409 /* {{{ Returns location information for a timezone, including country code, latitude/longitude and comments */
PHP_FUNCTION(timezone_location_get)4410 PHP_FUNCTION(timezone_location_get)
4411 {
4412 	zval                *object;
4413 	php_timezone_obj    *tzobj;
4414 
4415 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &object, date_ce_timezone) == FAILURE) {
4416 		RETURN_THROWS();
4417 	}
4418 	tzobj = Z_PHPTIMEZONE_P(object);
4419 	DATE_CHECK_INITIALIZED(tzobj->initialized, Z_OBJCE_P(object));
4420 	if (tzobj->type != TIMELIB_ZONETYPE_ID) {
4421 		RETURN_FALSE;
4422 	}
4423 
4424 	array_init(return_value);
4425 	add_assoc_string(return_value, "country_code", tzobj->tzi.tz->location.country_code);
4426 	add_assoc_double(return_value, "latitude", tzobj->tzi.tz->location.latitude);
4427 	add_assoc_double(return_value, "longitude", tzobj->tzi.tz->location.longitude);
4428 	add_assoc_string(return_value, "comments", tzobj->tzi.tz->location.comments);
4429 }
4430 /* }}} */
4431 
date_interval_initialize(timelib_rel_time ** rt,char * format,size_t format_length)4432 static bool date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, size_t format_length) /* {{{ */
4433 {
4434 	timelib_time     *b = NULL, *e = NULL;
4435 	timelib_rel_time *p = NULL;
4436 	int               r = 0;
4437 	bool              retval = false;
4438 	timelib_error_container *errors;
4439 
4440 	timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors);
4441 
4442 	if (errors->error_count > 0) {
4443 		zend_throw_exception_ex(date_ce_date_malformed_interval_string_exception, 0, "Unknown or bad format (%s)", format);
4444 		retval = false;
4445 		if (p) {
4446 			timelib_rel_time_dtor(p);
4447 		}
4448 	} else {
4449 		if (p) {
4450 			*rt = p;
4451 			retval = true;
4452 		} else {
4453 			if (b && e) {
4454 				timelib_update_ts(b, NULL);
4455 				timelib_update_ts(e, NULL);
4456 				*rt = timelib_diff(b, e);
4457 				retval = true;
4458 			} else {
4459 				zend_throw_exception_ex(date_ce_date_malformed_interval_string_exception, 0, "Failed to parse interval (%s)", format);
4460 				retval = false;
4461 			}
4462 		}
4463 	}
4464 	timelib_error_container_dtor(errors);
4465 	timelib_free(b);
4466 	timelib_free(e);
4467 	return retval;
4468 } /* }}} */
4469 
date_interval_compare_objects(zval * o1,zval * o2)4470 static int date_interval_compare_objects(zval *o1, zval *o2)
4471 {
4472 	ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
4473 	/* There is no well defined way to compare intervals like P1M and P30D, which may compare
4474 	 * smaller, equal or greater depending on the point in time at which the interval starts. As
4475 	 * such, we treat DateInterval objects are non-comparable and emit a warning. */
4476 	zend_error(E_WARNING, "Cannot compare DateInterval objects");
4477 	return ZEND_UNCOMPARABLE;
4478 }
4479 
4480 /* {{{ date_interval_read_property */
date_interval_read_property(zend_object * object,zend_string * name,int type,void ** cache_slot,zval * rv)4481 static zval *date_interval_read_property(zend_object *object, zend_string *name, int type, void **cache_slot, zval *rv)
4482 {
4483 	php_interval_obj *obj;
4484 	zval *retval;
4485 	timelib_sll value = -1;
4486 	double      fvalue = -1;
4487 
4488 	obj = php_interval_obj_from_obj(object);
4489 
4490 	if (!obj->initialized) {
4491 		retval = zend_std_read_property(object, name, type, cache_slot, rv);
4492 		return retval;
4493 	}
4494 
4495 #define GET_VALUE_FROM_STRUCT(n,m)            \
4496 	if (zend_string_equals_literal(name, m)) { \
4497 		value = obj->diff->n; \
4498 		break; \
4499 	}
4500 	do {
4501 		GET_VALUE_FROM_STRUCT(y, "y");
4502 		GET_VALUE_FROM_STRUCT(m, "m");
4503 		GET_VALUE_FROM_STRUCT(d, "d");
4504 		GET_VALUE_FROM_STRUCT(h, "h");
4505 		GET_VALUE_FROM_STRUCT(i, "i");
4506 		GET_VALUE_FROM_STRUCT(s, "s");
4507 		if (zend_string_equals_literal(name, "f")) {
4508 			fvalue = obj->diff->us / 1000000.0;
4509 			break;
4510 		}
4511 		GET_VALUE_FROM_STRUCT(invert, "invert");
4512 		GET_VALUE_FROM_STRUCT(days, "days");
4513 		/* didn't find any */
4514 		retval = zend_std_read_property(object, name, type, cache_slot, rv);
4515 
4516 		return retval;
4517 	} while(0);
4518 
4519 	retval = rv;
4520 
4521 	if (fvalue != -1) {
4522 		ZVAL_DOUBLE(retval, fvalue);
4523 	} else if (value != TIMELIB_UNSET) {
4524 		ZVAL_LONG(retval, value);
4525 	} else {
4526 		ZVAL_FALSE(retval);
4527 	}
4528 
4529 	return retval;
4530 }
4531 /* }}} */
4532 
4533 /* {{{ date_interval_write_property */
date_interval_write_property(zend_object * object,zend_string * name,zval * value,void ** cache_slot)4534 static zval *date_interval_write_property(zend_object *object, zend_string *name, zval *value, void **cache_slot)
4535 {
4536 	php_interval_obj *obj;
4537 
4538 	obj = php_interval_obj_from_obj(object);
4539 
4540 	if (!obj->initialized) {
4541 		return zend_std_write_property(object, name, value, cache_slot);
4542 	}
4543 
4544 #define SET_VALUE_FROM_STRUCT(n,m) \
4545 	if (zend_string_equals_literal(name, m)) { \
4546 		obj->diff->n = zval_get_long(value); \
4547 		break; \
4548 	}
4549 
4550 	do {
4551 		SET_VALUE_FROM_STRUCT(y, "y");
4552 		SET_VALUE_FROM_STRUCT(m, "m");
4553 		SET_VALUE_FROM_STRUCT(d, "d");
4554 		SET_VALUE_FROM_STRUCT(h, "h");
4555 		SET_VALUE_FROM_STRUCT(i, "i");
4556 		SET_VALUE_FROM_STRUCT(s, "s");
4557 		if (zend_string_equals_literal(name, "f")) {
4558 			obj->diff->us = zend_dval_to_lval(zval_get_double(value) * 1000000.0);
4559 			break;
4560 		}
4561 		SET_VALUE_FROM_STRUCT(invert, "invert");
4562 		/* didn't find any */
4563 		value = zend_std_write_property(object, name, value, cache_slot);
4564 	} while(0);
4565 
4566 	return value;
4567 }
4568 /* }}} */
4569 
4570 /* {{{ date_interval_get_property_ptr_ptr */
date_interval_get_property_ptr_ptr(zend_object * object,zend_string * name,int type,void ** cache_slot)4571 static zval *date_interval_get_property_ptr_ptr(zend_object *object, zend_string *name, int type, void **cache_slot)
4572 {
4573 	zval *ret;
4574 
4575 	if (
4576 		zend_string_equals_literal(name, "y") ||
4577 		zend_string_equals_literal(name, "m") ||
4578 		zend_string_equals_literal(name, "d") ||
4579 		zend_string_equals_literal(name, "h") ||
4580 		zend_string_equals_literal(name, "i") ||
4581 		zend_string_equals_literal(name, "s") ||
4582 		zend_string_equals_literal(name, "f") ||
4583 		zend_string_equals_literal(name, "days") ||
4584 		zend_string_equals_literal(name, "invert") ) {
4585 		/* Fallback to read_property. */
4586 		ret = NULL;
4587 	} else {
4588 		ret = zend_std_get_property_ptr_ptr(object, name, type, cache_slot);
4589 	}
4590 
4591 	return ret;
4592 }
4593 /* }}} */
4594 
4595 /* {{{ Creates new DateInterval object. */
PHP_METHOD(DateInterval,__construct)4596 PHP_METHOD(DateInterval, __construct)
4597 {
4598 	zend_string *interval_string = NULL;
4599 	timelib_rel_time *reltime;
4600 
4601 	ZEND_PARSE_PARAMETERS_START(1, 1)
4602 		Z_PARAM_STR(interval_string)
4603 	ZEND_PARSE_PARAMETERS_END();
4604 
4605 	if (!date_interval_initialize(&reltime, ZSTR_VAL(interval_string), ZSTR_LEN(interval_string))) {
4606 		RETURN_THROWS();
4607 	}
4608 
4609 	php_interval_obj *diobj = Z_PHPINTERVAL_P(ZEND_THIS);
4610 	diobj->diff = reltime;
4611 	diobj->initialized = 1;
4612 	diobj->civil_or_wall = PHP_DATE_WALL;
4613 }
4614 /* }}} */
4615 
php_date_interval_initialize_from_hash(zval ** return_value,php_interval_obj ** intobj,HashTable * myht)4616 static void php_date_interval_initialize_from_hash(zval **return_value, php_interval_obj **intobj, HashTable *myht) /* {{{ */
4617 {
4618 	/* If ->diff is already set, then we need to free it first */
4619 	if ((*intobj)->diff) {
4620 		timelib_rel_time_dtor((*intobj)->diff);
4621 	}
4622 
4623 	/* If we have a date_string, use that instead */
4624 	zval *date_str = zend_hash_str_find(myht, "date_string", strlen("date_string"));
4625 	if (date_str && Z_TYPE_P(date_str) == IS_STRING) {
4626 		timelib_time   *time;
4627 		timelib_error_container *err = NULL;
4628 
4629 		time = timelib_strtotime(Z_STRVAL_P(date_str), Z_STRLEN_P(date_str), &err, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
4630 
4631 		if (err->error_count > 0)  {
4632 			zend_throw_error(NULL,
4633 				"Unknown or bad format (%s) at position %d (%c) while unserializing: %s",
4634 				Z_STRVAL_P(date_str),
4635 				err->error_messages[0].position,
4636 				err->error_messages[0].character ? err->error_messages[0].character : ' ', err->error_messages[0].message);
4637 		}
4638 
4639 		(*intobj)->diff = timelib_rel_time_clone(&time->relative);
4640 		(*intobj)->initialized = 1;
4641 		(*intobj)->civil_or_wall = PHP_DATE_CIVIL;
4642 		(*intobj)->from_string = true;
4643 		(*intobj)->date_string = zend_string_copy(Z_STR_P(date_str));
4644 
4645 		timelib_time_dtor(time);
4646 		timelib_error_container_dtor(err);
4647 
4648 		return;
4649 	}
4650 
4651 	/* Set new value */
4652 	(*intobj)->diff = timelib_rel_time_ctor();
4653 
4654 #define PHP_DATE_INTERVAL_READ_PROPERTY(element, member, itype, def) \
4655 	do { \
4656 		zval *z_arg = zend_hash_str_find(myht, element, sizeof(element) - 1); \
4657 		if (z_arg && Z_TYPE_P(z_arg) <= IS_STRING) { \
4658 			(*intobj)->diff->member = (itype)zval_get_long(z_arg); \
4659 		} else { \
4660 			(*intobj)->diff->member = (itype)def; \
4661 		} \
4662 	} while (0);
4663 
4664 #define PHP_DATE_INTERVAL_READ_PROPERTY_I64(element, member) \
4665 	do { \
4666 		zval *z_arg = zend_hash_str_find(myht, element, sizeof(element) - 1); \
4667 		if (z_arg && Z_TYPE_P(z_arg) <= IS_STRING) { \
4668 			zend_string *tmp_str; \
4669 			zend_string *str = zval_get_tmp_string(z_arg, &tmp_str); \
4670 			DATE_A64I((*intobj)->diff->member, ZSTR_VAL(str)); \
4671 			zend_tmp_string_release(tmp_str); \
4672 		} else { \
4673 			(*intobj)->diff->member = -1LL; \
4674 		} \
4675 	} while (0);
4676 
4677 #define PHP_DATE_INTERVAL_READ_PROPERTY_DAYS(member) \
4678 	do { \
4679 		zval *z_arg = zend_hash_str_find(myht, "days", sizeof("days") - 1); \
4680 		if (z_arg && Z_TYPE_P(z_arg) == IS_FALSE) { \
4681 			(*intobj)->diff->member = TIMELIB_UNSET; \
4682 		} else if (z_arg && Z_TYPE_P(z_arg) <= IS_STRING) { \
4683 			zend_string *str = zval_get_string(z_arg); \
4684 			DATE_A64I((*intobj)->diff->member, ZSTR_VAL(str)); \
4685 			zend_string_release(str); \
4686 		} else { \
4687 			(*intobj)->diff->member = -1LL; \
4688 		} \
4689 	} while (0);
4690 
4691 #define PHP_DATE_INTERVAL_READ_PROPERTY_DOUBLE(element, member, def) \
4692 	do { \
4693 		zval *z_arg = zend_hash_str_find(myht, element, sizeof(element) - 1); \
4694 		if (z_arg) { \
4695 			(*intobj)->diff->member = (double)zval_get_double(z_arg); \
4696 		} else { \
4697 			(*intobj)->diff->member = (double)def; \
4698 		} \
4699 	} while (0);
4700 
4701 	PHP_DATE_INTERVAL_READ_PROPERTY("y", y, timelib_sll, -1)
4702 	PHP_DATE_INTERVAL_READ_PROPERTY("m", m, timelib_sll, -1)
4703 	PHP_DATE_INTERVAL_READ_PROPERTY("d", d, timelib_sll, -1)
4704 	PHP_DATE_INTERVAL_READ_PROPERTY("h", h, timelib_sll, -1)
4705 	PHP_DATE_INTERVAL_READ_PROPERTY("i", i, timelib_sll, -1)
4706 	PHP_DATE_INTERVAL_READ_PROPERTY("s", s, timelib_sll, -1)
4707 	{
4708 		zval *z_arg = zend_hash_str_find(myht, "f", sizeof("f") - 1);
4709 		if (z_arg) {
4710 			(*intobj)->diff->us = zend_dval_to_lval(zval_get_double(z_arg) * 1000000.0);
4711 		}
4712 	}
4713 	PHP_DATE_INTERVAL_READ_PROPERTY("weekday", weekday, int, -1)
4714 	PHP_DATE_INTERVAL_READ_PROPERTY("weekday_behavior", weekday_behavior, int, -1)
4715 	PHP_DATE_INTERVAL_READ_PROPERTY("first_last_day_of", first_last_day_of, int, -1)
4716 	PHP_DATE_INTERVAL_READ_PROPERTY("invert", invert, int, 0);
4717 	PHP_DATE_INTERVAL_READ_PROPERTY_DAYS(days);
4718 	PHP_DATE_INTERVAL_READ_PROPERTY("special_type", special.type, unsigned int, 0);
4719 	PHP_DATE_INTERVAL_READ_PROPERTY_I64("special_amount", special.amount);
4720 	PHP_DATE_INTERVAL_READ_PROPERTY("have_weekday_relative", have_weekday_relative, unsigned int, 0);
4721 	PHP_DATE_INTERVAL_READ_PROPERTY("have_special_relative", have_special_relative, unsigned int, 0);
4722 	{
4723 		zval *z_arg = zend_hash_str_find(myht, "civil_or_wall", sizeof("civil_or_wall") - 1);
4724 		(*intobj)->civil_or_wall = PHP_DATE_CIVIL;
4725 		if (z_arg) {
4726 			zend_long val = zval_get_long(z_arg);
4727 			(*intobj)->civil_or_wall = val;
4728 		}
4729 	}
4730 
4731 	(*intobj)->initialized = 1;
4732 } /* }}} */
4733 
4734 /* {{{ */
PHP_METHOD(DateInterval,__set_state)4735 PHP_METHOD(DateInterval, __set_state)
4736 {
4737 	php_interval_obj *intobj;
4738 	zval             *array;
4739 	HashTable        *myht;
4740 
4741 	ZEND_PARSE_PARAMETERS_START(1, 1)
4742 		Z_PARAM_ARRAY(array)
4743 	ZEND_PARSE_PARAMETERS_END();
4744 
4745 	myht = Z_ARRVAL_P(array);
4746 
4747 	php_date_instantiate(date_ce_interval, return_value);
4748 	intobj = Z_PHPINTERVAL_P(return_value);
4749 	php_date_interval_initialize_from_hash(&return_value, &intobj, myht);
4750 }
4751 /* }}} */
4752 
4753 /* {{{ */
PHP_METHOD(DateInterval,__serialize)4754 PHP_METHOD(DateInterval, __serialize)
4755 {
4756 	zval             *object = ZEND_THIS;
4757 	php_interval_obj *intervalobj;
4758 	HashTable        *myht;
4759 
4760 	ZEND_PARSE_PARAMETERS_NONE();
4761 
4762 	intervalobj = Z_PHPINTERVAL_P(object);
4763 	DATE_CHECK_INITIALIZED(intervalobj->initialized, Z_OBJCE_P(object));
4764 
4765 	array_init(return_value);
4766 	myht = Z_ARRVAL_P(return_value);
4767 	date_interval_object_to_hash(intervalobj, myht);
4768 
4769 	add_common_properties(myht, &intervalobj->std);
4770 }
4771 /* }}} */
4772 
date_interval_is_internal_property(zend_string * name)4773 static bool date_interval_is_internal_property(zend_string *name)
4774 {
4775 	if (
4776 		zend_string_equals_literal(name, "date_string") ||
4777 		zend_string_equals_literal(name, "from_string") ||
4778 		zend_string_equals_literal(name, "y") ||
4779 		zend_string_equals_literal(name, "m") ||
4780 		zend_string_equals_literal(name, "d") ||
4781 		zend_string_equals_literal(name, "h") ||
4782 		zend_string_equals_literal(name, "i") ||
4783 		zend_string_equals_literal(name, "s") ||
4784 		zend_string_equals_literal(name, "f") ||
4785 		zend_string_equals_literal(name, "invert") ||
4786 		zend_string_equals_literal(name, "days")
4787 	) {
4788 		return 1;
4789 	}
4790 	return 0;
4791 }
4792 
restore_custom_dateinterval_properties(zval * object,HashTable * myht)4793 static void restore_custom_dateinterval_properties(zval *object, HashTable *myht)
4794 {
4795 	zend_string      *prop_name;
4796 	zval             *prop_val;
4797 
4798 	ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(myht, prop_name, prop_val) {
4799 		if (!prop_name || (Z_TYPE_P(prop_val) == IS_REFERENCE) || date_interval_is_internal_property(prop_name)) {
4800 			continue;
4801 		}
4802 		update_property(Z_OBJ_P(object), prop_name, prop_val);
4803 	} ZEND_HASH_FOREACH_END();
4804 }
4805 
4806 
4807 /* {{{ */
PHP_METHOD(DateInterval,__unserialize)4808 PHP_METHOD(DateInterval, __unserialize)
4809 {
4810 	zval             *object = ZEND_THIS;
4811 	php_interval_obj *intervalobj;
4812 	zval             *array;
4813 	HashTable        *myht;
4814 
4815 	ZEND_PARSE_PARAMETERS_START(1, 1)
4816 		Z_PARAM_ARRAY(array)
4817 	ZEND_PARSE_PARAMETERS_END();
4818 
4819 	intervalobj = Z_PHPINTERVAL_P(object);
4820 	myht = Z_ARRVAL_P(array);
4821 
4822 	php_date_interval_initialize_from_hash(&object, &intervalobj, myht);
4823 	restore_custom_dateinterval_properties(object, myht);
4824 }
4825 /* }}} */
4826 
4827 /* {{{ */
PHP_METHOD(DateInterval,__wakeup)4828 PHP_METHOD(DateInterval, __wakeup)
4829 {
4830 	zval             *object = ZEND_THIS;
4831 	php_interval_obj *intobj;
4832 	HashTable        *myht;
4833 
4834 	ZEND_PARSE_PARAMETERS_NONE();
4835 
4836 	intobj = Z_PHPINTERVAL_P(object);
4837 
4838 	myht = Z_OBJPROP_P(object);
4839 
4840 	php_date_interval_initialize_from_hash(&return_value, &intobj, myht);
4841 }
4842 /* }}} */
4843 
date_interval_instantiate_from_time(zval * return_value,timelib_time * time,zend_string * time_str)4844 static void date_interval_instantiate_from_time(zval *return_value, timelib_time *time, zend_string *time_str)
4845 {
4846 	php_interval_obj *diobj;
4847 
4848 	php_date_instantiate(date_ce_interval, return_value);
4849 	diobj = Z_PHPINTERVAL_P(return_value);
4850 	diobj->diff = timelib_rel_time_clone(&time->relative);
4851 	diobj->initialized = 1;
4852 	diobj->civil_or_wall = PHP_DATE_CIVIL;
4853 	diobj->from_string = true;
4854 	diobj->date_string = zend_string_copy(time_str);
4855 }
4856 
4857 /* {{{ Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string */
PHP_FUNCTION(date_interval_create_from_date_string)4858 PHP_FUNCTION(date_interval_create_from_date_string)
4859 {
4860 	zend_string    *time_str = NULL;
4861 	timelib_time   *time;
4862 	timelib_error_container *err = NULL;
4863 
4864 	ZEND_PARSE_PARAMETERS_START(1, 1)
4865 		Z_PARAM_STR(time_str)
4866 	ZEND_PARSE_PARAMETERS_END();
4867 
4868 	time = timelib_strtotime(ZSTR_VAL(time_str), ZSTR_LEN(time_str), &err, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
4869 
4870 	if (err->error_count > 0)  {
4871 		php_error_docref(NULL, E_WARNING, "Unknown or bad format (%s) at position %d (%c): %s", ZSTR_VAL(time_str),
4872 			err->error_messages[0].position, err->error_messages[0].character ? err->error_messages[0].character : ' ', err->error_messages[0].message);
4873 		RETVAL_FALSE;
4874 		goto cleanup;
4875 	}
4876 
4877 	if (time->have_date || time->have_time || time->have_zone) {
4878 		php_error_docref(NULL, E_WARNING, "String '%s' contains non-relative elements", ZSTR_VAL(time_str));
4879 		RETVAL_FALSE;
4880 		goto cleanup;
4881 	}
4882 
4883 	date_interval_instantiate_from_time(return_value, time, time_str);
4884 
4885 cleanup:
4886 	timelib_time_dtor(time);
4887 	timelib_error_container_dtor(err);
4888 }
4889 /* }}} */
4890 
4891 /* {{{ Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string */
PHP_METHOD(DateInterval,createFromDateString)4892 PHP_METHOD(DateInterval, createFromDateString)
4893 {
4894 	zend_string    *time_str = NULL;
4895 	timelib_time   *time;
4896 	timelib_error_container *err = NULL;
4897 
4898 	ZEND_PARSE_PARAMETERS_START(1, 1)
4899 		Z_PARAM_STR(time_str)
4900 	ZEND_PARSE_PARAMETERS_END();
4901 
4902 	time = timelib_strtotime(ZSTR_VAL(time_str), ZSTR_LEN(time_str), &err, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
4903 
4904 	if (err->error_count > 0)  {
4905 		zend_throw_error(date_ce_date_malformed_interval_string_exception, "Unknown or bad format (%s) at position %d (%c): %s", ZSTR_VAL(time_str),
4906 			err->error_messages[0].position, err->error_messages[0].character ? err->error_messages[0].character : ' ', err->error_messages[0].message);
4907 		goto cleanup;
4908 	}
4909 
4910 	if (time->have_date || time->have_time || time->have_zone) {
4911 		zend_throw_error(date_ce_date_malformed_interval_string_exception, "String '%s' contains non-relative elements", ZSTR_VAL(time_str));
4912 		goto cleanup;
4913 	}
4914 
4915 	date_interval_instantiate_from_time(return_value, time, time_str);
4916 
4917 cleanup:
4918 	timelib_time_dtor(time);
4919 	timelib_error_container_dtor(err);
4920 }
4921 /* }}} */
4922 
4923 /* {{{ date_interval_format -  */
date_interval_format(char * format,size_t format_len,timelib_rel_time * t)4924 static zend_string *date_interval_format(char *format, size_t format_len, timelib_rel_time *t)
4925 {
4926 	smart_str            string = {0};
4927 	size_t               i;
4928 	int                  length, have_format_spec = 0;
4929 	char                 buffer[33];
4930 
4931 	if (!format_len) {
4932 		return ZSTR_EMPTY_ALLOC();
4933 	}
4934 
4935 	for (i = 0; i < format_len; i++) {
4936 		if (have_format_spec) {
4937 			switch (format[i]) {
4938 				case 'Y': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->y); break;
4939 				case 'y': length = slprintf(buffer, sizeof(buffer), "%d", (int) t->y); break;
4940 
4941 				case 'M': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->m); break;
4942 				case 'm': length = slprintf(buffer, sizeof(buffer), "%d", (int) t->m); break;
4943 
4944 				case 'D': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->d); break;
4945 				case 'd': length = slprintf(buffer, sizeof(buffer), "%d", (int) t->d); break;
4946 
4947 				case 'H': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->h); break;
4948 				case 'h': length = slprintf(buffer, sizeof(buffer), "%d", (int) t->h); break;
4949 
4950 				case 'I': length = slprintf(buffer, sizeof(buffer), "%02d", (int) t->i); break;
4951 				case 'i': length = slprintf(buffer, sizeof(buffer), "%d", (int) t->i); break;
4952 
4953 				case 'S': length = slprintf(buffer, sizeof(buffer), "%02" ZEND_LONG_FMT_SPEC, (zend_long) t->s); break;
4954 				case 's': length = slprintf(buffer, sizeof(buffer), ZEND_LONG_FMT, (zend_long) t->s); break;
4955 
4956 				case 'F': length = slprintf(buffer, sizeof(buffer), "%06" ZEND_LONG_FMT_SPEC, (zend_long) t->us); break;
4957 				case 'f': length = slprintf(buffer, sizeof(buffer), ZEND_LONG_FMT, (zend_long) t->us); break;
4958 
4959 				case 'a': {
4960 					if ((int) t->days != TIMELIB_UNSET) {
4961 						length = slprintf(buffer, sizeof(buffer), "%d", (int) t->days);
4962 					} else {
4963 						length = slprintf(buffer, sizeof(buffer), "(unknown)");
4964 					}
4965 				} break;
4966 				case 'r': length = slprintf(buffer, sizeof(buffer), "%s", t->invert ? "-" : ""); break;
4967 				case 'R': length = slprintf(buffer, sizeof(buffer), "%c", t->invert ? '-' : '+'); break;
4968 
4969 				case '%': length = slprintf(buffer, sizeof(buffer), "%%"); break;
4970 				default: buffer[0] = '%'; buffer[1] = format[i]; buffer[2] = '\0'; length = 2; break;
4971 			}
4972 			smart_str_appendl(&string, buffer, length);
4973 			have_format_spec = 0;
4974 		} else {
4975 			if (format[i] == '%') {
4976 				have_format_spec = 1;
4977 			} else {
4978 				smart_str_appendc(&string, format[i]);
4979 			}
4980 		}
4981 	}
4982 
4983 	smart_str_0(&string);
4984 
4985 	if (string.s == NULL) {
4986 		return ZSTR_EMPTY_ALLOC();
4987 	}
4988 
4989 	return string.s;
4990 }
4991 /* }}} */
4992 
4993 /* {{{ Formats the interval. */
PHP_FUNCTION(date_interval_format)4994 PHP_FUNCTION(date_interval_format)
4995 {
4996 	zval             *object;
4997 	php_interval_obj *diobj;
4998 	char             *format;
4999 	size_t            format_len;
5000 
5001 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Os", &object, date_ce_interval, &format, &format_len) == FAILURE) {
5002 		RETURN_THROWS();
5003 	}
5004 	diobj = Z_PHPINTERVAL_P(object);
5005 	DATE_CHECK_INITIALIZED(diobj->initialized, Z_OBJCE_P(object));
5006 
5007 	RETURN_STR(date_interval_format(format, format_len, diobj->diff));
5008 }
5009 /* }}} */
5010 
date_period_initialize(timelib_time ** st,timelib_time ** et,timelib_rel_time ** d,zend_long * recurrences,char * format,size_t format_length)5011 static bool date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, zend_long *recurrences, /*const*/ char *format, size_t format_length) /* {{{ */
5012 {
5013 	timelib_time     *b = NULL, *e = NULL;
5014 	timelib_rel_time *p = NULL;
5015 	int               r = 0;
5016 	timelib_error_container *errors;
5017 	bool              retval = false;
5018 
5019 	timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors);
5020 
5021 	if (errors->error_count > 0) {
5022 		retval = false;
5023 		zend_throw_exception_ex(date_ce_date_malformed_period_string_exception, 0, "Unknown or bad format (%s)", format);
5024 		if (b) {
5025 			timelib_time_dtor(b);
5026 		}
5027 		if (e) {
5028 			timelib_time_dtor(e);
5029 		}
5030 		if (p) {
5031 			timelib_rel_time_dtor(p);
5032 		}
5033 	} else {
5034 		*st = b;
5035 		*et = e;
5036 		*d  = p;
5037 		*recurrences = r;
5038 		retval = true;
5039 	}
5040 	timelib_error_container_dtor(errors);
5041 	return retval;
5042 } /* }}} */
5043 
date_period_init_iso8601_string(php_period_obj * dpobj,zend_class_entry * base_ce,char * isostr,size_t isostr_len,zend_long options,zend_long * recurrences)5044 static bool date_period_init_iso8601_string(php_period_obj *dpobj, zend_class_entry* base_ce, char *isostr, size_t isostr_len, zend_long options, zend_long *recurrences)
5045 {
5046 	if (!date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), recurrences, isostr, isostr_len)) {
5047 		return false;
5048 	}
5049 
5050 	if (dpobj->start == NULL) {
5051 		zend_string *func = get_active_function_or_method_name();
5052 		zend_throw_exception_ex(date_ce_date_malformed_period_string_exception, 0, "%s(): ISO interval must contain a start date, \"%s\" given", ZSTR_VAL(func), isostr);
5053 		zend_string_release(func);
5054 		return false;
5055 	}
5056 	if (dpobj->interval == NULL) {
5057 		zend_string *func = get_active_function_or_method_name();
5058 		zend_throw_exception_ex(date_ce_date_malformed_period_string_exception, 0, "%s(): ISO interval must contain an interval, \"%s\" given", ZSTR_VAL(func), isostr);
5059 		zend_string_release(func);
5060 		return false;
5061 	}
5062 	if (dpobj->end == NULL && recurrences == 0) {
5063 		zend_string *func = get_active_function_or_method_name();
5064 		zend_throw_exception_ex(date_ce_date_malformed_period_string_exception, 0, "%s(): ISO interval must contain an end date or a recurrence count, \"%s\" given", ZSTR_VAL(func), isostr);
5065 		zend_string_release(func);
5066 		return false;
5067 	}
5068 
5069 	if (dpobj->start) {
5070 		timelib_update_ts(dpobj->start, NULL);
5071 	}
5072 	if (dpobj->end) {
5073 		timelib_update_ts(dpobj->end, NULL);
5074 	}
5075 	dpobj->start_ce = base_ce;
5076 
5077 	return true;
5078 }
5079 
date_period_init_finish(php_period_obj * dpobj,zend_long options,zend_long recurrences)5080 static bool date_period_init_finish(php_period_obj *dpobj, zend_long options, zend_long recurrences)
5081 {
5082 	if (dpobj->end == NULL && recurrences < 1) {
5083 		zend_string *func = get_active_function_or_method_name();
5084 		zend_throw_exception_ex(date_ce_date_malformed_period_string_exception, 0, "%s(): Recurrence count must be greater than 0", ZSTR_VAL(func));
5085 		zend_string_release(func);
5086 		return false;
5087 	}
5088 
5089 	/* options */
5090 	dpobj->include_start_date = !(options & PHP_DATE_PERIOD_EXCLUDE_START_DATE);
5091 	dpobj->include_end_date = options & PHP_DATE_PERIOD_INCLUDE_END_DATE;
5092 
5093 	/* recurrrences */
5094 	dpobj->recurrences = recurrences + dpobj->include_start_date + dpobj->include_end_date;
5095 
5096 	dpobj->initialized = 1;
5097 
5098 	initialize_date_period_properties(dpobj);
5099 
5100 	return true;
5101 }
5102 
PHP_METHOD(DatePeriod,createFromISO8601String)5103 PHP_METHOD(DatePeriod, createFromISO8601String)
5104 {
5105 	php_period_obj *dpobj;
5106 	zend_long recurrences = 0, options = 0;
5107 	char *isostr = NULL;
5108 	size_t isostr_len = 0;
5109 
5110 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|l", &isostr, &isostr_len, &options) == FAILURE) {
5111 		RETURN_THROWS();
5112 	}
5113 
5114 	object_init_ex(return_value, execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_period);
5115 	dpobj = Z_PHPPERIOD_P(return_value);
5116 
5117 	dpobj->current = NULL;
5118 
5119 	if (!date_period_init_iso8601_string(dpobj, date_ce_immutable, isostr, isostr_len, options, &recurrences)) {
5120 		RETURN_THROWS();
5121 	}
5122 
5123 	if (!date_period_init_finish(dpobj, options, recurrences)) {
5124 		RETURN_THROWS();
5125 	}
5126 }
5127 
5128 /* {{{ Creates new DatePeriod object. */
PHP_METHOD(DatePeriod,__construct)5129 PHP_METHOD(DatePeriod, __construct)
5130 {
5131 	php_period_obj   *dpobj;
5132 	php_date_obj     *dateobj;
5133 	zval *start, *end = NULL, *interval;
5134 	zend_long  recurrences = 0, options = 0;
5135 	char *isostr = NULL;
5136 	size_t   isostr_len = 0;
5137 	timelib_time *clone;
5138 
5139 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "OOl|l", &start, date_ce_interface, &interval, date_ce_interval, &recurrences, &options) == FAILURE) {
5140 		if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "OOO|l", &start, date_ce_interface, &interval, date_ce_interval, &end, date_ce_interface, &options) == FAILURE) {
5141 			if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "s|l", &isostr, &isostr_len, &options) == FAILURE) {
5142 				zend_type_error("DatePeriod::__construct() accepts (DateTimeInterface, DateInterval, int [, int]), or (DateTimeInterface, DateInterval, DateTime [, int]), or (string [, int]) as arguments");
5143 				RETURN_THROWS();
5144 			}
5145 		}
5146 	}
5147 
5148 	dpobj = Z_PHPPERIOD_P(ZEND_THIS);
5149 	dpobj->current = NULL;
5150 
5151 	if (isostr) {
5152 		zend_error(E_DEPRECATED, "Calling DatePeriod::__construct(string $isostr, int $options = 0) is deprecated, "
5153 			"use DatePeriod::createFromISO8601String() instead");
5154 		if (UNEXPECTED(EG(exception))) {
5155 			RETURN_THROWS();
5156 		}
5157 
5158 		if (!date_period_init_iso8601_string(dpobj, date_ce_date, isostr, isostr_len, options, &recurrences)) {
5159 			RETURN_THROWS();
5160 		}
5161 	} else {
5162 		/* check initialisation */
5163 		DATE_CHECK_INITIALIZED(Z_PHPDATE_P(start)->time, date_ce_interface);
5164 		if (end) {
5165 			DATE_CHECK_INITIALIZED(Z_PHPDATE_P(end)->time, date_ce_interface);
5166 		}
5167 
5168 		/* init */
5169 		php_interval_obj *intobj = Z_PHPINTERVAL_P(interval);
5170 
5171 		/* start date */
5172 		dateobj = Z_PHPDATE_P(start);
5173 		clone = timelib_time_ctor();
5174 		memcpy(clone, dateobj->time, sizeof(timelib_time));
5175 		if (dateobj->time->tz_abbr) {
5176 			clone->tz_abbr = timelib_strdup(dateobj->time->tz_abbr);
5177 		}
5178 		if (dateobj->time->tz_info) {
5179 			clone->tz_info = dateobj->time->tz_info;
5180 		}
5181 		dpobj->start = clone;
5182 		dpobj->start_ce = Z_OBJCE_P(start);
5183 
5184 		/* interval */
5185 		dpobj->interval = timelib_rel_time_clone(intobj->diff);
5186 
5187 		/* end date */
5188 		if (end) {
5189 			dateobj = Z_PHPDATE_P(end);
5190 			clone = timelib_time_clone(dateobj->time);
5191 			dpobj->end = clone;
5192 		}
5193 	}
5194 
5195 	if (!date_period_init_finish(dpobj, options, recurrences)) {
5196 		RETURN_THROWS();
5197 	}
5198 }
5199 /* }}} */
5200 
5201 /* {{{ Get start date. */
PHP_METHOD(DatePeriod,getStartDate)5202 PHP_METHOD(DatePeriod, getStartDate)
5203 {
5204 	php_period_obj   *dpobj;
5205 	php_date_obj     *dateobj;
5206 
5207 	ZEND_PARSE_PARAMETERS_NONE();
5208 
5209 	dpobj = Z_PHPPERIOD_P(ZEND_THIS);
5210 	DATE_CHECK_INITIALIZED(dpobj->start, Z_OBJCE_P(ZEND_THIS));
5211 
5212 	php_date_instantiate(dpobj->start_ce, return_value);
5213 	dateobj = Z_PHPDATE_P(return_value);
5214 	dateobj->time = timelib_time_ctor();
5215 	*dateobj->time = *dpobj->start;
5216 	if (dpobj->start->tz_abbr) {
5217 		dateobj->time->tz_abbr = timelib_strdup(dpobj->start->tz_abbr);
5218 	}
5219 	if (dpobj->start->tz_info) {
5220 		dateobj->time->tz_info = dpobj->start->tz_info;
5221 	}
5222 }
5223 /* }}} */
5224 
5225 /* {{{ Get end date. */
PHP_METHOD(DatePeriod,getEndDate)5226 PHP_METHOD(DatePeriod, getEndDate)
5227 {
5228 	php_period_obj   *dpobj;
5229 	php_date_obj     *dateobj;
5230 
5231 	ZEND_PARSE_PARAMETERS_NONE();
5232 
5233 	dpobj = Z_PHPPERIOD_P(ZEND_THIS);
5234 
5235 	if (!dpobj->end) {
5236 		return;
5237 	}
5238 
5239 	php_date_instantiate(dpobj->start_ce, return_value);
5240 	dateobj = Z_PHPDATE_P(return_value);
5241 	dateobj->time = timelib_time_ctor();
5242 	*dateobj->time = *dpobj->end;
5243 	if (dpobj->end->tz_abbr) {
5244 			dateobj->time->tz_abbr = timelib_strdup(dpobj->end->tz_abbr);
5245 	}
5246 	if (dpobj->end->tz_info) {
5247 			dateobj->time->tz_info = dpobj->end->tz_info;
5248 	}
5249 }
5250 /* }}} */
5251 
5252 /* {{{ Get date interval. */
PHP_METHOD(DatePeriod,getDateInterval)5253 PHP_METHOD(DatePeriod, getDateInterval)
5254 {
5255 	php_period_obj   *dpobj;
5256 	php_interval_obj *diobj;
5257 
5258 	ZEND_PARSE_PARAMETERS_NONE();
5259 
5260 	dpobj = Z_PHPPERIOD_P(ZEND_THIS);
5261 	DATE_CHECK_INITIALIZED(dpobj->interval, Z_OBJCE_P(ZEND_THIS));
5262 
5263 	php_date_instantiate(date_ce_interval, return_value);
5264 	diobj = Z_PHPINTERVAL_P(return_value);
5265 	diobj->diff = timelib_rel_time_clone(dpobj->interval);
5266 	diobj->initialized = 1;
5267 }
5268 /* }}} */
5269 
5270 /* {{{ Get recurrences. */
PHP_METHOD(DatePeriod,getRecurrences)5271 PHP_METHOD(DatePeriod, getRecurrences)
5272 {
5273 	php_period_obj   *dpobj;
5274 
5275 	ZEND_PARSE_PARAMETERS_NONE();
5276 
5277 	dpobj = Z_PHPPERIOD_P(ZEND_THIS);
5278 
5279 	if (0 == dpobj->recurrences - dpobj->include_start_date - dpobj->include_end_date) {
5280 		return;
5281 	}
5282 
5283 	RETURN_LONG(dpobj->recurrences - dpobj->include_start_date - dpobj->include_end_date);
5284 }
5285 /* }}} */
5286 
PHP_METHOD(DatePeriod,getIterator)5287 PHP_METHOD(DatePeriod, getIterator)
5288 {
5289 	ZEND_PARSE_PARAMETERS_NONE();
5290 
5291 	zend_create_internal_iterator_zval(return_value, ZEND_THIS);
5292 }
5293 
check_id_allowed(char * id,zend_long what)5294 static int check_id_allowed(char *id, zend_long what) /* {{{ */
5295 {
5296 	if ((what & PHP_DATE_TIMEZONE_GROUP_AFRICA)     && strncasecmp(id, "Africa/",      7) == 0) return 1;
5297 	if ((what & PHP_DATE_TIMEZONE_GROUP_AMERICA)    && strncasecmp(id, "America/",     8) == 0) return 1;
5298 	if ((what & PHP_DATE_TIMEZONE_GROUP_ANTARCTICA) && strncasecmp(id, "Antarctica/", 11) == 0) return 1;
5299 	if ((what & PHP_DATE_TIMEZONE_GROUP_ARCTIC)     && strncasecmp(id, "Arctic/",      7) == 0) return 1;
5300 	if ((what & PHP_DATE_TIMEZONE_GROUP_ASIA)       && strncasecmp(id, "Asia/",        5) == 0) return 1;
5301 	if ((what & PHP_DATE_TIMEZONE_GROUP_ATLANTIC)   && strncasecmp(id, "Atlantic/",    9) == 0) return 1;
5302 	if ((what & PHP_DATE_TIMEZONE_GROUP_AUSTRALIA)  && strncasecmp(id, "Australia/",  10) == 0) return 1;
5303 	if ((what & PHP_DATE_TIMEZONE_GROUP_EUROPE)     && strncasecmp(id, "Europe/",      7) == 0) return 1;
5304 	if ((what & PHP_DATE_TIMEZONE_GROUP_INDIAN)     && strncasecmp(id, "Indian/",      7) == 0) return 1;
5305 	if ((what & PHP_DATE_TIMEZONE_GROUP_PACIFIC)    && strncasecmp(id, "Pacific/",     8) == 0) return 1;
5306 	if ((what & PHP_DATE_TIMEZONE_GROUP_UTC)        && strncasecmp(id, "UTC",          3) == 0) return 1;
5307 	return 0;
5308 } /* }}} */
5309 
5310 /* {{{ Returns numerically index array with all timezone identifiers. */
PHP_FUNCTION(timezone_identifiers_list)5311 PHP_FUNCTION(timezone_identifiers_list)
5312 {
5313 	const timelib_tzdb             *tzdb;
5314 	const timelib_tzdb_index_entry *table;
5315 	int                             i, item_count;
5316 	zend_long                       what = PHP_DATE_TIMEZONE_GROUP_ALL;
5317 	char                           *option = NULL;
5318 	size_t                          option_len = 0;
5319 
5320 	ZEND_PARSE_PARAMETERS_START(0, 2)
5321 		Z_PARAM_OPTIONAL
5322 		Z_PARAM_LONG(what)
5323 		Z_PARAM_STRING_OR_NULL(option, option_len)
5324 	ZEND_PARSE_PARAMETERS_END();
5325 
5326 	/* Extra validation */
5327 	if (what == PHP_DATE_TIMEZONE_PER_COUNTRY && option_len != 2) {
5328 		zend_argument_value_error(2, "must be a two-letter ISO 3166-1 compatible country code "
5329 			"when argument #1 ($timezoneGroup) is DateTimeZone::PER_COUNTRY");
5330 		RETURN_THROWS();
5331 	}
5332 
5333 	tzdb = DATE_TIMEZONEDB;
5334 	table = timelib_timezone_identifiers_list((timelib_tzdb*) tzdb, &item_count);
5335 
5336 	array_init(return_value);
5337 
5338 	for (i = 0; i < item_count; ++i) {
5339 		if (what == PHP_DATE_TIMEZONE_PER_COUNTRY) {
5340 			if (tzdb->data[table[i].pos + 5] == option[0] && tzdb->data[table[i].pos + 6] == option[1]) {
5341 				add_next_index_string(return_value, table[i].id);
5342 			}
5343 		} else if (what == PHP_DATE_TIMEZONE_GROUP_ALL_W_BC || (check_id_allowed(table[i].id, what) && (tzdb->data[table[i].pos + 4] == '\1'))) {
5344 			add_next_index_string(return_value, table[i].id);
5345 		}
5346 	};
5347 }
5348 /* }}} */
5349 
5350 /* {{{ Returns the Olson database version number. */
PHP_FUNCTION(timezone_version_get)5351 PHP_FUNCTION(timezone_version_get)
5352 {
5353 	const timelib_tzdb *tzdb;
5354 
5355 	ZEND_PARSE_PARAMETERS_NONE();
5356 
5357 	tzdb = DATE_TIMEZONEDB;
5358 	RETURN_STRING(tzdb->version);
5359 }
5360 /* }}} */
5361 
5362 /* {{{ Returns associative array containing dst, offset and the timezone name */
PHP_FUNCTION(timezone_abbreviations_list)5363 PHP_FUNCTION(timezone_abbreviations_list)
5364 {
5365 	const timelib_tz_lookup_table *table, *entry;
5366 	zval                          element, *abbr_array_p, abbr_array;
5367 
5368 	ZEND_PARSE_PARAMETERS_NONE();
5369 
5370 	table = timelib_timezone_abbreviations_list();
5371 	array_init(return_value);
5372 	entry = table;
5373 
5374 	do {
5375 		array_init(&element);
5376 		add_assoc_bool_ex(&element, "dst", sizeof("dst") -1, entry->type);
5377 		add_assoc_long_ex(&element, "offset", sizeof("offset") - 1, entry->gmtoffset);
5378 		if (entry->full_tz_name) {
5379 			add_assoc_string_ex(&element, "timezone_id", sizeof("timezone_id") - 1, entry->full_tz_name);
5380 		} else {
5381 			add_assoc_null_ex(&element, "timezone_id", sizeof("timezone_id") - 1);
5382 		}
5383 
5384 		abbr_array_p = zend_hash_str_find(Z_ARRVAL_P(return_value), entry->name, strlen(entry->name));
5385 		if (!abbr_array_p) {
5386 			array_init(&abbr_array);
5387 			add_assoc_zval(return_value, entry->name, &abbr_array);
5388 		} else {
5389 			ZVAL_COPY_VALUE(&abbr_array, abbr_array_p);
5390 		}
5391 		add_next_index_zval(&abbr_array, &element);
5392 		entry++;
5393 	} while (entry->name);
5394 }
5395 /* }}} */
5396 
5397 /* {{{ Sets the default timezone used by all date/time functions in a script */
PHP_FUNCTION(date_default_timezone_set)5398 PHP_FUNCTION(date_default_timezone_set)
5399 {
5400 	char *zone;
5401 	size_t   zone_len;
5402 
5403 	ZEND_PARSE_PARAMETERS_START(1, 1)
5404 		Z_PARAM_STRING(zone, zone_len)
5405 	ZEND_PARSE_PARAMETERS_END();
5406 
5407 	if (!timelib_timezone_id_is_valid(zone, DATE_TIMEZONEDB)) {
5408 		php_error_docref(NULL, E_NOTICE, "Timezone ID '%s' is invalid", zone);
5409 		RETURN_FALSE;
5410 	}
5411 	if (DATEG(timezone)) {
5412 		efree(DATEG(timezone));
5413 		DATEG(timezone) = NULL;
5414 	}
5415 	DATEG(timezone) = estrndup(zone, zone_len);
5416 	RETURN_TRUE;
5417 }
5418 /* }}} */
5419 
5420 /* {{{ Gets the default timezone used by all date/time functions in a script */
PHP_FUNCTION(date_default_timezone_get)5421 PHP_FUNCTION(date_default_timezone_get)
5422 {
5423 	timelib_tzinfo *default_tz;
5424 	ZEND_PARSE_PARAMETERS_NONE();
5425 
5426 	default_tz = get_timezone_info();
5427 	if (!default_tz) {
5428 		RETURN_THROWS();
5429 	}
5430 	RETVAL_STRING(default_tz->name);
5431 }
5432 /* }}} */
5433 
5434 /* {{{ php_do_date_sunrise_sunset
5435  *  Common for date_sunrise() and date_sunset() functions
5436  */
php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS,bool calc_sunset)5437 static void php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS, bool calc_sunset)
5438 {
5439 	double latitude, longitude, zenith, gmt_offset, altitude;
5440 	bool latitude_is_null = 1, longitude_is_null = 1, zenith_is_null = 1, gmt_offset_is_null = 1;
5441 	double h_rise, h_set, N;
5442 	timelib_sll rise, set, transit;
5443 	zend_long time, retformat = SUNFUNCS_RET_STRING;
5444 	int             rs;
5445 	timelib_time   *t;
5446 	timelib_tzinfo *tzi;
5447 	zend_string    *retstr;
5448 
5449 	ZEND_PARSE_PARAMETERS_START(1, 6)
5450 		Z_PARAM_LONG(time)
5451 		Z_PARAM_OPTIONAL
5452 		Z_PARAM_LONG(retformat)
5453 		Z_PARAM_DOUBLE_OR_NULL(latitude, latitude_is_null)
5454 		Z_PARAM_DOUBLE_OR_NULL(longitude, longitude_is_null)
5455 		Z_PARAM_DOUBLE_OR_NULL(zenith, zenith_is_null)
5456 		Z_PARAM_DOUBLE_OR_NULL(gmt_offset, gmt_offset_is_null)
5457 	ZEND_PARSE_PARAMETERS_END();
5458 
5459 	if (latitude_is_null) {
5460 		latitude = INI_FLT("date.default_latitude");
5461 	}
5462 
5463 	if (longitude_is_null) {
5464 		longitude = INI_FLT("date.default_longitude");
5465 	}
5466 
5467 	if (zenith_is_null) {
5468 		if (calc_sunset) {
5469 			zenith = INI_FLT("date.sunset_zenith");
5470 		} else {
5471 			zenith = INI_FLT("date.sunrise_zenith");
5472 		}
5473 	}
5474 
5475 	if (retformat != SUNFUNCS_RET_TIMESTAMP &&
5476 		retformat != SUNFUNCS_RET_STRING &&
5477 		retformat != SUNFUNCS_RET_DOUBLE)
5478 	{
5479 		zend_argument_value_error(2, "must be one of SUNFUNCS_RET_TIMESTAMP, SUNFUNCS_RET_STRING, or SUNFUNCS_RET_DOUBLE");
5480 		RETURN_THROWS();
5481 	}
5482 	altitude = 90 - zenith;
5483 
5484 	/* Initialize time struct */
5485 	tzi = get_timezone_info();
5486 	if (!tzi) {
5487 		RETURN_THROWS();
5488 	}
5489 	t = timelib_time_ctor();
5490 	t->tz_info = tzi;
5491 	t->zone_type = TIMELIB_ZONETYPE_ID;
5492 
5493 	if (gmt_offset_is_null) {
5494 		gmt_offset = timelib_get_current_offset(t) / 3600;
5495 	}
5496 
5497 	timelib_unixtime2local(t, time);
5498 	rs = timelib_astro_rise_set_altitude(t, longitude, latitude, altitude, 1, &h_rise, &h_set, &rise, &set, &transit);
5499 	timelib_time_dtor(t);
5500 
5501 	if (rs != 0) {
5502 		RETURN_FALSE;
5503 	}
5504 
5505 	if (retformat == SUNFUNCS_RET_TIMESTAMP) {
5506 		RETURN_LONG(calc_sunset ? set : rise);
5507 	}
5508 	N = (calc_sunset ? h_set : h_rise) + gmt_offset;
5509 
5510 	if (N > 24 || N < 0) {
5511 		N -= floor(N / 24) * 24;
5512 	}
5513 
5514 	switch (retformat) {
5515 		case SUNFUNCS_RET_STRING:
5516 			retstr = strpprintf(0, "%02d:%02d", (int) N, (int) (60 * (N - (int) N)));
5517 			RETURN_NEW_STR(retstr);
5518 			break;
5519 		case SUNFUNCS_RET_DOUBLE:
5520 			RETURN_DOUBLE(N);
5521 			break;
5522 	}
5523 }
5524 /* }}} */
5525 
5526 /* {{{ Returns time of sunrise for a given day and location */
PHP_FUNCTION(date_sunrise)5527 PHP_FUNCTION(date_sunrise)
5528 {
5529 	php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
5530 }
5531 /* }}} */
5532 
5533 /* {{{ Returns time of sunset for a given day and location */
PHP_FUNCTION(date_sunset)5534 PHP_FUNCTION(date_sunset)
5535 {
5536 	php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
5537 }
5538 /* }}} */
5539 
5540 /* {{{ Returns an array with information about sun set/rise and twilight begin/end */
PHP_FUNCTION(date_sun_info)5541 PHP_FUNCTION(date_sun_info)
5542 {
5543 	zend_long       time;
5544 	double          latitude, longitude;
5545 	timelib_time   *t, *t2;
5546 	timelib_tzinfo *tzi;
5547 	int             rs;
5548 	timelib_sll     rise, set, transit;
5549 	int             dummy;
5550 	double          ddummy;
5551 
5552 	ZEND_PARSE_PARAMETERS_START(3, 3)
5553 		Z_PARAM_LONG(time)
5554 		Z_PARAM_DOUBLE(latitude)
5555 		Z_PARAM_DOUBLE(longitude)
5556 	ZEND_PARSE_PARAMETERS_END();
5557 
5558 	/* Initialize time struct */
5559 	tzi = get_timezone_info();
5560 	if (!tzi) {
5561 		RETURN_THROWS();
5562 	}
5563 	t = timelib_time_ctor();
5564 	t->tz_info = tzi;
5565 	t->zone_type = TIMELIB_ZONETYPE_ID;
5566 	timelib_unixtime2local(t, time);
5567 
5568 	/* Setup */
5569 	t2 = timelib_time_ctor();
5570 	array_init(return_value);
5571 
5572 	/* Get sun up/down and transit */
5573 	rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -50.0/60, 1, &ddummy, &ddummy, &rise, &set, &transit);
5574 	switch (rs) {
5575 		case -1: /* always below */
5576 			add_assoc_bool(return_value, "sunrise", 0);
5577 			add_assoc_bool(return_value, "sunset", 0);
5578 			break;
5579 		case 1: /* always above */
5580 			add_assoc_bool(return_value, "sunrise", 1);
5581 			add_assoc_bool(return_value, "sunset", 1);
5582 			break;
5583 		default:
5584 			t2->sse = rise;
5585 			add_assoc_long(return_value, "sunrise", timelib_date_to_int(t2, &dummy));
5586 			t2->sse = set;
5587 			add_assoc_long(return_value, "sunset", timelib_date_to_int(t2, &dummy));
5588 	}
5589 	t2->sse = transit;
5590 	add_assoc_long(return_value, "transit", timelib_date_to_int(t2, &dummy));
5591 
5592 	/* Get civil twilight */
5593 	rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -6.0, 0, &ddummy, &ddummy, &rise, &set, &transit);
5594 	switch (rs) {
5595 		case -1: /* always below */
5596 			add_assoc_bool(return_value, "civil_twilight_begin", 0);
5597 			add_assoc_bool(return_value, "civil_twilight_end", 0);
5598 			break;
5599 		case 1: /* always above */
5600 			add_assoc_bool(return_value, "civil_twilight_begin", 1);
5601 			add_assoc_bool(return_value, "civil_twilight_end", 1);
5602 			break;
5603 		default:
5604 			t2->sse = rise;
5605 			add_assoc_long(return_value, "civil_twilight_begin", timelib_date_to_int(t2, &dummy));
5606 			t2->sse = set;
5607 			add_assoc_long(return_value, "civil_twilight_end", timelib_date_to_int(t2, &dummy));
5608 	}
5609 
5610 	/* Get nautical twilight */
5611 	rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -12.0, 0, &ddummy, &ddummy, &rise, &set, &transit);
5612 	switch (rs) {
5613 		case -1: /* always below */
5614 			add_assoc_bool(return_value, "nautical_twilight_begin", 0);
5615 			add_assoc_bool(return_value, "nautical_twilight_end", 0);
5616 			break;
5617 		case 1: /* always above */
5618 			add_assoc_bool(return_value, "nautical_twilight_begin", 1);
5619 			add_assoc_bool(return_value, "nautical_twilight_end", 1);
5620 			break;
5621 		default:
5622 			t2->sse = rise;
5623 			add_assoc_long(return_value, "nautical_twilight_begin", timelib_date_to_int(t2, &dummy));
5624 			t2->sse = set;
5625 			add_assoc_long(return_value, "nautical_twilight_end", timelib_date_to_int(t2, &dummy));
5626 	}
5627 
5628 	/* Get astronomical twilight */
5629 	rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -18.0, 0, &ddummy, &ddummy, &rise, &set, &transit);
5630 	switch (rs) {
5631 		case -1: /* always below */
5632 			add_assoc_bool(return_value, "astronomical_twilight_begin", 0);
5633 			add_assoc_bool(return_value, "astronomical_twilight_end", 0);
5634 			break;
5635 		case 1: /* always above */
5636 			add_assoc_bool(return_value, "astronomical_twilight_begin", 1);
5637 			add_assoc_bool(return_value, "astronomical_twilight_end", 1);
5638 			break;
5639 		default:
5640 			t2->sse = rise;
5641 			add_assoc_long(return_value, "astronomical_twilight_begin", timelib_date_to_int(t2, &dummy));
5642 			t2->sse = set;
5643 			add_assoc_long(return_value, "astronomical_twilight_end", timelib_date_to_int(t2, &dummy));
5644 	}
5645 	timelib_time_dtor(t);
5646 	timelib_time_dtor(t2);
5647 }
5648 /* }}} */
5649 
date_object_get_gc_period(zend_object * object,zval ** table,int * n)5650 static HashTable *date_object_get_gc_period(zend_object *object, zval **table, int *n) /* {{{ */
5651 {
5652 	*table = NULL;
5653 	*n = 0;
5654 	return zend_std_get_properties(object);
5655 } /* }}} */
5656 
date_period_object_to_hash(php_period_obj * period_obj,HashTable * props)5657 static void date_period_object_to_hash(php_period_obj *period_obj, HashTable *props)
5658 {
5659 	zval zv;
5660 
5661 	create_date_period_datetime(period_obj->start, period_obj->start_ce, &zv);
5662 	zend_hash_str_update(props, "start", sizeof("start")-1, &zv);
5663 
5664 	create_date_period_datetime(period_obj->current, period_obj->start_ce, &zv);
5665 	zend_hash_str_update(props, "current", sizeof("current")-1, &zv);
5666 
5667 	create_date_period_datetime(period_obj->end, period_obj->start_ce, &zv);
5668 	zend_hash_str_update(props, "end", sizeof("end")-1, &zv);
5669 
5670 	create_date_period_interval(period_obj->interval, &zv);
5671 	zend_hash_str_update(props, "interval", sizeof("interval")-1, &zv);
5672 
5673 	/* converted to larger type (int->long); must check when unserializing */
5674 	ZVAL_LONG(&zv, (zend_long) period_obj->recurrences);
5675 	zend_hash_str_update(props, "recurrences", sizeof("recurrences")-1, &zv);
5676 
5677 	ZVAL_BOOL(&zv, period_obj->include_start_date);
5678 	zend_hash_str_update(props, "include_start_date", sizeof("include_start_date")-1, &zv);
5679 
5680 	ZVAL_BOOL(&zv, period_obj->include_end_date);
5681 	zend_hash_str_update(props, "include_end_date", sizeof("include_end_date")-1, &zv);
5682 }
5683 
php_date_period_initialize_from_hash(php_period_obj * period_obj,HashTable * myht)5684 static bool php_date_period_initialize_from_hash(php_period_obj *period_obj, HashTable *myht) /* {{{ */
5685 {
5686 	zval *ht_entry;
5687 
5688 	/* this function does no rollback on error */
5689 
5690 	ht_entry = zend_hash_str_find(myht, "start", sizeof("start")-1);
5691 	if (ht_entry) {
5692 		if (Z_TYPE_P(ht_entry) == IS_OBJECT && instanceof_function(Z_OBJCE_P(ht_entry), date_ce_interface)) {
5693 			php_date_obj *date_obj;
5694 			date_obj = Z_PHPDATE_P(ht_entry);
5695 
5696 			if (!date_obj->time) {
5697 				return 0;
5698 			}
5699 
5700 			if (period_obj->start != NULL) {
5701 				timelib_time_dtor(period_obj->start);
5702 			}
5703 			period_obj->start = timelib_time_clone(date_obj->time);
5704 			period_obj->start_ce = Z_OBJCE_P(ht_entry);
5705 		} else if (Z_TYPE_P(ht_entry) != IS_NULL) {
5706 			return 0;
5707 		}
5708 	} else {
5709 		return 0;
5710 	}
5711 
5712 	ht_entry = zend_hash_str_find(myht, "end", sizeof("end")-1);
5713 	if (ht_entry) {
5714 		if (Z_TYPE_P(ht_entry) == IS_OBJECT && instanceof_function(Z_OBJCE_P(ht_entry), date_ce_interface)) {
5715 			php_date_obj *date_obj;
5716 			date_obj = Z_PHPDATE_P(ht_entry);
5717 
5718 			if (!date_obj->time) {
5719 				return 0;
5720 			}
5721 
5722 			if (period_obj->end != NULL) {
5723 				timelib_time_dtor(period_obj->end);
5724 			}
5725 			period_obj->end = timelib_time_clone(date_obj->time);
5726 		} else if (Z_TYPE_P(ht_entry) != IS_NULL) {
5727 			return 0;
5728 		}
5729 	} else {
5730 		return 0;
5731 	}
5732 
5733 	ht_entry = zend_hash_str_find(myht, "current", sizeof("current")-1);
5734 	if (ht_entry) {
5735 		if (Z_TYPE_P(ht_entry) == IS_OBJECT && instanceof_function(Z_OBJCE_P(ht_entry), date_ce_interface)) {
5736 			php_date_obj *date_obj;
5737 			date_obj = Z_PHPDATE_P(ht_entry);
5738 
5739 			if (!date_obj->time) {
5740 				return 0;
5741 			}
5742 
5743 			if (period_obj->current != NULL) {
5744 				timelib_time_dtor(period_obj->current);
5745 			}
5746 			period_obj->current = timelib_time_clone(date_obj->time);
5747 		} else if (Z_TYPE_P(ht_entry) != IS_NULL)  {
5748 			return 0;
5749 		}
5750 	} else {
5751 		return 0;
5752 	}
5753 
5754 	ht_entry = zend_hash_str_find(myht, "interval", sizeof("interval")-1);
5755 	if (ht_entry) {
5756 		if (Z_TYPE_P(ht_entry) == IS_OBJECT && Z_OBJCE_P(ht_entry) == date_ce_interval) {
5757 			php_interval_obj *interval_obj;
5758 			interval_obj = Z_PHPINTERVAL_P(ht_entry);
5759 
5760 			if (!interval_obj->initialized) {
5761 				return 0;
5762 			}
5763 
5764 			if (period_obj->interval != NULL) {
5765 				timelib_rel_time_dtor(period_obj->interval);
5766 			}
5767 			period_obj->interval = timelib_rel_time_clone(interval_obj->diff);
5768 		} else { /* interval is required */
5769 			return 0;
5770 		}
5771 	} else {
5772 		return 0;
5773 	}
5774 
5775 	ht_entry = zend_hash_str_find(myht, "recurrences", sizeof("recurrences")-1);
5776 	if (ht_entry &&
5777 			Z_TYPE_P(ht_entry) == IS_LONG && Z_LVAL_P(ht_entry) >= 0 && Z_LVAL_P(ht_entry) <= INT_MAX) {
5778 		period_obj->recurrences = Z_LVAL_P(ht_entry);
5779 	} else {
5780 		return 0;
5781 	}
5782 
5783 	ht_entry = zend_hash_str_find(myht, "include_start_date", sizeof("include_start_date")-1);
5784 	if (ht_entry &&
5785 			(Z_TYPE_P(ht_entry) == IS_FALSE || Z_TYPE_P(ht_entry) == IS_TRUE)) {
5786 		period_obj->include_start_date = (Z_TYPE_P(ht_entry) == IS_TRUE);
5787 	} else {
5788 		return 0;
5789 	}
5790 
5791 	ht_entry = zend_hash_str_find(myht, "include_end_date", sizeof("include_end_date")-1);
5792 	if (ht_entry &&
5793 			(Z_TYPE_P(ht_entry) == IS_FALSE || Z_TYPE_P(ht_entry) == IS_TRUE)) {
5794 		period_obj->include_end_date = (Z_TYPE_P(ht_entry) == IS_TRUE);
5795 	} else {
5796 		return 0;
5797 	}
5798 
5799 	period_obj->initialized = 1;
5800 
5801 	initialize_date_period_properties(period_obj);
5802 
5803 	return 1;
5804 } /* }}} */
5805 
5806 /* {{{ */
PHP_METHOD(DatePeriod,__set_state)5807 PHP_METHOD(DatePeriod, __set_state)
5808 {
5809 	php_period_obj   *period_obj;
5810 	zval             *array;
5811 	HashTable        *myht;
5812 
5813 	ZEND_PARSE_PARAMETERS_START(1, 1)
5814 		Z_PARAM_ARRAY(array)
5815 	ZEND_PARSE_PARAMETERS_END();
5816 
5817 	myht = Z_ARRVAL_P(array);
5818 
5819 	object_init_ex(return_value, date_ce_period);
5820 	period_obj = Z_PHPPERIOD_P(return_value);
5821 	if (!php_date_period_initialize_from_hash(period_obj, myht)) {
5822 		zend_throw_error(NULL, "Invalid serialization data for DatePeriod object");
5823 	}
5824 }
5825 /* }}} */
5826 
5827 /* {{{ */
PHP_METHOD(DatePeriod,__serialize)5828 PHP_METHOD(DatePeriod, __serialize)
5829 {
5830 	zval             *object = ZEND_THIS;
5831 	php_period_obj   *period_obj;
5832 	HashTable        *myht;
5833 
5834 	ZEND_PARSE_PARAMETERS_NONE();
5835 
5836 	period_obj = Z_PHPPERIOD_P(object);
5837 	DATE_CHECK_INITIALIZED(period_obj->start, Z_OBJCE_P(object));
5838 
5839 	array_init(return_value);
5840 	myht = Z_ARRVAL_P(return_value);
5841 	date_period_object_to_hash(period_obj, myht);
5842 
5843 	add_common_properties(myht, &period_obj->std);
5844 }
5845 /* }}} */
5846 
5847 /* {{{ date_period_is_internal_property
5848  *  Common for date_period_read_property(), date_period_write_property(), and
5849  *  restore_custom_dateperiod_properties functions
5850  */
date_period_is_internal_property(zend_string * name)5851 static bool date_period_is_internal_property(zend_string *name)
5852 {
5853 	if (
5854 		zend_string_equals_literal(name, "start") ||
5855 		zend_string_equals_literal(name, "current") ||
5856 		zend_string_equals_literal(name, "end") ||
5857 		zend_string_equals_literal(name, "interval") ||
5858 		zend_string_equals_literal(name, "recurrences") ||
5859 		zend_string_equals_literal(name, "include_start_date") ||
5860 		zend_string_equals_literal(name, "include_end_date")
5861 	) {
5862 		return 1;
5863 	}
5864 	return 0;
5865 }
5866 /* }}} */
5867 
restore_custom_dateperiod_properties(zval * object,HashTable * myht)5868 static void restore_custom_dateperiod_properties(zval *object, HashTable *myht)
5869 {
5870 	zend_string      *prop_name;
5871 	zval             *prop_val;
5872 
5873 	ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(myht, prop_name, prop_val) {
5874 		if (!prop_name || (Z_TYPE_P(prop_val) == IS_REFERENCE) || date_period_is_internal_property(prop_name)) {
5875 			continue;
5876 		}
5877 		update_property(Z_OBJ_P(object), prop_name, prop_val);
5878 	} ZEND_HASH_FOREACH_END();
5879 }
5880 
5881 /* {{{ */
PHP_METHOD(DatePeriod,__unserialize)5882 PHP_METHOD(DatePeriod, __unserialize)
5883 {
5884 	zval             *object = ZEND_THIS;
5885 	php_period_obj   *period_obj;
5886 	zval             *array;
5887 	HashTable        *myht;
5888 
5889 	ZEND_PARSE_PARAMETERS_START(1, 1)
5890 		Z_PARAM_ARRAY(array)
5891 	ZEND_PARSE_PARAMETERS_END();
5892 
5893 	period_obj = Z_PHPPERIOD_P(object);
5894 	myht = Z_ARRVAL_P(array);
5895 
5896 	if (!php_date_period_initialize_from_hash(period_obj, myht)) {
5897 		zend_throw_error(NULL, "Invalid serialization data for DatePeriod object");
5898 	}
5899 	restore_custom_dateperiod_properties(object, myht);
5900 }
5901 /* }}} */
5902 
5903 /* {{{ */
PHP_METHOD(DatePeriod,__wakeup)5904 PHP_METHOD(DatePeriod, __wakeup)
5905 {
5906 	zval             *object = ZEND_THIS;
5907 	php_period_obj   *period_obj;
5908 	HashTable        *myht;
5909 
5910 	ZEND_PARSE_PARAMETERS_NONE();
5911 
5912 	period_obj = Z_PHPPERIOD_P(object);
5913 
5914 	myht = Z_OBJPROP_P(object);
5915 
5916 	if (!php_date_period_initialize_from_hash(period_obj, myht)) {
5917 		zend_throw_error(NULL, "Invalid serialization data for DatePeriod object");
5918 	}
5919 }
5920 /* }}} */
5921 
5922 /* {{{ date_period_read_property */
date_period_read_property(zend_object * object,zend_string * name,int type,void ** cache_slot,zval * rv)5923 static zval *date_period_read_property(zend_object *object, zend_string *name, int type, void **cache_slot, zval *rv)
5924 {
5925 	if (type != BP_VAR_IS && type != BP_VAR_R) {
5926 		if (date_period_is_internal_property(name)) {
5927 			zend_throw_error(NULL, "Cannot modify readonly property DatePeriod::$%s", ZSTR_VAL(name));
5928 			return &EG(uninitialized_zval);
5929 		}
5930 	}
5931 
5932 	return zend_std_read_property(object, name, type, cache_slot, rv);
5933 }
5934 /* }}} */
5935 
date_period_write_property(zend_object * object,zend_string * name,zval * value,void ** cache_slot)5936 static zval *date_period_write_property(zend_object *object, zend_string *name, zval *value, void **cache_slot)
5937 {
5938 	if (date_period_is_internal_property(name)) {
5939 		zend_throw_error(NULL, "Cannot modify readonly property DatePeriod::$%s", ZSTR_VAL(name));
5940 		return value;
5941 	}
5942 
5943 	return zend_std_write_property(object, name, value, cache_slot);
5944 }
5945 
date_period_get_property_ptr_ptr(zend_object * object,zend_string * name,int type,void ** cache_slot)5946 static zval *date_period_get_property_ptr_ptr(zend_object *object, zend_string *name, int type, void **cache_slot)
5947 {
5948 	if (date_period_is_internal_property(name)) {
5949 		zend_throw_error(NULL, "Cannot modify readonly property DatePeriod::$%s", ZSTR_VAL(name));
5950 		return &EG(error_zval);
5951 	}
5952 
5953 	return zend_std_get_property_ptr_ptr(object, name, type, cache_slot);
5954 }
5955