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