]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_smtp.php
Imported Upstream version 0.7
[roundcube.git] / program / include / rcube_smtp.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_smtp.php                                        |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2005-2010, The Roundcube Dev Team                       |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Provide SMTP functionality using socket connections                 |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: rcube_smtp.php 5499 2011-11-28 09:03:27Z alec $
19
20 */
21
22 // define headers delimiter
23 define('SMTP_MIME_CRLF', "\r\n");
24
25 /**
26  * Class to provide SMTP functionality using PEAR Net_SMTP
27  *
28  * @package    Mail
29  * @author     Thomas Bruederli <roundcube@gmail.com>
30  * @author     Aleksander Machniak <alec@alec.pl>
31  */
32 class rcube_smtp
33 {
34
35   private $conn = null;
36   private $response;
37   private $error;
38
39
40   /**
41    * SMTP Connection and authentication
42    *
43    * @param string Server host
44    * @param string Server port
45    * @param string User name
46    * @param string Password
47    *
48    * @return bool  Returns true on success, or false on error
49    */
50   public function connect($host=null, $port=null, $user=null, $pass=null)
51   {
52     $RCMAIL = rcmail::get_instance();
53   
54     // disconnect/destroy $this->conn
55     $this->disconnect();
56     
57     // reset error/response var
58     $this->error = $this->response = null;
59   
60     // let plugins alter smtp connection config
61     $CONFIG = $RCMAIL->plugins->exec_hook('smtp_connect', array(
62       'smtp_server'    => $host ? $host : $RCMAIL->config->get('smtp_server'),
63       'smtp_port'      => $port ? $port : $RCMAIL->config->get('smtp_port', 25),
64       'smtp_user'      => $user ? $user : $RCMAIL->config->get('smtp_user'),
65       'smtp_pass'      => $pass ? $pass : $RCMAIL->config->get('smtp_pass'),
66       'smtp_auth_cid'  => $RCMAIL->config->get('smtp_auth_cid'),
67       'smtp_auth_pw'   => $RCMAIL->config->get('smtp_auth_pw'),
68       'smtp_auth_type' => $RCMAIL->config->get('smtp_auth_type'),
69       'smtp_helo_host' => $RCMAIL->config->get('smtp_helo_host'),
70       'smtp_timeout'   => $RCMAIL->config->get('smtp_timeout'),
71     ));
72
73     $smtp_host = rcube_parse_host($CONFIG['smtp_server']);
74     // when called from Installer it's possible to have empty $smtp_host here
75     if (!$smtp_host) $smtp_host = 'localhost';
76     $smtp_port = is_numeric($CONFIG['smtp_port']) ? $CONFIG['smtp_port'] : 25;
77     $smtp_host_url = parse_url($smtp_host);
78
79     // overwrite port
80     if (isset($smtp_host_url['host']) && isset($smtp_host_url['port']))
81     {
82       $smtp_host = $smtp_host_url['host'];
83       $smtp_port = $smtp_host_url['port'];
84     }
85
86     // re-write smtp host
87     if (isset($smtp_host_url['host']) && isset($smtp_host_url['scheme']))
88       $smtp_host = sprintf('%s://%s', $smtp_host_url['scheme'], $smtp_host_url['host']);
89
90     // remove TLS prefix and set flag for use in Net_SMTP::auth()
91     if (preg_match('#^tls://#i', $smtp_host)) {
92       $smtp_host = preg_replace('#^tls://#i', '', $smtp_host);
93       $use_tls = true;
94     }
95
96     if (!empty($CONFIG['smtp_helo_host']))
97       $helo_host = $CONFIG['smtp_helo_host'];
98     else if (!empty($_SERVER['SERVER_NAME']))
99       $helo_host = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
100     else
101       $helo_host = 'localhost';
102
103     // IDNA Support
104     $smtp_host = rcube_idn_to_ascii($smtp_host);
105
106     $this->conn = new Net_SMTP($smtp_host, $smtp_port, $helo_host);
107
108     if ($RCMAIL->config->get('smtp_debug'))
109       $this->conn->setDebug(true, array($this, 'debug_handler'));
110
111     // try to connect to server and exit on failure
112     $result = $this->conn->connect($smtp_timeout);
113
114     if (PEAR::isError($result)) {
115       $this->response[] = "Connection failed: ".$result->getMessage();
116       $this->error = array('label' => 'smtpconnerror', 'vars' => array('code' => $this->conn->_code));
117       $this->conn = null;
118       return false;
119     }
120
121     // workaround for timeout bug in Net_SMTP 1.5.[0-1] (#1487843)
122     if (method_exists($this->conn, 'setTimeout')
123       && ($timeout = ini_get('default_socket_timeout'))
124     ) {
125       $this->conn->setTimeout($timeout);
126     }
127
128     $smtp_user = str_replace('%u', $_SESSION['username'], $CONFIG['smtp_user']);
129     $smtp_pass = str_replace('%p', $RCMAIL->decrypt($_SESSION['password']), $CONFIG['smtp_pass']);
130     $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
131
132     if (!empty($CONFIG['smtp_auth_cid'])) {
133       $smtp_authz = $smtp_user;
134       $smtp_user  = $CONFIG['smtp_auth_cid'];
135       $smtp_pass  = $CONFIG['smtp_auth_pw'];
136     }
137
138     // attempt to authenticate to the SMTP server
139     if ($smtp_user && $smtp_pass)
140     {
141       // IDNA Support
142       if (strpos($smtp_user, '@')) {
143         $smtp_user = rcube_idn_to_ascii($smtp_user);
144       }
145
146       $result = $this->conn->auth($smtp_user, $smtp_pass, $smtp_auth_type, $use_tls, $smtp_authz);
147
148       if (PEAR::isError($result))
149       {
150         $this->error = array('label' => 'smtpautherror', 'vars' => array('code' => $this->conn->_code));
151         $this->response[] .= 'Authentication failure: ' . $result->getMessage() . ' (Code: ' . $result->getCode() . ')';
152         $this->reset();
153         $this->disconnect();
154         return false;
155       }
156     }
157
158     return true;
159   }
160
161
162   /**
163    * Function for sending mail
164    *
165    * @param string Sender e-Mail address
166    *
167    * @param mixed  Either a comma-seperated list of recipients
168    *               (RFC822 compliant), or an array of recipients,
169    *               each RFC822 valid. This may contain recipients not
170    *               specified in the headers, for Bcc:, resending
171    *               messages, etc.
172    * @param mixed  The message headers to send with the mail
173    *               Either as an associative array or a finally
174    *               formatted string
175    * @param mixed  The full text of the message body, including any Mime parts
176    *               or file handle
177    * @param array  Delivery options (e.g. DSN request)
178    *
179    * @return bool  Returns true on success, or false on error
180    */
181   public function send_mail($from, $recipients, &$headers, &$body, $opts=null)
182   {
183     if (!is_object($this->conn))
184       return false;
185
186     // prepare message headers as string
187     if (is_array($headers))
188     {
189       if (!($headerElements = $this->_prepare_headers($headers))) {
190         $this->reset();
191         return false;
192       }
193
194       list($from, $text_headers) = $headerElements;
195     }
196     else if (is_string($headers))
197       $text_headers = $headers;
198     else
199     {
200       $this->reset();
201       $this->response[] = "Invalid message headers";
202       return false;
203     }
204
205     // exit if no from address is given
206     if (!isset($from))
207     {
208       $this->reset();
209       $this->response[] = "No From address has been provided";
210       return false;
211     }
212
213     // RFC3461: Delivery Status Notification
214     if ($opts['dsn']) {
215       $exts = $this->conn->getServiceExtensions();
216
217       if (isset($exts['DSN'])) {
218         $from_params      = 'RET=HDRS';
219         $recipient_params = 'NOTIFY=SUCCESS,FAILURE';
220       }
221     }
222
223     // RFC2298.3: remove envelope sender address
224     if (preg_match('/Content-Type: multipart\/report/', $text_headers)
225       && preg_match('/report-type=disposition-notification/', $text_headers)
226     ) {
227       $from = '';
228     }
229
230     // set From: address
231     if (PEAR::isError($this->conn->mailFrom($from, $from_params)))
232     {
233       $err = $this->conn->getResponse();
234       $this->error = array('label' => 'smtpfromerror', 'vars' => array(
235         'from' => $from, 'code' => $this->conn->_code, 'msg' => $err[1]));
236       $this->response[] = "Failed to set sender '$from'";
237       $this->reset();
238       return false;
239     }
240
241     // prepare list of recipients
242     $recipients = $this->_parse_rfc822($recipients);
243     if (PEAR::isError($recipients))
244     {
245       $this->error = array('label' => 'smtprecipientserror');
246       $this->reset();
247       return false;
248     }
249
250     // set mail recipients
251     foreach ($recipients as $recipient)
252     {
253       if (PEAR::isError($this->conn->rcptTo($recipient, $recipient_params))) {
254         $err = $this->conn->getResponse();
255         $this->error = array('label' => 'smtptoerror', 'vars' => array(
256           'to' => $recipient, 'code' => $this->conn->_code, 'msg' => $err[1]));
257         $this->response[] = "Failed to add recipient '$recipient'";
258         $this->reset();
259         return false;
260       }
261     }
262
263     if (is_resource($body))
264     {
265       // file handle
266       $data = $body;
267       $text_headers = preg_replace('/[\r\n]+$/', '', $text_headers);
268     } else {
269       // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
270       // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy. 
271       // We are still forced to make another copy here for a couple ticks so we don't really 
272       // get to save a copy in the method call.
273       $data = $text_headers . "\r\n" . $body;
274
275       // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
276       unset($text_headers, $body);
277     }
278
279     // Send the message's headers and the body as SMTP data.
280     if (PEAR::isError($result = $this->conn->data($data, $text_headers)))
281     {
282       $err = $this->conn->getResponse();
283       if (!in_array($err[0], array(354, 250, 221)))
284         $msg = sprintf('[%d] %s', $err[0], $err[1]);
285       else
286         $msg = $result->getMessage();
287
288       $this->error = array('label' => 'smtperror', 'vars' => array('msg' => $msg));
289       $this->response[] = "Failed to send data";
290       $this->reset();
291       return false;
292     }
293
294     $this->response[] = join(': ', $this->conn->getResponse());
295     return true;
296   }
297
298
299   /**
300    * Reset the global SMTP connection
301    * @access public
302    */
303   public function reset()
304   {
305     if (is_object($this->conn))
306       $this->conn->rset();
307   }
308
309
310   /**
311    * Disconnect the global SMTP connection
312    * @access public
313    */
314   public function disconnect()
315   {
316     if (is_object($this->conn)) {
317       $this->conn->disconnect();
318       $this->conn = null;
319     }
320   }
321
322
323   /**
324    * This is our own debug handler for the SMTP connection
325    * @access public
326    */
327   public function debug_handler(&$smtp, $message)
328   {
329     write_log('smtp', preg_replace('/\r\n$/', '', $message));
330   }
331
332
333   /**
334    * Get error message
335    * @access public
336    */
337   public function get_error()
338   {
339     return $this->error;
340   }
341
342
343   /**
344    * Get server response messages array
345    * @access public
346    */
347   public function get_response()
348   {
349     return $this->response;
350   }
351
352
353   /**
354    * Take an array of mail headers and return a string containing
355    * text usable in sending a message.
356    *
357    * @param array $headers The array of headers to prepare, in an associative
358    *              array, where the array key is the header name (ie,
359    *              'Subject'), and the array value is the header
360    *              value (ie, 'test'). The header produced from those
361    *              values would be 'Subject: test'.
362    *
363    * @return mixed Returns false if it encounters a bad address,
364    *               otherwise returns an array containing two
365    *               elements: Any From: address found in the headers,
366    *               and the plain text version of the headers.
367    * @access private
368    */
369   private function _prepare_headers($headers)
370   {
371     $lines = array();
372     $from = null;
373
374     foreach ($headers as $key => $value)
375     {
376       if (strcasecmp($key, 'From') === 0)
377       {
378         $addresses = $this->_parse_rfc822($value);
379
380         if (is_array($addresses))
381           $from = $addresses[0];
382
383         // Reject envelope From: addresses with spaces.
384         if (strpos($from, ' ') !== false)
385           return false;
386
387         $lines[] = $key . ': ' . $value;
388       }
389       else if (strcasecmp($key, 'Received') === 0)
390       {
391         $received = array();
392         if (is_array($value))
393         {
394           foreach ($value as $line)
395             $received[] = $key . ': ' . $line;
396         }
397         else
398         {
399           $received[] = $key . ': ' . $value;
400         }
401
402         // Put Received: headers at the top.  Spam detectors often
403         // flag messages with Received: headers after the Subject:
404         // as spam.
405         $lines = array_merge($received, $lines);
406       }
407       else
408       {
409         // If $value is an array (i.e., a list of addresses), convert
410         // it to a comma-delimited string of its elements (addresses).
411         if (is_array($value))
412           $value = implode(', ', $value);
413
414         $lines[] = $key . ': ' . $value;
415       }
416     }
417     
418     return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
419   }
420
421   /**
422    * Take a set of recipients and parse them, returning an array of
423    * bare addresses (forward paths) that can be passed to sendmail
424    * or an smtp server with the rcpt to: command.
425    *
426    * @param mixed Either a comma-seperated list of recipients
427    *              (RFC822 compliant), or an array of recipients,
428    *              each RFC822 valid.
429    *
430    * @return array An array of forward paths (bare addresses).
431    * @access private
432    */
433   private function _parse_rfc822($recipients)
434   {
435     // if we're passed an array, assume addresses are valid and implode them before parsing.
436     if (is_array($recipients))
437       $recipients = implode(', ', $recipients);
438
439     $addresses = array();
440     $recipients = rcube_explode_quoted_string(',', $recipients);
441
442     reset($recipients);
443     while (list($k, $recipient) = each($recipients))
444     {
445       $a = rcube_explode_quoted_string(' ', $recipient);
446       while (list($k2, $word) = each($a))
447       {
448         if (strpos($word, "@") > 0 && $word[strlen($word)-1] != '"')
449         {
450           $word = preg_replace('/^<|>$/', '', trim($word));
451           if (in_array($word, $addresses)===false)
452             array_push($addresses, $word);
453         }
454       }
455     }
456
457     return $addresses;
458   }
459
460 }