Feed.php 25 KB

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