Feed.php 33 KB

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