Feed.php 34 KB

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