source: tags/2.0.1/lib/Email.inc.php

Last change on this file was 126, checked in by scdev, 18 years ago

Q - Releasing tags/2.0.1, use branches/2.0 for maintaining.

File size: 13.1 KB
Line 
1<?php
2/**
3 * Email.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * Easy email template usage.
7 *
8 * @author  Quinn Comendant <quinn@strangecode.com>
9 * @version 1.0
10-------------------------------------------------------------------------------------
11// Example.
12$email = new Email(array(
13    'to' => array($frm['email'], 'q@lovemachine.local'),
14    'from' => sprintf('%s <%s>', App::getParam('site_name'), App::getParam('site_email')),
15    'subject' => 'Your account has been activated',
16));
17$email->setTemplate('email_registration_confirm.ihtml');
18// $email->setString('Or you can pass your message body as a string, also with {VARIABLES}.');
19$email->replace(array(
20    'site_name' => App::getParam('site_name'),
21    'site_url' => App::getParam('site_url'),
22    'username' => $frm['username'],
23    'password' => $frm['password1'],
24));
25if ($email->send()) {
26    App::raiseMsg(sprintf(_("A confirmation email has been sent to %s."), $frm['email']), MSG_SUCCESS, __FILE__, __LINE__);
27} else {
28    App::logMsg(sprintf('Error sending confirmation email to address %s', $frm['email']), LOG_NOTICE, __FILE__, __LINE__);
29}
30-------------------------------------------------------------------------------------
31 */
32class Email {
33
34    // Default parameters, to be overwritten by setParam() and read with getParam()
35    var $_params = array(
36        'to' => null,
37        'from' => null,
38        'subject' => null,
39        'headers' => null,
40        'regex' => null
41    );
42
43    // String that contains the email body.
44    var $_template;
45
46    // String that contains the email body after replacements.
47    var $_template_replaced;
48
49    /**
50     * Constructor.
51     *
52     * @access  public
53     * @param   array   $params     Array of object parameters.
54     * @author  Quinn Comendant <quinn@strangecode.com>
55     * @since   28 Nov 2005 12:59:41
56     */
57    function Email($params=null)
58    {
59        // The regex used in validEmail(). Set here instead of in the default _params above so we can use the concatination . dot.
60        // This matches an email address as complex as:
61        //      Bob Smith <bob&smith's/dep=sales!@smith-wick.ca.us> (Sales department)
62        // ...and something as simple as:
63        //      x@x.com
64        $this->setParam(array('regex' => '/^(?:[^,@]*\s+|[^,@]*(<)|)'   // Display name
65        . '((?:[^.<>\s@\",\[\]]+[^<>\s@\",\[\]])*[^.<>\s@\",\[\]]+)'    // Local-part
66        . '@'                                                           // @
67        . '((?:(\[)|[A-Z0-9]?)'                                         // Domain, first char
68        . '(?(4)'                                                       // Domain conditional for if first domain char is [
69        . '(?:[0-9]{1,3}\.){3}[0-9]{1,3}\]'                             // TRUE, matches IP address
70        . '|'
71        . '[.-]?(?:[A-Z0-9]+[-.])*(?:[A-Z0-9]+\.)+[A-Z]{2,6}))'         // FALSE, matches domain name
72        . '(?(1)'                                                       // Comment conditional for if initial < exists
73        . '(?:>\s*|>\s+\([^,@]+\)\s*)'                                  // TRUE, ensure ending >
74        . '|'
75        . '(?:|\s*|\s+\([^,@]+\)\s*))$/i'));                            // FALSE ensure there is no ending >
76
77        if (isset($params)) {
78            $this->setParam($params);
79        }
80    }
81
82    /**
83     * Set (or overwrite existing) parameters by passing an array of new parameters.
84     *
85     * @access public
86     * @param  array    $params     Array of parameters (key => val pairs).
87     */
88    function setParam($params)
89    {
90        if (isset($params) && is_array($params)) {
91            // Enforce valid email addresses.
92            if (isset($params['to']) && !$this->validEmail($params['to'])) {
93                $params['to'] = null;
94            }
95            if (isset($params['from']) && !$this->validEmail($params['from'])) {
96                $params['from'] = null;
97            }
98
99            // Merge new parameters with old overriding only those passed.
100            $this->_params = array_merge($this->_params, $params);
101        } else {
102            App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
103        }
104    }
105
106    /**
107     * Return the value of a parameter, if it exists.
108     *
109     * @access public
110     * @param string $param        Which parameter to return.
111     * @return mixed               Configured parameter value.
112     */
113    function getParam($param)
114    {
115        if (isset($this->_params[$param])) {
116            return $this->_params[$param];
117        } else {
118            App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
119            return null;
120        }
121    }
122
123    /**
124     * Loads template from file to generate email body.
125     *
126     * @access  public
127     * @param   string  $template   Filename of email template.
128     * @author  Quinn Comendant <quinn@strangecode.com>
129     * @since   28 Nov 2005 12:56:23
130     */
131    function setTemplate($template)
132    {
133        // Load file, using include_path.
134        if (!$this->_template = file_get_contents($template, true)) {
135            App::logMsg(sprintf('Email template file does not exist: %s', $template), LOG_ERR, __FILE__, __LINE__);
136            $this->_template = null;
137            $this->_template_replaced = null;
138            return false;
139        }
140        // This could be a new template, so reset the _template_replaced.
141        $this->_template_replaced = null;
142        return true;
143    }
144
145    /**
146     * Loads template from string to generate email body.
147     *
148     * @access  public
149     * @param   string  $template   Filename of email template.
150     * @author  Quinn Comendant <quinn@strangecode.com>
151     * @since   28 Nov 2005 12:56:23
152     */
153    function setString($string)
154    {
155        // Load file, using include_path.
156        if ('' == trim($string)) {
157            App::logMsg(sprintf('Empty string provided.', null), LOG_ERR, __FILE__, __LINE__);
158            $this->_template_replaced = null;
159            return false;
160        } else {
161            $this->_template = $string;
162            // This could be a new template, so reset the _template_replaced.
163            $this->_template_replaced = null;
164            return true;
165        }
166    }
167
168    /**
169     * Replace variables in template with argument data.
170     *
171     * @access  public
172     * @param   array   $replacements   Array keys are the values to search for, array vales are the replacement values.
173     * @author  Quinn Comendant <quinn@strangecode.com>
174     * @since   28 Nov 2005 13:08:51
175     */
176    function replace($replacements)
177    {
178        // Ensure template exists.
179        if (!isset($this->_template)) {
180            App::logMsg(sprintf('Cannot replace variables, no template defined.', null), LOG_ERR, __FILE__, __LINE__);
181            return false;
182        }
183
184        // Ensure replacements argument is an array.
185        if (!is_array($replacements)) {
186            App::logMsg(sprintf('Cannot replace variables, invalid replacements.', null), LOG_ERR, __FILE__, __LINE__);
187            return false;
188        }
189
190        // Apply regex pattern to search elements.
191        $search = array_keys($replacements);
192        array_walk($search, create_function('&$v', '$v = "/{" . preg_quote($v) . "}/i";'));
193
194        // Replacement values.
195        $replace = array_values($replacements);
196
197        // Search and replace all values at once.
198        $this->_template_replaced = preg_replace($search, $replace, $this->_template);
199    }
200
201    /**
202     * Send email using PHP's mail() function.
203     *
204     * @access  public
205     * @param   string  $to
206     * @param   string  $from
207     * @param   string  $subject
208     * @author  Quinn Comendant <quinn@strangecode.com>
209     * @since   28 Nov 2005 12:56:09
210     */
211    function send($to=null, $from=null, $subject=null, $headers=null)
212    {
213        // Use arguments if provided.
214        if (isset($to)) {
215             $this->setParam(array('to' => $to));
216        }
217        if (isset($from)) {
218             $this->setParam(array('from' => $from));
219        }
220        if (isset($subject)) {
221             $this->setParam(array('subject' => $subject));
222        }
223        if (isset($headers)) {
224             $this->setParam(array('headers' => $headers));
225        }
226
227        // Ensure required values exist.
228        if (!isset($this->_params['subject'])) {
229            App::logMsg(sprintf('Cannot send email to %s. SUBJECT not defined.', $this->_params['to']), LOG_ERR, __FILE__, __LINE__);
230            return false;
231        } else if (!isset($this->_template)) {
232            App::logMsg(sprintf('Cannot send email: "%s". Template not set.', $this->_params['subject']), LOG_ERR, __FILE__, __LINE__);
233            return false;
234        } else if (!isset($this->_params['to'])) {
235            App::logMsg(sprintf('Cannot send email: "%s". TO not defined.', $this->_params['subject']), LOG_NOTICE, __FILE__, __LINE__);
236            return false;
237        } else if (!isset($this->_params['from'])) {
238            App::logMsg(sprintf('Cannot send email: "%s". FROM not defined.', $this->_params['subject']), LOG_ERR, __FILE__, __LINE__);
239            return false;
240        }
241
242        // Wrap email text body, using _template_replaced if replacements have been used, or just a fresh _template if not.
243        $final_body = wordwrap(isset($this->_template_replaced) ? $this->_template_replaced : $this->_template);
244
245        // Ensure all placeholders have been replaced. Find anything with {...} characters.
246        if (preg_match('/({[^}]+})/', $final_body, $unreplaced_match)) {
247            App::logMsg(sprintf('Cannot send email. Variables left unreplaced in template: %s', (isset($unreplaced_match[1]) ? $unreplaced_match[1] : '')), LOG_ERR, __FILE__, __LINE__);
248            return false;
249        }
250
251        // Final "to" header can have multiple addresses if in an array.
252        $final_to = is_array($this->_params['to']) ? join(', ', $this->_params['to']) : $this->_params['to'];
253
254        // From headers are custom headers.
255        $headers = array('From' => $this->_params['from']);
256
257        // Additional headers.
258        if (isset($this->_params['headers']) && is_array($this->_params['headers'])) {
259            $headers = array_merge($this->_params['headers'], $headers);
260        }
261
262        // Process headers.
263        $final_headers = array();
264        foreach ($headers as $key => $val) {
265            $final_headers[] = sprintf('%s: %s', $key, $val);
266        }
267        $final_headers = join("\r\n", $final_headers);
268
269        // This is the address where delivery problems are sent to. We must strip off everything except the local@domain part.
270        $envelope_sender_header = sprintf('-f %s', preg_replace('/^.*<?([^\s@\[\]<>()]+\@[A-Za-z0-9.-]{1,}\.[A-Za-z]{2,5})>?$/iU', '$1', $this->_params['from']));
271
272        // Check for mail header injection attacks.
273        $full_mail_content = join("\n", array($final_to, $this->_params['subject'], $final_body, $final_headers, $envelope_sender_header));
274        if (preg_match("/(Content-Type:|MIME-Version:|Content-Transfer-Encoding:|[\n\r]Bcc:|[\n\r]Cc:)/i", $full_mail_content)) {
275            App::logMsg(sprintf('Mail header injection attack in content: %s', $full_mail_content), LOG_WARNING, __FILE__, __LINE__);
276            sleep(3);
277            return false;
278        }
279
280        // Ensure message was successfully accepted for delivery.
281        if (mail($final_to, $this->_params['subject'], $final_body, $final_headers, $envelope_sender_header)) {
282            App::logMsg(sprintf('Email successfully sent to %s', $final_to), LOG_DEBUG, __FILE__, __LINE__);
283            return true;
284        } else {
285            App::logMsg(sprintf('Email failure with parameters: %s, %s, %s, %s', $final_to, $this->_params['subject'], str_replace("\r\n", '\r\n', $final_headers), $envelope_sender_header), LOG_NOTICE, __FILE__, __LINE__);
286            return false;
287        }
288    }
289
290    /**
291     * Validates an email address based on the recommendations in RFC 3696.
292     * Is more loose than restrictive, to allow the many valid variants of
293     * email addresses while catching the most common mistakes. Checks an array too.
294     * http://www.faqs.org/rfcs/rfc822.html
295     * http://www.faqs.org/rfcs/rfc2822.html
296     * http://www.faqs.org/rfcs/rfc3696.html
297     * http://www.faqs.org/rfcs/rfc1035.html
298     *
299     * @access  public
300     * @param   mixed  $email  Address to check, string or array.
301     * @return  bool    Validity of address.
302     * @author  Quinn Comendant <quinn@strangecode.com>
303     * @since   30 Nov 2005 22:00:50
304     */
305    function validEmail($email)
306    {
307        // If an array, check values recursively.
308        if (is_array($email)) {
309            foreach ($email as $e) {
310                if (!$this->validEmail($e)) {
311                    return false;
312                }
313            }
314            return true;
315        } else {
316            // To be valid email address must match regex and fit within the lenth constraints.
317            if (preg_match($this->getParam('regex'), $email, $e_parts) && strlen($e_parts[2]) < 64 && strlen($e_parts[3]) < 255) {
318                return true;
319            } else {
320                App::logMsg(sprintf('Invalid email: %s', $email), LOG_INFO, __FILE__, __LINE__);
321                return false;
322            }
323        }
324    }
325}
326
327?>
Note: See TracBrowser for help on using the repository browser.