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