source: subversion/trunk/roundcubemail/program/include/rcube_smtp.inc @ 2016

Last change on this file since 2016 was 2016, checked in by alec, 5 years ago

#1485518: validate SERVER_NAME for smtp_helo_host setting

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 10.0 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_smtp.inc                                        |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland                 |
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$
19
20*/
21
22/**
23 * SMTP delivery functions
24 *
25 * @package Mail
26 */
27
28// include required PEAR classes
29require_once('Net/SMTP.php');
30
31
32// define headers delimiter
33define('SMTP_MIME_CRLF', "\r\n");
34
35$SMTP_CONN = null;
36
37/**
38 * Function for sending mail using SMTP.
39 *
40 * @param string Sender e-Mail address
41 *
42 * @param mixed  Either a comma-seperated list of recipients
43 *               (RFC822 compliant), or an array of recipients,
44 *               each RFC822 valid. This may contain recipients not
45 *               specified in the headers, for Bcc:, resending
46 *               messages, etc.
47 *
48 * @param mixed  The message headers to send with the mail
49 *               Either as an associative array or a finally
50 *               formatted string
51 *
52 * @param string The full text of the message body, including any Mime parts, etc.
53 *
54 * @return bool  Returns TRUE on success, or FALSE on error
55 */
56function smtp_mail($from, $recipients, &$headers, &$body, &$response)
57  {
58  global $SMTP_CONN, $CONFIG, $RCMAIL;
59  $smtp_timeout = null;
60  $smtp_host = $CONFIG['smtp_server'];
61  $smtp_port = is_numeric($CONFIG['smtp_port']) ? $CONFIG['smtp_port'] : 25;
62  $smtp_host_url = parse_url($CONFIG['smtp_server']);
63 
64  // overwrite port
65  if (isset($smtp_host_url['host']) && isset($smtp_host_url['port']))
66    {
67    $smtp_host = $smtp_host_url['host'];
68    $smtp_port = $smtp_host_url['port'];
69    }
70
71  // re-write smtp host
72  if (isset($smtp_host_url['host']) && isset($smtp_host_url['scheme']))
73    $smtp_host = sprintf('%s://%s', $smtp_host_url['scheme'], $smtp_host_url['host']);
74
75
76  // create Net_SMTP object and connect to server
77  if (!is_object($SMTP_CONN))
78    {
79    if (!empty($CONFIG['smtp_helo_host']))
80      $helo_host = $CONFIG['smtp_helo_host'];
81    else if (!empty($_SERVER['SERVER_NAME']))
82      $helo_host = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
83    else
84      $helo_host = 'localhost';
85
86    $SMTP_CONN = new Net_SMTP($smtp_host, $smtp_port, $helo_host);
87
88    // set debugging
89    if ($CONFIG['debug_level'] & 8)
90      $SMTP_CONN->setDebug(TRUE);
91
92    // try to connect to server and exit on failure
93    $result = $SMTP_CONN->connect($smtp_timeout);
94    if (PEAR::isError($result))
95      {
96      $SMTP_CONN = null;
97      $response[] = "Connection failed: ".$result->getMessage();
98      return FALSE;
99      }
100     
101    // attempt to authenticate to the SMTP server
102    if ($CONFIG['smtp_user'] && $CONFIG['smtp_pass'])
103      {
104      if (strstr($CONFIG['smtp_user'], '%u'))
105        $smtp_user = str_replace('%u', $_SESSION['username'], $CONFIG['smtp_user']);
106      else
107        $smtp_user = $CONFIG['smtp_user'];
108
109      if (strstr($CONFIG['smtp_pass'], '%p'))
110        $smtp_pass = str_replace('%p', $RCMAIL->decrypt_passwd($_SESSION['password']), $CONFIG['smtp_pass']);
111      else
112        $smtp_pass = $CONFIG['smtp_pass'];
113
114      $smtp_auth_type = empty($CONFIG['smtp_auth_type']) ? NULL : $CONFIG['smtp_auth_type'];
115      $result = $SMTP_CONN->auth($smtp_user, $smtp_pass, $smtp_auth_type);
116   
117      if (PEAR::isError($result))
118        {
119        smtp_reset();
120        $response[] .= 'Authentication failure: ' . $result->getMessage() . ' (Code: ' . $result->getCode() . ')';
121        return FALSE;
122        }
123      }
124    }
125
126
127  // prepare message headers as string
128  if (is_array($headers))
129    {
130    $headerElements = smtp_prepare_headers($headers);
131    if (!$headerElements)
132      {
133      smtp_reset();
134      return FALSE;
135      }
136
137    list($from, $text_headers) = $headerElements;
138    }
139  else if (is_string($headers))
140    $text_headers = $headers;
141  else
142    {
143    smtp_reset();
144    $response[] .= "Invalid message headers";
145    return FALSE;
146    }
147
148  // exit if no from address is given
149  if (!isset($from))
150    {
151    smtp_reset();
152    $response[] .= "No From address has been provided";
153    return FALSE;
154    }
155
156
157  // set From: address
158  if (PEAR::isError($SMTP_CONN->mailFrom($from)))
159    {
160    smtp_reset();
161    $response[] .= "Failed to set sender '$from'";
162    return FALSE;
163    }
164
165
166  // prepare list of recipients
167  $recipients = smtp_parse_rfc822($recipients);
168  if (PEAR::isError($recipients))
169    {
170    smtp_reset();
171    return FALSE;
172    }
173
174
175  // set mail recipients
176  foreach ($recipients as $recipient)
177    {
178    if (PEAR::isError($SMTP_CONN->rcptTo($recipient)))
179      {
180      smtp_reset();
181      $response[] .= "Failed to add recipient '$recipient'";
182      return FALSE;
183      }
184    }
185
186
187  // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
188  // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy.
189  // We are still forced to make another copy here for a couple ticks so we don't really
190  // get to save a copy in the method call.
191  $data = $text_headers . "\r\n" . $body;
192
193  // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
194  unset($text_headers, $body);
195   
196  // Send the message's headers and the body as SMTP data.
197  if (PEAR::isError($SMTP_CONN->data($data)))
198    {
199    smtp_reset();
200    $response[] .= "Failed to send data";
201    return FALSE;
202    }
203
204  $response[] = join(': ', $SMTP_CONN->getResponse());
205  return TRUE;
206  }
207
208
209
210/**
211 * Reset the global SMTP connection
212 * @access public
213 */
214function smtp_reset()
215  {
216  global $SMTP_CONN;
217
218  if (is_object($SMTP_CONN))
219    {
220    $SMTP_CONN->rset();
221    smtp_disconnect();
222    }
223  }
224
225
226
227/**
228 * Disconnect the global SMTP connection and destroy object
229 * @access public
230 */
231function smtp_disconnect()
232  {
233  global $SMTP_CONN;
234
235  if (is_object($SMTP_CONN))
236    {
237    $SMTP_CONN->disconnect();
238    $SMTP_CONN = null;
239    }
240  }
241
242
243/**
244 * Take an array of mail headers and return a string containing
245 * text usable in sending a message.
246 *
247 * @param array $headers The array of headers to prepare, in an associative
248 *              array, where the array key is the header name (ie,
249 *              'Subject'), and the array value is the header
250 *              value (ie, 'test'). The header produced from those
251 *              values would be 'Subject: test'.
252 *
253 * @return mixed Returns false if it encounters a bad address,
254 *               otherwise returns an array containing two
255 *               elements: Any From: address found in the headers,
256 *               and the plain text version of the headers.
257 * @access private
258 */
259function smtp_prepare_headers($headers)
260  {
261  $lines = array();
262  $from = null;
263
264  foreach ($headers as $key => $value)
265    {
266    if (strcasecmp($key, 'From') === 0)
267      {
268      $addresses = smtp_parse_rfc822($value);
269
270      if (is_array($addresses))
271        $from = $addresses[0];
272
273      // Reject envelope From: addresses with spaces.
274      if (strstr($from, ' '))
275        return FALSE;
276
277
278      $lines[] = $key . ': ' . $value;
279      }
280    else if (strcasecmp($key, 'Received') === 0)
281      {
282      $received = array();
283      if (is_array($value))
284        {
285        foreach ($value as $line)
286          $received[] = $key . ': ' . $line;
287        }
288      else
289        {
290        $received[] = $key . ': ' . $value;
291        }
292
293      // Put Received: headers at the top.  Spam detectors often
294      // flag messages with Received: headers after the Subject:
295      // as spam.
296      $lines = array_merge($received, $lines);
297      }
298
299    else
300      {
301      // If $value is an array (i.e., a list of addresses), convert
302      // it to a comma-delimited string of its elements (addresses).
303      if (is_array($value))
304        $value = implode(', ', $value);
305
306      $lines[] = $key . ': ' . $value;
307      }
308    }
309
310  return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
311  }
312
313
314
315/**
316 * Take a set of recipients and parse them, returning an array of
317 * bare addresses (forward paths) that can be passed to sendmail
318 * or an smtp server with the rcpt to: command.
319 *
320 * @param mixed Either a comma-seperated list of recipients
321 *              (RFC822 compliant), or an array of recipients,
322 *              each RFC822 valid.
323 *
324 * @return array An array of forward paths (bare addresses).
325 * @access private
326 */
327function smtp_parse_rfc822($recipients)
328  {
329  // if we're passed an array, assume addresses are valid and implode them before parsing.
330  if (is_array($recipients))
331    $recipients = implode(', ', $recipients);
332   
333  $addresses = array();
334  $recipients = smtp_explode_quoted_str(",", $recipients);
335 
336  reset($recipients);
337  while (list($k, $recipient) = each($recipients))
338    {
339  $a = explode(" ", $recipient);
340  while (list($k2, $word) = each($a))
341    {
342      if ((strpos($word, "@") > 0) && (strpos($word, "\"")===false))
343        {
344        $word = ereg_replace('^<|>$', '', trim($word));
345        if (in_array($word, $addresses)===false)
346          array_push($addresses, $word);
347        }
348      }
349    }
350  return $addresses;
351  }
352
353
354/**
355 * @access private
356 */
357function smtp_explode_quoted_str($delimiter, $string)
358  {
359  $quotes=explode("\"", $string);
360  while ( list($key, $val) = each($quotes))
361    if (($key % 2) == 1)
362      $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
363    $string=implode("\"", $quotes);
364 
365    $result=explode($delimiter, $string);
366    while (list($key, $val) = each($result))
367      $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
368
369  return $result;
370  }
371
372
373?>
Note: See TracBrowser for help on using the repository browser.