thomascube
2007-03-21 ab6f8077e9b719db230798e658ba37f1f386b26b
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/sendmail.inc                                       |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2005, RoundCube Dev. - Switzerland                      |
30233b 9  | Licensed under the GNU GPL                                            |
4e17e6 10  |                                                                       |
T 11  | PURPOSE:                                                              |
12  |   Compose a new mail message with all headers and attachments         |
13  |   and send it using IlohaMail's SMTP methods or with PHP mail()       |
14  |                                                                       |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18
19  $Id$
20
21 */
22
23
968bdc 24 //require_once('lib/smtp.inc');
T 25 require_once('include/rcube_smtp.inc');
a0109c 26 require_once('lib/html2text.inc');
ab6f80 27 require_once('lib/rc_mail_mime.inc');
4e17e6 28
T 29
30 if (!isset($_SESSION['compose']['id']))
31   {
10a699 32   rcmail_overwrite_action('list');
4e17e6 33   return;
T 34   }
35
36
37 /****** message sending functions ********/
38
39
40 function rcmail_get_identity($id)
41   {
13c1af 42   global $DB, $CHARSET, $OUTPUT;
4e17e6 43   
T 44   // get identity record
d7cb77 45   $sql_result = $DB->query("SELECT *, email AS mailto
S 46                             FROM ".get_table_name('identities')."
47                             WHERE  identity_id=?
48                             AND    user_id=?
1cded8 49                             AND    del<>1",
d7cb77 50                             $id,$_SESSION['user_id']);
4e17e6 51                                    
T 52   if ($DB->num_rows($sql_result))
53     {
54     $sql_arr = $DB->fetch_assoc($sql_result);
55     $out = $sql_arr;
abb32e 56     $name = strpos($sql_arr['name'], ",") ? '"'.$sql_arr['name'].'"' : $sql_arr['name'];
13c1af 57     $out['string'] = sprintf('%s <%s>',
abb32e 58                              rcube_charset_convert($name, $CHARSET, $OUTPUT->get_charset()),
13c1af 59                              $sql_arr['mailto']);
4e17e6 60     return $out;
T 61     }
62
63   return FALSE;  
64   }
65
a0109c 66 /**
S 67  * go from this:
68  * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
69  *
70  * to this:
71  *
72  * <IMG src="cid:smiley-cool.gif"/>
73  * ...
74  * ------part...
75  * Content-Type: image/gif
76  * Content-Transfer-Encoding: base64
77  * Content-ID: <smiley-cool.gif>
78  */
79 function rcmail_attach_emoticons(&$mime_message)
80 {
81   global $CONFIG, $INSTALL_PATH;
82
83   $htmlContents = $mime_message->getHtmlBody();
84
85   // remove any null-byte characters before parsing
86   $body = preg_replace('/\x00/', '', $htmlContents);
87   
88   $last_img_pos = 0;
89
90   $searchstr = 'program/js/tiny_mce/plugins/emotions/images/';
91
ed6592 92   // keep track of added images, so they're only added once
S 93   $included_images = array();
94
a0109c 95   // find emoticon image tags
S 96   while ($pos = strpos($body, $searchstr, $last_img_pos))
97     {
98     $pos2 = strpos($body, '"', $pos);
99     $body_pre = substr($body, 0, $pos);
ed6592 100     $image_name = substr($body,
S 101                          $pos + strlen($searchstr),
102                          $pos2 - ($pos + strlen($searchstr)));
ee883a 103     // sanitize image name so resulting attachment doesn't leave images dir
T 104     $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i','',$image_name);
a0109c 105
4e6eb1 106     $body_post = substr($body, $pos2);
S 107
ed6592 108     if (! in_array($image_name, $included_images))
a0109c 109       {
ed6592 110       // add the image to the MIME message
S 111       $img_file = $INSTALL_PATH . '/' . $searchstr . $image_name;
112       if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, '_' . $image_name))
113         {
114         show_message("emoticonerror", 'error');
115         }
116       array_push($included_images, $image_name);
117       }
a0109c 118
4e6eb1 119     $body = $body_pre . 'cid:_' . $image_name . $body_post;
S 120
a0109c 121     $last_img_pos = $pos2;
S 122     }
123    
124   $mime_message->setHTMLBody($body);
125 }
41fa0b 126
b068a0 127 if (strlen($_POST['_draft_saveid']) > 3)
T 128   $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
129
8cb245 130 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), rcmail_mail_domain($_SESSION['imap_host']));
b068a0 131 $savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
41fa0b 132
T 133 // remove all scripts and act as called in frame
134 $OUTPUT->reset();
135 $_framed = TRUE;
136
b068a0 137
4e17e6 138 /****** check submission and compose message ********/
10a699 139
T 140
141 if (empty($_POST['_to']) && empty($_POST['_subject']) && $_POST['_message'])
142   {
143   show_message("sendingfailed", 'error'); 
41fa0b 144   //rcmail_overwrite_action('compose');
T 145   rcube_iframe_response();
10a699 146   return;
T 147   }
4e17e6 148
T 149
5bc8cb 150 // set default charset
13c1af 151 $input_charset = $OUTPUT->get_charset();
c03095 152 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
T 153
5a6ad2 154 $mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/');
T 155 $mailto_replace = array(', ', ', ', '', ',');
4e17e6 156
abb32e 157 // replace new lines and strip ending ', '
ea7c46 158 $mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
4e17e6 159
T 160 // decode address strings
161 $to_address_arr = $IMAP->decode_address_list($mailto);
b068a0 162 $identity_arr = rcmail_get_identity(get_input_value('_from', RCUBE_INPUT_POST));
4e17e6 163
T 164 $from = $identity_arr['mailto'];
165 $first_to = is_array($to_address_arr[0]) ? $to_address_arr[0]['mailto'] : $mailto;
166
b068a0 167 if (empty($identity_arr['string']))
T 168   $identity_arr['string'] = $from;
4e17e6 169
T 170 // compose headers array
421f5e 171 $headers = array('Date' => date('D, j M Y H:i:s O'),
b517af 172                  'From' => rcube_charset_convert($identity_arr['string'], $CHARSET, $message_charset),
5a6ad2 173                  'To'   => $mailto);
4e17e6 174
T 175 // additional recipients
ea7c46 176 if (!empty($_POST['_cc']))
T 177   $headers['Cc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
4e17e6 178
ea7c46 179 if (!empty($_POST['_bcc']))
T 180   $headers['Bcc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
4e17e6 181   
ea7c46 182 if (!empty($identity_arr['bcc']))
4e17e6 183   $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
T 184
185 // add subject
ea7c46 186 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
4e17e6 187
ea7c46 188 if (!empty($identity_arr['organization']))
4e17e6 189   $headers['Organization'] = $identity_arr['organization'];
T 190
ea7c46 191 if (!empty($identity_arr['reply-to']))
4e17e6 192   $headers['Reply-To'] = $identity_arr['reply-to'];
T 193
f88d41 194 if (!empty($_SESSION['compose']['reply_msgid']))
4e17e6 195   $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
T 196
f88d41 197 if (!empty($_SESSION['compose']['references']))
T 198   $headers['References'] = $_SESSION['compose']['references'];
4e17e6 199
ea7c46 200 if (!empty($_POST['_priority']))
4e17e6 201   {
T 202   $priority = (int)$_POST['_priority'];
3287e8 203   $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
4e17e6 204   if ($str_priority = $a_priorities[$priority])
T 205     $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
206   }
207
620439 208 if (!empty($_POST['_receipt']))
T 209   {
210   $headers['Return-Receipt-To'] = $identity_arr['string'];
211   $headers['Disposition-Notification-To'] = $identity_arr['string'];
212   }
4e17e6 213
T 214 // additional headers
215 $headers['Message-ID'] = $message_id;
216 $headers['X-Sender'] = $from;
217
ea7c46 218 if (!empty($CONFIG['useragent']))
4e17e6 219   $headers['User-Agent'] = $CONFIG['useragent'];
T 220
c03095 221 // fetch message body
ea7c46 222 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
4e17e6 223
4b0f65 224 // append generic footer to all messages
T 225 if (!empty($CONFIG['generic_message_footer']))
226   {
227   $file = realpath($CONFIG['generic_message_footer']);
228   if($fp = fopen($file, 'r'))
229     {
230     $content = fread($fp, filesize($file));
231     fclose($fp);
c03095 232     $message_body .= "\r\n" . rcube_charset_convert($content, 'UTF-8', $message_charset);
4b0f65 233     }
T 234   }
235
4647e1 236 // try to autodetect operating system and use the correct line endings
4b0f65 237 // use the configured delimiter for headers
4647e1 238 if (!empty($CONFIG['mail_header_delimiter']))
T 239   $header_delm = $CONFIG['mail_header_delimiter'];
240 else if (strtolower(substr(PHP_OS, 0, 3)=='win')) 
241   $header_delm = "\r\n";
242 else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
243   $header_delm = "\r\n";
244 else    
245   $header_delm = "\n";
4b0f65 246
a0109c 247
S 248 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
249 $isHtml = ($isHtmlVal == "1");
250
ab6f80 251 // create extended PEAR::Mail_mime instance
T 252 $MAIL_MIME = new rc_mail_mime($header_delm);
a0109c 253
S 254 // For HTML-formatted messages, construct the MIME message with both
255 // the HTML part and the plain-text part
256
257 if ($isHtml)
258   {
259   $MAIL_MIME->setHTMLBody($message_body);
260
261   // add a plain text version of the e-mail as an alternative part.
262   $h2t = new html2text($message_body);
263   $plainTextPart = $h2t->get_text();
264   $MAIL_MIME->setTXTBody($plainTextPart);
265
266   // look for "emoticon" images from TinyMCE and copy into message as attachments
267   rcmail_attach_emoticons($MAIL_MIME);
268   }
269 else
270   {
271   $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
272   }
4e17e6 273
T 274
275 // add stored attachments, if any
276 if (is_array($_SESSION['compose']['attachments']))
277   foreach ($_SESSION['compose']['attachments'] as $attachment)
ab6f80 278     $MAIL_MIME->addAttachment($attachment['path'], $attachment['mimetype'], $attachment['name'], true, 'base64', 'attachment', $message_charset);
4e17e6 279
T 280 // add submitted attachments
281 if (is_array($_FILES['_attachments']['tmp_name']))
282   foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
ab6f80 283     $MAIL_MIME->addAttachment($filepath, $files['type'][$i], $files['name'][$i], true, 'base64', 'attachment', $message_charset);
4e17e6 284
1cded8 285
f88d41 286 // chose transfer encoding
T 287 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
288 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
289
a95e0e 290 // encoding settings for mail composing
f88d41 291 $message_param = array('text_encoding' => $transfer_encoding,
a95e0e 292                        'html_encoding' => 'quoted-printable',
T 293                        'head_encoding' => 'quoted-printable',
1cded8 294                        'head_charset'  => $message_charset,
T 295                        'html_charset'  => $message_charset,
296                        'text_charset'  => $message_charset);
4e17e6 297
T 298 // compose message body and get headers
b517af 299 $msg_body = $MAIL_MIME->get($message_param);
T 300 // unset to save memory.
301 unset($MAIL_MIME->_parts);
4e17e6 302
5a6ad2 303 // encoding subject header with mb_encode provides better results with asian characters
13c1af 304 if ($MBSTRING && function_exists("mb_encode_mimeheader"))
b517af 305 {
24fe97 306   mb_internal_encoding($message_charset);
5a6ad2 307   $mb_subject = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
24fe97 308   mb_internal_encoding($CHARSET);
b517af 309 }
4e17e6 310
1966c5 311 // Begin SMTP Delivery Block 
S 312 if (!$savedraft) {
4e17e6 313
1966c5 314   // send thru SMTP server using custom SMTP library
S 315   if ($CONFIG['smtp_server'])
316     {
317     // generate list of recipients
318     $a_recipients = array($mailto);
319   
320     if (strlen($headers['Cc']))
321       $a_recipients[] = $headers['Cc'];
322     if (strlen($headers['Bcc']))
323       $a_recipients[] = $headers['Bcc'];
324   
325     // clean Bcc from header for recipients
326     $send_headers = $headers;
327     unset($send_headers['Bcc']);
328   
5a6ad2 329     if (!empty($mb_subject))
T 330       $send_headers['Subject'] = $mb_subject;
1966c5 331   
S 332     // send message
b517af 333     $smtp_response = array();
5a6ad2 334     $sent = smtp_mail($from, $a_recipients, $MAIL_MIME->txtHeaders($send_headers), $msg_body, $smtp_response);
1966c5 335   
S 336     // log error
337     if (!$sent)
338       {
339       raise_error(array('code' => 800,
340                         'type' => 'smtp',
341                         'line' => __LINE__,
342                         'file' => __FILE__,
b517af 343                         'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1966c5 344       }
S 345     }
346   
347   // send mail using PHP's mail() function
348   else
349     {
350     // unset some headers because they will be added by the mail() function
351     $headers_enc = $MAIL_MIME->headers($headers);
352     $headers_php = $MAIL_MIME->_headers;
353     unset($headers_php['To'], $headers_php['Subject']);
354     
5a6ad2 355     if (!empty($mb_subject))
T 356       $headers_enc['Subject'] = $mb_subject;
357     
1966c5 358     // reset stored headers and overwrite
S 359     $MAIL_MIME->_headers = array();
360     $header_str = $MAIL_MIME->txtHeaders($headers_php);
361   
362     if (ini_get('safe_mode'))
5a6ad2 363       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1966c5 364     else
5a6ad2 365       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1966c5 366     }
S 367   
368   
369   // return to compose page if sending failed
968bdc 370   if (!$sent)
4e17e6 371     {
1966c5 372     show_message("sendingfailed", 'error'); 
41fa0b 373     rcube_iframe_response();
1966c5 374     return;
4e17e6 375     }
13c1af 376   
1966c5 377   
S 378   // set repliead flag
379   if ($_SESSION['compose']['reply_uid'])
380     $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
c03095 381
1966c5 382   } // End of SMTP Delivery Block
41fa0b 383
T 384
4e17e6 385
1966c5 386 // Determine which folder to save message
b068a0 387 if ($savedraft)
T 388   $store_target = 'drafts_mbox';
389 else
390   $store_target = 'sent_mbox';
c03095 391
1966c5 392 if ($CONFIG[$store_target])
4e17e6 393   {
T 394   // create string of complete message headers
395   $header_str = $MAIL_MIME->txtHeaders($headers);
396
397   // check if mailbox exists
1966c5 398   if (!in_array_nocase($CONFIG[$store_target], $IMAP->list_mailboxes()))
S 399     $store_folder = $IMAP->create_mailbox($CONFIG[$store_target], TRUE);
520c36 400   else
1966c5 401     $store_folder = TRUE;
b068a0 402   
T 403   // add headers to message body
404   $msg_body = $header_str."\r\n".$msg_body;
4e17e6 405
T 406   // append message to sent box
1966c5 407   if ($store_folder)
b068a0 408     $saved = $IMAP->save_message($CONFIG[$store_target], $msg_body);
520c36 409
T 410   // raise error if saving failed
411   if (!$saved)
f0f98f 412     {
520c36 413     raise_error(array('code' => 800,
T 414                       'type' => 'imap',
415                       'file' => __FILE__,
1966c5 416                       'message' => "Could not save message in $CONFIG[$store_target]"), TRUE, FALSE);
41fa0b 417     
T 418     show_message('errorsaving', 'error');
419     rcube_iframe_response($errorout);
f0f98f 420     }
4e17e6 421
b068a0 422   if ($olddraftmessageid)
T 423     {
1966c5 424     // delete previous saved draft
S 425     $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'],'HEADER Message-ID',$olddraftmessageid);
426     $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0],$CONFIG['drafts_mbox']),$CONFIG['drafts_mbox']);
4e17e6 427
f0f98f 428     // raise error if deletion of old draft failed
1966c5 429     if (!$deleted)
S 430       raise_error(array('code' => 800,
431                         'type' => 'imap',
432                         'file' => __FILE__,
433                         'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
4e17e6 434     }
T 435   }
436
1966c5 437 if ($savedraft)
S 438   {
f0f98f 439   // clear the "saving message" busy status, and display success
41fa0b 440   show_message('messagesaved', 'confirmation');
f0f98f 441
S 442   // update "_draft_saveid" on the page, which is used to delete a previous draft
41fa0b 443   $frameout = "var foundid = parent.rcube_find_object('_draft_saveid', parent.document);\n";
T 444   $frameout .= sprintf("foundid.value = '%s';\n", str_replace(array('<','>'), "", $message_id));
f0f98f 445
S 446   // update the "cmp_hash" to prevent "Unsaved changes" warning
41fa0b 447   $frameout .= sprintf("parent.%s.cmp_hash = parent.%s.compose_field_hash();\n", $JS_OBJECT_NAME, $JS_OBJECT_NAME);
T 448
f0f98f 449   // start the auto-save timer again
41fa0b 450   $frameout .= sprintf("parent.%s.auto_save_start();", $JS_OBJECT_NAME);
f0f98f 451
S 452   // send html page with JS calls as response
41fa0b 453   rcube_iframe_response($frameout);
1966c5 454   }
S 455 else
456   {
457   if ($CONFIG['smtp_log'])
458     {
b517af 459     $log_entry = sprintf("[%s] User: %d on %s; Message for %s; %s\n",
1966c5 460                  date("d-M-Y H:i:s O", mktime()),
S 461                  $_SESSION['user_id'],
462                  $_SERVER['REMOTE_ADDR'],
463                  $mailto,
b517af 464                  !empty($smtp_response) ? join('; ', $smtp_response) : '');
4e17e6 465
1966c5 466     if ($fp = @fopen($CONFIG['log_dir'].'/sendmail', 'a'))
S 467       {
468       fwrite($fp, $log_entry);
469       fclose($fp);
470       }
471     }
41fa0b 472
1966c5 473   rcmail_compose_cleanup();
41fa0b 474   rcube_iframe_response(sprintf("parent.$JS_OBJECT_NAME.sent_successfully('%s');",
2bca6e 475                                 JQ(rcube_label('messagesent'))));
1966c5 476   }
4e17e6 477
T 478
1966c5 479 ?>