- Fix busy loop and notice when two literals in IMAP fetch (#1739433).
[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 $draft_message = _("Draft Email Saved");
416 /* If this is a resumed draft, then delete the original */
417 if(isset($delete_draft)) {
418 $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, false);
419 sqimap_mailbox_select($imap_stream, $draft_folder);
420 // force bypass_trash=true because message should be saved when deliverMessage() returns true.
421 // in current implementation of sqimap_msgs_list_flag() single message id can
422 // be submitted as string. docs state that it should be array.
423 sqimap_msgs_list_delete($imap_stream, $draft_folder, $delete_draft, true);
424 if ($auto_expunge) {
425 sqimap_mailbox_expunge($imap_stream, $draft_folder, true);
426 }
427 sqimap_logout($imap_stream);
428 }
429
430 $oErrorHandler->saveDelayedErrors();
431 session_write_close();
432
433 if ($compose_new_win == '1') {
434 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
435 Header("Location: $location/compose.php?saved_draft=yes&session=$composesession");
436 } else {
437 echo ' <br><br><div style="text-align: center;"><a href="' . $location
438 . '/compose.php?saved_sent=yes&amp;session=' . $composesession . '">'
439 . _("Return") . '</a></div>';
440 }
441 exit();
442 } else {
443 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
444 Header("Location: $location/right_main.php?mailbox=" . urlencode($draft_folder) .
445 "&startMessage=1&note=".urlencode($draft_message));
446 } else {
447 echo ' <br><br><div style="text-align: center;"><a href="' . $location
448 . '/right_main.php?mailbox=' . urlencode($draft_folder)
449 . '&amp;startMessage=1&amp;note=' . urlencode($draft_message) .'">'
450 . _("Return") . '</a></div>';
451 }
452 exit();
453 }
454 }
455 }
456
457 if ($send) {
458 if (isset($_FILES['attachfile']) &&
459 $_FILES['attachfile']['tmp_name'] &&
460 $_FILES['attachfile']['tmp_name'] != 'none') {
461 $AttachFailure = saveAttachedFiles($session);
462 }
463 if (checkInput(false) && !isset($AttachFailure)) {
464 if ($mailbox == "All Folders") {
465 /* We entered compose via the search results page */
466 $mailbox = 'INBOX'; /* Send 'em to INBOX, that's safe enough */
467 }
468 $urlMailbox = urlencode($mailbox);
469 if (! isset($passed_id)) {
470 $passed_id = 0;
471 }
472 /**
473 * Set $default_charset to correspond with the user's selection
474 * of language interface.
475 */
476 set_my_charset();
477 /**
478 * This is to change all newlines to \n
479 * We'll change them to \r\n later (in the sendMessage function)
480 */
481 $body = str_replace("\r\n", "\n", $body);
482 $body = str_replace("\r", "\n", $body);
483
484 /**
485 * Rewrap $body so that no line is bigger than $editor_size
486 */
487 $body = explode("\n", $body);
488 $newBody = '';
489 foreach ($body as $line) {
490 if( $line <> '-- ' ) {
491 $line = rtrim($line);
492 }
493 if (sq_strlen($line, $default_charset) <= $editor_size + 1) {
494 $newBody .= $line . "\n";
495 } else {
496 sqWordWrap($line, $editor_size, $default_charset);
497 $newBody .= $line . "\n";
498
499 }
500
501 }
502 $body = $newBody;
503
504 $composeMessage=$compose_messages[$session];
505
506 $Result = deliverMessage($composeMessage);
507
508 if ($Result)
509 $mail_sent = 'yes';
510 else
511 $mail_sent = 'no';
512
513 // NOTE: this hook changed in 1.5.2 from sending $Result and
514 // $composeMessage as args #2 and #3 to being in an array
515 // under arg #2
516 do_hook('compose_send_after', $temp=array(&$Result, &$composeMessage, &$mail_sent));
517 if (! $Result) {
518 showInputForm($session);
519 exit();
520 }
521 unset($compose_messages[$session]);
522
523 /* if it is resumed draft, delete draft message */
524 if ( isset($delete_draft)) {
525 $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, false);
526 sqimap_mailbox_select($imap_stream, $draft_folder);
527 // bypass_trash=true because message should be saved when deliverMessage() returns true.
528 // in current implementation of sqimap_msgs_list_flag() single message id can
529 // be submitted as string. docs state that it should be array.
530 sqimap_msgs_list_delete($imap_stream, $draft_folder, $delete_draft, true);
531 if ($auto_expunge) {
532 sqimap_mailbox_expunge($imap_stream, $draft_folder, true);
533 }
534 sqimap_logout($imap_stream);
535 }
536 /*
537 * Store the error array in the session because they will be lost on a redirect
538 */
539 $oErrorHandler->saveDelayedErrors();
540 session_write_close();
541
542 if ($compose_new_win == '1') {
543 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
544 Header("Location: $location/compose.php?mail_sent=$mail_sent");
545 } else {
546 echo ' <br><br><div style="text-align: center;"><a href="' . $location
547 . '/compose.php?mail_sent=$mail_sent">'
548 . _("Return") . '</a></div>';
549 }
550 exit();
551 } else {
552 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
553 Header("Location: $location/right_main.php?mailbox=$urlMailbox".
554 "&startMessage=$startMessage&mail_sent=$mail_sent");
555 } else {
556 echo ' <br><br><div style="text-align: center;"><a href="' . $location
557 . "/right_main.php?mailbox=$urlMailbox"
558 . "&amp;startMessage=$startMessage&amp;mail_sent=$mail_sent\">"
559 . _("Return") . '</a></div>';
560 }
561 exit();
562 }
563 } else {
564 if ($compose_new_win == '1') {
565 compose_Header($color, $mailbox);
566 }
567 else {
568 displayPageHeader($color, $mailbox);
569 }
570 if (isset($AttachFailure)) {
571 plain_error_message(_("Could not move/copy file. File not attached"),
572 $color);
573 }
574 checkInput(true);
575 showInputForm($session);
576 /* sqimap_logout($imapConnection); */
577 }
578 } elseif (isset($html_addr_search_done)) {
579 if ($compose_new_win == '1') {
580 compose_Header($color, $mailbox);
581 }
582 else {
583 displayPageHeader($color, $mailbox);
584 }
585
586 if (isset($send_to_search) && is_array($send_to_search)) {
587 foreach ($send_to_search as $k => $v) {
588 if (substr($k, 0, 1) == 'T') {
589 if ($send_to) {
590 $send_to .= ', ';
591 }
592 $send_to .= $v;
593 }
594 elseif (substr($k, 0, 1) == 'C') {
595 if ($send_to_cc) {
596 $send_to_cc .= ', ';
597 }
598 $send_to_cc .= $v;
599 }
600 elseif (substr($k, 0, 1) == 'B') {
601 if ($send_to_bcc) {
602 $send_to_bcc .= ', ';
603 }
604 $send_to_bcc .= $v;
605 }
606 }
607 }
608 showInputForm($session);
609 } elseif (isset($html_addr_search) && !isset($html_addr_search_cancel)) {
610 if (isset($_FILES['attachfile']) &&
611 $_FILES['attachfile']['tmp_name'] &&
612 $_FILES['attachfile']['tmp_name'] != 'none') {
613 if(saveAttachedFiles($session)) {
614 plain_error_message(_("Could not move/copy file. File not attached"));
615 }
616 }
617 /*
618 * I am using an include so as to elminiate an extra unnecessary
619 * click. If you can think of a better way, please implement it.
620 */
621 include_once('./addrbook_search_html.php');
622 } elseif (isset($attach)) {
623 if ($compose_new_win == '1') {
624 compose_Header($color, $mailbox);
625 } else {
626 displayPageHeader($color, $mailbox);
627 }
628 if (saveAttachedFiles($session)) {
629 plain_error_message(_("Could not move/copy file. File not attached"));
630 }
631 showInputForm($session);
632 }
633 elseif (isset($sigappend)) {
634 $signature = $idents[$identity]['signature'];
635
636 $body .= "\n\n".($prefix_sig==true? "-- \n":'').$signature;
637 if ($compose_new_win == '1') {
638 compose_Header($color, $mailbox);
639 } else {
640 displayPageHeader($color, $mailbox);
641 }
642 showInputForm($session);
643 } elseif (isset($do_delete)) {
644 if ($compose_new_win == '1') {
645 compose_Header($color, $mailbox);
646 } else {
647 displayPageHeader($color, $mailbox);
648 }
649
650 if (isset($delete) && is_array($delete)) {
651 $composeMessage = $compose_messages[$session];
652 foreach($delete as $index) {
653 if (!empty($composeMessage->entities) && isset($composeMessage->entities[$index])) {
654 $composeMessage->entities[$index]->purgeAttachments();
655 unset ($composeMessage->entities[$index]);
656 }
657 }
658 $new_entities = array();
659 foreach ($composeMessage->entities as $entity) {
660 $new_entities[] = $entity;
661 }
662 $composeMessage->entities = $new_entities;
663 $compose_messages[$session] = $composeMessage;
664 sqsession_register($compose_messages, 'compose_messages');
665 }
666 showInputForm($session);
667 } else {
668 /*
669 * This handles the default case as well as the error case
670 * (they had the same code) --> if (isset($smtpErrors))
671 */
672
673 if ($compose_new_win == '1') {
674 compose_Header($color, $mailbox);
675 } else {
676 displayPageHeader($color, $mailbox);
677 }
678
679 $newmail = true;
680
681 if (!isset($passed_ent_id)) {
682 $passed_ent_id = '';
683 }
684 if (!isset($passed_id)) {
685 $passed_id = '';
686 }
687 if (!isset($mailbox)) {
688 $mailbox = '';
689 }
690 if (!isset($action)) {
691 $action = '';
692 }
693
694 $values = newMail($mailbox,$passed_id,$passed_ent_id, $action, $session);
695
696 /* in case the origin is not read_body.php */
697 if (isset($send_to)) {
698 $values['send_to'] = $send_to;
699 }
700 if (isset($send_to_cc)) {
701 $values['send_to_cc'] = $send_to_cc;
702 }
703 if (isset($send_to_bcc)) {
704 $values['send_to_bcc'] = $send_to_bcc;
705 }
706 if (isset($subject)) {
707 $values['subject'] = $subject;
708 }
709 showInputForm($session, $values);
710 }
711
712 exit();
713
714 /**************** Only function definitions go below *************/
715
716 function getforwardSubject($subject)
717 {
718 if ((substr(strtolower($subject), 0, 4) != 'fwd:') &&
719 (substr(strtolower($subject), 0, 5) != '[fwd:') &&
720 (substr(strtolower($subject), 0, 6) != '[ fwd:')) {
721 $subject = '[Fwd: ' . $subject . ']';
722 }
723 return $subject;
724 }
725
726 /* This function is used when not sending or adding attachments */
727 function newMail ($mailbox='', $passed_id='', $passed_ent_id='', $action='', $session='') {
728 global $editor_size, $default_use_priority, $body, $idents,
729 $use_signature, $data_dir, $username,
730 $key, $imapServerAddress, $imapPort, $compose_messages,
731 $composeMessage, $body_quote, $request_mdn, $request_dr,
732 $mdn_user_support, $languages, $squirrelmail_language,
733 $default_charset;
734
735 /*
736 * Set $default_charset to correspond with the user's selection
737 * of language interface. $default_charset global is not correct,
738 * if message is composed in new window.
739 */
740 set_my_charset();
741
742 $send_to = $send_to_cc = $send_to_bcc = $subject = $identity = '';
743 $mailprio = 3;
744
745 if ($passed_id) {
746 $imapConnection = sqimap_login($username, false, $imapServerAddress,
747 $imapPort, 0);
748
749 sqimap_mailbox_select($imapConnection, $mailbox);
750 $message = sqimap_get_message($imapConnection, $passed_id, $mailbox);
751
752 $body = '';
753 if ($passed_ent_id) {
754 /* redefine the messsage in case of message/rfc822 */
755 $message = $message->getEntity($passed_ent_id);
756 /* message is an entity which contains the envelope and type0=message
757 * and type1=rfc822. The actual entities are childs from
758 * $message->entities[0]. That's where the encoding and is located
759 */
760
761 $entities = $message->entities[0]->findDisplayEntity
762 (array(), $alt_order = array('text/plain'));
763 if (!count($entities)) {
764 $entities = $message->entities[0]->findDisplayEntity
765 (array(), $alt_order = array('text/plain','text/html'));
766 }
767 $orig_header = $message->rfc822_header; /* here is the envelope located */
768 /* redefine the message for picking up the attachments */
769 $message = $message->entities[0];
770
771 } else {
772 $entities = $message->findDisplayEntity (array(), $alt_order = array('text/plain'));
773 if (!count($entities)) {
774 $entities = $message->findDisplayEntity (array(), $alt_order = array('text/plain','text/html'));
775 }
776 $orig_header = $message->rfc822_header;
777 }
778
779 $type0 = $message->type0;
780 $type1 = $message->type1;
781 foreach ($entities as $ent) {
782 $msg = $message->getEntity($ent);
783 $type0 = $msg->type0;
784 $type1 = $msg->type1;
785 $unencoded_bodypart = mime_fetch_body($imapConnection, $passed_id, $ent);
786 $body_part_entity = $message->getEntity($ent);
787 $bodypart = decodeBody($unencoded_bodypart,
788 $body_part_entity->header->encoding);
789 if ($type1 == 'html') {
790 $bodypart = str_replace("\n", ' ', $bodypart);
791 $bodypart = preg_replace(array('/<\/?p>/i','/<div><\/div>/i','/<br\s*(\/)*>/i','/<\/?div>/i'), "\n", $bodypart);
792 $bodypart = str_replace(array('&nbsp;','&gt;','&lt;'),array(' ','>','<'),$bodypart);
793 $bodypart = strip_tags($bodypart);
794 }
795 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
796 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
797 if (mb_detect_encoding($bodypart) != 'ASCII') {
798 $bodypart = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode', $bodypart);
799 }
800 }
801
802 // charset encoding in compose form stuff
803 if (isset($body_part_entity->header->parameters['charset'])) {
804 $actual = $body_part_entity->header->parameters['charset'];
805 } else {
806 $actual = 'us-ascii';
807 }
808
809 if ( $actual && is_conversion_safe($actual) && $actual != $default_charset){
810 $bodypart = charset_convert($actual,$bodypart,$default_charset,false);
811 }
812 // end of charset encoding in compose
813
814 $body .= $bodypart;
815 }
816 if ($default_use_priority) {
817 $mailprio = substr($orig_header->priority,0,1);
818 if (!$mailprio) {
819 $mailprio = 3;
820 }
821 } else {
822 $mailprio = '';
823 }
824
825 $from_o = $orig_header->from;
826 if (is_array($from_o)) {
827 if (isset($from_o[0])) {
828 $from_o = $from_o[0];
829 }
830 }
831 if (is_object($from_o)) {
832 $orig_from = $from_o->getAddress();
833 } else {
834 $orig_from = '';
835 }
836
837 $identities = array();
838 if (count($idents) > 1) {
839 foreach($idents as $nr=>$data) {
840 $enc_from_name = '"'.$data['full_name'].'" <'. $data['email_address'].'>';
841 if($enc_from_name == $orig_from) {
842 $identity = $nr;
843 break;
844 }
845 $identities[] = $enc_from_name;
846 }
847
848 $identity_match = $orig_header->findAddress($identities);
849 if ($identity_match) {
850 $identity = $identity_match;
851 }
852 }
853
854 switch ($action) {
855 case ('draft'):
856 $use_signature = FALSE;
857 $composeMessage->rfc822_header = $orig_header;
858 $send_to = decodeHeader($orig_header->getAddr_s('to'),false,false,true);
859 $send_to_cc = decodeHeader($orig_header->getAddr_s('cc'),false,false,true);
860 $send_to_bcc = decodeHeader($orig_header->getAddr_s('bcc'),false,false,true);
861 $send_from = $orig_header->getAddr_s('from');
862 $send_from_parts = new AddressStructure();
863 $send_from_parts = $orig_header->parseAddress($send_from);
864 $send_from_add = $send_from_parts->mailbox . '@' . $send_from_parts->host;
865 $identity = find_identity(array($send_from_add));
866 $subject = decodeHeader($orig_header->subject,false,false,true);
867
868 // Remember the receipt settings
869 $request_mdn = $mdn_user_support && !empty($orig_header->dnt) ? '1' : '0';
870 $request_dr = $mdn_user_support && !empty($orig_header->drnt) ? '1' : '0';
871
872 /* remember the references and in-reply-to headers in case of an reply */
873 $composeMessage->rfc822_header->more_headers['References'] = $orig_header->references;
874 $composeMessage->rfc822_header->more_headers['In-Reply-To'] = $orig_header->in_reply_to;
875 // rewrap the body to clean up quotations and line lengths
876 sqBodyWrap($body, $editor_size);
877 $composeMessage = getAttachments($message, $composeMessage, $passed_id, $entities, $imapConnection);
878 break;
879 case ('edit_as_new'):
880 $send_to = decodeHeader($orig_header->getAddr_s('to'),false,false,true);
881 $send_to_cc = decodeHeader($orig_header->getAddr_s('cc'),false,false,true);
882 $send_to_bcc = decodeHeader($orig_header->getAddr_s('bcc'),false,false,true);
883 $subject = decodeHeader($orig_header->subject,false,false,true);
884 $mailprio = $orig_header->priority;
885 $orig_from = '';
886 $composeMessage = getAttachments($message, $composeMessage, $passed_id, $entities, $imapConnection);
887 // rewrap the body to clean up quotations and line lengths
888 sqBodyWrap($body, $editor_size);
889 break;
890 case ('forward'):
891 $send_to = '';
892 $subject = getforwardSubject(decodeHeader($orig_header->subject,false,false,true));
893 $body = getforwardHeader($orig_header) . $body;
894 // the logic for calling sqUnWordWrap here would be to allow the browser to wrap the lines
895 // forwarded message text should be as undisturbed as possible, so commenting out this call
896 // sqUnWordWrap($body);
897 $composeMessage = getAttachments($message, $composeMessage, $passed_id, $entities, $imapConnection);
898
899 //add a blank line after the forward headers
900 $body = "\n" . $body;
901 break;
902 case ('forward_as_attachment'):
903 $subject = getforwardSubject(decodeHeader($orig_header->subject,false,false,true));
904 $composeMessage = getMessage_RFC822_Attachment($message, $composeMessage, $passed_id, $passed_ent_id, $imapConnection);
905 $body = '';
906 break;
907 case ('reply_all'):
908 if(isset($orig_header->mail_followup_to) && $orig_header->mail_followup_to) {
909 $send_to = $orig_header->getAddr_s('mail_followup_to');
910 } else {
911 $send_to_cc = replyAllString($orig_header);
912 $send_to_cc = decodeHeader($send_to_cc,false,false,true);
913 }
914 case ('reply'):
915 // skip this if send_to was already set right above here
916 if(!$send_to) {
917 $send_to = $orig_header->reply_to;
918 if (is_array($send_to) && count($send_to)) {
919 $send_to = $orig_header->getAddr_s('reply_to');
920 } else if (is_object($send_to)) { /* unneccesarry, just for failsafe purpose */
921 $send_to = $orig_header->getAddr_s('reply_to');
922 } else {
923 $send_to = $orig_header->getAddr_s('from');
924 }
925 }
926 $send_to = decodeHeader($send_to,false,false,true);
927 $subject = decodeHeader($orig_header->subject,false,false,true);
928 $subject = str_replace('"', "'", $subject);
929 $subject = trim($subject);
930 if (substr(strtolower($subject), 0, 3) != 're:') {
931 $subject = 'Re: ' . $subject;
932 }
933 /* this corrects some wrapping/quoting problems on replies */
934 $rewrap_body = explode("\n", $body);
935 $from = (is_array($orig_header->from) && !empty($orig_header->from)) ? $orig_header->from[0] : $orig_header->from;
936 $body = '';
937 $strip_sigs = getPref($data_dir, $username, 'strip_sigs');
938 foreach ($rewrap_body as $line) {
939 if ($strip_sigs && substr($line,0,3) == '-- ') {
940 break;
941 }
942 if (preg_match("/^(>+)/", $line, $matches)) {
943 $gt = $matches[1];
944 $body .= $body_quote . str_replace("\n", "\n$body_quote$gt ", rtrim($line)) ."\n";
945 } else {
946 $body .= $body_quote . (!empty($body_quote) ? ' ' : '') . str_replace("\n", "\n$body_quote" . (!empty($body_quote) ? ' ' : ''), rtrim($line)) . "\n";
947 }
948 }
949
950 //rewrap the body to clean up quotations and line lengths
951 $body = sqBodyWrap ($body, $editor_size);
952
953 $body = getReplyCitation($from , $orig_header->date) . $body;
954 $composeMessage->reply_rfc822_header = $orig_header;
955
956 break;
957 default:
958 break;
959 }
960 $compose_messages[$session] = $composeMessage;
961 sqsession_register($compose_messages, 'compose_messages');
962 session_write_close();
963 sqimap_logout($imapConnection);
964 }
965 $ret = array( 'send_to' => $send_to,
966 'send_to_cc' => $send_to_cc,
967 'send_to_bcc' => $send_to_bcc,
968 'subject' => $subject,
969 'mailprio' => $mailprio,
970 'body' => $body,
971 'identity' => $identity );
972
973 return ($ret);
974 } /* function newMail() */
975
976 /**
977 * downloads attachments from original message, stores them in attachment directory and adds
978 * them to composed message.
979 * @param object $message
980 * @param object $composeMessage
981 * @param integer $passed_id
982 * @param mixed $entities
983 * @param mixed $imapConnection
984 * @return object
985 */
986 function getAttachments($message, &$composeMessage, $passed_id, $entities, $imapConnection) {
987 global $squirrelmail_language, $languages;
988
989 if (!count($message->entities) ||
990 ($message->type0 == 'message' && $message->type1 == 'rfc822')) {
991 if ( !in_array($message->entity_id, $entities) && $message->entity_id) {
992 switch ($message->type0) {
993 case 'message':
994 if ($message->type1 == 'rfc822') {
995 $filename = $message->rfc822_header->subject;
996 if ($filename == "") {
997 $filename = "untitled-".$message->entity_id;
998 }
999 $filename .= '.msg';
1000 } else {
1001 $filename = $message->getFilename();
1002 }
1003 break;
1004 default:
1005 if (!$message->mime_header) { /* temporary hack */
1006 $message->mime_header = $message->header;
1007 }
1008 $filename = $message->getFilename();
1009 break;
1010 }
1011 $filename = str_replace('&#32;', ' ', decodeHeader($filename));
1012 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1013 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encode')) {
1014 $filename = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encode', $filename);
1015 }
1016 $localfilename = sq_get_attach_tempfile();
1017 $message->att_local_name = $localfilename;
1018
1019 $composeMessage->initAttachment($message->type0.'/'.$message->type1,$filename,
1020 $localfilename);
1021
1022 /* Write Attachment to file */
1023 $fp = fopen ($localfilename, 'wb');
1024 mime_print_body_lines ($imapConnection, $passed_id, $message->entity_id, $message->header->encoding, $fp);
1025 fclose ($fp);
1026 }
1027 } else {
1028 for ($i=0, $entCount=count($message->entities); $i<$entCount;$i++) {
1029 $composeMessage=getAttachments($message->entities[$i], $composeMessage, $passed_id, $entities, $imapConnection);
1030 }
1031 }
1032 return $composeMessage;
1033 }
1034
1035 function getMessage_RFC822_Attachment($message, $composeMessage, $passed_id,
1036 $passed_ent_id='', $imapConnection) {
1037 if (!$passed_ent_id) {
1038 $body_a = sqimap_run_command($imapConnection,
1039 'FETCH '.$passed_id.' RFC822',
1040 TRUE, $response, $readmessage,
1041 TRUE);
1042 } else {
1043 $body_a = sqimap_run_command($imapConnection,
1044 'FETCH '.$passed_id.' BODY['.$passed_ent_id.']',
1045 TRUE, $response, $readmessage, TRUE);
1046 $message = $message->parent;
1047 }
1048 if ($response == 'OK') {
1049 $subject = encodeHeader($message->rfc822_header->subject);
1050 array_shift($body_a);
1051 array_pop($body_a);
1052 $body = implode('', $body_a) . "\r\n";
1053
1054 $localfilename = sq_get_attach_tempfile();
1055 $fp = fopen($localfilename, 'wb');
1056 fwrite ($fp, $body);
1057 fclose($fp);
1058 $composeMessage->initAttachment('message/rfc822',$subject.'.msg',
1059 $localfilename);
1060 }
1061 return $composeMessage;
1062 }
1063
1064 function showInputForm ($session, $values=false) {
1065 global $send_to, $send_to_cc, $send_to_bcc,
1066 $body, $startMessage, $action,
1067 $use_signature, $signature, $prefix_sig,
1068 $editor_size, $editor_height, $subject, $newmail,
1069 $use_javascript_addr_book, $passed_id, $mailbox,
1070 $from_htmladdr_search, $location_of_buttons, $attachment_dir,
1071 $username, $data_dir, $identity, $idents, $delete_draft,
1072 $mailprio, $compose_new_win, $saved_draft, $mail_sent, $sig_first,
1073 $compose_messages, $composesession, $default_charset,
1074 $compose_onsubmit, $oTemplate, $oErrorHandler;
1075
1076 if (checkForJavascript()) {
1077 $onfocus = ' onfocus="alreadyFocused=true;"';
1078 $onfocus_array = array('onfocus' => 'alreadyFocused=true;');
1079 }
1080 else {
1081 $onfocus = '';
1082 $onfocus_array = array();
1083 }
1084
1085 $composeMessage = $compose_messages[$session];
1086 if ($values) {
1087 $send_to = $values['send_to'];
1088 $send_to_cc = $values['send_to_cc'];
1089 $send_to_bcc = $values['send_to_bcc'];
1090 $subject = $values['subject'];
1091 $mailprio = $values['mailprio'];
1092 $body = $values['body'];
1093 $identity = (int) $values['identity'];
1094 } else {
1095 $send_to = decodeHeader($send_to, true, false);
1096 $send_to_cc = decodeHeader($send_to_cc, true, false);
1097 $send_to_bcc = decodeHeader($send_to_bcc, true, false);
1098 }
1099
1100 if ($use_javascript_addr_book) {
1101 echo "\n". '<script type="text/javascript">'."\n<!--\n" .
1102 'function open_abook() { ' . "\n" .
1103 ' var nwin = window.open("addrbook_popup.php","abookpopup",' .
1104 '"width=670,height=300,resizable=yes,scrollbars=yes");' . "\n" .
1105 ' if((!nwin.opener) && (document.windows != null))' . "\n" .
1106 ' nwin.opener = document.windows;' . "\n" .
1107 "}\n" .
1108 "// -->\n</script>\n\n";
1109 }
1110
1111 echo "\n" . '<form name="compose" action="compose.php" method="post" ' .
1112 'enctype="multipart/form-data"';
1113
1114 $compose_onsubmit = array();
1115 global $null;
1116 do_hook('compose_form', $null);
1117
1118 // Plugins that use compose_form hook can add an array entry
1119 // to the globally scoped $compose_onsubmit; we add them up
1120 // here and format the form tag's full onsubmit handler.
1121 // Each plugin should use "return false" if they need to
1122 // stop form submission but otherwise should NOT use "return
1123 // true" to give other plugins the chance to do what they need
1124 // to do; SquirrelMail itself will add the final "return true".
1125 // Onsubmit text is enclosed inside of double quotes, so plugins
1126 // need to quote accordingly.
1127 if (checkForJavascript()) {
1128 $onsubmit_text = ' onsubmit="';
1129 if (empty($compose_onsubmit))
1130 $compose_onsubmit = array();
1131 else if (!is_array($compose_onsubmit))
1132 $compose_onsubmit = array($compose_onsubmit);
1133
1134 foreach ($compose_onsubmit as $text) {
1135 $text = trim($text);
1136 if (substr($text, -1) != ';' && substr($text, -1) != '}')
1137 $text .= '; ';
1138 $onsubmit_text .= $text;
1139 }
1140
1141 echo $onsubmit_text . ' return true;"';
1142 }
1143
1144
1145 echo ">\n";
1146
1147 echo addHidden('startMessage', $startMessage);
1148
1149 if ($action == 'draft') {
1150 echo addHidden('delete_draft', $passed_id);
1151 }
1152 if (isset($delete_draft)) {
1153 echo addHidden('delete_draft', $delete_draft);
1154 }
1155 if (isset($session)) {
1156 echo addHidden('session', $session);
1157 }
1158
1159 if (isset($passed_id)) {
1160 echo addHidden('passed_id', $passed_id);
1161 }
1162
1163 if ($saved_draft == 'yes') {
1164 $oTemplate->assign('note', _("Your draft has been saved."));
1165 $oTemplate->display('note.tpl');
1166 }
1167 if ($mail_sent == 'yes') {
1168 $oTemplate->assign('note', _("Your mail has been sent."));
1169 $oTemplate->display('note.tpl');
1170 }
1171 if ($compose_new_win == '1') {
1172 $oTemplate->display('compose_newwin_close.tpl');
1173 }
1174
1175 if ($location_of_buttons == 'top') {
1176 showComposeButtonRow();
1177 }
1178
1179 $identities = array();
1180 if (count($idents) > 1) {
1181 reset($idents);
1182 foreach($idents as $id => $data) {
1183 $identities[$id] = $data['full_name'].' &lt;'.$data['email_address'].'&gt;';
1184 }
1185 }
1186
1187 $oTemplate->assign('identities', $identities);
1188 $oTemplate->assign('identity_def', $identity);
1189 $oTemplate->assign('input_onfocus', 'onfocus="'.join(' ', $onfocus_array).'"');
1190
1191 $oTemplate->assign('to', htmlspecialchars($send_to));
1192 $oTemplate->assign('cc', htmlspecialchars($send_to_cc));
1193 $oTemplate->assign('bcc', htmlspecialchars($send_to_bcc));
1194 $oTemplate->assign('subject', htmlspecialchars($subject));
1195
1196 $oTemplate->display('compose_header.tpl');
1197
1198 if ($location_of_buttons == 'between') {
1199 showComposeButtonRow();
1200 }
1201
1202 $body_str = '';
1203 if ($use_signature == true && $newmail == true && !isset($from_htmladdr_search)) {
1204 $signature = $idents[$identity]['signature'];
1205
1206 if ($sig_first == '1') {
1207 /*
1208 * FIXME: test is specific to ja_JP translation implementation.
1209 * This test might apply incorrect conversion to other translations, but
1210 * use of 7bit iso-2022-jp charset in other translations might have other
1211 * issues too.
1212 */
1213 if ($default_charset == 'iso-2022-jp') {
1214 $body_str = "\n\n".($prefix_sig==true? "-- \n":'').mb_convert_encoding($signature, 'EUC-JP');
1215 } else {
1216 $body_str = "\n\n".($prefix_sig==true? "-- \n":'').decodeHeader($signature,false,false);
1217 }
1218 $body_str .= "\n\n".htmlspecialchars(decodeHeader($body,false,false));
1219 } else {
1220 $body_str = "\n\n".htmlspecialchars(decodeHeader($body,false,false));
1221 // FIXME: test is specific to ja_JP translation implementation. See above comments.
1222 if ($default_charset == 'iso-2022-jp') {
1223 $body_str .= "\n\n".($prefix_sig==true? "-- \n":'').mb_convert_encoding($signature, 'EUC-JP');
1224 } else {
1225 $body_str .= "\n\n".($prefix_sig==true? "-- \n":'').decodeHeader($signature,false,false);
1226 }
1227 }
1228 } else {
1229 $body_str = htmlspecialchars(decodeHeader($body,false,false));
1230 }
1231
1232 $oTemplate->assign('editor_width', (int)$editor_size);
1233 $oTemplate->assign('editor_height', (int)$editor_height);
1234 $oTemplate->assign('input_onfocus', 'onfocus="'.join(' ', $onfocus_array).'"');
1235 $oTemplate->assign('body', $body_str);
1236 $oTemplate->assign('show_bottom_send', $location_of_buttons!='bottom');
1237
1238 $oTemplate->display ('compose_body.tpl');
1239
1240 if ($location_of_buttons == 'bottom') {
1241 showComposeButtonRow();
1242 }
1243
1244 /* This code is for attachments */
1245 if ((bool) ini_get('file_uploads')) {
1246
1247 /* Calculate the max size for an uploaded file.
1248 * This is advisory for the user because we can't actually prevent
1249 * people to upload too large files. */
1250 $sizes = array();
1251 /* php.ini vars which influence the max for uploads */
1252 $configvars = array('post_max_size', 'memory_limit', 'upload_max_filesize');
1253 foreach($configvars as $var) {
1254 /* skip 0 or empty values, and -1 which means 'unlimited' */
1255 if( $size = getByteSize(ini_get($var)) ) {
1256 if ( $size != '-1' ) {
1257 $sizes[] = $size;
1258 }
1259 }
1260 }
1261
1262 $attach = array();
1263 // composeMessage can be empty when coming from a restored session
1264 if (is_object($composeMessage) && $composeMessage->entities) {
1265 foreach ($composeMessage->entities as $key => $attachment) {
1266 $attached_file = $attachment->att_local_name;
1267 if ($attachment->att_local_name || $attachment->body_part) {
1268 $attached_filename = decodeHeader($attachment->mime_header->getParameter('name'));
1269 $type = $attachment->mime_header->type0.'/'.
1270 $attachment->mime_header->type1;
1271
1272 $a = array();
1273 $a['Key'] = $key;
1274 $a['FileName'] = $attached_filename;
1275 $a['ContentType'] = $type;
1276 $a['Size'] = filesize($attached_file);
1277 $attach[$key] = $a;
1278 }
1279 }
1280 }
1281
1282 $max = min($sizes);
1283 $oTemplate->assign('max_file_size', empty($max) ? -1 : $max);
1284 $oTemplate->assign('attachments', $attach);
1285
1286 $oTemplate->display('compose_attachments.tpl');
1287 } // End of file_uploads if-block
1288 /* End of attachment code */
1289
1290 //FIXME: no direct echoing to browser, no HTML output in core!
1291 echo addHidden('username', $username).
1292 addHidden('smaction', $action).
1293 addHidden('mailbox', $mailbox);
1294 /*
1295 store the complete ComposeMessages array in a hidden input value
1296 so we can restore them in case of a session timeout.
1297 */
1298 sqgetGlobalVar('QUERY_STRING', $queryString, SQ_SERVER);
1299 //FIXME: no direct echoing to browser, no HTML output in core!
1300 echo addHidden('restoremessages', urlencode(serialize($compose_messages))).
1301 addHidden('composesession', $composesession).
1302 addHidden('querystring', $queryString).
1303 "</form>\n";
1304 if (!(bool) ini_get('file_uploads')) {
1305 /* File uploads are off, so we didn't show that part of the form.
1306 To avoid bogus bug reports, tell the user why. */
1307 //FIXME: no direct echoing to browser, no HTML output in core!
1308 echo '<p style="text-align:center">'
1309 . _("Because PHP file uploads are turned off, you can not attach files to this message. Please see your system administrator for details.")
1310 . "</p>\r\n";
1311 }
1312
1313 if ($compose_new_win=='1') {
1314 $oTemplate->display('compose_newwin_close.tpl');
1315 }
1316
1317 do_hook('compose_bottom', $null);
1318
1319 $oErrorHandler->setDelayedErrors(false);
1320 $oTemplate->display('footer.tpl');
1321 }
1322
1323
1324 function showComposeButtonRow() {
1325 global $use_javascript_addr_book, $save_as_draft,
1326 $default_use_priority, $mailprio, $default_use_mdn,
1327 $request_mdn, $request_dr,
1328 $data_dir, $username;
1329
1330 global $oTemplate, $buffer_hook;
1331
1332 if ($default_use_priority) {
1333 $priorities = array('1'=>_("High"), '3'=>_("Normal"), '5'=>_("Low"));
1334 $priority = isset($mailprio) ? $mailprio : 3;
1335 } else {
1336 $priorities = array();
1337 $priority = NULL;
1338 }
1339
1340 $mdn_user_support=getPref($data_dir, $username, 'mdn_user_support',$default_use_mdn);
1341
1342 if ($use_javascript_addr_book && checkForJavascript()) {
1343 $addr_book = addButton(_("Addresses"), null, array('onclick' => 'javascript:open_abook();'));
1344 } else {
1345 $addr_book = addSubmit(_("Addresses"), 'html_addr_search');
1346 }
1347
1348 $oTemplate->assign('allow_priority', $default_use_priority==1);
1349 $oTemplate->assign('priority_list', $priorities);
1350 $oTemplate->assign('current_priority', $priority);
1351
1352 $oTemplate->assign('notifications_enabled', $mdn_user_support==1);
1353 $oTemplate->assign('read_receipt', $request_mdn=='1');
1354 $oTemplate->assign('delivery_receipt', $request_dr=='1');
1355
1356 $oTemplate->assign('drafts_enabled', $save_as_draft);
1357 $oTemplate->assign('address_book_button', $addr_book);
1358
1359 $oTemplate->display('compose_buttons.tpl');
1360 }
1361
1362 function checkInput ($show) {
1363 /*
1364 * I implemented the $show variable because the error messages
1365 * were getting sent before the page header. So, I check once
1366 * using $show=false, and then when i'm ready to display the error
1367 * message, show=true
1368 */
1369 global $send_to, $send_to_bcc;
1370
1371 if ($send_to == '' && $send_to_bcc == '') {
1372 if ($show) {
1373 plain_error_message(_("You have not filled in the \"To:\" field."));
1374 }
1375 return false;
1376 }
1377 return true;
1378 } /* function checkInput() */
1379
1380
1381 /* True if FAILURE */
1382 function saveAttachedFiles($session) {
1383 global $compose_messages;
1384
1385 /* get out of here if no file was attached at all */
1386 if (! is_uploaded_file($_FILES['attachfile']['tmp_name']) ) {
1387 return true;
1388 }
1389
1390 $localfilename = sq_get_attach_tempfile();
1391
1392 // m_u_f works better with restricted PHP installs (safe_mode, open_basedir),
1393 // if that doesn't work, try a simple rename.
1394 if (!@move_uploaded_file($_FILES['attachfile']['tmp_name'],$localfilename)) {
1395 if (!@rename($_FILES['attachfile']['tmp_name'], $localfilename)) {
1396 return true;
1397 }
1398 }
1399 $message = $compose_messages[$session];
1400 $type = strtolower($_FILES['attachfile']['type']);
1401 $name = $_FILES['attachfile']['name'];
1402 $message->initAttachment($type, $name, $localfilename);
1403 $compose_messages[$session] = $message;
1404 sqsession_register($compose_messages , 'compose_messages');
1405 }
1406
1407 /* parse values like 8M and 2k into bytes */
1408 function getByteSize($ini_size) {
1409
1410 if(!$ini_size) {
1411 return FALSE;
1412 }
1413
1414 $ini_size = trim($ini_size);
1415
1416 // if there's some kind of letter at the end of the string we need to multiply.
1417 if(!is_numeric(substr($ini_size, -1))) {
1418
1419 switch(strtoupper(substr($ini_size, -1))) {
1420 case 'G':
1421 $bytesize = 1073741824;
1422 break;
1423 case 'M':
1424 $bytesize = 1048576;
1425 break;
1426 case 'K':
1427 $bytesize = 1024;
1428 break;
1429 }
1430
1431 return ($bytesize * (int)substr($ini_size, 0, -1));
1432 }
1433
1434 return $ini_size;
1435 }
1436
1437
1438 /**
1439 * temporary function to make use of the deliver class.
1440 * In the future the responsible backend should be automaticly loaded
1441 * and conf.pl should show a list of available backends.
1442 * The message also should be constructed by the message class.
1443 */
1444 function deliverMessage($composeMessage, $draft=false) {
1445 global $send_to, $send_to_cc, $send_to_bcc, $mailprio, $subject, $body,
1446 $username, $identity, $idents, $data_dir,
1447 $request_mdn, $request_dr, $default_charset, $useSendmail,
1448 $domain, $action, $default_move_to_sent, $move_to_sent,
1449 $imapServerAddress, $imapPort, $sent_folder, $key;
1450
1451 $rfc822_header = $composeMessage->rfc822_header;
1452
1453 $abook = addressbook_init(false, true);
1454 $rfc822_header->to = $rfc822_header->parseAddress($send_to,true, array(), '', $domain, array(&$abook,'lookup'));
1455 $rfc822_header->cc = $rfc822_header->parseAddress($send_to_cc,true,array(), '',$domain, array(&$abook,'lookup'));
1456 $rfc822_header->bcc = $rfc822_header->parseAddress($send_to_bcc,true, array(), '',$domain, array(&$abook,'lookup'));
1457 $rfc822_header->priority = $mailprio;
1458 $rfc822_header->subject = $subject;
1459
1460 $special_encoding='';
1461 if (strtolower($default_charset) == 'iso-2022-jp') {
1462 if (mb_detect_encoding($body) == 'ASCII') {
1463 $special_encoding = '8bit';
1464 } else {
1465 $body = mb_convert_encoding($body, 'JIS');
1466 $special_encoding = '7bit';
1467 }
1468 }
1469 $composeMessage->setBody($body);
1470
1471 $reply_to = '';
1472 $reply_to = $idents[$identity]['reply_to'];
1473
1474 $from_addr = build_from_header($identity);
1475 $rfc822_header->from = $rfc822_header->parseAddress($from_addr,true);
1476 if ($reply_to) {
1477 $rfc822_header->reply_to = $rfc822_header->parseAddress($reply_to,true);
1478 }
1479 /* Receipt: On Read */
1480 if (isset($request_mdn) && $request_mdn) {
1481 $rfc822_header->dnt = $rfc822_header->parseAddress($from_addr,true);
1482 } elseif (isset($rfc822_header->dnt)) {
1483 unset($rfc822_header->dnt);
1484 }
1485
1486 /* Receipt: On Delivery */
1487 if (isset($request_dr) && $request_dr) {
1488 $rfc822_header->more_headers['Return-Receipt-To'] = $from->mailbox.'@'.$from->domain;
1489 } elseif (isset($rfc822_header->more_headers['Return-Receipt-To'])) {
1490 unset($rfc822_header->more_headers['Return-Receipt-To']);
1491 }
1492
1493 /* multipart messages */
1494 if (count($composeMessage->entities)) {
1495 $message_body = new Message();
1496 $message_body->body_part = $composeMessage->body_part;
1497 $composeMessage->body_part = '';
1498 $mime_header = new MessageHeader;
1499 $mime_header->type0 = 'text';
1500 $mime_header->type1 = 'plain';
1501 if ($special_encoding) {
1502 $mime_header->encoding = $special_encoding;
1503 } else {
1504 $mime_header->encoding = '8bit';
1505 }
1506 if ($default_charset) {
1507 $mime_header->parameters['charset'] = $default_charset;
1508 }
1509 $message_body->mime_header = $mime_header;
1510 array_unshift($composeMessage->entities, $message_body);
1511 $content_type = new ContentType('multipart/mixed');
1512 } else {
1513 $content_type = new ContentType('text/plain');
1514 if ($special_encoding) {
1515 $rfc822_header->encoding = $special_encoding;
1516 } else {
1517 $rfc822_header->encoding = '8bit';
1518 }
1519 if ($default_charset) {
1520 $content_type->properties['charset']=$default_charset;
1521 }
1522 }
1523
1524 $rfc822_header->content_type = $content_type;
1525 $composeMessage->rfc822_header = $rfc822_header;
1526
1527 /* Here you can modify the message structure just before we hand
1528 it over to deliver; plugin authors note that $composeMessage
1529 is sent and modified by reference since 1.5.2 */
1530 do_hook('compose_send', $composeMessage);
1531
1532 if (!$useSendmail && !$draft) {
1533 require_once(SM_PATH . 'class/deliver/Deliver_SMTP.class.php');
1534 $deliver = new Deliver_SMTP();
1535 global $smtpServerAddress, $smtpPort, $pop_before_smtp;
1536
1537 $authPop = (isset($pop_before_smtp) && $pop_before_smtp) ? true : false;
1538 get_smtp_user($user, $pass);
1539 $stream = $deliver->initStream($composeMessage,$domain,0,
1540 $smtpServerAddress, $smtpPort, $user, $pass, $authPop);
1541 } elseif (!$draft) {
1542 require_once(SM_PATH . 'class/deliver/Deliver_SendMail.class.php');
1543 global $sendmail_path, $sendmail_args;
1544 // Check for outdated configuration
1545 if (!isset($sendmail_args)) {
1546 if ($sendmail_path=='/var/qmail/bin/qmail-inject') {
1547 $sendmail_args = '';
1548 } else {
1549 $sendmail_args = '-i -t';
1550 }
1551 }
1552 $deliver = new Deliver_SendMail(array('sendmail_args'=>$sendmail_args));
1553 $stream = $deliver->initStream($composeMessage,$sendmail_path);
1554 } elseif ($draft) {
1555 global $draft_folder;
1556 require_once(SM_PATH . 'class/deliver/Deliver_IMAP.class.php');
1557 $imap_stream = sqimap_login($username, false, $imapServerAddress,
1558 $imapPort, 0);
1559 if (sqimap_mailbox_exists ($imap_stream, $draft_folder)) {
1560 require_once(SM_PATH . 'class/deliver/Deliver_IMAP.class.php');
1561 $imap_deliver = new Deliver_IMAP();
1562 $length = $imap_deliver->mail($composeMessage);
1563 sqimap_append ($imap_stream, $draft_folder, $length);
1564 $imap_deliver->mail($composeMessage, $imap_stream);
1565 sqimap_append_done ($imap_stream, $draft_folder);
1566 sqimap_logout($imap_stream);
1567 unset ($imap_deliver);
1568 $composeMessage->purgeAttachments();
1569 return $length;
1570 } else {
1571 $msg = '<br />'.sprintf(_("Error: Draft folder %s does not exist."), htmlspecialchars($draft_folder));
1572 plain_error_message($msg);
1573 return false;
1574 }
1575 }
1576 $success = false;
1577 if ($stream) {
1578 $length = $deliver->mail($composeMessage, $stream);
1579 $success = $deliver->finalizeStream($stream);
1580 }
1581 if (!$success) {
1582 // $deliver->dlv_server_msg is not always server's reply
1583 $msg = _("Message not sent.") . "<br />\n" .
1584 $deliver->dlv_msg;
1585 if (!empty($deliver->dlv_server_msg)) {
1586 // add 'server replied' part only when it is not empty.
1587 // Delivery error can be generated by delivery class itself
1588 $msg.='<br />' .
1589 _("Server replied:") . ' ' . $deliver->dlv_ret_nr . ' ' .
1590 nl2br(htmlspecialchars($deliver->dlv_server_msg));
1591 }
1592 plain_error_message($msg);
1593 } else {
1594 unset ($deliver);
1595 $move_to_sent = getPref($data_dir,$username,'move_to_sent');
1596 $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, 0);
1597
1598 /* Move to sent code */
1599 if (isset($default_move_to_sent) && ($default_move_to_sent != 0)) {
1600 $svr_allow_sent = true;
1601 } else {
1602 $svr_allow_sent = false;
1603 }
1604
1605 if (isset($sent_folder) && (($sent_folder != '') || ($sent_folder != 'none'))
1606 && sqimap_mailbox_exists( $imap_stream, $sent_folder)) {
1607 $fld_sent = true;
1608 } else {
1609 $fld_sent = false;
1610 }
1611
1612 if ((isset($move_to_sent) && ($move_to_sent != 0)) || (!isset($move_to_sent))) {
1613 $lcl_allow_sent = true;
1614 } else {
1615 $lcl_allow_sent = false;
1616 }
1617
1618 global $passed_id, $mailbox;
1619 if (($fld_sent && $svr_allow_sent && !$lcl_allow_sent) || ($fld_sent && $lcl_allow_sent)) {
1620 if ($action == 'reply' || $action == 'reply_all') {
1621 $save_reply_with_orig=getPref($data_dir,$username,'save_reply_with_orig');
1622 if ($save_reply_with_orig) {
1623 $sent_folder = $mailbox;
1624 }
1625 }
1626 sqimap_append ($imap_stream, $sent_folder, $length);
1627 require_once(SM_PATH . 'class/deliver/Deliver_IMAP.class.php');
1628 $imap_deliver = new Deliver_IMAP();
1629 $imap_deliver->mail($composeMessage, $imap_stream);
1630 sqimap_append_done ($imap_stream, $sent_folder);
1631 unset ($imap_deliver);
1632 }
1633
1634 global $what, $iAccount, $startMessage;
1635
1636 $composeMessage->purgeAttachments();
1637 if ($action=='reply' || $action=='reply_all' || $action=='forward' || $action=='forward_as_attachment') {
1638 require(SM_PATH . 'functions/mailbox_display.php');
1639 $aMailbox = sqm_api_mailbox_select($imap_stream, $iAccount, $mailbox,array('setindex' => $what, 'offset' => $startMessage),array());
1640 switch($action) {
1641 case 'reply':
1642 case 'reply_all':
1643 // check if we are allowed to set the \\Answered flag
1644 if (in_array('\\answered',$aMailbox['PERMANENTFLAGS'], true)) {
1645 $aUpdatedMsgs = sqimap_toggle_flag($imap_stream, array($passed_id), '\\Answered', true, false);
1646 if (isset($aUpdatedMsgs[$passed_id]['FLAGS'])) {
1647 /**
1648 * Only update the cached headers if the header is
1649 * cached.
1650 */
1651 if (isset($aMailbox['MSG_HEADERS'][$passed_id])) {
1652 $aMailbox['MSG_HEADERS'][$passed_id]['FLAGS'] = $aMsg['FLAGS'];
1653 }
1654 }
1655 }
1656 break;
1657 case 'forward':
1658 case 'forward_as_attachment':
1659 // check if we are allowed to set the $Forwarded flag (RFC 4550 paragraph 2.8)
1660 if (in_array('$forwarded',$aMailbox['PERMANENTFLAGS'], true) ||
1661 in_array('\\*',$aMailbox['PERMANENTFLAGS'])) {
1662
1663 $aUpdatedMsgs = sqimap_toggle_flag($imap_stream, array($passed_id), '$Forwarded', true, false);
1664 if (isset($aUpdatedMsgs[$passed_id]['FLAGS'])) {
1665 if (isset($aMailbox['MSG_HEADERS'][$passed_id])) {
1666 $aMailbox['MSG_HEADERS'][$passed_id]['FLAGS'] = $aMsg['FLAGS'];
1667 }
1668 }
1669 }
1670 break;
1671 }
1672
1673 /**
1674 * Write mailbox with updated seen flag information back to cache.
1675 */
1676 if(isset($aUpdatedMsgs[$passed_id])) {
1677 $mailbox_cache[$iAccount.'_'.$aMailbox['NAME']] = $aMailbox;
1678 sqsession_register($mailbox_cache,'mailbox_cache');
1679 }
1680
1681 sqimap_logout($imap_stream);
1682 }
1683 }
1684 return $success;
1685 }