]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/sendmail.inc
Imported Upstream version 0.2~alpha
[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-2008, 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 1344 2008-04-30 08:21:42Z thomasb $
20
21 */
22
23
24 if (!isset($_SESSION['compose']['id']))
25   {
26   rcmail_overwrite_action('list');
27   return;
28   }
29
30
31 /****** message sending functions ********/
32
33
34 // get identity record
35 function rcmail_get_identity($id)
36   {
37   global $USER, $OUTPUT;
38   
39   if ($sql_arr = $USER->get_identity($id))
40     {
41     $out = $sql_arr;
42     $out['mailto'] = $sql_arr['email'];
43     $name = strpos($sql_arr['name'], ",") ? '"'.$sql_arr['name'].'"' : $sql_arr['name'];
44     $out['string'] = sprintf('%s <%s>',
45                              rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset()),
46                              $sql_arr['email']);
47     return $out;
48     }
49
50   return FALSE;  
51   }
52
53 /**
54  * go from this:
55  * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
56  *
57  * to this:
58  *
59  * <IMG src="cid:smiley-cool.gif"/>
60  * ...
61  * ------part...
62  * Content-Type: image/gif
63  * Content-Transfer-Encoding: base64
64  * Content-ID: <smiley-cool.gif>
65  */
66 function rcmail_attach_emoticons(&$mime_message)
67 {
68   global $CONFIG;
69
70   $htmlContents = $mime_message->getHtmlBody();
71
72   // remove any null-byte characters before parsing
73   $body = preg_replace('/\x00/', '', $htmlContents);
74   
75   $last_img_pos = 0;
76
77   $searchstr = 'program/js/tiny_mce/plugins/emotions/images/';
78
79   // keep track of added images, so they're only added once
80   $included_images = array();
81
82   // find emoticon image tags
83   while ($pos = strpos($body, $searchstr, $last_img_pos))
84     {
85     $pos2 = strpos($body, '"', $pos);
86     $body_pre = substr($body, 0, $pos);
87     $image_name = substr($body,
88                          $pos + strlen($searchstr),
89                          $pos2 - ($pos + strlen($searchstr)));
90     // sanitize image name so resulting attachment doesn't leave images dir
91     $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i','',$image_name);
92
93     $body_post = substr($body, $pos2);
94
95     if (! in_array($image_name, $included_images))
96       {
97       // add the image to the MIME message
98       $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
99       if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, '_' . $image_name))
100         $OUTPUT->show_message("emoticonerror", 'error');
101
102       array_push($included_images, $image_name);
103       }
104
105     $body = $body_pre . 'cid:_' . $image_name . $body_post;
106
107     $last_img_pos = $pos2;
108     }
109    
110   $mime_message->setHTMLBody($body);
111 }
112
113 if (strlen($_POST['_draft_saveid']) > 3)
114   $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
115
116 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), rcmail_mail_domain($_SESSION['imap_host']));
117 $savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
118
119 // remove all scripts and act as called in frame
120 $OUTPUT->reset();
121 $OUTPUT->framed = TRUE;
122
123
124 /****** check submission and compose message ********/
125
126
127 if (!$savedraft && empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc']) && empty($_POST['_subject']) && $_POST['_message'])
128   {
129   $OUTPUT->show_message("sendingfailed", 'error');
130   $OUTPUT->send('iframe');
131   return;
132   }
133
134
135 // set default charset
136 $input_charset = $OUTPUT->get_charset();
137 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
138
139 $mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/');
140 $mailto_replace = array(', ', ', ', '', ',');
141
142 // replace new lines and strip ending ', '
143 $mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
144 $mailcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
145 $mailbcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
146
147 if (empty($mailto) && !empty($mailcc)) {
148   $mailto = $mailcc;
149   $mailcc = null;
150 }
151 else if (empty($mailto))
152   $mailto = 'undisclosed-recipients:;';
153
154 // get sender name and address
155 $identity_arr = rcmail_get_identity(get_input_value('_from', RCUBE_INPUT_POST));
156 $from = $identity_arr['mailto'];
157
158 if (empty($identity_arr['string']))
159   $identity_arr['string'] = $from;
160
161 // compose headers array
162 $headers = array('Date' => date('r'),
163                  'From' => rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset),
164                  'To'   => $mailto);
165
166 // additional recipients
167 if (!empty($mailcc))
168   $headers['Cc'] = $mailcc;
169
170 if (!empty($mailbcc))
171   $headers['Bcc'] = $mailbcc;
172   
173 if (!empty($identity_arr['bcc']))
174   $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
175
176 // add subject
177 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
178
179 if (!empty($identity_arr['organization']))
180   $headers['Organization'] = $identity_arr['organization'];
181
182 if (!empty($_POST['_replyto']))
183   $headers['Reply-To'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
184 else if (!empty($identity_arr['reply-to']))
185   $headers['Reply-To'] = $identity_arr['reply-to'];
186
187 if (!empty($_SESSION['compose']['reply_msgid']))
188   $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
189
190 if (!empty($_SESSION['compose']['references']))
191   $headers['References'] = $_SESSION['compose']['references'];
192
193 if (!empty($_POST['_priority']))
194   {
195   $priority = intval($_POST['_priority']);
196   $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
197   if ($str_priority = $a_priorities[$priority])
198     $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
199   }
200
201 if (!empty($_POST['_receipt']))
202   {
203   $headers['Return-Receipt-To'] = $identity_arr['string'];
204   $headers['Disposition-Notification-To'] = $identity_arr['string'];
205   }
206
207 // additional headers
208 if ($CONFIG['http_received_header'])
209 {
210   $nldlm = rcmail_header_delm() . "\t";
211   $headers['Received'] =  wordwrap('from ' . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
212       gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']).' ['.$_SERVER['HTTP_X_FORWARDED_FOR'].']'.$nldlm.' via ' : '') .
213     gethostbyaddr($_SERVER['REMOTE_ADDR']).' ['.$_SERVER['REMOTE_ADDR'].']'.$nldlm.'with ' .
214     $_SERVER['SERVER_PROTOCOL'].' ('.$_SERVER['REQUEST_METHOD'].'); ' . date('r'),
215     69, $nldlm);
216 }
217
218 $headers['Message-ID'] = $message_id;
219 $headers['X-Sender'] = $from;
220
221 if (!empty($CONFIG['useragent']))
222   $headers['User-Agent'] = $CONFIG['useragent'];
223
224 // fetch message body
225 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
226
227 // append generic footer to all messages
228 if (!$savedraft && !empty($CONFIG['generic_message_footer']) && ($footer = file_get_contents(realpath($CONFIG['generic_message_footer']))))
229   $message_body .= "\r\n" . rcube_charset_convert($footer, 'UTF-8', $message_charset);
230
231 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
232 $isHtml = ($isHtmlVal == "1");
233
234 // create extended PEAR::Mail_mime instance
235 $MAIL_MIME = new rcube_mail_mime(rcmail_header_delm());
236
237 // For HTML-formatted messages, construct the MIME message with both
238 // the HTML part and the plain-text part
239
240 if ($isHtml)
241   {
242   $MAIL_MIME->setHTMLBody($message_body);
243
244   // add a plain text version of the e-mail as an alternative part.
245   $h2t = new html2text($message_body);
246   $plainTextPart = wordwrap($h2t->get_text(), 998, "\r\n", true);
247   if (!strlen($plainTextPart)) 
248     { 
249     // empty message body breaks attachment handling in drafts 
250     $plainTextPart = "\r\n"; 
251     }
252   $MAIL_MIME->setTXTBody(html_entity_decode($plainTextPart, ENT_COMPAT, 'utf-8'));
253
254   // look for "emoticon" images from TinyMCE and copy into message as attachments
255   rcmail_attach_emoticons($MAIL_MIME);
256   }
257 else
258   {
259   $message_body = wordwrap($message_body, 75, "\r\n");
260   $message_body = wordwrap($message_body, 998, "\r\n", true);
261   if (!strlen($message_body))  
262     { 
263     // empty message body breaks attachment handling in drafts 
264     $message_body = "\r\n"; 
265     } 
266   $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
267   }
268
269
270 // add stored attachments, if any
271 if (is_array($_SESSION['compose']['attachments']))
272   foreach ($_SESSION['compose']['attachments'] as $id => $attachment)
273   {
274     $dispurl = '/\ssrc\s*=\s*[\'"]?\S+display-attachment\S+file=rcmfile' . $id . '[\'"]?/';
275     $match = preg_match($dispurl, $message_body);
276     if ($isHtml && ($match > 0))
277     {
278       $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'"', $message_body);
279       $MAIL_MIME->setHTMLBody($message_body);
280       $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name']);
281     }
282     else
283     {
284       /*
285         We need to replace mime_content_type in a later release because the function
286         is deprecated in favour of File_Info
287       */
288       $MAIL_MIME->addAttachment($attachment['path'],
289         rc_mime_content_type($attachment['path'], $attachment['mimetype']),
290         $attachment['name'], true, 'base64',
291         'attachment', $message_charset);
292     }
293   }
294
295 // add submitted attachments
296 if (is_array($_FILES['_attachments']['tmp_name']))
297   foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
298     $MAIL_MIME->addAttachment($filepath, $files['type'][$i], $files['name'][$i], true, 'base64', 'attachment', $message_charset);
299
300
301 // chose transfer encoding
302 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
303 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
304
305 // encoding settings for mail composing
306 $MAIL_MIME->setParam(array(
307   'text_encoding' => $transfer_encoding,
308   'html_encoding' => 'quoted-printable',
309   'head_encoding' => 'quoted-printable',
310   'head_charset'  => $message_charset,
311   'html_charset'  => $message_charset,
312   'text_charset'  => $message_charset,
313 ));
314
315 // encoding subject header with mb_encode provides better results with asian characters
316 if (function_exists("mb_encode_mimeheader"))
317 {
318   mb_internal_encoding($message_charset);
319   $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
320   mb_internal_encoding(RCMAIL_CHARSET);
321 }
322
323 // pass headers to message object
324 $MAIL_MIME->headers($headers);
325
326 // Begin SMTP Delivery Block 
327 if (!$savedraft)
328 {
329   $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto);
330   
331   // return to compose page if sending failed
332   if (!$sent)
333     {
334     $OUTPUT->show_message("sendingfailed", 'error'); 
335     $OUTPUT->send('iframe');
336     return;
337     }
338   
339   // set repliead flag
340   if ($_SESSION['compose']['reply_uid'])
341     $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
342
343   } // End of SMTP Delivery Block
344
345
346
347 // Determine which folder to save message
348 if ($savedraft)
349   $store_target = 'drafts_mbox';
350 else
351   $store_target = 'sent_mbox';
352
353 if ($CONFIG[$store_target])
354   {
355   // check if mailbox exists
356   if (!in_array_nocase($CONFIG[$store_target], $IMAP->list_mailboxes()))
357     $store_folder = $IMAP->create_mailbox($CONFIG[$store_target], TRUE);
358   else
359     $store_folder = TRUE;
360   
361   // append message to sent box
362   if ($store_folder)
363     $saved = $IMAP->save_message($CONFIG[$store_target], $MAIL_MIME->getMessage());
364
365   // raise error if saving failed
366   if (!$saved)
367     {
368     raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
369                       'message' => "Could not save message in $CONFIG[$store_target]"), TRUE, FALSE);
370     
371     $OUTPUT->show_message('errorsaving', 'error');
372     $OUTPUT->send('iframe');
373     }
374
375   if ($olddraftmessageid)
376     {
377     // delete previous saved draft
378     $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'],'HEADER Message-ID',$olddraftmessageid);
379     $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0],$CONFIG['drafts_mbox']),$CONFIG['drafts_mbox']);
380
381     // raise error if deletion of old draft failed
382     if (!$deleted)
383       raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
384                         'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
385     }
386   }
387
388 if ($savedraft)
389   {
390   // display success
391   $OUTPUT->show_message('messagesaved', 'confirmation');
392
393   // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
394   $OUTPUT->command('set_draft_id', str_replace(array('<','>'), "", $message_id));
395   $OUTPUT->command('compose_field_hash', true);
396
397   // start the auto-save timer again
398   $OUTPUT->command('auto_save_start');
399
400   $OUTPUT->send('iframe');
401   }
402 else
403   {
404   if ($CONFIG['smtp_log'])
405     {
406     $log_entry = sprintf(
407       "[%s] User: %d on %s; Message for %s; %s\n",
408       date("d-M-Y H:i:s O", mktime()),
409       $_SESSION['user_id'],
410       $_SERVER['REMOTE_ADDR'],
411       $mailto,
412       !empty($smtp_response) ? join('; ', $smtp_response) : '');
413
414     if ($fp = @fopen($CONFIG['log_dir'].'/sendmail', 'a'))
415       {
416       fwrite($fp, $log_entry);
417       fclose($fp);
418       }
419     }
420
421   rcmail_compose_cleanup();
422   $OUTPUT->command('sent_successfully', rcube_label('messagesent'));
423   $OUTPUT->send('iframe');
424   }
425
426 ?>