-
Notifications
You must be signed in to change notification settings - Fork 270
/
SOGoMailFolder.m
2434 lines (2062 loc) · 74.3 KB
/
SOGoMailFolder.m
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
/*
Copyright (C) 2009-2021 Inverse inc.
Copyright (C) 2004-2005 SKYRIX Software AG
This file is part of SOGo.
SOGo is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.
SOGo 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 Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public
License along with OGo; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSValue.h>
#import <Foundation/NSFileHandle.h>
#import <NGObjWeb/NSException+HTTP.h>
#import <NGObjWeb/WOContext+SoObjects.h>
#import <NGExtensions/NSNull+misc.h>
#import <NGExtensions/NSURL+misc.h>
#import <NGExtensions/NSObject+Logs.h>
#import <NGExtensions/NSString+misc.h>
#import <NGExtensions/NSFileManager+Extensions.h>
#import <NGExtensions/NGHashMap.h>
#import <NGExtensions/NSCalendarDate+misc.h>
#import <SaxObjC/XMLNamespaces.h>
#import <EOControl/EOSortOrdering.h>
#import <NGMime/NGMimeBodyPart.h>
#import <NGMime/NGMimeFileData.h>
#import <NGMime/NGMimeMultipartBody.h>
#import <NGMail/NGMimeMessage.h>
#import <NGMail/NGMimeMessageGenerator.h>
#import <NGImap4/NGImap4Connection.h>
#import <NGImap4/NGImap4Client.h>
#import <NGImap4/NSString+Imap4.h>
#import <SOGo/DOMNode+SOGo.h>
#import <SOGo/NSArray+Utilities.h>
#import <SOGo/NSCalendarDate+SOGo.h>
#import <SOGo/SOGoDAVAuthenticator.h>
#import <SOGo/NSDictionary+Utilities.h>
#import <SOGo/NSString+Utilities.h>
#import <SOGo/NSString+DAV.h>
#import <SOGo/NSArray+DAV.h>
#import <SOGo/NSObject+DAV.h>
#import <SOGo/SOGoPermissions.h>
#import <SOGo/SOGoSystemDefaults.h>
#import <SOGo/SOGoUser.h>
#import <SOGo/SOGoUserFolder.h>
#import <SOGo/SOGoUserManager.h>
#import <SOGo/SOGoUserSettings.h>
#import <SOGo/WORequest+SOGo.h>
#import <SOGo/WOResponse+SOGo.h>
#import <SOGo/SOGoMailer.h>
#import <SOGo/SOGoZipArchiver.h>
#import "EOQualifier+MailDAV.h"
#import "SOGoMailAccount.h"
#import "SOGoMailAccounts.h"
#import "SOGoTrashFolder.h"
#import "SOGoMailObject+Draft.h"
#define XMLNS_INVERSEDAV @"urn:inverse:params:xml:ns:inverse-dav"
static NSString *defaultUserID = @"anyone";
static NSComparisonResult _compareFetchResultsByMODSEQ (id entry1, id entry2, void *data)
{
static NSNumber *zeroNumber = nil;
NSNumber *modseq1, *modseq2;
if (!zeroNumber)
{
zeroNumber = [NSNumber numberWithUnsignedLongLong: 0];
[zeroNumber retain];
}
modseq1 = [entry1 objectForKey: @"modseq"];
if (!modseq1)
modseq1 = zeroNumber;
modseq2 = [entry2 objectForKey: @"modseq"];
if (!modseq2)
modseq2 = zeroNumber;
return [modseq1 compare: modseq2];
}
static NSInteger _compareFetchResultsByUID (id entry1, id entry2, NSArray *uids)
{
NSString *uid1, *uid2;
NSUInteger pos1, pos2;
uid1 = [entry1 objectForKey: @"uid"];
uid2 = [entry2 objectForKey: @"uid"];
pos1 = [uids indexOfObject: uid1];
pos2 = [uids indexOfObject: uid2];
if (pos1 > pos2)
return NSOrderedDescending;
else
return NSOrderedAscending;
}
@interface NGImap4Connection (PrivateMethods)
- (NSString *) imap4FolderNameForURL: (NSURL *) url;
@end
@implementation SOGoMailFolder
- (BOOL) _path: (NSString *) path
isInNamespaces: (NSArray *) namespaces
{
int count, max;
BOOL rc;
rc = NO;
max = [namespaces count];
for (count = 0; !rc && count < max; count++)
rc = [path hasPrefix: [namespaces objectAtIndex: count]];
return rc;
}
- (void) _adjustOwner
{
SOGoMailAccount *mailAccount;
NSString *path;
NSArray *names;
mailAccount = [self mailAccountFolder];
path = [[self imap4Connection] imap4FolderNameForURL: [self imap4URL]];
if ([self _path: path
isInNamespaces: [mailAccount sharedFolderNamespaces]])
[self setOwner: @"nobody"];
else if ([self _path: path
isInNamespaces: [mailAccount otherUsersFolderNamespaces]])
{
names = [path componentsSeparatedByString: @"/"];
if ([names count] > 1)
[self setOwner: [names objectAtIndex: 1]];
else
[self setOwner: @"nobody"];
}
}
- (id) initWithName: (NSString *) newName
inContainer: (id) newContainer
{
if ((self = [super initWithName: newName
inContainer: newContainer]))
{
[self _adjustOwner];
mailboxACL = nil;
prefetchedInfos = nil;
}
return self;
}
- (void) dealloc
{
[filenames release];
[folderType release];
[mailboxACL release];
[prefetchedInfos release];
[super dealloc];
}
/* IMAP4 */
- (NSString *) relativeImap4Name
{
return [[nameInContainer substringFromIndex: 6] fromCSSIdentifier];
}
- (NSString *) absoluteImap4Name
{
NSString *name;
name = [[self imap4URL] path];
if (![name hasSuffix: @"/"])
name = [name stringByAppendingString: @"/"];
return name;
}
- (NSMutableString *) imap4URLString
{
NSMutableString *urlString;
urlString = [super imap4URLString];
[urlString appendString: @"/"];
return urlString;
}
/* listing the available folders */
- (NSArray *) toManyRelationshipKeys
{
NSArray *subfolders;
subfolders = [[self subfolders] resultsOfSelector: @selector (asCSSIdentifier)];
return [subfolders stringsWithFormat: @"folder%@"];
}
- (NSArray *) subfolders
{
return [[self imap4Connection] subfoldersForURL: [self imap4URL]];
}
- (BOOL) isSpecialFolder
{
return NO;
}
- (NSArray *) allFolderPaths
{
NSMutableArray *deepSubfolders;
NSEnumerator *folderNames;
NSArray *result;
NSString *currentFolderName, *prefix;
deepSubfolders = [NSMutableArray array];
prefix = [self absoluteImap4Name];
result = [[self mailAccountFolder] allFolderPaths: SOGoMailStandardListing];
folderNames = [result objectEnumerator];
while ((currentFolderName = [folderNames nextObject]))
if ([currentFolderName hasPrefix: prefix])
[deepSubfolders addObject: currentFolderName];
[deepSubfolders sortUsingSelector: @selector (compare:)];
return deepSubfolders;
}
- (NSArray *) allFolderURLs
{
NSURL *selfURL, *currentURL;
NSMutableArray *subfoldersURL;
NSEnumerator *subfolders;
NSString *currentFolder;
subfoldersURL = [NSMutableArray array];
selfURL = [self imap4URL];
subfolders = [[self allFolderPaths] objectEnumerator];
currentFolder = [subfolders nextObject];
while (currentFolder)
{
currentURL = [[NSURL alloc]
initWithScheme: [selfURL scheme]
host: [selfURL host]
path: currentFolder];
[currentURL autorelease];
[subfoldersURL addObject: currentURL];
currentFolder = [subfolders nextObject];
}
return subfoldersURL;
}
- (NSString *) davContentType
{
return @"httpd/unix-directory";
}
- (NSArray *) toOneRelationshipKeys
{
NSArray *uids;
unsigned int count, max;
NSString *filename;
if (!filenames)
{
filenames = [NSMutableArray new];
if ([self exists])
{
uids = [self fetchUIDsMatchingQualifier: nil sortOrdering: @"DATE"];
if (![uids isKindOfClass: [NSException class]])
{
max = [uids count];
for (count = 0; count < max; count++)
{
filename = [NSString stringWithFormat: @"%@.eml",
[uids objectAtIndex: count]];
[filenames addObject: filename];
}
}
}
}
return filenames;
}
- (NSException *) renameTo: (NSString *) theNewName
{
NSException *error;
SOGoMailFolder *inbox;
NSString *path, *newName, *destName;
NGImap4Client *client;
if ([theNewName length] > 0)
{
[self imap4URL];
if ([self imap4Connection])
{
client = [imap4 client];
inbox = [[self mailAccountFolder] inboxFolderInContext: context];
[client select: [inbox absoluteImap4Name]];
path = [[imap4URL path] stringByDeletingLastPathComponent];
if (![path hasSuffix: @"/"])
path = [path stringByAppendingString: @"/"];
newName = [theNewName stringByEncodingImap4FolderName];
// If new name contains the path - dont't need to add
if ([newName rangeOfString: @"/"].location == NSNotFound)
destName = [NSString stringWithFormat: @"%@%@",
path, newName];
else
destName = newName;
error = [imap4 moveMailbox: [imap4URL path]
to: destName];
if (!error)
{
// We unsubscribe to the old one, and subscribe back to the new one
[client subscribe: destName];
[client unsubscribe: [imap4URL path]];
ASSIGN (imap4URL, nil);
ASSIGN (nameInContainer,
([NSString stringWithFormat: @"folder%@", [newName asCSSIdentifier]]));
}
}
else
error = [NSException exceptionWithName: @"SOGoMailException"
reason: @"IMAP connection is invalid"
userInfo: nil];
}
else
error = [NSException exceptionWithName: @"SOGoMailException"
reason: @"given name is empty"
userInfo: nil];
return error;
}
/* messages */
- (void) prefetchCoreInfosForMessageKeys: (NSArray *) keys
{
NSUInteger count, max, keyLength;
NSMutableArray *uids;
NSDictionary *infos;
NSArray *allValues;
NSString *key;
if (!SOGoMailCoreInfoKeys)
{
/* ensure SOGoMailCoreInfoKeys is initialized */
[SOGoMailObject class];
}
[prefetchedInfos release];
max = [keys count];
if (max > 0)
{
uids = [NSMutableArray arrayWithCapacity: max];
for (count = 0; count < max; count++)
{
key = [keys objectAtIndex: count];
if ([key hasSuffix: @".eml"])
{
keyLength = [key length];
[uids addObject: [key substringToIndex: keyLength - 4]];
}
else
[uids addObject: key];
}
infos = (NSDictionary *) [self fetchUIDs: uids parts: SOGoMailCoreInfoKeys];
prefetchedInfos = [[NSMutableDictionary alloc] initWithCapacity: max];
// We MUST NOT use setObjects:forKeys here as the fetch's array does NOT
// necessarily have the same order!
allValues = [infos objectForKey: @"fetch"];
max = [allValues count];
for (count = 0; count < max ; count++)
{
infos = [allValues objectAtIndex: count];
key = [NSString stringWithFormat: @"%@", [infos objectForKey: @"uid"]];
[prefetchedInfos setObject: infos forKey: key];
}
}
else
prefetchedInfos = nil;
}
- (NSException *) deleteUIDs: (NSArray *) uids
useTrashFolder: (BOOL *) withTrash
inContext: (id) localContext
{
SOGoMailFolder *trashFolder;
NGImap4Client *client;
NSString *folderName;
NSException *error;
NSString *result;
BOOL b;
client = nil;
trashFolder = nil;
b = YES;
if (*withTrash)
{
trashFolder = [[self mailAccountFolder] trashFolderInContext: localContext];
b = NO;
if ([trashFolder isNotNull])
{
if ([trashFolder isKindOfClass: [NSException class]])
error = (NSException *) trashFolder;
else
{
if ([self imap4Connection])
{
error = nil;
client = [imap4 client];
[imap4 selectFolder: [self imap4URL]];
folderName = [imap4 imap4FolderNameForURL: [trashFolder imap4URL]];
b = YES;
// If we are deleting messages within the Trash folder itself, we
// do not, of course, try to move messages to the Trash folder.
if ([folderName isEqualToString: [imap4 imap4FolderNameForURL: [self imap4URL]]])
{
*withTrash = NO;
}
else
{
// If our Trash folder doesn't exist when we try to copy messages
// to it, we create it.
b = [self ensureTrashFolder];
if (b)
{
result = [[client copyUids: uids toFolder: folderName]
objectForKey: @"result"];
b = [result boolValue];
}
}
}
else
error = [NSException exceptionWithName: @"SOGoMailException"
reason: @"IMAP connection is invalid"
userInfo: nil];
}
}
else
error = [NSException exceptionWithHTTPStatus: 500
reason: @"Did not find Trash folder!"];
}
if (b)
{
if (client == nil)
{
client = [[self imap4Connection] client];
[imap4 selectFolder: [self imap4URL]];
}
result = [[client storeFlags: [NSArray arrayWithObject: @"Deleted"]
forUIDs: uids addOrRemove: YES]
objectForKey: @"result"];
if ([result boolValue])
{
if (*withTrash)
{
[self markForExpunge];
if (trashFolder)
[trashFolder flushMailCaches];
error = nil;
}
else
{
// When not using a trash folder, expunge the current folder
// immediately
error = [self expunge];
}
}
else
error
= [NSException exceptionWithHTTPStatus:500
reason: @"Could not mark UIDs as Deleted"];
}
else
error = [NSException exceptionWithHTTPStatus:500
reason: @"Could not copy UIDs"];
return error;
}
- (WOResponse *) archiveUIDs: (NSArray *) uids
inArchiveNamed: (NSString *) archiveName
inContext: (id) localContext
{
NSException *error;
NSFileManager *fm;
NSString *spoolPath, *fileName, *baseName, *extension, *zipPath, *qpFileName;
NSDictionary *msgs;
NSArray *messages;
NSData *content, *zipContent;
WOResponse *response;
SOGoZipArchiver *archiver;
NSFileHandle *zipFileHandle;
int i;
if (!archiveName)
archiveName = @"SavedMessages.zip";
spoolPath = [self userSpoolFolderPath];
if (![self ensureSpoolFolderPath])
{
[self errorWithFormat: @"spool directory '%@' doesn't exist", spoolPath];
error = [NSException exceptionWithHTTPStatus: 500
reason: @"spool directory does not exist"];
return (WOResponse *)error;
}
fm = [NSFileManager defaultManager];
zipPath = [NSString stringWithFormat: @"%@/%@", spoolPath, archiveName];
archiver = [SOGoZipArchiver archiverAtPath: zipPath];
if (archiver == nil) {
[self errorWithFormat: @"Failed to create zip archive at %@", spoolPath];
error = [NSException exceptionWithHTTPStatus: 500
reason: @"Internal server error"];
return (WOResponse *)error;
}
msgs = (NSDictionary *)[self fetchUIDs: uids
parts: [NSArray arrayWithObject: @"BODY.PEEK[]"]];
messages = [msgs objectForKey: @"fetch"];
for (i = 0; i < [messages count]; i++)
{
content = [[[messages objectAtIndex: i] objectForKey: @"body[]"] objectForKey: @"data"];
fileName = [NSString stringWithFormat:@"%@.eml", [uids objectAtIndex: i]];
[archiver putFileWithName: fileName andData: content];
}
[archiver close];
response = [context response];
// Check if SOPE has support for serving files directly
if ([response respondsToSelector: @selector(setContentFile:)]) {
zipFileHandle = [NSFileHandle fileHandleForReadingAtPath: zipPath];
[response setContentFile: zipFileHandle];
} else {
zipContent = [[NSData alloc] initWithContentsOfFile:zipPath];
[response setContent:zipContent];
[zipContent release];
}
[fm removeFileAtPath: zipPath handler: nil];
baseName = [archiveName stringByDeletingPathExtension];
extension = [archiveName pathExtension];
if ([extension length] > 0)
extension = [@"." stringByAppendingString: extension];
else
extension = @"";
qpFileName = [NSString stringWithFormat: @"%@%@",
[baseName asQPSubjectString: @"utf-8"],
extension];
[response setHeader: [NSString stringWithFormat: @"application/zip;"
@" name=\"%@\"",
qpFileName]
forKey: @"content-type"];
[response setHeader: [NSString stringWithFormat: @"attachment; filename=\"%@\"",
qpFileName]
forKey: @"Content-Disposition"];
return response;
}
- (WOResponse *) archiveAllMessagesInContext: (id) localContext
{
WOResponse *response;
NSArray *uids;
NSString *archiveName;
EOQualifier *notDeleted;
if ([self exists])
{
notDeleted = [EOQualifier qualifierWithQualifierFormat:
@"(not (flags = %@))", @"deleted"];
uids = [self fetchUIDsMatchingQualifier: notDeleted
sortOrdering: @"ARRIVAL"];
archiveName = [NSString stringWithFormat: @"%@.zip", [self relativeImap4Name]];
response = [self archiveUIDs: uids inArchiveNamed: archiveName
inContext: localContext];
}
else
response = (WOResponse *)
[NSException exceptionWithHTTPStatus: 404
reason: @"Folder does not exist."];
return response;
}
- (WOResponse *) copyUIDs: (NSArray *) uids
toFolder: (NSString *) destinationFolder
inContext: (id) localContext
{
return [self moveUIDs: uids
toFolder: destinationFolder
inContext: localContext
keepCopy: YES];
}
- (WOResponse *) moveUIDs: (NSArray *) uids
toFolder: (NSString *) destinationFolder
inContext: (id) localContext
{
return [self moveUIDs: uids
toFolder: destinationFolder
inContext: localContext
keepCopy: NO];
}
- (WOResponse *) moveUIDs: (NSArray *) uids
toFolder: (NSString *) destinationFolder
inContext: (id) localContext
keepCopy: (BOOL) copy
{
NSArray *folders;
NSString *currentFolderName, *currentAccountName, *destinationAccountName;
NSMutableString *imapDestinationFolder;
NGImap4Client *client;
id result;
int count, max;
#warning this code will fail on implementation using something else than '/' as delimiter
imapDestinationFolder = [NSMutableString string];
folders = [destinationFolder componentsSeparatedByString: @"/"];
max = [folders count];
if (max > 1)
{
currentAccountName = [[self mailAccountFolder] nameInContainer];
client = [[self imap4Connection] client];
[imap4 selectFolder: [self imap4URL]];
destinationAccountName = [[folders objectAtIndex: 1] fromCSSIdentifier];
for (count = 2; count < max; count++)
{
currentFolderName = [[[folders objectAtIndex: count] substringFromIndex: 6] fromCSSIdentifier];
[imapDestinationFolder appendFormat: @"/%@", currentFolderName];
}
if (client)
{
if ([destinationAccountName isEqualToString: currentAccountName])
{
// We make sure the destination IMAP folder exist, if not, we create it.
result = [[[client list: @"" pattern: imapDestinationFolder] objectForKey: @"list"] objectForKey: imapDestinationFolder];
if (!result)
result = [[self imap4Connection] createMailbox: imapDestinationFolder
atURL: [[self mailAccountFolder] imap4URL]];
if (!result || [result boolValue])
{
if (copy || ![[self mailAccountFolder] supportsMove])
result = [client copyUids: uids toFolder: imapDestinationFolder];
else
result = [client moveUids: uids toFolder: imapDestinationFolder];
}
if ([[result valueForKey: @"result"] boolValue])
{
result = nil;
if (!copy && ![[self mailAccountFolder] supportsMove])
{
// Server doesn't support MOVE -- delete messages
result = [client storeFlags: [NSArray arrayWithObject: @"Deleted"]
forUIDs: uids addOrRemove: YES];
if ([[result valueForKey: @"result"] boolValue])
{
[self markForExpunge];
result = nil;
}
}
}
else
{
result = [NSException exceptionWithHTTPStatus: 500
reason: [[[result objectForKey: @"RawResponse"]
objectForKey: @"ResponseResult"]
objectForKey: @"description"]];
}
}
else
{
// Destination folder is in a different account
SOGoMailAccounts *accounts;
SOGoMailAccount *account;
SOGoUserFolder *userFolder;
userFolder = [[context activeUser] homeFolderInContext: context];
accounts = [userFolder lookupName: @"Mail" inContext: context acquire: NO];
account = [accounts lookupName: destinationAccountName inContext: localContext acquire: NO];
if ([account isKindOfClass: [NSException class]])
{
result = [NSException exceptionWithHTTPStatus: 500
reason: @"Cannot copy messages to other account."];
}
else
{
NSEnumerator *messages;
NSDictionary *message;
NSData *content;
NSArray *flags;
// Fetch messages
result = [client fetchUids: uids parts: [NSArray arrayWithObjects: @"RFC822", @"FLAGS", nil]];
if ([[result objectForKey: @"result"] boolValue])
{
result = [result valueForKey: @"fetch"];
if ([result isKindOfClass: [NSArray class]] && [result count] > 0)
{
// Copy each message to the other account
client = [[account imap4Connection] client];
[[account imap4Connection] selectFolder: imapDestinationFolder];
messages = [result objectEnumerator];
result = nil;
while (result == nil && (message = [messages nextObject]))
{
if ((content = [message valueForKey: @"message"]) != nil)
{
flags = [message valueForKey: @"flags"];
result = [client append: content toFolder: imapDestinationFolder withFlags: flags];
if ([[result objectForKey: @"result"] boolValue])
result = nil;
else
[self logWithFormat: @"ERROR: Can't append message: %@", result];
}
}
if (!copy && result == nil)
{
// Delete messages
result = [client storeFlags: [NSArray arrayWithObject: @"Deleted"]
forUIDs: uids addOrRemove: YES];
if ([[result valueForKey: @"result"] boolValue])
{
[self markForExpunge];
result = nil;
}
}
}
else
{
[self logWithFormat: @"ERROR: unexpected IMAP4 result (missing 'fetch'): %@", result];
result = [NSException exceptionWithHTTPStatus: 500
reason: @"Unexpected IMAP4 result"];
}
}
else
{
[self logWithFormat: @"ERROR: Can't fetch messages: %@", result];
result = [NSException exceptionWithHTTPStatus: 500
reason: @"Can't fetch messages"];
}
}
}
}
else
result = [NSException exceptionWithName: @"SOGoMailException"
reason: @"IMAP connection is invalid"
userInfo: nil];
}
else
result = [NSException exceptionWithHTTPStatus: 500
reason: @"Invalid destination."];
return result;
}
- (WOResponse *) markMessagesAsJunkOrNotJunk: (NSArray *) uids
junk: (BOOL) isJunk
{
NSDictionary *junkSettings;
NSString *recipient, *subject;
NSException *error;
unsigned int limit;
junkSettings = [[[context activeUser] domainDefaults] mailJunkSettings];
error = nil;
if ([[junkSettings objectForKey: @"vendor"] caseInsensitiveCompare: @"generic"] == NSOrderedSame)
{
if (isJunk)
{
recipient = [junkSettings objectForKey: @"junkEmailAddress"];
subject = [[self labelForKey: @"Report: Marked messages as junk"] asQPSubjectString: @"utf-8"];
}
else
{
recipient = [junkSettings objectForKey: @"notJunkEmailAddress"];
subject = [[self labelForKey: @"Report: Marked messages as not junk"] asQPSubjectString: @"utf-8"];
}
limit = [[junkSettings objectForKey: @"limit"] intValue];
// If no limit is set, we only attach one mail at the time
// to reports sent by SOGo.
if (!limit)
limit = 1;
if ([recipient length])
{
NGMimeMessage *messageToSend;
SOGoMailObject *mailObject;
NGMimeBodyPart *bodyPart;
NGMutableHashMap *map;
NGMimeFileData *fdata;
NSArray *identities;
NSData *data;
id body;
int i;
identities = [[self mailAccountFolder] identities];
for (i = 0; i < [uids count]; i++)
{
// If we are starting or reaching the limit, we create
// a new mail message
if ((i%limit) == 0)
{
map = [NGMutableHashMap hashMapWithCapacity: 6];
#warning SOPE is just plain stupid here - if you change the case of keys, it will break the encoding of fields
[map setObject: @"multipart/mixed" forKey: @"content-type"];
[map setObject: @"1.0" forKey: @"MIME-Version"];
[map setObject: subject forKey: @"subject"];
[map setObject: [[identities objectAtIndex: 0] objectForKey: @"email"] forKey: @"from"];
[map setObject: recipient forKey: @"to"];
[map setObject: [[NSCalendarDate date] rfc822DateString] forKey: @"date"];
messageToSend = [[[NGMimeMessage alloc] initWithHeader: map] autorelease];
body = [[[NGMimeMultipartBody alloc] initWithPart: messageToSend] autorelease];
}
mailObject = [self lookupName: [NSString stringWithFormat: @"%@", [uids objectAtIndex: i]]
inContext: context
acquire: NO];
// We skip emails that might have disappeared before we were able
// to perform the action
if ([mailObject isKindOfClass: [NSException class]])
continue;
map = [[[NGMutableHashMap alloc] initWithCapacity: 1] autorelease];
[map setObject: @"message/rfc822" forKey: @"content-type"];
[map setObject: @"8bit" forKey: @"content-transfer-encoding"];
[map addObject: [NSString stringWithFormat: @"attachment; filename=\"%@\"", [mailObject filenameForForward]] forKey: @"content-disposition"];
bodyPart = [[[NGMimeBodyPart alloc] initWithHeader: map] autorelease];
data = [mailObject content];
fdata = [[NGMimeFileData alloc] initWithBytes: [data bytes] length: [data length]];
[bodyPart setBody: fdata];
RELEASE(fdata);
[body addBodyPart: bodyPart];
// We reached the limit or the end of the array
if ((i%limit) == 0 || i == [uids count]-1)
{
NGMimeMessageGenerator *generator;
[messageToSend setBody: body];
generator = [[[NGMimeMessageGenerator alloc] init] autorelease];
data = [generator generateMimeFromPart: messageToSend];
error = [[SOGoMailer mailerWithDomainDefaults: [[context activeUser] domainDefaults]]
sendMailData: data
toRecipients: [NSArray arrayWithObject: recipient]
sender: [[identities objectAtIndex: 0] objectForKey: @"email"]
withAuthenticator: [self authenticatorInContext: context]
inContext: context];
if (error)
break;
}
}
}
}
return (WOResponse *) error;
}
- (NSDictionary *) statusForFlags: (NSArray *) flags
{
NGImap4Client *client;
NSString *folderName;
NSDictionary *result, *status;
client = [[self imap4Connection] client];
folderName = [[self imap4Connection] imap4FolderNameForURL: [self imap4URL]];
result = [client status: folderName flags: flags];
if ([[result objectForKey: @"result"] boolValue])
status = [[[result objectForKey: @"RawResponse"] objectForKey: @"status"]
objectForKey: @"flags"];
else
status = nil;
return status;
}
- (unsigned int) unseenCount
{
NSDictionary *imapResult;
NGImap4Connection *connection;
NGImap4Client *client;
EOQualifier *searchQualifier;
NSArray *searchResult;
unsigned int unseen;
connection = [self imap4Connection];
client = [connection client];
if ([connection selectFolder: [self imap4URL]])
{
searchQualifier
= [EOQualifier qualifierWithQualifierFormat: @"flags = %@ AND not flags = %@",
@"unseen", @"deleted"];
imapResult = [client searchWithQualifier: searchQualifier];
searchResult = [[imapResult objectForKey: @"RawResponse"] objectForKey: @"search"];
unseen = [searchResult count];
}
else
unseen = 0;
return unseen;
}
- (NSArray *) fetchUIDsMatchingQualifier: (id) _q
sortOrdering: (id) _so
{
return [self fetchUIDsMatchingQualifier: _q
sortOrdering: _so
threaded: NO];
}
- (NSArray *) fetchUIDsMatchingQualifier: (id) _q
sortOrdering: (id) _so
threaded: (BOOL) _threaded
{
if (_threaded)
{
return [[self imap4Connection] fetchThreadedUIDsInURL: [self imap4URL]
qualifier: _q
sortOrdering: _so];
}
else
{
return [[self imap4Connection] fetchUIDsInURL: [self imap4URL]
qualifier: _q
sortOrdering: _so];
}
}
- (NSArray *) fetchUIDs: (NSArray *) _uids
parts: (NSArray *) _parts
{