Feed.php 24 KB

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