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