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