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