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