PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Zend/Log/Writer/Mail.php

https://bitbucket.org/mengqing/magento-mirror
PHP | 427 lines | 190 code | 45 blank | 192 comment | 31 complexity | 55fd43aec0a637a36704289d7b52e300 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-2010 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 22971 2010-09-18 20:32:24Z mikaelkael $
  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-2010 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 22971 2010-09-18 20:32:24Z mikaelkael $
  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. */
  170. protected static function _constructMailFromConfig(array $config)
  171. {
  172. $mailClass = 'Zend_Mail';
  173. if (isset($config['mail'])) {
  174. $mailClass = $config['mail'];
  175. }
  176. if (!array_key_exists('charset', $config)) {
  177. $config['charset'] = null;
  178. }
  179. $mail = new $mailClass($config['charset']);
  180. if (!$mail instanceof Zend_Mail) {
  181. throw new Zend_Log_Exception($mail . 'must extend Zend_Mail');
  182. }
  183. if (isset($config['subject'])) {
  184. $mail->setSubject($config['subject']);
  185. }
  186. $headerAddresses = array_intersect_key($config, self::$_methodMapHeaders);
  187. if (count($headerAddresses)) {
  188. foreach ($headerAddresses as $header => $address) {
  189. $method = self::$_methodMapHeaders[$header];
  190. if (is_array($address) && isset($address['name'])
  191. && !is_numeric($address['name'])
  192. ) {
  193. $params = array(
  194. $address['email'],
  195. $address['name']
  196. );
  197. } else if (is_array($address) && isset($address['email'])) {
  198. $params = array($address['email']);
  199. } else {
  200. $params = array($address);
  201. }
  202. call_user_func_array(array($mail, $method), $params);
  203. }
  204. }
  205. return $mail;
  206. }
  207. /**
  208. * Construct a Zend_Layout instance based on a configuration array
  209. *
  210. * @param array $config
  211. * @return Zend_Layout
  212. */
  213. protected function _constructLayoutFromConfig(array $config)
  214. {
  215. $config = array_merge(array(
  216. 'layout' => 'Zend_Layout',
  217. 'layoutOptions' => null
  218. ), $config);
  219. $layoutClass = $config['layout'];
  220. $layout = new $layoutClass($config['layoutOptions']);
  221. if (!$layout instanceof Zend_Layout) {
  222. throw new Zend_Log_Exception($layout . 'must extend Zend_Layout');
  223. }
  224. return $layout;
  225. }
  226. /**
  227. * Places event line into array of lines to be used as message body.
  228. *
  229. * Handles the formatting of both plaintext entries, as well as those
  230. * rendered with Zend_Layout.
  231. *
  232. * @param array $event Event data
  233. * @return void
  234. */
  235. protected function _write($event)
  236. {
  237. // Track the number of entries per priority level.
  238. if (!isset($this->_numEntriesPerPriority[$event['priorityName']])) {
  239. $this->_numEntriesPerPriority[$event['priorityName']] = 1;
  240. } else {
  241. $this->_numEntriesPerPriority[$event['priorityName']]++;
  242. }
  243. $formattedEvent = $this->_formatter->format($event);
  244. // All plaintext events are to use the standard formatter.
  245. $this->_eventsToMail[] = $formattedEvent;
  246. // If we have a Zend_Layout instance, use a specific formatter for the
  247. // layout if one exists. Otherwise, just use the event with its
  248. // default format.
  249. if ($this->_layout) {
  250. if ($this->_layoutFormatter) {
  251. $this->_layoutEventsToMail[] =
  252. $this->_layoutFormatter->format($event);
  253. } else {
  254. $this->_layoutEventsToMail[] = $formattedEvent;
  255. }
  256. }
  257. }
  258. /**
  259. * Gets instance of Zend_Log_Formatter_Instance used for formatting a
  260. * message using Zend_Layout, if applicable.
  261. *
  262. * @return Zend_Log_Formatter_Interface|null The formatter, or null.
  263. */
  264. public function getLayoutFormatter()
  265. {
  266. return $this->_layoutFormatter;
  267. }
  268. /**
  269. * Sets a specific formatter for use with Zend_Layout events.
  270. *
  271. * Allows use of a second formatter on lines that will be rendered with
  272. * Zend_Layout. In the event that Zend_Layout is not being used, this
  273. * formatter cannot be set, so an exception will be thrown.
  274. *
  275. * @param Zend_Log_Formatter_Interface $formatter
  276. * @return Zend_Log_Writer_Mail
  277. * @throws Zend_Log_Exception
  278. */
  279. public function setLayoutFormatter(Zend_Log_Formatter_Interface $formatter)
  280. {
  281. if (!$this->_layout) {
  282. throw new Zend_Log_Exception(
  283. 'cannot set formatter for layout; ' .
  284. 'a Zend_Layout instance is not in use');
  285. }
  286. $this->_layoutFormatter = $formatter;
  287. return $this;
  288. }
  289. /**
  290. * Allows caller to have the mail subject dynamically set to contain the
  291. * entry counts per-priority level.
  292. *
  293. * Sets the text for use in the subject, with entry counts per-priority
  294. * level appended to the end. Since a Zend_Mail subject can only be set
  295. * once, this method cannot be used if the Zend_Mail object already has a
  296. * subject set.
  297. *
  298. * @param string $subject Subject prepend text.
  299. * @return Zend_Log_Writer_Mail
  300. */
  301. public function setSubjectPrependText($subject)
  302. {
  303. if ($this->_mail->getSubject()) {
  304. throw new Zend_Log_Exception(
  305. 'subject already set on mail; ' .
  306. 'cannot set subject prepend text');
  307. }
  308. $this->_subjectPrependText = (string) $subject;
  309. return $this;
  310. }
  311. /**
  312. * Sends mail to recipient(s) if log entries are present. Note that both
  313. * plaintext and HTML portions of email are handled here.
  314. *
  315. * @return void
  316. */
  317. public function shutdown()
  318. {
  319. // If there are events to mail, use them as message body. Otherwise,
  320. // there is no mail to be sent.
  321. if (empty($this->_eventsToMail)) {
  322. return;
  323. }
  324. if ($this->_subjectPrependText !== null) {
  325. // Tack on the summary of entries per-priority to the subject
  326. // line and set it on the Zend_Mail object.
  327. $numEntries = $this->_getFormattedNumEntriesPerPriority();
  328. $this->_mail->setSubject(
  329. "{$this->_subjectPrependText} ({$numEntries})");
  330. }
  331. // Always provide events to mail as plaintext.
  332. $this->_mail->setBodyText(implode('', $this->_eventsToMail));
  333. // If a Zend_Layout instance is being used, set its "events"
  334. // value to the lines formatted for use with the layout.
  335. if ($this->_layout) {
  336. // Set the required "messages" value for the layout. Here we
  337. // are assuming that the layout is for use with HTML.
  338. $this->_layout->events =
  339. implode('', $this->_layoutEventsToMail);
  340. // If an exception occurs during rendering, convert it to a notice
  341. // so we can avoid an exception thrown without a stack frame.
  342. try {
  343. $this->_mail->setBodyHtml($this->_layout->render());
  344. } catch (Exception $e) {
  345. trigger_error(
  346. "exception occurred when rendering layout; " .
  347. "unable to set html body for message; " .
  348. "message = {$e->getMessage()}; " .
  349. "code = {$e->getCode()}; " .
  350. "exception class = " . get_class($e),
  351. E_USER_NOTICE);
  352. }
  353. }
  354. // Finally, send the mail. If an exception occurs, convert it into a
  355. // warning-level message so we can avoid an exception thrown without a
  356. // stack frame.
  357. try {
  358. $this->_mail->send();
  359. } catch (Exception $e) {
  360. trigger_error(
  361. "unable to send log entries via email; " .
  362. "message = {$e->getMessage()}; " .
  363. "code = {$e->getCode()}; " .
  364. "exception class = " . get_class($e),
  365. E_USER_WARNING);
  366. }
  367. }
  368. /**
  369. * Gets a string of number of entries per-priority level that occurred, or
  370. * an emptry string if none occurred.
  371. *
  372. * @return string
  373. */
  374. protected function _getFormattedNumEntriesPerPriority()
  375. {
  376. $strings = array();
  377. foreach ($this->_numEntriesPerPriority as $priority => $numEntries) {
  378. $strings[] = "{$priority}={$numEntries}";
  379. }
  380. return implode(', ', $strings);
  381. }
  382. }