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