PageRenderTime 19ms CodeModel.GetById 9ms app.highlight 5ms RepoModel.GetById 2ms app.codeStats 0ms

/library/Zend/Log/Writer/Mail.php

https://bitbucket.org/ksekar/campus
PHP | 430 lines | 194 code | 45 blank | 191 comment | 31 complexity | f854464b6930e46590b548356c749070 MD5 | raw file
  1<?php
  2/**
  3 * Zend Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the new BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://framework.zend.com/license/new-bsd
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@zend.com so we can send you a copy immediately.
 14 *
 15 * @category   Zend
 16 * @package    Zend_Log
 17 * @subpackage Writer
 18 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 19 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 20 * @version    $Id: Mail.php 24594 2012-01-05 21:27:01Z matthew $
 21 */
 22
 23/** Zend_Log_Writer_Abstract */
 24require_once 'Zend/Log/Writer/Abstract.php';
 25
 26/** Zend_Log_Exception */
 27require_once 'Zend/Log/Exception.php';
 28
 29/** Zend_Log_Formatter_Simple*/
 30require_once 'Zend/Log/Formatter/Simple.php';
 31
 32/**
 33 * Class used for writing log messages to email via Zend_Mail.
 34 *
 35 * Allows for emailing log messages at and above a certain level via a
 36 * Zend_Mail object.  Note that this class only sends the email upon
 37 * completion, so any log entries accumulated are sent in a single email.
 38 *
 39 * @category   Zend
 40 * @package    Zend_Log
 41 * @subpackage Writer
 42 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 43 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 44 * @version    $Id: Mail.php 24594 2012-01-05 21:27:01Z matthew $
 45 */
 46class Zend_Log_Writer_Mail extends Zend_Log_Writer_Abstract
 47{
 48    /**
 49     * Array of formatted events to include in message body.
 50     *
 51     * @var array
 52     */
 53    protected $_eventsToMail = array();
 54
 55    /**
 56     * Array of formatted lines for use in an HTML email body; these events
 57     * are formatted with an optional formatter if the caller is using
 58     * Zend_Layout.
 59     *
 60     * @var array
 61     */
 62    protected $_layoutEventsToMail = array();
 63
 64    /**
 65     * Zend_Mail instance to use
 66     *
 67     * @var Zend_Mail
 68     */
 69    protected $_mail;
 70
 71    /**
 72     * Zend_Layout instance to use; optional.
 73     *
 74     * @var Zend_Layout
 75     */
 76    protected $_layout;
 77
 78    /**
 79     * Optional formatter for use when rendering with Zend_Layout.
 80     *
 81     * @var Zend_Log_Formatter_Interface
 82     */
 83    protected $_layoutFormatter;
 84
 85    /**
 86     * Array keeping track of the number of entries per priority level.
 87     *
 88     * @var array
 89     */
 90    protected $_numEntriesPerPriority = array();
 91
 92    /**
 93     * Subject prepend text.
 94     *
 95     * Can only be used of the Zend_Mail object has not already had its
 96     * subject line set.  Using this will cause the subject to have the entry
 97     * counts per-priority level appended to it.
 98     *
 99     * @var string|null
100     */
101    protected $_subjectPrependText;
102
103    /**
104     * MethodMap for Zend_Mail's headers
105     *
106     * @var array
107     */
108    protected static $_methodMapHeaders = array(
109        'from' => 'setFrom',
110        'to' => 'addTo',
111        'cc' => 'addCc',
112        'bcc' => 'addBcc',
113    );
114
115    /**
116     * Class constructor.
117     *
118     * Constructs the mail writer; requires a Zend_Mail instance, and takes an
119     * optional Zend_Layout instance.  If Zend_Layout is being used,
120     * $this->_layout->events will be set for use in the layout template.
121     *
122     * @param  Zend_Mail $mail Mail instance
123     * @param  Zend_Layout $layout Layout instance; optional
124     * @return void
125     */
126    public function __construct(Zend_Mail $mail, Zend_Layout $layout = null)
127    {
128        $this->_mail = $mail;
129        if (null !== $layout) {
130            $this->setLayout($layout);
131        }
132        $this->_formatter = new Zend_Log_Formatter_Simple();
133    }
134
135    /**
136     * Create a new instance of Zend_Log_Writer_Mail
137     *
138     * @param  array|Zend_Config $config
139     * @return Zend_Log_Writer_Mail
140     */
141    static public function factory($config)
142    {
143        $config = self::_parseConfig($config);
144        $mail = self::_constructMailFromConfig($config);
145        $writer = new self($mail);
146
147        if (isset($config['layout']) || isset($config['layoutOptions'])) {
148            $writer->setLayout($config);
149        }
150        if (isset($config['layoutFormatter'])) {
151            $layoutFormatter = new $config['layoutFormatter'];
152            $writer->setLayoutFormatter($layoutFormatter);
153        }
154        if (isset($config['subjectPrependText'])) {
155            $writer->setSubjectPrependText($config['subjectPrependText']);
156        }
157
158        return $writer;
159    }
160
161    /**
162     * Set the layout
163     *
164     * @param Zend_Layout|array $layout
165     * @return Zend_Log_Writer_Mail
166     * @throws Zend_Log_Exception
167     */
168    public function setLayout($layout)
169    {
170        if (is_array($layout)) {
171            $layout = $this->_constructLayoutFromConfig($layout);
172        }
173
174        if (!$layout instanceof Zend_Layout) {
175            require_once 'Zend/Log/Exception.php';
176            throw new Zend_Log_Exception('Mail must be an instance of Zend_Layout or an array');
177        }
178        $this->_layout = $layout;
179
180        return $this;
181    }
182
183    /**
184     * Construct a Zend_Mail instance based on a configuration array
185     *
186     * @param array $config
187     * @return Zend_Mail
188     * @throws Zend_Log_Exception
189     */
190    protected static function _constructMailFromConfig(array $config)
191    {
192        $mailClass = 'Zend_Mail';
193        if (isset($config['mail'])) {
194            $mailClass = $config['mail'];
195        }
196
197        if (!array_key_exists('charset', $config)) {
198            $config['charset'] = null;
199        }
200        $mail = new $mailClass($config['charset']);
201        if (!$mail instanceof Zend_Mail) {
202            throw new Zend_Log_Exception($mail . 'must extend Zend_Mail');
203        }
204
205        if (isset($config['subject'])) {
206            $mail->setSubject($config['subject']);
207        }
208
209        $headerAddresses = array_intersect_key($config, self::$_methodMapHeaders);
210        if (count($headerAddresses)) {
211            foreach ($headerAddresses as $header => $address) {
212                $method = self::$_methodMapHeaders[$header];
213                if (is_array($address) && isset($address['name'])
214                    && !is_numeric($address['name'])
215                ) {
216                    $params = array(
217                        $address['email'],
218                        $address['name']
219                    );
220                } else if (is_array($address) && isset($address['email'])) {
221                    $params = array($address['email']);
222                } else {
223                    $params = array($address);
224                }
225                call_user_func_array(array($mail, $method), $params);
226            }
227        }
228
229        return $mail;
230    }
231
232    /**
233     * Construct a Zend_Layout instance based on a configuration array
234     *
235     * @param array $config
236     * @return Zend_Layout
237     * @throws Zend_Log_Exception
238     */
239    protected function _constructLayoutFromConfig(array $config)
240    {
241        $config = array_merge(array(
242            'layout' => 'Zend_Layout',
243            'layoutOptions' => null
244        ), $config);
245
246        $layoutClass = $config['layout'];
247        $layout = new $layoutClass($config['layoutOptions']);
248        if (!$layout instanceof Zend_Layout) {
249            throw new Zend_Log_Exception($layout . 'must extend Zend_Layout');
250        }
251
252        return $layout;
253    }
254
255    /**
256     * Places event line into array of lines to be used as message body.
257     *
258     * Handles the formatting of both plaintext entries, as well as those
259     * rendered with Zend_Layout.
260     *
261     * @param  array $event Event data
262     * @return void
263     */
264    protected function _write($event)
265    {
266        // Track the number of entries per priority level.
267        if (!isset($this->_numEntriesPerPriority[$event['priorityName']])) {
268            $this->_numEntriesPerPriority[$event['priorityName']] = 1;
269        } else {
270            $this->_numEntriesPerPriority[$event['priorityName']]++;
271        }
272
273        $formattedEvent = $this->_formatter->format($event);
274
275        // All plaintext events are to use the standard formatter.
276        $this->_eventsToMail[] = $formattedEvent;
277
278        // If we have a Zend_Layout instance, use a specific formatter for the
279        // layout if one exists.  Otherwise, just use the event with its
280        // default format.
281        if ($this->_layout) {
282            if ($this->_layoutFormatter) {
283                $this->_layoutEventsToMail[] =
284                    $this->_layoutFormatter->format($event);
285            } else {
286                $this->_layoutEventsToMail[] = $formattedEvent;
287            }
288        }
289    }
290
291    /**
292     * Gets instance of Zend_Log_Formatter_Instance used for formatting a
293     * message using Zend_Layout, if applicable.
294     *
295     * @return Zend_Log_Formatter_Interface|null The formatter, or null.
296     */
297    public function getLayoutFormatter()
298    {
299        return $this->_layoutFormatter;
300    }
301
302    /**
303     * Sets a specific formatter for use with Zend_Layout events.
304     *
305     * Allows use of a second formatter on lines that will be rendered with
306     * Zend_Layout.  In the event that Zend_Layout is not being used, this
307     * formatter cannot be set, so an exception will be thrown.
308     *
309     * @param  Zend_Log_Formatter_Interface $formatter
310     * @return Zend_Log_Writer_Mail
311     * @throws Zend_Log_Exception
312     */
313    public function setLayoutFormatter(Zend_Log_Formatter_Interface $formatter)
314    {
315        if (!$this->_layout) {
316            throw new Zend_Log_Exception(
317                'cannot set formatter for layout; ' .
318                    'a Zend_Layout instance is not in use');
319        }
320
321        $this->_layoutFormatter = $formatter;
322        return $this;
323    }
324
325    /**
326     * Allows caller to have the mail subject dynamically set to contain the
327     * entry counts per-priority level.
328     *
329     * Sets the text for use in the subject, with entry counts per-priority
330     * level appended to the end.  Since a Zend_Mail subject can only be set
331     * once, this method cannot be used if the Zend_Mail object already has a
332     * subject set.
333     *
334     * @param  string $subject Subject prepend text.
335     * @return Zend_Log_Writer_Mail
336     * @throws Zend_Log_Exception
337     */
338    public function setSubjectPrependText($subject)
339    {
340        if ($this->_mail->getSubject()) {
341            throw new Zend_Log_Exception(
342                'subject already set on mail; ' .
343                    'cannot set subject prepend text');
344        }
345
346        $this->_subjectPrependText = (string) $subject;
347        return $this;
348    }
349
350    /**
351     * Sends mail to recipient(s) if log entries are present.  Note that both
352     * plaintext and HTML portions of email are handled here.
353     *
354     * @return void
355     */
356    public function shutdown()
357    {
358        // If there are events to mail, use them as message body.  Otherwise,
359        // there is no mail to be sent.
360        if (empty($this->_eventsToMail)) {
361            return;
362        }
363
364        if ($this->_subjectPrependText !== null) {
365            // Tack on the summary of entries per-priority to the subject
366            // line and set it on the Zend_Mail object.
367            $numEntries = $this->_getFormattedNumEntriesPerPriority();
368            $this->_mail->setSubject(
369                "{$this->_subjectPrependText} ({$numEntries})");
370        }
371
372
373        // Always provide events to mail as plaintext.
374        $this->_mail->setBodyText(implode('', $this->_eventsToMail));
375
376        // If a Zend_Layout instance is being used, set its "events"
377        // value to the lines formatted for use with the layout.
378        if ($this->_layout) {
379            // Set the required "messages" value for the layout.  Here we
380            // are assuming that the layout is for use with HTML.
381            $this->_layout->events =
382                implode('', $this->_layoutEventsToMail);
383
384            // If an exception occurs during rendering, convert it to a notice
385            // so we can avoid an exception thrown without a stack frame.
386            try {
387                $this->_mail->setBodyHtml($this->_layout->render());
388            } catch (Exception $e) {
389                trigger_error(
390                    "exception occurred when rendering layout; " .
391                        "unable to set html body for message; " .
392                        "message = {$e->getMessage()}; " .
393                        "code = {$e->getCode()}; " .
394                        "exception class = " . get_class($e),
395                    E_USER_NOTICE);
396            }
397        }
398
399        // Finally, send the mail.  If an exception occurs, convert it into a
400        // warning-level message so we can avoid an exception thrown without a
401        // stack frame.
402        try {
403            $this->_mail->send();
404        } catch (Exception $e) {
405            trigger_error(
406                "unable to send log entries via email; " .
407                    "message = {$e->getMessage()}; " .
408                    "code = {$e->getCode()}; " .
409                        "exception class = " . get_class($e),
410                E_USER_WARNING);
411        }
412    }
413
414    /**
415     * Gets a string of number of entries per-priority level that occurred, or
416     * an emptry string if none occurred.
417     *
418     * @return string
419     */
420    protected function _getFormattedNumEntriesPerPriority()
421    {
422        $strings = array();
423
424        foreach ($this->_numEntriesPerPriority as $priority => $numEntries) {
425            $strings[] = "{$priority}={$numEntries}";
426        }
427
428        return implode(', ', $strings);
429    }
430}