2005-09-27 [colin] 1.9.14cvs56
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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_foreach_remove( pineFile->uniqTable, pine_free_table_vis, NULL );
100         g_hash_table_destroy( pineFile->uniqTable );
101
102         /* Clear pointers */
103         pineFile->file = NULL;
104         pineFile->path = NULL;
105         pineFile->retVal = MGU_SUCCESS;
106         pineFile->uniqTable = NULL;
107         pineFile->cbProgress = NULL;
108
109         /* Now release file object */
110         g_free( pineFile );
111 }
112
113 /*
114  * Display object to specified stream.
115  * Enter: pineFile File object.
116  *        stream   File..
117  */
118 void pine_print_file( PineFile *pineFile, FILE *stream ) {
119         g_return_if_fail( pineFile != NULL );
120         fprintf( stream, "Pine File:\n" );
121         fprintf( stream, "file spec: '%s'\n", pineFile->path );
122         fprintf( stream, "  ret val: %d\n",   pineFile->retVal );
123 }
124
125 /*
126  * Open file for read.
127  * Enter: pineFile File object.
128  * return: TRUE if file opened successfully.
129  */
130 static gint pine_open_file( PineFile* pineFile ) {
131         if( pineFile->path ) {
132                 pineFile->file = g_fopen( pineFile->path, "rb" );
133                 if( ! pineFile->file ) {
134                         pineFile->retVal = MGU_OPEN_FILE;
135                         return pineFile->retVal;
136                 }
137         }
138         else {
139                 /* printf( "file not specified\n" ); */
140                 pineFile->retVal = MGU_NO_FILE;
141                 return pineFile->retVal;
142         }
143
144         /* Setup a buffer area */
145         pineFile->retVal = MGU_SUCCESS;
146         return pineFile->retVal;
147 }
148
149 /*
150  * Close file.
151  * Enter: pineFile File object.
152  */
153 static void pine_close_file( PineFile *pineFile ) {
154         g_return_if_fail( pineFile != NULL );
155         if( pineFile->file ) fclose( pineFile->file );
156         pineFile->file = NULL;
157 }
158
159 /*
160  * Read line of text from file.
161  * Enter: pineFile File object.
162  * Return: Copy of buffer. Should be g_free'd when done.
163  */
164 static gchar *pine_read_line( PineFile *pineFile ) {
165         gchar buf[ PINEBUFSIZE ];
166         int c;
167         gchar ch;
168         gchar *ptr;
169
170         if( feof( pineFile->file ) ) return NULL;
171
172         ptr = buf;
173         while( TRUE ) {
174                 *ptr = '\0';
175                 c = fgetc( pineFile->file );
176                 if( c == EOF ) {
177                         if( *buf == '\0' ) return NULL;
178                         break;
179                 }
180                 ch = (gchar) c;
181                 if( ch == '\0' ) {
182                         if( *buf == '\0' ) return NULL;
183                         break;
184                 }
185                 if( ch == '\n' ) {
186                         break;
187                 }
188                 *ptr = ch;
189                 ptr++;
190         }
191
192         /* Copy into private buffer */
193         return g_strdup( buf );
194 }
195
196 /*
197  * Parsed address data.
198  */
199 typedef struct _Pine_ParsedRec_ Pine_ParsedRec;
200 struct _Pine_ParsedRec_ {
201         gchar *nickName;
202         gchar *name;
203         gchar *address;
204         gchar *fcc;
205         gchar *comments;
206         gboolean isGroup;
207         GSList *listName;
208         GSList *listAddr;
209 };
210
211 /*
212  * Free data record.
213  * Enter: rec Data record.
214  */
215 static void pine_free_rec( Pine_ParsedRec *rec ) {
216         if( rec ) {
217                 g_free( rec->nickName );
218                 g_free( rec->name );
219                 g_free( rec->address );
220                 g_free( rec->fcc );
221                 g_free( rec->comments );
222                 mgu_clear_slist( rec->listName );
223                 mgu_clear_slist( rec->listAddr );
224                 g_slist_free( rec->listName );
225                 g_slist_free( rec->listAddr );
226                 rec->nickName = NULL;
227                 rec->name = NULL;
228                 rec->address = NULL;
229                 rec->fcc = NULL;
230                 rec->comments = NULL;
231                 rec->isGroup = FALSE;
232                 g_free( rec );
233         }
234 }
235
236 /*
237  * Clean name.
238  */
239 static void pine_clean_name( Pine_ParsedRec *rec ) {
240         gchar *p;
241
242         p = rec->name;
243         if( p == NULL ) return;
244         if( *p == '\0' ) return;
245
246         g_strstrip( rec->name );
247         if( *p == CHAR_APOS || *p == CHAR_QUOTE ) {
248                 return;
249         }
250
251         /* If embedded comma present, surround match with quotes */
252         while( *p ) {
253                 if( *p == CHAR_COMMA ) {
254                         p = g_strdup_printf( "\"%s\"", rec->name );
255                         g_free( rec->name );
256                         rec->name = p;
257                         return;
258                 }
259                 p++;
260         }
261 }
262
263 /*
264  * Parse pine address record.
265  * Enter:  buf Address record buffer.
266  * Return: Data record.
267  */
268 static Pine_ParsedRec *pine_parse_record( gchar *buf ) {
269         Pine_ParsedRec *rec;
270         gchar *p, *f;
271         gint pos, len, i;
272         gchar *tmp[5];
273
274         for( i = 0; i < 5; i++ )
275                 tmp[i] = NULL;
276
277         /* Extract tab separated values */
278         rec = NULL;
279         pos = 0;
280         p = f = buf;
281         while( *p ) {
282                 if( *p == '\t' ) {
283                         len = p - f;
284                         if( len > 0 ) {
285                                 tmp[ pos ] = g_strndup( f, len );
286                                 f = p;
287                                 f++;
288                         }
289                         pos++;
290                 }
291                 p++;
292         }
293
294         /* Extract last value */
295         len = p - f;
296         if( len > 0 ) {
297                 tmp[ pos++ ] = g_strndup( f, len );
298         }
299
300         /* Populate record */
301         if( pos > 0 ) {
302                 rec = g_new0( Pine_ParsedRec, 1 );
303                 rec->isGroup = FALSE;
304                 for( i = 0; i < pos; i++ ) {
305                         f = tmp[i];
306                         if( f ) {
307                                 g_strstrip( f );
308                         }
309                         if( i == 0 ) rec->nickName = f;
310                         else if( i == 1 ) rec->name = f;
311                         else if( i == 2 ) rec->address = f;
312                         else if( i == 3 ) rec->fcc = f;
313                         else if( i == 4 ) rec->comments = f;
314                         tmp[i] = NULL;
315                 }
316
317                 if( rec->address != NULL ) {
318                         /* Strip leading/trailing parens */
319                         p = rec->address;
320                         if( *p == '(' ) {
321                                 len = strlen( p ) - 1;
322                                 *p = ' ';
323                                 *(p + len) = ' ';
324                                 rec->isGroup = TRUE;
325                         }
326                 }
327         }
328
329         return rec;
330 }
331
332 /*
333  * Parse name from email address string.
334  * Enter: buf Start address of buffer to process (not modified).
335  *        atp Pointer to email at (@) character.
336  *        ap  Pointer to start of email address returned.
337  *        ep  Pointer to end of email address returned.
338  * Return: Parsed name or NULL if not present. This should be g_free'd
339  * when done.
340  */
341 static gchar *pine_parse_name(
342                 const gchar *buf, const gchar *atp, const gchar **ap,
343                 const gchar **ep )
344 {
345         gchar *name;
346         const gchar *pos;
347         const gchar *tmp;
348         const gchar *bp;
349         gint ilen;
350
351         name = NULL;
352         *ap = NULL;
353         *ep = NULL;
354
355         /* Find first non-separator char */
356         bp = buf;
357         while( TRUE ) {
358                 if( strchr( ",; \n\r", *bp ) == NULL ) break;
359                 bp++;
360         }
361
362         /* Search back for start of name */
363         tmp = atp;
364         pos = atp;
365         while( pos >= bp ) {
366                 tmp = pos;
367                 if( *pos == '<' ) {
368                         /* Found start of address/end of name part */
369                         ilen = -1 + ( size_t ) ( pos - bp );
370                         name = g_strndup( bp, ilen + 1 );
371                         *(name + ilen + 1) = '\0';
372
373                         /* Remove leading trailing quotes and spaces */
374                         mgu_str_ltc2space( name, '\"', '\"' );
375                         mgu_str_ltc2space( name, '\'', '\'' );
376                         mgu_str_ltc2space( name, '\"', '\"' );
377                         mgu_str_unescape( name );
378                         g_strstrip( name );
379                         break;
380                 }
381                 pos--;
382         }
383         *ap = tmp;
384
385         /* Search forward for end of address */
386         pos = atp + 1;
387         while( TRUE ) {
388                 if( *pos == '>' ) {
389                         pos++;
390                         break;
391                 }
392                 if( strchr( ",; \'\n\r", *pos ) ) break;
393                 pos++;
394         }
395         *ep = pos;
396
397         return name;
398 }
399
400 /*
401  * Parse address list.
402  * Enter: pineFile Pine control data.
403  *        cache    Address cache.
404  *        rec      Data record.
405  */
406 static void pine_parse_address( PineFile *pineFile, AddressCache *cache, Pine_ParsedRec *rec ) {
407         const gchar *buf;
408         gchar addr[ PINEBUFSIZE ];
409         const gchar *bp;
410         const gchar *ep;
411         gchar *atCh;
412         gchar *name;
413         gint len;
414
415         g_return_if_fail( rec->address != NULL );
416
417         buf = rec->address;
418         while((atCh = strchr( buf, CHAR_AT )) != NULL) {
419                 name = pine_parse_name( buf, atCh, &bp, &ep );
420                 len = ( size_t ) ( ep - bp );
421                 strncpy( addr, bp, len );
422                 addr[ len ] = '\0';
423                 extract_address( addr );
424
425                 if( name == NULL ) name = g_strdup( "" );
426                 rec->listName = g_slist_append( rec->listName, name );
427                 rec->listAddr = g_slist_append( rec->listAddr, g_strdup( addr ) );
428
429                 buf = ep;
430                 if( atCh == ep ) {
431                         buf++;
432                 }
433         }
434 }
435
436 /*
437  * Insert person and address into address cache.
438  * Enter: pineFile Pine control data.
439  *        cache    Address cache.
440  *        address  E-Mail address.
441  *        name     Name.
442  *        remarks  Remarks.
443  * Return: E-Mail object, either inserted or found in hash table.
444  */
445 static ItemEMail *pine_insert_table(
446                 PineFile *pineFile, AddressCache *cache, gchar *address,
447                 gchar *name, gchar *remarks )
448 {
449         ItemPerson *person;
450         ItemEMail *email;
451         gchar *key;
452
453         g_return_val_if_fail( address != NULL, NULL );
454
455         /* create an entry with empty name if needed */
456         if ( name == NULL )
457                 name = "";
458
459         /* Test whether address already in hash table */
460         key = g_strdup( address );
461         g_strdown( key );
462         email = g_hash_table_lookup( pineFile->uniqTable, key );
463
464         if( email == NULL ) {
465                 /* No - create person */
466                 person = addritem_create_item_person();
467                 addritem_person_set_common_name( person, name );
468                 addrcache_id_person( cache, person );
469                 addrcache_add_person( cache, person );
470
471                 /* Add email for person */
472                 email = addritem_create_item_email();
473                 addritem_email_set_address( email, address );
474                 addritem_email_set_remarks( email, remarks );
475                 addrcache_id_email( cache, email );
476                 addrcache_person_add_email( cache, person, email );
477
478                 /* Insert entry */
479                 g_hash_table_insert( pineFile->uniqTable, key, email );
480         }
481         else {
482                 /* Yes - update person with longest name */
483                 person = ( ItemPerson * ) ADDRITEM_PARENT(email);
484                 if( strlen( name ) > strlen( ADDRITEM_NAME(person) ) ) {
485                         addritem_person_set_common_name( person, name );
486                 }
487
488                 /* Free up */
489                 g_free( key );
490         }
491
492         return email;
493 }
494
495 /*
496  * Parse address line adn build address items.
497  * Enter: pineFile Pine control data.
498  *        cache    Address cache to load.
499  *        line     Address record.
500  */
501 static void pine_build_items( PineFile *pineFile, AddressCache *cache, gchar *line ) {
502         Pine_ParsedRec *rec;
503         GSList *nodeAddr, *nodeName;
504         ItemGroup *group;
505         ItemEMail *email;
506
507         rec = pine_parse_record( line );
508         if( rec ) {
509                 pine_clean_name( rec );
510                 pine_parse_address( pineFile, cache, rec );
511                 /* pine_print_rec( rec, stdout ); */
512                 /* printf( "=========\n" ); */
513
514                 if( rec->isGroup ) {
515                         /* Create group */
516                         group = addritem_create_item_group();
517                         addritem_group_set_name( group, rec->nickName );
518                         addrcache_id_group( cache, group );
519                         addrcache_add_group( cache, group );
520
521                         /* Add email to group */
522                         nodeName = rec->listName;
523                         nodeAddr = rec->listAddr;
524                         while( nodeAddr ) {
525                                 email = pine_insert_table(
526                                                 pineFile, cache, nodeAddr->data,
527                                                 nodeName->data, "" );
528
529                                 /* Add email to group */
530                                 addritem_group_add_email( group, email );
531
532                                 nodeAddr = g_slist_next( nodeAddr );
533                                 nodeName = g_slist_next( nodeName );
534                         }
535                 }
536                 else {
537                         email = pine_insert_table(
538                                         pineFile, cache, rec->address,
539                                         rec->name, rec->comments );
540                 }
541
542                 pine_free_rec( rec );
543         }
544 }
545
546 /*
547  * Read file data into address cache.
548  * Enter: pineFile Pine control data.
549  *        cache    Address cache to load.
550  */
551 static void pine_read_file( PineFile *pineFile, AddressCache *cache ) {
552         GSList *listValue = NULL;
553         gboolean flagEOF = FALSE, flagProc = FALSE, flagDone = FALSE;
554         gchar *line =  NULL, *lineValue = NULL;
555         long posEnd = 0L;
556         long posCur = 0L;
557
558         /* Find EOF for progress indicator */
559         fseek( pineFile->file, 0L, SEEK_END );
560         posEnd = ftell( pineFile->file );
561         fseek( pineFile->file, 0L, SEEK_SET );
562
563         flagProc = FALSE;
564         while( ! flagDone ) {
565                 if( flagEOF ) {
566                         flagDone = TRUE;
567                         flagProc = TRUE;
568                 }
569                 else {
570                         line =  pine_read_line( pineFile );
571                 }
572
573                 posCur = ftell( pineFile->file );
574                 if( pineFile->cbProgress ) {
575                         /* Call progress indicator */
576                         ( pineFile->cbProgress ) ( pineFile, & posEnd, & posCur );
577                 }
578
579                 /* Add line to list */
580                 if( line == NULL ) {
581                         flagEOF = TRUE;
582                 }
583                 else {
584                         /* Check for continuation line (1 space only) */
585                         if( *line == ' ' ) {
586                                 g_strchug( line );
587                                 listValue = g_slist_append(
588                                                 listValue, g_strdup( line ) );
589                                 flagProc = FALSE;
590                         }
591                         else {
592                                 flagProc = TRUE;
593                         }
594                 }
595
596                 if( flagProc ) {
597                         if( listValue != NULL ) {
598                                 /* Process list */
599                                 lineValue = mgu_list_coalesce( listValue );
600                                 if( lineValue ) {
601                                         pine_build_items(
602                                                 pineFile, cache, lineValue );
603                                 }
604                                 g_free( lineValue );
605                                 lineValue = NULL;
606                                 mgu_free_list( listValue );
607                                 listValue = NULL;
608                         }
609                         if( line != NULL ) {
610                                 /* Append to list */
611                                 listValue = g_slist_append(
612                                                 listValue, g_strdup( line ) );
613                         }
614                 }
615
616                 g_free( line );
617                 line = NULL;
618         }
619
620         /* Release data */
621         mgu_free_list( listValue );
622         listValue = NULL;
623 }
624
625 /*
626  * ============================================================================================
627  * Read file into list. Main entry point
628  * Enter:  pineFile Pine control data.
629  *         cache    Address cache to load.
630  * Return: Status code.
631  * ============================================================================================
632  */
633 gint pine_import_data( PineFile *pineFile, AddressCache *cache ) {
634         g_return_val_if_fail( pineFile != NULL, MGU_BAD_ARGS );
635         g_return_val_if_fail( cache != NULL, MGU_BAD_ARGS );
636
637         pineFile->retVal = MGU_SUCCESS;
638         addrcache_clear( cache );
639         cache->dataRead = FALSE;
640         pine_open_file( pineFile );
641         if( pineFile->retVal == MGU_SUCCESS ) {
642                 /* Read data into the cache */
643                 pine_read_file( pineFile, cache );
644                 pine_close_file( pineFile );
645
646                 /* Mark cache */
647                 cache->modified = FALSE;
648                 cache->dataRead = TRUE;
649         }
650         return pineFile->retVal;
651 }
652
653 #define WORK_BUFLEN 1024
654
655 /*
656  * Attempt to find a Pine addressbook file.
657  * Return: Filename, or home directory if not found, or empty string if
658  * no home. Filename should be g_free() when done.
659  */
660 gchar *pine_find_file( void ) {
661         const gchar *homedir;
662         gchar str[ WORK_BUFLEN ];
663         gint len;
664         FILE *fp;
665
666         homedir = g_get_home_dir();
667         if( ! homedir ) return g_strdup( "" );
668
669         strcpy( str, homedir );
670         len = strlen( str );
671         if( len > 0 ) {
672                 if( str[ len-1 ] != G_DIR_SEPARATOR ) {
673                         str[ len ] = G_DIR_SEPARATOR;
674                         str[ ++len ] = '\0';
675                 }
676         }
677         strcat( str, PINE_HOME_FILE );
678
679         /* Attempt to open */
680         if( ( fp = g_fopen( str, "rb" ) ) != NULL ) {
681                 fclose( fp );
682         }
683         else {
684                 /* Truncate filename */
685                 str[ len ] = '\0';
686         }
687         return g_strdup( str );
688 }
689
690 /*
691 * End of Source.
692 */
693