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

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