Feed.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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_IMPORTANT = 20;
  29. public const PRIORITY_MAIN_STREAM = 10;
  30. public const PRIORITY_CATEGORY = 0;
  31. public const PRIORITY_ARCHIVED = -10;
  32. public const TTL_DEFAULT = 0;
  33. public const ARCHIVING_RETENTION_COUNT_LIMIT = 10000;
  34. public const ARCHIVING_RETENTION_PERIOD = 'P3M';
  35. private int $id = 0;
  36. private string $url = '';
  37. private int $kind = 0;
  38. private int $categoryId = 1;
  39. private ?FreshRSS_Category $category;
  40. private int $nbEntries = -1;
  41. private int $nbNotRead = -1;
  42. private int $nbPendingNotRead = 0;
  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(bool $includePending = false): int {
  194. if ($this->nbNotRead < 0) {
  195. $feedDAO = FreshRSS_Factory::createFeedDao();
  196. $this->nbNotRead = $feedDAO->countNotRead($this->id());
  197. }
  198. return $this->nbNotRead + ($includePending ? $this->nbPendingNotRead : 0);
  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. //HTML to HTML-PRE //ENT_COMPAT except '&'
  368. $title = strtr(html_only_entity_decode($simplePie->get_title()), ['<' => '&lt;', '>' => '&gt;', '"' => '&quot;']);
  369. $this->_name($title == '' ? $this->url : $title);
  370. $this->_website(html_only_entity_decode($simplePie->get_link()));
  371. $this->_description(html_only_entity_decode($simplePie->get_description()));
  372. } else {
  373. //The case of HTTP 301 Moved Permanently
  374. $subscribe_url = $simplePie->subscribe_url(true);
  375. }
  376. $clean_url = SimplePie_Misc::url_remove_credentials($subscribe_url);
  377. if ($subscribe_url !== null && $subscribe_url !== $url) {
  378. $this->_url($clean_url);
  379. }
  380. if (($mtime === true) || ($mtime > $this->lastUpdate) || $noCache) {
  381. //Minz_Log::debug('FreshRSS no cache ' . $mtime . ' > ' . $this->lastUpdate . ' for ' . $clean_url);
  382. return $simplePie;
  383. }
  384. //Minz_Log::debug('FreshRSS use cache for ' . $clean_url);
  385. }
  386. }
  387. return null;
  388. }
  389. /**
  390. * @return array<string>
  391. */
  392. public function loadGuids(SimplePie $simplePie): array {
  393. $hasUniqueGuids = true;
  394. $testGuids = [];
  395. $guids = [];
  396. $links = [];
  397. $hadBadGuids = $this->attributes('hasBadGuids');
  398. $items = $simplePie->get_items();
  399. if (empty($items)) {
  400. return $guids;
  401. }
  402. for ($i = count($items) - 1; $i >= 0; $i--) {
  403. $item = $items[$i];
  404. if ($item == null) {
  405. continue;
  406. }
  407. $guid = safe_ascii($item->get_id(false, false));
  408. $hasUniqueGuids &= empty($testGuids['_' . $guid]);
  409. $testGuids['_' . $guid] = true;
  410. $guids[] = $guid;
  411. $links[] = $item->get_permalink();
  412. }
  413. if ($hadBadGuids != !$hasUniqueGuids) {
  414. if ($hadBadGuids) {
  415. Minz_Log::warning('Feed has invalid GUIDs: ' . $this->url);
  416. } else {
  417. Minz_Log::warning('Feed has valid GUIDs again: ' . $this->url);
  418. }
  419. $feedDAO = FreshRSS_Factory::createFeedDao();
  420. $feedDAO->updateFeedAttribute($this, 'hasBadGuids', !$hasUniqueGuids);
  421. }
  422. return $hasUniqueGuids ? $guids : $links;
  423. }
  424. /** @return Traversable<FreshRSS_Entry> */
  425. public function loadEntries(SimplePie $simplePie): Traversable {
  426. $hasBadGuids = $this->attributes('hasBadGuids');
  427. $items = $simplePie->get_items();
  428. if (empty($items)) {
  429. return;
  430. }
  431. // We want chronological order and SimplePie uses reverse order.
  432. for ($i = count($items) - 1; $i >= 0; $i--) {
  433. $item = $items[$i];
  434. if ($item == null) {
  435. continue;
  436. }
  437. $title = html_only_entity_decode(strip_tags($item->get_title() ?? ''));
  438. $authors = $item->get_authors();
  439. $link = $item->get_permalink();
  440. $date = @strtotime((string)($item->get_date() ?? '')) ?: 0;
  441. //Tag processing (tag == category)
  442. $categories = $item->get_categories();
  443. $tags = array();
  444. if (is_array($categories)) {
  445. foreach ($categories as $category) {
  446. $text = html_only_entity_decode($category->get_label());
  447. //Some feeds use a single category with comma-separated tags
  448. $labels = explode(',', $text);
  449. if (!empty($labels)) {
  450. foreach ($labels as $label) {
  451. $tags[] = trim($label);
  452. }
  453. }
  454. }
  455. $tags = array_unique($tags);
  456. }
  457. $content = html_only_entity_decode($item->get_content());
  458. $attributeThumbnail = $item->get_thumbnail() ?? [];
  459. if (empty($attributeThumbnail['url'])) {
  460. $attributeThumbnail['url'] = '';
  461. }
  462. $attributeEnclosures = [];
  463. if (!empty($item->get_enclosures())) {
  464. foreach ($item->get_enclosures() as $enclosure) {
  465. $elink = $enclosure->get_link();
  466. if ($elink != '') {
  467. $etitle = $enclosure->get_title() ?? '';
  468. $credit = $enclosure->get_credit() ?? null;
  469. $description = $enclosure->get_description() ?? '';
  470. $mime = strtolower($enclosure->get_type() ?? '');
  471. $medium = strtolower($enclosure->get_medium() ?? '');
  472. $height = $enclosure->get_height();
  473. $width = $enclosure->get_width();
  474. $length = $enclosure->get_length();
  475. $attributeEnclosure = [
  476. 'url' => $elink,
  477. ];
  478. if ($etitle != '') {
  479. $attributeEnclosure['title'] = $etitle;
  480. }
  481. if ($credit != null) {
  482. $attributeEnclosure['credit'] = $credit->get_name();
  483. }
  484. if ($description != '') {
  485. $attributeEnclosure['description'] = $description;
  486. }
  487. if ($mime != '') {
  488. $attributeEnclosure['type'] = $mime;
  489. }
  490. if ($medium != '') {
  491. $attributeEnclosure['medium'] = $medium;
  492. }
  493. if ($length != '') {
  494. $attributeEnclosure['length'] = intval($length);
  495. }
  496. if ($height != '') {
  497. $attributeEnclosure['height'] = intval($height);
  498. }
  499. if ($width != '') {
  500. $attributeEnclosure['width'] = intval($width);
  501. }
  502. if (!empty($enclosure->get_thumbnails())) {
  503. foreach ($enclosure->get_thumbnails() as $thumbnail) {
  504. if ($thumbnail !== $attributeThumbnail['url']) {
  505. $attributeEnclosure['thumbnails'][] = $thumbnail;
  506. }
  507. }
  508. }
  509. $attributeEnclosures[] = $attributeEnclosure;
  510. }
  511. }
  512. }
  513. $guid = safe_ascii($item->get_id(false, false));
  514. unset($item);
  515. $authorNames = '';
  516. if (is_array($authors)) {
  517. foreach ($authors as $author) {
  518. $authorName = $author->name != '' ? $author->name : $author->email;
  519. if ($authorName != '') {
  520. $authorNames .= escapeToUnicodeAlternative(strip_tags($authorName), true) . '; ';
  521. }
  522. }
  523. }
  524. $authorNames = substr($authorNames, 0, -2);
  525. $entry = new FreshRSS_Entry(
  526. $this->id(),
  527. $hasBadGuids ? '' : $guid,
  528. $title == '' ? '' : $title,
  529. $authorNames,
  530. $content == '' ? '' : $content,
  531. $link == '' ? '' : $link,
  532. $date ?: time()
  533. );
  534. $entry->_tags($tags);
  535. $entry->_feed($this);
  536. if (!empty($attributeThumbnail['url'])) {
  537. $entry->_attributes('thumbnail', $attributeThumbnail);
  538. }
  539. $entry->_attributes('enclosures', $attributeEnclosures);
  540. $entry->hash(); //Must be computed before loading full content
  541. $entry->loadCompleteContent(); // Optionally load full content for truncated feeds
  542. yield $entry;
  543. }
  544. }
  545. /**
  546. * @throws FreshRSS_Context_Exception
  547. */
  548. public function loadHtmlXpath(): ?SimplePie {
  549. if ($this->url == '') {
  550. return null;
  551. }
  552. $feedSourceUrl = htmlspecialchars_decode($this->url, ENT_QUOTES);
  553. if ($this->httpAuth != '') {
  554. $feedSourceUrl = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $feedSourceUrl);
  555. }
  556. // Same naming conventions than https://rss-bridge.github.io/rss-bridge/Bridge_API/XPathAbstract.html
  557. // https://rss-bridge.github.io/rss-bridge/Bridge_API/BridgeAbstract.html#collectdata
  558. /** @var array<string,string> $xPathSettings */
  559. $xPathSettings = $this->attributes('xpath');
  560. $xPathFeedTitle = $xPathSettings['feedTitle'] ?? '';
  561. $xPathItem = $xPathSettings['item'] ?? '';
  562. $xPathItemTitle = $xPathSettings['itemTitle'] ?? '';
  563. $xPathItemContent = $xPathSettings['itemContent'] ?? '';
  564. $xPathItemUri = $xPathSettings['itemUri'] ?? '';
  565. $xPathItemAuthor = $xPathSettings['itemAuthor'] ?? '';
  566. $xPathItemTimestamp = $xPathSettings['itemTimestamp'] ?? '';
  567. $xPathItemTimeFormat = $xPathSettings['itemTimeFormat'] ?? '';
  568. $xPathItemThumbnail = $xPathSettings['itemThumbnail'] ?? '';
  569. $xPathItemCategories = $xPathSettings['itemCategories'] ?? '';
  570. $xPathItemUid = $xPathSettings['itemUid'] ?? '';
  571. if ($xPathItem == '') {
  572. return null;
  573. }
  574. $cachePath = FreshRSS_Feed::cacheFilename($feedSourceUrl, $this->attributes(), $this->kind());
  575. $html = httpGet($feedSourceUrl, $cachePath,
  576. $this->kind() === FreshRSS_Feed::KIND_XML_XPATH ? 'xml' : 'html', $this->attributes());
  577. if (strlen($html) <= 0) {
  578. return null;
  579. }
  580. $view = new FreshRSS_View();
  581. $view->_path('index/rss.phtml');
  582. $view->internal_rendering = true;
  583. $view->rss_url = $feedSourceUrl;
  584. $view->entries = [];
  585. try {
  586. $doc = new DOMDocument();
  587. $doc->recover = true;
  588. $doc->strictErrorChecking = false;
  589. $ok = false;
  590. switch ($this->kind()) {
  591. case FreshRSS_Feed::KIND_HTML_XPATH:
  592. $ok = $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false;
  593. break;
  594. case FreshRSS_Feed::KIND_XML_XPATH:
  595. $ok = $doc->loadXML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) !== false;
  596. break;
  597. }
  598. if (!$ok) {
  599. return null;
  600. }
  601. $xpath = new DOMXPath($doc);
  602. $view->rss_title = $xPathFeedTitle == '' ? $this->name() :
  603. htmlspecialchars(@$xpath->evaluate('normalize-space(' . $xPathFeedTitle . ')'), ENT_COMPAT, 'UTF-8');
  604. $view->rss_base = htmlspecialchars(trim($xpath->evaluate('normalize-space(//base/@href)')), ENT_COMPAT, 'UTF-8');
  605. $nodes = $xpath->query($xPathItem);
  606. if ($nodes === false || $nodes->length === 0) {
  607. return null;
  608. }
  609. foreach ($nodes as $node) {
  610. $item = [];
  611. $item['title'] = $xPathItemTitle == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTitle . ')', $node);
  612. $item['content'] = '';
  613. if ($xPathItemContent != '') {
  614. $result = @$xpath->evaluate($xPathItemContent, $node);
  615. if ($result instanceof DOMNodeList) {
  616. // List of nodes, save as HTML
  617. $content = '';
  618. foreach ($result as $child) {
  619. $content .= $doc->saveHTML($child) . "\n";
  620. }
  621. $item['content'] = $content;
  622. } else {
  623. // Typed expression, save as-is
  624. $item['content'] = (string)$result;
  625. }
  626. }
  627. $item['link'] = $xPathItemUri == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemUri . ')', $node);
  628. $item['author'] = $xPathItemAuthor == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemAuthor . ')', $node);
  629. $item['timestamp'] = $xPathItemTimestamp == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTimestamp . ')', $node);
  630. if ($xPathItemTimeFormat != '') {
  631. $dateTime = DateTime::createFromFormat($xPathItemTimeFormat, $item['timestamp'] ?? '');
  632. if ($dateTime != false) {
  633. $item['timestamp'] = $dateTime->format(DateTime::ATOM);
  634. }
  635. }
  636. $item['thumbnail'] = $xPathItemThumbnail == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemThumbnail . ')', $node);
  637. if ($xPathItemCategories != '') {
  638. $itemCategories = @$xpath->evaluate($xPathItemCategories, $node);
  639. if (is_string($itemCategories) && $itemCategories !== '') {
  640. $item['tags'] = [$itemCategories];
  641. } elseif ($itemCategories instanceof DOMNodeList && $itemCategories->length > 0) {
  642. $item['tags'] = [];
  643. /** @var DOMNode $itemCategory */
  644. foreach ($itemCategories as $itemCategory) {
  645. $item['tags'][] = $itemCategory->textContent;
  646. }
  647. }
  648. }
  649. if ($xPathItemUid != '') {
  650. $item['guid'] = @$xpath->evaluate('normalize-space(' . $xPathItemUid . ')', $node);
  651. }
  652. if (empty($item['guid'])) {
  653. $item['guid'] = 'urn:sha1:' . sha1($item['title'] . $item['content'] . $item['link']);
  654. }
  655. if ($item['title'] != '' || $item['content'] != '' || $item['link'] != '') {
  656. // HTML-encoding/escaping of the relevant fields (all except 'content')
  657. foreach (['author', 'guid', 'link', 'thumbnail', 'timestamp', 'tags', 'title'] as $key) {
  658. if (!empty($item[$key]) && is_string($item[$key])) {
  659. $item[$key] = Minz_Helper::htmlspecialchars_utf8($item[$key]);
  660. }
  661. }
  662. // CDATA protection
  663. $item['content'] = str_replace(']]>', ']]&gt;', $item['content']);
  664. $view->entries[] = FreshRSS_Entry::fromArray($item);
  665. }
  666. }
  667. } catch (Exception $ex) {
  668. Minz_Log::warning($ex->getMessage());
  669. return null;
  670. }
  671. $simplePie = customSimplePie();
  672. $simplePie->set_raw_data($view->renderToString());
  673. $simplePie->init();
  674. return $simplePie;
  675. }
  676. /**
  677. * To keep track of some new potentially unread articles since last commit+fetch from database
  678. */
  679. public function incPendingUnread(int $n = 1): void {
  680. $this->nbPendingNotRead += $n;
  681. }
  682. /**
  683. * Remember to call updateCachedValue($id_feed) or updateCachedValues() just after.
  684. * @return int|false the number of lines affected, or false if not applicable
  685. * @throws JsonException
  686. */
  687. public function keepMaxUnread() {
  688. $keepMaxUnread = $this->attributes('keep_max_n_unread');
  689. if ($keepMaxUnread === null) {
  690. $keepMaxUnread = FreshRSS_Context::$user_conf->mark_when['max_n_unread'];
  691. }
  692. $keepMaxUnread = (int)$keepMaxUnread;
  693. if ($keepMaxUnread > 0 && $this->nbNotRead(false) + $this->nbPendingNotRead > $keepMaxUnread) {
  694. return FreshRSS_Factory::createFeedDao()->keepMaxUnread($this->id(), max(0, $keepMaxUnread - $this->nbPendingNotRead));
  695. }
  696. return false;
  697. }
  698. /**
  699. * Applies the *mark as read upon gone* policy, if enabled.
  700. * Remember to call `updateCachedValue($id_feed)` or `updateCachedValues()` just after.
  701. * @return int|false the number of lines affected, or false if not applicable
  702. */
  703. public function markAsReadUponGone(bool $upstreamIsEmpty, int $maxTimestamp = 0) {
  704. $readUponGone = $this->attributes('read_upon_gone');
  705. if ($readUponGone === null) {
  706. $readUponGone = FreshRSS_Context::$user_conf->mark_when['gone'];
  707. }
  708. if (!$readUponGone) {
  709. return false;
  710. }
  711. if ($upstreamIsEmpty) {
  712. if ($maxTimestamp <= 0) {
  713. $maxTimestamp = time();
  714. }
  715. $entryDAO = FreshRSS_Factory::createEntryDao();
  716. $affected = $entryDAO->markReadFeed($this->id(), $maxTimestamp . '000000');
  717. } else {
  718. $feedDAO = FreshRSS_Factory::createFeedDao();
  719. $affected = $feedDAO->markAsReadUponGone($this->id());
  720. }
  721. if ($affected > 0) {
  722. Minz_Log::debug(__METHOD__ . " $affected items" . ($upstreamIsEmpty ? ' (all)' : '') . ' [' . $this->url(false) . ']');
  723. }
  724. return $affected;
  725. }
  726. /**
  727. * Remember to call `updateCachedValue($id_feed)` or `updateCachedValues()` just after
  728. * @return int|false
  729. */
  730. public function cleanOldEntries() {
  731. $archiving = $this->attributes('archiving');
  732. if ($archiving == null) {
  733. $catDAO = FreshRSS_Factory::createCategoryDao();
  734. $category = $catDAO->searchById($this->categoryId);
  735. $archiving = $category == null ? null : $category->attributes('archiving');
  736. if ($archiving == null) {
  737. $archiving = FreshRSS_Context::$user_conf->archiving;
  738. }
  739. }
  740. if (is_array($archiving)) {
  741. $entryDAO = FreshRSS_Factory::createEntryDao();
  742. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  743. if ($nb > 0) {
  744. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  745. }
  746. return $nb;
  747. }
  748. return false;
  749. }
  750. /** @param array<string,mixed> $attributes */
  751. public static function cacheFilename(string $url, array $attributes, int $kind = FreshRSS_Feed::KIND_RSS): string {
  752. $simplePie = customSimplePie($attributes);
  753. $filename = $simplePie->get_cache_filename($url);
  754. if ($kind === FreshRSS_Feed::KIND_HTML_XPATH) {
  755. return CACHE_PATH . '/' . $filename . '.html';
  756. } elseif ($kind === FreshRSS_Feed::KIND_XML_XPATH) {
  757. return CACHE_PATH . '/' . $filename . '.xml';
  758. } else {
  759. return CACHE_PATH . '/' . $filename . '.spc';
  760. }
  761. }
  762. public function clearCache(): bool {
  763. return @unlink(FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind));
  764. }
  765. /** @return int|false */
  766. public function cacheModifiedTime() {
  767. $filename = FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind);
  768. clearstatcache(true, $filename);
  769. return @filemtime($filename);
  770. }
  771. public function lock(): bool {
  772. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  773. if (file_exists($this->lockPath) && ((time() - (@filemtime($this->lockPath) ?: 0)) > 3600)) {
  774. @unlink($this->lockPath);
  775. }
  776. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  777. return false;
  778. }
  779. //register_shutdown_function('unlink', $this->lockPath);
  780. @fclose($handle);
  781. return true;
  782. }
  783. public function unlock(): bool {
  784. return @unlink($this->lockPath);
  785. }
  786. /**
  787. * @return array<FreshRSS_FilterAction>
  788. */
  789. public function filterActions(): array {
  790. if (empty($this->filterActions)) {
  791. $this->filterActions = [];
  792. $filters = $this->attributes('filters');
  793. if (is_array($filters)) {
  794. foreach ($filters as $filter) {
  795. $filterAction = FreshRSS_FilterAction::fromJSON($filter);
  796. if ($filterAction != null) {
  797. $this->filterActions[] = $filterAction;
  798. }
  799. }
  800. }
  801. }
  802. return $this->filterActions;
  803. }
  804. /**
  805. * @param array<FreshRSS_FilterAction>|null $filterActions
  806. */
  807. private function _filterActions(?array $filterActions): void {
  808. $this->filterActions = $filterActions;
  809. if (is_array($this->filterActions) && !empty($this->filterActions)) {
  810. $this->_attributes('filters', array_map(static function (?FreshRSS_FilterAction $af) {
  811. return $af == null ? null : $af->toJSON();
  812. }, $this->filterActions));
  813. } else {
  814. $this->_attributes('filters', null);
  815. }
  816. }
  817. /** @return array<FreshRSS_BooleanSearch> */
  818. public function filtersAction(string $action): array {
  819. $action = trim($action);
  820. if ($action == '') {
  821. return [];
  822. }
  823. $filters = [];
  824. $filterActions = $this->filterActions();
  825. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  826. $filterAction = $filterActions[$i];
  827. if ($filterAction != null && $filterAction->booleanSearch() != null &&
  828. $filterAction->actions() != null && in_array($action, $filterAction->actions(), true)) {
  829. $filters[] = $filterAction->booleanSearch();
  830. }
  831. }
  832. return $filters;
  833. }
  834. /**
  835. * @param array<string> $filters
  836. */
  837. public function _filtersAction(string $action, array $filters): void {
  838. $action = trim($action);
  839. if ($action == '') {
  840. return;
  841. }
  842. $filters = array_unique(array_map('trim', $filters));
  843. $filterActions = $this->filterActions();
  844. //Check existing filters
  845. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  846. $filterAction = $filterActions[$i];
  847. if ($filterAction == null || !is_array($filterAction->actions()) ||
  848. $filterAction->booleanSearch() == null || trim($filterAction->booleanSearch()->getRawInput()) == '') {
  849. array_splice($filterActions, $i, 1);
  850. continue;
  851. }
  852. $actions = $filterAction->actions();
  853. //Remove existing rules with same action
  854. for ($j = count($actions) - 1; $j >= 0; $j--) {
  855. if ($actions[$j] === $action) {
  856. array_splice($actions, $j, 1);
  857. }
  858. }
  859. //Update existing filter with new action
  860. for ($k = count($filters) - 1; $k >= 0; $k --) {
  861. $filter = $filters[$k];
  862. if ($filter === $filterAction->booleanSearch()->getRawInput()) {
  863. $actions[] = $action;
  864. array_splice($filters, $k, 1);
  865. }
  866. }
  867. //Save result
  868. if (empty($actions)) {
  869. array_splice($filterActions, $i, 1);
  870. } else {
  871. $filterAction->_actions($actions);
  872. }
  873. }
  874. //Add new filters
  875. for ($k = count($filters) - 1; $k >= 0; $k --) {
  876. $filter = $filters[$k];
  877. if ($filter != '') {
  878. $filterAction = FreshRSS_FilterAction::fromJSON([
  879. 'search' => $filter,
  880. 'actions' => [$action],
  881. ]);
  882. if ($filterAction != null) {
  883. $filterActions[] = $filterAction;
  884. }
  885. }
  886. }
  887. if (empty($filterActions)) {
  888. $filterActions = null;
  889. }
  890. $this->_filterActions($filterActions);
  891. }
  892. //<WebSub>
  893. public function pubSubHubbubEnabled(): bool {
  894. $url = $this->selfUrl ?: $this->url;
  895. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  896. if ($hubFile = @file_get_contents($hubFilename)) {
  897. $hubJson = json_decode($hubFile, true);
  898. if ($hubJson && empty($hubJson['error']) &&
  899. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  900. return true;
  901. }
  902. }
  903. return false;
  904. }
  905. public function pubSubHubbubError(bool $error = true): bool {
  906. $url = $this->selfUrl ?: $this->url;
  907. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  908. $hubFile = @file_get_contents($hubFilename);
  909. $hubJson = $hubFile ? json_decode($hubFile, true) : [];
  910. if (!isset($hubJson['error']) || $hubJson['error'] !== $error) {
  911. $hubJson['error'] = $error;
  912. file_put_contents($hubFilename, json_encode($hubJson));
  913. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  914. }
  915. return false;
  916. }
  917. /**
  918. * @return string|false
  919. */
  920. public function pubSubHubbubPrepare() {
  921. $key = '';
  922. if (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) &&
  923. $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
  924. $path = PSHB_PATH . '/feeds/' . sha1($this->selfUrl);
  925. $hubFilename = $path . '/!hub.json';
  926. if ($hubFile = @file_get_contents($hubFilename)) {
  927. $hubJson = json_decode($hubFile, true);
  928. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  929. $text = 'Invalid JSON for WebSub: ' . $this->url;
  930. Minz_Log::warning($text);
  931. Minz_Log::warning($text, PSHB_LOG);
  932. return false;
  933. }
  934. if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
  935. $text = 'WebSub lease ends at '
  936. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  937. . ' and needs renewal: ' . $this->url;
  938. Minz_Log::warning($text);
  939. Minz_Log::warning($text, PSHB_LOG);
  940. $key = $hubJson['key']; //To renew our lease
  941. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  942. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  943. $key = $hubJson['key']; //To renew our lease
  944. }
  945. } else {
  946. @mkdir($path, 0770, true);
  947. $key = sha1($path . FreshRSS_Context::$system_conf->salt);
  948. $hubJson = [
  949. 'hub' => $this->hubUrl,
  950. 'key' => $key,
  951. ];
  952. file_put_contents($hubFilename, json_encode($hubJson));
  953. @mkdir(PSHB_PATH . '/keys/', 0770, true);
  954. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', $this->selfUrl);
  955. $text = 'WebSub prepared for ' . $this->url;
  956. Minz_Log::debug($text);
  957. Minz_Log::debug($text, PSHB_LOG);
  958. }
  959. $currentUser = Minz_User::name();
  960. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  961. touch($path . '/' . $currentUser . '.txt');
  962. }
  963. }
  964. return $key;
  965. }
  966. //Parameter true to subscribe, false to unsubscribe.
  967. public function pubSubHubbubSubscribe(bool $state): bool {
  968. if ($state) {
  969. $url = $this->selfUrl ?: $this->url;
  970. } else {
  971. $url = $this->url; //Always use current URL during unsubscribe
  972. }
  973. if ($url && (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) || !$state)) {
  974. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  975. $hubFile = @file_get_contents($hubFilename);
  976. if ($hubFile === false) {
  977. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  978. return false;
  979. }
  980. $hubJson = json_decode($hubFile, true);
  981. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key']) || empty($hubJson['hub'])) {
  982. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  983. return false;
  984. }
  985. $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  986. if ($callbackUrl == '') {
  987. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  988. return false;
  989. }
  990. if (!$state) { //unsubscribe
  991. $hubJson['lease_end'] = time() - 60;
  992. file_put_contents($hubFilename, json_encode($hubJson));
  993. }
  994. $ch = curl_init();
  995. curl_setopt_array($ch, [
  996. CURLOPT_URL => $hubJson['hub'],
  997. CURLOPT_RETURNTRANSFER => true,
  998. CURLOPT_POSTFIELDS => http_build_query([
  999. 'hub.verify' => 'sync',
  1000. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  1001. 'hub.topic' => $url,
  1002. 'hub.callback' => $callbackUrl,
  1003. ]),
  1004. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  1005. CURLOPT_MAXREDIRS => 10,
  1006. CURLOPT_FOLLOWLOCATION => true,
  1007. CURLOPT_ENCODING => '', //Enable all encodings
  1008. ]);
  1009. $response = curl_exec($ch);
  1010. $info = curl_getinfo($ch);
  1011. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  1012. ' via hub ' . $hubJson['hub'] .
  1013. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response, PSHB_LOG);
  1014. if (substr('' . $info['http_code'], 0, 1) == '2') {
  1015. return true;
  1016. } else {
  1017. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  1018. $hubJson['error'] = true;
  1019. file_put_contents($hubFilename, json_encode($hubJson));
  1020. return false;
  1021. }
  1022. }
  1023. return false;
  1024. }
  1025. //</WebSub>
  1026. }