alecpl
2008-05-21 2b962c1074c45695da0376f830ec63923743c39e
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                     |
47124c 8  | Copyright (C) 2005-2008, 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         |
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
23
24 if (!isset($_SESSION['compose']['id']))
25   {
10a699 26   rcmail_overwrite_action('list');
4e17e6 27   return;
T 28   }
29
30
31 /****** message sending functions ********/
32
33
fba1f5 34 // get identity record
4e17e6 35 function rcmail_get_identity($id)
T 36   {
fba1f5 37   global $USER, $OUTPUT;
4e17e6 38   
fba1f5 39   if ($sql_arr = $USER->get_identity($id))
4e17e6 40     {
T 41     $out = $sql_arr;
fba1f5 42     $out['mailto'] = $sql_arr['email'];
abb32e 43     $name = strpos($sql_arr['name'], ",") ? '"'.$sql_arr['name'].'"' : $sql_arr['name'];
13c1af 44     $out['string'] = sprintf('%s <%s>',
f11541 45                              rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset()),
fba1f5 46                              $sql_arr['email']);
4e17e6 47     return $out;
T 48     }
49
50   return FALSE;  
51   }
52
a0109c 53 /**
S 54  * go from this:
55  * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
56  *
57  * to this:
58  *
59  * <IMG src="cid:smiley-cool.gif"/>
60  * ...
61  * ------part...
62  * Content-Type: image/gif
63  * Content-Transfer-Encoding: base64
64  * Content-ID: <smiley-cool.gif>
65  */
66 function rcmail_attach_emoticons(&$mime_message)
67 {
47124c 68   global $CONFIG;
a0109c 69
S 70   $htmlContents = $mime_message->getHtmlBody();
71
72   // remove any null-byte characters before parsing
73   $body = preg_replace('/\x00/', '', $htmlContents);
74   
75   $last_img_pos = 0;
76
77   $searchstr = 'program/js/tiny_mce/plugins/emotions/images/';
78
ed6592 79   // keep track of added images, so they're only added once
S 80   $included_images = array();
81
a0109c 82   // find emoticon image tags
S 83   while ($pos = strpos($body, $searchstr, $last_img_pos))
84     {
85     $pos2 = strpos($body, '"', $pos);
86     $body_pre = substr($body, 0, $pos);
ed6592 87     $image_name = substr($body,
S 88                          $pos + strlen($searchstr),
89                          $pos2 - ($pos + strlen($searchstr)));
ee883a 90     // sanitize image name so resulting attachment doesn't leave images dir
T 91     $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i','',$image_name);
a0109c 92
4e6eb1 93     $body_post = substr($body, $pos2);
S 94
ed6592 95     if (! in_array($image_name, $included_images))
a0109c 96       {
ed6592 97       // add the image to the MIME message
47124c 98       $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
ed6592 99       if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, '_' . $image_name))
f11541 100         $OUTPUT->show_message("emoticonerror", 'error');
T 101
ed6592 102       array_push($included_images, $image_name);
S 103       }
a0109c 104
4e6eb1 105     $body = $body_pre . 'cid:_' . $image_name . $body_post;
S 106
a0109c 107     $last_img_pos = $pos2;
S 108     }
109    
110   $mime_message->setHTMLBody($body);
111 }
41fa0b 112
b068a0 113 if (strlen($_POST['_draft_saveid']) > 3)
T 114   $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
115
8cb245 116 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), rcmail_mail_domain($_SESSION['imap_host']));
b068a0 117 $savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
41fa0b 118
T 119 // remove all scripts and act as called in frame
120 $OUTPUT->reset();
f11541 121 $OUTPUT->framed = TRUE;
41fa0b 122
b068a0 123
4e17e6 124 /****** check submission and compose message ********/
10a699 125
T 126
e8f8fe 127 if (!$savedraft && empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc']) && empty($_POST['_subject']) && $_POST['_message'])
10a699 128   {
f11541 129   $OUTPUT->show_message("sendingfailed", 'error');
T 130   $OUTPUT->send('iframe');
10a699 131   return;
T 132   }
4e17e6 133
T 134
5bc8cb 135 // set default charset
13c1af 136 $input_charset = $OUTPUT->get_charset();
c03095 137 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
T 138
5a6ad2 139 $mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/');
T 140 $mailto_replace = array(', ', ', ', '', ',');
4e17e6 141
abb32e 142 // replace new lines and strip ending ', '
ea7c46 143 $mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
e8f8fe 144 $mailcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
T 145 $mailbcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
4e17e6 146
e8f8fe 147 if (empty($mailto) && !empty($mailcc)) {
T 148   $mailto = $mailcc;
149   $mailcc = null;
150 }
151 else if (empty($mailto))
152   $mailto = 'undisclosed-recipients:;';
153
154 // get sender name and address
b068a0 155 $identity_arr = rcmail_get_identity(get_input_value('_from', RCUBE_INPUT_POST));
4e17e6 156 $from = $identity_arr['mailto'];
T 157
b068a0 158 if (empty($identity_arr['string']))
T 159   $identity_arr['string'] = $from;
4e17e6 160
T 161 // compose headers array
fba1f5 162 $headers = array('Date' => date('r'),
f11541 163                  'From' => rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset),
5a6ad2 164                  'To'   => $mailto);
4e17e6 165
T 166 // additional recipients
e8f8fe 167 if (!empty($mailcc))
T 168   $headers['Cc'] = $mailcc;
4e17e6 169
e8f8fe 170 if (!empty($mailbcc))
T 171   $headers['Bcc'] = $mailbcc;
4e17e6 172   
ea7c46 173 if (!empty($identity_arr['bcc']))
4e17e6 174   $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
T 175
176 // add subject
ea7c46 177 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
4e17e6 178
ea7c46 179 if (!empty($identity_arr['organization']))
4e17e6 180   $headers['Organization'] = $identity_arr['organization'];
T 181
7984ec 182 if (!empty($_POST['_replyto']))
T 183   $headers['Reply-To'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
184 else if (!empty($identity_arr['reply-to']))
4e17e6 185   $headers['Reply-To'] = $identity_arr['reply-to'];
T 186
f88d41 187 if (!empty($_SESSION['compose']['reply_msgid']))
4e17e6 188   $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
T 189
f88d41 190 if (!empty($_SESSION['compose']['references']))
T 191   $headers['References'] = $_SESSION['compose']['references'];
4e17e6 192
ea7c46 193 if (!empty($_POST['_priority']))
4e17e6 194   {
c57996 195   $priority = intval($_POST['_priority']);
3287e8 196   $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
4e17e6 197   if ($str_priority = $a_priorities[$priority])
T 198     $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
199   }
200
620439 201 if (!empty($_POST['_receipt']))
T 202   {
203   $headers['Return-Receipt-To'] = $identity_arr['string'];
204   $headers['Disposition-Notification-To'] = $identity_arr['string'];
205   }
4e17e6 206
T 207 // additional headers
5ec113 208 if ($CONFIG['http_received_header'])
T 209 {
210   $nldlm = rcmail_header_delm() . "\t";
211   $headers['Received'] =  wordwrap('from ' . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
212       gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']).' ['.$_SERVER['HTTP_X_FORWARDED_FOR'].']'.$nldlm.' via ' : '') .
213     gethostbyaddr($_SERVER['REMOTE_ADDR']).' ['.$_SERVER['REMOTE_ADDR'].']'.$nldlm.'with ' .
214     $_SERVER['SERVER_PROTOCOL'].' ('.$_SERVER['REQUEST_METHOD'].'); ' . date('r'),
215     69, $nldlm);
216 }
4e17e6 217
53e79d 218 $headers['Message-ID'] = $message_id;
A 219 $headers['X-Sender'] = $from;
220
ea7c46 221 if (!empty($CONFIG['useragent']))
4e17e6 222   $headers['User-Agent'] = $CONFIG['useragent'];
T 223
c03095 224 // fetch message body
ea7c46 225 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
4e17e6 226
4b0f65 227 // append generic footer to all messages
63f9d3 228 if (!$savedraft && !empty($CONFIG['generic_message_footer']) && ($footer = file_get_contents(realpath($CONFIG['generic_message_footer']))))
T 229   $message_body .= "\r\n" . rcube_charset_convert($footer, 'UTF-8', $message_charset);
4b0f65 230
a0109c 231 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
S 232 $isHtml = ($isHtmlVal == "1");
233
ab6f80 234 // create extended PEAR::Mail_mime instance
47124c 235 $MAIL_MIME = new rcube_mail_mime(rcmail_header_delm());
a0109c 236
S 237 // For HTML-formatted messages, construct the MIME message with both
238 // the HTML part and the plain-text part
239
240 if ($isHtml)
241   {
242   $MAIL_MIME->setHTMLBody($message_body);
243
244   // add a plain text version of the e-mail as an alternative part.
245   $h2t = new html2text($message_body);
a23884 246   $plainTextPart = wordwrap($h2t->get_text(), 998, "\r\n", true);
212352 247   if (!strlen($plainTextPart)) 
T 248     { 
249     // empty message body breaks attachment handling in drafts 
250     $plainTextPart = "\r\n"; 
251     }
606fc0 252   $MAIL_MIME->setTXTBody(html_entity_decode($plainTextPart, ENT_COMPAT, 'utf-8'));
a0109c 253
S 254   // look for "emoticon" images from TinyMCE and copy into message as attachments
255   rcmail_attach_emoticons($MAIL_MIME);
256   }
257 else
258   {
a23884 259   $message_body = wordwrap($message_body, 75, "\r\n");
T 260   $message_body = wordwrap($message_body, 998, "\r\n", true);
212352 261   if (!strlen($message_body))  
T 262     { 
263     // empty message body breaks attachment handling in drafts 
264     $message_body = "\r\n"; 
265     } 
a0109c 266   $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
S 267   }
4e17e6 268
T 269
270 // add stored attachments, if any
271 if (is_array($_SESSION['compose']['attachments']))
4315b0 272   foreach ($_SESSION['compose']['attachments'] as $id => $attachment)
S 273   {
274     $dispurl = '/\ssrc\s*=\s*[\'"]?\S+display-attachment\S+file=rcmfile' . $id . '[\'"]?/';
275     $match = preg_match($dispurl, $message_body);
276     if ($isHtml && ($match > 0))
277     {
278       $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'"', $message_body);
279       $MAIL_MIME->setHTMLBody($message_body);
280       $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name']);
281     }
282     else
283     {
75f0a7 284       /*
T 285         We need to replace mime_content_type in a later release because the function
286         is deprecated in favour of File_Info
287       */
734584 288       $MAIL_MIME->addAttachment($attachment['path'],
T 289         rc_mime_content_type($attachment['path'], $attachment['mimetype']),
290         $attachment['name'], true, 'base64',
291         'attachment', $message_charset);
4315b0 292     }
S 293   }
4e17e6 294
T 295 // add submitted attachments
296 if (is_array($_FILES['_attachments']['tmp_name']))
297   foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
ab6f80 298     $MAIL_MIME->addAttachment($filepath, $files['type'][$i], $files['name'][$i], true, 'base64', 'attachment', $message_charset);
4e17e6 299
1cded8 300
f88d41 301 // chose transfer encoding
T 302 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
303 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
304
a95e0e 305 // encoding settings for mail composing
fba1f5 306 $MAIL_MIME->setParam(array(
a23884 307   'text_encoding' => $transfer_encoding,
T 308   'html_encoding' => 'quoted-printable',
309   'head_encoding' => 'quoted-printable',
310   'head_charset'  => $message_charset,
311   'html_charset'  => $message_charset,
312   'text_charset'  => $message_charset,
fba1f5 313 ));
4e17e6 314
5a6ad2 315 // encoding subject header with mb_encode provides better results with asian characters
197601 316 if (function_exists("mb_encode_mimeheader"))
b517af 317 {
24fe97 318   mb_internal_encoding($message_charset);
fba1f5 319   $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
f11541 320   mb_internal_encoding(RCMAIL_CHARSET);
b517af 321 }
4e17e6 322
fba1f5 323 // pass headers to message object
T 324 $MAIL_MIME->headers($headers);
4e17e6 325
fba1f5 326 // Begin SMTP Delivery Block 
T 327 if (!$savedraft)
328 {
329   $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto);
1966c5 330   
S 331   // return to compose page if sending failed
968bdc 332   if (!$sent)
4e17e6 333     {
f11541 334     $OUTPUT->show_message("sendingfailed", 'error'); 
T 335     $OUTPUT->send('iframe');
1966c5 336     return;
4e17e6 337     }
1966c5 338   
S 339   // set repliead flag
340   if ($_SESSION['compose']['reply_uid'])
341     $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
c03095 342
1966c5 343   } // End of SMTP Delivery Block
41fa0b 344
T 345
4e17e6 346
1966c5 347 // Determine which folder to save message
b068a0 348 if ($savedraft)
T 349   $store_target = 'drafts_mbox';
350 else
351   $store_target = 'sent_mbox';
c03095 352
1966c5 353 if ($CONFIG[$store_target])
4e17e6 354   {
T 355   // check if mailbox exists
1966c5 356   if (!in_array_nocase($CONFIG[$store_target], $IMAP->list_mailboxes()))
S 357     $store_folder = $IMAP->create_mailbox($CONFIG[$store_target], TRUE);
520c36 358   else
1966c5 359     $store_folder = TRUE;
b068a0 360   
4e17e6 361   // append message to sent box
1966c5 362   if ($store_folder)
fba1f5 363     $saved = $IMAP->save_message($CONFIG[$store_target], $MAIL_MIME->getMessage());
520c36 364
T 365   // raise error if saving failed
366   if (!$saved)
f0f98f 367     {
f11541 368     raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
1966c5 369                       'message' => "Could not save message in $CONFIG[$store_target]"), TRUE, FALSE);
41fa0b 370     
f11541 371     $OUTPUT->show_message('errorsaving', 'error');
T 372     $OUTPUT->send('iframe');
f0f98f 373     }
4e17e6 374
b068a0 375   if ($olddraftmessageid)
T 376     {
1966c5 377     // delete previous saved draft
S 378     $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'],'HEADER Message-ID',$olddraftmessageid);
379     $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0],$CONFIG['drafts_mbox']),$CONFIG['drafts_mbox']);
4e17e6 380
f0f98f 381     // raise error if deletion of old draft failed
1966c5 382     if (!$deleted)
f11541 383       raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
1966c5 384                         'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
4e17e6 385     }
T 386   }
387
1966c5 388 if ($savedraft)
S 389   {
f11541 390   // display success
T 391   $OUTPUT->show_message('messagesaved', 'confirmation');
f0f98f 392
f11541 393   // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
T 394   $OUTPUT->command('set_draft_id', str_replace(array('<','>'), "", $message_id));
395   $OUTPUT->command('compose_field_hash', true);
41fa0b 396
f0f98f 397   // start the auto-save timer again
f11541 398   $OUTPUT->command('auto_save_start');
f0f98f 399
f11541 400   $OUTPUT->send('iframe');
1966c5 401   }
S 402 else
403   {
404   if ($CONFIG['smtp_log'])
405     {
f11541 406     $log_entry = sprintf(
T 407       "[%s] User: %d on %s; Message for %s; %s\n",
408       date("d-M-Y H:i:s O", mktime()),
409       $_SESSION['user_id'],
410       $_SERVER['REMOTE_ADDR'],
411       $mailto,
412       !empty($smtp_response) ? join('; ', $smtp_response) : '');
4e17e6 413
1966c5 414     if ($fp = @fopen($CONFIG['log_dir'].'/sendmail', 'a'))
S 415       {
416       fwrite($fp, $log_entry);
417       fclose($fp);
418       }
419     }
41fa0b 420
1966c5 421   rcmail_compose_cleanup();
f11541 422   $OUTPUT->command('sent_successfully', rcube_label('messagesent'));
T 423   $OUTPUT->send('iframe');
1966c5 424   }
4e17e6 425
1966c5 426 ?>