Ejemplo n.º 1
0
 /**
  * Prepares search results for rendering.
  *
  * @param \Drupal\Core\Database\StatementInterface $found
  *   Results found from a successful search query execute() method.
  *
  * @return array
  *   Array of search result item render arrays (empty array if no results).
  */
 protected function prepareResults(StatementInterface $found)
 {
     $results = array();
     $node_storage = $this->entityManager->getStorage('node');
     $node_render = $this->entityManager->getViewBuilder('node');
     $keys = $this->keywords;
     foreach ($found as $item) {
         // Render the node.
         /** @var \Drupal\node\NodeInterface $node */
         $node = $node_storage->load($item->sid)->getTranslation($item->langcode);
         $build = $node_render->view($node, 'search_result', $item->langcode);
         /** @var \Drupal\node\NodeTypeInterface $type*/
         $type = $this->entityManager->getStorage('node_type')->load($node->bundle());
         unset($build['#theme']);
         $build['#pre_render'][] = array($this, 'removeSubmittedInfo');
         // Fetch comment count for snippet.
         $rendered = SafeMarkup::set($this->renderer->renderPlain($build) . ' ' . SafeMarkup::escape($this->moduleHandler->invoke('comment', 'node_update_index', array($node, $item->langcode))));
         $extra = $this->moduleHandler->invokeAll('node_search_result', array($node, $item->langcode));
         $language = $this->languageManager->getLanguage($item->langcode);
         $username = array('#theme' => 'username', '#account' => $node->getOwner());
         $result = array('link' => $node->url('canonical', array('absolute' => TRUE, 'language' => $language)), 'type' => SafeMarkup::checkPlain($type->label()), 'title' => $node->label(), 'node' => $node, 'extra' => $extra, 'score' => $item->calculated_score, 'snippet' => search_excerpt($keys, $rendered, $item->langcode), 'langcode' => $node->language()->getId());
         if ($type->displaySubmitted()) {
             $result += array('user' => $this->renderer->renderPlain($username), 'date' => $node->getChangedTime());
         }
         $results[] = $result;
     }
     return $results;
 }
Ejemplo n.º 2
0
 /**
  * Prepares search results for rendering.
  *
  * @param \Drupal\Core\Database\StatementInterface $found
  *   Results found from a successful search query execute() method.
  *
  * @return array
  *   Array of search result item render arrays (empty array if no results).
  */
 protected function prepareResults(StatementInterface $found)
 {
     $results = array();
     $node_storage = $this->entityManager->getStorage('node');
     $node_render = $this->entityManager->getViewBuilder('node');
     $keys = $this->keywords;
     foreach ($found as $item) {
         // Render the node.
         /** @var \Drupal\node\NodeInterface $node */
         $node = $node_storage->load($item->sid)->getTranslation($item->langcode);
         $build = $node_render->view($node, 'search_result', $item->langcode);
         /** @var \Drupal\node\NodeTypeInterface $type*/
         $type = $this->entityManager->getStorage('node_type')->load($node->bundle());
         unset($build['#theme']);
         $build['#pre_render'][] = array($this, 'removeSubmittedInfo');
         // Fetch comments for snippet.
         $rendered = $this->renderer->renderPlain($build);
         $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
         $rendered .= ' ' . $this->moduleHandler->invoke('comment', 'node_update_index', [$node]);
         $extra = $this->moduleHandler->invokeAll('node_search_result', [$node]);
         $language = $this->languageManager->getLanguage($item->langcode);
         $username = array('#theme' => 'username', '#account' => $node->getOwner());
         $result = array('link' => $node->url('canonical', array('absolute' => TRUE, 'language' => $language)), 'type' => $type->label(), 'title' => $node->label(), 'node' => $node, 'extra' => $extra, 'score' => $item->calculated_score, 'snippet' => search_excerpt($keys, $rendered, $item->langcode), 'langcode' => $node->language()->getId());
         $this->addCacheableDependency($node);
         // We have to separately add the node owner's cache tags because search
         // module doesn't use the rendering system, it does its own rendering
         // without taking cacheability metadata into account. So we have to do it
         // explicitly here.
         $this->addCacheableDependency($node->getOwner());
         if ($type->displaySubmitted()) {
             $result += array('user' => $this->renderer->renderPlain($username), 'date' => $node->getChangedTime());
         }
         $results[] = $result;
     }
     return $results;
 }
