032c95f7534d2f0c37c2fccfaabe69702730cdcc
[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-2006 The SquirrelMail Project Team
14 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
15 * @version $Id$
16 * @package squirrelmail
17 */
18
19 /**
20 * Include the SquirrelMail initialization file.
21 */
22 require('../include/init.php');
23
24 /* SquirrelMail required files. */
25 require_once(SM_PATH . 'functions/imap_general.php');
26 require_once(SM_PATH . 'functions/imap_messages.php');
27 require_once(SM_PATH . 'functions/date.php');
28 require_once(SM_PATH . 'functions/mime.php');
29 require_once(SM_PATH . 'functions/compose.php');
30 require_once(SM_PATH . 'class/deliver/Deliver.class.php');
31 require_once(SM_PATH . 'functions/addressbook.php');
32 require_once(SM_PATH . 'functions/forms.php');
33 require_once(SM_PATH . 'functions/identity.php');
34
35 /* --------------------- Get globals ------------------------------------- */
36
37 /** SESSION VARS */
38 sqgetGlobalVar('delimiter', $delimiter, SQ_SESSION);
39
40 sqgetGlobalVar('composesession', $composesession, SQ_SESSION);
41 sqgetGlobalVar('compose_messages', $compose_messages, SQ_SESSION);
42 sqgetGlobalVar('delayed_errors', $delayed_errors, SQ_SESSION);
43
44 // Turn on delayed error handling in case we wind up redirecting below
45 $oErrorHandler->setDelayedErrors(true);
46
47 /** SESSION/POST/GET VARS */
48 sqgetGlobalVar('session',$session);
49 sqgetGlobalVar('mailbox',$mailbox);
50 if(!sqgetGlobalVar('identity',$identity)) {
51 $identity=0;
52 }
53 sqgetGlobalVar('send_to',$send_to);
54 sqgetGlobalVar('send_to_cc',$send_to_cc);
55 sqgetGlobalVar('send_to_bcc',$send_to_bcc);
56 sqgetGlobalVar('subject',$subject);
57 sqgetGlobalVar('body',$body);
58 sqgetGlobalVar('mailprio',$mailprio);
59 sqgetGlobalVar('request_mdn',$request_mdn);
60 sqgetGlobalVar('request_dr',$request_dr);
61 sqgetGlobalVar('html_addr_search',$html_addr_search);
62 sqgetGlobalVar('mail_sent',$mail_sent);
63 sqgetGlobalVar('passed_id',$passed_id);
64 sqgetGlobalVar('passed_ent_id',$passed_ent_id);
65 sqgetGlobalVar('send',$send);
66
67 sqgetGlobalVar('attach',$attach);
68
69 sqgetGlobalVar('draft',$draft);
70 sqgetGlobalVar('draft_id',$draft_id);
71 sqgetGlobalVar('ent_num',$ent_num);
72 sqgetGlobalVar('saved_draft',$saved_draft);
73
74 if ( sqgetGlobalVar('delete_draft',$delete_draft) ) {
75 $delete_draft = (int)$delete_draft;
76 }
77
78 if ( sqgetGlobalVar('startMessage',$startMessage) ) {
79 $startMessage = (int)$startMessage;
80 } else {
81 $startMessage = 1;
82 }
83
84
85 /** POST VARS */
86 sqgetGlobalVar('sigappend', $sigappend, SQ_POST);
87 sqgetGlobalVar('from_htmladdr_search', $from_htmladdr_search, SQ_POST);
88 sqgetGlobalVar('addr_search_done', $html_addr_search_done, SQ_POST);
89 sqgetGlobalVar('addr_search_cancel', $html_addr_search_cancel, SQ_POST);
90 sqgetGlobalVar('send_to_search', $send_to_search, SQ_POST);
91 sqgetGlobalVar('do_delete', $do_delete, SQ_POST);
92 sqgetGlobalVar('delete', $delete, SQ_POST);
93 sqgetGlobalVar('restoremessages', $restoremessages, SQ_POST);
94 if ( sqgetGlobalVar('return', $temp, SQ_POST) ) {
95 $html_addr_search_done = 'Use Addresses';
96 }
97
98 /** GET VARS */
99 sqgetGlobalVar('attachedmessages', $attachedmessages, SQ_GET);
100 if ( sqgetGlobalVar('account', $temp, SQ_GET) ) {
101 $iAccount = (int) $temp;
102 } else {
103 $iAccount = 0;
104 }
105
106
107 /** get smaction */
108 if ( !sqgetGlobalVar('smaction',$action) )
109 {
110 if ( sqgetGlobalVar('smaction_reply',$tmp) ) $action = 'reply';
111 if ( sqgetGlobalVar('smaction_reply_all',$tmp) ) $action = 'reply_all';
112 if ( sqgetGlobalVar('smaction_forward',$tmp) ) $action = 'forward';
113 if ( sqgetGlobalVar('smaction_attache',$tmp) ) $action = 'forward_as_attachment';
114 if ( sqgetGlobalVar('smaction_draft',$tmp) ) $action = 'draft';
115 if ( sqgetGlobalVar('smaction_edit_new',$tmp) ) $action = 'edit_as_new';
116 }
117
118 /**
119 * Here we decode the data passed in from mailto.php.
120 */
121 if ( sqgetGlobalVar('mailtodata', $mailtodata, SQ_GET) ) {
122 $trtable = array('to' => 'send_to',
123 'cc' => 'send_to_cc',
124 'bcc' => 'send_to_bcc',
125 'body' => 'body',
126 'subject' => 'subject');
127 $mtdata = unserialize($mailtodata);
128
129 foreach ($trtable as $f => $t) {
130 if ( !empty($mtdata[$f]) ) {
131 $$t = $mtdata[$f];
132 }
133 }
134 unset($mailtodata,$mtdata, $trtable);
135 }
136
137 /* Location (For HTTP 1.1 Header("Location: ...") redirects) */
138 $location = get_location();
139 /* Identities (fetch only once) */
140 $idents = get_identities();
141
142 /* --------------------- Specific Functions ------------------------------ */
143
144 function replyAllString($header) {
145 global $include_self_reply_all, $idents;
146 $excl_ar = array();
147 /**
148 * 1) Remove the addresses we'll be sending the message 'to'
149 */
150 if (isset($header->replyto)) {
151 $excl_ar = $header->getAddr_a('replyto');
152 }
153 /**
154 * 2) Remove our identities from the CC list (they still can be in the
155 * TO list) only if $include_self_reply_all is turned off
156 */
157 if (!$include_self_reply_all) {
158 foreach($idents as $id) {
159 $excl_ar[strtolower(trim($id['email_address']))] = '';
160 }
161 }
162
163 /**
164 * 3) get the addresses.
165 */
166 $url_replytoall_ar = $header->getAddr_a(array('to','cc'), $excl_ar);
167
168 /**
169 * 4) generate the string.
170 */
171 $url_replytoallcc = '';
172 foreach( $url_replytoall_ar as $email => $personal) {
173 if ($personal) {
174 // if personal name contains address separator then surround
175 // the personal name with double quotes.
176 if (strpos($personal,',') !== false) {
177 $personal = '"'.$personal.'"';
178 }
179 $url_replytoallcc .= ", $personal <$email>";
180 } else {
181 $url_replytoallcc .= ', '. $email;
182 }
183 }
184 $url_replytoallcc = substr($url_replytoallcc,2);
185
186 return $url_replytoallcc;
187 }
188
189 /**
190 * creates top line in reply citations
191 *
192 * Line style depends on user preferences.
193 * $orig_date argument is available only from 1.4.3 and 1.5.1 version.
194 * @param object $orig_from From: header object.
195 * @param integer $orig_date email's timestamp
196 * @return string reply citation
197 */
198 function getReplyCitation($orig_from, $orig_date) {
199 global $reply_citation_style, $reply_citation_start, $reply_citation_end;
200
201 if (!is_object($orig_from)) {
202 $sOrig_from = '';
203 } else {
204 $sOrig_from = decodeHeader($orig_from->getAddress(false),false,false,true);
205 }
206
207 /* First, return an empty string when no citation style selected. */
208 if (($reply_citation_style == '') || ($reply_citation_style == 'none')) {
209 return '';
210 }
211
212 /* Make sure our final value isn't an empty string. */
213 if ($sOrig_from == '') {
214 return '';
215 }
216
217 /* Otherwise, try to select the desired citation style. */
218 switch ($reply_citation_style) {
219 case 'author_said':
220 /**
221 * To translators: %s is for author's name
222 */
223 $full_reply_citation = sprintf(_("%s wrote:"),$sOrig_from);
224 break;
225 case 'quote_who':
226 $start = '<quote who="';
227 $end = '">';
228 $full_reply_citation = $start . $sOrig_from . $end;
229 break;
230 case 'date_time_author':
231 /**
232 * To translators:
233 * first %s is for date string, second %s is for author's name. Date uses
234 * formating from "D, F j, Y g:i a" and "D, F j, Y H:i" translations.
235 * Example string:
236 * "On Sat, December 24, 2004 23:59, Santa wrote:"
237 * If you have to put author's name in front of date string, check comments about
238 * argument swapping at http://www.php.net/sprintf
239 */
240 $full_reply_citation = sprintf(_("On %s, %s wrote:"), getLongDateString($orig_date), $sOrig_from);
241 break;
242 case 'user-defined':
243 $start = $reply_citation_start .
244 ($reply_citation_start == '' ? '' : ' ');
245 $end = $reply_citation_end;
246 $full_reply_citation = $start . $sOrig_from . $end;
247 break;
248 default:
249 return '';
250 }
251
252 /* Add line feed and return the citation string. */
253 return ($full_reply_citation . "\n");
254 }
255
256 /**
257 * Creates header fields in forwarded email body
258 *
259 * $default_charset global must be set correctly before you call this function.
260 * @param object $orig_header
261 * @return $string
262 */
263 function getforwardHeader($orig_header) {
264 global $editor_size, $default_charset;
265
266 // using own strlen function in order to detect correct string length
267 $display = array( _("Subject") => sq_strlen(_("Subject"),$default_charset),
268 _("From") => sq_strlen(_("From"),$default_charset),
269 _("Date") => sq_strlen(_("Date"),$default_charset),
270 _("To") => sq_strlen(_("To"),$default_charset),
271 _("Cc") => sq_strlen(_("Cc"),$default_charset) );
272 $maxsize = max($display);
273 $indent = str_pad('',$maxsize+2);
274 foreach($display as $key => $val) {
275 $display[$key] = $key .': '. str_pad('', $maxsize - $val);
276 }
277 $from = decodeHeader($orig_header->getAddr_s('from',"\n$indent"),false,false,true);
278 $from = str_replace('&nbsp;',' ',$from);
279 $to = decodeHeader($orig_header->getAddr_s('to',"\n$indent"),false,false,true);
280 $to = str_replace('&nbsp;',' ',$to);
281 $subject = decodeHeader($orig_header->subject,false,false,true);
282 $subject = str_replace('&nbsp;',' ',$subject);
283
284 // using own str_pad function in order to create correct string pad
285 $bodyTop = sq_str_pad(' '._("Original Message").' ',$editor_size -2,'-',STR_PAD_BOTH,$default_charset) .
286 "\n". $display[_("Subject")] . $subject . "\n" .
287 $display[_("From")] . $from . "\n" .
288 $display[_("Date")] . getLongDateString( $orig_header->date ). "\n" .
289 $display[_("To")] . $to . "\n";
290 if ($orig_header->cc != array() && $orig_header->cc !='') {
291 $cc = decodeHeader($orig_header->getAddr_s('cc',"\n$indent"),false,false,true);
292 $cc = str_replace('&nbsp;',' ',$cc);
293 $bodyTop .= $display[_("Cc")] .$cc . "\n";
294 }
295 $bodyTop .= str_pad('', $editor_size -2 , '-') .
296 "\n\n";
297 return $bodyTop;
298 }
299 /* ----------------------------------------------------------------------- */
300
301 /*
302 * If the session is expired during a post this restores the compose session
303 * vars.
304 */
305 if (sqsession_is_registered('session_expired_post')) {
306 sqgetGlobalVar('session_expired_post', $session_expired_post, SQ_SESSION);
307 /*
308 * extra check for username so we don't display previous post data from
309 * another user during this session.
310 */
311 if ($session_expired_post['username'] != $username) {
312 unset($session_expired_post);
313 sqsession_unregister('session_expired_post');
314 session_write_close();
315 } else {
316 // these are the vars that we can set from the expired composed session
317 $compo_var_list = array ( 'send_to', 'send_to_cc','body','startMessage',
318 'passed_body','use_signature','signature','attachments','subject','newmail',
319 'send_to_bcc', 'passed_id', 'mailbox', 'from_htmladdr_search', 'identity',
320 'draft_id', 'delete_draft', 'mailprio', 'edit_as_new', 'compose_messsages',
321 'composesession', 'request_mdn', 'request_dr');
322
323 foreach ($compo_var_list as $var) {
324 if ( isset($session_expired_post[$var]) && !isset($$var) ) {
325 $$var = $session_expired_post[$var];
326 }
327 }
328
329 $compose_messages = unserialize(urldecode($restoremessages));
330 sqsession_register($compose_messages,'compose_messages');
331 sqsession_register($composesession,'composesession');
332 if (isset($send)) {
333 unset($send);
334 }
335 $session_expired = true;
336 }
337 unset($session_expired_post);
338 sqsession_unregister('session_expired_post');
339 session_write_close();
340 if (!isset($mailbox)) {
341 $mailbox = '';
342 }
343 if ($compose_new_win == '1') {
344 compose_Header($color, $mailbox);
345 } else {
346 $sHeaderJs = (isset($sHeaderJs)) ? $sHeaderJs : '';
347 if (strpos($action, 'reply') !== false && $reply_focus) {
348 $sBodyTagJs = 'onload="checkForm(\''.$replyfocus.'\');"';
349 } else {
350 $sBodyTagJs = 'onload="checkForm();"';
351 }
352 displayPageHeader($color, $mailbox,$sHeaderJs,$sBodyTagJs);
353 }
354 showInputForm($session, false);
355 exit();
356 }
357 if (!isset($composesession)) {
358 $composesession = 0;
359 sqsession_register(0,'composesession');
360 } else {
361 $composesession = (int)$composesession;
362 }
363
364 if (!isset($session) || (isset($newmessage) && $newmessage)) {
365 sqsession_unregister('composesession');
366 $session = "$composesession" +1;
367 $composesession = $session;
368 sqsession_register($composesession,'composesession');
369 }
370 if (!isset($compose_messages)) {
371 $compose_messages = array();
372 }
373
374 if (!isset($compose_messages[$session]) || ($compose_messages[$session] == NULL)) {
375 $composeMessage = new Message();
376 $rfc822_header = new Rfc822Header();
377 $composeMessage->rfc822_header = $rfc822_header;
378 $composeMessage->reply_rfc822_header = '';
379 $compose_messages[$session] = $composeMessage;
380
381 sqsession_register($compose_messages,'compose_messages');
382 } else {
383 $composeMessage=$compose_messages[$session];
384 }
385
386 if (!isset($mailbox) || $mailbox == '' || ($mailbox == 'None')) {
387 $mailbox = 'INBOX';
388 }
389
390 if ($draft) {
391 /*
392 * Set $default_charset to correspond with the user's selection
393 * of language interface.
394 */
395 set_my_charset();
396 $composeMessage=$compose_messages[$session];
397 if (! deliverMessage($composeMessage, true)) {
398 showInputForm($session);
399 exit();
400 } else {
401 $compose_messages[$session] = NULL;
402 unset($compose_messages[$session]);
403 $draft_message = _("Draft Email Saved");
404 /* If this is a resumed draft, then delete the original */
405 if(isset($delete_draft)) {
406 $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, false);
407 sqimap_mailbox_select($imap_stream, $draft_folder);
408 // force bypass_trash=true because message should be saved when deliverMessage() returns true.
409 // in current implementation of sqimap_msgs_list_flag() single message id can
410 // be submitted as string. docs state that it should be array.
411 sqimap_msgs_list_delete($imap_stream, $draft_folder, $delete_draft, true);
412 if ($auto_expunge) {
413 sqimap_mailbox_expunge($imap_stream, $draft_folder, true);
414 }
415 sqimap_logout($imap_stream);
416 }
417
418 $oErrorHandler->saveDelayedErrors();
419 session_write_close();
420
421 if ($compose_new_win == '1') {
422 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
423 Header("Location: $location/compose.php?saved_draft=yes&session=$composesession");
424 } else {
425 echo ' <br><br><div style="text-align: center;"><a href="' . $location
426 . '/compose.php?saved_sent=yes&amp;session=' . $composesession . '">'
427 . _("Return") . '</a></div>';
428 }
429 exit();
430 } else {
431 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
432 Header("Location: $location/right_main.php?mailbox=" . urlencode($draft_folder) .
433 "&startMessage=1&note=".urlencode($draft_message));
434 } else {
435 echo ' <br><br><div style="text-align: center;"><a href="' . $location
436 . '/right_main.php?mailbox=' . urlencode($draft_folder)
437 . '&amp;startMessage=1&amp;note=' . urlencode($draft_message) .'">'
438 . _("Return") . '</a></div>';
439 }
440 exit();
441 }
442 }
443 }
444
445 if ($send) {
446 if (isset($_FILES['attachfile']) &&
447 $_FILES['attachfile']['tmp_name'] &&
448 $_FILES['attachfile']['tmp_name'] != 'none') {
449 $AttachFailure = saveAttachedFiles($session);
450 }
451 if (checkInput(false) && !isset($AttachFailure)) {
452 if ($mailbox == "All Folders") {
453 /* We entered compose via the search results page */
454 $mailbox = 'INBOX'; /* Send 'em to INBOX, that's safe enough */
455 }
456 $urlMailbox = urlencode (trim($mailbox));
457 if (! isset($passed_id)) {
458 $passed_id = 0;
459 }
460 /**
461 * Set $default_charset to correspond with the user's selection
462 * of language interface.
463 */
464 set_my_charset();
465 /**
466 * This is to change all newlines to \n
467 * We'll change them to \r\n later (in the sendMessage function)
468 */
469 $body = str_replace("\r\n", "\n", $body);
470 $body = str_replace("\r", "\n", $body);
471
472 /**
473 * Rewrap $body so that no line is bigger than $editor_size
474 */
475 $body = explode("\n", $body);
476 $newBody = '';
477 foreach ($body as $line) {
478 if( $line <> '-- ' ) {
479 $line = rtrim($line);
480 }
481 if (sq_strlen($line,$default_charset) <= $editor_size + 1) {
482 $newBody .= $line . "\n";
483 } else {
484 sqWordWrap($line, $editor_size,$default_charset);
485 $newBody .= $line . "\n";
486
487 }
488
489 }
490 $body = $newBody;
491
492 $composeMessage=$compose_messages[$session];
493
494 $Result = deliverMessage($composeMessage);
495
496 // NOTE: this hook changed in 1.5.2 from sending $Result and
497 // $composeMessage as args #2 and #3 to being in an array
498 // under arg #2
499 do_hook('compose_send_after', $temp=array(&$Result, &$composeMessage));
500 if (! $Result) {
501 showInputForm($session);
502 exit();
503 }
504 $compose_messages[$session] = NULL;
505 unset($compose_messages[$session]);
506
507 /* if it is resumed draft, delete draft message */
508 if ( isset($delete_draft)) {
509 $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, false);
510 sqimap_mailbox_select($imap_stream, $draft_folder);
511 // bypass_trash=true because message should be saved when deliverMessage() returns true.
512 // in current implementation of sqimap_msgs_list_flag() single message id can
513 // be submitted as string. docs state that it should be array.
514 sqimap_msgs_list_delete($imap_stream, $draft_folder, $delete_draft, true);
515 if ($auto_expunge) {
516 sqimap_mailbox_expunge($imap_stream, $draft_folder, true);
517 }
518 sqimap_logout($imap_stream);
519 }
520 /*
521 * Store the error array in the session because they will be lost on a redirect
522 */
523 $oErrorHandler->saveDelayedErrors();
524 session_write_close();
525
526 if ($compose_new_win == '1') {
527 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
528 Header("Location: $location/compose.php?mail_sent=yes");
529 } else {
530 echo ' <br><br><div style="text-align: center;"><a href="' . $location
531 . '/compose.php?mail_sent=yes">'
532 . _("Return") . '</a></div>';
533 }
534 exit();
535 } else {
536 if ( !isset($pageheader_sent) || !$pageheader_sent ) {
537 Header("Location: $location/right_main.php?mailbox=$urlMailbox".
538 "&startMessage=$startMessage&mail_sent=yes");
539 } else {
540 echo ' <br><br><div style="text-align: center;"><a href="' . $location
541 . "/right_main.php?mailbox=$urlMailbox"
542 . "&amp;startMessage=$startMessage&amp;mail_sent=yes\">"
543 . _("Return") . '</a></div>';
544 }
545 exit();
546 }
547 } else {
548 if ($compose_new_win == '1') {
549 compose_Header($color, $mailbox);
550 }
551 else {
552 displayPageHeader($color, $mailbox);
553 }
554 if (isset($AttachFailure)) {
555 plain_error_message(_("Could not move/copy file. File not attached"),
556 $color);
557 }
558 checkInput(true);
559 showInputForm($session);
560 /* sqimap_logout($imapConnection); */
561 }
562 } elseif (isset($html_addr_search_done)) {
563 if ($compose_new_win == '1') {
564 compose_Header($color, $mailbox);
565 }
566 else {
567 displayPageHeader($color, $mailbox);
568 }
569
570 if (isset($send_to_search) && is_array($send_to_search)) {
571 foreach ($send_to_search as $k => $v) {
572 if (substr($k, 0, 1) == 'T') {
573 if ($send_to) {
574 $send_to .= ', ';
575 }
576 $send_to .= $v;
577 }
578 elseif (substr($k, 0, 1) == 'C') {
579 if ($send_to_cc) {
580 $send_to_cc .= ', ';
581 }
582 $send_to_cc .= $v;
583 }
584 elseif (substr($k, 0, 1) == 'B') {
585 if ($send_to_bcc) {
586 $send_to_bcc .= ', ';
587 }
588 $send_to_bcc .= $v;
589 }
590 }
591 }
592 showInputForm($session);
593 } elseif (isset($html_addr_search) && !isset($html_addr_search_cancel)) {
594 if (isset($_FILES['attachfile']) &&
595 $_FILES['attachfile']['tmp_name'] &&
596 $_FILES['attachfile']['tmp_name'] != 'none') {
597 if(saveAttachedFiles($session)) {
598 plain_error_message(_("Could not move/copy file. File not attached"));
599 }
600 }
601 /*
602 * I am using an include so as to elminiate an extra unnecessary
603 * click. If you can think of a better way, please implement it.
604 */
605 include_once('./addrbook_search_html.php');
606 } elseif (isset($attach)) {
607 if ($compose_new_win == '1') {
608 compose_Header($color, $mailbox);
609 } else {
610 displayPageHeader($color, $mailbox);
611 }
612 if (saveAttachedFiles($session)) {
613 plain_error_message(_("Could not move/copy file. File not attached"));
614 }
615 showInputForm($session);
616 }
617 elseif (isset($sigappend)) {
618 $signature = $idents[$identity]['signature'];
619
620 $body .= "\n\n".($prefix_sig==true? "-- \n":'').$signature;
621 if ($compose_new_win == '1') {
622 compose_Header($color, $mailbox);
623 } else {
624 displayPageHeader($color, $mailbox);
625 }
626 showInputForm($session);
627 } elseif (isset($do_delete)) {
628 if ($compose_new_win == '1') {
629 compose_Header($color, $mailbox);
630 } else {
631 displayPageHeader($color, $mailbox);
632 }
633
634 if (isset($delete) && is_array($delete)) {
635 $composeMessage = $compose_messages[$session];
636 foreach($delete as $index) {
637 if (!empty($composeMessage->entities) && isset($composeMessage->entities[$index])) {
638 $composeMessage->entities[$index]->purgeAttachments();
639 unset ($composeMessage->entities[$index]);
640 }
641 }
642 $new_entities = array();
643 foreach ($composeMessage->entities as $entity) {
644 $new_entities[] = $entity;
645 }
646 $composeMessage->entities = $new_entities;
647 $compose_messages[$session] = $composeMessage;
648 sqsession_register($compose_messages, 'compose_messages');
649 }
650 showInputForm($session);
651 } else {
652 /*
653 * This handles the default case as well as the error case
654 * (they had the same code) --> if (isset($smtpErrors))
655 */
656
657 if ($compose_new_win == '1') {
658 compose_Header($color, $mailbox);
659 } else {
660 displayPageHeader($color, $mailbox);
661 }
662
663 $newmail = true;
664
665 if (!isset($passed_ent_id)) {
666 $passed_ent_id = '';
667 }
668 if (!isset($passed_id)) {
669 $passed_id = '';
670 }
671 if (!isset($mailbox)) {
672 $mailbox = '';
673 }
674 if (!isset($action)) {
675 $action = '';
676 }
677
678 $values = newMail($mailbox,$passed_id,$passed_ent_id, $action, $session);
679
680 /* in case the origin is not read_body.php */
681 if (isset($send_to)) {
682 $values['send_to'] = $send_to;
683 }
684 if (isset($send_to_cc)) {
685 $values['send_to_cc'] = $send_to_cc;
686 }
687 if (isset($send_to_bcc)) {
688 $values['send_to_bcc'] = $send_to_bcc;
689 }
690 if (isset($subject)) {
691 $values['subject'] = $subject;
692 }
693 showInputForm($session, $values);
694 }
695
696 exit();
697
698 /**************** Only function definitions go below *************/
699
700 function getforwardSubject($subject)
701 {
702 if ((substr(strtolower($subject), 0, 4) != 'fwd:') &&
703 (substr(strtolower($subject), 0, 5) != '[fwd:') &&
704 (substr(strtolower($subject), 0, 6) != '[ fwd:')) {
705 $subject = '[Fwd: ' . $subject . ']';
706 }
707 return $subject;
708 }
709
710 /* This function is used when not sending or adding attachments */
711 function newMail ($mailbox='', $passed_id='', $passed_ent_id='', $action='', $session='') {
712 global $editor_size, $default_use_priority, $body, $idents,
713 $use_signature, $data_dir, $username,
714 $key, $imapServerAddress, $imapPort, $compose_messages,
715 $composeMessage, $body_quote, $request_mdn, $request_dr,
716 $default_use_mdn, $mdn_user_support;
717 global $languages, $squirrelmail_language, $default_charset;
718
719 /*
720 * Set $default_charset to correspond with the user's selection
721 * of language interface. $default_charset global is not correct,
722 * if message is composed in new window.
723 */
724 set_my_charset();
725
726 $send_to = $send_to_cc = $send_to_bcc = $subject = $identity = '';
727 $mailprio = 3;
728
729 if ($passed_id) {
730 $imapConnection = sqimap_login($username, false, $imapServerAddress,
731 $imapPort, 0);
732
733 sqimap_mailbox_select($imapConnection, $mailbox);
734 $message = sqimap_get_message($imapConnection, $passed_id, $mailbox);
735
736 $body = '';
737 if ($passed_ent_id) {
738 /* redefine the messsage in case of message/rfc822 */
739 $message = $message->getEntity($passed_ent_id);
740 /* message is an entity which contains the envelope and type0=message
741 * and type1=rfc822. The actual entities are childs from
742 * $message->entities[0]. That's where the encoding and is located
743 */
744
745 $entities = $message->entities[0]->findDisplayEntity
746 (array(), $alt_order = array('text/plain'));
747 if (!count($entities)) {
748 $entities = $message->entities[0]->findDisplayEntity
749 (array(), $alt_order = array('text/plain','html/plain'));
750 }
751 $orig_header = $message->rfc822_header; /* here is the envelope located */
752 /* redefine the message for picking up the attachments */
753 $message = $message->entities[0];
754
755 } else {
756 $entities = $message->findDisplayEntity (array(), $alt_order = array('text/plain'));
757 if (!count($entities)) {
758 $entities = $message->findDisplayEntity (array(), $alt_order = array('text/plain','html/plain'));
759 }
760 $orig_header = $message->rfc822_header;
761 }
762
763 $type0 = $message->type0;
764 $type1 = $message->type1;
765 foreach ($entities as $ent) {
766 $msg = $message->getEntity($ent);
767 $type0 = $msg->type0;
768 $type1 = $msg->type1;
769 $unencoded_bodypart = mime_fetch_body($imapConnection, $passed_id, $ent);
770 $body_part_entity = $message->getEntity($ent);
771 $bodypart = decodeBody($unencoded_bodypart,
772 $body_part_entity->header->encoding);
773 if ($type1 == 'html') {
774 $bodypart = str_replace("\n", ' ', $bodypart);
775 $bodypart = preg_replace(array('/<\/?p>/i','/<div><\/div>/i','/<br\s*(\/)*>/i','/<\/?div>/i'), "\n", $bodypart);
776 $bodypart = str_replace(array('&nbsp;','&gt;','&lt;'),array(' ','>','<'),$bodypart);
777 $bodypart = strip_tags($bodypart);
778 }
779 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
780 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
781 if (mb_detect_encoding($bodypart) != 'ASCII') {
782 $bodypart = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode', $bodypart);
783 }
784 }
785
786 // charset encoding in compose form stuff
787 if (isset($body_part_entity->header->parameters['charset'])) {
788 $actual = $body_part_entity->header->parameters['charset'];
789 } else {
790 $actual = 'us-ascii';
791 }
792
793 if ( $actual && is_conversion_safe($actual) && $actual != $default_charset){
794 $bodypart = charset_convert($actual,$bodypart,$default_charset,false);
795 }
796 // end of charset encoding in compose
797
798 $body .= $bodypart;
799 }
800 if ($default_use_priority) {
801 $mailprio = substr($orig_header->priority,0,1);
802 if (!$mailprio) {
803 $mailprio = 3;
804 }
805 } else {
806 $mailprio = '';
807 }
808
809 $identity = '';
810 $from_o = $orig_header->from;
811 if (is_array($from_o)) {
812 if (isset($from_o[0])) {
813 $from_o = $from_o[0];
814 }
815 }
816 if (is_object($from_o)) {
817 $orig_from = $from_o->getAddress();
818 } else {
819 $orig_from = '';
820 }
821
822 $identities = array();
823 if (count($idents) > 1) {
824 foreach($idents as $nr=>$data) {
825 $enc_from_name = '"'.$data['full_name'].'" <'. $data['email_address'].'>';
826 if($enc_from_name == $orig_from) {
827 $identity = $nr;
828 break;
829 }
830 $identities[] = $enc_from_name;
831 }
832
833 $identity_match = $orig_header->findAddress($identities);
834 if ($identity_match) {
835 $identity = $identity_match;
836 }
837 }
838
839 switch ($action) {
840 case ('draft'):
841 $use_signature = FALSE;
842 $composeMessage->rfc822_header = $orig_header;
843 $send_to = decodeHeader($orig_header->getAddr_s('to'),false,false,true);
844 $send_to_cc = decodeHeader($orig_header->getAddr_s('cc'),false,false,true);
845 $send_to_bcc = decodeHeader($orig_header->getAddr_s('bcc'),false,false,true);
846 $send_from = $orig_header->getAddr_s('from');
847 $send_from_parts = new AddressStructure();
848 $send_from_parts = $orig_header->parseAddress($send_from);
849 $send_from_add = $send_from_parts->mailbox . '@' . $send_from_parts->host;
850 $identities = get_identities();
851 if (count($identities) > 0) {
852 foreach($identities as $iddata) {
853 if ($send_from_add == $iddata['email_address']) {
854 $identity = $iddata['index'];
855 break;
856 }
857 }
858 }
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)) ? $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', _("Draft Saved"));
1157 $oTemplate->display('note.tpl');
1158 }
1159 if ($mail_sent == 'yes') {
1160 $oTemplate->assign('note', _("Your message 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 if ($composeMessage->entities) {
1256 foreach ($composeMessage->entities as $key => $attachment) {
1257 $attached_file = $attachment->att_local_name;
1258 if ($attachment->att_local_name || $attachment->body_part) {
1259 $attached_filename = decodeHeader($attachment->mime_header->getParameter('name'));
1260 $type = $attachment->mime_header->type0.'/'.
1261 $attachment->mime_header->type1;
1262
1263 $a = array();
1264 $a['Key'] = $key;
1265 $a['FileName'] = $attached_filename;
1266 $a['ContentType'] = $type;
1267 $a['Size'] = filesize($attached_file);
1268 $attach[$key] = $a;
1269 }
1270 }
1271 }
1272
1273 $max = min($sizes);
1274 $oTemplate->assign('max_file_size', empty($max) ? -1 : $max);
1275 $oTemplate->assign('attachments', $attach);
1276
1277 $oTemplate->display('compose_attachments.tpl');
1278 } // End of file_uploads if-block
1279 /* End of attachment code */
1280
1281 echo addHidden('username', $username).
1282 addHidden('smaction', $action).
1283 addHidden('mailbox', $mailbox);
1284 /*
1285 store the complete ComposeMessages array in a hidden input value
1286 so we can restore them in case of a session timeout.
1287 */
1288 //sm_print_r($compose_messages);
1289 sqgetGlobalVar('QUERY_STRING', $queryString, SQ_SERVER);
1290 echo addHidden('restoremessages', urlencode(serialize($compose_messages))).
1291 addHidden('composesession', $composesession).
1292 addHidden('querystring', $queryString).
1293 "</form>\n";
1294 if (!(bool) ini_get('file_uploads')) {
1295 /* File uploads are off, so we didn't show that part of the form.
1296 To avoid bogus bug reports, tell the user why. */
1297 echo '<p style="text-align:center">'
1298 . _("Because PHP file uploads are turned off, you can not attach files to this message. Please see your system administrator for details.")
1299 . "</p>\r\n";
1300 }
1301
1302 do_hook('compose_bottom', $null);
1303
1304 if ($compose_new_win=='1') {
1305 $oTemplate->display('compose_newwin_close.tpl');
1306 }
1307
1308 $oErrorHandler->setDelayedErrors(false);
1309 $oTemplate->display('footer.tpl');
1310 }
1311
1312
1313 function showComposeButtonRow() {
1314 global $use_javascript_addr_book, $save_as_draft,
1315 $default_use_priority, $mailprio, $default_use_mdn,
1316 $request_mdn, $request_dr,
1317 $data_dir, $username;
1318
1319 global $oTemplate, $buffer_hook;
1320
1321 if ($default_use_priority) {
1322 $priorities = array('1'=>_("High"), '3'=>_("Normal"), '5'=>_("Low"));
1323 $priority = isset($mailprio) ? $mailprio : 3;
1324 } else {
1325 $priorities = array();
1326 $priority = NULL;
1327 }
1328
1329 $mdn_user_support=getPref($data_dir, $username, 'mdn_user_support',$default_use_mdn);
1330
1331 if ($use_javascript_addr_book) {
1332 $addr_book = " <script type=\"text/javascript\"><!--\n document.write(\"".
1333 " <input type=button value=\\\""._("Addresses").
1334 "\\\" onclick=\\\"javascript:open_abook();\\\" />\");".
1335 " // --></script><noscript>\n".
1336 ' <input type="submit" name="html_addr_search" value="'.
1337 _("Addresses").'" />'.
1338 " </noscript>\n";
1339 } else {
1340 $addr_book = ' <input type="submit" name="html_addr_search" value="'.
1341 _("Addresses").'" />' . "\n";
1342 }
1343
1344 $oTemplate->assign('allow_priority', $default_use_priority==1);
1345 $oTemplate->assign('priority_list', $priorities);
1346 $oTemplate->assign('current_priority', $priority);
1347
1348 $oTemplate->assign('notifications_enabled', $mdn_user_support==1);
1349 $oTemplate->assign('read_receipt', $request_mdn=='1');
1350 $oTemplate->assign('delivery_receipt', $request_dr=='1');
1351
1352 $oTemplate->assign('drafts_enabled', $save_as_draft);
1353 $oTemplate->assign('address_book_button', $addr_book);
1354
1355 $oTemplate->display('compose_buttons.tpl');
1356 }
1357
1358 function checkInput ($show) {
1359 /*
1360 * I implemented the $show variable because the error messages
1361 * were getting sent before the page header. So, I check once
1362 * using $show=false, and then when i'm ready to display the error
1363 * message, show=true
1364 */
1365 global $send_to, $send_to_bcc;
1366
1367 if ($send_to == '' && $send_to_bcc == '') {
1368 if ($show) {
1369 plain_error_message(_("You have not filled in the \"To:\" field."));
1370 }
1371 return false;
1372 }
1373 return true;
1374 } /* function checkInput() */
1375
1376
1377 /* True if FAILURE */
1378 function saveAttachedFiles($session) {
1379 global $compose_messages;
1380
1381 /* get out of here if no file was attached at all */
1382 if (! is_uploaded_file($_FILES['attachfile']['tmp_name']) ) {
1383 return true;
1384 }
1385
1386 $localfilename = sq_get_attach_tempfile();
1387
1388 // m_u_f works better with restricted PHP installs (safe_mode, open_basedir),
1389 // if that doesn't work, try a simple rename.
1390 if (!@move_uploaded_file($_FILES['attachfile']['tmp_name'],$localfilename)) {
1391 if (!@rename($_FILES['attachfile']['tmp_name'], $localfilename)) {
1392 return true;
1393 }
1394 }
1395 $message = $compose_messages[$session];
1396 $type = strtolower($_FILES['attachfile']['type']);
1397 $name = $_FILES['attachfile']['name'];
1398 $message->initAttachment($type, $name, $localfilename);
1399 $compose_messages[$session] = $message;
1400 sqsession_register($compose_messages , 'compose_messages');
1401 }
1402
1403 /* parse values like 8M and 2k into bytes */
1404 function getByteSize($ini_size) {
1405
1406 if(!$ini_size) {
1407 return FALSE;
1408 }
1409
1410 $ini_size = trim($ini_size);
1411
1412 // if there's some kind of letter at the end of the string we need to multiply.
1413 if(!is_numeric(substr($ini_size, -1))) {
1414
1415 switch(strtoupper(substr($ini_size, -1))) {
1416 case 'G':
1417 $bytesize = 1073741824;
1418 break;
1419 case 'M':
1420 $bytesize = 1048576;
1421 break;
1422 case 'K':
1423 $bytesize = 1024;
1424 break;
1425 }
1426
1427 return ($bytesize * (int)substr($ini_size, 0, -1));
1428 }
1429
1430 return $ini_size;
1431 }
1432
1433
1434 /**
1435 * temporary function to make use of the deliver class.
1436 * In the future the responsible backend should be automaticly loaded
1437 * and conf.pl should show a list of available backends.
1438 * The message also should be constructed by the message class.
1439 */
1440 function deliverMessage($composeMessage, $draft=false) {
1441 global $send_to, $send_to_cc, $send_to_bcc, $mailprio, $subject, $body,
1442 $username, $popuser, $usernamedata, $identity, $idents, $data_dir,
1443 $request_mdn, $request_dr, $default_charset, $color, $useSendmail,
1444 $domain, $action, $default_move_to_sent, $move_to_sent;
1445 global $imapServerAddress, $imapPort, $sent_folder, $key;
1446
1447 $rfc822_header = $composeMessage->rfc822_header;
1448
1449 $abook = addressbook_init(false, true);
1450 $rfc822_header->to = $rfc822_header->parseAddress($send_to,true, array(), '', $domain, array(&$abook,'lookup'));
1451 $rfc822_header->cc = $rfc822_header->parseAddress($send_to_cc,true,array(), '',$domain, array(&$abook,'lookup'));
1452 $rfc822_header->bcc = $rfc822_header->parseAddress($send_to_bcc,true, array(), '',$domain, array(&$abook,'lookup'));
1453 $rfc822_header->priority = $mailprio;
1454 $rfc822_header->subject = $subject;
1455
1456 $special_encoding='';
1457 if (strtolower($default_charset) == 'iso-2022-jp') {
1458 if (mb_detect_encoding($body) == 'ASCII') {
1459 $special_encoding = '8bit';
1460 } else {
1461 $body = mb_convert_encoding($body, 'JIS');
1462 $special_encoding = '7bit';
1463 }
1464 }
1465 $composeMessage->setBody($body);
1466
1467 if (ereg("^([^@%/]+)[@%/](.+)$", $username, $usernamedata)) {
1468 $popuser = $usernamedata[1];
1469 $domain = $usernamedata[2];
1470 unset($usernamedata);
1471 } else {
1472 $popuser = $username;
1473 }
1474 $reply_to = '';
1475 $from_mail = $idents[$identity]['email_address'];
1476 $full_name = $idents[$identity]['full_name'];
1477 $reply_to = $idents[$identity]['reply_to'];
1478 if (!$from_mail) {
1479 $from_mail = "$popuser@$domain";
1480 }
1481 $rfc822_header->from = $rfc822_header->parseAddress($from_mail,true);
1482 if ($full_name) {
1483 $from = $rfc822_header->from[0];
1484 if (!$from->host) $from->host = $domain;
1485 $full_name_encoded = encodeHeader($full_name);
1486 if ($full_name_encoded != $full_name) {
1487 $from_addr = $full_name_encoded .' <'.$from->mailbox.'@'.$from->host.'>';
1488 } else {
1489 $from_addr = '"'.$full_name .'" <'.$from->mailbox.'@'.$from->host.'>';
1490 }
1491 $rfc822_header->from = $rfc822_header->parseAddress($from_addr,true);
1492 }
1493 if ($reply_to) {
1494 $rfc822_header->reply_to = $rfc822_header->parseAddress($reply_to,true);
1495 }
1496 /* Receipt: On Read */
1497 if (isset($request_mdn) && $request_mdn) {
1498 $rfc822_header->dnt = $rfc822_header->parseAddress($from_mail,true);
1499 } elseif (isset($rfc822_header->dnt)) {
1500 unset($rfc822_header->dnt);
1501 }
1502
1503 /* Receipt: On Delivery */
1504 if (isset($request_dr) && $request_dr) {
1505 $rfc822_header->more_headers['Return-Receipt-To'] = $from_mail;
1506 } elseif (isset($rfc822_header->more_headers['Return-Receipt-To'])) {
1507 unset($rfc822_header->more_headers['Return-Receipt-To']);
1508 }
1509
1510 /* multipart messages */
1511 if (count($composeMessage->entities)) {
1512 $message_body = new Message();
1513 $message_body->body_part = $composeMessage->body_part;
1514 $composeMessage->body_part = '';
1515 $mime_header = new MessageHeader;
1516 $mime_header->type0 = 'text';
1517 $mime_header->type1 = 'plain';
1518 if ($special_encoding) {
1519 $mime_header->encoding = $special_encoding;
1520 } else {
1521 $mime_header->encoding = '8bit';
1522 }
1523 if ($default_charset) {
1524 $mime_header->parameters['charset'] = $default_charset;
1525 }
1526 $message_body->mime_header = $mime_header;
1527 array_unshift($composeMessage->entities, $message_body);
1528 $content_type = new ContentType('multipart/mixed');
1529 } else {
1530 $content_type = new ContentType('text/plain');
1531 if ($special_encoding) {
1532 $rfc822_header->encoding = $special_encoding;
1533 } else {
1534 $rfc822_header->encoding = '8bit';
1535 }
1536 if ($default_charset) {
1537 $content_type->properties['charset']=$default_charset;
1538 }
1539 }
1540
1541 $rfc822_header->content_type = $content_type;
1542 $composeMessage->rfc822_header = $rfc822_header;
1543
1544 /* Here you can modify the message structure just before we hand
1545 it over to deliver; plugin authors note that $composeMessage
1546 is sent and modified by reference since 1.5.2 */
1547 do_hook('compose_send', $composeMessage);
1548
1549 if (!$useSendmail && !$draft) {
1550 require_once(SM_PATH . 'class/deliver/Deliver_SMTP.class.php');
1551 $deliver = new Deliver_SMTP();
1552 global $smtpServerAddress, $smtpPort, $pop_before_smtp;
1553
1554 $authPop = (isset($pop_before_smtp) && $pop_before_smtp) ? true : false;
1555 get_smtp_user($user, $pass);
1556 $stream = $deliver->initStream($composeMessage,$domain,0,
1557 $smtpServerAddress, $smtpPort, $user, $pass, $authPop);
1558 } elseif (!$draft) {
1559 require_once(SM_PATH . 'class/deliver/Deliver_SendMail.class.php');
1560 global $sendmail_path, $sendmail_args;
1561 // Check for outdated configuration
1562 if (!isset($sendmail_args)) {
1563 if ($sendmail_path=='/var/qmail/bin/qmail-inject') {
1564 $sendmail_args = '';
1565 } else {
1566 $sendmail_args = '-i -t';
1567 }
1568 }
1569 $deliver = new Deliver_SendMail(array('sendmail_args'=>$sendmail_args));
1570 $stream = $deliver->initStream($composeMessage,$sendmail_path);
1571 } elseif ($draft) {
1572 global $draft_folder;
1573 require_once(SM_PATH . 'class/deliver/Deliver_IMAP.class.php');
1574 $imap_stream = sqimap_login($username, false, $imapServerAddress,
1575 $imapPort, 0);
1576 if (sqimap_mailbox_exists ($imap_stream, $draft_folder)) {
1577 require_once(SM_PATH . 'class/deliver/Deliver_IMAP.class.php');
1578 $imap_deliver = new Deliver_IMAP();
1579 $length = $imap_deliver->mail($composeMessage);
1580 sqimap_append ($imap_stream, $draft_folder, $length);
1581 $imap_deliver->mail($composeMessage, $imap_stream);
1582 sqimap_append_done ($imap_stream, $draft_folder);
1583 sqimap_logout($imap_stream);
1584 unset ($imap_deliver);
1585 $composeMessage->purgeAttachments();
1586 return $length;
1587 } else {
1588 $msg = '<br />'.sprintf(_("Error: Draft folder %s does not exist."), htmlspecialchars($draft_folder));
1589 plain_error_message($msg);
1590 return false;
1591 }
1592 }
1593 $success = false;
1594 if ($stream) {
1595 $length = $deliver->mail($composeMessage, $stream);
1596 $success = $deliver->finalizeStream($stream);
1597 }
1598 if (!$success) {
1599 // $deliver->dlv_server_msg is not always server's reply
1600 $msg = _("Message not sent.") . "<br />\n" .
1601 $deliver->dlv_msg;
1602 if (!empty($deliver->dlv_server_msg)) {
1603 // add 'server replied' part only when it is not empty.
1604 // Delivery error can be generated by delivery class itself
1605 $msg.='<br />' .
1606 _("Server replied:") . ' ' . $deliver->dlv_ret_nr . ' ' .
1607 nl2br(htmlspecialchars($deliver->dlv_server_msg));
1608 }
1609 plain_error_message($msg);
1610 } else {
1611 unset ($deliver);
1612 $move_to_sent = getPref($data_dir,$username,'move_to_sent');
1613 $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, 0);
1614
1615 /* Move to sent code */
1616 if (isset($default_move_to_sent) && ($default_move_to_sent != 0)) {
1617 $svr_allow_sent = true;
1618 } else {
1619 $svr_allow_sent = false;
1620 }
1621
1622 if (isset($sent_folder) && (($sent_folder != '') || ($sent_folder != 'none'))
1623 && sqimap_mailbox_exists( $imap_stream, $sent_folder)) {
1624 $fld_sent = true;
1625 } else {
1626 $fld_sent = false;
1627 }
1628
1629 if ((isset($move_to_sent) && ($move_to_sent != 0)) || (!isset($move_to_sent))) {
1630 $lcl_allow_sent = true;
1631 } else {
1632 $lcl_allow_sent = false;
1633 }
1634
1635 if (($fld_sent && $svr_allow_sent && !$lcl_allow_sent) || ($fld_sent && $lcl_allow_sent)) {
1636 global $passed_id, $mailbox, $action;
1637 if ($action == 'reply' || $action == 'reply_all') {
1638 $save_reply_with_orig=getPref($data_dir,$username,'save_reply_with_orig');
1639 if ($save_reply_with_orig) {
1640 $sent_folder = $mailbox;
1641 }
1642 }
1643 sqimap_append ($imap_stream, $sent_folder, $length);
1644 require_once(SM_PATH . 'class/deliver/Deliver_IMAP.class.php');
1645 $imap_deliver = new Deliver_IMAP();
1646 $imap_deliver->mail($composeMessage, $imap_stream);
1647 sqimap_append_done ($imap_stream, $sent_folder);
1648 unset ($imap_deliver);
1649 }
1650
1651 global $passed_id, $mailbox, $action, $what, $iAccount,$startMessage;
1652
1653 $composeMessage->purgeAttachments();
1654 unset($composeMessage);
1655 if ($action=='reply' || $action=='reply_all' || $action=='forward' || $action=='forward_as_attachment') {
1656 require(SM_PATH . 'functions/mailbox_display.php');
1657 $aMailbox = sqm_api_mailbox_select($imap_stream, $iAccount, $mailbox,array('setindex' => $what, 'offset' => $startMessage),array());
1658 switch($action) {
1659 case 'reply':
1660 case 'reply_all':
1661 // check if we are allowed to set the \\Answered flag
1662 if (in_array('\\answered',$aMailbox['PERMANENTFLAGS'], true)) {
1663 $aUpdatedMsgs = sqimap_toggle_flag($imap_stream, array($passed_id), '\\Answered', true, false);
1664 if (isset($aUpdatedMsgs[$passed_id]['FLAGS'])) {
1665 /**
1666 * Only update the cached headers if the header is
1667 * cached.
1668 */
1669 if (isset($aMailbox['MSG_HEADERS'][$passed_id])) {
1670 $aMailbox['MSG_HEADERS'][$passed_id]['FLAGS'] = $aMsg['FLAGS'];
1671 }
1672 }
1673 }
1674 break;
1675 case 'forward':
1676 case 'forward_as_attachment':
1677 // check if we are allowed to set the $Forwarded flag (RFC 4550 paragraph 2.8)
1678 if (in_array('$forwarded',$aMailbox['PERMANENTFLAGS'], true) ||
1679 in_array('\\*',$aMailbox['PERMANENTFLAGS'])) {
1680
1681 $aUpdatedMsgs = sqimap_toggle_flag($imap_stream, array($passed_id), '$Forwarded', true, false);
1682 if (isset($aUpdatedMsgs[$passed_id]['FLAGS'])) {
1683 if (isset($aMailbox['MSG_HEADERS'][$passed_id])) {
1684 $aMailbox['MSG_HEADERS'][$passed_id]['FLAGS'] = $aMsg['FLAGS'];
1685 }
1686 }
1687 }
1688 break;
1689 }
1690
1691 /**
1692 * Write mailbox with updated seen flag information back to cache.
1693 */
1694 if(isset($aUpdatedMsgs[$passed_id])) {
1695 $mailbox_cache[$iAccount.'_'.$aMailbox['NAME']] = $aMailbox;
1696 sqsession_register($mailbox_cache,'mailbox_cache');
1697 }
1698
1699 sqimap_logout($imap_stream);
1700 }
1701 }
1702 return $success;
1703 }
1704 ?>