source: github/program/steps/mail/sendmail.inc @ 53604a0

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