RssView.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. * Constructor
  79. *
  80. * @param Controller $controller
  81. */
  82. public function __construct(Controller $controller = null) {
  83. parent::__construct($controller);
  84. if (isset($controller->response) && $controller->response instanceof CakeResponse) {
  85. $controller->response->type('rss');
  86. }
  87. }
  88. /**
  89. * If you are using namespaces that are not yet known to the class, you need to globablly
  90. * add them with this method. Namespaces will only be added for actually used prefixes.
  91. *
  92. * @param string $prefix
  93. * @param string $url
  94. * @return void
  95. */
  96. public function setNamespace($prefix, $url) {
  97. $this->_namespaces[$prefix] = $url;
  98. }
  99. /**
  100. * Converts an array into an `<item />` element and its contents
  101. *
  102. * @param array $att The attributes of the `<item />` element
  103. * @param array $elements The list of elements contained in this `<item />`
  104. * @return string An RSS `<item />` element
  105. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html#RssHelper::item
  106. */
  107. public function channel($channel) {
  108. if (!isset($channel['title']) && !empty($this->pageTitle)) {
  109. $channel['title'] = $this->pageTitle;
  110. }
  111. if (!isset($channel['description'])) {
  112. $channel['description'] = '';
  113. }
  114. //$channel['link'] = Router::url($elements['link'], true);
  115. $channel = $this->_prepareOutput($channel);
  116. return $channel;
  117. }
  118. /**
  119. * Converts a time in any format to an RSS time
  120. *
  121. * @param integer|string|DateTime $time
  122. * @return string An RSS-formatted timestamp
  123. * @see CakeTime::toRSS
  124. */
  125. public function time($time) {
  126. return CakeTime::toRSS($time);
  127. }
  128. /**
  129. * Skip loading helpers if this is a _serialize based view.
  130. *
  131. * @return void
  132. */
  133. public function loadHelpers() {
  134. if (isset($this->viewVars['_serialize'])) {
  135. return;
  136. }
  137. parent::loadHelpers();
  138. }
  139. /**
  140. * Render a RSS view.
  141. *
  142. * Uses the special '_serialize' parameter to convert a set of
  143. * view variables into a XML response. Makes generating simple
  144. * XML responses very easy. You can omit the '_serialize' parameter,
  145. * and use a normal view + layout as well.
  146. *
  147. * @param string $view The view being rendered.
  148. * @param string $layout The layout being rendered.
  149. * @return string The rendered view.
  150. */
  151. public function render($view = null, $layout = null) {
  152. if (isset($this->viewVars['_serialize'])) {
  153. return $this->_serialize($this->viewVars['_serialize']);
  154. }
  155. if ($view !== false && $this->_getViewFileName($view)) {
  156. return parent::render($view, false);
  157. }
  158. }
  159. /**
  160. * Serialize view vars.
  161. *
  162. * @param array $serialize The viewVars that need to be serialized.
  163. * @return string The serialized data
  164. */
  165. protected function _serialize($serialize) {
  166. $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'channel';
  167. if (is_array($serialize)) {
  168. $data = array($rootNode => array());
  169. foreach ($serialize as $alias => $key) {
  170. if (is_numeric($alias)) {
  171. $alias = $key;
  172. }
  173. $data[$rootNode][$alias] = $this->viewVars[$key];
  174. }
  175. } else {
  176. $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
  177. if (is_array($data) && Set::numeric(array_keys($data))) {
  178. $data = array($rootNode => array($serialize => $data));
  179. }
  180. }
  181. $defaults = array('document' => array(), 'channel' => array(), 'items' => array());
  182. $data += $defaults;
  183. if (!empty($data['document']['namespace'])) {
  184. foreach ($data['document']['namespace'] as $prefix => $url) {
  185. $this->setNamespace($prefix, $url);
  186. }
  187. }
  188. $channel = $this->channel($data['channel']);
  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. $namespaces['xmlns:' . $usedNamespacePrefix] = $this->_namespaces[$usedNamespacePrefix];
  201. }
  202. $array['rss'] += $namespaces;
  203. $options = array();
  204. if (Configure::read('debug')) {
  205. $options['pretty'] = true;
  206. }
  207. $output = Xml::fromArray($array, $options)->asXML();
  208. //$output = preg_replace('/version="([0-9\.]+)" encoding="([a-z-]+)"/i', 'version="\1"', $output);
  209. //$output = str_replace(' encoding="UTF-8"', '', $output);
  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. if (is_array($val)) {
  234. $val = $this->_prepareOutput($val);
  235. }
  236. $attrib = null;
  237. switch ($bareKey) {
  238. case 'encoded':
  239. $val = $this->_newCdata($val);
  240. break;
  241. case 'pubDate':
  242. $val = $this->time($val);
  243. break;
  244. /*
  245. case 'category' :
  246. if (is_array($val) && !empty($val[0])) {
  247. foreach ($val as $category) {
  248. $attrib = array();
  249. if (is_array($category) && isset($category['domain'])) {
  250. $attrib['domain'] = $category['domain'];
  251. unset($category['domain']);
  252. }
  253. $categories[] = $this->elem($key, $attrib, $category);
  254. }
  255. $elements[$key] = implode('', $categories);
  256. continue 2;
  257. } elseif (is_array($val) && isset($val['domain'])) {
  258. $attrib['domain'] = $val['domain'];
  259. }
  260. break;
  261. */
  262. case 'link':
  263. case 'guid':
  264. case 'comments':
  265. if (is_array($val) && isset($val['@href'])) {
  266. $attrib = $val;
  267. $attrib['@href'] = Router::url($val['@href'], true);
  268. if ($prefix === 'atom') {
  269. $attrib['@rel'] = 'self';
  270. $attrib['@type'] = 'application/rss+xml';
  271. }
  272. $val = $attrib;
  273. } elseif (is_array($val) && isset($val['url'])) {
  274. $val['url'] = Router::url($val['url'], true);
  275. if ($bareKey === 'guid') {
  276. $val['@'] = $val['url'];
  277. unset($val['url']);
  278. }
  279. } else {
  280. $val = Router::url($val, true);
  281. }
  282. break;
  283. case 'source':
  284. if (is_array($val) && isset($val['url'])) {
  285. $attrib['url'] = Router::url($val['url'], true);
  286. $val = $val['title'];
  287. } elseif (is_array($val)) {
  288. $attrib['url'] = Router::url($val[0], true);
  289. $val = $val[1];
  290. }
  291. break;
  292. case 'enclosure':
  293. if (is_string($val['url']) && is_file(WWW_ROOT . $val['url']) && file_exists(WWW_ROOT . $val['url'])) {
  294. if (!isset($val['length']) && strpos($val['url'], '://') === false) {
  295. $val['length'] = sprintf("%u", filesize(WWW_ROOT . $val['url']));
  296. }
  297. if (!isset($val['type']) && function_exists('mime_content_type')) {
  298. $val['type'] = mime_content_type(WWW_ROOT . $val['url']);
  299. }
  300. }
  301. $val['url'] = Router::url($val['url'], true);
  302. $attrib = $val;
  303. $val = null;
  304. break;
  305. default:
  306. //$attrib = $att;
  307. }
  308. $item[$key] = $val;
  309. }
  310. return $item;
  311. }
  312. protected $_cdata = array();
  313. protected function _newCdata($content) {
  314. $i = count($this->_cdata);
  315. $this->_cdata[$i] = $content;
  316. return '###CDATA-' . $i . '###';
  317. }
  318. protected function _replaceCdata($content) {
  319. foreach ($this->_cdata as $n => $data) {
  320. $data = '<![CDATA[' . $data . ']]>';
  321. $content = str_replace('###CDATA-' . $n . '###', $data, $content);
  322. }
  323. return $content;
  324. }
  325. }