]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_smtp.inc
Imported Upstream version 0.1~rc1
[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 587 2007-05-28 19:21:36Z 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, &$response)
53   {
54   global $SMTP_CONN, $CONFIG;
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       $response[] = "Connection failed: ".$result->getMessage();
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         $response[] .= "Authentication failure: ".$result->getMessage();
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     $response[] .= "Invalid message headers";
136     return FALSE;
137     }
138
139   // exit if no from address is given
140   if (!isset($from))
141     {
142     smtp_reset();
143     $response[] .= "No From address has been provided";
144     return FALSE;
145     }
146
147
148   // set From: address
149   if (PEAR::isError($SMTP_CONN->mailFrom($from)))
150     {
151     smtp_reset();
152     $response[] .= "Failed to set sender '$from'";
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       $response[] .= "Failed to add recipient '$recipient'";
173       return FALSE;
174       }
175     }
176
177
178   // Concatenate headers and body so it can be passed by reference to SMTP_CONN->data
179   // so preg_replace in SMTP_CONN->quotedata will store a reference instead of a copy. 
180   // We are still forced to make another copy here for a couple ticks so we don't really 
181   // get to save a copy in the method call.
182   $data = $text_headers . "\r\n" . $body;
183
184   // unset old vars to save data and so we can pass into SMTP_CONN->data by reference.
185   unset($text_headers, $body);
186    
187   // Send the message's headers and the body as SMTP data.
188   if (PEAR::isError($SMTP_CONN->data($data)))
189     {
190     smtp_reset();
191     $response[] .= "Failed to send data";
192     return FALSE;
193     }
194
195   $response[] = join(': ', $SMTP_CONN->getResponse());
196   return TRUE;
197   }
198
199
200
201 /**
202  * Reset the global SMTP connection
203  * @access public
204  */
205 function smtp_reset()
206   {
207   global $SMTP_CONN;
208
209   if (is_object($SMTP_CONN))
210     {
211     $SMTP_CONN->rset();
212     smtp_disconnect();
213     }
214   }
215
216
217
218 /**
219  * Disconnect the global SMTP connection and destroy object
220  * @access public
221  */
222 function smtp_disconnect()
223   {
224   global $SMTP_CONN;
225
226   if (is_object($SMTP_CONN))
227     {
228     $SMTP_CONN->disconnect();
229     $SMTP_CONN = null;
230     }
231   }
232
233
234 /**
235  * Take an array of mail headers and return a string containing
236  * text usable in sending a message.
237  *
238  * @param array $headers The array of headers to prepare, in an associative
239  *              array, where the array key is the header name (ie,
240  *              'Subject'), and the array value is the header
241  *              value (ie, 'test'). The header produced from those
242  *              values would be 'Subject: test'.
243  *
244  * @return mixed Returns false if it encounters a bad address,
245  *               otherwise returns an array containing two
246  *               elements: Any From: address found in the headers,
247  *               and the plain text version of the headers.
248  * @access private
249  */
250 function smtp_prepare_headers($headers)
251   {
252   $lines = array();
253   $from = null;
254
255   foreach ($headers as $key => $value)
256     {
257     if (strcasecmp($key, 'From') === 0)
258       {
259       $addresses = smtp_parse_rfc822($value);
260
261       if (is_array($addresses))
262         $from = $addresses[0];
263
264       // Reject envelope From: addresses with spaces.
265       if (strstr($from, ' '))
266         return FALSE;
267
268
269       $lines[] = $key . ': ' . $value;
270       }
271     else if (strcasecmp($key, 'Received') === 0)
272       {
273       $received = array();
274       if (is_array($value))
275         {
276         foreach ($value as $line)
277           $received[] = $key . ': ' . $line;
278         }
279       else
280         {
281         $received[] = $key . ': ' . $value;
282         }
283
284       // Put Received: headers at the top.  Spam detectors often
285       // flag messages with Received: headers after the Subject:
286       // as spam.
287       $lines = array_merge($received, $lines);
288       }
289
290     else
291       {
292       // If $value is an array (i.e., a list of addresses), convert
293       // it to a comma-delimited string of its elements (addresses).
294       if (is_array($value))
295         $value = implode(', ', $value);
296
297       $lines[] = $key . ': ' . $value;
298       }
299     }
300
301   return array($from, join(SMTP_MIME_CRLF, $lines) . SMTP_MIME_CRLF);
302   }
303
304
305
306 /**
307  * Take a set of recipients and parse them, returning an array of
308  * bare addresses (forward paths) that can be passed to sendmail
309  * or an smtp server with the rcpt to: command.
310  *
311  * @param mixed Either a comma-seperated list of recipients
312  *              (RFC822 compliant), or an array of recipients,
313  *              each RFC822 valid.
314  *
315  * @return array An array of forward paths (bare addresses).
316  * @access private
317  */
318 function smtp_parse_rfc822($recipients)
319   {
320   // if we're passed an array, assume addresses are valid and implode them before parsing.
321   if (is_array($recipients))
322     $recipients = implode(', ', $recipients);
323     
324   $addresses = array();
325   $recipients = smtp_explode_quoted_str(",", $recipients);
326   
327   reset($recipients);
328   while (list($k, $recipient) = each($recipients))
329     {
330   $a = explode(" ", $recipient);
331   while (list($k2, $word) = each($a))
332     {
333       if ((strpos($word, "@") > 0) && (strpos($word, "\"")===false))
334         {
335         $word = ereg_replace('^<|>$', '', trim($word));
336         if (in_array($word, $addresses)===false)
337           array_push($addresses, $word);
338         }
339       }
340     }
341   return $addresses;
342   }
343
344
345 function smtp_explode_quoted_str($delimiter, $string)
346   {
347   $quotes=explode("\"", $string);
348   while ( list($key, $val) = each($quotes))
349     if (($key % 2) == 1) 
350       $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
351     $string=implode("\"", $quotes);
352   
353     $result=explode($delimiter, $string);
354     while (list($key, $val) = each($result))
355       $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
356
357   return $result;
358   } 
359
360
361 ?>