Feed.php 23 KB

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