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