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