874 lines
35 KiB
Plaintext
874 lines
35 KiB
Plaintext
<?php
|
|
|
|
/**
|
|
* @file
|
|
* Enables site-wide keyword searching.
|
|
*/
|
|
|
|
use Drupal\Core\Entity\EntityInterface;
|
|
use Drupal\Component\Utility\Unicode;
|
|
use Drupal\search\SearchExpression;
|
|
use Drupal\search\Plugin\SearchInterface;
|
|
|
|
/**
|
|
* Matches all 'N' Unicode character classes (numbers)
|
|
*/
|
|
define('PREG_CLASS_NUMBERS',
|
|
'\x{30}-\x{39}\x{b2}\x{b3}\x{b9}\x{bc}-\x{be}\x{660}-\x{669}\x{6f0}-\x{6f9}' .
|
|
'\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}' .
|
|
'\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}' .
|
|
'\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-' .
|
|
'\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}' .
|
|
'\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}' .
|
|
'\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}' .
|
|
'\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-' .
|
|
'\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');
|
|
|
|
/**
|
|
* Matches all 'P' Unicode character classes (punctuation)
|
|
*/
|
|
define('PREG_CLASS_PUNCTUATION',
|
|
'\x{21}-\x{23}\x{25}-\x{2a}\x{2c}-\x{2f}\x{3a}\x{3b}\x{3f}\x{40}\x{5b}-\x{5d}' .
|
|
'\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}' .
|
|
'\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}' .
|
|
'\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}' .
|
|
'\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}' .
|
|
'\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}' .
|
|
'\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}' .
|
|
'\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}' .
|
|
'\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-' .
|
|
'\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}' .
|
|
'\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}' .
|
|
'\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}' .
|
|
'\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}' .
|
|
'\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-' .
|
|
'\x{ff65}');
|
|
|
|
/**
|
|
* Matches CJK (Chinese, Japanese, Korean) letter-like characters.
|
|
*
|
|
* This list is derived from the "East Asian Scripts" section of
|
|
* http://www.unicode.org/charts/index.html, as well as a comment on
|
|
* http://unicode.org/reports/tr11/tr11-11.html listing some character
|
|
* ranges that are reserved for additional CJK ideographs.
|
|
*
|
|
* The character ranges do not include numbers, punctuation, or symbols, since
|
|
* these are handled separately in search. Note that radicals and strokes are
|
|
* considered symbols. (See
|
|
* http://www.unicode.org/Public/UNIDATA/extracted/DerivedGeneralCategory.txt)
|
|
*
|
|
* @see search_expand_cjk()
|
|
*/
|
|
define('PREG_CLASS_CJK', '\x{1100}-\x{11FF}\x{3040}-\x{309F}\x{30A1}-\x{318E}' .
|
|
'\x{31A0}-\x{31B7}\x{31F0}-\x{31FF}\x{3400}-\x{4DBF}\x{4E00}-\x{9FCF}' .
|
|
'\x{A000}-\x{A48F}\x{A4D0}-\x{A4FD}\x{A960}-\x{A97F}\x{AC00}-\x{D7FF}' .
|
|
'\x{F900}-\x{FAFF}\x{FF21}-\x{FF3A}\x{FF41}-\x{FF5A}\x{FF66}-\x{FFDC}' .
|
|
'\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}');
|
|
|
|
/**
|
|
* Implements hook_help().
|
|
*/
|
|
function search_help($path, $arg) {
|
|
switch ($path) {
|
|
case 'admin/help#search':
|
|
$output = '';
|
|
$output .= '<h3>' . t('About') . '</h3>';
|
|
$output .= '<p>' . t('The Search module provides the ability to index and search for content by exact keywords, and for users by username or e-mail. For more information, see the online handbook entry for <a href="@search-module">Search module</a>.', array('@search-module' => 'http://drupal.org/documentation/modules/search', '@search' => url('search'))) . '</p>';
|
|
$output .= '<h3>' . t('Uses') . '</h3>';
|
|
$output .= '<dl>';
|
|
$output .= '<dt>' . t('Searching content and users') . '</dt>';
|
|
$output .= '<dd>' . t('Users with <em>Use search</em> permission can use the search block and <a href="@search">Search page</a>. Users with the <em>View published content</em> permission can search for content containing exact keywords. Users with the <em>View user profiles</em> permission can search for users containing the keyword anywhere in the user name, and users with the <em>Administer users</em> permission can search for users by email address. Additionally, users with <em>Use advanced search</em> permission can find content using more complex search methods and filtering by choosing the <em>Advanced search</em> option on the <a href="@search">Search page</a>.', array('@search' => url('search'))) . '</dd>';
|
|
$output .= '<dt>' . t('Indexing content with cron') . '</dt>';
|
|
$output .= '<dd>' . t('To provide keyword searching, the search engine maintains an index of words found in the content and its fields, along with text added to your content by other modules (such as comments from the core Comment module, and taxonomy terms from the core Taxonomy module). To build and maintain this index, a correctly configured <a href="@cron">cron maintenance task</a> is required. Users with <em>Administer search</em> permission can further configure the cron settings on the <a href="@searchsettings">Search settings page</a>.', array('@cron' => 'http://drupal.org/cron', '@searchsettings' => url('admin/config/search/settings'))) . '</dd>';
|
|
$output .= '<dt>' . t('Content reindexing') . '</dt>';
|
|
$output .= '<dd>' . t('Content-related actions on your site (creating, editing, or deleting content and comments) automatically cause affected content items to be marked for indexing or reindexing at the next cron run. When content is marked for reindexing, the previous content remains in the index until cron runs, at which time it is replaced by the new content. Unlike content-related actions, actions related to the structure of your site do not cause affected content to be marked for reindexing. Examples of structure-related actions that affect content include deleting or editing taxonomy terms, enabling or disabling modules that add text to content (such as Taxonomy, Comment, and field-providing modules), and modifying the fields or display parameters of your content types. If you take one of these actions and you want to ensure that the search index is updated to reflect your changed site structure, you can mark all content for reindexing by clicking the "Re-index site" button on the <a href="@searchsettings">Search settings page</a>. If you have a lot of content on your site, it may take several cron runs for the content to be reindexed.', array('@searchsettings' => url('admin/config/search/settings'))) . '</dd>';
|
|
$output .= '<dt>' . t('Configuring search settings') . '</dt>';
|
|
$output .= '<dd>' . t('Indexing behavior can be adjusted using the <a href="@searchsettings">Search settings page</a>. Users with <em>Administer search</em> permission can control settings such as the <em>Number of items to index per cron run</em>, <em>Indexing settings</em> (word length), <em>Active search plugins</em>, and <em>Content ranking</em>, which lets you adjust the priority in which indexed content is returned in results.', array('@searchsettings' => url('admin/config/search/settings'))) . '</dd>';
|
|
$output .= '<dt>' . t('Search block') . '</dt>';
|
|
$output .= '<dd>' . t('The Search module includes a default <em>Search form</em> block, which can be enabled and configured on the <a href="@blocks">Blocks administration page</a>. The block is available to users with the <em>Search content</em> permission.', array('@blocks' => url('admin/structure/block'))) . '</dd>';
|
|
$output .= '<dt>' . t('Extending Search module') . '</dt>';
|
|
$output .= '<dd>' . t('By default, the Search module only supports exact keyword matching in content searches. You can modify this behavior by installing a language-specific stemming module for your language (such as <a href="@porterstemmer_url">Porter Stemmer</a> for American English), which allows words such as walk, walking, and walked to be matched in the Search module. Another approach is to use a third-party search technology with stemming or partial word matching features built in, such as <a href="@solr_url">Apache Solr</a> or <a href="@sphinx_url">Sphinx</a>. These and other <a href="@contrib-search">search-related contributed modules</a> can be downloaded by visiting Drupal.org.', array('@contrib-search' => 'http://drupal.org/project/modules?filters=tid%3A105', '@porterstemmer_url' => 'http://drupal.org/project/porterstemmer', '@solr_url' => 'http://drupal.org/project/apachesolr', '@sphinx_url' => 'http://drupal.org/project/sphinx')) . '</dd>';
|
|
$output .= '</dl>';
|
|
return $output;
|
|
case 'admin/config/search/settings':
|
|
return '<p>' . t('The search engine maintains an index of words found in your site\'s content. To build and maintain this index, a correctly configured <a href="@cron">cron maintenance task</a> is required. Indexing behavior can be adjusted using the settings below.', array('@cron' => url('admin/reports/status'))) . '</p>';
|
|
case 'search#noresults':
|
|
return t('<ul>
|
|
<li>Check if your spelling is correct.</li>
|
|
<li>Remove quotes around phrases to search for each word individually. <em>bike shed</em> will often show more results than <em>"bike shed"</em>.</li>
|
|
<li>Consider loosening your query with <em>OR</em>. <em>bike OR shed</em> will often show more results than <em>bike shed</em>.</li>
|
|
</ul>');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Implements hook_theme().
|
|
*/
|
|
function search_theme() {
|
|
return array(
|
|
'search_result' => array(
|
|
'variables' => array('result' => NULL, 'plugin_id' => NULL),
|
|
'file' => 'search.pages.inc',
|
|
'template' => 'search-result',
|
|
),
|
|
'search_results' => array(
|
|
'variables' => array('results' => NULL, 'plugin_id' => NULL),
|
|
'file' => 'search.pages.inc',
|
|
'template' => 'search-results',
|
|
),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Implements hook_permission().
|
|
*/
|
|
function search_permission() {
|
|
return array(
|
|
'administer search' => array(
|
|
'title' => t('Administer search'),
|
|
),
|
|
'search content' => array(
|
|
'title' => t('Use search'),
|
|
),
|
|
'use advanced search' => array(
|
|
'title' => t('Use advanced search'),
|
|
),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Implements hook_preprocess_HOOK() for block templates.
|
|
*/
|
|
function search_preprocess_block(&$variables) {
|
|
if ($variables['plugin_id'] == 'search_form_block') {
|
|
$variables['attributes']['role'] = 'search';
|
|
$variables['content_attributes']['class'][] = 'container-inline';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Implements hook_menu().
|
|
*/
|
|
function search_menu() {
|
|
$items['search'] = array(
|
|
'title' => 'Search',
|
|
'type' => MENU_SUGGESTED_ITEM,
|
|
'route_name' => 'search.view',
|
|
);
|
|
$items['admin/config/search/settings'] = array(
|
|
'title' => 'Search settings',
|
|
'description' => 'Configure relevance settings for search and other indexing options.',
|
|
'route_name' => 'search.settings',
|
|
'weight' => -10,
|
|
);
|
|
$items['admin/config/search/settings/reindex'] = array(
|
|
'title' => 'Clear index',
|
|
'route_name' => 'search.reindex_confirm',
|
|
'type' => MENU_VISIBLE_IN_BREADCRUMB,
|
|
);
|
|
|
|
// Add paths for searching. We add each plugin search path twice: once without
|
|
// and once with %menu_tail appended. The reason for this is that we want to
|
|
// preserve keywords when switching tabs, and also to have search tabs
|
|
// highlighted properly. The only way to do that within the Drupal menu
|
|
// system appears to be having two sets of tabs. See discussion on issue
|
|
// http://drupal.org/node/245103 for details.
|
|
|
|
$default_info = search_get_default_plugin_info();
|
|
if ($default_info) {
|
|
foreach (\Drupal::service('plugin.manager.search')->getActiveDefinitions() as $plugin_id => $search_info) {
|
|
$path = 'search/' . $search_info['path'];
|
|
$items[$path] = array(
|
|
'title' => $search_info['title'],
|
|
'route_name' => 'search.view_' . $plugin_id,
|
|
'type' => MENU_LOCAL_TASK,
|
|
'weight' => $plugin_id == $default_info['id'] ? -10 : 0,
|
|
);
|
|
}
|
|
}
|
|
return $items;
|
|
}
|
|
|
|
/**
|
|
* Returns information about the default search plugin.
|
|
*
|
|
* @return array
|
|
* The search plugin definition for the default search plugin, if any.
|
|
*/
|
|
function search_get_default_plugin_info() {
|
|
$info = \Drupal::service('plugin.manager.search')->getActiveDefinitions();
|
|
$default = \Drupal::config('search.settings')->get('default_plugin');
|
|
if (isset($info[$default])) {
|
|
return $info[$default];
|
|
}
|
|
// The config setting does not match any active plugin, so just return
|
|
// the info for the first active plugin (if any).
|
|
return reset($info);
|
|
}
|
|
|
|
/**
|
|
* Clears either a part of, or the entire search index.
|
|
*
|
|
* @param $sid
|
|
* (optional) The ID of the item to remove from the search index. If
|
|
* specified, $type must also be given. Omit both $sid and $type to clear
|
|
* the entire search index.
|
|
* @param $type
|
|
* (optional) The plugin ID or other machine-readable type for the item to
|
|
* remove from the search index.
|
|
* @param $reindex
|
|
* (optional) Boolean to specify whether reindexing happens.
|
|
* @param $langcode
|
|
* (optional) Language code for the operation. If not provided, all
|
|
* index records for the $sid will be deleted.
|
|
*/
|
|
function search_reindex($sid = NULL, $type = NULL, $reindex = FALSE, $langcode = NULL) {
|
|
if ($type == NULL && $sid == NULL) {
|
|
foreach (\Drupal::service('plugin.manager.search')->getActiveIndexingPlugins() as $plugin) {
|
|
$plugin->resetIndex();
|
|
}
|
|
}
|
|
else {
|
|
$query = db_delete('search_dataset')
|
|
->condition('sid', $sid)
|
|
->condition('type', $type);
|
|
if (!empty($langcode)) {
|
|
$query->condition('langcode', $langcode);
|
|
}
|
|
$query->execute();
|
|
|
|
$query = db_delete('search_index')
|
|
->condition('sid', $sid)
|
|
->condition('type', $type);
|
|
if (!empty($langcode)) {
|
|
$query->condition('langcode', $langcode);
|
|
}
|
|
$query->execute();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Marks a word as "dirty" (changed), or retrieves the list of dirty words.
|
|
*
|
|
* This is used during indexing (cron). Words that are dirty have outdated
|
|
* total counts in the search_total table, and need to be recounted.
|
|
*/
|
|
function search_dirty($word = NULL) {
|
|
$dirty = &drupal_static(__FUNCTION__, array());
|
|
if ($word !== NULL) {
|
|
$dirty[$word] = TRUE;
|
|
}
|
|
else {
|
|
return $dirty;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Implements hook_cron().
|
|
*
|
|
* Fires updateIndex() in all plugins and cleans up dirty words.
|
|
*
|
|
* @see search_dirty()
|
|
*/
|
|
function search_cron() {
|
|
// We register a shutdown function to ensure that search_total is always up
|
|
// to date.
|
|
drupal_register_shutdown_function('search_update_totals');
|
|
|
|
foreach (\Drupal::service('plugin.manager.search')->getActiveIndexingPlugins() as $plugin) {
|
|
$plugin->updateIndex();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Updates the {search_total} database table.
|
|
*
|
|
* This function is called on shutdown to ensure that {search_total} is always
|
|
* up to date (even if cron times out or otherwise fails).
|
|
*/
|
|
function search_update_totals() {
|
|
// Update word IDF (Inverse Document Frequency) counts for new/changed words.
|
|
foreach (search_dirty() as $word => $dummy) {
|
|
// Get total count
|
|
$total = db_query("SELECT SUM(score) FROM {search_index} WHERE word = :word", array(':word' => $word), array('target' => 'slave'))->fetchField();
|
|
// Apply Zipf's law to equalize the probability distribution.
|
|
$total = log10(1 + 1/(max(1, $total)));
|
|
db_merge('search_total')
|
|
->key(array('word' => $word))
|
|
->fields(array('count' => $total))
|
|
->execute();
|
|
}
|
|
// Find words that were deleted from search_index, but are still in
|
|
// search_total. We use a LEFT JOIN between the two tables and keep only the
|
|
// rows which fail to join.
|
|
$result = db_query("SELECT t.word AS realword, i.word FROM {search_total} t LEFT JOIN {search_index} i ON t.word = i.word WHERE i.word IS NULL", array(), array('target' => 'slave'));
|
|
$or = db_or();
|
|
foreach ($result as $word) {
|
|
$or->condition('word', $word->realword);
|
|
}
|
|
if (count($or) > 0) {
|
|
db_delete('search_total')
|
|
->condition($or)
|
|
->execute();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Simplifies a string according to indexing rules.
|
|
*
|
|
* @param $text
|
|
* Text to simplify.
|
|
*
|
|
* @return
|
|
* Simplified text.
|
|
*
|
|
* @see hook_search_preprocess()
|
|
*/
|
|
function search_simplify($text, $langcode = NULL) {
|
|
// Decode entities to UTF-8
|
|
$text = decode_entities($text);
|
|
|
|
// Lowercase
|
|
$text = drupal_strtolower($text);
|
|
|
|
// Call an external processor for word handling.
|
|
search_invoke_preprocess($text, $langcode);
|
|
|
|
// Simple CJK handling
|
|
if (\Drupal::config('search.settings')->get('index.overlap_cjk')) {
|
|
$text = preg_replace_callback('/[' . PREG_CLASS_CJK . ']+/u', 'search_expand_cjk', $text);
|
|
}
|
|
|
|
// To improve searching for numerical data such as dates, IP addresses
|
|
// or version numbers, we consider a group of numerical characters
|
|
// separated only by punctuation characters to be one piece.
|
|
// This also means that searching for e.g. '20/03/1984' also returns
|
|
// results with '20-03-1984' in them.
|
|
// Readable regexp: ([number]+)[punctuation]+(?=[number])
|
|
$text = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' . PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\1', $text);
|
|
|
|
// Multiple dot and dash groups are word boundaries and replaced with space.
|
|
// No need to use the unicode modifer here because 0-127 ASCII characters
|
|
// can't match higher UTF-8 characters as the leftmost bit of those are 1.
|
|
$text = preg_replace('/[.-]{2,}/', ' ', $text);
|
|
|
|
// The dot, underscore and dash are simply removed. This allows meaningful
|
|
// search behavior with acronyms and URLs. See unicode note directly above.
|
|
$text = preg_replace('/[._-]+/', '', $text);
|
|
|
|
// With the exception of the rules above, we consider all punctuation,
|
|
// marks, spacers, etc, to be a word boundary.
|
|
$text = preg_replace('/[' . Unicode::PREG_CLASS_WORD_BOUNDARY . ']+/u', ' ', $text);
|
|
|
|
// Truncate everything to 50 characters.
|
|
$words = explode(' ', $text);
|
|
array_walk($words, '_search_index_truncate');
|
|
$text = implode(' ', $words);
|
|
|
|
return $text;
|
|
}
|
|
|
|
/**
|
|
* Splits CJK (Chinese, Japanese, Korean) text into tokens.
|
|
*
|
|
* The Search module matches exact words, where a word is defined to be a
|
|
* sequence of characters delimited by spaces or punctuation. CJK languages are
|
|
* written in long strings of characters, though, not split up into words. So
|
|
* in order to allow search matching, we split up CJK text into tokens
|
|
* consisting of consecutive, overlapping sequences of characters whose length
|
|
* is equal to the 'minimum_word_size' variable. This tokenizing is only done
|
|
* if the 'overlap_cjk' variable is TRUE.
|
|
*
|
|
* @param $matches
|
|
* This function is a callback for preg_replace_callback(), which is called
|
|
* from search_simplify(). So, $matches is an array of regular expression
|
|
* matches, which means that $matches[0] contains the matched text -- a
|
|
* string of CJK characters to tokenize.
|
|
*
|
|
* @return
|
|
* Tokenized text, starting and ending with a space character.
|
|
*/
|
|
function search_expand_cjk($matches) {
|
|
$min = \Drupal::config('search.settings')->get('index.minimum_word_size');
|
|
$str = $matches[0];
|
|
$length = drupal_strlen($str);
|
|
// If the text is shorter than the minimum word size, don't tokenize it.
|
|
if ($length <= $min) {
|
|
return ' ' . $str . ' ';
|
|
}
|
|
$tokens = ' ';
|
|
// Build a FIFO queue of characters.
|
|
$chars = array();
|
|
for ($i = 0; $i < $length; $i++) {
|
|
// Add the next character off the beginning of the string to the queue.
|
|
$current = drupal_substr($str, 0, 1);
|
|
$str = substr($str, strlen($current));
|
|
$chars[] = $current;
|
|
if ($i >= $min - 1) {
|
|
// Make a token of $min characters, and add it to the token string.
|
|
$tokens .= implode('', $chars) . ' ';
|
|
// Shift out the first character in the queue.
|
|
array_shift($chars);
|
|
}
|
|
}
|
|
return $tokens;
|
|
}
|
|
|
|
/**
|
|
* Simplifies and splits a string into tokens for indexing.
|
|
*/
|
|
function search_index_split($text, $langcode = NULL) {
|
|
$last = &drupal_static(__FUNCTION__);
|
|
$lastsplit = &drupal_static(__FUNCTION__ . ':lastsplit');
|
|
|
|
if ($last == $text) {
|
|
return $lastsplit;
|
|
}
|
|
// Process words
|
|
$text = search_simplify($text, $langcode);
|
|
$words = explode(' ', $text);
|
|
|
|
// Save last keyword result
|
|
$last = $text;
|
|
$lastsplit = $words;
|
|
|
|
return $words;
|
|
}
|
|
|
|
/**
|
|
* Helper function for array_walk in search_index_split.
|
|
*/
|
|
function _search_index_truncate(&$text) {
|
|
if (is_numeric($text)) {
|
|
$text = ltrim($text, '0');
|
|
}
|
|
$text = truncate_utf8($text, 50);
|
|
}
|
|
|
|
/**
|
|
* Invokes hook_search_preprocess() in modules.
|
|
*/
|
|
function search_invoke_preprocess(&$text, $langcode = NULL) {
|
|
foreach (\Drupal::moduleHandler()->getImplementations('search_preprocess') as $module) {
|
|
$text = module_invoke($module, 'search_preprocess', $text, $langcode);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Updates the full-text search index for a particular item.
|
|
*
|
|
* @param $sid
|
|
* An ID number identifying this particular item (e.g., node ID).
|
|
* @param $type
|
|
* The plugin ID or other machine-readable type of this item.
|
|
* @param $text
|
|
* The content of this item. Must be a piece of HTML or plain text.
|
|
* @param $langcode
|
|
* Language code for text being indexed.
|
|
*
|
|
* @ingroup search
|
|
*/
|
|
function search_index($sid, $type, $text, $langcode) {
|
|
$minimum_word_size = \Drupal::config('search.settings')->get('index.minimum_word_size');
|
|
|
|
// Multipliers for scores of words inside certain HTML tags. The weights are
|
|
// stored in config so that modules can overwrite the default weights.
|
|
// Note: 'a' must be included for link ranking to work.
|
|
$tags = \Drupal::config('search.settings')->get('index.tag_weights');
|
|
|
|
// Strip off all ignored tags to speed up processing, but insert space before
|
|
// and after them to keep word boundaries.
|
|
$text = str_replace(array('<', '>'), array(' <', '> '), $text);
|
|
$text = strip_tags($text, '<' . implode('><', array_keys($tags)) . '>');
|
|
|
|
// Split HTML tags from plain text.
|
|
$split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
|
|
// Note: PHP ensures the array consists of alternating delimiters and literals
|
|
// and begins and ends with a literal (inserting $null as required).
|
|
|
|
$tag = FALSE; // Odd/even counter. Tag or no tag.
|
|
$score = 1; // Starting score per word
|
|
$accum = ' '; // Accumulator for cleaned up data
|
|
$tagstack = array(); // Stack with open tags
|
|
$tagwords = 0; // Counter for consecutive words
|
|
$focus = 1; // Focus state
|
|
|
|
$scored_words = array(); // Accumulator for words for index
|
|
|
|
foreach ($split as $value) {
|
|
if ($tag) {
|
|
// Increase or decrease score per word based on tag
|
|
list($tagname) = explode(' ', $value, 2);
|
|
$tagname = drupal_strtolower($tagname);
|
|
// Closing or opening tag?
|
|
if ($tagname[0] == '/') {
|
|
$tagname = substr($tagname, 1);
|
|
// If we encounter unexpected tags, reset score to avoid incorrect boosting.
|
|
if (!count($tagstack) || $tagstack[0] != $tagname) {
|
|
$tagstack = array();
|
|
$score = 1;
|
|
}
|
|
else {
|
|
// Remove from tag stack and decrement score
|
|
$score = max(1, $score - $tags[array_shift($tagstack)]);
|
|
}
|
|
}
|
|
else {
|
|
if (isset($tagstack[0]) && $tagstack[0] == $tagname) {
|
|
// None of the tags we look for make sense when nested identically.
|
|
// If they are, it's probably broken HTML.
|
|
$tagstack = array();
|
|
$score = 1;
|
|
}
|
|
else {
|
|
// Add to open tag stack and increment score
|
|
array_unshift($tagstack, $tagname);
|
|
$score += $tags[$tagname];
|
|
}
|
|
}
|
|
// A tag change occurred, reset counter.
|
|
$tagwords = 0;
|
|
}
|
|
else {
|
|
// Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty values
|
|
if ($value != '') {
|
|
$words = search_index_split($value, $langcode);
|
|
foreach ($words as $word) {
|
|
// Add word to accumulator
|
|
$accum .= $word . ' ';
|
|
// Check wordlength
|
|
if (is_numeric($word) || drupal_strlen($word) >= $minimum_word_size) {
|
|
if (!isset($scored_words[$word])) {
|
|
$scored_words[$word] = 0;
|
|
}
|
|
$scored_words[$word] += $score * $focus;
|
|
// Focus is a decaying value in terms of the amount of unique words up to this point.
|
|
// From 100 words and more, it decays, to e.g. 0.5 at 500 words and 0.3 at 1000 words.
|
|
$focus = min(1, .01 + 3.5 / (2 + count($scored_words) * .015));
|
|
}
|
|
$tagwords++;
|
|
// Too many words inside a single tag probably mean a tag was accidentally left open.
|
|
if (count($tagstack) && $tagwords >= 15) {
|
|
$tagstack = array();
|
|
$score = 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
$tag = !$tag;
|
|
}
|
|
|
|
search_reindex($sid, $type, TRUE, $langcode);
|
|
|
|
// Insert cleaned up data into dataset
|
|
db_insert('search_dataset')
|
|
->fields(array(
|
|
'sid' => $sid,
|
|
'langcode' => $langcode,
|
|
'type' => $type,
|
|
'data' => $accum,
|
|
'reindex' => 0,
|
|
))
|
|
->execute();
|
|
|
|
// Insert results into search index
|
|
foreach ($scored_words as $word => $score) {
|
|
// If a word already exists in the database, its score gets increased
|
|
// appropriately. If not, we create a new record with the appropriate
|
|
// starting score.
|
|
db_merge('search_index')
|
|
->key(array(
|
|
'word' => $word,
|
|
'sid' => $sid,
|
|
'langcode' => $langcode,
|
|
'type' => $type,
|
|
))
|
|
->fields(array('score' => $score))
|
|
->expression('score', 'score + :score', array(':score' => $score))
|
|
->execute();
|
|
search_dirty($word);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Changes the timestamp on an indexed item to 'now' to force reindexing.
|
|
*
|
|
* @param $type
|
|
* The plugin ID or other machine-readable type of this item.
|
|
* @param $sid
|
|
* An ID number identifying this particular item (e.g., node ID).
|
|
*/
|
|
function search_mark_for_reindex($type, $sid) {
|
|
db_update('search_dataset')
|
|
->fields(array('reindex' => REQUEST_TIME))
|
|
->condition('type', $type)
|
|
->condition('sid', $sid)
|
|
->execute();
|
|
}
|
|
|
|
/**
|
|
* @defgroup search Search interface
|
|
* @{
|
|
* The Drupal search interface manages a global search mechanism.
|
|
*
|
|
* Modules may plug into this system to provide searches of different types of
|
|
* data. Most of the system is handled by the Search module, so this must be
|
|
* enabled for all of the search features to work.
|
|
*
|
|
* To be discovered, the plugins must implement
|
|
* \Drupal\search\Plugin\SearchInterface and be annotated as
|
|
* \Drupal\search\Annotation\SearchPlugin plugins.
|
|
*
|
|
* There are three ways to interact with the search system:
|
|
* - Specifically for searching nodes, you can implement
|
|
* hook_node_update_index() and hook_node_search_result(). However, note that
|
|
* the search system already indexes all visible output of a node; i.e.,
|
|
* everything displayed normally during node viewing. This is
|
|
* usually sufficient. You should only use this mechanism if you want
|
|
* additional, non-visible data to be indexed.
|
|
* - Define a plugin implementing \Drupal\search\Plugin\SearchInterface and
|
|
* annotated as \Drupal\search\Annotation\SearchPlugin. This will create a
|
|
* search tab for your plugin on the /search page with a simple keyword
|
|
* search form. You will also need to implement the execute() method
|
|
* from the interface to perform the search. A base class is provided in
|
|
* \Drupal\search\Plugin\SearchPluginBase.
|
|
*
|
|
* If your module needs to provide a more complicated search form, then you
|
|
* need to implement it yourself. In that case, you may wish to define it as a
|
|
* local task (tab) under the /search page (e.g. /search/mymodule) so that users
|
|
* can easily find it.
|
|
*/
|
|
|
|
/**
|
|
* Returns snippets from a piece of text, with certain keywords highlighted.
|
|
*
|
|
* Used for formatting search results.
|
|
*
|
|
* @param $keys
|
|
* A string containing a search query.
|
|
*
|
|
* @param $text
|
|
* The text to extract fragments from.
|
|
*
|
|
* @return
|
|
* A string containing HTML for the excerpt.
|
|
*/
|
|
function search_excerpt($keys, $text, $langcode = NULL) {
|
|
// We highlight around non-indexable or CJK characters.
|
|
$boundary = '(?:(?<=[' . Unicode::PREG_CLASS_WORD_BOUNDARY . PREG_CLASS_CJK . '])|(?=[' . Unicode::PREG_CLASS_WORD_BOUNDARY . PREG_CLASS_CJK . ']))';
|
|
|
|
// Extract positive keywords and phrases
|
|
preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' ' . $keys, $matches);
|
|
$keys = array_merge($matches[2], $matches[3]);
|
|
|
|
// Prepare text by stripping HTML tags and decoding HTML entities.
|
|
$text = strip_tags(str_replace(array('<', '>'), array(' <', '> '), $text));
|
|
$text = decode_entities($text);
|
|
|
|
// Slash-escape quotes in the search keyword string.
|
|
array_walk($keys, '_search_excerpt_replace');
|
|
$workkeys = $keys;
|
|
|
|
// Extract fragments around keywords.
|
|
// First we collect ranges of text around each keyword, starting/ending
|
|
// at spaces, trying to get to 256 characters.
|
|
// If the sum of all fragments is too short, we look for second occurrences.
|
|
$ranges = array();
|
|
$included = array();
|
|
$foundkeys = array();
|
|
$length = 0;
|
|
while ($length < 256 && count($workkeys)) {
|
|
foreach ($workkeys as $k => $key) {
|
|
if (strlen($key) == 0) {
|
|
unset($workkeys[$k]);
|
|
unset($keys[$k]);
|
|
continue;
|
|
}
|
|
if ($length >= 256) {
|
|
break;
|
|
}
|
|
// Remember occurrence of key so we can skip over it if more occurrences
|
|
// are desired.
|
|
if (!isset($included[$key])) {
|
|
$included[$key] = 0;
|
|
}
|
|
// Locate a keyword (position $p, always >0 because $text starts with a
|
|
// space). First try bare keyword, but if that doesn't work, try to find a
|
|
// derived form from search_simplify().
|
|
$p = 0;
|
|
if (preg_match('/' . $boundary . $key . $boundary . '/iu', $text, $match, PREG_OFFSET_CAPTURE, $included[$key])) {
|
|
$p = $match[0][1];
|
|
}
|
|
else {
|
|
$info = search_simplify_excerpt_match($key, $text, $included[$key], $boundary, $langcode);
|
|
if ($info['where']) {
|
|
$p = $info['where'];
|
|
if ($info['keyword']) {
|
|
$foundkeys[] = $info['keyword'];
|
|
}
|
|
}
|
|
}
|
|
// Now locate a space in front (position $q) and behind it (position $s),
|
|
// leaving about 60 characters extra before and after for context.
|
|
// Note that a space was added to the front and end of $text above.
|
|
if ($p) {
|
|
if (($q = strpos(' ' . $text, ' ', max(0, $p - 61))) !== FALSE) {
|
|
$end = substr($text . ' ', $p, 80);
|
|
if (($s = strrpos($end, ' ')) !== FALSE) {
|
|
// Account for the added spaces.
|
|
$q = max($q - 1, 0);
|
|
$s = min($s, strlen($end) - 1);
|
|
$ranges[$q] = $p + $s;
|
|
$length += $p + $s - $q;
|
|
$included[$key] = $p + 1;
|
|
}
|
|
else {
|
|
unset($workkeys[$k]);
|
|
}
|
|
}
|
|
else {
|
|
unset($workkeys[$k]);
|
|
}
|
|
}
|
|
else {
|
|
unset($workkeys[$k]);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (count($ranges) == 0) {
|
|
// We didn't find any keyword matches, so just return the first part of the
|
|
// text. We also need to re-encode any HTML special characters that we
|
|
// entity-decoded above.
|
|
return check_plain(truncate_utf8($text, 256, TRUE, TRUE));
|
|
}
|
|
|
|
// Sort the text ranges by starting position.
|
|
ksort($ranges);
|
|
|
|
// Now we collapse overlapping text ranges into one. The sorting makes it O(n).
|
|
$newranges = array();
|
|
foreach ($ranges as $from2 => $to2) {
|
|
if (!isset($from1)) {
|
|
$from1 = $from2;
|
|
$to1 = $to2;
|
|
continue;
|
|
}
|
|
if ($from2 <= $to1) {
|
|
$to1 = max($to1, $to2);
|
|
}
|
|
else {
|
|
$newranges[$from1] = $to1;
|
|
$from1 = $from2;
|
|
$to1 = $to2;
|
|
}
|
|
}
|
|
$newranges[$from1] = $to1;
|
|
|
|
// Fetch text
|
|
$out = array();
|
|
foreach ($newranges as $from => $to) {
|
|
$out[] = substr($text, $from, $to - $from);
|
|
}
|
|
|
|
// Let translators have the ... separator text as one chunk.
|
|
$dots = explode('!excerpt', t('... !excerpt ... !excerpt ...'));
|
|
|
|
$text = (isset($newranges[0]) ? '' : $dots[0]) . implode($dots[1], $out) . $dots[2];
|
|
$text = check_plain($text);
|
|
|
|
// Slash-escape quotes in keys found in a derived form and merge with original keys.
|
|
array_walk($foundkeys, '_search_excerpt_replace');
|
|
$keys = array_merge($keys, $foundkeys);
|
|
|
|
// Highlight keywords. Must be done at once to prevent conflicts ('strong' and '<strong>').
|
|
$text = preg_replace('/' . $boundary . '(' . implode('|', $keys) . ')' . $boundary . '/iu', '<strong>\0</strong>', $text);
|
|
return $text;
|
|
}
|
|
|
|
/**
|
|
* @} End of "defgroup search".
|
|
*/
|
|
|
|
/**
|
|
* Helper function for array_walk() in search_excerpt().
|
|
*/
|
|
function _search_excerpt_replace(&$text) {
|
|
$text = preg_quote($text, '/');
|
|
}
|
|
|
|
/**
|
|
* Finds words in the original text that matched via search_simplify().
|
|
*
|
|
* This is called in search_excerpt() if an exact match is not found in the
|
|
* text, so that we can find the derived form that matches.
|
|
*
|
|
* @param $key
|
|
* The keyword to find.
|
|
* @param $text
|
|
* The text to search for the keyword.
|
|
* @param $offset
|
|
* Offset position in $text to start searching at.
|
|
* @param $boundary
|
|
* Text to include in a regular expression that will match a word boundary.
|
|
*
|
|
* @return
|
|
* FALSE if no match is found. If a match is found, return an associative
|
|
* array with element 'where' giving the position of the match, and element
|
|
* 'keyword' giving the actual word found in the text at that position.
|
|
*/
|
|
function search_simplify_excerpt_match($key, $text, $offset, $boundary, $langcode = NULL) {
|
|
$pos = NULL;
|
|
$simplified_key = search_simplify($key, $langcode);
|
|
$simplified_text = search_simplify($text, $langcode);
|
|
|
|
// Return immediately if simplified key or text are empty.
|
|
if (!$simplified_key || !$simplified_text) {
|
|
return FALSE;
|
|
}
|
|
|
|
// Check if we have a match after simplification in the text.
|
|
if (!preg_match('/' . $boundary . $simplified_key . $boundary . '/iu', $simplified_text, $match, PREG_OFFSET_CAPTURE, $offset)) {
|
|
return FALSE;
|
|
}
|
|
|
|
// If we get here, we have a match. Now find the exact location of the match
|
|
// and the original text that matched. Start by splitting up the text by all
|
|
// potential starting points of the matching text and iterating through them.
|
|
$split = array_filter(preg_split('/' . $boundary . '/iu', $text, -1, PREG_SPLIT_OFFSET_CAPTURE), '_search_excerpt_match_filter');
|
|
foreach ($split as $value) {
|
|
// Skip starting points before the offset.
|
|
if ($value[1] < $offset) {
|
|
continue;
|
|
}
|
|
|
|
// Check a window of 80 characters after the starting point for a match,
|
|
// based on the size of the excerpt window.
|
|
$window = substr($text, $value[1], 80);
|
|
$simplified_window = search_simplify($window);
|
|
if (strpos($simplified_window, $simplified_key) === 0) {
|
|
// We have a match in this window. Store the position of the match.
|
|
$pos = $value[1];
|
|
// Iterate through the text in the window until we find the full original
|
|
// matching text.
|
|
$length = strlen($window);
|
|
for ($i = 1; $i <= $length; $i++) {
|
|
$keyfound = substr($text, $value[1], $i);
|
|
if ($simplified_key == search_simplify($keyfound)) {
|
|
break;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
return $pos ? array('where' => $pos, 'keyword' => $keyfound) : FALSE;
|
|
}
|
|
|
|
/**
|
|
* Helper function for array_filter() in search_search_excerpt_match().
|
|
*/
|
|
function _search_excerpt_match_filter($var) {
|
|
return strlen(trim($var[0]));
|
|
}
|