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