Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 namespace Drupal\node\Plugin\Search;
|
Chris@0
|
4
|
Chris@0
|
5 use Drupal\Core\Access\AccessResult;
|
Chris@0
|
6 use Drupal\Core\Cache\CacheableMetadata;
|
Chris@0
|
7 use Drupal\Core\Config\Config;
|
Chris@0
|
8 use Drupal\Core\Database\Connection;
|
Chris@0
|
9 use Drupal\Core\Database\Query\SelectExtender;
|
Chris@0
|
10 use Drupal\Core\Database\StatementInterface;
|
Chris@0
|
11 use Drupal\Core\Entity\EntityManagerInterface;
|
Chris@0
|
12 use Drupal\Core\Extension\ModuleHandlerInterface;
|
Chris@0
|
13 use Drupal\Core\Form\FormStateInterface;
|
Chris@0
|
14 use Drupal\Core\Language\LanguageInterface;
|
Chris@0
|
15 use Drupal\Core\Language\LanguageManagerInterface;
|
Chris@0
|
16 use Drupal\Core\Session\AccountInterface;
|
Chris@0
|
17 use Drupal\Core\Access\AccessibleInterface;
|
Chris@0
|
18 use Drupal\Core\Database\Query\Condition;
|
Chris@0
|
19 use Drupal\Core\Render\RendererInterface;
|
Chris@0
|
20 use Drupal\node\NodeInterface;
|
Chris@0
|
21 use Drupal\search\Plugin\ConfigurableSearchPluginBase;
|
Chris@0
|
22 use Drupal\search\Plugin\SearchIndexingInterface;
|
Chris@0
|
23 use Drupal\Search\SearchQuery;
|
Chris@0
|
24 use Symfony\Component\DependencyInjection\ContainerInterface;
|
Chris@0
|
25
|
Chris@0
|
26 /**
|
Chris@0
|
27 * Handles searching for node entities using the Search module index.
|
Chris@0
|
28 *
|
Chris@0
|
29 * @SearchPlugin(
|
Chris@0
|
30 * id = "node_search",
|
Chris@0
|
31 * title = @Translation("Content")
|
Chris@0
|
32 * )
|
Chris@0
|
33 */
|
Chris@0
|
34 class NodeSearch extends ConfigurableSearchPluginBase implements AccessibleInterface, SearchIndexingInterface {
|
Chris@0
|
35
|
Chris@0
|
36 /**
|
Chris@0
|
37 * A database connection object.
|
Chris@0
|
38 *
|
Chris@0
|
39 * @var \Drupal\Core\Database\Connection
|
Chris@0
|
40 */
|
Chris@0
|
41 protected $database;
|
Chris@0
|
42
|
Chris@0
|
43 /**
|
Chris@0
|
44 * An entity manager object.
|
Chris@0
|
45 *
|
Chris@0
|
46 * @var \Drupal\Core\Entity\EntityManagerInterface
|
Chris@0
|
47 */
|
Chris@0
|
48 protected $entityManager;
|
Chris@0
|
49
|
Chris@0
|
50 /**
|
Chris@0
|
51 * A module manager object.
|
Chris@0
|
52 *
|
Chris@0
|
53 * @var \Drupal\Core\Extension\ModuleHandlerInterface
|
Chris@0
|
54 */
|
Chris@0
|
55 protected $moduleHandler;
|
Chris@0
|
56
|
Chris@0
|
57 /**
|
Chris@0
|
58 * A config object for 'search.settings'.
|
Chris@0
|
59 *
|
Chris@0
|
60 * @var \Drupal\Core\Config\Config
|
Chris@0
|
61 */
|
Chris@0
|
62 protected $searchSettings;
|
Chris@0
|
63
|
Chris@0
|
64 /**
|
Chris@0
|
65 * The language manager.
|
Chris@0
|
66 *
|
Chris@0
|
67 * @var \Drupal\Core\Language\LanguageManagerInterface
|
Chris@0
|
68 */
|
Chris@0
|
69 protected $languageManager;
|
Chris@0
|
70
|
Chris@0
|
71 /**
|
Chris@0
|
72 * The Drupal account to use for checking for access to advanced search.
|
Chris@0
|
73 *
|
Chris@0
|
74 * @var \Drupal\Core\Session\AccountInterface
|
Chris@0
|
75 */
|
Chris@0
|
76 protected $account;
|
Chris@0
|
77
|
Chris@0
|
78 /**
|
Chris@0
|
79 * The Renderer service to format the username and node.
|
Chris@0
|
80 *
|
Chris@0
|
81 * @var \Drupal\Core\Render\RendererInterface
|
Chris@0
|
82 */
|
Chris@0
|
83 protected $renderer;
|
Chris@0
|
84
|
Chris@0
|
85 /**
|
Chris@0
|
86 * An array of additional rankings from hook_ranking().
|
Chris@0
|
87 *
|
Chris@0
|
88 * @var array
|
Chris@0
|
89 */
|
Chris@0
|
90 protected $rankings;
|
Chris@0
|
91
|
Chris@0
|
92 /**
|
Chris@0
|
93 * The list of options and info for advanced search filters.
|
Chris@0
|
94 *
|
Chris@0
|
95 * Each entry in the array has the option as the key and for its value, an
|
Chris@0
|
96 * array that determines how the value is matched in the database query. The
|
Chris@0
|
97 * possible keys in that array are:
|
Chris@0
|
98 * - column: (required) Name of the database column to match against.
|
Chris@0
|
99 * - join: (optional) Information on a table to join. By default the data is
|
Chris@0
|
100 * matched against the {node_field_data} table.
|
Chris@0
|
101 * - operator: (optional) OR or AND, defaults to OR.
|
Chris@0
|
102 *
|
Chris@0
|
103 * @var array
|
Chris@0
|
104 */
|
Chris@0
|
105 protected $advanced = [
|
Chris@0
|
106 'type' => ['column' => 'n.type'],
|
Chris@0
|
107 'language' => ['column' => 'i.langcode'],
|
Chris@0
|
108 'author' => ['column' => 'n.uid'],
|
Chris@0
|
109 'term' => ['column' => 'ti.tid', 'join' => ['table' => 'taxonomy_index', 'alias' => 'ti', 'condition' => 'n.nid = ti.nid']],
|
Chris@0
|
110 ];
|
Chris@0
|
111
|
Chris@0
|
112 /**
|
Chris@0
|
113 * A constant for setting and checking the query string.
|
Chris@0
|
114 */
|
Chris@0
|
115 const ADVANCED_FORM = 'advanced-form';
|
Chris@0
|
116
|
Chris@0
|
117 /**
|
Chris@0
|
118 * {@inheritdoc}
|
Chris@0
|
119 */
|
Chris@0
|
120 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
|
Chris@0
|
121 return new static(
|
Chris@0
|
122 $configuration,
|
Chris@0
|
123 $plugin_id,
|
Chris@0
|
124 $plugin_definition,
|
Chris@0
|
125 $container->get('database'),
|
Chris@0
|
126 $container->get('entity.manager'),
|
Chris@0
|
127 $container->get('module_handler'),
|
Chris@0
|
128 $container->get('config.factory')->get('search.settings'),
|
Chris@0
|
129 $container->get('language_manager'),
|
Chris@0
|
130 $container->get('renderer'),
|
Chris@0
|
131 $container->get('current_user')
|
Chris@0
|
132 );
|
Chris@0
|
133 }
|
Chris@0
|
134
|
Chris@0
|
135 /**
|
Chris@0
|
136 * Constructs a \Drupal\node\Plugin\Search\NodeSearch object.
|
Chris@0
|
137 *
|
Chris@0
|
138 * @param array $configuration
|
Chris@0
|
139 * A configuration array containing information about the plugin instance.
|
Chris@0
|
140 * @param string $plugin_id
|
Chris@0
|
141 * The plugin_id for the plugin instance.
|
Chris@0
|
142 * @param mixed $plugin_definition
|
Chris@0
|
143 * The plugin implementation definition.
|
Chris@0
|
144 * @param \Drupal\Core\Database\Connection $database
|
Chris@0
|
145 * A database connection object.
|
Chris@0
|
146 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
|
Chris@0
|
147 * An entity manager object.
|
Chris@0
|
148 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
Chris@0
|
149 * A module manager object.
|
Chris@0
|
150 * @param \Drupal\Core\Config\Config $search_settings
|
Chris@0
|
151 * A config object for 'search.settings'.
|
Chris@0
|
152 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
|
Chris@0
|
153 * The language manager.
|
Chris@0
|
154 * @param \Drupal\Core\Render\RendererInterface $renderer
|
Chris@0
|
155 * The renderer.
|
Chris@0
|
156 * @param \Drupal\Core\Session\AccountInterface $account
|
Chris@0
|
157 * The $account object to use for checking for access to advanced search.
|
Chris@0
|
158 */
|
Chris@0
|
159 public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $database, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, Config $search_settings, LanguageManagerInterface $language_manager, RendererInterface $renderer, AccountInterface $account = NULL) {
|
Chris@0
|
160 $this->database = $database;
|
Chris@0
|
161 $this->entityManager = $entity_manager;
|
Chris@0
|
162 $this->moduleHandler = $module_handler;
|
Chris@0
|
163 $this->searchSettings = $search_settings;
|
Chris@0
|
164 $this->languageManager = $language_manager;
|
Chris@0
|
165 $this->renderer = $renderer;
|
Chris@0
|
166 $this->account = $account;
|
Chris@0
|
167 parent::__construct($configuration, $plugin_id, $plugin_definition);
|
Chris@0
|
168
|
Chris@0
|
169 $this->addCacheTags(['node_list']);
|
Chris@0
|
170 }
|
Chris@0
|
171
|
Chris@0
|
172 /**
|
Chris@0
|
173 * {@inheritdoc}
|
Chris@0
|
174 */
|
Chris@0
|
175 public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
|
Chris@0
|
176 $result = AccessResult::allowedIfHasPermission($account, 'access content');
|
Chris@0
|
177 return $return_as_object ? $result : $result->isAllowed();
|
Chris@0
|
178 }
|
Chris@0
|
179
|
Chris@0
|
180 /**
|
Chris@0
|
181 * {@inheritdoc}
|
Chris@0
|
182 */
|
Chris@0
|
183 public function isSearchExecutable() {
|
Chris@0
|
184 // Node search is executable if we have keywords or an advanced parameter.
|
Chris@0
|
185 // At least, we should parse out the parameters and see if there are any
|
Chris@0
|
186 // keyword matches in that case, rather than just printing out the
|
Chris@0
|
187 // "Please enter keywords" message.
|
Chris@0
|
188 return !empty($this->keywords) || (isset($this->searchParameters['f']) && count($this->searchParameters['f']));
|
Chris@0
|
189 }
|
Chris@0
|
190
|
Chris@0
|
191 /**
|
Chris@0
|
192 * {@inheritdoc}
|
Chris@0
|
193 */
|
Chris@0
|
194 public function getType() {
|
Chris@0
|
195 return $this->getPluginId();
|
Chris@0
|
196 }
|
Chris@0
|
197
|
Chris@0
|
198 /**
|
Chris@0
|
199 * {@inheritdoc}
|
Chris@0
|
200 */
|
Chris@0
|
201 public function execute() {
|
Chris@0
|
202 if ($this->isSearchExecutable()) {
|
Chris@0
|
203 $results = $this->findResults();
|
Chris@0
|
204
|
Chris@0
|
205 if ($results) {
|
Chris@0
|
206 return $this->prepareResults($results);
|
Chris@0
|
207 }
|
Chris@0
|
208 }
|
Chris@0
|
209
|
Chris@0
|
210 return [];
|
Chris@0
|
211 }
|
Chris@0
|
212
|
Chris@0
|
213 /**
|
Chris@0
|
214 * Queries to find search results, and sets status messages.
|
Chris@0
|
215 *
|
Chris@0
|
216 * This method can assume that $this->isSearchExecutable() has already been
|
Chris@0
|
217 * checked and returned TRUE.
|
Chris@0
|
218 *
|
Chris@0
|
219 * @return \Drupal\Core\Database\StatementInterface|null
|
Chris@0
|
220 * Results from search query execute() method, or NULL if the search
|
Chris@0
|
221 * failed.
|
Chris@0
|
222 */
|
Chris@0
|
223 protected function findResults() {
|
Chris@0
|
224 $keys = $this->keywords;
|
Chris@0
|
225
|
Chris@0
|
226 // Build matching conditions.
|
Chris@0
|
227 $query = $this->database
|
Chris@0
|
228 ->select('search_index', 'i', ['target' => 'replica'])
|
Chris@0
|
229 ->extend('Drupal\search\SearchQuery')
|
Chris@0
|
230 ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
|
Chris@0
|
231 $query->join('node_field_data', 'n', 'n.nid = i.sid AND n.langcode = i.langcode');
|
Chris@0
|
232 $query->condition('n.status', 1)
|
Chris@0
|
233 ->addTag('node_access')
|
Chris@0
|
234 ->searchExpression($keys, $this->getPluginId());
|
Chris@0
|
235
|
Chris@0
|
236 // Handle advanced search filters in the f query string.
|
Chris@0
|
237 // \Drupal::request()->query->get('f') is an array that looks like this in
|
Chris@0
|
238 // the URL: ?f[]=type:page&f[]=term:27&f[]=term:13&f[]=langcode:en
|
Chris@0
|
239 // So $parameters['f'] looks like:
|
Chris@0
|
240 // array('type:page', 'term:27', 'term:13', 'langcode:en');
|
Chris@0
|
241 // We need to parse this out into query conditions, some of which go into
|
Chris@0
|
242 // the keywords string, and some of which are separate conditions.
|
Chris@0
|
243 $parameters = $this->getParameters();
|
Chris@0
|
244 if (!empty($parameters['f']) && is_array($parameters['f'])) {
|
Chris@0
|
245 $filters = [];
|
Chris@0
|
246 // Match any query value that is an expected option and a value
|
Chris@0
|
247 // separated by ':' like 'term:27'.
|
Chris@0
|
248 $pattern = '/^(' . implode('|', array_keys($this->advanced)) . '):([^ ]*)/i';
|
Chris@0
|
249 foreach ($parameters['f'] as $item) {
|
Chris@0
|
250 if (preg_match($pattern, $item, $m)) {
|
Chris@0
|
251 // Use the matched value as the array key to eliminate duplicates.
|
Chris@0
|
252 $filters[$m[1]][$m[2]] = $m[2];
|
Chris@0
|
253 }
|
Chris@0
|
254 }
|
Chris@0
|
255
|
Chris@0
|
256 // Now turn these into query conditions. This assumes that everything in
|
Chris@0
|
257 // $filters is a known type of advanced search.
|
Chris@0
|
258 foreach ($filters as $option => $matched) {
|
Chris@0
|
259 $info = $this->advanced[$option];
|
Chris@0
|
260 // Insert additional conditions. By default, all use the OR operator.
|
Chris@0
|
261 $operator = empty($info['operator']) ? 'OR' : $info['operator'];
|
Chris@0
|
262 $where = new Condition($operator);
|
Chris@0
|
263 foreach ($matched as $value) {
|
Chris@0
|
264 $where->condition($info['column'], $value);
|
Chris@0
|
265 }
|
Chris@0
|
266 $query->condition($where);
|
Chris@0
|
267 if (!empty($info['join'])) {
|
Chris@0
|
268 $query->join($info['join']['table'], $info['join']['alias'], $info['join']['condition']);
|
Chris@0
|
269 }
|
Chris@0
|
270 }
|
Chris@0
|
271 }
|
Chris@0
|
272
|
Chris@0
|
273 // Add the ranking expressions.
|
Chris@0
|
274 $this->addNodeRankings($query);
|
Chris@0
|
275
|
Chris@0
|
276 // Run the query.
|
Chris@0
|
277 $find = $query
|
Chris@0
|
278 // Add the language code of the indexed item to the result of the query,
|
Chris@0
|
279 // since the node will be rendered using the respective language.
|
Chris@0
|
280 ->fields('i', ['langcode'])
|
Chris@0
|
281 // And since SearchQuery makes these into GROUP BY queries, if we add
|
Chris@0
|
282 // a field, for PostgreSQL we also need to make it an aggregate or a
|
Chris@0
|
283 // GROUP BY. In this case, we want GROUP BY.
|
Chris@0
|
284 ->groupBy('i.langcode')
|
Chris@0
|
285 ->limit(10)
|
Chris@0
|
286 ->execute();
|
Chris@0
|
287
|
Chris@0
|
288 // Check query status and set messages if needed.
|
Chris@0
|
289 $status = $query->getStatus();
|
Chris@0
|
290
|
Chris@0
|
291 if ($status & SearchQuery::EXPRESSIONS_IGNORED) {
|
Chris@0
|
292 drupal_set_message($this->t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', ['@count' => $this->searchSettings->get('and_or_limit')]), 'warning');
|
Chris@0
|
293 }
|
Chris@0
|
294
|
Chris@0
|
295 if ($status & SearchQuery::LOWER_CASE_OR) {
|
Chris@0
|
296 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');
|
Chris@0
|
297 }
|
Chris@0
|
298
|
Chris@0
|
299 if ($status & SearchQuery::NO_POSITIVE_KEYWORDS) {
|
Chris@0
|
300 drupal_set_message($this->formatPlural($this->searchSettings->get('index.minimum_word_size'), 'You must include at least one keyword to match in the content, and punctuation is ignored.', 'You must include at least one keyword to match in the content. Keywords must be at least @count characters, and punctuation is ignored.'), 'warning');
|
Chris@0
|
301 }
|
Chris@0
|
302
|
Chris@0
|
303 return $find;
|
Chris@0
|
304 }
|
Chris@0
|
305
|
Chris@0
|
306 /**
|
Chris@0
|
307 * Prepares search results for rendering.
|
Chris@0
|
308 *
|
Chris@0
|
309 * @param \Drupal\Core\Database\StatementInterface $found
|
Chris@0
|
310 * Results found from a successful search query execute() method.
|
Chris@0
|
311 *
|
Chris@0
|
312 * @return array
|
Chris@0
|
313 * Array of search result item render arrays (empty array if no results).
|
Chris@0
|
314 */
|
Chris@0
|
315 protected function prepareResults(StatementInterface $found) {
|
Chris@0
|
316 $results = [];
|
Chris@0
|
317
|
Chris@0
|
318 $node_storage = $this->entityManager->getStorage('node');
|
Chris@0
|
319 $node_render = $this->entityManager->getViewBuilder('node');
|
Chris@0
|
320 $keys = $this->keywords;
|
Chris@0
|
321
|
Chris@0
|
322 foreach ($found as $item) {
|
Chris@0
|
323 // Render the node.
|
Chris@0
|
324 /** @var \Drupal\node\NodeInterface $node */
|
Chris@0
|
325 $node = $node_storage->load($item->sid)->getTranslation($item->langcode);
|
Chris@0
|
326 $build = $node_render->view($node, 'search_result', $item->langcode);
|
Chris@0
|
327
|
Chris@0
|
328 /** @var \Drupal\node\NodeTypeInterface $type*/
|
Chris@0
|
329 $type = $this->entityManager->getStorage('node_type')->load($node->bundle());
|
Chris@0
|
330
|
Chris@0
|
331 unset($build['#theme']);
|
Chris@0
|
332 $build['#pre_render'][] = [$this, 'removeSubmittedInfo'];
|
Chris@0
|
333
|
Chris@0
|
334 // Fetch comments for snippet.
|
Chris@0
|
335 $rendered = $this->renderer->renderPlain($build);
|
Chris@0
|
336 $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
|
Chris@0
|
337 $rendered .= ' ' . $this->moduleHandler->invoke('comment', 'node_update_index', [$node]);
|
Chris@0
|
338
|
Chris@0
|
339 $extra = $this->moduleHandler->invokeAll('node_search_result', [$node]);
|
Chris@0
|
340
|
Chris@0
|
341 $language = $this->languageManager->getLanguage($item->langcode);
|
Chris@0
|
342 $username = [
|
Chris@0
|
343 '#theme' => 'username',
|
Chris@0
|
344 '#account' => $node->getOwner(),
|
Chris@0
|
345 ];
|
Chris@0
|
346
|
Chris@0
|
347 $result = [
|
Chris@0
|
348 'link' => $node->url('canonical', ['absolute' => TRUE, 'language' => $language]),
|
Chris@0
|
349 'type' => $type->label(),
|
Chris@0
|
350 'title' => $node->label(),
|
Chris@0
|
351 'node' => $node,
|
Chris@0
|
352 'extra' => $extra,
|
Chris@0
|
353 'score' => $item->calculated_score,
|
Chris@0
|
354 'snippet' => search_excerpt($keys, $rendered, $item->langcode),
|
Chris@0
|
355 'langcode' => $node->language()->getId(),
|
Chris@0
|
356 ];
|
Chris@0
|
357
|
Chris@0
|
358 $this->addCacheableDependency($node);
|
Chris@0
|
359
|
Chris@0
|
360 // We have to separately add the node owner's cache tags because search
|
Chris@0
|
361 // module doesn't use the rendering system, it does its own rendering
|
Chris@0
|
362 // without taking cacheability metadata into account. So we have to do it
|
Chris@0
|
363 // explicitly here.
|
Chris@0
|
364 $this->addCacheableDependency($node->getOwner());
|
Chris@0
|
365
|
Chris@0
|
366 if ($type->displaySubmitted()) {
|
Chris@0
|
367 $result += [
|
Chris@0
|
368 'user' => $this->renderer->renderPlain($username),
|
Chris@0
|
369 'date' => $node->getChangedTime(),
|
Chris@0
|
370 ];
|
Chris@0
|
371 }
|
Chris@0
|
372
|
Chris@0
|
373 $results[] = $result;
|
Chris@0
|
374
|
Chris@0
|
375 }
|
Chris@0
|
376 return $results;
|
Chris@0
|
377 }
|
Chris@0
|
378
|
Chris@0
|
379 /**
|
Chris@0
|
380 * Removes the submitted by information from the build array.
|
Chris@0
|
381 *
|
Chris@0
|
382 * This information is being removed from the rendered node that is used to
|
Chris@0
|
383 * build the search result snippet. It just doesn't make sense to have it
|
Chris@0
|
384 * displayed in the snippet.
|
Chris@0
|
385 *
|
Chris@0
|
386 * @param array $build
|
Chris@0
|
387 * The build array.
|
Chris@0
|
388 *
|
Chris@0
|
389 * @return array
|
Chris@0
|
390 * The modified build array.
|
Chris@0
|
391 */
|
Chris@0
|
392 public function removeSubmittedInfo(array $build) {
|
Chris@0
|
393 unset($build['created']);
|
Chris@0
|
394 unset($build['uid']);
|
Chris@0
|
395 return $build;
|
Chris@0
|
396 }
|
Chris@0
|
397
|
Chris@0
|
398 /**
|
Chris@0
|
399 * Adds the configured rankings to the search query.
|
Chris@0
|
400 *
|
Chris@0
|
401 * @param $query
|
Chris@0
|
402 * A query object that has been extended with the Search DB Extender.
|
Chris@0
|
403 */
|
Chris@0
|
404 protected function addNodeRankings(SelectExtender $query) {
|
Chris@0
|
405 if ($ranking = $this->getRankings()) {
|
Chris@0
|
406 $tables = &$query->getTables();
|
Chris@0
|
407 foreach ($ranking as $rank => $values) {
|
Chris@0
|
408 if (isset($this->configuration['rankings'][$rank]) && !empty($this->configuration['rankings'][$rank])) {
|
Chris@0
|
409 $node_rank = $this->configuration['rankings'][$rank];
|
Chris@0
|
410 // If the table defined in the ranking isn't already joined, then add it.
|
Chris@0
|
411 if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
|
Chris@0
|
412 $query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
|
Chris@0
|
413 }
|
Chris@0
|
414 $arguments = isset($values['arguments']) ? $values['arguments'] : [];
|
Chris@0
|
415 $query->addScore($values['score'], $arguments, $node_rank);
|
Chris@0
|
416 }
|
Chris@0
|
417 }
|
Chris@0
|
418 }
|
Chris@0
|
419 }
|
Chris@0
|
420
|
Chris@0
|
421 /**
|
Chris@0
|
422 * {@inheritdoc}
|
Chris@0
|
423 */
|
Chris@0
|
424 public function updateIndex() {
|
Chris@0
|
425 // Interpret the cron limit setting as the maximum number of nodes to index
|
Chris@0
|
426 // per cron run.
|
Chris@0
|
427 $limit = (int) $this->searchSettings->get('index.cron_limit');
|
Chris@0
|
428
|
Chris@0
|
429 $query = db_select('node', 'n', ['target' => 'replica']);
|
Chris@0
|
430 $query->addField('n', 'nid');
|
Chris@0
|
431 $query->leftJoin('search_dataset', 'sd', 'sd.sid = n.nid AND sd.type = :type', [':type' => $this->getPluginId()]);
|
Chris@0
|
432 $query->addExpression('CASE MAX(sd.reindex) WHEN NULL THEN 0 ELSE 1 END', 'ex');
|
Chris@0
|
433 $query->addExpression('MAX(sd.reindex)', 'ex2');
|
Chris@0
|
434 $query->condition(
|
Chris@0
|
435 $query->orConditionGroup()
|
Chris@0
|
436 ->where('sd.sid IS NULL')
|
Chris@0
|
437 ->condition('sd.reindex', 0, '<>')
|
Chris@0
|
438 );
|
Chris@0
|
439 $query->orderBy('ex', 'DESC')
|
Chris@0
|
440 ->orderBy('ex2')
|
Chris@0
|
441 ->orderBy('n.nid')
|
Chris@0
|
442 ->groupBy('n.nid')
|
Chris@0
|
443 ->range(0, $limit);
|
Chris@0
|
444
|
Chris@0
|
445 $nids = $query->execute()->fetchCol();
|
Chris@0
|
446 if (!$nids) {
|
Chris@0
|
447 return;
|
Chris@0
|
448 }
|
Chris@0
|
449
|
Chris@0
|
450 $node_storage = $this->entityManager->getStorage('node');
|
Chris@0
|
451 foreach ($node_storage->loadMultiple($nids) as $node) {
|
Chris@0
|
452 $this->indexNode($node);
|
Chris@0
|
453 }
|
Chris@0
|
454 }
|
Chris@0
|
455
|
Chris@0
|
456 /**
|
Chris@0
|
457 * Indexes a single node.
|
Chris@0
|
458 *
|
Chris@0
|
459 * @param \Drupal\node\NodeInterface $node
|
Chris@0
|
460 * The node to index.
|
Chris@0
|
461 */
|
Chris@0
|
462 protected function indexNode(NodeInterface $node) {
|
Chris@0
|
463 $languages = $node->getTranslationLanguages();
|
Chris@0
|
464 $node_render = $this->entityManager->getViewBuilder('node');
|
Chris@0
|
465
|
Chris@0
|
466 foreach ($languages as $language) {
|
Chris@0
|
467 $node = $node->getTranslation($language->getId());
|
Chris@0
|
468 // Render the node.
|
Chris@0
|
469 $build = $node_render->view($node, 'search_index', $language->getId());
|
Chris@0
|
470
|
Chris@0
|
471 unset($build['#theme']);
|
Chris@0
|
472
|
Chris@0
|
473 // Add the title to text so it is searchable.
|
Chris@0
|
474 $build['search_title'] = [
|
Chris@0
|
475 '#prefix' => '<h1>',
|
Chris@0
|
476 '#plain_text' => $node->label(),
|
Chris@0
|
477 '#suffix' => '</h1>',
|
Chris@0
|
478 '#weight' => -1000
|
Chris@0
|
479 ];
|
Chris@0
|
480 $text = $this->renderer->renderPlain($build);
|
Chris@0
|
481
|
Chris@0
|
482 // Fetch extra data normally not visible.
|
Chris@0
|
483 $extra = $this->moduleHandler->invokeAll('node_update_index', [$node]);
|
Chris@0
|
484 foreach ($extra as $t) {
|
Chris@0
|
485 $text .= $t;
|
Chris@0
|
486 }
|
Chris@0
|
487
|
Chris@0
|
488 // Update index, using search index "type" equal to the plugin ID.
|
Chris@0
|
489 search_index($this->getPluginId(), $node->id(), $language->getId(), $text);
|
Chris@0
|
490 }
|
Chris@0
|
491 }
|
Chris@0
|
492
|
Chris@0
|
493 /**
|
Chris@0
|
494 * {@inheritdoc}
|
Chris@0
|
495 */
|
Chris@0
|
496 public function indexClear() {
|
Chris@0
|
497 // All NodeSearch pages share a common search index "type" equal to
|
Chris@0
|
498 // the plugin ID.
|
Chris@0
|
499 search_index_clear($this->getPluginId());
|
Chris@0
|
500 }
|
Chris@0
|
501
|
Chris@0
|
502 /**
|
Chris@0
|
503 * {@inheritdoc}
|
Chris@0
|
504 */
|
Chris@0
|
505 public function markForReindex() {
|
Chris@0
|
506 // All NodeSearch pages share a common search index "type" equal to
|
Chris@0
|
507 // the plugin ID.
|
Chris@0
|
508 search_mark_for_reindex($this->getPluginId());
|
Chris@0
|
509 }
|
Chris@0
|
510
|
Chris@0
|
511 /**
|
Chris@0
|
512 * {@inheritdoc}
|
Chris@0
|
513 */
|
Chris@0
|
514 public function indexStatus() {
|
Chris@0
|
515 $total = $this->database->query('SELECT COUNT(*) FROM {node}')->fetchField();
|
Chris@0
|
516 $remaining = $this->database->query("SELECT COUNT(DISTINCT n.nid) FROM {node} n LEFT JOIN {search_dataset} sd ON sd.sid = n.nid AND sd.type = :type WHERE sd.sid IS NULL OR sd.reindex <> 0", [':type' => $this->getPluginId()])->fetchField();
|
Chris@0
|
517
|
Chris@0
|
518 return ['remaining' => $remaining, 'total' => $total];
|
Chris@0
|
519 }
|
Chris@0
|
520
|
Chris@0
|
521 /**
|
Chris@0
|
522 * {@inheritdoc}
|
Chris@0
|
523 */
|
Chris@0
|
524 public function searchFormAlter(array &$form, FormStateInterface $form_state) {
|
Chris@0
|
525 $parameters = $this->getParameters();
|
Chris@0
|
526 $keys = $this->getKeywords();
|
Chris@0
|
527 $used_advanced = !empty($parameters[self::ADVANCED_FORM]);
|
Chris@0
|
528 if ($used_advanced) {
|
Chris@0
|
529 $f = isset($parameters['f']) ? (array) $parameters['f'] : [];
|
Chris@0
|
530 $defaults = $this->parseAdvancedDefaults($f, $keys);
|
Chris@0
|
531 }
|
Chris@0
|
532 else {
|
Chris@0
|
533 $defaults = ['keys' => $keys];
|
Chris@0
|
534 }
|
Chris@0
|
535
|
Chris@0
|
536 $form['basic']['keys']['#default_value'] = $defaults['keys'];
|
Chris@0
|
537
|
Chris@0
|
538 // Add advanced search keyword-related boxes.
|
Chris@0
|
539 $form['advanced'] = [
|
Chris@0
|
540 '#type' => 'details',
|
Chris@0
|
541 '#title' => t('Advanced search'),
|
Chris@0
|
542 '#attributes' => ['class' => ['search-advanced']],
|
Chris@0
|
543 '#access' => $this->account && $this->account->hasPermission('use advanced search'),
|
Chris@0
|
544 '#open' => $used_advanced,
|
Chris@0
|
545 ];
|
Chris@0
|
546 $form['advanced']['keywords-fieldset'] = [
|
Chris@0
|
547 '#type' => 'fieldset',
|
Chris@0
|
548 '#title' => t('Keywords'),
|
Chris@0
|
549 ];
|
Chris@0
|
550
|
Chris@0
|
551 $form['advanced']['keywords'] = [
|
Chris@0
|
552 '#prefix' => '<div class="criterion">',
|
Chris@0
|
553 '#suffix' => '</div>',
|
Chris@0
|
554 ];
|
Chris@0
|
555
|
Chris@0
|
556 $form['advanced']['keywords-fieldset']['keywords']['or'] = [
|
Chris@0
|
557 '#type' => 'textfield',
|
Chris@0
|
558 '#title' => t('Containing any of the words'),
|
Chris@0
|
559 '#size' => 30,
|
Chris@0
|
560 '#maxlength' => 255,
|
Chris@0
|
561 '#default_value' => isset($defaults['or']) ? $defaults['or'] : '',
|
Chris@0
|
562 ];
|
Chris@0
|
563
|
Chris@0
|
564 $form['advanced']['keywords-fieldset']['keywords']['phrase'] = [
|
Chris@0
|
565 '#type' => 'textfield',
|
Chris@0
|
566 '#title' => t('Containing the phrase'),
|
Chris@0
|
567 '#size' => 30,
|
Chris@0
|
568 '#maxlength' => 255,
|
Chris@0
|
569 '#default_value' => isset($defaults['phrase']) ? $defaults['phrase'] : '',
|
Chris@0
|
570 ];
|
Chris@0
|
571
|
Chris@0
|
572 $form['advanced']['keywords-fieldset']['keywords']['negative'] = [
|
Chris@0
|
573 '#type' => 'textfield',
|
Chris@0
|
574 '#title' => t('Containing none of the words'),
|
Chris@0
|
575 '#size' => 30,
|
Chris@0
|
576 '#maxlength' => 255,
|
Chris@0
|
577 '#default_value' => isset($defaults['negative']) ? $defaults['negative'] : '',
|
Chris@0
|
578 ];
|
Chris@0
|
579
|
Chris@0
|
580 // Add node types.
|
Chris@0
|
581 $types = array_map(['\Drupal\Component\Utility\Html', 'escape'], node_type_get_names());
|
Chris@0
|
582 $form['advanced']['types-fieldset'] = [
|
Chris@0
|
583 '#type' => 'fieldset',
|
Chris@0
|
584 '#title' => t('Types'),
|
Chris@0
|
585 ];
|
Chris@0
|
586 $form['advanced']['types-fieldset']['type'] = [
|
Chris@0
|
587 '#type' => 'checkboxes',
|
Chris@0
|
588 '#title' => t('Only of the type(s)'),
|
Chris@0
|
589 '#prefix' => '<div class="criterion">',
|
Chris@0
|
590 '#suffix' => '</div>',
|
Chris@0
|
591 '#options' => $types,
|
Chris@0
|
592 '#default_value' => isset($defaults['type']) ? $defaults['type'] : [],
|
Chris@0
|
593 ];
|
Chris@0
|
594
|
Chris@0
|
595 $form['advanced']['submit'] = [
|
Chris@0
|
596 '#type' => 'submit',
|
Chris@0
|
597 '#value' => t('Advanced search'),
|
Chris@0
|
598 '#prefix' => '<div class="action">',
|
Chris@0
|
599 '#suffix' => '</div>',
|
Chris@0
|
600 '#weight' => 100,
|
Chris@0
|
601 ];
|
Chris@0
|
602
|
Chris@0
|
603 // Add languages.
|
Chris@0
|
604 $language_options = [];
|
Chris@0
|
605 $language_list = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL);
|
Chris@0
|
606 foreach ($language_list as $langcode => $language) {
|
Chris@0
|
607 // Make locked languages appear special in the list.
|
Chris@0
|
608 $language_options[$langcode] = $language->isLocked() ? t('- @name -', ['@name' => $language->getName()]) : $language->getName();
|
Chris@0
|
609 }
|
Chris@0
|
610 if (count($language_options) > 1) {
|
Chris@0
|
611 $form['advanced']['lang-fieldset'] = [
|
Chris@0
|
612 '#type' => 'fieldset',
|
Chris@0
|
613 '#title' => t('Languages'),
|
Chris@0
|
614 ];
|
Chris@0
|
615 $form['advanced']['lang-fieldset']['language'] = [
|
Chris@0
|
616 '#type' => 'checkboxes',
|
Chris@0
|
617 '#title' => t('Languages'),
|
Chris@0
|
618 '#prefix' => '<div class="criterion">',
|
Chris@0
|
619 '#suffix' => '</div>',
|
Chris@0
|
620 '#options' => $language_options,
|
Chris@0
|
621 '#default_value' => isset($defaults['language']) ? $defaults['language'] : [],
|
Chris@0
|
622 ];
|
Chris@0
|
623 }
|
Chris@0
|
624 }
|
Chris@0
|
625
|
Chris@0
|
626 /**
|
Chris@0
|
627 * {@inheritdoc}
|
Chris@0
|
628 */
|
Chris@0
|
629 public function buildSearchUrlQuery(FormStateInterface $form_state) {
|
Chris@0
|
630 // Read keyword and advanced search information from the form values,
|
Chris@0
|
631 // and put these into the GET parameters.
|
Chris@0
|
632 $keys = trim($form_state->getValue('keys'));
|
Chris@0
|
633 $advanced = FALSE;
|
Chris@0
|
634
|
Chris@0
|
635 // Collect extra filters.
|
Chris@0
|
636 $filters = [];
|
Chris@0
|
637 if ($form_state->hasValue('type') && is_array($form_state->getValue('type'))) {
|
Chris@0
|
638 // Retrieve selected types - Form API sets the value of unselected
|
Chris@0
|
639 // checkboxes to 0.
|
Chris@0
|
640 foreach ($form_state->getValue('type') as $type) {
|
Chris@0
|
641 if ($type) {
|
Chris@0
|
642 $advanced = TRUE;
|
Chris@0
|
643 $filters[] = 'type:' . $type;
|
Chris@0
|
644 }
|
Chris@0
|
645 }
|
Chris@0
|
646 }
|
Chris@0
|
647
|
Chris@0
|
648 if ($form_state->hasValue('term') && is_array($form_state->getValue('term'))) {
|
Chris@0
|
649 foreach ($form_state->getValue('term') as $term) {
|
Chris@0
|
650 $filters[] = 'term:' . $term;
|
Chris@0
|
651 $advanced = TRUE;
|
Chris@0
|
652 }
|
Chris@0
|
653 }
|
Chris@0
|
654 if ($form_state->hasValue('language') && is_array($form_state->getValue('language'))) {
|
Chris@0
|
655 foreach ($form_state->getValue('language') as $language) {
|
Chris@0
|
656 if ($language) {
|
Chris@0
|
657 $advanced = TRUE;
|
Chris@0
|
658 $filters[] = 'language:' . $language;
|
Chris@0
|
659 }
|
Chris@0
|
660 }
|
Chris@0
|
661 }
|
Chris@0
|
662 if ($form_state->getValue('or') != '') {
|
Chris@0
|
663 if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state->getValue('or'), $matches)) {
|
Chris@0
|
664 $keys .= ' ' . implode(' OR ', $matches[1]);
|
Chris@0
|
665 $advanced = TRUE;
|
Chris@0
|
666 }
|
Chris@0
|
667 }
|
Chris@0
|
668 if ($form_state->getValue('negative') != '') {
|
Chris@0
|
669 if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state->getValue('negative'), $matches)) {
|
Chris@0
|
670 $keys .= ' -' . implode(' -', $matches[1]);
|
Chris@0
|
671 $advanced = TRUE;
|
Chris@0
|
672 }
|
Chris@0
|
673 }
|
Chris@0
|
674 if ($form_state->getValue('phrase') != '') {
|
Chris@0
|
675 $keys .= ' "' . str_replace('"', ' ', $form_state->getValue('phrase')) . '"';
|
Chris@0
|
676 $advanced = TRUE;
|
Chris@0
|
677 }
|
Chris@0
|
678 $keys = trim($keys);
|
Chris@0
|
679
|
Chris@0
|
680 // Put the keywords and advanced parameters into GET parameters. Make sure
|
Chris@0
|
681 // to put keywords into the query even if it is empty, because the page
|
Chris@0
|
682 // controller uses that to decide it's time to check for search results.
|
Chris@0
|
683 $query = ['keys' => $keys];
|
Chris@0
|
684 if ($filters) {
|
Chris@0
|
685 $query['f'] = $filters;
|
Chris@0
|
686 }
|
Chris@0
|
687 // Record that the person used the advanced search form, if they did.
|
Chris@0
|
688 if ($advanced) {
|
Chris@0
|
689 $query[self::ADVANCED_FORM] = '1';
|
Chris@0
|
690 }
|
Chris@0
|
691
|
Chris@0
|
692 return $query;
|
Chris@0
|
693 }
|
Chris@0
|
694
|
Chris@0
|
695 /**
|
Chris@0
|
696 * Parses the advanced search form default values.
|
Chris@0
|
697 *
|
Chris@0
|
698 * @param array $f
|
Chris@0
|
699 * The 'f' query parameter set up in self::buildUrlSearchQuery(), which
|
Chris@0
|
700 * contains the advanced query values.
|
Chris@0
|
701 * @param string $keys
|
Chris@0
|
702 * The search keywords string, which contains some information from the
|
Chris@0
|
703 * advanced search form.
|
Chris@0
|
704 *
|
Chris@0
|
705 * @return array
|
Chris@0
|
706 * Array of default form values for the advanced search form, including
|
Chris@0
|
707 * a modified 'keys' element for the bare search keywords.
|
Chris@0
|
708 */
|
Chris@0
|
709 protected function parseAdvancedDefaults($f, $keys) {
|
Chris@0
|
710 $defaults = [];
|
Chris@0
|
711
|
Chris@0
|
712 // Split out the advanced search parameters.
|
Chris@0
|
713 foreach ($f as $advanced) {
|
Chris@0
|
714 list($key, $value) = explode(':', $advanced, 2);
|
Chris@0
|
715 if (!isset($defaults[$key])) {
|
Chris@0
|
716 $defaults[$key] = [];
|
Chris@0
|
717 }
|
Chris@0
|
718 $defaults[$key][] = $value;
|
Chris@0
|
719 }
|
Chris@0
|
720
|
Chris@0
|
721 // Split out the negative, phrase, and OR parts of keywords.
|
Chris@0
|
722
|
Chris@0
|
723 // For phrases, the form only supports one phrase.
|
Chris@0
|
724 $matches = [];
|
Chris@0
|
725 $keys = ' ' . $keys . ' ';
|
Chris@0
|
726 if (preg_match('/ "([^"]+)" /', $keys, $matches)) {
|
Chris@0
|
727 $keys = str_replace($matches[0], ' ', $keys);
|
Chris@0
|
728 $defaults['phrase'] = $matches[1];
|
Chris@0
|
729 }
|
Chris@0
|
730
|
Chris@0
|
731 // Negative keywords: pull all of them out.
|
Chris@0
|
732 if (preg_match_all('/ -([^ ]+)/', $keys, $matches)) {
|
Chris@0
|
733 $keys = str_replace($matches[0], ' ', $keys);
|
Chris@0
|
734 $defaults['negative'] = implode(' ', $matches[1]);
|
Chris@0
|
735 }
|
Chris@0
|
736
|
Chris@0
|
737 // OR keywords: pull up to one set of them out of the query.
|
Chris@0
|
738 if (preg_match('/ [^ ]+( OR [^ ]+)+ /', $keys, $matches)) {
|
Chris@0
|
739 $keys = str_replace($matches[0], ' ', $keys);
|
Chris@0
|
740 $words = explode(' OR ', trim($matches[0]));
|
Chris@0
|
741 $defaults['or'] = implode(' ', $words);
|
Chris@0
|
742 }
|
Chris@0
|
743
|
Chris@0
|
744 // Put remaining keywords string back into keywords.
|
Chris@0
|
745 $defaults['keys'] = trim($keys);
|
Chris@0
|
746
|
Chris@0
|
747 return $defaults;
|
Chris@0
|
748 }
|
Chris@0
|
749
|
Chris@0
|
750 /**
|
Chris@0
|
751 * Gathers ranking definitions from hook_ranking().
|
Chris@0
|
752 *
|
Chris@0
|
753 * @return array
|
Chris@0
|
754 * An array of ranking definitions.
|
Chris@0
|
755 */
|
Chris@0
|
756 protected function getRankings() {
|
Chris@0
|
757 if (!$this->rankings) {
|
Chris@0
|
758 $this->rankings = $this->moduleHandler->invokeAll('ranking');
|
Chris@0
|
759 }
|
Chris@0
|
760 return $this->rankings;
|
Chris@0
|
761 }
|
Chris@0
|
762
|
Chris@0
|
763 /**
|
Chris@0
|
764 * {@inheritdoc}
|
Chris@0
|
765 */
|
Chris@0
|
766 public function defaultConfiguration() {
|
Chris@0
|
767 $configuration = [
|
Chris@0
|
768 'rankings' => [],
|
Chris@0
|
769 ];
|
Chris@0
|
770 return $configuration;
|
Chris@0
|
771 }
|
Chris@0
|
772
|
Chris@0
|
773 /**
|
Chris@0
|
774 * {@inheritdoc}
|
Chris@0
|
775 */
|
Chris@0
|
776 public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
|
Chris@0
|
777 // Output form for defining rank factor weights.
|
Chris@0
|
778 $form['content_ranking'] = [
|
Chris@0
|
779 '#type' => 'details',
|
Chris@0
|
780 '#title' => t('Content ranking'),
|
Chris@0
|
781 '#open' => TRUE,
|
Chris@0
|
782 ];
|
Chris@0
|
783 $form['content_ranking']['info'] = [
|
Chris@0
|
784 '#markup' => '<p><em>' . $this->t('Influence is a numeric multiplier used in ordering search results. A higher number means the corresponding factor has more influence on search results; zero means the factor is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em></p>'
|
Chris@0
|
785 ];
|
Chris@0
|
786 // Prepare table.
|
Chris@0
|
787 $header = [$this->t('Factor'), $this->t('Influence')];
|
Chris@0
|
788 $form['content_ranking']['rankings'] = [
|
Chris@0
|
789 '#type' => 'table',
|
Chris@0
|
790 '#header' => $header,
|
Chris@0
|
791 ];
|
Chris@0
|
792
|
Chris@0
|
793 // Note: reversed to reflect that higher number = higher ranking.
|
Chris@0
|
794 $range = range(0, 10);
|
Chris@0
|
795 $options = array_combine($range, $range);
|
Chris@0
|
796 foreach ($this->getRankings() as $var => $values) {
|
Chris@0
|
797 $form['content_ranking']['rankings'][$var]['name'] = [
|
Chris@0
|
798 '#markup' => $values['title'],
|
Chris@0
|
799 ];
|
Chris@0
|
800 $form['content_ranking']['rankings'][$var]['value'] = [
|
Chris@0
|
801 '#type' => 'select',
|
Chris@0
|
802 '#options' => $options,
|
Chris@0
|
803 '#attributes' => ['aria-label' => $this->t("Influence of '@title'", ['@title' => $values['title']])],
|
Chris@0
|
804 '#default_value' => isset($this->configuration['rankings'][$var]) ? $this->configuration['rankings'][$var] : 0,
|
Chris@0
|
805 ];
|
Chris@0
|
806 }
|
Chris@0
|
807 return $form;
|
Chris@0
|
808 }
|
Chris@0
|
809
|
Chris@0
|
810 /**
|
Chris@0
|
811 * {@inheritdoc}
|
Chris@0
|
812 */
|
Chris@0
|
813 public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
|
Chris@0
|
814 foreach ($this->getRankings() as $var => $values) {
|
Chris@0
|
815 if (!$form_state->isValueEmpty(['rankings', $var, 'value'])) {
|
Chris@0
|
816 $this->configuration['rankings'][$var] = $form_state->getValue(['rankings', $var, 'value']);
|
Chris@0
|
817 }
|
Chris@0
|
818 else {
|
Chris@0
|
819 unset($this->configuration['rankings'][$var]);
|
Chris@0
|
820 }
|
Chris@0
|
821 }
|
Chris@0
|
822 }
|
Chris@0
|
823
|
Chris@0
|
824 }
|