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