aboutsummaryrefslogtreecommitdiffstats
path: root/camel/providers/imap/camel-imap-folder.c
blob: 643587bbe7902578413e7dcc9f70393c0cc56737 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; fill-column: 160 -*- */
/* camel-imap-folder.c: Abstract class for an imap folder */

/* 
 * Authors: Jeffrey Stedfast <fejj@helixcode.com> 
 *
 * Copyright (C) 2000 Helix Code, Inc.
 *
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License as 
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 */


#include <config.h> 

#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>

#include <e-util/e-util.h>

#include "camel-imap-folder.h"
#include "camel-imap-store.h"
#include "camel-imap-stream.h"
#include "camel-imap-utils.h"
#include "string-utils.h"
#include "camel-stream.h"
#include "camel-stream-fs.h"
#include "camel-stream-mem.h"
#include "camel-stream-buffer.h"
#include "camel-data-wrapper.h"
#include "camel-mime-message.h"
#include "camel-stream-filter.h"
#include "camel-mime-filter-from.h"
#include "camel-mime-filter-crlf.h"
#include "camel-exception.h"
#include "camel-mime-utils.h"

#define d(x) x

#define CF_CLASS(o) (CAMEL_FOLDER_CLASS (CAMEL_OBJECT_GET_CLASS(o)))

static CamelFolderClass *parent_class = NULL;

static void imap_init (CamelFolder *folder, CamelStore *parent_store,
               CamelFolder *parent_folder, const gchar *name,
               gchar *separator, gboolean path_begns_with_sep,
               CamelException *ex);
static void imap_finalize (CamelObject *object);
static void imap_refresh_info (CamelFolder *folder, CamelException *ex);
static void imap_sync (CamelFolder *folder, gboolean expunge, CamelException *ex);
static void imap_expunge (CamelFolder *folder, CamelException *ex);

/* message counts */
static gint imap_get_message_count_internal (CamelFolder *folder, CamelException *ex);
static gint imap_get_message_count (CamelFolder *folder);
static gint imap_get_unread_message_count (CamelFolder *folder);

/* message manipulation */
static CamelMimeMessage *imap_get_message (CamelFolder *folder, const gchar *uid,
                       CamelException *ex);
static void imap_append_message (CamelFolder *folder, CamelMimeMessage *message,
                 const CamelMessageInfo *info, CamelException *ex);
static void imap_copy_message_to (CamelFolder *source, const char *uid,
                  CamelFolder *destination, CamelException *ex);
static void imap_move_message_to (CamelFolder *source, const char *uid,
                  CamelFolder *destination, CamelException *ex);

/* subfolder listing */
static GPtrArray *imap_get_subfolder_names_internal (CamelFolder *folder, CamelException *ex);
static GPtrArray *imap_get_subfolder_names (CamelFolder *folder);

/* summary info */
static GPtrArray *imap_get_uids (CamelFolder *folder);
static GPtrArray *imap_get_summary_internal (CamelFolder *folder, CamelException *ex);
static GPtrArray *imap_get_summary (CamelFolder *folder);
static const CamelMessageInfo *imap_get_message_info (CamelFolder *folder, const char *uid);

/* searching */
static GPtrArray *imap_search_by_expression (CamelFolder *folder, const char *expression, CamelException *ex);

/* flag methods */
/*static guint32  imap_get_permanent_flags   (CamelFolder *folder, CamelException *ex);*/
static guint32  imap_get_message_flags     (CamelFolder *folder, const char *uid);
static void     imap_set_message_flags     (CamelFolder *folder, const char *uid, guint32 flags, guint32 set);
static gboolean imap_get_message_user_flag (CamelFolder *folder, const char *uid, const char *name);
static void     imap_set_message_user_flag (CamelFolder *folder, const char *uid, const char *name,
                        gboolean value);


static void
camel_imap_folder_class_init (CamelImapFolderClass *camel_imap_folder_class)
{
    CamelFolderClass *camel_folder_class = CAMEL_FOLDER_CLASS (camel_imap_folder_class);

    parent_class = CAMEL_FOLDER_CLASS(camel_type_get_global_classfuncs (camel_folder_get_type ()));
    
    /* virtual method definition */
    
    /* virtual method overload */
    camel_folder_class->init = imap_init;
    camel_folder_class->refresh_info = imap_refresh_info;
    camel_folder_class->sync = imap_sync;
    camel_folder_class->expunge = imap_expunge;
    
    camel_folder_class->get_uids = imap_get_uids;
    camel_folder_class->free_uids = camel_folder_free_nop;
    camel_folder_class->get_subfolder_names = imap_get_subfolder_names;
    camel_folder_class->free_subfolder_names = camel_folder_free_nop;
    
    camel_folder_class->get_message_count = imap_get_message_count;
    camel_folder_class->get_unread_message_count = imap_get_unread_message_count;
    camel_folder_class->get_message = imap_get_message;
    camel_folder_class->append_message = imap_append_message;
    camel_folder_class->copy_message_to = imap_copy_message_to;
    camel_folder_class->move_message_to = imap_move_message_to;
    
    camel_folder_class->get_summary = imap_get_summary;
    camel_folder_class->get_message_info = imap_get_message_info;
    camel_folder_class->free_summary = camel_folder_free_nop;
    
    camel_folder_class->search_by_expression = imap_search_by_expression;
    
    /*camel_folder_class->get_permanent_flags = imap_get_permanent_flags;*/
    camel_folder_class->get_message_flags = imap_get_message_flags;
    camel_folder_class->set_message_flags = imap_set_message_flags;
    camel_folder_class->get_message_user_flag = imap_get_message_user_flag;
    camel_folder_class->set_message_user_flag = imap_set_message_user_flag;
}

static void
camel_imap_folder_init (gpointer object, gpointer klass)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (object);
    CamelFolder *folder = CAMEL_FOLDER (object);
    
    folder->can_hold_messages = TRUE;
    folder->can_hold_folders = TRUE;
    folder->has_summary_capability = TRUE;
    folder->has_search_capability = TRUE;
    
    imap_folder->summary = NULL;
    imap_folder->summary_hash = NULL;
    imap_folder->lsub = NULL;
}

CamelType
camel_imap_folder_get_type (void)
{
    static CamelType camel_imap_folder_type = CAMEL_INVALID_TYPE;
    
    if (camel_imap_folder_type == CAMEL_INVALID_TYPE) {
        camel_imap_folder_type =
            camel_type_register (CAMEL_FOLDER_TYPE, "CamelImapFolder",
                         sizeof (CamelImapFolder),
                         sizeof (CamelImapFolderClass),
                         (CamelObjectClassInitFunc) camel_imap_folder_class_init,
                         NULL,
                         (CamelObjectInitFunc) camel_imap_folder_init,
                         (CamelObjectFinalizeFunc) imap_finalize);
    }
    
    return camel_imap_folder_type;
}

