source: github/program/steps/mail/sendmail.inc @ 1d8cbca

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