search.api.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <?php
  2. /**
  3. * @file
  4. * Hooks provided by the Search module.
  5. */
  6. /**
  7. * @addtogroup hooks
  8. * @{
  9. */
  10. /**
  11. * Define a custom search type.
  12. *
  13. * This hook allows a module to tell search.module that it wishes to perform
  14. * searches on content it defines (custom node types, users, or comments for
  15. * example) when a site search is performed.
  16. *
  17. * In order for the search to do anything, your module must also implement
  18. * hook_search_execute(), which is called when someone requests a search
  19. * on your module's type of content. If you want to have your content
  20. * indexed in the standard search index, your module should also implement
  21. * hook_update_index(). If your search type has settings, you can implement
  22. * hook_search_admin() to add them to the search settings page. You can use
  23. * hook_form_FORM_ID_alter(), with FORM_ID set to 'search_form', to add fields
  24. * to the search form (see node_form_search_form_alter() for an example).
  25. * You can use hook_search_access() to limit access to searching,
  26. * and hook_search_page() to override how search results are displayed.
  27. *
  28. * @return
  29. * Array with optional keys:
  30. * - title: Title for the tab on the search page for this module. Defaults
  31. * to the module name if not given.
  32. * - path: Path component after 'search/' for searching with this module.
  33. * Defaults to the module name if not given.
  34. * - conditions_callback: An implementation of callback_search_conditions().
  35. *
  36. * @ingroup search
  37. */
  38. function hook_search_info() {
  39. return array(
  40. 'title' => 'Content',
  41. 'path' => 'node',
  42. 'conditions_callback' => 'callback_search_conditions',
  43. );
  44. }
  45. /**
  46. * Define access to a custom search routine.
  47. *
  48. * This hook allows a module to define permissions for a search tab.
  49. *
  50. * @ingroup search
  51. */
  52. function hook_search_access() {
  53. return user_access('access content');
  54. }
  55. /**
  56. * Take action when the search index is going to be rebuilt.
  57. *
  58. * Modules that use hook_update_index() should update their indexing
  59. * bookkeeping so that it starts from scratch the next time
  60. * hook_update_index() is called.
  61. *
  62. * @ingroup search
  63. */
  64. function hook_search_reset() {
  65. db_update('search_dataset')
  66. ->fields(array('reindex' => REQUEST_TIME))
  67. ->condition('type', 'node')
  68. ->execute();
  69. }
  70. /**
  71. * Report the status of indexing.
  72. *
  73. * The core search module only invokes this hook on active modules.
  74. * Implementing modules do not need to check whether they are active when
  75. * calculating their return values.
  76. *
  77. * @return
  78. * An associative array with the key-value pairs:
  79. * - 'remaining': The number of items left to index.
  80. * - 'total': The total number of items to index.
  81. *
  82. * @ingroup search
  83. */
  84. function hook_search_status() {
  85. $total = db_query('SELECT COUNT(*) FROM {node} WHERE status = 1')->fetchField();
  86. $remaining = db_query("SELECT COUNT(*) FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE n.status = 1 AND d.sid IS NULL OR d.reindex <> 0")->fetchField();
  87. return array('remaining' => $remaining, 'total' => $total);
  88. }
  89. /**
  90. * Add elements to the search settings form.
  91. *
  92. * @return
  93. * Form array for the Search settings page at admin/config/search/settings.
  94. *
  95. * @ingroup search
  96. */
  97. function hook_search_admin() {
  98. // Output form for defining rank factor weights.
  99. $form['content_ranking'] = array(
  100. '#type' => 'fieldset',
  101. '#title' => t('Content ranking'),
  102. );
  103. $form['content_ranking']['#theme'] = 'node_search_admin';
  104. $form['content_ranking']['info'] = array(
  105. '#value' => '<em>' . t('The following numbers control which properties the content search should favor when ordering the results. Higher numbers mean more influence, zero means the property is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em>'
  106. );
  107. // Note: reversed to reflect that higher number = higher ranking.
  108. $options = drupal_map_assoc(range(0, 10));
  109. foreach (module_invoke_all('ranking') as $var => $values) {
  110. $form['content_ranking']['factors']['node_rank_' . $var] = array(
  111. '#title' => $values['title'],
  112. '#type' => 'select',
  113. '#options' => $options,
  114. '#default_value' => variable_get('node_rank_' . $var, 0),
  115. );
  116. }
  117. return $form;
  118. }
  119. /**
  120. * Execute a search for a set of key words.
  121. *
  122. * Use database API with the 'PagerDefault' query extension to perform your
  123. * search.
  124. *
  125. * If your module uses hook_update_index() and search_index() to index its
  126. * items, use table 'search_index' aliased to 'i' as the main table in your
  127. * query, with the 'SearchQuery' extension. You can join to your module's table
  128. * using the 'i.sid' field, which will contain the $sid values you provided to
  129. * search_index(). Add the main keywords to the query by using method
  130. * searchExpression(). The functions search_expression_extract() and
  131. * search_expression_insert() may also be helpful for adding custom search
  132. * parameters to the search expression.
  133. *
  134. * See node_search_execute() for an example of a module that uses the search
  135. * index, and user_search_execute() for an example that doesn't use the search
  136. * index.
  137. *
  138. * @param $keys
  139. * The search keywords as entered by the user.
  140. * @param $conditions
  141. * An optional array of additional conditions, such as filters.
  142. *
  143. * @return
  144. * An array of search results. To use the default search result
  145. * display, each item should have the following keys':
  146. * - 'link': Required. The URL of the found item.
  147. * - 'type': The type of item (such as the content type).
  148. * - 'title': Required. The name of the item.
  149. * - 'user': The author of the item.
  150. * - 'date': A timestamp when the item was last modified.
  151. * - 'extra': An array of optional extra information items.
  152. * - 'snippet': An excerpt or preview to show with the result (can be
  153. * generated with search_excerpt()).
  154. * - 'language': Language code for the item (usually two characters).
  155. *
  156. * @ingroup search
  157. */
  158. function hook_search_execute($keys = NULL, $conditions = NULL) {
  159. // Build matching conditions
  160. $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
  161. $query->join('node', 'n', 'n.nid = i.sid');
  162. $query
  163. ->condition('n.status', 1)
  164. ->addTag('node_access')
  165. ->searchExpression($keys, 'node');
  166. // Insert special keywords.
  167. $query->setOption('type', 'n.type');
  168. $query->setOption('language', 'n.language');
  169. if ($query->setOption('term', 'ti.tid')) {
  170. $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  171. }
  172. // Only continue if the first pass query matches.
  173. if (!$query->executeFirstPass()) {
  174. return array();
  175. }
  176. // Add the ranking expressions.
  177. _node_rankings($query);
  178. // Load results.
  179. $find = $query
  180. ->limit(10)
  181. ->execute();
  182. $results = array();
  183. foreach ($find as $item) {
  184. // Build the node body.
  185. $node = node_load($item->sid);
  186. node_build_content($node, 'search_result');
  187. $node->body = drupal_render($node->content);
  188. // Fetch comments for snippet.
  189. $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
  190. // Fetch terms for snippet.
  191. $node->rendered .= ' ' . module_invoke('taxonomy', 'node_update_index', $node);
  192. $extra = module_invoke_all('node_search_result', $node);
  193. $results[] = array(
  194. 'link' => url('node/' . $item->sid, array('absolute' => TRUE)),
  195. 'type' => check_plain(node_type_get_name($node)),
  196. 'title' => $node->title,
  197. 'user' => theme('username', array('account' => $node)),
  198. 'date' => $node->changed,
  199. 'node' => $node,
  200. 'extra' => $extra,
  201. 'score' => $item->calculated_score,
  202. 'snippet' => search_excerpt($keys, $node->body),
  203. );
  204. }
  205. return $results;
  206. }
  207. /**
  208. * Override the rendering of search results.
  209. *
  210. * A module that implements hook_search_info() to define a type of search may
  211. * implement this hook in order to override the default theming of its search
  212. * results, which is otherwise themed using theme('search_results').
  213. *
  214. * Note that by default, theme('search_results') and theme('search_result')
  215. * work together to create an ordered list (OL). So your hook_search_page()
  216. * implementation should probably do this as well.
  217. *
  218. * @param $results
  219. * An array of search results.
  220. *
  221. * @return
  222. * A renderable array, which will render the formatted search results with a
  223. * pager included.
  224. *
  225. * @see search-result.tpl.php
  226. * @see search-results.tpl.php
  227. */
  228. function hook_search_page($results) {
  229. $output['prefix']['#markup'] = '<ol class="search-results">';
  230. foreach ($results as $entry) {
  231. $output[] = array(
  232. '#theme' => 'search_result',
  233. '#result' => $entry,
  234. '#module' => 'my_module_name',
  235. );
  236. }
  237. $output['suffix']['#markup'] = '</ol>' . theme('pager');
  238. return $output;
  239. }
  240. /**
  241. * Preprocess text for search.
  242. *
  243. * This hook is called to preprocess both the text added to the search index and
  244. * the keywords users have submitted for searching.
  245. *
  246. * Possible uses:
  247. * - Adding spaces between words of Chinese or Japanese text.
  248. * - Stemming words down to their root words to allow matches between, for
  249. * instance, walk, walked, walking, and walks in searching.
  250. * - Expanding abbreviations and acronymns that occur in text.
  251. *
  252. * @param $text
  253. * The text to preprocess. This is a single piece of plain text extracted
  254. * from between two HTML tags or from the search query. It will not contain
  255. * any HTML entities or HTML tags.
  256. *
  257. * @return
  258. * The text after preprocessing. Note that if your module decides not to alter
  259. * the text, it should return the original text. Also, after preprocessing,
  260. * words in the text should be separated by a space.
  261. *
  262. * @ingroup search
  263. */
  264. function hook_search_preprocess($text) {
  265. // Do processing on $text
  266. return $text;
  267. }
  268. /**
  269. * Update the search index for this module.
  270. *
  271. * This hook is called every cron run if search.module is enabled, your
  272. * module has implemented hook_search_info(), and your module has been set as
  273. * an active search module on the Search settings page
  274. * (admin/config/search/settings). It allows your module to add items to the
  275. * built-in search index using search_index(), or to add them to your module's
  276. * own indexing mechanism.
  277. *
  278. * When implementing this hook, your module should index content items that
  279. * were modified or added since the last run. PHP has a time limit
  280. * for cron, though, so it is advisable to limit how many items you index
  281. * per run using variable_get('search_cron_limit') (see example below). Also,
  282. * since the cron run could time out and abort in the middle of your run, you
  283. * should update your module's internal bookkeeping on when items have last
  284. * been indexed as you go rather than waiting to the end of indexing.
  285. *
  286. * @ingroup search
  287. */
  288. function hook_update_index() {
  289. $limit = (int)variable_get('search_cron_limit', 100);
  290. $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit);
  291. foreach ($result as $node) {
  292. $node = node_load($node->nid);
  293. // Save the changed time of the most recent indexed node, for the search
  294. // results half-life calculation.
  295. variable_set('node_cron_last', $node->changed);
  296. // Render the node.
  297. node_build_content($node, 'search_index');
  298. $node->rendered = drupal_render($node->content);
  299. $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->rendered;
  300. // Fetch extra data normally not visible
  301. $extra = module_invoke_all('node_update_index', $node);
  302. foreach ($extra as $t) {
  303. $text .= $t;
  304. }
  305. // Update index
  306. search_index($node->nid, 'node', $text);
  307. }
  308. }
  309. /**
  310. * @} End of "addtogroup hooks".
  311. */
  312. /**
  313. * Provide search query conditions.
  314. *
  315. * Callback for hook_search_info().
  316. *
  317. * This callback is invoked by search_view() to get an array of additional
  318. * search conditions to pass to search_data(). For example, a search module
  319. * may get additional keywords, filters, or modifiers for the search from
  320. * the query string.
  321. *
  322. * This example pulls additional search keywords out of the $_REQUEST variable,
  323. * (i.e. from the query string of the request). The conditions may also be
  324. * generated internally - for example based on a module's settings.
  325. *
  326. * @param $keys
  327. * The search keywords string.
  328. *
  329. * @return
  330. * An array of additional conditions, such as filters.
  331. *
  332. * @ingroup callbacks
  333. * @ingroup search
  334. */
  335. function callback_search_conditions($keys) {
  336. $conditions = array();
  337. if (!empty($_REQUEST['keys'])) {
  338. $conditions['keys'] = $_REQUEST['keys'];
  339. }
  340. if (!empty($_REQUEST['sample_search_keys'])) {
  341. $conditions['sample_search_keys'] = $_REQUEST['sample_search_keys'];
  342. }
  343. if ($force_keys = config('sample_search.settings')->get('force_keywords')) {
  344. $conditions['sample_search_force_keywords'] = $force_keys;
  345. }
  346. return $conditions;
  347. }