Feed.php 35 KB

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