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