source: github/program/steps/mail/sendmail.inc @ 99f2b31

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 99f2b31 was 99f2b31, checked in by alecpl <alec@…>, 4 years ago

#1485653: fix enless loop in rcmail_attach_emoticons() + fix attaching the same image a few times

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