source: subversion/branches/devel-api/program/steps/mail/sendmail.inc @ 2336

Last change on this file since 2336 was 2336, checked in by ziba, 4 years ago

Added an array of required plugins rcube_plugin_api.php. It's got room to grow.
New core plugin: filesystem_attachments - the existing disk based attachment handling now in plugin form (with one garbage collection bug fix)
New plugin: database_attachments - multi-server safe, database backed attachment temp file handling
New plugin hooks: remove_attachment, display_attachment, upload_attachment, save_attachment, cleanup_attachments, get_attachment

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