]> git.deb.at Git - pkg/abook.git/blob - database.c
- don't use items variable outside of database.c
[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_DAY},    /* 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("day", type))
181                 f->type = FIELD_DAY;
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 < fields_count; i++)
207                 if(database[i])
208                         database[i] = xrealloc(database[i], ITEM_SIZE);
209 }
210
211 /*
212  * Declare "standard" fields, thus preserving them while parsing a database,
213  * even if they won't be displayed.
214  */
215 void
216 init_standard_fields()
217 {
218         int i;
219
220         for(i = 0; standard_fields[i].key; i++)
221                 if(standard_fields_indexed[i] == -1)
222                         declare_standard_field(i);
223 }
224
225 /* Some initializations - Must be called _before_ load_opts() */
226 void
227 prepare_database_internals()
228 {
229         int i;
230
231         for(i = 0; i < ITEM_FIELDS; i++)
232                 standard_fields_indexed[i] = -1;
233
234         /* the only two mandatory fields */
235         declare_standard_field(NAME);
236         declare_standard_field(EMAIL);
237 }
238
239 int
240 parse_database(FILE *in)
241 {
242         char *line = NULL;
243         char *tmp;
244         int sec=0, field;
245         list_item item;
246
247         item = item_create();
248
249         for(;;) {
250                 line = getaline(in);
251                 if(feof(in)) {
252                         if(item[field_id(NAME)] && sec) {
253                                 add_item2database(item);
254                         } else {
255                                 item_empty(item);
256                         }
257                         break;
258                 }
259
260                 if(!*line || *line == '\n' || *line == '#') {
261                         goto next;
262                 } else if(*line == '[') {
263                         if(item[field_id(NAME)] && sec ) {
264                                 add_item2database(item);
265                         } else {
266                                 item_empty(item);
267                         }
268                         sec = 1;
269                         memset(item, 0, ITEM_SIZE);
270                         if(!(tmp = strchr(line, ']')))
271                                 sec = 0; /*incorrect section lines are skipped*/
272                 } else if((tmp = strchr(line, '=') ) && sec) {
273                         *tmp++ = '\0';
274                         find_field_number(line, &field);
275                         if(field != -1) {
276                                 item[field] = xstrdup(tmp);
277                                 goto next;
278                         } else if(!strcasecmp(opt_get_str(STR_PRESERVE_FIELDS),
279                                                 "all")){
280                                 declare_unknown_field(line);
281                                 item = xrealloc(item, ITEM_SIZE);
282                                 item[fields_count - 1] = xstrdup(tmp);
283                                 goto next;
284                         }
285                 }
286 next:
287                 xfree(line);
288         }
289
290         xfree(line);
291         item_free(&item);
292         return 0;
293 }
294
295 int
296 load_database(char *filename)
297 {
298         FILE *in;
299
300         if(database != NULL)
301                 close_database();
302
303         if ((in = abook_fopen(filename, "r")) == NULL)
304                 return -1;
305
306         parse_database(in);
307
308         return (items == 0) ? 2 : 0;
309 }
310
311 int
312 write_database(FILE *out, struct db_enumerator e)
313 {
314         int j;
315         int i = 0;
316         abook_field_list *cur;
317
318         fprintf(out,
319                 "# abook addressbook file\n\n"
320                 "[format]\n"
321                 "program=" PACKAGE "\n"
322                 "version=" VERSION "\n"
323                 "\n\n"
324         );
325
326         db_enumerate_items(e) {
327                 fprintf(out, "[%d]\n", i);
328
329                 for(cur = fields_list, j = 0; cur; cur = cur->next, j++) {
330                         if( database[e.item][j] != NULL &&
331                                         *database[e.item][j] )
332                                 fprintf(out, "%s=%s\n",
333                                         cur->field->key,
334                                         database[e.item][j]
335                                         );
336                 }
337
338                 fputc('\n', out);
339                 i++;
340         }
341
342         return 0;
343 }
344
345 int
346 save_database()
347 {
348         FILE *out;
349         int ret = 0;
350         struct db_enumerator e = init_db_enumerator(ENUM_ALL);
351         char *datafile_new = strconcat(datafile, ".new", NULL);
352         char *datafile_old = strconcat(datafile, "~", NULL);
353
354         if( (out = abook_fopen(datafile_new, "w")) == NULL ) {
355                 ret = -1;
356                 goto out;
357         }
358
359         if(list_is_empty()) {
360                 fclose(out);
361                 unlink(datafile);
362                 ret = 1;
363                 goto out;
364         }
365
366         /*
367          * Possibly should check if write_database failed.
368          * Currently it returns always zero.
369          */
370         write_database(out, e);
371         fclose(out);
372
373         if(access(datafile, F_OK) == 0 &&
374                         (rename(datafile, datafile_old)) == -1)
375                 ret = -1;
376         
377         if((rename(datafile_new, datafile)) == -1)
378                 ret = -1;
379
380 out:
381         free(datafile_new);
382         free(datafile_old);
383         return ret;
384 }
385
386 static void
387 db_free_item(int item)
388 {
389         item_empty(database[item]);
390 }
391
392 void
393 close_database()
394 {
395         int i;
396
397         for(i=0; i <= LAST_ITEM; i++)
398                 db_free_item(i);
399
400         xfree(database);
401         free(selected);
402
403         database = NULL;
404         selected = NULL;
405
406         items = 0;
407         first_list_item = curitem = -1;
408         list_capacity = 0;
409 }
410
411
412 static void
413 validate_item(list_item item)
414 {
415         abook_field_list *f;
416         int i, max_field_len;
417         char *tmp;
418
419         for(f = fields_list, i = 0; f; f = f->next, i++) {
420                 max_field_len = 0;
421
422                 switch(f->field->type) {
423                         case FIELD_EMAILS:
424                                 max_field_len = MAX_EMAILSTR_LEN;
425                                 if(item[i] == NULL)
426                                         item[i] = xstrdup("");
427                                 break;
428                         case FIELD_LIST:
429                                 /* TODO quote string if it contains commas */
430                                 break;
431                         case FIELD_STRING:
432                                 max_field_len = MAX_FIELD_LEN;
433                                 break;
434                         case FIELD_DAY:
435                                 break;
436                         default:
437                                 assert(0);
438                 }
439
440                 if(max_field_len && item[i] &&
441                                 ((int)strlen(item[i]) > max_field_len)) {
442                         /* truncate field */
443                         tmp = item[i];
444                         item[i][max_field_len - 1] = 0;
445                         item[i] = xstrdup(item[i]);
446                         free(tmp);
447                 }
448         }
449 }
450
451 static void
452 adjust_list_capacity()
453 {
454         if(list_capacity < 1)
455                 list_capacity = INITIAL_LIST_CAPACITY;
456         else if(items >= list_capacity)
457                 list_capacity *= 2;
458         else if(list_capacity / 2 > items)
459                 list_capacity /= 2;
460         else
461                 return;
462
463         if(database)
464                 database = xrealloc(database,sizeof(list_item) * list_capacity);
465         else /* allocate memory _and_ initialize pointers to NULL */
466                 database = xmalloc0(sizeof(list_item) * list_capacity);
467
468         selected = xrealloc(selected, list_capacity);
469 }
470
471 int
472 add_item2database(list_item item)
473 {
474         /* 'name' field is mandatory */
475         if((item[field_id(NAME)] == NULL) || ! *item[field_id(NAME)]) {
476                 item_empty(item);
477                 return 1;
478         }
479
480         if(++items > list_capacity)
481                 adjust_list_capacity();
482
483         validate_item(item);
484
485         selected[LAST_ITEM] = 0;
486
487         database[LAST_ITEM] = item_create();
488         item_copy(database[LAST_ITEM], item);
489
490         return 0;
491 }
492         
493
494 void
495 remove_selected_items()
496 {
497         int i, j;
498
499         if(list_is_empty())
500                 return;
501
502         if(!selected_items())
503                 selected[curitem] = 1;
504
505         for(j = LAST_ITEM; j >= 0; j--) {
506                 if(selected[j]) {
507                         db_free_item(j); /* added for .4 data_s_ */
508                         for(i = j; i < LAST_ITEM; i++) {
509                                 item_copy(database[i], database[i + 1]);
510                                 selected[i] = selected[i + 1];
511                         }
512                         item_free(&database[LAST_ITEM]);
513                         items--;
514                 }
515         }
516
517         if(curitem > LAST_ITEM && items > 0)
518                 curitem = LAST_ITEM;
519
520         adjust_list_capacity();
521
522         select_none();
523 }
524
525 char *
526 get_surname(char *s)
527 {
528         char *p = s + strlen(s);
529
530         assert(s != NULL);
531
532         while(p > s && *(p - 1) != ' ')
533                 p--;
534
535         return xstrdup(p);
536 }
537
538 static int
539 surnamecmp(const void *i1, const void *i2)
540 {
541         int ret, idx = field_id(NAME);
542         char *n1, *n2, *s1, *s2;
543
544         if(idx == 0)
545                 return 0; /* no 'name' field */
546
547         n1 = (*(list_item *)i1)[idx];
548         n2 = (*(list_item *)i2)[idx];
549         
550         s1 = get_surname(n1);
551         s2 = get_surname(n2);
552
553         if( !(ret = safe_strcoll(s1, s2)) )
554                 ret = safe_strcoll(n1, n2);
555
556         free(s1);
557         free(s2);
558
559         return ret;
560 }
561
562 static int sort_field = -1;
563
564 static int
565 namecmp(const void *i1, const void *i2)
566 {
567         char *n1, *n2;
568
569         assert(sort_field >= 0 && sort_field < fields_count);
570
571         n1 = (*(list_item *)i1)[sort_field];
572         n2 = (*(list_item *)i2)[sort_field];
573
574         return safe_strcoll(n1, n2);
575 }
576
577 void
578 sort_by_field(char *name)
579 {
580         int field;
581
582         select_none();
583
584         name = (name == NULL) ? opt_get_str(STR_SORT_FIELD) : name;
585         find_field_number(name, &field);
586
587         if(field < 0) {
588                 if(name == opt_get_str(STR_SORT_FIELD))
589                         statusline_msg(_("Invalid field value defined "
590                                 "in configuration"));
591                 else
592                         statusline_msg(_("Invalid field value for sorting"));
593
594                 return;
595         }
596
597         sort_field = field;
598
599         qsort((void *)database, items, sizeof(list_item), namecmp);
600
601         refresh_screen();
602 }
603
604 void
605 sort_surname()
606 {
607         select_none();
608
609         qsort((void *)database, items, sizeof(list_item), surnamecmp);
610
611         refresh_screen();
612 }
613
614 /* TODO implement a search based on more sophisticated patterns */
615 int
616 find_item(char *str, int start, int search_fields[])
617 {
618         int i, id;
619         char *findstr = NULL;
620         char *tmp = NULL;
621         int ret = -1; /* not found */
622         struct db_enumerator e = init_db_enumerator(ENUM_ALL);
623
624         if(list_is_empty() || !is_valid_item(start))
625                 return -2; /* error */
626
627         findstr = xstrdup(str);
628         findstr = strlower(findstr);
629
630         e.item = start - 1; /* must be "real start" - 1 */
631         db_enumerate_items(e) {
632                 for(i = 0; search_fields[i] >= 0; i++) {
633                         if((id = field_id(search_fields[i])) == -1)
634                                 continue;
635                         if(database[e.item][id] == NULL)
636                                 continue;
637                         tmp = xstrdup(database[e.item][id]);
638                         if( tmp && strstr(strlower(tmp), findstr) ) {
639                                 ret = e.item;
640                                 goto out;
641                         }
642                         xfree(tmp);
643                 }
644         }
645
646 out:
647         free(findstr);
648         free(tmp);
649         return ret;
650 }
651
652 int
653 is_selected(int item)
654 {
655         return selected[item];
656 }
657
658 int
659 is_valid_item(int item)
660 {
661         return item <= LAST_ITEM && item >= 0;
662 }
663
664 int
665 last_item()
666 {
667         return LAST_ITEM;
668 }
669
670 int
671 db_n_items()
672 {
673         return items;
674 }
675
676 int
677 real_db_enumerate_items(struct db_enumerator e)
678 {
679         int item = max(0, e.item + 1);
680         int i;
681
682         switch(e.mode) {
683 #ifdef DEBUG
684                 case ENUM_ALL:
685                         break;
686 #endif
687                 case ENUM_SELECTED:
688                         for(i = item; i <= LAST_ITEM; i++) {
689                                 if(is_selected(i)) {
690                                         item = i;
691                                         goto out;
692                                 }
693                         }
694                         return -1;
695 #ifdef DEBUG
696                 default:
697                         fprintf(stderr, "real_db_enumerate_items() "
698                                         "BUG: unknown db_enumerator mode: %d\n",
699                                         e.mode);
700                         break;
701 #endif
702         }
703 out:
704         return (item > LAST_ITEM || item < 0) ? -1 : item;
705 }
706
707 struct db_enumerator
708 init_db_enumerator(int mode)
709 {
710         struct db_enumerator e;
711
712         e.item = -1; /* important - means "start from beginning" */
713         e.mode = mode;
714
715         return e;
716 }
717
718
719 list_item
720 item_create()
721 {
722         return xmalloc0(ITEM_SIZE);
723 }
724
725 void
726 item_free(list_item *item)
727 {
728         assert(item);
729
730         xfree(*item);
731 }
732
733 void
734 item_empty(list_item item)
735 {       int i;
736
737         assert(item);
738
739         for(i = 0; i < fields_count; i++)
740                 if(item[i])
741                         xfree(item[i]);
742
743 }
744
745 void
746 item_copy(list_item dest, list_item src)
747 {
748         memmove(dest, src, ITEM_SIZE);
749 }
750
751 void
752 item_duplicate(list_item dest, list_item src)
753 {
754         int i;
755
756         for(i = 0; i < fields_count; i++)
757                 dest[i] = src[i] ? xstrdup(src[i]) : NULL;
758 }
759
760 /* 
761  * Things like item[field_id(NICK)] should never be used, since besides NAME
762  * and EMAIL, none of the standard fields can be assumed to be existing.
763  *
764  * Prefer the functions item_fput(), item_fget(), db_fput() and db_fget()
765  * to access fields in items and database.
766  */
767
768 /* quick lookup by "standard" field number */
769 inline int
770 field_id(int i)
771 {
772         assert((i >= 0) && (i < ITEM_FIELDS));
773         return standard_fields_indexed[i];
774 }
775
776 int
777 item_fput(list_item item, int i, char *val)
778 {
779         int id = field_id(i);
780
781         if(id != -1) {
782                 item[id] = val;
783                 return 1;
784         }
785
786         return 0;
787 }
788
789 char *
790 item_fget(list_item item, int i)
791 {
792         int id = field_id(i);
793
794         if(id != -1)
795                 return item[id];
796         else
797                 return NULL;
798 }
799
800 int
801 real_db_field_put(int item, int i, int std, char *val)
802 {
803         int id;
804
805         assert(database[item]);
806
807         id = std ? field_id(i) : i;
808
809         if(id != -1) {
810                 database[item][id] = val;
811                 return 1;
812         }
813
814         return 0;
815 }
816
817 char *
818 real_db_field_get(int item, int i, int std)
819 {
820         int id;
821
822         assert(database[item]);
823
824         id = std ? field_id(i) : i;
825
826         if(id != -1)
827                 return database[item][id];
828         else
829                 return NULL;
830 }
831
832 list_item
833 db_item_get(int i)
834 {
835         return database[i];
836 }
837