Entry.php 29 KB

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