3 * $Id: database.c,v 1.36 2006/08/09 21:54:56 cduval Exp $
5 * by JH <jheinonen@users.sourceforge.net>
7 * Copyright (C) Jaakko Heinonen
25 abook_field_list *fields_list = NULL;
28 list_item *database = NULL;
31 #define ITEM_SIZE (fields_count * sizeof(char *))
32 #define LAST_ITEM (items - 1)
34 #define INITIAL_LIST_CAPACITY 30
35 static int list_capacity = 0;
37 int standard_fields_indexed[ITEM_FIELDS];
40 * notes about adding predefined "standard" fields:
41 * - leave alone "name" and "email"
42 * - reorganize the field numbers in database.h
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 */
65 extern int first_list_item;
67 extern char *selected;
68 extern char *datafile;
73 declare_standard_field(int i)
75 abook_field *f = xmalloc(sizeof(abook_field));
77 f = memcpy(f, &standard_fields[i], sizeof(abook_field));
78 f->name = xstrdup(gettext(f->name));
80 add_field(&fields_list, f);
82 assert(standard_fields_indexed[i] == -1);
83 standard_fields_indexed[i] = fields_count++;
89 find_standard_field(char *key, int do_declare)
93 for(i = 0; standard_fields[i].key; i++)
94 if(0 == strcmp(standard_fields[i].key, key))
100 return do_declare ? declare_standard_field(i) : &standard_fields[i];
103 /* Search for a field. Use the list of declared fields if no list specified. */
105 real_find_field(char *key, abook_field_list *list, int *number)
107 abook_field_list *cur;
110 for(cur = (list ? list : fields_list), i = 0; cur; cur = cur->next, i++)
111 if(0 == strcmp(cur->field->key, key)) {
124 get_field_keyname(int i, char **key, char **name)
126 abook_field_list *cur = fields_list;
129 assert(i < fields_count);
131 for(j = 0; i >= 0 && j < i; j++, cur = cur->next)
135 *key = (i < 0) ? NULL : cur->field->key;
137 *name = (i < 0) ? NULL : cur->field->name;
141 add_field(abook_field_list **list, abook_field *f)
143 abook_field_list *tmp;
145 for(tmp = *list; tmp && tmp->next; tmp = tmp->next)
149 tmp->next = xmalloc(sizeof(abook_field_list));
152 *list = tmp = xmalloc(sizeof(abook_field_list));
159 declare_new_field(char *key, char *name, char *type, int accept_standard)
163 if(find_declared_field(key))
164 return _("field already defined");
166 if(find_standard_field(key, accept_standard))
167 return accept_standard ? NULL /* ok, added */ :
168 _("standard field does not need to be declared");
170 f = xmalloc(sizeof(abook_field));
171 f->key = xstrdup(key);
172 f->name = xstrdup(name);
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))
183 return _("unknown type");
185 add_field(&fields_list, f);
192 * Declare a new field while database is already loaded
193 * making it grow accordingly
196 declare_unknown_field(char *key)
200 declare_new_field(key, key, "string",
201 1 /* accept to declare "standard" fields */);
206 for(i = 0; i < items; i++)
208 database[i] = xrealloc(database[i], ITEM_SIZE);
209 database[i][fields_count - 1] = NULL;
214 * Declare "standard" fields, thus preserving them while parsing a database,
215 * even if they won't be displayed.
218 init_standard_fields()
222 for(i = 0; standard_fields[i].key; i++)
223 if(standard_fields_indexed[i] == -1)
224 declare_standard_field(i);
227 /* Some initializations - Must be called _before_ load_opts() */
229 prepare_database_internals()
233 for(i = 0; i < ITEM_FIELDS; i++)
234 standard_fields_indexed[i] = -1;
236 /* the only two mandatory fields */
237 declare_standard_field(NAME);
238 declare_standard_field(EMAIL);
242 parse_database(FILE *in)
249 item = item_create();
254 if(item[field_id(NAME)] && sec) {
255 add_item2database(item);
262 if(!*line || *line == '\n' || *line == '#') {
264 } else if(*line == '[') {
265 if(item[field_id(NAME)] && sec ) {
266 add_item2database(item);
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) {
276 find_field_number(line, &field);
278 item[field] = xstrdup(tmp);
280 } else if(!strcasecmp(opt_get_str(STR_PRESERVE_FIELDS),
282 declare_unknown_field(line);
283 item = xrealloc(item, ITEM_SIZE);
284 item[fields_count - 1] = xstrdup(tmp);
298 load_database(char *filename)
305 if ((in = abook_fopen(filename, "r")) == NULL)
310 return (items == 0) ? 2 : 0;
314 write_database(FILE *out, struct db_enumerator e)
318 abook_field_list *cur;
321 "# abook addressbook file\n\n"
323 "program=" PACKAGE "\n"
324 "version=" VERSION "\n"
328 db_enumerate_items(e) {
329 fprintf(out, "[%d]\n", i);
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",
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);
356 if( (out = abook_fopen(datafile_new, "w")) == NULL ) {
361 if(list_is_empty()) {
369 * Possibly should check if write_database failed.
370 * Currently it returns always zero.
372 write_database(out, e);
375 if(access(datafile, F_OK) == 0 &&
376 (rename(datafile, datafile_old)) == -1)
379 if((rename(datafile_new, datafile)) == -1)
389 db_free_item(int item)
391 item_empty(database[item]);
399 for(i=0; i <= LAST_ITEM; i++)
409 first_list_item = curitem = -1;
415 validate_item(list_item item)
418 int i, max_field_len;
421 for(f = fields_list, i = 0; f; f = f->next, i++) {
424 switch(f->field->type) {
426 max_field_len = MAX_EMAILSTR_LEN;
428 item[i] = xstrdup("");
431 /* TODO quote string if it contains commas */
434 max_field_len = MAX_FIELD_LEN;
442 if(max_field_len && item[i] &&
443 ((int)strlen(item[i]) > max_field_len)) {
446 item[i][max_field_len - 1] = 0;
447 item[i] = xstrdup(item[i]);
454 adjust_list_capacity()
456 if(list_capacity < 1)
457 list_capacity = INITIAL_LIST_CAPACITY;
458 else if(items >= list_capacity)
460 else if(list_capacity / 2 > items)
466 database = xrealloc(database,sizeof(list_item) * list_capacity);
467 else /* allocate memory _and_ initialize pointers to NULL */
468 database = xmalloc0(sizeof(list_item) * list_capacity);
470 selected = xrealloc(selected, list_capacity);
474 add_item2database(list_item item)
476 /* 'name' field is mandatory */
477 if((item[field_id(NAME)] == NULL) || ! *item[field_id(NAME)]) {
482 if(++items > list_capacity)
483 adjust_list_capacity();
487 selected[LAST_ITEM] = 0;
489 database[LAST_ITEM] = item_create();
490 item_copy(database[LAST_ITEM], item);
497 remove_selected_items()
504 if(!selected_items())
505 selected[curitem] = 1;
507 for(j = LAST_ITEM; j >= 0; j--) {
509 db_free_item(j); /* added for .4 data_s_ */
510 for(i = j; i < LAST_ITEM; i++) {
511 item_copy(database[i], database[i + 1]);
512 selected[i] = selected[i + 1];
514 item_free(&database[LAST_ITEM]);
519 if(curitem > LAST_ITEM && items > 0)
522 adjust_list_capacity();
530 char *p = s + strlen(s);
534 while(p > s && *(p - 1) != ' ')
541 surnamecmp(const void *i1, const void *i2)
543 int ret, idx = field_id(NAME);
544 char *n1, *n2, *s1, *s2;
546 n1 = (*(list_item *)i1)[idx];
547 n2 = (*(list_item *)i2)[idx];
549 s1 = get_surname(n1);
550 s2 = get_surname(n2);
552 if( !(ret = safe_strcoll(s1, s2)) )
553 ret = safe_strcoll(n1, n2);
561 static int sort_field = -1;
564 namecmp(const void *i1, const void *i2)
568 assert(sort_field >= 0 && sort_field < fields_count);
570 n1 = (*(list_item *)i1)[sort_field];
571 n2 = (*(list_item *)i2)[sort_field];
573 return safe_strcoll(n1, n2);
577 sort_by_field(char *name)
583 name = (name == NULL) ? opt_get_str(STR_SORT_FIELD) : name;
584 find_field_number(name, &field);
587 if(name == opt_get_str(STR_SORT_FIELD))
588 statusline_msg(_("Invalid field value defined "
589 "in configuration"));
591 statusline_msg(_("Invalid field value for sorting"));
598 qsort((void *)database, items, sizeof(list_item), namecmp);
608 qsort((void *)database, items, sizeof(list_item), surnamecmp);
613 /* TODO implement a search based on more sophisticated patterns */
615 find_item(char *str, int start, int search_fields[])
618 char *findstr = NULL;
620 int ret = -1; /* not found */
621 struct db_enumerator e = init_db_enumerator(ENUM_ALL);
623 if(list_is_empty() || !is_valid_item(start))
624 return -2; /* error */
626 findstr = xstrdup(str);
627 findstr = strlower(findstr);
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)
634 if(database[e.item][id] == NULL)
636 tmp = xstrdup(database[e.item][id]);
637 if( tmp && strstr(strlower(tmp), findstr) ) {
652 is_selected(int item)
654 return selected[item];
658 is_valid_item(int item)
660 return item <= LAST_ITEM && item >= 0;
676 real_db_enumerate_items(struct db_enumerator e)
678 int item = max(0, e.item + 1);
687 for(i = item; i <= LAST_ITEM; i++) {
696 fprintf(stderr, "real_db_enumerate_items() "
697 "BUG: unknown db_enumerator mode: %d\n",
703 return (item > LAST_ITEM || item < 0) ? -1 : item;
707 init_db_enumerator(int mode)
709 struct db_enumerator e;
711 e.item = -1; /* important - means "start from beginning" */
721 return xmalloc0(ITEM_SIZE);
725 item_free(list_item *item)
733 item_empty(list_item item)
738 for(i = 0; i < fields_count; i++)
745 item_copy(list_item dest, list_item src)
747 memmove(dest, src, ITEM_SIZE);
751 item_duplicate(list_item dest, list_item src)
755 for(i = 0; i < fields_count; i++)
756 dest[i] = src[i] ? xstrdup(src[i]) : NULL;
760 * Things like item[field_id(NICK)] should never be used, since besides NAME
761 * and EMAIL, none of the standard fields can be assumed to be existing.
763 * Prefer the functions item_fput(), item_fget(), db_fput() and db_fget()
764 * to access fields in items and database.
767 /* quick lookup by "standard" field number */
771 assert((i >= 0) && (i < ITEM_FIELDS));
772 return standard_fields_indexed[i];
776 item_fput(list_item item, int i, char *val)
778 int id = field_id(i);
789 item_fget(list_item item, int i)
791 int id = field_id(i);
800 real_db_field_put(int item, int i, int std, char *val)
804 assert(database[item]);
806 id = std ? field_id(i) : i;
809 database[item][id] = val;
817 real_db_field_get(int item, int i, int std)
821 assert(database[item]);
823 id = std ? field_id(i) : i;
826 return database[item][id];
837 /* Fetch addresses from all fields of FIELD_EMAILS type */
838 /* Memory has to be freed by the caller */
840 db_email_get(int item)
844 abook_field_list *cur;
845 abook_list *emails = NULL;
847 for(cur = fields_list, i = 0; cur; cur = cur->next, i++)
848 if(cur->field->type == FIELD_EMAILS && *database[item][i])
849 abook_list_append(&emails, database[item][i]);
851 res = abook_list_to_csv(emails);
852 abook_list_free(&emails);
853 return res ? res : xstrdup("");