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

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

Fixed mime_content_type bug in Upload.inc.php

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