Entry.php 29 KB

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