PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Network/Email/CakeEmail.php

https://github.com/vgarcias/expediamedicus
PHP | 1588 lines | 839 code | 127 blank | 622 comment | 149 complexity | 0111144ea522491f28ca3f5ef0cef519 MD5 | raw file
  1. <?php
  2. /**
  3. * Cake E-Mail
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Network.Email
  16. * @since CakePHP(tm) v 2.0.0
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('Validation', 'Utility');
  20. App::uses('Multibyte', 'I18n');
  21. App::uses('AbstractTransport', 'Network/Email');
  22. App::uses('String', 'Utility');
  23. App::uses('View', 'View');
  24. App::import('I18n', 'Multibyte');
  25. /**
  26. * Cake e-mail class.
  27. *
  28. * This class is used for handling Internet Message Format based
  29. * based on the standard outlined in http://www.rfc-editor.org/rfc/rfc2822.txt
  30. *
  31. * @package Cake.Network.Email
  32. */
  33. class CakeEmail {
  34. /**
  35. * Default X-Mailer
  36. *
  37. * @constant EMAIL_CLIENT
  38. */
  39. const EMAIL_CLIENT = 'CakePHP Email';
  40. /**
  41. * Line length - no should more - RFC 2822 - 2.1.1
  42. *
  43. * @constant LINE_LENGTH_SHOULD
  44. */
  45. const LINE_LENGTH_SHOULD = 78;
  46. /**
  47. * Line length - no must more - RFC 2822 - 2.1.1
  48. *
  49. * @constant LINE_LENGTH_MUST
  50. */
  51. const LINE_LENGTH_MUST = 998;
  52. /**
  53. * Type of message - HTML
  54. *
  55. * @constant MESSAGE_HTML
  56. */
  57. const MESSAGE_HTML = 'html';
  58. /**
  59. * Type of message - TEXT
  60. *
  61. * @constant MESSAGE_TEXT
  62. */
  63. const MESSAGE_TEXT = 'text';
  64. /**
  65. * Recipient of the email
  66. *
  67. * @var array
  68. */
  69. protected $_to = array();
  70. /**
  71. * The mail which the email is sent from
  72. *
  73. * @var array
  74. */
  75. protected $_from = array();
  76. /**
  77. * The sender email
  78. *
  79. * @var array();
  80. */
  81. protected $_sender = array();
  82. /**
  83. * The email the recipient will reply to
  84. *
  85. * @var array
  86. */
  87. protected $_replyTo = array();
  88. /**
  89. * The read receipt email
  90. *
  91. * @var array
  92. */
  93. protected $_readReceipt = array();
  94. /**
  95. * The mail that will be used in case of any errors like
  96. * - Remote mailserver down
  97. * - Remote user has exceeded his quota
  98. * - Unknown user
  99. *
  100. * @var array
  101. */
  102. protected $_returnPath = array();
  103. /**
  104. * Carbon Copy
  105. *
  106. * List of email's that should receive a copy of the email.
  107. * The Recipient WILL be able to see this list
  108. *
  109. * @var array
  110. */
  111. protected $_cc = array();
  112. /**
  113. * Blind Carbon Copy
  114. *
  115. * List of email's that should receive a copy of the email.
  116. * The Recipient WILL NOT be able to see this list
  117. *
  118. * @var array
  119. */
  120. protected $_bcc = array();
  121. /**
  122. * Message ID
  123. *
  124. * @var boolean|string True to generate, False to ignore, String with value
  125. */
  126. protected $_messageId = true;
  127. /**
  128. * Domain for messageId generation.
  129. * Needs to be manually set for CLI mailing as env('HTTP_HOST') is empty
  130. *
  131. * @var string
  132. */
  133. protected $_domain = null;
  134. /**
  135. * The subject of the email
  136. *
  137. * @var string
  138. */
  139. protected $_subject = '';
  140. /**
  141. * Associative array of a user defined headers
  142. * Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5
  143. *
  144. * @var array
  145. */
  146. protected $_headers = array();
  147. /**
  148. * Layout for the View
  149. *
  150. * @var string
  151. */
  152. protected $_layout = 'default';
  153. /**
  154. * Template for the view
  155. *
  156. * @var string
  157. */
  158. protected $_template = '';
  159. /**
  160. * View for render
  161. *
  162. * @var string
  163. */
  164. protected $_viewRender = 'View';
  165. /**
  166. * Vars to sent to render
  167. *
  168. * @var array
  169. */
  170. protected $_viewVars = array();
  171. /**
  172. * Theme for the View
  173. *
  174. * @var array
  175. */
  176. protected $_theme = null;
  177. /**
  178. * Helpers to be used in the render
  179. *
  180. * @var array
  181. */
  182. protected $_helpers = array('Html');
  183. /**
  184. * Text message
  185. *
  186. * @var string
  187. */
  188. protected $_textMessage = '';
  189. /**
  190. * Html message
  191. *
  192. * @var string
  193. */
  194. protected $_htmlMessage = '';
  195. /**
  196. * Final message to send
  197. *
  198. * @var array
  199. */
  200. protected $_message = array();
  201. /**
  202. * Available formats to be sent.
  203. *
  204. * @var array
  205. */
  206. protected $_emailFormatAvailable = array('text', 'html', 'both');
  207. /**
  208. * What format should the email be sent in
  209. *
  210. * @var string
  211. */
  212. protected $_emailFormat = 'text';
  213. /**
  214. * What method should the email be sent
  215. *
  216. * @var string
  217. */
  218. protected $_transportName = 'Mail';
  219. /**
  220. * Instance of transport class
  221. *
  222. * @var AbstractTransport
  223. */
  224. protected $_transportClass = null;
  225. /**
  226. * Charset the email body is sent in
  227. *
  228. * @var string
  229. */
  230. public $charset = 'utf-8';
  231. /**
  232. * Charset the email header is sent in
  233. * If null, the $charset property will be used as default
  234. *
  235. * @var string
  236. */
  237. public $headerCharset = null;
  238. /**
  239. * The application wide charset, used to encode headers and body
  240. *
  241. * @var string
  242. */
  243. protected $_appCharset = null;
  244. /**
  245. * List of files that should be attached to the email.
  246. *
  247. * Only absolute paths
  248. *
  249. * @var array
  250. */
  251. protected $_attachments = array();
  252. /**
  253. * If set, boundary to use for multipart mime messages
  254. *
  255. * @var string
  256. */
  257. protected $_boundary = null;
  258. /**
  259. * Configuration to transport
  260. *
  261. * @var string|array
  262. */
  263. protected $_config = array();
  264. /**
  265. * 8Bit character sets
  266. *
  267. * @var array
  268. */
  269. protected $_charset8bit = array('UTF-8', 'SHIFT_JIS');
  270. /**
  271. * Define Content-Type charset name
  272. *
  273. * @var array
  274. */
  275. protected $_contentTypeCharset = array(
  276. 'ISO-2022-JP-MS' => 'ISO-2022-JP'
  277. );
  278. /**
  279. * Constructor
  280. * @param array|string $config Array of configs, or string to load configs from email.php
  281. *
  282. */
  283. public function __construct($config = null) {
  284. $this->_appCharset = Configure::read('App.encoding');
  285. if ($this->_appCharset !== null) {
  286. $this->charset = $this->_appCharset;
  287. }
  288. $this->_domain = preg_replace('/\:\d+$/', '', env('HTTP_HOST'));
  289. if (empty($this->_domain)) {
  290. $this->_domain = php_uname('n');
  291. }
  292. if ($config) {
  293. $this->config($config);
  294. }
  295. if (empty($this->headerCharset)) {
  296. $this->headerCharset = $this->charset;
  297. }
  298. }
  299. /**
  300. * From
  301. *
  302. * @param string|array $email
  303. * @param string $name
  304. * @return array|CakeEmail
  305. * @throws SocketException
  306. */
  307. public function from($email = null, $name = null) {
  308. if ($email === null) {
  309. return $this->_from;
  310. }
  311. return $this->_setEmailSingle('_from', $email, $name, __d('cake_dev', 'From requires only 1 email address.'));
  312. }
  313. /**
  314. * Sender
  315. *
  316. * @param string|array $email
  317. * @param string $name
  318. * @return array|CakeEmail
  319. * @throws SocketException
  320. */
  321. public function sender($email = null, $name = null) {
  322. if ($email === null) {
  323. return $this->_sender;
  324. }
  325. return $this->_setEmailSingle('_sender', $email, $name, __d('cake_dev', 'Sender requires only 1 email address.'));
  326. }
  327. /**
  328. * Reply-To
  329. *
  330. * @param string|array $email
  331. * @param string $name
  332. * @return array|CakeEmail
  333. * @throws SocketException
  334. */
  335. public function replyTo($email = null, $name = null) {
  336. if ($email === null) {
  337. return $this->_replyTo;
  338. }
  339. return $this->_setEmailSingle('_replyTo', $email, $name, __d('cake_dev', 'Reply-To requires only 1 email address.'));
  340. }
  341. /**
  342. * Read Receipt (Disposition-Notification-To header)
  343. *
  344. * @param string|array $email
  345. * @param string $name
  346. * @return array|CakeEmail
  347. * @throws SocketException
  348. */
  349. public function readReceipt($email = null, $name = null) {
  350. if ($email === null) {
  351. return $this->_readReceipt;
  352. }
  353. return $this->_setEmailSingle('_readReceipt', $email, $name, __d('cake_dev', 'Disposition-Notification-To requires only 1 email address.'));
  354. }
  355. /**
  356. * Return Path
  357. *
  358. * @param string|array $email
  359. * @param string $name
  360. * @return array|CakeEmail
  361. * @throws SocketException
  362. */
  363. public function returnPath($email = null, $name = null) {
  364. if ($email === null) {
  365. return $this->_returnPath;
  366. }
  367. return $this->_setEmailSingle('_returnPath', $email, $name, __d('cake_dev', 'Return-Path requires only 1 email address.'));
  368. }
  369. /**
  370. * To
  371. *
  372. * @param string|array $email Null to get, String with email, Array with email as key, name as value or email as value (without name)
  373. * @param string $name
  374. * @return array|CakeEmail
  375. */
  376. public function to($email = null, $name = null) {
  377. if ($email === null) {
  378. return $this->_to;
  379. }
  380. return $this->_setEmail('_to', $email, $name);
  381. }
  382. /**
  383. * Add To
  384. *
  385. * @param string|array $email String with email, Array with email as key, name as value or email as value (without name)
  386. * @param string $name
  387. * @return CakeEmail $this
  388. */
  389. public function addTo($email, $name = null) {
  390. return $this->_addEmail('_to', $email, $name);
  391. }
  392. /**
  393. * Cc
  394. *
  395. * @param string|array $email String with email, Array with email as key, name as value or email as value (without name)
  396. * @param string $name
  397. * @return array|CakeEmail
  398. */
  399. public function cc($email = null, $name = null) {
  400. if ($email === null) {
  401. return $this->_cc;
  402. }
  403. return $this->_setEmail('_cc', $email, $name);
  404. }
  405. /**
  406. * Add Cc
  407. *
  408. * @param string|array $email String with email, Array with email as key, name as value or email as value (without name)
  409. * @param string $name
  410. * @return CakeEmail $this
  411. */
  412. public function addCc($email, $name = null) {
  413. return $this->_addEmail('_cc', $email, $name);
  414. }
  415. /**
  416. * Bcc
  417. *
  418. * @param string|array $email String with email, Array with email as key, name as value or email as value (without name)
  419. * @param string $name
  420. * @return array|CakeEmail
  421. */
  422. public function bcc($email = null, $name = null) {
  423. if ($email === null) {
  424. return $this->_bcc;
  425. }
  426. return $this->_setEmail('_bcc', $email, $name);
  427. }
  428. /**
  429. * Add Bcc
  430. *
  431. * @param string|array $email String with email, Array with email as key, name as value or email as value (without name)
  432. * @param string $name
  433. * @return CakeEmail $this
  434. */
  435. public function addBcc($email, $name = null) {
  436. return $this->_addEmail('_bcc', $email, $name);
  437. }
  438. /**
  439. * Charset setter/getter
  440. *
  441. * @param string $charset
  442. * @return string $this->charset
  443. */
  444. public function charset($charset = null) {
  445. if ($charset === null) {
  446. return $this->charset;
  447. }
  448. $this->charset = $charset;
  449. if (empty($this->headerCharset)) {
  450. $this->headerCharset = $charset;
  451. }
  452. return $this->charset;
  453. }
  454. /**
  455. * HeaderCharset setter/getter
  456. *
  457. * @param string $charset
  458. * @return string $this->charset
  459. */
  460. public function headerCharset($charset = null) {
  461. if ($charset === null) {
  462. return $this->headerCharset;
  463. }
  464. return $this->headerCharset = $charset;
  465. }
  466. /**
  467. * Set email
  468. *
  469. * @param string $varName
  470. * @param string|array $email
  471. * @param string $name
  472. * @return CakeEmail $this
  473. * @throws SocketException
  474. */
  475. protected function _setEmail($varName, $email, $name) {
  476. if (!is_array($email)) {
  477. if (!Validation::email($email)) {
  478. throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $email));
  479. }
  480. if ($name === null) {
  481. $name = $email;
  482. }
  483. $this->{$varName} = array($email => $name);
  484. return $this;
  485. }
  486. $list = array();
  487. foreach ($email as $key => $value) {
  488. if (is_int($key)) {
  489. $key = $value;
  490. }
  491. if (!Validation::email($key)) {
  492. throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $key));
  493. }
  494. $list[$key] = $value;
  495. }
  496. $this->{$varName} = $list;
  497. return $this;
  498. }
  499. /**
  500. * Set only 1 email
  501. *
  502. * @param string $varName
  503. * @param string|array $email
  504. * @param string $name
  505. * @param string $throwMessage
  506. * @return CakeEmail $this
  507. * @throws SocketException
  508. */
  509. protected function _setEmailSingle($varName, $email, $name, $throwMessage) {
  510. $current = $this->{$varName};
  511. $this->_setEmail($varName, $email, $name);
  512. if (count($this->{$varName}) !== 1) {
  513. $this->{$varName} = $current;
  514. throw new SocketException($throwMessage);
  515. }
  516. return $this;
  517. }
  518. /**
  519. * Add email
  520. *
  521. * @param string $varName
  522. * @param string|array $email
  523. * @param string $name
  524. * @return CakeEmail $this
  525. * @throws SocketException
  526. */
  527. protected function _addEmail($varName, $email, $name) {
  528. if (!is_array($email)) {
  529. if (!Validation::email($email)) {
  530. throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $email));
  531. }
  532. if ($name === null) {
  533. $name = $email;
  534. }
  535. $this->{$varName}[$email] = $name;
  536. return $this;
  537. }
  538. $list = array();
  539. foreach ($email as $key => $value) {
  540. if (is_int($key)) {
  541. $key = $value;
  542. }
  543. if (!Validation::email($key)) {
  544. throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $key));
  545. }
  546. $list[$key] = $value;
  547. }
  548. $this->{$varName} = array_merge($this->{$varName}, $list);
  549. return $this;
  550. }
  551. /**
  552. * Get/Set Subject.
  553. *
  554. * @param string $subject
  555. * @return string|CakeEmail
  556. */
  557. public function subject($subject = null) {
  558. if ($subject === null) {
  559. return $this->_subject;
  560. }
  561. $this->_subject = $this->_encode((string)$subject);
  562. return $this;
  563. }
  564. /**
  565. * Sets headers for the message
  566. *
  567. * @param array $headers Associative array containing headers to be set.
  568. * @return CakeEmail $this
  569. * @throws SocketException
  570. */
  571. public function setHeaders($headers) {
  572. if (!is_array($headers)) {
  573. throw new SocketException(__d('cake_dev', '$headers should be an array.'));
  574. }
  575. $this->_headers = $headers;
  576. return $this;
  577. }
  578. /**
  579. * Add header for the message
  580. *
  581. * @param array $headers
  582. * @return object $this
  583. * @throws SocketException
  584. */
  585. public function addHeaders($headers) {
  586. if (!is_array($headers)) {
  587. throw new SocketException(__d('cake_dev', '$headers should be an array.'));
  588. }
  589. $this->_headers = array_merge($this->_headers, $headers);
  590. return $this;
  591. }
  592. /**
  593. * Get list of headers
  594. *
  595. * ### Includes:
  596. *
  597. * - `from`
  598. * - `replyTo`
  599. * - `readReceipt`
  600. * - `returnPath`
  601. * - `to`
  602. * - `cc`
  603. * - `bcc`
  604. * - `subject`
  605. *
  606. * @param array $include
  607. * @return array
  608. */
  609. public function getHeaders($include = array()) {
  610. if ($include == array_values($include)) {
  611. $include = array_fill_keys($include, true);
  612. }
  613. $defaults = array_fill_keys(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject'), false);
  614. $include += $defaults;
  615. $headers = array();
  616. $relation = array(
  617. 'from' => 'From',
  618. 'replyTo' => 'Reply-To',
  619. 'readReceipt' => 'Disposition-Notification-To',
  620. 'returnPath' => 'Return-Path'
  621. );
  622. foreach ($relation as $var => $header) {
  623. if ($include[$var]) {
  624. $var = '_' . $var;
  625. $headers[$header] = current($this->_formatAddress($this->{$var}));
  626. }
  627. }
  628. if ($include['sender']) {
  629. if (key($this->_sender) === key($this->_from)) {
  630. $headers['Sender'] = '';
  631. } else {
  632. $headers['Sender'] = current($this->_formatAddress($this->_sender));
  633. }
  634. }
  635. foreach (array('to', 'cc', 'bcc') as $var) {
  636. if ($include[$var]) {
  637. $classVar = '_' . $var;
  638. $headers[ucfirst($var)] = implode(', ', $this->_formatAddress($this->{$classVar}));
  639. }
  640. }
  641. $headers += $this->_headers;
  642. if (!isset($headers['X-Mailer'])) {
  643. $headers['X-Mailer'] = self::EMAIL_CLIENT;
  644. }
  645. if (!isset($headers['Date'])) {
  646. $headers['Date'] = date(DATE_RFC2822);
  647. }
  648. if ($this->_messageId !== false) {
  649. if ($this->_messageId === true) {
  650. $headers['Message-ID'] = '<' . str_replace('-', '', String::UUID()) . '@' . $this->_domain . '>';
  651. } else {
  652. $headers['Message-ID'] = $this->_messageId;
  653. }
  654. }
  655. if ($include['subject']) {
  656. $headers['Subject'] = $this->_subject;
  657. }
  658. $headers['MIME-Version'] = '1.0';
  659. if (!empty($this->_attachments) || $this->_emailFormat === 'both') {
  660. $headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"';
  661. } elseif ($this->_emailFormat === 'text') {
  662. $headers['Content-Type'] = 'text/plain; charset=' . $this->_getContentTypeCharset();
  663. } elseif ($this->_emailFormat === 'html') {
  664. $headers['Content-Type'] = 'text/html; charset=' . $this->_getContentTypeCharset();
  665. }
  666. $headers['Content-Transfer-Encoding'] = $this->_getContentTransferEncoding();
  667. return $headers;
  668. }
  669. /**
  670. * Format addresses
  671. *
  672. * @param array $address
  673. * @return array
  674. */
  675. protected function _formatAddress($address) {
  676. $return = array();
  677. foreach ($address as $email => $alias) {
  678. if ($email === $alias) {
  679. $return[] = $email;
  680. } else {
  681. if (strpos($alias, ',') !== false) {
  682. $alias = '"' . $alias . '"';
  683. }
  684. $return[] = sprintf('%s <%s>', $this->_encode($alias), $email);
  685. }
  686. }
  687. return $return;
  688. }
  689. /**
  690. * Template and layout
  691. *
  692. * @param boolean|string $template Template name or null to not use
  693. * @param boolean|string $layout Layout name or null to not use
  694. * @return array|CakeEmail
  695. */
  696. public function template($template = false, $layout = false) {
  697. if ($template === false) {
  698. return array(
  699. 'template' => $this->_template,
  700. 'layout' => $this->_layout
  701. );
  702. }
  703. $this->_template = $template;
  704. if ($layout !== false) {
  705. $this->_layout = $layout;
  706. }
  707. return $this;
  708. }
  709. /**
  710. * View class for render
  711. *
  712. * @param string $viewClass
  713. * @return string|CakeEmail
  714. */
  715. public function viewRender($viewClass = null) {
  716. if ($viewClass === null) {
  717. return $this->_viewRender;
  718. }
  719. $this->_viewRender = $viewClass;
  720. return $this;
  721. }
  722. /**
  723. * Variables to be set on render
  724. *
  725. * @param array $viewVars
  726. * @return array|CakeEmail
  727. */
  728. public function viewVars($viewVars = null) {
  729. if ($viewVars === null) {
  730. return $this->_viewVars;
  731. }
  732. $this->_viewVars = array_merge($this->_viewVars, (array)$viewVars);
  733. return $this;
  734. }
  735. /**
  736. * Theme to use when rendering
  737. *
  738. * @param string $theme
  739. * @return string|CakeEmail
  740. */
  741. public function theme($theme = null) {
  742. if ($theme === null) {
  743. return $this->_theme;
  744. }
  745. $this->_theme = $theme;
  746. return $this;
  747. }
  748. /**
  749. * Helpers to be used in render
  750. *
  751. * @param array $helpers
  752. * @return array|CakeEmail
  753. */
  754. public function helpers($helpers = null) {
  755. if ($helpers === null) {
  756. return $this->_helpers;
  757. }
  758. $this->_helpers = (array)$helpers;
  759. return $this;
  760. }
  761. /**
  762. * Email format
  763. *
  764. * @param string $format
  765. * @return string|CakeEmail
  766. * @throws SocketException
  767. */
  768. public function emailFormat($format = null) {
  769. if ($format === null) {
  770. return $this->_emailFormat;
  771. }
  772. if (!in_array($format, $this->_emailFormatAvailable)) {
  773. throw new SocketException(__d('cake_dev', 'Format not available.'));
  774. }
  775. $this->_emailFormat = $format;
  776. return $this;
  777. }
  778. /**
  779. * Transport name
  780. *
  781. * @param string $name
  782. * @return string|CakeEmail
  783. */
  784. public function transport($name = null) {
  785. if ($name === null) {
  786. return $this->_transportName;
  787. }
  788. $this->_transportName = (string)$name;
  789. $this->_transportClass = null;
  790. return $this;
  791. }
  792. /**
  793. * Return the transport class
  794. *
  795. * @return CakeEmail
  796. * @throws SocketException
  797. */
  798. public function transportClass() {
  799. if ($this->_transportClass) {
  800. return $this->_transportClass;
  801. }
  802. list($plugin, $transportClassname) = pluginSplit($this->_transportName, true);
  803. $transportClassname .= 'Transport';
  804. App::uses($transportClassname, $plugin . 'Network/Email');
  805. if (!class_exists($transportClassname)) {
  806. throw new SocketException(__d('cake_dev', 'Class "%s" not found.', $transportClassname));
  807. } elseif (!method_exists($transportClassname, 'send')) {
  808. throw new SocketException(__d('cake_dev', 'The "%s" do not have send method.', $transportClassname));
  809. }
  810. return $this->_transportClass = new $transportClassname();
  811. }
  812. /**
  813. * Message-ID
  814. *
  815. * @param boolean|string $message True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID
  816. * @return boolean|string|CakeEmail
  817. * @throws SocketException
  818. */
  819. public function messageId($message = null) {
  820. if ($message === null) {
  821. return $this->_messageId;
  822. }
  823. if (is_bool($message)) {
  824. $this->_messageId = $message;
  825. } else {
  826. if (!preg_match('/^\<.+@.+\>$/', $message)) {
  827. throw new SocketException(__d('cake_dev', 'Invalid format for Message-ID. The text should be something like "<uuid@server.com>"'));
  828. }
  829. $this->_messageId = $message;
  830. }
  831. return $this;
  832. }
  833. /**
  834. * Domain as top level (the part after @)
  835. *
  836. * @param string $domain Manually set the domain for CLI mailing
  837. * @return string|CakeEmail
  838. */
  839. public function domain($domain = null) {
  840. if ($domain === null) {
  841. return $this->_domain;
  842. }
  843. $this->_domain = $domain;
  844. return $this;
  845. }
  846. /**
  847. * Add attachments to the email message
  848. *
  849. * Attachments can be defined in a few forms depending on how much control you need:
  850. *
  851. * Attach a single file:
  852. *
  853. * {{{
  854. * $email->attachments('path/to/file');
  855. * }}}
  856. *
  857. * Attach a file with a different filename:
  858. *
  859. * {{{
  860. * $email->attachments(array('custom_name.txt' => 'path/to/file.txt'));
  861. * }}}
  862. *
  863. * Attach a file and specify additional properties:
  864. *
  865. * {{{
  866. * $email->attachments(array('custom_name.png' => array(
  867. * 'file' => 'path/to/file',
  868. * 'mimetype' => 'image/png',
  869. * 'contentId' => 'abc123'
  870. * ));
  871. * }}}
  872. *
  873. * The `contentId` key allows you to specify an inline attachment. In your email text, you
  874. * can use `<img src="cid:abc123" />` to display the image inline.
  875. *
  876. * @param string|array $attachments String with the filename or array with filenames
  877. * @return array|CakeEmail Either the array of attachments when getting or $this when setting.
  878. * @throws SocketException
  879. */
  880. public function attachments($attachments = null) {
  881. if ($attachments === null) {
  882. return $this->_attachments;
  883. }
  884. $attach = array();
  885. foreach ((array)$attachments as $name => $fileInfo) {
  886. if (!is_array($fileInfo)) {
  887. $fileInfo = array('file' => $fileInfo);
  888. }
  889. if (!isset($fileInfo['file'])) {
  890. throw new SocketException(__d('cake_dev', 'File not specified.'));
  891. }
  892. $fileInfo['file'] = realpath($fileInfo['file']);
  893. if ($fileInfo['file'] === false || !file_exists($fileInfo['file'])) {
  894. throw new SocketException(__d('cake_dev', 'File not found: "%s"', $fileInfo['file']));
  895. }
  896. if (is_int($name)) {
  897. $name = basename($fileInfo['file']);
  898. }
  899. if (!isset($fileInfo['mimetype'])) {
  900. $fileInfo['mimetype'] = 'application/octet-stream';
  901. }
  902. $attach[$name] = $fileInfo;
  903. }
  904. $this->_attachments = $attach;
  905. return $this;
  906. }
  907. /**
  908. * Add attachments
  909. *
  910. * @param string|array $attachments String with the filename or array with filenames
  911. * @return CakeEmail $this
  912. * @throws SocketException
  913. */
  914. public function addAttachments($attachments) {
  915. $current = $this->_attachments;
  916. $this->attachments($attachments);
  917. $this->_attachments = array_merge($current, $this->_attachments);
  918. return $this;
  919. }
  920. /**
  921. * Get generated message (used by transport classes)
  922. *
  923. * @param string $type Use MESSAGE_* constants or null to return the full message as array
  924. * @return string|array String if have type, array if type is null
  925. */
  926. public function message($type = null) {
  927. switch ($type) {
  928. case self::MESSAGE_HTML:
  929. return $this->_htmlMessage;
  930. case self::MESSAGE_TEXT:
  931. return $this->_textMessage;
  932. }
  933. return $this->_message;
  934. }
  935. /**
  936. * Configuration to use when send email
  937. *
  938. * @param string|array $config String with configuration name (from email.php), array with config or null to return current config
  939. * @return string|array|CakeEmail
  940. */
  941. public function config($config = null) {
  942. if ($config === null) {
  943. return $this->_config;
  944. }
  945. if (!is_array($config)) {
  946. $config = (string)$config;
  947. }
  948. $this->_applyConfig($config);
  949. return $this;
  950. }
  951. /**
  952. * Send an email using the specified content, template and layout
  953. *
  954. * @param string|array $content String with message or array with messages
  955. * @return array
  956. * @throws SocketException
  957. */
  958. public function send($content = null) {
  959. if (empty($this->_from)) {
  960. throw new SocketException(__d('cake_dev', 'From is not specified.'));
  961. }
  962. if (empty($this->_to) && empty($this->_cc) && empty($this->_bcc)) {
  963. throw new SocketException(__d('cake_dev', 'You need to specify at least one destination for to, cc or bcc.'));
  964. }
  965. if (is_array($content)) {
  966. $content = implode("\n", $content) . "\n";
  967. }
  968. $this->_textMessage = $this->_htmlMessage = '';
  969. $this->_createBoundary();
  970. $this->_message = $this->_render($this->_wrap($content));
  971. $contents = $this->transportClass()->send($this);
  972. if (!empty($this->_config['log'])) {
  973. $level = LOG_DEBUG;
  974. if ($this->_config['log'] !== true) {
  975. $level = $this->_config['log'];
  976. }
  977. CakeLog::write($level, PHP_EOL . $contents['headers'] . PHP_EOL . $contents['message']);
  978. }
  979. return $contents;
  980. }
  981. /**
  982. * Static method to fast create an instance of CakeEmail
  983. *
  984. * @param string|array $to Address to send (see CakeEmail::to()). If null, will try to use 'to' from transport config
  985. * @param string $subject String of subject or null to use 'subject' from transport config
  986. * @param string|array $message String with message or array with variables to be used in render
  987. * @param string|array $transportConfig String to use config from EmailConfig or array with configs
  988. * @param boolean $send Send the email or just return the instance pre-configured
  989. * @return CakeEmail Instance of CakeEmail
  990. * @throws SocketException
  991. */
  992. public static function deliver($to = null, $subject = null, $message = null, $transportConfig = 'fast', $send = true) {
  993. $class = __CLASS__;
  994. $instance = new $class($transportConfig);
  995. if ($to !== null) {
  996. $instance->to($to);
  997. }
  998. if ($subject !== null) {
  999. $instance->subject($subject);
  1000. }
  1001. if (is_array($message)) {
  1002. $instance->viewVars($message);
  1003. $message = null;
  1004. } elseif ($message === null && array_key_exists('message', $config = $instance->config())) {
  1005. $message = $config['message'];
  1006. }
  1007. if ($send === true) {
  1008. $instance->send($message);
  1009. }
  1010. return $instance;
  1011. }
  1012. /**
  1013. * Apply the config to an instance
  1014. *
  1015. * @param CakeEmail $obj CakeEmail
  1016. * @param array $config
  1017. * @return void
  1018. * @throws ConfigureException When configuration file cannot be found, or is missing
  1019. * the named config.
  1020. */
  1021. protected function _applyConfig($config) {
  1022. if (is_string($config)) {
  1023. if (!class_exists('EmailConfig') && !config('email')) {
  1024. throw new ConfigureException(__d('cake_dev', '%s not found.', APP . 'Config' . DS . 'email.php'));
  1025. }
  1026. $configs = new EmailConfig();
  1027. if (!isset($configs->{$config})) {
  1028. throw new ConfigureException(__d('cake_dev', 'Unknown email configuration "%s".', $config));
  1029. }
  1030. $config = $configs->{$config};
  1031. }
  1032. $this->_config += $config;
  1033. if (!empty($config['charset'])) {
  1034. $this->charset = $config['charset'];
  1035. }
  1036. if (!empty($config['headerCharset'])) {
  1037. $this->headerCharset = $config['headerCharset'];
  1038. }
  1039. if (empty($this->headerCharset)) {
  1040. $this->headerCharset = $this->charset;
  1041. }
  1042. $simpleMethods = array(
  1043. 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', 'cc', 'bcc',
  1044. 'messageId', 'domain', 'subject', 'viewRender', 'viewVars', 'attachments',
  1045. 'transport', 'emailFormat', 'theme', 'helpers'
  1046. );
  1047. foreach ($simpleMethods as $method) {
  1048. if (isset($config[$method])) {
  1049. $this->$method($config[$method]);
  1050. unset($config[$method]);
  1051. }
  1052. }
  1053. if (isset($config['headers'])) {
  1054. $this->setHeaders($config['headers']);
  1055. unset($config['headers']);
  1056. }
  1057. if (array_key_exists('template', $config)) {
  1058. $layout = false;
  1059. if (array_key_exists('layout', $config)) {
  1060. $layout = $config['layout'];
  1061. unset($config['layout']);
  1062. }
  1063. $this->template($config['template'], $layout);
  1064. unset($config['template']);
  1065. }
  1066. $this->transportClass()->config($config);
  1067. }
  1068. /**
  1069. * Reset all EmailComponent internal variables to be able to send out a new email.
  1070. *
  1071. * @return CakeEmail $this
  1072. */
  1073. public function reset() {
  1074. $this->_to = array();
  1075. $this->_from = array();
  1076. $this->_sender = array();
  1077. $this->_replyTo = array();
  1078. $this->_readReceipt = array();
  1079. $this->_returnPath = array();
  1080. $this->_cc = array();
  1081. $this->_bcc = array();
  1082. $this->_messageId = true;
  1083. $this->_subject = '';
  1084. $this->_headers = array();
  1085. $this->_layout = 'default';
  1086. $this->_template = '';
  1087. $this->_viewRender = 'View';
  1088. $this->_viewVars = array();
  1089. $this->_theme = null;
  1090. $this->_helpers = array('Html');
  1091. $this->_textMessage = '';
  1092. $this->_htmlMessage = '';
  1093. $this->_message = '';
  1094. $this->_emailFormat = 'text';
  1095. $this->_transportName = 'Mail';
  1096. $this->_transportClass = null;
  1097. $this->charset = 'utf-8';
  1098. $this->headerCharset = null;
  1099. $this->_attachments = array();
  1100. $this->_config = array();
  1101. return $this;
  1102. }
  1103. /**
  1104. * Encode the specified string using the current charset
  1105. *
  1106. * @param string $text String to encode
  1107. * @return string Encoded string
  1108. */
  1109. protected function _encode($text) {
  1110. $internalEncoding = function_exists('mb_internal_encoding');
  1111. if ($internalEncoding) {
  1112. $restore = mb_internal_encoding();
  1113. mb_internal_encoding($this->_appCharset);
  1114. }
  1115. if (empty($this->headerCharset)) {
  1116. $this->headerCharset = $this->charset;
  1117. }
  1118. $return = mb_encode_mimeheader($text, $this->headerCharset, 'B');
  1119. if ($internalEncoding) {
  1120. mb_internal_encoding($restore);
  1121. }
  1122. return $return;
  1123. }
  1124. /**
  1125. * Translates a string for one charset to another if the App.encoding value
  1126. * differs and the mb_convert_encoding function exists
  1127. *
  1128. * @param string $text The text to be converted
  1129. * @param string $charset the target encoding
  1130. * @return string
  1131. */
  1132. protected function _encodeString($text, $charset) {
  1133. if ($this->_appCharset === $charset || !function_exists('mb_convert_encoding')) {
  1134. return $text;
  1135. }
  1136. return mb_convert_encoding($text, $charset, $this->_appCharset);
  1137. }
  1138. /**
  1139. * Wrap the message to follow the RFC 2822 - 2.1.1
  1140. *
  1141. * @param string $message Message to wrap
  1142. * @return array Wrapped message
  1143. */
  1144. protected function _wrap($message) {
  1145. $message = str_replace(array("\r\n", "\r"), "\n", $message);
  1146. $lines = explode("\n", $message);
  1147. $formatted = array();
  1148. foreach ($lines as $line) {
  1149. if (empty($line)) {
  1150. $formatted[] = '';
  1151. continue;
  1152. }
  1153. if (!preg_match('/\<[a-z]/i', $line)) {
  1154. $formatted = array_merge($formatted, explode("\n", wordwrap($line, self::LINE_LENGTH_SHOULD, "\n")));
  1155. continue;
  1156. }
  1157. $tagOpen = false;
  1158. $tmpLine = $tag = '';
  1159. $tmpLineLength = 0;
  1160. for ($i = 0, $count = strlen($line); $i < $count; $i++) {
  1161. $char = $line[$i];
  1162. if ($tagOpen) {
  1163. $tag .= $char;
  1164. if ($char === '>') {
  1165. $tagLength = strlen($tag);
  1166. if ($tagLength + $tmpLineLength < self::LINE_LENGTH_SHOULD) {
  1167. $tmpLine .= $tag;
  1168. $tmpLineLength += $tagLength;
  1169. } else {
  1170. if ($tmpLineLength > 0) {
  1171. $formatted[] = trim($tmpLine);
  1172. $tmpLine = '';
  1173. $tmpLineLength = 0;
  1174. }
  1175. if ($tagLength > self::LINE_LENGTH_SHOULD) {
  1176. $formatted[] = $tag;
  1177. } else {
  1178. $tmpLine = $tag;
  1179. $tmpLineLength = $tagLength;
  1180. }
  1181. }
  1182. $tag = '';
  1183. $tagOpen = false;
  1184. }
  1185. continue;
  1186. }
  1187. if ($char === '<') {
  1188. $tagOpen = true;
  1189. $tag = '<';
  1190. continue;
  1191. }
  1192. if ($char === ' ' && $tmpLineLength >= self::LINE_LENGTH_SHOULD) {
  1193. $formatted[] = $tmpLine;
  1194. $tmpLineLength = 0;
  1195. continue;
  1196. }
  1197. $tmpLine .= $char;
  1198. $tmpLineLength++;
  1199. if ($tmpLineLength === self::LINE_LENGTH_SHOULD) {
  1200. $nextChar = $line[$i + 1];
  1201. if ($nextChar === ' ' || $nextChar === '<') {
  1202. $formatted[] = trim($tmpLine);
  1203. $tmpLine = '';
  1204. $tmpLineLength = 0;
  1205. if ($nextChar === ' ') {
  1206. $i++;
  1207. }
  1208. } else {
  1209. $lastSpace = strrpos($tmpLine, ' ');
  1210. if ($lastSpace === false) {
  1211. continue;
  1212. }
  1213. $formatted[] = trim(substr($tmpLine, 0, $lastSpace));
  1214. $tmpLine = substr($tmpLine, $lastSpace + 1);
  1215. $tmpLineLength = strlen($tmpLine);
  1216. }
  1217. }
  1218. }
  1219. if (!empty($tmpLine)) {
  1220. $formatted[] = $tmpLine;
  1221. }
  1222. }
  1223. $formatted[] = '';
  1224. return $formatted;
  1225. }
  1226. /**
  1227. * Create unique boundary identifier
  1228. *
  1229. * @return void
  1230. */
  1231. protected function _createBoundary() {
  1232. if (!empty($this->_attachments) || $this->_emailFormat === 'both') {
  1233. $this->_boundary = md5(uniqid(time()));
  1234. }
  1235. }
  1236. /**
  1237. * Attach non-embedded files by adding file contents inside boundaries.
  1238. *
  1239. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  1240. * @return array An array of lines to add to the message
  1241. */
  1242. protected function _attachFiles($boundary = null) {
  1243. if ($boundary === null) {
  1244. $boundary = $this->_boundary;
  1245. }
  1246. $msg = array();
  1247. foreach ($this->_attachments as $filename => $fileInfo) {
  1248. if (!empty($fileInfo['contentId'])) {
  1249. continue;
  1250. }
  1251. $data = $this->_readFile($fileInfo['file']);
  1252. $msg[] = '--' . $boundary;
  1253. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  1254. $msg[] = 'Content-Transfer-Encoding: base64';
  1255. $msg[] = 'Content-Disposition: attachment; filename="' . $filename . '"';
  1256. $msg[] = '';
  1257. $msg[] = $data;
  1258. $msg[] = '';
  1259. }
  1260. return $msg;
  1261. }
  1262. /**
  1263. * Read the file contents and return a base64 version of the file contents.
  1264. *
  1265. * @param string $file The file to read.
  1266. * @return string File contents in base64 encoding
  1267. */
  1268. protected function _readFile($file) {
  1269. $handle = fopen($file, 'rb');
  1270. $data = fread($handle, filesize($file));
  1271. $data = chunk_split(base64_encode($data));
  1272. fclose($handle);
  1273. return $data;
  1274. }
  1275. /**
  1276. * Attach inline/embedded files to the message.
  1277. *
  1278. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  1279. * @return array An array of lines to add to the message
  1280. */
  1281. protected function _attachInlineFiles($boundary = null) {
  1282. if ($boundary === null) {
  1283. $boundary = $this->_boundary;
  1284. }
  1285. $msg = array();
  1286. foreach ($this->_attachments as $filename => $fileInfo) {
  1287. if (empty($fileInfo['contentId'])) {
  1288. continue;
  1289. }
  1290. $data = $this->_readFile($fileInfo['file']);
  1291. $msg[] = '--' . $boundary;
  1292. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  1293. $msg[] = 'Content-Transfer-Encoding: base64';
  1294. $msg[] = 'Content-ID: <' . $fileInfo['contentId'] . '>';
  1295. $msg[] = 'Content-Disposition: inline; filename="' . $filename . '"';
  1296. $msg[] = '';
  1297. $msg[] = $data;
  1298. $msg[] = '';
  1299. }
  1300. return $msg;
  1301. }
  1302. /**
  1303. * Render the body of the email.
  1304. *
  1305. * @param string $content Content to render
  1306. * @return array Email body ready to be sent
  1307. */
  1308. protected function _render($content) {
  1309. $content = implode("\n", $content);
  1310. $rendered = $this->_renderTemplates($content);
  1311. $msg = array();
  1312. $contentIds = array_filter((array)Hash::extract($this->_attachments, '{s}.contentId'));
  1313. $hasInlineAttachments = count($contentIds) > 0;
  1314. $hasAttachments = !empty($this->_attachments);
  1315. $hasMultipleTypes = count($rendered) > 1;
  1316. $boundary = $relBoundary = $textBoundary = $this->_boundary;
  1317. if ($hasInlineAttachments) {
  1318. $msg[] = '--' . $boundary;
  1319. $msg[] = 'Content-Type: multipart/related; boundary="rel-' . $boundary . '"';
  1320. $msg[] = '';
  1321. $relBoundary = $textBoundary = 'rel-' . $boundary;
  1322. }
  1323. if ($hasMultipleTypes) {
  1324. $msg[] = '--' . $relBoundary;
  1325. $msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $boundary . '"';
  1326. $msg[] = '';
  1327. $textBoundary = 'alt-' . $boundary;
  1328. }
  1329. if (isset($rendered['text'])) {
  1330. if ($textBoundary !== $boundary || $hasAttachments) {
  1331. $msg[] = '--' . $textBoundary;
  1332. $msg[] = 'Content-Type: text/plain; charset=' . $this->_getContentTypeCharset();
  1333. $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding();
  1334. $msg[] = '';
  1335. }
  1336. $this->_textMessage = $rendered['text'];
  1337. $content = explode("\n", $this->_textMessage);
  1338. $msg = array_merge($msg, $content);
  1339. $msg[] = '';
  1340. }
  1341. if (isset($rendered['html'])) {
  1342. if ($textBoundary !== $boundary || $hasAttachments) {
  1343. $msg[] = '--' . $textBoundary;
  1344. $msg[] = 'Content-Type: text/html; charset=' . $this->_getContentTypeCharset();
  1345. $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding();
  1346. $msg[] = '';
  1347. }
  1348. $this->_htmlMessage = $rendered['html'];
  1349. $content = explode("\n", $this->_htmlMessage);
  1350. $msg = array_merge($msg, $content);
  1351. $msg[] = '';
  1352. }
  1353. if ($hasMultipleTypes) {
  1354. $msg[] = '--' . $textBoundary . '--';
  1355. $msg[] = '';
  1356. }
  1357. if ($hasInlineAttachments) {
  1358. $attachments = $this->_attachInlineFiles($relBoundary);
  1359. $msg = array_merge($msg, $attachments);
  1360. $msg[] = '';
  1361. $msg[] = '--' . $relBoundary . '--';
  1362. $msg[] = '';
  1363. }
  1364. if ($hasAttachments) {
  1365. $attachments = $this->_attachFiles($boundary);
  1366. $msg = array_merge($msg, $attachments);
  1367. }
  1368. if ($hasAttachments || $hasMultipleTypes) {
  1369. $msg[] = '';
  1370. $msg[] = '--' . $boundary . '--';
  1371. $msg[] = '';
  1372. }
  1373. return $msg;
  1374. }
  1375. /**
  1376. * Gets the text body types that are in this email message
  1377. *
  1378. * @return array Array of types. Valid types are 'text' and 'html'
  1379. */
  1380. protected function _getTypes() {
  1381. $types = array($this->_emailFormat);
  1382. if ($this->_emailFormat == 'both') {
  1383. $types = array('html', 'text');
  1384. }
  1385. return $types;
  1386. }
  1387. /**
  1388. * Build and set all the view properties needed to render the templated emails.
  1389. * If there is no template set, the $content will be returned in a hash
  1390. * of the text content types for the email.
  1391. *
  1392. * @param string $content The content passed in from send() in most cases.
  1393. * @return array The rendered content with html and text keys.
  1394. */
  1395. protected function _renderTemplates($content) {
  1396. $types = $this->_getTypes();
  1397. $rendered = array();
  1398. if (empty($this->_template)) {
  1399. foreach ($types as $type) {
  1400. $rendered[$type] = $this->_encodeString($content, $this->charset);
  1401. }
  1402. return $rendered;
  1403. }
  1404. $viewClass = $this->_viewRender;
  1405. if ($viewClass !== 'View') {
  1406. list($plugin, $viewClass) = pluginSplit($viewClass, true);
  1407. $viewClass .= 'View';
  1408. App::uses($viewClass, $plugin . 'View');
  1409. }
  1410. $View = new $viewClass(null);
  1411. $View->viewVars = $this->_viewVars;
  1412. $View->helpers = $this->_helpers;
  1413. list($templatePlugin, $template) = pluginSplit($this->_template);
  1414. list($layoutPlugin, $layout) = pluginSplit($this->_layout);
  1415. if ($templatePlugin) {
  1416. $View->plugin = $templatePlugin;
  1417. } elseif ($layoutPlugin) {
  1418. $View->plugin = $layoutPlugin;
  1419. }
  1420. if ($this->_theme) {
  1421. $View->theme = $this->_theme;
  1422. }
  1423. foreach ($types as $type) {
  1424. $View->set('content', $content);
  1425. $View->hasRendered = false;
  1426. $View->viewPath = $View->layoutPath = 'Emails' . DS . $type;
  1427. $render = $View->render($template, $layout);
  1428. $render = str_replace(array("\r\n", "\r"), "\n", $render);
  1429. $rendered[$type] = $this->_encodeString($render, $this->charset);
  1430. }
  1431. return $rendered;
  1432. }
  1433. /**
  1434. * Return the Content-Transfer Encoding value based on the set charset
  1435. *
  1436. * @return void
  1437. */
  1438. protected function _getContentTransferEncoding() {
  1439. $charset = strtoupper($this->charset);
  1440. if (in_array($charset, $this->_charset8bit)) {
  1441. return '8bit';
  1442. }
  1443. return '7bit';
  1444. }
  1445. /**
  1446. * Return charset value for Content-Type.
  1447. *
  1448. * Checks fallback/compatibility types which include workarounds
  1449. * for legacy japanese character sets.
  1450. *
  1451. * @return string
  1452. */
  1453. protected function _getContentTypeCharset() {
  1454. $charset = strtoupper($this->charset);
  1455. if (array_key_exists($charset, $this->_contentTypeCharset)) {
  1456. return strtoupper($this->_contentTypeCharset[$charset]);
  1457. } else {
  1458. return strtoupper($this->charset);
  1459. }
  1460. }
  1461. }