PageRenderTime 39ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

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

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