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