Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / node / node.module
1 <?php
2
3 /**
4  * @file
5  * The core module that allows content to be submitted to the site.
6  *
7  * Modules and scripts may programmatically submit nodes using the usual form
8  * API pattern.
9  */
10
11 use Drupal\Component\Utility\Xss;
12 use Drupal\Core\Access\AccessResult;
13 use Drupal\Core\Cache\Cache;
14 use Drupal\Core\Database\Query\AlterableInterface;
15 use Drupal\Core\Database\Query\SelectInterface;
16 use Drupal\Core\Database\StatementInterface;
17 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
18 use Drupal\Core\Form\FormStateInterface;
19 use Drupal\Core\Render\Element;
20 use Drupal\Core\Routing\RouteMatchInterface;
21 use Drupal\Core\Session\AccountInterface;
22 use Drupal\Core\Template\Attribute;
23 use Drupal\Core\Url;
24 use Drupal\field\Entity\FieldConfig;
25 use Drupal\field\Entity\FieldStorageConfig;
26 use Drupal\language\ConfigurableLanguageInterface;
27 use Drupal\node\Entity\Node;
28 use Drupal\node\Entity\NodeType;
29 use Drupal\node\NodeInterface;
30 use Drupal\node\NodeTypeInterface;
31
32 /**
33  * Denotes that the node is not published.
34  *
35  * @deprecated Scheduled for removal in Drupal 9.0.x.
36  *   Use \Drupal\node\NodeInterface::NOT_PUBLISHED instead.
37  */
38 const NODE_NOT_PUBLISHED = 0;
39
40 /**
41  * Denotes that the node is published.
42  *
43  * @deprecated Scheduled for removal in Drupal 9.0.x.
44  *   Use \Drupal\node\NodeInterface::PUBLISHED instead.
45  */
46 const NODE_PUBLISHED = 1;
47
48 /**
49  * Denotes that the node is not promoted to the front page.
50  *
51  * @deprecated Scheduled for removal in Drupal 9.0.x.
52  *   Use \Drupal\node\NodeInterface::NOT_PROMOTED instead.
53  */
54 const NODE_NOT_PROMOTED = 0;
55
56 /**
57  * Denotes that the node is promoted to the front page.
58  *
59  * @deprecated Scheduled for removal in Drupal 9.0.x.
60  *   Use \Drupal\node\NodeInterface::PROMOTED instead.
61  */
62 const NODE_PROMOTED = 1;
63
64 /**
65  * Denotes that the node is not sticky at the top of the page.
66  *
67  * @deprecated Scheduled for removal in Drupal 9.0.x.
68  *   Use \Drupal\node\NodeInterface::NOT_STICKY instead.
69  */
70 const NODE_NOT_STICKY = 0;
71
72 /**
73  * Denotes that the node is sticky at the top of the page.
74  *
75  * @deprecated Scheduled for removal in Drupal 9.0.x.
76  *   Use \Drupal\node\NodeInterface::STICKY instead.
77  */
78 const NODE_STICKY = 1;
79
80 /**
81  * Implements hook_help().
82  */
83 function node_help($route_name, RouteMatchInterface $route_match) {
84   // Remind site administrators about the {node_access} table being flagged
85   // for rebuild. We don't need to issue the message on the confirm form, or
86   // while the rebuild is being processed.
87   if ($route_name != 'node.configure_rebuild_confirm' && $route_name != 'system.batch_page.normal' && $route_name != 'help.page.node' && $route_name != 'help.main'
88     && \Drupal::currentUser()->hasPermission('access administration pages') && node_access_needs_rebuild()) {
89     if ($route_name == 'system.status') {
90       $message = t('The content access permissions need to be rebuilt.');
91     }
92     else {
93       $message = t('The content access permissions need to be rebuilt. <a href=":node_access_rebuild">Rebuild permissions</a>.', [':node_access_rebuild' => \Drupal::url('node.configure_rebuild_confirm')]);
94     }
95     drupal_set_message($message, 'error');
96   }
97
98   switch ($route_name) {
99     case 'help.page.node':
100       $output = '';
101       $output .= '<h3>' . t('About') . '</h3>';
102       $output .= '<p>' . t('The Node module manages the creation, editing, deletion, settings, and display of the main site content. Content items managed by the Node module are typically displayed as pages on your site, and include a title, some meta-data (author, creation time, content type, etc.), and optional fields containing text or other data (fields are managed by the <a href=":field">Field module</a>). For more information, see the <a href=":node">online documentation for the Node module</a>.', [':node' => 'https://www.drupal.org/documentation/modules/node', ':field' => \Drupal::url('help.page', ['name' => 'field'])]) . '</p>';
103       $output .= '<h3>' . t('Uses') . '</h3>';
104       $output .= '<dl>';
105       $output .= '<dt>' . t('Creating content') . '</dt>';
106       $output .= '<dd>' . t('When new content is created, the Node module records basic information about the content, including the author, date of creation, and the <a href=":content-type">Content type</a>. It also manages the <em>publishing options</em>, which define whether or not the content is published, promoted to the front page of the site, and/or sticky at the top of content lists. Default settings can be configured for each <a href=":content-type">type of content</a> on your site.', [':content-type' => \Drupal::url('entity.node_type.collection')]) . '</dd>';
107       $output .= '<dt>' . t('Creating custom content types') . '</dt>';
108       $output .= '<dd>' . t('The Node module gives users with the <em>Administer content types</em> permission the ability to <a href=":content-new">create new content types</a> in addition to the default ones already configured. Creating custom content types gives you the flexibility to add <a href=":field">fields</a> and configure default settings that suit the differing needs of various site content.', [':content-new' => \Drupal::url('node.type_add'), ':field' => \Drupal::url('help.page', ['name' => 'field'])]) . '</dd>';
109       $output .= '<dt>' . t('Administering content') . '</dt>';
110       $output .= '<dd>' . t('The <a href=":content">Content</a> page lists your content, allowing you add new content, filter, edit or delete existing content, or perform bulk operations on existing content.', [':content' => \Drupal::url('system.admin_content')]) . '</dd>';
111       $output .= '<dt>' . t('Creating revisions') . '</dt>';
112       $output .= '<dd>' . t('The Node module also enables you to create multiple versions of any content, and revert to older versions using the <em>Revision information</em> settings.') . '</dd>';
113       $output .= '<dt>' . t('User permissions') . '</dt>';
114       $output .= '<dd>' . t('The Node module makes a number of permissions available for each content type, which can be set by role on the <a href=":permissions">permissions page</a>.', [':permissions' => \Drupal::url('user.admin_permissions', [], ['fragment' => 'module-node'])]) . '</dd>';
115       $output .= '</dl>';
116       return $output;
117
118     case 'node.type_add':
119       return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
120
121     case 'entity.entity_form_display.node.default':
122     case 'entity.entity_form_display.node.form_mode':
123       $type = $route_match->getParameter('node_type');
124       return '<p>' . t('Content items can be edited using different form modes. Here, you can define which fields are shown and hidden when %type content is edited in each form mode, and define how the field form widgets are displayed in each form mode.', ['%type' => $type->label()]) . '</p>' ;
125
126     case 'entity.entity_view_display.node.default':
127     case 'entity.entity_view_display.node.view_mode':
128       $type = $route_match->getParameter('node_type');
129       return '<p>' . t('Content items can be displayed using different view modes: Teaser, Full content, Print, RSS, etc. <em>Teaser</em> is a short format that is typically used in lists of multiple content items. <em>Full content</em> is typically used when the content is displayed on its own page.') . '</p>' .
130         '<p>' . t('Here, you can define which fields are shown and hidden when %type content is displayed in each view mode, and define how the fields are displayed in each view mode.', ['%type' => $type->label()]) . '</p>';
131
132     case 'entity.node.version_history':
133       return '<p>' . t('Revisions allow you to track differences between multiple versions of your content, and revert to older versions.') . '</p>';
134
135     case 'entity.node.edit_form':
136       $node = $route_match->getParameter('node');
137       $type = NodeType::load($node->getType());
138       $help = $type->getHelp();
139       return (!empty($help) ? Xss::filterAdmin($help) : '');
140
141     case 'node.add':
142       $type = $route_match->getParameter('node_type');
143       $help = $type->getHelp();
144       return (!empty($help) ? Xss::filterAdmin($help) : '');
145   }
146 }
147
148 /**
149  * Implements hook_theme().
150  */
151 function node_theme() {
152   return [
153     'node' => [
154       'render element' => 'elements',
155     ],
156     'node_add_list' => [
157       'variables' => ['content' => NULL],
158     ],
159     'node_edit_form' => [
160       'render element' => 'form',
161     ],
162     'field__node__title' => [
163       'base hook' => 'field',
164     ],
165     'field__node__uid' => [
166       'base hook' => 'field',
167     ],
168     'field__node__created' => [
169       'base hook' => 'field',
170     ],
171   ];
172 }
173
174 /**
175  * Implements hook_entity_view_display_alter().
176  */
177 function node_entity_view_display_alter(EntityViewDisplayInterface $display, $context) {
178   if ($context['entity_type'] == 'node') {
179     // Hide field labels in search index.
180     if ($context['view_mode'] == 'search_index') {
181       foreach ($display->getComponents() as $name => $options) {
182         if (isset($options['label'])) {
183           $options['label'] = 'hidden';
184           $display->setComponent($name, $options);
185         }
186       }
187     }
188   }
189 }
190
191 /**
192  * Gathers a listing of links to nodes.
193  *
194  * @param \Drupal\Core\Database\StatementInterface $result
195  *   A database result object from a query to fetch node entities. If your
196  *   query joins the {comment_entity_statistics} table so that the comment_count
197  *   field is available, a title attribute will be added to show the number of
198  *   comments.
199  * @param $title
200  *   (optional) A heading for the resulting list.
201  *
202  * @return array|false
203  *   A renderable array containing a list of linked node titles fetched from
204  *   $result, or FALSE if there are no rows in $result.
205  */
206 function node_title_list(StatementInterface $result, $title = NULL) {
207   $items = [];
208   $num_rows = FALSE;
209   $nids = [];
210   foreach ($result as $row) {
211     // Do not use $node->label() or $node->urlInfo() here, because we only have
212     // database rows, not actual nodes.
213     $nids[] = $row->nid;
214     $options = !empty($row->comment_count) ? ['attributes' => ['title' => \Drupal::translation()->formatPlural($row->comment_count, '1 comment', '@count comments')]] : [];
215     $items[] = \Drupal::l($row->title, new Url('entity.node.canonical', ['node' => $row->nid], $options));
216     $num_rows = TRUE;
217   }
218
219   return $num_rows ? ['#theme' => 'item_list__node', '#items' => $items, '#title' => $title, '#cache' => ['tags' => Cache::mergeTags(['node_list'], Cache::buildTags('node', $nids))]] : FALSE;
220 }
221
222 /**
223  * Determines the type of marker to be displayed for a given node.
224  *
225  * @param int $nid
226  *   Node ID whose history supplies the "last viewed" timestamp.
227  * @param int $timestamp
228  *   Time which is compared against node's "last viewed" timestamp.
229  *
230  * @return int
231  *   One of the MARK constants.
232  */
233 function node_mark($nid, $timestamp) {
234
235   $cache = &drupal_static(__FUNCTION__, []);
236
237   if (\Drupal::currentUser()->isAnonymous() || !\Drupal::moduleHandler()->moduleExists('history')) {
238     return MARK_READ;
239   }
240   if (!isset($cache[$nid])) {
241     $cache[$nid] = history_read($nid);
242   }
243   if ($cache[$nid] == 0 && $timestamp > HISTORY_READ_LIMIT) {
244     return MARK_NEW;
245   }
246   elseif ($timestamp > $cache[$nid] && $timestamp > HISTORY_READ_LIMIT) {
247     return MARK_UPDATED;
248   }
249   return MARK_READ;
250 }
251
252 /**
253  * Returns a list of all the available node types.
254  *
255  * This list can include types that are queued for addition or deletion.
256  *
257  * @return \Drupal\node\NodeTypeInterface[]
258  *   An array of node type entities, keyed by ID.
259  *
260  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
261  *   Use \Drupal\node\Entity\NodeType::loadMultiple().
262  *
263  * @see \Drupal\node\Entity\NodeType::load()
264  */
265 function node_type_get_types() {
266   return NodeType::loadMultiple();
267 }
268
269 /**
270  * Returns a list of available node type names.
271  *
272  * This list can include types that are queued for addition or deletion.
273  *
274  * @return string[]
275  *   An array of node type labels, keyed by the node type name.
276  */
277 function node_type_get_names() {
278   return array_map(function ($bundle_info) {
279     return $bundle_info['label'];
280   }, \Drupal::entityManager()->getBundleInfo('node'));
281 }
282
283 /**
284  * Returns the node type label for the passed node.
285  *
286  * @param \Drupal\node\NodeInterface $node
287  *   A node entity to return the node type's label for.
288  *
289  * @return string|false
290  *   The node type label or FALSE if the node type is not found.
291  *
292  * @todo Add this as generic helper method for config entities representing
293  *   entity bundles.
294  */
295 function node_get_type_label(NodeInterface $node) {
296   $type = NodeType::load($node->bundle());
297   return $type ? $type->label() : FALSE;
298 }
299
300 /**
301  * Description callback: Returns the node type description.
302  *
303  * @param \Drupal\node\NodeTypeInterface $node_type
304  *   The node type object.
305  *
306  * @return string
307  *   The node type description.
308  */
309 function node_type_get_description(NodeTypeInterface $node_type) {
310   return $node_type->getDescription();
311 }
312
313 /**
314  * Menu argument loader: Loads a node type by string.
315  *
316  * @param $name
317  *   The machine name of a node type to load.
318  *
319  * @return \Drupal\node\NodeTypeInterface
320  *   A node type object or NULL if $name does not exist.
321  *
322  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
323  *   Use \Drupal\node\Entity\NodeType::load().
324  */
325 function node_type_load($name) {
326   return NodeType::load($name);
327 }
328
329 /**
330  * Adds the default body field to a node type.
331  *
332  * @param \Drupal\node\NodeTypeInterface $type
333  *   A node type object.
334  * @param string $label
335  *   (optional) The label for the body instance.
336  *
337  * @return \Drupal\field\Entity\FieldConfig
338  *   A Body field object.
339  */
340 function node_add_body_field(NodeTypeInterface $type, $label = 'Body') {
341   // Add or remove the body field, as needed.
342   $field_storage = FieldStorageConfig::loadByName('node', 'body');
343   $field = FieldConfig::loadByName('node', $type->id(), 'body');
344   if (empty($field)) {
345     $field = FieldConfig::create([
346       'field_storage' => $field_storage,
347       'bundle' => $type->id(),
348       'label' => $label,
349       'settings' => ['display_summary' => TRUE],
350     ]);
351     $field->save();
352
353     // Assign widget settings for the 'default' form mode.
354     entity_get_form_display('node', $type->id(), 'default')
355       ->setComponent('body', [
356         'type' => 'text_textarea_with_summary',
357       ])
358       ->save();
359
360     // Assign display settings for the 'default' and 'teaser' view modes.
361     entity_get_display('node', $type->id(), 'default')
362       ->setComponent('body', [
363         'label' => 'hidden',
364         'type' => 'text_default',
365       ])
366       ->save();
367
368     // The teaser view mode is created by the Standard profile and therefore
369     // might not exist.
370     $view_modes = \Drupal::entityManager()->getViewModes('node');
371     if (isset($view_modes['teaser'])) {
372       entity_get_display('node', $type->id(), 'teaser')
373         ->setComponent('body', [
374           'label' => 'hidden',
375           'type' => 'text_summary_or_trimmed',
376         ])
377         ->save();
378     }
379   }
380
381   return $field;
382 }
383
384 /**
385  * Implements hook_entity_extra_field_info().
386  */
387 function node_entity_extra_field_info() {
388   $extra = [];
389   $description = t('Node module element');
390   foreach (NodeType::loadMultiple() as $bundle) {
391     $extra['node'][$bundle->id()]['display']['links'] = [
392       'label' => t('Links'),
393       'description' => $description,
394       'weight' => 100,
395       'visible' => TRUE,
396     ];
397   }
398
399   return $extra;
400 }
401
402 /**
403  * Updates all nodes of one type to be of another type.
404  *
405  * @param string $old_id
406  *   The current node type of the nodes.
407  * @param string $new_id
408  *   The new node type of the nodes.
409  *
410  * @return
411  *   The number of nodes whose node type field was modified.
412  */
413 function node_type_update_nodes($old_id, $new_id) {
414   return \Drupal::entityManager()->getStorage('node')->updateType($old_id, $new_id);
415 }
416
417 /**
418  * Loads node entities from the database.
419  *
420  * This function should be used whenever you need to load more than one node
421  * from the database. Nodes are loaded into memory and will not require database
422  * access if loaded again during the same page request.
423  *
424  * @param array $nids
425  *   (optional) An array of entity IDs. If omitted, all entities are loaded.
426  * @param bool $reset
427  *   (optional) Whether to reset the internal node_load() cache.  Defaults to
428  *   FALSE.
429  *
430  * @return \Drupal\node\NodeInterface[]
431  *   An array of node entities indexed by nid.
432  *
433  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
434  *   Use \Drupal\node\Entity\Node::loadMultiple().
435  *
436  * @see entity_load_multiple()
437  * @see \Drupal\Core\Entity\Query\EntityQueryInterface
438  */
439 function node_load_multiple(array $nids = NULL, $reset = FALSE) {
440   if ($reset) {
441     \Drupal::entityManager()->getStorage('node')->resetCache($nids);
442   }
443   return Node::loadMultiple($nids);
444 }
445
446 /**
447  * Loads a node entity from the database.
448  *
449  * @param int $nid
450  *   The node ID.
451  * @param bool $reset
452  *   (optional) Whether to reset the node_load_multiple() cache. Defaults to
453  *   FALSE.
454  *
455  * @return \Drupal\node\NodeInterface|null
456  *   A fully-populated node entity, or NULL if the node is not found.
457  *
458  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
459  *   Use \Drupal\node\Entity\Node::load().
460  */
461 function node_load($nid = NULL, $reset = FALSE) {
462   if ($reset) {
463     \Drupal::entityManager()->getStorage('node')->resetCache([$nid]);
464   }
465   return Node::load($nid);
466 }
467
468 /**
469  * Loads a node revision from the database.
470  *
471  * @param int $vid
472  *   The node revision id.
473  *
474  * @return \Drupal\node\NodeInterface|null
475  *   A fully-populated node entity, or NULL if the node is not found.
476  */
477 function node_revision_load($vid = NULL) {
478   return \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);
479 }
480
481 /**
482  * Deletes a node revision.
483  *
484  * @param int $revision_id
485  *   The revision ID to delete.
486  */
487 function node_revision_delete($revision_id) {
488   \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id);
489 }
490
491 /**
492  * Checks whether the current page is the full page view of the passed-in node.
493  *
494  * @param \Drupal\node\NodeInterface $node
495  *   A node entity.
496  *
497  * @return int|false
498  *   The ID of the node if this is a full page view, otherwise FALSE.
499  */
500 function node_is_page(NodeInterface $node) {
501   $route_match = \Drupal::routeMatch();
502   if ($route_match->getRouteName() == 'entity.node.canonical') {
503     $page_node = $route_match->getParameter('node');
504   }
505   return (!empty($page_node) ? $page_node->id() == $node->id() : FALSE);
506 }
507
508 /**
509  * Prepares variables for list of available node type templates.
510  *
511  * Default template: node-add-list.html.twig.
512  *
513  * @param array $variables
514  *   An associative array containing:
515  *   - content: An array of content types.
516  *
517  * @see node_add_page()
518  */
519 function template_preprocess_node_add_list(&$variables) {
520   $variables['types'] = [];
521   if (!empty($variables['content'])) {
522     foreach ($variables['content'] as $type) {
523       $variables['types'][$type->id()] = [
524         'type' => $type->id(),
525         'add_link' => \Drupal::l($type->label(), new Url('node.add', ['node_type' => $type->id()])),
526         'description' => [
527           '#markup' => $type->getDescription(),
528         ],
529       ];
530     }
531   }
532 }
533
534 /**
535  * Implements hook_preprocess_HOOK() for HTML document templates.
536  */
537 function node_preprocess_html(&$variables) {
538   // If on an individual node page, add the node type to body classes.
539   if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof NodeInterface) {
540     $variables['node_type'] = $node->getType();
541   }
542 }
543
544 /**
545  * Implements hook_preprocess_HOOK() for block templates.
546  */
547 function node_preprocess_block(&$variables) {
548   if ($variables['configuration']['provider'] == 'node') {
549     switch ($variables['elements']['#plugin_id']) {
550       case 'node_syndicate_block':
551         $variables['attributes']['role'] = 'complementary';
552         break;
553     }
554   }
555 }
556
557 /**
558  * Implements hook_theme_suggestions_HOOK().
559  */
560 function node_theme_suggestions_node(array $variables) {
561   $suggestions = [];
562   $node = $variables['elements']['#node'];
563   $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
564
565   $suggestions[] = 'node__' . $sanitized_view_mode;
566   $suggestions[] = 'node__' . $node->bundle();
567   $suggestions[] = 'node__' . $node->bundle() . '__' . $sanitized_view_mode;
568   $suggestions[] = 'node__' . $node->id();
569   $suggestions[] = 'node__' . $node->id() . '__' . $sanitized_view_mode;
570
571   return $suggestions;
572 }
573
574 /**
575  * Prepares variables for node templates.
576  *
577  * Default template: node.html.twig.
578  *
579  * Most themes use their own copy of node.html.twig. The default is located
580  * inside "/core/modules/node/templates/node.html.twig". Look in there for the
581  * full list of variables.
582  *
583  * @param array $variables
584  *   An associative array containing:
585  *   - elements: An array of elements to display in view mode.
586  *   - node: The node object.
587  *   - view_mode: View mode; e.g., 'full', 'teaser', etc.
588  */
589 function template_preprocess_node(&$variables) {
590   $variables['view_mode'] = $variables['elements']['#view_mode'];
591   // Provide a distinct $teaser boolean.
592   $variables['teaser'] = $variables['view_mode'] == 'teaser';
593   $variables['node'] = $variables['elements']['#node'];
594   /** @var \Drupal\node\NodeInterface $node */
595   $node = $variables['node'];
596   $variables['date'] = drupal_render($variables['elements']['created']);
597   unset($variables['elements']['created']);
598   $variables['author_name'] = drupal_render($variables['elements']['uid']);
599   unset($variables['elements']['uid']);
600
601   $variables['url'] = $node->url('canonical', [
602     'language' => $node->language(),
603   ]);
604   $variables['label'] = $variables['elements']['title'];
605   unset($variables['elements']['title']);
606   // The 'page' variable is set to TRUE in two occasions:
607   //   - The view mode is 'full' and we are on the 'node.view' route.
608   //   - The node is in preview and view mode is either 'full' or 'default'.
609   $variables['page'] = ($variables['view_mode'] == 'full' && (node_is_page($node)) || (isset($node->in_preview) && in_array($node->preview_view_mode, ['full', 'default'])));
610
611   // Helpful $content variable for templates.
612   $variables += ['content' => []];
613   foreach (Element::children($variables['elements']) as $key) {
614     $variables['content'][$key] = $variables['elements'][$key];
615   }
616
617   // Display post information only on certain node types.
618   $node_type = $node->type->entity;
619   // Used by RDF to add attributes around the author and date submitted.
620   $variables['author_attributes'] = new Attribute();
621   $variables['display_submitted'] = $node_type->displaySubmitted();
622   if ($variables['display_submitted']) {
623     if (theme_get_setting('features.node_user_picture')) {
624       // To change user picture settings (e.g. image style), edit the 'compact'
625       // view mode on the User entity. Note that the 'compact' view mode might
626       // not be configured, so remember to always check the theme setting first.
627       $variables['author_picture'] = user_view($node->getOwner(), 'compact');
628     }
629   }
630
631   // Add article ARIA role.
632   $variables['attributes']['role'] = 'article';
633 }
634
635 /**
636  * Implements hook_cron().
637  */
638 function node_cron() {
639   // Calculate the oldest and newest node created times, for use in search
640   // rankings. (Note that field aliases have to be variables passed by
641   // reference.)
642   if (\Drupal::moduleHandler()->moduleExists('search')) {
643     $min_alias = 'min_created';
644     $max_alias = 'max_created';
645     $result = \Drupal::entityQueryAggregate('node')
646       ->aggregate('created', 'MIN', NULL, $min_alias)
647       ->aggregate('created', 'MAX', NULL, $max_alias)
648       ->execute();
649     if (isset($result[0])) {
650       // Make an array with definite keys and store it in the state system.
651       $array = [
652         'min_created' => $result[0][$min_alias],
653         'max_created' => $result[0][$max_alias],
654       ];
655       \Drupal::state()->set('node.min_max_update_time', $array);
656     }
657   }
658 }
659
660 /**
661  * Implements hook_ranking().
662  */
663 function node_ranking() {
664   // Create the ranking array and add the basic ranking options.
665   $ranking = [
666     'relevance' => [
667       'title' => t('Keyword relevance'),
668       // Average relevance values hover around 0.15
669       'score' => 'i.relevance',
670     ],
671     'sticky' => [
672       'title' => t('Content is sticky at top of lists'),
673       // The sticky flag is either 0 or 1, which is automatically normalized.
674       'score' => 'n.sticky',
675     ],
676     'promote' => [
677       'title' => t('Content is promoted to the front page'),
678       // The promote flag is either 0 or 1, which is automatically normalized.
679       'score' => 'n.promote',
680     ],
681   ];
682   // Add relevance based on updated date, but only if it the scale values have
683   // been calculated in node_cron().
684   if ($node_min_max = \Drupal::state()->get('node.min_max_update_time')) {
685     $ranking['recent'] = [
686       'title' => t('Recently created'),
687       // Exponential decay with half life of 14% of the age range of nodes.
688       'score' => 'EXP(-5 * (1 - (n.created - :node_oldest) / :node_range))',
689       'arguments' => [
690         ':node_oldest' => $node_min_max['min_created'],
691         ':node_range' => max($node_min_max['max_created'] - $node_min_max['min_created'], 1),
692       ],
693     ];
694   }
695   return $ranking;
696 }
697
698 /**
699  * Implements hook_user_cancel().
700  */
701 function node_user_cancel($edit, $account, $method) {
702   switch ($method) {
703     case 'user_cancel_block_unpublish':
704       // Unpublish nodes (current revisions).
705       $nids = \Drupal::entityQuery('node')
706         ->condition('uid', $account->id())
707         ->execute();
708       module_load_include('inc', 'node', 'node.admin');
709       node_mass_update($nids, ['status' => 0], NULL, TRUE);
710       break;
711
712     case 'user_cancel_reassign':
713       // Anonymize all of the nodes for this old account.
714       module_load_include('inc', 'node', 'node.admin');
715       $vids = \Drupal::entityManager()->getStorage('node')->userRevisionIds($account);
716       node_mass_update($vids, [
717         'uid' => 0,
718         'revision_uid' => 0,
719       ], NULL, TRUE, TRUE);
720       break;
721   }
722 }
723
724 /**
725  * Implements hook_ENTITY_TYPE_predelete() for user entities.
726  */
727 function node_user_predelete($account) {
728   // Delete nodes (current revisions).
729   // @todo Introduce node_mass_delete() or make node_mass_update() more flexible.
730   $nids = \Drupal::entityQuery('node')
731     ->condition('uid', $account->id())
732     ->accessCheck(FALSE)
733     ->execute();
734   entity_delete_multiple('node', $nids);
735   // Delete old revisions.
736   $storage_controller = \Drupal::entityManager()->getStorage('node');
737   $revisions = $storage_controller->userRevisionIds($account);
738   foreach ($revisions as $revision) {
739     node_revision_delete($revision);
740   }
741 }
742
743 /**
744  * Finds the most recently changed nodes that are available to the current user.
745  *
746  * @param $number
747  *   (optional) The maximum number of nodes to find. Defaults to 10.
748  *
749  * @return \Drupal\node\NodeInterface[]
750  *   An array of node entities or an empty array if there are no recent nodes
751  *   visible to the current user.
752  */
753 function node_get_recent($number = 10) {
754   $account = \Drupal::currentUser();
755   $query = \Drupal::entityQuery('node');
756
757   if (!$account->hasPermission('bypass node access')) {
758     // If the user is able to view their own unpublished nodes, allow them
759     // to see these in addition to published nodes. Check that they actually
760     // have some unpublished nodes to view before adding the condition.
761     $access_query = \Drupal::entityQuery('node')
762       ->condition('uid', $account->id())
763       ->condition('status', NodeInterface::NOT_PUBLISHED);
764     if ($account->hasPermission('view own unpublished content') && ($own_unpublished = $access_query->execute())) {
765       $query->orConditionGroup()
766         ->condition('status', NodeInterface::PUBLISHED)
767         ->condition('nid', $own_unpublished, 'IN');
768     }
769     else {
770       // If not, restrict the query to published nodes.
771       $query->condition('status', NodeInterface::PUBLISHED);
772     }
773   }
774   $nids = $query
775     ->sort('changed', 'DESC')
776     ->range(0, $number)
777     ->addTag('node_access')
778     ->execute();
779
780   $nodes = Node::loadMultiple($nids);
781
782   return $nodes ? $nodes : [];
783 }
784
785 /**
786  * Generates an array for rendering the given node.
787  *
788  * @param \Drupal\node\NodeInterface $node
789  *   A node entity.
790  * @param $view_mode
791  *   (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'full.'
792  * @param $langcode
793  *   (optional) A language code to use for rendering. Defaults to NULL which is
794  *   the global content language of the current request.
795  *
796  * @return array
797  *   An array as expected by drupal_render().
798  */
799 function node_view(NodeInterface $node, $view_mode = 'full', $langcode = NULL) {
800   return entity_view($node, $view_mode, $langcode);
801 }
802
803 /**
804  * Constructs a drupal_render() style array from an array of loaded nodes.
805  *
806  * @param $nodes
807  *   An array of nodes as returned by Node::loadMultiple().
808  * @param $view_mode
809  *   (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
810  * @param $langcode
811  *   (optional) A language code to use for rendering. Defaults to the global
812  *   content language of the current request.
813  *
814  * @return array
815  *   An array in the format expected by drupal_render().
816  */
817 function node_view_multiple($nodes, $view_mode = 'teaser', $langcode = NULL) {
818   return entity_view_multiple($nodes, $view_mode, $langcode);
819 }
820
821 /**
822  * Implements hook_page_top().
823  */
824 function node_page_top(array &$page) {
825   // Add 'Back to content editing' link on preview page.
826   $route_match = \Drupal::routeMatch();
827   if ($route_match->getRouteName() == 'entity.node.preview') {
828     $page['page_top']['node_preview'] = [
829       '#type' => 'container',
830       '#attributes' => [
831         'class' => ['node-preview-container', 'container-inline']
832       ],
833     ];
834
835     $form = \Drupal::formBuilder()->getForm('\Drupal\node\Form\NodePreviewForm', $route_match->getParameter('node_preview'));
836     $page['page_top']['node_preview']['view_mode'] = $form;
837   }
838 }
839
840 /**
841  * Implements hook_form_FORM_ID_alter().
842  *
843  * Alters the theme form to use the admin theme on node editing.
844  *
845  * @see node_form_system_themes_admin_form_submit()
846  */
847 function node_form_system_themes_admin_form_alter(&$form, FormStateInterface $form_state, $form_id) {
848   $form['admin_theme']['use_admin_theme'] = [
849     '#type' => 'checkbox',
850     '#title' => t('Use the administration theme when editing or creating content'),
851     '#description' => t('Control which roles can "View the administration theme" on the <a href=":permissions">Permissions page</a>.', [':permissions' => Url::fromRoute('user.admin_permissions')->toString()]),
852     '#default_value' => \Drupal::configFactory()->getEditable('node.settings')->get('use_admin_theme'),
853   ];
854   $form['#submit'][] = 'node_form_system_themes_admin_form_submit';
855 }
856
857 /**
858  * Form submission handler for system_themes_admin_form().
859  *
860  * @see node_form_system_themes_admin_form_alter()
861  */
862 function node_form_system_themes_admin_form_submit($form, FormStateInterface $form_state) {
863   \Drupal::configFactory()->getEditable('node.settings')
864     ->set('use_admin_theme', $form_state->getValue('use_admin_theme'))
865     ->save();
866   \Drupal::service('router.builder')->setRebuildNeeded();
867 }
868
869 /**
870  * @defgroup node_access Node access rights
871  * @{
872  * The node access system determines who can do what to which nodes.
873  *
874  * In determining access rights for a node, \Drupal\node\NodeAccessControlHandler
875  * first checks whether the user has the "bypass node access" permission. Such
876  * users have unrestricted access to all nodes. user 1 will always pass this
877  * check.
878  *
879  * Next, all implementations of hook_node_access() will be called. Each
880  * implementation may explicitly allow, explicitly forbid, or ignore the access
881  * request. If at least one module says to forbid the request, it will be
882  * rejected. If no modules deny the request and at least one says to allow it,
883  * the request will be permitted.
884  *
885  * If all modules ignore the access request, then the node_access table is used
886  * to determine access. All node access modules are queried using
887  * hook_node_grants() to assemble a list of "grant IDs" for the user. This list
888  * is compared against the table. If any row contains the node ID in question
889  * (or 0, which stands for "all nodes"), one of the grant IDs returned, and a
890  * value of TRUE for the operation in question, then access is granted. Note
891  * that this table is a list of grants; any matching row is sufficient to grant
892  * access to the node.
893  *
894  * In node listings (lists of nodes generated from a select query, such as the
895  * default home page at path 'node', an RSS feed, a recent content block, etc.),
896  * the process above is followed except that hook_node_access() is not called on
897  * each node for performance reasons and for proper functioning of the pager
898  * system. When adding a node listing to your module, be sure to use an entity
899  * query, which will add a tag of "node_access". This will allow modules dealing
900  * with node access to ensure only nodes to which the user has access are
901  * retrieved, through the use of hook_query_TAG_alter(). See the
902  * @link entity_api Entity API topic @endlink for more information on entity
903  * queries. Tagging a query with "node_access" does not check the
904  * published/unpublished status of nodes, so the base query is responsible
905  * for ensuring that unpublished nodes are not displayed to inappropriate users.
906  *
907  * Note: Even a single module returning an AccessResultInterface object from
908  * hook_node_access() whose isForbidden() method equals TRUE will block access
909  * to the node. Therefore, implementers should take care to not deny access
910  * unless they really intend to. Unless a module wishes to actively forbid
911  * access it should return an AccessResultInterface object whose isAllowed() nor
912  * isForbidden() methods return TRUE, to allow other modules or the node_access
913  * table to control access.
914  *
915  * To see how to write a node access module of your own, see
916  * node_access_example.module.
917  */
918
919 /**
920  * Implements hook_node_access().
921  */
922 function node_node_access(NodeInterface $node, $op, $account) {
923   $type = $node->bundle();
924
925   switch ($op) {
926     case 'create':
927       return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
928
929     case 'update':
930       if ($account->hasPermission('edit any ' . $type . ' content', $account)) {
931         return AccessResult::allowed()->cachePerPermissions();
932       }
933       else {
934         return AccessResult::allowedIf($account->hasPermission('edit own ' . $type . ' content', $account) && ($account->id() == $node->getOwnerId()))->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
935       }
936
937     case 'delete':
938       if ($account->hasPermission('delete any ' . $type . ' content', $account)) {
939         return AccessResult::allowed()->cachePerPermissions();
940       }
941       else {
942         return AccessResult::allowedIf($account->hasPermission('delete own ' . $type . ' content', $account) && ($account->id() == $node->getOwnerId()))->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
943       }
944
945     default:
946       // No opinion.
947       return AccessResult::neutral();
948   }
949 }
950
951 /**
952  * Fetches an array of permission IDs granted to the given user ID.
953  *
954  * The implementation here provides only the universal "all" grant. A node
955  * access module should implement hook_node_grants() to provide a grant list for
956  * the user.
957  *
958  * After the default grants have been loaded, we allow modules to alter the
959  * grants array by reference. This hook allows for complex business logic to be
960  * applied when integrating multiple node access modules.
961  *
962  * @param string $op
963  *   The operation that the user is trying to perform.
964  * @param \Drupal\Core\Session\AccountInterface $account
965  *   The account object for the user performing the operation.
966  *
967  * @return array
968  *   An associative array in which the keys are realms, and the values are
969  *   arrays of grants for those realms.
970  */
971 function node_access_grants($op, AccountInterface $account) {
972   // Fetch node access grants from other modules.
973   $grants = \Drupal::moduleHandler()->invokeAll('node_grants', [$account, $op]);
974   // Allow modules to alter the assigned grants.
975   \Drupal::moduleHandler()->alter('node_grants', $grants, $account, $op);
976
977   return array_merge(['all' => [0]], $grants);
978 }
979
980 /**
981  * Determines whether the user has a global viewing grant for all nodes.
982  *
983  * Checks to see whether any module grants global 'view' access to a user
984  * account; global 'view' access is encoded in the {node_access} table as a
985  * grant with nid=0. If no node access modules are enabled, node.module defines
986  * such a global 'view' access grant.
987  *
988  * This function is called when a node listing query is tagged with
989  * 'node_access'; when this function returns TRUE, no node access joins are
990  * added to the query.
991  *
992  * @param $account
993  *   (optional) The user object for the user whose access is being checked. If
994  *   omitted, the current user is used. Defaults to NULL.
995  *
996  * @return
997  *   TRUE if 'view' access to all nodes is granted, FALSE otherwise.
998  *
999  * @see hook_node_grants()
1000  * @see node_query_node_access_alter()
1001  */
1002 function node_access_view_all_nodes($account = NULL) {
1003
1004   if (!$account) {
1005     $account = \Drupal::currentUser();
1006   }
1007
1008   // Statically cache results in an array keyed by $account->id().
1009   $access = &drupal_static(__FUNCTION__);
1010   if (isset($access[$account->id()])) {
1011     return $access[$account->id()];
1012   }
1013
1014   // If no modules implement the node access system, access is always TRUE.
1015   if (!\Drupal::moduleHandler()->getImplementations('node_grants')) {
1016     $access[$account->id()] = TRUE;
1017   }
1018   else {
1019     $access[$account->id()] = \Drupal::entityManager()->getAccessControlHandler('node')->checkAllGrants($account);
1020   }
1021
1022   return $access[$account->id()];
1023 }
1024
1025
1026 /**
1027  * Implements hook_query_TAG_alter().
1028  *
1029  * This is the hook_query_alter() for queries tagged with 'node_access'. It adds
1030  * node access checks for the user account given by the 'account' meta-data (or
1031  * current user if not provided), for an operation given by the 'op' meta-data
1032  * (or 'view' if not provided; other possible values are 'update' and 'delete').
1033  *
1034  * Queries tagged with 'node_access' that are not against the {node} table
1035  * must add the base table as metadata. For example:
1036  * @code
1037  *   $query
1038  *     ->addTag('node_access')
1039  *     ->addMetaData('base_table', 'taxonomy_index');
1040  * @endcode
1041  */
1042 function node_query_node_access_alter(AlterableInterface $query) {
1043   // Read meta-data from query, if provided.
1044   if (!$account = $query->getMetaData('account')) {
1045     $account = \Drupal::currentUser();
1046   }
1047   if (!$op = $query->getMetaData('op')) {
1048     $op = 'view';
1049   }
1050
1051   // If $account can bypass node access, or there are no node access modules,
1052   // or the operation is 'view' and the $account has a global view grant
1053   // (such as a view grant for node ID 0), we don't need to alter the query.
1054   if ($account->hasPermission('bypass node access')) {
1055     return;
1056   }
1057   if (!count(\Drupal::moduleHandler()->getImplementations('node_grants'))) {
1058     return;
1059   }
1060   if ($op == 'view' && node_access_view_all_nodes($account)) {
1061     return;
1062   }
1063
1064   $tables = $query->getTables();
1065   $base_table = $query->getMetaData('base_table');
1066   // If the base table is not given, default to one of the node base tables.
1067   if (!$base_table) {
1068     /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
1069     $table_mapping = \Drupal::entityTypeManager()->getStorage('node')->getTableMapping();
1070     $node_base_tables = $table_mapping->getTableNames();
1071
1072     foreach ($tables as $table_info) {
1073       if (!($table_info instanceof SelectInterface)) {
1074         $table = $table_info['table'];
1075         // Ensure that 'node' and 'node_field_data' are always preferred over
1076         // 'node_revision' and 'node_field_revision'.
1077         if ($table == 'node' || $table == 'node_field_data') {
1078           $base_table = $table;
1079           break;
1080         }
1081         // If one of the node base tables are in the query, add it to the list
1082         // of possible base tables to join against.
1083         if (in_array($table, $node_base_tables)) {
1084           $base_table = $table;
1085         }
1086       }
1087     }
1088
1089     // Bail out if the base table is missing.
1090     if (!$base_table) {
1091       throw new Exception(t('Query tagged for node access but there is no node table, specify the base_table using meta data.'));
1092     }
1093   }
1094
1095   // Update the query for the given storage method.
1096   \Drupal::service('node.grant_storage')->alterQuery($query, $tables, $op, $account, $base_table);
1097
1098   // Bubble the 'user.node_grants:$op' cache context to the current render
1099   // context.
1100   $request = \Drupal::requestStack()->getCurrentRequest();
1101   $renderer = \Drupal::service('renderer');
1102   if ($request->isMethodSafe() && $renderer->hasRenderContext()) {
1103     $build = ['#cache' => ['contexts' => ['user.node_grants:' . $op]]];
1104     $renderer->render($build);
1105   }
1106 }
1107
1108 /**
1109  * Toggles or reads the value of a flag for rebuilding the node access grants.
1110  *
1111  * When the flag is set, a message is displayed to users with 'access
1112  * administration pages' permission, pointing to the 'rebuild' confirm form.
1113  * This can be used as an alternative to direct node_access_rebuild calls,
1114  * allowing administrators to decide when they want to perform the actual
1115  * (possibly time consuming) rebuild.
1116  *
1117  * When unsure if the current user is an administrator, node_access_rebuild()
1118  * should be used instead.
1119  *
1120  * @param $rebuild
1121  *   (optional) The boolean value to be written.
1122  *
1123  * @return bool|null
1124  *   The current value of the flag if no value was provided for $rebuild. If a
1125  *   value was provided for $rebuild, nothing (NULL) is returned.
1126  *
1127  * @see node_access_rebuild()
1128  */
1129 function node_access_needs_rebuild($rebuild = NULL) {
1130   if (!isset($rebuild)) {
1131     return \Drupal::state()->get('node.node_access_needs_rebuild') ?: FALSE;
1132   }
1133   elseif ($rebuild) {
1134     \Drupal::state()->set('node.node_access_needs_rebuild', TRUE);
1135   }
1136   else {
1137     \Drupal::state()->delete('node.node_access_needs_rebuild');
1138   }
1139 }
1140
1141 /**
1142  * Rebuilds the node access database.
1143  *
1144  * This rebuild is occasionally needed by modules that make system-wide changes
1145  * to access levels. When the rebuild is required by an admin-triggered action
1146  * (e.g module settings form), calling node_access_needs_rebuild(TRUE) instead
1147  * of node_access_rebuild() lets the user perform his changes and actually
1148  * rebuild only once he is done.
1149  *
1150  * Note : As of Drupal 6, node access modules are not required to (and actually
1151  * should not) call node_access_rebuild() in hook_install/uninstall anymore.
1152  *
1153  * @param $batch_mode
1154  *   (optional) Set to TRUE to process in 'batch' mode, spawning processing over
1155  *   several HTTP requests (thus avoiding the risk of PHP timeout if the site
1156  *   has a large number of nodes). hook_update_N() and any form submit handler
1157  *   are safe contexts to use the 'batch mode'. Less decidable cases (such as
1158  *   calls from hook_user(), hook_taxonomy(), etc.) might consider using the
1159  *   non-batch mode. Defaults to FALSE.
1160  *
1161  * @see node_access_needs_rebuild()
1162  */
1163 function node_access_rebuild($batch_mode = FALSE) {
1164   $node_storage = \Drupal::entityManager()->getStorage('node');
1165   /** @var \Drupal\node\NodeAccessControlHandlerInterface $access_control_handler */
1166   $access_control_handler = \Drupal::entityManager()->getAccessControlHandler('node');
1167   $access_control_handler->deleteGrants();
1168   // Only recalculate if the site is using a node_access module.
1169   if (count(\Drupal::moduleHandler()->getImplementations('node_grants'))) {
1170     if ($batch_mode) {
1171       $batch = [
1172         'title' => t('Rebuilding content access permissions'),
1173         'operations' => [
1174           ['_node_access_rebuild_batch_operation', []],
1175         ],
1176         'finished' => '_node_access_rebuild_batch_finished'
1177       ];
1178       batch_set($batch);
1179     }
1180     else {
1181       // Try to allocate enough time to rebuild node grants
1182       drupal_set_time_limit(240);
1183
1184       // Rebuild newest nodes first so that recent content becomes available
1185       // quickly.
1186       $entity_query = \Drupal::entityQuery('node');
1187       $entity_query->sort('nid', 'DESC');
1188       // Disable access checking since all nodes must be processed even if the
1189       // user does not have access. And unless the current user has the bypass
1190       // node access permission, no nodes are accessible since the grants have
1191       // just been deleted.
1192       $entity_query->accessCheck(FALSE);
1193       $nids = $entity_query->execute();
1194       foreach ($nids as $nid) {
1195         $node_storage->resetCache([$nid]);
1196         $node = Node::load($nid);
1197         // To preserve database integrity, only write grants if the node
1198         // loads successfully.
1199         if (!empty($node)) {
1200           $grants = $access_control_handler->acquireGrants($node);
1201           \Drupal::service('node.grant_storage')->write($node, $grants);
1202         }
1203       }
1204     }
1205   }
1206   else {
1207     // Not using any node_access modules. Add the default grant.
1208     $access_control_handler->writeDefaultGrant();
1209   }
1210
1211   if (!isset($batch)) {
1212     drupal_set_message(t('Content permissions have been rebuilt.'));
1213     node_access_needs_rebuild(FALSE);
1214   }
1215 }
1216
1217 /**
1218  * Implements callback_batch_operation().
1219  *
1220  * Performs batch operation for node_access_rebuild().
1221  *
1222  * This is a multistep operation: we go through all nodes by packs of 20. The
1223  * batch processing engine interrupts processing and sends progress feedback
1224  * after 1 second execution time.
1225  *
1226  * @param array $context
1227  *   An array of contextual key/value information for rebuild batch process.
1228  */
1229 function _node_access_rebuild_batch_operation(&$context) {
1230   $node_storage = \Drupal::entityManager()->getStorage('node');
1231   if (empty($context['sandbox'])) {
1232     // Initiate multistep processing.
1233     $context['sandbox']['progress'] = 0;
1234     $context['sandbox']['current_node'] = 0;
1235     $context['sandbox']['max'] = \Drupal::entityQuery('node')->accessCheck(FALSE)->count()->execute();
1236   }
1237
1238   // Process the next 20 nodes.
1239   $limit = 20;
1240   $nids = \Drupal::entityQuery('node')
1241     ->condition('nid', $context['sandbox']['current_node'], '>')
1242     ->sort('nid', 'ASC')
1243     // Disable access checking since all nodes must be processed even if the
1244     // user does not have access. And unless the current user has the bypass
1245     // node access permission, no nodes are accessible since the grants have
1246     // just been deleted.
1247     ->accessCheck(FALSE)
1248     ->range(0, $limit)
1249     ->execute();
1250   $node_storage->resetCache($nids);
1251   $nodes = Node::loadMultiple($nids);
1252   foreach ($nodes as $nid => $node) {
1253     // To preserve database integrity, only write grants if the node
1254     // loads successfully.
1255     if (!empty($node)) {
1256       /** @var \Drupal\node\NodeAccessControlHandlerInterface $access_control_handler */
1257       $access_control_handler = \Drupal::entityManager()->getAccessControlHandler('node');
1258       $grants = $access_control_handler->acquireGrants($node);
1259       \Drupal::service('node.grant_storage')->write($node, $grants);
1260     }
1261     $context['sandbox']['progress']++;
1262     $context['sandbox']['current_node'] = $nid;
1263   }
1264
1265   // Multistep processing : report progress.
1266   if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
1267     $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
1268   }
1269 }
1270
1271 /**
1272  * Implements callback_batch_finished().
1273  *
1274  * Performs post-processing for node_access_rebuild().
1275  *
1276  * @param bool $success
1277  *   A boolean indicating whether the re-build process has completed.
1278  * @param array $results
1279  *   An array of results information.
1280  * @param array $operations
1281  *   An array of function calls (not used in this function).
1282  */
1283 function _node_access_rebuild_batch_finished($success, $results, $operations) {
1284   if ($success) {
1285     drupal_set_message(t('The content access permissions have been rebuilt.'));
1286     node_access_needs_rebuild(FALSE);
1287   }
1288   else {
1289     drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
1290   }
1291 }
1292
1293 /**
1294  * @} End of "defgroup node_access".
1295  */
1296
1297 /**
1298  * Implements hook_modules_installed().
1299  */
1300 function node_modules_installed($modules) {
1301   // Check if any of the newly enabled modules require the node_access table to
1302   // be rebuilt.
1303   if (!node_access_needs_rebuild() && array_intersect($modules, \Drupal::moduleHandler()->getImplementations('node_grants'))) {
1304     node_access_needs_rebuild(TRUE);
1305   }
1306 }
1307
1308 /**
1309  * Implements hook_modules_uninstalled().
1310  */
1311 function node_modules_uninstalled($modules) {
1312   // Check whether any of the disabled modules implemented hook_node_grants(),
1313   // in which case the node access table needs to be rebuilt.
1314   foreach ($modules as $module) {
1315     // At this point, the module is already disabled, but its code is still
1316     // loaded in memory. Module functions must no longer be called. We only
1317     // check whether a hook implementation function exists and do not invoke it.
1318     // Node access also needs to be rebuilt if language module is disabled to
1319     // remove any language-specific grants.
1320     if (!node_access_needs_rebuild() && (\Drupal::moduleHandler()->implementsHook($module, 'node_grants') || $module == 'language')) {
1321       node_access_needs_rebuild(TRUE);
1322     }
1323   }
1324
1325   // If there remains no more node_access module, rebuilding will be
1326   // straightforward, we can do it right now.
1327   if (node_access_needs_rebuild() && count(\Drupal::moduleHandler()->getImplementations('node_grants')) == 0) {
1328     node_access_rebuild();
1329   }
1330 }
1331
1332 /**
1333  * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'.
1334  */
1335 function node_configurable_language_delete(ConfigurableLanguageInterface $language) {
1336   // On nodes with this language, unset the language.
1337   \Drupal::entityManager()->getStorage('node')->clearRevisionsLanguage($language);
1338 }
1339
1340 /**
1341  * Marks a node to be re-indexed by the node_search plugin.
1342  *
1343  * @param int $nid
1344  *   The node ID.
1345  */
1346 function node_reindex_node_search($nid) {
1347   if (\Drupal::moduleHandler()->moduleExists('search')) {
1348     // Reindex node context indexed by the node module search plugin.
1349     search_mark_for_reindex('node_search', $nid);
1350   }
1351 }
1352
1353 /**
1354  * Implements hook_ENTITY_TYPE_insert() for comment entities.
1355  */
1356 function node_comment_insert($comment) {
1357   // Reindex the node when comments are added.
1358   if ($comment->getCommentedEntityTypeId() == 'node') {
1359     node_reindex_node_search($comment->getCommentedEntityId());
1360   }
1361 }
1362
1363 /**
1364  * Implements hook_ENTITY_TYPE_update() for comment entities.
1365  */
1366 function node_comment_update($comment) {
1367   // Reindex the node when comments are changed.
1368   if ($comment->getCommentedEntityTypeId() == 'node') {
1369     node_reindex_node_search($comment->getCommentedEntityId());
1370   }
1371 }
1372
1373 /**
1374  * Implements hook_ENTITY_TYPE_delete() for comment entities.
1375  */
1376 function node_comment_delete($comment) {
1377   // Reindex the node when comments are deleted.
1378   if ($comment->getCommentedEntityTypeId() == 'node') {
1379     node_reindex_node_search($comment->getCommentedEntityId());
1380   }
1381 }
1382
1383 /**
1384  * Implements hook_config_translation_info_alter().
1385  */
1386 function node_config_translation_info_alter(&$info) {
1387   $info['node_type']['class'] = 'Drupal\node\ConfigTranslation\NodeTypeMapper';
1388 }