SimpleMimeEntity.php 23 KB

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