PHP Universal Feed Generator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

883 lines
28 KiB

  1. <?php
  2. namespace FeedWriter;
  3. use \DateTime;
  4. /*
  5. * Copyright (C) 2008 Anis uddin Ahmad <anisniit@gmail.com>
  6. * Copyright (C) 2010-2014 Michael Bemmerl <mail@mx-server.de>
  7. *
  8. * This file is part of the "Universal Feed Writer" project.
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation, either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. // RSS 0.90 Officially obsoleted by 1.0
  24. // RSS 0.91, 0.92, 0.93 and 0.94 Officially obsoleted by 2.0
  25. // So, define constants for RSS 1.0, RSS 2.0 and ATOM
  26. /**
  27. * Universal Feed Writer class
  28. *
  29. * Generate RSS 1.0, RSS2.0 and ATOM Feeds
  30. *
  31. * @package UniversalFeedWriter
  32. * @author Anis uddin Ahmad <anisniit@gmail.com>
  33. * @link http://www.ajaxray.com/projects/rss
  34. */
  35. abstract class Feed
  36. {
  37. const RSS1 = 'RSS 1.0';
  38. const RSS2 = 'RSS 2.0';
  39. const ATOM = 'ATOM';
  40. /**
  41. * Collection of all channel elements
  42. */
  43. private $channels = array();
  44. /**
  45. * Collection of items as object of \FeedWriter\Item class.
  46. */
  47. private $items = array();
  48. /**
  49. * Store some other version wise data
  50. */
  51. private $data = array();
  52. /**
  53. * The tag names which have to encoded as CDATA
  54. */
  55. private $CDATAEncoding = array();
  56. /**
  57. * Collection of XML namespaces
  58. */
  59. private $namespaces = array();
  60. /**
  61. * Contains the format of this feed.
  62. */
  63. private $version = null;
  64. /**
  65. * Constructor
  66. *
  67. * If no version is given, a feed in RSS 2.0 format will be generated.
  68. *
  69. * @param constant the version constant (RSS1/RSS2/ATOM).
  70. */
  71. protected function __construct($version = Feed::RSS2)
  72. {
  73. $this->version = $version;
  74. // Setting default encoding
  75. $this->encoding = 'utf-8';
  76. // Setting default value for essential channel elements
  77. $this->channels['title'] = $version . ' Feed';
  78. $this->channels['link'] = 'http://www.ajaxray.com/blog';
  79. // Add some default XML namespaces
  80. $this->namespaces['content'] = 'http://purl.org/rss/1.0/modules/content/';
  81. $this->namespaces['wfw'] = 'http://wellformedweb.org/CommentAPI/';
  82. $this->namespaces['atom'] = 'http://www.w3.org/2005/Atom';
  83. $this->namespaces['rdf'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
  84. $this->namespaces['rss1'] = 'http://purl.org/rss/1.0/';
  85. $this->namespaces['dc'] = 'http://purl.org/dc/elements/1.1/';
  86. $this->namespaces['sy'] = 'http://purl.org/rss/1.0/modules/syndication/';
  87. // Tag names to encode in CDATA
  88. $this->addCDATAEncoding(array('description', 'content:encoded', 'summary'));
  89. }
  90. // Start # public functions ---------------------------------------------
  91. /**
  92. * Set the URLs for feed pagination.
  93. *
  94. * See RFC 5005, chapter 3. At least one page URL must be specified.
  95. *
  96. * @param string The URL to the next page of this feed. Optional.
  97. * @param string The URL to the previous page of this feed. Optional.
  98. * @param string The URL to the first page of this feed. Optional.
  99. * @param string The URL to the last page of this feed. Optional.
  100. * @link http://tools.ietf.org/html/rfc5005#section-3
  101. * @return self
  102. */
  103. public function setPagination($nextURL = null, $previousURL = null, $firstURL = null, $lastURL = null)
  104. {
  105. if (empty($nextURL) && empty($previousURL) && empty($firstURL) && empty($lastURL))
  106. die('At least one URL must be specified for pagination to work.');
  107. if (!empty($nextURL))
  108. $this->setAtomLink($nextURL, 'next');
  109. if (!empty($previousURL))
  110. $this->setAtomLink($previousURL, 'previous');
  111. if (!empty($firstURL))
  112. $this->setAtomLink($firstURL, 'first');
  113. if (!empty($lastURL))
  114. $this->setAtomLink($lastURL, 'last');
  115. return $this;
  116. }
  117. /**
  118. * Add a channel element indicating the program used to generate the feed.
  119. *
  120. * @return self
  121. */
  122. public function addGenerator()
  123. {
  124. if ($this->version == Feed::ATOM)
  125. $this->setChannelElement('atom:generator', 'FeedWriter', array('uri' => 'https://github.com/mibe/FeedWriter'));
  126. else if ($this->version == Feed::RSS2)
  127. $this->setChannelElement('generator', 'FeedWriter');
  128. else
  129. die('The generator element is not supported in RSS1 feeds.');
  130. return $this;
  131. }
  132. /**
  133. * Add a XML namespace to the internal list of namespaces. After that,
  134. * custom channel elements can be used properly to generate a valid feed.
  135. *
  136. * @access public
  137. * @param string namespace prefix
  138. * @param string namespace name (URI)
  139. * @return self
  140. * @link http://www.w3.org/TR/REC-xml-names/
  141. */
  142. public function addNamespace($prefix, $uri)
  143. {
  144. $this->namespaces[$prefix] = $uri;
  145. return $this;
  146. }
  147. /**
  148. * Add a channel element to the feed.
  149. *
  150. * @access public
  151. * @param string name of the channel tag
  152. * @param string content of the channel tag
  153. * @param array array of element attributes with attribute name as array key
  154. * @param bool TRUE if this element can appear multiple times
  155. * @return self
  156. */
  157. public function setChannelElement($elementName, $content, $attributes = null, $multiple = false)
  158. {
  159. $entity['content'] = $content;
  160. $entity['attributes'] = $attributes;
  161. if ($multiple === TRUE)
  162. $this->channels[$elementName][] = $entity;
  163. else
  164. $this->channels[$elementName] = $entity;
  165. return $this;
  166. }
  167. /**
  168. * Set multiple channel elements from an array. Array elements
  169. * should be 'channelName' => 'channelContent' format.
  170. *
  171. * @access public
  172. * @param array array of channels
  173. * @return self
  174. */
  175. public function setChannelElementsFromArray($elementArray)
  176. {
  177. if (!is_array($elementArray))
  178. return;
  179. foreach ($elementArray as $elementName => $content) {
  180. $this->setChannelElement($elementName, $content);
  181. }
  182. return $this;
  183. }
  184. /**
  185. * Get the appropriate MIME type string for the current feed.
  186. *
  187. * @access public
  188. * @return string The MIME type string.
  189. */
  190. public function getMIMEType()
  191. {
  192. switch ($this->version) {
  193. case Feed::RSS2 : $mimeType = "application/rss+xml";
  194. break;
  195. case Feed::RSS1 : $mimeType = "application/rdf+xml";
  196. break;
  197. case Feed::ATOM : $mimeType = "application/atom+xml";
  198. break;
  199. default : $mimeType = "text/xml";
  200. }
  201. return $mimeType;
  202. }
  203. /**
  204. * Print the actual RSS/ATOM file
  205. *
  206. * Sets a Content-Type header and echoes the contents of the feed.
  207. * Should only be used in situations where direct output is desired;
  208. * if you need to pass a string around, use generateFeed() instead.
  209. *
  210. * @access public
  211. * @param bool FALSE if the specific feed media type should be sent.
  212. * @return void
  213. */
  214. public function printFeed($useGenericContentType = false)
  215. {
  216. $contentType = "text/xml";
  217. if (!$useGenericContentType) {
  218. $contentType = $this->getMIMEType();
  219. }
  220. header("Content-Type: " . $contentType);
  221. echo $this->generateFeed();
  222. }
  223. /**
  224. * Generate the feed.
  225. *
  226. * @access public
  227. * @return string The complete feed XML.
  228. */
  229. public function generateFeed()
  230. {
  231. return $this->makeHeader()
  232. . $this->makeChannels()
  233. . $this->makeItems()
  234. . $this->makeFooter();
  235. }
  236. /**
  237. * Create a new Item.
  238. *
  239. * @access public
  240. * @return Item instance of Item class
  241. */
  242. public function createNewItem()
  243. {
  244. $Item = new Item($this->version);
  245. return $Item;
  246. }
  247. /**
  248. * Add a properties to be CDATA encoded
  249. *
  250. * @access public
  251. * @param array An array of properties that are merged into the list of properties should be encoded as CDATA
  252. * @return self
  253. */
  254. public function addCDATAEncoding(Array $property_list)
  255. {
  256. $this->CDATAEncoding = array_merge($this->CDATAEncoding, $property_list);
  257. return $this;
  258. }
  259. /**
  260. * Get list of CDATA encoded properties
  261. *
  262. * @access public
  263. * @return array Return an array of CDATA properties that are to be encoded as CDATA
  264. */
  265. public function getCDATAEncoding()
  266. {
  267. return $this->CDATAEncoding;
  268. }
  269. /**
  270. * Add a FeedItem to the main class
  271. *
  272. * @access public
  273. * @param Item instance of Item class
  274. * @return self
  275. */
  276. public function addItem(Item $feedItem)
  277. {
  278. if ($feedItem->getVersion() != $this->version)
  279. die('Feed type mismatch: This instance can handle ' . $this->version . ' feeds only, but item with type ' . $feedItem->getVersion() . ' given.');
  280. $this->items[] = $feedItem;
  281. return $this;
  282. }
  283. // Wrapper functions -------------------------------------------------------------------
  284. /**
  285. * Set the 'encoding' attribute in the XML prolog.
  286. *
  287. * @access public
  288. * @param string value of 'encoding' attribute
  289. * @return self
  290. */
  291. public function setEncoding($encoding)
  292. {
  293. $this->encoding = $encoding;
  294. return $this;
  295. }
  296. /**
  297. * Set the 'title' channel element
  298. *
  299. * @access public
  300. * @param string value of 'title' channel tag
  301. * @return self
  302. */
  303. public function setTitle($title)
  304. {
  305. return $this->setChannelElement('title', $title);
  306. }
  307. /**
  308. * Set the date when the ATOM feed was lastly updated.
  309. *
  310. * This adds the 'updated' element to the feed. The value of the date parameter
  311. * can be either an instance of the DateTime class, an integer containing a UNIX
  312. * timestamp or a string which is parseable by PHP's 'strtotime' function.
  313. *
  314. * Not supported in RSS1 feeds.
  315. *
  316. * @access public
  317. * @param DateTime|int|string Date which should be used.
  318. * @return self
  319. */
  320. public function setDate($date)
  321. {
  322. if ($this->version == Feed::RSS1)
  323. die('The publication date is not supported in RSS1 feeds.');
  324. // The feeds have different date formats.
  325. $format = $this->version == Feed::ATOM ? \DATE_ATOM : \DATE_RSS;
  326. if ($date instanceof DateTime)
  327. $date = $date->format($format);
  328. else if(is_numeric($date) && $date >= 0)
  329. $date = date($format, $date);
  330. else if (is_string($date))
  331. $date = date($format, strtotime($date));
  332. else
  333. die('The given date was not an instance of DateTime, a UNIX timestamp or a date string.');
  334. if ($this->version == Feed::ATOM)
  335. $this->setChannelElement('updated', $date);
  336. else
  337. $this->setChannelElement('lastBuildDate', $date);
  338. return $this;
  339. }
  340. /**
  341. * Set the 'description' channel element
  342. *
  343. * @access public
  344. * @param string value of 'description' channel tag
  345. * @return self
  346. */
  347. public function setDescription($description)
  348. {
  349. if ($this->version != Feed::ATOM)
  350. $this->setChannelElement('description', $description);
  351. return $this;
  352. }
  353. /**
  354. * Set the 'link' channel element
  355. *
  356. * @access public
  357. * @param string value of 'link' channel tag
  358. * @return self
  359. */
  360. public function setLink($link)
  361. {
  362. if ($this->version == Feed::ATOM)
  363. $this->setChannelElement('link', '', array('href' => $link));
  364. else
  365. $this->setChannelElement('link', $link);
  366. return $this;
  367. }
  368. /**
  369. * Set custom 'link' channel elements.
  370. *
  371. * In ATOM feeds, only one link with alternate relation and the same combination of
  372. * type and hreflang values.
  373. *
  374. * @access public
  375. * @param string URI of this link
  376. * @param string relation type of the resource
  377. * @param string MIME type of the target resource
  378. * @param string language of the resource
  379. * @param string human-readable information about the resource
  380. * @param int length of the resource in bytes
  381. * @link https://www.iana.org/assignments/link-relations/link-relations.xml
  382. * @link https://tools.ietf.org/html/rfc4287#section-4.2.7
  383. * @return self
  384. */
  385. public function setAtomLink($href, $rel = null, $type = null, $hreflang = null, $title = null, $length = null)
  386. {
  387. $data = array('href' => $href);
  388. if ($rel != null) {
  389. if (!is_string($rel) || empty($rel))
  390. die('rel parameter must be a string and a valid relation identifier.');
  391. $data['rel'] = $rel;
  392. }
  393. if ($type != null) {
  394. // Regex used from RFC 4287, page 41
  395. if (!is_string($type) || preg_match('/.+\/.+/', $type) != 1)
  396. die('type parameter must be a string and a MIME type.');
  397. $data['type'] = $type;
  398. }
  399. if ($hreflang != null) {
  400. // Regex used from RFC 4287, page 41
  401. if (!is_string($hreflang) || preg_match('/[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*/', $hreflang) != 1)
  402. die('hreflang parameter must be a string and a valid language code.');
  403. $data['hreflang'] = $hreflang;
  404. }
  405. if ($title != null) {
  406. if (!is_string($title) || empty($title))
  407. die('title parameter must be a string and not empty.');
  408. $data['title'] = $title;
  409. }
  410. if ($length != null) {
  411. if (!is_int($length) || $length < 0)
  412. die('length parameter must be a positive integer.');
  413. $data['length'] = (string) $length;
  414. }
  415. // ATOM spec. has some restrictions on atom:link usage
  416. // See RFC 4287, page 12 (4.1.1)
  417. if ($this->version == Feed::ATOM) {
  418. foreach ($this->channels as $key => $value) {
  419. if ($key != 'atom:link')
  420. continue;
  421. // $value is an array , so check every element
  422. foreach ($value as $linkItem) {
  423. // Only one link with relation alternate and same hreflang & type is allowed.
  424. if (@$linkItem['rel'] == 'alternate' && @$linkItem['hreflang'] == $hreflang && @$linkItem['type'] == $type)
  425. die('The feed must not contain more than one link element with a relation of "alternate"'
  426. . ' that has the same combination of type and hreflang attribute values.');
  427. }
  428. }
  429. }
  430. return $this->setChannelElement('atom:link', '', $data, true);
  431. }
  432. /**
  433. * Set an 'atom:link' channel element with relation=self attribute.
  434. * Needs the full URL to this feed.
  435. *
  436. * @link http://www.rssboard.org/rss-profile#namespace-elements-atom-link
  437. * @access public
  438. * @param string URL to this feed
  439. * @return self
  440. */
  441. public function setSelfLink($url)
  442. {
  443. return $this->setAtomLink($url, 'self', $this->getMIMEType());
  444. }
  445. /**
  446. * Set the 'image' channel element
  447. *
  448. * @access public
  449. * @param string title of image
  450. * @param string link url of the image
  451. * @param string path url of the image
  452. * @return self
  453. */
  454. public function setImage($title, $link, $url)
  455. {
  456. return $this->setChannelElement('image', array('title'=>$title, 'link'=>$link, 'url'=>$url));
  457. }
  458. /**
  459. * Set the 'about' channel element. Only for RSS 1.0
  460. *
  461. * @access public
  462. * @param string value of 'about' channel tag
  463. * @return self
  464. */
  465. public function setChannelAbout($url)
  466. {
  467. $this->data['ChannelAbout'] = $url;
  468. return $this;
  469. }
  470. /**
  471. * Generate an UUID.
  472. *
  473. * The UUID is based on an MD5 hash. If no key is given, a unique ID as the input
  474. * for the MD5 hash is generated.
  475. *
  476. * @author Anis uddin Ahmad <admin@ajaxray.com>
  477. * @param string optional key on which the UUID is generated
  478. * @param string an optional prefix
  479. * @return string the formated UUID
  480. */
  481. public static function uuid($key = null, $prefix = '')
  482. {
  483. $key = ($key == null) ? uniqid(rand()) : $key;
  484. $chars = md5($key);
  485. $uuid = substr($chars,0,8) . '-';
  486. $uuid .= substr($chars,8,4) . '-';
  487. $uuid .= substr($chars,12,4) . '-';
  488. $uuid .= substr($chars,16,4) . '-';
  489. $uuid .= substr($chars,20,12);
  490. return $prefix . $uuid;
  491. }
  492. /**
  493. * Replace invalid xml utf-8 chars.
  494. *
  495. * See utf8_for_xml() function at
  496. * http://www.phpwact.org/php/i18n/charsets#xml and
  497. * http://www.w3.org/TR/REC-xml/#charsets
  498. *
  499. * @param string
  500. * @return string
  501. */
  502. public static function utf8_for_xml($string)
  503. {
  504. return preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $string);
  505. }
  506. // End # public functions ----------------------------------------------
  507. // Start # private functions ----------------------------------------------
  508. /**
  509. * Returns all used XML namespace prefixes in this instance.
  510. * This includes all channel elements and feed items.
  511. * Unfortunately some namespace prefixes are not included,
  512. * because they are hardcoded, e.g. rdf.
  513. *
  514. * @access private
  515. * @return array Array with namespace prefix as value.
  516. */
  517. private function getNamespacePrefixes()
  518. {
  519. $prefixes = array();
  520. // Get all tag names from channel elements...
  521. $tags = array_keys($this->channels);
  522. // ... and now all names from feed items
  523. foreach ($this->items as $item)
  524. $tags = array_merge($tags, array_keys($item->getElements()));
  525. // Look for prefixes in those tag names
  526. foreach ($tags as $tag) {
  527. $elements = explode(':', $tag);
  528. if (count($elements) != 2)
  529. continue;
  530. $prefixes[] = $elements[0];
  531. }
  532. return array_unique($prefixes);
  533. }
  534. /**
  535. * Returns the XML header and root element, depending on the feed type.
  536. *
  537. * @access private
  538. * @return string The XML header of the feed.
  539. */
  540. private function makeHeader()
  541. {
  542. $out = '<?xml version="1.0" encoding="'.$this->encoding.'" ?>' . PHP_EOL;
  543. $prefixes = $this->getNamespacePrefixes();
  544. $attributes = array();
  545. $tagName = '';
  546. $defaultNamespace = '';
  547. if ($this->version == Feed::RSS2) {
  548. $tagName = 'rss';
  549. $attributes['version'] = '2.0';
  550. } elseif ($this->version == Feed::RSS1) {
  551. $tagName = 'rdf:RDF';
  552. $prefixes[] = 'rdf';
  553. $defaultNamespace = $this->namespaces['rss1'];
  554. } elseif ($this->version == Feed::ATOM) {
  555. $tagName = 'feed';
  556. $defaultNamespace = $this->namespaces['atom'];
  557. // Ugly hack to remove the 'atom' value from the prefixes array.
  558. $prefixes = array_flip($prefixes);
  559. unset($prefixes['atom']);
  560. $prefixes = array_flip($prefixes);
  561. }
  562. // Iterate through every namespace prefix and add it to the element attributes.
  563. foreach ($prefixes as $prefix) {
  564. if (!isset($this->namespaces[$prefix]))
  565. die('Unknown XML namespace prefix: \'' . $prefix . '\'. Use the addNamespace method to add support for this prefix.');
  566. else
  567. $attributes['xmlns:' . $prefix] = $this->namespaces[$prefix];
  568. }
  569. // Include default namepsace, if required
  570. if (!empty($defaultNamespace))
  571. $attributes['xmlns'] = $defaultNamespace;
  572. $out .= $this->makeNode($tagName, '', $attributes, true);
  573. return $out;
  574. }
  575. /**
  576. * Closes the open tags at the end of file
  577. *
  578. * @access private
  579. * @return string The XML footer of the feed.
  580. */
  581. private function makeFooter()
  582. {
  583. if ($this->version == Feed::RSS2) {
  584. return '</channel>' . PHP_EOL . '</rss>';
  585. } elseif ($this->version == Feed::RSS1) {
  586. return '</rdf:RDF>';
  587. } elseif ($this->version == Feed::ATOM) {
  588. return '</feed>';
  589. }
  590. }
  591. /**
  592. * Creates a single node in XML format
  593. *
  594. * @access private
  595. * @param string name of the tag
  596. * @param mixed tag value as string or array of nested tags in 'tagName' => 'tagValue' format
  597. * @param array Attributes (if any) in 'attrName' => 'attrValue' format
  598. * @param string True if the end tag should be omitted. Defaults to false.
  599. * @return string formatted xml tag
  600. */
  601. private function makeNode($tagName, $tagContent, $attributes = null, $omitEndTag = false)
  602. {
  603. $nodeText = '';
  604. $attrText = '';
  605. if (is_array($attributes) && count($attributes) > 0) {
  606. foreach ($attributes as $key => $value) {
  607. $value = self::utf8_for_xml($value);
  608. $value = htmlspecialchars($value);
  609. $attrText .= " $key=\"$value\"";
  610. }
  611. }
  612. if (is_array($tagContent) && $this->version == Feed::RSS1) {
  613. $attrText = ' rdf:parseType="Resource"';
  614. }
  615. $attrText .= (in_array($tagName, $this->CDATAEncoding) && $this->version == Feed::ATOM) ? ' type="html"' : '';
  616. $nodeText .= "<{$tagName}{$attrText}>";
  617. $nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? '<![CDATA[' : '';
  618. if (is_array($tagContent)) {
  619. foreach ($tagContent as $key => $value) {
  620. $nodeText .= $this->makeNode($key, $value);
  621. }
  622. } else {
  623. $tagContent = self::utf8_for_xml($tagContent);
  624. $nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? $this->sanitizeCDATA($tagContent) : htmlspecialchars($tagContent);
  625. }
  626. $nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? ']]>' : '';
  627. if (!$omitEndTag)
  628. $nodeText .= "</$tagName>";
  629. $nodeText .= PHP_EOL;
  630. return $nodeText;
  631. }
  632. /**
  633. * Make the channels.
  634. *
  635. * @access private
  636. * @return string The feed header as XML containing all the feed metadata.
  637. */
  638. private function makeChannels()
  639. {
  640. $out = '';
  641. //Start channel tag
  642. switch ($this->version) {
  643. case Feed::RSS2:
  644. $out .= '<channel>' . PHP_EOL;
  645. break;
  646. case Feed::RSS1:
  647. $out .= (isset($this->data['ChannelAbout']))? "<channel rdf:about=\"{$this->data['ChannelAbout']}\">" : "<channel rdf:about=\"{$this->channels['link']}\">";
  648. break;
  649. }
  650. //Print Items of channel
  651. foreach ($this->channels as $key => $value) {
  652. // In ATOM feeds, strip all ATOM namespace prefixes from the tag name. They are not needed here,
  653. // because the ATOM namespace name is set as default namespace.
  654. if ($this->version == Feed::ATOM && strncmp($key, 'atom', 4) == 0) {
  655. $key = substr($key, 5);
  656. }
  657. // The channel element can occur multiple times, when the key 'content' is not in the array.
  658. if (!isset($value['content'])) {
  659. // If this is the case, iterate through the array with the multiple elements.
  660. foreach ($value as $singleElement) {
  661. $out .= $this->makeNode($key, $singleElement['content'], $singleElement['attributes']);
  662. }
  663. } else {
  664. $out .= $this->makeNode($key, $value['content'], $value['attributes']);
  665. }
  666. }
  667. if ($this->version == Feed::RSS1) {
  668. //RSS 1.0 have special tag <rdf:Seq> with channel
  669. $out .= "<items>" . PHP_EOL . "<rdf:Seq>" . PHP_EOL;
  670. foreach ($this->items as $item) {
  671. $thisItems = $item->getElements();
  672. $out .= "<rdf:li resource=\"{$thisItems['link']['content']}\"/>" . PHP_EOL;
  673. }
  674. $out .= "</rdf:Seq>" . PHP_EOL . "</items>" . PHP_EOL . "</channel>" . PHP_EOL;
  675. } else if ($this->version == Feed::ATOM) {
  676. // ATOM feeds have a unique feed ID. This is generated from the 'link' channel element.
  677. $out .= $this->makeNode('id', Feed::uuid($this->channels['link']['attributes']['href'], 'urn:uuid:'));
  678. }
  679. return $out;
  680. }
  681. /**
  682. * Prints formatted feed items
  683. *
  684. * @access private
  685. * @return string The XML of every feed item.
  686. */
  687. private function makeItems()
  688. {
  689. $out = '';
  690. foreach ($this->items as $item) {
  691. $thisItems = $item->getElements();
  692. // the argument is printed as rdf:about attribute of item in rss 1.0
  693. $out .= $this->startItem($thisItems['link']['content']);
  694. foreach ($thisItems as $feedItem) {
  695. $name = $feedItem['name'];
  696. // Strip all ATOM namespace prefixes from tags when feed is an ATOM feed.
  697. // Not needed here, because the ATOM namespace name is used as default namespace.
  698. if ($this->version == Feed::ATOM && strncmp($name, 'atom', 4) == 0)
  699. $name = substr($name, 5);
  700. $out .= $this->makeNode($name, $feedItem['content'], $feedItem['attributes']);
  701. }
  702. $out .= $this->endItem();
  703. }
  704. return $out;
  705. }
  706. /**
  707. * Make the starting tag of channels
  708. *
  709. * @access private
  710. * @param string The vale of about tag which is used for RSS 1.0 only.
  711. * @return string The starting XML tag of an feed item.
  712. */
  713. private function startItem($about = false)
  714. {
  715. $out = '';
  716. if ($this->version == Feed::RSS2) {
  717. $out .= '<item>' . PHP_EOL;
  718. } elseif ($this->version == Feed::RSS1) {
  719. if ($about) {
  720. $out .= "<item rdf:about=\"$about\">" . PHP_EOL;
  721. } else {
  722. throw new \Exception("link element is not set - It's required for RSS 1.0 to be used as the about attribute of the item tag.");
  723. }
  724. } elseif ($this->version == Feed::ATOM) {
  725. $out .= "<entry>" . PHP_EOL;
  726. }
  727. return $out;
  728. }
  729. /**
  730. * Closes feed item tag
  731. *
  732. * @access private
  733. * @return string The ending XML tag of an feed item.
  734. */
  735. private function endItem()
  736. {
  737. if ($this->version == Feed::RSS2 || $this->version == Feed::RSS1) {
  738. return '</item>' . PHP_EOL;
  739. } elseif ($this->version == Feed::ATOM) {
  740. return '</entry>' . PHP_EOL;
  741. }
  742. }
  743. /**
  744. * Sanitizes data which will be later on returned as CDATA in the feed.
  745. *
  746. * A "]]>" respectively "<![CDATA" in the data would break the CDATA in the
  747. * XML, so the brackets are converted to a HTML entity.
  748. *
  749. * @access private
  750. * @param string Data to be sanitized
  751. * @return string Sanitized data
  752. */
  753. private function sanitizeCDATA($text)
  754. {
  755. $text = str_replace("]]>", "]]&gt;", $text);
  756. $text = str_replace("<![CDATA[", "&lt;![CDATA[", $text);
  757. return $text;
  758. }
  759. // End # private functions ----------------------------------------------
  760. } // end of class Feed