SimpleMimeEntity.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. <?php
  2. /*
  3. * This file is part of SwiftMailer.
  4. * (c) 2004-2009 Chris Corbyn
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * A MIME entity, in a multipart message.
  11. *
  12. * @package Swift
  13. * @subpackage Mime
  14. * @author Chris Corbyn
  15. */
  16. class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
  17. {
  18. /** A collection of Headers for this mime entity */
  19. private $_headers;
  20. /** The body as a string, or a stream */
  21. private $_body;
  22. /** The encoder that encodes the body into a streamable format */
  23. private $_encoder;
  24. /** The grammar to use for id validation */
  25. private $_grammar;
  26. /** A mime boundary, if any is used */
  27. private $_boundary;
  28. /** Mime types to be used based on the nesting level */
  29. private $_compositeRanges = array(
  30. 'multipart/mixed' => array(self::LEVEL_TOP, self::LEVEL_MIXED),
  31. 'multipart/alternative' => array(self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE),
  32. 'multipart/related' => array(self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED)
  33. );
  34. /** A set of filter rules to define what level an entity should be nested at */
  35. private $_compoundLevelFilters = array();
  36. /** The nesting level of this entity */
  37. private $_nestingLevel = self::LEVEL_ALTERNATIVE;
  38. /** A KeyCache instance used during encoding and streaming */
  39. private $_cache;
  40. /** Direct descendants of this entity */
  41. private $_immediateChildren = array();
  42. /** All descendants of this entity */
  43. private $_children = array();
  44. /** The maximum line length of the body of this entity */
  45. private $_maxLineLength = 78;
  46. /** The order in which alternative mime types should appear */
  47. private $_alternativePartOrder = array(
  48. 'text/plain' => 1,
  49. 'text/html' => 2,
  50. 'multipart/related' => 3
  51. );
  52. /** The CID of this entity */
  53. private $_id;
  54. /** The key used for accessing the cache */
  55. private $_cacheKey;
  56. protected $_userContentType;
  57. /**
  58. * Create a new SimpleMimeEntity with $headers, $encoder and $cache.
  59. *
  60. * @param Swift_Mime_HeaderSet $headers
  61. * @param Swift_Mime_ContentEncoder $encoder
  62. * @param Swift_KeyCache $cache
  63. * @param Swift_Mime_Grammar $grammar
  64. */
  65. public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar)
  66. {
  67. $this->_cacheKey = md5(uniqid(getmypid().mt_rand(), true));
  68. $this->_cache = $cache;
  69. $this->_headers = $headers;
  70. $this->_grammar = $grammar;
  71. $this->setEncoder($encoder);
  72. $this->_headers->defineOrdering(array('Content-Type', 'Content-Transfer-Encoding'));
  73. // This array specifies that, when the entire MIME document contains
  74. // $compoundLevel, then for each child within $level, if its Content-Type
  75. // is $contentType then it should be treated as if it's level is
  76. // $neededLevel instead. I tried to write that unambiguously! :-\
  77. // Data Structure:
  78. // array (
  79. // $compoundLevel => array(
  80. // $level => array(
  81. // $contentType => $neededLevel
  82. // )
  83. // )
  84. // )
  85. $this->_compoundLevelFilters = array(
  86. (self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => array(
  87. self::LEVEL_ALTERNATIVE => array(
  88. 'text/plain' => self::LEVEL_ALTERNATIVE,
  89. 'text/html' => self::LEVEL_RELATED
  90. )
  91. )
  92. );
  93. $this->_id = $this->getRandomId();
  94. }
  95. /**
  96. * Generate a new Content-ID or Message-ID for this MIME entity.
  97. *
  98. * @return string
  99. */
  100. public function generateId()
  101. {
  102. $this->setId($this->getRandomId());
  103. return $this->_id;
  104. }
  105. /**
  106. * Get the {@link Swift_Mime_HeaderSet} for this entity.
  107. *
  108. * @return Swift_Mime_HeaderSet
  109. */
  110. public function getHeaders()
  111. {
  112. return $this->_headers;
  113. }
  114. /**
  115. * Get the nesting level of this entity.
  116. *
  117. * @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE
  118. *
  119. * @return int
  120. */
  121. public function getNestingLevel()
  122. {
  123. return $this->_nestingLevel;
  124. }
  125. /**
  126. * Get the Content-type of this entity.
  127. *
  128. * @return string
  129. */
  130. public function getContentType()
  131. {
  132. return $this->_getHeaderFieldModel('Content-Type');
  133. }
  134. /**
  135. * Set the Content-type of this entity.
  136. *
  137. * @param string $type
  138. *
  139. * @return Swift_Mime_SimpleMimeEntity
  140. */
  141. public function setContentType($type)
  142. {
  143. $this->_setContentTypeInHeaders($type);
  144. // Keep track of the value so that if the content-type changes automatically
  145. // due to added child entities, it can be restored if they are later removed
  146. $this->_userContentType = $type;
  147. return $this;
  148. }
  149. /**
  150. * Get the CID of this entity.
  151. *
  152. * The CID will only be present in headers if a Content-ID header is present.
  153. *
  154. * @return string
  155. */
  156. public function getId()
  157. {
  158. $tmp = (array) $this->_getHeaderFieldModel($this->_getIdField());
  159. return $this->_headers->has($this->_getIdField()) ? current($tmp) : $this->_id;
  160. }
  161. /**
  162. * Set the CID of this entity.
  163. *
  164. * @param string $id
  165. *
  166. * @return Swift_Mime_SimpleMimeEntity
  167. */
  168. public function setId($id)
  169. {
  170. if (!$this->_setHeaderFieldModel($this->_getIdField(), $id)) {
  171. $this->_headers->addIdHeader($this->_getIdField(), $id);
  172. }
  173. $this->_id = $id;
  174. return $this;
  175. }
  176. /**
  177. * Get the description of this entity.
  178. *
  179. * This value comes from the Content-Description header if set.
  180. *
  181. * @return string
  182. */
  183. public function getDescription()
  184. {
  185. return $this->_getHeaderFieldModel('Content-Description');
  186. }
  187. /**
  188. * Set the description of this entity.
  189. *
  190. * This method sets a value in the Content-ID header.
  191. *
  192. * @param string $description
  193. *
  194. * @return Swift_Mime_SimpleMimeEntity
  195. */
  196. public function setDescription($description)
  197. {
  198. if (!$this->_setHeaderFieldModel('Content-Description', $description)) {
  199. $this->_headers->addTextHeader('Content-Description', $description);
  200. }
  201. return $this;
  202. }
  203. /**
  204. * Get the maximum line length of the body of this entity.
  205. *
  206. * @return int
  207. */
  208. public function getMaxLineLength()
  209. {
  210. return $this->_maxLineLength;
  211. }
  212. /**
  213. * Set the maximum line length of lines in this body.
  214. *
  215. * Though not enforced by the library, lines should not exceed 1000 chars.
  216. *
  217. * @param int $length
  218. *
  219. * @return Swift_Mime_SimpleMimeEntity
  220. */
  221. public function setMaxLineLength($length)
  222. {
  223. $this->_maxLineLength = $length;
  224. return $this;
  225. }
  226. /**
  227. * Get all children added to this entity.
  228. *
  229. * @return array of Swift_Mime_Entity
  230. */
  231. public function getChildren()
  232. {
  233. return $this->_children;
  234. }
  235. /**
  236. * Set all children of this entity.
  237. *
  238. * @param array $children Swift_Mime_Entity instances
  239. * @param int $compoundLevel For internal use only
  240. *
  241. * @return Swift_Mime_SimpleMimeEntity
  242. */
  243. public function setChildren(array $children, $compoundLevel = null)
  244. {
  245. // TODO: Try to refactor this logic
  246. $compoundLevel = isset($compoundLevel)
  247. ? $compoundLevel
  248. : $this->_getCompoundLevel($children)
  249. ;
  250. $immediateChildren = array();
  251. $grandchildren = array();
  252. $newContentType = $this->_userContentType;
  253. foreach ($children as $child) {
  254. $level = $this->_getNeededChildLevel($child, $compoundLevel);
  255. if (empty($immediateChildren)) { //first iteration
  256. $immediateChildren = array($child);
  257. } else {
  258. $nextLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel);
  259. if ($nextLevel == $level) {
  260. $immediateChildren[] = $child;
  261. } elseif ($level < $nextLevel) {
  262. // Re-assign immediateChildren to grandchildren
  263. $grandchildren = array_merge($grandchildren, $immediateChildren);
  264. // Set new children
  265. $immediateChildren = array($child);
  266. } else {
  267. $grandchildren[] = $child;
  268. }
  269. }
  270. }
  271. if (!empty($immediateChildren)) {
  272. $lowestLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel);
  273. // Determine which composite media type is needed to accommodate the
  274. // immediate children
  275. foreach ($this->_compositeRanges as $mediaType => $range) {
  276. if ($lowestLevel > $range[0]
  277. && $lowestLevel <= $range[1])
  278. {
  279. $newContentType = $mediaType;
  280. break;
  281. }
  282. }
  283. // Put any grandchildren in a subpart
  284. if (!empty($grandchildren)) {
  285. $subentity = $this->_createChild();
  286. $subentity->_setNestingLevel($lowestLevel);
  287. $subentity->setChildren($grandchildren, $compoundLevel);
  288. array_unshift($immediateChildren, $subentity);
  289. }
  290. }
  291. $this->_immediateChildren = $immediateChildren;
  292. $this->_children = $children;
  293. $this->_setContentTypeInHeaders($newContentType);
  294. $this->_fixHeaders();
  295. $this->_sortChildren();
  296. return $this;
  297. }
  298. /**
  299. * Get the body of this entity as a string.
  300. *
  301. * @return string
  302. */
  303. public function getBody()
  304. {
  305. return ($this->_body instanceof Swift_OutputByteStream)
  306. ? $this->_readStream($this->_body)
  307. : $this->_body;
  308. }
  309. /**
  310. * Set the body of this entity, either as a string, or as an instance of
  311. * {@link Swift_OutputByteStream}.
  312. *
  313. * @param mixed $body
  314. * @param string $contentType optional
  315. *
  316. * @return Swift_Mime_SimpleMimeEntity
  317. */
  318. public function setBody($body, $contentType = null)
  319. {
  320. if ($body !== $this->_body) {
  321. $this->_clearCache();
  322. }
  323. $this->_body = $body;
  324. if (isset($contentType)) {
  325. $this->setContentType($contentType);
  326. }
  327. return $this;
  328. }
  329. /**
  330. * Get the encoder used for the body of this entity.
  331. *
  332. * @return Swift_Mime_ContentEncoder
  333. */
  334. public function getEncoder()
  335. {
  336. return $this->_encoder;
  337. }
  338. /**
  339. * Set the encoder used for the body of this entity.
  340. *
  341. * @param Swift_Mime_ContentEncoder $encoder
  342. *
  343. * @return Swift_Mime_SimpleMimeEntity
  344. */
  345. public function setEncoder(Swift_Mime_ContentEncoder $encoder)
  346. {
  347. if ($encoder !== $this->_encoder) {
  348. $this->_clearCache();
  349. }
  350. $this->_encoder = $encoder;
  351. $this->_setEncoding($encoder->getName());
  352. $this->_notifyEncoderChanged($encoder);
  353. return $this;
  354. }
  355. /**
  356. * Get the boundary used to separate children in this entity.
  357. *
  358. * @return string
  359. */
  360. public function getBoundary()
  361. {
  362. if (!isset($this->_boundary)) {
  363. $this->_boundary = '_=_swift_v4_' . time() . '_' . md5(getmypid().mt_rand().uniqid('', true)) . '_=_';
  364. }
  365. return $this->_boundary;
  366. }
  367. /**
  368. * Set the boundary used to separate children in this entity.
  369. *
  370. * @param string $boundary
  371. *
  372. * @return Swift_Mime_SimpleMimeEntity
  373. *
  374. * @throws Swift_RfcComplianceException
  375. */
  376. public function setBoundary($boundary)
  377. {
  378. $this->_assertValidBoundary($boundary);
  379. $this->_boundary = $boundary;
  380. return $this;
  381. }
  382. /**
  383. * Receive notification that the charset of this entity, or a parent entity
  384. * has changed.
  385. *
  386. * @param string $charset
  387. */
  388. public function charsetChanged($charset)
  389. {
  390. $this->_notifyCharsetChanged($charset);
  391. }
  392. /**
  393. * Receive notification that the encoder of this entity or a parent entity
  394. * has changed.
  395. *
  396. * @param Swift_Mime_ContentEncoder $encoder
  397. */
  398. public function encoderChanged(Swift_Mime_ContentEncoder $encoder)
  399. {
  400. $this->_notifyEncoderChanged($encoder);
  401. }
  402. /**
  403. * Get this entire entity as a string.
  404. *
  405. * @return string
  406. */
  407. public function toString()
  408. {
  409. $string = $this->_headers->toString();
  410. $string .= $this->_bodyToString();
  411. return $string;
  412. }
  413. /**
  414. * Get this entire entity as a string.
  415. *
  416. * @return string
  417. */
  418. protected function _bodyToString()
  419. {
  420. $string = '';
  421. if (isset($this->_body) && empty($this->_immediateChildren)) {
  422. if ($this->_cache->hasKey($this->_cacheKey, 'body')) {
  423. $body = $this->_cache->getString($this->_cacheKey, 'body');
  424. } else {
  425. $body = "\r\n" . $this->_encoder->encodeString($this->getBody(), 0,
  426. $this->getMaxLineLength()
  427. );
  428. $this->_cache->setString($this->_cacheKey, 'body', $body,
  429. Swift_KeyCache::MODE_WRITE
  430. );
  431. }
  432. $string .= $body;
  433. }
  434. if (!empty($this->_immediateChildren)) {
  435. foreach ($this->_immediateChildren as $child) {
  436. $string .= "\r\n\r\n--" . $this->getBoundary() . "\r\n";
  437. $string .= $child->toString();
  438. }
  439. $string .= "\r\n\r\n--" . $this->getBoundary() . "--\r\n";
  440. }
  441. return $string;
  442. }
  443. /**
  444. * Returns a string representation of this object.
  445. *
  446. * @see toString()
  447. *
  448. * @return string
  449. */
  450. public function __toString()
  451. {
  452. return $this->toString();
  453. }
  454. /**
  455. * Write this entire entity to a {@see Swift_InputByteStream}.
  456. *
  457. * @param Swift_InputByteStream
  458. */
  459. public function toByteStream(Swift_InputByteStream $is)
  460. {
  461. $is->write($this->_headers->toString());
  462. $is->commit();
  463. $this->_bodyToByteStream($is);
  464. }
  465. /**
  466. * Write this entire entity to a {@link Swift_InputByteStream}.
  467. *
  468. * @param Swift_InputByteStream
  469. */
  470. protected function _bodyToByteStream(Swift_InputByteStream $is)
  471. {
  472. if (empty($this->_immediateChildren)) {
  473. if (isset($this->_body)) {
  474. if ($this->_cache->hasKey($this->_cacheKey, 'body')) {
  475. $this->_cache->exportToByteStream($this->_cacheKey, 'body', $is);
  476. } else {
  477. $cacheIs = $this->_cache->getInputByteStream($this->_cacheKey, 'body');
  478. if ($cacheIs) {
  479. $is->bind($cacheIs);
  480. }
  481. $is->write("\r\n");
  482. if ($this->_body instanceof Swift_OutputByteStream) {
  483. $this->_body->setReadPointer(0);
  484. $this->_encoder->encodeByteStream($this->_body, $is, 0, $this->getMaxLineLength());
  485. } else {
  486. $is->write($this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()));
  487. }
  488. if ($cacheIs) {
  489. $is->unbind($cacheIs);
  490. }
  491. }
  492. }
  493. }
  494. if (!empty($this->_immediateChildren)) {
  495. foreach ($this->_immediateChildren as $child) {
  496. $is->write("\r\n\r\n--" . $this->getBoundary() . "\r\n");
  497. $child->toByteStream($is);
  498. }
  499. $is->write("\r\n\r\n--" . $this->getBoundary() . "--\r\n");
  500. }
  501. }
  502. // -- Protected methods
  503. /**
  504. * Get the name of the header that provides the ID of this entity
  505. */
  506. protected function _getIdField()
  507. {
  508. return 'Content-ID';
  509. }
  510. /**
  511. * Get the model data (usually an array or a string) for $field.
  512. */
  513. protected function _getHeaderFieldModel($field)
  514. {
  515. if ($this->_headers->has($field)) {
  516. return $this->_headers->get($field)->getFieldBodyModel();
  517. }
  518. return false;
  519. }
  520. /**
  521. * Set the model data for $field.
  522. */
  523. protected function _setHeaderFieldModel($field, $model)
  524. {
  525. if ($this->_headers->has($field)) {
  526. $this->_headers->get($field)->setFieldBodyModel($model);
  527. return true;
  528. } else {
  529. return false;
  530. }
  531. }
  532. /**
  533. * Get the parameter value of $parameter on $field header.
  534. */
  535. protected function _getHeaderParameter($field, $parameter)
  536. {
  537. if ($this->_headers->has($field)) {
  538. return $this->_headers->get($field)->getParameter($parameter);
  539. }
  540. }
  541. /**
  542. * Set the parameter value of $parameter on $field header.
  543. */
  544. protected function _setHeaderParameter($field, $parameter, $value)
  545. {
  546. if ($this->_headers->has($field)) {
  547. $this->_headers->get($field)->setParameter($parameter, $value);
  548. return true;
  549. } else {
  550. return false;
  551. }
  552. }
  553. /**
  554. * Re-evaluate what content type and encoding should be used on this entity.
  555. */
  556. protected function _fixHeaders()
  557. {
  558. if (count($this->_immediateChildren)) {
  559. $this->_setHeaderParameter('Content-Type', 'boundary',
  560. $this->getBoundary()
  561. );
  562. $this->_headers->remove('Content-Transfer-Encoding');
  563. } else {
  564. $this->_setHeaderParameter('Content-Type', 'boundary', null);
  565. $this->_setEncoding($this->_encoder->getName());
  566. }
  567. }
  568. /**
  569. * Get the KeyCache used in this entity.
  570. *
  571. * @return Swift_KeyCache
  572. */
  573. protected function _getCache()
  574. {
  575. return $this->_cache;
  576. }
  577. /**
  578. * Get the grammar used for validation.
  579. *
  580. * @return Swift_Mime_Grammar
  581. */
  582. protected function _getGrammar()
  583. {
  584. return $this->_grammar;
  585. }
  586. /**
  587. * Empty the KeyCache for this entity.
  588. */
  589. protected function _clearCache()
  590. {
  591. $this->_cache->clearKey($this->_cacheKey, 'body');
  592. }
  593. /**
  594. * Returns a random Content-ID or Message-ID.
  595. *
  596. * @return string
  597. */
  598. protected function getRandomId()
  599. {
  600. $idLeft = md5(getmypid() . '.' . time() . '.' . uniqid(mt_rand(), true));
  601. $idRight = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated';
  602. $id = $idLeft . '@' . $idRight;
  603. try {
  604. $this->_assertValidId($id);
  605. } catch (Swift_RfcComplianceException $e) {
  606. $id = $idLeft . '@swift.generated';
  607. }
  608. return $id;
  609. }
  610. // -- Private methods
  611. private function _readStream(Swift_OutputByteStream $os)
  612. {
  613. $string = '';
  614. while (false !== $bytes = $os->read(8192)) {
  615. $string .= $bytes;
  616. }
  617. return $string;
  618. }
  619. private function _setEncoding($encoding)
  620. {
  621. if (!$this->_setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) {
  622. $this->_headers->addTextHeader('Content-Transfer-Encoding', $encoding);
  623. }
  624. }
  625. private function _assertValidBoundary($boundary)
  626. {
  627. if (!preg_match(
  628. '/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di',
  629. $boundary))
  630. {
  631. throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.');
  632. }
  633. }
  634. private function _setContentTypeInHeaders($type)
  635. {
  636. if (!$this->_setHeaderFieldModel('Content-Type', $type)) {
  637. $this->_headers->addParameterizedHeader('Content-Type', $type);
  638. }
  639. }
  640. private function _setNestingLevel($level)
  641. {
  642. $this->_nestingLevel = $level;
  643. }
  644. private function _getCompoundLevel($children)
  645. {
  646. $level = 0;
  647. foreach ($children as $child) {
  648. $level |= $child->getNestingLevel();
  649. }
  650. return $level;
  651. }
  652. private function _getNeededChildLevel($child, $compoundLevel)
  653. {
  654. $filter = array();
  655. foreach ($this->_compoundLevelFilters as $bitmask => $rules) {
  656. if (($compoundLevel & $bitmask) === $bitmask) {
  657. $filter = $rules + $filter;
  658. }
  659. }
  660. $realLevel = $child->getNestingLevel();
  661. $lowercaseType = strtolower($child->getContentType());
  662. if (isset($filter[$realLevel])
  663. && isset($filter[$realLevel][$lowercaseType]))
  664. {
  665. return $filter[$realLevel][$lowercaseType];
  666. } else {
  667. return $realLevel;
  668. }
  669. }
  670. private function _createChild()
  671. {
  672. return new self($this->_headers->newInstance(),
  673. $this->_encoder, $this->_cache, $this->_grammar);
  674. }
  675. private function _notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder)
  676. {
  677. foreach ($this->_immediateChildren as $child) {
  678. $child->encoderChanged($encoder);
  679. }
  680. }
  681. private function _notifyCharsetChanged($charset)
  682. {
  683. $this->_encoder->charsetChanged($charset);
  684. $this->_headers->charsetChanged($charset);
  685. foreach ($this->_immediateChildren as $child) {
  686. $child->charsetChanged($charset);
  687. }
  688. }
  689. private function _sortChildren()
  690. {
  691. $shouldSort = false;
  692. foreach ($this->_immediateChildren as $child) {
  693. // NOTE: This include alternative parts moved into a related part
  694. if ($child->getNestingLevel() == self::LEVEL_ALTERNATIVE) {
  695. $shouldSort = true;
  696. break;
  697. }
  698. }
  699. // Sort in order of preference, if there is one
  700. if ($shouldSort) {
  701. usort($this->_immediateChildren, array($this, '_childSortAlgorithm'));
  702. }
  703. }
  704. private function _childSortAlgorithm($a, $b)
  705. {
  706. $typePrefs = array();
  707. $types = array(
  708. strtolower($a->getContentType()),
  709. strtolower($b->getContentType())
  710. );
  711. foreach ($types as $type) {
  712. $typePrefs[] = (array_key_exists($type, $this->_alternativePartOrder))
  713. ? $this->_alternativePartOrder[$type]
  714. : (max($this->_alternativePartOrder) + 1);
  715. }
  716. return ($typePrefs[0] >= $typePrefs[1]) ? 1 : -1;
  717. }
  718. // -- Destructor
  719. /**
  720. * Empties it's own contents from the cache.
  721. */
  722. public function __destruct()
  723. {
  724. $this->_cache->clearAll($this->_cacheKey);
  725. }
  726. /**
  727. * Throws an Exception if the id passed does not comply with RFC 2822.
  728. *
  729. * @param string $id
  730. *
  731. * @throws Swift_RfcComplianceException
  732. */
  733. private function _assertValidId($id)
  734. {
  735. if (!preg_match(
  736. '/^' . $this->_grammar->getDefinition('id-left') . '@' .
  737. $this->_grammar->getDefinition('id-right') . '$/D',
  738. $id
  739. ))
  740. {
  741. throw new Swift_RfcComplianceException(
  742. 'Invalid ID given <' . $id . '>'
  743. );
  744. }
  745. }
  746. }