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