Feed.php 23 KB

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