query.inc 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. * @throws SearchApiException
  218. * If any error occurred during the preparation of the query.
  219. */
  220. public function preExecute();
  221. /**
  222. * Postprocesses the search results before they are returned.
  223. *
  224. * This method should always be called by execute() and contain all necessary
  225. * operations after the results are returned from the server.
  226. *
  227. * @param array $results
  228. * The results returned by the server, which may be altered. The data
  229. * structure is the same as returned by execute().
  230. */
  231. public function postExecute(array &$results);
  232. /**
  233. * Retrieves the index associated with this search.
  234. *
  235. * @return SearchApiIndex
  236. * The search index this query should be executed on.
  237. */
  238. public function getIndex();
  239. /**
  240. * Retrieves the search keys for this query.
  241. *
  242. * @return array|string|null
  243. * This object's search keys - either a string or an array specifying a
  244. * complex search expression.
  245. * An array will contain a '#conjunction' key specifying the conjunction
  246. * type, and search strings or nested expression arrays at numeric keys.
  247. * Additionally, a '#negation' key might be present, which means – unless it
  248. * maps to a FALSE value – that the search keys contained in that array
  249. * should be negated, i.e. not be present in returned results. The negation
  250. * works on the whole array, not on each contained term individually – i.e.,
  251. * with the "AND" conjunction and negation, only results that contain all
  252. * the terms in the array should be excluded; with the "OR" conjunction and
  253. * negation, all results containing one or more of the terms in the array
  254. * should be excluded.
  255. *
  256. * @see keys()
  257. */
  258. public function &getKeys();
  259. /**
  260. * Retrieves the unparsed search keys for this query as originally entered.
  261. *
  262. * @return array|string|null
  263. * The unprocessed search keys, exactly as passed to this object. Has the
  264. * same format as the return value of getKeys().
  265. *
  266. * @see keys()
  267. */
  268. public function getOriginalKeys();
  269. /**
  270. * Retrieves the fulltext fields that will be searched for the search keys.
  271. *
  272. * @return array
  273. * An array containing the fields that should be searched for the search
  274. * keys.
  275. *
  276. * @see fields()
  277. */
  278. public function &getFields();
  279. /**
  280. * Retrieves the filter object associated with this search query.
  281. *
  282. * @return SearchApiQueryFilterInterface
  283. * This object's associated filter object.
  284. */
  285. public function getFilter();
  286. /**
  287. * Retrieves the sorts set for this query.
  288. *
  289. * @return array
  290. * An array specifying the sort order for this query. Array keys are the
  291. * field names in order of importance, the values are the respective order
  292. * in which to sort the results according to the field.
  293. *
  294. * @see sort()
  295. */
  296. public function &getSort();
  297. /**
  298. * Retrieves an option set on this search query.
  299. *
  300. * @param string $name
  301. * The name of an option.
  302. * @param mixed $default
  303. * The value to return if the specified option is not set.
  304. *
  305. * @return mixed
  306. * The value of the option with the specified name, if set. NULL otherwise.
  307. */
  308. public function getOption($name, $default = NULL);
  309. /**
  310. * Sets an option for this search query.
  311. *
  312. * @param string $name
  313. * The name of an option.
  314. * @param mixed $value
  315. * The new value of the option.
  316. *
  317. * @return mixed
  318. * The option's previous value.
  319. */
  320. public function setOption($name, $value);
  321. /**
  322. * Retrieves all options set for this search query.
  323. *
  324. * The return value is a reference to the options so they can also be altered
  325. * this way.
  326. *
  327. * @return array
  328. * An associative array of query options.
  329. */
  330. public function &getOptions();
  331. }
  332. /**
  333. * Provides a standard implementation of the SearchApiQueryInterface.
  334. */
  335. class SearchApiQuery implements SearchApiQueryInterface {
  336. /**
  337. * The index this query will use.
  338. *
  339. * @var SearchApiIndex
  340. */
  341. protected $index;
  342. /**
  343. * The index's machine name.
  344. *
  345. * Used during serialization to avoid serializing the whole index object.
  346. *
  347. * @var string
  348. */
  349. protected $index_id;
  350. /**
  351. * The search keys. If NULL, this will be a filter-only search.
  352. *
  353. * @var mixed
  354. */
  355. protected $keys;
  356. /**
  357. * The unprocessed search keys, as passed to the keys() method.
  358. *
  359. * @var mixed
  360. */
  361. protected $orig_keys;
  362. /**
  363. * The fields that will be searched for the keys.
  364. *
  365. * @var array
  366. */
  367. protected $fields;
  368. /**
  369. * The search filter associated with this query.
  370. *
  371. * @var SearchApiQueryFilterInterface
  372. */
  373. protected $filter;
  374. /**
  375. * The sort associated with this query.
  376. *
  377. * @var array
  378. */
  379. protected $sort;
  380. /**
  381. * Search options configuring this query.
  382. *
  383. * @var array
  384. */
  385. protected $options;
  386. /**
  387. * Flag for whether preExecute() was already called for this query.
  388. *
  389. * @var bool
  390. */
  391. protected $pre_execute = FALSE;
  392. /**
  393. * {@inheritdoc}
  394. */
  395. public function __construct(SearchApiIndex $index, array $options = array()) {
  396. if (empty($index->options['fields'])) {
  397. throw new SearchApiException(t("Can't search an index which hasn't got any fields defined."));
  398. }
  399. if (empty($index->enabled)) {
  400. throw new SearchApiException(t("Can't search a disabled index."));
  401. }
  402. if (isset($options['parse mode'])) {
  403. $modes = $this->parseModes();
  404. if (!isset($modes[$options['parse mode']])) {
  405. throw new SearchApiException(t('Unknown parse mode: @mode.', array('@mode' => $options['parse mode'])));
  406. }
  407. }
  408. $this->index = $index;
  409. $this->options = $options + array(
  410. 'conjunction' => 'AND',
  411. 'parse mode' => 'terms',
  412. 'filter class' => 'SearchApiQueryFilter',
  413. 'search id' => __CLASS__,
  414. );
  415. $this->filter = $this->createFilter('AND');
  416. $this->sort = array();
  417. }
  418. /**
  419. * {@inheritdoc}
  420. */
  421. public function parseModes() {
  422. $modes['direct'] = array(
  423. 'name' => t('Direct query'),
  424. 'description' => t("Don't parse the query, just hand it to the search server unaltered. " .
  425. "Might fail if the query contains syntax errors in regard to the specific server's query syntax."),
  426. );
  427. $modes['single'] = array(
  428. 'name' => t('Single term'),
  429. 'description' => t('The query is interpreted as a single keyword, maybe containing spaces or special characters.'),
  430. );
  431. $modes['terms'] = array(
  432. 'name' => t('Multiple terms'),
  433. 'description' => t('The query is interpreted as multiple keywords seperated by spaces. ' .
  434. 'Keywords containing spaces may be "quoted". Quoted keywords must still be seperated by spaces.'),
  435. );
  436. // @todo Add fourth mode for complicated expressions, e.g.: »"vanilla ice" OR (love NOT hate)«
  437. return $modes;
  438. }
  439. /**
  440. * {@inheritdoc}
  441. */
  442. protected function parseKeys($keys, $mode) {
  443. if ($keys === NULL || is_array($keys)) {
  444. return $keys;
  445. }
  446. $keys = '' . $keys;
  447. switch ($mode) {
  448. case 'direct':
  449. return $keys;
  450. case 'single':
  451. return array('#conjunction' => $this->options['conjunction'], $keys);
  452. case 'terms':
  453. $ret = preg_split('/\s+/u', $keys);
  454. $quoted = FALSE;
  455. $str = '';
  456. foreach ($ret as $k => $v) {
  457. if (!$v) {
  458. continue;
  459. }
  460. if ($quoted) {
  461. if (substr($v, -1) == '"') {
  462. $v = substr($v, 0, -1);
  463. $str .= ' ' . $v;
  464. $ret[$k] = $str;
  465. $quoted = FALSE;
  466. }
  467. else {
  468. $str .= ' ' . $v;
  469. unset($ret[$k]);
  470. }
  471. }
  472. elseif ($v[0] == '"') {
  473. $len = strlen($v);
  474. if ($len > 1 && $v[$len-1] == '"') {
  475. $ret[$k] = substr($v, 1, -1);
  476. }
  477. else {
  478. $str = substr($v, 1);
  479. $quoted = TRUE;
  480. unset($ret[$k]);
  481. }
  482. }
  483. }
  484. if ($quoted) {
  485. $ret[] = $str;
  486. }
  487. $ret['#conjunction'] = $this->options['conjunction'];
  488. return array_filter($ret);
  489. }
  490. }
  491. /**
  492. * {@inheritdoc}
  493. */
  494. public function createFilter($conjunction = 'AND', $tags = array()) {
  495. $filter_class = $this->options['filter class'];
  496. return new $filter_class($conjunction, $tags);
  497. }
  498. /**
  499. * {@inheritdoc}
  500. */
  501. public function keys($keys = NULL) {
  502. $this->orig_keys = $keys;
  503. if (isset($keys)) {
  504. $this->keys = $this->parseKeys($keys, $this->options['parse mode']);
  505. }
  506. else {
  507. $this->keys = NULL;
  508. }
  509. return $this;
  510. }
  511. /**
  512. * {@inheritdoc}
  513. */
  514. public function fields(array $fields) {
  515. $fulltext_fields = $this->index->getFulltextFields();
  516. foreach (array_diff($fields, $fulltext_fields) as $field) {
  517. throw new SearchApiException(t('Trying to search on field @field which is no indexed fulltext field.', array('@field' => $field)));
  518. }
  519. $this->fields = $fields;
  520. return $this;
  521. }
  522. /**
  523. * {@inheritdoc}
  524. */
  525. public function filter(SearchApiQueryFilterInterface $filter) {
  526. $this->filter->filter($filter);
  527. return $this;
  528. }
  529. /**
  530. * {@inheritdoc}
  531. */
  532. public function condition($field, $value, $operator = '=') {
  533. $this->filter->condition($field, $value, $operator);
  534. return $this;
  535. }
  536. /**
  537. * {@inheritdoc}
  538. */
  539. public function sort($field, $order = 'ASC') {
  540. $fields = $this->index->options['fields'];
  541. $fields += array(
  542. 'search_api_relevance' => array('type' => 'decimal'),
  543. 'search_api_id' => array('type' => 'integer'),
  544. );
  545. if (empty($fields[$field])) {
  546. throw new SearchApiException(t('Trying to sort on unknown field @field.', array('@field' => $field)));
  547. }
  548. $type = $fields[$field]['type'];
  549. if (search_api_is_list_type($type) || search_api_is_text_type($type)) {
  550. throw new SearchApiException(t('Trying to sort on field @field of illegal type @type.', array('@field' => $field, '@type' => $type)));
  551. }
  552. $order = strtoupper(trim($order)) == 'DESC' ? 'DESC' : 'ASC';
  553. $this->sort[$field] = $order;
  554. return $this;
  555. }
  556. /**
  557. * {@inheritdoc}
  558. */
  559. public function range($offset = NULL, $limit = NULL) {
  560. $this->options['offset'] = $offset;
  561. $this->options['limit'] = $limit;
  562. return $this;
  563. }
  564. /**
  565. * {@inheritdoc}
  566. */
  567. public function execute() {
  568. $start = microtime(TRUE);
  569. // Prepare the query for execution by the server.
  570. $this->preExecute();
  571. $pre_search = microtime(TRUE);
  572. // Execute query.
  573. $response = $this->index->server()->search($this);
  574. $post_search = microtime(TRUE);
  575. // Postprocess the search results.
  576. $this->postExecute($response);
  577. $end = microtime(TRUE);
  578. $response['performance']['complete'] = $end - $start;
  579. $response['performance']['hooks'] = $response['performance']['complete'] - ($post_search - $pre_search);
  580. // Store search for later retrieval for facets, etc.
  581. search_api_current_search(NULL, $this, $response);
  582. return $response;
  583. }
  584. /**
  585. * Adds language filters for the query.
  586. *
  587. * Internal helper function.
  588. *
  589. * @param array $languages
  590. * The languages for which results should be returned.
  591. *
  592. * @throws SearchApiException
  593. * If there was a logical error in the combination of filters and languages.
  594. */
  595. protected function addLanguages(array $languages) {
  596. if (array_search(LANGUAGE_NONE, $languages) === FALSE) {
  597. $languages[] = LANGUAGE_NONE;
  598. }
  599. $languages = drupal_map_assoc($languages);
  600. $langs_to_add = $languages;
  601. $filters = $this->filter->getFilters();
  602. while ($filters && $langs_to_add) {
  603. $filter = array_shift($filters);
  604. if (is_array($filter)) {
  605. if ($filter[0] == 'search_api_language' && $filter[2] == '=') {
  606. $lang = $filter[1];
  607. if (isset($languages[$lang])) {
  608. unset($langs_to_add[$lang]);
  609. }
  610. else {
  611. 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))));
  612. }
  613. }
  614. }
  615. else {
  616. if ($filter->getConjunction() == 'AND') {
  617. $filters += $filter->getFilters();
  618. }
  619. }
  620. }
  621. if ($langs_to_add) {
  622. if (count($langs_to_add) == 1) {
  623. $this->condition('search_api_language', reset($langs_to_add));
  624. }
  625. else {
  626. $filter = $this->createFilter('OR');
  627. foreach ($langs_to_add as $lang) {
  628. $filter->condition('search_api_language', $lang);
  629. }
  630. $this->filter($filter);
  631. }
  632. }
  633. }
  634. /**
  635. * {@inheritdoc}
  636. */
  637. public function preExecute() {
  638. // Make sure to only execute this once per query.
  639. if (!$this->pre_execute) {
  640. $this->pre_execute = TRUE;
  641. // Add filter for languages.
  642. if (isset($this->options['languages'])) {
  643. $this->addLanguages($this->options['languages']);
  644. }
  645. // Add fulltext fields, unless set
  646. if ($this->fields === NULL) {
  647. $this->fields = $this->index->getFulltextFields();
  648. }
  649. // Preprocess query.
  650. $this->index->preprocessSearchQuery($this);
  651. // Let modules alter the query.
  652. drupal_alter('search_api_query', $this);
  653. }
  654. }
  655. /**
  656. * {@inheritdoc}
  657. */
  658. public function postExecute(array &$results) {
  659. // Postprocess results.
  660. $this->index->postprocessSearchResults($results, $this);
  661. }
  662. /**
  663. * {@inheritdoc}
  664. */
  665. public function getIndex() {
  666. return $this->index;
  667. }
  668. /**
  669. * {@inheritdoc}
  670. */
  671. public function &getKeys() {
  672. return $this->keys;
  673. }
  674. /**
  675. * {@inheritdoc}
  676. */
  677. public function getOriginalKeys() {
  678. return $this->orig_keys;
  679. }
  680. /**
  681. * {@inheritdoc}
  682. */
  683. public function &getFields() {
  684. return $this->fields;
  685. }
  686. /**
  687. * {@inheritdoc}
  688. */
  689. public function getFilter() {
  690. return $this->filter;
  691. }
  692. /**
  693. * {@inheritdoc}
  694. */
  695. public function &getSort() {
  696. return $this->sort;
  697. }
  698. /**
  699. * {@inheritdoc}
  700. */
  701. public function getOption($name, $default = NULL) {
  702. return array_key_exists($name, $this->options) ? $this->options[$name] : $default;
  703. }
  704. /**
  705. * {@inheritdoc}
  706. */
  707. public function setOption($name, $value) {
  708. $old = $this->getOption($name);
  709. $this->options[$name] = $value;
  710. return $old;
  711. }
  712. /**
  713. * {@inheritdoc}
  714. */
  715. public function &getOptions() {
  716. return $this->options;
  717. }
  718. /**
  719. * Implements the magic __sleep() method to avoid serializing the index.
  720. */
  721. public function __sleep() {
  722. $this->index_id = $this->index->machine_name;
  723. $keys = get_object_vars($this);
  724. unset($keys['index']);
  725. return array_keys($keys);
  726. }
  727. /**
  728. * Implements the magic __wakeup() method to reload the query's index.
  729. */
  730. public function __wakeup() {
  731. if (!isset($this->index) && !empty($this->index_id)) {
  732. $this->index = search_api_index_load($this->index_id);
  733. unset($this->index_id);
  734. }
  735. }
  736. /**
  737. * Implements the magic __clone() method to clone the filter, too.
  738. */
  739. public function __clone() {
  740. $this->filter = clone $this->filter;
  741. }
  742. /**
  743. * Implements the magic __toString() method to simplify debugging.
  744. */
  745. public function __toString() {
  746. $ret = 'Index: ' . $this->index->machine_name . "\n";
  747. $ret .= 'Keys: ' . str_replace("\n", "\n ", var_export($this->orig_keys, TRUE)) . "\n";
  748. if (isset($this->keys)) {
  749. $ret .= 'Parsed keys: ' . str_replace("\n", "\n ", var_export($this->keys, TRUE)) . "\n";
  750. $ret .= 'Searched fields: ' . (isset($this->fields) ? implode(', ', $this->fields) : '[ALL]') . "\n";
  751. }
  752. if ($filter = (string) $this->filter) {
  753. $filter = str_replace("\n", "\n ", $filter);
  754. $ret .= "Filters:\n $filter\n";
  755. }
  756. if ($this->sort) {
  757. $sort = array();
  758. foreach ($this->sort as $field => $order) {
  759. $sort[] = "$field $order";
  760. }
  761. $ret .= 'Sorting: ' . implode(', ', $sort) . "\n";
  762. }
  763. $ret .= 'Options: ' . str_replace("\n", "\n ", var_export($this->options, TRUE)) . "\n";
  764. return $ret;
  765. }
  766. }
  767. /**
  768. * Represents a filter on a search query.
  769. *
  770. * Filters apply conditions on one or more fields with a specific conjunction
  771. * (AND or OR) and may contain nested filters.
  772. */
  773. interface SearchApiQueryFilterInterface {
  774. /**
  775. * Constructs a new filter that uses the specified conjunction.
  776. *
  777. * @param string $conjunction
  778. * (optional) The conjunction to use for this filter - either 'AND' or 'OR'.
  779. * @param array $tags
  780. * (optional) An arbitrary set of tags. Can be used to identify this filter
  781. * down the line if necessary. This is primarily used by the facet system
  782. * to support OR facet queries.
  783. */
  784. public function __construct($conjunction = 'AND', array $tags = array());
  785. /**
  786. * Sets this filter's conjunction.
  787. *
  788. * @param string $conjunction
  789. * The conjunction to use for this filter - either 'AND' or 'OR'.
  790. *
  791. * @return SearchApiQueryFilterInterface
  792. * The called object.
  793. */
  794. public function setConjunction($conjunction);
  795. /**
  796. * Adds a subfilter.
  797. *
  798. * @param SearchApiQueryFilterInterface $filter
  799. * A SearchApiQueryFilterInterface object that should be added as a
  800. * subfilter.
  801. *
  802. * @return SearchApiQueryFilterInterface
  803. * The called object.
  804. */
  805. public function filter(SearchApiQueryFilterInterface $filter);
  806. /**
  807. * Adds a new ($field $operator $value) condition.
  808. *
  809. * @param string $field
  810. * The field to filter on, e.g. 'title'.
  811. * @param mixed $value
  812. * The value the field should have (or be related to by the operator).
  813. * @param string $operator
  814. * The operator to use for checking the constraint. The following operators
  815. * are supported for primitive types: "=", "<>", "<", "<=", ">=", ">". They
  816. * have the same semantics as the corresponding SQL operators.
  817. * If $field is a fulltext field, $operator can only be "=" or "<>", which
  818. * are in this case interpreted as "contains" or "doesn't contain",
  819. * respectively.
  820. * If $value is NULL, $operator also can only be "=" or "<>", meaning the
  821. * field must have no or some value, respectively.
  822. *
  823. * @return SearchApiQueryFilterInterface
  824. * The called object.
  825. */
  826. public function condition($field, $value, $operator = '=');
  827. /**
  828. * Retrieves the conjunction used by this filter.
  829. *
  830. * @return string
  831. * The conjunction used by this filter - either 'AND' or 'OR'.
  832. */
  833. public function getConjunction();
  834. /**
  835. * Return all conditions and nested filters contained in this filter.
  836. *
  837. * @return array
  838. * An array containing this filter's subfilters. Each of these is either a
  839. * condition, represented as a numerically indexed array with the arguments
  840. * of a previous SearchApiQueryFilterInterface::condition() call (field,
  841. * value, operator); or a nested filter, represented by a
  842. * SearchApiQueryFilterInterface filter object.
  843. */
  844. public function &getFilters();
  845. /**
  846. * Checks whether a certain tag was set on this filter.
  847. *
  848. * @param string $tag
  849. * A tag to check for.
  850. *
  851. * @return bool
  852. * TRUE if the tag was set for this filter, FALSE otherwise.
  853. */
  854. public function hasTag($tag);
  855. /**
  856. * Retrieves the tags set on this filter.
  857. *
  858. * @return array
  859. * The tags associated with this filter, as both the array keys and values.
  860. */
  861. public function &getTags();
  862. }
  863. /**
  864. * Provides a standard implementation of SearchApiQueryFilterInterface.
  865. */
  866. class SearchApiQueryFilter implements SearchApiQueryFilterInterface {
  867. /**
  868. * Array containing subfilters.
  869. *
  870. * Each of these is either an array (field, value, operator), or another
  871. * SearchApiFilter object.
  872. *
  873. * @var array
  874. */
  875. protected $filters;
  876. /**
  877. * String specifying this filter's conjunction ('AND' or 'OR').
  878. *
  879. * @var string
  880. */
  881. protected $conjunction;
  882. /**
  883. * {@inheritdoc}
  884. */
  885. public function __construct($conjunction = 'AND', array $tags = array()) {
  886. $this->setConjunction($conjunction);
  887. $this->filters = array();
  888. $this->tags = drupal_map_assoc($tags);
  889. }
  890. /**
  891. * {@inheritdoc}
  892. */
  893. public function setConjunction($conjunction) {
  894. $this->conjunction = strtoupper(trim($conjunction)) == 'OR' ? 'OR' : 'AND';
  895. return $this;
  896. }
  897. /**
  898. * {@inheritdoc}
  899. */
  900. public function filter(SearchApiQueryFilterInterface $filter) {
  901. $this->filters[] = $filter;
  902. return $this;
  903. }
  904. /**
  905. * {@inheritdoc}
  906. */
  907. public function condition($field, $value, $operator = '=') {
  908. $this->filters[] = array($field, $value, $operator);
  909. return $this;
  910. }
  911. /**
  912. * {@inheritdoc}
  913. */
  914. public function getConjunction() {
  915. return $this->conjunction;
  916. }
  917. /**
  918. * {@inheritdoc}
  919. */
  920. public function &getFilters() {
  921. return $this->filters;
  922. }
  923. /**
  924. * {@inheritdoc}
  925. */
  926. public function hasTag($tag) {
  927. return isset($this->tags[$tag]);
  928. }
  929. /**
  930. * {@inheritdoc}
  931. */
  932. public function &getTags() {
  933. return $this->tags;
  934. }
  935. /**
  936. * Implements the magic __clone() method to clone nested filters, too.
  937. */
  938. public function __clone() {
  939. foreach ($this->filters as $i => $filter) {
  940. if (is_object($filter)) {
  941. $this->filters[$i] = clone $filter;
  942. }
  943. }
  944. }
  945. /**
  946. * Implements the magic __toString() method to simplify debugging.
  947. */
  948. public function __toString() {
  949. // Special case for a single, nested filter:
  950. if (count($this->filters) == 1 && is_object($this->filters[0])) {
  951. return (string) $this->filters[0];
  952. }
  953. $ret = array();
  954. foreach ($this->filters as $filter) {
  955. if (is_object($filter)) {
  956. $ret[] = "[\n " . str_replace("\n", "\n ", (string) $filter) . "\n ]";
  957. }
  958. else {
  959. $ret[] = "$filter[0] $filter[2] " . str_replace("\n", "\n ", var_export($filter[1], TRUE));
  960. }
  961. }
  962. return $ret ? ' ' . implode("\n{$this->conjunction}\n ", $ret) : '';
  963. }
  964. }