Feed.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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. $length = $enclosure->get_length();
  376. if ($medium === 'image' || strpos($mime, 'image/') === 0) {
  377. $enclosureContent .= '<p class="enclosure-content"><img src="' . $elink . '" alt="" /></p>';
  378. } elseif ($medium === 'audio' || strpos($mime, 'audio/') === 0) {
  379. $enclosureContent .= '<p class="enclosure-content"><audio preload="none" src="' . $elink
  380. . ($length == null ? '' : '" data-length="' . intval($length))
  381. . '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8')
  382. . '" controls="controls"></audio> <a download="" href="' . $elink . '">💾</a></p>';
  383. } elseif ($medium === 'video' || strpos($mime, 'video/') === 0) {
  384. $enclosureContent .= '<p class="enclosure-content"><video preload="none" src="' . $elink
  385. . ($length == null ? '' : '" data-length="' . intval($length))
  386. . '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8')
  387. . '" controls="controls"></video> <a download="" href="' . $elink . '">💾</a></p>';
  388. } elseif ($medium != '' || strpos($mime, 'application/') === 0 || strpos($mime, 'text/') === 0) {
  389. $enclosureContent .= '<p class="enclosure-content"><a download="" href="' . $elink . '">💾</a></p>';
  390. } else {
  391. unset($elinks[$elink]);
  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. if ($this->pathEntries != '') {
  432. // Optionally load full content for truncated feeds
  433. $entry->loadCompleteContent();
  434. }
  435. yield $entry;
  436. }
  437. }
  438. public function cleanOldEntries() { //Remember to call updateCachedValue($id_feed) or updateCachedValues() just after
  439. $archiving = $this->attributes('archiving');
  440. if ($archiving == null) {
  441. $catDAO = FreshRSS_Factory::createCategoryDao();
  442. $category = $catDAO->searchById($this->category());
  443. $archiving = $category == null ? null : $category->attributes('archiving');
  444. if ($archiving == null) {
  445. $archiving = FreshRSS_Context::$user_conf->archiving;
  446. }
  447. }
  448. if (is_array($archiving)) {
  449. $entryDAO = FreshRSS_Factory::createEntryDao();
  450. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  451. if ($nb > 0) {
  452. $needFeedCacheRefresh = true;
  453. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  454. }
  455. return $nb;
  456. }
  457. return false;
  458. }
  459. protected function cacheFilename() {
  460. return CACHE_PATH . '/' . md5($this->url) . '.spc';
  461. }
  462. public function clearCache() {
  463. return @unlink($this->cacheFilename());
  464. }
  465. public function cacheModifiedTime() {
  466. return @filemtime($this->cacheFilename());
  467. }
  468. public function lock() {
  469. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  470. if (file_exists($this->lockPath) && ((time() - @filemtime($this->lockPath)) > 3600)) {
  471. @unlink($this->lockPath);
  472. }
  473. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  474. return false;
  475. }
  476. //register_shutdown_function('unlink', $this->lockPath);
  477. @fclose($handle);
  478. return true;
  479. }
  480. public function unlock() {
  481. @unlink($this->lockPath);
  482. }
  483. public function filterActions() {
  484. if ($this->filterActions == null) {
  485. $this->filterActions = array();
  486. $filters = $this->attributes('filters');
  487. if (is_array($filters)) {
  488. foreach ($filters as $filter) {
  489. $filterAction = FreshRSS_FilterAction::fromJSON($filter);
  490. if ($filterAction != null) {
  491. $this->filterActions[] = $filterAction;
  492. }
  493. }
  494. }
  495. }
  496. return $this->filterActions;
  497. }
  498. private function _filterActions($filterActions) {
  499. $this->filterActions = $filterActions;
  500. if (is_array($this->filterActions) && !empty($this->filterActions)) {
  501. $this->_attributes('filters', array_map(function ($af) {
  502. return $af == null ? null : $af->toJSON();
  503. }, $this->filterActions));
  504. } else {
  505. $this->_attributes('filters', null);
  506. }
  507. }
  508. public function filtersAction($action) {
  509. $action = trim($action);
  510. if ($action == '') {
  511. return array();
  512. }
  513. $filters = array();
  514. $filterActions = $this->filterActions();
  515. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  516. $filterAction = $filterActions[$i];
  517. if ($filterAction != null && $filterAction->booleanSearch() != null &&
  518. $filterAction->actions() != null && in_array($action, $filterAction->actions(), true)) {
  519. $filters[] = $filterAction->booleanSearch();
  520. }
  521. }
  522. return $filters;
  523. }
  524. public function _filtersAction($action, $filters) {
  525. $action = trim($action);
  526. if ($action == '' || !is_array($filters)) {
  527. return false;
  528. }
  529. $filters = array_unique(array_map('trim', $filters));
  530. $filterActions = $this->filterActions();
  531. //Check existing filters
  532. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  533. $filterAction = $filterActions[$i];
  534. if ($filterAction == null || !is_array($filterAction->actions()) ||
  535. $filterAction->booleanSearch() == null || trim($filterAction->booleanSearch()->getRawInput()) == '') {
  536. array_splice($filterAction, $i, 1);
  537. continue;
  538. }
  539. $actions = $filterAction->actions();
  540. //Remove existing rules with same action
  541. for ($j = count($actions) - 1; $j >= 0; $j--) {
  542. if ($actions[$j] === $action) {
  543. array_splice($actions, $j, 1);
  544. }
  545. }
  546. //Update existing filter with new action
  547. for ($k = count($filters) - 1; $k >= 0; $k --) {
  548. $filter = $filters[$k];
  549. if ($filter === $filterAction->booleanSearch()->getRawInput()) {
  550. $actions[] = $action;
  551. array_splice($filters, $k, 1);
  552. }
  553. }
  554. //Save result
  555. if (empty($actions)) {
  556. array_splice($filterActions, $i, 1);
  557. } else {
  558. $filterAction->_actions($actions);
  559. }
  560. }
  561. //Add new filters
  562. for ($k = count($filters) - 1; $k >= 0; $k --) {
  563. $filter = $filters[$k];
  564. if ($filter != '') {
  565. $filterAction = FreshRSS_FilterAction::fromJSON(array(
  566. 'search' => $filter,
  567. 'actions' => array($action),
  568. ));
  569. if ($filterAction != null) {
  570. $filterActions[] = $filterAction;
  571. }
  572. }
  573. }
  574. if (empty($filterActions)) {
  575. $filterActions = null;
  576. }
  577. $this->_filterActions($filterActions);
  578. }
  579. //<WebSub>
  580. public function pubSubHubbubEnabled() {
  581. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  582. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  583. if ($hubFile = @file_get_contents($hubFilename)) {
  584. $hubJson = json_decode($hubFile, true);
  585. if ($hubJson && empty($hubJson['error']) &&
  586. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  587. return true;
  588. }
  589. }
  590. return false;
  591. }
  592. public function pubSubHubbubError($error = true) {
  593. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  594. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  595. $hubFile = @file_get_contents($hubFilename);
  596. $hubJson = $hubFile ? json_decode($hubFile, true) : array();
  597. if (!isset($hubJson['error']) || $hubJson['error'] !== (bool)$error) {
  598. $hubJson['error'] = (bool)$error;
  599. file_put_contents($hubFilename, json_encode($hubJson));
  600. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  601. }
  602. return false;
  603. }
  604. public function pubSubHubbubPrepare() {
  605. $key = '';
  606. if (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) &&
  607. $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
  608. $path = PSHB_PATH . '/feeds/' . base64url_encode($this->selfUrl);
  609. $hubFilename = $path . '/!hub.json';
  610. if ($hubFile = @file_get_contents($hubFilename)) {
  611. $hubJson = json_decode($hubFile, true);
  612. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  613. $text = 'Invalid JSON for WebSub: ' . $this->url;
  614. Minz_Log::warning($text);
  615. Minz_Log::warning($text, PSHB_LOG);
  616. return false;
  617. }
  618. if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
  619. $text = 'WebSub lease ends at '
  620. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  621. . ' and needs renewal: ' . $this->url;
  622. Minz_Log::warning($text);
  623. Minz_Log::warning($text, PSHB_LOG);
  624. $key = $hubJson['key']; //To renew our lease
  625. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  626. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  627. $key = $hubJson['key']; //To renew our lease
  628. }
  629. } else {
  630. @mkdir($path, 0777, true);
  631. $key = sha1($path . FreshRSS_Context::$system_conf->salt);
  632. $hubJson = array(
  633. 'hub' => $this->hubUrl,
  634. 'key' => $key,
  635. );
  636. file_put_contents($hubFilename, json_encode($hubJson));
  637. @mkdir(PSHB_PATH . '/keys/');
  638. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', base64url_encode($this->selfUrl));
  639. $text = 'WebSub prepared for ' . $this->url;
  640. Minz_Log::debug($text);
  641. Minz_Log::debug($text, PSHB_LOG);
  642. }
  643. $currentUser = Minz_Session::param('currentUser');
  644. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  645. touch($path . '/' . $currentUser . '.txt');
  646. }
  647. }
  648. return $key;
  649. }
  650. //Parameter true to subscribe, false to unsubscribe.
  651. public function pubSubHubbubSubscribe($state) {
  652. if ($state) {
  653. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  654. } else {
  655. $url = $this->url; //Always use current URL during unsubscribe
  656. }
  657. if ($url && (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) || !$state)) {
  658. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  659. $hubFile = @file_get_contents($hubFilename);
  660. if ($hubFile === false) {
  661. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  662. return false;
  663. }
  664. $hubJson = json_decode($hubFile, true);
  665. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key']) || empty($hubJson['hub'])) {
  666. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  667. return false;
  668. }
  669. $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  670. if ($callbackUrl == '') {
  671. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  672. return false;
  673. }
  674. if (!$state) { //unsubscribe
  675. $hubJson['lease_end'] = time() - 60;
  676. file_put_contents($hubFilename, json_encode($hubJson));
  677. }
  678. $ch = curl_init();
  679. curl_setopt_array($ch, [
  680. CURLOPT_URL => $hubJson['hub'],
  681. CURLOPT_RETURNTRANSFER => true,
  682. CURLOPT_POSTFIELDS => http_build_query(array(
  683. 'hub.verify' => 'sync',
  684. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  685. 'hub.topic' => $url,
  686. 'hub.callback' => $callbackUrl,
  687. )),
  688. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  689. CURLOPT_MAXREDIRS => 10,
  690. CURLOPT_FOLLOWLOCATION => true,
  691. CURLOPT_ENCODING => '', //Enable all encodings
  692. ]);
  693. $response = curl_exec($ch);
  694. $info = curl_getinfo($ch);
  695. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  696. ' via hub ' . $hubJson['hub'] .
  697. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response, PSHB_LOG);
  698. if (substr($info['http_code'], 0, 1) == '2') {
  699. return true;
  700. } else {
  701. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  702. $hubJson['error'] = true;
  703. file_put_contents($hubFilename, json_encode($hubJson));
  704. return false;
  705. }
  706. }
  707. return false;
  708. }
  709. //</WebSub>
  710. }