RssView.php 9.6 KB

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