Feed.php 35 KB

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