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

Last change on this file since 3647 was 3647, checked in by thomasb, 3 years ago

No need for the padding since quoted lines are not wrapped at all

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 23.0 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-2010, 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// remove all scripts and act as called in frame
24$OUTPUT->reset();
25$OUTPUT->framed = TRUE;
26
27$savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
28
29/****** checks ********/
30
31if (!isset($_SESSION['compose']['id'])) {
32  raise_error(array('code' => 500, 'type' => 'smtp',
33    'file' => __FILE__, 'line' => __LINE__,
34    'message' => "Invalid compose ID"), true, false);
35
36  $OUTPUT->show_message("An internal error occured. Please try again.", 'error');
37  $OUTPUT->send('iframe');
38}
39
40if (!$savedraft) {
41  if (empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc'])
42    && empty($_POST['_subject']) && $_POST['_message']) {
43    $OUTPUT->show_message('sendingfailed', 'error');
44    $OUTPUT->send('iframe');
45  }
46
47  if(!empty($CONFIG['sendmail_delay'])) {
48    $wait_sec = time() - intval($CONFIG['sendmail_delay']) - intval($CONFIG['last_message_time']);
49    if($wait_sec < 0) {
50      $OUTPUT->show_message('senttooquickly', 'error', array('sec' => $wait_sec * -1));
51      $OUTPUT->send('iframe');
52    }
53  }
54}
55
56
57/****** message sending functions ********/
58
59// encrypt parts of the header
60function rcmail_encrypt_header($what)
61{
62  global $CONFIG, $RCMAIL;
63  if (!$CONFIG['http_received_header_encrypt'])
64  {
65    return $what;
66  }
67  return $RCMAIL->encrypt($what);
68}
69
70// get identity record
71function rcmail_get_identity($id)
72  {
73  global $USER, $OUTPUT;
74 
75  if ($sql_arr = $USER->get_identity($id))
76    {
77    $out = $sql_arr;
78    $out['mailto'] = $sql_arr['email'];
79   
80    // Special chars as defined by RFC 822 need to in quoted string (or escaped).
81    if (preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $sql_arr['name']))
82      $name = '"' . addcslashes($sql_arr['name'], '"') . '"';
83    else
84      $name = $sql_arr['name'];
85
86    $out['string'] = rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset());
87    if ($sql_arr['email'])
88      $out['string'] .= ' <' . $sql_arr['email'] . '>';
89
90    return $out;
91    }
92
93  return FALSE; 
94  }
95
96/**
97 * go from this:
98 * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
99 *
100 * to this:
101 *
102 * <IMG src="cid:smiley-cool.gif"/>
103 * ...
104 * ------part...
105 * Content-Type: image/gif
106 * Content-Transfer-Encoding: base64
107 * Content-ID: <smiley-cool.gif>
108 */
109function rcmail_attach_emoticons(&$mime_message)
110{
111  global $CONFIG;
112
113  $body = $mime_message->getHTMLBody();
114
115  // remove any null-byte characters before parsing
116  $body = preg_replace('/\x00/', '', $body);
117 
118  $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
119  $offset = 0;
120
121  // keep track of added images, so they're only added once
122  $included_images = array();
123
124  if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
125    foreach ($matches[1] as $m) {
126      // find emoticon image tags
127      if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
128        $image_name = $imatches[1];
129
130        // sanitize image name so resulting attachment doesn't leave images dir
131        $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
132        $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
133
134        if (! in_array($image_name, $included_images)) {
135          // add the image to the MIME message
136          if (! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name))
137            $OUTPUT->show_message("emoticonerror", 'error');
138          array_push($included_images, $image_name);
139        }
140
141        $body = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
142        $offset += strlen($img_file) - strlen($m[0]);
143      }
144    }
145  }
146
147  $mime_message->setHTMLBody($body);
148
149  return $body;
150}
151
152// parse email address input (and count addresses)
153function rcmail_email_input_format($mailto, $count=false)
154{
155  global $EMAIL_FORMAT_ERROR, $RECIPIENT_COUNT;
156
157  $regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/', '/(\S{1})(<\S+@\S+>)/U');
158  $replace = array(', ', ', ', '', ',', '\\1 \\2');
159
160  // replace new lines and strip ending ', ', make address input more valid
161  $mailto = trim(preg_replace($regexp, $replace, $mailto));
162
163  $result = array();
164  $items = rcube_explode_quoted_string(',', $mailto);
165
166  foreach($items as $item) {
167    $item = trim($item);
168    // address in brackets without name (do nothing)
169    if (preg_match('/^<\S+@\S+>$/', $item)) {
170      $result[] = $item;
171    // address without brackets and without name (add brackets)
172    } else if (preg_match('/^\S+@\S+$/', $item)) {
173      $result[] = '<'.$item.'>';
174    // address with name (handle name)
175    } else if (preg_match('/\S+@\S+>*$/', $item, $matches)) {
176      $address = $matches[0];
177      $name = str_replace($address, '', $item);
178      $name = trim($name);
179      if ($name && ($name[0] != '"' || $name[strlen($name)-1] != '"')
180          && preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name)) {
181          $name = '"'.addcslashes($name, '"').'"';
182      }
183      if (!preg_match('/^<\S+@\S+>$/', $address))
184        $address = '<'.$address.'>';
185
186      $result[] = $name.' '.$address;
187      $item = $address;
188    } else if (trim($item)) {
189      continue;
190    }
191
192    // check address format
193    $item = trim($item, '<>');
194    if ($item && !check_email($item)) {
195      $EMAIL_FORMAT_ERROR = $item;
196      return;
197    }
198  }
199
200  if ($count) {
201    $RECIPIENT_COUNT += count($result);
202  }
203
204  return implode(', ', $result);
205}
206
207/****** compose message ********/
208
209if (strlen($_POST['_draft_saveid']) > 3)
210  $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
211
212$message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.mt_rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host']));
213
214// set default charset
215$input_charset = $OUTPUT->get_charset();
216$message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
217
218$EMAIL_FORMAT_ERROR = NULL;
219$RECIPIENT_COUNT = 0;
220
221$mailto = rcmail_email_input_format(get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset), true);
222$mailcc = rcmail_email_input_format(get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset), true);
223$mailbcc = rcmail_email_input_format(get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset), true);
224
225if ($EMAIL_FORMAT_ERROR) {
226  $OUTPUT->show_message('emailformaterror', 'error', array('email' => $EMAIL_FORMAT_ERROR));
227  $OUTPUT->send('iframe');
228}
229
230if (empty($mailto) && !empty($mailcc)) {
231  $mailto = $mailcc;
232  $mailcc = null;
233}
234else if (empty($mailto))
235  $mailto = 'undisclosed-recipients:;';
236
237// get sender name and address
238$from = get_input_value('_from', RCUBE_INPUT_POST, true, $message_charset);
239$identity_arr = rcmail_get_identity($from);
240
241if (!$identity_arr && ($from = rcmail_email_input_format($from))) {
242  if (preg_match('/(\S+@\S+)/', $from, $m))
243    $identity_arr['mailto'] = $m[1];
244} else
245  $from = $identity_arr['mailto'];
246
247if (empty($identity_arr['string']))
248  $identity_arr['string'] = $from;
249
250// compose headers array
251$headers = array();
252
253// if configured, the Received headers goes to top, for good measure
254if ($CONFIG['http_received_header'])
255{
256  $nldlm = $RCMAIL->config->header_delimiter() . "\t";
257  // FROM/VIA
258  $http_header = 'from ';
259  if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
260    $host = $_SERVER['HTTP_X_FORWARDED_FOR'];
261    $hostname = gethostbyaddr($host);
262    if ($CONFIG['http_received_header_encrypt']) {
263      $http_header .= rcmail_encrypt_header($hostname);
264      if ($host != $hostname)
265        $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
266    } else {
267      $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
268      if ($host != $hostname)
269        $http_header .= ' (['. $host .'])';
270    }
271    $http_header .= $nldlm . ' via ';
272  }
273  $host = $_SERVER['REMOTE_ADDR'];
274  $hostname = gethostbyaddr($host);
275  if ($CONFIG['http_received_header_encrypt']) {
276    $http_header .= rcmail_encrypt_header($hostname);
277    if ($host != $hostname)
278      $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
279  } else {
280    $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
281    if ($host != $hostname)
282      $http_header .= ' (['. $host .'])';
283  }
284  // BY
285  $http_header .= $nldlm . 'by ' . $_SERVER['HTTP_HOST'];
286  // WITH
287  $http_header .= $nldlm . 'with HTTP (' . $_SERVER['SERVER_PROTOCOL'] .
288      ' '.$_SERVER['REQUEST_METHOD'] . '); ' . date('r');
289  $http_header = wordwrap($http_header, 69, $nldlm);
290
291  $headers['Received'] = $http_header;
292}
293
294$headers['Date'] = date('r');
295$headers['From'] = rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset);
296$headers['To'] = $mailto;
297
298// additional recipients
299if (!empty($mailcc))
300  $headers['Cc'] = $mailcc;
301
302if (!empty($mailbcc))
303  $headers['Bcc'] = $mailbcc;
304 
305if (!empty($identity_arr['bcc'])) {
306  $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
307  $RECIPIENT_COUNT ++;
308}
309
310if (($max_recipients = (int) $RCMAIL->config->get('max_recipients')) > 0) {
311  if ($RECIPIENT_COUNT > $max_recipients) {
312    $OUTPUT->show_message('toomanyrecipients', 'error', array('max' => $max_recipients));
313    $OUTPUT->send('iframe');
314  }
315}
316
317// add subject
318$headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, TRUE, $message_charset));
319
320if (!empty($identity_arr['organization']))
321  $headers['Organization'] = $identity_arr['organization'];
322
323if (!empty($_POST['_replyto']))
324  $headers['Reply-To'] = rcmail_email_input_format(get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
325else if (!empty($identity_arr['reply-to']))
326  $headers['Reply-To'] = $identity_arr['reply-to'];
327
328if (!empty($_SESSION['compose']['reply_msgid']))
329  $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
330 
331// remember reply/forward UIDs in special headers
332if (!empty($_SESSION['compose']['reply_uid']) && $savedraft)
333  $headers['X-Draft-Info'] = array('type' => 'reply', 'uid' => $_SESSION['compose']['reply_uid']);
334else if (!empty($_SESSION['compose']['forward_uid']) && $savedraft)
335  $headers['X-Draft-Info'] = array('type' => 'forward', 'uid' => $_SESSION['compose']['forward_uid']);
336
337if (!empty($_SESSION['compose']['references']))
338  $headers['References'] = $_SESSION['compose']['references'];
339
340if (!empty($_POST['_priority']))
341  {
342  $priority = intval($_POST['_priority']);
343  $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
344  if ($str_priority = $a_priorities[$priority])
345    $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
346  }
347
348if (!empty($_POST['_receipt']))
349  {
350  $headers['Return-Receipt-To'] = $identity_arr['string'];
351  $headers['Disposition-Notification-To'] = $identity_arr['string'];
352  }
353
354// additional headers
355$headers['Message-ID'] = $message_id;
356$headers['X-Sender'] = $from;
357
358if (is_array($headers['X-Draft-Info']))
359  $headers['X-Draft-Info'] = rcmail_draftinfo_encode($headers['X-Draft-Info'] + array('folder' => $_SESSION['compose']['mailbox']));
360
361if (!empty($CONFIG['useragent']))
362  $headers['User-Agent'] = $CONFIG['useragent'];
363
364// exec hook for header checking and manipulation
365$data = $RCMAIL->plugins->exec_hook('outgoing_message_headers', array('headers' => $headers));
366
367// sending aborted by plugin
368if ($data['abort'] && !$savedraft) {
369  $OUTPUT->show_message($data['message'] ? $data['message'] : 'sendingfailed');
370  $OUTPUT->send('iframe');
371}
372else
373  $headers = $data['headers'];
374
375
376$isHtml = (bool) get_input_value('_is_html', RCUBE_INPUT_POST);
377
378// fetch message body
379$message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
380
381if (!$savedraft) {
382  if ($isHtml) {
383    // remove signature's div ID
384    $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
385
386    // add inline css for blockquotes
387    $bstyle = 'padding-left:5px; border-left:#1010ff 2px solid; margin-left:5px; width:100%';
388    $message_body = preg_replace('/<blockquote>/',
389        '<blockquote type="cite" style="'.$bstyle.'">', $message_body);
390  }
391  // generic footer for all messages
392  if (!empty($CONFIG['generic_message_footer'])) {
393    $footer = file_get_contents(realpath($CONFIG['generic_message_footer']));
394    $footer = rcube_charset_convert($footer, RCMAIL_CHARSET, $message_charset);
395  }
396}
397
398// set line length for body wrapping
399$LINE_LENGTH = $RCMAIL->config->get('line_length', 72);
400
401// Since we can handle big messages with disk usage, we need more time to work
402@set_time_limit(0);
403
404// create PEAR::Mail_mime instance
405$MAIL_MIME = new Mail_mime($RCMAIL->config->header_delimiter());
406
407// Check if we have enough memory to handle the message in it
408// It's faster than using files, so we'll do this if we only can
409if (is_array($_SESSION['compose']['attachments']) && $CONFIG['smtp_server']
410  && ($mem_limit = parse_bytes(ini_get('memory_limit'))))
411{
412  $memory = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
413
414  foreach ($_SESSION['compose']['attachments'] as $id => $attachment)
415    $memory += $attachment['size'];
416
417  // Yeah, Net_SMTP needs up to 12x more memory, 1.33 is for base64
418  if ($memory * 1.33 * 12 > $mem_limit)
419    $MAIL_MIME->setParam('delay_file_io', true);
420}
421
422// For HTML-formatted messages, construct the MIME message with both
423// the HTML part and the plain-text part
424
425if ($isHtml) {
426  $plugin = $RCMAIL->plugins->exec_hook('outgoing_message_body', array('body' => $message_body, 'type' => 'html', 'message' => $MAIL_MIME));
427  $MAIL_MIME->setHTMLBody($plugin['body'] . ($footer ? "\r\n<pre>".$footer.'</pre>' : ''));
428
429  // add a plain text version of the e-mail as an alternative part.
430  $h2t = new html2text($plugin['body'], false, true, 0);
431  $plainTextPart = rc_wordwrap($h2t->get_text(), $LINE_LENGTH, "\r\n") . ($footer ? "\r\n".$footer : '');
432  $plainTextPart = wordwrap($plainTextPart, 998, "\r\n", true);
433  if (!strlen($plainTextPart)) {
434    // empty message body breaks attachment handling in drafts
435    $plainTextPart = "\r\n";
436  }
437  $plugin = $RCMAIL->plugins->exec_hook('outgoing_message_body', array('body' => $plainTextPart, 'type' => 'alternative', 'message' => $MAIL_MIME));
438  $MAIL_MIME->setTXTBody($plugin['body']);
439
440  // look for "emoticon" images from TinyMCE and copy into message as attachments
441  $message_body = rcmail_attach_emoticons($MAIL_MIME);
442}
443else {
444  if ($footer)
445    $message_body .= "\r\n" . $footer;
446 
447  // compose format=flowed content if enabled and not a reply message
448  if (empty($_SESSION['compose']['reply_msgid']) && ($flowed = $RCMAIL->config->get('send_format_flowed', true)))
449    $message_body = rcube_message::format_flowed($message_body, $LINE_LENGTH);
450  else
451    $message_body = rc_wordwrap($message_body, $LINE_LENGTH, "\r\n");
452 
453  $message_body = wordwrap($message_body, 998, "\r\n", true);
454  if (!strlen($message_body)) {
455    // empty message body breaks attachment handling in drafts
456    $message_body = "\r\n";
457  }
458  $plugin = $RCMAIL->plugins->exec_hook('outgoing_message_body', array('body' => $message_body, 'type' => 'plain', 'message' => $MAIL_MIME));
459  $MAIL_MIME->setTXTBody($plugin['body'], false, true);
460}
461
462// add stored attachments, if any
463if (is_array($_SESSION['compose']['attachments']))
464{
465  foreach ($_SESSION['compose']['attachments'] as $id => $attachment) {
466    // This hook retrieves the attachment contents from the file storage backend
467    $attachment = $RCMAIL->plugins->exec_hook('get_attachment', $attachment);
468
469    $dispurl = '/\ssrc\s*=\s*[\'"]*\S+display-attachment\S+file=rcmfile' . preg_quote($attachment['id']) . '[\s\'"]\s*/';
470    $message_body = $MAIL_MIME->getHTMLBody();
471    if ($isHtml && (preg_match($dispurl, $message_body) > 0)) {
472      $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'" ', $message_body);
473      $MAIL_MIME->setHTMLBody($message_body);
474
475      if ($attachment['data'])
476        $MAIL_MIME->addHTMLImage($attachment['data'], $attachment['mimetype'], $attachment['name'], false);
477      else
478        $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name'], true);
479    }
480    else {
481      $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
482      $file = $attachment['data'] ? $attachment['data'] : $attachment['path'];
483
484      // .eml attachments send inline
485      $MAIL_MIME->addAttachment($file,
486        $ctype,
487        $attachment['name'],
488        ($attachment['data'] ? false : true),
489        ($ctype == 'message/rfc822' ? '8bit' : 'base64'),
490        ($ctype == 'message/rfc822' ? 'inline' : 'attachment'),
491        $message_charset, '', '',
492        $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
493        $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
494      );
495    }
496  }
497}
498
499// choose transfer encoding for plain/text body
500if (preg_match('/[^\x00-\x7F]/', $MAIL_MIME->getTXTBody()))
501  $transfer_encoding = $RCMAIL->config->get('force_7bit') ? 'quoted-printable' : '8bit';
502else
503  $transfer_encoding = '7bit';
504
505// encoding settings for mail composing
506$MAIL_MIME->setParam('text_encoding', $transfer_encoding);
507$MAIL_MIME->setParam('html_encoding', 'quoted-printable');
508$MAIL_MIME->setParam('head_encoding', 'quoted-printable');
509$MAIL_MIME->setParam('head_charset', $message_charset);
510$MAIL_MIME->setParam('html_charset', $message_charset);
511$MAIL_MIME->setParam('text_charset', $message_charset . ($flowed ? ";\r\n format=flowed" : ''));
512
513// encoding subject header with mb_encode provides better results with asian characters
514if (function_exists('mb_encode_mimeheader'))
515{
516  mb_internal_encoding($message_charset);
517  $headers['Subject'] = mb_encode_mimeheader($headers['Subject'],
518    $message_charset, 'Q', $RCMAIL->config->header_delimiter(), 8);
519  mb_internal_encoding(RCMAIL_CHARSET);
520}
521
522// pass headers to message object
523$MAIL_MIME->headers($headers);
524
525// Begin SMTP Delivery Block
526if (!$savedraft)
527{
528  // check for 'From' address (identity may be incomplete)
529  if ($identity_arr && !$identity_arr['mailto']) {
530    $OUTPUT->show_message('nofromaddress', 'error');
531    $OUTPUT->send('iframe');
532  }
533
534  $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto, $smtp_error, $mailbody_file);
535
536  // return to compose page if sending failed
537  if (!$sent)
538    {
539    // remove temp file
540    if ($mailbody_file) {
541      unlink($mailbody_file);
542      }
543
544    if ($smtp_error)
545      $OUTPUT->show_message($smtp_error['label'], 'error', $smtp_error['vars']);
546    else
547      $OUTPUT->show_message('sendingfailed', 'error');
548    $OUTPUT->send('iframe');
549    }
550
551  // save message sent time
552  if (!empty($CONFIG['sendmail_delay']))
553    $RCMAIL->user->save_prefs(array('last_message_time' => time()));
554 
555  // set replied/forwarded flag
556  if ($_SESSION['compose']['reply_uid'])
557    $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED', $_SESSION['compose']['mailbox']);
558  else if ($_SESSION['compose']['forward_uid'])
559    $IMAP->set_flag($_SESSION['compose']['forward_uid'], 'FORWARDED', $_SESSION['compose']['mailbox']);
560
561} // End of SMTP Delivery Block
562
563
564// Determine which folder to save message
565if ($savedraft)
566  $store_target = $CONFIG['drafts_mbox'];
567else   
568  $store_target = isset($_POST['_store_target']) ? get_input_value('_store_target', RCUBE_INPUT_POST) : $CONFIG['sent_mbox'];
569
570if ($store_target)
571  {
572  // check if folder is subscribed
573  if ($IMAP->mailbox_exists($store_target, true))
574    $store_folder = true;
575  // folder may be existing but not subscribed (#1485241)
576  else if (!$IMAP->mailbox_exists($store_target))
577    $store_folder = $IMAP->create_mailbox($store_target, true);
578  else if ($IMAP->subscribe($store_target))
579    $store_folder = true;
580
581  // append message to sent box
582  if ($store_folder) {
583
584    // message body in file
585    if ($mailbody_file || $MAIL_MIME->getParam('delay_file_io')) {
586      $headers = $MAIL_MIME->txtHeaders();
587     
588      // file already created
589      if ($mailbody_file)
590        $msg = $mailbody_file;
591      else {
592        $temp_dir = $RCMAIL->config->get('temp_dir');
593        $mailbody_file = tempnam($temp_dir, 'rcmMsg');
594        if (!PEAR::isError($msg = $MAIL_MIME->saveMessageBody($mailbody_file)))
595          $msg = $mailbody_file;
596        }
597      }
598    else {
599      $msg = $MAIL_MIME->getMessage();
600      $headers = '';
601      }
602
603    if (PEAR::isError($msg))
604      raise_error(array('code' => 600, 'type' => 'php',
605            'file' => __FILE__, 'line' => __LINE__,
606            'message' => "Could not create message: ".$msg->getMessage()),
607            TRUE, FALSE);
608    else {
609      $saved = $IMAP->save_message($store_target, $msg, $headers, $mailbody_file ? true : false);
610      }
611
612    if ($mailbody_file) {
613      unlink($mailbody_file);
614      $mailbody_file = null;
615      }
616
617    // raise error if saving failed
618    if (!$saved) {
619      raise_error(array('code' => 800, 'type' => 'imap',
620            'file' => __FILE__, 'line' => __LINE__,
621            'message' => "Could not save message in $store_target"), TRUE, FALSE);
622   
623      if ($savedraft) {
624        $OUTPUT->show_message('errorsaving', 'error');
625        $OUTPUT->send('iframe');
626        }
627      }
628    }
629
630  if ($olddraftmessageid)
631    {
632    // delete previous saved draft
633    $a_deleteid = $IMAP->search_once($CONFIG['drafts_mbox'],
634        'HEADER Message-ID '.$olddraftmessageid, true);
635    $deleted = $IMAP->delete_message($a_deleteid, $CONFIG['drafts_mbox']);
636
637    // raise error if deletion of old draft failed
638    if (!$deleted)
639      raise_error(array('code' => 800, 'type' => 'imap',
640                'file' => __FILE__, 'line' => __LINE__,
641                'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
642    }
643  }
644// remove temp file
645else if ($mailbody_file) {
646  unlink($mailbody_file);
647  }
648
649
650if ($savedraft)
651  {
652  $msgid = strtr($message_id, array('>' => '', '<' => ''));
653 
654  // remember new draft-uid
655  $draftuids = $IMAP->search_once($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$msgid, true);
656  $_SESSION['compose']['param']['_draft_uid'] = $draftuids[0];
657
658  // display success
659  $OUTPUT->show_message('messagesaved', 'confirmation');
660
661  // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
662  $OUTPUT->command('set_draft_id', $msgid);
663  $OUTPUT->command('compose_field_hash', true);
664
665  // start the auto-save timer again
666  $OUTPUT->command('auto_save_start');
667
668  $OUTPUT->send('iframe');
669  }
670else
671  {
672  rcmail_compose_cleanup();
673
674  if ($store_folder && !$saved)
675    $OUTPUT->command('sent_successfully', 'error', rcube_label('errorsavingsent'));
676  else
677    $OUTPUT->command('sent_successfully', 'confirmation', rcube_label('messagesent'));
678  $OUTPUT->send('iframe');
679  }
680
681?>
Note: See TracBrowser for help on using the repository browser.