Feed.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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_exists($txt)) {
  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($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 = $links[0] ?? '';
  336. $links = $simplePie->get_links('hub');
  337. $this->hubUrl = $links[0] ?? '';
  338. if ($loadDetails) {
  339. // si on a utilisé l’auto-discover, notre url va avoir changé
  340. $subscribe_url = $simplePie->subscribe_url(false);
  341. //HTML to HTML-PRE //ENT_COMPAT except '&'
  342. $title = strtr(html_only_entity_decode($simplePie->get_title()), array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
  343. $this->_name($title == '' ? $this->url : $title);
  344. $this->_website(html_only_entity_decode($simplePie->get_link()));
  345. $this->_description(html_only_entity_decode($simplePie->get_description()));
  346. } else {
  347. //The case of HTTP 301 Moved Permanently
  348. $subscribe_url = $simplePie->subscribe_url(true);
  349. }
  350. $clean_url = SimplePie_Misc::url_remove_credentials($subscribe_url);
  351. if ($subscribe_url !== null && $subscribe_url !== $url) {
  352. $this->_url($clean_url);
  353. }
  354. if (($mtime === true) || ($mtime > $this->lastUpdate) || $noCache) {
  355. //Minz_Log::debug('FreshRSS no cache ' . $mtime . ' > ' . $this->lastUpdate . ' for ' . $clean_url);
  356. return $simplePie;
  357. }
  358. //Minz_Log::debug('FreshRSS use cache for ' . $clean_url);
  359. }
  360. }
  361. return null;
  362. }
  363. /**
  364. * @return array<string>
  365. */
  366. public function loadGuids(SimplePie $simplePie) {
  367. $hasUniqueGuids = true;
  368. $testGuids = [];
  369. $guids = [];
  370. $hasBadGuids = $this->attributes('hasBadGuids');
  371. // TODO: Replace very slow $simplePie->get_item($i) by getting all items at once
  372. for ($i = $simplePie->get_item_quantity() - 1; $i >= 0; $i--) {
  373. $item = $simplePie->get_item($i);
  374. if ($item == null) {
  375. continue;
  376. }
  377. $guid = safe_ascii($item->get_id(false, false));
  378. $hasUniqueGuids &= empty($testGuids['_' . $guid]);
  379. $testGuids['_' . $guid] = true;
  380. $guids[] = $guid;
  381. }
  382. if ($hasBadGuids != !$hasUniqueGuids) {
  383. $hasBadGuids = !$hasUniqueGuids;
  384. if ($hasBadGuids) {
  385. Minz_Log::warning('Feed has invalid GUIDs: ' . $this->url);
  386. } else {
  387. Minz_Log::warning('Feed has valid GUIDs again: ' . $this->url);
  388. }
  389. $feedDAO = FreshRSS_Factory::createFeedDao();
  390. $feedDAO->updateFeedAttribute($this, 'hasBadGuids', $hasBadGuids);
  391. }
  392. return $guids;
  393. }
  394. public function loadEntries(SimplePie $simplePie) {
  395. $hasBadGuids = $this->attributes('hasBadGuids');
  396. // We want chronological order and SimplePie uses reverse order.
  397. // TODO: Replace very slow $simplePie->get_item($i) by getting all items at once
  398. for ($i = $simplePie->get_item_quantity() - 1; $i >= 0; $i--) {
  399. $item = $simplePie->get_item($i);
  400. if ($item == null) {
  401. continue;
  402. }
  403. $title = html_only_entity_decode(strip_tags($item->get_title() ?? ''));
  404. $authors = $item->get_authors();
  405. $link = $item->get_permalink();
  406. $date = @strtotime($item->get_date() ?? '');
  407. //Tag processing (tag == category)
  408. $categories = $item->get_categories();
  409. $tags = array();
  410. if (is_array($categories)) {
  411. foreach ($categories as $category) {
  412. $text = html_only_entity_decode($category->get_label());
  413. //Some feeds use a single category with comma-separated tags
  414. $labels = explode(',', $text);
  415. if (is_array($labels)) {
  416. foreach ($labels as $label) {
  417. $tags[] = trim($label);
  418. }
  419. }
  420. }
  421. $tags = array_unique($tags);
  422. }
  423. $content = html_only_entity_decode($item->get_content());
  424. if ($item->get_enclosures() != null) {
  425. $elinks = array();
  426. foreach ($item->get_enclosures() as $enclosure) {
  427. $elink = $enclosure->get_link();
  428. if ($elink != '' && empty($elinks[$elink])) {
  429. $content .= '<div class="enclosure">';
  430. if ($enclosure->get_title() != '') {
  431. $content .= '<p class="enclosure-title">' . $enclosure->get_title() . '</p>';
  432. }
  433. $enclosureContent = '';
  434. $elinks[$elink] = true;
  435. $mime = strtolower($enclosure->get_type() ?? '');
  436. $medium = strtolower($enclosure->get_medium() ?? '');
  437. $height = $enclosure->get_height();
  438. $width = $enclosure->get_width();
  439. $length = $enclosure->get_length();
  440. if ($medium === 'image' || strpos($mime, 'image') === 0 ||
  441. ($mime == '' && $length == null && ($width != 0 || $height != 0 || preg_match('/[.](avif|gif|jpe?g|png|svg|webp)$/i', $elink)))) {
  442. $enclosureContent .= '<p class="enclosure-content"><img src="' . $elink . '" alt="" /></p>';
  443. } elseif ($medium === 'audio' || strpos($mime, 'audio') === 0) {
  444. $enclosureContent .= '<p class="enclosure-content"><audio preload="none" src="' . $elink
  445. . ($length == null ? '' : '" data-length="' . intval($length))
  446. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  447. . '" controls="controls"></audio> <a download="" href="' . $elink . '">💾</a></p>';
  448. } elseif ($medium === 'video' || strpos($mime, 'video') === 0) {
  449. $enclosureContent .= '<p class="enclosure-content"><video preload="none" src="' . $elink
  450. . ($length == null ? '' : '" data-length="' . intval($length))
  451. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  452. . '" controls="controls"></video> <a download="" href="' . $elink . '">💾</a></p>';
  453. } else { //e.g. application, text, unknown
  454. $enclosureContent .= '<p class="enclosure-content"><a download="" href="' . $elink
  455. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  456. . ($medium == '' ? '' : '" data-medium="' . htmlspecialchars($medium, ENT_COMPAT, 'UTF-8'))
  457. . '">💾</a></p>';
  458. }
  459. $thumbnailContent = '';
  460. if ($enclosure->get_thumbnails() != null) {
  461. foreach ($enclosure->get_thumbnails() as $thumbnail) {
  462. if (empty($elinks[$thumbnail])) {
  463. $elinks[$thumbnail] = true;
  464. $thumbnailContent .= '<p><img class="enclosure-thumbnail" src="' . $thumbnail . '" alt="" /></p>';
  465. }
  466. }
  467. }
  468. $content .= $thumbnailContent;
  469. $content .= $enclosureContent;
  470. if ($enclosure->get_description() != '') {
  471. $content .= '<p class="enclosure-description">' . $enclosure->get_description() . '</p>';
  472. }
  473. $content .= "</div>\n";
  474. }
  475. }
  476. }
  477. $guid = safe_ascii($item->get_id(false, false));
  478. unset($item);
  479. $author_names = '';
  480. if (is_array($authors)) {
  481. foreach ($authors as $author) {
  482. $author_names .= escapeToUnicodeAlternative(strip_tags($author->name == '' ? $author->email : $author->name), true) . '; ';
  483. }
  484. }
  485. $author_names = substr($author_names, 0, -2);
  486. $entry = new FreshRSS_Entry(
  487. $this->id(),
  488. $hasBadGuids ? '' : $guid,
  489. $title == '' ? '' : $title,
  490. $author_names,
  491. $content == '' ? '' : $content,
  492. $link == '' ? '' : $link,
  493. $date ? $date : time()
  494. );
  495. $entry->_tags($tags);
  496. $entry->_feed($this);
  497. $entry->hash(); //Must be computed before loading full content
  498. $entry->loadCompleteContent(); // Optionally load full content for truncated feeds
  499. yield $entry;
  500. }
  501. }
  502. /**
  503. * @param array<string,mixed> $attributes
  504. * @return SimplePie|null
  505. */
  506. public function loadHtmlXpath(bool $loadDetails = false, bool $noCache = false, array $attributes = []) {
  507. if ($this->url == '') {
  508. return null;
  509. }
  510. $feedSourceUrl = htmlspecialchars_decode($this->url, ENT_QUOTES);
  511. if ($this->httpAuth != '') {
  512. $feedSourceUrl = preg_replace('#((.+)://)(.+)#', '${1}' . $this->httpAuth . '@${3}', $feedSourceUrl);
  513. }
  514. // Same naming conventions than https://github.com/RSS-Bridge/rss-bridge/wiki/XPathAbstract
  515. // https://github.com/RSS-Bridge/rss-bridge/wiki/The-collectData-function
  516. /** @var array<string,string> */
  517. $xPathSettings = $this->attributes('xpath');
  518. $xPathFeedTitle = $xPathSettings['feedTitle'] ?? '';
  519. $xPathItem = $xPathSettings['item'] ?? '';
  520. $xPathItemTitle = $xPathSettings['itemTitle'] ?? '';
  521. $xPathItemContent = $xPathSettings['itemContent'] ?? '';
  522. $xPathItemUri = $xPathSettings['itemUri'] ?? '';
  523. $xPathItemAuthor = $xPathSettings['itemAuthor'] ?? '';
  524. $xPathItemTimestamp = $xPathSettings['itemTimestamp'] ?? '';
  525. $xPathItemThumbnail = $xPathSettings['itemThumbnail'] ?? '';
  526. $xPathItemCategories = $xPathSettings['itemCategories'] ?? '';
  527. if ($xPathItem == '') {
  528. return null;
  529. }
  530. $html = getHtml($feedSourceUrl, $attributes);
  531. if (strlen($html) <= 0) {
  532. return null;
  533. }
  534. $view = new FreshRSS_View();
  535. $view->_path('index/rss.phtml');
  536. $view->internal_rendering = true;
  537. $view->rss_url = $feedSourceUrl;
  538. $view->entries = [];
  539. try {
  540. $doc = new DOMDocument();
  541. $doc->recover = true;
  542. $doc->strictErrorChecking = false;
  543. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  544. $xpath = new DOMXPath($doc);
  545. $view->rss_title = $xPathFeedTitle == '' ? '' : htmlspecialchars(@$xpath->evaluate('normalize-space(' . $xPathFeedTitle . ')'), ENT_COMPAT, 'UTF-8');
  546. $view->rss_base = htmlspecialchars(trim($xpath->evaluate('normalize-space(//base/@href)')), ENT_COMPAT, 'UTF-8');
  547. $nodes = $xpath->query($xPathItem);
  548. if (empty($nodes)) {
  549. return null;
  550. }
  551. foreach ($nodes as $node) {
  552. $item = [];
  553. $item['title'] = $xPathItemTitle == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTitle . ')', $node);
  554. $item['content'] = $xPathItemContent == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemContent . ')', $node);
  555. $item['link'] = $xPathItemUri == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemUri . ')', $node);
  556. $item['author'] = $xPathItemAuthor == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemAuthor . ')', $node);
  557. $item['timestamp'] = $xPathItemTimestamp == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemTimestamp . ')', $node);
  558. $item['thumbnail'] = $xPathItemThumbnail == '' ? '' : @$xpath->evaluate('normalize-space(' . $xPathItemThumbnail . ')', $node);
  559. if ($xPathItemCategories != '') {
  560. $itemCategories = @$xpath->query($xPathItemCategories);
  561. if ($itemCategories) {
  562. foreach ($itemCategories as $itemCategory) {
  563. $item['categories'][] = $itemCategory->textContent;
  564. }
  565. }
  566. }
  567. if ($item['title'] . $item['content'] . $item['link'] != '') {
  568. $item['guid'] = 'urn:sha1:' . sha1($item['title'] . $item['content'] . $item['link']);
  569. $item = Minz_Helper::htmlspecialchars_utf8($item);
  570. $view->entries[] = FreshRSS_Entry::fromArray($item);
  571. }
  572. }
  573. } catch (Exception $ex) {
  574. Minz_Log::warning($ex->getMessage());
  575. return null;
  576. }
  577. if (count($view->entries) < 1) {
  578. return null;
  579. }
  580. $simplePie = customSimplePie();
  581. $simplePie->set_raw_data($view->renderToString());
  582. $simplePie->init();
  583. return $simplePie;
  584. }
  585. /**
  586. * To keep track of some new potentially unread articles since last commit+fetch from database
  587. */
  588. public function incPendingUnread(int $n = 1) {
  589. $this->nbPendingNotRead += $n;
  590. }
  591. public function keepMaxUnread() {
  592. $keepMaxUnread = $this->attributes('keep_max_n_unread');
  593. if ($keepMaxUnread == false) {
  594. $keepMaxUnread = FreshRSS_Context::$user_conf->mark_when['max_n_unread'];
  595. }
  596. if ($keepMaxUnread > 0 && $this->nbNotRead(false) + $this->nbPendingNotRead > $keepMaxUnread) {
  597. $feedDAO = FreshRSS_Factory::createFeedDao();
  598. $feedDAO->keepMaxUnread($this->id(), max(0, $keepMaxUnread - $this->nbPendingNotRead));
  599. }
  600. }
  601. /**
  602. * Remember to call updateCachedValue($id_feed) or updateCachedValues() just after
  603. */
  604. public function cleanOldEntries() {
  605. $archiving = $this->attributes('archiving');
  606. if ($archiving == null) {
  607. $catDAO = FreshRSS_Factory::createCategoryDao();
  608. $category = $catDAO->searchById($this->category());
  609. $archiving = $category == null ? null : $category->attributes('archiving');
  610. if ($archiving == null) {
  611. $archiving = FreshRSS_Context::$user_conf->archiving;
  612. }
  613. }
  614. if (is_array($archiving)) {
  615. $entryDAO = FreshRSS_Factory::createEntryDao();
  616. $nb = $entryDAO->cleanOldEntries($this->id(), $archiving);
  617. if ($nb > 0) {
  618. $needFeedCacheRefresh = true;
  619. Minz_Log::debug($nb . ' entries cleaned in feed [' . $this->url(false) . '] with: ' . json_encode($archiving));
  620. }
  621. return $nb;
  622. }
  623. return false;
  624. }
  625. public static function cacheFilename(string $url, array $attributes, int $kind = FreshRSS_Feed::KIND_RSS): string {
  626. $simplePie = customSimplePie($attributes);
  627. $filename = $simplePie->get_cache_filename($url);
  628. if ($kind == FreshRSS_Feed::KIND_HTML_XPATH) {
  629. return CACHE_PATH . '/' . $filename . '.html';
  630. } else {
  631. return CACHE_PATH . '/' . $filename . '.spc';
  632. }
  633. }
  634. public function clearCache(): bool {
  635. return @unlink(FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind));
  636. }
  637. /** @return int|false */
  638. public function cacheModifiedTime() {
  639. return @filemtime(FreshRSS_Feed::cacheFilename($this->url, $this->attributes(), $this->kind));
  640. }
  641. public function lock(): bool {
  642. $this->lockPath = TMP_PATH . '/' . $this->hash() . '.freshrss.lock';
  643. if (file_exists($this->lockPath) && ((time() - @filemtime($this->lockPath)) > 3600)) {
  644. @unlink($this->lockPath);
  645. }
  646. if (($handle = @fopen($this->lockPath, 'x')) === false) {
  647. return false;
  648. }
  649. //register_shutdown_function('unlink', $this->lockPath);
  650. @fclose($handle);
  651. return true;
  652. }
  653. public function unlock(): bool {
  654. return @unlink($this->lockPath);
  655. }
  656. /**
  657. * @return array<FreshRSS_FilterAction>
  658. */
  659. public function filterActions(): array {
  660. if (empty($this->filterActions)) {
  661. $this->filterActions = array();
  662. $filters = $this->attributes('filters');
  663. if (is_array($filters)) {
  664. foreach ($filters as $filter) {
  665. $filterAction = FreshRSS_FilterAction::fromJSON($filter);
  666. if ($filterAction != null) {
  667. $this->filterActions[] = $filterAction;
  668. }
  669. }
  670. }
  671. }
  672. return $this->filterActions;
  673. }
  674. /**
  675. * @param array<FreshRSS_FilterAction> $filterActions
  676. */
  677. private function _filterActions($filterActions) {
  678. $this->filterActions = $filterActions;
  679. if (is_array($this->filterActions) && !empty($this->filterActions)) {
  680. $this->_attributes('filters', array_map(function ($af) {
  681. return $af == null ? null : $af->toJSON();
  682. }, $this->filterActions));
  683. } else {
  684. $this->_attributes('filters', null);
  685. }
  686. }
  687. public function filtersAction(string $action) {
  688. $action = trim($action);
  689. if ($action == '') {
  690. return array();
  691. }
  692. $filters = array();
  693. $filterActions = $this->filterActions();
  694. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  695. $filterAction = $filterActions[$i];
  696. if ($filterAction != null && $filterAction->booleanSearch() != null &&
  697. $filterAction->actions() != null && in_array($action, $filterAction->actions(), true)) {
  698. $filters[] = $filterAction->booleanSearch();
  699. }
  700. }
  701. return $filters;
  702. }
  703. public function _filtersAction(string $action, $filters) {
  704. $action = trim($action);
  705. if ($action == '' || !is_array($filters)) {
  706. return false;
  707. }
  708. $filters = array_unique(array_map('trim', $filters));
  709. $filterActions = $this->filterActions();
  710. //Check existing filters
  711. for ($i = count($filterActions) - 1; $i >= 0; $i--) {
  712. $filterAction = $filterActions[$i];
  713. if ($filterAction == null || !is_array($filterAction->actions()) ||
  714. $filterAction->booleanSearch() == null || trim($filterAction->booleanSearch()->getRawInput()) == '') {
  715. array_splice($filterActions, $i, 1);
  716. continue;
  717. }
  718. $actions = $filterAction->actions();
  719. //Remove existing rules with same action
  720. for ($j = count($actions) - 1; $j >= 0; $j--) {
  721. if ($actions[$j] === $action) {
  722. array_splice($actions, $j, 1);
  723. }
  724. }
  725. //Update existing filter with new action
  726. for ($k = count($filters) - 1; $k >= 0; $k --) {
  727. $filter = $filters[$k];
  728. if ($filter === $filterAction->booleanSearch()->getRawInput()) {
  729. $actions[] = $action;
  730. array_splice($filters, $k, 1);
  731. }
  732. }
  733. //Save result
  734. if (empty($actions)) {
  735. array_splice($filterActions, $i, 1);
  736. } else {
  737. $filterAction->_actions($actions);
  738. }
  739. }
  740. //Add new filters
  741. for ($k = count($filters) - 1; $k >= 0; $k --) {
  742. $filter = $filters[$k];
  743. if ($filter != '') {
  744. $filterAction = FreshRSS_FilterAction::fromJSON(array(
  745. 'search' => $filter,
  746. 'actions' => array($action),
  747. ));
  748. if ($filterAction != null) {
  749. $filterActions[] = $filterAction;
  750. }
  751. }
  752. }
  753. if (empty($filterActions)) {
  754. $filterActions = null;
  755. }
  756. $this->_filterActions($filterActions);
  757. }
  758. //<WebSub>
  759. public function pubSubHubbubEnabled(): bool {
  760. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  761. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  762. if ($hubFile = @file_get_contents($hubFilename)) {
  763. $hubJson = json_decode($hubFile, true);
  764. if ($hubJson && empty($hubJson['error']) &&
  765. (empty($hubJson['lease_end']) || $hubJson['lease_end'] > time())) {
  766. return true;
  767. }
  768. }
  769. return false;
  770. }
  771. public function pubSubHubbubError(bool $error = true): bool {
  772. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  773. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  774. $hubFile = @file_get_contents($hubFilename);
  775. $hubJson = $hubFile ? json_decode($hubFile, true) : array();
  776. if (!isset($hubJson['error']) || $hubJson['error'] !== (bool)$error) {
  777. $hubJson['error'] = (bool)$error;
  778. file_put_contents($hubFilename, json_encode($hubJson));
  779. Minz_Log::warning('Set error to ' . ($error ? 1 : 0) . ' for ' . $url, PSHB_LOG);
  780. }
  781. return false;
  782. }
  783. /**
  784. * @return string|false
  785. */
  786. public function pubSubHubbubPrepare() {
  787. $key = '';
  788. if (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) &&
  789. $this->hubUrl && $this->selfUrl && @is_dir(PSHB_PATH)) {
  790. $path = PSHB_PATH . '/feeds/' . base64url_encode($this->selfUrl);
  791. $hubFilename = $path . '/!hub.json';
  792. if ($hubFile = @file_get_contents($hubFilename)) {
  793. $hubJson = json_decode($hubFile, true);
  794. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key'])) {
  795. $text = 'Invalid JSON for WebSub: ' . $this->url;
  796. Minz_Log::warning($text);
  797. Minz_Log::warning($text, PSHB_LOG);
  798. return false;
  799. }
  800. if ((!empty($hubJson['lease_end'])) && ($hubJson['lease_end'] < (time() + (3600 * 23)))) { //TODO: Make a better policy
  801. $text = 'WebSub lease ends at '
  802. . date('c', empty($hubJson['lease_end']) ? time() : $hubJson['lease_end'])
  803. . ' and needs renewal: ' . $this->url;
  804. Minz_Log::warning($text);
  805. Minz_Log::warning($text, PSHB_LOG);
  806. $key = $hubJson['key']; //To renew our lease
  807. } elseif (((!empty($hubJson['error'])) || empty($hubJson['lease_end'])) &&
  808. (empty($hubJson['lease_start']) || $hubJson['lease_start'] < time() - (3600 * 23))) { //Do not renew too often
  809. $key = $hubJson['key']; //To renew our lease
  810. }
  811. } else {
  812. @mkdir($path, 0777, true);
  813. $key = sha1($path . FreshRSS_Context::$system_conf->salt);
  814. $hubJson = array(
  815. 'hub' => $this->hubUrl,
  816. 'key' => $key,
  817. );
  818. file_put_contents($hubFilename, json_encode($hubJson));
  819. @mkdir(PSHB_PATH . '/keys/');
  820. file_put_contents(PSHB_PATH . '/keys/' . $key . '.txt', base64url_encode($this->selfUrl));
  821. $text = 'WebSub prepared for ' . $this->url;
  822. Minz_Log::debug($text);
  823. Minz_Log::debug($text, PSHB_LOG);
  824. }
  825. $currentUser = Minz_Session::param('currentUser');
  826. if (FreshRSS_user_Controller::checkUsername($currentUser) && !file_exists($path . '/' . $currentUser . '.txt')) {
  827. touch($path . '/' . $currentUser . '.txt');
  828. }
  829. }
  830. return $key;
  831. }
  832. //Parameter true to subscribe, false to unsubscribe.
  833. public function pubSubHubbubSubscribe(bool $state): bool {
  834. if ($state) {
  835. $url = $this->selfUrl ? $this->selfUrl : $this->url;
  836. } else {
  837. $url = $this->url; //Always use current URL during unsubscribe
  838. }
  839. if ($url && (Minz_Request::serverIsPublic(FreshRSS_Context::$system_conf->base_url) || !$state)) {
  840. $hubFilename = PSHB_PATH . '/feeds/' . base64url_encode($url) . '/!hub.json';
  841. $hubFile = @file_get_contents($hubFilename);
  842. if ($hubFile === false) {
  843. Minz_Log::warning('JSON not found for WebSub: ' . $this->url);
  844. return false;
  845. }
  846. $hubJson = json_decode($hubFile, true);
  847. if (!$hubJson || empty($hubJson['key']) || !ctype_xdigit($hubJson['key']) || empty($hubJson['hub'])) {
  848. Minz_Log::warning('Invalid JSON for WebSub: ' . $this->url);
  849. return false;
  850. }
  851. $callbackUrl = checkUrl(Minz_Request::getBaseUrl() . '/api/pshb.php?k=' . $hubJson['key']);
  852. if ($callbackUrl == '') {
  853. Minz_Log::warning('Invalid callback for WebSub: ' . $this->url);
  854. return false;
  855. }
  856. if (!$state) { //unsubscribe
  857. $hubJson['lease_end'] = time() - 60;
  858. file_put_contents($hubFilename, json_encode($hubJson));
  859. }
  860. $ch = curl_init();
  861. curl_setopt_array($ch, [
  862. CURLOPT_URL => $hubJson['hub'],
  863. CURLOPT_RETURNTRANSFER => true,
  864. CURLOPT_POSTFIELDS => http_build_query(array(
  865. 'hub.verify' => 'sync',
  866. 'hub.mode' => $state ? 'subscribe' : 'unsubscribe',
  867. 'hub.topic' => $url,
  868. 'hub.callback' => $callbackUrl,
  869. )),
  870. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  871. CURLOPT_MAXREDIRS => 10,
  872. CURLOPT_FOLLOWLOCATION => true,
  873. CURLOPT_ENCODING => '', //Enable all encodings
  874. ]);
  875. $response = curl_exec($ch);
  876. $info = curl_getinfo($ch);
  877. Minz_Log::warning('WebSub ' . ($state ? 'subscribe' : 'unsubscribe') . ' to ' . $url .
  878. ' via hub ' . $hubJson['hub'] .
  879. ' with callback ' . $callbackUrl . ': ' . $info['http_code'] . ' ' . $response, PSHB_LOG);
  880. if (substr($info['http_code'], 0, 1) == '2') {
  881. return true;
  882. } else {
  883. $hubJson['lease_start'] = time(); //Prevent trying again too soon
  884. $hubJson['error'] = true;
  885. file_put_contents($hubFilename, json_encode($hubJson));
  886. return false;
  887. }
  888. }
  889. return false;
  890. }
  891. //</WebSub>
  892. }