search.api.php 13 KB

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