source: subversion/trunk/roundcubemail/program/steps/mail/sendmail.inc @ 1897

Last change on this file since 1897 was 1897, checked in by alec, 5 years ago
  • Added 'mime_param_folding' option with possibility to choose long/non-ascii attachment names encoding eg. to be readable in MS Outlook/OE (#1485320)
  • Added "advanced options" feature in User Preferences
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 15.3 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-2008, 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 the PEAR::Net_SMTP class or with PHP mail()       |
14 |                                                                       |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17 +-----------------------------------------------------------------------+
18
19 $Id$
20
21*/
22
23
24// remove all scripts and act as called in frame
25$OUTPUT->reset();
26$OUTPUT->framed = TRUE;
27
28$savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
29
30/****** checks ********/
31
32if (!isset($_SESSION['compose']['id'])) {
33  raise_error(array('code' => 500, 'file' => __FILE__, 'message' => "Invalid compose ID"), true, false);
34  console("Sendmail error", $_SESSION['compose']);
35  $OUTPUT->show_message("An internal error occured. Please try again.", 'error');
36  $OUTPUT->send('iframe');
37}
38
39if (!$savedraft && empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc']) && empty($_POST['_subject']) && $_POST['_message']) {
40  $OUTPUT->show_message('sendingfailed', 'error');
41  $OUTPUT->send('iframe');
42}
43
44if(!$savedraft && !empty($CONFIG['sendmail_delay'])) {
45  $wait_sec = time() - intval($CONFIG['sendmail_delay']) - intval($_SESSION['last_message_time']);
46  if($wait_sec < 0)
47    {
48    $OUTPUT->show_message('senttooquickly', 'error', array('sec' => $wait_sec * -1));
49    $OUTPUT->send('iframe');
50    }
51}
52
53
54/****** message sending functions ********/
55
56// get identity record
57function rcmail_get_identity($id)
58  {
59  global $USER, $OUTPUT;
60 
61  if ($sql_arr = $USER->get_identity($id))
62    {
63    $out = $sql_arr;
64    $out['mailto'] = $sql_arr['email'];
65    $name = strpos($sql_arr['name'], ",") ? '"'.$sql_arr['name'].'"' : $sql_arr['name'];
66    $out['string'] = sprintf('%s <%s>',
67                             rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset()),
68                             $sql_arr['email']);
69    return $out;
70    }
71
72  return FALSE; 
73  }
74
75/**
76 * go from this:
77 * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
78 *
79 * to this:
80 *
81 * <IMG src="cid:smiley-cool.gif"/>
82 * ...
83 * ------part...
84 * Content-Type: image/gif
85 * Content-Transfer-Encoding: base64
86 * Content-ID: <smiley-cool.gif>
87 */
88function rcmail_attach_emoticons(&$mime_message)
89{
90  global $CONFIG;
91
92  $htmlContents = $mime_message->getHtmlBody();
93
94  // remove any null-byte characters before parsing
95  $body = preg_replace('/\x00/', '', $htmlContents);
96 
97  $last_img_pos = 0;
98
99  $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
100
101  // keep track of added images, so they're only added once
102  $included_images = array();
103
104  // find emoticon image tags
105  while ($pos = strpos($body, $searchstr, $last_img_pos))
106    {
107    $pos2 = strpos($body, '"', $pos);
108    $body_pre = substr($body, 0, $pos);
109    $image_name = substr($body,
110                         $pos + strlen($searchstr),
111                         $pos2 - ($pos + strlen($searchstr)));
112    // sanitize image name so resulting attachment doesn't leave images dir
113    $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i','',$image_name);
114
115    $body_post = substr($body, $pos2);
116
117    if (! in_array($image_name, $included_images))
118      {
119      // add the image to the MIME message
120      $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
121      if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name))
122        $OUTPUT->show_message("emoticonerror", 'error');
123
124      array_push($included_images, $image_name);
125      }
126
127    $body = $body_pre . $img_file . $body_post;
128
129    $last_img_pos = $pos2;
130    }
131   
132  $mime_message->setHTMLBody($body);
133}
134
135
136/****** compose message ********/
137
138if (strlen($_POST['_draft_saveid']) > 3)
139  $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
140
141$message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host']));
142
143// set default charset
144$input_charset = $OUTPUT->get_charset();
145$message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
146
147$mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/');
148$mailto_replace = array(', ', ', ', '', ',');
149
150// replace new lines and strip ending ', '
151$mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
152$mailcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
153$mailbcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
154
155if (empty($mailto) && !empty($mailcc)) {
156  $mailto = $mailcc;
157  $mailcc = null;
158}
159else if (empty($mailto))
160  $mailto = 'undisclosed-recipients:;';
161
162// get sender name and address
163$identity_arr = rcmail_get_identity(get_input_value('_from', RCUBE_INPUT_POST));
164$from = $identity_arr['mailto'];
165
166if (empty($identity_arr['string']))
167  $identity_arr['string'] = $from;
168
169// compose headers array
170$headers = array('Date' => date('r'),
171                 'From' => rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset),
172                 'To'   => $mailto);
173
174// additional recipients
175if (!empty($mailcc))
176  $headers['Cc'] = $mailcc;
177
178if (!empty($mailbcc))
179  $headers['Bcc'] = $mailbcc;
180 
181if (!empty($identity_arr['bcc']))
182  $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
183
184// add subject
185$headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
186
187if (!empty($identity_arr['organization']))
188  $headers['Organization'] = $identity_arr['organization'];
189
190if (!empty($_POST['_replyto']))
191  $headers['Reply-To'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
192else if (!empty($identity_arr['reply-to']))
193  $headers['Reply-To'] = $identity_arr['reply-to'];
194
195if (!empty($_SESSION['compose']['reply_msgid']))
196  $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
197
198if (!empty($_SESSION['compose']['references']))
199  $headers['References'] = $_SESSION['compose']['references'];
200
201if (!empty($_POST['_priority']))
202  {
203  $priority = intval($_POST['_priority']);
204  $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
205  if ($str_priority = $a_priorities[$priority])
206    $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
207  }
208
209if (!empty($_POST['_receipt']))
210  {
211  $headers['Return-Receipt-To'] = $identity_arr['string'];
212  $headers['Disposition-Notification-To'] = $identity_arr['string'];
213  }
214
215// additional headers
216if ($CONFIG['http_received_header'])
217{
218  $nldlm = $RCMAIL->config->header_delimiter() . "\t";
219  $headers['Received'] =  wordwrap('from ' . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
220      gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']).' ['.$_SERVER['HTTP_X_FORWARDED_FOR'].']'.$nldlm.' via ' : '') .
221    gethostbyaddr($_SERVER['REMOTE_ADDR']).' ['.$_SERVER['REMOTE_ADDR'].']'.$nldlm.'with ' .
222    $_SERVER['SERVER_PROTOCOL'].' ('.$_SERVER['REQUEST_METHOD'].'); ' . date('r'),
223    69, $nldlm);
224}
225
226$headers['Message-ID'] = $message_id;
227$headers['X-Sender'] = $from;
228
229if (!empty($CONFIG['useragent']))
230  $headers['User-Agent'] = $CONFIG['useragent'];
231
232$isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
233$isHtml = ($isHtmlVal == "1");
234
235// fetch message body
236$message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
237
238// remove signature's div ID
239if (!$savedraft && $isHtml)
240  $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
241
242// append generic footer to all messages
243if (!$savedraft && !empty($CONFIG['generic_message_footer']) && ($footer = file_get_contents(realpath($CONFIG['generic_message_footer']))))
244  $message_body .= "\r\n" . rcube_charset_convert($footer, 'UTF-8', $message_charset);
245
246// create extended PEAR::Mail_mime instance
247$MAIL_MIME = new rcube_mail_mime($RCMAIL->config->header_delimiter());
248
249// For HTML-formatted messages, construct the MIME message with both
250// the HTML part and the plain-text part
251
252if ($isHtml)
253  {
254  $MAIL_MIME->setHTMLBody($message_body);
255
256  // add a plain text version of the e-mail as an alternative part.
257  $h2t = new html2text($message_body);
258  $plainTextPart = wordwrap($h2t->get_text(), 998, "\r\n", true);
259  if (!strlen($plainTextPart))
260    {
261    // empty message body breaks attachment handling in drafts
262    $plainTextPart = "\r\n";
263    }
264  $MAIL_MIME->setTXTBody(html_entity_decode($plainTextPart, ENT_COMPAT, 'utf-8'));
265
266  // look for "emoticon" images from TinyMCE and copy into message as attachments
267  rcmail_attach_emoticons($MAIL_MIME);
268  }
269else
270  {
271  $message_body = wordwrap($message_body, 75, "\r\n");
272  $message_body = wordwrap($message_body, 998, "\r\n", true);
273  if (!strlen($message_body)) 
274    {
275    // empty message body breaks attachment handling in drafts
276    $message_body = "\r\n";
277    }
278  $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
279  }
280
281// chose transfer encoding
282$charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
283$transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
284
285// add stored attachments, if any
286if (is_array($_SESSION['compose']['attachments']))
287  foreach ($_SESSION['compose']['attachments'] as $id => $attachment)
288  {
289    $dispurl = '/\ssrc\s*=\s*[\'"]?\S+display-attachment\S+file=rcmfile' . $id . '[\'"]?/';
290    $match = preg_match($dispurl, $message_body);
291    if ($isHtml && ($match > 0))
292    {
293      $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'"', $message_body);
294      $MAIL_MIME->setHTMLBody($message_body);
295      $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name']);
296    }
297    else
298    {
299      $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
300
301      // .eml attachments send inline
302      $MAIL_MIME->addAttachment($attachment['path'],
303        $ctype,
304        $attachment['name'], true,
305        ($ctype == 'message/rfc822' ? $transfer_encoding : 'base64'),
306        ($ctype == 'message/rfc822' ? 'inline' : 'attachment'),
307        $message_charset, '', '',
308        $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
309        $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
310        );
311    }
312  }
313
314// add submitted attachments
315if (is_array($_FILES['_attachments']['tmp_name']))
316  foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
317    {
318    $ctype = $files['type'][$i];
319    $ctype = str_replace('image/pjpeg', 'image/jpeg', $ctype); // #1484914
320   
321    $MAIL_MIME->addAttachment($filepath, $ctype, $files['name'][$i], true,
322        $ctype == 'message/rfc822' ? $transfer_encoding : 'base64',
323        'attachment', $message_charset, '', '',
324        $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
325        $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
326        );
327    }
328
329
330// encoding settings for mail composing
331$MAIL_MIME->setParam(array(
332  'text_encoding' => $transfer_encoding,
333  'html_encoding' => 'quoted-printable',
334  'head_encoding' => 'quoted-printable',
335  'head_charset'  => $message_charset,
336  'html_charset'  => $message_charset,
337  'text_charset'  => $message_charset,
338));
339
340// encoding subject header with mb_encode provides better results with asian characters
341if (function_exists("mb_encode_mimeheader"))
342{
343  mb_internal_encoding($message_charset);
344  $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
345  mb_internal_encoding(RCMAIL_CHARSET);
346}
347
348// pass headers to message object
349$MAIL_MIME->headers($headers);
350
351// Begin SMTP Delivery Block
352if (!$savedraft)
353{
354  $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto);
355 
356  // return to compose page if sending failed
357  if (!$sent)
358    {
359    $OUTPUT->show_message("sendingfailed", 'error');
360    $OUTPUT->send('iframe');
361    }
362
363  // save message sent time
364  if (!empty($CONFIG['sendmail_delay']))
365    $_SESSION['last_message_time'] = time();
366 
367  // set replied/forwarded flag
368  if ($_SESSION['compose']['reply_uid'])
369    $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
370  else if ($_SESSION['compose']['forward_uid'])
371    $IMAP->set_flag($_SESSION['compose']['forward_uid'], 'FORWARDED');
372
373} // End of SMTP Delivery Block
374
375
376
377// Determine which folder to save message
378if ($savedraft)
379  $store_target = $CONFIG['drafts_mbox'];
380else   
381  $store_target = isset($_POST['_store_target']) ? get_input_value('_store_target', RCUBE_INPUT_POST) : $CONFIG['sent_mbox'];
382
383if ($store_target)
384  {
385  // check if mailbox exists
386  if (!in_array_nocase($store_target, $IMAP->list_mailboxes()))
387    {
388      // folder may be existing but not subscribed (#1485241)
389      if (!in_array_nocase($store_target, $IMAP->list_unsubscribed()))
390        $store_folder = $IMAP->create_mailbox($store_target, TRUE);
391      else if ($IMAP->subscribe($store_target))
392        $store_folder = TRUE;
393    }
394  else
395    $store_folder = TRUE;
396 
397  // append message to sent box
398  if ($store_folder)
399    $saved = $IMAP->save_message($store_target, $MAIL_MIME->getMessage());
400
401  // raise error if saving failed
402  if (!$saved)
403    {
404    raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
405                      'message' => "Could not save message in $store_target"), TRUE, FALSE);
406   
407    if ($savedraft) {
408      $OUTPUT->show_message('errorsaving', 'error');
409      $OUTPUT->send('iframe');
410      }
411    }
412
413  if ($olddraftmessageid)
414    {
415    // delete previous saved draft
416    $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID', $olddraftmessageid);
417    $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0], $CONFIG['drafts_mbox']), $CONFIG['drafts_mbox']);
418
419    // raise error if deletion of old draft failed
420    if (!$deleted)
421      raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
422                        'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
423    }
424  }
425
426if ($savedraft)
427  {
428  $msgid = strtr($message_id, array('>' => '', '<' => ''));
429 
430  // remember new draft-uid
431  $draftids = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID', $msgid);
432  $_SESSION['compose']['param']['_draft_uid'] = $IMAP->get_uid($draftids[0], $CONFIG['drafts_mbox']);
433
434  // display success
435  $OUTPUT->show_message('messagesaved', 'confirmation');
436
437  // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
438  $OUTPUT->command('set_draft_id', $msgid);
439  $OUTPUT->command('compose_field_hash', true);
440
441  // start the auto-save timer again
442  $OUTPUT->command('auto_save_start');
443
444  $OUTPUT->send('iframe');
445  }
446else
447  {
448  rcmail_compose_cleanup();
449
450  if ($store_folder && !$saved)
451    $OUTPUT->command('sent_successfully', 'error', rcube_label('errorsavingsent'));
452  else
453    $OUTPUT->command('sent_successfully', 'confirmation', rcube_label('messagesent'));
454  $OUTPUT->send('iframe');
455  }
456
457?>
Note: See TracBrowser for help on using the repository browser.