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