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