Updated PEAR and PEAR packages.
[timetracker.git] / WEB-INF / lib / pear / Mail / smtp.php
1 <?php
2 /**
3  * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
4  *
5  * PHP version 5
6  *
7  * LICENSE:
8  *
9  * Copyright (c) 2010, Chuck Hagenbuch
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  *
16  * o Redistributions of source code must retain the above copyright
17  *   notice, this list of conditions and the following disclaimer.
18  * o Redistributions in binary form must reproduce the above copyright
19  *   notice, this list of conditions and the following disclaimer in the
20  *   documentation and/or other materials provided with the distribution.
21  * o The names of the authors may not be used to endorse or promote
22  *   products derived from this software without specific prior written
23  *   permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  *
37  * @category    HTTP
38  * @package     HTTP_Request
39  * @author      Jon Parise <jon@php.net> 
40  * @author      Chuck Hagenbuch <chuck@horde.org>
41  * @copyright   2010 Chuck Hagenbuch
42  * @license     http://opensource.org/licenses/bsd-license.php New BSD License
43  * @version     CVS: $Id$
44  * @link        http://pear.php.net/package/Mail/
45  */
46
47 /** Error: Failed to create a Net_SMTP object */
48 define('PEAR_MAIL_SMTP_ERROR_CREATE', 10000);
49
50 /** Error: Failed to connect to SMTP server */
51 define('PEAR_MAIL_SMTP_ERROR_CONNECT', 10001);
52
53 /** Error: SMTP authentication failure */
54 define('PEAR_MAIL_SMTP_ERROR_AUTH', 10002);
55
56 /** Error: No From: address has been provided */
57 define('PEAR_MAIL_SMTP_ERROR_FROM', 10003);
58
59 /** Error: Failed to set sender */
60 define('PEAR_MAIL_SMTP_ERROR_SENDER', 10004);
61
62 /** Error: Failed to add recipient */
63 define('PEAR_MAIL_SMTP_ERROR_RECIPIENT', 10005);
64
65 /** Error: Failed to send data */
66 define('PEAR_MAIL_SMTP_ERROR_DATA', 10006);
67
68 /**
69  * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
70  * @access public
71  * @package Mail
72  * @version $Revision$
73  */
74 class Mail_smtp extends Mail {
75
76     /**
77      * SMTP connection object.
78      *
79      * @var object
80      * @access private
81      */
82     var $_smtp = null;
83
84     /**
85      * The list of service extension parameters to pass to the Net_SMTP
86      * mailFrom() command.
87      * @var array
88      */
89     var $_extparams = array();
90
91     /**
92      * The SMTP host to connect to.
93      * @var string
94      */
95     var $host = 'localhost';
96
97     /**
98      * The port the SMTP server is on.
99      * @var integer
100      */
101     var $port = 25;
102
103     /**
104      * Should SMTP authentication be used?
105      *
106      * This value may be set to true, false or the name of a specific
107      * authentication method.
108      *
109      * If the value is set to true, the Net_SMTP package will attempt to use
110      * the best authentication method advertised by the remote SMTP server.
111      *
112      * @var mixed
113      */
114     var $auth = false;
115
116     /**
117      * The username to use if the SMTP server requires authentication.
118      * @var string
119      */
120     var $username = '';
121
122     /**
123      * The password to use if the SMTP server requires authentication.
124      * @var string
125      */
126     var $password = '';
127
128     /**
129      * Hostname or domain that will be sent to the remote SMTP server in the
130      * HELO / EHLO message.
131      *
132      * @var string
133      */
134     var $localhost = 'localhost';
135
136     /**
137      * SMTP connection timeout value.  NULL indicates no timeout.
138      *
139      * @var integer
140      */
141     var $timeout = null;
142
143     /**
144      * Turn on Net_SMTP debugging?
145      *
146      * @var boolean $debug
147      */
148     var $debug = false;
149
150     /**
151      * Indicates whether or not the SMTP connection should persist over
152      * multiple calls to the send() method.
153      *
154      * @var boolean
155      */
156     var $persist = false;
157
158     /**
159      * Use SMTP command pipelining (specified in RFC 2920) if the SMTP server
160      * supports it. This speeds up delivery over high-latency connections. By
161      * default, use the default value supplied by Net_SMTP.
162      * @var bool
163      */
164     var $pipelining;
165     
166     var $socket_options = array();
167
168     /**
169      * Constructor.
170      *
171      * Instantiates a new Mail_smtp:: object based on the parameters
172      * passed in. It looks for the following parameters:
173      *     host        The server to connect to. Defaults to localhost.
174      *     port        The port to connect to. Defaults to 25.
175      *     auth        SMTP authentication.  Defaults to none.
176      *     username    The username to use for SMTP auth. No default.
177      *     password    The password to use for SMTP auth. No default.
178      *     localhost   The local hostname / domain. Defaults to localhost.
179      *     timeout     The SMTP connection timeout. Defaults to none.
180      *     verp        Whether to use VERP or not. Defaults to false.
181      *                 DEPRECATED as of 1.2.0 (use setMailParams()).
182      *     debug       Activate SMTP debug mode? Defaults to false.
183      *     persist     Should the SMTP connection persist?
184      *     pipelining  Use SMTP command pipelining
185      *
186      * If a parameter is present in the $params array, it replaces the
187      * default.
188      *
189      * @param array Hash containing any parameters different from the
190      *              defaults.
191      */
192     public function __construct($params)
193     {
194         if (isset($params['host'])) $this->host = $params['host'];
195         if (isset($params['port'])) $this->port = $params['port'];
196         if (isset($params['auth'])) $this->auth = $params['auth'];
197         if (isset($params['username'])) $this->username = $params['username'];
198         if (isset($params['password'])) $this->password = $params['password'];
199         if (isset($params['localhost'])) $this->localhost = $params['localhost'];
200         if (isset($params['timeout'])) $this->timeout = $params['timeout'];
201         if (isset($params['debug'])) $this->debug = (bool)$params['debug'];
202         if (isset($params['persist'])) $this->persist = (bool)$params['persist'];
203         if (isset($params['pipelining'])) $this->pipelining = (bool)$params['pipelining'];
204         if (isset($params['socket_options'])) $this->socket_options = $params['socket_options'];
205         // Deprecated options
206         if (isset($params['verp'])) {
207             $this->addServiceExtensionParameter('XVERP', is_bool($params['verp']) ? null : $params['verp']);
208         }
209     }
210
211     /**
212      * Destructor implementation to ensure that we disconnect from any
213      * potentially-alive persistent SMTP connections.
214      */
215     public function __destruct()
216     {
217         $this->disconnect();
218     }
219
220     /**
221      * Implements Mail::send() function using SMTP.
222      *
223      * @param mixed $recipients Either a comma-seperated list of recipients
224      *              (RFC822 compliant), or an array of recipients,
225      *              each RFC822 valid. This may contain recipients not
226      *              specified in the headers, for Bcc:, resending
227      *              messages, etc.
228      *
229      * @param array $headers The array of headers to send with the mail, in an
230      *              associative array, where the array key is the
231      *              header name (e.g., 'Subject'), and the array value
232      *              is the header value (e.g., 'test'). The header
233      *              produced from those values would be 'Subject:
234      *              test'.
235      *
236      * @param string $body The full text of the message body, including any
237      *               MIME parts, etc.
238      *
239      * @return mixed Returns true on success, or a PEAR_Error
240      *               containing a descriptive error message on
241      *               failure.
242      */
243     public function send($recipients, $headers, $body)
244     {
245         /* If we don't already have an SMTP object, create one. */
246         $result = $this->getSMTPObject();
247         if (PEAR::isError($result)) {
248             return $result;
249         }
250
251         if (!is_array($headers)) {
252             return PEAR::raiseError('$headers must be an array');
253         }
254
255         $this->_sanitizeHeaders($headers);
256
257         $headerElements = $this->prepareHeaders($headers);
258         if (is_a($headerElements, 'PEAR_Error')) {
259             $this->_smtp->rset();
260             return $headerElements;
261         }
262         list($from, $textHeaders) = $headerElements;
263
264         /* Since few MTAs are going to allow this header to be forged
265          * unless it's in the MAIL FROM: exchange, we'll use
266          * Return-Path instead of From: if it's set. */
267         if (!empty($headers['Return-Path'])) {
268             $from = $headers['Return-Path'];
269         }
270
271         if (!isset($from)) {
272             $this->_smtp->rset();
273             return PEAR::raiseError('No From: address has been provided',
274                                     PEAR_MAIL_SMTP_ERROR_FROM);
275         }
276
277         $params = null;
278         if (!empty($this->_extparams)) {
279             foreach ($this->_extparams as $key => $val) {
280                 $params .= ' ' . $key . (is_null($val) ? '' : '=' . $val);
281             }
282         }
283         if (PEAR::isError($res = $this->_smtp->mailFrom($from, ltrim($params)))) {
284             $error = $this->_error("Failed to set sender: $from", $res);
285             $this->_smtp->rset();
286             return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
287         }
288
289         $recipients = $this->parseRecipients($recipients);
290         if (is_a($recipients, 'PEAR_Error')) {
291             $this->_smtp->rset();
292             return $recipients;
293         }
294
295         foreach ($recipients as $recipient) {
296             $res = $this->_smtp->rcptTo($recipient);
297             if (is_a($res, 'PEAR_Error')) {
298                 $error = $this->_error("Failed to add recipient: $recipient", $res);
299                 $this->_smtp->rset();
300                 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
301             }
302         }
303
304         /* Send the message's headers and the body as SMTP data. */
305         $res = $this->_smtp->data($body, $textHeaders);
306                 list(,$args) = $this->_smtp->getResponse();
307
308                 if (preg_match("/Ok: queued as (.*)/", $args, $queued)) {
309                         $this->queued_as = $queued[1];
310                 }
311
312                 /* we need the greeting; from it we can extract the authorative name of the mail server we've really connected to.
313                  * ideal if we're connecting to a round-robin of relay servers and need to track which exact one took the email */
314                 $this->greeting = $this->_smtp->getGreeting();
315
316         if (is_a($res, 'PEAR_Error')) {
317             $error = $this->_error('Failed to send data', $res);
318             $this->_smtp->rset();
319             return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
320         }
321
322         /* If persistent connections are disabled, destroy our SMTP object. */
323         if ($this->persist === false) {
324             $this->disconnect();
325         }
326
327         return true;
328     }
329
330     /**
331      * Connect to the SMTP server by instantiating a Net_SMTP object.
332      *
333      * @return mixed Returns a reference to the Net_SMTP object on success, or
334      *               a PEAR_Error containing a descriptive error message on
335      *               failure.
336      *
337      * @since  1.2.0
338      */
339     public function getSMTPObject()
340     {
341         if (is_object($this->_smtp) !== false) {
342             return $this->_smtp;
343         }
344
345         include_once 'Net/SMTP.php';
346         $this->_smtp = new Net_SMTP($this->host,
347                                      $this->port,
348                                      $this->localhost,
349                                      $this->pipelining,
350                                      0,
351                                      $this->socket_options);
352
353         /* If we still don't have an SMTP object at this point, fail. */
354         if (is_object($this->_smtp) === false) {
355             return PEAR::raiseError('Failed to create a Net_SMTP object',
356                                     PEAR_MAIL_SMTP_ERROR_CREATE);
357         }
358
359         /* Configure the SMTP connection. */
360         if ($this->debug) {
361             $this->_smtp->setDebug(true);
362         }
363
364         /* Attempt to connect to the configured SMTP server. */
365         if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
366             $error = $this->_error('Failed to connect to ' .
367                                    $this->host . ':' . $this->port,
368                                    $res);
369             return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
370         }
371
372         /* Attempt to authenticate if authentication has been enabled. */
373         if ($this->auth) {
374             $method = is_string($this->auth) ? $this->auth : '';
375
376             if (PEAR::isError($res = $this->_smtp->auth($this->username,
377                                                         $this->password,
378                                                         $method))) {
379                 $error = $this->_error("$method authentication failure",
380                                        $res);
381                 $this->_smtp->rset();
382                 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
383             }
384         }
385
386         return $this->_smtp;
387     }
388
389     /**
390      * Add parameter associated with a SMTP service extension.
391      *
392      * @param string Extension keyword.
393      * @param string Any value the keyword needs.
394      *
395      * @since 1.2.0
396      */
397     public function addServiceExtensionParameter($keyword, $value = null)
398     {
399         $this->_extparams[$keyword] = $value;
400     }
401
402     /**
403      * Disconnect and destroy the current SMTP connection.
404      *
405      * @return boolean True if the SMTP connection no longer exists.
406      *
407      * @since  1.1.9
408      */
409     public function disconnect()
410     {
411         /* If we have an SMTP object, disconnect and destroy it. */
412         if (is_object($this->_smtp) && $this->_smtp->disconnect()) {
413             $this->_smtp = null;
414         }
415
416         /* We are disconnected if we no longer have an SMTP object. */
417         return ($this->_smtp === null);
418     }
419
420     /**
421      * Build a standardized string describing the current SMTP error.
422      *
423      * @param string $text  Custom string describing the error context.
424      * @param object $error Reference to the current PEAR_Error object.
425      *
426      * @return string       A string describing the current SMTP error.
427      *
428      * @since  1.1.7
429      */
430     protected function _error($text, $error)
431     {
432         /* Split the SMTP response into a code and a response string. */
433         list($code, $response) = $this->_smtp->getResponse();
434
435         /* Build our standardized error string. */
436         return $text
437             . ' [SMTP: ' . $error->getMessage()
438             . " (code: $code, response: $response)]";
439     }
440
441 }