Aleksander Machniak
2015-07-29 c5157fb74ad800c1d7473ad053c192cb543abf28
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/sendmail.inc                                       |
6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
0f16a0 8  | Copyright (C) 2005-2013, The Roundcube Dev Team                       |
7fe381 9  |                                                                       |
T 10  | Licensed under the GNU General Public License version 3 or            |
11  | any later version with exceptions for skins & plugins.                |
12  | See the README file for a full license statement.                     |
4e17e6 13  |                                                                       |
T 14  | PURPOSE:                                                              |
15  |   Compose a new mail message with all headers and attachments         |
e8f8fe 16  |   and send it using the PEAR::Net_SMTP class or with PHP mail()       |
4e17e6 17  |                                                                       |
T 18  +-----------------------------------------------------------------------+
19  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
20  +-----------------------------------------------------------------------+
21 */
22
0b6c1c 23 // remove all scripts and act as called in frame
T 24 $OUTPUT->reset();
25 $OUTPUT->framed = TRUE;
26
0f16a0 27 $savedraft      = !empty($_POST['_draft']) ? true : false;
AM 28 $sendmail_delay = (int) $RCMAIL->config->get('sendmail_delay');
29 $drafts_mbox    = $RCMAIL->config->get('drafts_mbox');
acb08f 30
6b2b2e 31 $COMPOSE_ID = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC);
72ff6a 32 $COMPOSE    =& $_SESSION['compose_data_'.$COMPOSE_ID];
4591de 33
acb08f 34 /****** checks ********/
0b6c1c 35
72ff6a 36 if (!isset($COMPOSE['id'])) {
0f16a0 37     rcube::raise_error(array('code' => 500, 'type' => 'php',
AM 38         'file' => __FILE__, 'line' => __LINE__,
39         'message' => "Invalid compose ID"), true, false);
10eedb 40
0f16a0 41     $OUTPUT->show_message('internalerror', 'error');
AM 42     $OUTPUT->send('iframe');
0b6c1c 43 }
4e17e6 44
4b60fa 45 if (!$savedraft) {
0f16a0 46     if (empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc'])
AM 47         && empty($_POST['_subject']) && $_POST['_message']
48     ) {
49         $OUTPUT->show_message('sendingfailed', 'error');
50         $OUTPUT->send('iframe');
acb08f 51     }
0f16a0 52
AM 53     if ($sendmail_delay) {
54         $wait_sec = time() - $sendmail_delay - intval($RCMAIL->config->get('last_message_time'));
55         if ($wait_sec < 0) {
56             $OUTPUT->show_message('senttooquickly', 'error', array('sec' => $wait_sec * -1));
57             $OUTPUT->send('iframe');
58         }
59     }
acb08f 60 }
A 61
4e17e6 62
acb08f 63 /****** compose message ********/
A 64
10936f 65 if (empty($COMPOSE['param']['message-id'])) {
0f16a0 66     $COMPOSE['param']['message-id'] = $RCMAIL->gen_message_id();
10936f 67 }
AM 68 $message_id = $COMPOSE['param']['message-id'];
4e17e6 69
5bc8cb 70 // set default charset
27be4e 71 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $OUTPUT->get_charset();
c03095 72
e4acbb 73 $EMAIL_FORMAT_ERROR = NULL;
0f16a0 74 $RECIPIENT_COUNT    = 0;
e4acbb 75
0f16a0 76 $mailto  = rcmail_email_input_format(rcube_utils::get_input_value('_to', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
AM 77 $mailcc  = rcmail_email_input_format(rcube_utils::get_input_value('_cc', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
6b2b2e 78 $mailbcc = rcmail_email_input_format(rcube_utils::get_input_value('_bcc', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
4e17e6 79
db2c1a 80 if ($EMAIL_FORMAT_ERROR && !$savedraft) {
0f16a0 81     $OUTPUT->show_message('emailformaterror', 'error', array('email' => $EMAIL_FORMAT_ERROR));
AM 82     $OUTPUT->send('iframe');
e4acbb 83 }
A 84
e8f8fe 85 if (empty($mailto) && !empty($mailcc)) {
0f16a0 86     $mailto = $mailcc;
AM 87     $mailcc = null;
e8f8fe 88 }
0f16a0 89 else if (empty($mailto)) {
AM 90     $mailto = 'undisclosed-recipients:;';
91 }
e8f8fe 92
d2b884 93 // Get sender name and address...
6b2b2e 94 $from = rcube_utils::get_input_value('_from', rcube_utils::INPUT_POST, true, $message_charset);
d2b884 95 // ... from identity...
A 96 if (is_numeric($from)) {
0f16a0 97     if (is_array($identity_arr = rcmail_get_identity($from))) {
AM 98         if ($identity_arr['mailto'])
99             $from = $identity_arr['mailto'];
100         if ($identity_arr['string'])
101             $from_string = $identity_arr['string'];
102     }
103     else {
104         $from = null;
105     }
d2b884 106 }
A 107 // ... if there is no identity record, this might be a custom from
108 else if ($from_string = rcmail_email_input_format($from)) {
0f16a0 109     if (preg_match('/(\S+@\S+)/', $from_string, $m))
AM 110         $from = trim($m[1], '<>');
111     else
112         $from = null;
d2b884 113 }
fd51e0 114
0f16a0 115 if (!$from_string && $from) {
AM 116     $from_string = $from;
117 }
4e17e6 118
T 119 // compose headers array
2471d3 120 $headers = array();
A 121
122 // if configured, the Received headers goes to top, for good measure
0f16a0 123 if ($RCMAIL->config->get('http_received_header')) {
AM 124     $nldlm   = "\r\n\t";
125     $encrypt = $RCMAIL->config->get('http_received_header_encrypt');
a520f3 126
0f16a0 127     // FROM/VIA
AM 128     $http_header = 'from ';
129
130     if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
131         $hosts    = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'], 2);
132         $hostname = gethostbyaddr($hosts[0]);
133
134         if ($encrypt) {
135             $http_header .= rcmail_encrypt_header($hostname);
136             if ($host != $hostname)
137                 $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
138         }
139         else {
140             $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
141             if ($host != $hostname)
142                 $http_header .= ' (['. $host .'])';
143         }
144         $http_header .= $nldlm . ' via ';
ddc891 145     }
A 146
0f16a0 147     $host = $_SERVER['REMOTE_ADDR'];
AM 148     $hostname = gethostbyaddr($host);
149
150     if ($encrypt) {
151         $http_header .= rcmail_encrypt_header($hostname);
152         if ($host != $hostname)
153             $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
154     }
155     else {
156         $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
157         if ($host != $hostname)
158             $http_header .= ' (['. $host .'])';
159     }
160
161     // BY
162     $http_header .= $nldlm . 'by ' . $_SERVER['HTTP_HOST'];
163
164     // WITH
165     $http_header .= $nldlm . 'with HTTP (' . $_SERVER['SERVER_PROTOCOL'] .
166       ' '.$_SERVER['REQUEST_METHOD'] . '); ' . date('r');
167     $http_header = wordwrap($http_header, 69, $nldlm);
168
169     $headers['Received'] = $http_header;
2471d3 170 }
A 171
6b2b2e 172 $headers['Date'] = $RCMAIL->user_date();
AM 173 $headers['From'] = rcube_charset::convert($from_string, RCUBE_CHARSET, $message_charset);
2471d3 174 $headers['To'] = $mailto;
4e17e6 175
T 176 // additional recipients
14f87f 177 if (!empty($mailcc)) {
0f16a0 178     $headers['Cc'] = $mailcc;
14f87f 179 }
A 180 if (!empty($mailbcc)) {
0f16a0 181     $headers['Bcc'] = $mailbcc;
14f87f 182 }
751b22 183
A 184 if (($max_recipients = (int) $RCMAIL->config->get('max_recipients')) > 0) {
0f16a0 185     if ($RECIPIENT_COUNT > $max_recipients) {
AM 186         $OUTPUT->show_message('toomanyrecipients', 'error', array('max' => $max_recipients));
187         $OUTPUT->send('iframe');
188     }
751b22 189 }
4e17e6 190
T 191 // add subject
6b2b2e 192 $headers['Subject'] = trim(rcube_utils::get_input_value('_subject', rcube_utils::INPUT_POST, TRUE, $message_charset));
4e17e6 193
14f87f 194 if (!empty($identity_arr['organization'])) {
0f16a0 195     $headers['Organization'] = $identity_arr['organization'];
3ee5a7 196 }
0f16a0 197 if ($hdr = rcube_utils::get_input_value('_replyto', rcube_utils::INPUT_POST, TRUE, $message_charset)) {
AM 198     $headers['Reply-To'] = rcmail_email_input_format($hdr);
14f87f 199 }
A 200 if (!empty($headers['Reply-To'])) {
0f16a0 201     $headers['Mail-Reply-To'] = $headers['Reply-To'];
14f87f 202 }
0f16a0 203 if ($hdr = rcube_utils::get_input_value('_followupto', rcube_utils::INPUT_POST, TRUE, $message_charset)) {
847e75 204     $headers['Mail-Followup-To'] = rcmail_email_input_format($hdr);
14f87f 205 }
e99991 206
bbc856 207 // remember reply/forward UIDs in special headers
72ff6a 208 if (!empty($COMPOSE['reply_uid']) && $savedraft) {
0f16a0 209     $headers['X-Draft-Info'] = array('type' => 'reply', 'uid' => $COMPOSE['reply_uid']);
14f87f 210 }
72ff6a 211 else if (!empty($COMPOSE['forward_uid']) && $savedraft) {
e089c5 212     $headers['X-Draft-Info'] = array('type' => 'forward', 'uid' => rcube_imap_generic::compressMessageSet($COMPOSE['forward_uid']));
14f87f 213 }
bbc856 214
eafd5b 215 if (!empty($COMPOSE['reply_msgid'])) {
0f16a0 216     $headers['In-Reply-To'] = $COMPOSE['reply_msgid'];
eafd5b 217 }
72ff6a 218 if (!empty($COMPOSE['references'])) {
0f16a0 219     $headers['References'] = $COMPOSE['references'];
14f87f 220 }
4e17e6 221
d2b884 222 if (!empty($_POST['_priority'])) {
0f16a0 223     $priority     = intval($_POST['_priority']);
AM 224     $a_priorities = array(1 => 'highest', 2 => 'high', 4 => 'low', 5 => 'lowest');
225
226     if ($str_priority = $a_priorities[$priority]) {
227         $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
228     }
d2b884 229 }
4e17e6 230
d2b884 231 if (!empty($_POST['_receipt'])) {
0f16a0 232     $headers['Return-Receipt-To']           = $from_string;
AM 233     $headers['Disposition-Notification-To'] = $from_string;
d2b884 234 }
4e17e6 235
T 236 // additional headers
53e79d 237 $headers['Message-ID'] = $message_id;
0f16a0 238 $headers['X-Sender']   = $from;
53e79d 239
14f87f 240 if (is_array($headers['X-Draft-Info'])) {
0f16a0 241     $headers['X-Draft-Info'] = rcmail_draftinfo_encode($headers['X-Draft-Info'] + array('folder' => $COMPOSE['mailbox']));
14f87f 242 }
0f16a0 243 if ($hdr = $RCMAIL->config->get('useragent')) {
AM 244     $headers['User-Agent'] = $hdr;
14f87f 245 }
4e17e6 246
b44b4d 247 // exec hook for header checking and manipulation
6efadf 248 // Depracated: use message_before_send hook instead
e6ce00 249 $data = $RCMAIL->plugins->exec_hook('message_outgoing_headers', array('headers' => $headers));
b44b4d 250
T 251 // sending aborted by plugin
252 if ($data['abort'] && !$savedraft) {
0f16a0 253     $OUTPUT->show_message($data['message'] ? $data['message'] : 'sendingfailed');
AM 254     $OUTPUT->send('iframe');
b44b4d 255 }
0f16a0 256 else {
AM 257     $headers = $data['headers'];
258 }
b44b4d 259
6b2b2e 260 $isHtml = (bool) rcube_utils::get_input_value('_is_html', rcube_utils::INPUT_POST);
940fc1 261
c03095 262 // fetch message body
6b2b2e 263 $message_body = rcube_utils::get_input_value('_message', rcube_utils::INPUT_POST, TRUE, $message_charset);
940fc1 264
7e263e 265 if ($isHtml) {
0f16a0 266     $bstyle = array();
f7b2bf 267
0f16a0 268     if ($font_size = $RCMAIL->config->get('default_font_size')) {
AM 269         $bstyle[] = 'font-size: ' . $font_size;
270     }
271     if ($font_family = $RCMAIL->config->get('default_font')) {
272         $bstyle[] = 'font-family: ' . rcmail::font_defs($font_family);
273     }
7e263e 274
0f16a0 275     // append doctype and html/body wrappers
AM 276     $message_body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">'
277         . "\r\n<html><body" . (!empty($bstyle) ? " style='" . implode($bstyle, '; ') . "'" : '') . ">\r\n"
278         . $message_body;
7e263e 279 }
A 280
65605c 281 if (!$savedraft) {
0f16a0 282     if ($isHtml) {
AM 283         // remove signature's div ID
284         $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
4e17e6 285
0f16a0 286         // add inline css for blockquotes
AM 287         $bstyle       = 'padding-left:5px; border-left:#1010ff 2px solid; margin-left:5px';
288         $message_body = preg_replace('/<blockquote>/',
289             '<blockquote type="cite" style="'.$bstyle.'">', $message_body);
1d5779 290     }
A 291
0f16a0 292     // Check spelling before send
AM 293     if ($RCMAIL->config->get('spellcheck_before_send') && $RCMAIL->config->get('enable_spellcheck')
294         && empty($COMPOSE['spell_checked']) && !empty($message_body)
295     ) {
296         $message_body = str_replace("\r\n", "\n", $message_body);
297         $spellchecker = new rcube_spellchecker(rcube_utils::get_input_value('_lang', rcube_utils::INPUT_GPC));
298         $spell_result = $spellchecker->check($message_body, $isHtml);
299
300         $COMPOSE['spell_checked'] = true;
301
302         if (!$spell_result) {
303             $result = $isHtml ? $spellchecker->get_words() : $spellchecker->get_xml();
304
305             $OUTPUT->show_message('mispellingsfound', 'error');
306             $OUTPUT->command('spellcheck_resume', $isHtml, $result);
307             $OUTPUT->send('iframe');
308         }
309     }
310
311     // generic footer for all messages
312     if ($footer = rcmail_generic_message_footer($isHtml)) {
313         $footer = rcube_charset::convert($footer, RCUBE_CHARSET, $message_charset);
314         $message_body .= "\r\n" . $footer;
315     }
7e263e 316 }
A 317
318 if ($isHtml) {
0f16a0 319     $message_body .= "\r\n</body></html>\r\n";
65605c 320 }
a0109c 321
b169de 322 // sort attachments to make sure the order is the same as in the UI (#1488423)
0f16a0 323 if ($files = rcube_utils::get_input_value('_attachments', rcube_utils::INPUT_POST)) {
AM 324     $files = explode(',', $files);
325     $files = array_flip($files);
326     foreach ($files as $idx => $val) {
327         $files[$idx] = $COMPOSE['attachments'][$idx];
328         unset($COMPOSE['attachments'][$idx]);
329     }
b169de 330
0f16a0 331     $COMPOSE['attachments'] = array_merge(array_filter($files), $COMPOSE['attachments']);
b169de 332 }
AM 333
b62049 334 // set line length for body wrapping
c769c6 335 $LINE_LENGTH = $RCMAIL->config->get('line_length', 72);
b62049 336
91790e 337 // Since we can handle big messages with disk usage, we need more time to work
A 338 @set_time_limit(0);
339
340 // create PEAR::Mail_mime instance
ac8edb 341 $MAIL_MIME = new Mail_mime("\r\n");
91790e 342
A 343 // Check if we have enough memory to handle the message in it
344 // It's faster than using files, so we'll do this if we only can
0f16a0 345 if (is_array($COMPOSE['attachments']) && $RCMAIL->config->get('smtp_server')
AM 346   && ($mem_limit = parse_bytes(ini_get('memory_limit')))
347 ) {
348     $memory = 0;
349     foreach ($COMPOSE['attachments'] as $id => $attachment) {
350         $memory += $attachment['size'];
351     }
91790e 352
0f16a0 353     // Yeah, Net_SMTP needs up to 12x more memory, 1.33 is for base64
AM 354     if (!rcube_utils::mem_check($memory * 1.33 * 12)) {
355         $MAIL_MIME->setParam('delay_file_io', true);
356     }
91790e 357 }
a0109c 358
S 359 // For HTML-formatted messages, construct the MIME message with both
360 // the HTML part and the plain-text part
cc97ea 361 if ($isHtml) {
0f16a0 362     $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
AM 363         array('body' => $message_body, 'type' => 'html', 'message' => $MAIL_MIME));
ac8edb 364
0f16a0 365     $MAIL_MIME->setHTMLBody($plugin['body']);
a0109c 366
0f16a0 367     // replace emoticons
AM 368     $plugin['body'] = $RCMAIL->replace_emoticons($plugin['body']);
747289 369
0f16a0 370     // add a plain text version of the e-mail as an alternative part.
AM 371     $h2t = new rcube_html2text($plugin['body'], false, true, 0, $message_charset);
372     $plainTextPart = rcube_mime::wordwrap($h2t->get_text(), $LINE_LENGTH, "\r\n", false, $message_charset);
373     $plainTextPart = wordwrap($plainTextPart, 998, "\r\n", true);
21d463 374
0f16a0 375     // make sure all line endings are CRLF (#1486712)
AM 376     $plainTextPart = preg_replace('/\r?\n/', "\r\n", $plainTextPart);
ac8edb 377
0f16a0 378     $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
AM 379         array('body' => $plainTextPart, 'type' => 'alternative', 'message' => $MAIL_MIME));
ac8edb 380
0f16a0 381     $MAIL_MIME->setTXTBody($plugin['body']);
a0109c 382
0f16a0 383     // look for "emoticon" images from TinyMCE and change their src paths to
AM 384     // be file paths on the server instead of URL paths.
385     rcmail_fix_emoticon_paths($MAIL_MIME);
9287ed 386
0f16a0 387     // Extract image Data URIs into message attachments (#1488502)
AM 388     rcmail_extract_inline_images($MAIL_MIME, $from);
cc97ea 389 }
6b6f2e 390 else {
0f16a0 391     $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
AM 392         array('body' => $message_body, 'type' => 'plain', 'message' => $MAIL_MIME));
5852c1 393
0f16a0 394     $message_body = $plugin['body'];
5852c1 395
0f16a0 396     // compose format=flowed content if enabled
AM 397     if ($flowed = ($savedraft || $RCMAIL->config->get('send_format_flowed', true)))
398         $message_body = rcube_mime::format_flowed($message_body, min($LINE_LENGTH+2, 79), $message_charset);
399     else
400         $message_body = rcube_mime::wordwrap($message_body, $LINE_LENGTH, "\r\n", false, $message_charset);
5852c1 401
0f16a0 402     $message_body = wordwrap($message_body, 998, "\r\n", true);
ac8edb 403
0f16a0 404     $MAIL_MIME->setTXTBody($message_body, false, true);
cc97ea 405 }
4e17e6 406
T 407 // add stored attachments, if any
e28b12 408 if (is_array($COMPOSE['attachments'])) {
0f16a0 409     foreach ($COMPOSE['attachments'] as $id => $attachment) {
AM 410         // This hook retrieves the attachment contents from the file storage backend
411         $attachment = $RCMAIL->plugins->exec_hook('attachment_get', $attachment);
cc97ea 412
0f16a0 413         if ($isHtml) {
AM 414             $dispurl      = '/\ssrc\s*=\s*[\'"]*\S+display-attachment\S+file=rcmfile'
415                 . preg_quote($attachment['id']) . '[\s\'"]*/';
416             $message_body = $MAIL_MIME->getHTMLBody();
417             $is_inline    = preg_match($dispurl, $message_body);
418         }
419         else {
420             $is_inline = false;
421         }
422
423         // inline image
424         if ($is_inline) {
425             // Mail_Mime does not support many inline attachments with the same name (#1489406)
426             // we'll generate cid: urls here to workaround this
427             $cid = preg_replace('/[^0-9a-zA-Z]/', '', uniqid(time(), true));
428             if (preg_match('#(@[0-9a-zA-Z\-\.]+)#', $from, $matches)) {
429                 $cid .= $matches[1];
430             }
431             else {
432                 $cid .= '@localhost';
433             }
434
435             $message_body = preg_replace($dispurl, ' src="cid:' . $cid . '" ', $message_body);
436
437             $MAIL_MIME->setHTMLBody($message_body);
438
439             if ($attachment['data'])
440                 $MAIL_MIME->addHTMLImage($attachment['data'], $attachment['mimetype'], $attachment['name'], false, $cid);
441             else
442                 $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name'], true, $cid);
443         }
444         else {
445             $ctype   = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
446             $file    = $attachment['data'] ? $attachment['data'] : $attachment['path'];
447             $folding = (int) $RCMAIL->config->get('mime_param_folding');
448
449             $MAIL_MIME->addAttachment($file,
450                 $ctype,
451                 $attachment['name'],
452                 $attachment['data'] ? false : true,
453                 $ctype == 'message/rfc822' ? '8bit' : 'base64',
454                 'attachment',
455                 '', '', '',
456                 $folding ? 'quoted-printable' : NULL,
457                 $folding == 2 ? 'quoted-printable' : NULL,
458                 '', RCUBE_CHARSET
459             );
460         }
e28b12 461     }
cc97ea 462 }
4e17e6 463
3d0ec7 464 // choose transfer encoding for plain/text body
ac3cdd 465 if (preg_match('/[^\x00-\x7F]/', $MAIL_MIME->getTXTBody())) {
0f16a0 466     $text_charset      = $message_charset;
AM 467     $transfer_encoding = $RCMAIL->config->get('force_7bit') ? 'quoted-printable' : '8bit';
ac3cdd 468 }
AM 469 else {
8d4b48 470     $text_charset      = 'US-ASCII';
0f16a0 471     $transfer_encoding = '7bit';
ac3cdd 472 }
AM 473
474 if ($flowed) {
0f16a0 475     $text_charset .= ";\r\n format=flowed";
ac3cdd 476 }
3d0ec7 477
a95e0e 478 // encoding settings for mail composing
91790e 479 $MAIL_MIME->setParam('text_encoding', $transfer_encoding);
A 480 $MAIL_MIME->setParam('html_encoding', 'quoted-printable');
481 $MAIL_MIME->setParam('head_encoding', 'quoted-printable');
482 $MAIL_MIME->setParam('head_charset', $message_charset);
483 $MAIL_MIME->setParam('html_charset', $message_charset);
ac3cdd 484 $MAIL_MIME->setParam('text_charset', $text_charset);
cc97ea 485
5a6ad2 486 // encoding subject header with mb_encode provides better results with asian characters
d2b884 487 if (function_exists('mb_encode_mimeheader')) {
0f16a0 488     mb_internal_encoding($message_charset);
AM 489     $headers['Subject'] = mb_encode_mimeheader($headers['Subject'],
490         $message_charset, 'Q', "\r\n", 8);
491     mb_internal_encoding(RCUBE_CHARSET);
b517af 492 }
4e17e6 493
fba1f5 494 // pass headers to message object
T 495 $MAIL_MIME->headers($headers);
4e17e6 496
d2b884 497 // Begin SMTP Delivery Block
0f16a0 498 if (!$savedraft) {
AM 499     // check 'From' address (identity may be incomplete)
500     if (empty($from)) {
501         $OUTPUT->show_message('nofromaddress', 'error');
502         $OUTPUT->send('iframe');
e04e31 503     }
91790e 504
0f16a0 505     // Handle Delivery Status Notification request
AM 506     if (!empty($_POST['_dsn'])) {
507         $smtp_opts['dsn'] = true;
508     }
acb08f 509
0f16a0 510     $sent = $RCMAIL->deliver_message($MAIL_MIME, $from, $mailto,
AM 511         $smtp_error, $mailbody_file, $smtp_opts);
765fde 512
0f16a0 513     // return to compose page if sending failed
AM 514     if (!$sent) {
515         // remove temp file
516         if ($mailbody_file) {
517             unlink($mailbody_file);
518         }
c03095 519
0f16a0 520         if ($smtp_error)
AM 521             $OUTPUT->show_message($smtp_error['label'], 'error', $smtp_error['vars']); 
522         else
523             $OUTPUT->show_message('sendingfailed', 'error'); 
524         $OUTPUT->send('iframe');
525     }
41fa0b 526
0f16a0 527     // save message sent time
AM 528     if ($sendmail_delay) {
529         $RCMAIL->user->save_prefs(array('last_message_time' => time()));
530     }
531
532     // set replied/forwarded flag
533     if ($COMPOSE['reply_uid'])
534         $RCMAIL->storage->set_flag($COMPOSE['reply_uid'], 'ANSWERED', $COMPOSE['mailbox']);
535     else if ($COMPOSE['forward_uid'])
536         $RCMAIL->storage->set_flag($COMPOSE['forward_uid'], 'FORWARDED', $COMPOSE['mailbox']);
537 }
41fa0b 538
1966c5 539 // Determine which folder to save message
0f16a0 540 if ($savedraft) {
AM 541     $store_target = $drafts_mbox;
542 }
543 else if (!$RCMAIL->config->get('no_save_sent_messages')) {
ed3283 544     if (isset($_POST['_store_target'])) {
AM 545         $store_target = rcube_utils::get_input_value('_store_target', rcube_utils::INPUT_POST);
546     }
547     else {
a42890 548         $store_target = $RCMAIL->config->get('sent_mbox');
0f16a0 549     }
AM 550 }
c03095 551
56ec81 552 if ($store_target) {
0f16a0 553     // check if folder is subscribed
AM 554     if ($RCMAIL->storage->folder_exists($store_target, true)) {
555         $store_folder = true;
56ec81 556     }
0f16a0 557     // folder may be existing but not subscribed (#1485241)
AM 558     else if (!$RCMAIL->storage->folder_exists($store_target)) {
559         $store_folder = $RCMAIL->storage->create_folder($store_target, true);
560     }
561     else if ($RCMAIL->storage->subscribe($store_target)) {
562         $store_folder = true;
56ec81 563     }
91790e 564
0f16a0 565     // append message to sent box
AM 566     if ($store_folder) {
567         // message body in file
568         if ($mailbody_file || $MAIL_MIME->getParam('delay_file_io')) {
569             $headers = $MAIL_MIME->txtHeaders();
570
571             // file already created
572             if ($mailbody_file) {
573                 $msg = $mailbody_file;
574             }
575             else {
576                 $temp_dir      = $RCMAIL->config->get('temp_dir');
577                 $mailbody_file = tempnam($temp_dir, 'rcmMsg');
578
579                 if (!PEAR::isError($msg = $MAIL_MIME->saveMessageBody($mailbody_file))) {
580                     $msg = $mailbody_file;
581                 }
582             }
583         }
584         else {
585             $msg     = $MAIL_MIME->getMessage();
586             $headers = '';
587         }
588
589         if (PEAR::isError($msg)) {
590             rcube::raise_error(array('code' => 650, 'type' => 'php',
591                 'file' => __FILE__, 'line' => __LINE__,
592                 'message' => "Could not create message: ".$msg->getMessage()),
593                 true, false);
594         }
595         else {
596             $saved = $RCMAIL->storage->save_message($store_target, $msg, $headers,
597                 $mailbody_file ? true : false, array('SEEN'));
598         }
599
600         if ($mailbody_file) {
601             unlink($mailbody_file);
602             $mailbody_file = null;
603         }
56ec81 604     }
91790e 605
0f16a0 606     // raise error if saving failed
AM 607     if (!$saved) {
608         rcube::raise_error(array('code' => 800, 'type' => 'imap',
609             'file' => __FILE__, 'line' => __LINE__,
610             'message' => "Could not save message in $store_target"), true, false);
611
612         if ($savedraft) {
613             $OUTPUT->show_message('errorsaving', 'error');
614             // start the auto-save timer again
615             $OUTPUT->command('auto_save_start');
616             $OUTPUT->send('iframe');
617         }
56ec81 618     }
A 619 }
91790e 620 // remove temp file
A 621 else if ($mailbody_file) {
0f16a0 622     unlink($mailbody_file);
56ec81 623 }
91790e 624
c5157f 625 // delete previous saved draft
AM 626 $old_id = rcube_utils::get_input_value('_draft_saveid', rcube_utils::INPUT_POST);
627 if ($old_id && ($sent || $saved)) {
628     $deleted = $RCMAIL->storage->delete_message($old_id, $drafts_mbox);
629
630     // raise error if deletion of old draft failed
631     if (!$deleted) {
632         rcube::raise_error(array('code' => 800, 'type' => 'imap',
633             'file' => __FILE__, 'line' => __LINE__,
634             'message' => "Could not delete message from $drafts_mbox"), true, false);
635     }
636 }
4e17e6 637
56ec81 638 if ($savedraft) {
0f16a0 639     // remember new draft-uid ($saved could be an UID or true/false here)
AM 640     if ($saved && is_bool($saved)) {
641         $index = $RCMAIL->storage->search_once($drafts_mbox, 'HEADER Message-ID ' . $message_id);
642         $saved = @max($index->get());
643     }
c719f3 644
0f16a0 645     if ($saved) {
AM 646         $plugin = $RCMAIL->plugins->exec_hook('message_draftsaved',
647             array('msgid' => $message_id, 'uid' => $saved, 'folder' => $store_target));
f0f98f 648
0f16a0 649         // display success
AM 650         $OUTPUT->show_message($plugin['message'] ? $plugin['message'] : 'messagesaved', 'confirmation');
10936f 651
0f16a0 652         // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
AM 653         $COMPOSE['param']['draft_uid'] = $plugin['uid'];
654         $OUTPUT->command('set_draft_id', $plugin['uid']);
655         $OUTPUT->command('compose_field_hash', true);
656     }
41fa0b 657
0f16a0 658     // start the auto-save timer again
AM 659     $OUTPUT->command('auto_save_start');
56ec81 660 }
A 661 else {
0f16a0 662     $folders = array();
66a549 663
0f16a0 664     if ($COMPOSE['mode'] == 'reply' || $COMPOSE['mode'] == 'forward') {
AM 665         $folders[] = $COMPOSE['mailbox'];
666     }
66a549 667
0f16a0 668     rcmail_compose_cleanup($COMPOSE_ID);
AM 669     $OUTPUT->command('remove_compose_data', $COMPOSE_ID);
9a5762 670
0f16a0 671     if ($store_folder && !$saved) {
AM 672         $OUTPUT->command('sent_successfully', 'error', $RCMAIL->gettext('errorsavingsent'), $folders);
673     }
674     else if ($store_folder) {
675         $folders[] = $store_target;
66a549 676     }
AM 677
6b2b2e 678     $OUTPUT->command('sent_successfully', 'confirmation', $RCMAIL->gettext('messagesent'), $folders);
56ec81 679 }
66a549 680
AM 681 $OUTPUT->send('iframe');
f5d2ee 682
AM 683
684 /****** message sending functions ********/
685
686 // encrypt parts of the header
687 function rcmail_encrypt_header($what)
688 {
689     global $RCMAIL;
690
691     if (!$RCMAIL->config->get('http_received_header_encrypt')) {
692         return $what;
693     }
694
695     return $RCMAIL->encrypt($what);
696 }
697
698 // get identity record
699 function rcmail_get_identity($id)
700 {
701     global $RCMAIL, $message_charset;
702
703     if ($sql_arr = $RCMAIL->user->get_identity($id)) {
704         $out = $sql_arr;
705
706         if ($message_charset != RCUBE_CHARSET) {
707             foreach ($out as $k => $v) {
708                 $out[$k] = rcube_charset::convert($v, RCUBE_CHARSET, $message_charset);
709             }
710         }
711
712         $out['mailto'] = $sql_arr['email'];
713         $out['string'] = format_email_recipient($sql_arr['email'], $sql_arr['name']);
714
715         return $out;
716     }
717
718     return false;
719 }
720
721 /**
722  * go from this:
723  * <img src="http[s]://.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
724  *
725  * to this:
726  *
727  * <img src="/path/on/server/.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
728  */
729 function rcmail_fix_emoticon_paths($mime_message)
730 {
731     global $RCMAIL;
732
733     $body = $mime_message->getHTMLBody();
734
735     // remove any null-byte characters before parsing
736     $body = preg_replace('/\x00/', '', $body);
737
738     $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
739     $offset = 0;
740
741     // keep track of added images, so they're only added once
742     $included_images = array();
743
744     if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
745         foreach ($matches[1] as $m) {
746             // find emoticon image tags
747             if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
748                 $image_name = $imatches[1];
749
750                 // sanitize image name so resulting attachment doesn't leave images dir
751                 $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
752                 $img_file   = INSTALL_PATH . '/' . $searchstr . $image_name;
753
754                 if (! in_array($image_name, $included_images)) {
755                     // add the image to the MIME message
756                     if (!$mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name)) {
757                         $RCMAIL->output->show_message("emoticonerror", 'error');
758                     }
759
760                     array_push($included_images, $image_name);
761                 }
762
763                 $body    = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
764                 $offset += strlen($img_file) - strlen($m[0]);
765             }
766         }
767     }
768
769     $mime_message->setHTMLBody($body);
770 }
771
772 /**
773  * Extract image attachments from HTML content (data URIs)
774  */
775 function rcmail_extract_inline_images($mime_message, $from)
776 {
777     $body   = $mime_message->getHTMLBody();
778     $offset = 0;
779     $list   = array();
14bd92 780     $domain = 'localhost';
AM 781     $regexp = '#img[^>]+src=[\'"](data:([^;]*);base64,([a-z0-9+/=\r\n]+))([\'"])#i';
f5d2ee 782
AM 783     if (preg_match_all($regexp, $body, $matches, PREG_OFFSET_CAPTURE)) {
14bd92 784         // get domain for the Content-ID, must be the same as in Mail_Mime::get()
AM 785         if (preg_match('#@([0-9a-zA-Z\-\.]+)#', $from, $m)) {
786             $domain = $m[1];
787         }
788
f5d2ee 789         foreach ($matches[1] as $idx => $m) {
AM 790             $data = preg_replace('/\r\n/', '', $matches[3][$idx][0]);
791             $data = base64_decode($data);
792
793             if (empty($data)) {
794                 continue;
795             }
796
797             $hash      = md5($data) . '@' . $domain;
798             $mime_type = $matches[2][$idx][0];
799             $name      = $list[$hash];
800
14bd92 801             if (empty($mime_type)) {
AM 802                 $mime_type = rcube_mime::image_content_type($data);
803             }
804
f5d2ee 805             // add the image to the MIME message
AM 806             if (!$name) {
807                 $ext         = preg_replace('#^[^/]+/#', '', $mime_type);
808                 $name        = substr($hash, 0, 8) . '.' . $ext;
809                 $list[$hash] = $name;
810
811                 $mime_message->addHTMLImage($data, $mime_type, $name, false, $hash);
812             }
813
814             $body = substr_replace($body, $name, $m[1] + $offset, strlen($m[0]));
815             $offset += strlen($name) - strlen($m[0]);
816         }
817     }
818
819     $mime_message->setHTMLBody($body);
820 }
821
822 /**
823  * Parse and cleanup email address input (and count addresses)
824  *
825  * @param string  Address input
826  * @param boolean Do count recipients (saved in global $RECIPIENT_COUNT)
827  * @param boolean Validate addresses (errors saved in global $EMAIL_FORMAT_ERROR)
828  * @return string Canonical recipients string separated by comma
829  */
830 function rcmail_email_input_format($mailto, $count=false, $check=true)
831 {
832     global $RCMAIL, $EMAIL_FORMAT_ERROR, $RECIPIENT_COUNT;
833
834     // simplified email regexp, supporting quoted local part
835     $email_regexp = '(\S+|("[^"]+"))@\S+';
836
837     $delim   = trim($RCMAIL->config->get('recipients_separator', ','));
838     $regexp  = array("/[,;$delim]\s*[\r\n]+/", '/[\r\n]+/', "/[,;$delim]\s*\$/m", '/;/', '/(\S{1})(<'.$email_regexp.'>)/U');
839     $replace = array($delim.' ', ', ', '', $delim, '\\1 \\2');
840
841     // replace new lines and strip ending ', ', make address input more valid
842     $mailto = trim(preg_replace($regexp, $replace, $mailto));
843     $items  = rcube_utils::explode_quoted_string($delim, $mailto);
844     $result = array();
845
846     foreach ($items as $item) {
847         $item = trim($item);
848         // address in brackets without name (do nothing)
849         if (preg_match('/^<'.$email_regexp.'>$/', $item)) {
850             $item     = rcube_utils::idn_to_ascii(trim($item, '<>'));
851             $result[] = $item;
852         }
853         // address without brackets and without name (add brackets)
854         else if (preg_match('/^'.$email_regexp.'$/', $item)) {
855             $item     = rcube_utils::idn_to_ascii($item);
856             $result[] = $item;
857         }
858         // address with name (handle name)
859         else if (preg_match('/<*'.$email_regexp.'>*$/', $item, $matches)) {
860             $address = $matches[0];
861             $name    = trim(str_replace($address, '', $item));
862             if ($name[0] == '"' && $name[count($name)-1] == '"') {
863                 $name = substr($name, 1, -1);
864             }
865             $name     = stripcslashes($name);
866             $address  = rcube_utils::idn_to_ascii(trim($address, '<>'));
867             $result[] = format_email_recipient($address, $name);
868             $item     = $address;
869         }
870         else if (trim($item)) {
871             continue;
872         }
873
874         // check address format
875         $item = trim($item, '<>');
876         if ($item && $check && !rcube_utils::check_email($item)) {
877             $EMAIL_FORMAT_ERROR = $item;
878             return;
879         }
880     }
881
882     if ($count) {
883         $RECIPIENT_COUNT += count($result);
884     }
885
886     return implode(', ', $result);
887 }
888
889
890 function rcmail_generic_message_footer($isHtml)
891 {
892     global $RCMAIL;
893
894     if ($isHtml && ($file = $RCMAIL->config->get('generic_message_footer_html'))) {
895         $html_footer = true;
896     }
897     else {
898         $file = $RCMAIL->config->get('generic_message_footer');
899         $html_footer = false;
900     }
901
902     if ($file && realpath($file)) {
903         // sanity check
904         if (!preg_match('/\.(php|ini|conf)$/', $file) && strpos($file, '/etc/') === false) {
905             $footer = file_get_contents($file);
906             if ($isHtml && !$html_footer) {
907                 $footer = '<pre>' . $footer . '</pre>';
908             }
909             return $footer;
910         }
911     }
912
913     return false;
914 }