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