xref: /php-src/ext/date/php_date.c (revision 16c0e575)
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_main.h"
19 #include "php_ini.h"
20 #include "ext/standard/info.h"
21 #include "ext/standard/php_versioning.h"
22 #include "php_date.h"
23 #include "zend_attributes.h"
24 #include "zend_interfaces.h"
25 #include "zend_exceptions.h"
26 #include "lib/timelib.h"
27 #include "lib/timelib_private.h"
28 #ifndef PHP_WIN32
29 #include <time.h>
30 #else
31 #include "win32/time.h"
32 #endif
33 
34 #ifdef PHP_WIN32
php_date_llabs(__int64 i)35 static __inline __int64 php_date_llabs( __int64 i ) { return i >= 0? i: -i; }
36 #elif defined(__GNUC__) && __GNUC__ < 3
php_date_llabs(__int64_t i)37 static __inline __int64_t php_date_llabs( __int64_t i ) { return i >= 0 ? i : -i; }
38 #else
php_date_llabs(long long i)39 static inline long long php_date_llabs( long long i ) { return i >= 0 ? i : -i; }
40 #endif
41 
42 #ifdef PHP_WIN32
43 #define DATE_I64_BUF_LEN 65
44 # define DATE_I64A(i, s, len) _i64toa_s(i, s, len, 10)
45 # define DATE_A64I(i, s) i = _atoi64(s)
46 #else
47 #define DATE_I64_BUF_LEN 65
48 # define DATE_I64A(i, s, len) \
49 	do { \
50 		int st = snprintf(s, len, "%lld", i); \
51 		s[st] = '\0'; \
52 	} while (0);
53 #define DATE_A64I(i, s) i = strtoll(s, NULL, 10)
54 #endif
55 
php_time(void)56 PHPAPI time_t php_time(void)
57 {
58 #ifdef HAVE_GETTIMEOFDAY
59 	struct timeval tm;
60 
61 	if (UNEXPECTED(gettimeofday(&tm, NULL) != SUCCESS)) {
62 		/* fallback, can't reasonably happen */
63 		return time(NULL);
64 	}
65 
66 	return tm.tv_sec;
67 #else
68 	return time(NULL);
69 #endif
70 }
71 
72 /*
73  * RFC822, Section 5.1: http://www.ietf.org/rfc/rfc822.txt
74  *  date-time   =  [ day "," ] date time        ; dd mm yy hh:mm:ss zzz
75  *  day         =  "Mon"  / "Tue" /  "Wed"  / "Thu"  /  "Fri"  / "Sat" /  "Sun"
76  *  date        =  1*2DIGIT month 2DIGIT        ; day month year e.g. 20 Jun 82
77  *  month       =  "Jan"  /  "Feb" /  "Mar"  /  "Apr"  /  "May"  /  "Jun" /  "Jul"  /  "Aug"  /  "Sep"  /  "Oct" /  "Nov"  /  "Dec"
78  *  time        =  hour zone                    ; ANSI and Military
79  *  hour        =  2DIGIT ":" 2DIGIT [":" 2DIGIT] ; 00:00:00 - 23:59:59
80  *  zone        =  "UT"  / "GMT"  /  "EST" / "EDT"  /  "CST" / "CDT"  /  "MST" / "MDT"  /  "PST" / "PDT"  /  1ALPHA  / ( ("+" / "-") 4DIGIT )
81  */
82 #define DATE_FORMAT_RFC822   "D, d M y H:i:s O"
83 
84 /*
85  * RFC850, Section 2.1.4: http://www.ietf.org/rfc/rfc850.txt
86  *  Format must be acceptable both to the ARPANET and to the getdate routine.
87  *  One format that is acceptable to both is Weekday, DD-Mon-YY HH:MM:SS TIMEZONE
88  *  TIMEZONE can be any timezone name (3 or more letters)
89  */
90 #define DATE_FORMAT_RFC850   "l, d-M-y H:i:s T"
91 
92 /*
93  * RFC1036, Section 2.1.2: http://www.ietf.org/rfc/rfc1036.txt
94  *  Its format must be acceptable both in RFC-822 and to the getdate(3)
95  *  Wdy, DD Mon YY HH:MM:SS TIMEZONE
96  *  There is no hope of having a complete list of timezones.  Universal
97  *  Time (GMT), the North American timezones (PST, PDT, MST, MDT, CST,
98  *  CDT, EST, EDT) and the +/-hhmm offset specified in RFC-822 should be supported.
99  */
100 #define DATE_FORMAT_RFC1036  "D, d M y H:i:s O"
101 
102 /*
103  * RFC1123, Section 5.2.14: http://www.ietf.org/rfc/rfc1123.txt
104  *  RFC-822 Date and Time Specification: RFC-822 Section 5
105  *  The syntax for the date is hereby changed to: date = 1*2DIGIT month 2*4DIGIT
106  */
107 #define DATE_FORMAT_RFC1123  "D, d M Y H:i:s O"
108 
109 /*
110  * RFC7231, Section 7.1.1: http://tools.ietf.org/html/rfc7231
111  */
112 #define DATE_FORMAT_RFC7231  "D, d M Y H:i:s \\G\\M\\T"
113 
114 /*
115  * RFC2822, Section 3.3: http://www.ietf.org/rfc/rfc2822.txt
116  *  FWS             =       ([*WSP CRLF] 1*WSP) /   ; Folding white space
117  *  CFWS            =       *([FWS] comment) (([FWS] comment) / FWS)
118  *
119  *  date-time       =       [ day-of-week "," ] date FWS time [CFWS]
120  *  day-of-week     =       ([FWS] day-name)
121  *  day-name        =       "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun"
122  *  date            =       day month year
123  *  year            =       4*DIGIT
124  *  month           =       (FWS month-name FWS)
125  *  month-name      =       "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
126  *  day             =       ([FWS] 1*2DIGIT)
127  *  time            =       time-of-day FWS zone
128  *  time-of-day     =       hour ":" minute [ ":" second ]
129  *  hour            =       2DIGIT
130  *  minute          =       2DIGIT
131  *  second          =       2DIGIT
132  *  zone            =       (( "+" / "-" ) 4DIGIT)
133  */
134 #define DATE_FORMAT_RFC2822  "D, d M Y H:i:s O"
135 
136 /*
137  * RFC3339, Section 5.6: http://www.ietf.org/rfc/rfc3339.txt
138  *  date-fullyear   = 4DIGIT
139  *  date-month      = 2DIGIT  ; 01-12
140  *  date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on month/year
141  *
142  *  time-hour       = 2DIGIT  ; 00-23
143  *  time-minute     = 2DIGIT  ; 00-59
144  *  time-second     = 2DIGIT  ; 00-58, 00-59, 00-60 based on leap second rules
145  *
146  *  time-secfrac    = "." 1*DIGIT
147  *  time-numoffset  = ("+" / "-") time-hour ":" time-minute
148  *  time-offset     = "Z" / time-numoffset
149  *
150  *  partial-time    = time-hour ":" time-minute ":" time-second [time-secfrac]
151  *  full-date       = date-fullyear "-" date-month "-" date-mday
152  *  full-time       = partial-time time-offset
153  *
154  *  date-time       = full-date "T" full-time
155  */
156 #define DATE_FORMAT_RFC3339  "Y-m-d\\TH:i:sP"
157 
158 /*
159  * This format does not technically match the ISO 8601 standard, as it does not
160  * use : in the UTC offset format specifier. This is kept for BC reasons. The
161  * DATE_FORMAT_ISO8601_EXPANDED format does correct this, as well as adding
162  * support for years out side of the traditional 0000-9999 range.
163  */
164 #define DATE_FORMAT_ISO8601  "Y-m-d\\TH:i:sO"
165 
166 /* ISO 8601:2004(E)
167  *
168  * Section 3.5 Expansion:
169  * By mutual agreement of the partners in information interchange, it is
170  * permitted to expand the component identifying the calendar year, which is
171  * otherwise limited to four digits. This enables reference to dates and times
172  * in calendar years outside the range supported by complete representations,
173  * i.e. before the start of the year [0000] or after the end of the year
174  * [9999]."
175  *
176  * Section 4.1.2.4 Expanded representations:
177  * If, by agreement, expanded representations are used, the formats shall be as
178  * specified below. The interchange parties shall agree the additional number of
179  * digits in the time element year. In the examples below it has been agreed to
180  * expand the time element year with two digits.
181  * Extended format: ±YYYYY-MM-DD
182  * Example: +001985-04-12
183  *
184  * PHP's year expansion digits are variable.
185  */
186 #define DATE_FORMAT_ISO8601_EXPANDED    "X-m-d\\TH:i:sP"
187 
188 /* Internal Only
189  * This format only extends the year when needed, keeping the 'P' format with
190  * colon for UTC offsets
191  */
192 #define DATE_FORMAT_ISO8601_LARGE_YEAR  "x-m-d\\TH:i:sP"
193 
194 /*
195  * RFC3339, Appendix A: http://www.ietf.org/rfc/rfc3339.txt
196  *  ISO 8601 also requires (in section 5.3.1.3) that a decimal fraction
197  *  be proceeded by a "0" if less than unity.  Annex B.2 of ISO 8601
198  *  gives examples where the decimal fractions are not preceded by a "0".
199  *  This grammar assumes section 5.3.1.3 is correct and that Annex B.2 is
200  *  in error.
201  */
202 #define DATE_FORMAT_RFC3339_EXTENDED  "Y-m-d\\TH:i:s.vP"
203 
204 /*
205  * This comes from various sources that like to contradict. I'm going with the
206  * format here because of:
207  * http://msdn.microsoft.com/en-us/library/windows/desktop/aa384321%28v=vs.85%29.aspx
208  * and http://curl.haxx.se/rfc/cookie_spec.html
209  */
210 #define DATE_FORMAT_COOKIE   "l, d-M-Y H:i:s T"
211 
212 #define SUNFUNCS_RET_TIMESTAMP 0
213 #define SUNFUNCS_RET_STRING    1
214 #define SUNFUNCS_RET_DOUBLE    2
215 
216 #define PHP_DATE_TIMEZONE_GROUP_AFRICA     0x0001
217 #define PHP_DATE_TIMEZONE_GROUP_AMERICA    0x0002
218 #define PHP_DATE_TIMEZONE_GROUP_ANTARCTICA 0x0004
219 #define PHP_DATE_TIMEZONE_GROUP_ARCTIC     0x0008
220 #define PHP_DATE_TIMEZONE_GROUP_ASIA       0x0010
221 #define PHP_DATE_TIMEZONE_GROUP_ATLANTIC   0x0020
222 #define PHP_DATE_TIMEZONE_GROUP_AUSTRALIA  0x0040
223 #define PHP_DATE_TIMEZONE_GROUP_EUROPE     0x0080
224 #define PHP_DATE_TIMEZONE_GROUP_INDIAN     0x0100
225 #define PHP_DATE_TIMEZONE_GROUP_PACIFIC    0x0200
226 #define PHP_DATE_TIMEZONE_GROUP_UTC        0x0400
227 #define PHP_DATE_TIMEZONE_GROUP_ALL        0x07FF
228 #define PHP_DATE_TIMEZONE_GROUP_ALL_W_BC   0x0FFF
229 #define PHP_DATE_TIMEZONE_PER_COUNTRY      0x1000
230 
231 #define PHP_DATE_PERIOD_EXCLUDE_START_DATE 0x0001
232 #define PHP_DATE_PERIOD_INCLUDE_END_DATE   0x0002
233 
234 #include "php_date_arginfo.h"
235 
236 static const char* guess_timezone(const timelib_tzdb *tzdb);
237 static void date_register_classes(void);
238 /* }}} */
239 
240 ZEND_DECLARE_MODULE_GLOBALS(date)
241 static PHP_GINIT_FUNCTION(date);
242 
243 /* True global */
244 timelib_tzdb *php_date_global_timezone_db;
245 int php_date_global_timezone_db_enabled;
246 
247 #define DATE_DEFAULT_LATITUDE "31.7667"
248 #define DATE_DEFAULT_LONGITUDE "35.2333"
249 
250 /* on 90'50; common sunset declaration (start of sun body appear) */
251 #define DATE_SUNSET_ZENITH "90.833333"
252 
253 /* on 90'50; common sunrise declaration (sun body disappeared) */
254 #define DATE_SUNRISE_ZENITH "90.833333"
255 
256 static PHP_INI_MH(OnUpdate_date_timezone);
257 
258 /* {{{ INI Settings */
259 PHP_INI_BEGIN()
260 	STD_PHP_INI_ENTRY("date.timezone", "UTC", PHP_INI_ALL, OnUpdate_date_timezone, default_timezone, zend_date_globals, date_globals)
261 	PHP_INI_ENTRY("date.default_latitude",           DATE_DEFAULT_LATITUDE,        PHP_INI_ALL, NULL)
262 	PHP_INI_ENTRY("date.default_longitude",          DATE_DEFAULT_LONGITUDE,       PHP_INI_ALL, NULL)
263 	PHP_INI_ENTRY("date.sunset_zenith",              DATE_SUNSET_ZENITH,           PHP_INI_ALL, NULL)
264 	PHP_INI_ENTRY("date.sunrise_zenith",             DATE_SUNRISE_ZENITH,          PHP_INI_ALL, NULL)
265 PHP_INI_END()
266 /* }}} */
267 
268 static zend_class_entry *date_ce_date, *date_ce_timezone, *date_ce_interval, *date_ce_period;
269 static zend_class_entry *date_ce_immutable, *date_ce_interface;
270 static zend_class_entry *date_ce_date_error, *date_ce_date_object_error, *date_ce_date_range_error;
271 static 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;
272 
273 
php_date_get_date_ce(void)274 PHPAPI zend_class_entry *php_date_get_date_ce(void)
275 {
276 	return date_ce_date;
277 }
278 
php_date_get_immutable_ce(void)279 PHPAPI zend_class_entry *php_date_get_immutable_ce(void)
280 {
281 	return date_ce_immutable;
282 }
283 
php_date_get_interface_ce(void)284 PHPAPI zend_class_entry *php_date_get_interface_ce(void)
285 {
286 	return date_ce_interface;
287 }
288 
php_date_get_timezone_ce(void)289 PHPAPI zend_class_entry *php_date_get_timezone_ce(void)
290 {
291 	return date_ce_timezone;
292 }
293 
php_date_get_interval_ce(void)294 PHPAPI zend_class_entry *php_date_get_interval_ce(void)
295 {
296 	return date_ce_interval;
297 }
298 
php_date_get_period_ce(void)299 PHPAPI zend_class_entry *php_date_get_period_ce(void)
300 {
301 	return date_ce_period;
302 }
303 
304 static zend_object_handlers date_object_handlers_date;
305 static zend_object_handlers date_object_handlers_immutable;
306 static zend_object_handlers date_object_handlers_timezone;
307 static zend_object_handlers date_object_handlers_interval;
308 static zend_object_handlers date_object_handlers_period;
309 
date_throw_uninitialized_error(zend_class_entry * ce)310 static void date_throw_uninitialized_error(zend_class_entry *ce)
311 {
312 	if (ce->type == ZEND_INTERNAL_CLASS) {
313 		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));
314 	} else {
315 		zend_class_entry *ce_ptr = ce;
316 		while (ce_ptr && ce_ptr->parent && ce_ptr->type == ZEND_USER_CLASS) {
317 			ce_ptr = ce_ptr->parent;
318 		}
319 		if (ce_ptr->type != ZEND_INTERNAL_CLASS) {
320 			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));
321 			return;
322 		}
323 		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));
324 	}
325 }
326 
327 #define DATE_CHECK_INITIALIZED(member, ce) \
328 	if (UNEXPECTED(!member)) { \
329 		date_throw_uninitialized_error(ce); \
330 		RETURN_THROWS(); \
331 	}
332 
333 static void date_object_free_storage_date(zend_object *object);
334 static void date_object_free_storage_timezone(zend_object *object);
335 static void date_object_free_storage_interval(zend_object *object);
336 static void date_object_free_storage_period(zend_object *object);
337 
338 static zend_object *date_object_new_date(zend_class_entry *class_type);
339 static zend_object *date_object_new_timezone(zend_class_entry *class_type);
340 static zend_object *date_object_new_interval(zend_class_entry *class_type);
341 static zend_object *date_object_new_period(zend_class_entry *class_type);
342 
343 static zend_object *date_object_clone_date(zend_object *this_ptr);
344 static zend_object *date_object_clone_timezone(zend_object *this_ptr);
345 static zend_object *date_object_clone_interval(zend_object *this_ptr);
346 static zend_object *date_object_clone_period(zend_object *this_ptr);
347 
348 static int date_object_compare_date(zval *d1, zval *d2);
349 static HashTable *date_object_get_gc(zend_object *object, zval **table, int *n);
350 static HashTable *date_object_get_properties_for(zend_object *object, zend_prop_purpose purpose);
351 static HashTable *date_object_get_gc_interval(zend_object *object, zval **table, int *n);
352 static HashTable *date_object_get_properties_interval(zend_object *object);
353 static HashTable *date_object_get_gc_period(zend_object *object, zval **table, int *n);
354 static HashTable *date_object_get_properties_for_timezone(zend_object *object, zend_prop_purpose purpose);
355 static HashTable *date_object_get_gc_timezone(zend_object *object, zval **table, int *n);
356 static HashTable *date_object_get_debug_info_timezone(zend_object *object, int *is_temp);
357 static void php_timezone_to_string(php_timezone_obj *tzobj, zval *zv);
358 
359 static int date_interval_compare_objects(zval *o1, zval *o2);
360 static zval *date_interval_read_property(zend_object *object, zend_string *member, int type, void **cache_slot, zval *rv);
361 static zval *date_interval_write_property(zend_object *object, zend_string *member, zval *value, void **cache_slot);
362 static zval *date_interval_get_property_ptr_ptr(zend_object *object, zend_string *member, int type, void **cache_slot);
363 static int date_period_has_property(zend_object *object, zend_string *name, int type, void **cache_slot);
364 static zval *date_period_read_property(zend_object *object, zend_string *name, int type, void **cache_slot, zval *rv);
365 static zval *date_period_write_property(zend_object *object, zend_string *name, zval *value, void **cache_slot);
366 static zval *date_period_get_property_ptr_ptr(zend_object *object, zend_string *name, int type, void **cache_slot);
367 static void date_period_unset_property(zend_object *object, zend_string *name, void **cache_slot);
368 static HashTable *date_period_get_properties_for(zend_object *object, zend_prop_purpose purpose);
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_format_date_obj(const char * format,size_t format_len,php_date_obj * date_obj)848 PHPAPI zend_string *php_format_date_obj(const char *format, size_t format_len, php_date_obj *date_obj)
849 {
850 	if (!date_obj->time) {
851 		return NULL;
852 	}
853 
854 	return date_format(format, format_len, date_obj->time, date_obj->time->is_localtime);
855 }
856 
php_date(INTERNAL_FUNCTION_PARAMETERS,bool localtime)857 static void php_date(INTERNAL_FUNCTION_PARAMETERS, bool localtime)
858 {
859 	zend_string *format;
860 	zend_long    ts;
861 	bool    ts_is_null = 1;
862 
863 	ZEND_PARSE_PARAMETERS_START(1, 2)
864 		Z_PARAM_STR(format)
865 		Z_PARAM_OPTIONAL
866 		Z_PARAM_LONG_OR_NULL(ts, ts_is_null)
867 	ZEND_PARSE_PARAMETERS_END();
868 
869 	if (ts_is_null) {
870 		ts = php_time();
871 	}
872 
873 	RETURN_STR(php_format_date(ZSTR_VAL(format), ZSTR_LEN(format), ts, localtime));
874 }
875 /* }}} */
876 
php_format_date(const char * format,size_t format_len,time_t ts,bool localtime)877 PHPAPI zend_string *php_format_date(const char *format, size_t format_len, time_t ts, bool localtime) /* {{{ */
878 {
879 	timelib_time   *t;
880 	timelib_tzinfo *tzi;
881 	zend_string *string;
882 
883 	t = timelib_time_ctor();
884 
885 	if (localtime) {
886 		tzi = get_timezone_info();
887 		t->tz_info = tzi;
888 		t->zone_type = TIMELIB_ZONETYPE_ID;
889 		timelib_unixtime2local(t, ts);
890 	} else {
891 		tzi = NULL;
892 		timelib_unixtime2gmt(t, ts);
893 	}
894 
895 	string = date_format(format, format_len, t, localtime);
896 
897 	timelib_time_dtor(t);
898 	return string;
899 }
900 /* }}} */
901 
902 /* {{{ php_idate */
php_idate(char format,time_t ts,bool localtime)903 PHPAPI int php_idate(char format, time_t ts, bool localtime)
904 {
905 	timelib_time   *t;
906 	timelib_tzinfo *tzi;
907 	int retval = -1;
908 	timelib_time_offset *offset = NULL;
909 	timelib_sll isoweek, isoyear;
910 
911 	t = timelib_time_ctor();
912 
913 	if (!localtime) {
914 		tzi = get_timezone_info();
915 		t->tz_info = tzi;
916 		t->zone_type = TIMELIB_ZONETYPE_ID;
917 		timelib_unixtime2local(t, ts);
918 	} else {
919 		tzi = NULL;
920 		timelib_unixtime2gmt(t, ts);
921 	}
922 
923 	if (!localtime) {
924 		if (t->zone_type == TIMELIB_ZONETYPE_ABBR) {
925 			offset = timelib_time_offset_ctor();
926 			offset->offset = (t->z + (t->dst * 3600));
927 			offset->leap_secs = 0;
928 			offset->is_dst = t->dst;
929 			offset->abbr = timelib_strdup(t->tz_abbr);
930 		} else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) {
931 			offset = timelib_time_offset_ctor();
932 			offset->offset = (t->z + (t->dst * 3600));
933 			offset->leap_secs = 0;
934 			offset->is_dst = t->dst;
935 			offset->abbr = timelib_malloc(9); /* GMT±xxxx\0 */
936 			snprintf(offset->abbr, 9, "GMT%c%02d%02d",
937 			                          (offset->offset < 0) ? '-' : '+',
938 			                          abs(offset->offset / 3600),
939 			                          abs((offset->offset % 3600) / 60));
940 		} else {
941 			offset = timelib_get_time_zone_info(t->sse, t->tz_info);
942 		}
943 	}
944 
945 	timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear);
946 
947 	switch (format) {
948 		/* day */
949 		case 'd': case 'j': retval = (int) t->d; break;
950 
951 		case 'N': retval = (int) timelib_iso_day_of_week(t->y, t->m, t->d); break;
952 		case 'w': retval = (int) timelib_day_of_week(t->y, t->m, t->d); break;
953 		case 'z': retval = (int) timelib_day_of_year(t->y, t->m, t->d); break;
954 
955 		/* week */
956 		case 'W': retval = (int) isoweek; break; /* iso weeknr */
957 
958 		/* month */
959 		case 'm': case 'n': retval = (int) t->m; break;
960 		case 't': retval = (int) timelib_days_in_month(t->y, t->m); break;
961 
962 		/* year */
963 		case 'L': retval = (int) timelib_is_leap((int) t->y); break;
964 		case 'y': retval = (int) (t->y % 100); break;
965 		case 'Y': retval = (int) t->y; break;
966 		case 'o': retval = (int) isoyear; break; /* iso year */
967 
968 		/* Swatch Beat a.k.a. Internet Time */
969 		case 'B':
970 			retval = ((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10);
971 			if (retval < 0) {
972 				retval += 864000;
973 			}
974 			/* Make sure to do this on a positive int to avoid rounding errors */
975 			retval = (retval / 864) % 1000;
976 			break;
977 
978 		/* time */
979 		case 'g': case 'h': retval = (int) ((t->h % 12) ? (int) t->h % 12 : 12); break;
980 		case 'H': case 'G': retval = (int) t->h; break;
981 		case 'i': retval = (int) t->i; break;
982 		case 's': retval = (int) t->s; break;
983 
984 		/* timezone */
985 		case 'I': retval = (int) (!localtime ? offset->is_dst : 0); break;
986 		case 'Z': retval = (int) (!localtime ? offset->offset : 0); break;
987 
988 		case 'U': retval = (int) t->sse; break;
989 	}
990 
991 	if (!localtime) {
992 		timelib_time_offset_dtor(offset);
993 	}
994 	timelib_time_dtor(t);
995 
996 	return retval;
997 }
998 /* }}} */
999 
1000 /* {{{ Format a local date/time */
PHP_FUNCTION(date)1001 PHP_FUNCTION(date)
1002 {
1003 	php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1004 }
1005 /* }}} */
1006 
1007 /* {{{ Format a GMT date/time */
PHP_FUNCTION(gmdate)1008 PHP_FUNCTION(gmdate)
1009 {
1010 	php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1011 }
1012 /* }}} */
1013 
1014 /* {{{ Format a local time/date as integer */
PHP_FUNCTION(idate)1015 PHP_FUNCTION(idate)
1016 {
1017 	zend_string *format;
1018 	zend_long    ts;
1019 	bool    ts_is_null = 1;
1020 	int ret;
1021 
1022 	ZEND_PARSE_PARAMETERS_START(1, 2)
1023 		Z_PARAM_STR(format)
1024 		Z_PARAM_OPTIONAL
1025 		Z_PARAM_LONG_OR_NULL(ts, ts_is_null)
1026 	ZEND_PARSE_PARAMETERS_END();
1027 
1028 	if (ZSTR_LEN(format) != 1) {
1029 		php_error_docref(NULL, E_WARNING, "idate format is one char");
1030 		RETURN_FALSE;
1031 	}
1032 
1033 	if (ts_is_null) {
1034 		ts = php_time();
1035 	}
1036 
1037 	ret = php_idate(ZSTR_VAL(format)[0], ts, 0);
1038 	if (ret == -1) {
1039 		php_error_docref(NULL, E_WARNING, "Unrecognized date format token");
1040 		RETURN_FALSE;
1041 	}
1042 	RETURN_LONG(ret);
1043 }
1044 /* }}} */
1045 
1046 /* {{{ php_date_set_tzdb - NOT THREADSAFE */
php_date_set_tzdb(timelib_tzdb * tzdb)1047 PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb)
1048 {
1049 	const timelib_tzdb *builtin = timelib_builtin_db();
1050 
1051 	if (php_version_compare(tzdb->version, builtin->version) > 0) {
1052 		php_date_global_timezone_db = tzdb;
1053 		php_date_global_timezone_db_enabled = 1;
1054 	}
1055 }
1056 /* }}} */
1057 
1058 /* {{{ php_parse_date: Backwards compatibility function */
php_parse_date(const char * string,zend_long * now)1059 PHPAPI zend_long php_parse_date(const char *string, zend_long *now)
1060 {
1061 	timelib_time *parsed_time;
1062 	timelib_error_container *error = NULL;
1063 	int           error2;
1064 	zend_long   retval;
1065 
1066 	parsed_time = timelib_strtotime(string, strlen(string), &error, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
1067 	if (error->error_count) {
1068 		timelib_time_dtor(parsed_time);
1069 		timelib_error_container_dtor(error);
1070 		return -1;
1071 	}
1072 	timelib_error_container_dtor(error);
1073 	timelib_update_ts(parsed_time, NULL);
1074 	retval = timelib_date_to_int(parsed_time, &error2);
1075 	timelib_time_dtor(parsed_time);
1076 	if (error2) {
1077 		return -1;
1078 	}
1079 	return retval;
1080 }
1081 /* }}} */
1082 
1083 /* {{{ Convert string representation of date and time to a timestamp */
PHP_FUNCTION(strtotime)1084 PHP_FUNCTION(strtotime)
1085 {
1086 	zend_string *times;
1087 	int parse_error, epoch_does_not_fit_in_zend_long;
1088 	timelib_error_container *error;
1089 	zend_long preset_ts, ts;
1090 	bool preset_ts_is_null = 1;
1091 	timelib_time *t, *now;
1092 	timelib_tzinfo *tzi;
1093 
1094 	ZEND_PARSE_PARAMETERS_START(1, 2)
1095 		Z_PARAM_STR(times)
1096 		Z_PARAM_OPTIONAL
1097 		Z_PARAM_LONG_OR_NULL(preset_ts, preset_ts_is_null)
1098 	ZEND_PARSE_PARAMETERS_END();
1099 
1100 	/* timelib_strtotime() expects the string to not be empty */
1101 	if (ZSTR_LEN(times) == 0) {
1102 		RETURN_FALSE;
1103 	}
1104 
1105 	tzi = get_timezone_info();
1106 	if (!tzi) {
1107 		return;
1108 	}
1109 
1110 	now = timelib_time_ctor();
1111 	now->tz_info = tzi;
1112 	now->zone_type = TIMELIB_ZONETYPE_ID;
1113 	timelib_unixtime2local(now,
1114 		!preset_ts_is_null ? (timelib_sll) preset_ts : (timelib_sll) php_time());
1115 
1116 	t = timelib_strtotime(ZSTR_VAL(times), ZSTR_LEN(times), &error,
1117 		DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
1118 	parse_error = error->error_count;
1119 	timelib_error_container_dtor(error);
1120 	if (parse_error) {
1121 		timelib_time_dtor(now);
1122 		timelib_time_dtor(t);
1123 		RETURN_FALSE;
1124 	}
1125 
1126 	timelib_fill_holes(t, now, TIMELIB_NO_CLONE);
1127 	timelib_update_ts(t, tzi);
1128 	ts = timelib_date_to_int(t, &epoch_does_not_fit_in_zend_long);
1129 
1130 	timelib_time_dtor(now);
1131 	timelib_time_dtor(t);
1132 
1133 	if (epoch_does_not_fit_in_zend_long) {
1134 		php_error_docref(NULL, E_WARNING, "Epoch doesn't fit in a PHP integer");
1135 		RETURN_FALSE;
1136 	}
1137 
1138 	RETURN_LONG(ts);
1139 }
1140 /* }}} */
1141 
1142 /* {{{ php_mktime - (gm)mktime helper */
php_mktime(INTERNAL_FUNCTION_PARAMETERS,bool gmt)1143 PHPAPI void php_mktime(INTERNAL_FUNCTION_PARAMETERS, bool gmt)
1144 {
1145 	zend_long hou, min, sec, mon, day, yea;
1146 	bool min_is_null = 1, sec_is_null = 1, mon_is_null = 1, day_is_null = 1, yea_is_null = 1;
1147 	timelib_time *now;
1148 	timelib_tzinfo *tzi = NULL;
1149 	zend_long ts, adjust_seconds = 0;
1150 	int epoch_does_not_fit_in_zend_long;
1151 
1152 	ZEND_PARSE_PARAMETERS_START(1, 6)
1153 		Z_PARAM_LONG(hou)
1154 		Z_PARAM_OPTIONAL
1155 		Z_PARAM_LONG_OR_NULL(min, min_is_null)
1156 		Z_PARAM_LONG_OR_NULL(sec, sec_is_null)
1157 		Z_PARAM_LONG_OR_NULL(mon, mon_is_null)
1158 		Z_PARAM_LONG_OR_NULL(day, day_is_null)
1159 		Z_PARAM_LONG_OR_NULL(yea, yea_is_null)
1160 	ZEND_PARSE_PARAMETERS_END();
1161 
1162 	/* Initialize structure with current time */
1163 	now = timelib_time_ctor();
1164 	if (gmt) {
1165 		timelib_unixtime2gmt(now, (timelib_sll) php_time());
1166 	} else {
1167 		tzi = get_timezone_info();
1168 		if (!tzi) {
1169 			return;
1170 		}
1171 		now->tz_info = tzi;
1172 		now->zone_type = TIMELIB_ZONETYPE_ID;
1173 		timelib_unixtime2local(now, (timelib_sll) php_time());
1174 	}
1175 
1176 	now->h = hou;
1177 
1178 	if (!min_is_null) {
1179 		now->i = min;
1180 	}
1181 
1182 	if (!sec_is_null) {
1183 		now->s = sec;
1184 	}
1185 
1186 	if (!mon_is_null) {
1187 		now->m = mon;
1188 	}
1189 
1190 	if (!day_is_null) {
1191 		now->d = day;
1192 	}
1193 
1194 	if (!yea_is_null) {
1195 		if (yea >= 0 && yea < 70) {
1196 			yea += 2000;
1197 		} else if (yea >= 70 && yea <= 100) {
1198 			yea += 1900;
1199 		}
1200 		now->y = yea;
1201 	}
1202 
1203 	/* Update the timestamp */
1204 	if (gmt) {
1205 		timelib_update_ts(now, NULL);
1206 	} else {
1207 		timelib_update_ts(now, tzi);
1208 	}
1209 
1210 	/* Clean up and return */
1211 	ts = timelib_date_to_int(now, &epoch_does_not_fit_in_zend_long);
1212 
1213 	if (epoch_does_not_fit_in_zend_long) {
1214 		timelib_time_dtor(now);
1215 		php_error_docref(NULL, E_WARNING, "Epoch doesn't fit in a PHP integer");
1216 		RETURN_FALSE;
1217 	}
1218 
1219 	ts += adjust_seconds;
1220 	timelib_time_dtor(now);
1221 
1222 	RETURN_LONG(ts);
1223 }
1224 /* }}} */
1225 
1226 /* {{{ Get UNIX timestamp for a date */
PHP_FUNCTION(mktime)1227 PHP_FUNCTION(mktime)
1228 {
1229 	php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1230 }
1231 /* }}} */
1232 
1233 /* {{{ Get UNIX timestamp for a GMT date */
PHP_FUNCTION(gmmktime)1234 PHP_FUNCTION(gmmktime)
1235 {
1236 	php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1237 }
1238 /* }}} */
1239 
1240 /* {{{ Returns true(1) if it is a valid date in gregorian calendar */
PHP_FUNCTION(checkdate)1241 PHP_FUNCTION(checkdate)
1242 {
1243 	zend_long m, d, y;
1244 
1245 	ZEND_PARSE_PARAMETERS_START(3, 3)
1246 		Z_PARAM_LONG(m)
1247 		Z_PARAM_LONG(d)
1248 		Z_PARAM_LONG(y)
1249 	ZEND_PARSE_PARAMETERS_END();
1250 
1251 	if (y < 1 || y > 32767 || !timelib_valid_date(y, m, d)) {
1252 		RETURN_FALSE;
1253 	}
1254 	RETURN_TRUE;	/* True : This month, day, year arguments are valid */
1255 }
1256 /* }}} */
1257 
1258 /* {{{ php_strftime - (gm)strftime helper */
php_strftime(INTERNAL_FUNCTION_PARAMETERS,bool gmt)1259 PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, bool gmt)
1260 {
1261 	zend_string         *format;
1262 	zend_long            timestamp;
1263 	bool            timestamp_is_null = 1;
1264 	struct tm            ta;
1265 	int                  max_reallocs = 5;
1266 	size_t               buf_len = 256, real_len;
1267 	timelib_time        *ts;
1268 	timelib_tzinfo      *tzi;
1269 	timelib_time_offset *offset = NULL;
1270 	zend_string 		*buf;
1271 
1272 	ZEND_PARSE_PARAMETERS_START(1, 2)
1273 		Z_PARAM_STR(format)
1274 		Z_PARAM_OPTIONAL
1275 		Z_PARAM_LONG_OR_NULL(timestamp, timestamp_is_null)
1276 	ZEND_PARSE_PARAMETERS_END();
1277 
1278 	if (ZSTR_LEN(format) == 0) {
1279 		RETURN_FALSE;
1280 	}
1281 
1282 	if (timestamp_is_null) {
1283 		timestamp = (zend_long) php_time();
1284 	}
1285 
1286 	ts = timelib_time_ctor();
1287 	if (gmt) {
1288 		tzi = NULL;
1289 		timelib_unixtime2gmt(ts, (timelib_sll) timestamp);
1290 	} else {
1291 		tzi = get_timezone_info();
1292 		if (!tzi) {
1293 			return;
1294 		}
1295 		ts->tz_info = tzi;
1296 		ts->zone_type = TIMELIB_ZONETYPE_ID;
1297 		timelib_unixtime2local(ts, (timelib_sll) timestamp);
1298 	}
1299 	ta.tm_sec   = ts->s;
1300 	ta.tm_min   = ts->i;
1301 	ta.tm_hour  = ts->h;
1302 	ta.tm_mday  = ts->d;
1303 	ta.tm_mon   = ts->m - 1;
1304 	ta.tm_year  = ts->y - 1900;
1305 	ta.tm_wday  = timelib_day_of_week(ts->y, ts->m, ts->d);
1306 	ta.tm_yday  = timelib_day_of_year(ts->y, ts->m, ts->d);
1307 	if (gmt) {
1308 		ta.tm_isdst = 0;
1309 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
1310 		ta.tm_gmtoff = 0;
1311 #endif
1312 #ifdef HAVE_STRUCT_TM_TM_ZONE
1313 		ta.tm_zone = "GMT";
1314 #endif
1315 	} else {
1316 		offset = timelib_get_time_zone_info(timestamp, tzi);
1317 
1318 		ta.tm_isdst = offset->is_dst;
1319 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
1320 		ta.tm_gmtoff = offset->offset;
1321 #endif
1322 #ifdef HAVE_STRUCT_TM_TM_ZONE
1323 		ta.tm_zone = offset->abbr;
1324 #endif
1325 	}
1326 
1327 	/* VS2012 crt has a bug where strftime crash with %z and %Z format when the
1328 	   initial buffer is too small. See
1329 	   http://connect.microsoft.com/VisualStudio/feedback/details/759720/vs2012-strftime-crash-with-z-formatting-code */
1330 	buf = zend_string_alloc(buf_len, 0);
1331 	while ((real_len = strftime(ZSTR_VAL(buf), buf_len, ZSTR_VAL(format), &ta)) == buf_len || real_len == 0) {
1332 		buf_len *= 2;
1333 		buf = zend_string_extend(buf, buf_len, 0);
1334 		if (!--max_reallocs) {
1335 			break;
1336 		}
1337 	}
1338 #ifdef PHP_WIN32
1339 	/* VS2012 strftime() returns number of characters, not bytes.
1340 		See VC++11 bug id 766205. */
1341 	if (real_len > 0) {
1342 		real_len = strlen(buf->val);
1343 	}
1344 #endif
1345 
1346 	timelib_time_dtor(ts);
1347 	if (!gmt) {
1348 		timelib_time_offset_dtor(offset);
1349 	}
1350 
1351 	if (real_len && real_len != buf_len) {
1352 		buf = zend_string_truncate(buf, real_len, 0);
1353 		RETURN_NEW_STR(buf);
1354 	}
1355 	zend_string_efree(buf);
1356 	RETURN_FALSE;
1357 }
1358 /* }}} */
1359 
1360 /* {{{ Format a local time/date according to locale settings */
PHP_FUNCTION(strftime)1361 PHP_FUNCTION(strftime)
1362 {
1363 	php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1364 }
1365 /* }}} */
1366 
1367 /* {{{ Format a GMT/UCT time/date according to locale settings */
PHP_FUNCTION(gmstrftime)1368 PHP_FUNCTION(gmstrftime)
1369 {
1370 	php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1371 }
1372 /* }}} */
1373 
1374 /* {{{ Return current UNIX timestamp */
PHP_FUNCTION(time)1375 PHP_FUNCTION(time)
1376 {
1377 	ZEND_PARSE_PARAMETERS_NONE();
1378 
1379 	RETURN_LONG((zend_long)php_time());
1380 }
1381 /* }}} */
1382 
1383 /* {{{ 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)1384 PHP_FUNCTION(localtime)
1385 {
1386 	zend_long timestamp;
1387 	bool timestamp_is_null = 1;
1388 	bool associative = 0;
1389 	timelib_tzinfo *tzi;
1390 	timelib_time   *ts;
1391 
1392 	ZEND_PARSE_PARAMETERS_START(0, 2)
1393 		Z_PARAM_OPTIONAL
1394 		Z_PARAM_LONG_OR_NULL(timestamp, timestamp_is_null)
1395 		Z_PARAM_BOOL(associative)
1396 	ZEND_PARSE_PARAMETERS_END();
1397 
1398 	if (timestamp_is_null) {
1399 		timestamp = (zend_long) php_time();
1400 	}
1401 
1402 	tzi = get_timezone_info();
1403 	if (!tzi) {
1404 		RETURN_THROWS();
1405 	}
1406 	ts = timelib_time_ctor();
1407 	ts->tz_info = tzi;
1408 	ts->zone_type = TIMELIB_ZONETYPE_ID;
1409 	timelib_unixtime2local(ts, (timelib_sll) timestamp);
1410 
1411 	array_init(return_value);
1412 
1413 	if (associative) {
1414 		add_assoc_long(return_value, "tm_sec",   ts->s);
1415 		add_assoc_long(return_value, "tm_min",   ts->i);
1416 		add_assoc_long(return_value, "tm_hour",  ts->h);
1417 		add_assoc_long(return_value, "tm_mday",  ts->d);
1418 		add_assoc_long(return_value, "tm_mon",   ts->m - 1);
1419 		add_assoc_long(return_value, "tm_year",  ts->y - 1900);
1420 		add_assoc_long(return_value, "tm_wday",  timelib_day_of_week(ts->y, ts->m, ts->d));
1421 		add_assoc_long(return_value, "tm_yday",  timelib_day_of_year(ts->y, ts->m, ts->d));
1422 		add_assoc_long(return_value, "tm_isdst", ts->dst);
1423 	} else {
1424 		add_next_index_long(return_value, ts->s);
1425 		add_next_index_long(return_value, ts->i);
1426 		add_next_index_long(return_value, ts->h);
1427 		add_next_index_long(return_value, ts->d);
1428 		add_next_index_long(return_value, ts->m - 1);
1429 		add_next_index_long(return_value, ts->y- 1900);
1430 		add_next_index_long(return_value, timelib_day_of_week(ts->y, ts->m, ts->d));
1431 		add_next_index_long(return_value, timelib_day_of_year(ts->y, ts->m, ts->d));
1432 		add_next_index_long(return_value, ts->dst);
1433 	}
1434 
1435 	timelib_time_dtor(ts);
1436 }
1437 /* }}} */
1438 
1439 /* {{{ Get date/time information */
PHP_FUNCTION(getdate)1440 PHP_FUNCTION(getdate)
1441 {
1442 	zend_long timestamp;
1443 	bool timestamp_is_null = 1;
1444 	timelib_tzinfo *tzi;
1445 	timelib_time   *ts;
1446 
1447 	ZEND_PARSE_PARAMETERS_START(0, 1)
1448 		Z_PARAM_OPTIONAL
1449 		Z_PARAM_LONG_OR_NULL(timestamp, timestamp_is_null)
1450 	ZEND_PARSE_PARAMETERS_END();
1451 
1452 	if (timestamp_is_null) {
1453 		timestamp = (zend_long) php_time();
1454 	}
1455 
1456 	tzi = get_timezone_info();
1457 	if (!tzi) {
1458 		RETURN_THROWS();
1459 	}
1460 	ts = timelib_time_ctor();
1461 	ts->tz_info = tzi;
1462 	ts->zone_type = TIMELIB_ZONETYPE_ID;
1463 	timelib_unixtime2local(ts, (timelib_sll) timestamp);
1464 
1465 	array_init(return_value);
1466 
1467 	add_assoc_long(return_value, "seconds", ts->s);
1468 	add_assoc_long(return_value, "minutes", ts->i);
1469 	add_assoc_long(return_value, "hours", ts->h);
1470 	add_assoc_long(return_value, "mday", ts->d);
1471 	add_assoc_long(return_value, "wday", timelib_day_of_week(ts->y, ts->m, ts->d));
1472 	add_assoc_long(return_value, "mon", ts->m);
1473 	add_assoc_long(return_value, "year", ts->y);
1474 	add_assoc_long(return_value, "yday", timelib_day_of_year(ts->y, ts->m, ts->d));
1475 	add_assoc_string(return_value, "weekday", php_date_full_day_name(ts->y, ts->m, ts->d));
1476 	add_assoc_string(return_value, "month", mon_full_names[ts->m - 1]);
1477 	add_index_long(return_value, 0, timestamp);
1478 
1479 	timelib_time_dtor(ts);
1480 }
1481 /* }}} */
1482 
create_date_period_datetime(timelib_time * datetime,zend_class_entry * ce,zval * zv)1483 static void create_date_period_datetime(timelib_time *datetime, zend_class_entry *ce, zval *zv)
1484 {
1485 	if (datetime) {
1486 		php_date_obj *date_obj;
1487 
1488 		object_init_ex(zv, ce);
1489 		date_obj = Z_PHPDATE_P(zv);
1490 		date_obj->time = timelib_time_clone(datetime);
1491 	} else {
1492 		ZVAL_NULL(zv);
1493 	}
1494 }
1495 
create_date_period_interval(timelib_rel_time * interval,zval * zv)1496 static void create_date_period_interval(timelib_rel_time *interval, zval *zv)
1497 {
1498 	if (interval) {
1499 		php_interval_obj *interval_obj;
1500 
1501 		object_init_ex(zv, date_ce_interval);
1502 		interval_obj = Z_PHPINTERVAL_P(zv);
1503 		interval_obj->diff = timelib_rel_time_clone(interval);
1504 		interval_obj->initialized = 1;
1505 	} else {
1506 		ZVAL_NULL(zv);
1507 	}
1508 }
1509 
1510 /* define an overloaded iterator structure */
1511 typedef struct {
1512 	zend_object_iterator  intern;
1513 	zval                  current;
1514 	php_period_obj       *object;
1515 	int                   current_index;
1516 } date_period_it;
1517 
1518 /* {{{ date_period_it_invalidate_current */
date_period_it_invalidate_current(zend_object_iterator * iter)1519 static void date_period_it_invalidate_current(zend_object_iterator *iter)
1520 {
1521 	date_period_it *iterator = (date_period_it *)iter;
1522 
1523 	if (Z_TYPE(iterator->current) != IS_UNDEF) {
1524 		zval_ptr_dtor(&iterator->current);
1525 		ZVAL_UNDEF(&iterator->current);
1526 	}
1527 }
1528 /* }}} */
1529 
1530 /* {{{ date_period_it_dtor */
date_period_it_dtor(zend_object_iterator * iter)1531 static void date_period_it_dtor(zend_object_iterator *iter)
1532 {
1533 	date_period_it *iterator = (date_period_it *)iter;
1534 
1535 	date_period_it_invalidate_current(iter);
1536 
1537 	zval_ptr_dtor(&iterator->intern.data);
1538 }
1539 /* }}} */
1540 
1541 /* {{{ date_period_it_has_more */
date_period_it_has_more(zend_object_iterator * iter)1542 static zend_result date_period_it_has_more(zend_object_iterator *iter)
1543 {
1544 	date_period_it *iterator = (date_period_it *)iter;
1545 	php_period_obj *object   = Z_PHPPERIOD_P(&iterator->intern.data);
1546 
1547 	if (object->end) {
1548 		if (object->current->sse == object->end->sse) {
1549 			if (object->include_end_date) {
1550 				return object->current->us <= object->end->us ? SUCCESS : FAILURE;
1551 			} else {
1552 				return object->current->us < object->end->us ? SUCCESS : FAILURE;
1553 			}
1554 		}
1555 
1556 		return object->current->sse < object->end->sse ? SUCCESS : FAILURE;
1557 	} else {
1558 		return (iterator->current_index < object->recurrences) ? SUCCESS : FAILURE;
1559 	}
1560 }
1561 /* }}} */
1562 
get_base_date_class(zend_class_entry * start_ce)1563 static zend_class_entry *get_base_date_class(zend_class_entry *start_ce)
1564 {
1565 	zend_class_entry *tmp = start_ce;
1566 
1567 	while (tmp != date_ce_date && tmp != date_ce_immutable && tmp->parent) {
1568 		tmp = tmp->parent;
1569 	}
1570 
1571 	return tmp;
1572 }
1573 
1574 /* {{{ date_period_it_current_data */
date_period_it_current_data(zend_object_iterator * iter)1575 static zval *date_period_it_current_data(zend_object_iterator *iter)
1576 {
1577 	date_period_it *iterator = (date_period_it *)iter;
1578 	php_period_obj *object   = Z_PHPPERIOD_P(&iterator->intern.data);
1579 	timelib_time   *it_time = object->current;
1580 	php_date_obj   *newdateobj;
1581 
1582 	/* Create new object */
1583 	php_date_instantiate(get_base_date_class(object->start_ce), &iterator->current);
1584 	newdateobj = Z_PHPDATE_P(&iterator->current);
1585 	newdateobj->time = timelib_time_ctor();
1586 	*newdateobj->time = *it_time;
1587 	if (it_time->tz_abbr) {
1588 		newdateobj->time->tz_abbr = timelib_strdup(it_time->tz_abbr);
1589 	}
1590 	if (it_time->tz_info) {
1591 		newdateobj->time->tz_info = it_time->tz_info;
1592 	}
1593 
1594 	return &iterator->current;
1595 }
1596 /* }}} */
1597 
1598 /* {{{ date_period_it_current_key */
date_period_it_current_key(zend_object_iterator * iter,zval * key)1599 static void date_period_it_current_key(zend_object_iterator *iter, zval *key)
1600 {
1601 	date_period_it *iterator = (date_period_it *)iter;
1602 	ZVAL_LONG(key, iterator->current_index);
1603 }
1604 /* }}} */
1605 
date_period_advance(timelib_time * it_time,timelib_rel_time * interval)1606 static void date_period_advance(timelib_time *it_time, timelib_rel_time *interval)
1607 {
1608 	it_time->have_relative = 1;
1609 	it_time->relative = *interval;
1610 	it_time->sse_uptodate = 0;
1611 	timelib_update_ts(it_time, NULL);
1612 	timelib_update_from_sse(it_time);
1613 }
1614 
1615 /* {{{ date_period_it_move_forward */
date_period_it_move_forward(zend_object_iterator * iter)1616 static void date_period_it_move_forward(zend_object_iterator *iter)
1617 {
1618 	date_period_it *iterator = (date_period_it *)iter;
1619 	php_period_obj *object   = Z_PHPPERIOD_P(&iterator->intern.data);
1620 	timelib_time   *it_time  = object->current;
1621 	zval current_zv;
1622 
1623 	date_period_advance(it_time, object->interval);
1624 
1625 	/* rebuild properties */
1626 	zend_std_get_properties_ex(&object->std);
1627 
1628 	create_date_period_datetime(object->current, object->start_ce, &current_zv);
1629 	zval_ptr_dtor(&current_zv);
1630 
1631 	iterator->current_index++;
1632 	date_period_it_invalidate_current(iter);
1633 }
1634 /* }}} */
1635 
1636 /* {{{ date_period_it_rewind */
date_period_it_rewind(zend_object_iterator * iter)1637 static void date_period_it_rewind(zend_object_iterator *iter)
1638 {
1639 	date_period_it *iterator = (date_period_it *)iter;
1640 
1641 	iterator->current_index = 0;
1642 	if (iterator->object->current) {
1643 		timelib_time_dtor(iterator->object->current);
1644 	}
1645 	if (!iterator->object->start) {
1646 		date_throw_uninitialized_error(date_ce_period);
1647 		return;
1648 	}
1649 
1650 	iterator->object->current = timelib_time_clone(iterator->object->start);
1651 
1652 	if (!iterator->object->include_start_date) {
1653 		date_period_advance(iterator->object->current, iterator->object->interval);
1654 	}
1655 
1656 	date_period_it_invalidate_current(iter);
1657 }
1658 /* }}} */
1659 
1660 /* iterator handler table */
1661 static const zend_object_iterator_funcs date_period_it_funcs = {
1662 	date_period_it_dtor,
1663 	date_period_it_has_more,
1664 	date_period_it_current_data,
1665 	date_period_it_current_key,
1666 	date_period_it_move_forward,
1667 	date_period_it_rewind,
1668 	date_period_it_invalidate_current,
1669 	NULL, /* get_gc */
1670 };
1671 
date_object_period_get_iterator(zend_class_entry * ce,zval * object,int by_ref)1672 static zend_object_iterator *date_object_period_get_iterator(zend_class_entry *ce, zval *object, int by_ref) /* {{{ */
1673 {
1674 	date_period_it *iterator;
1675 
1676 	if (by_ref) {
1677 		zend_throw_error(NULL, "An iterator cannot be used with foreach by reference");
1678 		return NULL;
1679 	}
1680 
1681 	iterator = emalloc(sizeof(date_period_it));
1682 
1683 	zend_iterator_init((zend_object_iterator*)iterator);
1684 
1685 	ZVAL_OBJ_COPY(&iterator->intern.data, Z_OBJ_P(object));
1686 	iterator->intern.funcs = &date_period_it_funcs;
1687 	iterator->object = Z_PHPPERIOD_P(object);
1688 	ZVAL_UNDEF(&iterator->current);
1689 
1690 	return (zend_object_iterator*)iterator;
1691 } /* }}} */
1692 
implement_date_interface_handler(zend_class_entry * interface,zend_class_entry * implementor)1693 static int implement_date_interface_handler(zend_class_entry *interface, zend_class_entry *implementor) /* {{{ */
1694 {
1695 	if (implementor->type == ZEND_USER_CLASS &&
1696 		!instanceof_function(implementor, date_ce_date) &&
1697 		!instanceof_function(implementor, date_ce_immutable)
1698 	) {
1699 		zend_error_noreturn(E_ERROR, "DateTimeInterface can't be implemented by user classes");
1700 	}
1701 
1702 	return SUCCESS;
1703 } /* }}} */
1704 
date_interval_has_property(zend_object * object,zend_string * name,int type,void ** cache_slot)1705 static int date_interval_has_property(zend_object *object, zend_string *name, int type, void **cache_slot) /* {{{ */
1706 {
1707 	php_interval_obj *obj;
1708 	zval rv;
1709 	zval *prop;
1710 	int retval = 0;
1711 
1712 	obj = php_interval_obj_from_obj(object);
1713 
1714 	if (!obj->initialized) {
1715 		retval = zend_std_has_property(object, name, type, cache_slot);
1716 		return retval;
1717 	}
1718 
1719 	prop = date_interval_read_property(object, name, BP_VAR_IS, cache_slot, &rv);
1720 
1721 	if (prop != &EG(uninitialized_zval)) {
1722 		if (type == 2) {
1723 			retval = 1;
1724 		} else if (type == 1) {
1725 			retval = zend_is_true(prop);
1726 		} else if (type == 0) {
1727 			retval = (Z_TYPE_P(prop) != IS_NULL);
1728 		}
1729 	} else {
1730 		retval = zend_std_has_property(object, name, type, cache_slot);
1731 	}
1732 
1733 	return retval;
1734 
1735 }
1736 /* }}} */
1737 
date_register_classes(void)1738 static void date_register_classes(void) /* {{{ */
1739 {
1740 	date_ce_interface = register_class_DateTimeInterface();
1741 	date_ce_interface->interface_gets_implemented = implement_date_interface_handler;
1742 
1743 	date_ce_date = register_class_DateTime(date_ce_interface);
1744 	date_ce_date->create_object = date_object_new_date;
1745 	date_ce_date->default_object_handlers = &date_object_handlers_date;
1746 	memcpy(&date_object_handlers_date, &std_object_handlers, sizeof(zend_object_handlers));
1747 	date_object_handlers_date.offset = XtOffsetOf(php_date_obj, std);
1748 	date_object_handlers_date.free_obj = date_object_free_storage_date;
1749 	date_object_handlers_date.clone_obj = date_object_clone_date;
1750 	date_object_handlers_date.compare = date_object_compare_date;
1751 	date_object_handlers_date.get_properties_for = date_object_get_properties_for;
1752 	date_object_handlers_date.get_gc = date_object_get_gc;
1753 
1754 	date_ce_immutable = register_class_DateTimeImmutable(date_ce_interface);
1755 	date_ce_immutable->create_object = date_object_new_date;
1756 	date_ce_immutable->default_object_handlers = &date_object_handlers_date;
1757 	memcpy(&date_object_handlers_immutable, &std_object_handlers, sizeof(zend_object_handlers));
1758 	date_object_handlers_immutable.clone_obj = date_object_clone_date;
1759 	date_object_handlers_immutable.compare = date_object_compare_date;
1760 	date_object_handlers_immutable.get_properties_for = date_object_get_properties_for;
1761 	date_object_handlers_immutable.get_gc = date_object_get_gc;
1762 
1763 	date_ce_timezone = register_class_DateTimeZone();
1764 	date_ce_timezone->create_object = date_object_new_timezone;
1765 	date_ce_timezone->default_object_handlers = &date_object_handlers_timezone;
1766 	memcpy(&date_object_handlers_timezone, &std_object_handlers, sizeof(zend_object_handlers));
1767 	date_object_handlers_timezone.offset = XtOffsetOf(php_timezone_obj, std);
1768 	date_object_handlers_timezone.free_obj = date_object_free_storage_timezone;
1769 	date_object_handlers_timezone.clone_obj = date_object_clone_timezone;
1770 	date_object_handlers_timezone.get_properties_for = date_object_get_properties_for_timezone;
1771 	date_object_handlers_timezone.get_gc = date_object_get_gc_timezone;
1772 	date_object_handlers_timezone.get_debug_info = date_object_get_debug_info_timezone;
1773 	date_object_handlers_timezone.compare = date_object_compare_timezone;
1774 
1775 	date_ce_interval = register_class_DateInterval();
1776 	date_ce_interval->create_object = date_object_new_interval;
1777 	date_ce_interval->default_object_handlers = &date_object_handlers_interval;
1778 	memcpy(&date_object_handlers_interval, &std_object_handlers, sizeof(zend_object_handlers));
1779 	date_object_handlers_interval.offset = XtOffsetOf(php_interval_obj, std);
1780 	date_object_handlers_interval.free_obj = date_object_free_storage_interval;
1781 	date_object_handlers_interval.clone_obj = date_object_clone_interval;
1782 	date_object_handlers_interval.has_property = date_interval_has_property;
1783 	date_object_handlers_interval.read_property = date_interval_read_property;
1784 	date_object_handlers_interval.write_property = date_interval_write_property;
1785 	date_object_handlers_interval.get_properties = date_object_get_properties_interval;
1786 	date_object_handlers_interval.get_property_ptr_ptr = date_interval_get_property_ptr_ptr;
1787 	date_object_handlers_interval.get_gc = date_object_get_gc_interval;
1788 	date_object_handlers_interval.compare = date_interval_compare_objects;
1789 
1790 	date_ce_period = register_class_DatePeriod(zend_ce_aggregate);
1791 	date_ce_period->create_object = date_object_new_period;
1792 	date_ce_period->default_object_handlers = &date_object_handlers_period;
1793 	date_ce_period->get_iterator = date_object_period_get_iterator;
1794 	memcpy(&date_object_handlers_period, &std_object_handlers, sizeof(zend_object_handlers));
1795 	date_object_handlers_period.offset = XtOffsetOf(php_period_obj, std);
1796 	date_object_handlers_period.free_obj = date_object_free_storage_period;
1797 	date_object_handlers_period.clone_obj = date_object_clone_period;
1798 	date_object_handlers_period.get_gc = date_object_get_gc_period;
1799 	date_object_handlers_period.get_property_ptr_ptr = date_period_get_property_ptr_ptr;
1800 	date_object_handlers_period.has_property = date_period_has_property;
1801 	date_object_handlers_period.read_property = date_period_read_property;
1802 	date_object_handlers_period.write_property = date_period_write_property;
1803 	date_object_handlers_period.get_properties_for = date_period_get_properties_for;
1804 	date_object_handlers_period.unset_property = date_period_unset_property;
1805 
1806 	date_ce_date_error = register_class_DateError(zend_ce_error);
1807 	date_ce_date_object_error = register_class_DateObjectError(date_ce_date_error);
1808 	date_ce_date_range_error = register_class_DateRangeError(date_ce_date_error);
1809 
1810 	date_ce_date_exception = register_class_DateException(zend_ce_exception);
1811 	date_ce_date_invalid_timezone_exception = register_class_DateInvalidTimeZoneException(date_ce_date_exception);
1812 	date_ce_date_invalid_operation_exception = register_class_DateInvalidOperationException(date_ce_date_exception);
1813 	date_ce_date_malformed_string_exception = register_class_DateMalformedStringException(date_ce_date_exception);
1814 	date_ce_date_malformed_interval_string_exception = register_class_DateMalformedIntervalStringException(date_ce_date_exception);
1815 	date_ce_date_malformed_period_string_exception = register_class_DateMalformedPeriodStringException(date_ce_date_exception);
1816 } /* }}} */
1817 
date_object_new_date(zend_class_entry * class_type)1818 static zend_object *date_object_new_date(zend_class_entry *class_type) /* {{{ */
1819 {
1820 	php_date_obj *intern = zend_object_alloc(sizeof(php_date_obj), class_type);
1821 
1822 	zend_object_std_init(&intern->std, class_type);
1823 	object_properties_init(&intern->std, class_type);
1824 
1825 	return &intern->std;
1826 } /* }}} */
1827 
date_object_clone_date(zend_object * this_ptr)1828 static zend_object *date_object_clone_date(zend_object *this_ptr) /* {{{ */
1829 {
1830 	php_date_obj *old_obj = php_date_obj_from_obj(this_ptr);
1831 	php_date_obj *new_obj = php_date_obj_from_obj(date_object_new_date(old_obj->std.ce));
1832 
1833 	zend_objects_clone_members(&new_obj->std, &old_obj->std);
1834 	if (!old_obj->time) {
1835 		return &new_obj->std;
1836 	}
1837 
1838 	/* this should probably moved to a new `timelib_time *timelime_time_clone(timelib_time *)` */
1839 	new_obj->time = timelib_time_ctor();
1840 	*new_obj->time = *old_obj->time;
1841 	if (old_obj->time->tz_abbr) {
1842 		new_obj->time->tz_abbr = timelib_strdup(old_obj->time->tz_abbr);
1843 	}
1844 	if (old_obj->time->tz_info) {
1845 		new_obj->time->tz_info = old_obj->time->tz_info;
1846 	}
1847 
1848 	return &new_obj->std;
1849 } /* }}} */
1850 
date_clone_immutable(zval * object,zval * new_object)1851 static void date_clone_immutable(zval *object, zval *new_object) /* {{{ */
1852 {
1853 	ZVAL_OBJ(new_object, date_object_clone_date(Z_OBJ_P(object)));
1854 } /* }}} */
1855 
date_object_compare_date(zval * d1,zval * d2)1856 static int date_object_compare_date(zval *d1, zval *d2) /* {{{ */
1857 {
1858 	php_date_obj *o1;
1859 	php_date_obj *o2;
1860 
1861 	ZEND_COMPARE_OBJECTS_FALLBACK(d1, d2);
1862 
1863 	o1 = Z_PHPDATE_P(d1);
1864 	o2 = Z_PHPDATE_P(d2);
1865 
1866 	if (!o1->time || !o2->time) {
1867 		zend_throw_error(date_ce_date_object_error, "Trying to compare an incomplete DateTime or DateTimeImmutable object");
1868 		return ZEND_UNCOMPARABLE;
1869 	}
1870 	if (!o1->time->sse_uptodate) {
1871 		timelib_update_ts(o1->time, o1->time->tz_info);
1872 	}
1873 	if (!o2->time->sse_uptodate) {
1874 		timelib_update_ts(o2->time, o2->time->tz_info);
1875 	}
1876 
1877 	return timelib_time_compare(o1->time, o2->time);
1878 } /* }}} */
1879 
date_object_get_gc(zend_object * object,zval ** table,int * n)1880 static HashTable *date_object_get_gc(zend_object *object, zval **table, int *n) /* {{{ */
1881 {
1882 	*table = NULL;
1883 	*n = 0;
1884 	return zend_std_get_properties(object);
1885 } /* }}} */
1886 
date_object_get_gc_timezone(zend_object * object,zval ** table,int * n)1887 static HashTable *date_object_get_gc_timezone(zend_object *object, zval **table, int *n) /* {{{ */
1888 {
1889 	*table = NULL;
1890 	*n = 0;
1891 	return zend_std_get_properties(object);
1892 } /* }}} */
1893 
date_object_to_hash(php_date_obj * dateobj,HashTable * props)1894 static void date_object_to_hash(php_date_obj *dateobj, HashTable *props)
1895 {
1896 	zval zv;
1897 
1898 	/* first we add the date and time in ISO format */
1899 	ZVAL_STR(&zv, date_format("x-m-d H:i:s.u", sizeof("x-m-d H:i:s.u")-1, dateobj->time, 1));
1900 	zend_hash_str_update(props, "date", sizeof("date")-1, &zv);
1901 
1902 	/* then we add the timezone name (or similar) */
1903 	if (dateobj->time->is_localtime) {
1904 		ZVAL_LONG(&zv, dateobj->time->zone_type);
1905 		zend_hash_str_update(props, "timezone_type", sizeof("timezone_type")-1, &zv);
1906 
1907 		switch (dateobj->time->zone_type) {
1908 			case TIMELIB_ZONETYPE_ID:
1909 				ZVAL_STRING(&zv, dateobj->time->tz_info->name);
1910 				break;
1911 			case TIMELIB_ZONETYPE_OFFSET: {
1912 				zend_string *tmpstr = zend_string_alloc(sizeof("UTC+05:00")-1, 0);
1913 				int utc_offset = dateobj->time->z;
1914 
1915 				ZSTR_LEN(tmpstr) = snprintf(ZSTR_VAL(tmpstr), sizeof("+05:00"), "%c%02d:%02d",
1916 					utc_offset < 0 ? '-' : '+',
1917 					abs(utc_offset / 3600),
1918 					abs(((utc_offset % 3600) / 60)));
1919 
1920 				ZVAL_NEW_STR(&zv, tmpstr);
1921 				}
1922 				break;
1923 			case TIMELIB_ZONETYPE_ABBR:
1924 				ZVAL_STRING(&zv, dateobj->time->tz_abbr);
1925 				break;
1926 		}
1927 		zend_hash_str_update(props, "timezone", sizeof("timezone")-1, &zv);
1928 	}
1929 }
1930 
date_object_get_properties_for(zend_object * object,zend_prop_purpose purpose)1931 static HashTable *date_object_get_properties_for(zend_object *object, zend_prop_purpose purpose) /* {{{ */
1932 {
1933 	HashTable *props;
1934 	php_date_obj *dateobj;
1935 
1936 	switch (purpose) {
1937 		case ZEND_PROP_PURPOSE_DEBUG:
1938 		case ZEND_PROP_PURPOSE_SERIALIZE:
1939 		case ZEND_PROP_PURPOSE_VAR_EXPORT:
1940 		case ZEND_PROP_PURPOSE_JSON:
1941 		case ZEND_PROP_PURPOSE_ARRAY_CAST:
1942 			break;
1943 		default:
1944 			return zend_std_get_properties_for(object, purpose);
1945 	}
1946 
1947 	dateobj = php_date_obj_from_obj(object);
1948 	props = zend_array_dup(zend_std_get_properties(object));
1949 	if (!dateobj->time) {
1950 		return props;
1951 	}
1952 
1953 	date_object_to_hash(dateobj, props);
1954 
1955 	return props;
1956 } /* }}} */
1957 
date_object_new_timezone(zend_class_entry * class_type)1958 static zend_object *date_object_new_timezone(zend_class_entry *class_type) /* {{{ */
1959 {
1960 	php_timezone_obj *intern = zend_object_alloc(sizeof(php_timezone_obj), class_type);
1961 
1962 	zend_object_std_init(&intern->std, class_type);
1963 	object_properties_init(&intern->std, class_type);
1964 
1965 	return &intern->std;
1966 } /* }}} */
1967 
date_object_clone_timezone(zend_object * this_ptr)1968 static zend_object *date_object_clone_timezone(zend_object *this_ptr) /* {{{ */
1969 {
1970 	php_timezone_obj *old_obj = php_timezone_obj_from_obj(this_ptr);
1971 	php_timezone_obj *new_obj = php_timezone_obj_from_obj(date_object_new_timezone(old_obj->std.ce));
1972 
1973 	zend_objects_clone_members(&new_obj->std, &old_obj->std);
1974 	if (!old_obj->initialized) {
1975 		return &new_obj->std;
1976 	}
1977 
1978 	new_obj->type = old_obj->type;
1979 	new_obj->initialized = 1;
1980 	switch (new_obj->type) {
1981 		case TIMELIB_ZONETYPE_ID:
1982 			new_obj->tzi.tz = old_obj->tzi.tz;
1983 			break;
1984 		case TIMELIB_ZONETYPE_OFFSET:
1985 			new_obj->tzi.utc_offset = old_obj->tzi.utc_offset;
1986 			break;
1987 		case TIMELIB_ZONETYPE_ABBR:
1988 			new_obj->tzi.z.utc_offset = old_obj->tzi.z.utc_offset;
1989 			new_obj->tzi.z.dst        = old_obj->tzi.z.dst;
1990 			new_obj->tzi.z.abbr       = timelib_strdup(old_obj->tzi.z.abbr);
1991 			break;
1992 	}
1993 
1994 	return &new_obj->std;
1995 } /* }}} */
1996 
date_object_compare_timezone(zval * tz1,zval * tz2)1997 static int date_object_compare_timezone(zval *tz1, zval *tz2) /* {{{ */
1998 {
1999 	php_timezone_obj *o1, *o2;
2000 
2001 	ZEND_COMPARE_OBJECTS_FALLBACK(tz1, tz2);
2002 
2003 	o1 = Z_PHPTIMEZONE_P(tz1);
2004 	o2 = Z_PHPTIMEZONE_P(tz2);
2005 
2006 	if (!o1->initialized || !o2->initialized) {
2007 		zend_throw_error(date_ce_date_object_error, "Trying to compare uninitialized DateTimeZone objects");
2008 		return ZEND_UNCOMPARABLE;
2009 	}
2010 
2011 	if (o1->type != o2->type) {
2012 		zend_throw_error(date_ce_date_exception, "Cannot compare two different kinds of DateTimeZone objects");
2013 		return ZEND_UNCOMPARABLE;
2014 	}
2015 
2016 	switch (o1->type) {
2017 		case TIMELIB_ZONETYPE_OFFSET:
2018 			return o1->tzi.utc_offset == o2->tzi.utc_offset ? 0 : 1;
2019 		case TIMELIB_ZONETYPE_ABBR:
2020 			return strcmp(o1->tzi.z.abbr, o2->tzi.z.abbr) ? 1 : 0;
2021 		case TIMELIB_ZONETYPE_ID:
2022 			return strcmp(o1->tzi.tz->name, o2->tzi.tz->name) ? 1 : 0;
2023 		EMPTY_SWITCH_DEFAULT_CASE();
2024 	}
2025 } /* }}} */
2026 
php_timezone_to_string(php_timezone_obj * tzobj,zval * zv)2027 static void php_timezone_to_string(php_timezone_obj *tzobj, zval *zv)
2028 {
2029 	switch (tzobj->type) {
2030 		case TIMELIB_ZONETYPE_ID:
2031 			ZVAL_STRING(zv, tzobj->tzi.tz->name);
2032 			break;
2033 		case TIMELIB_ZONETYPE_OFFSET: {
2034 			timelib_sll utc_offset = tzobj->tzi.utc_offset;
2035 			int seconds = utc_offset % 60;
2036 			size_t size;
2037 			const char *format;
2038 			if (seconds == 0) {
2039 				size = sizeof("+05:00");
2040 				format = "%c%02d:%02d";
2041 			} else {
2042 				size = sizeof("+05:00:01");
2043 				format = "%c%02d:%02d:%02d";
2044 			}
2045 			zend_string *tmpstr = zend_string_alloc(size - 1, 0);
2046 
2047 			/* Note: if seconds == 0, the seconds argument will be excessive and therefore ignored. */
2048 			ZSTR_LEN(tmpstr) = snprintf(ZSTR_VAL(tmpstr), size, format,
2049 				utc_offset < 0 ? '-' : '+',
2050 				abs((int)(utc_offset / 3600)),
2051 				abs((int)(utc_offset % 3600) / 60),
2052 				abs(seconds));
2053 
2054 			ZVAL_NEW_STR(zv, tmpstr);
2055 			}
2056 			break;
2057 		case TIMELIB_ZONETYPE_ABBR:
2058 			ZVAL_STRING(zv, tzobj->tzi.z.abbr);
2059 			break;
2060 	}
2061 }
2062 
date_timezone_object_to_hash(php_timezone_obj * tzobj,HashTable * props)2063 static void date_timezone_object_to_hash(php_timezone_obj *tzobj, HashTable *props)
2064 {
2065 	zval zv;
2066 
2067 	ZVAL_LONG(&zv, tzobj->type);
2068 	zend_hash_str_update(props, "timezone_type", strlen("timezone_type"), &zv);
2069 
2070 	php_timezone_to_string(tzobj, &zv);
2071 	zend_hash_str_update(props, "timezone", strlen("timezone"), &zv);
2072 }
2073 
date_object_get_properties_for_timezone(zend_object * object,zend_prop_purpose purpose)2074 static HashTable *date_object_get_properties_for_timezone(zend_object *object, zend_prop_purpose purpose) /* {{{ */
2075 {
2076 	HashTable *props;
2077 	php_timezone_obj *tzobj;
2078 
2079 	switch (purpose) {
2080 		case ZEND_PROP_PURPOSE_DEBUG:
2081 		case ZEND_PROP_PURPOSE_SERIALIZE:
2082 		case ZEND_PROP_PURPOSE_VAR_EXPORT:
2083 		case ZEND_PROP_PURPOSE_JSON:
2084 		case ZEND_PROP_PURPOSE_ARRAY_CAST:
2085 			break;
2086 		default:
2087 			return zend_std_get_properties_for(object, purpose);
2088 	}
2089 
2090 	tzobj = php_timezone_obj_from_obj(object);
2091 	props = zend_array_dup(zend_std_get_properties(object));
2092 	if (!tzobj->initialized) {
2093 		return props;
2094 	}
2095 
2096 	date_timezone_object_to_hash(tzobj, props);
2097 
2098 	return props;
2099 } /* }}} */
2100 
date_object_get_debug_info_timezone(zend_object * object,int * is_temp)2101 static HashTable *date_object_get_debug_info_timezone(zend_object *object, int *is_temp) /* {{{ */
2102 {
2103 	HashTable *ht, *props;
2104 	zval zv;
2105 	php_timezone_obj *tzobj;
2106 
2107 	tzobj = php_timezone_obj_from_obj(object);
2108 	props = zend_std_get_properties(object);
2109 
2110 	*is_temp = 1;
2111 	ht = zend_array_dup(props);
2112 
2113 	ZVAL_LONG(&zv, tzobj->type);
2114 	zend_hash_str_update(ht, "timezone_type", sizeof("timezone_type")-1, &zv);
2115 
2116 	php_timezone_to_string(tzobj, &zv);
2117 	zend_hash_str_update(ht, "timezone", sizeof("timezone")-1, &zv);
2118 
2119 	return ht;
2120 } /* }}} */
2121 
date_object_new_interval(zend_class_entry * class_type)2122 static zend_object *date_object_new_interval(zend_class_entry *class_type) /* {{{ */
2123 {
2124 	php_interval_obj *intern = zend_object_alloc(sizeof(php_interval_obj), class_type);
2125 
2126 	zend_object_std_init(&intern->std, class_type);
2127 	object_properties_init(&intern->std, class_type);
2128 
2129 	return &intern->std;
2130 } /* }}} */
2131 
date_object_clone_interval(zend_object * this_ptr)2132 static zend_object *date_object_clone_interval(zend_object *this_ptr) /* {{{ */
2133 {
2134 	php_interval_obj *old_obj = php_interval_obj_from_obj(this_ptr);
2135 	php_interval_obj *new_obj = php_interval_obj_from_obj(date_object_new_interval(old_obj->std.ce));
2136 
2137 	zend_objects_clone_members(&new_obj->std, &old_obj->std);
2138 	new_obj->civil_or_wall = old_obj->civil_or_wall;
2139 	new_obj->from_string = old_obj->from_string;
2140 	if (old_obj->date_string) {
2141 		new_obj->date_string = zend_string_copy(old_obj->date_string);
2142 	}
2143 	new_obj->initialized = old_obj->initialized;
2144 	if (old_obj->diff) {
2145 		new_obj->diff = timelib_rel_time_clone(old_obj->diff);
2146 	}
2147 
2148 	return &new_obj->std;
2149 } /* }}} */
2150 
date_object_get_gc_interval(zend_object * object,zval ** table,int * n)2151 static HashTable *date_object_get_gc_interval(zend_object *object, zval **table, int *n) /* {{{ */
2152 {
2153 
2154 	*table = NULL;
2155 	*n = 0;
2156 	return zend_std_get_properties(object);
2157 } /* }}} */
2158 
date_interval_object_to_hash(php_interval_obj * intervalobj,HashTable * props)2159 static void date_interval_object_to_hash(php_interval_obj *intervalobj, HashTable *props)
2160 {
2161 	zval zv;
2162 
2163 	/* Records whether this is a special relative interval that needs to be recreated from a string */
2164 	if (intervalobj->from_string) {
2165 		ZVAL_BOOL(&zv, (bool)intervalobj->from_string);
2166 		zend_hash_str_update(props, "from_string", strlen("from_string"), &zv);
2167 		ZVAL_STR_COPY(&zv, intervalobj->date_string);
2168 		zend_hash_str_update(props, "date_string", strlen("date_string"), &zv);
2169 		return;
2170 	}
2171 
2172 #define PHP_DATE_INTERVAL_ADD_PROPERTY(n,f) \
2173 	ZVAL_LONG(&zv, (zend_long)intervalobj->diff->f); \
2174 	zend_hash_str_update(props, n, sizeof(n)-1, &zv);
2175 
2176 	PHP_DATE_INTERVAL_ADD_PROPERTY("y", y);
2177 	PHP_DATE_INTERVAL_ADD_PROPERTY("m", m);
2178 	PHP_DATE_INTERVAL_ADD_PROPERTY("d", d);
2179 	PHP_DATE_INTERVAL_ADD_PROPERTY("h", h);
2180 	PHP_DATE_INTERVAL_ADD_PROPERTY("i", i);
2181 	PHP_DATE_INTERVAL_ADD_PROPERTY("s", s);
2182 	ZVAL_DOUBLE(&zv, (double)intervalobj->diff->us / 1000000.0);
2183 	zend_hash_str_update(props, "f", sizeof("f") - 1, &zv);
2184 	PHP_DATE_INTERVAL_ADD_PROPERTY("invert", invert);
2185 	if (intervalobj->diff->days != TIMELIB_UNSET) {
2186 		PHP_DATE_INTERVAL_ADD_PROPERTY("days", days);
2187 	} else {
2188 		ZVAL_FALSE(&zv);
2189 		zend_hash_str_update(props, "days", sizeof("days")-1, &zv);
2190 	}
2191 	ZVAL_BOOL(&zv, (bool)intervalobj->from_string);
2192 	zend_hash_str_update(props, "from_string", strlen("from_string"), &zv);
2193 
2194 #undef PHP_DATE_INTERVAL_ADD_PROPERTY
2195 }
2196 
date_object_get_properties_interval(zend_object * object)2197 static HashTable *date_object_get_properties_interval(zend_object *object) /* {{{ */
2198 {
2199 	HashTable *props;
2200 	php_interval_obj *intervalobj;
2201 
2202 	intervalobj = php_interval_obj_from_obj(object);
2203 	props = zend_std_get_properties(object);
2204 	if (!intervalobj->initialized) {
2205 		return props;
2206 	}
2207 
2208 	date_interval_object_to_hash(intervalobj, props);
2209 
2210 	return props;
2211 } /* }}} */
2212 
date_object_new_period(zend_class_entry * class_type)2213 static zend_object *date_object_new_period(zend_class_entry *class_type) /* {{{ */
2214 {
2215 	php_period_obj *intern = zend_object_alloc(sizeof(php_period_obj), class_type);
2216 
2217 	zend_object_std_init(&intern->std, class_type);
2218 	object_properties_init(&intern->std, class_type);
2219 
2220 	return &intern->std;
2221 } /* }}} */
2222 
date_object_clone_period(zend_object * this_ptr)2223 static zend_object *date_object_clone_period(zend_object *this_ptr) /* {{{ */
2224 {
2225 	php_period_obj *old_obj = php_period_obj_from_obj(this_ptr);
2226 	php_period_obj *new_obj = php_period_obj_from_obj(date_object_new_period(old_obj->std.ce));
2227 
2228 	zend_objects_clone_members(&new_obj->std, &old_obj->std);
2229 	new_obj->initialized = old_obj->initialized;
2230 	new_obj->recurrences = old_obj->recurrences;
2231 	new_obj->include_start_date = old_obj->include_start_date;
2232 	new_obj->include_end_date = old_obj->include_end_date;
2233 	new_obj->start_ce = old_obj->start_ce;
2234 
2235 	if (old_obj->start) {
2236 		new_obj->start = timelib_time_clone(old_obj->start);
2237 	}
2238 	if (old_obj->current) {
2239 		new_obj->current = timelib_time_clone(old_obj->current);
2240 	}
2241 	if (old_obj->end) {
2242 		new_obj->end = timelib_time_clone(old_obj->end);
2243 	}
2244 	if (old_obj->interval) {
2245 		new_obj->interval = timelib_rel_time_clone(old_obj->interval);
2246 	}
2247 	return &new_obj->std;
2248 } /* }}} */
2249 
date_object_free_storage_date(zend_object * object)2250 static void date_object_free_storage_date(zend_object *object) /* {{{ */
2251 {
2252 	php_date_obj *intern = php_date_obj_from_obj(object);
2253 
2254 	if (intern->time) {
2255 		timelib_time_dtor(intern->time);
2256 	}
2257 
2258 	zend_object_std_dtor(&intern->std);
2259 } /* }}} */
2260 
date_object_free_storage_timezone(zend_object * object)2261 static void date_object_free_storage_timezone(zend_object *object) /* {{{ */
2262 {
2263 	php_timezone_obj *intern = php_timezone_obj_from_obj(object);
2264 
2265 	if (intern->type == TIMELIB_ZONETYPE_ABBR) {
2266 		timelib_free(intern->tzi.z.abbr);
2267 	}
2268 	zend_object_std_dtor(&intern->std);
2269 } /* }}} */
2270 
date_object_free_storage_interval(zend_object * object)2271 static void date_object_free_storage_interval(zend_object *object) /* {{{ */
2272 {
2273 	php_interval_obj *intern = php_interval_obj_from_obj(object);
2274 
2275 	if (intern->date_string) {
2276 		zend_string_release(intern->date_string);
2277 		intern->date_string = NULL;
2278 	}
2279 	timelib_rel_time_dtor(intern->diff);
2280 	zend_object_std_dtor(&intern->std);
2281 } /* }}} */
2282 
date_object_free_storage_period(zend_object * object)2283 static void date_object_free_storage_period(zend_object *object) /* {{{ */
2284 {
2285 	php_period_obj *intern = php_period_obj_from_obj(object);
2286 
2287 	if (intern->start) {
2288 		timelib_time_dtor(intern->start);
2289 	}
2290 
2291 	if (intern->current) {
2292 		timelib_time_dtor(intern->current);
2293 	}
2294 
2295 	if (intern->end) {
2296 		timelib_time_dtor(intern->end);
2297 	}
2298 
2299 	timelib_rel_time_dtor(intern->interval);
2300 	zend_object_std_dtor(&intern->std);
2301 } /* }}} */
2302 
add_common_properties(HashTable * myht,zend_object * zobj)2303 static void add_common_properties(HashTable *myht, zend_object *zobj)
2304 {
2305 	HashTable *common;
2306 	zend_string *name;
2307 	zval *prop;
2308 
2309 	common = zend_std_get_properties(zobj);
2310 
2311 	ZEND_HASH_FOREACH_STR_KEY_VAL_IND(common, name, prop) {
2312 		if (zend_hash_add(myht, name, prop) != NULL) {
2313 			Z_TRY_ADDREF_P(prop);
2314 		}
2315 	} ZEND_HASH_FOREACH_END();
2316 }
2317 
2318 /* Advanced Interface */
php_date_instantiate(zend_class_entry * pce,zval * object)2319 PHPAPI zval *php_date_instantiate(zend_class_entry *pce, zval *object) /* {{{ */
2320 {
2321 	object_init_ex(object, pce);
2322 	return object;
2323 } /* }}} */
2324 
2325 /* Helper function used to store the latest found warnings and errors while
2326  * parsing, from either strtotime or parse_from_format. */
update_errors_warnings(timelib_error_container ** last_errors)2327 static void update_errors_warnings(timelib_error_container **last_errors) /* {{{ */
2328 {
2329 	if (DATEG(last_errors)) {
2330 		timelib_error_container_dtor(DATEG(last_errors));
2331 		DATEG(last_errors) = NULL;
2332 	}
2333 
2334 	if (last_errors == NULL || (*last_errors) == NULL) {
2335 		return;
2336 	}
2337 
2338 	if ((*last_errors)->warning_count || (*last_errors)->error_count) {
2339 		DATEG(last_errors) = *last_errors;
2340 		return;
2341 	}
2342 
2343 	timelib_error_container_dtor(*last_errors);
2344 	*last_errors = NULL;
2345 } /* }}} */
2346 
php_date_set_time_fraction(timelib_time * time,int microsecond)2347 static void php_date_set_time_fraction(timelib_time *time, int microsecond)
2348 {
2349 	time->us = microsecond;
2350 }
2351 
php_date_get_current_time_with_fraction(time_t * sec,suseconds_t * usec)2352 static void php_date_get_current_time_with_fraction(time_t *sec, suseconds_t *usec)
2353 {
2354 #ifdef HAVE_GETTIMEOFDAY
2355 	struct timeval tp = {0}; /* For setting microsecond */
2356 
2357 	gettimeofday(&tp, NULL);
2358 	*sec = tp.tv_sec;
2359 	*usec = tp.tv_usec;
2360 #else
2361 	*sec = time(NULL);
2362 	*usec = 0;
2363 #endif
2364 }
2365 
php_date_initialize(php_date_obj * dateobj,const char * time_str,size_t time_str_len,const char * format,zval * timezone_object,int flags)2366 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) /* {{{ */
2367 {
2368 	timelib_time   *now;
2369 	timelib_tzinfo *tzi = NULL;
2370 	timelib_error_container *err = NULL;
2371 	int type = TIMELIB_ZONETYPE_ID, new_dst = 0;
2372 	char *new_abbr = NULL;
2373 	timelib_sll new_offset = 0;
2374 	time_t sec;
2375 	suseconds_t usec;
2376 	int options = 0;
2377 
2378 	if (dateobj->time) {
2379 		timelib_time_dtor(dateobj->time);
2380 	}
2381 	if (format) {
2382 		if (time_str_len == 0) {
2383 			time_str = "";
2384 		}
2385 		dateobj->time = timelib_parse_from_format(format, time_str, time_str_len, &err, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
2386 	} else {
2387 		if (time_str_len == 0) {
2388 			time_str = "now";
2389 			time_str_len = sizeof("now") - 1;
2390 		}
2391 		dateobj->time = timelib_strtotime(time_str, time_str_len, &err, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
2392 	}
2393 
2394 	/* update last errors and warnings */
2395 	update_errors_warnings(&err);
2396 
2397 	/* If called from a constructor throw an exception */
2398 	if ((flags & PHP_DATE_INIT_CTOR) && err && err->error_count) {
2399 		/* spit out the first library error message, at least */
2400 		zend_throw_exception_ex(date_ce_date_malformed_string_exception, 0, "Failed to parse time string (%s) at position %d (%c): %s", time_str,
2401 			err->error_messages[0].position, err->error_messages[0].character ? err->error_messages[0].character : ' ', err->error_messages[0].message);
2402 	}
2403 	if (err && err->error_count) {
2404 		timelib_time_dtor(dateobj->time);
2405 		dateobj->time = 0;
2406 		return 0;
2407 	}
2408 
2409 	if (timezone_object) {
2410 		php_timezone_obj *tzobj;
2411 
2412 		tzobj = Z_PHPTIMEZONE_P(timezone_object);
2413 		switch (tzobj->type) {
2414 			case TIMELIB_ZONETYPE_ID:
2415 				tzi = tzobj->tzi.tz;
2416 				break;
2417 			case TIMELIB_ZONETYPE_OFFSET:
2418 				new_offset = tzobj->tzi.utc_offset;
2419 				break;
2420 			case TIMELIB_ZONETYPE_ABBR:
2421 				new_offset = tzobj->tzi.z.utc_offset;
2422 				new_dst    = tzobj->tzi.z.dst;
2423 				new_abbr   = timelib_strdup(tzobj->tzi.z.abbr);
2424 				break;
2425 			default:
2426 				zend_throw_error(NULL, "The DateTimeZone object has not been correctly initialized by its constructor");
2427 				return 0;
2428 		}
2429 		type = tzobj->type;
2430 	} else if (dateobj->time->tz_info) {
2431 		tzi = dateobj->time->tz_info;
2432 	} else {
2433 		tzi = get_timezone_info();
2434 		if (!tzi) {
2435 			return 0;
2436 		}
2437 	}
2438 
2439 	now = timelib_time_ctor();
2440 	now->zone_type = type;
2441 	switch (type) {
2442 		case TIMELIB_ZONETYPE_ID:
2443 			now->tz_info = tzi;
2444 			break;
2445 		case TIMELIB_ZONETYPE_OFFSET:
2446 			now->z = new_offset;
2447 			break;
2448 		case TIMELIB_ZONETYPE_ABBR:
2449 			now->z = new_offset;
2450 			now->dst = new_dst;
2451 			now->tz_abbr = new_abbr;
2452 			break;
2453 	}
2454 	php_date_get_current_time_with_fraction(&sec, &usec);
2455 	timelib_unixtime2local(now, (timelib_sll) sec);
2456 	php_date_set_time_fraction(now, usec);
2457 
2458 	if (!format
2459 	 && time_str_len == sizeof("now") - 1
2460 	 && memcmp(time_str, "now", sizeof("now") - 1) == 0) {
2461 		timelib_time_dtor(dateobj->time);
2462 		dateobj->time = now;
2463 		return 1;
2464 	}
2465 
2466 	options = TIMELIB_NO_CLONE;
2467 	if (flags & PHP_DATE_INIT_FORMAT) {
2468 		options |= TIMELIB_OVERRIDE_TIME;
2469 	}
2470 	timelib_fill_holes(dateobj->time, now, options);
2471 
2472 	timelib_update_ts(dateobj->time, tzi);
2473 	timelib_update_from_sse(dateobj->time);
2474 
2475 	dateobj->time->have_relative = 0;
2476 
2477 	timelib_time_dtor(now);
2478 
2479 	return 1;
2480 } /* }}} */
2481 
php_date_initialize_from_ts_long(php_date_obj * dateobj,zend_long sec,int usec)2482 PHPAPI void php_date_initialize_from_ts_long(php_date_obj *dateobj, zend_long sec, int usec) /* {{{ */
2483 {
2484 	dateobj->time = timelib_time_ctor();
2485 	dateobj->time->zone_type = TIMELIB_ZONETYPE_OFFSET;
2486 
2487 	timelib_unixtime2gmt(dateobj->time, (timelib_sll)sec);
2488 	timelib_update_ts(dateobj->time, NULL);
2489 	php_date_set_time_fraction(dateobj->time, usec);
2490 } /* }}} */
2491 
php_date_initialize_from_ts_double(php_date_obj * dateobj,double ts)2492 PHPAPI bool php_date_initialize_from_ts_double(php_date_obj *dateobj, double ts) /* {{{ */
2493 {
2494 	double sec_dval = trunc(ts);
2495 	zend_long sec;
2496 	int usec;
2497 
2498 	if (UNEXPECTED(isnan(sec_dval) || !PHP_DATE_DOUBLE_FITS_LONG(sec_dval))) {
2499 		zend_argument_error(
2500 			date_ce_date_range_error,
2501 			1,
2502 			"must be a finite number between " TIMELIB_LONG_FMT " and " TIMELIB_LONG_FMT ".999999, %g given",
2503 			TIMELIB_LONG_MIN,
2504 			TIMELIB_LONG_MAX,
2505 			ts
2506 		);
2507 		return false;
2508 	}
2509 
2510 	sec = (zend_long)sec_dval;
2511 	usec = (int) round(fmod(ts, 1) * 1000000);
2512 
2513 	if (UNEXPECTED(abs(usec) == 1000000)) {
2514 		sec += usec > 0 ? 1 : -1;
2515 		usec = 0;
2516 	}
2517 
2518 	if (UNEXPECTED(usec < 0)) {
2519 		if (UNEXPECTED(sec == TIMELIB_LONG_MIN)) {
2520 			zend_argument_error(
2521 				date_ce_date_range_error,
2522 				1,
2523 				"must be a finite number between " TIMELIB_LONG_FMT " and " TIMELIB_LONG_FMT ".999999, %g given",
2524 				TIMELIB_LONG_MIN,
2525 				TIMELIB_LONG_MAX,
2526 				ts
2527 			);
2528 			return false;
2529 		}
2530 
2531 		sec = sec - 1;
2532 		usec = 1000000 + usec;
2533 	}
2534 
2535 	php_date_initialize_from_ts_long(dateobj, sec, usec);
2536 
2537 	return true;
2538 } /* }}} */
2539 
2540 /* {{{ Returns new DateTime object */
PHP_FUNCTION(date_create)2541 PHP_FUNCTION(date_create)
2542 {
2543 	zval           *timezone_object = NULL;
2544 	char           *time_str = NULL;
2545 	size_t          time_str_len = 0;
2546 
2547 	ZEND_PARSE_PARAMETERS_START(0, 2)
2548 		Z_PARAM_OPTIONAL
2549 		Z_PARAM_STRING(time_str, time_str_len)
2550 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2551 	ZEND_PARSE_PARAMETERS_END();
2552 
2553 	php_date_instantiate(date_ce_date, return_value);
2554 	if (!php_date_initialize(Z_PHPDATE_P(return_value), time_str, time_str_len, NULL, timezone_object, 0)) {
2555 		zval_ptr_dtor(return_value);
2556 		RETURN_FALSE;
2557 	}
2558 }
2559 /* }}} */
2560 
2561 /* {{{ Returns new DateTimeImmutable object */
PHP_FUNCTION(date_create_immutable)2562 PHP_FUNCTION(date_create_immutable)
2563 {
2564 	zval           *timezone_object = NULL;
2565 	char           *time_str = NULL;
2566 	size_t          time_str_len = 0;
2567 
2568 	ZEND_PARSE_PARAMETERS_START(0, 2)
2569 		Z_PARAM_OPTIONAL
2570 		Z_PARAM_STRING(time_str, time_str_len)
2571 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2572 	ZEND_PARSE_PARAMETERS_END();
2573 
2574 	php_date_instantiate(date_ce_immutable, return_value);
2575 	if (!php_date_initialize(Z_PHPDATE_P(return_value), time_str, time_str_len, NULL, timezone_object, 0)) {
2576 		zval_ptr_dtor(return_value);
2577 		RETURN_FALSE;
2578 	}
2579 }
2580 /* }}} */
2581 
2582 /* {{{ Returns new DateTime object formatted according to the specified format */
PHP_FUNCTION(date_create_from_format)2583 PHP_FUNCTION(date_create_from_format)
2584 {
2585 	zval           *timezone_object = NULL;
2586 	char           *time_str = NULL, *format_str = NULL;
2587 	size_t          time_str_len = 0, format_str_len = 0;
2588 
2589 	ZEND_PARSE_PARAMETERS_START(2, 3)
2590 		Z_PARAM_STRING(format_str, format_str_len)
2591 		Z_PARAM_PATH(time_str, time_str_len)
2592 		Z_PARAM_OPTIONAL
2593 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2594 	ZEND_PARSE_PARAMETERS_END();
2595 
2596 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_date, return_value);
2597 	if (!php_date_initialize(Z_PHPDATE_P(return_value), time_str, time_str_len, format_str, timezone_object, PHP_DATE_INIT_FORMAT)) {
2598 		zval_ptr_dtor(return_value);
2599 		RETURN_FALSE;
2600 	}
2601 }
2602 /* }}} */
2603 
2604 /* {{{ Returns new DateTimeImmutable object formatted according to the specified format */
PHP_FUNCTION(date_create_immutable_from_format)2605 PHP_FUNCTION(date_create_immutable_from_format)
2606 {
2607 	zval           *timezone_object = NULL;
2608 	char           *time_str = NULL, *format_str = NULL;
2609 	size_t          time_str_len = 0, format_str_len = 0;
2610 
2611 	ZEND_PARSE_PARAMETERS_START(2, 3)
2612 		Z_PARAM_STRING(format_str, format_str_len)
2613 		Z_PARAM_PATH(time_str, time_str_len)
2614 		Z_PARAM_OPTIONAL
2615 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2616 	ZEND_PARSE_PARAMETERS_END();
2617 
2618 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_immutable, return_value);
2619 	if (!php_date_initialize(Z_PHPDATE_P(return_value), time_str, time_str_len, format_str, timezone_object, PHP_DATE_INIT_FORMAT)) {
2620 		zval_ptr_dtor(return_value);
2621 		RETURN_FALSE;
2622 	}
2623 }
2624 /* }}} */
2625 
2626 /* {{{ Creates new DateTime object */
PHP_METHOD(DateTime,__construct)2627 PHP_METHOD(DateTime, __construct)
2628 {
2629 	zval *timezone_object = NULL;
2630 	char *time_str = NULL;
2631 	size_t time_str_len = 0;
2632 
2633 	ZEND_PARSE_PARAMETERS_START(0, 2)
2634 		Z_PARAM_OPTIONAL
2635 		Z_PARAM_STRING(time_str, time_str_len)
2636 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2637 	ZEND_PARSE_PARAMETERS_END();
2638 
2639 	php_date_initialize(Z_PHPDATE_P(ZEND_THIS), time_str, time_str_len, NULL, timezone_object, PHP_DATE_INIT_CTOR);
2640 }
2641 /* }}} */
2642 
2643 /* {{{ Creates new DateTimeImmutable object */
PHP_METHOD(DateTimeImmutable,__construct)2644 PHP_METHOD(DateTimeImmutable, __construct)
2645 {
2646 	zval *timezone_object = NULL;
2647 	char *time_str = NULL;
2648 	size_t time_str_len = 0;
2649 
2650 	ZEND_PARSE_PARAMETERS_START(0, 2)
2651 		Z_PARAM_OPTIONAL
2652 		Z_PARAM_STRING(time_str, time_str_len)
2653 		Z_PARAM_OBJECT_OF_CLASS_OR_NULL(timezone_object, date_ce_timezone)
2654 	ZEND_PARSE_PARAMETERS_END();
2655 
2656 	php_date_initialize(Z_PHPDATE_P(ZEND_THIS), time_str, time_str_len, NULL, timezone_object, PHP_DATE_INIT_CTOR);
2657 }
2658 /* }}} */
2659 
2660 /* {{{ Creates new DateTime object from an existing immutable DateTimeImmutable object. */
PHP_METHOD(DateTime,createFromImmutable)2661 PHP_METHOD(DateTime, createFromImmutable)
2662 {
2663 	zval *datetimeimmutable_object = NULL;
2664 	php_date_obj *new_obj = NULL;
2665 	php_date_obj *old_obj = NULL;
2666 
2667 	ZEND_PARSE_PARAMETERS_START(1, 1)
2668 		Z_PARAM_OBJECT_OF_CLASS(datetimeimmutable_object, date_ce_immutable)
2669 	ZEND_PARSE_PARAMETERS_END();
2670 
2671 	old_obj = Z_PHPDATE_P(datetimeimmutable_object);
2672 	DATE_CHECK_INITIALIZED(old_obj->time, Z_OBJCE_P(datetimeimmutable_object));
2673 
2674 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_date, return_value);
2675 	new_obj = Z_PHPDATE_P(return_value);
2676 
2677 	new_obj->time = timelib_time_clone(old_obj->time);
2678 }
2679 /* }}} */
2680 
2681 /* {{{ Creates new DateTime object from an existing DateTimeInterface object. */
PHP_METHOD(DateTime,createFromInterface)2682 PHP_METHOD(DateTime, createFromInterface)
2683 {
2684 	zval *datetimeinterface_object = NULL;
2685 	php_date_obj *new_obj = NULL;
2686 	php_date_obj *old_obj = NULL;
2687 
2688 	ZEND_PARSE_PARAMETERS_START(1, 1)
2689 		Z_PARAM_OBJECT_OF_CLASS(datetimeinterface_object, date_ce_interface)
2690 	ZEND_PARSE_PARAMETERS_END();
2691 
2692 	old_obj = Z_PHPDATE_P(datetimeinterface_object);
2693 	DATE_CHECK_INITIALIZED(old_obj->time, Z_OBJCE_P(datetimeinterface_object));
2694 
2695 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_date, return_value);
2696 	new_obj = Z_PHPDATE_P(return_value);
2697 
2698 	new_obj->time = timelib_time_clone(old_obj->time);
2699 }
2700 /* }}} */
2701 
2702 /* {{{ Creates new DateTime object from given unix timestamp */
PHP_METHOD(DateTime,createFromTimestamp)2703 PHP_METHOD(DateTime, createFromTimestamp)
2704 {
2705 	zval         *value;
2706 	zval         new_object;
2707 	php_date_obj *new_dateobj;
2708 
2709 	ZEND_PARSE_PARAMETERS_START(1, 1)
2710 		Z_PARAM_NUMBER(value)
2711 	ZEND_PARSE_PARAMETERS_END();
2712 
2713 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_date, &new_object);
2714 	new_dateobj = Z_PHPDATE_P(&new_object);
2715 
2716 	switch (Z_TYPE_P(value)) {
2717 		case IS_LONG:
2718 			php_date_initialize_from_ts_long(new_dateobj, Z_LVAL_P(value), 0);
2719 			break;
2720 
2721 		case IS_DOUBLE:
2722 			if (!php_date_initialize_from_ts_double(new_dateobj, Z_DVAL_P(value))) {
2723 				zval_ptr_dtor(&new_object);
2724 				RETURN_THROWS();
2725 			}
2726 			break;
2727 
2728 		EMPTY_SWITCH_DEFAULT_CASE();
2729 	}
2730 
2731 	RETURN_OBJ(Z_OBJ(new_object));
2732 }
2733 /* }}} */
2734 
2735 /* {{{ Creates new DateTimeImmutable object from an existing mutable DateTime object. */
PHP_METHOD(DateTimeImmutable,createFromMutable)2736 PHP_METHOD(DateTimeImmutable, createFromMutable)
2737 {
2738 	zval *datetime_object = NULL;
2739 	php_date_obj *new_obj = NULL;
2740 	php_date_obj *old_obj = NULL;
2741 
2742 	ZEND_PARSE_PARAMETERS_START(1, 1)
2743 		Z_PARAM_OBJECT_OF_CLASS(datetime_object, date_ce_date)
2744 	ZEND_PARSE_PARAMETERS_END();
2745 
2746 	old_obj = Z_PHPDATE_P(datetime_object);
2747 	DATE_CHECK_INITIALIZED(old_obj->time, Z_OBJCE_P(datetime_object));
2748 
2749 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_immutable, return_value);
2750 	new_obj = Z_PHPDATE_P(return_value);
2751 
2752 	new_obj->time = timelib_time_clone(old_obj->time);
2753 }
2754 /* }}} */
2755 
2756 /* {{{ Creates new DateTimeImmutable object from an existing DateTimeInterface object. */
PHP_METHOD(DateTimeImmutable,createFromInterface)2757 PHP_METHOD(DateTimeImmutable, createFromInterface)
2758 {
2759 	zval *datetimeinterface_object = NULL;
2760 	php_date_obj *new_obj = NULL;
2761 	php_date_obj *old_obj = NULL;
2762 
2763 	ZEND_PARSE_PARAMETERS_START(1, 1)
2764 		Z_PARAM_OBJECT_OF_CLASS(datetimeinterface_object, date_ce_interface)
2765 	ZEND_PARSE_PARAMETERS_END();
2766 
2767 	old_obj = Z_PHPDATE_P(datetimeinterface_object);
2768 	DATE_CHECK_INITIALIZED(old_obj->time, Z_OBJCE_P(datetimeinterface_object));
2769 
2770 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_immutable, return_value);
2771 	new_obj = Z_PHPDATE_P(return_value);
2772 
2773 	new_obj->time = timelib_time_clone(old_obj->time);
2774 }
2775 /* }}} */
2776 
2777 /* {{{ Creates new DateTimeImmutable object from given unix timestamp */
PHP_METHOD(DateTimeImmutable,createFromTimestamp)2778 PHP_METHOD(DateTimeImmutable, createFromTimestamp)
2779 {
2780 	zval         *value;
2781 	zval         new_object;
2782 	php_date_obj *new_dateobj;
2783 
2784 	ZEND_PARSE_PARAMETERS_START(1, 1)
2785 		Z_PARAM_NUMBER(value)
2786 	ZEND_PARSE_PARAMETERS_END();
2787 
2788 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_immutable, &new_object);
2789 	new_dateobj = Z_PHPDATE_P(&new_object);
2790 
2791 	switch (Z_TYPE_P(value)) {
2792 		case IS_LONG:
2793 			php_date_initialize_from_ts_long(new_dateobj, Z_LVAL_P(value), 0);
2794 			break;
2795 
2796 		case IS_DOUBLE:
2797 			if (!php_date_initialize_from_ts_double(new_dateobj, Z_DVAL_P(value))) {
2798 				zval_ptr_dtor(&new_object);
2799 				RETURN_THROWS();
2800 			}
2801 			break;
2802 
2803 		EMPTY_SWITCH_DEFAULT_CASE();
2804 	}
2805 
2806 	RETURN_OBJ(Z_OBJ(new_object));
2807 }
2808 /* }}} */
2809 
php_date_initialize_from_hash(php_date_obj ** dateobj,HashTable * myht)2810 static bool php_date_initialize_from_hash(php_date_obj **dateobj, HashTable *myht)
2811 {
2812 	zval             *z_date;
2813 	zval             *z_timezone_type;
2814 	zval             *z_timezone;
2815 	zval              tmp_obj;
2816 	timelib_tzinfo   *tzi;
2817 
2818 	z_date = zend_hash_str_find(myht, "date", sizeof("date")-1);
2819 	if (!z_date || Z_TYPE_P(z_date) != IS_STRING) {
2820 		return false;
2821 	}
2822 
2823 	z_timezone_type = zend_hash_str_find(myht, "timezone_type", sizeof("timezone_type")-1);
2824 	if (!z_timezone_type || Z_TYPE_P(z_timezone_type) != IS_LONG) {
2825 		return false;
2826 	}
2827 
2828 	z_timezone = zend_hash_str_find(myht, "timezone", sizeof("timezone")-1);
2829 	if (!z_timezone || Z_TYPE_P(z_timezone) != IS_STRING) {
2830 		return false;
2831 	}
2832 
2833 	switch (Z_LVAL_P(z_timezone_type)) {
2834 		case TIMELIB_ZONETYPE_OFFSET:
2835 		case TIMELIB_ZONETYPE_ABBR: {
2836 			zend_string *tmp = zend_string_concat3(
2837 				Z_STRVAL_P(z_date), Z_STRLEN_P(z_date), " ", 1,
2838 				Z_STRVAL_P(z_timezone), Z_STRLEN_P(z_timezone));
2839 			bool ret = php_date_initialize(*dateobj, ZSTR_VAL(tmp), ZSTR_LEN(tmp), NULL, NULL, 0);
2840 			zend_string_release(tmp);
2841 			return ret;
2842 		}
2843 
2844 		case TIMELIB_ZONETYPE_ID: {
2845 			bool ret;
2846 			php_timezone_obj *tzobj;
2847 
2848 			tzi = php_date_parse_tzfile(Z_STRVAL_P(z_timezone), DATE_TIMEZONEDB);
2849 
2850 			if (tzi == NULL) {
2851 				return false;
2852 			}
2853 
2854 			tzobj = Z_PHPTIMEZONE_P(php_date_instantiate(date_ce_timezone, &tmp_obj));
2855 			tzobj->type = TIMELIB_ZONETYPE_ID;
2856 			tzobj->tzi.tz = tzi;
2857 			tzobj->initialized = 1;
2858 
2859 			ret = php_date_initialize(*dateobj, Z_STRVAL_P(z_date), Z_STRLEN_P(z_date), NULL, &tmp_obj, 0);
2860 			zval_ptr_dtor(&tmp_obj);
2861 			return ret;
2862 		}
2863 	}
2864 	return false;
2865 } /* }}} */
2866 
2867 /* {{{ */
PHP_METHOD(DateTime,__set_state)2868 PHP_METHOD(DateTime, __set_state)
2869 {
2870 	php_date_obj     *dateobj;
2871 	zval             *array;
2872 	HashTable        *myht;
2873 
2874 	ZEND_PARSE_PARAMETERS_START(1, 1)
2875 		Z_PARAM_ARRAY(array)
2876 	ZEND_PARSE_PARAMETERS_END();
2877 
2878 	myht = Z_ARRVAL_P(array);
2879 
2880 	php_date_instantiate(date_ce_date, return_value);
2881 	dateobj = Z_PHPDATE_P(return_value);
2882 	if (!php_date_initialize_from_hash(&dateobj, myht)) {
2883 		zend_throw_error(NULL, "Invalid serialization data for DateTime object");
2884 		RETURN_THROWS();
2885 	}
2886 }
2887 /* }}} */
2888 
2889 /* {{{ */
PHP_METHOD(DateTimeImmutable,__set_state)2890 PHP_METHOD(DateTimeImmutable, __set_state)
2891 {
2892 	php_date_obj     *dateobj;
2893 	zval             *array;
2894 	HashTable        *myht;
2895 
2896 	ZEND_PARSE_PARAMETERS_START(1, 1)
2897 		Z_PARAM_ARRAY(array)
2898 	ZEND_PARSE_PARAMETERS_END();
2899 
2900 	myht = Z_ARRVAL_P(array);
2901 
2902 	php_date_instantiate(date_ce_immutable, return_value);
2903 	dateobj = Z_PHPDATE_P(return_value);
2904 	if (!php_date_initialize_from_hash(&dateobj, myht)) {
2905 		zend_throw_error(NULL, "Invalid serialization data for DateTimeImmutable object");
2906 		RETURN_THROWS();
2907 	}
2908 }
2909 /* }}} */
2910 
2911 /* {{{ */
PHP_METHOD(DateTime,__serialize)2912 PHP_METHOD(DateTime, __serialize)
2913 {
2914 	zval             *object = ZEND_THIS;
2915 	php_date_obj     *dateobj;
2916 	HashTable        *myht;
2917 
2918 	ZEND_PARSE_PARAMETERS_NONE();
2919 
2920 	dateobj = Z_PHPDATE_P(object);
2921 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
2922 
2923 	array_init(return_value);
2924 	myht = Z_ARRVAL_P(return_value);
2925 	date_object_to_hash(dateobj, myht);
2926 
2927 	add_common_properties(myht, &dateobj->std);
2928 }
2929 /* }}} */
2930 
2931 /* {{{ */
PHP_METHOD(DateTimeImmutable,__serialize)2932 PHP_METHOD(DateTimeImmutable, __serialize)
2933 {
2934 	zval             *object = ZEND_THIS;
2935 	php_date_obj     *dateobj;
2936 	HashTable        *myht;
2937 
2938 	ZEND_PARSE_PARAMETERS_NONE();
2939 
2940 	dateobj = Z_PHPDATE_P(object);
2941 	DATE_CHECK_INITIALIZED(dateobj->time, Z_OBJCE_P(object));
2942 
2943 	array_init(return_value);
2944 	myht = Z_ARRVAL_P(return_value);
2945 	date_object_to_hash(dateobj, myht);
2946 
2947 	add_common_properties(myht, &dateobj->std);
2948 }
2949 /* }}} */
2950 
date_time_is_internal_property(zend_string * name)2951 static bool date_time_is_internal_property(