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