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
|
/*
Copyright (C) 2004-2005 SKYRIX Software AG
Copyright (C) 2008-2014 Inverse inc.
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 SOGo; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/
#import <Foundation/NSCalendarDate.h>
#import <Foundation/NSCharacterSet.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSKeyValueCoding.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
#import <NGHttp/NGHttpRequest.h>
#import <NGObjWeb/NSException+HTTP.h>
#import <NGObjWeb/SoSubContext.h>
#define COMPILING_NGOBJWEB 1 /* we want httpRequest for parsing multi-part
form data */
#import <NGObjWeb/WORequest.h>
#undef COMPILING_NGOBJWEB
#import <NGObjWeb/WOApplication.h>
#import <NGObjWeb/WOResponse.h>
#import <NGExtensions/NSNull+misc.h>
#import <NGExtensions/NSObject+Logs.h>
#import <NGExtensions/NSString+misc.h>
#import <NGExtensions/NSException+misc.h>
#import <NGMail/NGMimeMessage.h>
#import <NGMail/NGMimeMessageGenerator.h>
#import <NGMime/NGMimeBodyPart.h>
#import <NGMime/NGMimeHeaderFields.h>
#import <NGMime/NGMimeMultipartBody.h>
#import <NGMime/NGMimeType.h>
#import <SOGo/SOGoCache.h>
#import <SOGo/SOGoSystemDefaults.h>
#import <SOGo/SOGoUserDefaults.h>
#import <SOGo/SOGoUser.h>
#import <SOGo/SOGoUserFolder.h>
#import <SOGo/NSArray+Utilities.h>
#import <SOGo/NSDictionary+Utilities.h>
#import <SOGo/WOResourceManager+SOGo.h>
#import <SOGoUI/UIxComponent.h>
#import <Mailer/SOGoDraftObject.h>
#import <Mailer/SOGoMailObject+Draft.h>
#import <Mailer/SOGoMailFolder.h>
#import <Mailer/SOGoMailAccount.h>
#import <Mailer/SOGoMailAccounts.h>
#import <Contacts/SOGoContactFolders.h>
#import <Contacts/SOGoContactFolder.h>
#import <Contacts/SOGoContactSourceFolder.h>
#import <UI/MailPartViewers/UIxMailSizeFormatter.h>
/*
UIxMailEditor
A mail editor component which works on SOGoDraftObject's.
*/
@interface UIxMailEditor : UIxComponent
{
NSArray *to;
NSArray *cc;
NSArray *bcc;
NSString *subject;
NSString *sourceUID;
NSString *sourceFolder;
NSString *text;
NSMutableArray *fromEMails;
NSString *from;
SOGoMailFolder *sentFolder;
BOOL isHTML;
NSString *priority;
NSString *receipt;
id item;
id currentFolder;
/* these are for the inline attachment list */
NSDictionary *attachment;
NSArray *attachmentAttrs;
NSString *currentAttachment;
NSMutableArray *attachedFiles;
}
@end
@implementation UIxMailEditor
static NSArray *infoKeys = nil;
+ (void) initialize
{
if (!infoKeys)
infoKeys = [[NSArray alloc] initWithObjects:
@"subject", @"to", @"cc", @"bcc",
@"from", @"inReplyTo",
@"replyTo",
@"priority", @"receipt", nil];
}
- (id) init
{
if ((self = [super init]))
{
priority = @"NORMAL";
receipt = nil;
currentFolder = nil;
currentAttachment = nil;
attachmentAttrs = nil;
attachedFiles = nil;
}
return self;
}
- (void) dealloc
{
[item release];
[priority release];
[receipt release];
[sentFolder release];
[fromEMails release];
[from release];
[text release];
[subject release];
[to release];
[cc release];
[bcc release];
[sourceUID release];
[sourceFolder release];
[attachment release];
[currentAttachment release];
[attachmentAttrs release];
[attachedFiles release];
[currentFolder release];
[super dealloc];
}
/* accessors */
- (void) setItem: (id) _item
{
ASSIGN (item, _item);
}
- (id) item
{
return item;
}
- (NSString *) uid
{
return [[self clientObject] nameInContainer];
}
- (NSArray *) priorityClasses
{
static NSArray *priorities = nil;
if (!priorities)
{
priorities = [NSArray arrayWithObjects: @"HIGHEST", @"HIGH",
@"NORMAL", @"LOW", @"LOWEST", nil];
[priorities retain];
}
return priorities;
}
- (void) setPriority: (NSString *) _priority
{
ASSIGN (priority, _priority);
}
- (NSString *) priority
{
return priority;
}
- (void) setReceipt: (NSString *) newReceipt
{
ASSIGN (receipt, newReceipt);
}
- (NSString *) receipt
{
return receipt;
}
- (void) setIsHTML: (BOOL) aBool
{
isHTML = aBool;
}
- (BOOL) isHTML
{
SOGoUserDefaults *ud;
ud = [[context activeUser] userDefaults];
return [[ud mailComposeMessageType] isEqualToString: @"html"];
}
- (NSString *) itemPriorityText
{
return [self labelForKey: [NSString stringWithFormat: @"%@", [item lowercaseString]]];
}
- (NSString *) isMailReply
{
return ([to count] > 0 ? @"true" : @"false");
}
- (NSString *) localeCode
{
// WARNING : NSLocaleCode is not defined in <Foundation/NSUserDefaults.h>
return [locale objectForKey: @"NSLocaleCode"];
}
- (void) setFrom: (NSString *) newFrom
{
ASSIGN (from, newFrom);
}
- (NSString *) _emailFromIdentity: (NSDictionary *) identity
{
NSString *fullName, *format;
fullName = [identity objectForKey: @"fullName"];
if ([fullName length])
format = @"%{fullName} <%{email}>";
else
format = @"%{email}";
return [identity keysWithFormat: format];
}
- (NSString *) from
{
NSDictionary *identity;
if (!from)
{
identity = [[context activeUser] primaryIdentity];
from = [self _emailFromIdentity: identity];
[from retain];
}
return from;
}
- (NSString *) replyTo
{
NSString *value;
value = nil;
//
// We add the correct replyTo here. That is, the one specified in the defaults
// for the main "SOGo mail account" versus the one specified in the auxiliary
// IMAP accounts.
//
if ([[[[self clientObject] mailAccountFolder] nameInContainer] intValue] == 0)
{
SOGoUserDefaults *ud;
ud = [[context activeUser] userDefaults];
value = [ud mailReplyTo];
}
else
{
NSArray *identities;
identities = [[[self clientObject] mailAccountFolder] identities];
if ([identities count])
value = [[identities objectAtIndex: 0] objectForKey: @"replyTo"];
}
return value;
}
- (void) setSubject: (NSString *) newSubject
{
ASSIGN (subject, newSubject);
}
- (NSString *) subject
{
return subject;
}
- (void) setText: (NSString *) newText
{
ASSIGN (text, newText);
}
- (NSString *) text
{
return text;
}
- (void) setSourceUID: (int) newSourceUID
{
NSString *s;
s = [NSString stringWithFormat: @"%i", newSourceUID];
ASSIGN (sourceUID, s);
}
- (NSString *) sourceUID
{
return sourceUID;
}
- (void) setSourceFolder: (NSString *) newSourceFolder
{
ASSIGN (sourceFolder, newSourceFolder);
}
- (NSString *) sourceFolder
{
return sourceFolder;
}
- (void) setTo: (NSArray *) newTo
{
if ([newTo isKindOfClass: [NSNull class]])
newTo = nil;
ASSIGN (to, newTo);
}
- (NSArray *) to
{
return to;
}
- (void) setCc: (NSArray *) newCc
{
if ([newCc isKindOfClass: [NSNull class]])
newCc = nil;
ASSIGN (cc, newCc);
}
- (NSArray *) cc
{
return cc;
}
- (void) setBcc: (NSArray *) newBcc
{
if ([newBcc isKindOfClass: [NSNull class]])
newBcc = nil;
ASSIGN (bcc, newBcc);
}
- (NSArray *) bcc
{
return bcc;
}
- (BOOL) hasOneOrMoreRecipients
{
return (([to count] + [cc count] + [bcc count]) > 0);
}
- (void) setAttachment: (NSDictionary *) newAttachment
{
ASSIGN (attachment, newAttachment);
}
- (NSDictionary *) attachment
{
return attachment;
}
- (NSFormatter *) sizeFormatter
{
return [UIxMailSizeFormatter sharedMailSizeFormatter];
}
/* from addresses */
- (NSArray *) fromEMails
{
NSArray *identities;
int count, max;
NSString *email;
SOGoMailAccount *account;
if (!fromEMails)
{
account = [[self clientObject] mailAccountFolder];
identities = [account identities];
max = [identities count];
fromEMails = [[NSMutableArray alloc] initWithCapacity: max];
for (count = 0; count < max; count++)
{
email
= [self _emailFromIdentity: [identities objectAtIndex: count]];
[fromEMails addObjectUniquely: email];
}
}
return fromEMails;
}
/* info loading */
- (void) loadInfo: (NSDictionary *) _info
{
if (![_info isNotNull]) return;
[self debugWithFormat:@"loading info ..."];
[self setValuesForKeysWithDictionary:_info];
}
- (NSDictionary *) storeInfo
{
[self debugWithFormat:@"storing info ..."];
return [self valuesForKeys: infoKeys];
}
/* contacts search */
- (NSArray *) contactFolders
{
SOGoContactFolders *folderContainer;
folderContainer = (SOGoContactFolders *) [[[self clientObject] lookupUserFolder] privateContacts: @"Contacts"
inContext: nil];
return [folderContainer subFolders];
}
- (NSArray *) personalContactInfos
{
SOGoContactFolders *folderContainer;
id <SOGoContactFolder> folder;
NSArray *contactInfos;
folderContainer = (SOGoContactFolders *) [[[self clientObject] lookupUserFolder] privateContacts: @"Contacts"
inContext: nil];
folder = [folderContainer lookupPersonalFolder: @"personal" ignoringRights: YES];
// If the folder doesn't exist anymore or if the database is down, we
// return an empty array.
if ([folder isKindOfClass: [NSException class]])
return [NSArray array];
contactInfos = [folder lookupContactsWithFilter: nil
onCriteria: nil
sortBy: @"c_cn"
ordering: NSOrderedAscending
inDomain: nil];
return contactInfos;
}
- (void) setCurrentFolder: (id) _currentFolder
{
ASSIGN (currentFolder, _currentFolder);
}
- (NSString *) currentContactFolderId
{
return [NSString stringWithFormat: @"/%@", [currentFolder nameInContainer]];
}
- (NSString *) currentContactFolderName
{
return [currentFolder displayName];
}
- (NSString *) currentContactFolderOwner
{
return [currentFolder ownerInContext: context];
}
- (NSString *) currentContactFolderClass
{
return ([currentFolder isKindOfClass: [SOGoContactSourceFolder class]]
? @"remote" : @"local");
}
/* requests */
- (BOOL) shouldTakeValuesFromRequest: (WORequest *) request
inContext: (WOContext*) localContext
{
return YES;
}
/* actions */
- (NSString *) _fixedFilename: (NSString *) filename
{
NSString *newFilename, *baseFilename, *extension;
unsigned int variation;
if (!attachedFiles)
attachedFiles = [NSMutableArray new];
newFilename = filename;
baseFilename = [filename stringByDeletingPathExtension];
extension = [filename pathExtension];
variation = 0;
while ([attachedFiles containsObject: newFilename])
{
variation++;
newFilename = [NSString stringWithFormat: @"%@-%d.%@", baseFilename,
variation, extension];
}
[attachedFiles addObject: newFilename];
return newFilename;
}
- (NSDictionary *) _scanAttachmentFilenamesInRequest: (id) httpBody
{
NSMutableDictionary *files;
NSDictionary *file;
NSArray *parts;
unsigned int count, max;
NGMimeBodyPart *part;
NGMimeContentDispositionHeaderField *header;
NSString *mimeType, *filename;
parts = [httpBody parts];
max = [parts count];
files = [NSMutableDictionary dictionaryWithCapacity: max];
for (count = 0; count < max; count++)
{
part = [parts objectAtIndex: count];
header = (NGMimeContentDispositionHeaderField *)[part headerForKey: @"content-disposition"];
if ([[header name] hasPrefix: @"attachments"])
{
mimeType = [(NGMimeType *)[part headerForKey: @"content-type"] stringValue];
filename = [self _fixedFilename: [header filename]];
file = [NSDictionary dictionaryWithObjectsAndKeys:
filename, @"filename",
mimeType, @"mimetype",
[part body], @"body",
nil];
[files setObject: file forKey: [NSString stringWithFormat: @"%@_%@", [header name], filename]];
}
}
return files;
}
- (NSException *) _saveAttachments
{
NSException *error;
WORequest *request;
NSEnumerator *allAttachments;
NSDictionary *attrs, *filenames;
NGMimeType *mimeType;
id httpBody;
SOGoDraftObject *co;
error = nil;
request = [context request];
mimeType = [[request httpRequest] contentType];
if ([[mimeType type] isEqualToString: @"multipart"])
{
httpBody = [[request httpRequest] body];
filenames = [self _scanAttachmentFilenamesInRequest: httpBody];
co = [self clientObject];
allAttachments = [filenames objectEnumerator];
while ((attrs = [allAttachments nextObject]) && !error)
{
error = [co saveAttachment: (NSData *) [attrs objectForKey: @"body"]
withMetadata: attrs];
// Keep the name of the last attachment saved
ASSIGN(currentAttachment, [attrs objectForKey: @"filename"]);
}
}
return error;
}
- (NSException *) _saveFormInfo
{
NSDictionary *info;
NSException *error;
SOGoDraftObject *co;
co = [self clientObject];
[co fetchInfo];
error = [self _saveAttachments];
if (!error)
{
info = [self storeInfo];
[co setHeaders: info];
[co setIsHTML: isHTML];
[co setText: (isHTML ? [NSString stringWithFormat: @"<html>%@</html>", text] : text)];;
error = [co storeInfo];
}
return error;
}
- (id) failedToSaveFormResponse: (NSString *) msg
{
NSDictionary *d;
d = [NSDictionary dictionaryWithObjectsAndKeys: msg, @"textStatus", nil];
return [self responseWithStatus: 500
andString: [d jsonRepresentation]];
}
/* attachment helper */
- (NSArray *) attachmentAttrs
{
SOGoDraftObject *co;
SOGoMailObject *mail;
NSArray *a;
co = [self clientObject];
if (!attachmentAttrs || ![co imap4URL])
{
[co fetchInfo];
if ((![co inReplyTo] || currentAttachment) && [co IMAP4ID] > -1)
{
// When currentAttachment is defined, it means we just attached a new file to the mail
mail = [[[SOGoMailObject alloc] initWithImap4URL: [co imap4URL] inContainer: [co container]] autorelease];
a = [mail fetchFileAttachmentKeys];
ASSIGN (attachmentAttrs, a);
}
}
if (currentAttachment)
{
// When currentAttachment is defined, only return the attributes of the last
// attachment saved
NSEnumerator *allAttachments;
NSDictionary* attrs;
allAttachments = [attachmentAttrs objectEnumerator];
while ((attrs = [allAttachments nextObject]))
{
if ([[attrs objectForKey: @"filename"] isEqualToString: currentAttachment])
{
return [NSArray arrayWithObject: attrs];
}
}
}
return attachmentAttrs;
}
- (BOOL) hasAttachments
{
return [[self attachmentAttrs] count] > 0 ? YES : NO;
}
- (id) defaultAction
{
SOGoDraftObject *co;
co = [self clientObject];
[co fetchInfo];
[self loadInfo: [co headers]];
[self setText: [co text]];
[self setSourceUID: [co IMAP4ID]];
[self setSourceFolder: [co sourceFolder]];
return self;
}
- (id <WOActionResults>) saveAction
{
id result;
result = [self _saveFormInfo];
if (!result)
{
result = [[self clientObject] save];
}
if (!result)
{
attachmentAttrs = nil;
NSArray *attrs = [self attachmentAttrs];
result = [self responseWithStatus: 200
andString: [attrs jsonRepresentation]];
}
else
result = [self failedToSaveFormResponse: [result reason]];
return result;
}
- (NSException *) validateForSend
{
NSException *error;
if (![self hasOneOrMoreRecipients])
error = [NSException exceptionWithHTTPStatus: 400 /* Bad Request */
reason: [self labelForKey: @"error_missingrecipients"]];
else
error = nil;
return error;
}
//
//
//
- (WOResponse *) sendAction
{
SOGoDraftObject *co;
NSDictionary *jsonResponse;
NSException *error;
NSMutableArray *errorMsg;
NSDictionary *messageSubmissions;
SOGoSystemDefaults *dd;
int messages_count, recipients_count;
messageSubmissions = [[SOGoCache sharedCache] messageSubmissionsCountForLogin: [[context activeUser] login]];
dd = [SOGoSystemDefaults sharedSystemDefaults];
messages_count = recipients_count = 0;
if (messageSubmissions)
{
unsigned int current_time, start_time, delta, block_time;
current_time = [[NSCalendarDate date] timeIntervalSince1970];
start_time = [[messageSubmissions objectForKey: @"InitialDate"] unsignedIntValue];
delta = current_time - start_time;
block_time = [dd messageSubmissionBlockInterval];
messages_count = [[messageSubmissions objectForKey: @"MessagesCount"] intValue];
recipients_count = [[messageSubmissions objectForKey: @"RecipientsCount"] intValue];
if ((messages_count >= [dd maximumMessageSubmissionCount] || recipients_count >= [dd maximumRecipientCount]) &&
delta <= block_time)
{
jsonResponse = [NSDictionary dictionaryWithObjectsAndKeys:
@"failure", @"status",
[self labelForKey: @"Tried to send too many mails. Please wait."],
@"message",
nil];
return [self responseWithStatus: 200
andString: [jsonResponse jsonRepresentation]];
}
if (delta > block_time ||
(delta >= [dd maximumSubmissionInterval] && messages_count < [dd maximumMessageSubmissionCount] && recipients_count < [dd maximumRecipientCount]))
{
[[SOGoCache sharedCache] setMessageSubmissionsCount: 0
recipientsCount: 0
forLogin: [[context activeUser] login]];
}
}
co = [self clientObject];
/* first, save form data */
error = [self validateForSend];
if (!error)
{
error = [self _saveFormInfo];
if (!error)
error = [co sendMail];
else
error = [self failedToSaveFormResponse: [error reason]];
}
if (error)
{
// Only the first line is translated
errorMsg = [NSMutableArray arrayWithArray: [[error reason] componentsSeparatedByString: @"\n"]];
[errorMsg replaceObjectAtIndex: 0
withObject: [self labelForKey: [errorMsg objectAtIndex: 0]]];
jsonResponse = [NSDictionary dictionaryWithObjectsAndKeys:
@"failure", @"status",
[errorMsg componentsJoinedByString: @"\n"],
@"message",
nil];
}
else
{
jsonResponse = [NSDictionary dictionaryWithObjectsAndKeys:
@"success", @"status",
[co sourceFolder], @"sourceFolder",
[NSNumber numberWithInt: [co sourceIMAP4ID]], @"sourceMessageID",
nil];
recipients_count += [[co allRecipients] count];
messages_count += 1;
if ([dd maximumMessageSubmissionCount] > 0 && [dd maximumRecipientCount] > 0)
{
[[SOGoCache sharedCache] setMessageSubmissionsCount: messages_count
recipientsCount: recipients_count
forLogin: [[context activeUser] login]];
}
}
return [self responseWithStatus: 200
andString: [jsonResponse jsonRepresentation]];
}
@end /* UIxMailEditor */
|