]> git.deb.at Git - pkg/abook.git/blob - database.c
Support for 'date' field type.
[pkg/abook.git] / database.c
1
2 /*
3  * $Id$
4  *
5  * by JH <jheinonen@users.sourceforge.net>
6  *
7  * Copyright (C) Jaakko Heinonen
8  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <assert.h>
15 #ifdef HAVE_CONFIG_H
16 #       include "config.h"
17 #endif
18 #include "abook.h"
19 #include "database.h"
20 #include "gettext.h"
21 #include "list.h"
22 #include "misc.h"
23 #include "xmalloc.h"
24
25 abook_field_list *fields_list = NULL;
26 int fields_count = 0;
27
28 list_item *database = NULL;
29 static int items = 0;
30
31 #define ITEM_SIZE (fields_count * sizeof(char *))
32 #define LAST_ITEM (items - 1)
33
34 #define INITIAL_LIST_CAPACITY   30
35 static int list_capacity = 0;
36
37 int standard_fields_indexed[ITEM_FIELDS];
38
39 /*
40  * notes about adding predefined "standard" fields:
41  *      - leave alone "name" and "email"
42  *      - reorganize the field numbers in database.h
43  */
44 abook_field standard_fields[] = {
45         {"name",        N_("Name"),             FIELD_STRING}, /* NAME */
46         {"email",       N_("E-mail addresses"), FIELD_EMAILS}, /* EMAIL */
47         {"address",     N_("Address"),          FIELD_STRING}, /* ADDRESS */
48         {"address2",    N_("Address2"),         FIELD_STRING}, /* ADDRESS2 */
49         {"city",        N_("City"),             FIELD_STRING}, /* CITY */
50         {"state",       N_("State/Province"),   FIELD_STRING}, /* STATE */
51         {"zip",         N_("ZIP/Postal Code"),  FIELD_STRING}, /* ZIP */
52         {"country",     N_("Country"),          FIELD_STRING}, /* COUNTRY */
53         {"phone",       N_("Home Phone"),       FIELD_STRING}, /* PHONE */
54         {"workphone",   N_("Work Phone"),       FIELD_STRING}, /* WORKPHONE */
55         {"fax",         N_("Fax"),              FIELD_STRING}, /* FAX */
56         {"mobile",      N_("Mobile"),           FIELD_STRING}, /* MOBILEPHONE */
57         {"nick",        N_("Nickname/Alias"),   FIELD_STRING}, /* NICK */
58         {"url",         N_("URL"),              FIELD_STRING}, /* URL */
59         {"notes",       N_("Notes"),            FIELD_STRING}, /* NOTES */
60         {"anniversary", N_("Anniversary day"),  FIELD_DATE},   /* ANNIVERSARY */
61         {0} /* ITEM_FIELDS */
62 };
63
64
65 extern int first_list_item;
66 extern int curitem;
67 extern char *selected;
68 extern char *datafile;
69
70
71
72 static abook_field *
73 declare_standard_field(int i)
74 {
75         abook_field *f = xmalloc(sizeof(abook_field));
76
77         f = memcpy(f, &standard_fields[i], sizeof(abook_field));
78         f->name = xstrdup(gettext(f->name));
79
80         add_field(&fields_list, f);
81
82         assert(standard_fields_indexed[i] == -1);
83         standard_fields_indexed[i] = fields_count++;
84
85         return f;
86 }
87
88 abook_field *
89 find_standard_field(char *key, int do_declare)
90 {
91         int i;
92
93         for(i = 0; standard_fields[i].key; i++)
94                 if(0 == strcmp(standard_fields[i].key, key))
95                         goto found;
96
97         return NULL;
98
99 found:
100         return do_declare ? declare_standard_field(i) : &standard_fields[i];
101 }
102
103 /* Search for a field. Use the list of declared fields if no list specified. */
104 abook_field *
105 real_find_field(char *key, abook_field_list *list, int *number)
106 {
107         abook_field_list *cur;
108         int i;
109
110         for(cur = (list ? list : fields_list), i = 0; cur; cur = cur->next, i++)
111                 if(0 == strcmp(cur->field->key, key)) {
112                         if(number)
113                                 *number = i;
114                         return cur->field;
115                 }
116
117         if(number)
118                 *number = -1;
119
120         return NULL;
121 }
122
123 void
124 get_field_keyname(int i, char **key, char **name)
125 {
126         abook_field_list *cur = fields_list;
127         int j;
128
129         assert(i < fields_count);
130
131         for(j = 0; i >= 0 && j < i; j++, cur = cur->next)
132                 ;
133
134         if(key)
135                 *key = (i < 0) ? NULL : cur->field->key;
136         if(name)
137                 *name = (i < 0) ? NULL : cur->field->name;
138 }
139
140 void
141 add_field(abook_field_list **list, abook_field *f)
142 {
143         abook_field_list *tmp;
144
145         for(tmp = *list; tmp && tmp->next; tmp = tmp->next)
146                 ;
147
148         if(tmp) {
149                 tmp->next = xmalloc(sizeof(abook_field_list));
150                 tmp = tmp->next;
151         } else
152                 *list = tmp = xmalloc(sizeof(abook_field_list));
153
154         tmp->field = f;
155         tmp->next = NULL;
156 }
157
158 char *
159 declare_new_field(char *key, char *name, char *type, int accept_standard)
160 {
161         abook_field *f;
162
163         if(find_declared_field(key))
164                 return _("field already defined");
165
166         if(find_standard_field(key, accept_standard))
167                 return accept_standard ? NULL /* ok, added */ :
168                         _("standard field does not need to be declared");
169
170         f = xmalloc(sizeof(abook_field));
171         f->key = xstrdup(key);
172         f->name = xstrdup(name);
173
174         if(!*type || (0 == strcasecmp("string", type)))
175                 f->type = FIELD_STRING;
176         else if(0 == strcasecmp("emails", type))
177                 f->type = FIELD_EMAILS;
178         else if(0 == strcasecmp("list", type))
179                 f->type = FIELD_LIST;
180         else if(0 == strcasecmp("date", type))
181                 f->type = FIELD_DATE;
182         else
183                 return _("unknown type");
184
185         add_field(&fields_list, f);
186         fields_count++;
187
188         return NULL;
189 }
190
191 /*
192  * Declare a new field while database is already loaded
193  * making it grow accordingly
194  */
195 static void
196 declare_unknown_field(char *key)
197 {
198         int i;
199
200         declare_new_field(key, key, "string",
201                         1 /* accept to declare "standard" fields */);
202
203         if(!database)
204                 return;
205
206         for(i = 0; i < items; i++)
207                 if(database[i]) {
208                         database[i] = xrealloc(database[i], ITEM_SIZE);
209                         database[i][fields_count - 1] = NULL;
210                 }
211 }
212
213 /*
214  * Declare "standard" fields, thus preserving them while parsing a database,
215  * even if they won't be displayed.
216  */
217 void
218 init_standard_fields()
219 {
220         int i;
221
222         for(i = 0; standard_fields[i].key; i++)
223                 if(standard_fields_indexed[i] == -1)
224                         declare_standard_field(i);
225 }
226
227 /* Some initializations - Must be called _before_ load_opts() */
228 void
229 prepare_database_internals()
230 {
231         int i;
232
233         for(i = 0; i < ITEM_FIELDS; i++)
234                 standard_fields_indexed[i] = -1;
235
236         /* the only two mandatory fields */
237         declare_standard_field(NAME);
238         declare_standard_field(EMAIL);
239 }
240
241 int
242 parse_database(FILE *in)
243 {
244         char *line = NULL;
245         char *tmp;
246         int sec=0, field;
247         list_item item;
248
249         item = item_create();
250
251         for(;;) {
252                 line = getaline(in);
253                 if(feof(in)) {
254                         if(item[field_id(NAME)] && sec) {
255                                 add_item2database(item);
256                         } else {
257                                 item_empty(item);
258                         }
259                         break;
260                 }
261
262                 if(!*line || *line == '\n' || *line == '#') {
263                         goto next;
264                 } else if(*line == '[') {
265                         if(item[field_id(NAME)] && sec ) {
266                                 add_item2database(item);
267                         } else {
268                                 item_empty(item);
269                         }
270                         sec = 1;
271                         memset(item, 0, ITEM_SIZE);
272                         if(!(tmp = strchr(line, ']')))
273                                 sec = 0; /*incorrect section lines are skipped*/
274                 } else if((tmp = strchr(line, '=') ) && sec) {
275                         *tmp++ = '\0';
276                         find_field_number(line, &field);
277                         if(field != -1) {
278                                 item[field] = xstrdup(tmp);
279                                 goto next;
280                         } else if(!strcasecmp(opt_get_str(STR_PRESERVE_FIELDS),
281                                                 "all")){
282                                 declare_unknown_field(line);
283                                 item = xrealloc(item, ITEM_SIZE);
284                                 item[fields_count - 1] = xstrdup(tmp);
285                                 goto next;
286                         }
287                 }
288 next:
289                 xfree(line);
290         }
291
292         xfree(line);
293         item_free(&item);
294         return 0;
295 }
296
297 int
298 load_database(char *filename)
299 {
300         FILE *in;
301
302         if(database != NULL)
303                 close_database();
304
305         if ((in = abook_fopen(filename, "r")) == NULL)
306                 return -1;
307
308         parse_database(in);
309
310         return (items == 0) ? 2 : 0;
311 }
312
313 int
314 write_database(FILE *out, struct db_enumerator e)
315 {
316         int j;
317         int i = 0;
318         abook_field_list *cur;
319
320         fprintf(out,
321                 "# abook addressbook file\n\n"
322                 "[format]\n"
323                 "program=" PACKAGE "\n"
324                 "version=" VERSION "\n"
325                 "\n\n"
326         );
327
328         db_enumerate_items(e) {
329                 fprintf(out, "[%d]\n", i);
330
331                 for(cur = fields_list, j = 0; cur; cur = cur->next, j++) {
332                         if( database[e.item][j] != NULL &&
333                                         *database[e.item][j] )
334                                 fprintf(out, "%s=%s\n",
335                                         cur->field->key,
336                                         database[e.item][j]
337                                         );
338                 }
339
340                 fputc('\n', out);
341                 i++;
342         }
343
344         return 0;
345 }
346
347 int
348 save_database()
349 {
350         FILE *out;
351         int ret = 0;
352         struct db_enumerator e = init_db_enumerator(ENUM_ALL);
353         char *datafile_new = strconcat(datafile, ".new", NULL);
354         char *datafile_old = strconcat(datafile, "~", NULL);
355
356         if( (out = abook_fopen(datafile_new, "w")) == NULL ) {
357                 ret = -1;
358                 goto out;
359         }
360
361         if(!list_is_empty())
362                 /*
363                  * Possibly should check if write_database failed.
364                  * Currently it returns always zero.
365                  */
366                 write_database(out, e);
367
368         fclose(out);
369
370         if(access(datafile, F_OK) == 0 &&
371                         (rename(datafile, datafile_old)) == -1)
372                 ret = -1;
373         
374         if((rename(datafile_new, datafile)) == -1)
375                 ret = -1;
376
377 out:
378         free(datafile_new);
379         free(datafile_old);
380         return ret;
381 }
382
383 static void
384 db_free_item(int item)
385 {
386         item_empty(database[item]);
387 }
388
389 void
390 close_database()
391 {
392         int i;
393
394         for(i=0; i <= LAST_ITEM; i++)
395                 db_free_item(i);
396
397         xfree(database);
398         free(selected);
399
400         database = NULL;
401         selected = NULL;
402
403         items = 0;
404         first_list_item = curitem = -1;
405         list_capacity = 0;
406 }
407
408
409 static void
410 validate_item(list_item item)
411 {
412         abook_field_list *f;
413         int i, max_field_len;
414         char *tmp;
415
416         for(f = fields_list, i = 0; f; f = f->next, i++) {
417                 max_field_len = 0;
418
419                 switch(f->field->type) {
420                         case FIELD_EMAILS:
421                                 max_field_len = MAX_EMAILSTR_LEN;
422                                 if(item[i] == NULL)
423                                         item[i] = xstrdup("");
424                                 break;
425                         case FIELD_LIST:
426                                 /* TODO quote string if it contains commas */
427                                 break;
428                         case FIELD_STRING:
429                                 max_field_len = MAX_FIELD_LEN;
430                                 break;
431                         case FIELD_DATE:
432                                 break;
433                         default:
434                                 assert(0);
435                 }
436
437                 if(max_field_len && item[i] &&
438                                 ((int)strlen(item[i]) > max_field_len)) {
439                         /* truncate field */
440                         tmp = item[i];
441                         item[i][max_field_len - 1] = 0;
442                         item[i] = xstrdup(item[i]);
443                         free(tmp);
444                 }
445         }
446 }
447
448 static void
449 adjust_list_capacity()
450 {
451         if(list_capacity < 1)
452                 list_capacity = INITIAL_LIST_CAPACITY;
453         else if(items >= list_capacity)
454                 list_capacity *= 2;
455         else if(list_capacity / 2 > items)
456                 list_capacity /= 2;
457         else
458                 return;
459
460         if(database)
461                 database = xrealloc(database,sizeof(list_item) * list_capacity);
462         else /* allocate memory _and_ initialize pointers to NULL */
463                 database = xmalloc0(sizeof(list_item) * list_capacity);
464
465         selected = xrealloc(selected, list_capacity);
466 }
467
468 int
469 add_item2database(list_item item)
470 {
471         /* 'name' field is mandatory */
472         if((item[field_id(NAME)] == NULL) || ! *item[field_id(NAME)]) {
473                 item_empty(item);
474                 return 1;
475         }
476
477         if(++items > list_capacity)
478                 adjust_list_capacity();
479
480         validate_item(item);
481
482         selected[LAST_ITEM] = 0;
483
484         database[LAST_ITEM] = item_create();
485         item_copy(database[LAST_ITEM], item);
486
487         return 0;
488 }
489         
490
491 void
492 remove_selected_items()
493 {
494         int i, j;
495
496         if(list_is_empty())
497                 return;
498
499         if(!selected_items())
500                 selected[curitem] = 1;
501
502         for(j = LAST_ITEM; j >= 0; j--) {
503                 if(selected[j]) {
504                         db_free_item(j); /* added for .4 data_s_ */
505                         for(i = j; i < LAST_ITEM; i++) {
506                                 item_copy(database[i], database[i + 1]);
507                                 selected[i] = selected[i + 1];
508                         }
509                         item_free(&database[LAST_ITEM]);
510                         items--;
511                 }
512         }
513
514         if(curitem > LAST_ITEM && items > 0)
515                 curitem = LAST_ITEM;
516
517         adjust_list_capacity();
518
519         select_none();
520 }
521
522 char *
523 get_surname(char *s)
524 {
525         char *p = s + strlen(s);
526
527         assert(s != NULL);
528
529         while(p > s && *(p - 1) != ' ')
530                 p--;
531
532         return xstrdup(p);
533 }
534
535 static int
536 surnamecmp(const void *i1, const void *i2)
537 {
538         int ret, idx = field_id(NAME);
539         char *n1, *n2, *s1, *s2;
540
541         n1 = (*(list_item *)i1)[idx];
542         n2 = (*(list_item *)i2)[idx];
543         
544         s1 = get_surname(n1);
545         s2 = get_surname(n2);
546
547         if( !(ret = safe_strcoll(s1, s2)) )
548                 ret = safe_strcoll(n1, n2);
549
550         free(s1);
551         free(s2);
552
553         return ret;
554 }
555
556 static int sort_field = -1;
557
558 static int
559 namecmp(const void *i1, const void *i2)
560 {
561         char *n1, *n2;
562
563         assert(sort_field >= 0 && sort_field < fields_count);
564
565         n1 = (*(list_item *)i1)[sort_field];
566         n2 = (*(list_item *)i2)[sort_field];
567
568         return safe_strcoll(n1, n2);
569 }
570
571 void
572 sort_by_field(char *name)
573 {
574         int field;
575
576         select_none();
577
578         name = (name == NULL) ? opt_get_str(STR_SORT_FIELD) : name;
579         find_field_number(name, &field);
580
581         if(field < 0) {
582                 if(name == opt_get_str(STR_SORT_FIELD))
583                         statusline_msg(_("Invalid field value defined "
584                                 "in configuration"));
585                 else
586                         statusline_msg(_("Invalid field value for sorting"));
587
588                 return;
589         }
590
591         sort_field = field;
592
593         qsort((void *)database, items, sizeof(list_item), namecmp);
594
595         refresh_screen();
596 }
597
598 void
599 sort_surname()
600 {
601         select_none();
602
603         qsort((void *)database, items, sizeof(list_item), surnamecmp);
604
605         refresh_screen();
606 }
607
608 /* TODO implement a search based on more sophisticated patterns */
609 int
610 find_item(char *str, int start, int search_fields[])
611 {
612         int i, id;
613         char *findstr = NULL;
614         char *tmp = NULL;
615         int ret = -1; /* not found */
616         struct db_enumerator e = init_db_enumerator(ENUM_ALL);
617
618         if(list_is_empty() || !is_valid_item(start))
619                 return -2; /* error */
620
621         findstr = xstrdup(str);
622         findstr = strlower(findstr);
623
624         e.item = start - 1; /* must be "real start" - 1 */
625         db_enumerate_items(e) {
626                 for(i = 0; search_fields[i] >= 0; i++) {
627                         if((id = field_id(search_fields[i])) == -1)
628                                 continue;
629                         if(database[e.item][id] == NULL)
630                                 continue;
631                         tmp = xstrdup(database[e.item][id]);
632                         if( tmp && strstr(strlower(tmp), findstr) ) {
633                                 ret = e.item;
634                                 goto out;
635                         }
636                         xfree(tmp);
637                 }
638         }
639
640 out:
641         free(findstr);
642         free(tmp);
643         return ret;
644 }
645
646 int
647 is_selected(int item)
648 {
649         return selected[item];
650 }
651
652 int
653 is_valid_item(int item)
654 {
655         return item <= LAST_ITEM && item >= 0;
656 }
657
658 int
659 last_item()
660 {
661         return LAST_ITEM;
662 }
663
664 int
665 db_n_items()
666 {
667         return items;
668 }
669
670 int
671 real_db_enumerate_items(struct db_enumerator e)
672 {
673         int item = max(0, e.item + 1);
674         int i;
675
676         switch(e.mode) {
677 #ifdef DEBUG
678                 case ENUM_ALL:
679                         break;
680 #endif
681                 case ENUM_SELECTED:
682                         for(i = item; i <= LAST_ITEM; i++) {
683                                 if(is_selected(i)) {
684                                         item = i;
685                                         goto out;
686                                 }
687                         }
688                         return -1;
689 #ifdef DEBUG
690                 default:
691                         fprintf(stderr, "real_db_enumerate_items() "
692                                         "BUG: unknown db_enumerator mode: %d\n",
693                                         e.mode);
694                         break;
695 #endif
696         }
697 out:
698         return (item > LAST_ITEM || item < 0) ? -1 : item;
699 }
700
701 struct db_enumerator
702 init_db_enumerator(int mode)
703 {
704         struct db_enumerator e;
705
706         e.item = -1; /* important - means "start from beginning" */
707         e.mode = mode;
708
709         return e;
710 }
711
712
713 list_item
714 item_create()
715 {
716         return xmalloc0(ITEM_SIZE);
717 }
718
719 void
720 item_free(list_item *item)
721 {
722         assert(item);
723
724         xfree(*item);
725 }
726
727 void
728 item_empty(list_item item)
729 {       int i;
730
731         assert(item);
732
733         for(i = 0; i < fields_count; i++)
734                 if(item[i])
735                         xfree(item[i]);
736
737 }
738
739 void
740 item_copy(list_item dest, list_item src)
741 {
742         memmove(dest, src, ITEM_SIZE);
743 }
744
745 void
746 item_duplicate(list_item dest, list_item src)
747 {
748         int i;
749
750         for(i = 0; i < fields_count; i++)
751                 dest[i] = src[i] ? xstrdup(src[i]) : NULL;
752 }
753
754 /* 
755  * Things like item[field_id(NICK)] should never be used, since besides NAME
756  * and EMAIL, none of the standard fields can be assumed to be existing.
757  *
758  * Prefer the functions item_fput(), item_fget(), db_fput() and db_fget()
759  * to access fields in items and database.
760  */
761
762 /* quick lookup by "standard" field number */
763 inline int
764 field_id(int i)
765 {
766         assert((i >= 0) && (i < ITEM_FIELDS));
767         return standard_fields_indexed[i];
768 }
769
770 int
771 item_fput(list_item item, int i, char *val)
772 {
773         int id = field_id(i);
774
775         if(id != -1) {
776                 item[id] = val;
777                 return 1;
778         }
779
780         return 0;
781 }
782
783 char *
784 item_fget(list_item item, int i)
785 {
786         int id = field_id(i);
787
788         if(id != -1)
789                 return item[id];
790         else
791                 return NULL;
792 }
793
794 int
795 real_db_field_put(int item, int i, int std, char *val)
796 {
797         int id;
798
799         assert(database[item]);
800
801         id = std ? field_id(i) : i;
802
803         if(id != -1) {
804                 database[item][id] = val;
805                 return 1;
806         }
807
808         return 0;
809 }
810
811 char *
812 real_db_field_get(int item, int i, int std)
813 {
814         int id;
815
816         assert(database[item]);
817
818         id = std ? field_id(i) : i;
819
820         if(id != -1)
821                 return database[item][id];
822         else
823                 return NULL;
824 }
825
826 list_item
827 db_item_get(int i)
828 {
829         return database[i];
830 }
831
832 /* Fetch addresses from all fields of FIELD_EMAILS type */
833 /* Memory has to be freed by the caller */
834 char *
835 db_email_get(int item)
836 {
837         int i;
838         char *res;
839         abook_field_list *cur;
840         abook_list *emails = NULL;
841
842         for(cur = fields_list, i = 0; cur; cur = cur->next, i++)
843                 if(cur->field->type == FIELD_EMAILS && *database[item][i])
844                         abook_list_append(&emails, database[item][i]);
845
846         res = abook_list_to_csv(emails);
847         abook_list_free(&emails);
848         return res ? res : xstrdup("");
849 }
850