RssView.php 9.7 KB

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