File: bdengine.c

package info (click to toggle)
birthday 1.6.2-3
  • links: PTS
  • area: main
  • in suites: lenny, squeeze, wheezy
  • size: 464 kB
  • ctags: 168
  • sloc: ansic: 1,401; makefile: 54; sh: 44; perl: 31
file content (647 lines) | stat: -rw-r--r-- 18,028 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/*
   birthday.c

   Birthday/Anniversary display on login

   (c) 1996 AS Mortimer

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.  You may also
    distribute it under the Artistic License, as comes with Perl.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    You should also have recieved a copy of the Artistic license with
    this program.

   $Id: bdengine.c,v 1.4 2006/01/10 17:27:53 andymort Exp $
   
   We're getting there. At the moment, the file used by default is ~/.birthdays
   under UNIX, or C:\PERSONAL\BDAYS.LST under DOS, but this can be overridden on
   the command line. The file has the following format:

   name/event/whatever=date flags
   where:
     date is dd/mm, dd/mm/yy (assumes 20th century!) or dd/mm/yyyy
     flags is ONE or ZERO of 
       o  bd  for a birthday (default)
       o  bir for a birthday (exactly equivalent to `bd')
       o  ann for an anniversary
       o  ev  for an event
     and zero or more of
       o  w<n> to set the warn-in-advance time to n days (don't include the
	 brackets! :)
       o  to<date>
       o  for<days>
               to specify the length of time taken by an event, for example a
	       holiday.

     Comment lines are preceeded by #.
     
     Note: If you deviate from this format, I cannot guarantee anything about
     it's behaviour. In most cases, it will just quietly ignore the error,
     which probably isn't ideal behaviour. Oh, well.

     2003/05/20: Automatic reallocation of output buffer in listsrings() by
                 Sebastian Schmidt <yath@yath.eu.org>.

*/

/* ========== */

#include "birthday.h"

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

#ifdef UNIX
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#endif

/* ========== */

int skptok(int j, char *ptr);
int evcmp(const void *e1, const void *e2);
char *deffname(void);

struct event *dir_include(char *dir, char *parm, const struct date *today);

/* ========== Global variables */

int iDWarn   = DEF_WARN;
int iMaxWarn = MAX_WARN;
int iMinWarn = MIN_WARN;

const unsigned MLENDAT[]={31,-1,31,30,31,30,31,31,30,31,30,31};

const struct _ftable FTABLE[] =
{
  {"bir",F_TBIRTHDAY},
  {"bd", F_TBIRTHDAY},
  {"ann",F_TANNIVERSARY},
  {"ev", F_TEVENT},
  {"mes", F_TMESSAGE},
  {"w",  F_WTIME_P},
  {"to", F_TODATE},
  {"for", F_FORDAYS},
  {NULL, 0}
};

#ifdef NUMS_AS_WORDS
const char *NUMBERS[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
#endif

/* list of directives. These are entered in the file prefixed by '&'. The function should be declared as
   	struct event *dir_func(char *directive, char *parameters);
   and should return a pointer to a NULL-terminated list of extra records, or NULL if there are none.
   This structure will allow us to dynamically add directives, if we wish to do so in the future.
   */

struct {
  const char *text;
  int len;
  struct event *(*func)(char*,char*,const struct date*);
} directlist[] = {
  { "include", 0, dir_include },
  { NULL, 0, NULL }
};

/* ========== */

/* compare the first strlen(a) characters of a and b */
#define strbegcmp(a,b) strncmp(a,b,strlen(a))

/* like strcat(), but lets the buffer automagically grow :-)
 * (needs local variable "size" with the buffer size) */
#define append(where, what) do {				    \
    if (strlen(what) > (size - strlen(where) - 1)) {		    \
      where = xrealloc(where, size + 128 + strlen(what));	    \
      size += 128 + strlen(what);				    \
    }								    \
    strcat(where, what);					    \
  } while(0)

/* ========== */

