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