thomascube
2006-12-13 7a5c48e7f70b8bc938fcae3ffd2be0fdbeaab145
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');
4e17e6 27 require_once('Mail/mime.php');
T 28
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)));
a0109c 103
4e6eb1 104     $body_post = substr($body, $pos2);
S 105
ed6592 106     if (! in_array($image_name, $included_images))
a0109c 107       {
ed6592 108       // add the image to the MIME message
S 109       $img_file = $INSTALL_PATH . '/' . $searchstr . $image_name;
110       if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, '_' . $image_name))
111         {
112         show_message("emoticonerror", 'error');
113         }
114       array_push($included_images, $image_name);
115       }
a0109c 116
4e6eb1 117     $body = $body_pre . 'cid:_' . $image_name . $body_post;
S 118
a0109c 119     $last_img_pos = $pos2;
S 120     }
121    
122   $mime_message->setHTMLBody($body);
123 }
41fa0b 124
b068a0 125 if (strlen($_POST['_draft_saveid']) > 3)
T 126   $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
127
8cb245 128 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), rcmail_mail_domain($_SESSION['imap_host']));
b068a0 129 $savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
41fa0b 130
T 131 // remove all scripts and act as called in frame
132 $OUTPUT->reset();
133 $_framed = TRUE;
134
b068a0 135
4e17e6 136 /****** check submission and compose message ********/
10a699 137
T 138
139 if (empty($_POST['_to']) && empty($_POST['_subject']) && $_POST['_message'])
140   {
141   show_message("sendingfailed", 'error'); 
41fa0b 142   //rcmail_overwrite_action('compose');
T 143   rcube_iframe_response();
10a699 144   return;
T 145   }
4e17e6 146
T 147
5bc8cb 148 // set default charset
13c1af 149 $input_charset = $OUTPUT->get_charset();
c03095 150 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
T 151
1cded8 152 $mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m');
T 153 $mailto_replace = array(', ', ', ', '');
4e17e6 154
abb32e 155 // replace new lines and strip ending ', '
ea7c46 156 $mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
4e17e6 157
T 158 // decode address strings
159 $to_address_arr = $IMAP->decode_address_list($mailto);
b068a0 160 $identity_arr = rcmail_get_identity(get_input_value('_from', RCUBE_INPUT_POST));
4e17e6 161
T 162 $from = $identity_arr['mailto'];
163 $first_to = is_array($to_address_arr[0]) ? $to_address_arr[0]['mailto'] : $mailto;
164
b068a0 165 if (empty($identity_arr['string']))
T 166   $identity_arr['string'] = $from;
4e17e6 167
T 168 // compose headers array
421f5e 169 $headers = array('Date' => date('D, j M Y H:i:s O'),
b517af 170                  'From' => rcube_charset_convert($identity_arr['string'], $CHARSET, $message_charset),
508442 171                  'To'   => rcube_charset_convert($mailto, $input_charset, $message_charset));
4e17e6 172
T 173 // additional recipients
ea7c46 174 if (!empty($_POST['_cc']))
T 175   $headers['Cc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
4e17e6 176
ea7c46 177 if (!empty($_POST['_bcc']))
T 178   $headers['Bcc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
4e17e6 179   
ea7c46 180 if (!empty($identity_arr['bcc']))
4e17e6 181   $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
T 182
183 // add subject
ea7c46 184 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
4e17e6 185
ea7c46 186 if (!empty($identity_arr['organization']))
4e17e6 187   $headers['Organization'] = $identity_arr['organization'];
T 188
ea7c46 189 if (!empty($identity_arr['reply-to']))
4e17e6 190   $headers['Reply-To'] = $identity_arr['reply-to'];
T 191
f88d41 192 if (!empty($_SESSION['compose']['reply_msgid']))
4e17e6 193   $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
T 194
f88d41 195 if (!empty($_SESSION['compose']['references']))
T 196   $headers['References'] = $_SESSION['compose']['references'];
4e17e6 197
ea7c46 198 if (!empty($_POST['_priority']))
4e17e6 199   {
T 200   $priority = (int)$_POST['_priority'];
3287e8 201   $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
4e17e6 202   if ($str_priority = $a_priorities[$priority])
T 203     $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
204   }
205
620439 206 if (!empty($_POST['_receipt']))
T 207   {
208   $headers['Return-Receipt-To'] = $identity_arr['string'];
209   $headers['Disposition-Notification-To'] = $identity_arr['string'];
210   }
4e17e6 211
T 212 // additional headers
213 $headers['Message-ID'] = $message_id;
214 $headers['X-Sender'] = $from;
215
ea7c46 216 if (!empty($CONFIG['useragent']))
4e17e6 217   $headers['User-Agent'] = $CONFIG['useragent'];
T 218
c03095 219 // fetch message body
ea7c46 220 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
4e17e6 221
4b0f65 222 // append generic footer to all messages
T 223 if (!empty($CONFIG['generic_message_footer']))
224   {
225   $file = realpath($CONFIG['generic_message_footer']);
226   if($fp = fopen($file, 'r'))
227     {
228     $content = fread($fp, filesize($file));
229     fclose($fp);
c03095 230     $message_body .= "\r\n" . rcube_charset_convert($content, 'UTF-8', $message_charset);
4b0f65 231     }
T 232   }
233
4647e1 234 // try to autodetect operating system and use the correct line endings
4b0f65 235 // use the configured delimiter for headers
4647e1 236 if (!empty($CONFIG['mail_header_delimiter']))
T 237   $header_delm = $CONFIG['mail_header_delimiter'];
238 else if (strtolower(substr(PHP_OS, 0, 3)=='win')) 
239   $header_delm = "\r\n";
240 else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
241   $header_delm = "\r\n";
242 else    
243   $header_delm = "\n";
4b0f65 244
4e17e6 245 // create PEAR::Mail_mime instance
a0109c 246
S 247 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
248 $isHtml = ($isHtmlVal == "1");
249
4b0f65 250 $MAIL_MIME = new Mail_mime($header_delm);
a0109c 251
S 252 // For HTML-formatted messages, construct the MIME message with both
253 // the HTML part and the plain-text part
254
255 if ($isHtml)
256   {
257   $MAIL_MIME->setHTMLBody($message_body);
258
259   // add a plain text version of the e-mail as an alternative part.
260   $h2t = new html2text($message_body);
261   $plainTextPart = $h2t->get_text();
262   $MAIL_MIME->setTXTBody($plainTextPart);
263
264   // look for "emoticon" images from TinyMCE and copy into message as attachments
265   rcmail_attach_emoticons($MAIL_MIME);
266   }
267 else
268   {
269   $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
270   }
4e17e6 271
T 272
273 // add stored attachments, if any
274 if (is_array($_SESSION['compose']['attachments']))
275   foreach ($_SESSION['compose']['attachments'] as $attachment)
276     $MAIL_MIME->addAttachment($attachment['path'], $attachment['mimetype'], $attachment['name'], TRUE);
277
278   
279 // add submitted attachments
280 if (is_array($_FILES['_attachments']['tmp_name']))
281   foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
282     $MAIL_MIME->addAttachment($filepath, $files['type'][$i], $files['name'][$i], TRUE);
283
1cded8 284
f88d41 285 // chose transfer encoding
T 286 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
287 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
288
a95e0e 289 // encoding settings for mail composing
f88d41 290 $message_param = array('text_encoding' => $transfer_encoding,
a95e0e 291                        'html_encoding' => 'quoted-printable',
T 292                        'head_encoding' => 'quoted-printable',
1cded8 293                        'head_charset'  => $message_charset,
T 294                        'html_charset'  => $message_charset,
295                        'text_charset'  => $message_charset);
4e17e6 296
T 297 // compose message body and get headers
b517af 298 $msg_body = $MAIL_MIME->get($message_param);
T 299 // unset to save memory.
300 unset($MAIL_MIME->_parts);
4e17e6 301
f88d41 302 $msg_subject = $headers['Subject'];
13c1af 303
T 304 if ($MBSTRING && function_exists("mb_encode_mimeheader"))
b517af 305 {
T 306   mb_internal_encoding($CHARSET);
307   $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
308 }
4e17e6 309
1966c5 310 // Begin SMTP Delivery Block 
S 311 if (!$savedraft) {
4e17e6 312
1966c5 313   // send thru SMTP server using custom SMTP library
S 314   if ($CONFIG['smtp_server'])
315     {
316     // generate list of recipients
317     $a_recipients = array($mailto);
318   
319     if (strlen($headers['Cc']))
320       $a_recipients[] = $headers['Cc'];
321     if (strlen($headers['Bcc']))
322       $a_recipients[] = $headers['Bcc'];
323   
324     // clean Bcc from header for recipients
325     $send_headers = $headers;
326     unset($send_headers['Bcc']);
327   
328     // generate message headers
329     $header_str = $MAIL_MIME->txtHeaders($send_headers);
330   
331     // send message
b517af 332     $smtp_response = array();
T 333     $sent = smtp_mail($from, $a_recipients, $header_str, $msg_body, $smtp_response);
1966c5 334   
S 335     // log error
336     if (!$sent)
337       {
338       raise_error(array('code' => 800,
339                         'type' => 'smtp',
340                         'line' => __LINE__,
341                         'file' => __FILE__,
b517af 342                         'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1966c5 343       }
S 344     }
345   
346   // send mail using PHP's mail() function
347   else
348     {
349     // unset some headers because they will be added by the mail() function
350     $headers_enc = $MAIL_MIME->headers($headers);
351     $headers_php = $MAIL_MIME->_headers;
352     unset($headers_php['To'], $headers_php['Subject']);
353     
354     // reset stored headers and overwrite
355     $MAIL_MIME->_headers = array();
356     $header_str = $MAIL_MIME->txtHeaders($headers_php);
357   
358     if (ini_get('safe_mode'))
359       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
360     else
361       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
362     }
363   
364   
365   // return to compose page if sending failed
968bdc 366   if (!$sent)
4e17e6 367     {
1966c5 368     show_message("sendingfailed", 'error'); 
41fa0b 369     rcube_iframe_response();
1966c5 370     return;
4e17e6 371     }
13c1af 372   
1966c5 373   
S 374   // set repliead flag
375   if ($_SESSION['compose']['reply_uid'])
376     $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
c03095 377
1966c5 378   } // End of SMTP Delivery Block
41fa0b 379
T 380
4e17e6 381
1966c5 382 // Determine which folder to save message
b068a0 383 if ($savedraft)
T 384   $store_target = 'drafts_mbox';
385 else
386   $store_target = 'sent_mbox';
c03095 387
1966c5 388 if ($CONFIG[$store_target])
4e17e6 389   {
T 390   // create string of complete message headers
391   $header_str = $MAIL_MIME->txtHeaders($headers);
392
393   // check if mailbox exists
1966c5 394   if (!in_array_nocase($CONFIG[$store_target], $IMAP->list_mailboxes()))
S 395     $store_folder = $IMAP->create_mailbox($CONFIG[$store_target], TRUE);
520c36 396   else
1966c5 397     $store_folder = TRUE;
b068a0 398   
T 399   // add headers to message body
400   $msg_body = $header_str."\r\n".$msg_body;
4e17e6 401
T 402   // append message to sent box
1966c5 403   if ($store_folder)
b068a0 404     $saved = $IMAP->save_message($CONFIG[$store_target], $msg_body);
520c36 405
T 406   // raise error if saving failed
407   if (!$saved)
f0f98f 408     {
520c36 409     raise_error(array('code' => 800,
T 410                       'type' => 'imap',
411                       'file' => __FILE__,
1966c5 412                       'message' => "Could not save message in $CONFIG[$store_target]"), TRUE, FALSE);
41fa0b 413     
T 414     show_message('errorsaving', 'error');
415     rcube_iframe_response($errorout);
f0f98f 416     }
4e17e6 417
b068a0 418   if ($olddraftmessageid)
T 419     {
1966c5 420     // delete previous saved draft
S 421     $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'],'HEADER Message-ID',$olddraftmessageid);
422     $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0],$CONFIG['drafts_mbox']),$CONFIG['drafts_mbox']);
4e17e6 423
f0f98f 424     // raise error if deletion of old draft failed
1966c5 425     if (!$deleted)
S 426       raise_error(array('code' => 800,
427                         'type' => 'imap',
428                         'file' => __FILE__,
429                         'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
4e17e6 430     }
T 431   }
432
1966c5 433 if ($savedraft)
S 434   {
f0f98f 435   // clear the "saving message" busy status, and display success
41fa0b 436   show_message('messagesaved', 'confirmation');
f0f98f 437
S 438   // update "_draft_saveid" on the page, which is used to delete a previous draft
41fa0b 439   $frameout = "var foundid = parent.rcube_find_object('_draft_saveid', parent.document);\n";
T 440   $frameout .= sprintf("foundid.value = '%s';\n", str_replace(array('<','>'), "", $message_id));
f0f98f 441
S 442   // update the "cmp_hash" to prevent "Unsaved changes" warning
41fa0b 443   $frameout .= sprintf("parent.%s.cmp_hash = parent.%s.compose_field_hash();\n", $JS_OBJECT_NAME, $JS_OBJECT_NAME);
T 444
f0f98f 445   // start the auto-save timer again
41fa0b 446   $frameout .= sprintf("parent.%s.auto_save_start();", $JS_OBJECT_NAME);
f0f98f 447
S 448   // send html page with JS calls as response
41fa0b 449   rcube_iframe_response($frameout);
1966c5 450   }
S 451 else
452   {
453   if ($CONFIG['smtp_log'])
454     {
b517af 455     $log_entry = sprintf("[%s] User: %d on %s; Message for %s; %s\n",
1966c5 456                  date("d-M-Y H:i:s O", mktime()),
S 457                  $_SESSION['user_id'],
458                  $_SERVER['REMOTE_ADDR'],
459                  $mailto,
b517af 460                  !empty($smtp_response) ? join('; ', $smtp_response) : '');
4e17e6 461
1966c5 462     if ($fp = @fopen($CONFIG['log_dir'].'/sendmail', 'a'))
S 463       {
464       fwrite($fp, $log_entry);
465       fclose($fp);
466       }
467     }
41fa0b 468
1966c5 469   rcmail_compose_cleanup();
41fa0b 470   rcube_iframe_response(sprintf("parent.$JS_OBJECT_NAME.sent_successfully('%s');",
T 471                                 rep_specialchars_output(rcube_label('messagesent'), 'js')));
1966c5 472   }
4e17e6 473
T 474
1966c5 475 ?>