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

Last change on this file since 805 was 805, checked in by robin, 6 years ago

Fix order of checks.

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