Feed.php 22 KB

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