BooleanSearch.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Contains Boolean search from the search form.
  5. */
  6. class FreshRSS_BooleanSearch {
  7. private string $raw_input = '';
  8. /** @var array<FreshRSS_BooleanSearch|FreshRSS_Search> */
  9. private array $searches = [];
  10. /**
  11. * @phpstan-var 'AND'|'OR'|'AND NOT'
  12. */
  13. private string $operator;
  14. /** @param 'AND'|'OR'|'AND NOT' $operator */
  15. public function __construct(string $input, int $level = 0, string $operator = 'AND') {
  16. $this->operator = $operator;
  17. $input = trim($input);
  18. if ($input === '') {
  19. return;
  20. }
  21. $this->raw_input = $input;
  22. if ($level === 0) {
  23. $input = preg_replace('/:&quot;(.*?)&quot;/', ':"\1"', $input);
  24. if (!is_string($input)) {
  25. return;
  26. }
  27. $input = preg_replace('/(?<=[\s!-]|^)&quot;(.*?)&quot;/', '"\1"', $input);
  28. if (!is_string($input)) {
  29. return;
  30. }
  31. $input = $this->parseUserQueryNames($input);
  32. $input = $this->parseUserQueryIds($input);
  33. }
  34. // Either parse everything as a series of BooleanSearch’s combined by implicit AND
  35. // or parse everything as a series of Search’s combined by explicit OR
  36. $this->parseParentheses($input, $level) || $this->parseOrSegments($input);
  37. }
  38. /**
  39. * Parse the user queries (saved searches) by name and expand them in the input string.
  40. */
  41. private function parseUserQueryNames(string $input): string {
  42. $all_matches = [];
  43. if (preg_match_all('/\bsearch:(?P<delim>[\'"])(?P<search>.*)(?P=delim)/U', $input, $matchesFound)) {
  44. $all_matches[] = $matchesFound;
  45. }
  46. if (preg_match_all('/\bsearch:(?P<search>[^\s"]*)/', $input, $matchesFound)) {
  47. $all_matches[] = $matchesFound;
  48. }
  49. if (!empty($all_matches)) {
  50. /** @var array<string,FreshRSS_UserQuery> */
  51. $queries = [];
  52. foreach (FreshRSS_Context::userConf()->queries as $raw_query) {
  53. $query = new FreshRSS_UserQuery($raw_query);
  54. $queries[$query->getName()] = $query;
  55. }
  56. $fromS = [];
  57. $toS = [];
  58. foreach ($all_matches as $matches) {
  59. if (empty($matches['search'])) {
  60. continue;
  61. }
  62. for ($i = count($matches['search']) - 1; $i >= 0; $i--) {
  63. $name = trim($matches['search'][$i]);
  64. if (!empty($queries[$name])) {
  65. $fromS[] = $matches[0][$i];
  66. $toS[] = '(' . trim($queries[$name]->getSearch()->getRawInput()) . ')';
  67. }
  68. }
  69. }
  70. $input = str_replace($fromS, $toS, $input);
  71. }
  72. return $input;
  73. }
  74. /**
  75. * Parse the user queries (saved searches) by ID and expand them in the input string.
  76. */
  77. private function parseUserQueryIds(string $input): string {
  78. $all_matches = [];
  79. if (preg_match_all('/\bS:(?P<search>\d+)/', $input, $matchesFound)) {
  80. $all_matches[] = $matchesFound;
  81. }
  82. if (!empty($all_matches)) {
  83. $category_dao = FreshRSS_Factory::createCategoryDao();
  84. $feed_dao = FreshRSS_Factory::createFeedDao();
  85. $tag_dao = FreshRSS_Factory::createTagDao();
  86. /** @var array<string,FreshRSS_UserQuery> */
  87. $queries = [];
  88. foreach (FreshRSS_Context::userConf()->queries as $raw_query) {
  89. $query = new FreshRSS_UserQuery($raw_query, $feed_dao, $category_dao, $tag_dao);
  90. $queries[] = $query;
  91. }
  92. $fromS = [];
  93. $toS = [];
  94. foreach ($all_matches as $matches) {
  95. if (empty($matches['search'])) {
  96. continue;
  97. }
  98. for ($i = count($matches['search']) - 1; $i >= 0; $i--) {
  99. // Index starting from 1
  100. $id = (int)(trim($matches['search'][$i])) - 1;
  101. if (!empty($queries[$id])) {
  102. $fromS[] = $matches[0][$i];
  103. $toS[] = '(' . trim($queries[$id]->getSearch()->getRawInput()) . ')';
  104. }
  105. }
  106. }
  107. $input = str_replace($fromS, $toS, $input);
  108. }
  109. return $input;
  110. }
  111. /** @return bool True if some parenthesis logic took over, false otherwise */
  112. private function parseParentheses(string $input, int $level): bool {
  113. $input = trim($input);
  114. $length = strlen($input);
  115. $i = 0;
  116. $before = '';
  117. $hasParenthesis = false;
  118. $nextOperator = 'AND';
  119. while ($i < $length) {
  120. $c = $input[$i];
  121. $backslashed = $i >= 1 ? $input[$i - 1] === '\\' : false;
  122. if ($c === '(' && !$backslashed) {
  123. $hasParenthesis = true;
  124. $before = trim($before);
  125. if (preg_match('/[!-]$/i', $before)) {
  126. // Trim trailing negation
  127. $before = substr($before, 0, -1);
  128. // The text prior to the negation is a BooleanSearch
  129. $searchBefore = new FreshRSS_BooleanSearch($before, $level + 1, $nextOperator);
  130. if (count($searchBefore->searches()) > 0) {
  131. $this->searches[] = $searchBefore;
  132. }
  133. $before = '';
  134. // The next BooleanSearch will have to be combined with AND NOT instead of default AND
  135. $nextOperator = 'AND NOT';
  136. } elseif (preg_match('/\bOR$/i', $before)) {
  137. // Trim trailing OR
  138. $before = substr($before, 0, -2);
  139. // The text prior to the OR is a BooleanSearch
  140. $searchBefore = new FreshRSS_BooleanSearch($before, $level + 1, $nextOperator);
  141. if (count($searchBefore->searches()) > 0) {
  142. $this->searches[] = $searchBefore;
  143. }
  144. $before = '';
  145. // The next BooleanSearch will have to be combined with OR instead of default AND
  146. $nextOperator = 'OR';
  147. } elseif ($before !== '') {
  148. // The text prior to the opening parenthesis is a BooleanSearch
  149. $searchBefore = new FreshRSS_BooleanSearch($before, $level + 1, $nextOperator);
  150. if (count($searchBefore->searches()) > 0) {
  151. $this->searches[] = $searchBefore;
  152. }
  153. $before = '';
  154. }
  155. // Search the matching closing parenthesis
  156. $parentheses = 1;
  157. $sub = '';
  158. $i++;
  159. while ($i < $length) {
  160. $c = $input[$i];
  161. $backslashed = $input[$i - 1] === '\\';
  162. if ($c === '(' && !$backslashed) {
  163. // One nested level deeper
  164. $parentheses++;
  165. $sub .= $c;
  166. } elseif ($c === ')' && !$backslashed) {
  167. $parentheses--;
  168. if ($parentheses === 0) {
  169. // Found the matching closing parenthesis
  170. $searchSub = new FreshRSS_BooleanSearch($sub, $level + 1, $nextOperator);
  171. $nextOperator = 'AND';
  172. if (count($searchSub->searches()) > 0) {
  173. $this->searches[] = $searchSub;
  174. }
  175. $sub = '';
  176. break;
  177. } else {
  178. $sub .= $c;
  179. }
  180. } else {
  181. $sub .= $c;
  182. }
  183. $i++;
  184. }
  185. // $sub = trim($sub);
  186. // if ($sub != '') {
  187. // // TODO: Consider throwing an error or warning in case of non-matching parenthesis
  188. // }
  189. // } elseif ($c === ')') {
  190. // // TODO: Consider throwing an error or warning in case of non-matching parenthesis
  191. } else {
  192. $before .= $c;
  193. }
  194. $i++;
  195. }
  196. if ($hasParenthesis) {
  197. $before = trim($before);
  198. if (preg_match('/^OR\b/i', $before)) {
  199. // The next BooleanSearch will have to be combined with OR instead of default AND
  200. $nextOperator = 'OR';
  201. // Trim leading OR
  202. $before = substr($before, 2);
  203. }
  204. // The remaining text after the last parenthesis is a BooleanSearch
  205. $searchBefore = new FreshRSS_BooleanSearch($before, $level + 1, $nextOperator);
  206. $nextOperator = 'AND';
  207. if (count($searchBefore->searches()) > 0) {
  208. $this->searches[] = $searchBefore;
  209. }
  210. return true;
  211. }
  212. // There was no parenthesis logic to apply
  213. return false;
  214. }
  215. private function parseOrSegments(string $input): void {
  216. $input = trim($input);
  217. if ($input === '') {
  218. return;
  219. }
  220. $splits = preg_split('/\b(OR)\b/i', $input, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];
  221. $segment = '';
  222. $ns = count($splits);
  223. for ($i = 0; $i < $ns; $i++) {
  224. $segment = $segment . $splits[$i];
  225. if (trim($segment) == '' || strcasecmp($segment, 'OR') === 0) {
  226. $segment = '';
  227. } else {
  228. $quotes = substr_count($segment, '"') + substr_count($segment, '&quot;');
  229. if ($quotes % 2 === 0) {
  230. $segment = trim($segment);
  231. $this->searches[] = new FreshRSS_Search($segment);
  232. $segment = '';
  233. }
  234. }
  235. }
  236. $segment = trim($segment);
  237. if ($segment != '') {
  238. $this->searches[] = new FreshRSS_Search($segment);
  239. }
  240. }
  241. /**
  242. * Either a list of FreshRSS_BooleanSearch combined by implicit AND
  243. * or a series of FreshRSS_Search combined by explicit OR
  244. * @return array<FreshRSS_BooleanSearch|FreshRSS_Search>
  245. */
  246. public function searches(): array {
  247. return $this->searches;
  248. }
  249. /** @return 'AND'|'OR'|'AND NOT' depending on how this BooleanSearch should be combined */
  250. public function operator(): string {
  251. return $this->operator;
  252. }
  253. /** @param FreshRSS_BooleanSearch|FreshRSS_Search $search */
  254. public function add($search): void {
  255. $this->searches[] = $search;
  256. }
  257. public function __toString(): string {
  258. return $this->getRawInput();
  259. }
  260. public function getRawInput(): string {
  261. return $this->raw_input;
  262. }
  263. }