389ccd8337e99116b8e14640fff01ad515a748df
[squirrelmail.git] / src / compose.php
1 <?php
2 /**
3 * compose.php
4 *
5 * This code sends a mail.
6 *
7 * There are 4 modes of operation:
8 * - Start new mail
9 * - Add an attachment
10 * - Send mail
11 * - Save As Draft
12 *
13 * @copyright &copy; 1999-2007 The SquirrelMail Project Team
14 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
15 * @version $Id$
16 * @package squirrelmail
17 */
18
19 /**
20 * Include the SquirrelMail initialization file.
21 */
22 require('../include/init.php');
23
24 /* SquirrelMail required files. */
25 require_once(SM_PATH . 'functions/imap_general.php');
26 require_once(SM_PATH . 'functions/imap_messages.php');
27 require_once(SM_PATH . 'functions/date.php');
28 require_once(SM_PATH . 'functions/mime.php');
29 require_once(SM_PATH . 'functions/compose.php');
30 require_once(SM_PATH . 'class/deliver/Deliver.class.php');
31 require_once(SM_PATH . 'functions/addressbook.php');
32 require_once(SM_PATH . 'functions/forms.php');
33 require_once(SM_PATH . 'functions/identity.php');
34
35 /* --------------------- Get globals ------------------------------------- */
36
37 /** SESSION VARS */
38 sqgetGlobalVar('delimiter', $delimiter, SQ_SESSION);
39
40 sqgetGlobalVar('composesession', $composesession, SQ_SESSION);
41 sqgetGlobalVar('compose_messages', $compose_messages, SQ_SESSION);
42 sqgetGlobalVar('delayed_errors', $delayed_errors, SQ_SESSION);
43
44 // Turn on delayed error handling in case we wind up redirecting below
45 $oErrorHandler->setDelayedErrors(true);
46
47 /** SESSION/POST/GET VARS */
48 sqgetGlobalVar('session',$session);
49 sqgetGlobalVar('mailbox',$mailbox);
50 if(!sqgetGlobalVar('identity',$identity)) {
51 $identity=0;
52 }
53 sqgetGlobalVar('send_to',$send_to);
54 sqgetGlobalVar('send_to_cc',$send_to_cc);
55 sqgetGlobalVar('send_to_bcc',$send_to_bcc);
56 sqgetGlobalVar('subject',$subject);
57 sqgetGlobalVar('body',$body);
58 sqgetGlobalVar('mailprio',$mailprio);
59 sqgetGlobalVar('request_mdn',$request_mdn);
60 sqgetGlobalVar('request_dr',$request_dr);
61 sqgetGlobalVar('html_addr_search',$html_addr_search);
62 sqgetGlobalVar('mail_sent',$mail_sent);
63 sqgetGlobalVar('passed_id',$passed_id);
64 sqgetGlobalVar('passed_ent_id',$passed_ent_id);
65 sqgetGlobalVar('send',$send);
66
67 sqgetGlobalVar('attach',$attach);
68
69 sqgetGlobalVar('draft',$draft);
70 sqgetGlobalVar('draft_id',$draft_id);
71 sqgetGlobalVar('ent_num',$ent_num);
72 sqgetGlobalVar('saved_draft',$saved_draft);
73
74 if ( sqgetGlobalVar('delete_draft',$delete_draft) ) {
75 $delete_draft = (int)$delete_draft;
76 }
77
78 if ( sqgetGlobalVar('startMessage',$startMessage) ) {
79 $startMessage = (int)$startMessage;
80 } else {
81 $startMessage = 1;
82 }
83
84
85 /** POST VARS */
86 sqgetGlobalVar('sigappend', $sigappend, SQ_POST);
87 sqgetGlobalVar('from_htmladdr_search', $from_htmladdr_search, SQ_POST);
88 sqgetGlobalVar('addr_search_done', $html_addr_search_done, SQ_POST);
89 sqgetGlobalVar('addr_search_cancel', $html_addr_search_cancel, SQ_POST);
90 sqgetGlobalVar('send_to_search', $send_to_search, SQ_POST);
91 sqgetGlobalVar('do_delete', $do_delete, SQ_POST);
92 sqgetGlobalVar('delete', $delete, SQ_POST);
93 sqgetGlobalVar('restoremessages', $restoremessages, SQ_POST);
94 if ( sqgetGlobalVar('return', $temp, SQ_POST) ) {
95 $html_addr_search_done = 'Use Addresses';
96 }
97
98 /** GET VARS */
99 sqgetGlobalVar('attachedmessages', $attachedmessages, SQ_GET);
100 if ( sqgetGlobalVar('account', $temp, SQ_GET) ) {
101 $iAccount = (int) $temp;
102 } else {
103 $iAccount = 0;
104 }
105
106
107 /** get smaction */
108 if ( !sqgetGlobalVar('smaction',$action) )
109 {
110 if ( sqgetGlobalVar('smaction_reply',$tmp) ) $action = 'reply';
111 if ( sqgetGlobalVar('smaction_reply_all',$tmp) ) $action = 'reply_all';
112 if ( sqgetGlobalVar('smaction_forward',$tmp) ) $action = 'forward';
113 if ( sqgetGlobalVar('smaction_attache',$tmp) ) $action = 'forward_as_attachment';
114 if ( sqgetGlobalVar('smaction_draft',$tmp) ) $action = 'draft';
115 if ( sqgetGlobalVar('smaction_edit_new',$tmp) ) $action = 'edit_as_new';
116 }
117
118 /**
119 * Here we decode the data passed in from mailto.php.
120 */
121 if ( sqgetGlobalVar('mailtodata', $mailtodata, SQ_GET) ) {
122 $trtable = array('to' => 'send_to',
123 'cc' => 'send_to_cc',
124 'bcc' => 'send_to_bcc',
125 'body' => 'body',
126 'subject' => 'subject');
127 $mtdata = unserialize($mailtodata);
128
129 foreach ($trtable as $f => $t) {
130 if ( !empty($mtdata[$f]) ) {
131 $$t = $mtdata[$f];
132 }
133 }
134 unset($mailtodata,$mtdata, $trtable);
135 }
136
137 /* Location (For HTTP 1.1 Header("Location: ...") redirects) */
138 $location = get_location();
139 /* Identities (fetch only once) */
140 $idents = get_identities();
141
142 /* --------------------- Specific Functions ------------------------------ */
143
144 function replyAllString($header) {
145 global $include_self_reply_all, $idents;
146 $excl_ar = array();
147 /**
148 * 1) Remove the addresses we'll be sending the message 'to'
149 */
150 if (isset($header->reply_to)) {
151 $excl_ar = $header->getAddr_a('reply_to');
152 }
153 /**
154 * 2) Remove our identities from the CC list (they still can be in the
155 * TO list) only if $include_self_reply_all is turned off
156 */
157 if (!$include_self_reply_all) {
158 foreach($idents as $id) {
159 $excl_ar[strtolower(trim($id['email_address']))] = '';
160 }
161 }
162
163 /**
164 * 3) get the addresses.
165 */
166 $url_replytoall_ar = $header->getAddr_a(array('to','cc'), $excl_ar);
167
168 /**
169 * 4) generate the string.
170 */
171 $url_replytoallcc = '';
172 foreach( $url_replytoall_ar as $email => $personal) {
173 if ($personal) {
174 // if personal name contains address separator then surround
175 // the personal name with double quotes.
176 if (strpos($personal,',') !== false) {
177 $personal = '"'.$personal.'"';
178 }
179 $url_replytoallcc .= ", $personal <$email>";
180 } else {
181 $url_replytoallcc .= ', '. $email;
182 }
183 }
184 $url_replytoallcc = substr($url_replytoallcc,2);
185
186 return $url_replytoallcc;
187 }
188
189 /**
190 * creates top line in reply citations
191 *
192 * Line style depends on user preferences.
193 * $orig_date argument is available only from 1.4.3 and 1.5.1 version.
194 * @param object $orig_from From: header object.
195 * @param integer $orig_date email's timestamp
196 * @return string reply citation
197 */
198 function getReplyCitation($orig_from, $orig_date) {
199 global $reply_citation_style, $reply_citation_start, $reply_citation_end;
200
201 if (!is_object($orig_from)) {
202 $sOrig_from = '';
203 } else {
204 $sOrig_from = decodeHeader($orig_from->getAddress(false),false,false,true);
205 }
206
207 /* First, return an empty string when no citation style selected. */
208 if (($reply_citation_style == '') || ($reply_citation_style == 'none')) {
209 return '';
210 }
211
212 /* Make sure our final value isn't an empty string. */
213 if ($sOrig_from == '') {
214 return '';
215 }
216
217 /* Otherwise, try to select the desired citation style. */
218 switch ($reply_citation_style) {
219 case 'author_said':
220 /**
221 * To translators: %s is for author's name
222 */
223 $full_reply_citation = sprintf(_("%s wrote:"),$sOrig_from);
224 break;
225 case 'quote_who':
226 $start = '<quote who="';
227 $end = '">';
228 $full_reply_citation = $start . $sOrig_from . $end;
229 break;
230 case 'date_time_author':
231 /**
232 * To translators:
233 * first %s is for date string, second %s is for author's name. Date uses
234 * formating from "D, F j, Y g:i a" and "D, F j, Y H:i" translations.
235 * Example string:
236 * "On Sat, December 24, 2004 23:59, Santa wrote:"
237 * If you have to put author's name in front of date string, check comments about
238 * argument swapping at http://www.php.net/sprintf
239 */
240 $full_reply_citation = sprintf(_("On %s, %s wrote:"), getLongDateString($orig_date), $sOrig_from);
241 break;
242 case 'user-defined':
243 $start = $reply_citation_start .
244 ($reply_citation_start == '' ? '' : ' ');
245 $end = $reply_citation_end;
246 $full_reply_citation = $start . $sOrig_from . $end;
247 break;
248 default:
249 return '';
250 }
251
252 /* Add line feed and return the citation string. */
253 return ($full_reply_citation . "\n");
254 }
255
256 /**
257 * Creates header fields in forwarded email body
258 *
259 * $default_charset global must be set correctly before you call this function.
260 * @param object $orig_header
261 * @return $string
262 */
263 function getforwardHeader($orig_header) {
264 global $editor_size, $default_charset;
265
266 // using own strlen function in order to detect correct string length
267 $display = array( _("Subject") => sq_strlen(_("Subject"),$default_charset),
268 _("From") => sq_strlen(_("From"),$default_charset),
269 _("Date") => sq_strlen(_("Date"),$default_charset),
270 _("To") => sq_strlen(_("To"),$default_charset),
271 _("Cc") => sq_strlen(_("Cc"),$default_charset) );
272 $maxsize = max($display);
273 $indent = str_pad('',$maxsize+2);
274 foreach($display as $key => $val) {
275 $display[$key] = $key .': '. str_pad('', $maxsize - $val);
276 }
277 $from = decodeHeader($orig_header->getAddr_s('from',"\n$indent"),false,false,true);
278 $from = str_replace('&nbsp;',' ',$from);
279 $to = decodeHeader($orig_header->getAddr_s('to',"\n$indent"),false,false,true);
280 $to = str_replace('&nbsp;',' ',$to);
281 $subject = decodeHeader($orig_header->subject,false,false,true);
282 $subject = str_replace('&nbsp;',' ',$subject);
283
284 // using own str_pad function in order to create correct string pad
285 $bodyTop = sq_str_pad(' '._("Original Message").' ',$editor_size -2,'-',STR_PAD_BOTH,$default_charset) .
286 "\n". $display[_("Subject")] . $subject . "\n" .
287 $display[_("From")] . $from . "\n" .
288 $display[_("Date")] . getLongDateString( $orig_header->date ). "\n" .
289 $display[_("To")] . $to . "\n";
290 if ($orig_header->cc != array() && $orig_header->cc !='') {
291 $cc = decodeHeader($orig_header->getAddr_s('cc',"\n$indent"),false,false,true);
292 $cc = str_replace('&nbsp;',' ',$cc);
293 $bodyTop .= $display[_("Cc")] .$cc . "\n";
294 }
295 $bodyTop .= str_pad('', $editor_size -2 , '-') .
296 "\n\n";
297 return $bodyTop;
298 }
299 /* ----------------------------------------------------------------------- */
300
301 /*
302 * If the session is expired during a post this restores the compose session
303 * vars.
304 */
305 if (sqsession_is_registered('session_expired_post')) {
306 sqgetGlobalVar('session_expired_post', $session_expired_post, SQ_SESSION);
307 /*
308 * extra check for username so we don't display previous post data from
309 * another user during this session.
310 */
311 if ($session_expired_post['username'] != $username) {
312 unset($session_expired_post);
313 sqsession_unregister('session_expired_post');
314 session_write_close();
315 } else {
316 // these are the vars that we can set from the expired composed session
317 $compo_var_list = array ( 'send_to', 'send_to_cc','body','startMessage',
318 'passed_body','use_signature','signature','attachments','subject','newmail',
319 'send_to_bcc', 'passed_id', 'mailbox', 'from_htmladdr_search', 'identity',
320 'draft_id', 'delete_draft', 'mailprio', 'edit_as_new', 'compose_messsages',
321 'composesession', 'request_mdn', 'request_dr');
322
323 foreach ($compo_var_list as $var) {
324 if ( isset($session_expired_post[$var]) && !isset($$var) ) {
325 $$var = $session_expired_post[$var];
326 }
327 }
328
329 $compose_messages = unserialize(urldecode($restoremessages));
330 sqsession_register($compose_messages,'compose_messages');
331 sqsession_register($composesession,'composesession');
332 if (isset($send)) {
333 unset($send);
334 }
335 $session_expired = true;
336 }
337 unset($session_expired_post);
338 sqsession_unregister('session_expired_post');
339 session_write_close();
340 if (!isset($mailbox)) {
341 $mailbox = '';
342 }
343 if ($compose_new_win == '1') {
344 compose_Header($color, $mailbox);
345 } else {
346 $sHeaderJs = (isset($sHeaderJs)) ? $sHeaderJs : '';
347 if (strpos($action, 'reply') !== false && $reply_focus) {
348 $sBodyTagJs = 'onload="checkForm(\''.$replyfocus.'\');"';
349 } else {
350 $sBodyTagJs = 'onload="checkForm();"';
351 }
352 displayPageHeader($color, $mailbox,$sHeaderJs,$sBodyTagJs);
353 }
354 showInputForm($session, false);
355 exit();
356 }
357 if (!isset($composesession)) {
358 $composesession = 0;
359 sqsession_register(0,'composesession');
360 } else {
361 $composesession = (int)$composesession;
362 }
363
364 if (!isset($session) || (isset($newmessage) && $newmessage)) {
365 sqsession_unregister('composesession');
366 $session = "$composesession" +1;
367 $composesession = $session;
368 sqsession_register($composesession,'composesession');
369 }
370 if (!isset($compose_messages)) {
371 $compose_messages = array();
372 }
373
374 if (!isset($compose_messages[$session]) || ($compose_messages[$session] == NULL)) {
375 $composeMessage = new Message();
376 $rfc822_header = new Rfc822Header();
377 $composeMessage->rfc822_header = $rfc822_header;
378 $composeMessage->reply_rfc822_header = '';
379 $compose_messages[$session] = $composeMessage;
380
381 sqsession_register($compose_messages,'compose_messages');
382 } else {
383 $composeMessage=$compose_messages[$session];
384 }
385
386 if (!isset($mailbox) || $mailbox == '' || ($mailbox == 'None')) {
387 $mailbox = 'INBOX';
388 }
389
390 if ($draft) {
391 /*
392 * Set $default_charset to correspond with the user's selection
393 * of language interface.
394 */
395 set_my_charset();
396 $composeMessage=$compose_messages[$session];
397 if (! deliverMessage($composeMessage, true)) {
398 showInputForm($session);
399 exit();
400 } else {
401 unset($compose_messages[$session]);
402 $draft_message = _("Draft Email Saved");
403 /* If this is a resumed draft, then delete the original */
404 if(isset($delete_draft)) {
405 $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, false);
406 sqimap_mailbox_select($imap_stream, $draft_folder);
407 // force bypass_trash=true because message should be saved when deliverMessage() returns true.
408 // in current implementation of sqimap_msgs_list_flag() single message id can
409 // be submitted as string. docs state that it should be array.
410 sqimap_msgs_list_delete($imap_stream, $draft_folder, $delete_draft, true);
411 if ($auto_expunge) {
412 sqimap_mailbox_expunge($imap_stream, $draft_folder, true);
413 }
414 sqimap_logout($imap_stream);
415 }
416
417 $oErrorHandler->saveDelayedErrors();
418 session_write_close();
419
420 if ($compose_new_win == '1') {
421 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
422 Header("Location: $location/compose.php?saved_draft=yes&session=$composesession");
423 } else {
424 echo ' <br><br><div style="text-align: center;"><a href="' . $location
425 . '/compose.php?saved_sent=yes&amp;session=' . $composesession . '">'
426 . _("Return") . '</a></div>';
427 }
428 exit();
429 } else {
430 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
431 Header("Location: $location/right_main.php?mailbox=" . urlencode($draft_folder) .
432 "&startMessage=1&note=".urlencode($draft_message));
433 } else {
434 echo ' <br><br><div style="text-align: center;"><a href="' . $location
435 . '/right_main.php?mailbox=' . urlencode($draft_folder)
436 . '&amp;startMessage=1&amp;note=' . urlencode($draft_message) .'">'
437 . _("Return") . '</a></div>';
438 }
439 exit();
440 }
441 }
442 }
443
444 if ($send) {
445 if (isset($_FILES['attachfile']) &&
446 $_FILES['attachfile']['tmp_name'] &&
447 $_FILES['attachfile']['tmp_name'] != 'none') {
448 $AttachFailure = saveAttachedFiles($session);
449 }
450 if (checkInput(false) && !isset($AttachFailure)) {
451 if ($mailbox == "All Folders") {
452 /* We entered compose via the search results page */
453 $mailbox = 'INBOX'; /* Send 'em to INBOX, that's safe enough */
454 }
455 $urlMailbox = urlencode (trim($mailbox));
456 if (! isset($passed_id)) {
457 $passed_id = 0;
458 }
459 /**
460 * Set $default_charset to correspond with the user's selection
461 * of language interface.
462 */
463 set_my_charset();
464 /**
465 * This is to change all newlines to \n
466 * We'll change them to \r\n later (in the sendMessage function)
467 */
468 $body = str_replace("\r\n", "\n", $body);
469 $body = str_replace("\r", "\n", $body);
470
471 /**
472 * Rewrap $body so that no line is bigger than $editor_size
473 */
474 $body = explode("\n", $body);
475 $newBody = '';
476 foreach ($body as $line) {
477 if( $line <> '-- ' ) {
478 $line = rtrim($line);
479 }
480 if (sq_strlen($line,$default_charset) <= $editor_size + 1) {
481 $newBody .= $line . "\n";
482 } else {
483 sqWordWrap($line, $editor_size,$default_charset);
484 $newBody .= $line . "\n";
485
486 }
487
488 }
489 $body = $newBody;
490
491 $composeMessage=$compose_messages[$session];
492
493 $Result = deliverMessage($composeMessage);
494
495 if ($Result)
496 $mail_sent = 'yes';
497 else
498 $mail_sent = 'no';
499
500 // NOTE: this hook changed in 1.5.2 from sending $Result and
501 // $composeMessage as args #2 and #3 to being in an array
502 // under arg #2
503 do_hook('compose_send_after', $temp=array(&$Result, &$composeMessage, &$mail_sent));
504 if (! $Result) {
505 showInputForm($session);
506 exit();
507 }
508 unset($compose_messages[$session]);
509
510 /* if it is resumed draft, delete draft message */
511 if ( isset($delete_draft)) {
512 $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, false);
513 sqimap_mailbox_select($imap_stream, $draft_folder);
514 // bypass_trash=true because message should be saved when deliverMessage() returns true.
515 // in current implementation of sqimap_msgs_list_flag() single message id can
516 // be submitted as string. docs state that it should be array.
517 sqimap_msgs_list_delete($imap_stream, $draft_folder, $delete_draft, true);
518 if ($auto_expunge) {
519 sqimap_mailbox_expunge($imap_stream, $draft_folder, true);
520 }
521 sqimap_logout($imap_stream);
522 }
523 /*
524 * Store the error array in the session because they will be lost on a redirect
525 */
526 $oErrorHandler->saveDelayedErrors();
527 session_write_close();
528
529 if ($compose_new_win == '1') {
530 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
531 Header("Location: $location/compose.php?mail_sent=$mail_sent");
532 } else {
533 echo ' <br><br><div style="text-align: center;"><a href="' . $location
534 . '/compose.php?mail_sent=$mail_sent">'
535 . _("Return") . '</a></div>';
536 }
537 exit();
538 } else {
539 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
540 Header("Location: $location/right_main.php?mailbox=$urlMailbox".
541 "&startMessage=$startMessage&mail_sent=$mail_sent");
542 } else {
543 echo ' <br><br><div style="text-align: center;"><a href="' . $location
544 . "/right_main.php?mailbox=$urlMailbox"
545 . "&amp;startMessage=$startMessage&amp;mail_sent=$mail_sent\">"
546 . _("Return") . '</a></div>';
547 }
548 exit();
549 }
550 } else {
551 if ($compose_new_win == '1') {
552 compose_Header($color, $mailbox);
553 }
554 else {
555 displayPageHeader($color, $mailbox);
556 }
557 if (isset($AttachFailure)) {
558 plain_error_message(_("Could not move/copy file. File not attached"),
559 $color);
560 }
561 checkInput(true);
562 showInputForm($session);
563 /* sqimap_logout($imapConnection); */
564 }
565 } elseif (isset($html_addr_search_done)) {
566 if ($compose_new_win == '1') {
567 compose_Header($color, $mailbox);
568 }
569 else {
570 displayPageHeader($color, $mailbox);
571 }
572
573 if (isset($send_to_search) && is_array($send_to_search)) {
574 foreach ($send_to_search as $k => $v) {
575 if (substr($k, 0, 1) == 'T') {
576 if ($send_to) {
577 $send_to .= ', ';
578 }
579 $send_to .= $v;
580 }
581 elseif (substr($k, 0, 1) == 'C') {
582 if ($send_to_cc) {
583 $send_to_cc .= ', ';
584 }
585 $send_to_cc .= $v;
586 }
587 elseif (substr($k, 0, 1) == 'B') {
588 if ($send_to_bcc) {
589 $send_to_bcc .= ', ';
590 }
591 $send_to_bcc .= $v;
592 }
593 }
594 }
595 showInputForm($session);
596 } elseif (isset($html_addr_search) && !isset($html_addr_search_cancel)) {
597 if (isset($_FILES['attachfile']) &&
598 $_FILES['attachfile']['tmp_name'] &&
599 $_FILES['attachfile']['tmp_name'] != 'none') {
600 if(saveAttachedFiles($session)) {
601 plain_error_message(_("Could not move/copy file. File not attached"));
602 }
603 }
604 /*
605 * I am using an include so as to elminiate an extra unnecessary
606 * click. If you can think of a better way, please implement it.
607 */
608 include_once('./addrbook_search_html.php');
609 } elseif (isset($attach)) {
610 if ($compose_new_win == '1') {
611 compose_Header($color, $mailbox);
612 } else {
613 displayPageHeader($color, $mailbox);
614 }
615 if (saveAttachedFiles($session)) {
616 plain_error_message(_("Could not move/copy file. File not attached"));
617 }
618 showInputForm($session);
619 }
620 elseif (isset($sigappend)) {
621 $signature = $idents[$identity]['signature'];
622
623 $body .= "\n\n".($prefix_sig==true? "-- \n":'').$signature;
624 if ($compose_new_win == '1') {
625 compose_Header($color, $mailbox);
626 } else {
627 displayPageHeader($color, $mailbox);
628 }
629 showInputForm($session);
630 } elseif (isset($do_delete)) {
631 if ($compose_new_win == '1') {
632 compose_Header($color, $mailbox);
633 } else {
634 displayPageHeader($color, $mailbox);
635 }
636
637 if (isset($delete) && is_array($delete)) {
638 $composeMessage = $compose_messages[$session];
639 foreach($delete as $index) {
640 if (!empty($composeMessage->entities) && isset($composeMessage->entities[$index])) {
641 $composeMessage->entities[$index]->purgeAttachments();
642 unset ($composeMessage->entities[$index]);
643 }
644 }
645 $new_entities = array();
646 foreach ($composeMessage->entities as $entity) {
647 $new_entities[] = $entity;
648 }
649 $composeMessage->entities = $new_entities;
650 $compose_messages[$session] = $composeMessage;
651 sqsession_register($compose_messages, 'compose_messages');
652 }
653 showInputForm($session);
654 } else {
655 /*
656 * This handles the default case as well as the error case
657 * (they had the same code) --> if (isset($smtpErrors))
658 */
659
660 if ($compose_new_win == '1') {
661 compose_Header($color, $mailbox);
662 } else {
663 displayPageHeader($color, $mailbox);
664 }
665
666 $newmail = true;
667
668 if (!isset($passed_ent_id)) {
669 $passed_ent_id = '';
670 }
671 if (!isset($passed_id)) {
672 $passed_id = '';
673 }
674 if (!isset($mailbox)) {
675 $mailbox = '';
676 }
677 if (!isset($action)) {
678 $action = '';
679 }
680
681 $values = newMail($mailbox,$passed_id,$passed_ent_id, $action, $session);
682
683 /* in case the origin is not read_body.php */
684 if (isset($send_to)) {
685 $values['send_to'] = $send_to;
686 }
687 if (isset($send_to_cc)) {
688 $values['send_to_cc'] = $send_to_cc;
689 }
690 if (isset($send_to_bcc)) {
691 $values['send_to_bcc'] = $send_to_bcc;
692 }
693 if (isset($subject)) {
694 $values['subject'] = $subject;
695 }
696 showInputForm($session, $values);
697 }
698
699 exit();
700
701 /**************** Only function definitions go below *************/
702
703 function getforwardSubject($subject)
704 {
705 if ((substr(strtolower($subject), 0, 4) != 'fwd:') &&
706 (substr(strtolower($subject), 0, 5) != '[fwd:') &&
707 (substr(strtolower($subject), 0, 6) != '[ fwd:')) {
708 $subject = '[Fwd: ' . $subject . ']';
709 }
710 return $subject;
711 }
712
713 /* This function is used when not sending or adding attachments */
714 function newMail ($mailbox='', $passed_id='', $passed_ent_id='', $action='', $session='') {
715 global $editor_size, $default_use_priority, $body, $idents,
716 $use_signature, $data_dir, $username,
717 $key, $imapServerAddress, $imapPort, $compose_messages,
718 $composeMessage, $body_quote, $request_mdn, $request_dr,
719 $default_use_mdn, $mdn_user_support;
720 global $languages, $squirrelmail_language, $default_charset;
721
722 /*
723 * Set $default_charset to correspond with the user's selection
724 * of language interface. $default_charset global is not correct,
725 * if message is composed in new window.
726 */
727 set_my_charset();
728
729 $send_to = $send_to_cc = $send_to_bcc = $subject = $identity = '';
730 $mailprio = 3;
731
732 if ($passed_id) {
733 $imapConnection = sqimap_login($username, false, $imapServerAddress,
734 $imapPort, 0);
735
736 sqimap_mailbox_select($imapConnection, $mailbox);
737 $message = sqimap_get_message($imapConnection, $passed_id, $mailbox);
738
739 $body = '';
740 if ($passed_ent_id) {
741 /* redefine the messsage in case of message/rfc822 */
742 $message = $message->getEntity($passed_ent_id);
743 /* message is an entity which contains the envelope and type0=message
744 * and type1=rfc822. The actual entities are childs from
745 * $message->entities[0]. That's where the encoding and is located
746 */
747
748 $entities = $message->entities[0]->findDisplayEntity
749 (array(), $alt_order = array('text/plain'));
750 if (!count($entities)) {
751 $entities = $message->entities[0]->findDisplayEntity
752 (array(), $alt_order = array('text/plain','html/plain'));
753 }
754 $orig_header = $message->rfc822_header; /* here is the envelope located */
755 /* redefine the message for picking up the attachments */
756 $message = $message->entities[0];
757
758 } else {
759 $entities = $message->findDisplayEntity (array(), $alt_order = array('text/plain'));
760 if (!count($entities)) {
761 $entities = $message->findDisplayEntity (array(), $alt_order = array('text/plain','html/plain'));
762 }
763 $orig_header = $message->rfc822_header;
764 }
765
766 $type0 = $message->type0;
767 $type1 = $message->type1;
768 foreach ($entities as $ent) {
769 $msg = $message->getEntity($ent);
770 $type0 = $msg->type0;
771 $type1 = $msg->type1;
772 $unencoded_bodypart = mime_fetch_body($imapConnection, $passed_id, $ent);
773 $body_part_entity = $message->getEntity($ent);
774 $bodypart = decodeBody($unencoded_bodypart,
775 $body_part_entity->header->encoding);
776 if ($type1 == 'html') {
777 $bodypart = str_replace("\n", ' ', $bodypart);
778 $bodypart = preg_replace(array('/<\/?p>/i','/<div><\/div>/i','/<br\s*(\/)*>/i','/<\/?div>/i'), "\n", $bodypart);
779 $bodypart = str_replace(array('&nbsp;','&gt;','&lt;'),array(' ','>','<'),$bodypart);
780 $bodypart = strip_tags($bodypart);
781 }
782 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
783 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
784 if (mb_detect_encoding($bodypart) != 'ASCII') {
785 $bodypart = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode', $bodypart);
786 }
787 }
788
789 // charset encoding in compose form stuff
790 if (isset($body_part_entity->header->parameters['charset'])) {
791 $actual = $body_part_entity->header->parameters['charset'];
792 } else {
793 $actual = 'us-ascii';
794 }
795
796 if ( $actual && is_conversion_safe($actual) && $actual != $default_charset){
797 $bodypart = charset_convert($actual,$bodypart,$default_charset,false);
798 }
799 // end of charset encoding in compose
800
801 $body .= $bodypart;
802 }
803 if ($default_use_priority) {
804 $mailprio = substr($orig_header->priority,0,1);
805 if (!$mailprio) {
806 $mailprio = 3;
807 }
808 } else {
809 $mailprio = '';
810 }
811
812 $identity = '';
813 $from_o = $orig_header->from;
814 if (is_array($from_o)) {
815 if (isset($from_o[0])) {
816 $from_o = $from_o[0];
817 }
818 }
819 if (is_object($from_o)) {
820 $orig_from = $from_o->getAddress();
821 } else {
822 $orig_from = '';
823 }
824
825 $identities = array();
826 if (count($idents) > 1) {
827 foreach($idents as $nr=>$data) {
828 $enc_from_name = '"'.$data['full_name'].'" <'. $data['email_address'].'>';
829 if($enc_from_name == $orig_from) {
830 $identity = $nr;
831 break;
832 }
833 $identities[] = $enc_from_name;
834 }
835
836 $identity_match = $orig_header->findAddress($identities);
837 if ($identity_match) {
838 $identity = $identity_match;
839 }
840 }
841
842 switch ($action) {
843 case ('draft'):
844 $use_signature = FALSE;
845 $composeMessage->rfc822_header = $orig_header;
846 $send_to = decodeHeader($orig_header->getAddr_s('to'),false,false,true);
847 $send_to_cc = decodeHeader($orig_header->getAddr_s('cc'),false,false,true);
848 $send_to_bcc = decodeHeader($orig_header->getAddr_s('bcc'),false,false,true);
849 $send_from = $orig_header->getAddr_s('from');
850 $send_from_parts = new AddressStructure();
851 $send_from_parts = $orig_header->parseAddress($send_from);
852 $send_from_add = $send_from_parts->mailbox . '@' . $send_from_parts->host;
853 $identities = get_identities();
854 if (count($identities) > 0) {
855 foreach($identities as $iddata) {
856 if ($send_from_add == $iddata['email_address']) {
857 $identity = $iddata['index'];
858 break;
859 }
860 }
861 }
862 $subject = decodeHeader($orig_header->subject,false,false,true);
863
864 // Remember the receipt settings
865 $request_mdn = $mdn_user_support && !empty($orig_header->dnt) ? '1' : '0';
866 $request_dr = $mdn_user_support && !empty($orig_header->drnt) ? '1' : '0';
867
868 /* remember the references and in-reply-to headers in case of an reply */
869 $composeMessage->rfc822_header->more_headers['References'] = $orig_header->references;
870 $composeMessage->rfc822_header->more_headers['In-Reply-To'] = $orig_header->in_reply_to;
871 // rewrap the body to clean up quotations and line lengths
872 sqBodyWrap($body, $editor_size);
873 $composeMessage = getAttachments($message, $composeMessage, $passed_id, $entities, $imapConnection);
874 break;
875 case ('edit_as_new'):
876 $send_to = decodeHeader($orig_header->getAddr_s('to'),false,false,true);
877 $send_to_cc = decodeHeader($orig_header->getAddr_s('cc'),false,false,true);
878 $send_to_bcc = decodeHeader($orig_header->getAddr_s('bcc'),false,false,true);
879 $subject = decodeHeader($orig_header->subject,false,false,true);
880 $mailprio = $orig_header->priority;
881 $orig_from = '';
882 $composeMessage = getAttachments($message, $composeMessage, $passed_id, $entities, $imapConnection);
883 // rewrap the body to clean up quotations and line lengths
884 sqBodyWrap($body, $editor_size);
885 break;
886 case ('forward'):
887 $send_to = '';
888 $subject = getforwardSubject(decodeHeader($orig_header->subject,false,false,true));
889 $body = getforwardHeader($orig_header) . $body;
890 // the logic for calling sqUnWordWrap here would be to allow the browser to wrap the lines
891 // forwarded message text should be as undisturbed as possible, so commenting out this call
892 // sqUnWordWrap($body);
893 $composeMessage = getAttachments($message, $composeMessage, $passed_id, $entities, $imapConnection);
894
895 //add a blank line after the forward headers
896 $body = "\n" . $body;
897 break;
898 case ('forward_as_attachment'):
899 $subject = getforwardSubject(decodeHeader($orig_header->subject,false,false,true));
900 $composeMessage = getMessage_RFC822_Attachment($message, $composeMessage, $passed_id, $passed_ent_id, $imapConnection);
901 $body = '';
902 break;
903 case ('reply_all'):
904 if(isset($orig_header->mail_followup_to) && $orig_header->mail_followup_to) {
905 $send_to = $orig_header->getAddr_s('mail_followup_to');
906 } else {
907 $send_to_cc = replyAllString($orig_header);
908 $send_to_cc = decodeHeader($send_to_cc,false,false,true);
909 }
910 case ('reply'):
911 // skip this if send_to was already set right above here
912 if(!$send_to) {
913 $send_to = $orig_header->reply_to;
914 if (is_array($send_to) && count($send_to)) {
915 $send_to = $orig_header->getAddr_s('reply_to');
916 } else if (is_object($send_to)) { /* unneccesarry, just for failsafe purpose */
917 $send_to = $orig_header->getAddr_s('reply_to');
918 } else {
919 $send_to = $orig_header->getAddr_s('from');
920 }
921 }
922 $send_to = decodeHeader($send_to,false,false,true);
923 $subject = decodeHeader($orig_header->subject,false,false,true);
924 $subject = str_replace('"', "'", $subject);
925 $subject = trim($subject);
926 if (substr(strtolower($subject), 0, 3) != 're:') {
927 $subject = 'Re: ' . $subject;
928 }
929 /* this corrects some wrapping/quoting problems on replies */
930 $rewrap_body = explode("\n", $body);
931 $from = (is_array($orig_header->from)) ? $orig_header->from[0] : $orig_header->from;
932 $body = '';
933 $strip_sigs = getPref($data_dir, $username, 'strip_sigs');
934 foreach ($rewrap_body as $line) {
935 if ($strip_sigs && substr($line,0,3) == '-- ') {
936 break;
937 }
938 if (preg_match("/^(>+)/", $line, $matches)) {
939 $gt = $matches[1];
940 $body .= $body_quote . str_replace("\n", "\n$body_quote$gt ", rtrim($line)) ."\n";
941 } else {
942 $body .= $body_quote . (!empty($body_quote) ? ' ' : '') . str_replace("\n", "\n$body_quote" . (!empty($body_quote) ? ' ' : ''), rtrim($line)) . "\n";
943 }
944 }
945
946 //rewrap the body to clean up quotations and line lengths
947 $body = sqBodyWrap ($body, $editor_size);
948
949 $body = getReplyCitation($from , $orig_header->date) . $body;
950 $composeMessage->reply_rfc822_header = $orig_header;
951
952 break;
953 default:
954 break;
955 }
956 $compose_messages[$session] = $composeMessage;
957 sqsession_register($compose_messages, 'compose_messages');
958 session_write_close();
959 sqimap_logout($imapConnection);
960 }
961 $ret = array( 'send_to' => $send_to,
962 'send_to_cc' => $send_to_cc,
963 'send_to_bcc' => $send_to_bcc,
964 'subject' => $subject,
965 'mailprio' => $mailprio,
966 'body' => $body,
967 'identity' => $identity );
968
969 return ($ret);
970 } /* function newMail() */
971
972 /**
973 * downloads attachments from original message, stores them in attachment directory and adds
974 * them to composed message.
975 * @param object $message
976 * @param object $composeMessage
977 * @param integer $passed_id
978 * @param mixed $entities
979 * @param mixed $imapConnection
980 * @return object
981 */
982 function getAttachments($message, &$composeMessage, $passed_id, $entities, $imapConnection) {
983 global $squirrelmail_language, $languages;
984
985 if (!count($message->entities) ||
986 ($message->type0 == 'message' && $message->type1 == 'rfc822')) {
987 if ( !in_array($message->entity_id, $entities) && $message->entity_id) {
988 switch ($message->type0) {
989 case 'message':
990 if ($message->type1 == 'rfc822') {
991 $filename = $message->rfc822_header->subject;
992 if ($filename == "") {
993 $filename = "untitled-".$message->entity_id;
994 }
995 $filename .= '.msg';
996 } else {
997 $filename = $message->getFilename();
998 }
999 break;
1000 default:
1001 if (!$message->mime_header) { /* temporary hack */
1002 $message->mime_header = $message->header;
1003 }
1004 $filename = $message->getFilename();
1005 break;
1006 }
1007 $filename = str_replace('&#32;', ' ', decodeHeader($filename));
1008 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1009 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encode')) {
1010 $filename = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encode', $filename);
1011 }
1012 $localfilename = sq_get_attach_tempfile();
1013 $message->att_local_name = $localfilename;
1014
1015 $composeMessage->initAttachment($message->type0.'/'.$message->type1,$filename,
1016 $localfilename);
1017
1018 /* Write Attachment to file */
1019 $fp = fopen ($localfilename, 'wb');
1020 mime_print_body_lines ($imapConnection, $passed_id, $message->entity_id, $message->header->encoding, $fp);
1021 fclose ($fp);
1022 }
1023 } else {
1024 for ($i=0, $entCount=count($message->entities); $i<$entCount;$i++) {
1025 $composeMessage=getAttachments($message->entities[$i], $composeMessage, $passed_id, $entities, $imapConnection);
1026 }
1027 }
1028 return $composeMessage;
1029 }
1030
1031 function getMessage_RFC822_Attachment($message, $composeMessage, $passed_id,
1032 $passed_ent_id='', $imapConnection) {
1033 if (!$passed_ent_id) {
1034 $body_a = sqimap_run_command($imapConnection,
1035 'FETCH '.$passed_id.' RFC822',
1036 TRUE, $response, $readmessage,
1037 TRUE);
1038 } else {
1039 $body_a = sqimap_run_command($imapConnection,
1040 'FETCH '.$passed_id.' BODY['.$passed_ent_id.']',
1041 TRUE, $response, $readmessage, TRUE);
1042 $message = $message->parent;
1043 }
1044 if ($response == 'OK') {
1045 $subject = encodeHeader($message->rfc822_header->subject);
1046 array_shift($body_a);
1047 array_pop($body_a);
1048 $body = implode('', $body_a) . "\r\n";
1049
1050 $localfilename = sq_get_attach_tempfile();
1051 $fp = fopen($localfilename, 'wb');
1052 fwrite ($fp, $body);
1053 fclose($fp);
1054 $composeMessage->initAttachment('message/rfc822',$subject.'.msg',
1055 $localfilename);
1056 }
1057 return $composeMessage;
1058 }
1059
1060 function showInputForm ($session, $values=false) {
1061 global $send_to, $send_to_cc, $body, $startMessage, $action,
1062 $color, $use_signature, $signature, $prefix_sig,
1063 $editor_size, $editor_height, $subject, $newmail,
1064 $use_javascript_addr_book, $send_to_bcc, $passed_id, $mailbox,
1065 $from_htmladdr_search, $location_of_buttons, $attachment_dir,
1066 $username, $data_dir, $identity, $idents, $delete_draft,
1067 $mailprio, $compose_new_win, $saved_draft, $mail_sent, $sig_first,
1068 $compose_messages, $composesession, $default_charset,
1069 $compose_onsubmit, $oTemplate, $oErrorHandler;
1070
1071 if (checkForJavascript()) {
1072 $onfocus = ' onfocus="alreadyFocused=true;"';
1073 $onfocus_array = array('onfocus' => 'alreadyFocused=true;');
1074 }
1075 else {
1076 $onfocus = '';
1077 $onfocus_array = array();
1078 }
1079
1080 $composeMessage = $compose_messages[$session];
1081 if ($values) {
1082 $send_to = $values['send_to'];
1083 $send_to_cc = $values['send_to_cc'];
1084 $send_to_bcc = $values['send_to_bcc'];
1085 $subject = $values['subject'];
1086 $mailprio = $values['mailprio'];
1087 $body = $values['body'];
1088 $identity = (int) $values['identity'];
1089 } else {
1090 $send_to = decodeHeader($send_to, true, false);
1091 $send_to_cc = decodeHeader($send_to_cc, true, false);
1092 $send_to_bcc = decodeHeader($send_to_bcc, true, false);
1093 }
1094
1095 if ($use_javascript_addr_book) {
1096 echo "\n". '<script type="text/javascript">'."\n<!--\n" .
1097 'function open_abook() { ' . "\n" .
1098 ' var nwin = window.open("addrbook_popup.php","abookpopup",' .
1099 '"width=670,height=300,resizable=yes,scrollbars=yes");' . "\n" .
1100 ' if((!nwin.opener) && (document.windows != null))' . "\n" .
1101 ' nwin.opener = document.windows;' . "\n" .
1102 "}\n" .
1103 "// -->\n</script>\n\n";
1104 }
1105
1106 echo "\n" . '<form name="compose" action="compose.php" method="post" ' .
1107 'enctype="multipart/form-data"';
1108
1109 $compose_onsubmit = array();
1110 global $null;
1111 do_hook('compose_form', $null);
1112
1113 // Plugins that use compose_form hook can add an array entry
1114 // to the globally scoped $compose_onsubmit; we add them up
1115 // here and format the form tag's full onsubmit handler.
1116 // Each plugin should use "return false" if they need to
1117 // stop form submission but otherwise should NOT use "return
1118 // true" to give other plugins the chance to do what they need
1119 // to do; SquirrelMail itself will add the final "return true".
1120 // Onsubmit text is enclosed inside of double quotes, so plugins
1121 // need to quote accordingly.
1122 if (checkForJavascript()) {
1123 $onsubmit_text = ' onsubmit="';
1124 if (empty($compose_onsubmit))
1125 $compose_onsubmit = array();
1126 else if (!is_array($compose_onsubmit))
1127 $compose_onsubmit = array($compose_onsubmit);
1128
1129 foreach ($compose_onsubmit as $text) {
1130 $text = trim($text);
1131 if (substr($text, -1) != ';' && substr($text, -1) != '}')
1132 $text .= '; ';
1133 $onsubmit_text .= $text;
1134 }
1135
1136 echo $onsubmit_text . ' return true;"';
1137 }
1138
1139
1140 echo ">\n";
1141
1142 echo addHidden('startMessage', $startMessage);
1143
1144 if ($action == 'draft') {
1145 echo addHidden('delete_draft', $passed_id);
1146 }
1147 if (isset($delete_draft)) {
1148 echo addHidden('delete_draft', $delete_draft);
1149 }
1150 if (isset($session)) {
1151 echo addHidden('session', $session);
1152 }
1153
1154 if (isset($passed_id)) {
1155 echo addHidden('passed_id', $passed_id);
1156 }
1157
1158 if ($saved_draft == 'yes') {
1159 $oTemplate->assign('note', _("Draft Saved"));
1160 $oTemplate->display('note.tpl');
1161 }
1162 if ($mail_sent == 'yes') {
1163 $oTemplate->assign('note', _("Your message has been sent."));
1164 $oTemplate->display('note.tpl');
1165 }
1166 if ($compose_new_win == '1') {
1167 $oTemplate->display('compose_newwin_close.tpl');
1168 }
1169
1170 if ($location_of_buttons == 'top') {
1171 showComposeButtonRow();
1172 }
1173
1174 $identities = array();
1175 if (count($idents) > 1) {
1176 reset($idents);
1177 foreach($idents as $id => $data) {
1178 $identities[$id] = $data['full_name'].' &lt;'.$data['email_address'].'&gt;';
1179 }
1180 }
1181
1182 $oTemplate->assign('identities', $identities);
1183 $oTemplate->assign('identity_def', $identity);
1184 $oTemplate->assign('input_onfocus', 'onfocus="'.join(' ', $onfocus_array).'"');
1185
1186 $oTemplate->assign('to', htmlspecialchars($send_to));
1187 $oTemplate->assign('cc', htmlspecialchars($send_to_cc));
1188 $oTemplate->assign('bcc', htmlspecialchars($send_to_bcc));
1189 $oTemplate->assign('subject', htmlspecialchars($subject));
1190
1191 $oTemplate->display('compose_header.tpl');
1192
1193 if ($location_of_buttons == 'between') {
1194 showComposeButtonRow();
1195 }
1196
1197 $body_str = '';
1198 if ($use_signature == true && $newmail == true && !isset($from_htmladdr_search)) {
1199 $signature = $idents[$identity]['signature'];
1200
1201 if ($sig_first == '1') {
1202 /*
1203 * FIXME: test is specific to ja_JP translation implementation.
1204 * This test might apply incorrect conversion to other translations, but
1205 * use of 7bit iso-2022-jp charset in other translations might have other
1206 * issues too.
1207 */
1208 if ($default_charset == 'iso-2022-jp') {
1209 $body_str = "\n\n".($prefix_sig==true? "-- \n":'').mb_convert_encoding($signature, 'EUC-JP');
1210 } else {
1211 $body_str = "\n\n".($prefix_sig==true? "-- \n":'').decodeHeader($signature,false,false);
1212 }
1213 $body_str .= "\n\n".htmlspecialchars(decodeHeader($body,false,false));
1214 } else {
1215 $body_str = "\n\n".htmlspecialchars(decodeHeader($body,false,false));
1216 // FIXME: test is specific to ja_JP translation implementation. See above comments.
1217 if ($default_charset == 'iso-2022-jp') {
1218 $body_str .= "\n\n".($prefix_sig==true? "-- \n":'').mb_convert_encoding($signature, 'EUC-JP');
1219 } else {
1220 $body_str .= "\n\n".($prefix_sig==true? "-- \n":'').decodeHeader($signature,false,false);
1221 }
1222 }
1223 } else {
1224 $body_str = htmlspecialchars(decodeHeader($body,false,false));
1225 }
1226
1227 $oTemplate->assign('editor_width', (int)$editor_size);
1228 $oTemplate->assign('editor_height', (int)$editor_height);
1229 $oTemplate->assign('input_onfocus', 'onfocus="'.join(' ', $onfocus_array).'"');
1230 $oTemplate->assign('body', $body_str);
1231 $oTemplate->assign('show_bottom_send', $location_of_buttons!='bottom');
1232
1233 $oTemplate->display ('compose_body.tpl');
1234
1235 if ($location_of_buttons == 'bottom') {
1236 showComposeButtonRow();
1237 }
1238
1239 /* This code is for attachments */
1240 if ((bool) ini_get('file_uploads')) {
1241
1242 /* Calculate the max size for an uploaded file.
1243 * This is advisory for the user because we can't actually prevent
1244 * people to upload too large files. */
1245 $sizes = array();
1246 /* php.ini vars which influence the max for uploads */
1247 $configvars = array('post_max_size', 'memory_limit', 'upload_max_filesize');
1248 foreach($configvars as $var) {
1249 /* skip 0 or empty values, and -1 which means 'unlimited' */
1250 if( $size = getByteSize(ini_get($var)) ) {
1251 if ( $size != '-1' ) {
1252 $sizes[] = $size;
1253 }
1254 }
1255 }
1256
1257 $attach = array();
1258 if ($composeMessage->entities) {
1259 foreach ($composeMessage->entities as $key => $attachment) {
1260 $attached_file = $attachment->att_local_name;
1261 if ($attachment->att_local_name || $attachment->body_part) {
1262 $attached_filename = decodeHeader($attachment->mime_header->getParameter('name'));
1263 $type = $attachment->mime_header->type0.'/'.
1264 $attachment->mime_header->type1;
1265
1266 $a = array();
1267 $a['Key'] = $key;
1268 $a['FileName'] = $attached_filename;
1269 $a['ContentType'] = $type;
1270 $a['Size'] = filesize($attached_file);
1271 $attach[$key] = $a;
1272 }
1273 }
1274 }
1275
1276 $max = min($sizes);
1277 $oTemplate->assign('max_file_size', empty($max) ? -1 : $max);
1278 $oTemplate->assign('attachments', $attach);
1279
1280 $oTemplate->display('compose_attachments.tpl');
1281 } // End of file_uploads if-block
1282 /* End of attachment code */
1283
1284 //FIXME: no direct echoing to browser, no HTML output in core!
1285 echo addHidden('username', $username).
1286 addHidden('smaction', $action).
1287 addHidden('mailbox', $mailbox);
1288 /*
1289 store the complete ComposeMessages array in a hidden input value
1290 so we can restore them in case of a session timeout.
1291 */
1292 sqgetGlobalVar('QUERY_STRING', $queryString, SQ_SERVER);
1293 //FIXME: no direct echoing to browser, no HTML output in core!
1294 echo addHidden('restoremessages', urlencode(serialize($compose_messages))).
1295 addHidden('composesession', $composesession).
1296 addHidden('querystring', $queryString).
1297 "</form>\n";
1298 if (!(bool) ini_get('file_uploads')) {
1299 /* File uploads are off, so we didn't show that part of the form.
1300 To avoid bogus bug reports, tell the user why. */
1301 //FIXME: no direct echoing to browser, no HTML output in core!
1302 echo '<p style="text-align:center">'
1303 . _("Because PHP file uploads are turned off, you can not attach files to this message. Please see your system administrator for details.")
1304 . "</p>\r\n";
1305 }
1306
1307 do_hook('compose_bottom', $null);
1308
1309 if ($compose_new_win=='1') {
1310 $oTemplate->display('compose_newwin_close.tpl');
1311 }
1312
1313 $oErrorHandler->setDelayedErrors(false);
1314 $oTemplate->display('footer.tpl');
1315 }
1316
1317
1318 function showComposeButtonRow() {
1319 global $use_javascript_addr_book, $save_as_draft,
1320 $default_use_priority, $mailprio, $default_use_mdn,
1321 $request_mdn, $request_dr,
1322 $data_dir, $username;
1323
1324 global $oTemplate, $buffer_hook;
1325
1326 if ($default_use_priority) {
1327 $priorities = array('1'=>_("High"), '3'=>_("Normal"), '5'=>_("Low"));
1328 $priority = isset($mailprio) ? $mailprio : 3;
1329 } else {
1330 $priorities = array();
1331 $priority = NULL;
1332 }
1333
1334 $mdn_user_support=getPref($data_dir, $username, 'mdn_user_support',$default_use_mdn);
1335
1336 if ($use_javascript_addr_book) {
1337 //FIXME: do not construct HTML in core!
1338 $addr_book = " <script type=\"text/javascript\"><!--\n document.write(\"".
1339 " <input type=button value=\\\""._("Addresses").
1340 "\\\" onclick=\\\"javascript:open_abook();\\\" />\");".
1341 " // --></script><noscript>\n".
1342 ' <input type="submit" name="html_addr_search" value="'.
1343 _("Addresses").'" />'.
1344 " </noscript>\n";
1345 } else {
1346 $addr_book = ' <input type="submit" name="html_addr_search" value="'.
1347 _("Addresses").'" />' . "\n";
1348 }
1349
1350 $oTemplate->assign('allow_priority', $default_use_priority==1);
1351 $oTemplate->assign('priority_list', $priorities);
1352 $oTemplate->assign('current_priority', $priority);
1353
1354 $oTemplate->assign('notifications_enabled', $mdn_user_support==1);
1355 $oTemplate->assign('read_receipt', $request_mdn=='1');
1356 $oTemplate->assign('delivery_receipt', $request_dr=='1');
1357
1358 $oTemplate->assign('drafts_enabled', $save_as_draft);
1359 $oTemplate->assign('address_book_button', $addr_book);
1360
1361 $oTemplate->display('compose_buttons.tpl');
1362 }
1363
1364 function checkInput ($show) {
1365 /*
1366 * I implemented the $show variable because the error messages
1367 * were getting sent before the page header. So, I check once
1368 * using $show=false, and then when i'm ready to display the error
1369 * message, show=true
1370 */
1371 global $send_to, $send_to_bcc;
1372
1373 if ($send_to == '' && $send_to_bcc == '') {
1374 if ($show) {
1375 plain_error_message(_("You have not filled in the \"To:\" field."));
1376 }
1377 return false;
1378 }
1379 return true;
1380 } /* function checkInput() */
1381
1382
1383 /* True if FAILURE */
1384 function saveAttachedFiles($session) {
1385 global $compose_messages;
1386
1387 /* get out of here if no file was attached at all */
1388 if (! is_uploaded_file($_FILES['attachfile']['tmp_name']) ) {
1389 return true;
1390 }
1391
1392 $localfilename = sq_get_attach_tempfile();
1393
1394 // m_u_f works better with restricted PHP installs (safe_mode, open_basedir),
1395 // if that doesn't work, try a simple rename.
1396 if (!@move_uploaded_file($_FILES['attachfile']['tmp_name'],$localfilename)) {
1397 if (!@rename($_FILES['attachfile']['tmp_name'], $localfilename)) {
1398 return true;
1399 }
1400 }
1401 $message = $compose_messages[$session];
1402 $type = strtolower($_FILES['attachfile']['type']);
1403 $name = $_FILES['attachfile']['name'];
1404 $message->initAttachment($type, $name, $localfilename);
1405 $compose_messages[$session] = $message;
1406 sqsession_register($compose_messages , 'compose_messages');
1407 }
1408
1409 /* parse values like 8M and 2k into bytes */
1410 function getByteSize($ini_size) {
1411
1412 if(!$ini_size) {
1413 return FALSE;
1414 }
1415
1416 $ini_size = trim($ini_size);
1417
1418 // if there's some kind of letter at the end of the string we need to multiply.
1419 if(!is_numeric(substr($ini_size, -1))) {
1420
1421 switch(strtoupper(substr($ini_size, -1))) {
1422 case 'G':
1423 $bytesize = 1073741824;
1424 break;
1425 case 'M':
1426 $bytesize = 1048576;
1427 break;
1428 case 'K':
1429 $bytesize = 1024;
1430 break;
1431 }
1432
1433 return ($bytesize * (int)substr($ini_size, 0, -1));
1434 }
1435
1436 return $ini_size;
1437 }
1438
1439
1440 /**
1441 * temporary function to make use of the deliver class.
1442 * In the future the responsible backend should be automaticly loaded
1443 * and conf.pl should show a list of available backends.
1444 * The message also should be constructed by the message class.
1445 */
1446 function deliverMessage($composeMessage, $draft=false) {
1447 global $send_to, $send_to_cc, $send_to_bcc, $mailprio, $subject, $body,
1448 $username, $popuser, $usernamedata, $identity, $idents, $data_dir,
1449 $request_mdn, $request_dr, $default_charset, $color, $useSendmail,
1450 $domain, $action, $default_move_to_sent, $move_to_sent;
1451 global $imapServerAddress, $imapPort, $sent_folder, $key;
1452
1453 $rfc822_header = $composeMessage->rfc822_header;
1454
1455 $abook = addressbook_init(false, true);
1456 $rfc822_header->to = $rfc822_header->parseAddress($send_to,true, array(), '', $domain, array(&$abook,'lookup'));
1457 $rfc822_header->cc = $rfc822_header->parseAddress($send_to_cc,true,array(), '',$domain, array(&$abook,'lookup'));
1458 $rfc822_header->bcc = $rfc822_header->parseAddress($send_to_bcc,true, array(), '',$domain, array(&$abook,'lookup'));
1459 $rfc822_header->priority = $mailprio;
1460 $rfc822_header->subject = $subject;
1461
1462 $special_encoding='';
1463 if (strtolower($default_charset) == 'iso-2022-jp') {
1464 if (mb_detect_encoding($body) == 'ASCII') {
1465 $special_encoding = '8bit';
1466 } else {
1467 $body = mb_convert_encoding($body, 'JIS');
1468 $special_encoding = '7bit';
1469 }
1470 }
1471 $composeMessage->setBody($body);
1472
1473 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
1474 $popuser = $usernamedata[1];
1475 $domain = $usernamedata[2];
1476 unset($usernamedata);
1477 } else {
1478 $popuser = $username;
1479 }
1480 $reply_to = '';
1481 $from_mail = $idents[$identity]['email_address'];
1482 $full_name = $idents[$identity]['full_name'];
1483 $reply_to = $idents[$identity]['reply_to'];
1484 if (!$from_mail) {
1485 $from_mail = "$popuser@$domain";
1486 }
1487 $rfc822_header->from = $rfc822_header->parseAddress($from_mail,true);
1488 if ($full_name) {
1489 $from = $rfc822_header->from[0];
1490 if (!$from->host) $from->host = $domain;
1491 $full_name_encoded = encodeHeader($full_name);
1492 if ($full_name_encoded != $full_name) {
1493 $from_addr = $full_name_encoded .' <'.$from->mailbox.'@'.$from->host.'>';
1494 } else {
1495 $from_addr = '"'.$full_name .'" <'.$from->mailbox.'@'.$from->host.'>';
1496 }
1497 $rfc822_header->from = $rfc822_header->parseAddress($from_addr,true);
1498 }
1499 if ($reply_to) {
1500 $rfc822_header->reply_to = $rfc822_header->parseAddress($reply_to,true);
1501 }
1502 /* Receipt: On Read */
1503 if (isset($request_mdn) && $request_mdn) {
1504 $rfc822_header->dnt = $rfc822_header->parseAddress($from_mail,true);
1505 } elseif (isset($rfc822_header->dnt)) {
1506 unset($rfc822_header->dnt);
1507 }
1508
1509 /* Receipt: On Delivery */
1510 if (isset($request_dr) && $request_dr) {
1511 $rfc822_header->more_headers['Return-Receipt-To'] = $from_mail;
1512 } elseif (isset($rfc822_header->more_headers['Return-Receipt-To'])) {
1513 unset($rfc822_header->more_headers['Return-Receipt-To']);
1514 }
1515
1516 /* multipart messages */
1517 if (count($composeMessage->entities)) {
1518 $message_body = new Message();
1519 $message_body->body_part = $composeMessage->body_part;
1520 $composeMessage->body_part = '';
1521 $mime_header = new MessageHeader;
1522 $mime_header->type0 = 'text';
1523 $mime_header->type1 = 'plain';
1524 if ($special_encoding) {
1525 $mime_header->encoding = $special_encoding;
1526 } else {
1527 $mime_header->encoding = '8bit';
1528 }
1529 if ($default_charset) {
1530 $mime_header->parameters['charset'] = $default_charset;
1531 }
1532 $message_body->mime_header = $mime_header;
1533 array_unshift($composeMessage->entities, $message_body);
1534 $content_type = new ContentType('multipart/mixed');
1535 } else {
1536 $content_type = new ContentType('text/plain');
1537 if ($special_encoding) {
1538 $rfc822_header->encoding = $special_encoding;
1539 } else {
1540 $rfc822_header->encoding = '8bit';
1541 }
1542 if ($default_charset) {
1543 $content_type->properties['charset']=$default_charset;
1544 }
1545 }
1546
1547 $rfc822_header->content_type = $content_type;
1548 $composeMessage->rfc822_header = $rfc822_header;
1549
1550 /* Here you can modify the message structure just before we hand
1551 it over to deliver; plugin authors note that $composeMessage
1552 is sent and modified by reference since 1.5.2 */
1553 do_hook('compose_send', $composeMessage);
1554
1555 if (!$useSendmail && !$draft) {
1556 require_once(SM_PATH . 'class/deliver/Deliver_SMTP.class.php');
1557 $deliver = new Deliver_SMTP();
1558 global $smtpServerAddress, $smtpPort, $pop_before_smtp;
1559
1560 $authPop = (isset($pop_before_smtp) && $pop_before_smtp) ? true : false;
1561 get_smtp_user($user, $pass);
1562 $stream = $deliver->initStream($composeMessage,$domain,0,
1563 $smtpServerAddress, $smtpPort, $user, $pass, $authPop);
1564 } elseif (!$draft) {
1565 require_once(SM_PATH . 'class/deliver/Deliver_SendMail.class.php');
1566 global $sendmail_path, $sendmail_args;
1567 // Check for outdated configuration
1568 if (!isset($sendmail_args)) {
1569 if ($sendmail_path=='/var/qmail/bin/qmail-inject') {
1570 $sendmail_args = '';
1571 } else {
1572 $sendmail_args = '-i -t';
1573 }
1574 }
1575 $deliver = new Deliver_SendMail(array('sendmail_args'=>$sendmail_args));
1576 $stream = $deliver->initStream($composeMessage,$sendmail_path);
1577 } elseif ($draft) {
1578 global $draft_folder;
1579 require_once(SM_PATH . 'class/deliver/Deliver_IMAP.class.php');
1580 $imap_stream = sqimap_login($username, false, $imapServerAddress,
1581 $imapPort, 0);
1582 if (sqimap_mailbox_exists ($imap_stream, $draft_folder)) {
1583 require_once(SM_PATH . 'class/deliver/Deliver_IMAP.class.php');
1584 $imap_deliver = new Deliver_IMAP();
1585 $length = $imap_deliver->mail($composeMessage);
1586 sqimap_append ($imap_stream, $draft_folder, $length);
1587 $imap_deliver->mail($composeMessage, $imap_stream);
1588 sqimap_append_done ($imap_stream, $draft_folder);
1589 sqimap_logout($imap_stream);
1590 unset ($imap_deliver);
1591 $composeMessage->purgeAttachments();
1592 return $length;
1593 } else {
1594 $msg = '<br />'.sprintf(_("Error: Draft folder %s does not exist."), htmlspecialchars($draft_folder));
1595 plain_error_message($msg);
1596 return false;
1597 }
1598 }
1599 $success = false;
1600 if ($stream) {
1601 $length = $deliver->mail($composeMessage, $stream);
1602 $success = $deliver->finalizeStream($stream);
1603 }
1604 if (!$success) {
1605 // $deliver->dlv_server_msg is not always server's reply
1606 $msg = _("Message not sent.") . "<br />\n" .
1607 $deliver->dlv_msg;
1608 if (!empty($deliver->dlv_server_msg)) {
1609 // add 'server replied' part only when it is not empty.
1610 // Delivery error can be generated by delivery class itself
1611 $msg.='<br />' .
1612 _("Server replied:") . ' ' . $deliver->dlv_ret_nr . ' ' .
1613 nl2br(htmlspecialchars($deliver->dlv_server_msg));
1614 }
1615 plain_error_message($msg);
1616 } else {
1617 unset ($deliver);
1618 $move_to_sent = getPref($data_dir,$username,'move_to_sent');
1619 $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, 0);
1620
1621 /* Move to sent code */
1622 if (isset($default_move_to_sent) && ($default_move_to_sent != 0)) {
1623 $svr_allow_sent = true;
1624 } else {
1625 $svr_allow_sent = false;
1626 }
1627
1628 if (isset($sent_folder) && (($sent_folder != '') || ($sent_folder != 'none'))
1629 && sqimap_mailbox_exists( $imap_stream, $sent_folder)) {
1630 $fld_sent = true;
1631 } else {
1632 $fld_sent = false;
1633 }
1634
1635 if ((isset($move_to_sent) && ($move_to_sent != 0)) || (!isset($move_to_sent))) {
1636 $lcl_allow_sent = true;
1637 } else {
1638 $lcl_allow_sent = false;
1639 }
1640
1641 if (($fld_sent && $svr_allow_sent && !$lcl_allow_sent) || ($fld_sent && $lcl_allow_sent)) {
1642 global $passed_id, $mailbox, $action;
1643 if ($action == 'reply' || $action == 'reply_all') {
1644 $save_reply_with_orig=getPref($data_dir,$username,'save_reply_with_orig');
1645 if ($save_reply_with_orig) {
1646 $sent_folder = $mailbox;
1647 }
1648 }
1649 sqimap_append ($imap_stream, $sent_folder, $length);
1650 require_once(SM_PATH . 'class/deliver/Deliver_IMAP.class.php');
1651 $imap_deliver = new Deliver_IMAP();
1652 $imap_deliver->mail($composeMessage, $imap_stream);
1653 sqimap_append_done ($imap_stream, $sent_folder);
1654 unset ($imap_deliver);
1655 }
1656
1657 global $passed_id, $mailbox, $action, $what, $iAccount,$startMessage;
1658
1659 $composeMessage->purgeAttachments();
1660 if ($action=='reply' || $action=='reply_all' || $action=='forward' || $action=='forward_as_attachment') {
1661 require(SM_PATH . 'functions/mailbox_display.php');
1662 $aMailbox = sqm_api_mailbox_select($imap_stream, $iAccount, $mailbox,array('setindex' => $what, 'offset' => $startMessage),array());
1663 switch($action) {
1664 case 'reply':
1665 case 'reply_all':
1666 // check if we are allowed to set the \\Answered flag
1667 if (in_array('\\answered',$aMailbox['PERMANENTFLAGS'], true)) {
1668 $aUpdatedMsgs = sqimap_toggle_flag($imap_stream, array($passed_id), '\\Answered', true, false);
1669 if (isset($aUpdatedMsgs[$passed_id]['FLAGS'])) {
1670 /**
1671 * Only update the cached headers if the header is
1672 * cached.
1673 */
1674 if (isset($aMailbox['MSG_HEADERS'][$passed_id])) {
1675 $aMailbox['MSG_HEADERS'][$passed_id]['FLAGS'] = $aMsg['FLAGS'];
1676 }
1677 }
1678 }
1679 break;
1680 case 'forward':
1681 case 'forward_as_attachment':
1682 // check if we are allowed to set the $Forwarded flag (RFC 4550 paragraph 2.8)
1683 if (in_array('$forwarded',$aMailbox['PERMANENTFLAGS'], true) ||
1684 in_array('\\*',$aMailbox['PERMANENTFLAGS'])) {
1685
1686 $aUpdatedMsgs = sqimap_toggle_flag($imap_stream, array($passed_id), '$Forwarded', true, false);
1687 if (isset($aUpdatedMsgs[$passed_id]['FLAGS'])) {
1688 if (isset($aMailbox['MSG_HEADERS'][$passed_id])) {
1689 $aMailbox['MSG_HEADERS'][$passed_id]['FLAGS'] = $aMsg['FLAGS'];
1690 }
1691 }
1692 }
1693 break;
1694 }
1695
1696 /**
1697 * Write mailbox with updated seen flag information back to cache.
1698 */
1699 if(isset($aUpdatedMsgs[$passed_id])) {
1700 $mailbox_cache[$iAccount.'_'.$aMailbox['NAME']] = $aMailbox;
1701 sqsession_register($mailbox_cache,'mailbox_cache');
1702 }
1703
1704 sqimap_logout($imap_stream);
1705 }
1706 }
1707 return $success;
1708 }
1709 ?>