]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/sendmail.inc
Imported Upstream version 0.3
[roundcube.git] / program / steps / mail / sendmail.inc
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-2009, 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: sendmail.inc 2713 2009-07-06 09:13:10Z alec $
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
32 if (!isset($_SESSION['compose']['id'])) {
33   raise_error(array('code' => 500, 'type' => 'smtp', '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
39 if (!$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 // encrypt parts of the header
59 function rcmail_encrypt_header($what)
60 {
61   global $CONFIG, $RCMAIL;
62   if (!$CONFIG['http_received_header_encrypt'])
63   {
64     return $what;
65   }
66   return $RCMAIL->encrypt($what);
67 }
68
69 // get identity record
70 function rcmail_get_identity($id)
71   {
72   global $USER, $OUTPUT;
73   
74   if ($sql_arr = $USER->get_identity($id))
75     {
76     $out = $sql_arr;
77     $out['mailto'] = $sql_arr['email'];
78     
79     // Special chars as defined by RFC 822 need to in quoted string (or escaped).
80     if (preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $sql_arr['name']))
81       $name = '"' . addcslashes($sql_arr['name'], '"') . '"';
82     else
83       $name = $sql_arr['name'];
84
85     $out['string'] = rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset());
86     if ($sql_arr['email'])
87       $out['string'] .= ' <' . $sql_arr['email'] . '>';
88
89     return $out;
90     }
91
92   return FALSE;  
93   }
94
95 /**
96  * go from this:
97  * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
98  *
99  * to this:
100  *
101  * <IMG src="cid:smiley-cool.gif"/>
102  * ...
103  * ------part...
104  * Content-Type: image/gif
105  * Content-Transfer-Encoding: base64
106  * Content-ID: <smiley-cool.gif>
107  */
108 function rcmail_attach_emoticons(&$mime_message)
109 {
110   global $CONFIG;
111
112   $body = $mime_message->getHtmlBody();
113
114   // remove any null-byte characters before parsing
115   $body = preg_replace('/\x00/', '', $body);
116   
117   $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
118   $offset = 0;
119
120   // keep track of added images, so they're only added once
121   $included_images = array();
122
123   if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
124     foreach ($matches[1] as $m) {
125       // find emoticon image tags
126       if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
127         $image_name = $imatches[1];
128
129         // sanitize image name so resulting attachment doesn't leave images dir
130         $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
131         $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
132
133         if (! in_array($image_name, $included_images)) {
134           // add the image to the MIME message
135           if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name))
136             $OUTPUT->show_message("emoticonerror", 'error');
137           array_push($included_images, $image_name);
138         }
139
140         $body = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
141         $offset += strlen($img_file) - strlen($m[0]);
142       }
143     }
144   }
145
146   $mime_message->setHTMLBody($body);
147
148   return $body;
149 }
150
151 // parse email address input
152 function rcmail_email_input_format($mailto)
153 {
154   $regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/', '/(\S{1})(<\S+@\S+>)/U');
155   $replace = array(', ', ', ', '', ',', '\\1 \\2');
156
157   // replace new lines and strip ending ', ', make address input more valid
158   $mailto = trim(preg_replace($regexp, $replace, $mailto));
159
160   $result = array();
161   $items = rcube_explode_quoted_string(',', $mailto);
162
163   foreach($items as $item) {
164     $item = trim($item);
165     // address in brackets without name (do nothing)
166     if (preg_match('/^<\S+@\S+>$/', $item)) {
167       $result[] = $item;
168     // address without brackets and without name (add brackets)
169     } else if (preg_match('/^\S+@\S+$/', $item)) {
170       $result[] = '<'.$item.'>';
171     // address with name (handle name)
172     } else if (preg_match('/\S+@\S+>*$/', $item, $matches)) {
173       $address = $matches[0];
174       $name = str_replace($address, '', $item);
175       $name = trim($name);
176       if ($name && ($name[0] != '"' || $name[strlen($name)-1] != '"')
177           && preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name)) {
178           $name = '"'.addcslashes($name, '"').'"';
179       }
180       if (!preg_match('/^<\S+@\S+>$/', $address))
181         $address = '<'.$address.'>';
182
183       $result[] = $name.' '.$address;
184     } else if (trim($item)) {
185       // @TODO: handle errors
186     }
187   }
188
189   return implode(', ', $result);
190 }
191
192 /****** compose message ********/
193
194 if (strlen($_POST['_draft_saveid']) > 3)
195   $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
196
197 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host']));
198
199 // set default charset
200 $input_charset = $OUTPUT->get_charset();
201 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
202
203 $mailto = rcmail_email_input_format(get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
204 $mailcc = rcmail_email_input_format(get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
205 $mailbcc = rcmail_email_input_format(get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
206
207 if (empty($mailto) && !empty($mailcc)) {
208   $mailto = $mailcc;
209   $mailcc = null;
210 }
211 else if (empty($mailto))
212   $mailto = 'undisclosed-recipients:;';
213
214 // get sender name and address
215 $from = get_input_value('_from', RCUBE_INPUT_POST, true, $message_charset);
216 $identity_arr = rcmail_get_identity($from);
217
218 if (!$identity_arr && ($from = rcmail_email_input_format($from))) {
219   if (preg_match('/(\S+@\S+)/', $from, $m))
220     $identity_arr['mailto'] = $m[1];
221 } else
222   $from = $identity_arr['mailto'];
223
224 if (empty($identity_arr['string']))
225   $identity_arr['string'] = $from;
226
227 // compose headers array
228 $headers = array();
229
230 // if configured, the Received headers goes to top, for good measure
231 if ($CONFIG['http_received_header'])
232 {
233   $nldlm = $RCMAIL->config->header_delimiter() . "\t";
234   $http_header = 'from ';
235   if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
236     $http_header .= rcmail_encrypt_header(gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR'])) .
237       ' [' . rcmail_encrypt_header($_SERVER['HTTP_X_FORWARDED_FOR']) . ']';
238     $http_header .= $nldlm . ' via ';
239   }
240   $http_header .= rcmail_encrypt_header(gethostbyaddr($_SERVER['REMOTE_ADDR'])) .
241       ' [' . rcmail_encrypt_header($_SERVER['REMOTE_ADDR']) .']';
242   $http_header .= $nldlm . 'with ' . $_SERVER['SERVER_PROTOCOL'] .
243       ' ('.$_SERVER['REQUEST_METHOD'] . '); ' . date('r');
244   $http_header = wordwrap($http_header, 69, $nldlm);
245   $headers['Received'] = $http_header;
246 }
247
248 $headers['Date'] = date('r');
249 $headers['From'] = rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset);
250 $headers['To'] = $mailto;
251
252 // additional recipients
253 if (!empty($mailcc))
254   $headers['Cc'] = $mailcc;
255
256 if (!empty($mailbcc))
257   $headers['Bcc'] = $mailbcc;
258   
259 if (!empty($identity_arr['bcc']))
260   $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
261
262 // add subject
263 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, TRUE, $message_charset));
264
265 if (!empty($identity_arr['organization']))
266   $headers['Organization'] = $identity_arr['organization'];
267
268 if (!empty($_POST['_replyto']))
269   $headers['Reply-To'] = rcmail_email_input_format(get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
270 else if (!empty($identity_arr['reply-to']))
271   $headers['Reply-To'] = $identity_arr['reply-to'];
272
273 if (!empty($_SESSION['compose']['reply_msgid']))
274   $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
275
276 if (!empty($_SESSION['compose']['references']))
277   $headers['References'] = $_SESSION['compose']['references'];
278
279 if (!empty($_POST['_priority']))
280   {
281   $priority = intval($_POST['_priority']);
282   $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
283   if ($str_priority = $a_priorities[$priority])
284     $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
285   }
286
287 if (!empty($_POST['_receipt']))
288   {
289   $headers['Return-Receipt-To'] = $identity_arr['string'];
290   $headers['Disposition-Notification-To'] = $identity_arr['string'];
291   }
292
293 // additional headers
294 $headers['Message-ID'] = $message_id;
295 $headers['X-Sender'] = $from;
296
297 if (!empty($CONFIG['useragent']))
298   $headers['User-Agent'] = $CONFIG['useragent'];
299
300 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
301 $isHtml = ($isHtmlVal == "1");
302
303 // fetch message body
304 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
305
306 if (!$savedraft) {
307   // remove signature's div ID
308   if ($isHtml)
309     $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
310
311   // generic footer for all messages
312   if (!empty($CONFIG['generic_message_footer'])) {
313     $footer = file_get_contents(realpath($CONFIG['generic_message_footer']));
314     $footer = rcube_charset_convert($footer, RCMAIL_CHARSET, $message_charset);
315   }
316 }
317
318 // create extended PEAR::Mail_mime instance
319 $MAIL_MIME = new rcube_mail_mime($RCMAIL->config->header_delimiter());
320
321 // For HTML-formatted messages, construct the MIME message with both
322 // the HTML part and the plain-text part
323
324 if ($isHtml) {
325   $plugin = $RCMAIL->plugins->exec_hook('outgoing_message_body', array('body' => $message_body, 'type' => 'html', 'message' => $MAIL_MIME));
326   $MAIL_MIME->setHTMLBody($plugin['body'] . ($footer ? "\r\n<pre>".$footer.'</pre>' : ''));
327
328   // add a plain text version of the e-mail as an alternative part.
329   $h2t = new html2text($plugin['body'], false, true, 0);
330   $plainTextPart = rc_wordwrap($h2t->get_text(), 75, "\r\n") . ($footer ? "\r\n".$footer : '');
331   $plainTextPart = wordwrap($plainTextPart, 998, "\r\n", true);
332   if (!strlen($plainTextPart)) {
333     // empty message body breaks attachment handling in drafts 
334     $plainTextPart = "\r\n"; 
335   }
336   $plugin = $RCMAIL->plugins->exec_hook('outgoing_message_body', array('body' => $plainTextPart, 'type' => 'alternative', 'message' => $MAIL_MIME));
337   $MAIL_MIME->setTXTBody($plugin['body']);
338
339   // look for "emoticon" images from TinyMCE and copy into message as attachments
340   $message_body = rcmail_attach_emoticons($MAIL_MIME);
341 }
342 else
343   {
344   $message_body = rc_wordwrap($message_body, 75, "\r\n");
345   if ($footer)
346     $message_body .= "\r\n" . $footer;
347   $message_body = wordwrap($message_body, 998, "\r\n", true);
348   if (!strlen($message_body)) { 
349     // empty message body breaks attachment handling in drafts 
350     $message_body = "\r\n"; 
351   }
352   $plugin = $RCMAIL->plugins->exec_hook('outgoing_message_body', array('body' => $message_body, 'type' => 'plain', 'message' => $MAIL_MIME));
353   $MAIL_MIME->setTXTBody($plugin['body'], false, true);
354 }
355
356 // chose transfer encoding
357 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
358 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
359
360 // add stored attachments, if any
361 if (is_array($_SESSION['compose']['attachments'])) {
362   foreach ($_SESSION['compose']['attachments'] as $id => $attachment) {
363     // This hook retrieves the attachment contents from the file storage backend
364     $attachment = $RCMAIL->plugins->exec_hook('get_attachment', $attachment);
365
366     $dispurl = '/\ssrc\s*=\s*[\'"]*\S+display-attachment\S+file=rcmfile' . preg_quote($attachment['id']) . '[\s\'"]\s*/';
367     $message_body = $MAIL_MIME->getHTMLBody();
368     if ($isHtml && (preg_match($dispurl, $message_body) > 0)) {
369       $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'" ', $message_body);
370       $MAIL_MIME->setHTMLBody($message_body);
371       
372       if ($attachment['data'])
373         $MAIL_MIME->addHTMLImage($attachment['data'], $attachment['mimetype'], $attachment['name'], false);
374       else
375         $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name'], true);
376     }
377     else {
378       $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
379       $file = $attachment['data'] ? $attachment['data'] : $attachment['path'];
380
381       // .eml attachments send inline
382       $MAIL_MIME->addAttachment($file,
383         $ctype, 
384         $attachment['name'],
385         ($attachment['data'] ? false : true),
386         ($ctype == 'message/rfc822' ? $transfer_encoding : 'base64'),
387         ($ctype == 'message/rfc822' ? 'inline' : 'attachment'),
388         $message_charset, '', '', 
389         $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
390         $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
391       );
392     }
393   }
394 }
395
396 // add submitted attachments
397 if (is_array($_FILES['_attachments']['tmp_name'])) {
398   foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath) {
399     $ctype = $files['type'][$i];
400     $ctype = str_replace('image/pjpeg', 'image/jpeg', $ctype); // #1484914
401     
402     $MAIL_MIME->addAttachment($filepath, $ctype, $files['name'][$i], true,
403       $ctype == 'message/rfc822' ? $transfer_encoding : 'base64',
404       'attachment', $message_charset, '', '', 
405       $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
406       $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
407     );
408   }
409 }
410
411 // encoding settings for mail composing
412 $MAIL_MIME->setParam(array(
413   'text_encoding' => $transfer_encoding,
414   'html_encoding' => 'quoted-printable',
415   'head_encoding' => 'quoted-printable',
416   'head_charset'  => $message_charset,
417   'html_charset'  => $message_charset,
418   'text_charset'  => $message_charset,
419 ));
420
421 $data = $RCMAIL->plugins->exec_hook('outgoing_message_headers', array('headers' => $headers));
422 $headers = $data['headers'];
423
424 // encoding subject header with mb_encode provides better results with asian characters
425 if (function_exists("mb_encode_mimeheader"))
426 {
427   mb_internal_encoding($message_charset);
428   $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
429   mb_internal_encoding(RCMAIL_CHARSET);
430 }
431
432 // pass headers to message object
433 $MAIL_MIME->headers($headers);
434
435 // Begin SMTP Delivery Block 
436 if (!$savedraft)
437 {
438   // check for 'From' address (identity may be incomplete)
439   if ($identity_arr && !$identity_arr['mailto']) {
440     $OUTPUT->show_message('nofromaddress', 'error');
441     $OUTPUT->send('iframe'); 
442   }
443
444   $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto, $smtp_error);
445   
446   // return to compose page if sending failed
447   if (!$sent)
448     {
449     if ($smtp_error)
450       $OUTPUT->show_message($smtp_error['label'], 'error', $smtp_error['vars']); 
451     else
452       $OUTPUT->show_message('sendingfailed', 'error'); 
453     $OUTPUT->send('iframe');
454     }
455
456   // save message sent time
457   if (!empty($CONFIG['sendmail_delay']))
458     $RCMAIL->user->save_prefs(array('last_message_time' => time()));
459   
460   // set replied/forwarded flag
461   if ($_SESSION['compose']['reply_uid'])
462     $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED', $_SESSION['compose']['mailbox']);
463   else if ($_SESSION['compose']['forward_uid'])
464     $IMAP->set_flag($_SESSION['compose']['forward_uid'], 'FORWARDED', $_SESSION['compose']['mailbox']);
465
466 } // End of SMTP Delivery Block
467
468
469
470 // Determine which folder to save message
471 if ($savedraft)
472   $store_target = $CONFIG['drafts_mbox'];
473 else    
474   $store_target = isset($_POST['_store_target']) ? get_input_value('_store_target', RCUBE_INPUT_POST) : $CONFIG['sent_mbox'];
475
476 if ($store_target)
477   {
478   // check if mailbox exists
479   if (!in_array_nocase($store_target, $IMAP->list_mailboxes()))
480     {
481       // folder may be existing but not subscribed (#1485241)
482       if (!in_array_nocase($store_target, $IMAP->list_unsubscribed()))
483         $store_folder = $IMAP->create_mailbox($store_target, TRUE);
484       else if ($IMAP->subscribe($store_target))
485         $store_folder = TRUE;
486     }
487   else
488     $store_folder = TRUE;
489   
490   // append message to sent box
491   if ($store_folder)
492     $saved = $IMAP->save_message($store_target, $MAIL_MIME->getMessage());
493
494   // raise error if saving failed
495   if (!$saved)
496     {
497     raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
498                       'message' => "Could not save message in $store_target"), TRUE, FALSE);
499     
500     if ($savedraft) {
501       $OUTPUT->show_message('errorsaving', 'error');
502       $OUTPUT->send('iframe');
503       }
504     }
505
506   if ($olddraftmessageid)
507     {
508     // delete previous saved draft
509     $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$olddraftmessageid);
510
511     $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0], $CONFIG['drafts_mbox']), $CONFIG['drafts_mbox']);
512
513     // raise error if deletion of old draft failed
514     if (!$deleted)
515       raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
516                         'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
517     }
518   }
519
520 if ($savedraft)
521   {
522   $msgid = strtr($message_id, array('>' => '', '<' => ''));
523   
524   // remember new draft-uid
525   $draftids = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$msgid);
526   $_SESSION['compose']['param']['_draft_uid'] = $IMAP->get_uid($draftids[0], $CONFIG['drafts_mbox']);
527
528   // display success
529   $OUTPUT->show_message('messagesaved', 'confirmation');
530
531   // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
532   $OUTPUT->command('set_draft_id', $msgid);
533   $OUTPUT->command('compose_field_hash', true);
534
535   // start the auto-save timer again
536   $OUTPUT->command('auto_save_start');
537
538   $OUTPUT->send('iframe');
539   }
540 else
541   {
542   rcmail_compose_cleanup();
543
544   if ($store_folder && !$saved)
545     $OUTPUT->command('sent_successfully', 'error', rcube_label('errorsavingsent'));
546   else
547     $OUTPUT->command('sent_successfully', 'confirmation', rcube_label('messagesent'));
548   $OUTPUT->send('iframe');
549   }
550
551 ?>