search.api.php 13 KB

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