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