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