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