CamelFolder *
camel_imap_folder_new (CamelStore *parent, char *folder_name, CamelException *ex)
{
    CamelFolder *folder = CAMEL_FOLDER (camel_object_new (camel_imap_folder_get_type ()));
    CamelURL *url = CAMEL_SERVICE (parent)->url;
    char *dir_sep;
    
    dir_sep = CAMEL_IMAP_STORE (parent)->dir_sep;
    
    CF_CLASS (folder)->init (folder, parent, NULL, folder_name, dir_sep, FALSE, ex);
    
    if (camel_exception_is_set (ex)) {
        camel_object_unref (CAMEL_OBJECT (folder));
        return NULL;
    }
    
    if (!strcmp (folder_name, url->path + 1))
        folder->can_hold_messages = FALSE;
    
    /*CF_CLASS (folder)->refresh_info (folder, ex);*/
    
    if (camel_exception_is_set (ex)) {
        camel_object_unref (CAMEL_OBJECT (folder));
        return NULL;
    }
    
    return folder;
}

static void
imap_summary_free (GPtrArray **summary)
{
    CamelMessageInfo *info;
    GPtrArray *array = *summary;
    gint i, max;
    
    if (array) {
        max = array->len;
        for (i = 0; i < max; i++) {
            info = g_ptr_array_index (array, i);
            g_free (info->subject);
            g_free (info->from);
            g_free (info->to);
            g_free (info->cc);
            g_free (info->uid);
            g_free (info->message_id);
            header_references_list_clear (&info->references);
            g_free (info);
            info = NULL;
        }
        
        g_ptr_array_free (array, TRUE);
        *summary = NULL;
    }
}

static void
imap_folder_summary_free (CamelImapFolder *imap_folder)
{
    if (imap_folder->summary_hash) {
        g_hash_table_destroy (imap_folder->summary_hash);
        imap_folder->summary_hash = NULL;
    }
    
    imap_summary_free (&imap_folder->summary);
}

static void           
imap_finalize (CamelObject *object)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (object);
    gint max, i;
    
    imap_folder_summary_free (imap_folder);
    
    if (imap_folder->lsub) {
        max = imap_folder->lsub->len;
        
        for (i = 0; i < max; i++) {
            g_free (imap_folder->lsub->pdata[i]);
            imap_folder->lsub->pdata[i] = NULL;
        }
        
        g_ptr_array_free (imap_folder->lsub, TRUE);
    }
}

static void 
imap_init (CamelFolder *folder, CamelStore *parent_store, CamelFolder *parent_folder,
       const gchar *name, gchar *separator, gboolean path_begins_with_sep, CamelException *ex)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    
    /* call parent method */
    parent_class->init (folder, parent_store, parent_folder, name, separator, path_begins_with_sep, ex);
    if (camel_exception_get_id (ex))
        return;
    
    /* we assume that the parent init
       method checks for the existance of @folder */
    folder->can_hold_messages = TRUE;
    folder->can_hold_folders = TRUE;
    folder->has_summary_capability = TRUE;
    folder->has_search_capability = TRUE;
    
        /* some IMAP daemons support user-flags              *
     * I would not, however, rely on this feature as     *
     * most IMAP daemons do not support all the features */
    folder->permanent_flags = CAMEL_MESSAGE_SEEN |
        CAMEL_MESSAGE_ANSWERED |
        CAMEL_MESSAGE_FLAGGED |
        CAMEL_MESSAGE_DELETED |
        CAMEL_MESSAGE_DRAFT |
        CAMEL_MESSAGE_USER;
    
    imap_folder->search = NULL;
    imap_folder->summary = NULL;
    imap_folder->summary_hash = NULL;
    imap_folder->lsub = NULL;
}

static void
imap_refresh_info (CamelFolder *folder, CamelException *ex)
{
    imap_get_subfolder_names_internal (folder, ex);
    
    if (folder->can_hold_messages)
        imap_get_summary_internal (folder, ex);
}

static void
imap_sync (CamelFolder *folder, gboolean expunge, CamelException *ex)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    gint i, max;
    
    if (expunge) {
        imap_expunge (folder, ex);
        return;
    }
    
    /* Set the flags on any messages that have changed this session */
    if (imap_folder->summary) {
        max = imap_folder->summary->len;
        for (i = 0; i < max; i++) {
            CamelMessageInfo *info;
            
            info = (CamelMessageInfo *) g_ptr_array_index (imap_folder->summary, i);
            if (info->flags & CAMEL_MESSAGE_FOLDER_FLAGGED) {
                char *flags;
                
                flags = g_strconcat (info->flags & CAMEL_MESSAGE_SEEN ? "\\Seen " : "",
                             info->flags & CAMEL_MESSAGE_DRAFT ? "\\Draft " : "",
                             info->flags & CAMEL_MESSAGE_DELETED ? "\\Deleted " : "",
                             info->flags & CAMEL_MESSAGE_ANSWERED ? "\\Answered " : "",
                             NULL);
                if (*flags) {
                    gchar *result;
                    gint s;
                    
                    *(flags + strlen (flags) - 1) = '\0';
                    s = camel_imap_command_extended (CAMEL_IMAP_STORE (folder->parent_store),
                                     folder, &result, ex,
                                     "UID STORE %s FLAGS.SILENT (%s)",
                                     info->uid, flags);
                    
                    if (s != CAMEL_IMAP_OK)
                        return;
                    
                    g_free (result);
                }
                g_free (flags);
            }
        }
    }
}

