Feed.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. if (count($view->entries) < 1) {
  591. return null;
  592. }
  593. $simplePie = customSimplePie();
  594. $simplePie->set_raw_data($view->renderToString());
  595. $simplePie->init();
  596. return $simplePie;
  597. }
  598. /**
  599. * To keep track of some new potentially unread articles since last commit+fetch from database
  600. */
  601. public function incPendingUnread(int $n = 1) {
  602. $this->nbPendingNotRead += $n;
  603. }
  604. public function keepMaxUnread() {
  605. $keepMaxUnread = $this->attributes('keep_max_n_unread');
  606. if ($keepMaxUnread == false) {
  607. $keepMaxUnread = FreshRSS_Context::$user_conf->mark_when['max_n_unread'];
  608. }
  609. if ($keepMaxUnread > 0 && $this->nbNotRead(false) + $this->nbPendingNotRead > $keepMaxUnread) {
  610. $feedDAO = FreshRSS_Factory::createFeedDao();
  611. $feedDAO->keepMaxUnread($this->id(), max(0, $keepMaxUnread - $this->nbPendingNotRead));
  612. }
  613. }
  614. /**
  615. * Remember to call updateCachedValue($id_feed) or updateCachedValues() just after
  616. */
  617. public function cleanOldEntries() {
  618. $archiving = $this->attributes('archiving');
  619. if ($archiving == null) {
  620. $catDAO = FreshRSS_Factory::createCategoryDao();
  621. $category = $catDAO->searchById($this->category());
  622. $archiving = $category == null ? null : $category->attributes('archiving');
  623. if ($archiving == null) {
  624. $archiving = FreshRSS_Context::$user_conf->archiving;
  625. }
  626. }
  627. if (is_array($archiving)) {
  628. $entryDAO = FreshRSS_Factory::createEntryDao();
  629. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  630. if ($nb > 0) {
  631. $needFeedCacheRefresh = true;
  632. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  633. }
  634. return $nb;
  635. }
  636. return false;
  637. }
  638. public static function cacheFilename(string $url, array $attributes, int $kind = FreshRSS_Feed::KIND_RSS): string {
  639. $simplePie = customSimplePie($attributes);
  640. $filename = $simplePie->get_cache_filename($url);
  641. if ($kind == FreshRSS_Feed::KIND_HTML_XPATH) {
  642. return CACHE_PATH . '/' . $filename . '.html';
  643. } else {
  644. return CACHE_PATH . '/' . $filename . '.spc';
  645. }
  646. }
  647. public function clearCache(): bool {
  648. return @unlink(FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind));
  649. }
  650. /** @return int|false */
  651. public function cacheModifiedTime() {
  652. return @filemtime(FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind));
  653. }
  654. public function lock(): bool {
  655. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  656. if (file_exists($this->lockPath) && ((time() - @filemtime($this->lockPath)) > 3600)) {
  657. @unlink($this->lockPath);
  658. }
  659. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  660. return false;
  661. }
  662. //register_shutdown_function('unlink', $this->lockPath);
  663. @fclose($handle);
  664. return true;
  665. }
  666. public function unlock(): bool {
  667. return @unlink($this->lockPath);
  668. }
  669. /**
  670. * @return array<FreshRSS_FilterAction>
  671. */
  672. public function filterActions(): array {
  673. if (empty($this->filterActions)) {
  674. $this->filterActions = array();
  675. $filters = $this->attributes('filters');
  676. if (is_array($filters)) {
  677. foreach ($filters as $filter) {
  678. $filterAction = FreshRSS_FilterAction::fromJSON($filter);
  679. if ($filterAction != null) {
  680. $this->filterActions[] = $filterAction;
  681. }
  682. }
  683. }
  684. }
  685. return $this->filterActions;
  686. }
  687. /**
  688. * @param array<FreshRSS_FilterAction> $filterActions
  689. */
  690. private function _filterActions($filterActions) {
  691. $this->filterActions = $filterActions;
  692. if (is_array($this->filterActions) && !empty($this->filterActions)) {
  693. $this->_attributes('filters', array_map(function ($af) {
  694. return $af == null ? null : $af->toJSON();
  695. }, $this->filterActions));
  696. } else {
  697. $this->_attributes('filters', null);
  698. }
  699. }
  700. /** @return array<FreshRSS_BooleanSearch> */
  701. public function filtersAction(string $action): array {
  702. $action = trim($action);
  703. if ($action == '') {
  704. return array();
  705. }
  706. $filters = array();
  707. $filterActions = $this->filterActions();
  708. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  709. $filterAction = $filterActions[$i];
  710. if ($filterAction != null && $filterAction->booleanSearch() != null &&
  711. $filterAction->actions() != null && in_array($action, $filterAction->actions(), true)) {
  712. $filters[] = $filterAction->booleanSearch();
  713. }
  714. }
  715. return $filters;
  716. }
  717. /**
  718. * @param array<string> $filters
  719. */
  720. public function _filtersAction(string $action, $filters) {
  721. $action = trim($action);
  722. if ($action == '' || !is_array($filters)) {
  723. return false;
  724. }
  725. $filters = array_unique(array_map('trim', $filters));
  726. $filterActions = $this->filterActions();
  727. //Check existing filters
  728. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  729. $filterAction = $filterActions[$i];
  730. if ($filterAction == null || !is_array($filterAction->actions()) ||
  731. $filterAction->booleanSearch() == null || trim($filterAction->booleanSearch()->getRawInput()) == '') {
  732. array_splice($filterActions, $i, 1);
  733. continue;
  734. }
  735. $actions = $filterAction->actions();
  736. //Remove existing rules with same action
  737. for ($j = count($actions) - 1; $j >= 0; $j--) {
  738. if ($actions[$j] === $action) {
  739. array_splice($actions, $j, 1);
  740. }
  741. }
  742. //Update existing filter with new action
  743. for ($k = count($filters) - 1; $k >= 0; $k --) {
  744. $filter = $filters[$k];
  745. if ($filter === $filterAction->booleanSearch()->getRawInput()) {
  746. $actions[] = $action;
  747. array_splice($filters, $k, 1);
  748. }
  749. }
  750. //Save result
  751. if (empty($actions)) {
  752. array_splice($filterActions, $i, 1);
  753. } else {
  754. $filterAction->_actions($actions);
  755. }
  756. }
  757. //Add new filters
  758. for ($k = count($filters) - 1; $k >= 0; $k --) {
  759. $filter = $filters[$k];
  760. if ($filter != '') {
  761. $filterAction = FreshRSS_FilterAction::fromJSON(array(
  762. 'search' => $filter,
  763. 'actions' => array($action),
  764. ));
  765. if ($filterAction != null) {
  766. $filterActions[] = $filterAction;
  767. }
  768. }
  769. }
  770. if (empty($filterActions)) {
  771. $filterActions = null;
  772. }
  773. $this->_filterActions($filterActions);
  774. }
  775. //<WebSub>
  776. public function pubSubHubbubEnabled(): bool {
  777. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  778. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  779. if ($hubFile = @file_get_contents($hubFilename)) {
  780. $hubJson = json_decode($hubFile, true);
  781. if ($hubJson && empty($hubJson['error']) &&
  782. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  783. return true;
  784. }
  785. }
  786. return false;
  787. }
  788. public function pubSubHubbubError(bool $error = true): bool {
  789. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  790. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  791. $hubFile = @file_get_contents($hubFilename);
  792. $hubJson = $hubFile ? json_decode($hubFile, true) : array();
  793. if (!isset($hubJson['error']) || $hubJson['error'] !== (bool)$error) {
  794. $hubJson['error'] = (bool)$error;
  795. file_put_contents($hubFilename, json_encode($hubJson));
  796. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  797. }
  798. return false;
  799. }
  800. /**
  801. * @return string|false
  802. */
  803. public function pubSubHubbubPrepare() {
  804. $key = '';
  805. if (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) &&
  806. $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
  807. $path = PSHB_PATH . '/feeds/' . sha1($this->selfUrl);
  808. $hubFilename = $path . '/!hub.json';
  809. if ($hubFile = @file_get_contents($hubFilename)) {
  810. $hubJson = json_decode($hubFile, true);
  811. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  812. $text = 'Invalid JSON for WebSub: ' . $this->url;
  813. Minz_Log::warning($text);
  814. Minz_Log::warning($text, PSHB_LOG);
  815. return false;
  816. }
  817. if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
  818. $text = 'WebSub lease ends at '
  819. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  820. . ' and needs renewal: ' . $this->url;
  821. Minz_Log::warning($text);
  822. Minz_Log::warning($text, PSHB_LOG);
  823. $key = $hubJson['key']; //To renew our lease
  824. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  825. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  826. $key = $hubJson['key']; //To renew our lease
  827. }
  828. } else {
  829. @mkdir($path, 0777, true);
  830. $key = sha1($path . FreshRSS_Context::$system_conf->salt);
  831. $hubJson = array(
  832. 'hub' => $this->hubUrl,
  833. 'key' => $key,
  834. );
  835. file_put_contents($hubFilename, json_encode($hubJson));
  836. @mkdir(PSHB_PATH . '/keys/');
  837. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', $this->selfUrl);
  838. $text = 'WebSub prepared for ' . $this->url;
  839. Minz_Log::debug($text);
  840. Minz_Log::debug($text, PSHB_LOG);
  841. }
  842. $currentUser = Minz_Session::param('currentUser');
  843. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  844. touch($path . '/' . $currentUser . '.txt');
  845. }
  846. }
  847. return $key;
  848. }
  849. //Parameter true to subscribe, false to unsubscribe.
  850. public function pubSubHubbubSubscribe(bool $state): bool {
  851. if ($state) {
  852. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  853. } else {
  854. $url = $this->url; //Always use current URL during unsubscribe
  855. }
  856. if ($url && (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) || !$state)) {
  857. $hubFilename = PSHB_PATH . '/feeds/' . sha1($url) . '/!hub.json';
  858. $hubFile = @file_get_contents($hubFilename);
  859. if ($hubFile === false) {
  860. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  861. return false;
  862. }
  863. $hubJson = json_decode($hubFile, true);
  864. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key']) || empty($hubJson['hub'])) {
  865. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  866. return false;
  867. }
  868. $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  869. if ($callbackUrl == '') {
  870. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  871. return false;
  872. }
  873. if (!$state) { //unsubscribe
  874. $hubJson['lease_end'] = time() - 60;
  875. file_put_contents($hubFilename, json_encode($hubJson));
  876. }
  877. $ch = curl_init();
  878. curl_setopt_array($ch, [
  879. CURLOPT_URL => $hubJson['hub'],
  880. CURLOPT_RETURNTRANSFER => true,
  881. CURLOPT_POSTFIELDS => http_build_query(array(
  882. 'hub.verify' => 'sync',
  883. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  884. 'hub.topic' => $url,
  885. 'hub.callback' => $callbackUrl,
  886. )),
  887. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  888. CURLOPT_MAXREDIRS => 10,
  889. CURLOPT_FOLLOWLOCATION => true,
  890. CURLOPT_ENCODING => '', //Enable all encodings
  891. ]);
  892. $response = curl_exec($ch);
  893. $info = curl_getinfo($ch);
  894. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  895. ' via hub ' . $hubJson['hub'] .
  896. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response, PSHB_LOG);
  897. if (substr('' . $info['http_code'], 0, 1) == '2') {
  898. return true;
  899. } else {
  900. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  901. $hubJson['error'] = true;
  902. file_put_contents($hubFilename, json_encode($hubJson));
  903. return false;
  904. }
  905. }
  906. return false;
  907. }
  908. //</WebSub>
  909. }