RssView.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. <?php
  2. /**
  3. * Licensed under The MIT License
  4. * For full copyright and license information, please see the LICENSE.txt
  5. * Redistributions of files must retain the above copyright notice.
  6. *
  7. * @author Mark Scherer
  8. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  9. * @link http://www.dereuromark.de/2013/10/03/rss-feeds-in-cakephp
  10. */
  11. App::uses('View', 'View');
  12. App::uses('Xml', 'Utility');
  13. App::uses('CakeTime', 'Utility');
  14. App::uses('Routing', 'Router');
  15. App::uses('Hash', 'Utility');
  16. /**
  17. * A view class that is used for creating RSS feeds.
  18. *
  19. * By setting the '_serialize' key in your controller, you can specify a view variable
  20. * that should be serialized to XML and used as the response for the request.
  21. * This allows you to omit views + layouts, if your just need to emit a single view
  22. * variable as the XML response.
  23. *
  24. * In your controller, you could do the following:
  25. *
  26. * `$this->set(array('posts' => $posts, '_serialize' => 'posts'));`
  27. *
  28. * When the view is rendered, the `$posts` view variable will be serialized
  29. * into the RSS XML.
  30. *
  31. * **Note** The view variable you specify must be compatible with Xml::fromArray().
  32. *
  33. * If you don't use the `_serialize` key, you will need a view. You can use extended
  34. * views to provide layout like functionality. This is currently not yet tested/supported.
  35. */
  36. class RssView extends View {
  37. /**
  38. * Default spec version of generated RSS.
  39. *
  40. * @var string
  41. */
  42. public $version = '2.0';
  43. /**
  44. * The subdirectory. RSS views are always in rss. Currently not in use.
  45. *
  46. * @var string
  47. */
  48. public $subDir = 'rss';
  49. /**
  50. * Holds usable namespaces.
  51. *
  52. * @var array
  53. * @link http://validator.w3.org/feed/docs/howto/declare_namespaces.html
  54. */
  55. protected $_namespaces = array(
  56. 'atom' => 'http://www.w3.org/2005/Atom',
  57. 'content' => 'http://purl.org/rss/1.0/modules/content/',
  58. 'dc' => 'http://purl.org/dc/elements/1.1/',
  59. 'sy' => 'http://purl.org/rss/1.0/modules/syndication/'
  60. );
  61. /**
  62. * Holds the namespace keys in use.
  63. *
  64. * @var array
  65. */
  66. protected $_usedNamespaces = array();
  67. /**
  68. * Holds CDATA placeholders.
  69. *
  70. * @var array
  71. */
  72. protected $_cdata = array();
  73. /**
  74. * Constructor
  75. *
  76. * @param Controller $controller
  77. */
  78. public function __construct(Controller $controller = null) {
  79. parent::__construct($controller);
  80. if (isset($controller->response) && $controller->response instanceof CakeResponse) {
  81. $controller->response->type('rss');
  82. }
  83. }
  84. /**
  85. * If you are using namespaces that are not yet known to the class, you need to globablly
  86. * add them with this method. Namespaces will only be added for actually used prefixes.
  87. *
  88. * @param string $prefix
  89. * @param string $url
  90. * @return void
  91. */
  92. public function setNamespace($prefix, $url) {
  93. $this->_namespaces[$prefix] = $url;
  94. }
  95. /**
  96. * Prepares the channel and sets default values.
  97. *
  98. * @param array $channel
  99. * @return array Channel
  100. */
  101. public function channel($channel) {
  102. if (!isset($channel['link'])) {
  103. $channel['link'] = '/';
  104. }
  105. if (!isset($channel['title'])) {
  106. $channel['title'] = '';
  107. }
  108. if (!isset($channel['description'])) {
  109. $channel['description'] = '';
  110. }
  111. $channel = $this->_prepareOutput($channel);
  112. return $channel;
  113. }
  114. /**
  115. * Converts a time in any format to an RSS time
  116. *
  117. * @param int|string|DateTime $time
  118. * @return string An RSS-formatted timestamp
  119. * @see CakeTime::toRSS
  120. */
  121. public function time($time) {
  122. return CakeTime::toRSS($time);
  123. }
  124. /**
  125. * Skip loading helpers if this is a _serialize based view.
  126. *
  127. * @return void
  128. */
  129. public function loadHelpers() {
  130. if (isset($this->viewVars['_serialize'])) {
  131. return;
  132. }
  133. parent::loadHelpers();
  134. }
  135. /**
  136. * Render a RSS view.
  137. *
  138. * Uses the special '_serialize' parameter to convert a set of
  139. * view variables into a XML response. Makes generating simple
  140. * XML responses very easy. You can omit the '_serialize' parameter,
  141. * and use a normal view + layout as well.
  142. *
  143. * @param string $view The view being rendered.
  144. * @param string $layout The layout being rendered.
  145. * @return string The rendered view.
  146. */
  147. public function render($view = null, $layout = null) {
  148. if (isset($this->viewVars['_serialize'])) {
  149. return $this->_serialize($this->viewVars['_serialize']);
  150. }
  151. if ($view !== false && $this->_getViewFileName($view)) {
  152. return parent::render($view, false);
  153. }
  154. }
  155. /**
  156. * Serialize view vars.
  157. *
  158. * @param string|array $serialize The viewVars that need to be serialized.
  159. * @return string The serialized data
  160. * @throws RuntimeException When the prefix is not specified
  161. */
  162. protected function _serialize($serialize) {
  163. $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'channel';
  164. if (is_array($serialize)) {
  165. $data = array($rootNode => array());
  166. foreach ($serialize as $alias => $key) {
  167. if (is_numeric($alias)) {
  168. $alias = $key;
  169. }
  170. $data[$rootNode][$alias] = $this->viewVars[$key];
  171. }
  172. } else {
  173. $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
  174. if (is_array($data) && Hash::numeric(array_keys($data))) {
  175. $data = array($rootNode => array($serialize => $data));
  176. }
  177. }
  178. $defaults = array('document' => array(), 'channel' => array(), 'items' => array());
  179. $data += $defaults;
  180. if (!empty($data['document']['namespace'])) {
  181. foreach ($data['document']['namespace'] as $prefix => $url) {
  182. $this->setNamespace($prefix, $url);
  183. }
  184. }
  185. $channel = $this->channel($data['channel']);
  186. if (!empty($channel['image']) && empty($channel['image']['title'])) {
  187. $channel['image']['title'] = $channel['title'];
  188. }
  189. foreach ($data['items'] as $item) {
  190. $channel['item'][] = $this->_prepareOutput($item);
  191. }
  192. $array = array(
  193. 'rss' => array(
  194. '@version' => $this->version,
  195. 'channel' => $channel,
  196. )
  197. );
  198. $namespaces = array();
  199. foreach ($this->_usedNamespaces as $usedNamespacePrefix) {
  200. if (!isset($this->_namespaces[$usedNamespacePrefix])) {
  201. throw new RuntimeException(sprintf('The prefix %s is not specified.', $usedNamespacePrefix));
  202. }
  203. $namespaces['xmlns:' . $usedNamespacePrefix] = $this->_namespaces[$usedNamespacePrefix];
  204. }
  205. $array['rss'] += $namespaces;
  206. $options = array();
  207. if (Configure::read('debug')) {
  208. $options['pretty'] = true;
  209. }
  210. $output = Xml::fromArray($array, $options)->asXML();
  211. $output = $this->_replaceCdata($output);
  212. return $output;
  213. }
  214. /**
  215. * RssView::_prepareOutput()
  216. *
  217. * @param array $item
  218. * @return array
  219. */
  220. protected function _prepareOutput($item) {
  221. foreach ($item as $key => $val) {
  222. $prefix = null;
  223. // The cast prevents a PHP bug for switch case and false positives with integers
  224. $bareKey = (string)$key;
  225. // Detect namespaces
  226. if (strpos($key, ':') !== false) {
  227. list($prefix, $bareKey) = explode(':', $key, 2);
  228. if (strpos($prefix, '@') !== false) {
  229. $prefix = substr($prefix, 1);
  230. }
  231. if (!in_array($prefix, $this->_usedNamespaces)) {
  232. $this->_usedNamespaces[] = $prefix;
  233. }
  234. }
  235. $attrib = null;
  236. switch ($bareKey) {
  237. case 'encoded':
  238. $val = $this->_newCdata($val);
  239. break;
  240. case 'pubDate':
  241. $val = $this->time($val);
  242. break;
  243. case 'category':
  244. if (is_array($val) && isset($val['domain'])) {
  245. $attrib['@domain'] = $val['domain'];
  246. $attrib['@'] = isset($val['content']) ? $val['content'] : $attrib['@domain'];
  247. $val = $attrib;
  248. } elseif (is_array($val) && !empty($val[0])) {
  249. $categories = array();
  250. foreach ($val as $category) {
  251. $attrib = array();
  252. if (is_array($category) && isset($category['domain'])) {
  253. $attrib['@domain'] = $category['domain'];
  254. $attrib['@'] = isset($val['content']) ? $val['content'] : $attrib['@domain'];
  255. $category = $attrib;
  256. }
  257. $categories[] = $category;
  258. }
  259. $val = $categories;
  260. }
  261. break;
  262. case 'link':
  263. case 'url':
  264. case 'guid':
  265. case 'comments':
  266. if (is_array($val) && isset($val['@href'])) {
  267. $attrib = $val;
  268. $attrib['@href'] = Router::url($val['@href'], true);
  269. if ($prefix === 'atom') {
  270. $attrib['@rel'] = 'self';
  271. $attrib['@type'] = 'application/rss+xml';
  272. }
  273. $val = $attrib;
  274. } elseif (is_array($val) && isset($val['url'])) {
  275. $val['url'] = Router::url($val['url'], true);
  276. if ($bareKey === 'guid') {
  277. $val['@'] = $val['url'];
  278. unset($val['url']);
  279. }
  280. } else {
  281. $val = Router::url($val, true);
  282. }
  283. break;
  284. case 'source':
  285. if (is_array($val) && isset($val['url'])) {
  286. $attrib['@url'] = Router::url($val['url'], true);
  287. $attrib['@'] = isset($val['content']) ? $val['content'] : $attrib['@url'];
  288. } elseif (!is_array($val)) {
  289. $attrib['@url'] = Router::url($val, true);
  290. $attrib['@'] = $attrib['@url'];
  291. }
  292. $val = $attrib;
  293. break;
  294. case 'enclosure':
  295. if (isset($val['url']) && is_string($val['url']) && is_file(WWW_ROOT . $val['url']) && file_exists(WWW_ROOT . $val['url'])) {
  296. if (!isset($val['length']) && strpos($val['url'], '://') === false) {
  297. $val['length'] = sprintf("%u", filesize(WWW_ROOT . $val['url']));
  298. }
  299. if (!isset($val['type']) && function_exists('mime_content_type')) {
  300. $val['type'] = mime_content_type(WWW_ROOT . $val['url']);
  301. }
  302. }
  303. $attrib['@url'] = Router::url($val['url'], true);
  304. $attrib['@length'] = $val['length'];
  305. $attrib['@type'] = $val['type'];
  306. $val = $attrib;
  307. break;
  308. default:
  309. //nothing
  310. }
  311. if (is_array($val)) {
  312. $val = $this->_prepareOutput($val);
  313. }
  314. $item[$key] = $val;
  315. }
  316. return $item;
  317. }
  318. /**
  319. * RssView::_newCdata()
  320. *
  321. * @param string $content
  322. * @return string
  323. */
  324. protected function _newCdata($content) {
  325. $i = count($this->_cdata);
  326. $this->_cdata[$i] = $content;
  327. return '###CDATA-' . $i . '###';
  328. }
  329. /**
  330. * RssView::_replaceCdata()
  331. *
  332. * @param string $content
  333. * @return string
  334. */
  335. protected function _replaceCdata($content) {
  336. foreach ($this->_cdata as $n => $data) {
  337. $data = '<![CDATA[' . $data . ']]>';
  338. $content = str_replace('###CDATA-' . $n . '###', $data, $content);
  339. }
  340. return $content;
  341. }
  342. }