/
Compose.php
3325 lines (2901 loc) · 117 KB
/
Compose.php
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
<?php
/**
* Copyright 2002-2014 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (GPL). If you
* did not receive this file, see http://www.horde.org/licenses/gpl.
*
* @category Horde
* @copyright 2002-2014 Horde LLC
* @license http://www.horde.org/licenses/gpl GPL
* @package IMP
*/
/**
* The IMP_Compose:: class represents an outgoing mail message.
*
* @author Michael Slusarz <slusarz@horde.org>
* @category Horde
* @copyright 2002-2014 Horde LLC
* @license http://www.horde.org/licenses/gpl GPL
* @package IMP
*/
class IMP_Compose implements ArrayAccess, Countable, IteratorAggregate
{
/* The virtual path to save drafts. */
const VFS_DRAFTS_PATH = '.horde/imp/drafts';
/* Compose types. */
const COMPOSE = 0;
const REPLY = 1;
const REPLY_ALL = 2;
const REPLY_AUTO = 3;
const REPLY_LIST = 4;
const REPLY_SENDER = 5;
const FORWARD = 6;
const FORWARD_ATTACH = 7;
const FORWARD_AUTO = 8;
const FORWARD_BODY = 9;
const FORWARD_BOTH = 10;
const REDIRECT = 11;
const EDITASNEW = 12;
const TEMPLATE = 13;
/* Related part attribute name. */
const RELATED_ATTR = 'imp_related_attr';
/* The blockquote tag to use to indicate quoted text in HTML data. */
const HTML_BLOCKQUOTE = '<blockquote type="cite" style="border-left:2px solid blue;margin-left:2px;padding-left:12px;">';
/**
* Attachment ID counter.
*
* @var integer
*/
public $atcId = 0;
/**
* Mark as changed for purposes of storing in the session.
* Either empty, 'changed', or 'deleted'.
*
* @var string
*/
public $changed = '';
/**
* The charset to use for sending.
*
* @var string
*/
public $charset;
/**
* Attachment data.
*
* @var array
*/
protected $_atc = array();
/**
* The cache ID used to store object in session.
*
* @var string
*/
protected $_cacheid;
/**
* Various metadata for this message.
*
* @var array
*/
protected $_metadata = array();
/**
* The reply type.
*
* @var integer
*/
protected $_replytype = self::COMPOSE;
/**
* Constructor.
*
* @param string $cacheid The cache ID string.
*/
public function __construct($cacheid)
{
$this->_cacheid = $cacheid;
$this->charset = $GLOBALS['registry']->getEmailCharset();
}
/**
* Tasks to do upon unserialize().
*/
public function __wakeup()
{
$this->changed = '';
}
/**
* Destroys an IMP_Compose instance.
*
* @param string $action The action performed to cause the end of this
* instance. Either 'cancel', 'discard',
* 'save_draft', or 'send'.
*/
public function destroy($action)
{
switch ($action) {
case 'discard':
case 'send':
/* Delete the draft. */
$GLOBALS['injector']->getInstance('IMP_Message')->delete(
new IMP_Indices($this->getMetadata('draft_uid')),
array('nuke' => true)
);
break;
case 'save_draft':
/* Don't delete any drafts. */
$this->changed = 'deleted';
return;
case 'cancel':
if ($this->getMetadata('draft_auto')) {
$this->destroy('discard');
return;
}
// Fall-through
default:
// No-op
break;
}
$this->deleteAllAttachments();
$this->changed = 'deleted';
}
/**
* Gets metadata about the current object.
*
* @param string $name The metadata name.
*
* @return mixed The metadata value or null if it doesn't exist.
*/
public function getMetadata($name)
{
return isset($this->_metadata[$name])
? $this->_metadata[$name]
: null;
}
/**
* Saves a draft message.
*
* @param array $headers List of message headers (UTF-8).
* @param mixed $message Either the message text (string) or a
* Horde_Mime_Part object that contains the text
* to send.
* @param array $opts An array of options w/the following keys:
* <pre>
* - autosave: (boolean) Is this an auto-saved draft?
* - html: (boolean) Is this an HTML message?
* - priority: (string) The message priority ('high', 'normal', 'low').
* - readreceipt: (boolean) Add return receipt headers?
* </pre>
*
* @return string Notification text on success (not HTML encoded).
*
* @throws IMP_Compose_Exception
*/
public function saveDraft($headers, $message, array $opts = array())
{
$body = $this->_saveDraftMsg($headers, $message, $opts);
$ret = $this->_saveDraftServer($body);
$this->_metadata['draft_auto'] = !empty($opts['autosave']);
return $ret;
}
/**
* Prepare the draft message.
*
* @param array $headers List of message headers.
* @param mixed $message Either the message text (string) or a
* Horde_Mime_Part object that contains the text
* to send.
* @param array $opts An array of options w/the following keys:
* - html: (boolean) Is this an HTML message?
* - priority: (string) The message priority ('high', 'normal', 'low').
* - readreceipt: (boolean) Add return receipt headers?
* - verify_email: (boolean) Verify e-mail messages? Default: no.
*
* @return string The body text.
*
* @throws IMP_Compose_Exception
*/
protected function _saveDraftMsg($headers, $message, $opts)
{
$has_session = (bool)$GLOBALS['registry']->getAuth();
/* Set up the base message now. */
$base = $this->_createMimeMessage(new Horde_Mail_Rfc822_List(), $message, array(
'html' => !empty($opts['html']),
'noattach' => !$has_session,
'nofinal' => true
));
$base->isBasePart(true);
$recip_list = $this->recipientList($headers);
if (!empty($opts['verify_email'])) {
foreach ($recip_list['list'] as $val) {
try {
IMP::parseAddressList($val->writeAddress(true), array(
'validate' => true
));
} catch (Horde_Mail_Exception $e) {
throw new IMP_Compose_Exception(sprintf(
_("Saving the message failed because it contains an invalid e-mail address: %s."),
strval($val),
$e->getMessage()
), $e->getCode());
}
}
}
$headers = array_merge($headers, $recip_list['header']);
/* Initalize a header object for the draft. */
$draft_headers = $this->_prepareHeaders($headers, array_merge($opts, array('bcc' => true)));
/* Add information necessary to log replies/forwards when finally
* sent. */
$imp_imap = $GLOBALS['injector']->getInstance('IMP_Factory_Imap')->create();
if ($this->_replytype) {
try {
$indices = $this->getMetadata('indices');
$imap_url = new Horde_Imap_Client_Url();
$imap_url->hostspec = $imp_imap->getParam('hostspec');
list($imap_url->mailbox, $imap_url->uid) = $indices->getSingle();
$imap_url->protocol = $imp_imap->isImap() ? 'imap' : 'pop';
$imap_url->uidvalidity = $imap_url->mailbox->uidvalid;
$imap_url->username = $imp_imap->getParam('username');
switch ($this->replyType(true)) {
case self::FORWARD:
$draft_headers->addHeader('X-IMP-Draft-Forward', '<' . $imap_url . '>');
break;
case self::REPLY:
$draft_headers->addHeader('X-IMP-Draft-Reply', '<' . $imap_url . '>');
$draft_headers->addHeader('X-IMP-Draft-Reply-Type', $this->_replytype);
break;
}
} catch (Horde_Exception $e) {}
} else {
$draft_headers->addHeader('X-IMP-Draft', 'Yes');
}
return $base->toString(array(
'defserver' => $has_session ? $imp_imap->config->maildomain : null,
'headers' => $draft_headers
));
}
/**
* Save a draft message on the IMAP server.
*
* @param string $data The text of the draft message.
*
* @return string Status string (not HTML escaped).
*
* @throws IMP_Compose_Exception
*/
protected function _saveDraftServer($data)
{
if (!$drafts_mbox = IMP_Mailbox::getPref(IMP_Mailbox::MBOX_DRAFTS)) {
throw new IMP_Compose_Exception(_("Saving the draft failed. No drafts mailbox specified."));
}
/* Check for access to drafts mailbox. */
if (!$drafts_mbox->create()) {
throw new IMP_Compose_Exception(_("Saving the draft failed. Could not create a drafts mailbox."));
}
$append_flags = array(
Horde_Imap_Client::FLAG_DRAFT,
/* RFC 3503 [3.4] - MUST set MDNSent flag on draft message. */
Horde_Imap_Client::FLAG_MDNSENT
);
if (!$GLOBALS['prefs']->getValue('unseen_drafts')) {
$append_flags[] = Horde_Imap_Client::FLAG_SEEN;
}
$old_uid = $this->getMetadata('draft_uid');
/* Add the message to the mailbox. */
try {
$ids = $drafts_mbox->imp_imap->append($drafts_mbox, array(array('data' => $data, 'flags' => $append_flags)));
if ($old_uid) {
$GLOBALS['injector']->getInstance('IMP_Message')->delete($old_uid, array('nuke' => true));
}
$this->_metadata['draft_uid'] = $drafts_mbox->getIndicesOb($ids);
$this->changed = 'changed';
return sprintf(_("The draft has been saved to the \"%s\" mailbox."), $drafts_mbox->display);
} catch (IMP_Imap_Exception $e) {
return _("The draft was not successfully saved.");
}
}
/**
* Edits a message as new.
*
* @see resumeDraft().
*
* @param IMP_Indices $indices An indices object.
* @param array $opts Additional options:
* - format: (string) Force to this format.
* DEFAULT: Auto-determine.
*
* @return mixed See resumeDraft().
*
* @throws IMP_Compose_Exception
*/
public function editAsNew($indices, array $opts = array())
{
$ret = $this->_resumeDraft($indices, self::EDITASNEW, $opts);
$ret['type'] = self::EDITASNEW;
return $ret;
}
/**
* Edit an existing template message. Saving this template later
* (using saveTemplate()) will cause the original message to be deleted.
*
* @param IMP_Indices $indices An indices object.
*
* @return mixed See resumeDraft().
*
* @throws IMP_Compose_Exception
*/
public function editTemplate($indices)
{
$res = $this->useTemplate($indices);
$this->_metadata['template_uid_edit'] = $indices;
return $res;
}
/**
* Resumes a previously saved draft message.
*
* @param IMP_Indices $indices An indices object.
* @param array $opts Additional options:
* - format: (string) Force to this format.
* DEFAULT: Auto-determine.
*
* @return mixed An array with the following keys:
* - addr: (array) Address lists (to, cc, bcc; Horde_Mail_Rfc822_List
* objects).
* - body: (string) The text of the body part.
* - format: (string) The format of the body message ('html', 'text').
* - identity: (mixed) See IMP_Prefs_Identity#getMatchingIdentity().
* - priority: (string) The message priority.
* - readreceipt: (boolean) Add return receipt headers?
* - subject: (string) Formatted subject.
* - type: (integer) - The compose type.
*
* @throws IMP_Compose_Exception
*/
public function resumeDraft($indices, array $opts = array())
{
$res = $this->_resumeDraft($indices, null, $opts);
$this->_metadata['draft_uid'] = $indices;
return $res;
}
/**
* Uses a template to create a message.
*
* @see resumeDraft().
*
* @param IMP_Indices $indices An indices object.
* @param array $opts Additional options:
* - format: (string) Force to this format.
* DEFAULT: Auto-determine.
*
* @return mixed See resumeDraft().
*
* @throws IMP_Compose_Exception
*/
public function useTemplate($indices, array $opts = array())
{
$ret = $this->_resumeDraft($indices, self::TEMPLATE, $opts);
$ret['type'] = self::TEMPLATE;
return $ret;
}
/**
* Resumes a previously saved draft message.
*
* @param IMP_Indices $indices See resumeDraft().
* @param integer $type Compose type.
* @param array $opts Additional options:
* - format: (string) Force to this format.
* DEFAULT: Auto-determine.
*
* @return mixed See resumeDraft().
*
* @throws IMP_Compose_Exception
*/
protected function _resumeDraft($indices, $type, $opts)
{
global $injector, $prefs;
try {
$contents = $injector->getInstance('IMP_Factory_Contents')->create($indices);
} catch (IMP_Exception $e) {
throw new IMP_Compose_Exception($e);
}
$headers = $contents->getHeader();
$imp_draft = false;
if ($draft_url = $headers->getValue('x-imp-draft-reply')) {
if (is_null($type) &&
!($type = $headers->getValue('x-imp-draft-reply-type'))) {
$type = self::REPLY;
}
$imp_draft = self::REPLY;
} elseif ($draft_url = $headers->getValue('x-imp-draft-forward')) {
$imp_draft = self::FORWARD;
if (is_null($type)) {
$type = self::FORWARD;
}
} elseif ($headers->getValue('x-imp-draft')) {
$imp_draft = self::COMPOSE;
}
if (!empty($opts['format'])) {
$compose_html = ($opts['format'] == 'html');
} elseif ($prefs->getValue('compose_html')) {
$compose_html = true;
} else {
switch ($type) {
case self::EDITASNEW:
case self::FORWARD:
case self::FORWARD_BODY:
case self::FORWARD_BOTH:
$compose_html = $prefs->getValue('forward_format');
break;
case self::REPLY:
case self::REPLY_ALL:
case self::REPLY_LIST:
case self::REPLY_SENDER:
$compose_html = $prefs->getValue('reply_format');
break;
case self::TEMPLATE:
$compose_html = true;
break;
default:
/* If this is an draft saved by IMP, we know 100% for sure
* that if an HTML part exists, the user was composing in
* HTML. */
$compose_html = ($imp_draft !== false);
break;
}
}
$msg_text = $this->_getMessageText($contents, array(
'html' => $compose_html,
'imp_msg' => $imp_draft,
'toflowed' => false
));
if (empty($msg_text)) {
$body = '';
$format = 'text';
$text_id = 0;
} else {
/* Use charset at time of initial composition if this is an IMP
* draft. */
if ($imp_draft !== false) {
$this->charset = $msg_text['charset'];
}
$body = $msg_text['text'];
$format = $msg_text['mode'];
$text_id = $msg_text['id'];
}
$mime_message = $contents->getMIMEMessage();
/* Add attachments. */
if (($mime_message->getPrimaryType() == 'multipart') &&
($mime_message->getType() != 'multipart/alternative')) {
for ($i = 1; ; ++$i) {
if (intval($text_id) == $i) {
continue;
}
if (!($part = $contents->getMIMEPart($i))) {
break;
}
try {
$this->addAttachmentFromPart($part);
} catch (IMP_Compose_Exception $e) {
$GLOBALS['notification']->push($e, 'horde.warning');
}
}
}
$identity_id = null;
if (($fromaddr = $headers->getValue('from'))) {
$identity = $injector->getInstance('IMP_Identity');
$identity_id = $identity->getMatchingIdentity($fromaddr);
}
$alist = new Horde_Mail_Rfc822_List();
$addr = array(
'to' => clone $alist,
'cc' => clone $alist,
'bcc' => clone $alist
);
if ($type != self::EDITASNEW) {
foreach (array('to', 'cc', 'bcc') as $val) {
if ($tmp = $headers->getOb($val)) {
$addr[$val] = $tmp;
}
}
if ($val = $headers->getValue('references')) {
$ref_ob = new IMP_Compose_References();
$ref_ob->parse($val);
$this->_metadata['references'] = $ref_ob->references;
if ($val = $headers->getValue('in-reply-to')) {
$this->_metadata['in_reply_to'] = $val;
}
}
if ($draft_url) {
$imap_url = new Horde_Imap_Client_Url(rtrim(ltrim($draft_url, '<'), '>'));
$imp_imap = $injector->getInstance('IMP_Factory_Imap')->create();
try {
if (($imap_url->protocol == ($imp_imap->isImap() ? 'imap' : 'pop')) &&
($imap_url->username == $imp_imap->getParam('username')) &&
// Ignore hostspec and port, since these can change
// even though the server is the same. UIDVALIDITY
// should catch any true server/backend changes.
(IMP_Mailbox::get($imap_url->mailbox)->uidvalid == $imap_url->uidvalidity) &&
$injector->getInstance('IMP_Factory_Contents')->create(new IMP_Indices($imap_url->mailbox, $imap_url->uid))) {
$this->_metadata['indices'] = new IMP_Indices($imap_url->mailbox, $imap_url->uid);
$this->_replytype = $type;
}
} catch (Exception $e) {}
}
}
$mdn = new Horde_Mime_Mdn($headers);
$readreceipt = (bool)$mdn->getMdnReturnAddr();
$this->changed = 'changed';
return array(
'addr' => $addr,
'body' => $body,
'format' => $format,
'identity' => $identity_id,
'priority' => $injector->getInstance('IMP_Mime_Headers')->getPriority($headers),
'readreceipt' => $readreceipt,
'subject' => $headers->getValue('subject'),
'type' => $type
);
}
/**
* Save a template message on the IMAP server.
*
* @param array $headers List of message headers (UTF-8).
* @param mixed $message Either the message text (string) or a
* Horde_Mime_Part object that contains the text
* to save.
* @param array $opts An array of options w/the following keys:
* - html: (boolean) Is this an HTML message?
* - priority: (string) The message priority ('high', 'normal', 'low').
* - readreceipt: (boolean) Add return receipt headers?
*
* @return string Notification text on success.
*
* @throws IMP_Compose_Exception
*/
public function saveTemplate($headers, $message, array $opts = array())
{
if (!$mbox = IMP_Mailbox::getPref(IMP_Mailbox::MBOX_TEMPLATES)) {
throw new IMP_Compose_Exception(_("Saving the template failed: no template mailbox exists."));
}
/* Check for access to mailbox. */
if (!$mbox->create()) {
throw new IMP_Compose_Exception(_("Saving the template failed: could not create the templates mailbox."));
}
$append_flags = array(
// Don't mark as draft, since other MUAs could potentially
// delete it.
Horde_Imap_Client::FLAG_SEEN
);
$old_uid = $this->getMetadata('template_uid_edit');
/* Add the message to the mailbox. */
try {
$mbox->imp_imap->append($mbox, array(array(
'data' => $this->_saveDraftMsg($headers, $message, $opts),
'flags' => $append_flags,
'verify_email' => true
)));
if ($old_uid) {
$GLOBALS['injector']->getInstance('IMP_Message')->delete($old_uid, array('nuke' => true));
}
} catch (IMP_Imap_Exception $e) {
return _("The template was not successfully saved.");
}
return _("The template has been saved.");
}
/**
* Does this message have any drafts associated with it?
*
* @return boolean True if draft messages exist.
*/
public function hasDrafts()
{
return !empty($this->_metadata['draft_uid']);
}
/**
* Builds and sends a MIME message.
*
* @param string $body The message body.
* @param array $header List of message headers.
* @param IMP_Prefs_Identity $identity The Identity object for the sender
* of this message.
* @param array $opts An array of options w/the
* following keys:
* - encrypt: (integer) A flag whether to encrypt or sign the message.
* One of:
* - IMP_Crypt_Pgp::ENCRYPT</li>
* - IMP_Crypt_Pgp::SIGNENC</li>
* - IMP_Crypt_Smime::ENCRYPT</li>
* - IMP_Crypt_Smime::SIGNENC</li>
* - html: (boolean) Whether this is an HTML message.
* DEFAULT: false
* - pgp_attach_pubkey: (boolean) Attach the user's PGP public key to the
* message?
* - priority: (string) The message priority ('high', 'normal', 'low').
* - save_sent: (boolean) Save sent mail?
* - sent_mail: (IMP_Mailbox) The sent-mail mailbox (UTF-8).
* - save_attachments: (bool) Save attachments with the message?
* - signature: (string) The message signature.
* - readreceipt: (boolean) Add return receipt headers?
* - useragent: (string) The User-Agent string to use.
* - vcard_attach: (string) Attach the user's vCard (value is name to
* display as vcard filename).
*
* @throws Horde_Exception
* @throws IMP_Compose_Exception
* @throws IMP_Compose_Exception_Address
* @throws IMP_Exception
*/
public function buildAndSendMessage(
$body, $header, IMP_Prefs_Identity $identity, array $opts = array()
)
{
global $conf, $injector, $notification, $prefs, $registry;
/* We need at least one recipient & RFC 2822 requires that no 8-bit
* characters can be in the address fields. */
$recip = $this->recipientList($header);
if (!count($recip['list'])) {
if ($recip['has_input']) {
throw new IMP_Compose_Exception(_("Invalid e-mail address."));
}
throw new IMP_Compose_Exception(_("Need at least one message recipient."));
}
$header = array_merge($header, $recip['header']);
/* Check for correct identity usage. */
if (!$this->getMetadata('identity_check') &&
(count($recip['list']) === 1)) {
$identity_search = $identity->getMatchingIdentity($recip['list'], false);
if (!is_null($identity_search) &&
($identity->getDefault() != $identity_search)) {
$this->_metadata['identity_check'] = true;
$this->changed = 'changed';
$e = new IMP_Compose_Exception(_("Recipient address does not match the currently selected identity."));
$e->tied_identity = $identity_search;
throw $e;
}
}
/* Check body size of message. */
$imp_imap = $injector->getInstance('IMP_Factory_Imap')->create();
if (!$imp_imap->accessCompose(IMP_Imap::ACCESS_COMPOSE_BODYSIZE, strlen($body))) {
Horde::permissionDeniedError('imp', 'max_bodysize');
throw new IMP_Compose_Exception(sprintf(
_("Your message body has exceeded the limit by body size by %d characters."),
(strlen($body) - $imp_imap->max_compose_bodysize)
));
}
$from = new Horde_Mail_Rfc822_Address($header['from']);
if (is_null($from->host)) {
$from->host = $imp_imap->config->maildomain;
}
/* Prepare the array of messages to send out. May be more
* than one if we are encrypting for multiple recipients or
* are storing an encrypted message locally. */
$encrypt = empty($opts['encrypt']) ? 0 : $opts['encrypt'];
$send_msgs = array();
$msg_options = array(
'encrypt' => $encrypt,
'html' => !empty($opts['html']),
'identity' => $identity,
'pgp_attach_pubkey' => (!empty($opts['pgp_attach_pubkey']) && $prefs->getValue('use_pgp') && $prefs->getValue('pgp_public_key')),
'signature' => is_null($opts['signature']) ? $identity : $opts['signature'],
'vcard_attach' => ((!empty($opts['vcard_attach']) && $registry->hasMethod('contacts/ownVCard')) ? ((strlen($opts['vcard_attach']) ? $opts['vcard_attach'] : 'vcard') . '.vcf') : null)
);
/* Must encrypt & send the message one recipient at a time. */
if ($prefs->getValue('use_smime') &&
in_array($encrypt, array(IMP_Crypt_Smime::ENCRYPT, IMP_Crypt_Smime::SIGNENC))) {
foreach ($recip['list'] as $val) {
$list_ob = new Horde_Mail_Rfc822_List($val);
$send_msgs[] = array(
'base' => $this->_createMimeMessage($list_ob, $body, $msg_options),
'recipients' => $list_ob
);
}
/* Must target the encryption for the sender before saving message
* in sent-mail. */
$save_msg = $this->_createMimeMessage(IMP::parseAddressList($header['from']), $body, $msg_options);
} else {
/* Can send in clear-text all at once, or PGP can encrypt
* multiple addresses in the same message. */
$msg_options['from'] = $from;
$save_msg = $this->_createMimeMessage($recip['list'], $body, $msg_options);
$send_msgs[] = array(
'base' => $save_msg,
'recipients' => $recip['list']
);
}
/* Initalize a header object for the outgoing message. */
$headers = $this->_prepareHeaders($header, $opts);
/* Add a Received header for the hop from browser to server. */
$headers->addReceivedHeader(array(
'dns' => $injector->getInstance('Net_DNS2_Resolver'),
'server' => $conf['server']['name']
));
/* Add Reply-To header. */
if (!empty($header['replyto']) &&
($header['replyto'] != $from->bare_address)) {
$headers->addHeader('Reply-to', $header['replyto']);
}
/* Add the 'User-Agent' header. */
if (empty($opts['useragent'])) {
$headers->setUserAgent('Internet Messaging Program (IMP) ' . $registry->getVersion());
} else {
$headers->setUserAgent($opts['useragent']);
}
$headers->addUserAgentHeader();
/* Add preferred reply language(s). */
if ($lang = @unserialize($prefs->getValue('reply_lang'))) {
$headers->addHeader('Accept-Language', implode(',', $lang));
}
/* Send the messages out now. */
$sentmail = $injector->getInstance('IMP_Sentmail');
foreach ($send_msgs as $val) {
switch (intval($this->replyType(true))) {
case self::REPLY:
$senttype = IMP_Sentmail::REPLY;
break;
case self::FORWARD:
$senttype = IMP_Sentmail::FORWARD;
break;
case self::REDIRECT:
$senttype = IMP_Sentmail::REDIRECT;
break;
default:
$senttype = IMP_Sentmail::NEWMSG;
break;
}
try {
$this->_prepSendMessageAssert($val['recipients'], $headers, $val['base']);
$this->sendMessage($val['recipients'], $headers, $val['base']);
/* Store history information. */
$sentmail->log($senttype, $headers->getValue('message-id'), $val['recipients'], true);
} catch (IMP_Compose_Exception_Address $e) {
throw $e;
} catch (IMP_Compose_Exception $e) {
/* Unsuccessful send. */
if ($e->log()) {
$sentmail->log($senttype, $headers->getValue('message-id'), $val['recipients'], false);
}
throw new IMP_Compose_Exception(sprintf(_("There was an error sending your message: %s"), $e->getMessage()));
}
}
$recipients = strval($recip['list']);
if ($this->_replytype) {
/* Log the reply. */
if ($this->getMetadata('in_reply_to')) {
$injector->getInstance('IMP_Maillog')->log(
$this->_replytype,
$this->getMetadata('in_reply_to'),
$recipients
);
}
$imp_message = $injector->getInstance('IMP_Message');
$reply_uid = new IMP_Indices($this);
switch ($this->replyType(true)) {
case self::FORWARD:
/* Set the Forwarded flag, if possible, in the mailbox.
* See RFC 5550 [5.9] */
$imp_message->flag(array(
'add' => array(Horde_Imap_Client::FLAG_FORWARDED)
), $reply_uid);
break;
case self::REPLY:
/* Make sure to set the IMAP reply flag and unset any
* 'flagged' flag. */
$imp_message->flag(array(
'add' => array(Horde_Imap_Client::FLAG_ANSWERED),
'remove' => array(Horde_Imap_Client::FLAG_FLAGGED)
), $reply_uid);
break;
}
}
$entry = sprintf("%s Message sent to %s from %s", $_SERVER['REMOTE_ADDR'], $recipients, $registry->getAuth());
Horde::log($entry, 'INFO');
/* Should we save this message in the sent mail mailbox? */
if (!empty($opts['sent_mail']) &&
((!$prefs->isLocked('save_sent_mail') &&
!empty($opts['save_sent'])) ||
($prefs->isLocked('save_sent_mail') &&
$prefs->getValue('save_sent_mail')))) {
/* Keep Bcc: headers on saved messages. */
if (count($header['bcc'])) {
$headers->addHeader('Bcc', $header['bcc']);
}
/* Strip attachments if requested. */
if (empty($opts['save_attachments'])) {
$save_msg->buildMimeIds();
/* Don't strip any part if this is a text message with both
* plaintext and HTML representation. */
if ($save_msg->getType() != 'multipart/alternative') {
for ($i = 2; ; ++$i) {
if (!($oldPart = $save_msg->getPart($i))) {
break;
}
$replace_part = new Horde_Mime_Part();
$replace_part->setType('text/plain');
$replace_part->setCharset($this->charset);
$replace_part->setLanguage($GLOBALS['language']);
$replace_part->setContents('[' . _("Attachment stripped: Original attachment type") . ': "' . $oldPart->getType() . '", ' . _("name") . ': "' . $oldPart->getName(true) . '"]');
$save_msg->alterPart($i, $replace_part);
}
}
}
/* Generate the message string. */
$fcc = $save_msg->toString(array(
'defserver' => $imp_imap->config->maildomain,
'headers' => $headers,
'stream' => true
));
/* Make sure sent mailbox is created. */
$sent_mail = IMP_Mailbox::get($opts['sent_mail']);
$sent_mail->create();
$flags = array(
Horde_Imap_Client::FLAG_SEEN,
/* RFC 3503 [3.3] - MUST set MDNSent flag on sent message. */
Horde_Imap_Client::FLAG_MDNSENT
);
try {
$imp_imap->append($sent_mail, array(array('data' => $fcc, 'flags' => $flags)));
} catch (IMP_Imap_Exception $e) {
$notification->push(sprintf(_("Message sent successfully, but not saved to %s."), $sent_mail->display));
}
}
/* Delete the attachment data. */
$this->deleteAllAttachments();
/* Save recipients to address book? */
$this->_saveRecipients($recip['list']);
/* Call post-sent hook. */
try {
$injector->getInstance('Horde_Core_Hooks')->callHook(
'post_sent',
'imp',
array($save_msg['msg'], $headers)
);
} catch (Horde_Exception_HookNotSet $e) {}
}
/**
* Prepare header object with basic header fields and converts headers
* to the current compose charset.
*
* @param array $headers Array with 'from', 'to', 'cc', 'bcc', and
* 'subject' values.
* @param array $opts An array of options w/the following keys:
* - bcc: (boolean) Add BCC header to output.
* - priority: (string) The message priority ('high', 'normal', 'low').
*
* @return Horde_Mime_Headers Headers object with the appropriate headers
* set.
*/
protected function _prepareHeaders($headers, array $opts = array())
{
$ob = new Horde_Mime_Headers();
$ob->addHeader('Date', date('r'));
$ob->addMessageIdHeader();
if (isset($headers['from']) && strlen($headers['from'])) {
$ob->addHeader('From', $headers['from']);
}
if (isset($headers['to']) &&
(is_object($headers['to']) || strlen($headers['to']))) {
$ob->addHeader('To', $headers['to']);
} elseif (!isset($headers['cc'])) {
$ob->addHeader('To', 'undisclosed-recipients:;');
}
if (isset($headers['cc']) &&
(is_object($headers['cc']) || strlen($headers['cc']))) {
$ob->addHeader('Cc', $headers['cc']);
}
if (!empty($opts['bcc']) &&