query.inc 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. <?php
  2. /**
  3. * @file
  4. * Contains SearchApiQueryInterface and SearchApiQuery.
  5. */
  6. /**
  7. * Interface representing a search query on an Search API index.
  8. *
  9. * Methods not returning something else will return the object itself, so calls
  10. * can be chained.
  11. */
  12. interface SearchApiQueryInterface {
  13. /**
  14. * Constructs a new search query.
  15. *
  16. * @param SearchApiIndex $index
  17. * The index the query should be executed on.
  18. * @param array $options
  19. * Associative array of options configuring this query. Recognized options
  20. * are:
  21. * - conjunction: The type of conjunction to use for this query - either
  22. * 'AND' or 'OR'. 'AND' by default. This only influences the search keys,
  23. * filters will always use AND by default.
  24. * - 'parse mode': The mode with which to parse the $keys variable, if it
  25. * is set and not already an array. See SearchApiQuery::parseModes() for
  26. * recognized parse modes.
  27. * - languages: The languages to search for, as an array of language IDs.
  28. * If not specified, all languages will be searched. Language-neutral
  29. * content (LANGUAGE_NONE) is always searched.
  30. * - offset: The position of the first returned search results relative to
  31. * the whole result in the index.
  32. * - limit: The maximum number of search results to return. -1 means no
  33. * limit.
  34. * - 'filter class': Can be used to change the SearchApiQueryFilterInterface
  35. * implementation to use.
  36. * - 'search id': A string that will be used as the identifier when storing
  37. * this search in the Search API's static cache.
  38. * - 'skip result count': If present and set to TRUE, the result's
  39. * "result count" key will not be needed. Service classes can check for
  40. * this option to possibly avoid executing expensive operations to compute
  41. * the result count in cases where it is not needed.
  42. * - search_api_access_account: The account which will be used for entity
  43. * access checks, if available and enabled for the index.
  44. * - search_api_bypass_access: If set to TRUE, entity access checks will be
  45. * skipped, even if enabled for the index.
  46. * All options are optional. Third-party modules might define and use other
  47. * options not listed here.
  48. *
  49. * @throws SearchApiException
  50. * If a search on that index (or with those options) won't be possible.
  51. */
  52. public function __construct(SearchApiIndex $index, array $options = array());
  53. /**
  54. * Retrieves the parse modes supported by this query class.
  55. *
  56. * @return array
  57. * An associative array of parse modes recognized by objects of this class.
  58. * The keys are the parse modes' ids, values are associative arrays
  59. * containing the following entries:
  60. * - name: The translated name of the parse mode.
  61. * - description: (optional) A translated text describing the parse mode.
  62. */
  63. public function parseModes();
  64. /**
  65. * Creates a new filter to use with this query object.
  66. *
  67. * @param string $conjunction
  68. * The conjunction to use for the filter - either 'AND' or 'OR'.
  69. * @param $tags
  70. * (Optional) An arbitrary set of tags. Can be used to identify this filter
  71. * down the line if necessary. This is primarily used by the facet system
  72. * to support OR facet queries.
  73. *
  74. * @return SearchApiQueryFilterInterface
  75. * A filter object that is set to use the specified conjunction.
  76. */
  77. public function createFilter($conjunction = 'AND', $tags = array());
  78. /**
  79. * Sets the keys to search for.
  80. *
  81. * If this method is not called on the query before execution, this will be a
  82. * filter-only query.
  83. *
  84. * @param array|string|null $keys
  85. * A string with the unparsed search keys, or NULL to use no search keys.
  86. *
  87. * @return SearchApiQueryInterface
  88. * The called object.
  89. */
  90. public function keys($keys = NULL);
  91. /**
  92. * Sets the fields that will be searched for the search keys.
  93. *
  94. * If this is not called, all fulltext fields will be searched.
  95. *
  96. * @param array $fields
  97. * An array containing fulltext fields that should be searched.
  98. *
  99. * @return SearchApiQueryInterface
  100. * The called object.
  101. *
  102. * @throws SearchApiException
  103. * If one of the fields isn't of type "text".
  104. */
  105. // @todo Allow calling with NULL.
  106. public function fields(array $fields);
  107. /**
  108. * Adds a subfilter to this query's filter.
  109. *
  110. * @param SearchApiQueryFilterInterface $filter
  111. * A SearchApiQueryFilter object that should be added as a subfilter.
  112. *
  113. * @return SearchApiQueryInterface
  114. * The called object.
  115. */
  116. public function filter(SearchApiQueryFilterInterface $filter);
  117. /**
  118. * Adds a new ($field $operator $value) condition filter.
  119. *
  120. * @param string $field
  121. * The field to filter on, e.g. 'title'.
  122. * @param mixed $value
  123. * The value the field should have (or be related to by the operator).
  124. * @param string $operator
  125. * The operator to use for checking the constraint. The following operators
  126. * are supported for primitive types: "=", "<>", "<", "<=", ">=", ">". They
  127. * have the same semantics as the corresponding SQL operators.
  128. * If $field is a fulltext field, $operator can only be "=" or "<>", which
  129. * are in this case interpreted as "contains" or "doesn't contain",
  130. * respectively.
  131. * If $value is NULL, $operator also can only be "=" or "<>", meaning the
  132. * field must have no or some value, respectively.
  133. *
  134. * @return SearchApiQueryInterface
  135. * The called object.
  136. */
  137. public function condition($field, $value, $operator = '=');
  138. /**
  139. * Adds a sort directive to this search query.
  140. *
  141. * If no sort is manually set, the results will be sorted descending by
  142. * relevance.
  143. *
  144. * @param string $field
  145. * The field to sort by. The special fields 'search_api_relevance' (sort by
  146. * relevance) and 'search_api_id' (sort by item id) may be used.
  147. * @param string $order
  148. * The order to sort items in - either 'ASC' or 'DESC'.
  149. *
  150. * @return SearchApiQueryInterface
  151. * The called object.
  152. *
  153. * @throws SearchApiException
  154. * If the field is multi-valued or of a fulltext type.
  155. */
  156. public function sort($field, $order = 'ASC');
  157. /**
  158. * Adds a range of results to return.
  159. *
  160. * This will be saved in the query's options. If called without parameters,
  161. * this will remove all range restrictions previously set.
  162. *
  163. * @param int|null $offset
  164. * The zero-based offset of the first result returned.
  165. * @param int|null $limit
  166. * The number of results to return.
  167. *
  168. * @return SearchApiQueryInterface
  169. * The called object.
  170. */
  171. public function range($offset = NULL, $limit = NULL);
  172. /**
  173. * Executes this search query.
  174. *
  175. * @return array
  176. * An associative array containing the search results. The following keys
  177. * are standardized:
  178. * - 'result count': The overall number of results for this query, without
  179. * range restrictions. Might be approximated, for large numbers, or
  180. * skipped entirely if the "skip result count" option was set on this
  181. * query.
  182. * - results: An array of results, ordered as specified. The array keys are
  183. * the items' IDs, values are arrays containing the following keys:
  184. * - id: The item's ID.
  185. * - score: A float measuring how well the item fits the search.
  186. * - fields: (optional) If set, an array containing some field values
  187. * already ready-to-use. This allows search engines (or postprocessors)
  188. * to store extracted fields so other modules don't have to extract them
  189. * again. This fields should always be checked by modules that want to
  190. * use field contents of the result items.
  191. * - entity: (optional) If set, the fully loaded result item. This field
  192. * should always be used by modules using search results, to avoid
  193. * duplicate item loads.
  194. * - excerpt: (optional) If set, an HTML text containing highlighted
  195. * portions of the fulltext that match the query.
  196. * - warnings: A numeric array of translated warning messages that may be
  197. * displayed to the user.
  198. * - ignored: A numeric array of search keys that were ignored for this
  199. * search (e.g., because of being too short or stop words).
  200. * - performance: An associative array with the time taken (as floats, in
  201. * seconds) for specific parts of the search execution:
  202. * - complete: The complete runtime of the query.
  203. * - hooks: Hook invocations and other client-side preprocessing.
  204. * - preprocessing: Preprocessing of the service class.
  205. * - execution: The actual query to the search server, in whatever form.
  206. * - postprocessing: Preparing the results for returning.
  207. * Additional metadata may be returned in other keys. Only 'result count'
  208. * and 'result' always have to be set, all other entries are optional.
  209. */
  210. public function execute();
  211. /**
  212. * Prepares the query object for the search.
  213. *
  214. * This method should always be called by execute() and contain all necessary
  215. * operations before the query is passed to the server's search() method.
  216. */
  217. public function preExecute();
  218. /**
  219. * Postprocesses the search results before they are returned.
  220. *
  221. * This method should always be called by execute() and contain all necessary
  222. * operations after the results are returned from the server.
  223. *
  224. * @param array $results
  225. * The results returned by the server, which may be altered. The data
  226. * structure is the same as returned by execute().
  227. */
  228. public function postExecute(array &$results);
  229. /**
  230. * Retrieves the index associated with this search.
  231. *
  232. * @return SearchApiIndex
  233. * The search index this query should be executed on.
  234. */
  235. public function getIndex();
  236. /**
  237. * Retrieves the search keys for this query.
  238. *
  239. * @return array|string|null
  240. * This object's search keys - either a string or an array specifying a
  241. * complex search expression.
  242. * An array will contain a '#conjunction' key specifying the conjunction
  243. * type, and search strings or nested expression arrays at numeric keys.
  244. * Additionally, a '#negation' key might be present, which means – unless it
  245. * maps to a FALSE value – that the search keys contained in that array
  246. * should be negated, i.e. not be present in returned results. The negation
  247. * works on the whole array, not on each contained term individually – i.e.,
  248. * with the "AND" conjunction and negation, only results that contain all
  249. * the terms in the array should be excluded; with the "OR" conjunction and
  250. * negation, all results containing one or more of the terms in the array
  251. * should be excluded.
  252. *
  253. * @see keys()
  254. */
  255. public function &getKeys();
  256. /**
  257. * Retrieves the unparsed search keys for this query as originally entered.
  258. *
  259. * @return array|string|null
  260. * The unprocessed search keys, exactly as passed to this object. Has the
  261. * same format as the return value of getKeys().
  262. *
  263. * @see keys()
  264. */
  265. public function getOriginalKeys();
  266. /**
  267. * Retrieves the fulltext fields that will be searched for the search keys.
  268. *
  269. * @return array
  270. * An array containing the fields that should be searched for the search
  271. * keys.
  272. *
  273. * @see fields()
  274. */
  275. public function &getFields();
  276. /**
  277. * Retrieves the filter object associated with this search query.
  278. *
  279. * @return SearchApiQueryFilterInterface
  280. * This object's associated filter object.
  281. */
  282. public function getFilter();
  283. /**
  284. * Retrieves the sorts set for this query.
  285. *
  286. * @return array
  287. * An array specifying the sort order for this query. Array keys are the
  288. * field names in order of importance, the values are the respective order
  289. * in which to sort the results according to the field.
  290. *
  291. * @see sort()
  292. */
  293. public function &getSort();
  294. /**
  295. * Retrieves an option set on this search query.
  296. *
  297. * @param string $name
  298. * The name of an option.
  299. * @param mixed $default
  300. * The value to return if the specified option is not set.
  301. *
  302. * @return mixed
  303. * The value of the option with the specified name, if set. NULL otherwise.
  304. */
  305. public function getOption($name, $default = NULL);
  306. /**
  307. * Sets an option for this search query.
  308. *
  309. * @param string $name
  310. * The name of an option.
  311. * @param mixed $value
  312. * The new value of the option.
  313. *
  314. * @return mixed
  315. * The option's previous value.
  316. */
  317. public function setOption($name, $value);
  318. /**
  319. * Retrieves all options set for this search query.
  320. *
  321. * The return value is a reference to the options so they can also be altered
  322. * this way.
  323. *
  324. * @return array
  325. * An associative array of query options.
  326. */
  327. public function &getOptions();
  328. }
  329. /**
  330. * Provides a standard implementation of the SearchApiQueryInterface.
  331. */
  332. class SearchApiQuery implements SearchApiQueryInterface {
  333. /**
  334. * The index this query will use.
  335. *
  336. * @var SearchApiIndex
  337. */
  338. protected $index;
  339. /**
  340. * The index's machine name.
  341. *
  342. * used during serialization to avoid serializing the whole index object.
  343. *
  344. * @var string
  345. */
  346. protected $index_id;
  347. /**
  348. * The search keys. If NULL, this will be a filter-only search.
  349. *
  350. * @var mixed
  351. */
  352. protected $keys;
  353. /**
  354. * The unprocessed search keys, as passed to the keys() method.
  355. *
  356. * @var mixed
  357. */
  358. protected $orig_keys;
  359. /**
  360. * The fields that will be searched for the keys.
  361. *
  362. * @var array
  363. */
  364. protected $fields;
  365. /**
  366. * The search filter associated with this query.
  367. *
  368. * @var SearchApiQueryFilterInterface
  369. */
  370. protected $filter;
  371. /**
  372. * The sort associated with this query.
  373. *
  374. * @var array
  375. */
  376. protected $sort;
  377. /**
  378. * Search options configuring this query.
  379. *
  380. * @var array
  381. */
  382. protected $options;
  383. /**
  384. * Flag for whether preExecute() was already called for this query.
  385. *
  386. * @var bool
  387. */
  388. protected $pre_execute = FALSE;
  389. /**
  390. * {@inheritdoc}
  391. */
  392. public function __construct(SearchApiIndex $index, array $options = array()) {
  393. if (empty($index->options['fields'])) {
  394. throw new SearchApiException(t("Can't search an index which hasn't got any fields defined."));
  395. }
  396. if (empty($index->enabled)) {
  397. throw new SearchApiException(t("Can't search a disabled index."));
  398. }
  399. if (isset($options['parse mode'])) {
  400. $modes = $this->parseModes();
  401. if (!isset($modes[$options['parse mode']])) {
  402. throw new SearchApiException(t('Unknown parse mode: @mode.', array('@mode' => $options['parse mode'])));
  403. }
  404. }
  405. $this->index = $index;
  406. $this->options = $options + array(
  407. 'conjunction' => 'AND',
  408. 'parse mode' => 'terms',
  409. 'filter class' => 'SearchApiQueryFilter',
  410. 'search id' => __CLASS__,
  411. );
  412. $this->filter = $this->createFilter('AND');
  413. $this->sort = array();
  414. }
  415. /**
  416. * {@inheritdoc}
  417. */
  418. public function parseModes() {
  419. $modes['direct'] = array(
  420. 'name' => t('Direct query'),
  421. 'description' => t("Don't parse the query, just hand it to the search server unaltered. " .
  422. "Might fail if the query contains syntax errors in regard to the specific server's query syntax."),
  423. );
  424. $modes['single'] = array(
  425. 'name' => t('Single term'),
  426. 'description' => t('The query is interpreted as a single keyword, maybe containing spaces or special characters.'),
  427. );
  428. $modes['terms'] = array(
  429. 'name' => t('Multiple terms'),
  430. 'description' => t('The query is interpreted as multiple keywords seperated by spaces. ' .
  431. 'Keywords containing spaces may be "quoted". Quoted keywords must still be seperated by spaces.'),
  432. );
  433. // @todo Add fourth mode for complicated expressions, e.g.: »"vanilla ice" OR (love NOT hate)«
  434. return $modes;
  435. }
  436. /**
  437. * {@inheritdoc}
  438. */
  439. protected function parseKeys($keys, $mode) {
  440. if ($keys === NULL || is_array($keys)) {
  441. return $keys;
  442. }
  443. $keys = '' . $keys;
  444. switch ($mode) {
  445. case 'direct':
  446. return $keys;
  447. case 'single':
  448. return array('#conjunction' => $this->options['conjunction'], $keys);
  449. case 'terms':
  450. $ret = preg_split('/\s+/u', $keys);
  451. $quoted = FALSE;
  452. $str = '';
  453. foreach ($ret as $k => $v) {
  454. if (!$v) {
  455. continue;
  456. }
  457. if ($quoted) {
  458. if (substr($v, -1) == '"') {
  459. $v = substr($v, 0, -1);
  460. $str .= ' ' . $v;
  461. $ret[$k] = $str;
  462. $quoted = FALSE;
  463. }
  464. else {
  465. $str .= ' ' . $v;
  466. unset($ret[$k]);
  467. }
  468. }
  469. elseif ($v[0] == '"') {
  470. $len = strlen($v);
  471. if ($len > 1 && $v[$len-1] == '"') {
  472. $ret[$k] = substr($v, 1, -1);
  473. }
  474. else {
  475. $str = substr($v, 1);
  476. $quoted = TRUE;
  477. unset($ret[$k]);
  478. }
  479. }
  480. }
  481. if ($quoted) {
  482. $ret[] = $str;
  483. }
  484. $ret['#conjunction'] = $this->options['conjunction'];
  485. return array_filter($ret);
  486. }
  487. }
  488. /**
  489. * {@inheritdoc}
  490. */
  491. public function createFilter($conjunction = 'AND', $tags = array()) {
  492. $filter_class = $this->options['filter class'];
  493. return new $filter_class($conjunction, $tags);
  494. }
  495. /**
  496. * {@inheritdoc}
  497. */
  498. public function keys($keys = NULL) {
  499. $this->orig_keys = $keys;
  500. if (isset($keys)) {
  501. $this->keys = $this->parseKeys($keys, $this->options['parse mode']);
  502. }
  503. else {
  504. $this->keys = NULL;
  505. }
  506. return $this;
  507. }
  508. /**
  509. * {@inheritdoc}
  510. */
  511. public function fields(array $fields) {
  512. $fulltext_fields = $this->index->getFulltextFields();
  513. foreach (array_diff($fields, $fulltext_fields) as $field) {
  514. throw new SearchApiException(t('Trying to search on field @field which is no indexed fulltext field.', array('@field' => $field)));
  515. }
  516. $this->fields = $fields;
  517. return $this;
  518. }
  519. /**
  520. * {@inheritdoc}
  521. */
  522. public function filter(SearchApiQueryFilterInterface $filter) {
  523. $this->filter->filter($filter);
  524. return $this;
  525. }
  526. /**
  527. * {@inheritdoc}
  528. */
  529. public function condition($field, $value, $operator = '=') {
  530. $this->filter->condition($field, $value, $operator);
  531. return $this;
  532. }
  533. /**
  534. * {@inheritdoc}
  535. */
  536. public function sort($field, $order = 'ASC') {
  537. $fields = $this->index->options['fields'];
  538. $fields += array(
  539. 'search_api_relevance' => array('type' => 'decimal'),
  540. 'search_api_id' => array('type' => 'integer'),
  541. );
  542. if (empty($fields[$field])) {
  543. throw new SearchApiException(t('Trying to sort on unknown field @field.', array('@field' => $field)));
  544. }
  545. $type = $fields[$field]['type'];
  546. if (search_api_is_list_type($type) || search_api_is_text_type($type)) {
  547. throw new SearchApiException(t('Trying to sort on field @field of illegal type @type.', array('@field' => $field, '@type' => $type)));
  548. }
  549. $order = strtoupper(trim($order)) == 'DESC' ? 'DESC' : 'ASC';
  550. $this->sort[$field] = $order;
  551. return $this;
  552. }
  553. /**
  554. * {@inheritdoc}
  555. */
  556. public function range($offset = NULL, $limit = NULL) {
  557. $this->options['offset'] = $offset;
  558. $this->options['limit'] = $limit;
  559. return $this;
  560. }
  561. /**
  562. * {@inheritdoc}
  563. */
  564. public function execute() {
  565. $start = microtime(TRUE);
  566. // Prepare the query for execution by the server.
  567. $this->preExecute();
  568. $pre_search = microtime(TRUE);
  569. // Execute query.
  570. $response = $this->index->server()->search($this);
  571. $post_search = microtime(TRUE);
  572. // Postprocess the search results.
  573. $this->postExecute($response);
  574. $end = microtime(TRUE);
  575. $response['performance']['complete'] = $end - $start;
  576. $response['performance']['hooks'] = $response['performance']['complete'] - ($post_search - $pre_search);
  577. // Store search for later retrieval for facets, etc.
  578. search_api_current_search(NULL, $this, $response);
  579. return $response;
  580. }
  581. /**
  582. * Adds language filters for the query.
  583. *
  584. * Internal helper function.
  585. *
  586. * @param array $languages
  587. * The languages for which results should be returned.
  588. *
  589. * @throws SearchApiException
  590. * If there was a logical error in the combination of filters and languages.
  591. */
  592. protected function addLanguages(array $languages) {
  593. if (array_search(LANGUAGE_NONE, $languages) === FALSE) {
  594. $languages[] = LANGUAGE_NONE;
  595. }
  596. $languages = drupal_map_assoc($languages);
  597. $langs_to_add = $languages;
  598. $filters = $this->filter->getFilters();
  599. while ($filters && $langs_to_add) {
  600. $filter = array_shift($filters);
  601. if (is_array($filter)) {
  602. if ($filter[0] == 'search_api_language' && $filter[2] == '=') {
  603. $lang = $filter[1];
  604. if (isset($languages[$lang])) {
  605. unset($langs_to_add[$lang]);
  606. }
  607. else {
  608. throw new SearchApiException(t('Impossible combination of filters and languages. There is a filter for "@language", but allowed languages are: "@languages".', array('@language' => $lang, '@languages' => implode('", "', $languages))));
  609. }
  610. }
  611. }
  612. else {
  613. if ($filter->getConjunction() == 'AND') {
  614. $filters += $filter->getFilters();
  615. }
  616. }
  617. }
  618. if ($langs_to_add) {
  619. if (count($langs_to_add) == 1) {
  620. $this->condition('search_api_language', reset($langs_to_add));
  621. }
  622. else {
  623. $filter = $this->createFilter('OR');
  624. foreach ($langs_to_add as $lang) {
  625. $filter->condition('search_api_language', $lang);
  626. }
  627. $this->filter($filter);
  628. }
  629. }
  630. }
  631. /**
  632. * {@inheritdoc}
  633. */
  634. public function preExecute() {
  635. // Make sure to only execute this once per query.
  636. if (!$this->pre_execute) {
  637. $this->pre_execute = TRUE;
  638. // Add filter for languages.
  639. if (isset($this->options['languages'])) {
  640. $this->addLanguages($this->options['languages']);
  641. }
  642. // Add fulltext fields, unless set
  643. if ($this->fields === NULL) {
  644. $this->fields = $this->index->getFulltextFields();
  645. }
  646. // Preprocess query.
  647. $this->index->preprocessSearchQuery($this);
  648. // Let modules alter the query.
  649. drupal_alter('search_api_query', $this);
  650. }
  651. }
  652. /**
  653. * {@inheritdoc}
  654. */
  655. public function postExecute(array &$results) {
  656. // Postprocess results.
  657. $this->index->postprocessSearchResults($results, $this);
  658. }
  659. /**
  660. * {@inheritdoc}
  661. */
  662. public function getIndex() {
  663. return $this->index;
  664. }
  665. /**
  666. * {@inheritdoc}
  667. */
  668. public function &getKeys() {
  669. return $this->keys;
  670. }
  671. /**
  672. * {@inheritdoc}
  673. */
  674. public function getOriginalKeys() {
  675. return $this->orig_keys;
  676. }
  677. /**
  678. * {@inheritdoc}
  679. */
  680. public function &getFields() {
  681. return $this->fields;
  682. }
  683. /**
  684. * {@inheritdoc}
  685. */
  686. public function getFilter() {
  687. return $this->filter;
  688. }
  689. /**
  690. * {@inheritdoc}
  691. */
  692. public function &getSort() {
  693. return $this->sort;
  694. }
  695. /**
  696. * {@inheritdoc}
  697. */
  698. public function getOption($name, $default = NULL) {
  699. return array_key_exists($name, $this->options) ? $this->options[$name] : $default;
  700. }
  701. /**
  702. * {@inheritdoc}
  703. */
  704. public function setOption($name, $value) {
  705. $old = $this->getOption($name);
  706. $this->options[$name] = $value;
  707. return $old;
  708. }
  709. /**
  710. * {@inheritdoc}
  711. */
  712. public function &getOptions() {
  713. return $this->options;
  714. }
  715. /**
  716. * Implements the magic __sleep() method to avoid serializing the index.
  717. */
  718. public function __sleep() {
  719. $this->index_id = $this->index->machine_name;
  720. $keys = get_object_vars($this);
  721. unset($keys['index']);
  722. return array_keys($keys);
  723. }
  724. /**
  725. * Implements the magic __wakeup() method to reload the query's index.
  726. */
  727. public function __wakeup() {
  728. if (!isset($this->index) && !empty($this->index_id)) {
  729. $this->index = search_api_index_load($this->index_id);
  730. unset($this->index_id);
  731. }
  732. }
  733. /**
  734. * Implements the magic __clone() method to clone the filter, too.
  735. */
  736. public function __clone() {
  737. $this->filter = clone $this->filter;
  738. }
  739. }
  740. /**
  741. * Represents a filter on a search query.
  742. *
  743. * Filters apply conditions on one or more fields with a specific conjunction
  744. * (AND or OR) and may contain nested filters.
  745. */
  746. interface SearchApiQueryFilterInterface {
  747. /**
  748. * Constructs a new filter that uses the specified conjunction.
  749. *
  750. * @param string $conjunction
  751. * (optional) The conjunction to use for this filter - either 'AND' or 'OR'.
  752. * @param array $tags
  753. * (optional) An arbitrary set of tags. Can be used to identify this filter
  754. * down the line if necessary. This is primarily used by the facet system
  755. * to support OR facet queries.
  756. */
  757. public function __construct($conjunction = 'AND', array $tags = array());
  758. /**
  759. * Sets this filter's conjunction.
  760. *
  761. * @param string $conjunction
  762. * The conjunction to use for this filter - either 'AND' or 'OR'.
  763. *
  764. * @return SearchApiQueryFilterInterface
  765. * The called object.
  766. */
  767. public function setConjunction($conjunction);
  768. /**
  769. * Adds a subfilter.
  770. *
  771. * @param SearchApiQueryFilterInterface $filter
  772. * A SearchApiQueryFilterInterface object that should be added as a
  773. * subfilter.
  774. *
  775. * @return SearchApiQueryFilterInterface
  776. * The called object.
  777. */
  778. public function filter(SearchApiQueryFilterInterface $filter);
  779. /**
  780. * Adds a new ($field $operator $value) condition.
  781. *
  782. * @param string $field
  783. * The field to filter on, e.g. 'title'.
  784. * @param mixed $value
  785. * The value the field should have (or be related to by the operator).
  786. * @param string $operator
  787. * The operator to use for checking the constraint. The following operators
  788. * are supported for primitive types: "=", "<>", "<", "<=", ">=", ">". They
  789. * have the same semantics as the corresponding SQL operators.
  790. * If $field is a fulltext field, $operator can only be "=" or "<>", which
  791. * are in this case interpreted as "contains" or "doesn't contain",
  792. * respectively.
  793. * If $value is NULL, $operator also can only be "=" or "<>", meaning the
  794. * field must have no or some value, respectively.
  795. *
  796. * @return SearchApiQueryFilterInterface
  797. * The called object.
  798. */
  799. public function condition($field, $value, $operator = '=');
  800. /**
  801. * Retrieves the conjunction used by this filter.
  802. *
  803. * @return string
  804. * The conjunction used by this filter - either 'AND' or 'OR'.
  805. */
  806. public function getConjunction();
  807. /**
  808. * Return all conditions and nested filters contained in this filter.
  809. *
  810. * @return array
  811. * An array containing this filter's subfilters. Each of these is either an
  812. * array (field, value, operator), or another SearchApiFilter object.
  813. */
  814. public function &getFilters();
  815. /**
  816. * Checks whether a certain tag was set on this filter.
  817. *
  818. * @param string $tag
  819. * A tag to check for.
  820. *
  821. * @return bool
  822. * TRUE if the tag was set for this filter, FALSE otherwise.
  823. */
  824. public function hasTag($tag);
  825. /**
  826. * Retrieves the tags set on this filter.
  827. *
  828. * @return array
  829. * The tags associated with this filter, as both the array keys and values.
  830. */
  831. public function &getTags();
  832. }
  833. /**
  834. * Provides a standard implementation of SearchApiQueryFilterInterface.
  835. */
  836. class SearchApiQueryFilter implements SearchApiQueryFilterInterface {
  837. /**
  838. * Array containing subfilters.
  839. *
  840. * Each of these is either an array (field, value, operator), or another
  841. * SearchApiFilter object.
  842. *
  843. * @var array
  844. */
  845. protected $filters;
  846. /**
  847. * String specifying this filter's conjunction ('AND' or 'OR').
  848. *
  849. * @var string
  850. */
  851. protected $conjunction;
  852. /**
  853. * {@inheritdoc}
  854. */
  855. public function __construct($conjunction = 'AND', array $tags = array()) {
  856. $this->setConjunction($conjunction);
  857. $this->filters = array();
  858. $this->tags = drupal_map_assoc($tags);
  859. }
  860. /**
  861. * {@inheritdoc}
  862. */
  863. public function setConjunction($conjunction) {
  864. $this->conjunction = strtoupper(trim($conjunction)) == 'OR' ? 'OR' : 'AND';
  865. return $this;
  866. }
  867. /**
  868. * {@inheritdoc}
  869. */
  870. public function filter(SearchApiQueryFilterInterface $filter) {
  871. $this->filters[] = $filter;
  872. return $this;
  873. }
  874. /**
  875. * {@inheritdoc}
  876. */
  877. public function condition($field, $value, $operator = '=') {
  878. $this->filters[] = array($field, $value, $operator);
  879. return $this;
  880. }
  881. /**
  882. * {@inheritdoc}
  883. */
  884. public function getConjunction() {
  885. return $this->conjunction;
  886. }
  887. /**
  888. * {@inheritdoc}
  889. */
  890. public function &getFilters() {
  891. return $this->filters;
  892. }
  893. /**
  894. * {@inheritdoc}
  895. */
  896. public function hasTag($tag) {
  897. return isset($this->tags[$tag]);
  898. }
  899. /**
  900. * {@inheritdoc}
  901. */
  902. public function &getTags() {
  903. return $this->tags;
  904. }
  905. /**
  906. * Implements the magic __clone() method to clone nested filters, too.
  907. */
  908. public function __clone() {
  909. foreach ($this->filters as $i => $filter) {
  910. if (is_object($filter)) {
  911. $this->filters[$i] = clone $filter;
  912. }
  913. }
  914. }
  915. }