Feed.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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. if ($medium === 'image' || strpos($mime, 'image/') === 0) {
  346. $enclosureContent .= '<p class="enclosure-content"><img src="' . $elink . '" alt="" /></p>';
  347. } elseif ($medium === 'audio' || strpos($mime, 'audio/') === 0) {
  348. $enclosureContent .= '<p class="enclosure-content"><audio preload="none" src="' . $elink
  349. . '" controls="controls"></audio> <a download="" href="' . $elink . '">💾</a></p>';
  350. } elseif ($medium === 'video' || strpos($mime, 'video/') === 0) {
  351. $enclosureContent .= '<p class="enclosure-content"><video preload="none" src="' . $elink
  352. . '" controls="controls"></video> <a download="" href="' . $elink . '">💾</a></p>';
  353. } elseif ($medium != '' || strpos($mime, 'application/') === 0 || strpos($mime, 'text/') === 0) {
  354. $enclosureContent .= '<p class="enclosure-content"><a download="" href="' . $elink . '">💾</a></p>';
  355. } else {
  356. unset($elinks[$elink]);
  357. }
  358. $thumbnailContent = '';
  359. if ($enclosure->get_thumbnails() != null) {
  360. foreach ($enclosure->get_thumbnails() as $thumbnail) {
  361. if (empty($elinks[$thumbnail])) {
  362. $elinks[$thumbnail] = true;
  363. $thumbnailContent .= '<p><img class="enclosure-thumbnail" src="' . $thumbnail . '" alt="" /></p>';
  364. }
  365. }
  366. }
  367. $content .= $thumbnailContent;
  368. $content .= $enclosureContent;
  369. if ($enclosure->get_description() != '') {
  370. $content .= '<pre class="enclosure-description">' . $enclosure->get_description() . '</pre>';
  371. }
  372. $content .= "</div>\n";
  373. }
  374. }
  375. }
  376. $guid = $item->get_id(false, false);
  377. $hasUniqueGuids &= empty($guids['_' . $guid]);
  378. $guids['_' . $guid] = true;
  379. $author_names = '';
  380. if (is_array($authors)) {
  381. foreach ($authors as $author) {
  382. $author_names .= escapeToUnicodeAlternative(strip_tags($author->name == '' ? $author->email : $author->name), true) . '; ';
  383. }
  384. }
  385. $author_names = substr($author_names, 0, -2);
  386. $entry = new FreshRSS_Entry(
  387. $this->id(),
  388. $guid,
  389. $title === null ? '' : $title,
  390. $author_names,
  391. $content === null ? '' : $content,
  392. $link === null ? '' : $link,
  393. $date ? $date : time()
  394. );
  395. $entry->_tags($tags);
  396. $entry->_feed($this);
  397. if ($this->pathEntries != '') {
  398. // Optionally load full content for truncated feeds
  399. $entry->loadCompleteContent();
  400. }
  401. $entries[] = $entry;
  402. unset($item);
  403. }
  404. $hasBadGuids = $this->attributes('hasBadGuids');
  405. if ($hasBadGuids != !$hasUniqueGuids) {
  406. $hasBadGuids = !$hasUniqueGuids;
  407. if ($hasBadGuids) {
  408. Minz_Log::warning('Feed has invalid GUIDs: ' . $this->url);
  409. } else {
  410. Minz_Log::warning('Feed has valid GUIDs again: ' . $this->url);
  411. }
  412. $feedDAO = FreshRSS_Factory::createFeedDao();
  413. $feedDAO->updateFeedAttribute($this, 'hasBadGuids', $hasBadGuids);
  414. }
  415. if (!$hasUniqueGuids) {
  416. foreach ($entries as $entry) {
  417. $entry->_guid('');
  418. }
  419. }
  420. $this->entries = $entries;
  421. }
  422. public function cleanOldEntries() { //Remember to call updateCachedValue($id_feed) or updateCachedValues() just after
  423. $archiving = $this->attributes('archiving');
  424. if ($archiving == null) {
  425. $catDAO = FreshRSS_Factory::createCategoryDao();
  426. $category = $catDAO->searchById($this->category());
  427. $archiving = $category == null ? null : $category->attributes('archiving');
  428. if ($archiving == null) {
  429. $archiving = FreshRSS_Context::$user_conf->archiving;
  430. }
  431. }
  432. if (is_array($archiving)) {
  433. $entryDAO = FreshRSS_Factory::createEntryDao();
  434. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  435. if ($nb > 0) {
  436. $needFeedCacheRefresh = true;
  437. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  438. }
  439. return $nb;
  440. }
  441. return false;
  442. }
  443. protected function cacheFilename() {
  444. return CACHE_PATH . '/' . md5($this->url) . '.spc';
  445. }
  446. public function clearCache() {
  447. return @unlink($this->cacheFilename());
  448. }
  449. public function cacheModifiedTime() {
  450. return @filemtime($this->cacheFilename());
  451. }
  452. public function lock() {
  453. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  454. if (file_exists($this->lockPath) && ((time() - @filemtime($this->lockPath)) > 3600)) {
  455. @unlink($this->lockPath);
  456. }
  457. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  458. return false;
  459. }
  460. //register_shutdown_function('unlink', $this->lockPath);
  461. @fclose($handle);
  462. return true;
  463. }
  464. public function unlock() {
  465. @unlink($this->lockPath);
  466. }
  467. public function filterActions() {
  468. if ($this->filterActions == null) {
  469. $this->filterActions = array();
  470. $filters = $this->attributes('filters');
  471. if (is_array($filters)) {
  472. foreach ($filters as $filter) {
  473. $filterAction = FreshRSS_FilterAction::fromJSON($filter);
  474. if ($filterAction != null) {
  475. $this->filterActions[] = $filterAction;
  476. }
  477. }
  478. }
  479. }
  480. return $this->filterActions;
  481. }
  482. private function _filterActions($filterActions) {
  483. $this->filterActions = $filterActions;
  484. if (is_array($this->filterActions) && !empty($this->filterActions)) {
  485. $this->_attributes('filters', array_map(function ($af) {
  486. return $af == null ? null : $af->toJSON();
  487. }, $this->filterActions));
  488. } else {
  489. $this->_attributes('filters', null);
  490. }
  491. }
  492. public function filtersAction($action) {
  493. $action = trim($action);
  494. if ($action == '') {
  495. return array();
  496. }
  497. $filters = array();
  498. $filterActions = $this->filterActions();
  499. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  500. $filterAction = $filterActions[$i];
  501. if ($filterAction != null && $filterAction->booleanSearch() != null &&
  502. $filterAction->actions() != null && in_array($action, $filterAction->actions(), true)) {
  503. $filters[] = $filterAction->booleanSearch();
  504. }
  505. }
  506. return $filters;
  507. }
  508. public function _filtersAction($action, $filters) {
  509. $action = trim($action);
  510. if ($action == '' || !is_array($filters)) {
  511. return false;
  512. }
  513. $filters = array_unique(array_map('trim', $filters));
  514. $filterActions = $this->filterActions();
  515. //Check existing filters
  516. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  517. $filterAction = $filterActions[$i];
  518. if ($filterAction == null || !is_array($filterAction->actions()) ||
  519. $filterAction->booleanSearch() == null || trim($filterAction->booleanSearch()->getRawInput()) == '') {
  520. array_splice($filterAction, $i, 1);
  521. continue;
  522. }
  523. $actions = $filterAction->actions();
  524. //Remove existing rules with same action
  525. for ($j = count($actions) - 1; $j >= 0; $j--) {
  526. if ($actions[$j] === $action) {
  527. array_splice($actions, $j, 1);
  528. }
  529. }
  530. //Update existing filter with new action
  531. for ($k = count($filters) - 1; $k >= 0; $k --) {
  532. $filter = $filters[$k];
  533. if ($filter === $filterAction->booleanSearch()->getRawInput()) {
  534. $actions[] = $action;
  535. array_splice($filters, $k, 1);
  536. }
  537. }
  538. //Save result
  539. if (empty($actions)) {
  540. array_splice($filterActions, $i, 1);
  541. } else {
  542. $filterAction->_actions($actions);
  543. }
  544. }
  545. //Add new filters
  546. for ($k = count($filters) - 1; $k >= 0; $k --) {
  547. $filter = $filters[$k];
  548. if ($filter != '') {
  549. $filterAction = FreshRSS_FilterAction::fromJSON(array(
  550. 'search' => $filter,
  551. 'actions' => array($action),
  552. ));
  553. if ($filterAction != null) {
  554. $filterActions[] = $filterAction;
  555. }
  556. }
  557. }
  558. if (empty($filterActions)) {
  559. $filterActions = null;
  560. }
  561. $this->_filterActions($filterActions);
  562. }
  563. //<WebSub>
  564. public function pubSubHubbubEnabled() {
  565. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  566. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  567. if ($hubFile = @file_get_contents($hubFilename)) {
  568. $hubJson = json_decode($hubFile, true);
  569. if ($hubJson && empty($hubJson['error']) &&
  570. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  571. return true;
  572. }
  573. }
  574. return false;
  575. }
  576. public function pubSubHubbubError($error = true) {
  577. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  578. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  579. $hubFile = @file_get_contents($hubFilename);
  580. $hubJson = $hubFile ? json_decode($hubFile, true) : array();
  581. if (!isset($hubJson['error']) || $hubJson['error'] !== (bool)$error) {
  582. $hubJson['error'] = (bool)$error;
  583. file_put_contents($hubFilename, json_encode($hubJson));
  584. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  585. }
  586. return false;
  587. }
  588. public function pubSubHubbubPrepare() {
  589. $key = '';
  590. if (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) &&
  591. $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
  592. $path = PSHB_PATH . '/feeds/' . base64url_encode($this->selfUrl);
  593. $hubFilename = $path . '/!hub.json';
  594. if ($hubFile = @file_get_contents($hubFilename)) {
  595. $hubJson = json_decode($hubFile, true);
  596. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  597. $text = 'Invalid JSON for WebSub: ' . $this->url;
  598. Minz_Log::warning($text);
  599. Minz_Log::warning($text, PSHB_LOG);
  600. return false;
  601. }
  602. if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
  603. $text = 'WebSub lease ends at '
  604. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  605. . ' and needs renewal: ' . $this->url;
  606. Minz_Log::warning($text);
  607. Minz_Log::warning($text, PSHB_LOG);
  608. $key = $hubJson['key']; //To renew our lease
  609. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  610. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  611. $key = $hubJson['key']; //To renew our lease
  612. }
  613. } else {
  614. @mkdir($path, 0777, true);
  615. $key = sha1($path . FreshRSS_Context::$system_conf->salt);
  616. $hubJson = array(
  617. 'hub' => $this->hubUrl,
  618. 'key' => $key,
  619. );
  620. file_put_contents($hubFilename, json_encode($hubJson));
  621. @mkdir(PSHB_PATH . '/keys/');
  622. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', base64url_encode($this->selfUrl));
  623. $text = 'WebSub prepared for ' . $this->url;
  624. Minz_Log::debug($text);
  625. Minz_Log::debug($text, PSHB_LOG);
  626. }
  627. $currentUser = Minz_Session::param('currentUser');
  628. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  629. touch($path . '/' . $currentUser . '.txt');
  630. }
  631. }
  632. return $key;
  633. }
  634. //Parameter true to subscribe, false to unsubscribe.
  635. public function pubSubHubbubSubscribe($state) {
  636. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  637. if ($url && (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) || !$state)) {
  638. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  639. $hubFile = @file_get_contents($hubFilename);
  640. if ($hubFile === false) {
  641. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  642. return false;
  643. }
  644. $hubJson = json_decode($hubFile, true);
  645. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key']) || empty($hubJson['hub'])) {
  646. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  647. return false;
  648. }
  649. $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  650. if ($callbackUrl == '') {
  651. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  652. return false;
  653. }
  654. if (!$state) { //unsubscribe
  655. $hubJson['lease_end'] = time() - 60;
  656. file_put_contents($hubFilename, json_encode($hubJson));
  657. }
  658. $ch = curl_init();
  659. curl_setopt_array($ch, [
  660. CURLOPT_URL => $hubJson['hub'],
  661. CURLOPT_RETURNTRANSFER => true,
  662. CURLOPT_POSTFIELDS => http_build_query(array(
  663. 'hub.verify' => 'sync',
  664. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  665. 'hub.topic' => $url,
  666. 'hub.callback' => $callbackUrl,
  667. )),
  668. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  669. CURLOPT_MAXREDIRS => 10,
  670. CURLOPT_FOLLOWLOCATION => true,
  671. CURLOPT_ENCODING => '', //Enable all encodings
  672. ]);
  673. $response = curl_exec($ch);
  674. $info = curl_getinfo($ch);
  675. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  676. ' via hub ' . $hubJson['hub'] .
  677. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response, PSHB_LOG);
  678. if (substr($info['http_code'], 0, 1) == '2') {
  679. return true;
  680. } else {
  681. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  682. $hubJson['error'] = true;
  683. file_put_contents($hubFilename, json_encode($hubJson));
  684. return false;
  685. }
  686. }
  687. return false;
  688. }
  689. //</WebSub>
  690. }