source: github/program/steps/mail/sendmail.inc @ 5a6ad20

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 5a6ad20 was 5a6ad20, checked in by thomascube <thomas@…>, 6 years ago

Fixed message headers encoding; improved recipient splitting; applied patch for attachment download (#1484198)

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