-
Notifications
You must be signed in to change notification settings - Fork 9
/
database.c
952 lines (765 loc) · 17.2 KB
/
database.c
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
/*
* $Id$
*
* by JH <[email protected]>
*
* Copyright (C) Jaakko Heinonen
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "abook.h"
#include "database.h"
#include "gettext.h"
#include "list.h"
#include "misc.h"
#include "xmalloc.h"
abook_field_list *fields_list = NULL;
int fields_count = 0;
list_item *database = NULL;
static int items = 0;
#define ITEM_SIZE (fields_count * sizeof(char *))
#define LAST_ITEM (items - 1)
#define INITIAL_LIST_CAPACITY 30
static int list_capacity = 0;
int standard_fields_indexed[ITEM_FIELDS];
/*
* notes about adding predefined "standard" fields:
* - leave alone "name" and "email"
* - reorganize the field numbers in database.h
*/
abook_field standard_fields[] = {
{"name", N_("Name"), FIELD_STRING}, /* NAME */
{"email", N_("E-mail addresses"), FIELD_EMAILS}, /* EMAIL */
{"address", N_("Address"), FIELD_STRING}, /* ADDRESS */
{"address2", N_("Address2"), FIELD_STRING}, /* ADDRESS2 */
{"city", N_("City"), FIELD_STRING}, /* CITY */
{"state", N_("State/Province"), FIELD_STRING}, /* STATE */
{"zip", N_("ZIP/Postal Code"), FIELD_STRING}, /* ZIP */
{"country", N_("Country"), FIELD_STRING}, /* COUNTRY */
{"phone", N_("Home Phone"), FIELD_STRING}, /* PHONE */
{"workphone", N_("Work Phone"), FIELD_STRING}, /* WORKPHONE */
{"fax", N_("Fax"), FIELD_STRING}, /* FAX */
{"mobile", N_("Mobile"), FIELD_STRING}, /* MOBILEPHONE */
{"nick", N_("Nickname/Alias"), FIELD_STRING}, /* NICK */
{"url", N_("URL"), FIELD_STRING}, /* URL */
{"notes", N_("Notes"), FIELD_STRING}, /* NOTES */
{"anniversary", N_("Anniversary day"), FIELD_DATE}, /* ANNIVERSARY */
{"groups", N_("Groups"), FIELD_LIST}, /* GROUPS */
{0} /* ITEM_FIELDS */
};
extern int first_list_item;
extern int curitem;
extern char *selected;
extern char *datafile;
static abook_field *
declare_standard_field(int i)
{
abook_field *f = xmalloc(sizeof(abook_field));
f = memcpy(f, &standard_fields[i], sizeof(abook_field));
f->name = xstrdup(gettext(f->name));
add_field(&fields_list, f);
assert(standard_fields_indexed[i] == -1);
standard_fields_indexed[i] = fields_count++;
return f;
}
abook_field *
find_standard_field(char *key, int do_declare)
{
int i;
for(i = 0; standard_fields[i].key; i++)
if(0 == strcmp(standard_fields[i].key, key))
goto found;
return NULL;
found:
return do_declare ? declare_standard_field(i) : &standard_fields[i];
}
/* Search for a field. Use the list of declared fields if no list specified. */
abook_field *
real_find_field(char *key, abook_field_list *list, int *number)
{
abook_field_list *cur;
int i;
for(cur = (list ? list : fields_list), i = 0; cur; cur = cur->next, i++)
if(0 == strcmp(cur->field->key, key)) {
if(number)
*number = i;
return cur->field;
}
if(number)
*number = -1;
return NULL;
}
void
get_field_info(int i, char **key, char **name, int *type)
{
abook_field_list *cur = fields_list;
int j;
assert(i < fields_count);
for(j = 0; i >= 0 && j < i; j++, cur = cur->next)
;
if(key)
*key = (i < 0) ? NULL : cur->field->key;
if(name)
*name = (i < 0) ? NULL : cur->field->name;
if(type)
*type = (i < 0) ? -1 : cur->field->type;
}
void
add_field(abook_field_list **list, abook_field *f)
{
abook_field_list *tmp;
for(tmp = *list; tmp && tmp->next; tmp = tmp->next)
;
if(tmp) {
tmp->next = xmalloc(sizeof(abook_field_list));
tmp = tmp->next;
} else
*list = tmp = xmalloc(sizeof(abook_field_list));
tmp->field = f;
tmp->next = NULL;
}
char *
declare_new_field(char *key, char *name, char *type, int accept_standard)
{
abook_field *f;
if(find_declared_field(key))
return _("field already defined");
if(find_standard_field(key, accept_standard))
return accept_standard ? NULL /* ok, added */ :
_("standard field does not need to be declared");
f = xmalloc(sizeof(abook_field));
f->key = xstrdup(key);
f->name = xstrdup(name);
if(!*type || (0 == strcasecmp("string", type)))
f->type = FIELD_STRING;
else if(0 == strcasecmp("emails", type))
f->type = FIELD_EMAILS;
else if(0 == strcasecmp("list", type))
f->type = FIELD_LIST;
else if(0 == strcasecmp("date", type))
f->type = FIELD_DATE;
else
return _("unknown type");
add_field(&fields_list, f);
fields_count++;
return NULL;
}
/*
* Declare a new field while database is already loaded
* making it grow accordingly
*/
static void
declare_unknown_field(char *key)
{
int i;
declare_new_field(key, key, "string",
1 /* accept to declare "standard" fields */);
if(!database)
return;
for(i = 0; i < items; i++)
if(database[i]) {
database[i] = xrealloc(database[i], ITEM_SIZE);
database[i][fields_count - 1] = NULL;
}
}
/*
* Declare "standard" fields, thus preserving them while parsing a database,
* even if they won't be displayed.
*/
void
init_standard_fields()
{
int i;
for(i = 0; standard_fields[i].key; i++)
if(standard_fields_indexed[i] == -1)
declare_standard_field(i);
}
/* Some initializations - Must be called _before_ load_opts() */
void
prepare_database_internals()
{
int i;
for(i = 0; i < ITEM_FIELDS; i++)
standard_fields_indexed[i] = -1;
/* the only two mandatory fields */
declare_standard_field(NAME);
declare_standard_field(EMAIL);
/* search NICK as well */
declare_standard_field(NICK);
}
int
parse_database(FILE *in)
{
char *line = NULL;
char *tmp;
int sec=0, field;
list_item item;
item = item_create();
for(;;) {
line = getaline(in);
if(feof(in)) {
if(item[field_id(NAME)] && sec) {
add_item2database(item);
} else {
item_empty(item);
}
break;
}
if(!*line || *line == '\n' || *line == '#') {
goto next;
} else if(*line == '[') {
if(item[field_id(NAME)] && sec ) {
add_item2database(item);
} else {
item_empty(item);
}
sec = 1;
memset(item, 0, ITEM_SIZE);
if(!(tmp = strchr(line, ']')))
sec = 0; /*incorrect section lines are skipped*/
} else if((tmp = strchr(line, '=') ) && sec) {
*tmp++ = '\0';
find_field_number(line, &field);
if(field != -1) {
item[field] = xstrdup(tmp);
goto next;
} else if(!strcasecmp(opt_get_str(STR_PRESERVE_FIELDS),
"all")){
declare_unknown_field(line);
item = xrealloc(item, ITEM_SIZE);
item[fields_count - 1] = xstrdup(tmp);
goto next;
}
}
next:
xfree(line);
}
xfree(line);
item_free(&item);
return 0;
}
int
load_database(char *filename)
{
FILE *in;
if(database != NULL)
close_database();
if ((in = abook_fopen(filename, "r")) == NULL)
return -1;
parse_database(in);
return (items == 0) ? 2 : 0;
}
int
write_database(FILE *out, struct db_enumerator e)
{
int j;
int i = 0;
abook_field_list *cur;
fprintf(out,
"# abook addressbook file\n\n"
"[format]\n"
"program=" PACKAGE "\n"
"version=" VERSION "\n"
"\n\n"
);
db_enumerate_items(e) {
fprintf(out, "[%d]\n", i);
for(cur = fields_list, j = 0; cur; cur = cur->next, j++) {
if( database[e.item][j] != NULL &&
*database[e.item][j] )
fprintf(out, "%s=%s\n",
cur->field->key,
database[e.item][j]
);
}
fputc('\n', out);
i++;
}
return 0;
}
int
save_database()
{
FILE *out;
int ret = 0;
struct db_enumerator e = init_db_enumerator(ENUM_ALL);
char *datafile_new = strconcat(datafile, ".new", NULL);
char *datafile_old = strconcat(datafile, "~", NULL);
if( (out = abook_fopen(datafile_new, "w")) == NULL ) {
ret = -1;
goto out;
}
if(!list_is_empty())
/*
* Possibly should check if write_database failed.
* Currently it returns always zero.
*/
write_database(out, e);
fclose(out);
if(access(datafile, F_OK) == 0 &&
(rename(datafile, datafile_old)) == -1)
ret = -1;
if((rename(datafile_new, datafile)) == -1)
ret = -1;
out:
free(datafile_new);
free(datafile_old);
return ret;
}
static void
db_free_item(int item)
{
item_empty(database[item]);
}
void
close_database()
{
int i;
for(i=0; i <= LAST_ITEM; i++)
db_free_item(i);
xfree(database);
free(selected);
database = NULL;
selected = NULL;
items = 0;
first_list_item = curitem = -1;
list_capacity = 0;
}
static void
validate_item(list_item item)
{
abook_field_list *f;
int i, max_field_len;
char *tmp;
for(f = fields_list, i = 0; f; f = f->next, i++) {
max_field_len = 0;
switch(f->field->type) {
case FIELD_EMAILS:
max_field_len = MAX_EMAILSTR_LEN;
if(item[i] == NULL)
item[i] = xstrdup("");
break;
case FIELD_LIST:
/* TODO quote string if it contains commas */
break;
case FIELD_STRING:
max_field_len = MAX_FIELD_LEN;
break;
case FIELD_DATE:
break;
default:
assert(0);
}
if(max_field_len && item[i] &&
((int)strlen(item[i]) > max_field_len)) {
/* truncate field */
tmp = item[i];
item[i][max_field_len - 1] = 0;
item[i] = xstrdup(item[i]);
free(tmp);
}
}
}
static void
adjust_list_capacity()
{
if(list_capacity < 1)
list_capacity = INITIAL_LIST_CAPACITY;
else if(items >= list_capacity)
list_capacity *= 2;
else if(list_capacity / 2 > items)
list_capacity /= 2;
else
return;
if(database)
database = xrealloc(database,sizeof(list_item) * list_capacity);
else /* allocate memory _and_ initialize pointers to NULL */
database = xmalloc0(sizeof(list_item) * list_capacity);
selected = xrealloc(selected, list_capacity);
}
int
add_item2database(list_item item)
{
/* 'name' field is mandatory */
if((item[field_id(NAME)] == NULL) || ! *item[field_id(NAME)]) {
item_empty(item);
return 1;
}
if(++items > list_capacity)
adjust_list_capacity();
validate_item(item);
selected[LAST_ITEM] = 0;
database[LAST_ITEM] = item_create();
item_copy(database[LAST_ITEM], item);
return 0;
}
void
remove_selected_items()
{
int i, j;
if(list_is_empty())
return;
if(!selected_items())
selected[curitem] = 1;
for(j = LAST_ITEM; j >= 0; j--) {
if(selected[j]) {
db_free_item(j); /* added for .4 data_s_ */
for(i = j; i < LAST_ITEM; i++) {
item_copy(database[i], database[i + 1]);
selected[i] = selected[i + 1];
}
item_free(&database[LAST_ITEM]);
items--;
}
}
if(curitem > LAST_ITEM && items > 0)
curitem = LAST_ITEM;
adjust_list_capacity();
select_none();
}
void merge_selected_items()
{
int i, j;
int destitem = -1;
if((list_is_empty()) || (selected_items() < 2))
return;
/* Find the top item */
for(j=0; destitem < 0; j++)
if(selected[j])
destitem = j;
/* Merge pairwise */
for(j = LAST_ITEM; j > destitem; j--) {
if(selected[j]) {
item_merge(database[destitem],database[j]);
for(i = j; i < LAST_ITEM; i++) {
/* TODO: this can be done by moving pointers */
item_copy(database[i], database[i + 1]);
selected[i] = selected[i + 1];
}
item_free(&database[LAST_ITEM]);
items--;
}
}
if(curitem > LAST_ITEM && items > 0)
curitem = LAST_ITEM;
adjust_list_capacity();
select_none();
}
void remove_duplicates()
{
int i,j,k;
char *tmpj;
if(list_is_empty())
return;
/* Scan from the last one */
for(j = LAST_ITEM - 1; j >= 0; j--) {
tmpj = db_name_get(j);
for(i = LAST_ITEM; i > j; i--)
/* Check name and merge if dups */
if (0 == strcmp(tmpj,db_name_get(i))) {
item_merge(database[j],database[i]);
if (curitem == i) curitem--;
for(k = i; k < LAST_ITEM; k++) {
item_copy(database[k], database[k + 1]);
}
item_free(&database[LAST_ITEM]);
items--;
}
}
adjust_list_capacity();
}
char *
get_surname(char *s)
{
char *p = s + strlen(s);
assert(s != NULL);
while(p > s && *(p - 1) != ' ')
p--;
return xstrdup(p);
}
static int
surnamecmp(const void *i1, const void *i2)
{
int ret, idx = field_id(NAME);
char *n1, *n2, *s1, *s2;
n1 = (*(list_item *)i1)[idx];
n2 = (*(list_item *)i2)[idx];
s1 = get_surname(n1);
s2 = get_surname(n2);
if( !(ret = safe_strcoll(s1, s2)) )
ret = safe_strcoll(n1, n2);
free(s1);
free(s2);
return ret;
}
static int sort_field = -1;
static int
namecmp(const void *i1, const void *i2)
{
char *n1, *n2;
assert(sort_field >= 0 && sort_field < fields_count);
n1 = (*(list_item *)i1)[sort_field];
n2 = (*(list_item *)i2)[sort_field];
return safe_strcoll(n1, n2);
}
void
sort_by_field(char *name)
{
int field;
select_none();
name = (name == NULL) ? opt_get_str(STR_SORT_FIELD) : name;
find_field_number(name, &field);
if(field < 0) {
if(name == opt_get_str(STR_SORT_FIELD))
statusline_msg(_("Invalid field value defined "
"in configuration"));
else
statusline_msg(_("Invalid field value for sorting"));
return;
}
sort_field = field;
qsort((void *)database, items, sizeof(list_item), namecmp);
refresh_screen();
}
void
sort_surname()
{
select_none();
qsort((void *)database, items, sizeof(list_item), surnamecmp);
refresh_screen();
}
/* TODO implement a search based on more sophisticated patterns */
int
find_item(char *str, int start, int search_fields[])
{
int i, id;
char *findstr = NULL;
char *tmp = NULL;
int ret = -1; /* not found */
struct db_enumerator e = init_db_enumerator(ENUM_ALL);
if(list_is_empty() || !is_valid_item(start))
return -2; /* error */
findstr = xstrdup(str);
findstr = strlower(findstr);
e.item = start - 1; /* must be "real start" - 1 */
db_enumerate_items(e) {
for(i = 0; search_fields[i] >= 0; i++) {
if((id = field_id(search_fields[i])) == -1)
continue;
if(database[e.item][id] == NULL)
continue;
tmp = xstrdup(database[e.item][id]);
if( tmp && strstr(strlower(tmp), findstr) ) {
ret = e.item;
goto out;
}
xfree(tmp);
}
}
out:
free(findstr);
free(tmp);
return ret;
}
int
is_selected(int item)
{
return selected[item];
}
int
is_valid_item(int item)
{
return item <= LAST_ITEM && item >= 0;
}
int
last_item()
{
return LAST_ITEM;
}
int
db_n_items()
{
return items;
}
int
real_db_enumerate_items(struct db_enumerator e)
{
int item = max(0, e.item + 1);
int i;
switch(e.mode) {
#ifdef DEBUG
case ENUM_ALL:
break;
#endif
case ENUM_SELECTED:
for(i = item; i <= LAST_ITEM; i++) {
if(is_selected(i)) {
item = i;
goto out;
}
}
return -1;
#ifdef DEBUG
default:
fprintf(stderr, "real_db_enumerate_items() "
"BUG: unknown db_enumerator mode: %d\n",
e.mode);
break;
#endif
}
out:
return (item > LAST_ITEM || item < 0) ? -1 : item;
}
struct db_enumerator
init_db_enumerator(int mode)
{
struct db_enumerator e;
e.item = -1; /* important - means "start from beginning" */
e.mode = mode;
return e;
}
list_item
item_create()
{
return xmalloc0(ITEM_SIZE);
}
void
item_free(list_item *item)
{
assert(item);
xfree(*item);
}
void
item_empty(list_item item)
{ int i;
assert(item);
for(i = 0; i < fields_count; i++)
if(item[i])
xfree(item[i]);
}
void
item_copy(list_item dest, list_item src)
{
memmove(dest, src, ITEM_SIZE);
}
void
item_duplicate(list_item dest, list_item src)
{
int i;
for(i = 0; i < fields_count; i++)
dest[i] = src[i] ? xstrdup(src[i]) : NULL;
}
/*
* Merging works as follows:
* - fields present only in source are copied over to dest
* - multi-fields (email, groups) are checked for dupes ad merged
* */
void
item_merge(list_item dest, list_item src)
{
int i, found = 0;
abook_list *dfield, *sfield, *ed, *es;
for(i = 0; i < fields_count; i++)
if (src[i]) {
if (!dest[i])
dest[i] = xstrdup(src[i]);
else if((i == field_id(EMAIL)) || (i == field_id(GROUPS))) {
dfield = csv_to_abook_list(dest[i]);
sfield = csv_to_abook_list(src[i]);
for(es = sfield; es; es = es->next) {
for(found=0, ed = dfield; (!found) && ed; ed = ed->next)
found = (0 == strcmp(es->data,ed->data));
if (!found)
abook_list_append(&dfield, es->data);
}
xfree(dest[i]);
dest[i] = abook_list_to_csv(dfield);
abook_list_free(&dfield);
abook_list_free(&sfield);
}
}
item_empty(src);
}
/*
* Things like item[field_id(NICK)] should never be used, since besides NAME
* and EMAIL, none of the standard fields can be assumed to be existing.
*
* Prefer the functions item_fput(), item_fget(), db_fput() and db_fget()
* to access fields in items and database.
*/
/* quick lookup by "standard" field number */
inline int
field_id(int i)
{
assert((i >= 0) && (i < ITEM_FIELDS));
return standard_fields_indexed[i];
}
int
item_fput(list_item item, int i, char *val)
{
int id = field_id(i);
if(id != -1) {
item[id] = val;
return 1;
}
return 0;
}
char *
item_fget(list_item item, int i)
{
int id = field_id(i);
if(id != -1)
return item[id];
else
return NULL;
}
int
real_db_field_put(int item, int i, int std, char *val)
{
int id;
assert(database[item]);
id = std ? field_id(i) : i;
if(id != -1) {
database[item][id] = val;
return 1;
}
return 0;
}
char *
real_db_field_get(int item, int i, int std)
{
int id;
assert(database[item]);
id = std ? field_id(i) : i;
if(id != -1)
return database[item][id];
else
return NULL;
}
list_item
db_item_get(int i)
{
return database[i];
}
/* Fetch addresses from all fields of FIELD_EMAILS type */
/* Memory has to be freed by the caller */
char *
db_email_get(int item)
{
int i;
char *res;
abook_field_list *cur;
abook_list *emails = NULL;
for(cur = fields_list, i = 0; cur; cur = cur->next, i++)
if(cur->field->type == FIELD_EMAILS && *database[item][i])
abook_list_append(&emails, database[item][i]);
res = abook_list_to_csv(emails);
abook_list_free(&emails);
return res ? res : xstrdup("");
}