query.inc 31 KB

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