1/*
2 * Copyright (c) 1989, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: src/usr.bin/calendar/day.c,v 1.27 2007/06/09 05:54:13 grog Exp $");
36
37#include <sys/types.h>
38#include <sys/uio.h>
39#include <ctype.h>
40#include <err.h>
41#include <locale.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <string.h>
45#include <time.h>
46
47#include "pathnames.h"
48#include "calendar.h"
49
50struct tm *tp;
51static const struct tm tm0;
52int *cumdays, yrdays;
53char dayname[10];
54
55
56/* 1-based month, 0-based days, cumulative */
57int daytab[][14] = {
58	{ 0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 },
59	{ 0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
60};
61
62static char const *days[] = {
63	"sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
64};
65
66static const char *months[] = {
67	"jan", "feb", "mar", "apr", "may", "jun",
68	"jul", "aug", "sep", "oct", "nov", "dec", NULL,
69};
70
71static struct fixs fndays[8];         /* full national days names */
72static struct fixs ndays[8];          /* short national days names */
73
74static struct fixs fnmonths[13];      /* full national months names */
75static struct fixs nmonths[13];       /* short national month names */
76
77
78void
79setnnames(void)
80{
81	char buf[80];
82	int i, l;
83	struct tm tm;
84
85	for (i = 0; i < 7; i++) {
86		tm.tm_wday = i;
87		strftime(buf, sizeof(buf), "%a", &tm);
88		for (l = strlen(buf);
89		     l > 0 && isspace((unsigned char)buf[l - 1]);
90		     l--)
91			;
92		buf[l] = '\0';
93		if (ndays[i].name != NULL)
94			free(ndays[i].name);
95		if ((ndays[i].name = strdup(buf)) == NULL)
96			errx(1, "cannot allocate memory");
97		ndays[i].len = strlen(buf);
98
99		strftime(buf, sizeof(buf), "%A", &tm);
100		for (l = strlen(buf);
101		     l > 0 && isspace((unsigned char)buf[l - 1]);
102		     l--)
103			;
104		buf[l] = '\0';
105		if (fndays[i].name != NULL)
106			free(fndays[i].name);
107		if ((fndays[i].name = strdup(buf)) == NULL)
108			errx(1, "cannot allocate memory");
109		fndays[i].len = strlen(buf);
110	}
111
112	for (i = 0; i < 12; i++) {
113		tm.tm_mon = i;
114		strftime(buf, sizeof(buf), "%b", &tm);
115		for (l = strlen(buf);
116		     l > 0 && isspace((unsigned char)buf[l - 1]);
117		     l--)
118			;
119		buf[l] = '\0';
120		if (nmonths[i].name != NULL)
121			free(nmonths[i].name);
122		if ((nmonths[i].name = strdup(buf)) == NULL)
123			errx(1, "cannot allocate memory");
124		nmonths[i].len = strlen(buf);
125
126		strftime(buf, sizeof(buf), "%B", &tm);
127		for (l = strlen(buf);
128		     l > 0 && isspace((unsigned char)buf[l - 1]);
129		     l--)
130			;
131		buf[l] = '\0';
132		if (fnmonths[i].name != NULL)
133			free(fnmonths[i].name);
134		if ((fnmonths[i].name = strdup(buf)) == NULL)
135			errx(1, "cannot allocate memory");
136		fnmonths[i].len = strlen(buf);
137	}
138}
139
140void
141settime(time_t now)
142{
143	char *oldl, *lbufp;
144
145	tp = localtime(&now);
146	if ( isleap(tp->tm_year + 1900) ) {
147		yrdays = 366;
148		cumdays = daytab[1];
149	} else {
150		yrdays = 365;
151		cumdays = daytab[0];
152	}
153	/* Friday displays Monday's events */
154	/* -A n ignores weekends */
155	if (f_dayAfter != 0 && Friday != -1) {
156		int weeks = f_dayAfter / 5;
157		int days = f_dayAfter % 5;
158		f_dayAfter += 2 * weeks;
159		if (days &&
160		    (tp->tm_wday <= Friday) &&
161		    (tp->tm_wday+days > Friday)) {
162			f_dayAfter += 2;
163		}
164	}
165	header[5].iov_base = dayname;
166
167	oldl = NULL;
168	lbufp = setlocale(LC_TIME, NULL);
169	if (lbufp != NULL && (oldl = strdup(lbufp)) == NULL)
170		errx(1, "cannot allocate memory");
171	(void) setlocale(LC_TIME, "C");
172	header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
173	(void) setlocale(LC_TIME, (oldl != NULL ? oldl : ""));
174	if (oldl != NULL)
175		free(oldl);
176
177	setnnames();
178}
179
180/* convert Day[/Month][/Year] into unix time (since 1970)
181 * Day: two digits, Month: two digits, Year: digits
182 */
183time_t
184Mktime (char *dp)
185{
186    time_t t;
187    int d, m, y;
188    struct tm tm;
189
190    (void)time(&t);
191    tp = localtime(&t);
192
193    tm = tm0;
194    tm.tm_mday = tp->tm_mday;
195    tm.tm_mon = tp->tm_mon;
196    tm.tm_year = tp->tm_year;
197
198    switch (sscanf(dp, "%d.%d.%d", &d, &m, &y)) {
199    case 3:
200	if (y > 1900)
201	    y -= 1900;
202	tm.tm_year = y;
203	/* FALLTHROUGH */
204    case 2:
205	tm.tm_mon = m - 1;
206	/* FALLTHROUGH */
207    case 1:
208	tm.tm_mday = d;
209    }
210
211#ifdef DEBUG
212    fprintf(stderr, "Mktime: %d %d %s\n", (int)mktime(&tm), (int)t,
213	   asctime(&tm));
214#endif
215    return(mktime(&tm));
216}
217
218/*
219 * Possible date formats include any combination of:
220 *	3-charmonth			(January, Jan, Jan)
221 *	3-charweekday			(Friday, Monday, mon.)
222 *	numeric month or day		(1, 2, 04)
223 *
224 * Any character may separate them, or they may not be separated.  Any line,
225 * following a line that is matched, that starts with "whitespace", is shown
226 * along with the matched line.
227 */
228int
229isnow(char *endp, int *monthp, int *dayp, int *varp)
230{
231	int day, flags, month = 0, v1, v2;
232
233	/*
234	 * CONVENTION
235	 *
236	 * Month:     1-12
237	 * Monthname: Jan .. Dec
238	 * Day:       1-31
239	 * Weekday:   Mon-Sun
240	 *
241	 */
242
243	flags = 0;
244
245	/* read first field */
246	/* didn't recognize anything, skip it */
247	if (!(v1 = getfield(endp, &endp, &flags)))
248		return (0);
249
250	/* Easter or Easter depending days */
251	if (flags & F_EASTER)
252	    day = v1 - 1; /* days since January 1 [0-365] */
253
254	 /*
255	  * 1. {Weekday,Day} XYZ ...
256	  *
257	  *    where Day is > 12
258	  */
259	else if (flags & F_ISDAY || v1 > 12) {
260
261		/* found a day; day: 1-31 or weekday: 1-7 */
262		day = v1;
263
264		/* {Day,Weekday} {Month,Monthname} ... */
265		/* if no recognizable month, assume just a day alone
266		 * in other words, find month or use current month */
267		if (!(month = getfield(endp, &endp, &flags)))
268			month = tp->tm_mon + 1;
269	}
270
271	/* 2. {Monthname} XYZ ... */
272	else if (flags & F_ISMONTH) {
273		month = v1;
274
275		/* Monthname {day,weekday} */
276		/* if no recognizable day, assume the first day in month */
277		if (!(day = getfield(endp, &endp, &flags)))
278			day = 1;
279	}
280
281	/* Hm ... */
282	else {
283		v2 = getfield(endp, &endp, &flags);
284
285		/*
286		 * {Day} {Monthname} ...
287		 * where Day <= 12
288		 */
289		if (flags & F_ISMONTH) {
290			day = v1;
291			month = v2;
292			*varp = 0;
293		}
294
295		/* {Month} {Weekday,Day} ...  */
296		else {
297			/* F_ISDAY set, v2 > 12, or no way to tell */
298			month = v1;
299			/* if no recognizable day, assume the first */
300			day = v2 ? v2 : 1;
301			*varp = 0;
302		}
303	}
304
305	/* convert Weekday into *next*  Day,
306	 * e.g.: 'Sunday' -> 22
307	 *       'SundayLast' -> ??
308	 */
309	if (flags & F_ISDAY) {
310#ifdef DEBUG
311	    fprintf(stderr, "\nday: %d %s month %d\n", day, endp, month);
312#endif
313
314	    *varp = 1;
315	    /* variable weekday, SundayLast, MondayFirst ... */
316	    if (day < 0 || day >= 10) {
317
318		/* negative offset; last, -4 .. -1 */
319		if (day < 0) {
320		    v1 = day/10 - 1;          /* offset -4 ... -1 */
321	            day = 10 + (day % 10);    /* day 1 ... 7 */
322
323		    /* day, eg '22nd' */
324		    v2 = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
325
326		    /* (month length - day) / 7 + 1 */
327		    if (cumdays[month+1] - cumdays[month] >= v2
328			&& ((int)((cumdays[month+1] -
329		               cumdays[month] - v2) / 7) + 1) == -v1)
330			/* bingo ! */
331			day = v2;
332
333		    /* set to yesterday */
334		    else {
335			day = tp->tm_mday - 1;
336			if (day == 0)
337			    return (0);
338		    }
339		}
340
341		/* first, second ... +1 ... +5 */
342		else {
343		    v1 = day/10;        /* offset: +1 (first Sunday) ... */
344		    day = day % 10;
345
346		    /* day, eg '22th' */
347		    v2 = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
348
349		    /* Hurrah! matched */
350		    if ( ((v2 - 1 + 7) / 7) == v1 )
351			day = v2;
352
353		    /* set to yesterday */
354		    else {
355			day = tp->tm_mday - 1;
356			if (day == 0)
357			    return (0);
358		    }
359		}
360	    }
361
362	    /* wired */
363	    else {
364		day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
365		*varp = 1;
366	    }
367	}
368
369	if (!(flags & F_EASTER)) {
370	    if (day + cumdays[month] > cumdays[month + 1]) {    /* off end of month */
371		day -= (cumdays[month + 1] - cumdays[month]);   /* adjust */
372		if (++month > 12)                               /* next year */
373		    month = 1;
374	    }
375	    *monthp = month;
376	    *dayp = day;
377	    day = cumdays[month] + day;
378	}
379	else {
380	    for (v1 = 0; day > cumdays[v1]; v1++)
381		;
382	    *monthp = v1 - 1;
383	    *dayp = day - cumdays[v1 - 1];
384	    *varp = 1;
385	}
386
387#ifdef DEBUG
388	fprintf(stderr, "day2: day %d(%d-%d) yday %d\n", *dayp, day,
389                cumdays[month], tp->tm_yday);
390#endif
391
392	/* When days before or days after is specified */
393	/* no year rollover */
394	if (day >= tp->tm_yday - f_dayBefore &&
395	    day <= tp->tm_yday + f_dayAfter)
396		return (1);
397
398	/* next year */
399	if (tp->tm_yday + f_dayAfter >= yrdays) {
400		int end = tp->tm_yday + f_dayAfter - yrdays;
401		if (day <= end)
402			return (1);
403	}
404
405	/* previous year */
406	if (tp->tm_yday - f_dayBefore < 0) {
407		int before = yrdays + (tp->tm_yday - f_dayBefore );
408		if (day >= before)
409			return (1);
410	}
411
412	return (0);
413}
414
415
416int
417getmonth(char *s)
418{
419	const char **p;
420	struct fixs *n;
421
422	for (n = fnmonths; n->name; ++n)
423		if (!strncasecmp(s, n->name, n->len))
424			return ((n - fnmonths) + 1);
425	for (n = nmonths; n->name; ++n)
426		if (!strncasecmp(s, n->name, n->len))
427			return ((n - nmonths) + 1);
428	for (p = months; *p; ++p)
429		if (!strncasecmp(s, *p, 3))
430			return ((p - months) + 1);
431	return (0);
432}
433
434
435int
436getday(char *s)
437{
438	const char **p;
439	struct fixs *n;
440
441	for (n = fndays; n->name; ++n)
442		if (!strncasecmp(s, n->name, n->len))
443			return ((n - fndays) + 1);
444	for (n = ndays; n->name; ++n)
445		if (!strncasecmp(s, n->name, n->len))
446			return ((n - ndays) + 1);
447	for (p = days; *p; ++p)
448		if (!strncasecmp(s, *p, 3))
449			return ((p - days) + 1);
450	return (0);
451}
452
453/* return offset for variable weekdays
454 * -1 -> last weekday in month
455 * +1 -> first weekday in month
456 * ... etc ...
457 */
458int
459getdayvar(char *s)
460{
461	int offs;
462
463
464	offs = strlen(s);
465
466
467	/* Sun+1 or Wednesday-2
468	 *    ^              ^   */
469
470	/* fprintf(stderr, "x: %s %s %d\n", s, s + offs - 2, offs); */
471	switch(*(s + offs - 2)) {
472	case '-':
473	    return(-(atoi(s + offs - 1)));
474	case '+':
475	    return(atoi(s + offs - 1));
476	}
477
478
479	/*
480	 * some aliases: last, first, second, third, fourth
481	 */
482
483	/* last */
484	if      (offs > 4 && !strcasecmp(s + offs - 4, "last"))
485	    return(-1);
486	else if (offs > 5 && !strcasecmp(s + offs - 5, "first"))
487	    return(+1);
488	else if (offs > 6 && !strcasecmp(s + offs - 6, "second"))
489	    return(+2);
490	else if (offs > 5 && !strcasecmp(s + offs - 5, "third"))
491	    return(+3);
492	else if (offs > 6 && !strcasecmp(s + offs - 6, "fourth"))
493	    return(+4);
494
495
496	/* no offset detected */
497	return(0);
498}
499