Feed.php 30 KB

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