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