BooleanSearch.php 7.9 KB

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