Ejemplo n.º 3
0
/**
 * Execute a search for a set of key words.
 *
 * We call do_search() with the keys, the module name, and extra SQL fragments
 * to use when searching. See hook_update_index() for more information.
 *
 * @param $keys
 *   The search keywords as entered by the user.
 *
 * @return
 *   An array of search results. To use the default search result
 *   display, each item should have the following keys':
 *   - 'link': Required. The URL of the found item.
 *   - 'type': The type of item.
 *   - 'title': Required. The name of the item.
 *   - 'user': The author of the item.
 *   - 'date': A timestamp when the item was last modified.
 *   - 'extra': An array of optional extra information items.
 *   - 'snippet': An excerpt or preview to show with the result (can be
 *     generated with search_excerpt()).
 *
 * @ingroup search
 */
function hook_search_execute($keys = NULL)
{
    // Build matching conditions
    $query = db_search()->extend('PagerDefault');
    $query->join('node', 'n', 'n.nid = i.sid');
    $query->condition('n.status', 1)->addTag('node_access')->searchExpression($keys, 'node');
    // Insert special keywords.
    $query->setOption('type', 'n.type');
    $query->setOption('language', 'n.language');
    if ($query->setOption('term', 'ti.tid')) {
        $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
    }
    // Only continue if the first pass query matches.
    if (!$query->executeFirstPass()) {
        return array();
    }
    // Add the ranking expressions.
    _node_rankings($query);
    // Add a count query.
    $inner_query = clone $query;
    $count_query = db_select($inner_query->fields('i', array('sid')));
    $count_query->addExpression('COUNT(*)');
    $query->setCountQuery($count_query);
    $find = $query->limit(10)->execute();
    // Load results.
    $results = array();
    foreach ($find as $item) {
        // Build the node body.
        $node = node_load($item->sid);
        node_build_content($node, 'search_result');
        $node->body = drupal_render($node->content);
        // Fetch comments for snippet.
        $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
        // Fetch terms for snippet.
        $node->rendered .= ' ' . module_invoke('taxonomy', 'node_update_index', $node);
        $extra = module_invoke_all('node_search_result', $node);
        $results[] = array('link' => url('node/' . $item->sid, array('absolute' => TRUE)), 'type' => check_plain(node_type_get_name($node)), 'title' => $node->title, 'user' => theme('username', array('account' => $node)), 'date' => $node->changed, 'node' => $node, 'extra' => $extra, 'score' => $item->calculated_score, 'snippet' => search_excerpt($keys, $node->body));
    }
    return $results;
}
Ejemplo n.º 4
0
/**
 * Define a custom search routine.
 *
 * This hook allows a module to perform searches on content it defines
 * (custom node types, users, or comments, for example) when a site search
 * is performed.
 *
 * Note that you can use form API to extend the search. You will need to use
 * hook_form_alter() to add any additional required form elements. You can
 * process their values on submission using a custom validation function.
 * You will need to merge any custom search values into the search keys
 * using a key:value syntax. This allows all search queries to have a clean
 * and permanent URL. See node_form_search_form_alter() for an example.
 *
 * The example given here is for node.module, which uses the indexed search
 * capabilities. To do this, node module also implements hook_update_index()
 * which is used to create and maintain the index.
 *
 * We call do_search() with the keys, the module name, and extra SQL fragments
 * to use when searching. See hook_update_index() for more information.
 *
 * @param $op
 *   A string defining which operation to perform:
 *   - 'admin': The hook should return a form array containing any fieldsets the
 *     module wants to add to the Search settings page at admin/settings/search.
 *   - 'name': The hook should return a translated name defining the type of
 *     items that are searched for with this module ('content', 'users', ...).
 *   - 'reset': The search index is going to be rebuilt. Modules which use
 *     hook_update_index() should update their indexing bookkeeping so that it
 *     starts from scratch the next time hook_update_index() is called.
 *   - 'search': The hook should perform a search using the keywords in $keys.
 *   - 'status': If the module implements hook_update_index(), it should return
 *     an array containing the following keys:
 *     - remaining: The amount of items that still need to be indexed.
 *     - total: The total amount of items (both indexed and unindexed).
 * @param $keys
 *   The search keywords as entered by the user.
 * @return
 *   This varies depending on the operation.
 *   - 'admin': The form array for the Search settings page at
 *     admin/settings/search.
 *   - 'name': The translated string of 'Content'.
 *   - 'reset': None.
 *   - 'search': An array of search results. To use the default search result
 *     display, each item should have the following keys':
 *     - 'link': Required. The URL of the found item.
 *     - 'type': The type of item.
 *     - 'title': Required. The name of the item.
 *     - 'user': The author of the item.
 *     - 'date': A timestamp when the item was last modified.
 *     - 'extra': An array of optional extra information items.
 *     - 'snippet': An excerpt or preview to show with the result (can be
 *     generated with search_excerpt()).
 *   - 'status': An associative array with the key-value pairs:
 *     - 'remaining': The number of items left to index.
 *     - 'total': The total number of items to index.
 *
 * @ingroup search
 */
