xref: /PHP-7.4/ext/date/lib/tm2unixtime.c (revision 778902db)
1 /*
2  * The MIT License (MIT)
3  *
4  * Copyright (c) 2015-2019 Derick Rethans
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "timelib.h"
26 #include "timelib_private.h"
27 
28 /*                                    jan  feb  mrt  apr  may  jun  jul  aug  sep  oct  nov  dec */
29 static int month_tab_leap[12]     = {  -1,  30,  59,  90, 120, 151, 181, 212, 243, 273, 304, 334 };
30 static int month_tab[12]          = {   0,  31,  59,  90, 120, 151, 181, 212, 243, 273, 304, 334 };
31 
32 /*                                    dec  jan  feb  mrt  apr  may  jun  jul  aug  sep  oct  nov  dec */
33 static int days_in_month_leap[13] = {  31,  31,  29,  31,  30,  31,  30,  31,  31,  30,  31,  30,  31 };
34 static int days_in_month[13]      = {  31,  31,  28,  31,  30,  31,  30,  31,  31,  30,  31,  30,  31 };
35 
do_range_limit(timelib_sll start,timelib_sll end,timelib_sll adj,timelib_sll * a,timelib_sll * b)36 static void do_range_limit(timelib_sll start, timelib_sll end, timelib_sll adj, timelib_sll *a, timelib_sll *b)
37 {
38 	if (*a < start) {
39 		*b -= (start - *a - 1) / adj + 1;
40 		*a += adj * ((start - *a - 1) / adj + 1);
41 	}
42 	if (*a >= end) {
43 		*b += *a / adj;
44 		*a -= adj * (*a / adj);
45 	}
46 }
47 
inc_month(timelib_sll * y,timelib_sll * m)48 static void inc_month(timelib_sll *y, timelib_sll *m)
49 {
50 	(*m)++;
51 	if (*m > 12) {
52 		*m -= 12;
53 		(*y)++;
54 	}
55 }
56 
dec_month(timelib_sll * y,timelib_sll * m)57 static void dec_month(timelib_sll *y, timelib_sll *m)
58 {
59 	(*m)--;
60 	if (*m < 1) {
61 		*m += 12;
62 		(*y)--;
63 	}
64 }
65 
do_range_limit_days_relative(timelib_sll * base_y,timelib_sll * base_m,timelib_sll * y,timelib_sll * m,timelib_sll * d,timelib_sll invert)66 static void do_range_limit_days_relative(timelib_sll *base_y, timelib_sll *base_m, timelib_sll *y, timelib_sll *m, timelib_sll *d, timelib_sll invert)
67 {
68 	timelib_sll leapyear;
69 	timelib_sll month, year;
70 	timelib_sll days;
71 
72 	do_range_limit(1, 13, 12, base_m, base_y);
73 
74 	year = *base_y;
75 	month = *base_m;
76 
77 /*
78 	printf( "S: Y%d M%d   %d %d %d   %d\n", year, month, *y, *m, *d, days);
79 */
80 	if (!invert) {
81 		while (*d < 0) {
82 			dec_month(&year, &month);
83 			leapyear = timelib_is_leap(year);
84 			days = leapyear ? days_in_month_leap[month] : days_in_month[month];
85 
86 			/* printf( "I  Y%d M%d   %d %d %d   %d\n", year, month, *y, *m, *d, days); */
87 
88 			*d += days;
89 			(*m)--;
90 		}
91 	} else {
92 		while (*d < 0) {
93 			leapyear = timelib_is_leap(year);
94 			days = leapyear ? days_in_month_leap[month] : days_in_month[month];
95 
96 			/* printf( "I  Y%d M%d   %d %d %d   %d\n", year, month, *y, *m, *d, days); */
97 
98 			*d += days;
99 			(*m)--;
100 			inc_month(&year, &month);
101 		}
102 	}
103 	/*
104 	printf( "E: Y%d M%d   %d %d %d   %d\n", year, month, *y, *m, *d, days);
105 	*/
106 }
107 
do_range_limit_days(timelib_sll * y,timelib_sll * m,timelib_sll * d)108 static int do_range_limit_days(timelib_sll *y, timelib_sll *m, timelib_sll *d)
109 {
110 	timelib_sll leapyear;
111 	timelib_sll days_this_month;
112 	timelib_sll last_month, last_year;
113 	timelib_sll days_last_month;
114 
115 	/* can jump an entire leap year period quickly */
116 	if (*d >= DAYS_PER_LYEAR_PERIOD || *d <= -DAYS_PER_LYEAR_PERIOD) {
117 		*y += YEARS_PER_LYEAR_PERIOD * (*d / DAYS_PER_LYEAR_PERIOD);
118 		*d -= DAYS_PER_LYEAR_PERIOD * (*d / DAYS_PER_LYEAR_PERIOD);
119 	}
120 
121 	do_range_limit(1, 13, 12, m, y);
122 
123 	leapyear = timelib_is_leap(*y);
124 	days_this_month = leapyear ? days_in_month_leap[*m] : days_in_month[*m];
125 	last_month = (*m) - 1;
126 
127 	if (last_month < 1) {
128 		last_month += 12;
129 		last_year = (*y) - 1;
130 	} else {
131 		last_year = (*y);
132 	}
133 	leapyear = timelib_is_leap(last_year);
134 	days_last_month = leapyear ? days_in_month_leap[last_month] : days_in_month[last_month];
135 
136 	if (*d <= 0) {
137 		*d += days_last_month;
138 		(*m)--;
139 		return 1;
140 	}
141 	if (*d > days_this_month) {
142 		*d -= days_this_month;
143 		(*m)++;
144 		return 1;
145 	}
146 	return 0;
147 }
148 
do_adjust_for_weekday(timelib_time * time)149 static void do_adjust_for_weekday(timelib_time* time)
150 {
151 	timelib_sll current_dow, difference;
152 
153 	current_dow = timelib_day_of_week(time->y, time->m, time->d);
154 	if (time->relative.weekday_behavior == 2)
155 	{
156 		/* To make "this week" work, where the current DOW is a "sunday" */
157 		if (current_dow == 0 && time->relative.weekday != 0) {
158 			time->relative.weekday -= 7;
159 		}
160 
161 		/* To make "sunday this week" work, where the current DOW is not a
162 		 * "sunday" */
163 		if (time->relative.weekday == 0 && current_dow != 0) {
164 			time->relative.weekday = 7;
165 		}
166 
167 		time->d -= current_dow;
168 		time->d += time->relative.weekday;
169 		return;
170 	}
171 	difference = time->relative.weekday - current_dow;
172 	if ((time->relative.d < 0 && difference < 0) || (time->relative.d >= 0 && difference <= -time->relative.weekday_behavior)) {
173 		difference += 7;
174 	}
175 	if (time->relative.weekday >= 0) {
176 		time->d += difference;
177 	} else {
178 		time->d -= (7 - (abs(time->relative.weekday) - current_dow));
179 	}
180 	time->relative.have_weekday_relative = 0;
181 }
182 
timelib_do_rel_normalize(timelib_time * base,timelib_rel_time * rt)183 void timelib_do_rel_normalize(timelib_time *base, timelib_rel_time *rt)
184 {
185 	do_range_limit(0, 1000000, 1000000, &rt->us, &rt->s);
186 	do_range_limit(0, 60, 60, &rt->s, &rt->i);
187 	do_range_limit(0, 60, 60, &rt->i, &rt->h);
188 	do_range_limit(0, 24, 24, &rt->h, &rt->d);
189 	do_range_limit(0, 12, 12, &rt->m, &rt->y);
190 
191 	do_range_limit_days_relative(&base->y, &base->m, &rt->y, &rt->m, &rt->d, rt->invert);
192 	do_range_limit(0, 12, 12, &rt->m, &rt->y);
193 }
194 
195 #define EPOCH_DAY 719468
196 
magic_date_calc(timelib_time * time)197 static void magic_date_calc(timelib_time *time)
198 {
199 	timelib_sll y, ddd, mi, mm, dd, g;
200 
201 	/* The algorithm doesn't work before the year 1 */
202 	if (time->d < -719498) {
203 		return;
204 	}
205 
206 	g = time->d + EPOCH_DAY - 1;
207 
208 	y = (10000 * g + 14780) / 3652425;
209 	ddd = g - ((365*y) + (y/4) - (y/100) + (y/400));
210 	if (ddd < 0) {
211 		y--;
212 		ddd = g - ((365*y) + (y/4) - (y/100) + (y/400));
213 	}
214 	mi = (100 * ddd + 52) / 3060;
215 	mm = ((mi + 2) % 12) + 1;
216 	y = y + (mi + 2) / 12;
217 	dd = ddd - ((mi * 306 + 5) / 10) + 1;
218 	time->y = y;
219 	time->m = mm;
220 	time->d = dd;
221 }
222 
timelib_do_normalize(timelib_time * time)223 void timelib_do_normalize(timelib_time* time)
224 {
225 	if (time->us != TIMELIB_UNSET) do_range_limit(0, 1000000, 1000000, &time->us, &time->s);
226 	if (time->s != TIMELIB_UNSET) do_range_limit(0, 60, 60, &time->s, &time->i);
227 	if (time->s != TIMELIB_UNSET) do_range_limit(0, 60, 60, &time->i, &time->h);
228 	if (time->s != TIMELIB_UNSET) do_range_limit(0, 24, 24, &time->h, &time->d);
229 	do_range_limit(1, 13, 12, &time->m, &time->y);
230 
231 	/* Short cut if we're doing things against the Epoch */
232 	if (time->y == 1970 && time->m == 1 && time->d != 1) {
233 		magic_date_calc(time);
234 	}
235 
236 	do {} while (do_range_limit_days(&time->y, &time->m, &time->d));
237 	do_range_limit(1, 13, 12, &time->m, &time->y);
238 }
239 
do_adjust_relative(timelib_time * time)240 static void do_adjust_relative(timelib_time* time)
241 {
242 	if (time->relative.have_weekday_relative) {
243 		do_adjust_for_weekday(time);
244 	}
245 	timelib_do_normalize(time);
246 
247 	if (time->have_relative) {
248 		time->us += time->relative.us;
249 
250 		time->s += time->relative.s;
251 		time->i += time->relative.i;
252 		time->h += time->relative.h;
253 
254 		time->d += time->relative.d;
255 		time->m += time->relative.m;
256 		time->y += time->relative.y;
257 	}
258 
259 	switch (time->relative.first_last_day_of) {
260 		case TIMELIB_SPECIAL_FIRST_DAY_OF_MONTH: /* first */
261 			time->d = 1;
262 			break;
263 		case TIMELIB_SPECIAL_LAST_DAY_OF_MONTH: /* last */
264 			time->d = 0;
265 			time->m++;
266 			break;
267 	}
268 
269 	timelib_do_normalize(time);
270 }
271 
do_adjust_special_weekday(timelib_time * time)272 static void do_adjust_special_weekday(timelib_time* time)
273 {
274 	timelib_sll count, dow, rem;
275 
276 	count = time->relative.special.amount;
277 	dow = timelib_day_of_week(time->y, time->m, time->d);
278 
279 	/* Add increments of 5 weekdays as a week, leaving the DOW unchanged. */
280 	time->d += (count / 5) * 7;
281 
282 	/* Deal with the remainder. */
283 	rem = (count % 5);
284 
285 	if (count > 0) {
286 		if (rem == 0) {
287 			/* Head back to Friday if we stop on the weekend. */
288 			if (dow == 0) {
289 				time->d -= 2;
290 			} else if (dow == 6) {
291 				time->d -= 1;
292 			}
293 		} else if (dow == 6) {
294 			/* We ended up on Saturday, but there's still work to do, so move
295 			 * to Sunday and continue from there. */
296 			time->d += 1;
297 		} else if (dow + rem > 5) {
298 			/* We're on a weekday, but we're going past Friday, so skip right
299 			 * over the weekend. */
300 			time->d += 2;
301 		}
302 	} else {
303 		/* Completely mirror the forward direction. This also covers the 0
304 		 * case, since if we start on the weekend, we want to move forward as
305 		 * if we stopped there while going backwards. */
306 		if (rem == 0) {
307 			if (dow == 6) {
308 				time->d += 2;
309 			} else if (dow == 0) {
310 				time->d += 1;
311 			}
312 		} else if (dow == 0) {
313 			time->d -= 1;
314 		} else if (dow + rem < 1) {
315 			time->d -= 2;
316 		}
317 	}
318 
319 	time->d += rem;
320 }
321 
do_adjust_special(timelib_time * time)322 static void do_adjust_special(timelib_time* time)
323 {
324 	if (time->relative.have_special_relative) {
325 		switch (time->relative.special.type) {
326 			case TIMELIB_SPECIAL_WEEKDAY:
327 				do_adjust_special_weekday(time);
328 				break;
329 		}
330 	}
331 	timelib_do_normalize(time);
332 	memset(&(time->relative.special), 0, sizeof(time->relative.special));
333 }
334 
do_adjust_special_early(timelib_time * time)335 static void do_adjust_special_early(timelib_time* time)
336 {
337 	if (time->relative.have_special_relative) {
338 		switch (time->relative.special.type) {
339 			case TIMELIB_SPECIAL_DAY_OF_WEEK_IN_MONTH:
340 				time->d = 1;
341 				time->m += time->relative.m;
342 				time->relative.m = 0;
343 				break;
344 			case TIMELIB_SPECIAL_LAST_DAY_OF_WEEK_IN_MONTH:
345 				time->d = 1;
346 				time->m += time->relative.m + 1;
347 				time->relative.m = 0;
348 				break;
349 		}
350 	}
351 	switch (time->relative.first_last_day_of) {
352 		case TIMELIB_SPECIAL_FIRST_DAY_OF_MONTH: /* first */
353 			time->d = 1;
354 			break;
355 		case TIMELIB_SPECIAL_LAST_DAY_OF_MONTH: /* last */
356 			time->d = 0;
357 			time->m++;
358 			break;
359 	}
360 	timelib_do_normalize(time);
361 }
362 
do_years(timelib_sll year)363 static timelib_sll do_years(timelib_sll year)
364 {
365 	timelib_sll i;
366 	timelib_sll res = 0;
367 	timelib_sll eras;
368 
369 	eras = (year - 1970) / 40000;
370 
371 	/* Hack to make sure we don't overflow. Right now, we can't easily thrown a
372 	 * warning in this case, so we'll just return some rubbish. Sucks, but at
373 	 * least it doesn't show UBSAN warnings anymore */
374 	if (eras < -1000000 || eras > 1000000) {
375 		return eras > 0 ? LLONG_MAX/10 : LLONG_MIN/10;
376 	}
377 
378 	if (eras != 0) {
379 		year = year - (eras * 40000);
380 		res += (SECS_PER_ERA * eras * 100);
381 	}
382 
383 	if (year >= 1970) {
384 		for (i = year - 1; i >= 1970; i--) {
385 			if (timelib_is_leap(i)) {
386 				res += (DAYS_PER_LYEAR * SECS_PER_DAY);
387 			} else {
388 				res += (DAYS_PER_YEAR * SECS_PER_DAY);
389 			}
390 		}
391 	} else {
392 		for (i = 1969; i >= year; i--) {
393 			if (timelib_is_leap(i)) {
394 				res -= (DAYS_PER_LYEAR * SECS_PER_DAY);
395 			} else {
396 				res -= (DAYS_PER_YEAR * SECS_PER_DAY);
397 			}
398 		}
399 	}
400 	return res;
401 }
402 
do_months(timelib_ull month,timelib_sll year)403 static timelib_sll do_months(timelib_ull month, timelib_sll year)
404 {
405 	if (timelib_is_leap(year)) {
406 		return ((month_tab_leap[month - 1] + 1) * SECS_PER_DAY);
407 	} else {
408 		return ((month_tab[month - 1]) * SECS_PER_DAY);
409 	}
410 }
411 
do_days(timelib_ull day)412 static timelib_sll do_days(timelib_ull day)
413 {
414 	return ((day - 1) * SECS_PER_DAY);
415 }
416 
do_time(timelib_ull hour,timelib_ull minute,timelib_ull second)417 static timelib_sll do_time(timelib_ull hour, timelib_ull minute, timelib_ull second)
418 {
419 	timelib_sll res = 0;
420 
421 	res += hour * 3600;
422 	res += minute * 60;
423 	res += second;
424 	return res;
425 }
426 
do_adjust_timezone(timelib_time * tz,timelib_tzinfo * tzi)427 static timelib_sll do_adjust_timezone(timelib_time *tz, timelib_tzinfo *tzi)
428 {
429 	switch (tz->zone_type) {
430 		case TIMELIB_ZONETYPE_OFFSET:
431 
432 			tz->is_localtime = 1;
433 			return -tz->z;
434 			break;
435 
436 		case TIMELIB_ZONETYPE_ABBR: {
437 			timelib_sll tmp;
438 
439 			tz->is_localtime = 1;
440 			tmp = -tz->z;
441 			tmp -= tz->dst * 3600;
442 			return tmp;
443 			}
444 			break;
445 
446 		case TIMELIB_ZONETYPE_ID:
447 			tzi = tz->tz_info;
448 			/* Break intentionally missing */
449 
450 		default:
451 			/* No timezone in struct, fallback to reference if possible */
452 			if (tzi) {
453 				timelib_time_offset *before, *after;
454 				timelib_sll          tmp;
455 				int                  in_transition;
456 
457 				tz->is_localtime = 1;
458 				before = timelib_get_time_zone_info(tz->sse, tzi);
459 				after = timelib_get_time_zone_info(tz->sse - before->offset, tzi);
460 				timelib_set_timezone(tz, tzi);
461 
462 				in_transition = (
463 					((tz->sse - after->offset) >= (after->transition_time + (before->offset - after->offset))) &&
464 					((tz->sse - after->offset) < after->transition_time)
465 				);
466 
467 				if ((before->offset != after->offset) && !in_transition) {
468 					tmp = -after->offset;
469 				} else {
470 					tmp = -tz->z;
471 				}
472 				timelib_time_offset_dtor(before);
473 				timelib_time_offset_dtor(after);
474 
475 				{
476 					timelib_time_offset *gmt_offset;
477 
478 					gmt_offset = timelib_get_time_zone_info(tz->sse + tmp, tzi);
479 					tz->z = gmt_offset->offset;
480 
481 					tz->dst = gmt_offset->is_dst;
482 					if (tz->tz_abbr) {
483 						timelib_free(tz->tz_abbr);
484 					}
485 					tz->tz_abbr = timelib_strdup(gmt_offset->abbr);
486 					timelib_time_offset_dtor(gmt_offset);
487 				}
488 				return tmp;
489 			}
490 	}
491 	return 0;
492 }
493 
timelib_update_ts(timelib_time * time,timelib_tzinfo * tzi)494 void timelib_update_ts(timelib_time* time, timelib_tzinfo* tzi)
495 {
496 	timelib_sll res = 0;
497 
498 	do_adjust_special_early(time);
499 	do_adjust_relative(time);
500 	do_adjust_special(time);
501 	res += do_years(time->y);
502 	res += do_months(time->m, time->y);
503 	res += do_days(time->d);
504 	res += do_time(time->h, time->i, time->s);
505 	time->sse = res;
506 
507 	res += do_adjust_timezone(time, tzi);
508 	time->sse = res;
509 
510 	time->sse_uptodate = 1;
511 	time->have_relative = time->relative.have_weekday_relative = time->relative.have_special_relative = time->relative.first_last_day_of = 0;
512 }
513 
514 #if 0
515 int main(void)
516 {
517 	timelib_sll res;
518 	timelib_time time;
519 
520 	time = timelib_strtotime("10 Feb 2005 06:07:03 PM CET"); /* 1108055223 */
521 	printf ("%04d-%02d-%02d %02d:%02d:%02d.%-5d %+04d %1d",
522 		time.y, time.m, time.d, time.h, time.i, time.s, time.f, time.z, time.dst);
523 	if (time.have_relative) {
524 		printf ("%3dY %3dM %3dD / %3dH %3dM %3dS",
525 			time.relative.y, time.relative.m, time.relative.d, time.relative.h, time.relative.i, time.relative.s);
526 	}
527 	if (time.have_weekday_relative) {
528 		printf (" / %d", time.relative.weekday);
529 	}
530 	res = time2unixtime(&time);
531 	printf("%Ld\n", res);
532 
533 	return 0;
534 }
535 #endif
536