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