Entry.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. <?php
  2. class FreshRSS_Entry extends Minz_Model {
  3. const STATE_READ = 1;
  4. const STATE_NOT_READ = 2;
  5. const STATE_ALL = 3;
  6. const STATE_FAVORITE = 4;
  7. const STATE_NOT_FAVORITE = 8;
  8. /** @var string */
  9. private $id = '0';
  10. /** @var string */
  11. private $guid;
  12. /** @var string */
  13. private $title;
  14. /** @var array<string> */
  15. private $authors;
  16. /** @var string */
  17. private $content;
  18. /** @var string */
  19. private $link;
  20. /** @var int */
  21. private $date;
  22. /** @var string In microseconds */
  23. private $date_added = '0';
  24. /** @var string */
  25. private $hash = '';
  26. /** @var bool|null */
  27. private $is_read;
  28. /** @var bool|null */
  29. private $is_favorite;
  30. /** @var int */
  31. private $feedId;
  32. /** @var FreshRSS_Feed|null */
  33. private $feed;
  34. /** @var array<string> */
  35. private $tags = [];
  36. /** @var array<string,mixed> */
  37. private $attributes = [];
  38. /**
  39. * @param int|string $pubdate
  40. * @param bool|int|null $is_read
  41. * @param bool|int|null $is_favorite
  42. * @param string|array<string> $tags
  43. */
  44. public function __construct(int $feedId = 0, string $guid = '', string $title = '', string $authors = '', string $content = '',
  45. string $link = '', $pubdate = 0, $is_read = false, $is_favorite = false, $tags = '') {
  46. $this->_title($title);
  47. $this->_authors($authors);
  48. $this->_content($content);
  49. $this->_link($link);
  50. $this->_date($pubdate);
  51. $this->_isRead($is_read);
  52. $this->_isFavorite($is_favorite);
  53. $this->_feedId($feedId);
  54. $this->_tags($tags);
  55. $this->_guid($guid);
  56. }
  57. /** @param array{'id'?:string,'id_feed'?:int,'guid'?:string,'title'?:string,'author'?:string,'content'?:string,'link'?:string,'date'?:int|string,
  58. * 'is_read'?:bool|int,'is_favorite'?:bool|int,'tags'?:string|array<string>,'attributes'?:string,'thumbnail'?:string,'timestamp'?:string} $dao */
  59. public static function fromArray(array $dao): FreshRSS_Entry {
  60. if (empty($dao['content'])) {
  61. $dao['content'] = '';
  62. }
  63. $dao['attributes'] = empty($dao['attributes']) ? [] : json_decode($dao['attributes'], true);
  64. if (!is_array($dao['attributes'])) {
  65. $dao['attributes'] = [];
  66. }
  67. if (!empty($dao['thumbnail'])) {
  68. $dao['attributes']['thumbnail'] = [
  69. 'url' => $dao['thumbnail'],
  70. ];
  71. }
  72. $entry = new FreshRSS_Entry(
  73. $dao['id_feed'] ?? 0,
  74. $dao['guid'] ?? '',
  75. $dao['title'] ?? '',
  76. $dao['author'] ?? '',
  77. $dao['content'],
  78. $dao['link'] ?? '',
  79. $dao['date'] ?? 0,
  80. $dao['is_read'] ?? false,
  81. $dao['is_favorite'] ?? false,
  82. $dao['tags'] ?? ''
  83. );
  84. if (!empty($dao['id'])) {
  85. $entry->_id($dao['id']);
  86. }
  87. if (!empty($dao['timestamp'])) {
  88. $entry->_date(strtotime($dao['timestamp']) ?: 0);
  89. }
  90. if (!empty($dao['attributes'])) {
  91. $entry->_attributes('', $dao['attributes']);
  92. }
  93. return $entry;
  94. }
  95. public function id(): string {
  96. return $this->id;
  97. }
  98. public function guid(): string {
  99. return $this->guid;
  100. }
  101. public function title(): string {
  102. return $this->title == '' ? $this->guid() : $this->title;
  103. }
  104. /** @deprecated */
  105. public function author(): string {
  106. return $this->authors(true);
  107. }
  108. /**
  109. * @phpstan-return ($asString is true ? string : array<string>)
  110. * @return string|array<string>
  111. */
  112. public function authors(bool $asString = false) {
  113. if ($asString) {
  114. return $this->authors == null ? '' : ';' . implode('; ', $this->authors);
  115. } else {
  116. return $this->authors;
  117. }
  118. }
  119. /**
  120. * Basic test without ambition to catch all cases such as unquoted addresses, variants of entities, HTML comments, etc.
  121. */
  122. private static function containsLink(string $html, string $link): bool {
  123. return preg_match('/(?P<delim>[\'"])' . preg_quote($link, '/') . '(?P=delim)/', $html) == 1;
  124. }
  125. /** @param array{'url'?:string,'length'?:int,'medium'?:string,'type'?:string} $enclosure */
  126. private static function enclosureIsImage(array $enclosure): bool {
  127. $elink = $enclosure['url'] ?? '';
  128. $length = $enclosure['length'] ?? 0;
  129. $medium = $enclosure['medium'] ?? '';
  130. $mime = $enclosure['type'] ?? '';
  131. return $elink != '' && $medium === 'image' || strpos($mime, 'image') === 0 ||
  132. ($mime == '' && $length == 0 && preg_match('/[.](avif|gif|jpe?g|png|svg|webp)$/i', $elink));
  133. }
  134. /**
  135. * @param bool $withEnclosures Set to true to include the enclosures in the returned HTML, false otherwise.
  136. * @param bool $allowDuplicateEnclosures Set to false to remove obvious enclosure duplicates (based on simple string comparison), true otherwise.
  137. * @return string HTML content
  138. */
  139. public function content(bool $withEnclosures = true, bool $allowDuplicateEnclosures = false): string {
  140. if (!$withEnclosures) {
  141. return $this->content;
  142. }
  143. $content = $this->content;
  144. $thumbnailAttribute = $this->attributes('thumbnail');
  145. if (!empty($thumbnailAttribute['url'])) {
  146. $elink = $thumbnailAttribute['url'];
  147. if ($allowDuplicateEnclosures || !self::containsLink($content, $elink)) {
  148. $content .= <<<HTML
  149. <figure class="enclosure">
  150. <p class="enclosure-content">
  151. <img class="enclosure-thumbnail" src="{$elink}" alt="" />
  152. </p>
  153. </figure>
  154. HTML;
  155. }
  156. }
  157. $attributeEnclosures = $this->attributes('enclosures');
  158. if (empty($attributeEnclosures)) {
  159. return $content;
  160. }
  161. foreach ($attributeEnclosures as $enclosure) {
  162. $elink = $enclosure['url'] ?? '';
  163. if ($elink == '') {
  164. continue;
  165. }
  166. if (!$allowDuplicateEnclosures && self::containsLink($content, $elink)) {
  167. continue;
  168. }
  169. $credit = $enclosure['credit'] ?? '';
  170. $description = $enclosure['description'] ?? '';
  171. $length = $enclosure['length'] ?? 0;
  172. $medium = $enclosure['medium'] ?? '';
  173. $mime = $enclosure['type'] ?? '';
  174. $thumbnails = $enclosure['thumbnails'] ?? [];
  175. $etitle = $enclosure['title'] ?? '';
  176. $content .= "\n";
  177. $content .= '<figure class="enclosure">';
  178. foreach ($thumbnails as $thumbnail) {
  179. $content .= '<p><img class="enclosure-thumbnail" src="' . $thumbnail . '" alt="" title="' . $etitle . '" /></p>';
  180. }
  181. if (self::enclosureIsImage($enclosure)) {
  182. $content .= '<p class="enclosure-content"><img src="' . $elink . '" alt="" title="' . $etitle . '" /></p>';
  183. } elseif ($medium === 'audio' || strpos($mime, 'audio') === 0) {
  184. $content .= '<p class="enclosure-content"><audio preload="none" src="' . $elink
  185. . ($length == null ? '' : '" data-length="' . intval($length))
  186. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  187. . '" controls="controls" title="' . $etitle . '"></audio> <a download="" href="' . $elink . '">💾</a></p>';
  188. } elseif ($medium === 'video' || strpos($mime, 'video') === 0) {
  189. $content .= '<p class="enclosure-content"><video preload="none" src="' . $elink
  190. . ($length == null ? '' : '" data-length="' . intval($length))
  191. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  192. . '" controls="controls" title="' . $etitle . '"></video> <a download="" href="' . $elink . '">💾</a></p>';
  193. } else { //e.g. application, text, unknown
  194. $content .= '<p class="enclosure-content"><a download="" href="' . $elink
  195. . ($mime == '' ? '' : '" data-type="' . htmlspecialchars($mime, ENT_COMPAT, 'UTF-8'))
  196. . ($medium == '' ? '' : '" data-medium="' . htmlspecialchars($medium, ENT_COMPAT, 'UTF-8'))
  197. . '" title="' . $etitle . '">💾</a></p>';
  198. }
  199. if ($credit != '') {
  200. $content .= '<p class="enclosure-credits">© ' . $credit . '</p>';
  201. }
  202. if ($description != '') {
  203. $content .= '<figcaption class="enclosure-description">' . $description . '</figcaption>';
  204. }
  205. $content .= "</figure>\n";
  206. }
  207. return $content;
  208. }
  209. /** @return Traversable<array{'url':string,'type'?:string,'medium'?:string,'length'?:int,'title'?:string,'description'?:string,'credit'?:string,'height'?:int,'width'?:int,'thumbnails'?:array<string>}> */
  210. public function enclosures(bool $searchBodyImages = false): Traversable {
  211. $attributeEnclosures = $this->attributes('enclosures');
  212. if (is_array($attributeEnclosures)) {
  213. // FreshRSS 1.20.1+: The enclosures are saved as attributes
  214. yield from $attributeEnclosures;
  215. }
  216. try {
  217. $searchEnclosures = !is_array($attributeEnclosures) && (strpos($this->content, '<p class="enclosure-content') !== false);
  218. $searchBodyImages &= (stripos($this->content, '<img') !== false);
  219. $xpath = null;
  220. if ($searchEnclosures || $searchBodyImages) {
  221. $dom = new DOMDocument();
  222. $dom->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $this->content, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  223. $xpath = new DOMXPath($dom);
  224. }
  225. if ($searchEnclosures) {
  226. // Legacy code for database entries < FreshRSS 1.20.1
  227. $enclosures = $xpath->query('//div[@class="enclosure"]/p[@class="enclosure-content"]/*[@src]');
  228. if (!empty($enclosures)) {
  229. /** @var DOMElement $enclosure */
  230. foreach ($enclosures as $enclosure) {
  231. $result = [
  232. 'url' => $enclosure->getAttribute('src'),
  233. 'type' => $enclosure->getAttribute('data-type'),
  234. 'medium' => $enclosure->getAttribute('data-medium'),
  235. 'length' => (int)($enclosure->getAttribute('data-length')),
  236. ];
  237. if (empty($result['medium'])) {
  238. switch (strtolower($enclosure->nodeName)) {
  239. case 'img': $result['medium'] = 'image'; break;
  240. case 'video': $result['medium'] = 'video'; break;
  241. case 'audio': $result['medium'] = 'audio'; break;
  242. }
  243. }
  244. yield Minz_Helper::htmlspecialchars_utf8($result);
  245. }
  246. }
  247. }
  248. if ($searchBodyImages) {
  249. $images = $xpath->query('//img');
  250. if (!empty($images)) {
  251. /** @var DOMElement $img */
  252. foreach ($images as $img) {
  253. $src = $img->getAttribute('src');
  254. if ($src == null) {
  255. $src = $img->getAttribute('data-src');
  256. }
  257. if ($src != null) {
  258. $result = [
  259. 'url' => $src,
  260. ];
  261. yield Minz_Helper::htmlspecialchars_utf8($result);
  262. }
  263. }
  264. }
  265. }
  266. } catch (Exception $ex) {
  267. Minz_Log::debug(__METHOD__ . ' ' . $ex->getMessage());
  268. }
  269. }
  270. /**
  271. * @return array{'url':string,'type'?:string,'medium'?:string,'length'?:int,'title'?:string,'description'?:string,'credit'?:string,'height'?:int,'width'?:int,'thumbnails'?:array<string>}|null
  272. */
  273. public function thumbnail(bool $searchEnclosures = true): ?array {
  274. $thumbnail = $this->attributes('thumbnail');
  275. if (!empty($thumbnail['url'])) {
  276. return $thumbnail;
  277. }
  278. if ($searchEnclosures) {
  279. foreach ($this->enclosures(true) as $enclosure) {
  280. if (self::enclosureIsImage($enclosure)) {
  281. return $enclosure;
  282. }
  283. }
  284. }
  285. return null;
  286. }
  287. /** @return string HTML-encoded link of the entry */
  288. public function link(): string {
  289. return $this->link;
  290. }
  291. /**
  292. * @phpstan-return ($raw is false ? string : int)
  293. * @return string|int
  294. */
  295. public function date(bool $raw = false) {
  296. if ($raw) {
  297. return $this->date;
  298. }
  299. return timestamptodate($this->date);
  300. }
  301. public function machineReadableDate(): string {
  302. return @date (DATE_ATOM, $this->date);
  303. }
  304. /**
  305. * @phpstan-return ($raw is false ? string : ($microsecond is true ? string : int))
  306. * @return int|string
  307. */
  308. public function dateAdded(bool $raw = false, bool $microsecond = false) {
  309. if ($raw) {
  310. if ($microsecond) {
  311. return $this->date_added;
  312. } else {
  313. return intval(substr($this->date_added, 0, -6));
  314. }
  315. } else {
  316. $date = intval(substr($this->date_added, 0, -6));
  317. return timestamptodate($date);
  318. }
  319. }
  320. public function isRead(): ?bool {
  321. return $this->is_read;
  322. }
  323. public function isFavorite(): ?bool {
  324. return $this->is_favorite;
  325. }
  326. public function feed(): ?FreshRSS_Feed {
  327. if ($this->feed === null) {
  328. $feedDAO = FreshRSS_Factory::createFeedDao();
  329. $this->feed = $feedDAO->searchById($this->feedId);
  330. }
  331. return $this->feed;
  332. }
  333. public function feedId(): int {
  334. return $this->feedId;
  335. }
  336. /**
  337. * @phpstan-return ($asString is true ? string : array<string>)
  338. * @return string|array<string>
  339. */
  340. public function tags(bool $asString = false) {
  341. if ($asString) {
  342. return $this->tags == null ? '' : '#' . implode(' #', $this->tags);
  343. } else {
  344. return $this->tags;
  345. }
  346. }
  347. /**
  348. * @phpstan-return ($key is non-empty-string ? mixed : array<string,mixed>)
  349. * @return array<string,mixed>|mixed|null
  350. */
  351. public function attributes(string $key = '') {
  352. if ($key === '') {
  353. return $this->attributes;
  354. } else {
  355. return $this->attributes[$key] ?? null;
  356. }
  357. }
  358. /** @param string|array<mixed>|bool|int|null $value Value, not HTML-encoded */
  359. public function _attributes(string $key, $value): void {
  360. if ($key == '') {
  361. if (is_string($value)) {
  362. $value = json_decode($value, true);
  363. }
  364. if (is_array($value)) {
  365. $this->attributes = $value;
  366. }
  367. } elseif ($value === null) {
  368. unset($this->attributes[$key]);
  369. } else {
  370. $this->attributes[$key] = $value;
  371. }
  372. }
  373. public function hash(): string {
  374. if ($this->hash == '') {
  375. //Do not include $this->date because it may be automatically generated when lacking
  376. $this->hash = md5($this->link . $this->title . $this->authors(true) . $this->content . $this->tags(true));
  377. }
  378. return $this->hash;
  379. }
  380. public function _hash(string $value): string {
  381. $value = trim($value);
  382. if (ctype_xdigit($value)) {
  383. $this->hash = substr($value, 0, 32);
  384. }
  385. return $this->hash;
  386. }
  387. public function _id(string $value): void {
  388. $this->id = $value;
  389. if ($this->date_added == 0) {
  390. $this->date_added = $value;
  391. }
  392. }
  393. public function _guid(string $value): void {
  394. if ($value == '') {
  395. $value = $this->link;
  396. if ($value == '') {
  397. $value = $this->hash();
  398. }
  399. }
  400. $this->guid = $value;
  401. }
  402. public function _title(string $value): void {
  403. $this->hash = '';
  404. $this->title = trim($value);
  405. }
  406. /** @deprecated */
  407. public function _author(string $value): void {
  408. $this->_authors($value);
  409. }
  410. /** @param array<string>|string $value */
  411. public function _authors($value): void {
  412. $this->hash = '';
  413. if (!is_array($value)) {
  414. if (strpos($value, ';') !== false) {
  415. $value = htmlspecialchars_decode($value, ENT_QUOTES);
  416. $value = preg_split('/\s*[;]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  417. $value = Minz_Helper::htmlspecialchars_utf8($value);
  418. } else {
  419. $value = preg_split('/\s*[,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  420. }
  421. }
  422. $this->authors = $value;
  423. }
  424. public function _content(string $value): void {
  425. $this->hash = '';
  426. $this->content = $value;
  427. }
  428. public function _link(string $value): void {
  429. $this->hash = '';
  430. $this->link = $value;
  431. }
  432. /** @param int|string $value */
  433. public function _date($value): void {
  434. $this->hash = '';
  435. $value = intval($value);
  436. $this->date = $value > 1 ? $value : time();
  437. }
  438. /** @param int|string $value */
  439. public function _dateAdded($value, bool $microsecond = false): void {
  440. if ($microsecond) {
  441. $this->date_added = (string)($value);
  442. } else {
  443. $this->date_added = $value . '000000';
  444. }
  445. }
  446. /** @param bool|int|null $value */
  447. public function _isRead($value): void {
  448. $this->is_read = $value === null ? null : (bool)$value;
  449. }
  450. /** @param bool|int|null $value */
  451. public function _isFavorite($value): void {
  452. $this->is_favorite = $value === null ? null : (bool)$value;
  453. }
  454. public function _feed(?FreshRSS_Feed $feed): void {
  455. $this->feed = $feed;
  456. $this->feedId = $this->feed == null ? 0 : $this->feed->id();
  457. }
  458. /** @param int|string $id */
  459. private function _feedId($id): void {
  460. $this->feed = null;
  461. $this->feedId = intval($id);
  462. }
  463. /** @param array<string>|string $value */
  464. public function _tags($value): void {
  465. $this->hash = '';
  466. if (!is_array($value)) {
  467. $value = preg_split('/\s*[#,]\s*/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
  468. }
  469. $this->tags = $value;
  470. }
  471. public function matches(FreshRSS_BooleanSearch $booleanSearch): bool {
  472. $ok = true;
  473. foreach ($booleanSearch->searches() as $filter) {
  474. if ($filter instanceof FreshRSS_BooleanSearch) {
  475. // BooleanSearches are combined by AND (default) or OR or AND NOT (special cases) operators and are recursive
  476. if ($filter->operator() === 'OR') {
  477. $ok |= $this->matches($filter);
  478. } elseif ($filter->operator() === 'AND NOT') {
  479. $ok &= !$this->matches($filter);
  480. } else { // AND
  481. $ok &= $this->matches($filter);
  482. }
  483. } elseif ($filter instanceof FreshRSS_Search) {
  484. // Searches are combined by OR and are not recursive
  485. $ok = true;
  486. if ($filter->getEntryIds()) {
  487. $ok &= in_array($this->id, $filter->getEntryIds(), true);
  488. }
  489. if ($ok && $filter->getNotEntryIds()) {
  490. $ok &= !in_array($this->id, $filter->getNotEntryIds(), true);
  491. }
  492. if ($ok && $filter->getMinDate()) {
  493. $ok &= strnatcmp($this->id, $filter->getMinDate() . '000000') >= 0;
  494. }
  495. if ($ok && $filter->getNotMinDate()) {
  496. $ok &= strnatcmp($this->id, $filter->getNotMinDate() . '000000') < 0;
  497. }
  498. if ($ok && $filter->getMaxDate()) {
  499. $ok &= strnatcmp($this->id, $filter->getMaxDate() . '000000') <= 0;
  500. }
  501. if ($ok && $filter->getNotMaxDate()) {
  502. $ok &= strnatcmp($this->id, $filter->getNotMaxDate() . '000000') > 0;
  503. }
  504. if ($ok && $filter->getMinPubdate()) {
  505. $ok &= $this->date >= $filter->getMinPubdate();
  506. }
  507. if ($ok && $filter->getNotMinPubdate()) {
  508. $ok &= $this->date < $filter->getNotMinPubdate();
  509. }
  510. if ($ok && $filter->getMaxPubdate()) {
  511. $ok &= $this->date <= $filter->getMaxPubdate();
  512. }
  513. if ($ok && $filter->getNotMaxPubdate()) {
  514. $ok &= $this->date > $filter->getNotMaxPubdate();
  515. }
  516. if ($ok && $filter->getFeedIds()) {
  517. $ok &= in_array($this->feedId, $filter->getFeedIds(), true);
  518. }
  519. if ($ok && $filter->getNotFeedIds()) {
  520. $ok &= !in_array($this->feedId, $filter->getFeedIds(), true);
  521. }
  522. if ($ok && $filter->getAuthor()) {
  523. foreach ($filter->getAuthor() as $author) {
  524. $ok &= stripos(implode(';', $this->authors), $author) !== false;
  525. }
  526. }
  527. if ($ok && $filter->getNotAuthor()) {
  528. foreach ($filter->getNotAuthor() as $author) {
  529. $ok &= stripos(implode(';', $this->authors), $author) === false;
  530. }
  531. }
  532. if ($ok && $filter->getIntitle()) {
  533. foreach ($filter->getIntitle() as $title) {
  534. $ok &= stripos($this->title, $title) !== false;
  535. }
  536. }
  537. if ($ok && $filter->getNotIntitle()) {
  538. foreach ($filter->getNotIntitle() as $title) {
  539. $ok &= stripos($this->title, $title) === false;
  540. }
  541. }
  542. if ($ok && $filter->getTags()) {
  543. foreach ($filter->getTags() as $tag2) {
  544. $found = false;
  545. foreach ($this->tags as $tag1) {
  546. if (strcasecmp($tag1, $tag2) === 0) {
  547. $found = true;
  548. }
  549. }
  550. $ok &= $found;
  551. }
  552. }
  553. if ($ok && $filter->getNotTags()) {
  554. foreach ($filter->getNotTags() as $tag2) {
  555. $found = false;
  556. foreach ($this->tags as $tag1) {
  557. if (strcasecmp($tag1, $tag2) === 0) {
  558. $found = true;
  559. }
  560. }
  561. $ok &= !$found;
  562. }
  563. }
  564. if ($ok && $filter->getInurl()) {
  565. foreach ($filter->getInurl() as $url) {
  566. $ok &= stripos($this->link, $url) !== false;
  567. }
  568. }
  569. if ($ok && $filter->getNotInurl()) {
  570. foreach ($filter->getNotInurl() as $url) {
  571. $ok &= stripos($this->link, $url) === false;
  572. }
  573. }
  574. if ($ok && $filter->getSearch()) {
  575. foreach ($filter->getSearch() as $needle) {
  576. $ok &= (stripos($this->title, $needle) !== false || stripos($this->content, $needle) !== false);
  577. }
  578. }
  579. if ($ok && $filter->getNotSearch()) {
  580. foreach ($filter->getNotSearch() as $needle) {
  581. $ok &= (stripos($this->title, $needle) === false && stripos($this->content, $needle) === false);
  582. }
  583. }
  584. if ($ok) {
  585. return true;
  586. }
  587. }
  588. }
  589. return (bool)$ok;
  590. }
  591. /** @param array<string,bool> $titlesAsRead */
  592. public function applyFilterActions(array $titlesAsRead = []): void {
  593. if ($this->feed != null) {
  594. if ($this->feed->attributes('read_upon_reception') ||
  595. ($this->feed->attributes('read_upon_reception') === null && FreshRSS_Context::$user_conf->mark_when['reception'])) {
  596. $this->_isRead(true);
  597. }
  598. if (!empty($titlesAsRead[$this->title()])) {
  599. Minz_Log::debug('Mark title as read: ' . $this->title());
  600. $this->_isRead(true);
  601. }
  602. foreach ($this->feed->filterActions() as $filterAction) {
  603. if ($this->matches($filterAction->booleanSearch())) {
  604. foreach ($filterAction->actions() as $action) {
  605. switch ($action) {
  606. case 'read':
  607. $this->_isRead(true);
  608. break;
  609. case 'star':
  610. $this->_isFavorite(true);
  611. break;
  612. case 'label':
  613. //TODO: Implement more actions
  614. break;
  615. }
  616. }
  617. }
  618. }
  619. }
  620. }
  621. public function isDay(int $day, int $today): bool {
  622. $date = $this->dateAdded(true);
  623. switch ($day) {
  624. case FreshRSS_Days::TODAY:
  625. $tomorrow = $today + 86400;
  626. return $date >= $today && $date < $tomorrow;
  627. case FreshRSS_Days::YESTERDAY:
  628. $yesterday = $today - 86400;
  629. return $date >= $yesterday && $date < $today;
  630. case FreshRSS_Days::BEFORE_YESTERDAY:
  631. $yesterday = $today - 86400;
  632. return $date < $yesterday;
  633. default:
  634. return false;
  635. }
  636. }
  637. /**
  638. * @param array<string,mixed> $attributes
  639. */
  640. public static function getContentByParsing(string $url, string $path, array $attributes = [], int $maxRedirs = 3): string {
  641. $cachePath = FreshRSS_Feed::cacheFilename($url, $attributes, FreshRSS_Feed::KIND_HTML_XPATH);
  642. $html = httpGet($url, $cachePath, 'html', $attributes);
  643. if (strlen($html) > 0) {
  644. $doc = new DOMDocument();
  645. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  646. $xpath = new DOMXPath($doc);
  647. if ($maxRedirs > 0) {
  648. //Follow any HTML redirection
  649. $metas = $xpath->query('//meta[@content]');
  650. /** @var array<DOMElement> $metas */
  651. foreach ($metas as $meta) {
  652. if (strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
  653. $refresh = preg_replace('/^[0-9.; ]*\s*(url\s*=)?\s*/i', '', trim($meta->getAttribute('content')));
  654. $refresh = SimplePie_Misc::absolutize_url($refresh, $url);
  655. if ($refresh != false && $refresh !== $url) {
  656. return self::getContentByParsing($refresh, $path, $attributes, $maxRedirs - 1);
  657. }
  658. }
  659. }
  660. }
  661. $base = $xpath->evaluate('normalize-space(//base/@href)');
  662. if ($base == false || !is_string($base)) {
  663. $base = $url;
  664. } elseif (substr($base, 0, 2) === '//') {
  665. //Protocol-relative URLs "//www.example.net"
  666. $base = (parse_url($url, PHP_URL_SCHEME) ?? 'https') . ':' . $base;
  667. }
  668. $content = '';
  669. $nodes = $xpath->query(new Gt\CssXPath\Translator($path));
  670. if ($nodes != false) {
  671. foreach ($nodes as $node) {
  672. if (!empty($attributes['path_entries_filter'])) {
  673. $filterednodes = $xpath->query(new Gt\CssXPath\Translator($attributes['path_entries_filter']), $node) ?: [];
  674. foreach ($filterednodes as $filterednode) {
  675. $filterednode->parentNode->removeChild($filterednode);
  676. }
  677. }
  678. $content .= $doc->saveHTML($node) . "\n";
  679. }
  680. }
  681. $html = trim(sanitizeHTML($content, $base));
  682. return $html;
  683. } else {
  684. throw new Exception();
  685. }
  686. }
  687. public function loadCompleteContent(bool $force = false): bool {
  688. // Gestion du contenu
  689. // Trying to fetch full article content even when feeds do not propose it
  690. $feed = $this->feed();
  691. if ($feed != null && trim($feed->pathEntries()) != '') {
  692. $entryDAO = FreshRSS_Factory::createEntryDao();
  693. $entry = $force ? null : $entryDAO->searchByGuid($this->feedId, $this->guid);
  694. if ($entry) {
  695. // l’article existe déjà en BDD, en se contente de recharger ce contenu
  696. $this->content = $entry->content(false);
  697. } else {
  698. try {
  699. // The article is not yet in the database, so let’s fetch it
  700. $fullContent = self::getContentByParsing(
  701. htmlspecialchars_decode($this->link(), ENT_QUOTES),
  702. htmlspecialchars_decode($feed->pathEntries(), ENT_QUOTES),
  703. $feed->attributes()
  704. );
  705. if ('' !== $fullContent) {
  706. $fullContent = "<!-- FULLCONTENT start //-->{$fullContent}<!-- FULLCONTENT end //-->";
  707. $originalContent = preg_replace('#<!-- FULLCONTENT start //-->.*<!-- FULLCONTENT end //-->#s', '', $this->content());
  708. switch ($feed->attributes('content_action')) {
  709. case 'prepend':
  710. $this->content = $fullContent . $originalContent;
  711. break;
  712. case 'append':
  713. $this->content = $originalContent . $fullContent;
  714. break;
  715. case 'replace':
  716. default:
  717. $this->content = $fullContent;
  718. break;
  719. }
  720. return true;
  721. }
  722. } catch (Exception $e) {
  723. // rien à faire, on garde l’ancien contenu(requête a échoué)
  724. Minz_Log::warning($e->getMessage());
  725. }
  726. }
  727. }
  728. return false;
  729. }
  730. /**
  731. * @return array{'id':string,'guid':string,'title':string,'author':string,'content':string,'link':string,'date':int,
  732. * 'hash':string,'is_read':?bool,'is_favorite':?bool,'id_feed':int,'tags':string,'attributes':array<string,mixed>}
  733. */
  734. public function toArray(): array {
  735. return array(
  736. 'id' => $this->id(),
  737. 'guid' => $this->guid(),
  738. 'title' => $this->title(),
  739. 'author' => $this->authors(true),
  740. 'content' => $this->content(false),
  741. 'link' => $this->link(),
  742. 'date' => $this->date(true),
  743. 'hash' => $this->hash(),
  744. 'is_read' => $this->isRead(),
  745. 'is_favorite' => $this->isFavorite(),
  746. 'id_feed' => $this->feedId(),
  747. 'tags' => $this->tags(true),
  748. 'attributes' => $this->attributes(),
  749. );
  750. }
  751. /**
  752. * Integer format conversion for Google Reader API format
  753. * @param string|int $dec Decimal number
  754. * @return string 64-bit hexa http://code.google.com/p/google-reader-api/wiki/ItemId
  755. */
  756. private static function dec2hex($dec): string {
  757. return PHP_INT_SIZE < 8 ? // 32-bit ?
  758. str_pad(gmp_strval(gmp_init($dec, 10), 16), 16, '0', STR_PAD_LEFT) :
  759. str_pad(dechex((int)($dec)), 16, '0', STR_PAD_LEFT);
  760. }
  761. /**
  762. * Some clients (tested with News+) would fail if sending too long item content
  763. * @var int
  764. */
  765. const API_MAX_COMPAT_CONTENT_LENGTH = 500000;
  766. /**
  767. * N.B.: To avoid expensive lookups, ensure to set `$entry->_feed($feed)` before calling this function.
  768. * N.B.: You might have to populate `$entry->_tags()` prior to calling this function.
  769. * @param string $mode Set to `'compat'` to use an alternative Unicode representation for problematic HTML special characters not decoded by some clients;
  770. * set to `'freshrss'` for using FreshRSS additions for internal use (e.g. export/import).
  771. * @return array<string,mixed> A representation of this entry in a format compatible with Google Reader API
  772. */
  773. public function toGReader(string $mode = ''): array {
  774. $feed = $this->feed();
  775. $category = $feed == null ? null : $feed->category();
  776. $item = [
  777. 'id' => 'tag:google.com,2005:reader/item/' . self::dec2hex($this->id()),
  778. 'crawlTimeMsec' => substr($this->dateAdded(true, true), 0, -3),
  779. 'timestampUsec' => '' . $this->dateAdded(true, true), //EasyRSS & Reeder
  780. 'published' => $this->date(true),
  781. // 'updated' => $this->date(true),
  782. 'title' => $this->title(),
  783. 'canonical' => [
  784. ['href' => htmlspecialchars_decode($this->link(), ENT_QUOTES)],
  785. ],
  786. 'alternate' => [
  787. [
  788. 'href' => htmlspecialchars_decode($this->link(), ENT_QUOTES),
  789. 'type' => 'text/html',
  790. ],
  791. ],
  792. 'categories' => [
  793. 'user/-/state/com.google/reading-list',
  794. ],
  795. 'origin' => [
  796. 'streamId' => 'feed/' . $this->feedId,
  797. ],
  798. ];
  799. if ($mode === 'compat') {
  800. $item['title'] = escapeToUnicodeAlternative($this->title(), false);
  801. unset($item['alternate'][0]['type']);
  802. $item['summary'] = [
  803. 'content' => mb_strcut($this->content(true), 0, self::API_MAX_COMPAT_CONTENT_LENGTH, 'UTF-8'),
  804. ];
  805. } else {
  806. $item['content'] = [
  807. 'content' => $this->content(false),
  808. ];
  809. }
  810. if ($mode === 'freshrss') {
  811. $item['guid'] = $this->guid();
  812. }
  813. if ($category != null && $mode !== 'freshrss') {
  814. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($category->name(), ENT_QUOTES);
  815. }
  816. if ($feed != null) {
  817. $item['origin']['htmlUrl'] = htmlspecialchars_decode($feed->website());
  818. $item['origin']['title'] = $feed->name(); //EasyRSS
  819. if ($mode === 'compat') {
  820. $item['origin']['title'] = escapeToUnicodeAlternative($feed->name(), true);
  821. } elseif ($mode === 'freshrss') {
  822. $item['origin']['feedUrl'] = htmlspecialchars_decode($feed->url());
  823. }
  824. }
  825. foreach ($this->enclosures() as $enclosure) {
  826. if (!empty($enclosure['url'])) {
  827. $media = [
  828. 'href' => $enclosure['url'],
  829. 'type' => $enclosure['type'] ?? $enclosure['medium'] ??
  830. (self::enclosureIsImage($enclosure) ? 'image' : ''),
  831. ];
  832. if (!empty($enclosure['length'])) {
  833. $media['length'] = intval($enclosure['length']);
  834. }
  835. $item['enclosure'][] = $media;
  836. }
  837. }
  838. $author = $this->authors(true);
  839. $author = trim($author, '; ');
  840. if ($author != '') {
  841. if ($mode === 'compat') {
  842. $item['author'] = escapeToUnicodeAlternative($author, false);
  843. } else {
  844. $item['author'] = $author;
  845. }
  846. }
  847. if ($this->isRead()) {
  848. $item['categories'][] = 'user/-/state/com.google/read';
  849. } elseif ($mode === 'freshrss') {
  850. $item['categories'][] = 'user/-/state/com.google/unread';
  851. }
  852. if ($this->isFavorite()) {
  853. $item['categories'][] = 'user/-/state/com.google/starred';
  854. }
  855. foreach ($this->tags() as $tagName) {
  856. $item['categories'][] = 'user/-/label/' . htmlspecialchars_decode($tagName, ENT_QUOTES);
  857. }
  858. return $item;
  859. }
  860. }