Feed.php 33 KB

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