Feed.php 25 KB

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