static void
imap_expunge (CamelFolder *folder, CamelException *ex)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    gchar *node, *result;
    gint i, status, recent = -1;
    
    g_return_if_fail (folder != NULL);
    
    imap_sync (folder, FALSE, ex);
    
    status = camel_imap_command_extended (CAMEL_IMAP_STORE (folder->parent_store), folder, 
                          &result, ex, "EXPUNGE");
    
    if (status != CAMEL_IMAP_OK)
        return;
    
    /* determine which messages were successfully expunged */
    node = result;
    for (i = 0; node; i++) {
        char *word;
        
        if (*node != '*')
            break;
        
        word = imap_next_word (node);
        
        if (!strncmp (word, "NO", 2)) {
            /* Something failed, probably a Read-Only mailbox? */
            CamelService *service = CAMEL_SERVICE (folder->parent_store);
            char *reason, *ep;
            
            word = imap_next_word (word);
            for (ep = word; *ep && *ep != '\n'; ep++);
            reason = g_strndup (word, (gint)(ep - word));
            
            camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
                          "Could not EXPUNGE from IMAP server %s: %s.",
                          service->url->host, reason ? reason :
                          "Unknown error");
            
            g_free (reason);
            break;
        }
        
        /* else we have a message id? */
        if (*word >= '0' && *word <= '9' && !strncmp ("EXPUNGE", imap_next_word (word), 7)) {
            int id;
            
            id = atoi (word);
            
            d(fprintf (stderr, "Expunging message %d from the summary (i = %d)\n", id + i, i));
            
            if (id <= imap_folder->summary->len) {
                CamelMessageInfo *info;
                
                info = (CamelMessageInfo *) imap_folder->summary->pdata[id - 1];
                
                /* remove from the lookup table and summary */
                g_hash_table_remove (imap_folder->summary_hash, info->uid);
                g_ptr_array_remove_index (imap_folder->summary, id - 1);
                
                /* free the info data */
                g_free (info->subject);
                g_free (info->from);
                g_free (info->to);
                g_free (info->cc);
                g_free (info->uid);
                g_free (info->message_id);
                header_references_list_clear (&info->references);
                g_free (info);
                info = NULL;
            } else {
                /* Hopefully this should never happen */
                d(fprintf (stderr, "imap expunge-error: message %d is out of range\n", id));
            }
        } else if (*word >= '0' && *word <= '9' && !strncmp ("RECENT", imap_next_word (word), 6)) {
            recent = atoi (word);
            if (!recent)
                recent = -1;
        }
        
        for ( ; *node && *node != '\n'; node++);
        if (*node)
            node++;
    }
    
    g_free (result);
    
    camel_imap_folder_changed (folder, recent, NULL, ex);
}

static gint
imap_get_message_count_internal (CamelFolder *folder, CamelException *ex)
{
    CamelStore *store = CAMEL_STORE (folder->parent_store);
    CamelURL *url = CAMEL_SERVICE (store)->url;
    gchar *result, *msg_count, *folder_path, *dir_sep;
    gint status, count = 0;
    
    g_return_val_if_fail (folder != NULL, 0);
    g_return_val_if_fail (folder->can_hold_messages, 0);
    
    dir_sep = CAMEL_IMAP_STORE (folder->parent_store)->dir_sep;
    
    if (url && url->path && *(url->path + 1) && strcmp (folder->full_name, "INBOX"))
        folder_path = g_strdup_printf ("%s%s%s", url->path + 1, dir_sep, folder->full_name);
    else
        folder_path = g_strdup (folder->full_name);
    
    if (CAMEL_IMAP_STORE (store)->has_status_capability)
        status = camel_imap_command_extended (CAMEL_IMAP_STORE (store), folder,
                              &result, ex, "STATUS %s (MESSAGES)", folder_path);
    else
        status = camel_imap_command_extended (CAMEL_IMAP_STORE (store), folder,
                              &result, ex, "EXAMINE %s", folder_path);
    
    g_free (folder_path);
    
    if (status != CAMEL_IMAP_OK)
        return 0;
    
    /* parse out the message count */
    if (result && *result == '*') {
        if (CAMEL_IMAP_STORE (store)->has_status_capability) {
            /* should come in the form: "* STATUS <folder> (MESSAGES <count>)" */
            if ((msg_count = strstr (result, "MESSAGES")) != NULL) {
                msg_count = imap_next_word (msg_count);
            
                /* we should now be pointing to the message count */
                count = atoi (msg_count);
            }
        } else {
            /* should come in the form: "* <count> EXISTS" */
            if ((msg_count = strstr (result, "EXISTS")) != NULL) {
                for ( ; msg_count > result && *msg_count != '*'; msg_count--);
                
                msg_count = imap_next_word (msg_count);
                
                /* we should now be pointing to the message count */
                count = atoi (msg_count);
            }
        }
    }
    g_free (result);
    
    return count;
}

static gint
imap_get_message_count (CamelFolder *folder)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    
    if (imap_folder->summary)
        return imap_folder->summary->len;
    else
        return 0;
}

static gint
imap_get_unread_message_count (CamelFolder *folder)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    CamelMessageInfo *info;
    GPtrArray *infolist;
    gint i, count = 0;
    
    g_return_val_if_fail (folder != NULL, 0);
    
    /* If we don't have a message count, return 0 */
    if (!imap_folder->summary)
        return 0;
    
    infolist = imap_folder->summary;
    
    for (i = 0; i < infolist->len; i++) {
        info = (CamelMessageInfo *) g_ptr_array_index (infolist, i);
        if (!(info->flags & CAMEL_MESSAGE_SEEN))
            count++;
    }
    
    return count;
}

static void
imap_append_message (CamelFolder *folder, CamelMimeMessage *message, const CamelMessageInfo *info, CamelException *ex)
{
    CamelStore *store = CAMEL_STORE (folder->parent_store);
    CamelURL *url = CAMEL_SERVICE (store)->url;
    CamelStream *memstream;
    GByteArray *ba;
    gchar *result, *cmdid, *dir_sep;
    gchar *folder_path, *flagstr = NULL;
    gint status;
    
    g_return_if_fail (folder != NULL);
    g_return_if_fail (message != NULL);
        
    dir_sep = CAMEL_IMAP_STORE (folder->parent_store)->dir_sep;
    
    if (url && url->path && *(url->path + 1) && strcmp (folder->full_name, "INBOX"))
        folder_path = g_strdup_printf ("%s%s%s", url->path + 1, dir_sep, folder->full_name);
    else
        folder_path = g_strdup (folder->full_name);
    
    /* create flag string param */
    if (info && info->flags) {
        flagstr = g_strconcat (" (", info->flags & CAMEL_MESSAGE_SEEN ? "\\Seen " : "",
                       info->flags & CAMEL_MESSAGE_DRAFT ? "\\Draft " : "",
                       info->flags & CAMEL_MESSAGE_DELETED ? "\\Answered " : "",
                       NULL);
        if (flagstr)
            *(flagstr + strlen (flagstr) - 1) = ')';
    }
    
    ba = g_byte_array_new ();
    memstream = camel_stream_mem_new_with_byte_array (ba);
    /* FIXME: we need to crlf/dot filter */
    camel_data_wrapper_write_to_stream (CAMEL_DATA_WRAPPER (message), memstream);
    camel_stream_write_string (memstream, "\r\n");
    camel_stream_reset (memstream);
    
    status = camel_imap_command_preliminary (CAMEL_IMAP_STORE (folder->parent_store),
                         &cmdid, ex, "APPEND %s%s {%d}",
                         folder_path, flagstr ? flagstr : "", ba->len - 2);
    g_free (folder_path);
    
    if (status != CAMEL_IMAP_PLUS) {
        g_free (cmdid);
        return;
    }
    
    /* send the rest of our data - the mime message */
    status = camel_imap_command_continuation_with_stream (CAMEL_IMAP_STORE (folder->parent_store),
                                  &result, cmdid, memstream, ex);
    g_free (cmdid);
    
    if (status != CAMEL_IMAP_OK)
        return;
    
    g_free (result);
    
    camel_object_unref (CAMEL_OBJECT (memstream));
        camel_imap_folder_changed (folder, 1, NULL, ex);
}

