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