/* returns delta(d) in days, weeks, months, etc
 * the returned buffer is malloc()ed, do not forget to free() it */
char *tdelta(struct date *d, const struct date *today) {
  int dy, wk, mn, yr;
  char *tmp;
  char *buf = xmalloc(128);
  int size = 128;
  *buf = 0;
  
  switch (delta(d, today)) {
  case 0:
    append(buf, "today");
    return buf;
  case 1:
    append(buf, "tomorrow");
    return buf;
  default:
    /* like delta(), we ignore the year */
    yr=-before(*d,*today);
    mn=d->month - today->month;
    dy=d->day - today->day;
    
    if (dy < 0) {
      dy += mlen(today->month, today->year);
      mn--;
    }
    if (mn < 0) {
      mn += 12;
      yr++;
    }

    wk = (dy/7);
    dy%=7;
    
    append(buf, "in ");
    tmp = ttime(yr, mn, wk, dy);
    append(buf, tmp);
    free(tmp);
    
    if (*(buf + strlen(buf) - 1) == 's')
      append(buf, "'");
    else
      append(buf, "'s");

    append(buf, " time");

    return buf;
  }
}

#ifdef NUMS_AS_WORDS
#define donum(n,txt) do {                          \
      if (n > 0) {                                 \
         if (n < 10) {                             \
            append(buf, NUMBERS[n]);               \
            append(buf, " " txt);                  \
               if (n != 1) {                       \
                  append(buf, "s");                \
               }                                   \
         } else {                                  \
            snprintf(tmp, sizeof(tmp), "%d", n);	\
            append(buf, tmp);                      \
            append(buf, " " txt "s");              \
         }                                         \
         terms--;                                  \
         if (orgterms > 1) {                       \
	         if (terms == 1)                        \
               append(buf, " and ");               \
            else if (terms > 1)                    \
               append(buf, ", ");                  \
         }                                         \
      }                                            \
   } while(0)
#else /* NUMS_AS_WORDS */
#define donum(n,txt) do {                       \
      if (n > 0) {                              \
         snprintf(tmp, sizeof(tmp), "%d", n);   \
         append(buf, tmp);                      \
         append(buf, " " txt);                  \
         if (n != 1)                            \
            append(buf, "s");                   \
         terms--;                               \
         if (orgterms > 1) {                    \
            if (terms == 1)                     \
               append(buf, " and ");            \
            else if (terms > 1)                 \
               append(buf, ", ");               \
         }                                      \
      }                                         \
   } while(0)
#endif /* NUMS_AS_WORDS */

/* returns allocated buffer, don't forget to free() */
char *ttime(int yr, int mn, int wk, int dy) {
  char *buf = xmalloc(128);
  int size = 128;
  int terms, orgterms;
  char tmp[128];
  
  *buf = 0; /* Initialize buffer */
  terms = orgterms = (yr!=0) + (mn!=0) + (wk!=0) + (dy!=0);

  donum(yr, "year");
  donum(mn, "month");
  donum(wk, "week");
  donum(dy, "day");

  return buf;
}
#undef donum

/* lists the birthdays in their string format, one by one, and passes the string
   to a function. */