static void
imap_copy_message_to (CamelFolder *source, const char *uid, CamelFolder *destination, CamelException *ex)
{
    CamelStore *store = CAMEL_STORE (source->parent_store);
    CamelURL *url = CAMEL_SERVICE (store)->url;
    char *result, *folder_path, *dir_sep;
    int status;
    
    dir_sep = CAMEL_IMAP_STORE (source->parent_store)->dir_sep;
    
    if (url && url->path && *(url->path + 1) && strcmp (destination->full_name, "INBOX"))
        folder_path = g_strdup_printf ("%s%s%s", url->path + 1, dir_sep, destination->full_name);
    else
        folder_path = g_strdup (destination->full_name);
    
    status = camel_imap_command_extended (CAMEL_IMAP_STORE (store), source, &result, ex,
                          "UID COPY %s %s", uid, folder_path);
    g_free (folder_path);
    
    if (status != CAMEL_IMAP_OK)
        return;
    
    g_free (result);
    
    camel_imap_folder_changed (destination, 1, NULL, ex);
}

/* FIXME: Duplication of code! */
static void
imap_move_message_to (CamelFolder *source, const char *uid, CamelFolder *destination, CamelException *ex)
{
    CamelStore *store = CAMEL_STORE (source->parent_store);
    CamelURL *url = CAMEL_SERVICE (store)->url;
    CamelMessageInfo *info;
    char *result, *folder_path, *dir_sep;
    int status;
    
    dir_sep = CAMEL_IMAP_STORE (source->parent_store)->dir_sep;
    
    if (url && url->path && *(url->path + 1) && strcmp (destination->full_name, "INBOX"))
        folder_path = g_strdup_printf ("%s%s%s", url->path + 1, dir_sep, destination->full_name);
    else
        folder_path = g_strdup (destination->full_name);
    
    status = camel_imap_command_extended (CAMEL_IMAP_STORE (store), source, &result, ex,
                          "UID COPY %s %s", uid, folder_path);
    g_free (folder_path);
    
    if (status != CAMEL_IMAP_OK)
        return;
    
    g_free (result);
    
    if (!(info = (CamelMessageInfo *)imap_get_message_info (source, uid))) {
        CamelService *service = CAMEL_SERVICE (store);
        
        camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
                      "Could not set flags for message %s on IMAP server %s: %s",
                      uid, service->url->host, "Unknown error");
        return;
    }
    
    imap_set_message_flags (source, uid, CAMEL_MESSAGE_DELETED, ~(info->flags));
    
    camel_imap_folder_changed (destination, 1, NULL, ex);
}

static GPtrArray *
imap_get_uids (CamelFolder *folder) 
{
    CamelMessageInfo *info;
    GPtrArray *array, *infolist;
    gint i, count;
    
    infolist = imap_get_summary (folder);
    
    count = infolist ? infolist->len : 0;
    
    array = g_ptr_array_new ();
    g_ptr_array_set_size (array, count);
    
    for (i = 0; i < count; i++) {
        info = (CamelMessageInfo *) g_ptr_array_index (infolist, i);
        array->pdata[i] = g_strdup (info->uid);
    }
    
    return array;
}

static GPtrArray *
imap_get_subfolder_names_internal (CamelFolder *folder, CamelException *ex)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    CamelStore *store = CAMEL_STORE (folder->parent_store);
    CamelURL *url = CAMEL_SERVICE (store)->url;
    GPtrArray *listing;
    gboolean found_inbox = FALSE;
    gint status;
    gchar *result, *namespace, *dir_sep;
    
    g_return_val_if_fail (folder != NULL, g_ptr_array_new ());
    
    dir_sep = CAMEL_IMAP_STORE (folder->parent_store)->dir_sep;
    
    if (url && url->path) {
        char *path = url->path + 1;
        
        if (*path) {
            if (!strcmp (folder->full_name, path))
                namespace = g_strdup (path);
            else if (!g_strcasecmp (folder->full_name, "INBOX"))
                namespace = g_strdup (path); /* FIXME: erm...not sure */
            else
                namespace = g_strdup_printf ("%s%s%s", path, dir_sep, folder->full_name);
        } else {
            if (!strcmp (folder->full_name, "/"))
                namespace = g_strdup ("");
            else
                namespace = g_strdup (folder->full_name);
        }
    } else {
        namespace = g_strdup (folder->full_name);
    }
    
    status = camel_imap_command_extended (CAMEL_IMAP_STORE (folder->parent_store), NULL,
                          &result, ex, "LIST \"\" \"%s%s*\"", namespace,
                          *namespace ? dir_sep : "");
    
    if (status != CAMEL_IMAP_OK) {
        g_free (namespace);
        
        imap_folder->lsub = g_ptr_array_new ();
        return imap_folder->lsub;
    }
    
    /* parse out the subfolders */
    listing = g_ptr_array_new ();
    if (result) {
        char *ptr = result;
        
        while (ptr && *ptr == '*') {
            gchar *flags, *sep, *dir, *buf, *end;
            
            for (end = ptr; *end && *end != '\n'; end++);
            buf = g_strndup (ptr, (gint)(end - ptr));
            ptr = end;
            
            if (!imap_parse_list_response (buf, namespace, &flags, &sep, &dir)) {
                g_free (buf);
                g_free (flags);
                g_free (sep);
                g_free (dir);
                
                if (*ptr == '\n')
                    ptr++;
                
                continue;
            }
            
            g_free (buf);
            g_free (flags);
            
            if (*dir) {
                d(fprintf (stderr, "adding folder: %s\n", dir));
                if (!g_strcasecmp (dir, "INBOX"))
                    found_inbox = TRUE;
                g_ptr_array_add (listing, dir);
            }
            
            g_free (sep);
            
            if (*ptr == '\n')
                ptr++;
        }
    }
    
    if (!strcmp (folder->name, namespace) && !found_inbox) {
        g_ptr_array_add (listing, g_strdup ("INBOX"));
    }
    
    g_free (result);
    g_free (namespace);
    
    imap_folder->lsub = listing;
    
    return listing;
}

