0.7.2claws release
[claws.git] / src / jpilot.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2001-2002 Match Grun
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Functions necessary to access JPilot database files.
22  * JPilot is Copyright(c) by Judd Montgomery.
23  * Visit http://www.jpilot.org for more details.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #ifdef USE_JPILOT
31
32 #include <glib.h>
33 #include <time.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <sys/stat.h>
38 #include <netinet/in.h>
39
40 #ifdef HAVE_LIBPISOCK_PI_ARGS_H
41 #  include <libpisock/pi-args.h>
42 #  include <libpisock/pi-appinfo.h>
43 #  include <libpisock/pi-address.h>
44 #else
45 #  include <pi-args.h>
46 #  include <pi-appinfo.h>
47 #  include <pi-address.h>
48 #endif
49
50 #include "mgutils.h"
51 #include "addritem.h"
52 #include "addrcache.h"
53 #include "jpilot.h"
54 #include "adbookbase.h"
55
56 #define JPILOT_DBHOME_DIR   ".jpilot"
57 #define JPILOT_DBHOME_FILE  "AddressDB.pdb"
58 #define PILOT_LINK_LIB_NAME "libpisock.so"
59
60 #define IND_LABEL_LASTNAME  0   /* Index of last name in address data */
61 #define IND_LABEL_FIRSTNAME 1   /* Index of first name in address data */
62 #define IND_PHONE_EMAIL     4   /* Index of E-Mail address in phone labels */
63 #define OFFSET_PHONE_LABEL  3   /* Offset to phone data in address data */
64 #define IND_CUSTOM_LABEL    14  /* Offset to custom label names */
65 #define NUM_CUSTOM_LABEL    4   /* Number of custom labels */
66
67 /* Shamelessly copied from JPilot (libplugin.h) */
68 typedef struct {
69         unsigned char db_name[32];
70         unsigned char flags[2];
71         unsigned char version[2];
72         unsigned char creation_time[4];
73         unsigned char modification_time[4];
74         unsigned char backup_time[4];
75         unsigned char modification_number[4];
76         unsigned char app_info_offset[4];
77         unsigned char sort_info_offset[4];
78         unsigned char type[4];/*Database ID */
79         unsigned char creator_id[4];/*Application ID */
80         unsigned char unique_id_seed[4];
81         unsigned char next_record_list_id[4];
82         unsigned char number_of_records[2];
83 } RawDBHeader;
84
85 /* Shamelessly copied from JPilot (libplugin.h) */
86 typedef struct {
87         char db_name[32];
88         unsigned int flags;
89         unsigned int version;
90         time_t creation_time;
91         time_t modification_time;
92         time_t backup_time;
93         unsigned int modification_number;
94         unsigned int app_info_offset;
95         unsigned int sort_info_offset;
96         char type[5];/*Database ID */
97         char creator_id[5];/*Application ID */
98         char unique_id_seed[5];
99         unsigned int next_record_list_id;
100         unsigned int number_of_records;
101 } DBHeader;
102
103 /* Shamelessly copied from JPilot (libplugin.h) */
104 typedef struct {
105         unsigned char Offset[4];  /*4 bytes offset from BOF to record */
106         unsigned char attrib;
107         unsigned char unique_ID[3];
108 } record_header;
109
110 /* Shamelessly copied from JPilot (libplugin.h) */
111 typedef struct mem_rec_header_s {
112         unsigned int rec_num;
113         unsigned int offset;
114         unsigned int unique_id;
115         unsigned char attrib;
116         struct mem_rec_header_s *next;
117 } mem_rec_header;
118
119 /* Shamelessly copied from JPilot (libplugin.h) */
120 #define SPENT_PC_RECORD_BIT     256
121
122 typedef enum {
123         PALM_REC = 100L,
124         MODIFIED_PALM_REC = 101L,
125         DELETED_PALM_REC = 102L,
126         NEW_PC_REC = 103L,
127         DELETED_PC_REC = SPENT_PC_RECORD_BIT + 104L,
128         DELETED_DELETED_PALM_REC = SPENT_PC_RECORD_BIT + 105L
129 } PCRecType;
130
131 /* Shamelessly copied from JPilot (libplugin.h) */
132 typedef struct {
133         PCRecType rt;
134         unsigned int unique_id;
135         unsigned char attrib;
136         void *buf;
137         int size;
138 } buf_rec;
139
140 /* Shamelessly copied from JPilot (libplugin.h) */
141 typedef struct {
142         unsigned long header_len;
143         unsigned long header_version;
144         unsigned long rec_len;
145         unsigned long unique_id;
146         unsigned long rt; /* Record Type */
147         unsigned char attrib;
148 } PC3RecordHeader;
149
150 /*
151 * Create new pilot file object.
152 */
153 JPilotFile *jpilot_create() {
154         JPilotFile *pilotFile;
155         pilotFile = g_new0( JPilotFile, 1 );
156         pilotFile->type = ADBOOKTYPE_JPILOT;
157         pilotFile->addressCache = addrcache_create();
158         pilotFile->accessFlag = FALSE;
159         pilotFile->retVal = MGU_SUCCESS;
160
161         pilotFile->file = NULL;
162         pilotFile->path = NULL;
163         pilotFile->readMetadata = FALSE;
164         pilotFile->customLabels = NULL;
165         pilotFile->labelInd = NULL;
166         pilotFile->havePC3 = FALSE;
167         pilotFile->pc3ModifyTime = 0;
168         return pilotFile;
169 }
170
171 /*
172 * Create new pilot file object for specified file.
173 */
174 JPilotFile *jpilot_create_path( const gchar *path ) {
175         JPilotFile *pilotFile;
176         pilotFile = jpilot_create();
177         jpilot_set_file( pilotFile, path );
178         return pilotFile;
179 }
180
181 /*
182 * Properties...
183 */
184 void jpilot_set_name( JPilotFile* pilotFile, const gchar *value ) {
185         g_return_if_fail( pilotFile != NULL );
186         addrcache_set_name( pilotFile->addressCache, value );
187 }
188 void jpilot_set_file( JPilotFile* pilotFile, const gchar *value ) {
189         g_return_if_fail( pilotFile != NULL );
190         addrcache_refresh( pilotFile->addressCache );
191         pilotFile->readMetadata = FALSE;
192         pilotFile->path = mgu_replace_string( pilotFile->path, value );
193 }
194 void jpilot_set_accessed( JPilotFile *pilotFile, const gboolean value ) {
195         g_return_if_fail( pilotFile != NULL );
196         pilotFile->accessFlag = value;
197 }
198
199 gint jpilot_get_status( JPilotFile *pilotFile ) {
200         g_return_val_if_fail( pilotFile != NULL, -1 );
201         return pilotFile->retVal;
202 }
203 ItemFolder *jpilot_get_root_folder( JPilotFile *pilotFile ) {
204         g_return_val_if_fail( pilotFile != NULL, NULL );
205         return addrcache_get_root_folder( pilotFile->addressCache );
206 }
207 gchar *jpilot_get_name( JPilotFile *pilotFile ) {
208         g_return_val_if_fail( pilotFile != NULL, NULL );
209         return addrcache_get_name( pilotFile->addressCache );
210 }
211
212 /*
213 * Test whether file was read.
214 * Return: TRUE if file was read.
215 */
216 gboolean jpilot_get_read_flag( JPilotFile *pilotFile ) {
217         g_return_val_if_fail( pilotFile != NULL, FALSE );
218         return pilotFile->addressCache->dataRead;
219 }
220
221 /*
222 * Free up custom label list.
223 */
224 void jpilot_clear_custom_labels( JPilotFile *pilotFile ) {
225         GList *node;
226
227         g_return_if_fail( pilotFile != NULL );
228
229         /* Release custom labels */
230         mgu_free_dlist( pilotFile->customLabels );
231         pilotFile->customLabels = NULL;
232
233         /* Release indexes */
234         node = pilotFile->labelInd;
235         while( node ) {
236                 node->data = NULL;
237                 node = g_list_next( node );
238         }
239         g_list_free( pilotFile->labelInd );
240         pilotFile->labelInd = NULL;
241
242         /* Force a fresh read */
243         addrcache_refresh( pilotFile->addressCache );
244 }
245
246 /*
247 * Append a custom label, representing an E-Mail address field to the
248 * custom label list.
249 */
250 void jpilot_add_custom_label( JPilotFile *pilotFile, const gchar *labelName ) {
251         g_return_if_fail( pilotFile != NULL );
252
253         if( labelName ) {
254                 gchar *labelCopy = g_strdup( labelName );
255                 g_strstrip( labelCopy );
256                 if( *labelCopy == '\0' ) {
257                         g_free( labelCopy );
258                 }
259                 else {
260                         pilotFile->customLabels = g_list_append( pilotFile->customLabels, labelCopy );
261                         /* Force a fresh read */
262                         addrcache_refresh( pilotFile->addressCache );
263                 }
264         }
265 }
266
267 /*
268 * Get list of custom labels.
269 * Return: List of labels. Must use g_free() when done.
270 */
271 GList *jpilot_get_custom_labels( JPilotFile *pilotFile ) {
272         GList *retVal = NULL;
273         GList *node;
274
275         g_return_val_if_fail( pilotFile != NULL, NULL );
276
277         node = pilotFile->customLabels;
278         while( node ) {
279                 retVal = g_list_append( retVal, g_strdup( node->data ) );
280                 node = g_list_next( node );
281         }
282         return retVal;
283 }
284
285 /*
286 * Return filespec of PC3 file corresponding to JPilot PDB file.
287 * Note: Filespec should be g_free() when done.
288 */
289 static gchar *jpilot_get_pc3_file( JPilotFile *pilotFile ) {
290         gchar *fileSpec, *r;
291         gint i, len, pos;
292
293         if( pilotFile == NULL ) return NULL;
294         if( pilotFile->path == NULL ) return NULL;
295
296         fileSpec = g_strdup( pilotFile->path );
297         len = strlen( fileSpec );
298         pos = -1;
299         r = NULL;
300         for( i = len; i > 0; i-- ) {
301                 if( *(fileSpec + i) == '.' ) {
302                         pos = i + 1;
303                         r = fileSpec + pos;
304                         break;
305                 }
306         }
307         if( r ) {
308                 if( len - pos == 3 ) {
309                         *r++ = 'p'; *r++ = 'c'; *r = '3';
310                         return fileSpec;
311                 }
312         }
313         g_free( fileSpec );
314         return NULL;
315 }
316
317 /*
318 * Save PC3 file time to cache.
319 * return: TRUE if time marked.
320 */
321 static gboolean jpilot_mark_files( JPilotFile *pilotFile ) {
322         gboolean retVal = FALSE;
323         struct stat filestat;
324         gchar *pcFile;
325
326         /* Mark PDB file cache */
327         retVal = addrcache_mark_file( pilotFile->addressCache, pilotFile->path );
328
329         /* Now mark PC3 file */
330         pilotFile->havePC3 = FALSE;
331         pilotFile->pc3ModifyTime = 0;
332         pcFile = jpilot_get_pc3_file( pilotFile );
333         if( pcFile == NULL ) return retVal;
334         if( 0 == lstat( pcFile, &filestat ) ) {
335                 pilotFile->havePC3 = TRUE;
336                 pilotFile->pc3ModifyTime = filestat.st_mtime;
337                 retVal = TRUE;
338         }
339         g_free( pcFile );
340         return retVal;
341 }
342
343 /*
344 * Check whether JPilot PDB or PC3 file has changed by comparing
345 * with cached data.
346 * return: TRUE if file has changed.
347 */
348 static gboolean jpilot_check_files( JPilotFile *pilotFile ) {
349         gboolean retVal = TRUE;
350         struct stat filestat;
351         gchar *pcFile;
352
353         /* Check main file */
354         if( addrcache_check_file( pilotFile->addressCache, pilotFile->path ) )
355                 return TRUE;
356
357         /* Test PC3 file */
358         if( ! pilotFile->havePC3 ) return FALSE;
359         pcFile = jpilot_get_pc3_file( pilotFile );
360         if( pcFile == NULL ) return FALSE;
361
362         if( 0 == lstat( pcFile, &filestat ) ) {
363                 if( filestat.st_mtime == pilotFile->pc3ModifyTime ) retVal = FALSE;
364         }
365         g_free( pcFile );
366         return retVal;
367 }
368
369 /*
370 * Test whether file was modified since last access.
371 * Return: TRUE if file was modified.
372 */
373 gboolean jpilot_get_modified( JPilotFile *pilotFile ) {
374         g_return_val_if_fail( pilotFile != NULL, FALSE );
375         return jpilot_check_files( pilotFile );
376 }
377 gboolean jpilot_get_accessed( JPilotFile *pilotFile ) {
378         g_return_val_if_fail( pilotFile != NULL, FALSE );
379         return pilotFile->accessFlag;
380 }
381
382 /*
383 * Free up pilot file object by releasing internal memory.
384 */
385 void jpilot_free( JPilotFile *pilotFile ) {
386         g_return_if_fail( pilotFile != NULL );
387
388         /* Release custom labels */
389         jpilot_clear_custom_labels( pilotFile );
390
391         /* Clear cache */
392         addrcache_clear( pilotFile->addressCache );
393         addrcache_free( pilotFile->addressCache );
394
395         /* Free internal stuff */
396         g_free( pilotFile->path );
397
398         pilotFile->file = NULL;
399         pilotFile->path = NULL;
400         pilotFile->readMetadata = FALSE;
401         pilotFile->havePC3 = FALSE;
402         pilotFile->pc3ModifyTime = 0;
403
404         pilotFile->type = ADBOOKTYPE_NONE;
405         pilotFile->addressCache = NULL;
406         pilotFile->accessFlag = FALSE;
407         pilotFile->retVal = MGU_SUCCESS;
408
409         /* Now release file object */
410         g_free( pilotFile );
411 }
412
413 /*
414 * Refresh internal variables to force a file read.
415 */
416 void jpilot_force_refresh( JPilotFile *pilotFile ) {
417         addrcache_refresh( pilotFile->addressCache );
418 }
419
420 /*
421 * Print object to specified stream.
422 */
423 void jpilot_print_file( JPilotFile *pilotFile, FILE *stream ) {
424         GList *node;
425
426         g_return_if_fail( pilotFile != NULL );
427
428         fprintf( stream, "JPilotFile:\n" );
429         fprintf( stream, "file spec: '%s'\n", pilotFile->path );
430         fprintf( stream, " metadata: %s\n", pilotFile->readMetadata ? "yes" : "no" );
431         fprintf( stream, "  ret val: %d\n", pilotFile->retVal );
432
433         node = pilotFile->customLabels;
434         while( node ) {
435                 fprintf( stream, "  c label: %s\n", (gchar *)node->data );
436                 node = g_list_next( node );
437         }
438
439         node = pilotFile->labelInd;
440         while( node ) {
441                 fprintf( stream, " labelind: %d\n", GPOINTER_TO_INT(node->data) );
442                 node = g_list_next( node );
443         }
444
445         addrcache_print( pilotFile->addressCache, stream );
446         fprintf( stream, "  ret val: %d\n", pilotFile->retVal );
447         fprintf( stream, " have pc3: %s\n", pilotFile->havePC3 ? "yes" : "no" );
448         fprintf( stream, " pc3 time: %lu\n", pilotFile->pc3ModifyTime );
449         addritem_print_item_folder( pilotFile->addressCache->rootFolder, stream );
450 }
451
452 /*
453 * Print summary of object to specified stream.
454 */
455 void jpilot_print_short( JPilotFile *pilotFile, FILE *stream ) {
456         GList *node;
457         g_return_if_fail( pilotFile != NULL );
458         fprintf( stream, "JPilotFile:\n" );
459         fprintf( stream, "file spec: '%s'\n", pilotFile->path );
460         fprintf( stream, " metadata: %s\n", pilotFile->readMetadata ? "yes" : "no" );
461         fprintf( stream, "  ret val: %d\n", pilotFile->retVal );
462
463         node = pilotFile->customLabels;
464         while( node ) {
465                 fprintf( stream, "  c label: %s\n", (gchar *)node->data );
466                 node = g_list_next( node );
467         }
468
469         node = pilotFile->labelInd;
470         while( node ) {
471                 fprintf( stream, " labelind: %d\n", GPOINTER_TO_INT(node->data) );
472                 node = g_list_next( node );
473         }
474         addrcache_print( pilotFile->addressCache, stream );
475         fprintf( stream, " have pc3: %s\n", pilotFile->havePC3 ? "yes" : "no" );
476         fprintf( stream, " pc3 time: %lu\n", pilotFile->pc3ModifyTime );
477 }
478
479 /* Shamelessly copied from JPilot (libplugin.c) */
480 static unsigned int bytes_to_bin(unsigned char *bytes, unsigned int num_bytes) {
481 unsigned int i, n;
482         n=0;
483         for (i=0;i<num_bytes;i++) {
484                 n = n*256+bytes[i];
485         }
486         return n;
487 }
488
489 /* Shamelessly copied from JPilot (utils.c) */
490 /* These next 2 functions were copied from pi-file.c in the pilot-link app */
491 /* Exact value of "Jan 1, 1970 0:00:00 GMT" - "Jan 1, 1904 0:00:00 GMT" */
492 #define PILOT_TIME_DELTA (unsigned)(2082844800)
493
494 time_t pilot_time_to_unix_time ( unsigned long raw_time ) {
495    return (time_t)(raw_time - PILOT_TIME_DELTA);
496 }
497
498 /* Shamelessly copied from JPilot (libplugin.c) */
499 static int raw_header_to_header(RawDBHeader *rdbh, DBHeader *dbh) {
500         unsigned long temp;
501
502         strncpy(dbh->db_name, rdbh->db_name, 31);
503         dbh->db_name[31] = '\0';
504         dbh->flags = bytes_to_bin(rdbh->flags, 2);
505         dbh->version = bytes_to_bin(rdbh->version, 2);
506         temp = bytes_to_bin(rdbh->creation_time, 4);
507         dbh->creation_time = pilot_time_to_unix_time(temp);
508         temp = bytes_to_bin(rdbh->modification_time, 4);
509         dbh->modification_time = pilot_time_to_unix_time(temp);
510         temp = bytes_to_bin(rdbh->backup_time, 4);
511         dbh->backup_time = pilot_time_to_unix_time(temp);
512         dbh->modification_number = bytes_to_bin(rdbh->modification_number, 4);
513         dbh->app_info_offset = bytes_to_bin(rdbh->app_info_offset, 4);
514         dbh->sort_info_offset = bytes_to_bin(rdbh->sort_info_offset, 4);
515         strncpy(dbh->type, rdbh->type, 4);
516         dbh->type[4] = '\0';
517         strncpy(dbh->creator_id, rdbh->creator_id, 4);
518         dbh->creator_id[4] = '\0';
519         strncpy(dbh->unique_id_seed, rdbh->unique_id_seed, 4);
520         dbh->unique_id_seed[4] = '\0';
521         dbh->next_record_list_id = bytes_to_bin(rdbh->next_record_list_id, 4);
522         dbh->number_of_records = bytes_to_bin(rdbh->number_of_records, 2);
523         return 0;
524 }
525
526 /* Shamelessly copied from JPilot (libplugin.c) */
527 /* returns 1 if found */
528 /*         0 if eof */
529 static int find_next_offset( mem_rec_header *mem_rh, long fpos,
530         unsigned int *next_offset, unsigned char *attrib, unsigned int *unique_id )
531 {
532         mem_rec_header *temp_mem_rh;
533         unsigned char found = 0;
534         unsigned long found_at;
535
536         found_at=0xFFFFFF;
537         for (temp_mem_rh=mem_rh; temp_mem_rh; temp_mem_rh = temp_mem_rh->next) {
538                 if ((temp_mem_rh->offset > fpos) && (temp_mem_rh->offset < found_at)) {
539                         found_at = temp_mem_rh->offset;
540                         /* *attrib = temp_mem_rh->attrib; */
541                         /* *unique_id = temp_mem_rh->unique_id; */
542                 }
543                 if ((temp_mem_rh->offset == fpos)) {
544                         found = 1;
545                         *attrib = temp_mem_rh->attrib;
546                         *unique_id = temp_mem_rh->unique_id;
547                 }
548         }
549         *next_offset = found_at;
550         return found;
551 }
552
553 /* Shamelessly copied from JPilot (libplugin.c) */
554 static void free_mem_rec_header(mem_rec_header **mem_rh) {
555         mem_rec_header *h, *next_h;
556         for (h=*mem_rh; h; h=next_h) {
557                 next_h=h->next;
558                 free(h);
559         }
560         *mem_rh = NULL;
561 }
562
563 /* Shamelessly copied from JPilot (libplugin.c) */
564 static int jpilot_free_db_list( GList **br_list ) {
565         GList *temp_list, *first;
566         buf_rec *br;
567
568         /* Go to first entry in the list */
569         first=NULL;
570         for( temp_list = *br_list; temp_list; temp_list = temp_list->prev ) {
571                 first = temp_list;
572         }
573         for (temp_list = first; temp_list; temp_list = temp_list->next) {
574                 if (temp_list->data) {
575                         br=temp_list->data;
576                         if (br->buf) {
577                                 free(br->buf);
578                                 temp_list->data=NULL;
579                         }
580                         free(br);
581                 }
582         }
583         g_list_free(*br_list);
584         *br_list=NULL;
585         return 0;
586 }
587
588 /* Shamelessly copied from JPilot (libplugin.c) */
589 /* Read file size */
590 static int jpilot_get_info_size( FILE *in, int *size ) {
591         RawDBHeader rdbh;
592         DBHeader dbh;
593         unsigned int offset;
594         record_header rh;
595
596         fseek(in, 0, SEEK_SET);
597         fread(&rdbh, sizeof(RawDBHeader), 1, in);
598         if (feof(in)) {
599                 return MGU_EOF;
600         }
601
602         raw_header_to_header(&rdbh, &dbh);
603         if (dbh.app_info_offset==0) {
604                 *size=0;
605                 return MGU_SUCCESS;
606         }
607         if (dbh.sort_info_offset!=0) {
608                 *size = dbh.sort_info_offset - dbh.app_info_offset;
609                 return MGU_SUCCESS;
610         }
611         if (dbh.number_of_records==0) {
612                 fseek(in, 0, SEEK_END);
613                 *size=ftell(in) - dbh.app_info_offset;
614                 return MGU_SUCCESS;
615         }
616
617         fread(&rh, sizeof(record_header), 1, in);
618         offset = ((rh.Offset[0]*256+rh.Offset[1])*256+rh.Offset[2])*256+rh.Offset[3];
619         *size=offset - dbh.app_info_offset;
620
621         return MGU_SUCCESS;
622 }
623
624 /*
625  * Read address file into address list. Based on JPilot's
626  * libplugin.c (jp_get_app_info)
627  */
628 static gint jpilot_get_file_info( JPilotFile *pilotFile, unsigned char **buf, int *buf_size ) {
629         FILE *in;
630         int num;
631         unsigned int rec_size;
632         RawDBHeader rdbh;
633         DBHeader dbh;
634
635         if( ( !buf_size ) || ( ! buf ) ) {
636                 return MGU_BAD_ARGS;
637         }
638
639         *buf = NULL;
640         *buf_size=0;
641
642         if( pilotFile->path ) {
643                 in = fopen( pilotFile->path, "r" );
644                 if( !in ) {
645                         return MGU_OPEN_FILE;
646                 }
647         }
648         else {
649                 return MGU_NO_FILE;
650         }
651
652         num = fread( &rdbh, sizeof( RawDBHeader ), 1, in );
653         if( num != 1 ) {
654                 if( ferror(in) ) {
655                         fclose(in);
656                         return MGU_ERROR_READ;
657                 }
658         }
659         if (feof(in)) {
660                 fclose(in);
661                 return MGU_EOF;
662         }
663
664         /* Convert header into something recognizable */
665         raw_header_to_header(&rdbh, &dbh);
666
667         num = jpilot_get_info_size(in, &rec_size);
668         if (num) {
669                 fclose(in);
670                 return MGU_ERROR_READ;
671         }
672
673         fseek(in, dbh.app_info_offset, SEEK_SET);
674         *buf = ( char * ) malloc(rec_size);
675         if (!(*buf)) {
676                 fclose(in);
677                 return MGU_OO_MEMORY;
678         }
679         num = fread(*buf, rec_size, 1, in);
680         if (num != 1) {
681                 if (ferror(in)) {
682                         fclose(in);
683                         free(*buf);
684                         return MGU_ERROR_READ;
685                 }
686         }
687         fclose(in);
688
689         *buf_size = rec_size;
690
691         return MGU_SUCCESS;
692 }
693
694 /* Shamelessly copied from JPilot (libplugin.c) */
695 static int unpack_header(PC3RecordHeader *header, unsigned char *packed_header) {
696         unsigned char *p;
697         unsigned long l;
698
699         p = packed_header;
700
701         memcpy(&l, p, sizeof(l));
702         header->header_len=ntohl(l);
703         p+=sizeof(l);
704
705         memcpy(&l, p, sizeof(l));
706         header->header_version=ntohl(l);
707         p+=sizeof(l);
708
709         memcpy(&l, p, sizeof(l));
710         header->rec_len=ntohl(l);
711         p+=sizeof(l);
712
713         memcpy(&l, p, sizeof(l));
714         header->unique_id=ntohl(l);
715         p+=sizeof(l);
716
717         memcpy(&l, p, sizeof(l));
718         header->rt=ntohl(l);
719         p+=sizeof(l);
720
721         memcpy(&(header->attrib), p, sizeof(unsigned char));
722         p+=sizeof(unsigned char);
723
724         return 0;
725 }
726
727 /* Shamelessly copied from JPilot (libplugin.c) */
728 static int read_header(FILE *pc_in, PC3RecordHeader *header) {
729         unsigned long l, len;
730         unsigned char packed_header[256];
731         int num;
732
733         num = fread(&l, sizeof(l), 1, pc_in);
734         if (feof(pc_in)) {
735                 return -1;
736         }
737         if (num!=1) {
738                 return num;
739         }
740         memcpy(packed_header, &l, sizeof(l));
741         len=ntohl(l);
742         if (len > 255) {
743                 return -1;
744         }
745         num = fread(packed_header+sizeof(l), len-sizeof(l), 1, pc_in);
746         if (feof(pc_in)) {
747                 return -1;
748         }
749         if (num!=1) {
750                 return num;
751         }
752         unpack_header(header, packed_header);
753         return 1;
754 }
755
756 /* Read next record from PC3 file. Based on JPilot's
757  * pc_read_next_rec (libplugin.c) */
758 static gint jpilot_read_next_pc( FILE *in, buf_rec *br ) {
759         PC3RecordHeader header;
760         int rec_len, num;
761         char *record;
762
763         if(feof(in)) {
764                 return MGU_EOF;
765         }
766         num = read_header(in, &header);
767         if (num < 1) {
768                 if (ferror(in)) {
769                         return MGU_ERROR_READ;
770                 }
771                 if (feof(in)) {
772                         return MGU_EOF;
773                 }
774         }
775         rec_len = header.rec_len;
776         record = malloc(rec_len);
777         if (!record) {
778                 return MGU_OO_MEMORY;
779         }
780         num = fread(record, rec_len, 1, in);
781         if (num != 1) {
782                 if (ferror(in)) {
783                         free(record);
784                         return MGU_ERROR_READ;
785                 }
786         }
787         br->rt = header.rt;
788         br->unique_id = header.unique_id;
789         br->attrib = header.attrib;
790         br->buf = record;
791         br->size = rec_len;
792
793         return MGU_SUCCESS;
794 }
795
796 /*
797  * Read address file into a linked list. Based on JPilot's
798  * jp_read_DB_files (from libplugin.c)
799  */
800 static gint jpilot_read_db_files( JPilotFile *pilotFile, GList **records ) {
801         FILE *in, *pc_in;
802         char *buf;
803         GList *temp_list;
804         int num_records, recs_returned, i, num, r;
805         unsigned int offset, prev_offset, next_offset, rec_size;
806         int out_of_order;
807         long fpos;  /*file position indicator */
808         unsigned char attrib;
809         unsigned int unique_id;
810         mem_rec_header *mem_rh, *temp_mem_rh, *last_mem_rh;
811         record_header rh;
812         RawDBHeader rdbh;
813         DBHeader dbh;
814         buf_rec *temp_br;
815         gchar *pcFile;
816
817         mem_rh = last_mem_rh = NULL;
818         *records = NULL;
819         recs_returned = 0;
820
821         if( pilotFile->path == NULL ) {
822                 return MGU_BAD_ARGS;
823         }
824
825         in = fopen( pilotFile->path, "r" );
826         if (!in) {
827                 return MGU_OPEN_FILE;
828         }
829
830         /* Read the database header */
831         num = fread(&rdbh, sizeof(RawDBHeader), 1, in);
832         if (num != 1) {
833                 if (ferror(in)) {
834                         fclose(in);
835                         return MGU_ERROR_READ;
836                 }
837                 if (feof(in)) {
838                         fclose(in);
839                         return MGU_EOF;
840                 }
841         }
842         raw_header_to_header(&rdbh, &dbh);
843
844         /* Read each record entry header */
845         num_records = dbh.number_of_records;
846         out_of_order = 0;
847         prev_offset = 0;
848
849         for (i = 1; i < num_records + 1; i++) {
850                 num = fread(&rh, sizeof(record_header), 1, in);
851                 if (num != 1) {
852                         if (ferror(in)) {
853                                 break;
854                         }
855                         if (feof(in)) {
856                                 fclose(in);
857                                 return MGU_EOF;
858                         }
859                 }
860
861                 offset = ((rh.Offset[0]*256+rh.Offset[1])*256+rh.Offset[2])*256+rh.Offset[3];
862                 if (offset < prev_offset) {
863                         out_of_order = 1;
864                 }
865                 prev_offset = offset;
866                 temp_mem_rh = (mem_rec_header *)malloc(sizeof(mem_rec_header));
867                 if (!temp_mem_rh) {
868                         break;
869                 }
870                 temp_mem_rh->next = NULL;
871                 temp_mem_rh->rec_num = i;
872                 temp_mem_rh->offset = offset;
873                 temp_mem_rh->attrib = rh.attrib;
874                 temp_mem_rh->unique_id = (rh.unique_ID[0]*256+rh.unique_ID[1])*256+rh.unique_ID[2];
875                 if (mem_rh == NULL) {
876                         mem_rh = temp_mem_rh;
877                         last_mem_rh = temp_mem_rh;
878                 } else {
879                         last_mem_rh->next = temp_mem_rh;
880                         last_mem_rh = temp_mem_rh;
881                 }
882         }
883
884         temp_mem_rh = mem_rh;
885
886         if (num_records) {
887                 if (out_of_order) {
888                         find_next_offset(mem_rh, 0, &next_offset, &attrib, &unique_id);
889                 } else {
890                         if (mem_rh) {
891                                 next_offset = mem_rh->offset;
892                                 attrib = mem_rh->attrib;
893                                 unique_id = mem_rh->unique_id;
894                         }
895                 }
896                 fseek(in, next_offset, SEEK_SET);
897                 while(!feof(in)) {
898                         fpos = ftell(in);
899                         if (out_of_order) {
900                                 find_next_offset(mem_rh, fpos, &next_offset, &attrib, &unique_id);
901                         } else {
902                                 next_offset = 0xFFFFFF;
903                                 if (temp_mem_rh) {
904                                         attrib = temp_mem_rh->attrib;
905                                         unique_id = temp_mem_rh->unique_id;
906                                         if (temp_mem_rh->next) {
907                                                 temp_mem_rh = temp_mem_rh->next;
908                                                 next_offset = temp_mem_rh->offset;
909                                         }
910                                 }
911                         }
912                         rec_size = next_offset - fpos;
913                         buf = malloc(rec_size);
914                         if (!buf) break;
915                         num = fread(buf, rec_size, 1, in);
916                         if ((num != 1)) {
917                                 if (ferror(in)) {
918                                         free(buf);
919                                         break;
920                                 }
921                         }
922
923                         temp_br = malloc(sizeof(buf_rec));
924                         if (!temp_br) {
925                                 break;
926                         }
927                         temp_br->rt = PALM_REC;
928                         temp_br->unique_id = unique_id;
929                         temp_br->attrib = attrib;
930                         temp_br->buf = buf;
931                         temp_br->size = rec_size;
932
933                         *records = g_list_append(*records, temp_br);
934
935                         recs_returned++;
936                 }
937         }
938         fclose(in);
939         free_mem_rec_header(&mem_rh);
940
941         /* Read the PC3 file, if present */
942         pcFile = jpilot_get_pc3_file( pilotFile );
943         if( pcFile == NULL ) return MGU_SUCCESS;
944         pc_in = fopen( pcFile, "r");
945         g_free( pcFile );
946
947         if( pc_in == NULL ) {
948                 return MGU_SUCCESS;
949         }
950
951         while( ! feof( pc_in ) ) {
952                 temp_br = malloc(sizeof(buf_rec));
953                 if (!temp_br) {
954                         break;
955                 }
956                 r = jpilot_read_next_pc( pc_in, temp_br );
957                 if ( r != MGU_SUCCESS ) {
958                         free(temp_br);
959                         break;
960                 }
961                 if ((temp_br->rt!=DELETED_PC_REC)
962                         &&(temp_br->rt!=DELETED_PALM_REC)
963                         &&(temp_br->rt!=MODIFIED_PALM_REC)
964                         &&(temp_br->rt!=DELETED_DELETED_PALM_REC)) {
965                                 *records = g_list_append(*records, temp_br);
966                                 recs_returned++;
967                 }
968                 if ((temp_br->rt==DELETED_PALM_REC) || (temp_br->rt==MODIFIED_PALM_REC)) {
969                         temp_list=*records;
970                         if (*records) {
971                                 while(temp_list->next) {
972                                         temp_list=temp_list->next;
973                                 }
974                         }
975                         for (; temp_list; temp_list=temp_list->prev) {
976                                 if (((buf_rec *)temp_list->data)->unique_id == temp_br->unique_id) {
977                                         ((buf_rec *)temp_list->data)->rt = temp_br->rt;
978                                 }
979                         }
980                 }
981         }
982         fclose(pc_in);
983
984         return MGU_SUCCESS;
985 }
986
987 #define FULLNAME_BUFSIZE        256
988 #define EMAIL_BUFSIZE           256
989 /*
990  * Unpack address, building new data inside cache.
991  */
992 static void jpilot_load_address( JPilotFile *pilotFile, buf_rec *buf, ItemFolder *folderInd[] ) {
993         struct Address addr;
994         gchar **addrEnt;
995         gint num, k;
996         gint cat_id = 0;
997         guint unique_id;
998         guchar attrib;
999         gchar fullName[ FULLNAME_BUFSIZE ];
1000         gchar bufEMail[ EMAIL_BUFSIZE ];
1001         ItemPerson *person;
1002         ItemEMail *email;
1003         gint *indPhoneLbl;
1004         gchar *labelEntry;
1005         GList *node;
1006         gchar* extID;
1007         struct AddressAppInfo *ai;
1008
1009         /* Retrieve address */
1010         num = unpack_Address( & addr, buf->buf, buf->size );
1011         if( num > 0 ) {
1012                 addrEnt = addr.entry;
1013                 attrib = buf->attrib;
1014                 unique_id = buf->unique_id;
1015                 cat_id = attrib & 0x0F;
1016
1017                 *fullName = *bufEMail = '\0';
1018                 if( addrEnt[ IND_LABEL_FIRSTNAME ] ) {
1019                         strcat( fullName, addrEnt[ IND_LABEL_FIRSTNAME ] );
1020                 }
1021
1022                 if( addrEnt[ IND_LABEL_LASTNAME ] ) {
1023                         strcat( fullName, " " );
1024                         strcat( fullName, addrEnt[ IND_LABEL_LASTNAME ] );
1025                 }
1026                 g_strchug( fullName );
1027                 g_strchomp( fullName );
1028
1029                 person = addritem_create_item_person();
1030                 addritem_person_set_common_name( person, fullName );
1031                 addritem_person_set_first_name( person, addrEnt[ IND_LABEL_FIRSTNAME ] );
1032                 addritem_person_set_last_name( person, addrEnt[ IND_LABEL_LASTNAME ] );
1033                 addrcache_id_person( pilotFile->addressCache, person );
1034
1035                 extID = g_strdup_printf( "%d", unique_id );
1036                 addritem_person_set_external_id( person, extID );
1037                 g_free( extID );
1038                 extID = NULL;
1039
1040                 /* Pointer to address metadata. */
1041                 ai = & pilotFile->addrInfo;
1042
1043                 /* Add entry for each email address listed under phone labels. */
1044                 indPhoneLbl = addr.phoneLabel;
1045                 for( k = 0; k < JPILOT_NUM_ADDR_PHONE; k++ ) {
1046                         gint ind;
1047                         ind = indPhoneLbl[k];
1048                         /*
1049                         * fprintf( stdout, "%d : %d : %20s : %s\n", k, ind,
1050                         * ai->phoneLabels[ind], addrEnt[3+k] );
1051                         */
1052                         if( indPhoneLbl[k] == IND_PHONE_EMAIL ) {
1053                                 labelEntry = addrEnt[ OFFSET_PHONE_LABEL + k ];
1054                                 if( labelEntry ) {
1055                                         strcpy( bufEMail, labelEntry );
1056                                         g_strchug( bufEMail );
1057                                         g_strchomp( bufEMail );
1058
1059                                         email = addritem_create_item_email();
1060                                         addritem_email_set_address( email, bufEMail );
1061                                         addrcache_id_email( pilotFile->addressCache, email );
1062                                         addrcache_person_add_email
1063                                                 ( pilotFile->addressCache, person, email );
1064                                 }
1065                         }
1066                 }
1067
1068                 /* Add entry for each custom label */
1069                 node = pilotFile->labelInd;
1070                 while( node ) {
1071                         gint ind;
1072                         ind = GPOINTER_TO_INT( node->data );
1073                         if( ind > -1 ) {
1074                                 /*
1075                                 * fprintf( stdout, "%d : %20s : %s\n", ind, ai->labels[ind],
1076                                 * addrEnt[ind] );
1077                                 */
1078                                 labelEntry = addrEnt[ind];
1079                                 if( labelEntry ) {
1080                                         strcpy( bufEMail, labelEntry );
1081                                         g_strchug( bufEMail );
1082                                         g_strchomp( bufEMail );
1083
1084                                         email = addritem_create_item_email();
1085                                         addritem_email_set_address( email, bufEMail );
1086                                         addritem_email_set_remarks( email, ai->labels[ind] );
1087                                         addrcache_id_email( pilotFile->addressCache, email );
1088                                         addrcache_person_add_email
1089                                                 ( pilotFile->addressCache, person, email );
1090                                 }
1091                         }
1092
1093                         node = g_list_next( node );
1094                 }
1095
1096                 if( person->listEMail ) {
1097                         if( cat_id > -1 && cat_id < JPILOT_NUM_CATEG ) {
1098                                 /* Add to specified category */
1099                                 addrcache_folder_add_person
1100                                         ( pilotFile->addressCache, folderInd[cat_id], person );
1101                         } else {
1102                                 /* Add to root folder */
1103                                 addrcache_add_person( pilotFile->addressCache, person );
1104                         }
1105                 } else {
1106                         addritem_free_item_person( person );
1107                         person = NULL;
1108                 }
1109         }
1110 }
1111
1112 /*
1113  * Free up address list.
1114  */
1115 static void jpilot_free_addrlist( GList *records ) {
1116         GList *node;
1117         buf_rec *br;
1118
1119         node = records;
1120         while( node ) {
1121                 br = node->data;
1122                 free( br );
1123                 node->data = NULL;
1124                 node = g_list_next( node );
1125         }
1126
1127         /* Free up list */
1128         g_list_free( records );
1129 }
1130
1131 /*
1132  * Read address file into address cache.
1133  */
1134 static gint jpilot_read_file( JPilotFile *pilotFile ) {
1135         gint retVal, i;
1136         GList *records = NULL;
1137         GList *node;
1138         buf_rec *br;
1139         ItemFolder *folderInd[ JPILOT_NUM_CATEG ];
1140
1141         retVal = jpilot_read_db_files( pilotFile, &records );
1142         if( retVal != MGU_SUCCESS ) {
1143                 jpilot_free_addrlist( records );
1144                 return retVal;
1145         }
1146
1147         /* Build array of pointers to categories */
1148         i = 0;
1149         node = addrcache_get_list_folder( pilotFile->addressCache );
1150         while( node ) {
1151                 if( i < JPILOT_NUM_CATEG ) {
1152                         folderInd[i] = node->data;
1153                 }
1154                 node = g_list_next( node );
1155                 i++;
1156         }
1157
1158         /* Load all addresses, free up old stuff as we go */
1159         node = records;
1160         while( node ) {
1161                 br = node->data;
1162                 if( ( br->rt != DELETED_PC_REC ) &&
1163                     ( br->rt != DELETED_PALM_REC ) &&
1164                     ( br->rt != MODIFIED_PALM_REC ) &&
1165                     ( br->rt != DELETED_DELETED_PALM_REC ) ) {
1166                         jpilot_load_address( pilotFile, br, folderInd );
1167                 }
1168                 free( br );
1169                 node->data = NULL;
1170                 node = g_list_next( node );
1171         }
1172
1173         /* Free up list */
1174         g_list_free( records );
1175
1176         return retVal;
1177 }
1178
1179
1180 /*
1181 * Read metadata from file.
1182 */
1183 static gint jpilot_read_metadata( JPilotFile *pilotFile ) {
1184         gint retVal;
1185         unsigned int rec_size;
1186         unsigned char *buf;
1187         int num;
1188
1189         g_return_val_if_fail( pilotFile != NULL, -1 );
1190
1191         pilotFile->readMetadata = FALSE;
1192         addrcache_clear( pilotFile->addressCache );
1193
1194         /* Read file info */
1195         retVal = jpilot_get_file_info( pilotFile, &buf, &rec_size);
1196         if( retVal != MGU_SUCCESS ) {
1197                 pilotFile->retVal = retVal;
1198                 return pilotFile->retVal;
1199         }
1200
1201         num = unpack_AddressAppInfo( &pilotFile->addrInfo, buf, rec_size );
1202         if( buf ) {
1203                 free(buf);
1204         }
1205         if( num <= 0 ) {
1206                 pilotFile->retVal = MGU_ERROR_READ;
1207                 return pilotFile->retVal;
1208         }
1209
1210         pilotFile->readMetadata = TRUE;
1211         pilotFile->retVal = MGU_SUCCESS;
1212         return pilotFile->retVal;
1213 }
1214
1215 /*
1216 * Setup labels and indexes from metadata.
1217 * Return: TRUE is setup successfully.
1218 */
1219 static gboolean jpilot_setup_labels( JPilotFile *pilotFile ) {
1220         gboolean retVal = FALSE;
1221         struct AddressAppInfo *ai;
1222         GList *node;
1223
1224         g_return_val_if_fail( pilotFile != NULL, -1 );
1225
1226         /* Release indexes */
1227         node = pilotFile->labelInd;
1228         while( node ) {
1229                 node->data = NULL;
1230                 node = g_list_next( node );
1231         }
1232         pilotFile->labelInd = NULL;
1233
1234         if( pilotFile->readMetadata ) {
1235                 ai = & pilotFile->addrInfo;
1236                 node = pilotFile->customLabels;
1237                 while( node ) {
1238                         gchar *lbl = node->data;
1239                         gint ind = -1;
1240                         gint i;
1241                         for( i = 0; i < JPILOT_NUM_LABELS; i++ ) {
1242                                 gchar *labelName = ai->labels[i];
1243                                 if( g_strcasecmp( labelName, lbl ) == 0 ) {
1244                                         ind = i;
1245                                         break;
1246                                 }
1247                         }
1248                         pilotFile->labelInd = g_list_append( pilotFile->labelInd, GINT_TO_POINTER(ind) );
1249                         node = g_list_next( node );
1250                 }
1251                 retVal = TRUE;
1252         }
1253         return retVal;
1254 }
1255
1256 /*
1257 * Load list with character strings of label names.
1258 */
1259 GList *jpilot_load_label( JPilotFile *pilotFile, GList *labelList ) {
1260         int i;
1261
1262         g_return_val_if_fail( pilotFile != NULL, NULL );
1263
1264         if( pilotFile->readMetadata ) {
1265                 struct AddressAppInfo *ai = & pilotFile->addrInfo;
1266                 for( i = 0; i < JPILOT_NUM_LABELS; i++ ) {
1267                         gchar *labelName = ai->labels[i];
1268                         if( labelName ) {
1269                                 labelList = g_list_append( labelList, g_strdup( labelName ) );
1270                         }
1271                         else {
1272                                 labelList = g_list_append( labelList, g_strdup( "" ) );
1273                         }
1274                 }
1275         }
1276         return labelList;
1277 }
1278
1279 /*
1280 * Return category name for specified category ID.
1281 * Enter:  Category ID.
1282 * Return: Name, or empty string if not invalid ID. Name should be g_free() when done.
1283 */
1284 gchar *jpilot_get_category_name( JPilotFile *pilotFile, gint catID ) {
1285         gchar *catName = NULL;
1286
1287         g_return_val_if_fail( pilotFile != NULL, NULL );
1288
1289         if( pilotFile->readMetadata ) {
1290                 struct AddressAppInfo *ai = & pilotFile->addrInfo;
1291                 struct CategoryAppInfo *cat = & ai->category;
1292                 if( catID < 0 || catID > JPILOT_NUM_CATEG ) {
1293                 }
1294                 else {
1295                         catName = g_strdup( cat->name[catID] );
1296                 }
1297         }
1298         if( ! catName ) catName = g_strdup( "" );
1299         return catName;
1300 }
1301
1302 /*
1303 * Load list with character strings of phone label names.
1304 */
1305 GList *jpilot_load_phone_label( JPilotFile *pilotFile, GList *labelList ) {
1306         gint i;
1307
1308         g_return_val_if_fail( pilotFile != NULL, NULL );
1309
1310         if( pilotFile->readMetadata ) {
1311                 struct AddressAppInfo *ai = & pilotFile->addrInfo;
1312                 for( i = 0; i < JPILOT_NUM_PHONELABELS; i++ ) {
1313                         gchar   *labelName = ai->phoneLabels[i];
1314                         if( labelName ) {
1315                                 labelList = g_list_append( labelList, g_strdup( labelName ) );
1316                         }
1317                         else {
1318                                 labelList = g_list_append( labelList, g_strdup( "" ) );
1319                         }
1320                 }
1321         }
1322         return labelList;
1323 }
1324
1325 /*
1326 * Load list with character strings of label names. Only none blank names
1327 * are loaded.
1328 * Return: list of labels. Should by g_free()'d when done.
1329 */
1330 GList *jpilot_load_custom_label( JPilotFile *pilotFile, GList *labelList ) {
1331         gint i;
1332
1333         g_return_val_if_fail( pilotFile != NULL, NULL );
1334
1335         if( pilotFile->readMetadata ) {
1336                 struct AddressAppInfo *ai = & pilotFile->addrInfo;
1337                 for( i = 0; i < NUM_CUSTOM_LABEL; i++ ) {
1338                         gchar *labelName = ai->labels[i+IND_CUSTOM_LABEL];
1339                         if( labelName ) {
1340                                 g_strchomp( labelName );
1341                                 g_strchug( labelName );
1342                                 if( *labelName != '\0' ) {
1343                                         labelList = g_list_append( labelList, g_strdup( labelName ) );
1344                                 }
1345                         }
1346                 }
1347         }
1348         return labelList;
1349 }
1350
1351 /*
1352 * Load list with character strings of category names.
1353 */
1354 GList *jpilot_get_category_list( JPilotFile *pilotFile ) {
1355         GList *catList = NULL;
1356         gint i;
1357
1358         g_return_val_if_fail( pilotFile != NULL, NULL );
1359
1360         if( pilotFile->readMetadata ) {
1361                 struct AddressAppInfo *ai = & pilotFile->addrInfo;
1362                 struct CategoryAppInfo *cat = & ai->category;
1363                 for( i = 0; i < JPILOT_NUM_CATEG; i++ ) {
1364                         gchar *catName = cat->name[i];
1365                         if( catName ) {
1366                                 catList = g_list_append( catList, g_strdup( catName ) );
1367                         }
1368                         else {
1369                                 catList = g_list_append( catList, g_strdup( "" ) );
1370                         }
1371                 }
1372         }
1373         return catList;
1374 }
1375
1376 /*
1377 * Build folder for each category.
1378 */
1379 static void jpilot_build_category_list( JPilotFile *pilotFile ) {
1380         struct AddressAppInfo *ai = & pilotFile->addrInfo;
1381         struct CategoryAppInfo *cat = & ai->category;
1382         gint i;
1383
1384         for( i = 0; i < JPILOT_NUM_CATEG; i++ ) {
1385                 ItemFolder *folder = addritem_create_item_folder();
1386                 addritem_folder_set_name( folder, cat->name[i] );
1387                 addrcache_id_folder( pilotFile->addressCache, folder );
1388                 addrcache_add_folder( pilotFile->addressCache, folder );
1389         }
1390 }
1391
1392 /*
1393 * Remove empty folders (categories).
1394 */
1395 static void jpilot_remove_empty( JPilotFile *pilotFile ) {
1396         GList *listFolder;
1397         GList *remList;
1398         GList *node;
1399         gint i = 0;
1400
1401         listFolder = addrcache_get_list_folder( pilotFile->addressCache );
1402         node = listFolder;
1403         remList = NULL;
1404         while( node ) {
1405                 ItemFolder *folder = node->data;
1406                 if( ADDRITEM_NAME(folder) == NULL || *ADDRITEM_NAME(folder) == '\0' ) {
1407                         if( folder->listPerson ) {
1408                                 /* Give name to folder */
1409                                 gchar name[20];
1410                                 sprintf( name, "? %d", i );
1411                                 addritem_folder_set_name( folder, name );
1412                         }
1413                         else {
1414                                 /* Mark for removal */
1415                                 remList = g_list_append( remList, folder );
1416                         }
1417                 }
1418                 node = g_list_next( node );
1419                 i++;
1420         }
1421         node = remList;
1422         while( node ) {
1423                 ItemFolder *folder = node->data;
1424                 addrcache_remove_folder( pilotFile->addressCache, folder );
1425                 node = g_list_next( node );
1426         }
1427         g_list_free( remList );
1428 }
1429
1430 /*
1431 * ============================================================================================
1432 * Read file into list. Main entry point
1433 * Return: TRUE if file read successfully.
1434 * ============================================================================================
1435 */
1436 gint jpilot_read_data( JPilotFile *pilotFile ) {
1437         g_return_val_if_fail( pilotFile != NULL, -1 );
1438
1439         pilotFile->retVal = MGU_SUCCESS;
1440         pilotFile->accessFlag = FALSE;
1441
1442         if( jpilot_check_files( pilotFile ) ) {
1443                 addrcache_clear( pilotFile->addressCache );
1444                 jpilot_read_metadata( pilotFile );
1445                 if( pilotFile->retVal == MGU_SUCCESS ) {
1446                         jpilot_setup_labels( pilotFile );
1447                         jpilot_build_category_list( pilotFile );
1448                         pilotFile->retVal = jpilot_read_file( pilotFile );
1449                         if( pilotFile->retVal == MGU_SUCCESS ) {
1450                                 jpilot_remove_empty( pilotFile );
1451                                 jpilot_mark_files( pilotFile );
1452                                 pilotFile->addressCache->modified = FALSE;
1453                                 pilotFile->addressCache->dataRead = TRUE;
1454                         }
1455                 }
1456         }
1457         return pilotFile->retVal;
1458 }
1459
1460 /*
1461 * Return link list of persons.
1462 */
1463 GList *jpilot_get_list_person( JPilotFile *pilotFile ) {
1464         g_return_val_if_fail( pilotFile != NULL, NULL );
1465         return addrcache_get_list_person( pilotFile->addressCache );
1466 }
1467
1468 /*
1469 * Return link list of folders. This is always NULL since there are
1470 * no folders in GnomeCard.
1471 * Return: NULL.
1472 */
1473 GList *jpilot_get_list_folder( JPilotFile *pilotFile ) {
1474         g_return_val_if_fail( pilotFile != NULL, NULL );
1475         return addrcache_get_list_folder( pilotFile->addressCache );
1476 }
1477
1478 /*
1479 * Return link list of all persons. Note that the list contains references
1480 * to items. Do *NOT* attempt to use the addrbook_free_xxx() functions...
1481 * this will destroy the addressbook data!
1482 * Return: List of items, or NULL if none.
1483 */
1484 GList *jpilot_get_all_persons( JPilotFile *pilotFile ) {
1485         g_return_val_if_fail( pilotFile != NULL, NULL );
1486         return addrcache_get_all_persons( pilotFile->addressCache );
1487 }
1488
1489 /*
1490 * Check label list for specified label.
1491 */
1492 gint jpilot_check_label( struct AddressAppInfo *ai, gchar *lblCheck ) {
1493         gint i;
1494         gchar *lblName;
1495
1496         if( lblCheck == NULL ) return -1;
1497         if( strlen( lblCheck ) < 1 ) return -1;
1498         for( i = 0; i < JPILOT_NUM_LABELS; i++ ) {
1499                 lblName = ai->labels[i];
1500                 if( lblName ) {
1501                         if( strlen( lblName ) ) {
1502                                 if( g_strcasecmp( lblName, lblCheck ) == 0 ) return i;
1503                         }
1504                 }
1505         }
1506         return -2;
1507 }
1508
1509 /*
1510 * Validate that all parameters specified.
1511 * Return: TRUE if data is good.
1512 */
1513 gboolean jpilot_validate( JPilotFile *pilotFile ) {
1514         gboolean retVal;
1515         gchar *name;
1516
1517         g_return_val_if_fail( pilotFile != NULL, FALSE );
1518
1519         retVal = TRUE;
1520         if( pilotFile->path ) {
1521                 if( strlen( pilotFile->path ) < 1 ) retVal = FALSE;
1522         }
1523         else {
1524                 retVal = FALSE;
1525         }
1526         name = jpilot_get_name( pilotFile );
1527         if( name ) {
1528                 if( strlen( name ) < 1 ) retVal = FALSE;
1529         }
1530         else {
1531                 retVal = FALSE;
1532         }
1533         return retVal;
1534 }
1535
1536 #define WORK_BUFLEN 1024
1537
1538 /*
1539 * Attempt to find a valid JPilot file.
1540 * Return: Filename, or home directory if not found, or empty string if
1541 * no home. Filename should be g_free() when done.
1542 */
1543 gchar *jpilot_find_pilotdb( void ) {
1544         gchar *homedir;
1545         gchar str[ WORK_BUFLEN ];
1546         gint len;
1547         FILE *fp;
1548
1549         homedir = g_get_home_dir();
1550         if( ! homedir ) return g_strdup( "" );
1551
1552         strcpy( str, homedir );
1553         len = strlen( str );
1554         if( len > 0 ) {
1555                 if( str[ len-1 ] != G_DIR_SEPARATOR ) {
1556                         str[ len ] = G_DIR_SEPARATOR;
1557                         str[ ++len ] = '\0';
1558                 }
1559         }
1560         strcat( str, JPILOT_DBHOME_DIR );
1561         strcat( str, G_DIR_SEPARATOR_S );
1562         strcat( str, JPILOT_DBHOME_FILE );
1563
1564         /* Attempt to open */
1565         if( ( fp = fopen( str, "r" ) ) != NULL ) {
1566                 fclose( fp );
1567         }
1568         else {
1569                 /* Truncate filename */
1570                 str[ len ] = '\0';
1571         }
1572         return g_strdup( str );
1573 }
1574
1575 /*
1576 * Attempt to read file, testing for valid JPilot format.
1577 * Return: TRUE if file appears to be valid format.
1578 */
1579 gint jpilot_test_read_file( const gchar *fileSpec ) {
1580         JPilotFile *pilotFile;
1581         gint retVal;
1582
1583         if( fileSpec ) {
1584                 pilotFile = jpilot_create_path( fileSpec );
1585                 retVal = jpilot_read_metadata( pilotFile );
1586                 jpilot_free( pilotFile );
1587                 pilotFile = NULL;
1588         }
1589         else {
1590                 retVal = MGU_NO_FILE;
1591         }
1592         return retVal;
1593 }
1594
1595 /*
1596 * Check whether label is in custom labels.
1597 * Return: TRUE if found.
1598 */
1599 gboolean jpilot_test_custom_label( JPilotFile *pilotFile, const gchar *labelName ) {
1600         gboolean retVal;
1601         GList *node;
1602
1603         g_return_val_if_fail( pilotFile != NULL, FALSE );
1604
1605         retVal = FALSE;
1606         if( labelName ) {
1607                 node = pilotFile->customLabels;
1608                 while( node ) {
1609                         if( g_strcasecmp( labelName, ( gchar * ) node->data ) == 0 ) {
1610                                 retVal = TRUE;
1611                                 break;
1612                         }
1613                         node = g_list_next( node );
1614                 }
1615         }
1616         return retVal;
1617 }
1618
1619 /*
1620 * Test whether pilot link library installed.
1621 * Return: TRUE if library available.
1622 */
1623 gboolean jpilot_test_pilot_lib( void ) {
1624         return TRUE;
1625 }
1626
1627 #endif  /* USE_JPILOT */
1628
1629 /*
1630 * End of Source.
1631 */