source: branches/1.1dev/lib/Email.inc.php @ 608

Last change on this file since 608 was 567, checked in by anonymous, 8 years ago

Converting email templates to utf-8

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