Feed.php 32 KB

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