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