/
SOGoMailObject.m
1896 lines (1562 loc) · 49.3 KB
/
SOGoMailObject.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) 2007-2017 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/NSTask.h>
#import <Foundation/NSURL.h>
#import <Foundation/NSValue.h>
#import <NGObjWeb/WOContext+SoObjects.h>
#import <NGObjWeb/WORequest.h>
#import <NGObjWeb/NSException+HTTP.h>
#import <NGExtensions/NGHashMap.h>
#import <NGExtensions/NSFileManager+Extensions.h>
#import <NGExtensions/NSNull+misc.h>
#import <NGExtensions/NSObject+Logs.h>
#import <NGExtensions/NSString+Encoding.h>
#import <NGExtensions/NSString+misc.h>
#import <NGImap4/NGImap4Connection.h>
#import <NGImap4/NGImap4Envelope.h>
#import <NGImap4/NGImap4EnvelopeAddress.h>
#import <NGMail/NGMimeMessageParser.h>
#import <NGMime/NGMimeMultipartBody.h>
#import <NGMime/NGMimeType.h>
#import <SOGo/NSArray+Utilities.h>
#import <SOGo/NSDictionary+Utilities.h>
#import <SOGo/NSString+Utilities.h>
#import <SOGo/SOGoPermissions.h>
#import <SOGo/SOGoSystemDefaults.h>
#import <SOGo/SOGoUser.h>
#import <SOGo/SOGoUserDefaults.h>
#import <SOGo/NSCalendarDate+SOGo.h>
#import "NSString+Mail.h"
#import "NSData+Mail.h"
#import "NSData+SMIME.h"
#import "NSDictionary+Mail.h"
#import "SOGoMailAccount.h"
#import "SOGoMailFolder.h"
#import "SOGoMailManager.h"
#import "SOGoMailBodyPart.h"
#import "SOGoMailObject.h"
@implementation SOGoMailObject
NSArray *SOGoMailCoreInfoKeys = nil;
static NSString *mailETag = nil;
static BOOL heavyDebug = NO;
static BOOL debugOn = NO;
static BOOL debugBodyStructure = NO;
static BOOL debugSoParts = NO;
+ (void) initialize
{
if (!SOGoMailCoreInfoKeys)
{
/* Note: see SOGoMailManager.m for allowed IMAP4 keys */
SOGoMailCoreInfoKeys
= [[NSArray alloc] initWithObjects:
@"FLAGS", @"ENVELOPE", @"BODYSTRUCTURE",
@"RFC822.SIZE",
@"RFC822.HEADER",
// not yet supported: @"INTERNALDATE",
nil];
/* The following disabled code should not be needed, except if we use
annotations (see davEntityTag below) */
// if (![[ud objectForKey: @"SOGoMailDisableETag"] boolValue]) {
mailETag = [[NSString alloc] initWithFormat: @"\"imap4url_%@_%@_%@\"",
UIX_MAILER_MAJOR_VERSION,
UIX_MAILER_MINOR_VERSION,
UIX_MAILER_SUBMINOR_VERSION];
}
}
- (id) init
{
if ((self = [super init]))
{
headers = nil;
headerPart = nil;
coreInfos = nil;
}
return self;
}
- (void) dealloc
{
[headers release];
[headerPart release];
[coreInfos release];
[super dealloc];
}
/* IMAP4 */
- (NSString *) relativeImap4Name
{
return [nameInContainer stringByDeletingPathExtension];
}
/* hierarchy */
- (SOGoMailObject *) mailObject
{
return self;
}
/* part hierarchy */
- (NSString *) keyExtensionForPart: (id) _partInfo
{
NSString *mt, *st;
if (_partInfo == nil)
return nil;
mt = [_partInfo valueForKey: @"type"];
st = [[_partInfo valueForKey: @"subtype"] lowercaseString];
if ([mt isEqualToString: @"text"]) {
if ([st isEqualToString: @"plain"]) return @".txt";
if ([st isEqualToString: @"html"]) return @".html";
if ([st isEqualToString: @"calendar"]) return @".ics";
if ([st isEqualToString: @"x-vcard"]) return @".vcf";
}
else if ([mt isEqualToString: @"image"])
return [@"." stringByAppendingString:st];
else if ([mt isEqualToString: @"application"]) {
if ([st isEqualToString: @"pgp-signature"])
return @".asc";
}
return nil;
}
- (NSArray *)relationshipKeysWithParts:(BOOL)_withParts {
/* should return non-multipart children */
NSMutableArray *ma;
NSArray *parts;
unsigned i, count;
parts = [[self bodyStructure] valueForKey: @"parts"];
if (![parts isNotNull])
return nil;
if ((count = [parts count]) == 0)
return nil;
for (i = 0, ma = nil; i < count; i++) {
NSString *key, *ext;
id part;
BOOL hasParts;
part = [parts objectAtIndex:i];
hasParts = [part valueForKey: @"parts"] != nil ? YES:NO;
if ((hasParts && !_withParts) || (_withParts && !hasParts))
continue;
if (ma == nil)
ma = [NSMutableArray arrayWithCapacity:count - i];
ext = [self keyExtensionForPart:part];
key = [[NSString alloc] initWithFormat: @"%d%@", i + 1, ((id)ext?(id)ext: (id)@"")];
[ma addObject:key];
[key release];
}
return ma;
}
- (NSArray *) toOneRelationshipKeys
{
return [self relationshipKeysWithParts:NO];
}
- (NSArray *) toManyRelationshipKeys
{
return [self relationshipKeysWithParts:YES];
}
/* message */
- (id) fetchParts: (NSArray *) _parts
{
// TODO: explain what it does
/*
Called by -fetchPlainTextParts:
*/
return [[self imap4Connection] fetchURL: [self imap4URL] parts:_parts];
}
/* core infos */
- (BOOL) doesMailExist
{
static NSArray *existsKey = nil;
id msgs;
if (coreInfos != nil) /* if we have coreinfos, we can use them */
return [coreInfos isNotNull];
/* otherwise fetch something really simple */
if (existsKey == nil) /* we use size, other suggestions? */
existsKey = [[NSArray alloc] initWithObjects: @"RFC822.SIZE", nil];
msgs = [self fetchParts:existsKey]; // returns dict
msgs = [msgs valueForKey: @"fetch"];
return [msgs count] > 0 ? YES : NO;
}
- (id) fetchCoreInfos
{
id msgs;
int i;
if (!coreInfos)
{
msgs = [self fetchParts: SOGoMailCoreInfoKeys]; // returns dict
if (heavyDebug)
[self logWithFormat: @"M: %@", msgs];
msgs = [msgs valueForKey: @"fetch"];
// We MUST honor untagged IMAP responses here otherwise we could
// return really borken and nasty results.
if ([msgs count] > 0)
{
for (i = 0; i < [msgs count]; i++)
{
coreInfos = [msgs objectAtIndex: i];
if ([[coreInfos objectForKey: @"uid"] intValue] == [[self nameInContainer] intValue])
break;
coreInfos = nil;
}
}
[coreInfos retain];
}
return coreInfos;
}
- (void) setCoreInfos: (NSDictionary *) newCoreInfos
{
ASSIGN (coreInfos, newCoreInfos);
}
- (id) bodyStructure
{
id bodyStructure;
bodyStructure = [[self fetchCoreInfos] valueForKey: @"bodystructure"];
if (debugBodyStructure)
[self logWithFormat: @"BODYSTRUCTURE: %@", bodyStructure];
return bodyStructure;
}
- (NGImap4Envelope *) envelope
{
return [[self fetchCoreInfos] valueForKey: @"envelope"];
}
- (NSString *) subject
{
return [[self envelope] subject];
}
- (NSString *) displayName
{
return [self decodedSubject];
}
- (NSString *) decodedSubject
{
return [[self subject] decodedHeader];
}
- (NSCalendarDate *) date
{
SOGoUserDefaults *ud;
NSCalendarDate *date;
ud = [[context activeUser] userDefaults];
date = [[self envelope] date];
[date setTimeZone: [ud timeZone]];
return date;
}
- (NSArray *) fromEnvelopeAddresses
{
return [[self envelope] from];
}
- (NSArray *) toEnvelopeAddresses
{
return [[self envelope] to];
}
- (NSArray *) ccEnvelopeAddresses
{
return [[self envelope] cc];
}
- (NSArray *) bccEnvelopeAddresses
{
return [[self envelope] bcc];
}
- (NSArray *) replyToEnvelopeAddresses
{
return [[self envelope] replyTo];
}
- (NSData *) mailHeaderData
{
return [[self fetchCoreInfos] valueForKey: @"header"];
}
- (id) mailHeaderPart
{
NGMimeMessageParser *parser;
NSData *data;
if (headerPart != nil)
return [headerPart isNotNull] ? headerPart : nil;
if ([(data = [self mailHeaderData]) length] == 0)
return nil;
// TODO: do we need to set some delegate method which stops parsing the body?
parser = [[NGMimeMessageParser alloc] init];
headerPart = [[parser parsePartFromData: data] retain];
[parser release]; parser = nil;
if (headerPart == nil) {
headerPart = [[NSNull null] retain];
return nil;
}
return headerPart;
}
- (NSDictionary *) mailHeaders
{
if (!headers)
headers = [[[self mailHeaderPart] headers] copy];
return headers;
}
- (id) lookupInfoForBodyPart: (id) _path
{
NSEnumerator *pe;
NSString *p;
id info;
if (![_path isNotNull])
return nil;
if ((info = [self bodyStructure]) == nil) {
[self errorWithFormat: @"got no body part structure!"];
return nil;
}
/* ensure array argument */
if ([_path isKindOfClass:[NSString class]]) {
if ([_path length] == 0 || [_path isEqualToString: @"text"])
return info;
_path = [_path componentsSeparatedByString: @"."];
}
// deal with mails of type text/calendar
if ([[[info valueForKey: @"type"] lowercaseString] isEqualToString: @"text"] &&
[[[info valueForKey: @"subtype"] lowercaseString] isEqualToString: @"calendar"])
return info;
// deal with mails that contain only an attachment, for example:
// application/pkcs7-mime
// application/pdf
// etc.
if ([[[info valueForKey: @"type"] lowercaseString] isEqualToString: @"application"] ||
[[[info valueForKey: @"type"] lowercaseString] isEqualToString: @"audio"])
return info;
/*
For each path component, eg 1,1,3
Remember that we need special processing for message/rfc822 which maps the
namespace of multiparts directly into the main namespace.
TODO(hh): no I don't remember, please explain in more detail!
*/
pe = [_path objectEnumerator];
while ((p = [pe nextObject]) != nil && [info isNotNull]) {
unsigned idx;
NSArray *parts;
NSString *mt;
[self debugWithFormat: @"check PATH: %@", p];
idx = [p intValue] - 1;
parts = [info valueForKey: @"parts"];
mt = [[info valueForKey: @"type"] lowercaseString];
if ([mt isEqualToString: @"message"]) {
/* we have special behaviour for message types */
id body;
if ((body = [info valueForKey: @"body"]) != nil) {
mt = [body valueForKey: @"type"];
if ([mt isEqualToString: @"multipart"])
parts = [body valueForKey: @"parts"];
else
parts = [NSArray arrayWithObject:body];
}
}
if (idx >= [parts count]) {
[self errorWithFormat:
@"body part index out of bounds(idx=%d vs count=%d): %@",
(idx + 1), [parts count], info];
return nil;
}
info = [parts objectAtIndex:idx];
}
return [info isNotNull] ? info : nil;
}
/* content */
- (NSData *) content
{
NSData *content;
id result, fullResult;
// We avoid using RFC822 here as the part name as it'll flag the message as Seen
fullResult = [self fetchParts: [NSArray arrayWithObject: @"BODY.PEEK[]"]];
if (fullResult == nil)
return nil;
if ([fullResult isKindOfClass: [NSException class]])
return fullResult;
/* extract fetch result */
result = [fullResult valueForKey: @"fetch"];
if (![result isKindOfClass:[NSArray class]]) {
[self logWithFormat:
@"ERROR: unexpected IMAP4 result (missing 'fetch'): %@",
fullResult];
return [NSException exceptionWithHTTPStatus:500 /* server error */
reason: @"unexpected IMAP4 result"];
}
if ([result count] == 0)
return nil;
result = [result objectAtIndex:0];
/* extract message */
if ((content = [[result valueForKey: @"body[]"] valueForKey: @"data"]) == nil) {
[self logWithFormat:
@"ERROR: unexpected IMAP4 result (missing 'message'): %@",
result];
return [NSException exceptionWithHTTPStatus:500 /* server error */
reason: @"unexpected IMAP4 result"];
}
return [[content copy] autorelease];
}
- (NSString *) davContentType
{
return @"message/rfc822";
}
- (NSString *) contentAsString
{
id s;
NSData *content;
content = [self content];
if (content)
{
if ([content isKindOfClass: [NSData class]])
{
#warning we ignore the charset here?
s = [[NSString alloc] initWithData: content
encoding: NSISOLatin1StringEncoding];
if (s)
[s autorelease];
else
[self logWithFormat:
@"ERROR: could not convert data of length %d to string",
[content length]];
}
else
s = content;
}
else
s = nil;
return s;
}
/* This is defined before the public version without parentMimeType
argument to be able to call it recursively */
/* bulk fetching of plain/text content */
- (void) addRequiredKeysOfStructure: (NSDictionary *) info
path: (NSString *) p
toArray: (NSMutableArray *) keys
acceptedTypes: (NSArray *) types
withPeek: (BOOL) withPeek
parentMultipart: (NSString *) parentMPart
{
/*
This is used to collect the set of IMAP4 fetch-keys required to fetch
the basic parts of the body structure. That is, to fetch all parts which
are displayed 'inline' in a single IMAP4 fetch.
The method calls itself recursively to walk the body structure.
*/
NSArray *parts;
unsigned i, count;
NSString *k;
id body;
NSString *bodyToken, *sp, *mimeType;
id childInfo;
NSString *multipart;
bodyToken = (withPeek ? @"body.peek" : @"body");
mimeType = [[NSString stringWithFormat: @"%@/%@",
[info valueForKey: @"type"],
[info valueForKey: @"subtype"]]
lowercaseString];
if ([[info valueForKey: @"type"] isEqualToString: @"multipart"])
multipart = mimeType;
else
multipart = parentMPart;
if ([types containsObject: mimeType])
{
if ([p length] > 0)
k = [NSString stringWithFormat: @"%@[%@]", bodyToken, p];
else
{
/*
for some reason we need to add ".TEXT" for plain text stuff on root
entities?
TODO: check with HTML
*/
k = [NSString stringWithFormat: @"%@[text]", bodyToken];
}
[keys addObject: [NSDictionary dictionaryWithObjectsAndKeys: k, @"key",
mimeType, @"mimeType",
multipart, @"multipart", nil]];
}
parts = [info objectForKey: @"parts"];
count = [parts count];
for (i = 0; i < count; i++)
{
sp = (([p length] > 0)
? (id)[p stringByAppendingFormat: @".%d", i + 1]
: (id)[NSString stringWithFormat: @"%d", i + 1]);
childInfo = [parts objectAtIndex: i];
[self addRequiredKeysOfStructure: childInfo
path: sp
toArray: keys
acceptedTypes: types
withPeek: withPeek
parentMultipart: multipart];
}
/* check body */
body = [info objectForKey: @"body"];
if (body)
{
/* FIXME: this seems to generate bad mime part keys, which triggers a
exceptions such as this:
ERROR(-[NGImap4Client _processCommandParserException:]): catched
IMAP4 parser exception NGImap4ParserException: unsupported fetch key:
nil)
Do we really need to assign p to sp in a multipart body part? Or do
we need to do this only when the part in question is the first one in
the message? */
sp = [[body valueForKey: @"type"] lowercaseString];
if ([sp isEqualToString: @"multipart"])
sp = p;
else
sp = [p length] > 0 ? (id)[p stringByAppendingString: @".1"] : (id)@"1";
[self addRequiredKeysOfStructure: body
path: sp
toArray: keys
acceptedTypes: types
withPeek: withPeek
parentMultipart: multipart];
}
}
- (void) addRequiredKeysOfStructure: (NSDictionary *) info
path: (NSString *) p
toArray: (NSMutableArray *) keys
acceptedTypes: (NSArray *) types
withPeek: (BOOL) withPeek
{
[self addRequiredKeysOfStructure: (NSDictionary *) info
path: (NSString *) p
toArray: (NSMutableArray *) keys
acceptedTypes: (NSArray *) types
withPeek: (BOOL) withPeek
parentMultipart: @""];
}
- (NSArray *) plainTextContentFetchKeys
{
/*
The name is not 100% correct. The method returns all body structure fetch
keys which are marked by the -shouldFetchPartOfType:subtype: method.
*/
NSMutableArray *ma;
NSArray *types;
types = [NSArray arrayWithObjects: @"text/plain", @"text/html",
@"text/calendar", @"application/ics",
@"application/pgp-signature", nil];
ma = [NSMutableArray arrayWithCapacity: 4];
[self addRequiredKeysOfStructure: [self bodyStructure]
path: @""
toArray: ma
acceptedTypes: types
withPeek: YES];
return ma;
}
- (NSDictionary *) fetchPlainTextParts: (NSArray *) _fetchKeys
{
// TODO: is the name correct or does it also fetch other parts?
NSMutableDictionary *flatContents;
unsigned i, count;
NSArray *results;
id result;
[self debugWithFormat: @"fetch keys: %@", _fetchKeys];
result = [self fetchParts: [_fetchKeys objectsForKey: @"key"
notFoundMarker: nil]];
result = [result valueForKey: @"RawResponse"]; // hackish
// Note: -valueForKey: doesn't work!
results = [(NGHashMap *)result objectsForKey: @"fetch"];
result = [results flattenedDictionaries];
count = [_fetchKeys count];
flatContents = [NSMutableDictionary dictionaryWithCapacity:count];
for (i = 0; i < count; i++) {
NSString *key;
NSData *data;
key = [[_fetchKeys objectAtIndex:i] objectForKey: @"key"];
// We'll ask for the body.peek[] but SOPE returns us body[] responses
// so the key won't ever be found.
if ([key hasPrefix: @"body.peek["])
key = [NSString stringWithFormat: @"body[%@", [key substringFromIndex: 10]];
data = [(NSDictionary *)[(NSDictionary *)result objectForKey:key]
objectForKey: @"data"];
if (![data isNotNull]) {
[self errorWithFormat: @"got no data for key: %@", key];
continue;
}
if ([key isEqualToString: @"body[text]"])
key = @""; // see key collector for explanation (TODO: where?)
else if ([key hasPrefix: @"body["]) {
NSRange r;
key = [key substringFromIndex:5];
r = [key rangeOfString: @"]"];
if (r.length > 0)
key = [key substringToIndex:r.location];
}
[flatContents setObject:data forKey:key];
}
return flatContents;
}
- (NSDictionary *) fetchPlainTextParts
{
return [self fetchPlainTextParts: [self plainTextContentFetchKeys]];
}
- (NSString *) _urlToPart: (NSDictionary *) infos
withPrefix: (NSString *) urlPrefix
{
NSDictionary *parameters;
NSString *urlToPart, *filename;
parameters = [infos objectForKey: @"parameterList"];
filename = [parameters objectForKey: @"name"];
if (!filename)
{
parameters = [[infos objectForKey: @"disposition"]
objectForKey: @"parameterList"];
filename = [parameters objectForKey: @"filename"];
}
if ([filename length])
urlToPart = [NSString stringWithFormat: @"%@/%@", urlPrefix, filename];
else
urlToPart = urlPrefix;
return urlToPart;
}
- (void) _feedFileAttachmentIds: (NSMutableDictionary *) attachmentIds
withInfos: (NSDictionary *) infos
andPrefix: (NSString *) prefix
{
NSArray *parts;
NSDictionary *currentPart;
unsigned int count, max;
NSString *url, *cid;
cid = [infos objectForKey: @"bodyId"];
if ([cid length])
{
url = [self _urlToPart: infos withPrefix: prefix];
if (url)
[attachmentIds setObject: url forKey: cid];
}
parts = [infos objectForKey: @"parts"];
max = [parts count];
for (count = 0; count < max; count++)
{
currentPart = [parts objectAtIndex: count];
[self _feedFileAttachmentIds: attachmentIds
withInfos: currentPart
andPrefix: [NSString stringWithFormat: @"%@/%d",
prefix, count + 1]];
}
}
- (NSDictionary *) fetchFileAttachmentIds
{
NSMutableDictionary *attachmentIds;
NSString *prefix;
attachmentIds = [NSMutableDictionary dictionary];
[self fetchCoreInfos];
prefix = [[self soURL] absoluteString];
if ([prefix hasSuffix: @"/"])
prefix = [prefix substringToIndex: [prefix length] - 1];
[self _feedFileAttachmentIds: attachmentIds
withInfos: [coreInfos objectForKey: @"bodystructure"]
andPrefix: prefix];
return attachmentIds;
}
//
//
//
- (void) _fetchFileAttachmentKey: (NSDictionary *) part
intoArray: (NSMutableArray *) keys
withPath: (NSString *) path
andPrefix: (NSString *) prefix
{
NSString *filename, *mimeType, *filenameURL;
NSDictionary *currentFile;
filename = [part filename];
mimeType = [NSString stringWithFormat: @"%@/%@",
[part objectForKey: @"type"],
[part objectForKey: @"subtype"]];
if (!filename)
{
filename = [mimeType asPreferredFilenameUsingPath: path];
}
if (filename)
{
// We replace any slash by a dash since Apache won't allow encoded slashes by default.
// See http://httpd.apache.org/docs/2.2/mod/core.html#allowencodedslashes
// See [UIxMailPartViewer _filenameForAttachment:]
filenameURL = [[filename stringByReplacingString: @"/" withString: @"-"] stringByEscapingURL];
currentFile = [NSDictionary dictionaryWithObjectsAndKeys:
[filename stringByUnescapingURL], @"filename",
[mimeType lowercaseString], @"mimetype",
path, @"path",
[part objectForKey: @"encoding"], @"encoding",
[part objectForKey:@ "size"], @"size",
[part objectForKey: @"bodyId"], @"bodyId",
[NSString stringWithFormat: @"%@/%@", prefix, filenameURL], @"url",
[NSString stringWithFormat: @"%@/asAttachment/%@", prefix, filenameURL], @"urlAsAttachment",
nil];
[keys addObject: currentFile];
}
}
//
//
//
- (void) _fetchFileAttachmentKeysInPart: (NSDictionary *) part
intoArray: (NSMutableArray *) keys
withPath: (NSString *) path
andPrefix: (NSString *) prefix
{
NSMutableDictionary *currentPart;
NSString *newPath;
NSArray *subparts;
NSString *type, *subtype;
NSUInteger i;
type = [[part objectForKey: @"type"] lowercaseString];
if ([type isEqualToString: @"multipart"])
{
subparts = [part objectForKey: @"parts"];
for (i = 1; i <= [subparts count]; i++)
{
currentPart = [subparts objectAtIndex: i-1];
if (path)
newPath = [NSString stringWithFormat: @"%@.%d", path, (int)i];
else
newPath = [NSString stringWithFormat: @"%d", (int)i];
[self _fetchFileAttachmentKeysInPart: currentPart
intoArray: keys
withPath: newPath
andPrefix: [NSString stringWithFormat: @"%@/%i", prefix, (int)i]];
}
}
else
{
if (!path)
{
path = @"1";
// We set the path to 0 in case of a S/MIME mail if not provided.
subtype = [[part objectForKey: @"subtype"] lowercaseString];
if ([subtype isEqualToString: @"pkcs7-mime"] || [subtype isEqualToString: @"x-pkcs7-mime"])
path = @"0";
}
[self _fetchFileAttachmentKey: part
intoArray: keys
withPath: path
andPrefix: prefix];
}
}
//
//
//
#warning we might need to handle parts with a "name" attribute
- (NSArray *) fetchFileAttachmentKeys
{
NSString *prefix;
NSMutableArray *keys;
prefix = [[self soURL] absoluteString];
if ([prefix hasSuffix: @"/"])
prefix = [prefix substringToIndex: [prefix length] - 1];
keys = [NSMutableArray array];
[self _fetchFileAttachmentKeysInPart: [self bodyStructure]
intoArray: keys
withPath: nil
andPrefix: prefix];
return keys;
}
/**
* Returns an array of dictionaries with the following keys:
* - encoding
* - filename
* - mimetype
* - path
* - size
* - url
* - urlAsAttachment
* - body (NSData)
*/
- (NSArray *) fetchFileAttachments
{
unsigned int count, max;
NGHashMap *response;
NSArray *parts, *paths; //, *bodies;
NSData *body;
NSDictionary *fetch, *currentInfo, *currentBody;
NSMutableArray *attachments;
NSMutableDictionary *currentAttachment;
NSString *currentPath;
parts = [self fetchFileAttachmentKeys];
max = [parts count];
attachments = [NSMutableArray arrayWithCapacity: max];
if (max > 0)
{
paths = [parts keysWithFormat: @"BODY[%{path}]"];
response = [[self fetchParts: paths] objectForKey: @"RawResponse"];
fetch = [response objectForKey: @"fetch"];
for (count = 0; count < max; count++)
{
currentInfo = [parts objectAtIndex: count];
currentPath = [[paths objectAtIndex: count] lowercaseString];
currentBody = [fetch objectForKey: currentPath];
if (currentBody)
{
body = [currentBody objectForKey: @"data"];
body = [body bodyDataFromEncoding: [currentInfo objectForKey: @"encoding"]];
}
else
body = [NSData data];
currentAttachment = [NSMutableDictionary dictionaryWithDictionary: currentInfo];
[currentAttachment setObject: body forKey: @"body"];
[attachments addObject: currentAttachment];
}
}
return attachments;
}
- (WOResponse *) archiveAllFilesinArchiveNamed: (NSString *) archiveName
{
NSArray *attachments;
NSData *body, *zipContent;
NSDictionary *currentAttachment;
NSException *error;
NSFileManager *fm;
NSMutableArray *zipTaskArguments;
NSString *spoolPath, *name, *fileName, *baseName, *extension, *zipPath, *qpFileName;
NSTask *zipTask;
SOGoMailFolder *folder;
WOResponse *response;
unsigned int max, count;
if (!archiveName)
archiveName = @"attachments.zip";
folder = [self container];
spoolPath = [folder userSpoolFolderPath];
if (![folder ensureSpoolFolderPath])
{
[self errorWithFormat: @"spool directory '%@' doesn't exist", spoolPath];
error = [NSException exceptionWithHTTPStatus: 500
reason: @"spool directory does not exist"];
return (WOResponse *)error;
}
// Prepare execution of zip
zipPath = [[SOGoSystemDefaults sharedSystemDefaults] zipPath];
fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath: zipPath])
{
error = [NSException exceptionWithHTTPStatus: 500
reason: @"zip not available"];
return (WOResponse *)error;
}