BooleanSearch.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Contains Boolean search from the search form.
  5. */
  6. class FreshRSS_BooleanSearch implements \Stringable {
  7. private string $raw_input = '';
  8. /** @var list<FreshRSS_BooleanSearch|FreshRSS_Search> */
  9. private array $searches = [];
  10. /**
  11. * @param string $input
  12. * @param int $level
  13. * @param 'AND'|'OR'|'AND NOT'|'OR NOT' $operator
  14. * @param bool $allowUserQueries
  15. * @throws Minz_BadRequestException if the search is too long or if the parentheses are nested too deeply
  16. */
  17. public function __construct(
  18. string $input,
  19. int $level = 0,
  20. private readonly string $operator = 'AND',
  21. bool $allowUserQueries = true,
  22. bool $expandUserQueries = true
  23. ) {
  24. $input = trim($input);
  25. $input = ltrim($input, ' )');
  26. $input = rtrim($input, ' (\\');
  27. if ($input === '') {
  28. return;
  29. }
  30. $this->raw_input = $input;
  31. if ($level === 0) {
  32. if (strlen($input) > FreshRSS_Context::systemConf()->limits['max_search_length']) {
  33. throw new Minz_BadRequestException('Search is too long!');
  34. }
  35. $input = self::escapeLiterals($input);
  36. if ($expandUserQueries || !$allowUserQueries) {
  37. $input = $this->parseUserQueryNames($input, $allowUserQueries);
  38. $input = $this->parseUserQueryIds($input, $allowUserQueries);
  39. }
  40. $input = trim($input);
  41. }
  42. $input = self::consistentOrParentheses($input);
  43. // Either parse everything as a series of BooleanSearch’s combined by implicit AND
  44. // or parse everything as a series of Search’s combined by explicit OR
  45. $this->parseParentheses($input, $level) || $this->parseOrSegments($input);
  46. }
  47. public function __clone() {
  48. foreach ($this->searches as $key => $search) {
  49. $this->searches[$key] = clone $search;
  50. }
  51. $this->expanded = null;
  52. $this->notExpanded = null;
  53. }
  54. /**
  55. * Parse the user queries (saved searches) by name and expand them in the input string.
  56. */
  57. private function parseUserQueryNames(string $input, bool $allowUserQueries = true): string {
  58. $all_matches = [];
  59. if (preg_match_all('/\bsearch:(?P<delim>[\'"])(?P<search>.*)(?P=delim)/U', $input, $matchesFound)) {
  60. $all_matches[] = $matchesFound;
  61. }
  62. if (preg_match_all('/\bsearch:(?P<search>(?:[^\s"\'()]|(?<=\\\\)[()])*)/', $input, $matchesFound)) {
  63. $all_matches[] = $matchesFound;
  64. }
  65. if (!empty($all_matches)) {
  66. $queries = [];
  67. foreach (FreshRSS_Context::userConf()->queries as $raw_query) {
  68. if (($raw_query['name'] ?? '') !== '' && ($raw_query['search'] ?? '') !== '') {
  69. $queries[$raw_query['name']] = trim($raw_query['search']);
  70. }
  71. }
  72. $fromS = [];
  73. $toS = [];
  74. foreach ($all_matches as $matches) {
  75. for ($i = count($matches['search']) - 1; $i >= 0; $i--) {
  76. $name = trim($matches['search'][$i]);
  77. $name = self::unescapeLiterals($name);
  78. $fromS[] = $matches[0][$i];
  79. if ($allowUserQueries && !empty($queries[$name])) {
  80. $toS[] = '(' . self::escapeLiterals($queries[$name]) . ')';
  81. } else {
  82. $toS[] = '';
  83. }
  84. }
  85. }
  86. $input = strtr($input, array_combine($fromS, $toS));
  87. }
  88. return $input;
  89. }
  90. /**
  91. * Parse the user queries (saved searches) by ID and expand them in the input string.
  92. */
  93. private function parseUserQueryIds(string $input, bool $allowUserQueries = true): string {
  94. $all_matches = [];
  95. if (preg_match_all('/\bS:(?P<search>[0-9,]+)/', $input, $matchesFound)) {
  96. $all_matches[] = $matchesFound;
  97. }
  98. if (!empty($all_matches)) {
  99. $queries = [];
  100. foreach (FreshRSS_Context::userConf()->queries as $raw_query) {
  101. $queries[] = trim($raw_query['search'] ?? '');
  102. }
  103. $fromS = [];
  104. $toS = [];
  105. foreach ($all_matches as $matches) {
  106. if (empty($matches['search'])) { // @phpstan-ignore empty.offset (for additional safety)
  107. continue;
  108. }
  109. for ($i = count($matches['search']) - 1; $i >= 0; $i--) {
  110. $ids = explode(',', $matches['search'][$i]);
  111. $ids = array_map('intval', $ids);
  112. $matchedQueries = [];
  113. foreach ($ids as $id) {
  114. if (!empty($queries[$id])) {
  115. $matchedQueries[] = $queries[$id];
  116. }
  117. }
  118. $fromS[] = $matches[0][$i];
  119. if ($allowUserQueries && !empty($matchedQueries)) {
  120. $escapedQueries = array_map(fn(string $query): string => self::escapeLiterals($query), $matchedQueries);
  121. $toS[] = '((' . implode(') OR (', $escapedQueries) . '))';
  122. } else {
  123. $toS[] = '';
  124. }
  125. }
  126. }
  127. $input = strtr($input, array_combine($fromS, $toS));
  128. }
  129. return $input;
  130. }
  131. /**
  132. * Temporarily escape parentheses and 'OR' used in regex expressions or inside "quoted strings".
  133. */
  134. public static function escapeLiterals(string $input): string {
  135. return preg_replace_callback('%(?<=[\\s(:#!-]|^)(?<![\\\\])(?P<delim>[\'"/]).+?(?<!\\\\)(?P=delim)[im]*%',
  136. function (array $matches): string {
  137. $match = $matches[0];
  138. $match = str_replace(['(', ')'], ['\\u0028', '\\u0029'], $match);
  139. $match = preg_replace_callback('/\bOR\b/i', fn(array $ms): string =>
  140. str_replace(['O', 'o', 'R', 'r'], ['\\u004f', '\\u006f', '\\u0052', '\\u0072'], $ms[0]),
  141. $match
  142. ) ?? '';
  143. return $match;
  144. },
  145. $input
  146. ) ?? '';
  147. }
  148. public static function unescapeLiterals(string $input): string {
  149. return str_replace(
  150. ['\\u0028', '\\u0029', '\\u004f', '\\u006f', '\\u0052', '\\u0072'],
  151. ['(', ')', 'O', 'o', 'R', 'r'],
  152. $input
  153. );
  154. }
  155. /**
  156. * Example: 'ab cd OR ef OR "gh ij"' becomes '(ab cd) OR (ef) OR ("gh ij")'
  157. */
  158. public static function addOrParentheses(string $input): string {
  159. $input = trim($input);
  160. if ($input === '') {
  161. return '';
  162. }
  163. $splits = preg_split('/\b(OR)\b/i', $input, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];
  164. $ns = count($splits);
  165. if ($ns <= 1) {
  166. return $input;
  167. }
  168. $result = '';
  169. $segment = '';
  170. for ($i = 0; $i < $ns; $i++) {
  171. $segment .= $splits[$i];
  172. if (trim($segment) === '') {
  173. $segment = '';
  174. } elseif (strcasecmp($segment, 'OR') === 0) {
  175. $result .= $segment . ' ';
  176. $segment = '';
  177. } else {
  178. $quotes = substr_count($segment, '"') + substr_count($segment, '&quot;');
  179. if ($quotes % 2 === 0) {
  180. $segment = trim($segment);
  181. if (in_array($segment, ['!', '-'], true)) {
  182. $result .= $segment;
  183. } else {
  184. $result .= '(' . $segment . ') ';
  185. }
  186. $segment = '';
  187. }
  188. }
  189. }
  190. $segment = trim($segment);
  191. if (in_array($segment, ['!', '-'], true)) {
  192. $result .= $segment;
  193. } elseif ($segment !== '') {
  194. $result .= '(' . $segment . ')';
  195. }
  196. return trim($result);
  197. }
  198. /**
  199. * If the query contains a mix of `OR` expressions with and without parentheses,
  200. * then add parentheses to make the query consistent.
  201. * Example: '(ab (cd OR ef)) OR gh OR ij OR (kl)' becomes '(ab ((cd) OR (ef))) OR (gh) OR (ij) OR (kl)'
  202. *
  203. * @throws Minz_BadRequestException if the search is too long or if the parentheses are nested too deeply
  204. */
  205. public static function consistentOrParentheses(string $input): string {
  206. if (strlen($input) > FreshRSS_Context::systemConf()->limits['max_search_length']) {
  207. throw new Minz_BadRequestException('Search is too long!');
  208. }
  209. if (!preg_match('/(?<!\\\\)\\(/', $input)) {
  210. // No unescaped parentheses in the input
  211. return trim($input);
  212. }
  213. $parenthesesCount = 0;
  214. $result = '';
  215. $segment = '';
  216. $length = strlen($input);
  217. for ($i = 0; $i < $length; $i++) {
  218. $c = $input[$i];
  219. $backslashed = $i >= 1 ? $input[$i - 1] === '\\' : false;
  220. if (!$backslashed) {
  221. if ($c === '(') {
  222. if ($parenthesesCount === 0) {
  223. if ($segment !== '') {
  224. $result = rtrim($result) . ' ' . self::addOrParentheses($segment);
  225. $negation = preg_match('/[!-]$/', $result);
  226. if (!$negation) {
  227. $result .= ' ';
  228. }
  229. $segment = '';
  230. }
  231. $c = '';
  232. }
  233. if ($parenthesesCount >= FreshRSS_Context::systemConf()->limits['max_search_parentheses_depth']) {
  234. throw new Minz_BadRequestException('Search has too deeply nested parentheses!');
  235. }
  236. $parenthesesCount++;
  237. } elseif ($c === ')') {
  238. $parenthesesCount--;
  239. if ($parenthesesCount === 0) {
  240. $segment = self::consistentOrParentheses($segment);
  241. if ($segment !== '') {
  242. $result .= '(' . $segment . ')';
  243. $segment = '';
  244. }
  245. $c = '';
  246. }
  247. }
  248. }
  249. $segment .= $c;
  250. }
  251. if (trim($segment) !== '') {
  252. $result = rtrim($result);
  253. $negation = preg_match('/[!-]$/', $segment);
  254. if (!$negation) {
  255. $result .= ' ';
  256. }
  257. $result .= self::addOrParentheses($segment);
  258. }
  259. return trim($result);
  260. }
  261. /** @return bool True if some parenthesis logic took over, false otherwise */
  262. private function parseParentheses(string $input, int $level): bool {
  263. $input = trim($input);
  264. $length = strlen($input);
  265. $i = 0;
  266. $before = '';
  267. $hasParenthesis = false;
  268. $nextOperator = 'AND';
  269. while ($i < $length) {
  270. $c = $input[$i];
  271. $backslashed = $i >= 1 ? $input[$i - 1] === '\\' : false;
  272. if ($c === '(' && !$backslashed) {
  273. $hasParenthesis = true;
  274. $before = trim($before);
  275. if (preg_match('/[!-]$/', $before)) {
  276. // Trim trailing negation
  277. $before = rtrim($before, ' !-');
  278. $isOr = preg_match('/\bOR$/i', $before);
  279. if ($isOr) {
  280. // Trim trailing OR
  281. $before = substr($before, 0, -2);
  282. }
  283. // The text prior to the negation is a BooleanSearch
  284. $searchBefore = new FreshRSS_BooleanSearch($before, $level + 1, $nextOperator);
  285. if (count($searchBefore->searches()) > 0) {
  286. $this->searches[] = $searchBefore;
  287. }
  288. $before = '';
  289. // The next BooleanSearch will have to be combined with AND NOT or OR NOT instead of default AND
  290. $nextOperator = $isOr ? 'OR NOT' : 'AND NOT';
  291. } elseif (preg_match('/\bOR$/i', $before)) {
  292. // Trim trailing OR
  293. $before = substr($before, 0, -2);
  294. // The text prior to the OR is a BooleanSearch
  295. $searchBefore = new FreshRSS_BooleanSearch($before, $level + 1, $nextOperator);
  296. if (count($searchBefore->searches()) > 0) {
  297. $this->searches[] = $searchBefore;
  298. }
  299. $before = '';
  300. // The next BooleanSearch will have to be combined with OR instead of default AND
  301. $nextOperator = 'OR';
  302. } elseif ($before !== '') {
  303. // The text prior to the opening parenthesis is a BooleanSearch
  304. $searchBefore = new FreshRSS_BooleanSearch($before, $level + 1, $nextOperator);
  305. if (count($searchBefore->searches()) > 0) {
  306. $this->searches[] = $searchBefore;
  307. }
  308. $before = '';
  309. }
  310. // Search the matching closing parenthesis
  311. $parentheses = 1;
  312. $sub = '';
  313. $i++;
  314. while ($i < $length) {
  315. $c = $input[$i];
  316. $backslashed = $input[$i - 1] === '\\';
  317. if ($c === '(' && !$backslashed) {
  318. // One nested level deeper
  319. $parentheses++;
  320. $sub .= $c;
  321. } elseif ($c === ')' && !$backslashed) {
  322. $parentheses--;
  323. if ($parentheses === 0) {
  324. // Found the matching closing parenthesis
  325. $searchSub = new FreshRSS_BooleanSearch($sub, $level + 1, $nextOperator);
  326. $nextOperator = 'AND';
  327. if (count($searchSub->searches()) > 0) {
  328. $this->searches[] = $searchSub;
  329. }
  330. $sub = '';
  331. break;
  332. } else {
  333. $sub .= $c;
  334. }
  335. } else {
  336. $sub .= $c;
  337. }
  338. $i++;
  339. }
  340. // $sub = trim($sub);
  341. // if ($sub !== '') {
  342. // // TODO: Consider throwing an error or warning in case of non-matching parenthesis
  343. // }
  344. // } elseif ($c === ')') {
  345. // // TODO: Consider throwing an error or warning in case of non-matching parenthesis
  346. } else {
  347. $before .= $c;
  348. }
  349. $i++;
  350. }
  351. if ($hasParenthesis) {
  352. $before = trim($before);
  353. if (preg_match('/^OR\b/i', $before)) {
  354. // The next BooleanSearch will have to be combined with OR instead of default AND
  355. $nextOperator = 'OR';
  356. // Trim leading OR
  357. $before = substr($before, 2);
  358. }
  359. // The remaining text after the last parenthesis is a BooleanSearch
  360. $searchBefore = new FreshRSS_BooleanSearch($before, $level + 1, $nextOperator);
  361. $nextOperator = 'AND';
  362. if (count($searchBefore->searches()) > 0) {
  363. $this->searches[] = $searchBefore;
  364. }
  365. return true;
  366. }
  367. // There was no parenthesis logic to apply
  368. return false;
  369. }
  370. private function parseOrSegments(string $input): void {
  371. $input = trim($input);
  372. if ($input === '') {
  373. return;
  374. }
  375. $splits = preg_split('/\b(OR)\b/i', $input, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];
  376. $segment = '';
  377. $ns = count($splits);
  378. for ($i = 0; $i < $ns; $i++) {
  379. $segment = $segment . $splits[$i];
  380. if (trim($segment) === '' || strcasecmp($segment, 'OR') === 0) {
  381. $segment = '';
  382. } else {
  383. $quotes = substr_count($segment, '"') + substr_count($segment, '&quot;');
  384. if ($quotes % 2 === 0) {
  385. $segment = trim($segment);
  386. $this->searches[] = new FreshRSS_Search($segment);
  387. $segment = '';
  388. }
  389. }
  390. }
  391. $segment = trim($segment);
  392. if ($segment !== '') {
  393. $this->searches[] = new FreshRSS_Search($segment);
  394. }
  395. }
  396. /**
  397. * Either a list of FreshRSS_BooleanSearch combined by implicit AND
  398. * or a series of FreshRSS_Search combined by explicit OR
  399. * @return list<FreshRSS_BooleanSearch|FreshRSS_Search>
  400. */
  401. public function searches(): array {
  402. return $this->searches;
  403. }
  404. /** @return 'AND'|'OR'|'AND NOT'|'OR NOT' depending on how this BooleanSearch should be combined */
  405. public function operator(): string {
  406. return $this->operator;
  407. }
  408. /**
  409. * Wrap the existing searches in a single BooleanSearch if needed,
  410. * so that another search can be added as an additional restriction (AND).
  411. */
  412. private function wrapSearches(): void {
  413. if (count($this->searches) > 1 || (count($this->searches) > 0 && $this->searches[0] instanceof FreshRSS_Search)) {
  414. $wrap = new FreshRSS_BooleanSearch('');
  415. foreach ($this->searches as $existingSearch) {
  416. $wrap->add($existingSearch);
  417. }
  418. if (count($wrap->searches) > 0) {
  419. $this->searches = [$wrap];
  420. }
  421. }
  422. }
  423. /**
  424. * Add a search at the beginning of the Boolean expression, as an additional restriction (AND).
  425. * @param FreshRSS_BooleanSearch|FreshRSS_Search $search
  426. */
  427. public function prepend(FreshRSS_BooleanSearch|FreshRSS_Search $search): void {
  428. $this->wrapSearches();
  429. array_unshift($this->searches, $search);
  430. }
  431. /** @param FreshRSS_BooleanSearch|FreshRSS_Search $search */
  432. public function add(FreshRSS_BooleanSearch|FreshRSS_Search $search): void {
  433. $this->searches[] = $search;
  434. }
  435. /**
  436. * Modify the first compatible search of the Boolean expression, or add it at the beginning.
  437. * Useful to modify some search parameters.
  438. * @return FreshRSS_BooleanSearch a new instance, modified.
  439. */
  440. public function enforce(FreshRSS_Search $search): self {
  441. $result = clone $this;
  442. $result->raw_input = '';
  443. $result->expanded = null;
  444. $result->notExpanded = null;
  445. if (count($result->searches) === 1 && $result->searches[0] instanceof FreshRSS_Search) {
  446. $result->searches[0] = $result->searches[0]->enforce($search);
  447. return $result;
  448. }
  449. if (count($result->searches) === 2) {
  450. foreach ($result->searches as $booleanSearch) {
  451. if (!($booleanSearch instanceof FreshRSS_BooleanSearch)) {
  452. break;
  453. }
  454. if ($booleanSearch->operator() === 'AND') {
  455. if (count($booleanSearch->searches) === 1 && $booleanSearch->searches[0] instanceof FreshRSS_Search &&
  456. $booleanSearch->searches[0]->hasSameOperators($search)) {
  457. $booleanSearch->searches[0] = $search;
  458. return $result;
  459. }
  460. }
  461. }
  462. }
  463. $result->wrapSearches();
  464. array_unshift($result->searches, $search);
  465. return $result;
  466. }
  467. /**
  468. * Remove the first compatible search of the Boolean expression, if any.
  469. * Useful to modify some search parameters.
  470. * @return FreshRSS_BooleanSearch a new instance, modified.
  471. */
  472. public function remove(FreshRSS_Search $search): self {
  473. $result = clone $this;
  474. $result->raw_input = '';
  475. $result->expanded = null;
  476. $result->notExpanded = null;
  477. if (count($result->searches) === 1 && $result->searches[0] instanceof FreshRSS_Search) {
  478. $result->searches[0] = $result->searches[0]->remove($search);
  479. return $result;
  480. }
  481. if (count($result->searches) === 2) {
  482. foreach ($result->searches as $booleanSearch) {
  483. if (!($booleanSearch instanceof FreshRSS_BooleanSearch)) {
  484. break;
  485. }
  486. if ($booleanSearch->operator() === 'AND') {
  487. if (count($booleanSearch->searches) === 1 && $booleanSearch->searches[0] instanceof FreshRSS_Search &&
  488. $booleanSearch->searches[0]->hasSameOperators($search)) {
  489. array_shift($booleanSearch->searches);
  490. return $result;
  491. }
  492. }
  493. }
  494. }
  495. return $result;
  496. }
  497. /**
  498. * Return the minimum visibility (priority) level needed for this Boolean search, or null if it does not require any specific visibility level.
  499. * For instance, if the search includes some feed IDs then it will return PRIORITY_HIDDEN,
  500. * and if it includes some category IDs then it will return PRIORITY_CATEGORY.
  501. */
  502. public function needVisibility(): ?int {
  503. $minVisibility = FreshRSS_Feed::PRIORITY_IMPORTANT + 1;
  504. foreach ($this->searches as $search) {
  505. if ($search instanceof FreshRSS_BooleanSearch) {
  506. $visibility = $search->needVisibility();
  507. if ($visibility !== null) {
  508. $minVisibility = min($minVisibility, $visibility);
  509. }
  510. } elseif ($search instanceof FreshRSS_Search) {
  511. $visibility = $search->needVisibility();
  512. if ($visibility !== null) {
  513. $minVisibility = min($minVisibility, $visibility);
  514. }
  515. }
  516. }
  517. return $minVisibility < FreshRSS_Feed::PRIORITY_IMPORTANT ? $minVisibility : null;
  518. }
  519. private ?string $expanded = null;
  520. #[\Override]
  521. public function __toString(): string {
  522. if ($this->expanded === null) {
  523. $result = '';
  524. foreach ($this->searches as $search) {
  525. $part = $search->__toString();
  526. if ($part === '') {
  527. continue;
  528. }
  529. $operator = $search instanceof FreshRSS_BooleanSearch ? $search->operator : 'OR';
  530. if ((str_contains($part, ' ') || str_starts_with($part, '-')) && (count($this->searches) > 1 || in_array($operator, ['OR NOT', 'AND NOT'], true))) {
  531. $part = '(' . $part . ')';
  532. }
  533. $result .= match ($operator) {
  534. 'OR' => $result === '' ? '' : ' OR ',
  535. 'OR NOT' => $result === '' ? '-' : ' OR -',
  536. 'AND NOT' => $result === '' ? '-' : ' -',
  537. 'AND' => $result === '' ? '' : ' ',
  538. default => throw new InvalidArgumentException('Invalid operator: ' . $operator),
  539. } . $part;
  540. }
  541. $this->expanded = trim($result);
  542. }
  543. return $this->expanded;
  544. }
  545. private ?string $notExpanded = null;
  546. /**
  547. * @param bool $expandUserQueries Whether to expand user queries (saved searches) or not
  548. * @throws Minz_BadRequestException if the search is too long or if the parentheses are nested too deeply
  549. */
  550. public function toString(bool $expandUserQueries = true): string {
  551. if ($expandUserQueries) {
  552. return $this->__toString();
  553. }
  554. if ($this->notExpanded === null) {
  555. $this->notExpanded = (new FreshRSS_BooleanSearch($this->raw_input, expandUserQueries: false))->__toString();
  556. }
  557. return $this->notExpanded;
  558. }
  559. /** @return string Plain text search query. Must be XML-encoded or URL-encoded depending on the situation */
  560. #[Deprecated('Use __toString(expanded: false) instead')]
  561. public function getRawInput(): string {
  562. return $this->raw_input;
  563. }
  564. }