function hook_search($op = 'search', $keys = NULL)
{
    switch ($op) {
        case 'name':
            return t('Content');
        case 'reset':
            db_query("UPDATE {search_dataset} SET reindex = %d WHERE type = 'node'", REQUEST_TIME);
            return;
        case 'status':
            $total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1'));
            $remaining = db_result(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"));
            return array('remaining' => $remaining, 'total' => $total);
        case 'admin':
            $form = array();
            // Output form for defining rank factor weights.
            $form['content_ranking'] = array('#type' => 'fieldset', '#title' => t('Content ranking'));
            $form['content_ranking']['#theme'] = 'node_search_admin';
            $form['content_ranking']['info'] = array('#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>');
            // Note: reversed to reflect that higher number = higher ranking.
            $options = drupal_map_assoc(range(0, 10));
            foreach (module_invoke_all('ranking') as $var => $values) {
                $form['content_ranking']['factors']['node_rank_' . $var] = array('#title' => $values['title'], '#type' => 'select', '#options' => $options, '#default_value' => variable_get('node_rank_' . $var, 0));
            }
            return $form;
        case 'search':
            // Build matching conditions
            list($join1, $where1) = _db_rewrite_sql();
            $arguments1 = array();
            $conditions1 = 'n.status = 1';
            if ($type = search_query_extract($keys, 'type')) {
                $types = array();
                foreach (explode(',', $type) as $t) {
                    $types[] = "n.type = '%s'";
                    $arguments1[] = $t;
                }
                $conditions1 .= ' AND (' . implode(' OR ', $types) . ')';
                $keys = search_query_insert($keys, 'type');
            }
            if ($category = search_query_extract($keys, 'category')) {
                $categories = array();
                foreach (explode(',', $category) as $c) {
                    $categories[] = "tn.tid = %d";
                    $arguments1[] = $c;
                }
                $conditions1 .= ' AND (' . implode(' OR ', $categories) . ')';
                $join1 .= ' INNER JOIN {taxonomy_term_node} tn ON n.vid = tn.vid';
                $keys = search_query_insert($keys, 'category');
            }
            if ($languages = search_query_extract($keys, 'language')) {
                $categories = array();
                foreach (explode(',', $languages) as $l) {
                    $categories[] = "n.language = '%s'";
                    $arguments1[] = $l;
                }
                $conditions1 .= ' AND (' . implode(' OR ', $categories) . ')';
                $keys = search_query_insert($keys, 'language');
            }
            // Get the ranking expressions.
            $rankings = _node_rankings();
            // When all search factors are disabled (ie they have a weight of zero),
            // The default score is based only on keyword relevance.
            if ($rankings['total'] == 0) {
                $total = 1;
                $arguments2 = array();
                $join2 = '';
                $select2 = 'i.relevance AS score';
            } else {
                $total = $rankings['total'];
                $arguments2 = $rankings['arguments'];
                $join2 = implode(' ', $rankings['join']);
                $select2 = '(' . implode(' + ', $rankings['score']) . ') AS score';
            }
            // Do search.
            $find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid ' . $join1, $conditions1 . (empty($where1) ? '' : ' AND ' . $where1), $arguments1, $select2, $join2, $arguments2);
            // Load results.
            $results = array();
            foreach ($find as $item) {
                // Build the node body.
                $node = node_load($item->sid);
                $node = node_build_content($node, 'search_result');
                $node->body = drupal_render($node->content);
                // Fetch comments for snippet.
                $node->body .= module_invoke('comment', 'node', $node, 'update_index');
                // Fetch terms for snippet.
                $node->body .= module_invoke('taxonomy', 'node', $node, 'update_index');
                $extra = module_invoke_all('node_search_result', $node);
                $results[] = array('link' => url('node/' . $item->sid, array('absolute' => TRUE)), 'type' => check_plain(node_type_get_name($node)), 'title' => $node->title, 'user' => theme('username', $node), 'date' => $node->changed, 'node' => $node, 'extra' => $extra, 'score' => $total ? $item->score / $total : 0, 'snippet' => search_excerpt($keys, $node->body));
            }
            return $results;
    }
}
 /**
  * Tests search_excerpt() with search keywords matching simplified words.
  *
  * Excerpting should handle keywords that are matched only after going through
  * search_simplify(). This test passes keywords that match simplified words
  * and compares them with strings that contain the original unsimplified word.
  */
 function testSearchExcerptSimplified()
 {
     $lorem1 = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vitae arcu at leo cursus laoreet. Curabitur dui tortor, adipiscing malesuada tempor in, bibendum ac diam. Cras non tellus a libero pellentesque condimentum. What is a Drupalism? Suspendisse ac lacus libero. Ut non est vel nisl faucibus interdum nec sed leo. Pellentesque sem risus, vulputate eu semper eget, auctor in libero.';
     $lorem2 = 'Ut fermentum est vitae metus convallis scelerisque. Phasellus pellentesque rhoncus tellus, eu dignissim purus posuere id. Quisque eu fringilla ligula. Morbi ullamcorper, lorem et mattis egestas, tortor neque pretium velit, eget eleifend odio turpis eu purus. Donec vitae metus quis leo pretium tincidunt a pulvinar sem. Morbi adipiscing laoreet mauris vel placerat. Nullam elementum, nisl sit amet scelerisque malesuada, dolor nunc hendrerit quam, eu ultrices erat est in orci.';
     // Make some text with some keywords that will get simplified.
     $text = $lorem1 . ' Number: 123456.7890 Hyphenated: one-two abc,def ' . $lorem2;
     // Note: The search_excerpt() function adds some extra spaces -- not
     // important for HTML formatting. Remove these for comparison.
     $result = preg_replace('| +|', ' ', search_excerpt('123456.7890', $text));
     $this->assertTrue(strpos($result, 'Number: <strong>123456.7890</strong>') !== FALSE, 'Numeric keyword is highlighted with exact match');
     $result = preg_replace('| +|', ' ', search_excerpt('1234567890', $text));
     $this->assertTrue(strpos($result, 'Number: <strong>123456.7890</strong>') !== FALSE, 'Numeric keyword is highlighted with simplified match');
     $result = preg_replace('| +|', ' ', search_excerpt('Number 1234567890', $text));
     $this->assertTrue(strpos($result, '<strong>Number</strong>: <strong>123456.7890</strong>') !== FALSE, 'Punctuated and numeric keyword is highlighted with simplified match');
     $result = preg_replace('| +|', ' ', search_excerpt('"Number 1234567890"', $text));
     $this->assertTrue(strpos($result, '<strong>Number: 123456.7890</strong>') !== FALSE, 'Phrase with punctuated and numeric keyword is highlighted with simplified match');
     $result = preg_replace('| +|', ' ', search_excerpt('"Hyphenated onetwo"', $text));
     $this->assertTrue(strpos($result, '<strong>Hyphenated: one-two</strong>') !== FALSE, 'Phrase with punctuated and hyphenated keyword is highlighted with simplified match');
     $result = preg_replace('| +|', ' ', search_excerpt('"abc def"', $text));
     $this->assertTrue(strpos($result, '<strong>abc,def</strong>') !== FALSE, 'Phrase with keyword simplified into two separate words is highlighted with simplified match');
     // Test phrases with characters which are being truncated.
     $result = preg_replace('| +|', ' ', search_excerpt('"ipsum _"', $text));
     $this->assertTrue(strpos($result, '<strong>ipsum</strong>') !== FALSE, 'Only valid part of the phrase is highlighted and invalid part containing "_" is ignored.');
     $result = preg_replace('| +|', ' ', search_excerpt('"ipsum 0000"', $text));
     $this->assertTrue(strpos($result, '<strong>ipsum</strong>') !== FALSE, 'Only valid part of the phrase is highlighted and invalid part "0000" is ignored.');
     // Test combination of the valid keyword and keyword containing only
     // characters which are being truncated during simplification.
     $result = preg_replace('| +|', ' ', search_excerpt('ipsum _', $text));
     $this->assertTrue(strpos($result, '<strong>ipsum</strong>') !== FALSE, 'Only valid keyword is highlighted and invalid keyword "_" is ignored.');
     $result = preg_replace('| +|', ' ', search_excerpt('ipsum 0000', $text));
     $this->assertTrue(strpos($result, '<strong>ipsum</strong>') !== FALSE, 'Only valid keyword is highlighted and invalid keyword "0000" is ignored.');
     // Test using the hook_search_preprocess() from the test module.
     // The hook replaces "finding" or "finds" with "find".
     // So, if we search for "find" or "finds" or "finding", we should
     // highlight "finding".
     $text = "this tests finding a string";
     $result = preg_replace('| +|', ' ', search_excerpt('finds', $text, 'ex'));
     $this->assertTrue(strpos($result, '<strong>finding</strong>') !== FALSE, 'Search excerpt works with preprocess hook, search for finds');
     $result = preg_replace('| +|', ' ', search_excerpt('find', $text, 'ex'));
     $this->assertTrue(strpos($result, '<strong>finding</strong>') !== FALSE, 'Search excerpt works with preprocess hook, search for find');
     // Just to be sure, test with the replacement at the beginning and end.
     $text = "finding at the beginning";
     $result = preg_replace('| +|', ' ', search_excerpt('finds', $text, 'ex'));
     $this->assertTrue(strpos($result, '<strong>finding</strong>') !== FALSE, 'Search excerpt works with preprocess hook, text at start');
     $text = "at the end finding";
     $result = preg_replace('| +|', ' ', search_excerpt('finds', $text, 'ex'));
     $this->assertTrue(strpos($result, '<strong>finding</strong>') !== FALSE, 'Search excerpt works with preprocess hook, text at end');
     // Testing with a one-to-many replacement: the test module replaces DIC
     // with Dependency Injection Container.
     $text = "something about the DIC is happening";
     $result = preg_replace('| +|', ' ', search_excerpt('Dependency', $text, 'ex'));
     $this->assertTrue(strpos($result, '<strong>DIC</strong>') !== FALSE, 'Search excerpt works with preprocess hook, acronym first word');
     $result = preg_replace('| +|', ' ', search_excerpt('Injection', $text, 'ex'));
     $this->assertTrue(strpos($result, '<strong>DIC</strong>') !== FALSE, 'Search excerpt works with preprocess hook, acronym second word');
     $result = preg_replace('| +|', ' ', search_excerpt('Container', $text, 'ex'));
     $this->assertTrue(strpos($result, '<strong>DIC</strong>') !== FALSE, 'Search excerpt works with preprocess hook, acronym third word');
     // Testing with a many-to-one replacement: the test module replaces
     // hypertext markup language with HTML.
     $text = "we always use hypertext markup language to describe things";
     $result = preg_replace('| +|', ' ', search_excerpt('html', $text, 'ex'));
     $this->assertTrue(strpos($result, '<strong>hypertext markup language</strong>') !== FALSE, 'Search excerpt works with preprocess hook, acronym many to one');
 }
</h2>
  <?php 
    }
    ?>
  <ol class="search-results node-results">
    <?php 
    foreach ($rows as $id => $row) {
        ?>
    <?php 
        $view = $variables['view'];
        $node = node_load($view->result[$id]->nid);
        // dpm($node, 'da node for ' . $id . ':' . $view->result[$id]->nid);
        $title = l($node->title, 'node/' . $node->nid);
        $url = url('node/' . $node->nid);
        $keys = $view->exposed_raw_input['keys'];
        $snippet = search_excerpt($keys, $row);
        $username = theme('username', array('account' => $node));
        $date = date('n/j/Y - G:i', $node->created);
        $numcomments = format_plural('@count comment', '@count comments', $node->comment_count);
        ?>
<li<?php 
        if ($classes_array[$id]) {
            print ' class="' . $classes_array[$id] . '"';
        }
        print $attributes;
        ?>
>
  <?php 
        print render($title_prefix);
        ?>
  <h3 class="title"<?php 
Ejemplo n.º 7
0
 /**
  * Calls search_excerpt() and renders output.
  *
  * @param string $keys
  *   A string containing a search query.
  * @param string $render_array
  *   The text to extract fragments from.
  * @param string|null $langcode
  *   Language code for the language of $text, if known.
  *
  * @return string
  *   A string containing HTML for the excerpt.
  */
 protected function doSearchExcerpt($keys, $render_array, $langcode = NULL)
 {
     $render_array = search_excerpt($keys, $render_array, $langcode);
     return \Drupal::service('renderer')->renderPlain($render_array);
 }
Ejemplo n.º 8
0
 /**
  * {@inheritdoc}
  */
 public function execute()
 {
     $results = array();
     if (!$this->isSearchExecutable()) {
         return $results;
     }
     $keys = $this->keywords;
     // Build matching conditions.
     $query = $this->database->select('search_index', 'i', array('target' => 'replica'))->extend('Drupal\\search\\SearchQuery')->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender');
     $query->join('node_field_data', 'n', 'n.nid = i.sid');
     $query->condition('n.status', 1)->addTag('node_access')->searchExpression($keys, $this->getPluginId());
     // Handle advanced search filters in the f query string.
     // \Drupal::request()->query->get('f') is an array that looks like this in
     // the URL: ?f[]=type:page&f[]=term:27&f[]=term:13&f[]=langcode:en
     // So $parameters['f'] looks like:
     // array('type:page', 'term:27', 'term:13', 'langcode:en');
     // We need to parse this out into query conditions, some of which go into
     // the keywords string, and some of which are separate conditions.
     $parameters = $this->getParameters();
     if (!empty($parameters['f']) && is_array($parameters['f'])) {
         $filters = array();
         // Match any query value that is an expected option and a value
         // separated by ':' like 'term:27'.
         $pattern = '/^(' . implode('|', array_keys($this->advanced)) . '):([^ ]*)/i';
         foreach ($parameters['f'] as $item) {
             if (preg_match($pattern, $item, $m)) {
                 // Use the matched value as the array key to eliminate duplicates.
                 $filters[$m[1]][$m[2]] = $m[2];
             }
         }
         // Now turn these into query conditions. This assumes that everything in
         // $filters is a known type of advanced search.
         foreach ($filters as $option => $matched) {
             $info = $this->advanced[$option];
             // Insert additional conditions. By default, all use the OR operator.
             $operator = empty($info['operator']) ? 'OR' : $info['operator'];
             $where = new Condition($operator);
             foreach ($matched as $value) {
                 $where->condition($info['column'], $value);
             }
             $query->condition($where);
             if (!empty($info['join'])) {
                 $query->join($info['join']['table'], $info['join']['alias'], $info['join']['condition']);
             }
         }
     }
     // Add the ranking expressions.
     $this->addNodeRankings($query);
     // Run the query and load results.
     $find = $query->fields('i', array('langcode'))->groupBy('i.langcode')->limit(10)->execute();
     // Check query status and set messages if needed.
     $status = $query->getStatus();
     if ($status & SearchQuery::EXPRESSIONS_IGNORED) {
         drupal_set_message($this->t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', array('@count' => $this->searchSettings->get('and_or_limit'))), 'warning');
     }
     if ($status & SearchQuery::LOWER_CASE_OR) {
         drupal_set_message($this->t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'), 'warning');
     }
     if ($status & SearchQuery::NO_POSITIVE_KEYWORDS) {
         drupal_set_message(\Drupal::translation()->formatPlural($this->searchSettings->get('index.minimum_word_size'), 'You must include at least one positive keyword with 1 character or more.', 'You must include at least one positive keyword with @count characters or more.'), 'warning');
     }
     $node_storage = $this->entityManager->getStorage('node');
     $node_render = $this->entityManager->getViewBuilder('node');
     foreach ($find as $item) {
         // Render the node.
         /** @var \Drupal\node\NodeInterface $node */
         $node = $node_storage->load($item->sid)->getTranslation($item->langcode);
         $build = $node_render->view($node, 'search_result', $item->langcode);
         unset($build['#theme']);
         // Fetch comment count for snippet.
         $node->rendered = SafeMarkup::set(drupal_render($build) . ' ' . SafeMarkup::escape($this->moduleHandler->invoke('comment', 'node_update_index', array($node, $item->langcode))));
         $extra = $this->moduleHandler->invokeAll('node_search_result', array($node, $item->langcode));
         $language = language_load($item->langcode);
         $username = array('#theme' => 'username', '#account' => $node->getOwner());
         $results[] = array('link' => $node->url('canonical', array('absolute' => TRUE, 'language' => $language)), 'type' => String::checkPlain($this->entityManager->getStorage('node_type')->load($node->bundle())->label()), 'title' => $node->label(), 'user' => drupal_render($username), 'date' => $node->getChangedTime(), 'node' => $node, 'extra' => $extra, 'score' => $item->calculated_score, 'snippet' => search_excerpt($keys, $node->rendered, $item->langcode), 'langcode' => $node->language()->getId());
     }
     return $results;
 }
Ejemplo n.º 9
0
 /**
  * Calls search_excerpt() and renders output.
  *
  * @param string $keys
  *   A string containing a search query.
  * @param string $render_array
  *   The text to extract fragments from.
  * @param string|null $langcode
  *   Language code for the language of $text, if known.
  *
  * @return string
  *   A string containing HTML for the excerpt.
  */
 protected function doSearchExcerpt($keys, $render_array, $langcode = NULL)
 {
     $render_array = search_excerpt($keys, $render_array, $langcode);
     $text = \Drupal::service('renderer')->renderPlain($render_array);
     // The search_excerpt() function adds some extra spaces -- not
     // important for HTML formatting or this test. Remove these for comparison.
     return preg_replace('| +|', ' ', $text);
 }
Ejemplo n.º 10
0
  /**
   * {@inheritdoc}
   */
  public function execute() {
    if ($this->isSearchExecutable()) {
      $keys = $this->keywords;

      // Build matching conditions.
      $query = $this->database
        ->select('search_index', 'i', ['target' => 'replica'])
        ->extend('Drupal\search\SearchQuery')
        ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
      $query->join('advanced_help_index', 'ahi', 'ahi.sid = i.sid');
      $query->join('search_dataset', 'sd', "ahi.sid = sd.sid AND sd.type = '{$this->pluginId}'");
      $query->searchExpression($keys, $this->getPluginId());

      $find = $query
        ->fields('i', ['langcode'])
        ->fields('ahi', ['module', 'topic'])
        ->fields('sd', ['data'])
        ->groupBy('i.langcode, ahi.module, ahi.topic, sd.data')
        ->limit(10)
        ->execute();

      $results = [];
      foreach ($find as $key => $item) {
        $result = [
          'link' => '/help/ah/' . $item->module . '/' . $item->topic,
          'title' => $item->topic,
          'score' => $item->calculated_score,
          'snippet' => search_excerpt($keys, $item->data, $item->langcode),
          'langcode' => $item->langcode,
        ];
        $results[] = $result;
      }

      return $results;
    }
    return [];
  }