xref: /freebsd/usr.bin/calendar/day.c (revision f0a75d274af375d15b97b830966b99a02b7db911)
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$");
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 
50 struct tm *tp;
51 static const struct tm tm0;
52 int *cumdays, offset, yrdays;
53 char dayname[10];
54 
55 
56 /* 1-based month, 0-based days, cumulative */
57 int 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 
62 static char const *days[] = {
63 	"sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
64 };
65 
66 static const char *months[] = {
67 	"jan", "feb", "mar", "apr", "may", "jun",
68 	"jul", "aug", "sep", "oct", "nov", "dec", NULL,
69 };
70 
71 static struct fixs fndays[8];         /* full national days names */
72 static struct fixs ndays[8];          /* short national days names */
73 
74 static struct fixs fnmonths[13];      /* full national months names */
75 static struct fixs nmonths[13];       /* short national month names */
76 
77 
78 void setnnames(void)
79 {
80 	char buf[80];
81 	int i, l;
82 	struct tm tm;
83 
84 	for (i = 0; i < 7; i++) {
85 		tm.tm_wday = i;
86 		strftime(buf, sizeof(buf), "%a", &tm);
87 		for (l = strlen(buf);
88 		     l > 0 && isspace((unsigned char)buf[l - 1]);
89 		     l--)
90 			;
91 		buf[l] = '\0';
92 		if (ndays[i].name != NULL)
93 			free(ndays[i].name);
94 		if ((ndays[i].name = strdup(buf)) == NULL)
95 			errx(1, "cannot allocate memory");
96 		ndays[i].len = strlen(buf);
97 
98 		strftime(buf, sizeof(buf), "%A", &tm);
99 		for (l = strlen(buf);
100 		     l > 0 && isspace((unsigned char)buf[l - 1]);
101 		     l--)
102 			;
103 		buf[l] = '\0';
104 		if (fndays[i].name != NULL)
105 			free(fndays[i].name);
106 		if ((fndays[i].name = strdup(buf)) == NULL)
107 			errx(1, "cannot allocate memory");
108 		fndays[i].len = strlen(buf);
109 	}
110 
111 	for (i = 0; i < 12; i++) {
112 		tm.tm_mon = i;
113 		strftime(buf, sizeof(buf), "%b", &tm);
114 		for (l = strlen(buf);
115 		     l > 0 && isspace((unsigned char)buf[l - 1]);
116 		     l--)
117 			;
118 		buf[l] = '\0';
119 		if (nmonths[i].name != NULL)
120 			free(nmonths[i].name);
121 		if ((nmonths[i].name = strdup(buf)) == NULL)
122 			errx(1, "cannot allocate memory");
123 		nmonths[i].len = strlen(buf);
124 
125 		strftime(buf, sizeof(buf), "%B", &tm);
126 		for (l = strlen(buf);
127 		     l > 0 && isspace((unsigned char)buf[l - 1]);
128 		     l--)
129 			;
130 		buf[l] = '\0';
131 		if (fnmonths[i].name != NULL)
132 			free(fnmonths[i].name);
133 		if ((fnmonths[i].name = strdup(buf)) == NULL)
134 			errx(1, "cannot allocate memory");
135 		fnmonths[i].len = strlen(buf);
136 	}
137 }
138 
139 void
140 settime(now)
141     	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 	offset = tp->tm_wday == Friday ? 3 : 1;
155 	header[5].iov_base = dayname;
156 
157 	oldl = NULL;
158 	lbufp = setlocale(LC_TIME, NULL);
159 	if (lbufp != NULL && (oldl = strdup(lbufp)) == NULL)
160 		errx(1, "cannot allocate memory");
161 	(void) setlocale(LC_TIME, "C");
162 	header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
163 	(void) setlocale(LC_TIME, (oldl != NULL ? oldl : ""));
164 	if (oldl != NULL)
165 		free(oldl);
166 
167 	setnnames();
168 }
169 
170 /* convert Day[/Month][/Year] into unix time (since 1970)
171  * Day: two digits, Month: two digits, Year: digits
172  */
173 time_t Mktime (dp)
174     char *dp;
175 {
176     time_t t;
177     int d, m, y;
178     struct tm tm;
179 
180     (void)time(&t);
181     tp = localtime(&t);
182 
183     tm = tm0;
184     tm.tm_mday = tp->tm_mday;
185     tm.tm_mon = tp->tm_mon;
186     tm.tm_year = tp->tm_year;
187 
188     switch (sscanf(dp, "%d.%d.%d", &d, &m, &y)) {
189     case 3:
190 	if (y > 1900)
191 	    y -= 1900;
192 	tm.tm_year = y;
193 	/* FALLTHROUGH */
194     case 2:
195 	tm.tm_mon = m - 1;
196 	/* FALLTHROUGH */
197     case 1:
198 	tm.tm_mday = d;
199     }
200 
201 #ifdef DEBUG
202     fprintf(stderr, "Mktime: %d %d %s\n", (int)mktime(&tm), (int)t,
203 	   asctime(&tm));
204 #endif
205     return(mktime(&tm));
206 }
207 
208 /*
209  * Possible date formats include any combination of:
210  *	3-charmonth			(January, Jan, Jan)
211  *	3-charweekday			(Friday, Monday, mon.)
212  *	numeric month or day		(1, 2, 04)
213  *
214  * Any character may separate them, or they may not be separated.  Any line,
215  * following a line that is matched, that starts with "whitespace", is shown
216  * along with the matched line.
217  */
218 int
219 isnow(endp, monthp, dayp, varp)
220 	char *endp;
221 	int	*monthp;
222 	int	*dayp;
223 	int	*varp;
224 {
225 	int day, flags, month = 0, v1, v2;
226 
227 	/*
228 	 * CONVENTION
229 	 *
230 	 * Month:     1-12
231 	 * Monthname: Jan .. Dec
232 	 * Day:       1-31
233 	 * Weekday:   Mon-Sun
234 	 *
235 	 */
236 
237 	flags = 0;
238 
239 	/* read first field */
240 	/* didn't recognize anything, skip it */
241 	if (!(v1 = getfield(endp, &endp, &flags)))
242 		return (0);
243 
244 	/* Easter or Easter depending days */
245 	if (flags & F_EASTER)
246 	    day = v1 - 1; /* days since January 1 [0-365] */
247 
248 	 /*
249 	  * 1. {Weekday,Day} XYZ ...
250 	  *
251 	  *    where Day is > 12
252 	  */
253 	else if (flags & F_ISDAY || v1 > 12) {
254 
255 		/* found a day; day: 1-31 or weekday: 1-7 */
256 		day = v1;
257 
258 		/* {Day,Weekday} {Month,Monthname} ... */
259 		/* if no recognizable month, assume just a day alone
260 		 * in other words, find month or use current month */
261 		if (!(month = getfield(endp, &endp, &flags)))
262 			month = tp->tm_mon + 1;
263 	}
264 
265 	/* 2. {Monthname} XYZ ... */
266 	else if (flags & F_ISMONTH) {
267 		month = v1;
268 
269 		/* Monthname {day,weekday} */
270 		/* if no recognizable day, assume the first day in month */
271 		if (!(day = getfield(endp, &endp, &flags)))
272 			day = 1;
273 	}
274 
275 	/* Hm ... */
276 	else {
277 		v2 = getfield(endp, &endp, &flags);
278 
279 		/*
280 		 * {Day} {Monthname} ...
281 		 * where Day <= 12
282 		 */
283 		if (flags & F_ISMONTH) {
284 			day = v1;
285 			month = v2;
286 			*varp = 0;
287 		}
288 
289 		/* {Month} {Weekday,Day} ...  */
290 		else {
291 			/* F_ISDAY set, v2 > 12, or no way to tell */
292 			month = v1;
293 			/* if no recognizable day, assume the first */
294 			day = v2 ? v2 : 1;
295 			*varp = 0;
296 		}
297 	}
298 
299 	/* convert Weekday into *next*  Day,
300 	 * e.g.: 'Sunday' -> 22
301 	 *       'SundayLast' -> ??
302 	 */
303 	if (flags & F_ISDAY) {
304 #ifdef DEBUG
305 	    fprintf(stderr, "\nday: %d %s month %d\n", day, endp, month);
306 #endif
307 
308 	    *varp = 1;
309 	    /* variable weekday, SundayLast, MondayFirst ... */
310 	    if (day < 0 || day >= 10) {
311 
312 		/* negative offset; last, -4 .. -1 */
313 		if (day < 0) {
314 		    v1 = day/10 - 1;          /* offset -4 ... -1 */
315 	            day = 10 + (day % 10);    /* day 1 ... 7 */
316 
317 		    /* day, eg '22nd' */
318 		    v2 = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
319 
320 		    /* (month length - day) / 7 + 1 */
321 		    if (cumdays[month+1] - cumdays[month] >= v2
322 			&& ((int)((cumdays[month+1] -
323 		               cumdays[month] - v2) / 7) + 1) == -v1)
324 			/* bingo ! */
325 			day = v2;
326 
327 		    /* set to yesterday */
328 		    else {
329 			day = tp->tm_mday - 1;
330 			if (day == 0)
331 			    return (0);
332 		    }
333 		}
334 
335 		/* first, second ... +1 ... +5 */
336 		else {
337 		    v1 = day/10;        /* offset: +1 (first Sunday) ... */
338 		    day = day % 10;
339 
340 		    /* day, eg '22th' */
341 		    v2 = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
342 
343 		    /* Hurrah! matched */
344 		    if ( ((v2 - 1 + 7) / 7) == v1 )
345 			day = v2;
346 
347 		    /* set to yesterday */
348 		    else {
349 			day = tp->tm_mday - 1;
350 			if (day == 0)
351 			    return (0);
352 		    }
353 		}
354 	    }
355 
356 	    /* wired */
357 	    else {
358 		day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
359 		*varp = 1;
360 	    }
361 	}
362 
363 	if (!(flags & F_EASTER)) {
364 	    if (day + cumdays[month] > cumdays[month + 1]) {    /* off end of month */
365 		day -= (cumdays[month + 1] - cumdays[month]);   /* adjust */
366 		if (++month > 12)                               /* next year */
367 		    month = 1;
368 	    }
369 	    *monthp = month;
370 	    *dayp = day;
371 	    day = cumdays[month] + day;
372 	}
373 	else {
374 	    for (v1 = 0; day > cumdays[v1]; v1++)
375 		;
376 	    *monthp = v1 - 1;
377 	    *dayp = day - cumdays[v1 - 1];
378 	    *varp = 1;
379 	}
380 
381 #ifdef DEBUG
382 	fprintf(stderr, "day2: day %d(%d-%d) yday %d\n", *dayp, day, cumdays[month], tp->tm_yday);
383 #endif
384 	/* if today or today + offset days */
385 	if (day >= tp->tm_yday - f_dayBefore &&
386 	    day <= tp->tm_yday + offset + f_dayAfter)
387 		return (1);
388 
389 	/* if number of days left in this year + days to event in next year */
390 	if (yrdays - tp->tm_yday + day <= offset + f_dayAfter ||
391 	    /* a year backward, eg. 6 Jan and 10 days before -> 27. Dec */
392 	    tp->tm_yday + day - f_dayBefore < 0
393 	    )
394 		return (1);
395 	return (0);
396 }
397 
398 
399 int
400 getmonth(s)
401 	char *s;
402 {
403 	const char **p;
404 	struct fixs *n;
405 
406 	for (n = fnmonths; n->name; ++n)
407 		if (!strncasecmp(s, n->name, n->len))
408 			return ((n - fnmonths) + 1);
409 	for (n = nmonths; n->name; ++n)
410 		if (!strncasecmp(s, n->name, n->len))
411 			return ((n - nmonths) + 1);
412 	for (p = months; *p; ++p)
413 		if (!strncasecmp(s, *p, 3))
414 			return ((p - months) + 1);
415 	return (0);
416 }
417 
418 
419 int
420 getday(s)
421 	char *s;
422 {
423 	const char **p;
424 	struct fixs *n;
425 
426 	for (n = fndays; n->name; ++n)
427 		if (!strncasecmp(s, n->name, n->len))
428 			return ((n - fndays) + 1);
429 	for (n = ndays; n->name; ++n)
430 		if (!strncasecmp(s, n->name, n->len))
431 			return ((n - ndays) + 1);
432 	for (p = days; *p; ++p)
433 		if (!strncasecmp(s, *p, 3))
434 			return ((p - days) + 1);
435 	return (0);
436 }
437 
438 /* return offset for variable weekdays
439  * -1 -> last weekday in month
440  * +1 -> first weekday in month
441  * ... etc ...
442  */
443 int
444 getdayvar(s)
445 	char *s;
446 {
447 	int offs;
448 
449 
450 	offs = strlen(s);
451 
452 
453 	/* Sun+1 or Wednesday-2
454 	 *    ^              ^   */
455 
456 	/* fprintf(stderr, "x: %s %s %d\n", s, s + offs - 2, offs); */
457 	switch(*(s + offs - 2)) {
458 	case '-':
459 	    return(-(atoi(s + offs - 1)));
460 	case '+':
461 	    return(atoi(s + offs - 1));
462 	}
463 
464 
465 	/*
466 	 * some aliases: last, first, second, third, fourth
467 	 */
468 
469 	/* last */
470 	if      (offs > 4 && !strcasecmp(s + offs - 4, "last"))
471 	    return(-1);
472 	else if (offs > 5 && !strcasecmp(s + offs - 5, "first"))
473 	    return(+1);
474 	else if (offs > 6 && !strcasecmp(s + offs - 6, "second"))
475 	    return(+2);
476 	else if (offs > 5 && !strcasecmp(s + offs - 5, "third"))
477 	    return(+3);
478 	else if (offs > 6 && !strcasecmp(s + offs - 6, "fourth"))
479 	    return(+4);
480 
481 
482 	/* no offset detected */
483 	return(0);
484 }
485