]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/sendmail.inc
Imported Upstream version 0.1~beta2.2~dfsg
[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, 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 IlohaMail's SMTP methods or with PHP mail()       |
14  |                                                                       |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18
19  $Id: sendmail.inc 288 2006-07-31 22:51:23Z thomasb $
20
21 */
22
23
24 //require_once('lib/smtp.inc');
25 require_once('include/rcube_smtp.inc');
26 require_once('Mail/mime.php');
27
28
29 if (!isset($_SESSION['compose']['id']))
30   {
31   rcmail_overwrite_action('list');
32   return;
33   }
34
35
36 /****** message sending functions ********/
37
38
39 function rcmail_get_identity($id)
40   {
41   global $DB, $CHARSET, $OUTPUT;
42   
43   // get identity record
44   $sql_result = $DB->query("SELECT *, email AS mailto
45                             FROM ".get_table_name('identities')."
46                             WHERE  identity_id=?
47                             AND    user_id=?
48                             AND    del<>1",
49                             $id,$_SESSION['user_id']);
50                                    
51   if ($DB->num_rows($sql_result))
52     {
53     $sql_arr = $DB->fetch_assoc($sql_result);
54     $out = $sql_arr;
55     $name = strpos($sql_arr['name'], ",") ? '"'.$sql_arr['name'].'"' : $sql_arr['name'];
56     $out['string'] = sprintf('%s <%s>',
57                              rcube_charset_convert($name, $CHARSET, $OUTPUT->get_charset()),
58                              $sql_arr['mailto']);
59     return $out;
60     }
61
62   return FALSE;  
63   }
64
65
66 if (strlen($_POST['_draft_saveid']) > 3)
67   $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
68
69 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $_SESSION['imap_host']);
70 $savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
71
72 // remove all scripts and act as called in frame
73 $OUTPUT->reset();
74 $_framed = TRUE;
75
76
77 /****** check submission and compose message ********/
78
79
80 if (empty($_POST['_to']) && empty($_POST['_subject']) && $_POST['_message'])
81   {
82   show_message("sendingfailed", 'error'); 
83   //rcmail_overwrite_action('compose');
84   rcube_iframe_response();
85   return;
86   }
87
88
89 // set default charset
90 $input_charset = $OUTPUT->get_charset();
91 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
92
93 $mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m');
94 $mailto_replace = array(', ', ', ', '');
95
96 // replace new lines and strip ending ', '
97 $mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
98
99 // decode address strings
100 $to_address_arr = $IMAP->decode_address_list($mailto);
101 $identity_arr = rcmail_get_identity(get_input_value('_from', RCUBE_INPUT_POST));
102
103 $from = $identity_arr['mailto'];
104 $first_to = is_array($to_address_arr[0]) ? $to_address_arr[0]['mailto'] : $mailto;
105
106 if (empty($identity_arr['string']))
107   $identity_arr['string'] = $from;
108
109 // compose headers array
110 $headers = array('Date' => date('D, j M Y G:i:s O'),
111                  'From' => $identity_arr['string'],
112                  'To'   => rcube_charset_convert($mailto, $input_charset, $message_charset));
113
114 // additional recipients
115 if (!empty($_POST['_cc']))
116   $headers['Cc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
117
118 if (!empty($_POST['_bcc']))
119   $headers['Bcc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
120   
121 if (!empty($identity_arr['bcc']))
122   $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
123
124 // add subject
125 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
126
127 if (!empty($identity_arr['organization']))
128   $headers['Organization'] = $identity_arr['organization'];
129
130 if (!empty($identity_arr['reply-to']))
131   $headers['Reply-To'] = $identity_arr['reply-to'];
132
133 if (!empty($_SESSION['compose']['reply_msgid']))
134   $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
135
136 if (!empty($_SESSION['compose']['references']))
137   $headers['References'] = $_SESSION['compose']['references'];
138
139 if (!empty($_POST['_priority']))
140   {
141   $priority = (int)$_POST['_priority'];
142   $a_priorities = array(1=>'lowest', 2=>'low', 4=>'high', 5=>'highest');
143   if ($str_priority = $a_priorities[$priority])
144     $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
145   }
146
147 if (!empty($_POST['_receipt']))
148   {
149   $headers['Return-Receipt-To'] = $identity_arr['string'];
150   $headers['Disposition-Notification-To'] = $identity_arr['string'];
151   }
152
153 // additional headers
154 $headers['Message-ID'] = $message_id;
155 $headers['X-Sender'] = $from;
156
157 if (!empty($CONFIG['useragent']))
158   $headers['User-Agent'] = $CONFIG['useragent'];
159
160 // fetch message body
161 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
162
163 // append generic footer to all messages
164 if (!empty($CONFIG['generic_message_footer']))
165   {
166   $file = realpath($CONFIG['generic_message_footer']);
167   if($fp = fopen($file, 'r'))
168     {
169     $content = fread($fp, filesize($file));
170     fclose($fp);
171     $message_body .= "\r\n" . rcube_charset_convert($content, 'UTF-8', $message_charset);
172     }
173   }
174
175 // try to autodetect operating system and use the correct line endings
176 // use the configured delimiter for headers
177 if (!empty($CONFIG['mail_header_delimiter']))
178   $header_delm = $CONFIG['mail_header_delimiter'];
179 else if (strtolower(substr(PHP_OS, 0, 3)=='win')) 
180   $header_delm = "\r\n";
181 else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
182   $header_delm = "\r\n";
183 else    
184   $header_delm = "\n";
185
186 // create PEAR::Mail_mime instance
187 $MAIL_MIME = new Mail_mime($header_delm);
188 $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
189 //$MAIL_MIME->setTXTBody(wordwrap($message_body), FALSE, TRUE);
190
191
192 // add stored attachments, if any
193 if (is_array($_SESSION['compose']['attachments']))
194   foreach ($_SESSION['compose']['attachments'] as $attachment)
195     $MAIL_MIME->addAttachment($attachment['path'], $attachment['mimetype'], $attachment['name'], TRUE);
196
197   
198 // add submitted attachments
199 if (is_array($_FILES['_attachments']['tmp_name']))
200   foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
201     $MAIL_MIME->addAttachment($filepath, $files['type'][$i], $files['name'][$i], TRUE);
202
203
204 // chose transfer encoding
205 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
206 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
207
208 // encoding settings for mail composing
209 $message_param = array('text_encoding' => $transfer_encoding,
210                        'html_encoding' => 'quoted-printable',
211                        'head_encoding' => 'quoted-printable',
212                        'head_charset'  => $message_charset,
213                        'html_charset'  => $message_charset,
214                        'text_charset'  => $message_charset);
215
216 // compose message body and get headers
217 $msg_body = &$MAIL_MIME->get($message_param);
218
219 $msg_subject = $headers['Subject'];
220
221 if ($MBSTRING && function_exists("mb_encode_mimeheader"))
222   $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset);
223
224 // Begin SMTP Delivery Block 
225 if (!$savedraft) {
226
227   // send thru SMTP server using custom SMTP library
228   if ($CONFIG['smtp_server'])
229     {
230     // generate list of recipients
231     $a_recipients = array($mailto);
232   
233     if (strlen($headers['Cc']))
234       $a_recipients[] = $headers['Cc'];
235     if (strlen($headers['Bcc']))
236       $a_recipients[] = $headers['Bcc'];
237   
238     // clean Bcc from header for recipients
239     $send_headers = $headers;
240     unset($send_headers['Bcc']);
241   
242     // generate message headers
243     $header_str = $MAIL_MIME->txtHeaders($send_headers);
244   
245     // send message
246     $sent = smtp_mail($from, $a_recipients, $header_str, $msg_body);
247   
248     // log error
249     if (!$sent)
250       {
251       raise_error(array('code' => 800,
252                         'type' => 'smtp',
253                         'line' => __LINE__,
254                         'file' => __FILE__,
255                         'message' => "SMTP error: $SMTP_ERROR"), TRUE, FALSE);
256       }
257     }
258   
259   // send mail using PHP's mail() function
260   else
261     {
262     // unset some headers because they will be added by the mail() function
263     $headers_enc = $MAIL_MIME->headers($headers);
264     $headers_php = $MAIL_MIME->_headers;
265     unset($headers_php['To'], $headers_php['Subject']);
266     
267     // reset stored headers and overwrite
268     $MAIL_MIME->_headers = array();
269     $header_str = $MAIL_MIME->txtHeaders($headers_php);
270   
271     if (ini_get('safe_mode'))
272       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
273     else
274       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
275     }
276   
277   
278   // return to compose page if sending failed
279   if (!$sent)
280     {
281     show_message("sendingfailed", 'error'); 
282     rcube_iframe_response();
283     return;
284     }
285   
286   
287   // set repliead flag
288   if ($_SESSION['compose']['reply_uid'])
289     $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
290
291   } // End of SMTP Delivery Block
292
293
294
295 // Determine which folder to save message
296 if ($savedraft)
297   $store_target = 'drafts_mbox';
298 else
299   $store_target = 'sent_mbox';
300
301 if ($CONFIG[$store_target])
302   {
303   // create string of complete message headers
304   $header_str = $MAIL_MIME->txtHeaders($headers);
305
306   // check if mailbox exists
307   if (!in_array_nocase($CONFIG[$store_target], $IMAP->list_mailboxes()))
308     $store_folder = $IMAP->create_mailbox($CONFIG[$store_target], TRUE);
309   else
310     $store_folder = TRUE;
311   
312   // add headers to message body
313   $msg_body = $header_str."\r\n".$msg_body;
314
315   // append message to sent box
316   if ($store_folder)
317     $saved = $IMAP->save_message($CONFIG[$store_target], $msg_body);
318
319   // raise error if saving failed
320   if (!$saved)
321     {
322     raise_error(array('code' => 800,
323                       'type' => 'imap',
324                       'file' => __FILE__,
325                       'message' => "Could not save message in $CONFIG[$store_target]"), TRUE, FALSE);
326     
327     show_message('errorsaving', 'error');
328     rcube_iframe_response($errorout);
329     }
330
331   if ($olddraftmessageid)
332     {
333     // delete previous saved draft
334     $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'],'HEADER Message-ID',$olddraftmessageid);
335     $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0],$CONFIG['drafts_mbox']),$CONFIG['drafts_mbox']);
336
337     // raise error if deletion of old draft failed
338     if (!$deleted)
339       raise_error(array('code' => 800,
340                         'type' => 'imap',
341                         'file' => __FILE__,
342                         'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
343     }
344   }
345
346 if ($savedraft)
347   {
348   // clear the "saving message" busy status, and display success
349   show_message('messagesaved', 'confirmation');
350
351   // update "_draft_saveid" on the page, which is used to delete a previous draft
352   $frameout = "var foundid = parent.rcube_find_object('_draft_saveid', parent.document);\n";
353   $frameout .= sprintf("foundid.value = '%s';\n", str_replace(array('<','>'), "", $message_id));
354
355   // update the "cmp_hash" to prevent "Unsaved changes" warning
356   $frameout .= sprintf("parent.%s.cmp_hash = parent.%s.compose_field_hash();\n", $JS_OBJECT_NAME, $JS_OBJECT_NAME);
357
358   // start the auto-save timer again
359   $frameout .= sprintf("parent.%s.auto_save_start();", $JS_OBJECT_NAME);
360
361   // send html page with JS calls as response
362   rcube_iframe_response($frameout);
363   }
364 else
365   {
366   if ($CONFIG['smtp_log'])
367     {
368     $log_entry = sprintf("[%s] User: %d on %s; Message for %s; Subject: %s\n",
369                  date("d-M-Y H:i:s O", mktime()),
370                  $_SESSION['user_id'],
371                  $_SERVER['REMOTE_ADDR'],
372                  $mailto,
373                  $msg_subject);
374
375     if ($fp = @fopen($CONFIG['log_dir'].'/sendmail', 'a'))
376       {
377       fwrite($fp, $log_entry);
378       fclose($fp);
379       }
380     }
381
382   rcmail_compose_cleanup();
383   rcube_iframe_response(sprintf("parent.$JS_OBJECT_NAME.sent_successfully('%s');",
384                                 rep_specialchars_output(rcube_label('messagesent'), 'js')));
385   }
386
387
388 ?>