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