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