Feed.php 31 KB

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