source: trunk/lib/Email.inc.php @ 628

Last change on this file since 628 was 628, checked in by anonymous, 6 years ago

Add Email::SANDBOX_MODE_LOG

File size: 20.2 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24* Email.inc.php
25*
26* Easy email template usage.
27*
28* @author  Quinn Comendant <quinn@strangecode.com>
29* @version 1.0
30*
31* Example of use:
32---------------------------------------------------------------------
33// Setup email object.
34$email = new Email(array(
35    'to' => array($frm['email'], 'q@lovemachine.local'),
36    'from' => sprintf('"%s" <%s>', addcslashes($app->getParam('site_name'), '"'), $app->getParam('site_email')),
37    'subject' => 'Your account has been activated',
38));
39$email->setTemplate('email_registration_confirm.ihtml');
40// $email->setString('Or you can pass your message body as a string, also with {VARIABLES}.');
41$email->replace(array(
42    'site_name' => $app->getParam('site_name'),
43    'site_url' => $app->getParam('site_url'),
44    'username' => $frm['username'],
45    'password' => $frm['password1'],
46));
47if ($email->send()) {
48    $app->raiseMsg(sprintf(_("A confirmation email has been sent to %s."), $frm['email']), MSG_SUCCESS, __FILE__, __LINE__);
49} else {
50    $app->logMsg(sprintf('Error sending confirmation email to address %s', $frm['email']), LOG_NOTICE, __FILE__, __LINE__);
51}
52---------------------------------------------------------------------
53*/
54
55class Email
56{
57
58    // Default parameters, to be overwritten by setParam() and read with getParam()
59    protected $_params = array(
60        'to' => null,
61        'from' => null,
62        'subject' => null,
63        'headers' => null,
64        'envelope_sender_address' => null, // AKA the bounce-to address. Will default to 'from' if left null.
65        'regex' => null,
66
67        // A single carriage return (\n) should terminate lines for locally injected mail.
68        // A carriage return + line-feed (\r\n) should be used if sending mail directly with SMTP.
69        'crlf' => "\n",
70
71        // RFC 2822 says line length MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF.
72        // http://mailformat.dan.info/body/linelength.html
73        'wrap' => true,
74        'line_length' => 75,
75
76        'sandbox_mode' => null,
77        'sandbox_to_addr' => null,
78    );
79
80    // String that contains the email body.
81    protected $_template;
82
83    // String that contains the email body after replacements.
84    protected $_template_replaced;
85
86    // Email debug modes.
87    const SANDBOX_MODE_REDIRECT = 1; // Send all mail to 'sandbox_to_addr'
88    const SANDBOX_MODE_STDERR = 2; // Log all mail to stderr
89    const SANDBOX_MODE_LOG = 3; // Log all mail using $app->logMsg(
)
90
91    /**
92     * Constructor.
93     *
94     * @access  public
95     * @param   array   $params     Array of object parameters.
96     * @author  Quinn Comendant <quinn@strangecode.com>
97     * @since   28 Nov 2005 12:59:41
98     */
99    public function __construct($params=null)
100    {
101        // The regex used in validEmail(). Set here instead of in the default _params above so we can use the concatenation . dot.
102        // This matches a (valid) email address as complex as:
103        //      "Jane & Bob Smith" <bob&smith's/dep=sales!@smith-wick.ca.us > (Sales department)
104        // ...and something as simple as:
105        //      x@x.com
106        $this->setParam(array('regex' => '/^(?:(?:"[^"]*?"\s*|[^,@]*)(<\s*)|(?:"[^"]*?"|[^,@]*)\s+|)'   // Display name
107        . '((?:[^.<>\s@",\[\]]+[^<>\s@",\[\]])*[^.<>\s@",\[\]]+)'       // Local-part
108        . '@'                                                           // @
109        . '((?:(\[)|[A-Z0-9]?)'                                         // Domain, first char
110        . '(?(4)'                                                       // Domain conditional for if first domain char is [
111        . '(?:[0-9]{1,3}\.){3}[0-9]{1,3}\]'                             // TRUE, matches IP address
112        . '|'
113        . '[.-]?(?:[A-Z0-9]+[-.])*(?:[A-Z0-9]+\.)+[A-Z]{2,6}))'         // FALSE, matches domain name
114        . '(?(1)'                                                       // Comment conditional for if initial < exists
115        . '(?:\s*>\s*|>\s+\([^,@]+\)\s*)'                               // TRUE, ensure ending >
116        . '|'
117        . '(?:|\s*|\s+\([^,@]+\)\s*))$/i'));                            // FALSE ensure there is no ending >
118
119        if (isset($params)) {
120            $this->setParam($params);
121        }
122    }
123
124    /**
125     * Set (or overwrite existing) parameters by passing an array of new parameters.
126     *
127     * @access public
128     * @param  array    $params     Array of parameters (key => val pairs).
129     */
130    public function setParam($params)
131    {
132        $app =& App::getInstance();
133
134        if (isset($params) && is_array($params)) {
135            // Enforce valid email addresses.
136            if (isset($params['to']) && !$this->validEmail($params['to'])) {
137                $params['to'] = null;
138            }
139            if (isset($params['from']) && !$this->validEmail($params['from'])) {
140                $params['from'] = null;
141            }
142            if (isset($params['envelope_sender_address']) && !$this->validEmail($params['envelope_sender_address'])) {
143                $params['envelope_sender_address'] = null;
144            }
145
146            // Merge new parameters with old overriding only those passed.
147            $this->_params = array_merge($this->_params, $params);
148        } else {
149            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
150        }
151    }
152
153    /**
154     * Return the value of a parameter, if it exists.
155     *
156     * @access public
157     * @param string $param        Which parameter to return.
158     * @return mixed               Configured parameter value.
159     */
160    public function getParam($param)
161    {
162        $app =& App::getInstance();
163
164        if (array_key_exists($param, $this->_params)) {
165            return $this->_params[$param];
166        } else {
167            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
168            return null;
169        }
170    }
171
172    /**
173     * Loads template from file to generate email body.
174     *
175     * @access  public
176     * @param   string  $template   Filename of email template.
177     * @author  Quinn Comendant <quinn@strangecode.com>
178     * @since   28 Nov 2005 12:56:23
179     */
180    public function setTemplate($template)
181    {
182        $app =& App::getInstance();
183
184        // Load file, using include_path.
185        if (!$this->_template = file_get_contents($template, true)) {
186            $app->logMsg(sprintf('Email template file does not exist: %s', $template), LOG_ERR, __FILE__, __LINE__);
187            $this->_template = null;
188            $this->_template_replaced = null;
189            return false;
190        }
191
192        // Ensure template is UTF-8.
193        $detected_encoding = mb_detect_encoding($this->_template, array('UTF-8', 'ISO-8859-1', 'WINDOWS-1252'), true);
194        if ('UTF-8' != strtoupper($detected_encoding)) {
195            $this->_template = mb_convert_encoding($this->_template, 'UTF-8', $detected_encoding);
196        }
197
198        // This could be a new template, so reset the _template_replaced.
199        $this->_template_replaced = null;
200        return true;
201    }
202
203    /**
204     * Loads template from string to generate email body.
205     *
206     * @access  public
207     * @param   string  $template   Filename of email template.
208     * @author  Quinn Comendant <quinn@strangecode.com>
209     * @since   28 Nov 2005 12:56:23
210     */
211    public function setString($string)
212    {
213        $app =& App::getInstance();
214
215        if ('' == trim($string)) {
216            $app->logMsg(sprintf('Empty string provided.', null), LOG_ERR, __FILE__, __LINE__);
217            $this->_template_replaced = null;
218            return false;
219        } else {
220            $this->_template = $string;
221            // This could be a new template, so reset the _template_replaced.
222            $this->_template_replaced = null;
223            return true;
224        }
225    }
226
227    /**
228     * Replace variables in template with argument data.
229     *
230     * @access  public
231     * @param   array   $replacements   Array keys are the values to search for, array vales are the replacement values.
232     * @author  Quinn Comendant <quinn@strangecode.com>
233     * @since   28 Nov 2005 13:08:51
234     */
235    public function replace($replacements)
236    {
237        $app =& App::getInstance();
238
239        // Ensure template exists.
240        if (!isset($this->_template)) {
241            $app->logMsg(sprintf('Cannot replace variables, no template defined.', null), LOG_ERR, __FILE__, __LINE__);
242            return false;
243        }
244
245        // Ensure replacements argument is an array.
246        if (!is_array($replacements)) {
247            $app->logMsg(sprintf('Cannot replace variables, invalid replacements.', null), LOG_ERR, __FILE__, __LINE__);
248            return false;
249        }
250
251        // Apply regex pattern to search elements.
252        $search = array_keys($replacements);
253        array_walk($search, create_function('&$v', '$v = "{" . mb_strtoupper($v) . "}";'));
254
255        // Replacement values.
256        $replace = array_values($replacements);
257
258        // Search and replace all values at once.
259        $this->_template_replaced = str_replace($search, $replace, $this->_template);
260    }
261
262    /*
263    * Returns the body of the current email. This can be used to store the message that is being sent.
264    * It will use the original template, or the replaced template if it has been processed.
265    * You can also use this function to do post-processing on the email body before sending it,
266    * like removing extraneous lines:
267    * $email->setString(preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $email->getBody()));
268    *
269    * @access   public
270    * @return   string  Message body.
271    * @author   Quinn Comendant <quinn@strangecode.com>
272    * @version  1.0
273    * @since    18 Nov 2014 21:15:19
274    */
275    public function getBody()
276    {
277        $app =& App::getInstance();
278
279        $final_body = isset($this->_template_replaced) ? $this->_template_replaced : $this->_template;
280        // Ensure all placeholders have been replaced. Find anything with {...} characters.
281        if (preg_match('/({[^}]+})/', $final_body, $unreplaced_match)) {
282            unset($unreplaced_match[0]);
283            $app->logMsg(sprintf('Cannot get email body. Unreplaced variables in template: %s', getDump($unreplaced_match)), LOG_ERR, __FILE__, __LINE__);
284            return false;
285        }
286        return $final_body;
287    }
288
289    /**
290     * Send email using PHP's mail() function.
291     *
292     * @access  public
293     * @param   string  $to
294     * @param   string  $from
295     * @param   string  $subject
296     * @author  Quinn Comendant <quinn@strangecode.com>
297     * @since   28 Nov 2005 12:56:09
298     */
299    public function send($to=null, $from=null, $subject=null, $headers=null)
300    {
301        $app =& App::getInstance();
302
303        // Use arguments if provided.
304        if (isset($to)) {
305            $this->setParam(array('to' => $to));
306        }
307        if (isset($from)) {
308            $this->setParam(array('from' => $from));
309        }
310        if (isset($subject)) {
311            $this->setParam(array('subject' => $subject));
312        }
313        if (isset($headers)) {
314            $this->setParam(array('headers' => $headers));
315        }
316
317        // Ensure required values exist.
318        if (!isset($this->_params['subject'])) {
319            $app->logMsg('Cannot send email. SUBJECT not defined.', LOG_ERR, __FILE__, __LINE__);
320            return false;
321        } else if (!isset($this->_template)) {
322            $app->logMsg(sprintf('Cannot send email: "%s". Template not set.', $this->_params['subject']), LOG_ERR, __FILE__, __LINE__);
323            return false;
324        } else if (!isset($this->_params['to'])) {
325            $app->logMsg(sprintf('Cannot send email: "%s". TO not defined.', $this->_params['subject']), LOG_NOTICE, __FILE__, __LINE__);
326            return false;
327        } else if (!isset($this->_params['from'])) {
328            $app->logMsg(sprintf('Cannot send email: "%s". FROM not defined.', $this->_params['subject']), LOG_ERR, __FILE__, __LINE__);
329            return false;
330        }
331
332        // Wrap email text body, using _template_replaced if replacements have been used, or just a fresh _template if not.
333        $final_body = isset($this->_template_replaced) ? $this->_template_replaced : $this->_template;
334        if (false !== $this->getParam('wrap')) {
335            $final_body = wordwrap($final_body, $this->getParam('line_length'), $this->getParam('crlf'));
336        }
337
338        // Ensure all placeholders have been replaced. Find anything with {...} characters.
339        if (preg_match('/({[^}]+})/', $final_body, $unreplaced_match)) {
340            unset($unreplaced_match[0]);
341            $app->logMsg(sprintf('Cannot send email. Unreplaced variables in template: %s', getDump($unreplaced_match)), LOG_ERR, __FILE__, __LINE__);
342            return false;
343        }
344
345        // Final "to" header can have multiple addresses if in an array.
346        $final_to = is_array($this->_params['to']) ? join(', ', $this->_params['to']) : $this->_params['to'];
347
348        // From headers are custom headers.
349        $headers = array('From' => $this->_params['from']);
350
351        // Additional headers.
352        if (isset($this->_params['headers']) && is_array($this->_params['headers'])) {
353            $headers = array_merge($this->_params['headers'], $headers);
354        }
355
356        // Process headers.
357        $final_headers = array();
358        foreach ($headers as $key => $val) {
359            // Validate key and values.
360            if (empty($val)) {
361                $app->logMsg(sprintf('Empty email header provided: %s', $key), LOG_DEBUG, __FILE__, __LINE__);
362                continue;
363            }
364            if (empty($key) || !is_string($key) || !is_string($val) || preg_match("/[\n\r]/", $key . $val) || preg_match('/[^\w-]/', $key)) {
365                $app->logMsg(sprintf('Broken email header provided: %s=%s', $key, $val), LOG_WARNING, __FILE__, __LINE__);
366                continue;
367            }
368            // If the envelope_sender_address was given as a header, move it to the correct place.
369            if ('envelope_sender_address' == strtolower($key)) {
370                $this->_params['envelope_sender_address'] = isset($this->_params['envelope_sender_address']) ? $this->_params['envelope_sender_address'] : $val;
371                continue;
372            }
373            // If we're sending in sandbox mode, remove any headers with recipient addresses.
374            if ($this->getParam('sandbox_mode') == self::SANDBOX_MODE_REDIRECT && in_array(strtolower($key), array('to', 'cc', 'bcc')) && mb_strpos($val, '@') !== false) {
375                // Don't carry this into the $final_headers.
376                $app->logMsg(sprintf('Skipping header in sandbox mode: %s=%s', $key, $val), LOG_DEBUG, __FILE__, __LINE__);
377                continue;
378            }
379            $final_headers[] = sprintf('%s: %s', $key, $val);
380        }
381        $final_headers = join($this->getParam('crlf'), $final_headers);
382
383        // This is the address where delivery problems are sent to. We must strip off everything except the local@domain part.
384        if (isset($this->_params['envelope_sender_address'])) {
385            $envelope_sender_address = sprintf('<%s>', trim($this->_params['envelope_sender_address'], '<>'));
386        } else {
387            $envelope_sender_address = preg_replace('/^.*<?([^\s@\[\]<>()]+\@[A-Za-z0-9.-]{1,}\.[A-Za-z]{2,5})>?$/iU', '$1', $this->_params['from']);
388        }
389        if ('' != $envelope_sender_address && $this->validEmail($envelope_sender_address)) {
390            $additional_parameter = sprintf('-f %s', $envelope_sender_address);
391        } else {
392            $additional_parameter = '';
393        }
394
395        // Check for mail header injection attacks.
396        $full_mail_content = join($this->getParam('crlf'), array($final_to, $this->_params['subject'], $final_body));
397        if (preg_match("/(^|[\n\r])(Content-Type|MIME-Version|Content-Transfer-Encoding|Bcc|Cc)\s*:/i", $full_mail_content)) {
398            $app->logMsg(sprintf('Mail header injection attack in content: %s', $full_mail_content), LOG_WARNING, __FILE__, __LINE__);
399            return false;
400        }
401
402        // Enter sandbox mode, if specified.
403        switch ($this->getParam('sandbox_mode')) {
404        case self::SANDBOX_MODE_REDIRECT:
405            if (!$this->getParam('sandbox_to_addr')) {
406                $app->logMsg(sprintf('Email sandbox_mode is SANDBOX_MODE_REDIRECT but sandbox_to_addr is not set.', null), LOG_ERR, __FILE__, __LINE__);
407                break;
408            }
409            $final_to = $this->getParam('sandbox_to_addr');
410            break;
411
412        case self::SANDBOX_MODE_STDERR:
413            file_put_contents('php://stderr', sprintf("Subject: %s\nTo: %s\n%s\n\n%s", $this->getParam('subject'), $final_to, str_replace($this->getParam('crlf'), "\n", $final_headers), $final_body), FILE_APPEND);
414            return true;
415
416        case self::SANDBOX_MODE_LOG:
417            $log_serialize = $app->getParam('log_serialize');
418            $app->setParam(array('log_serialize' => false));
419            $app->logMsg(sprintf("\nSubject: %s\nTo: %s\n%s\n\n%s", $this->getParam('subject'), $final_to, str_replace($this->getParam('crlf'), "\n", $final_headers), $final_body), LOG_DEBUG, __FILE__, __LINE__);
420            $app->setParam(array('log_serialize' => $log_serialize));
421            return true;
422        }
423
424        // Send email without 5th parameter if safemode is enabled.
425        if (ini_get('safe_mode')) {
426            $ret = mb_send_mail($final_to, $this->_params['subject'], $final_body, $final_headers);
427        } else {
428            $ret = mb_send_mail($final_to, $this->_params['subject'], $final_body, $final_headers, $additional_parameter);
429        }
430
431        // Ensure message was successfully accepted for delivery.
432        if ($ret) {
433            $app->logMsg(sprintf('Email successfully sent to %s', $final_to), LOG_INFO, __FILE__, __LINE__);
434            return true;
435        } else {
436            $app->logMsg(sprintf('Email failure: %s, %s, %s, %s', $final_to, $this->_params['subject'], str_replace("\r\n", '\r\n', $final_headers), $additional_parameter), LOG_WARNING, __FILE__, __LINE__);
437            return false;
438        }
439    }
440
441    /**
442     * Validates an email address based on the recommendations in RFC 3696.
443     * Is more loose than restrictive, to allow the many valid variants of
444     * email addresses while catching the most common mistakes. Checks an array too.
445     * http://www.faqs.org/rfcs/rfc822.html
446     * http://www.faqs.org/rfcs/rfc2822.html
447     * http://www.faqs.org/rfcs/rfc3696.html
448     * http://www.faqs.org/rfcs/rfc1035.html
449     *
450     * @access  public
451     * @param   mixed  $email  Address to check, string or array.
452     * @return  bool    Validity of address.
453     * @author  Quinn Comendant <quinn@strangecode.com>
454     * @since   30 Nov 2005 22:00:50
455     */
456    public function validEmail($email)
457    {
458        $app =& App::getInstance();
459
460        // If an array, check values recursively.
461        if (is_array($email)) {
462            foreach ($email as $e) {
463                if (!$this->validEmail($e)) {
464                    return false;
465                }
466            }
467            return true;
468        } else {
469            // To be valid email address must match regex and fit within the length constraints.
470            if (preg_match($this->getParam('regex'), $email, $e_parts) && mb_strlen($e_parts[2]) < 64 && mb_strlen($e_parts[3]) < 255) {
471                return true;
472            } else {
473                $app->logMsg(sprintf('Invalid email address: %s', $email), LOG_INFO, __FILE__, __LINE__);
474                return false;
475            }
476        }
477    }
478}
479
Note: See TracBrowser for help on using the repository browser.