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