void liststrings(struct event *evl, prnfunc outf, const struct date *today) {
   int i,j;
   char *buf, *tmp;
   int size;
   
   for (i = 0; evl[i].text != NULL; i++) {
      buf = xmalloc(128);
      *buf = '\0';
      size = 128;
      
      if (evl[i].warn == -1 && delta(&(evl[i].date), today)==0) {
         append(buf, evl[i].text);
      } else if (evl[i].enddate.day == 0) {
	if (delta(&(evl[i].date), today) <= warnperiod(evl[i])) {
            append(buf, evl[i].text);
            append(buf, " ");
            tmp = tdelta(&(evl[i].date), today);
            append(buf, tmp);
            free(tmp);
         }
      } else {
	if (delta(&(evl[i].date), today) <= warnperiod(evl[i])) {
            append(buf, evl[i].text);
            append(buf, " for ");
	         /* +1 because, if the difference between two dates is one day,
	            then the length of an event on those days is two days */
	    j = ddiff(&(evl[i].date),&(evl[i].enddate), today) + 1;
	         tmp = ttime(0, 0, j/7, j%7);
            append(buf, tmp);
            free(tmp);
            append(buf, " ");
            tmp = tdelta(&(evl[i].date), today);
            append(buf, tmp);
	} else if (delta(&(evl[i].enddate), today) <= warnperiod(evl[i])) {
            append(buf, evl[i].text);
            append(buf, " ");
	    j = delta(&(evl[i].enddate), today);
	         if (j) {
               append(buf, "for ");
	            tmp = ttime(0, 0, j/7, j%7);
               append(buf, tmp);
               free(tmp);
               append(buf, " longer");
	         } else {
               append(buf, "finishes today");
	         }
         }
      }
      if (*buf) {
         append(buf, ".");
         outf(buf);
      }
      free(buf);
   }
}

char *
deffname(void)
{
#if defined(UNIX)
  char buf[256];

  strcpy(buf,getpwuid(getuid())->pw_dir);
  strcat(buf, "/" DEFAULT_FILE);

  return strdup(buf);
#elif defined(DOS)
  return strdup(DOSDEFDIR DEFAULT_FILE);
#endif
}
  
/* sort the events by the time before the next time they come up, putting those
   where the start has passed but we are still in the time-period first */
int
evcmp(const void *p1, const void *p2)
{
  struct event *e1=(struct event *)p1;
  struct event *e2=(struct event *)p2;
  unsigned d1,d2;

  /* if the delta for the enddate is less than that for the start date, then we
     have passed the start date but not yet the end date, and so we should
     display the enddate; otherwise, we should display the start date */
  
  d1 = e1->fromtoday;
  d2 = e2->fromtoday;

  if (d1 < d2) return -1;
  if (d1 > d2) return  1;
  
  return strcmp(e1->text, e2->text);
}

/* difference in days between two dates */
/* it is assumed that D1 < D2, and so the result is always positive */

unsigned ddiff(struct date *D1, struct date *D2, const struct date *today)
{
  struct date d1,d2;
  int dd,m;

  /* make working copies */
  d1=*D1;
  d2=*D2;
  
  /* sort out zero years */
  if (d1.year == 0 || d2.year==0) {
    if (d1.year != d2.year) {
      if (d1.year == 0) {
	if (before(d1,d2))
	  d1.year=d2.year;
	else
	  d1.year=d2.year-1;
      } else {
	if (before(d1,d2))
	  d2.year=d1.year;
	else
	  d2.year=d1.year+1;
      }
    } else { /* both years zero */
      /* NB we do actually have to use today's year, to get leap years
	 right. */
      if (before(d1,d2))
	d1.year=d2.year=today->year;
      else {
	d1.year=today->year;
	d2.year=d1.year+1;
      }
    }
  }

  /* now we can actually do the comparison ... */
  dd=0;
  
  /* to start with, we work in months */
  for (m=d1.month; m < d2.month + (d2.year-d1.year)*12; m++)
    dd += mlen(((m-1)%12)+1, d1.year + m/12);

  /* and then we renormalise for the days within the months */
  /* the first month was included in our calculations */
  dd -= d1.day;
  /* but the last one wasn't */
  dd += d2.day;

  return dd;
}

/* actually until the next anniversary of ... */
unsigned delta(struct date *date, const struct date *today)
{
  struct date d;
  unsigned dt, mn;
  
  memcpy(&d, date, sizeof(struct date));
  
  if (before(d, *today)) /* past the end of the year */
    {
      d.year = 1;
    } else {
      d.year = 0;
    }
    
  for (mn = today->month, dt=0; mn < d.month + 12*d.year; mn++)
    dt += mlen(((mn-1)%12) + 1,today->year + mn/12);
  
  dt -= today->day;
  dt += d.day;
  
  return dt;  
}

