Feed.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. <?php
  2. class FreshRSS_Feed extends Minz_Model {
  3. const PRIORITY_MAIN_STREAM = 10;
  4. const PRIORITY_NORMAL = 0;
  5. const PRIORITY_ARCHIVED = -10;
  6. const TTL_DEFAULT = 0;
  7. const ARCHIVING_RETENTION_COUNT_LIMIT = 10000;
  8. const ARCHIVING_RETENTION_PERIOD = 'P3M';
  9. private $id = 0;
  10. private $url;
  11. private $category = 1;
  12. private $nbEntries = -1;
  13. private $nbNotRead = -1;
  14. private $name = '';
  15. private $website = '';
  16. private $description = '';
  17. private $lastUpdate = 0;
  18. private $priority = self::PRIORITY_MAIN_STREAM;
  19. private $pathEntries = '';
  20. private $httpAuth = '';
  21. private $error = false;
  22. private $ttl = self::TTL_DEFAULT;
  23. private $attributes = [];
  24. private $mute = false;
  25. private $hash = null;
  26. private $lockPath = '';
  27. private $hubUrl = '';
  28. private $selfUrl = '';
  29. private $filterActions = null;
  30. public function __construct($url, $validate = true) {
  31. if ($validate) {
  32. $this->_url($url);
  33. } else {
  34. $this->url = $url;
  35. }
  36. }
  37. public static function example() {
  38. $f = new FreshRSS_Feed('http://example.net/', false);
  39. $f->faviconPrepare();
  40. return $f;
  41. }
  42. public function id() {
  43. return $this->id;
  44. }
  45. public function hash() {
  46. if ($this->hash === null) {
  47. $salt = FreshRSS_Context::$system_conf->salt;
  48. $this->hash = hash('crc32b', $salt . $this->url);
  49. }
  50. return $this->hash;
  51. }
  52. public function url($includeCredentials = true) {
  53. return $includeCredentials ? $this->url : SimplePie_Misc::url_remove_credentials($this->url);
  54. }
  55. public function selfUrl() {
  56. return $this->selfUrl;
  57. }
  58. public function hubUrl() {
  59. return $this->hubUrl;
  60. }
  61. public function category() {
  62. return $this->category;
  63. }
  64. public function entries() {
  65. Minz_Log::warning(__method__ . ' is deprecated since FreshRSS 1.16.1!');
  66. $simplePie = $this->load(false, true);
  67. return $simplePie == null ? [] : iterator_to_array($this->loadEntries($simplePie));
  68. }
  69. public function name() {
  70. return $this->name;
  71. }
  72. public function website() {
  73. return $this->website;
  74. }
  75. public function description() {
  76. return $this->description;
  77. }
  78. public function lastUpdate() {
  79. return $this->lastUpdate;
  80. }
  81. public function priority() {
  82. return $this->priority;
  83. }
  84. public function pathEntries() {
  85. return $this->pathEntries;
  86. }
  87. public function httpAuth($raw = true) {
  88. if ($raw) {
  89. return $this->httpAuth;
  90. } else {
  91. $pos_colon = strpos($this->httpAuth, ':');
  92. $user = substr($this->httpAuth, 0, $pos_colon);
  93. $pass = substr($this->httpAuth, $pos_colon + 1);
  94. return array(
  95. 'username' => $user,
  96. 'password' => $pass
  97. );
  98. }
  99. }
  100. public function inError() {
  101. return $this->error;
  102. }
  103. public function ttl() {
  104. return $this->ttl;
  105. }
  106. public function attributes($key = '') {
  107. if ($key == '') {
  108. return $this->attributes;
  109. } else {
  110. return isset($this->attributes[$key]) ? $this->attributes[$key] : null;
  111. }
  112. }
  113. public function mute() {
  114. return $this->mute;
  115. }
  116. // public function ttlExpire() {
  117. // $ttl = $this->ttl;
  118. // if ($ttl == self::TTL_DEFAULT) { //Default
  119. // $ttl = FreshRSS_Context::$user_conf->ttl_default;
  120. // }
  121. // if ($ttl == -1) { //Never
  122. // $ttl = 64000000; //~2 years. Good enough for PubSubHubbub logic
  123. // }
  124. // return $this->lastUpdate + $ttl;
  125. // }
  126. public function nbEntries() {
  127. if ($this->nbEntries < 0) {
  128. $feedDAO = FreshRSS_Factory::createFeedDao();
  129. $this->nbEntries = $feedDAO->countEntries($this->id());
  130. }
  131. return $this->nbEntries;
  132. }
  133. public function nbNotRead() {
  134. if ($this->nbNotRead < 0) {
  135. $feedDAO = FreshRSS_Factory::createFeedDao();
  136. $this->nbNotRead = $feedDAO->countNotRead($this->id());
  137. }
  138. return $this->nbNotRead;
  139. }
  140. public function faviconPrepare() {
  141. require_once(LIB_PATH . '/favicons.php');
  142. $url = $this->website;
  143. if ($url == '') {
  144. $url = $this->url;
  145. }
  146. $txt = FAVICONS_DIR . $this->hash() . '.txt';
  147. if (!file_exists($txt)) {
  148. file_put_contents($txt, $url);
  149. }
  150. if (FreshRSS_Context::$isCli) {
  151. $ico = FAVICONS_DIR . $this->hash() . '.ico';
  152. $ico_mtime = @filemtime($ico);
  153. $txt_mtime = @filemtime($txt);
  154. if ($txt_mtime != false &&
  155. ($ico_mtime == false || $ico_mtime < $txt_mtime || ($ico_mtime < time() - (14 * 86400)))) {
  156. // no ico file or we should download a new one.
  157. $url = file_get_contents($txt);
  158. download_favicon($url, $ico) || touch($ico);
  159. }
  160. }
  161. }
  162. public static function faviconDelete($hash) {
  163. $path = DATA_PATH . '/favicons/' . $hash;
  164. @unlink($path . '.ico');
  165. @unlink($path . '.txt');
  166. }
  167. public function favicon() {
  168. return Minz_Url::display('/f.php?' . $this->hash());
  169. }
  170. public function _id($value) {
  171. $this->id = intval($value);
  172. }
  173. public function _url($value, $validate = true) {
  174. $this->hash = null;
  175. if ($validate) {
  176. $value = checkUrl($value);
  177. }
  178. if ($value == '') {
  179. throw new FreshRSS_BadUrl_Exception($value);
  180. }
  181. $this->url = $value;
  182. }
  183. public function _category($value) {
  184. $value = intval($value);
  185. $this->category = $value >= 0 ? $value : 0;
  186. }
  187. public function _name($value) {
  188. $this->name = $value === null ? '' : $value;
  189. }
  190. public function _website($value, $validate = true) {
  191. if ($validate) {
  192. $value = checkUrl($value);
  193. }
  194. if ($value == '') {
  195. $value = '';
  196. }
  197. $this->website = $value;
  198. }
  199. public function _description($value) {
  200. $this->description = $value === null ? '' : $value;
  201. }
  202. public function _lastUpdate($value) {
  203. $this->lastUpdate = intval($value);
  204. }
  205. public function _priority($value) {
  206. $this->priority = intval($value);
  207. }
  208. public function _pathEntries($value) {
  209. $this->pathEntries = $value;
  210. }
  211. public function _httpAuth($value) {
  212. $this->httpAuth = $value;
  213. }
  214. public function _error($value) {
  215. $this->error = (bool)$value;
  216. }
  217. public function _ttl($value) {
  218. $value = intval($value);
  219. $value = min($value, 100000000);
  220. $this->ttl = abs($value);
  221. $this->mute = $value < self::TTL_DEFAULT;
  222. }
  223. public function _attributes($key, $value) {
  224. if ($key == '') {
  225. if (is_string($value)) {
  226. $value = json_decode($value, true);
  227. }
  228. if (is_array($value)) {
  229. $this->attributes = $value;
  230. }
  231. } elseif ($value === null) {
  232. unset($this->attributes[$key]);
  233. } else {
  234. $this->attributes[$key] = $value;
  235. }
  236. }
  237. public function _nbNotRead($value) {
  238. $this->nbNotRead = intval($value);
  239. }
  240. public function _nbEntries($value) {
  241. $this->nbEntries = intval($value);
  242. }
  243. public function load($loadDetails = false, $noCache = false) {
  244. if ($this->url !== null) {
  245. if (CACHE_PATH === false) {
  246. throw new Minz_FileNotExistException(
  247. 'CACHE_PATH',
  248. Minz_Exception::ERROR
  249. );
  250. } else {
  251. $url = htmlspecialchars_decode($this->url, ENT_QUOTES);
  252. if ($this->httpAuth != '') {
  253. $url = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $url);
  254. }
  255. $simplePie = customSimplePie($this->attributes());
  256. if (substr($url, -11) === '#force_feed') {
  257. $simplePie->force_feed(true);
  258. $url = substr($url, 0, -11);
  259. }
  260. $simplePie->set_feed_url($url);
  261. if (!$loadDetails) { //Only activates auto-discovery when adding a new feed
  262. $simplePie->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
  263. }
  264. if ($this->attributes('clear_cache')) {
  265. // Do not use `$simplePie->enable_cache(false);` as it would prevent caching in multiuser context
  266. $this->clearCache();
  267. }
  268. Minz_ExtensionManager::callHook('simplepie_before_init', $simplePie, $this);
  269. $mtime = $simplePie->init();
  270. if ((!$mtime) || $simplePie->error()) {
  271. $errorMessage = $simplePie->error();
  272. throw new FreshRSS_Feed_Exception(
  273. ($errorMessage == '' ? 'Unknown error for feed' : $errorMessage) . ' [' . $this->url . ']'
  274. );
  275. }
  276. $links = $simplePie->get_links('self');
  277. $this->selfUrl = isset($links[0]) ? $links[0] : null;
  278. $links = $simplePie->get_links('hub');
  279. $this->hubUrl = isset($links[0]) ? $links[0] : null;
  280. if ($loadDetails) {
  281. // si on a utilisé l'auto-discover, notre url va avoir changé
  282. $subscribe_url = $simplePie->subscribe_url(false);
  283. //HTML to HTML-PRE //ENT_COMPAT except '&'
  284. $title = strtr(html_only_entity_decode($simplePie->get_title()), array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
  285. $this->_name($title == '' ? $this->url : $title);
  286. $this->_website(html_only_entity_decode($simplePie->get_link()));
  287. $this->_description(html_only_entity_decode($simplePie->get_description()));
  288. } else {
  289. //The case of HTTP 301 Moved Permanently
  290. $subscribe_url = $simplePie->subscribe_url(true);
  291. }
  292. $clean_url = SimplePie_Misc::url_remove_credentials($subscribe_url);
  293. if ($subscribe_url !== null && $subscribe_url !== $url) {
  294. $this->_url($clean_url);
  295. }
  296. if (($mtime === true) || ($mtime > $this->lastUpdate) || $noCache) {
  297. //Minz_Log::debug('FreshRSS no cache ' . $mtime . ' > ' . $this->lastUpdate . ' for ' . $clean_url);
  298. return $simplePie;
  299. } else {
  300. //Minz_Log::debug('FreshRSS use cache for ' . $clean_url);
  301. return null;
  302. }
  303. }
  304. }
  305. }
  306. public function loadGuids($simplePie) {
  307. $hasUniqueGuids = true;
  308. $testGuids = [];
  309. $guids = [];
  310. $hasBadGuids = $this->attributes('hasBadGuids');
  311. for ($i = $simplePie->get_item_quantity() - 1; $i >= 0; $i--) {
  312. $item = $simplePie->get_item($i);
  313. if ($item == null) {
  314. continue;
  315. }
  316. $guid = safe_ascii($item->get_id(false, false));
  317. $hasUniqueGuids &= empty($testGuids['_' . $guid]);
  318. $testGuids['_' . $guid] = true;
  319. $guids[] = $guid;
  320. }
  321. if ($hasBadGuids != !$hasUniqueGuids) {
  322. $hasBadGuids = !$hasUniqueGuids;
  323. if ($hasBadGuids) {
  324. Minz_Log::warning('Feed has invalid GUIDs: ' . $this->url);
  325. } else {
  326. Minz_Log::warning('Feed has valid GUIDs again: ' . $this->url);
  327. }
  328. $feedDAO = FreshRSS_Factory::createFeedDao();
  329. $feedDAO->updateFeedAttribute($this, 'hasBadGuids', $hasBadGuids);
  330. }
  331. return $guids;
  332. }
  333. public function loadEntries($simplePie) {
  334. $hasBadGuids = $this->attributes('hasBadGuids');
  335. // We want chronological order and SimplePie uses reverse order.
  336. for ($i = $simplePie->get_item_quantity() - 1; $i >= 0; $i--) {
  337. $item = $simplePie->get_item($i);
  338. if ($item == null) {
  339. continue;
  340. }
  341. $title = html_only_entity_decode(strip_tags($item->get_title()));
  342. $authors = $item->get_authors();
  343. $link = $item->get_permalink();
  344. $date = @strtotime($item->get_date());
  345. //Tag processing (tag == category)
  346. $categories = $item->get_categories();
  347. $tags = array();
  348. if (is_array($categories)) {
  349. foreach ($categories as $category) {
  350. $text = html_only_entity_decode($category->get_label());
  351. //Some feeds use a single category with comma-separated tags
  352. $labels = explode(',', $text);
  353. if (is_array($labels)) {
  354. foreach ($labels as $label) {
  355. $tags[] = trim($label);
  356. }
  357. }
  358. }
  359. $tags = array_unique($tags);
  360. }
  361. $content = html_only_entity_decode($item->get_content());
  362. if ($item->get_enclosures() != null) {
  363. $elinks = array();
  364. foreach ($item->get_enclosures() as $enclosure) {
  365. $elink = $enclosure->get_link();
  366. if ($elink != '' && empty($elinks[$elink])) {
  367. $content .= '<div class="enclosure">';
  368. if ($enclosure->get_title() != '') {
  369. $content .= '<p class="enclosure-title">' . $enclosure->get_title() . '</p>';
  370. }
  371. $enclosureContent = '';
  372. $elinks[$elink] = true;
  373. $mime = strtolower($enclosure->get_type());
  374. $medium = strtolower($enclosure->get_medium());
  375. $height = $enclosure->get_height();
  376. $width = $enclosure->get_width();
  377. $length = $enclosure->get_length();
  378. if (strpos($mime, 'image') === 0 || ($mime == '' && $length == null && ($width != 0 || $height != 0))) {
  379. $enclosureContent .= '<p class="enclosure-content"><img src="' . $elink . '" alt="" /></p>';
  380. } elseif (strpos($mime, 'audio') === 0) {
  381. $enclosureContent .= '<p class="enclosure-content"><audio preload="none" src="' . $elink
  382. . ($length == null ? '' : '" data-length="' . intval($length))
  383. . '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8')
  384. . '" controls="controls"></audio> <a download="" href="' . $elink . '">💾</a></p>';
  385. } elseif (strpos($mime, 'video') === 0) {
  386. $enclosureContent .= '<p class="enclosure-content"><video preload="none" src="' . $elink
  387. . ($length == null ? '' : '" data-length="' . intval($length))
  388. . '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8')
  389. . '" controls="controls"></video> <a download="" href="' . $elink . '">💾</a></p>';
  390. } else { //e.g. application, text, unknown
  391. $enclosureContent .= '<p class="enclosure-content"><a download="" href="' . $elink . '">💾</a></p>';
  392. }
  393. $thumbnailContent = '';
  394. if ($enclosure->get_thumbnails() != null) {
  395. foreach ($enclosure->get_thumbnails() as $thumbnail) {
  396. if (empty($elinks[$thumbnail])) {
  397. $elinks[$thumbnail] = true;
  398. $thumbnailContent .= '<p><img class="enclosure-thumbnail" src="' . $thumbnail . '" alt="" /></p>';
  399. }
  400. }
  401. }
  402. $content .= $thumbnailContent;
  403. $content .= $enclosureContent;
  404. if ($enclosure->get_description() != '') {
  405. $content .= '<p class="enclosure-description">' . $enclosure->get_description() . '</p>';
  406. }
  407. $content .= "</div>\n";
  408. }
  409. }
  410. }
  411. $guid = safe_ascii($item->get_id(false, false));
  412. unset($item);
  413. $author_names = '';
  414. if (is_array($authors)) {
  415. foreach ($authors as $author) {
  416. $author_names .= escapeToUnicodeAlternative(strip_tags($author->name == '' ? $author->email : $author->name), true) . '; ';
  417. }
  418. }
  419. $author_names = substr($author_names, 0, -2);
  420. $entry = new FreshRSS_Entry(
  421. $this->id(),
  422. $hasBadGuids ? '' : $guid,
  423. $title === null ? '' : $title,
  424. $author_names,
  425. $content === null ? '' : $content,
  426. $link === null ? '' : $link,
  427. $date ? $date : time()
  428. );
  429. $entry->_tags($tags);
  430. $entry->_feed($this);
  431. $entry->hash(); //Must be computed before loading full content
  432. $entry->loadCompleteContent(); // Optionally load full content for truncated feeds
  433. yield $entry;
  434. }
  435. }
  436. public function cleanOldEntries() { //Remember to call updateCachedValue($id_feed) or updateCachedValues() just after
  437. $archiving = $this->attributes('archiving');
  438. if ($archiving == null) {
  439. $catDAO = FreshRSS_Factory::createCategoryDao();
  440. $category = $catDAO->searchById($this->category());
  441. $archiving = $category == null ? null : $category->attributes('archiving');
  442. if ($archiving == null) {
  443. $archiving = FreshRSS_Context::$user_conf->archiving;
  444. }
  445. }
  446. if (is_array($archiving)) {
  447. $entryDAO = FreshRSS_Factory::createEntryDao();
  448. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  449. if ($nb > 0) {
  450. $needFeedCacheRefresh = true;
  451. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  452. }
  453. return $nb;
  454. }
  455. return false;
  456. }
  457. protected function cacheFilename() {
  458. return CACHE_PATH . '/' . md5($this->url) . '.spc';
  459. }
  460. public function clearCache() {
  461. return @unlink($this->cacheFilename());
  462. }
  463. public function cacheModifiedTime() {
  464. return @filemtime($this->cacheFilename());
  465. }
  466. public function lock() {
  467. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  468. if (file_exists($this->lockPath) && ((time() - @filemtime($this->lockPath)) > 3600)) {
  469. @unlink($this->lockPath);
  470. }
  471. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  472. return false;
  473. }
  474. //register_shutdown_function('unlink', $this->lockPath);
  475. @fclose($handle);
  476. return true;
  477. }
  478. public function unlock() {
  479. @unlink($this->lockPath);
  480. }
  481. public function filterActions() {
  482. if ($this->filterActions == null) {
  483. $this->filterActions = array();
  484. $filters = $this->attributes('filters');
  485. if (is_array($filters)) {
  486. foreach ($filters as $filter) {
  487. $filterAction = FreshRSS_FilterAction::fromJSON($filter);
  488. if ($filterAction != null) {
  489. $this->filterActions[] = $filterAction;
  490. }
  491. }
  492. }
  493. }
  494. return $this->filterActions;
  495. }
  496. private function _filterActions($filterActions) {
  497. $this->filterActions = $filterActions;
  498. if (is_array($this->filterActions) && !empty($this->filterActions)) {
  499. $this->_attributes('filters', array_map(function ($af) {
  500. return $af == null ? null : $af->toJSON();
  501. }, $this->filterActions));
  502. } else {
  503. $this->_attributes('filters', null);
  504. }
  505. }
  506. public function filtersAction($action) {
  507. $action = trim($action);
  508. if ($action == '') {
  509. return array();
  510. }
  511. $filters = array();
  512. $filterActions = $this->filterActions();
  513. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  514. $filterAction = $filterActions[$i];
  515. if ($filterAction != null && $filterAction->booleanSearch() != null &&
  516. $filterAction->actions() != null && in_array($action, $filterAction->actions(), true)) {
  517. $filters[] = $filterAction->booleanSearch();
  518. }
  519. }
  520. return $filters;
  521. }
  522. public function _filtersAction($action, $filters) {
  523. $action = trim($action);
  524. if ($action == '' || !is_array($filters)) {
  525. return false;
  526. }
  527. $filters = array_unique(array_map('trim', $filters));
  528. $filterActions = $this->filterActions();
  529. //Check existing filters
  530. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  531. $filterAction = $filterActions[$i];
  532. if ($filterAction == null || !is_array($filterAction->actions()) ||
  533. $filterAction->booleanSearch() == null || trim($filterAction->booleanSearch()->getRawInput()) == '') {
  534. array_splice($filterAction, $i, 1);
  535. continue;
  536. }
  537. $actions = $filterAction->actions();
  538. //Remove existing rules with same action
  539. for ($j = count($actions) - 1; $j >= 0; $j--) {
  540. if ($actions[$j] === $action) {
  541. array_splice($actions, $j, 1);
  542. }
  543. }
  544. //Update existing filter with new action
  545. for ($k = count($filters) - 1; $k >= 0; $k --) {
  546. $filter = $filters[$k];
  547. if ($filter === $filterAction->booleanSearch()->getRawInput()) {
  548. $actions[] = $action;
  549. array_splice($filters, $k, 1);
  550. }
  551. }
  552. //Save result
  553. if (empty($actions)) {
  554. array_splice($filterActions, $i, 1);
  555. } else {
  556. $filterAction->_actions($actions);
  557. }
  558. }
  559. //Add new filters
  560. for ($k = count($filters) - 1; $k >= 0; $k --) {
  561. $filter = $filters[$k];
  562. if ($filter != '') {
  563. $filterAction = FreshRSS_FilterAction::fromJSON(array(
  564. 'search' => $filter,
  565. 'actions' => array($action),
  566. ));
  567. if ($filterAction != null) {
  568. $filterActions[] = $filterAction;
  569. }
  570. }
  571. }
  572. if (empty($filterActions)) {
  573. $filterActions = null;
  574. }
  575. $this->_filterActions($filterActions);
  576. }
  577. //<WebSub>
  578. public function pubSubHubbubEnabled() {
  579. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  580. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  581. if ($hubFile = @file_get_contents($hubFilename)) {
  582. $hubJson = json_decode($hubFile, true);
  583. if ($hubJson && empty($hubJson['error']) &&
  584. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  585. return true;
  586. }
  587. }
  588. return false;
  589. }
  590. public function pubSubHubbubError($error = true) {
  591. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  592. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  593. $hubFile = @file_get_contents($hubFilename);
  594. $hubJson = $hubFile ? json_decode($hubFile, true) : array();
  595. if (!isset($hubJson['error']) || $hubJson['error'] !== (bool)$error) {
  596. $hubJson['error'] = (bool)$error;
  597. file_put_contents($hubFilename, json_encode($hubJson));
  598. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  599. }
  600. return false;
  601. }
  602. public function pubSubHubbubPrepare() {
  603. $key = '';
  604. if (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) &&
  605. $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
  606. $path = PSHB_PATH . '/feeds/' . base64url_encode($this->selfUrl);
  607. $hubFilename = $path . '/!hub.json';
  608. if ($hubFile = @file_get_contents($hubFilename)) {
  609. $hubJson = json_decode($hubFile, true);
  610. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  611. $text = 'Invalid JSON for WebSub: ' . $this->url;
  612. Minz_Log::warning($text);
  613. Minz_Log::warning($text, PSHB_LOG);
  614. return false;
  615. }
  616. if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
  617. $text = 'WebSub lease ends at '
  618. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  619. . ' and needs renewal: ' . $this->url;
  620. Minz_Log::warning($text);
  621. Minz_Log::warning($text, PSHB_LOG);
  622. $key = $hubJson['key']; //To renew our lease
  623. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  624. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  625. $key = $hubJson['key']; //To renew our lease
  626. }
  627. } else {
  628. @mkdir($path, 0777, true);
  629. $key = sha1($path . FreshRSS_Context::$system_conf->salt);
  630. $hubJson = array(
  631. 'hub' => $this->hubUrl,
  632. 'key' => $key,
  633. );
  634. file_put_contents($hubFilename, json_encode($hubJson));
  635. @mkdir(PSHB_PATH . '/keys/');
  636. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', base64url_encode($this->selfUrl));
  637. $text = 'WebSub prepared for ' . $this->url;
  638. Minz_Log::debug($text);
  639. Minz_Log::debug($text, PSHB_LOG);
  640. }
  641. $currentUser = Minz_Session::param('currentUser');
  642. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  643. touch($path . '/' . $currentUser . '.txt');
  644. }
  645. }
  646. return $key;
  647. }
  648. //Parameter true to subscribe, false to unsubscribe.
  649. public function pubSubHubbubSubscribe($state) {
  650. if ($state) {
  651. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  652. } else {
  653. $url = $this->url; //Always use current URL during unsubscribe
  654. }
  655. if ($url && (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) || !$state)) {
  656. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  657. $hubFile = @file_get_contents($hubFilename);
  658. if ($hubFile === false) {
  659. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  660. return false;
  661. }
  662. $hubJson = json_decode($hubFile, true);
  663. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key']) || empty($hubJson['hub'])) {
  664. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  665. return false;
  666. }
  667. $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  668. if ($callbackUrl == '') {
  669. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  670. return false;
  671. }
  672. if (!$state) { //unsubscribe
  673. $hubJson['lease_end'] = time() - 60;
  674. file_put_contents($hubFilename, json_encode($hubJson));
  675. }
  676. $ch = curl_init();
  677. curl_setopt_array($ch, [
  678. CURLOPT_URL => $hubJson['hub'],
  679. CURLOPT_RETURNTRANSFER => true,
  680. CURLOPT_POSTFIELDS => http_build_query(array(
  681. 'hub.verify' => 'sync',
  682. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  683. 'hub.topic' => $url,
  684. 'hub.callback' => $callbackUrl,
  685. )),
  686. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  687. CURLOPT_MAXREDIRS => 10,
  688. CURLOPT_FOLLOWLOCATION => true,
  689. CURLOPT_ENCODING => '', //Enable all encodings
  690. ]);
  691. $response = curl_exec($ch);
  692. $info = curl_getinfo($ch);
  693. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  694. ' via hub ' . $hubJson['hub'] .
  695. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response, PSHB_LOG);
  696. if (substr($info['http_code'], 0, 1) == '2') {
  697. return true;
  698. } else {
  699. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  700. $hubJson['error'] = true;
  701. file_put_contents($hubFilename, json_encode($hubJson));
  702. return false;
  703. }
  704. }
  705. return false;
  706. }
  707. //</WebSub>
  708. }