Feed.php 25 KB

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