void scan_date( const char *str, struct date *date) {
  int n;
  n = sscanf(str, "%d/%d/%d", &(date->day), &(date->month), &(date->year));
  if ( n < 3 ) {
    /* didn't read the year */
    date->year=0;
  }
  else {
    /* if our year is only two digits, add 1900 to it ... */
    if(date->year < 100) date->year+=1900;
  }
}

struct event *readlist(char *fname, const struct date *today)
{
  FILE *file;
  int i,j,k,l,d;
  struct event *evl;
  char buf[1024], buf2[1024];
  char *ptr;
  unsigned flags;
  struct event *nevl;
  /* initialise */
  if (fname==NULL) {
    fname=deffname();
  }
  
  if (fname[0] == '-' && fname[1] == 0) {
    /* read from stdin */
    file=stdin;
  } else {
    /* now read it */
    if((file=fopen(fname, "rt"))==NULL) {
      fatal("Unable to open file \"%s\"\n", fname);
    }
  }


  for (i = 0, evl=NULL; fgets(buf, sizeof(buf), file) != NULL; i++) {
    evl = (struct event *) xrealloc(evl, sizeof(struct event) * (i + 1));

    if (*buf == '#' || *buf == '\n')
      {
	i--;
	continue;
      }
    if (*buf == '&') {
      buf[strlen(buf)-1] = 0;
      if ((ptr=strchr(buf+1,' ')) == NULL && (ptr=strchr((buf+1),'\t')) == NULL) {
	ptr=(buf+1)+strlen((buf+1));
      }

      *ptr++=0;
      nevl=NULL;
      k=0;
      for (j=0; directlist[j].text != NULL; j++) {
	if (directlist[j].len == 0) directlist[j].len = strlen(directlist[j].text);
	/*
	  fprintf(stderr, "Checking against directive #%d, %s, which has length %d, against \"%s\" with length %d\n",
		j, directlist[j].text, directlist[j].len, buf+1, ptr-(buf+1)-1);
		*/
	if (directlist[j].len == ptr-(buf+1)-1 && !strncmp(directlist[j].text,(buf+1),directlist[j].len))
	  {
	    nevl = directlist[j].func((buf+1),ptr,today);
	    k=1;
	    break;
	  }
      }
      
      if (nevl != NULL) {
	for (j=0; nevl[j].text != NULL; j++);
	i+=j-1;
	evl = (struct event *) xrealloc(evl, sizeof(struct event) * (i + 1));
	/* in fact, this loop reverses the order of the elements, but we're going to sort them later anyway. */
	for (j=0; nevl[j].text != NULL; j++)
	  evl[i-j]=nevl[j];
      }
      if (!k) {
	fprintf(stderr, "Warning: unrecognised directive \"%s\" ignored.\n", (buf+1));
	i--;
      }
      continue;
    }

    /* parse string in buf */ 
    ptr = strrchr(buf, '='); /* allow '=' in text */
    if(ptr==NULL) /* not a valid line, so ignore it! Cool, huh? */
      {
	fprintf(stderr, "WARNING: Invalid line in input file:\n%s", buf);
	i--;
	continue;
      }
      
    *(ptr++) = 0;  

    scan_date( ptr, &(evl[i].date) );

    /* parse flags */

    evl[i].warn=iDWarn;
    evl[i].enddate.day=evl[i].enddate.month=evl[i].enddate.year=0;

    flags=j=0;
    while(j = skptok(j, ptr),ptr[j]!=0)
      {
	for (k = 0; FTABLE[k].txt != NULL && strncmp(FTABLE[k].txt, ptr + j, strlen(FTABLE[k].txt)); k++);
	switch (FTABLE[k].flag) {
	case F_WTIME_P: /* w<n> -- sets warning time */
	  sscanf(ptr + j, "w %u", &(evl[i].warn));
	  break;
	case F_FORDAYS: /* for<days> -- sets the duration of the event */
	  sscanf(ptr + j, "for %d", &d);
	  evl[i].enddate=evl[i].date;
	  for (l=1; l < d; l++) {
	    evl[i].enddate.day++;
	    if (evl[i].enddate.day > mlen(evl[i].enddate.month,
					  evl[i].enddate.year)) {
	      evl[i].enddate.month++;
	      evl[i].enddate.day=1;
	    }
	    if (evl[i].enddate.month > 12) {
	      evl[i].enddate.year++;
	      evl[i].enddate.month=1;
	    }
	  }
	  break;
	case F_TODATE:
	  l = sscanf(ptr + j, "to %u/%u/%u", &(evl[i].enddate.day), &(evl[i].enddate.month), &(evl[i].enddate.year));
	  if (evl[i].enddate.year < 100) evl[i].enddate.year+=1900;
	  if (l == 2) evl[i].enddate.year=0;
	  break;
	case 0:
	  break;
	default:
	  flags|=FTABLE[k].flag;
	  break;
	}
      }

    /* construct event text */

    switch(flags & F_MTYPE) {
    case F_TBIRTHDAY:
    default: /* assume it's a birthday */
      if (evl[i].date.year != 0) {
	int tmp_age=ydelta(evl[i].date, *today);
	if (tmp_age!=1) {
	  sprintf(buf2, "%s is %d years old", buf, tmp_age);
	} else {
	  sprintf(buf2, "%s is %d year old", buf, tmp_age);
	}
      } else {
	sprintf(buf2, "%s has a birthday", buf);
      }
      break;
    case F_TANNIVERSARY:
      if (evl[i].date.year != 0) {
	sprintf(buf2, "%s %d years ago", buf, ydelta(evl[i].date, *today));
      } else {
	strcpy(buf2, buf);
      }
      break;
    case F_TEVENT:
      /* if a year was specified, and this warning isn't for it, ignore! */
      if ((evl[i].date.year != 0 && ydelta(evl[i].date, *today) != 0) &&
	  (evl[i].enddate.year == 0 || ydelta(evl[i].enddate, *today) != 0)) {
	i--;
	continue;
      }
      strcpy(buf2, buf);
      break;
    case F_TMESSAGE:
      /* Like an event, except that it only comes up on the given date, and no text at all is appended */
      if ((evl[i].date.year != 0 && ydelta(evl[i].date, *today) != 0) &&
	  (evl[i].enddate.year == 0 || ydelta(evl[i].enddate, *today) != 0)) {
	i--;
	continue;
      }
      strcpy(buf2, buf);
      evl[i].warn=-1; /* special code! */
      break;
    }      
    evl[i].text = strdup(buf2);

    /* precalculate the "priority", the time until we next need to
       display something about this event. */
    {
      unsigned d;
      d=delta(&(evl[i].date), today);
      if (evl[i].enddate.day && delta(&(evl[i].enddate), today) < d)
	d=delta(&(evl[i].enddate), today);
      evl[i].fromtoday = d;
    }
  }

  evl = (struct event *) xrealloc(evl, sizeof(struct event) * (i + 1));
  evl[i].date.day=evl[i].date.month=evl[i].date.year=0;
  evl[i].text = (char *) NULL;

  fclose(file);
  free(fname);

  /* NB uses i from above */
  qsort(evl, i, sizeof(struct event), evcmp);
  return evl;
}

int
skptok(int j, char *ptr)
{
  for (; ptr[j] != 0 &&  ptr[j] != ' ' && ptr[j] != '\t' ; j++);
  for (; ptr[j] != 0 && (ptr[j] == ' ' || ptr[j] == '\t'); j++);
  
  return j;
}

/* ---------------------------------------------------------------------- */
/* Functions to parse input file directives */
struct event *dir_include(char *dir, char *parm, const struct date *today)
{
  struct event *evl;

  evl=readlist(strdup(parm), today);

  return evl;
}