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

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