RssView.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 integer|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(__('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. // Detect namespaces
  223. $prefix = null;
  224. $bareKey = $key;
  225. if (strpos($key, ':') !== false) {
  226. list($prefix, $bareKey) = explode(':', $key, 2);
  227. if (strpos($prefix, '@') !== false) {
  228. $prefix = substr($prefix, 1);
  229. }
  230. if (!in_array($prefix, $this->_usedNamespaces)) {
  231. $this->_usedNamespaces[] = $prefix;
  232. }
  233. }
  234. $attrib = null;
  235. switch ($bareKey) {
  236. case 'encoded':
  237. $val = $this->_newCdata($val);
  238. break;
  239. case 'pubDate':
  240. $val = $this->time($val);
  241. break;
  242. /*
  243. case 'category' :
  244. if (is_array($val) && !empty($val[0])) {
  245. foreach ($val as $category) {
  246. $attrib = array();
  247. if (is_array($category) && isset($category['domain'])) {
  248. $attrib['domain'] = $category['domain'];
  249. unset($category['domain']);
  250. }
  251. $categories[] = $this->elem($key, $attrib, $category);
  252. }
  253. $elements[$key] = implode('', $categories);
  254. continue 2;
  255. } elseif (is_array($val) && isset($val['domain'])) {
  256. $attrib['domain'] = $val['domain'];
  257. }
  258. break;
  259. */
  260. case 'link':
  261. case 'url':
  262. case 'guid':
  263. case 'comments':
  264. if (is_array($val) && isset($val['@href'])) {
  265. $attrib = $val;
  266. $attrib['@href'] = Router::url($val['@href'], true);
  267. if ($prefix === 'atom') {
  268. $attrib['@rel'] = 'self';
  269. $attrib['@type'] = 'application/rss+xml';
  270. }
  271. $val = $attrib;
  272. } elseif (is_array($val) && isset($val['url'])) {
  273. $val['url'] = Router::url($val['url'], true);
  274. if ($bareKey === 'guid') {
  275. $val['@'] = $val['url'];
  276. unset($val['url']);
  277. }
  278. } else {
  279. $val = Router::url($val, true);
  280. }
  281. break;
  282. case 'source':
  283. if (is_array($val) && isset($val['url'])) {
  284. $attrib['url'] = Router::url($val['url'], true);
  285. $val = $val['title'];
  286. } elseif (is_array($val)) {
  287. $attrib['url'] = Router::url($val[0], true);
  288. $val = $val[1];
  289. }
  290. break;
  291. case 'enclosure':
  292. if (is_string($val['url']) && is_file(WWW_ROOT . $val['url']) && file_exists(WWW_ROOT . $val['url'])) {
  293. if (!isset($val['length']) && strpos($val['url'], '://') === false) {
  294. $val['length'] = sprintf("%u", filesize(WWW_ROOT . $val['url']));
  295. }
  296. if (!isset($val['type']) && function_exists('mime_content_type')) {
  297. $val['type'] = mime_content_type(WWW_ROOT . $val['url']);
  298. }
  299. }
  300. $val['url'] = Router::url($val['url'], true);
  301. $attrib = $val;
  302. $val = null;
  303. break;
  304. default:
  305. //$attrib = $att;
  306. }
  307. if (is_array($val)) {
  308. $val = $this->_prepareOutput($val);
  309. }
  310. $item[$key] = $val;
  311. }
  312. return $item;
  313. }
  314. /**
  315. * RssView::_newCdata()
  316. *
  317. * @param string $content
  318. * @return string
  319. */
  320. protected function _newCdata($content) {
  321. $i = count($this->_cdata);
  322. $this->_cdata[$i] = $content;
  323. return '###CDATA-' . $i . '###';
  324. }
  325. /**
  326. * RssView::_replaceCdata()
  327. *
  328. * @param string $content
  329. * @return string
  330. */
  331. protected function _replaceCdata($content) {
  332. foreach ($this->_cdata as $n => $data) {
  333. $data = '<![CDATA[' . $data . ']]>';
  334. $content = str_replace('###CDATA-' . $n . '###', $data, $content);
  335. }
  336. return $content;
  337. }
  338. }