Projet

Général

Profil

Paste
Télécharger (12,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / search / search.api.php @ 76597ebf

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