sync with 0.8.1cvs17
[claws.git] / src / pine.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2002 Match Grun
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Functions necessary to access Pine address book file.
22  */
23
24 #include <sys/stat.h>
25 #include <glib.h>
26 #include <string.h>
27
28 #include "utils.h"
29 #include "mgutils.h"
30 #include "pine.h"
31 #include "addritem.h"
32 #include "addrcache.h"
33
34 #define PINE_HOME_FILE  ".addressbook"
35 #define PINEBUFSIZE     2048
36 #define CHAR_QUOTE      '\"'
37 #define CHAR_APOS       '\''
38 #define CHAR_COMMA      ','
39 #define CHAR_AT         '@'
40
41 /*
42 * Create new object.
43 */
44 PineFile *pine_create() {
45         PineFile *pineFile;
46         pineFile = g_new0( PineFile, 1 );
47         pineFile->path = NULL;
48         pineFile->file = NULL;
49         pineFile->retVal = MGU_SUCCESS;
50         pineFile->uniqTable = g_hash_table_new( g_str_hash, g_str_equal );
51         pineFile->cbProgress = NULL;
52         return pineFile;
53 }
54
55 /*
56 * Properties...
57 */
58 void pine_set_file( PineFile* pineFile, const gchar *value ) {
59         g_return_if_fail( pineFile != NULL );
60         pineFile->path = mgu_replace_string( pineFile->path, value );
61         g_strstrip( pineFile->path );
62 }
63
64 /*
65 * Register a callback function. When called, the function will be passed
66 * the following arguments:
67 *       PineFile object,
68 *       File size (long),
69 *       Current position (long)
70 * This can be used for a progress indicator.
71 */
72 void pine_set_callback( PineFile *pineFile, void *func ) {
73         pineFile->cbProgress = func;
74 }
75
76 /*
77  * Free key in table.
78  */
79 static gint pine_free_table_vis( gpointer key, gpointer value, gpointer data ) {
80         g_free( key );
81         key = NULL;
82         value = NULL;
83         return TRUE;
84 }
85
86 /*
87 * Free up object by releasing internal memory.
88 */
89 void pine_free( PineFile *pineFile ) {
90         g_return_if_fail( pineFile != NULL );
91
92         /* Close file */
93         if( pineFile->file ) fclose( pineFile->file );
94
95         /* Free internal stuff */
96         g_free( pineFile->path );
97
98         /* Free unique address table */
99         g_hash_table_freeze( pineFile->uniqTable );
100         g_hash_table_foreach_remove( pineFile->uniqTable, pine_free_table_vis, NULL );
101         g_hash_table_thaw( pineFile->uniqTable );
102         g_hash_table_destroy( pineFile->uniqTable );
103
104         /* Clear pointers */
105         pineFile->file = NULL;
106         pineFile->path = NULL;
107         pineFile->retVal = MGU_SUCCESS;
108         pineFile->uniqTable = NULL;
109         pineFile->cbProgress = NULL;
110
111         /* Now release file object */
112         g_free( pineFile );
113 }
114
115 /*
116  * Display object to specified stream.
117  * Enter: pineFile File object.
118  *        stream   File..
119  */
120 void pine_print_file( PineFile *pineFile, FILE *stream ) {
121         g_return_if_fail( pineFile != NULL );
122         fprintf( stream, "Pine File:\n" );
123         fprintf( stream, "file spec: '%s'\n", pineFile->path );
124         fprintf( stream, "  ret val: %d\n",   pineFile->retVal );
125 }
126
127 /*
128  * Open file for read.
129  * Enter: pineFile File object.
130  * return: TRUE if file opened successfully.
131  */
132 static gint pine_open_file( PineFile* pineFile ) {
133         if( pineFile->path ) {
134                 pineFile->file = fopen( pineFile->path, "rb" );
135                 if( ! pineFile->file ) {
136                         pineFile->retVal = MGU_OPEN_FILE;
137                         return pineFile->retVal;
138                 }
139         }
140         else {
141                 /* printf( "file not specified\n" ); */
142                 pineFile->retVal = MGU_NO_FILE;
143                 return pineFile->retVal;
144         }
145
146         /* Setup a buffer area */
147         pineFile->retVal = MGU_SUCCESS;
148         return pineFile->retVal;
149 }
150
151 /*
152  * Close file.
153  * Enter: pineFile File object.
154  */
155 static void pine_close_file( PineFile *pineFile ) {
156         g_return_if_fail( pineFile != NULL );
157         if( pineFile->file ) fclose( pineFile->file );
158         pineFile->file = NULL;
159 }
160
161 /*
162  * Read line of text from file.
163  * Enter: pineFile File object.
164  * Return: Copy of buffer. Should be g_free'd when done.
165  */
166 static gchar *pine_read_line( PineFile *pineFile ) {
167         gchar buf[ PINEBUFSIZE ];
168         gchar ch;
169         gchar *ptr;
170
171         if( feof( pineFile->file ) ) return NULL;
172
173         ptr = buf;
174         while( TRUE ) {
175                 *ptr = '\0';
176                 ch = fgetc( pineFile->file );
177                 if( ch == '\0' || ch == EOF ) {
178                         if( *buf == '\0' ) return NULL;
179                         break;
180                 }
181                 if( ch == '\n' ) {
182                         break;
183                 }
184                 *ptr = ch;
185                 ptr++;
186         }
187
188         /* Copy into private buffer */
189         return g_strdup( buf );
190 }
191
192 /*
193  * Parsed address data.
194  */
195 typedef struct _Pine_ParsedRec_ Pine_ParsedRec;
196 struct _Pine_ParsedRec_ {
197         gchar *nickName;
198         gchar *name;
199         gchar *address;
200         gchar *fcc;
201         gchar *comments;
202         gboolean isGroup;
203         GSList *listName;
204         GSList *listAddr;
205 };
206
207 /*
208  * Free data record.
209  * Enter: rec Data record.
210  */
211 static void pine_free_rec( Pine_ParsedRec *rec ) {
212         if( rec ) {
213                 g_free( rec->nickName );
214                 g_free( rec->name );
215                 g_free( rec->address );
216                 g_free( rec->fcc );
217                 g_free( rec->comments );
218                 mgu_clear_slist( rec->listName );
219                 mgu_clear_slist( rec->listAddr );
220                 g_slist_free( rec->listName );
221                 g_slist_free( rec->listAddr );
222                 rec->nickName = NULL;
223                 rec->name = NULL;
224                 rec->address = NULL;
225                 rec->fcc = NULL;
226                 rec->comments = NULL;
227                 rec->isGroup = FALSE;
228                 g_free( rec );
229         }
230 }
231
232 /*
233  * Clean name.
234  */
235 static void pine_clean_name( Pine_ParsedRec *rec ) {
236         gchar *p;
237
238         p = rec->name;
239         if( p == NULL ) return;
240         if( *p == '\0' ) return;
241
242         g_strstrip( rec->name );
243         if( *p == CHAR_APOS || *p == CHAR_QUOTE ) {
244                 return;
245         }
246
247         /* If embedded comma present, surround match with quotes */
248         while( *p ) {
249                 if( *p == CHAR_COMMA ) {
250                         p = g_strdup_printf( "\"%s\"", rec->name );
251                         g_free( rec->name );
252                         rec->name = p;
253                         return;
254                 }
255                 p++;
256         }
257 }
258
259 /*
260  * Parse pine address record.
261  * Enter:  buf Address record buffer.
262  * Return: Data record.
263  */
264 static Pine_ParsedRec *pine_parse_record( gchar *buf ) {
265         Pine_ParsedRec *rec;
266         gchar *p, *f;
267         gint pos, len, i;
268         gchar *tmp[5];
269
270         for( i = 0; i < 5; i++ )
271                 tmp[i] = NULL;
272
273         /* Extract tab separated values */
274         rec = NULL;
275         pos = 0;
276         p = f = buf;
277         while( *p ) {
278                 if( *p == '\t' ) {
279                         len = p - f;
280                         if( len > 0 ) {
281                                 tmp[ pos ] = g_strndup( f, len );
282                                 f = p;
283                                 f++;
284                         }
285                         pos++;
286                 }
287                 p++;
288         }
289
290         /* Extract last value */
291         len = p - f;
292         if( len > 0 ) {
293                 tmp[ pos++ ] = g_strndup( f, len );
294         }
295
296         /* Populate record */
297         if( pos > 0 ) {
298                 rec = g_new0( Pine_ParsedRec, 1 );
299                 rec->isGroup = FALSE;
300                 for( i = 0; i < pos; i++ ) {
301                         f = tmp[i];
302                         if( f ) {
303                                 g_strstrip( f );
304                         }
305                         if( i == 0 ) rec->nickName = f;
306                         else if( i == 1 ) rec->name = f;
307                         else if( i == 2 ) rec->address = f;
308                         else if( i == 3 ) rec->fcc = f;
309                         else if( i == 4 ) rec->comments = f;
310                         tmp[i] = NULL;
311                 }
312
313                 if( rec->address != NULL ) {
314                         /* Strip leading/trailing parens */
315                         p = rec->address;
316                         if( *p == '(' ) {
317                                 len = strlen( p ) - 1;
318                                 *p = ' ';
319                                 *(p + len) = ' ';
320                                 rec->isGroup = TRUE;
321                         }
322                 }
323         }
324
325         return rec;
326 }
327
328 /*
329  * Parse name from email address string.
330  * Enter: buf Start address of buffer to process (not modified).
331  *        atp Pointer to email at (@) character.
332  *        ap  Pointer to start of email address returned.
333  *        ep  Pointer to end of email address returned.
334  * Return: Parsed name or NULL if not present. This should be g_free'd
335  * when done.
336  */
337 static gchar *pine_parse_name(
338                 const gchar *buf, const gchar *atp, const gchar **ap,
339                 const gchar **ep )
340 {
341         gchar *name;
342         const gchar *pos;
343         const gchar *tmp;
344         const gchar *bp;
345         gint ilen;
346
347         name = NULL;
348         *ap = NULL;
349         *ep = NULL;
350
351         /* Find first non-separator char */
352         bp = buf;
353         while( TRUE ) {
354                 if( strchr( ",; \n\r", *bp ) == NULL ) break;
355                 bp++;
356         }
357
358         /* Search back for start of name */
359         tmp = atp;
360         pos = atp;
361         while( pos >= bp ) {
362                 tmp = pos;
363                 if( *pos == '<' ) {
364                         /* Found start of address/end of name part */
365                         ilen = -1 + ( size_t ) ( pos - bp );
366                         name = g_strndup( bp, ilen + 1 );
367                         *(name + ilen + 1) = '\0';
368
369                         /* Remove leading trailing quotes and spaces */
370                         mgu_str_ltc2space( name, '\"', '\"' );
371                         mgu_str_ltc2space( name, '\'', '\'' );
372                         mgu_str_ltc2space( name, '\"', '\"' );
373                         mgu_str_unescape( name );
374                         g_strstrip( name );
375                         break;
376                 }
377                 pos--;
378         }
379         *ap = tmp;
380
381         /* Search forward for end of address */
382         pos = atp + 1;
383         while( TRUE ) {
384                 if( *pos == '>' ) {
385                         pos++;
386                         break;
387                 }
388                 if( strchr( ",; \'\n\r", *pos ) ) break;
389                 pos++;
390         }
391         *ep = pos;
392
393         return name;
394 }
395
396 /*
397  * Parse address list.
398  * Enter: pineFile Pine control data.
399  *        cache    Address cache.
400  *        rec      Data record.
401  */
402 static void pine_parse_address( PineFile *pineFile, AddressCache *cache, Pine_ParsedRec *rec ) {
403         const gchar *buf;
404         gchar addr[ PINEBUFSIZE ];
405         const gchar *bp;
406         const gchar *ep;
407         gchar *atCh;
408         gchar *name;
409         gint len;
410
411         buf = rec->address;
412         while((atCh = strchr( buf, CHAR_AT )) != NULL) {
413                 name = pine_parse_name( buf, atCh, &bp, &ep );
414                 len = ( size_t ) ( ep - bp );
415                 strncpy( addr, bp, len );
416                 addr[ len ] = '\0';
417                 extract_address( addr );
418
419                 if( name == NULL ) name = g_strdup( "" );
420                 rec->listName = g_slist_append( rec->listName, name );
421                 rec->listAddr = g_slist_append( rec->listAddr, g_strdup( addr ) );
422
423                 buf = ep;
424                 if( atCh == ep ) {
425                         buf++;
426                 }
427         }
428 }
429
430 /*
431  * Insert person and address into address cache.
432  * Enter: pineFile Pine control data.
433  *        cache    Address cache.
434  *        address  E-Mail address.
435  *        name     Name.
436  *        remarks  Remarks.
437  * Return: E-Mail object, either inserted or found in hash table.
438  */
439 static ItemEMail *pine_insert_table(
440                 PineFile *pineFile, AddressCache *cache, gchar *address,
441                 gchar *name, gchar *remarks )
442 {
443         ItemPerson *person;
444         ItemEMail *email;
445         gchar *key;
446
447         /* Test whether address already in hash table */
448         key = g_strdup( address );
449         g_strdown( key );
450         email = g_hash_table_lookup( pineFile->uniqTable, key );
451
452         if( email == NULL ) {
453                 /* No - create person */
454                 person = addritem_create_item_person();
455                 addritem_person_set_common_name( person, name );
456                 addrcache_id_person( cache, person );
457                 addrcache_add_person( cache, person );
458
459                 /* Add email for person */
460                 email = addritem_create_item_email();
461                 addritem_email_set_address( email, address );
462                 addritem_email_set_remarks( email, remarks );
463                 addrcache_id_email( cache, email );
464                 addrcache_person_add_email( cache, person, email );
465
466                 /* Insert entry */
467                 g_hash_table_insert( pineFile->uniqTable, key, email );
468         }
469         else {
470                 /* Yes - update person with longest name */
471                 person = ( ItemPerson * ) ADDRITEM_PARENT(email);
472                 if( strlen( name ) > strlen( ADDRITEM_NAME(person) ) ) {
473                         addritem_person_set_common_name( person, name );
474                 }
475
476                 /* Free up */
477                 g_free( key );
478         }
479
480         return email;
481 }
482
483 /*
484  * Parse address line adn build address items.
485  * Enter: pineFile Pine control data.
486  *        cache    Address cache to load.
487  *        line     Address record.
488  */
489 static void pine_build_items( PineFile *pineFile, AddressCache *cache, gchar *line ) {
490         Pine_ParsedRec *rec;
491         GSList *nodeAddr, *nodeName;
492         ItemGroup *group;
493         ItemEMail *email;
494
495         rec = pine_parse_record( line );
496         if( rec ) {
497                 pine_clean_name( rec );
498                 pine_parse_address( pineFile, cache, rec );
499                 /* pine_print_rec( rec, stdout ); */
500                 /* printf( "=========\n" ); */
501
502                 if( rec->isGroup ) {
503                         /* Create group */
504                         group = addritem_create_item_group();
505                         addritem_group_set_name( group, rec->nickName );
506                         addrcache_id_group( cache, group );
507                         addrcache_add_group( cache, group );
508
509                         /* Add email to group */
510                         nodeName = rec->listName;
511                         nodeAddr = rec->listAddr;
512                         while( nodeAddr ) {
513                                 email = pine_insert_table(
514                                                 pineFile, cache, nodeAddr->data,
515                                                 nodeName->data, "" );
516
517                                 /* Add email to group */
518                                 addritem_group_add_email( group, email );
519
520                                 nodeAddr = g_slist_next( nodeAddr );
521                                 nodeName = g_slist_next( nodeName );
522                         }
523                 }
524                 else {
525                         email = pine_insert_table(
526                                         pineFile, cache, rec->address,
527                                         rec->name, rec->comments );
528                 }
529
530                 pine_free_rec( rec );
531         }
532 }
533
534 /*
535  * Read file data into address cache.
536  * Enter: pineFile Pine control data.
537  *        cache    Address cache to load.
538  */
539 static void pine_read_file( PineFile *pineFile, AddressCache *cache ) {
540         GSList *listValue = NULL;
541         gboolean flagEOF = FALSE, flagProc = FALSE, flagDone = FALSE;
542         gchar *line =  NULL, *lineValue = NULL;
543         long posEnd = 0L;
544         long posCur = 0L;
545
546         /* Find EOF for progress indicator */
547         fseek( pineFile->file, 0L, SEEK_END );
548         posEnd = ftell( pineFile->file );
549         fseek( pineFile->file, 0L, SEEK_SET );
550
551         flagProc = FALSE;
552         while( ! flagDone ) {
553                 if( flagEOF ) {
554                         flagDone = TRUE;
555                         flagProc = TRUE;
556                 }
557                 else {
558                         line =  pine_read_line( pineFile );
559                 }
560
561                 posCur = ftell( pineFile->file );
562                 if( pineFile->cbProgress ) {
563                         /* Call progress indicator */
564                         ( pineFile->cbProgress ) ( pineFile, & posEnd, & posCur );
565                 }
566
567                 /* Add line to list */
568                 if( line == NULL ) {
569                         flagEOF = TRUE;
570                 }
571                 else {
572                         /* Check for continuation line (1 space only) */
573                         if( *line == ' ' ) {
574                                 g_strchug( line );
575                                 listValue = g_slist_append(
576                                                 listValue, g_strdup( line ) );
577                                 flagProc = FALSE;
578                         }
579                         else {
580                                 flagProc = TRUE;
581                         }
582                 }
583
584                 if( flagProc ) {
585                         if( listValue != NULL ) {
586                                 /* Process list */
587                                 lineValue = mgu_list_coalesce( listValue );
588                                 if( lineValue ) {
589                                         pine_build_items(
590                                                 pineFile, cache, lineValue );
591                                 }
592                                 g_free( lineValue );
593                                 lineValue = NULL;
594                                 mgu_free_list( listValue );
595                                 listValue = NULL;
596                         }
597                         if( line != NULL ) {
598                                 /* Append to list */
599                                 listValue = g_slist_append(
600                                                 listValue, g_strdup( line ) );
601                         }
602                 }
603
604                 g_free( line );
605                 line = NULL;
606         }
607
608         /* Release data */
609         mgu_free_list( listValue );
610         listValue = NULL;
611 }
612
613 /*
614  * ============================================================================================
615  * Read file into list. Main entry point
616  * Enter:  pineFile Pine control data.
617  *         cache    Address cache to load.
618  * Return: Status code.
619  * ============================================================================================
620  */
621 gint pine_import_data( PineFile *pineFile, AddressCache *cache ) {
622         g_return_val_if_fail( pineFile != NULL, MGU_BAD_ARGS );
623         g_return_val_if_fail( cache != NULL, MGU_BAD_ARGS );
624
625         pineFile->retVal = MGU_SUCCESS;
626         addrcache_clear( cache );
627         cache->dataRead = FALSE;
628         pine_open_file( pineFile );
629         if( pineFile->retVal == MGU_SUCCESS ) {
630                 /* Read data into the cache */
631                 pine_read_file( pineFile, cache );
632                 pine_close_file( pineFile );
633
634                 /* Mark cache */
635                 cache->modified = FALSE;
636                 cache->dataRead = TRUE;
637         }
638         return pineFile->retVal;
639 }
640
641 #define WORK_BUFLEN 1024
642
643 /*
644  * Attempt to find a Pine addressbook file.
645  * Return: Filename, or home directory if not found, or empty string if
646  * no home. Filename should be g_free() when done.
647  */
648 gchar *pine_find_file( void ) {
649         gchar *homedir;
650         gchar str[ WORK_BUFLEN ];
651         gint len;
652         FILE *fp;
653
654         homedir = g_get_home_dir();
655         if( ! homedir ) return g_strdup( "" );
656
657         strcpy( str, homedir );
658         len = strlen( str );
659         if( len > 0 ) {
660                 if( str[ len-1 ] != G_DIR_SEPARATOR ) {
661                         str[ len ] = G_DIR_SEPARATOR;
662                         str[ ++len ] = '\0';
663                 }
664         }
665         strcat( str, PINE_HOME_FILE );
666
667         /* Attempt to open */
668         if( ( fp = fopen( str, "rb" ) ) != NULL ) {
669                 fclose( fp );
670         }
671         else {
672                 /* Truncate filename */
673                 str[ len ] = '\0';
674         }
675         return g_strdup( str );
676 }
677
678 /*
679 * End of Source.
680 */
681