BooleanSearch.php 8.2 KB

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