1
0

lastRSS.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. <?php
  2. /* $Id: lastRSS.php 2907 2007-04-15 13:05:13Z b4rt $ */
  3. /*
  4. ======================================================================
  5. lastRSS 0.9.1
  6. Simple yet powerful PHP class to parse RSS files.
  7. by Vojtech Semecky, webmaster @ webdot . cz
  8. Latest version, features, manual and examples:
  9. http://lastrss.webdot.cz/
  10. ----------------------------------------------------------------------
  11. LICENSE
  12. This program is free software; you can redistribute it and/or
  13. modify it under the terms of the GNU General Public License (GPL)
  14. as published by the Free Software Foundation; either version 2
  15. of the License, or (at your option) any later version.
  16. This program is distributed in the hope that it will be useful,
  17. but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. GNU General Public License for more details.
  20. To read the license please visit http://www.gnu.org/copyleft/gpl.html
  21. ======================================================================
  22. */
  23. /**
  24. * lastRSS
  25. * Simple yet powerful PHP class to parse RSS files.
  26. */
  27. class lastRSS {
  28. // -------------------------------------------------------------------------
  29. // Public properties
  30. // -------------------------------------------------------------------------
  31. var $default_cp = 'UTF-8';
  32. var $CDATA = 'nochange';
  33. var $cp = '';
  34. var $items_limit = 0;
  35. var $stripHTML = False;
  36. var $date_format = '';
  37. // -------------------------------------------------------------------------
  38. // Private variables
  39. // -------------------------------------------------------------------------
  40. var $_channeltags = array ('title', 'link', 'description', 'language', 'copyright', 'managingEditor', 'webMaster', 'lastBuildDate', 'rating', 'docs');
  41. var $_itemtags = array('title', 'link', 'description', 'author', 'category', 'comments', 'enclosure', 'guid', 'pubDate', 'source');
  42. var $_imagetags = array('title', 'url', 'link', 'width', 'height');
  43. var $_textinputtags = array('title', 'description', 'name', 'link');
  44. // -------------------------------------------------------------------
  45. // parse RSS file and returns associative array.
  46. // -------------------------------------------------------------------
  47. function Get($rss_url) {
  48. // If CACHE ENABLED
  49. if ($this->cache_dir != '') {
  50. $cache_file = $this->cache_dir . '/rsscache_' . md5($rss_url);
  51. $timedif = @(time() - filemtime($cache_file));
  52. if ($timedif < $this->cache_time) {
  53. // cached file is fresh enough, return cached array
  54. $result = unserialize(join('', file($cache_file)));
  55. // set 'cached' to 1 only if cached file is correct
  56. if ($result) $result['cached'] = 1;
  57. } else {
  58. // cached file is too old, create new
  59. $result = $this->Parse($rss_url);
  60. if ($result !== false) {
  61. $serialized = serialize($result);
  62. if ($f = @fopen($cache_file, 'w')) {
  63. fwrite ($f, $serialized, strlen($serialized));
  64. fclose($f);
  65. }
  66. if ($result) $result['cached'] = 0;
  67. }
  68. }
  69. } else {
  70. // If CACHE DISABLED >> load and parse the file directly
  71. $result = $this->Parse($rss_url);
  72. if ($result) $result['cached'] = 0;
  73. }
  74. // return result
  75. return $result;
  76. }
  77. // -------------------------------------------------------------------
  78. // Modification of preg_match(); return trimmed field with index 1
  79. // from 'classic' preg_match() array output
  80. // -------------------------------------------------------------------
  81. function my_preg_match($pattern, $subject) {
  82. // start regular expression
  83. preg_match($pattern, $subject, $out);
  84. // if there is some result... process it and return it
  85. if (isset($out[1])) {
  86. // Process CDATA (if present)
  87. if ($this->CDATA == 'content') { // Get CDATA content (without CDATA tag)
  88. $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>''));
  89. } elseif ($this->CDATA == 'strip') { // Strip CDATA
  90. $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>''));
  91. }
  92. // If code page is set convert character encoding to required
  93. if ($this->cp != '')
  94. $out[1] = iconv($this->rsscp, $this->cp.'//TRANSLIT', $out[1]);
  95. // Return result
  96. return trim($out[1]);
  97. } else {
  98. // if there is NO result, return empty string
  99. return '';
  100. }
  101. }
  102. // -------------------------------------------------------------------
  103. // Replace HTML entities &something; by real characters
  104. // -------------------------------------------------------------------
  105. function unhtmlentities($string) {
  106. // Get HTML entities table
  107. $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
  108. // Flip keys<==>values
  109. $trans_tbl = array_flip($trans_tbl);
  110. // Add support for &apos; entity (missing in HTML_ENTITIES)
  111. $trans_tbl += array('&apos;' => "'");
  112. // Replace entities by values
  113. return strtr($string, $trans_tbl);
  114. }
  115. // -------------------------------------------------------------------
  116. // Parse() is private method used by Get() to load and parse RSS file.
  117. // Don't use Parse() in your scripts - use Get($rss_file) instead.
  118. // -------------------------------------------------------------------
  119. function Parse($rss_url) {
  120. // Load RSS file
  121. require_once("inc/classes/SimpleHTTP.php");
  122. $rss_content = SimpleHTTP::getData($rss_url);
  123. if (SimpleHTTP::getState() != SIMPLEHTTP_STATE_OK) {
  124. // last op was not ok
  125. // log
  126. global $cfg;
  127. $msgs = SimpleHTTP::getMessages();
  128. AuditAction($cfg["constants"]["error"], "lastRSS: could not download feed-data from url ".$rss_url." (".implode("; ", $msgs).")");
  129. // return false
  130. return false;
  131. }
  132. // result-array
  133. $result = array();
  134. // document encoding
  135. $result['encoding'] = $this->my_preg_match("'encoding=[\'\"](.*?)[\'\"]'si", $rss_content);
  136. // if document codepage is specified, use it
  137. if ($result['encoding'] != '') {
  138. $this->rsscp = $result['encoding']; // This is used in my_preg_match()
  139. } else {
  140. // otherwise use the default codepage
  141. $this->rsscp = $this->default_cp; // This is used in my_preg_match()
  142. }
  143. // CHANNEL info
  144. if (preg_match("'<channel.*?>(.*?)</channel>'si", $rss_content, $out_channel)) {
  145. foreach($this->_channeltags as $channeltag) {
  146. $temp = $this->my_preg_match("'<$channeltag.*?>(.*?)</$channeltag>'si", $out_channel[1]);
  147. if ($temp != '') $result[$channeltag] = $temp; // Set only if not empty
  148. }
  149. }
  150. // If date_format is specified and lastBuildDate is valid
  151. if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !== -1) {
  152. // convert lastBuildDate to specified date format
  153. $result['lastBuildDate'] = date($this->date_format, $timestamp);
  154. }
  155. // TEXTINPUT info
  156. preg_match("'<textinput(|[^>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo);
  157. // This a little strange regexp means:
  158. // Look for tag <textinput> with or without any attributes, but skip truncated version <textinput /> (it's not beginning tag)
  159. if (isset($out_textinfo[2])) {
  160. foreach($this->_textinputtags as $textinputtag) {
  161. $temp = $this->my_preg_match("'<$textinputtag.*?>(.*?)</$textinputtag>'si", $out_textinfo[2]);
  162. if ($temp != '') $result['textinput_'.$textinputtag] = $temp; // Set only if not empty
  163. }
  164. }
  165. // IMAGE info
  166. preg_match("'<image.*?>(.*?)</image>'si", $rss_content, $out_imageinfo);
  167. if (isset($out_imageinfo[1])) {
  168. foreach ($this->_imagetags as $imagetag) {
  169. $temp = $this->my_preg_match("'<$imagetag.*?>(.*?)</$imagetag>'si", $out_imageinfo[1]);
  170. if ($temp != '') $result['image_'.$imagetag] = $temp; // Set only if not empty
  171. }
  172. }
  173. // ITEMS
  174. preg_match_all("'<item(| .*?)>(.*?)</item>'si", $rss_content, $items);
  175. $rss_items = $items[2];
  176. $i = 0;
  177. $result['items'] = array(); // create array even if there are no items
  178. foreach ($rss_items as $rss_item) {
  179. // If number of items is lower then limit: parse one item
  180. if ($i < $this->items_limit || $this->items_limit == 0) {
  181. foreach($this->_itemtags as $itemtag) {
  182. $temp = $this->my_preg_match("'<$itemtag.*?>(.*?)</$itemtag>'si", $rss_item);
  183. if ($temp != '') $result['items'][$i][$itemtag] = $temp; // Set only if not empty
  184. }
  185. // Strip HTML tags and other bullshit from DESCRIPTION
  186. if ($this->stripHTML && $result['items'][$i]['description'])
  187. $result['items'][$i]['description'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['description'])));
  188. // Strip HTML tags and other bullshit from TITLE
  189. if ($this->stripHTML && $result['items'][$i]['title'])
  190. $result['items'][$i]['title'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['title'])));
  191. // If date_format is specified and pubDate is valid
  192. if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !==-1) {
  193. // convert pubDate to specified date format
  194. $result['items'][$i]['pubDate'] = date($this->date_format, $timestamp);
  195. }
  196. // Item counter
  197. $i++;
  198. }
  199. }
  200. $result['items_count'] = $i;
  201. return $result;
  202. }
  203. }
  204. ?>