Feed.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. <?php
  2. class FreshRSS_Feed extends Minz_Model {
  3. private $id = 0;
  4. private $url;
  5. private $category = 1;
  6. private $nbEntries = -1;
  7. private $nbNotRead = -1;
  8. private $entries = null;
  9. private $name = '';
  10. private $website = '';
  11. private $description = '';
  12. private $lastUpdate = 0;
  13. private $priority = 10;
  14. private $pathEntries = '';
  15. private $httpAuth = '';
  16. private $error = false;
  17. private $keep_history = -2;
  18. private $ttl = -2;
  19. private $hash = null;
  20. private $lockPath = '';
  21. private $hubUrl = '';
  22. private $selfUrl = '';
  23. public function __construct($url, $validate=true) {
  24. if ($validate) {
  25. $this->_url($url);
  26. } else {
  27. $this->url = $url;
  28. }
  29. }
  30. public static function example() {
  31. $f = new FreshRSS_Feed('http://example.net/', false);
  32. $f->faviconPrepare();
  33. return $f;
  34. }
  35. public function id() {
  36. return $this->id;
  37. }
  38. public function hash() {
  39. if ($this->hash === null) {
  40. $salt = FreshRSS_Context::$system_conf->salt;
  41. $this->hash = hash('crc32b', $salt . $this->url);
  42. }
  43. return $this->hash;
  44. }
  45. public function url() {
  46. return $this->url;
  47. }
  48. public function selfUrl() {
  49. return $this->selfUrl;
  50. }
  51. public function hubUrl() {
  52. return $this->hubUrl;
  53. }
  54. public function category() {
  55. return $this->category;
  56. }
  57. public function entries() {
  58. return $this->entries === null ? array() : $this->entries;
  59. }
  60. public function name() {
  61. return $this->name;
  62. }
  63. public function website() {
  64. return $this->website;
  65. }
  66. public function description() {
  67. return $this->description;
  68. }
  69. public function lastUpdate() {
  70. return $this->lastUpdate;
  71. }
  72. public function priority() {
  73. return $this->priority;
  74. }
  75. public function pathEntries() {
  76. return $this->pathEntries;
  77. }
  78. public function httpAuth($raw = true) {
  79. if ($raw) {
  80. return $this->httpAuth;
  81. } else {
  82. $pos_colon = strpos($this->httpAuth, ':');
  83. $user = substr($this->httpAuth, 0, $pos_colon);
  84. $pass = substr($this->httpAuth, $pos_colon + 1);
  85. return array(
  86. 'username' => $user,
  87. 'password' => $pass
  88. );
  89. }
  90. }
  91. public function inError() {
  92. return $this->error;
  93. }
  94. public function keepHistory() {
  95. return $this->keep_history;
  96. }
  97. public function ttl() {
  98. return $this->ttl;
  99. }
  100. public function nbEntries() {
  101. if ($this->nbEntries < 0) {
  102. $feedDAO = FreshRSS_Factory::createFeedDao();
  103. $this->nbEntries = $feedDAO->countEntries($this->id());
  104. }
  105. return $this->nbEntries;
  106. }
  107. public function nbNotRead() {
  108. if ($this->nbNotRead < 0) {
  109. $feedDAO = FreshRSS_Factory::createFeedDao();
  110. $this->nbNotRead = $feedDAO->countNotRead($this->id());
  111. }
  112. return $this->nbNotRead;
  113. }
  114. public function faviconPrepare() {
  115. $file = DATA_PATH . '/favicons/' . $this->hash() . '.txt';
  116. if (!file_exists($file)) {
  117. $t = $this->website;
  118. if ($t == '') {
  119. $t = $this->url;
  120. }
  121. file_put_contents($file, $t);
  122. }
  123. }
  124. public static function faviconDelete($hash) {
  125. $path = DATA_PATH . '/favicons/' . $hash;
  126. @unlink($path . '.ico');
  127. @unlink($path . '.txt');
  128. }
  129. public function favicon() {
  130. return Minz_Url::display('/f.php?' . $this->hash());
  131. }
  132. public function _id($value) {
  133. $this->id = $value;
  134. }
  135. public function _url($value, $validate=true) {
  136. $this->hash = null;
  137. if ($validate) {
  138. $value = checkUrl($value);
  139. }
  140. if (empty($value)) {
  141. throw new FreshRSS_BadUrl_Exception($value);
  142. }
  143. $this->url = $value;
  144. }
  145. public function _category($value) {
  146. $value = intval($value);
  147. $this->category = $value >= 0 ? $value : 0;
  148. }
  149. public function _name($value) {
  150. $this->name = $value === null ? '' : $value;
  151. }
  152. public function _website($value, $validate=true) {
  153. if ($validate) {
  154. $value = checkUrl($value);
  155. }
  156. if (empty($value)) {
  157. $value = '';
  158. }
  159. $this->website = $value;
  160. }
  161. public function _description($value) {
  162. $this->description = $value === null ? '' : $value;
  163. }
  164. public function _lastUpdate($value) {
  165. $this->lastUpdate = $value;
  166. }
  167. public function _priority($value) {
  168. $value = intval($value);
  169. $this->priority = $value >= 0 ? $value : 10;
  170. }
  171. public function _pathEntries($value) {
  172. $this->pathEntries = $value;
  173. }
  174. public function _httpAuth($value) {
  175. $this->httpAuth = $value;
  176. }
  177. public function _error($value) {
  178. $this->error = (bool)$value;
  179. }
  180. public function _keepHistory($value) {
  181. $value = intval($value);
  182. $value = min($value, 1000000);
  183. $value = max($value, -2);
  184. $this->keep_history = $value;
  185. }
  186. public function _ttl($value) {
  187. $value = intval($value);
  188. $value = min($value, 100000000);
  189. $value = max($value, -2);
  190. $this->ttl = $value;
  191. }
  192. public function _nbNotRead($value) {
  193. $this->nbNotRead = intval($value);
  194. }
  195. public function _nbEntries($value) {
  196. $this->nbEntries = intval($value);
  197. }
  198. public function load($loadDetails = false) {
  199. if ($this->url !== null) {
  200. if (CACHE_PATH === false) {
  201. throw new Minz_FileNotExistException(
  202. 'CACHE_PATH',
  203. Minz_Exception::ERROR
  204. );
  205. } else {
  206. $url = htmlspecialchars_decode($this->url, ENT_QUOTES);
  207. if ($this->httpAuth != '') {
  208. $url = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $url);
  209. }
  210. $feed = customSimplePie();
  211. if (substr($url, -11) === '#force_feed') {
  212. $feed->force_feed(true);
  213. $url = substr($url, 0, -11);
  214. }
  215. $feed->set_feed_url($url);
  216. if (!$loadDetails) { //Only activates auto-discovery when adding a new feed
  217. $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
  218. }
  219. $mtime = $feed->init();
  220. if ((!$mtime) || $feed->error()) {
  221. $errorMessage = $feed->error();
  222. throw new FreshRSS_Feed_Exception(($errorMessage == '' ? 'Feed error' : $errorMessage) . ' [' . $url . ']');
  223. }
  224. $links = $feed->get_links('self');
  225. $this->selfUrl = isset($links[0]) ? $links[0] : null;
  226. $links = $feed->get_links('hub');
  227. $this->hubUrl = isset($links[0]) ? $links[0] : null;
  228. if ($loadDetails) {
  229. // si on a utilisé l'auto-discover, notre url va avoir changé
  230. $subscribe_url = $feed->subscribe_url(false);
  231. $title = strtr(html_only_entity_decode($feed->get_title()), array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;')); //HTML to HTML-PRE //ENT_COMPAT except &
  232. $this->_name($title == '' ? $url : $title);
  233. $this->_website(html_only_entity_decode($feed->get_link()));
  234. $this->_description(html_only_entity_decode($feed->get_description()));
  235. } else {
  236. //The case of HTTP 301 Moved Permanently
  237. $subscribe_url = $feed->subscribe_url(true);
  238. }
  239. $clean_url = SimplePie_Misc::url_remove_credentials($subscribe_url);
  240. if ($subscribe_url !== null && $subscribe_url !== $url) {
  241. $this->_url($clean_url);
  242. }
  243. if (($mtime === true) || ($mtime > $this->lastUpdate)) {
  244. //Minz_Log::debug('FreshRSS no cache ' . $mtime . ' > ' . $this->lastUpdate . ' for ' . $clean_url);
  245. $this->loadEntries($feed); // et on charge les articles du flux
  246. } else {
  247. //Minz_Log::debug('FreshRSS use cache for ' . $clean_url);
  248. $this->entries = array();
  249. }
  250. $feed->__destruct(); //http://simplepie.org/wiki/faq/i_m_getting_memory_leaks
  251. unset($feed);
  252. }
  253. }
  254. }
  255. public function loadEntries($feed) {
  256. $entries = array();
  257. foreach ($feed->get_items() as $item) {
  258. $title = html_only_entity_decode(strip_tags($item->get_title()));
  259. $author = $item->get_author();
  260. $link = $item->get_permalink();
  261. $date = @strtotime($item->get_date());
  262. // gestion des tags (catégorie == tag)
  263. $tags_tmp = $item->get_categories();
  264. $tags = array();
  265. if ($tags_tmp !== null) {
  266. foreach ($tags_tmp as $tag) {
  267. $tags[] = html_only_entity_decode($tag->get_label());
  268. }
  269. }
  270. $content = html_only_entity_decode($item->get_content());
  271. $elinks = array();
  272. foreach ($item->get_enclosures() as $enclosure) {
  273. $elink = $enclosure->get_link();
  274. if (empty($elinks[$elink])) {
  275. $elinks[$elink] = '1';
  276. $mime = strtolower($enclosure->get_type());
  277. if (strpos($mime, 'image/') === 0) {
  278. $content .= '<br /><img lazyload="" postpone="" src="' . $elink . '" alt="" />';
  279. } elseif (strpos($mime, 'audio/') === 0) {
  280. $content .= '<br /><audio lazyload="" postpone="" preload="none" src="' . $elink . '" controls="controls" />';
  281. } elseif (strpos($mime, 'video/') === 0) {
  282. $content .= '<br /><video lazyload="" postpone="" preload="none" src="' . $elink . '" controls="controls" />';
  283. } else {
  284. unset($elinks[$elink]);
  285. }
  286. }
  287. }
  288. $entry = new FreshRSS_Entry(
  289. $this->id(),
  290. $item->get_id(),
  291. $title === null ? '' : $title,
  292. $author === null ? '' : html_only_entity_decode($author->name),
  293. $content === null ? '' : $content,
  294. $link === null ? '' : $link,
  295. $date ? $date : time()
  296. );
  297. $entry->_tags($tags);
  298. // permet de récupérer le contenu des flux tronqués
  299. $entry->loadCompleteContent($this->pathEntries());
  300. $entries[] = $entry;
  301. unset($item);
  302. }
  303. $this->entries = $entries;
  304. }
  305. function lock() {
  306. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  307. if (file_exists($this->lockPath) && ((time() - @filemtime($this->lockPath)) > 3600)) {
  308. @unlink($this->lockPath);
  309. }
  310. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  311. return false;
  312. }
  313. //register_shutdown_function('unlink', $this->lockPath);
  314. @fclose($handle);
  315. return true;
  316. }
  317. function unlock() {
  318. @unlink($this->lockPath);
  319. }
  320. //<PubSubHubbub>
  321. function pubSubHubbubPrepare() {
  322. $key = '';
  323. if (FreshRSS_Context::$system_conf->base_url && $this->hubUrl && $this->selfUrl) {
  324. $path = PSHB_PATH . '/feeds/' . base64url_encode($this->selfUrl);
  325. if ($hubFile = @file_get_contents($path . '/!hub.json')) {
  326. $hubJson = json_decode($hubFile, true);
  327. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  328. Minz_Log::warning('Invalid JSON for PubSubHubbub: ' . $this->url);
  329. return false;
  330. }
  331. if (empty($hubJson['lease_end']) || $hubJson['lease_end'] <= time()) {
  332. Minz_Log::warning('PubSubHubbub lease expired: ' . $this->url);
  333. $key = $hubJson['key']; //To renew our lease
  334. }
  335. } else {
  336. @mkdir($path, 0777, true);
  337. $key = sha1(FreshRSS_Context::$system_conf->salt . uniqid(mt_rand(), true));
  338. $hubJson = array(
  339. 'hub' => $this->hubUrl,
  340. 'key' => $key,
  341. );
  342. file_put_contents($path . '/!hub.json', json_encode($hubJson));
  343. @mkdir(PSHB_PATH . '/keys/');
  344. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', base64url_encode($this->selfUrl));
  345. Minz_Log::notice('PubSubHubbub prepared for ' . $this->url);
  346. file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" .
  347. 'PubSubHubbub prepared for ' . $this->url . "\n", FILE_APPEND);
  348. }
  349. $currentUser = Minz_Session::param('currentUser');
  350. if (ctype_alnum($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  351. touch($path . '/' . $currentUser . '.txt');
  352. }
  353. }
  354. return $key;
  355. }
  356. //Parameter true to subscribe, false to unsubscribe.
  357. function pubSubHubbubSubscribe($state) {
  358. if (FreshRSS_Context::$system_conf->base_url && $this->hubUrl && $this->selfUrl) {
  359. $hubFile = @file_get_contents(PSHB_PATH . '/feeds/' . base64url_encode($this->selfUrl) . '/!hub.json');
  360. if ($hubFile === false) {
  361. Minz_Log::warning('JSON not found for PubSubHubbub: ' . $this->url);
  362. return false;
  363. }
  364. $hubJson = json_decode($hubFile, true);
  365. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  366. Minz_Log::warning('Invalid JSON for PubSubHubbub: ' . $this->url);
  367. return false;
  368. }
  369. $callbackUrl = checkUrl(FreshRSS_Context::$system_conf->base_url . 'api/pshb.php?k=' . $hubJson['key']);
  370. if ($callbackUrl == '') {
  371. Minz_Log::warning('Invalid callback for PubSubHubbub: ' . $this->url);
  372. return false;
  373. }
  374. $ch = curl_init();
  375. curl_setopt_array($ch, array(
  376. CURLOPT_URL => $this->hubUrl,
  377. CURLOPT_FOLLOWLOCATION => true,
  378. CURLOPT_RETURNTRANSFER => true,
  379. CURLOPT_USERAGENT => _t('gen.freshrss') . '/' . FRESHRSS_VERSION . ' (' . PHP_OS . '; ' . FRESHRSS_WEBSITE . ')',
  380. CURLOPT_POSTFIELDS => 'hub.verify=sync'
  381. . '&hub.mode=' . ($state ? 'subscribe' : 'unsubscribe')
  382. . '&hub.topic=' . urlencode($this->selfUrl)
  383. . '&hub.callback=' . urlencode($callbackUrl)
  384. )
  385. );
  386. $response = curl_exec($ch);
  387. $info = curl_getinfo($ch);
  388. file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" .
  389. 'PubSubHubbub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $this->selfUrl .
  390. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response . "\n", FILE_APPEND);
  391. return substr($info['http_code'], 0, 1) == '2';
  392. }
  393. return false;
  394. }
  395. //</PubSubHubbub>
  396. }