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