static GPtrArray *
imap_get_subfolder_names (CamelFolder *folder)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    
    return imap_folder->lsub;
}

static CamelMimeMessage *
imap_get_message (CamelFolder *folder, const gchar *uid, CamelException *ex)
{
    CamelStream *msgstream = NULL;
    CamelMimeMessage *msg = NULL;
    gchar *result, *header, *body, *mesg, *p, *q, *data_item;
    int status, part_len;
    
    if (CAMEL_IMAP_STORE (folder->parent_store)->server_level >= IMAP_LEVEL_IMAP4REV1)
        data_item = "BODY.PEEK[HEADER]";
    else
        data_item = "RFC822.HEADER";
    
    status = camel_imap_fetch_command (CAMEL_IMAP_STORE (folder->parent_store), folder,
                       &result, ex, "UID FETCH %s %s", uid,
                       data_item);
    
    if (!result || status != CAMEL_IMAP_OK)
        return NULL;
    
    /* parse out the message part */
    for (p = result; *p && *p != '{' && *p != '"' && *p != '\n'; p++);
    switch (*p) {
    case '"':
        /* a quoted string - section 4.3 */
        p++;
        for (q = p; *q && *q != '"' && *q != '\n'; q++);
        part_len = (gint) (q - p);
        
        break;
    case '{':
        /* a literal string - section 4.3 */
        part_len = atoi (p + 1);
        for ( ; *p && *p != '\n'; p++);
        if (*p != '\n') {
            g_free (result);
            return NULL;
        }
        
        /* calculate the new part-length */
        for (q = p; *q && (q - p) <= part_len; q++) {
            if (*q == '\n')
                part_len--;
        }
        
        /* FIXME: This is a hack for IMAP daemons that send us a UID at the end of each FETCH */
        for ( ; q > p && *(q-1) != '\n'; q--, part_len--);
        part_len++;
        
        break;
    default:
        /* Bad input */
        g_free (result);
        return NULL;
    }
    
    header = g_strndup (p, part_len);
    
    g_free (result);
    d(fprintf (stderr, "*** We got the header ***\n"));
    
    if (CAMEL_IMAP_STORE (folder->parent_store)->server_level >= IMAP_LEVEL_IMAP4REV1)
        data_item = "BODY[TEXT]";
    else
        data_item = "RFC822.TEXT";
    
    status = camel_imap_fetch_command (CAMEL_IMAP_STORE (folder->parent_store), folder,
                       &result, ex, "UID FETCH %s %s", uid,
                       data_item);
    
    if (!result || status != CAMEL_IMAP_OK) {
        g_free (header);
        return NULL;
    }
    
    /* parse out the message part */
    for (p = result; *p && *p != '{' && *p != '"' && *p != '\n'; p++);
    switch (*p) {
    case '"':
        /* a quoted string - section 4.3 */
        p++;
        for (q = p; *q && *q != '"' && *q != '\n'; q++);
        part_len = (gint) (q - p);
        
        break;
    case '{':
        /* a literal string - section 4.3 */
        part_len = atoi (p + 1);
        for ( ; *p && *p != '\n'; p++);
        if (*p != '\n') {
            g_free (result);
            g_free (header);
            return NULL;
        }
        
        /* calculate the new part-length */
        for (q = p; *q && (q - p) <= part_len; q++) {
            if (*q == '\n')
                part_len--;
        }
        
        /* FIXME: This is a hack for IMAP daemons that send us a UID at the end of each FETCH */
        for ( ; q > p && *(q-1) != '\n'; q--, part_len--);
        part_len++;
        
        break;
    default:
        /* Bad input */
        g_free (result);
        g_free (header);
        return NULL;
    }
    
    body = g_strndup (p, part_len);
    
    g_free (result);
    d(fprintf (stderr, "*** We got the body ***\n"));
    
    mesg = g_strdup_printf ("%s\n%s", header, body);
    g_free (header);
    g_free (body);
    d(fprintf (stderr, "*** We got the mesg ***\n"));
    
    d(fprintf (stderr, "Message:\n%s\n", mesg));
    
    msgstream = camel_stream_mem_new_with_buffer (mesg, strlen (mesg) + 1);
#if 0
    f_stream = camel_stream_filter_new_with_stream (msgstream);
    filter = camel_mime_filter_crlf_new (CAMEL_MIME_FILTER_CRLF_DECODE, CAMEL_MIME_FILTER_CRLF_MODE_CRLF_DOTS);
    id = camel_stream_filter_add (f_stream, CAMEL_MIME_FILTER (filter));
#endif  
    msg = camel_mime_message_new ();
    d(fprintf (stderr, "*** We created the camel_mime_message ***\n"));
    
    camel_data_wrapper_construct_from_stream (CAMEL_DATA_WRAPPER (msg), msgstream);
#if 0   
    camel_stream_filter_remove (f_stream, id);
    camel_stream_close (CAMEL_STREAM (f_stream));
#endif
    camel_object_unref (CAMEL_OBJECT (msgstream));
    /*camel_object_unref (CAMEL_OBJECT (f_stream));*/
    
    d(fprintf (stderr, "*** We're returning... ***\n"));
    
    g_free (mesg);
    return msg;
}

/* This probably shouldn't go here...but it will for now */
static gchar *
get_header_field (gchar *header, gchar *field)
{
    gchar *part, *index, *p, *q;
    
    index = (char *) e_strstrcase (header, field);
    if (index == NULL)
        return NULL;
    
    p = index + strlen (field) + 1;
    for (q = p; *q; q++)
        if (*q == '\n' && (*(q + 1) != ' ' && *(q + 1) != '\t'))
            break;
    
    part = g_strndup (p, (gint)(q - p));
    
    /* it may be wrapped on multiple lines, so lets strip out \n's */
    for (p = part; *p; ) {
        if (*p == '\n')
            memmove (p, p + 1, strlen (p));
        else
            p++;
    }
    
    return part;
}

static char *header_fields[] = { "subject", "from", "to", "cc", "date",
                 "received", "message-id", "references",
                 "in-reply-to", "" };
