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