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