/**
 * imap_protocol_get_summary_specifier
 *
 * Make a data item specifier for the header lines we need,
 * appropriate to the server level.
 *
 * IMAP4rev1:  UID FLAGS BODY.PEEK[HEADER.FIELDS (SUBJECT FROM .. IN-REPLY-TO)]
 * IMAP4:      UID FLAGS RFC822.HEADER.LINES (SUBJECT FROM .. IN-REPLY-TO)
 **/
static char *
imap_protocol_get_summary_specifier (CamelFolder *folder)
{
    char *sect_begin, *sect_end;
    char *headers_wanted = "SUBJECT FROM TO CC DATE MESSAGE-ID REFERENCES IN-REPLY-TO";
    
    if (CAMEL_IMAP_STORE (folder->parent_store)->server_level >= IMAP_LEVEL_IMAP4REV1) {
        sect_begin = "BODY.PEEK[HEADER.FIELDS";
        sect_end = "]";
    } else {
        sect_begin = "RFC822.HEADER.LINES";
        sect_end   = "";
    }
    
    return g_strdup_printf ("UID FLAGS %s (%s)%s", sect_begin, headers_wanted, sect_end);
}

static GPtrArray *
imap_get_summary_internal (CamelFolder *folder, CamelException *ex)
{
    /* This ALWAYS updates the summary except on fail */
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    GPtrArray *summary = NULL, *headers = NULL;
    GHashTable *hash = NULL;
    gint num, i, j, status = 0;
    char *result, *q, *node;
    const char *received;
    char *summary_specifier;
    struct _header_raw *h = NULL, *tail = NULL;
    
    num = imap_get_message_count_internal (folder, ex);
    
    /* sync any previously set/changed message flags */
    imap_sync (folder, FALSE, ex);
    
    if (num == 0) {
        /* clean up any previous summary data */
        imap_folder_summary_free (imap_folder);
        
        imap_folder->summary = g_ptr_array_new ();
        imap_folder->summary_hash = g_hash_table_new (g_str_hash, g_str_equal);
        
        return imap_folder->summary;
    }
    
    summary_specifier = imap_protocol_get_summary_specifier (folder);
    
    /* We use camel_imap_command_extended here because it's safe */
    if (num == 1) {
        status = camel_imap_command_extended (CAMEL_IMAP_STORE (folder->parent_store), folder,
                              &result, ex, "FETCH 1 (%s)", summary_specifier);
    } else {
        status = camel_imap_command_extended (CAMEL_IMAP_STORE (folder->parent_store), folder,
                              &result, ex, "FETCH 1:%d (%s)", num, summary_specifier);
    }
    g_free (summary_specifier);
    
    if (status != CAMEL_IMAP_OK) {
        if (!imap_folder->summary) {
            imap_folder->summary = g_ptr_array_new ();
            imap_folder->summary_hash = g_hash_table_new (g_str_hash, g_str_equal);
        }
        
        return imap_folder->summary;
    }
    
    /* initialize our new summary-to-be */
    summary = g_ptr_array_new ();
    hash = g_hash_table_new (g_str_hash, g_str_equal);
    
    /* create our array of headers from the server response */
    headers = g_ptr_array_new ();
    node = result;
    for (i = 1; node; i++) {
        char *end;
        
        if ((end = strstr (node + 2, "\n*"))) {
            g_ptr_array_add (headers, g_strndup (node, (gint)(end - node)));
        } else {
            g_ptr_array_add (headers, g_strdup (node));
        }
        node = end;
    }
    if (i < num) {
        d(fprintf (stderr, "IMAP server didn't respond with as many headers as we expected...\n"));
        /* should we error?? */
    }
    
    g_free (result);
    result = NULL;
    
    for (i = 0; i < headers->len; i++) {
        CamelMessageInfo *info;
        char *uid, *flags, *header;
        
        info = g_malloc0 (sizeof (CamelMessageInfo));
        
        /* lets grab the UID... */
        if (!(uid = strstr (headers->pdata[i], "UID "))) {
            d(fprintf (stderr, "Cannot get a uid for %d\n\n%s\n\n", i+1, (char *) headers->pdata[i]));
            g_free (info);
            break;
        }
        
        for (uid += 4; *uid && (*uid < '0' || *uid > '9'); uid++); /* advance to <uid> */
        for (q = uid; *q && *q >= '0' && *q <= '9'; q++); /* find the end of the <uid> */
        info->uid = g_strndup (uid, (gint)(q - uid));
        /*d(fprintf (stderr, "*** info->uid = %s\n", info->uid));*/
        
        /* now lets grab the FLAGS */
        if (!(flags = strstr (headers->pdata[i], "FLAGS "))) {
            d(fprintf (stderr, "We didn't seem to get any flags for %d...\n", i));
            g_free (info->uid);
            g_free (info);
            break;
        }
        
        for (flags += 6; *flags && *flags != '('; flags++); /* advance to <flags> */
        for (q = flags; *q && *q != ')'; q++);         /* find the end of <flags> */
        flags = g_strndup (flags, (gint)(q - flags + 1));
        /*d(fprintf (stderr, "*** info->flags = %s\n", flags));*/
        
        /* now we gotta parse for the flags */
        info->flags = 0;
        if (strstr (flags, "\\Seen"))
            info->flags |= CAMEL_MESSAGE_SEEN;
        if (strstr (flags, "\\Answered"))
            info->flags |= CAMEL_MESSAGE_ANSWERED;
        if (strstr (flags, "\\Flagged"))
            info->flags |= CAMEL_MESSAGE_FLAGGED;
        if (strstr (flags, "\\Deleted"))
            info->flags |= CAMEL_MESSAGE_DELETED;
        if (strstr (flags, "\\Draft"))
            info->flags |= CAMEL_MESSAGE_DRAFT;
        g_free (flags);
        flags = NULL;
        
        /* construct the header list */
        /* fast-forward to beginning of header info... */
        for (header = headers->pdata[i]; *header && *header != '\n'; header++);
        h = NULL;
        for (j = 0; *header_fields[j]; j++) {
            struct _header_raw *raw;
            char *field, *value;
            
            field = g_strdup_printf ("\n%s:", header_fields[j]);
            value = get_header_field (header, field);
            g_free (field);
            if (!value)
                continue;
            
            raw = g_malloc0 (sizeof (struct _header_raw));
            raw->next = NULL;
            raw->name = g_strdup (header_fields[j]);
            raw->value = value;
            raw->offset = -1;
            
            if (!h) {
                h = raw;
                tail = h;
            } else {
                tail->next = raw;
                tail = raw;
            }
        }
        
        /* construct the CamelMessageInfo */
        info->subject = camel_summary_format_string (h, "subject");
        info->from = camel_summary_format_address (h, "from");
        info->to = camel_summary_format_address (h, "to");
        info->cc = camel_summary_format_address (h, "cc");
        info->user_flags = NULL;
        info->date_sent = header_decode_date (header_raw_find (&h, "date", NULL), NULL);
        received = header_raw_find (&h, "received", NULL);
        if (received)
            received = strrchr (received, ';');
        if (received)
            info->date_received = header_decode_date (received + 1, NULL);
        else
            info->date_received = 0;
        info->message_id = header_msgid_decode (header_raw_find (&h, "message-id", NULL));
        /* if we have a references, use that, otherwise, see if we have an in-reply-to
           header, with parsable content, otherwise *shrug* */
        info->references = header_references_decode (header_raw_find (&h, "references", NULL));
        if (info->references == NULL)
            info->references = header_references_decode (header_raw_find (&h, "in-reply-to", NULL));
        
        while (h) {
            struct _header_raw *next = h->next;
            
            g_free (h->name);
            g_free (h->value);
            g_free (h);
            h = next;
        }
        
        g_ptr_array_add (summary, info);
        g_hash_table_insert (hash, info->uid, info);
    }
    
    for (i = 0; i < headers->len; i++)
        g_free (headers->pdata[i]);
    g_ptr_array_free (headers, TRUE);
    
    /* clean up any previous summary data */
    imap_folder_summary_free (imap_folder);
    
    imap_folder->summary = summary;
    imap_folder->summary_hash = hash;
    
    return imap_folder->summary;
}

