query.inc 31 KB

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