source: subversion/trunk/roundcubemail/program/include/rcube_smtp.php @ 6092

Last change on this file since 6092 was 6092, checked in by alec, 13 months ago
  • Replace some references to rcmail with rcube
  • Property svn:keywords set to Id
File size: 14.6 KB
Line 
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 |                                                                       |
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.                     |
13 |                                                                       |
14 | PURPOSE:                                                              |
15 |   Provide SMTP functionality using socket connections                 |
16 |                                                                       |
17 +-----------------------------------------------------------------------+
18 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
19 +-----------------------------------------------------------------------+
20
21 $Id$
22
23*/
24
25// define headers delimiter
26define('SMTP_MIME_CRLF', "\r\n");
27
28/**
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 */
35class rcube_smtp
36{
37
38  private $conn = null;
39  private $response;
40  private $error;
41
42
43  /**
44   * SMTP Connection and authentication
45   *
46   * @param string Server host
47   * @param string Server port
48   * @param string User name
49   * @param string Password
50   *
51   * @return bool  Returns true on success, or false on error
52   */
53  public function connect($host=null, $port=null, $user=null, $pass=null)
54  {
55    $rcube = rcube::get_instance();
56
57    // disconnect/destroy $this->conn
58    $this->disconnect();
59
60    // reset error/response var
61    $this->error = $this->response = null;
62
63    // let plugins alter smtp connection config
64    $CONFIG = $rcube->plugins->exec_hook('smtp_connect', array(
65      'smtp_server'    => $host ? $host : $rcube->config->get('smtp_server'),
66      'smtp_port'      => $port ? $port : $rcube->config->get('smtp_port', 25),
67      'smtp_user'      => $user ? $user : $rcube->config->get('smtp_user'),
68      'smtp_pass'      => $pass ? $pass : $rcube->config->get('smtp_pass'),
69      'smtp_auth_cid'  => $rcube->config->get('smtp_auth_cid'),
70      'smtp_auth_pw'   => $rcube->config->get('smtp_auth_pw'),
71      'smtp_auth_type' => $rcube->config->get('smtp_auth_type'),
72      'smtp_helo_host' => $rcube->config->get('smtp_helo_host'),
73      'smtp_timeout'   => $rcube->config->get('smtp_timeout'),
74      'smtp_auth_callbacks' => array(),
75    ));
76
77    $smtp_host = rcube_utils::parse_host($CONFIG['smtp_server']);
78    // when called from Installer it's possible to have empty $smtp_host here
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
94    // remove TLS prefix and set flag for use in Net_SMTP::auth()
95    if (preg_match('#^tls://#i', $smtp_host)) {
96      $smtp_host = preg_replace('#^tls://#i', '', $smtp_host);
97      $use_tls = true;
98    }
99
100    if (!empty($CONFIG['smtp_helo_host']))
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
107    // IDNA Support
108    $smtp_host = rcube_utils::idn_to_ascii($smtp_host);
109
110    $this->conn = new Net_SMTP($smtp_host, $smtp_port, $helo_host);
111
112    if ($rcube->config->get('smtp_debug'))
113      $this->conn->setDebug(true, array($this, 'debug_handler'));
114
115    // register authentication methods
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
123    // try to connect to server and exit on failure
124    $result = $this->conn->connect($smtp_timeout);
125
126    if (PEAR::isError($result)) {
127      $this->response[] = "Connection failed: ".$result->getMessage();
128      $this->error = array('label' => 'smtpconnerror', 'vars' => array('code' => $this->conn->_code));
129      $this->conn = null;
130      return false;
131    }
132
133    // workaround for timeout bug in Net_SMTP 1.5.[0-1] (#1487843)
134    if (method_exists($this->conn, 'setTimeout')
135      && ($timeout = ini_get('default_socket_timeout'))
136    ) {
137      $this->conn->setTimeout($timeout);
138    }
139
140    $smtp_user = str_replace('%u', $_SESSION['username'], $CONFIG['smtp_user']);
141    $smtp_pass = str_replace('%p', $rcube->decrypt($_SESSION['password']), $CONFIG['smtp_pass']);
142    $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
143
144    if (!empty($CONFIG['smtp_auth_cid'])) {
145      $smtp_authz = $smtp_user;
146      $smtp_user  = $CONFIG['smtp_auth_cid'];
147      $smtp_pass  = $CONFIG['smtp_auth_pw'];
148    }
149
150    // attempt to authenticate to the SMTP server
151    if ($smtp_user && $smtp_pass)
152    {
153      // IDNA Support
154      if (strpos($smtp_user, '@')) {
155        $smtp_user = rcube_utils::idn_to_ascii($smtp_user);
156      }
157
158      $result = $this->conn->auth($smtp_user, $smtp_pass, $smtp_auth_type, $use_tls, $smtp_authz);
159
160      if (PEAR::isError($result))
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();
165        $this->disconnect();
166        return false;
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
187   * @param mixed  The full text of the message body, including any Mime parts
188   *               or file handle
189   * @param array  Delivery options (e.g. DSN request)
190   *
191   * @return bool  Returns true on success, or false on error
192   */
193  public function send_mail($from, $recipients, &$headers, &$body, $opts=null)
194  {
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();
213      $this->response[] = "Invalid message headers";
214      return false;
215    }
216
217    // exit if no from address is given
218    if (!isset($from))
219    {
220      $this->reset();
221      $this->response[] = "No From address has been provided";
222      return false;
223    }
224
225    // RFC3461: Delivery Status Notification
226    if ($opts['dsn']) {
227      $exts = $this->conn->getServiceExtensions();
228
229      if (isset($exts['DSN'])) {
230        $from_params      = 'RET=HDRS';
231        $recipient_params = 'NOTIFY=SUCCESS,FAILURE';
232      }
233    }
234
235    // RFC2298.3: remove envelope sender address
236    if (preg_match('/Content-Type: multipart\/report/', $text_headers)
237      && preg_match('/report-type=disposition-notification/', $text_headers)
238    ) {
239      $from = '';
240    }
241
242    // set From: address
243    if (PEAR::isError($this->conn->mailFrom($from, $from_params)))
244    {
245      $err = $this->conn->getResponse();
246      $this->error = array('label' => 'smtpfromerror', 'vars' => array(
247        'from' => $from, 'code' => $this->conn->_code, 'msg' => $err[1]));
248      $this->response[] = "Failed to set sender '$from'";
249      $this->reset();
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    {
265      if (PEAR::isError($this->conn->rcptTo($recipient, $recipient_params))) {
266        $err = $this->conn->getResponse();
267        $this->error = array('label' => 'smtptoerror', 'vars' => array(
268          'to' => $recipient, 'code' => $this->conn->_code, 'msg' => $err[1]));
269        $this->response[] = "Failed to add recipient '$recipient'";
270        $this->reset();
271        return false;
272      }
273    }
274
275    if (is_resource($body))
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;
286
287      // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
288      unset($text_headers, $body);
289    }
290
291    // Send the message's headers and the body as SMTP data.
292    if (PEAR::isError($result = $this->conn->data($data, $text_headers)))
293    {
294      $err = $this->conn->getResponse();
295      if (!in_array($err[0], array(354, 250, 221)))
296        $msg = sprintf('[%d] %s', $err[0], $err[1]);
297      else
298        $msg = $result->getMessage();
299
300      $this->error = array('label' => 'smtperror', 'vars' => array('msg' => $msg));
301      $this->response[] = "Failed to send data";
302      $this->reset();
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  {
341    rcube::write_log('smtp', preg_replace('/\r\n$/', '', $message));
342  }
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.
396        if (strpos($from, ' ') !== false)
397          return false;
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);
450
451    $addresses = array();
452    $recipients = rcube_utils::explode_quoted_string(',', $recipients);
453
454    reset($recipients);
455    while (list($k, $recipient) = each($recipients))
456    {
457      $a = rcube_utils::explode_quoted_string(' ', $recipient);
458      while (list($k2, $word) = each($a))
459      {
460        if (strpos($word, "@") > 0 && $word[strlen($word)-1] != '"')
461        {
462          $word = preg_replace('/^<|>$/', '', trim($word));
463          if (in_array($word, $addresses)===false)
464            array_push($addresses, $word);
465        }
466      }
467    }
468
469    return $addresses;
470  }
471
472}
Note: See TracBrowser for help on using the repository browser.