static GPtrArray *
imap_get_summary (CamelFolder *folder)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    
    return imap_folder->summary;
}

/* get a single message info from the server */
static CamelMessageInfo *
imap_get_message_info_internal (CamelFolder *folder, guint id, CamelException *ex)
{
    CamelMessageInfo *info = NULL;
    struct _header_raw *h, *tail = NULL;
    const char *received;
    char *result, *uid, *flags, *header, *q;
    char *summary_specifier;
    int j, status;
    
    /* we don't have a cached copy, so fetch it */
    summary_specifier = imap_protocol_get_summary_specifier (folder);
    
    /* again, we use camel_imap_command_extended here because it's safe to do so */
    status = camel_imap_command_extended (CAMEL_IMAP_STORE (folder->parent_store), folder,
                          &result, ex, "FETCH %d (%s)", id, summary_specifier);
    
    g_free (summary_specifier);
    
    if (status != CAMEL_IMAP_OK)
        return NULL;
    
    /* lets grab the UID... */
    if (!(uid = (char *) e_strstrcase (result, "UID "))) {
        d(fprintf (stderr, "Cannot get a uid for %d\n\n%s\n\n", id, result));
        g_free (result);
        return NULL;
    }
        
    for (uid += 4; *uid && (*uid < '0' || *uid > '9'); uid++); /* advance to <uid> */
    for (q = uid; *q && *q >= '0' && *q <= '9'; q++); /* find the end of the <uid> */
    uid = g_strndup (uid, (gint)(q - uid));
    
    info = g_malloc0 (sizeof (CamelMessageInfo));
    info->uid = uid;
    d(fprintf (stderr, "*** info->uid = %s\n", info->uid));
    
    /* now lets grab the FLAGS */
    if (!(flags = strstr (q, "FLAGS "))) {
        d(fprintf (stderr, "We didn't seem to get any flags for %s...\n", uid));
        g_free (info->uid);
        g_free (info);
        g_free (result);
        return NULL;
    }
    
    for (flags += 6; *flags && *flags != '('; flags++); /* advance to <flags> */
    for (q = flags; *q && *q != ')'; q++);              /* find the end of <flags> */
    flags = g_strndup (flags, (gint)(q - flags + 1));
    d(fprintf (stderr, "*** info->flags = %s\n", flags));
    
    /* now we gotta parse for the flags */
    info->flags = 0;
    if (strstr (flags, "\\Seen"))
        info->flags |= CAMEL_MESSAGE_SEEN;
    if (strstr (flags, "\\Answered"))
        info->flags |= CAMEL_MESSAGE_ANSWERED;
    if (strstr (flags, "\\Flagged"))
        info->flags |= CAMEL_MESSAGE_FLAGGED;
    if (strstr (flags, "\\Deleted"))
        info->flags |= CAMEL_MESSAGE_DELETED;
    if (strstr (flags, "\\Draft"))
        info->flags |= CAMEL_MESSAGE_DRAFT;
    g_free (flags);
    flags = NULL;
    
    /* construct the header list */
    /* fast-forward to beginning of header info... */
    for (header = q; *header && *header != '\n'; header++);
    h = NULL;
    for (j = 0; *header_fields[j]; j++) {
        struct _header_raw *raw;
        char *field, *value;
        
        field = g_strdup_printf ("\n%s:", header_fields[j]);
        value = get_header_field (header, field);
        g_free (field);
        if (!value)
            continue;
        
        raw = g_malloc0 (sizeof (struct _header_raw));
        raw->next = NULL;
        raw->name = g_strdup (header_fields[j]);
        raw->value = value;
        raw->offset = -1;
        
        if (!h) {
            h = raw;
            tail = h;
        } else {
            tail->next = raw;
            tail = raw;
        }
    }
    
    /* construct the CamelMessageInfo */
    info->subject = camel_summary_format_string (h, "subject");
    info->from = camel_summary_format_address (h, "from");
    info->to = camel_summary_format_address (h, "to");
    info->cc = camel_summary_format_address (h, "cc");
    info->user_flags = NULL;
    info->date_sent = header_decode_date (header_raw_find (&h, "date", NULL), NULL);
    received = header_raw_find (&h, "received", NULL);
    if (received)
        received = strrchr (received, ';');
    if (received)
        info->date_received = header_decode_date (received + 1, NULL);
    else
        info->date_received = 0;
    info->message_id = header_msgid_decode (header_raw_find (&h, "message-id", NULL));
    /* if we have a references, use that, otherwise, see if we have an in-reply-to
       header, with parsable content, otherwise *shrug* */
    info->references = header_references_decode (header_raw_find (&h, "references", NULL));
    if (info->references == NULL)
        info->references = header_references_decode (header_raw_find (&h, "in-reply-to", NULL));
    
    while (h->next) {
        struct _header_raw *next = h->next;
        
        g_free (h->name);
        g_free (h->value);
        g_free (h);
        h = next;
    }
    
    g_free (result);
    
    return info;
}

