Feed.php 35 KB

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