/* get a single message info, by uid */
static const CamelMessageInfo *
imap_get_message_info (CamelFolder *folder, const char *uid)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    
    g_return_val_if_fail (*uid != '\0', NULL);
    
    if (imap_folder->summary)
        return (CamelMessageInfo *) g_hash_table_lookup (imap_folder->summary_hash, uid);
    
    return NULL;
}

static GPtrArray *
imap_search_by_expression (CamelFolder *folder, const char *expression, CamelException *ex)
{
    GPtrArray *uids = NULL;
    char *result, *sexp, *p;
    int status;
    
    d(fprintf (stderr, "camel sexp: '%s'\n", expression));
    sexp = imap_translate_sexp (expression);
    d(fprintf (stderr, "imap sexp: '%s'\n", sexp));
    
    uids = g_ptr_array_new ();
    
    if (!folder->has_search_capability) {
        g_free (sexp);
        return uids;
    }
    
    status = camel_imap_command_extended (CAMEL_IMAP_STORE (folder->parent_store), folder,
                          &result, ex, "UID SEARCH %s", sexp);
    
    if (status != CAMEL_IMAP_OK) {
        g_free (sexp);
        return uids;
    }
    
    if ((p = strstr (result, "* SEARCH"))) {
        char *word;
        
        word = imap_next_word (p); /* word now points to SEARCH */
        
        for (word = imap_next_word (word); *word && *word != '*'; word = imap_next_word (word)) {
            gboolean word_is_numeric = TRUE;
            char *ep;
            
            /* find the end of this word and make sure it's a numeric uid */
            for (ep = word; *ep && *ep != ' ' && *ep != '\n'; ep++)
                if (*ep < '0' || *ep > '9')
                    word_is_numeric = FALSE;
            
            if (word_is_numeric)
                g_ptr_array_add (uids, g_strndup (word, (gint)(ep - word)));
        }
    }
    
    g_free (result);
    g_free (sexp);
    
    return uids;
}

#if 0
static guint32
imap_get_permanent_flags (CamelFolder *folder, CamelException *ex)
{
    /* return permamnant flags */
    return folder->permanent_flags;
}
#endif

static guint32
imap_get_message_flags (CamelFolder *folder, const char *uid)
{
    const CamelMessageInfo *info;
    
    info = imap_get_message_info (folder, uid);
    g_return_val_if_fail (info != NULL, 0);
    
    return info->flags;
}

static void
imap_set_message_flags (CamelFolder *folder, const char *uid, guint32 flags, guint32 set)
{
    CamelMessageInfo *info;
    
    info = (CamelMessageInfo*)imap_get_message_info (folder, uid);
    g_return_if_fail (info != NULL);
    
    info->flags = (info->flags & ~flags) | (set & flags) | CAMEL_MESSAGE_FOLDER_FLAGGED;
    
    /*gtk_signal_emit_by_name (GTK_OBJECT (folder), "message_changed", uid);*/
    camel_object_trigger_event (CAMEL_OBJECT (folder), "message_changed", (gpointer *) uid);
}

static gboolean
imap_get_message_user_flag (CamelFolder *folder, const char *uid, const char *name)
{
    return FALSE;
}

static void
imap_set_message_user_flag (CamelFolder *folder, const char *uid, const char *name, gboolean value)
{
    /*gtk_signal_emit_by_name (GTK_OBJECT (folder), "message_changed", uid);*/
    camel_object_trigger_event (CAMEL_OBJECT (folder), "message_changed", (gpointer *) uid);
}

void
camel_imap_folder_changed (CamelFolder *folder, gint recent, GPtrArray *expunged, CamelException *ex)
{
    CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
    
    if (expunged) {
        gint i, id;
        
        for (i = 0; i < expunged->len; i++) {
            id = atoi (expunged->pdata[i]);
            d(fprintf (stderr, "Expunging message %d from the summary (i = %d)\n", id + i, i));
            
            if (id <= imap_folder->summary->len) {
                CamelMessageInfo *info;
                
                info = (CamelMessageInfo *) imap_folder->summary->pdata[id - 1];
                
                /* remove from the lookup table and summary */
                g_hash_table_remove (imap_folder->summary_hash, info->uid);
                g_ptr_array_remove_index (imap_folder->summary, id - 1);
                
                /* free the info data */
                g_free (info->subject);
                g_free (info->from);
                g_free (info->to);
                g_free (info->cc);
                g_free (info->uid);
                g_free (info->message_id);
                header_references_list_clear (&info->references);
                g_free (info);
                info = NULL;
            } else {
                /* Hopefully this should never happen */
                d(fprintf (stderr, "imap expunge-error: message %d is out of range\n", id));
            }
        }
    }
    
    if (recent > 0) {
        CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
        CamelMessageInfo *info;
        gint i, j, last, slast;
        
        if (!imap_folder->summary) {
            imap_folder->summary = g_ptr_array_new ();
            imap_folder->summary_hash = g_hash_table_new (g_str_hash, g_str_equal);
        }
        
        last = imap_folder->summary->len + 1;
        slast = imap_get_message_count_internal (folder, ex);
        fprintf (stderr, "calculated next message is: %d\n", last);
        fprintf (stderr, "server says %d mesgs total\n", slast);
        slast -= (recent - 1);
        fprintf (stderr, "based on total, new guess is: %d\n", slast);
        
        for (i = slast, j = 0; j < recent; i++, j++) {
            info = imap_get_message_info_internal (folder, i, ex);
            if (info) {
                if (!imap_get_message_info (folder, info->uid)) {
                    /* add to our summary */
                    g_ptr_array_add (imap_folder->summary, info);
                    g_hash_table_insert (imap_folder->summary_hash, info->uid, info);
                } else {
                    /* we already have a record of it */
                    g_free (info->subject);
                    g_free (info->from);
                    g_free (info->to);
                    g_free (info->cc);
                    g_free (info->uid);
                    g_free (info->message_id);
                    header_references_list_clear (&info->references);
                    g_free (info);
                    info = NULL;
                    d(fprintf (stderr, "we already had message %d!!\n", i));
                }
            } else {
                /* our hack failed so now we need to do it the old fashioned way */
                /*imap_get_summary_internal (folder, ex);*/
                d(fprintf (stderr, "*** we tried to get message %d but failed\n", i));
                break;
            }
        }
    }
    
    /*gtk_signal_emit_by_name (GTK_OBJECT (folder), "folder_changed", 0);*/
    camel_object_trigger_event (CAMEL_OBJECT (folder), "folder_changed", GINT_TO_POINTER (0));
}