5 * The core module that allows content to be submitted to the site.
7 * Modules and scripts may programmatically submit nodes using the usual form
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;
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;
33 * Denotes that the node is not published.
35 * @deprecated Scheduled for removal in Drupal 9.0.x.
36 * Use \Drupal\node\NodeInterface::NOT_PUBLISHED instead.
38 const NODE_NOT_PUBLISHED = 0;
41 * Denotes that the node is published.
43 * @deprecated Scheduled for removal in Drupal 9.0.x.
44 * Use \Drupal\node\NodeInterface::PUBLISHED instead.
46 const NODE_PUBLISHED = 1;
49 * Denotes that the node is not promoted to the front page.
51 * @deprecated Scheduled for removal in Drupal 9.0.x.
52 * Use \Drupal\node\NodeInterface::NOT_PROMOTED instead.
54 const NODE_NOT_PROMOTED = 0;
57 * Denotes that the node is promoted to the front page.
59 * @deprecated Scheduled for removal in Drupal 9.0.x.
60 * Use \Drupal\node\NodeInterface::PROMOTED instead.
62 const NODE_PROMOTED = 1;
65 * Denotes that the node is not sticky at the top of the page.
67 * @deprecated Scheduled for removal in Drupal 9.0.x.
68 * Use \Drupal\node\NodeInterface::NOT_STICKY instead.
70 const NODE_NOT_STICKY = 0;
73 * Denotes that the node is sticky at the top of the page.
75 * @deprecated Scheduled for removal in Drupal 9.0.x.
76 * Use \Drupal\node\NodeInterface::STICKY instead.
78 const NODE_STICKY = 1;
81 * Implements hook_help().
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.');
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')]);
95 drupal_set_message($message, 'error');
98 switch ($route_name) {
99 case 'help.page.node':
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>';
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>';
118 case 'node.type_add':
119 return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
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>' ;
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>';
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>';
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) : '');
142 $type = $route_match->getParameter('node_type');
143 $help = $type->getHelp();
144 return (!empty($help) ? Xss::filterAdmin($help) : '');
149 * Implements hook_theme().
151 function node_theme() {
154 'render element' => 'elements',
157 'variables' => ['content' => NULL],
159 'node_edit_form' => [
160 'render element' => 'form',
162 'field__node__title' => [
163 'base hook' => 'field',
165 'field__node__uid' => [
166 'base hook' => 'field',
168 'field__node__created' => [
169 'base hook' => 'field',
175 * Implements hook_entity_view_display_alter().
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);
192 * Gathers a listing of links to nodes.
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
200 * (optional) A heading for the resulting list.
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.
206 function node_title_list(StatementInterface $result, $title = NULL) {
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.
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));
219 return $num_rows ? ['#theme' => 'item_list__node', '#items' => $items, '#title' => $title, '#cache' => ['tags' => Cache::mergeTags(['node_list'], Cache::buildTags('node', $nids))]] : FALSE;
223 * Determines the type of marker to be displayed for a given node.
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.
231 * One of the MARK constants.
233 function node_mark($nid, $timestamp) {
235 $cache = &drupal_static(__FUNCTION__, []);
237 if (\Drupal::currentUser()->isAnonymous() || !\Drupal::moduleHandler()->moduleExists('history')) {
240 if (!isset($cache[$nid])) {
241 $cache[$nid] = history_read($nid);
243 if ($cache[$nid] == 0 && $timestamp > HISTORY_READ_LIMIT) {
246 elseif ($timestamp > $cache[$nid] && $timestamp > HISTORY_READ_LIMIT) {
253 * Returns a list of all the available node types.
255 * This list can include types that are queued for addition or deletion.
257 * @return \Drupal\node\NodeTypeInterface[]
258 * An array of node type entities, keyed by ID.
260 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
261 * Use \Drupal\node\Entity\NodeType::loadMultiple().
263 * @see \Drupal\node\Entity\NodeType::load()
265 function node_type_get_types() {
266 return NodeType::loadMultiple();
270 * Returns a list of available node type names.
272 * This list can include types that are queued for addition or deletion.
275 * An array of node type labels, keyed by the node type name.
277 function node_type_get_names() {
278 return array_map(function ($bundle_info) {
279 return $bundle_info['label'];
280 }, \Drupal::entityManager()->getBundleInfo('node'));
284 * Returns the node type label for the passed node.
286 * @param \Drupal\node\NodeInterface $node
287 * A node entity to return the node type's label for.
289 * @return string|false
290 * The node type label or FALSE if the node type is not found.
292 * @todo Add this as generic helper method for config entities representing
295 function node_get_type_label(NodeInterface $node) {
296 $type = NodeType::load($node->bundle());
297 return $type ? $type->label() : FALSE;
301 * Description callback: Returns the node type description.
303 * @param \Drupal\node\NodeTypeInterface $node_type
304 * The node type object.
307 * The node type description.
309 function node_type_get_description(NodeTypeInterface $node_type) {
310 return $node_type->getDescription();
314 * Menu argument loader: Loads a node type by string.
317 * The machine name of a node type to load.
319 * @return \Drupal\node\NodeTypeInterface
320 * A node type object or NULL if $name does not exist.
322 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
323 * Use \Drupal\node\Entity\NodeType::load().
325 function node_type_load($name) {
326 return NodeType::load($name);
330 * Adds the default body field to a node type.
332 * @param \Drupal\node\NodeTypeInterface $type
333 * A node type object.
334 * @param string $label
335 * (optional) The label for the body instance.
337 * @return \Drupal\field\Entity\FieldConfig
338 * A Body field object.
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');
345 $field = FieldConfig::create([
346 'field_storage' => $field_storage,
347 'bundle' => $type->id(),
349 'settings' => ['display_summary' => TRUE],
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',
360 // Assign display settings for the 'default' and 'teaser' view modes.
361 entity_get_display('node', $type->id(), 'default')
362 ->setComponent('body', [
364 'type' => 'text_default',
368 // The teaser view mode is created by the Standard profile and therefore
370 $view_modes = \Drupal::entityManager()->getViewModes('node');
371 if (isset($view_modes['teaser'])) {
372 entity_get_display('node', $type->id(), 'teaser')
373 ->setComponent('body', [
375 'type' => 'text_summary_or_trimmed',
385 * Implements hook_entity_extra_field_info().
387 function node_entity_extra_field_info() {
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,
403 * Updates all nodes of one type to be of another type.
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.
411 * The number of nodes whose node type field was modified.
413 function node_type_update_nodes($old_id, $new_id) {
414 return \Drupal::entityManager()->getStorage('node')->updateType($old_id, $new_id);
418 * Loads node entities from the database.
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.
425 * (optional) An array of entity IDs. If omitted, all entities are loaded.
427 * (optional) Whether to reset the internal node_load() cache. Defaults to
430 * @return \Drupal\node\NodeInterface[]
431 * An array of node entities indexed by nid.
433 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
434 * Use \Drupal\node\Entity\Node::loadMultiple().
436 * @see entity_load_multiple()
437 * @see \Drupal\Core\Entity\Query\EntityQueryInterface
439 function node_load_multiple(array $nids = NULL, $reset = FALSE) {
441 \Drupal::entityManager()->getStorage('node')->resetCache($nids);
443 return Node::loadMultiple($nids);
447 * Loads a node entity from the database.
452 * (optional) Whether to reset the node_load_multiple() cache. Defaults to
455 * @return \Drupal\node\NodeInterface|null
456 * A fully-populated node entity, or NULL if the node is not found.
458 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
459 * Use \Drupal\node\Entity\Node::load().
461 function node_load($nid = NULL, $reset = FALSE) {
463 \Drupal::entityManager()->getStorage('node')->resetCache([$nid]);
465 return Node::load($nid);
469 * Loads a node revision from the database.
472 * The node revision id.
474 * @return \Drupal\node\NodeInterface|null
475 * A fully-populated node entity, or NULL if the node is not found.
477 function node_revision_load($vid = NULL) {
478 return \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);
482 * Deletes a node revision.
484 * @param int $revision_id
485 * The revision ID to delete.
487 function node_revision_delete($revision_id) {
488 \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id);
492 * Checks whether the current page is the full page view of the passed-in node.
494 * @param \Drupal\node\NodeInterface $node
498 * The ID of the node if this is a full page view, otherwise FALSE.
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');
505 return (!empty($page_node) ? $page_node->id() == $node->id() : FALSE);
509 * Prepares variables for list of available node type templates.
511 * Default template: node-add-list.html.twig.
513 * @param array $variables
514 * An associative array containing:
515 * - content: An array of content types.
517 * @see node_add_page()
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()])),
527 '#markup' => $type->getDescription(),
535 * Implements hook_preprocess_HOOK() for HTML document templates.
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();
545 * Implements hook_preprocess_HOOK() for block templates.
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';
558 * Implements hook_theme_suggestions_HOOK().
560 function node_theme_suggestions_node(array $variables) {
562 $node = $variables['elements']['#node'];
563 $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
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;
575 * Prepares variables for node templates.
577 * Default template: node.html.twig.
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.
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.
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']);
601 $variables['url'] = $node->url('canonical', [
602 'language' => $node->language(),
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'])));
611 // Helpful $content variable for templates.
612 $variables += ['content' => []];
613 foreach (Element::children($variables['elements']) as $key) {
614 $variables['content'][$key] = $variables['elements'][$key];
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');
631 // Add article ARIA role.
632 $variables['attributes']['role'] = 'article';
636 * Implements hook_cron().
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
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)
649 if (isset($result[0])) {
650 // Make an array with definite keys and store it in the state system.
652 'min_created' => $result[0][$min_alias],
653 'max_created' => $result[0][$max_alias],
655 \Drupal::state()->set('node.min_max_update_time', $array);
661 * Implements hook_ranking().
663 function node_ranking() {
664 // Create the ranking array and add the basic ranking options.
667 'title' => t('Keyword relevance'),
668 // Average relevance values hover around 0.15
669 'score' => 'i.relevance',
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',
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',
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))',
690 ':node_oldest' => $node_min_max['min_created'],
691 ':node_range' => max($node_min_max['max_created'] - $node_min_max['min_created'], 1),
699 * Implements hook_user_cancel().
701 function node_user_cancel($edit, $account, $method) {
703 case 'user_cancel_block_unpublish':
704 // Unpublish nodes (current revisions).
705 $nids = \Drupal::entityQuery('node')
706 ->condition('uid', $account->id())
708 module_load_include('inc', 'node', 'node.admin');
709 node_mass_update($nids, ['status' => 0], NULL, TRUE);
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, [
719 ], NULL, TRUE, TRUE);
725 * Implements hook_ENTITY_TYPE_predelete() for user entities.
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())
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);
744 * Finds the most recently changed nodes that are available to the current user.
747 * (optional) The maximum number of nodes to find. Defaults to 10.
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.
753 function node_get_recent($number = 10) {
754 $account = \Drupal::currentUser();
755 $query = \Drupal::entityQuery('node');
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');
770 // If not, restrict the query to published nodes.
771 $query->condition('status', NodeInterface::PUBLISHED);
775 ->sort('changed', 'DESC')
777 ->addTag('node_access')
780 $nodes = Node::loadMultiple($nids);
782 return $nodes ? $nodes : [];
786 * Generates an array for rendering the given node.
788 * @param \Drupal\node\NodeInterface $node
791 * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'full.'
793 * (optional) A language code to use for rendering. Defaults to NULL which is
794 * the global content language of the current request.
797 * An array as expected by drupal_render().
799 function node_view(NodeInterface $node, $view_mode = 'full', $langcode = NULL) {
800 return entity_view($node, $view_mode, $langcode);
804 * Constructs a drupal_render() style array from an array of loaded nodes.
807 * An array of nodes as returned by Node::loadMultiple().
809 * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
811 * (optional) A language code to use for rendering. Defaults to the global
812 * content language of the current request.
815 * An array in the format expected by drupal_render().
817 function node_view_multiple($nodes, $view_mode = 'teaser', $langcode = NULL) {
818 return entity_view_multiple($nodes, $view_mode, $langcode);
822 * Implements hook_page_top().
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',
831 'class' => ['node-preview-container', 'container-inline']
835 $form = \Drupal::formBuilder()->getForm('\Drupal\node\Form\NodePreviewForm', $route_match->getParameter('node_preview'));
836 $page['page_top']['node_preview']['view_mode'] = $form;
841 * Implements hook_form_FORM_ID_alter().
843 * Alters the theme form to use the admin theme on node editing.
845 * @see node_form_system_themes_admin_form_submit()
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'),
854 $form['#submit'][] = 'node_form_system_themes_admin_form_submit';
858 * Form submission handler for system_themes_admin_form().
860 * @see node_form_system_themes_admin_form_alter()
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'))
866 \Drupal::service('router.builder')->setRebuildNeeded();
870 * @defgroup node_access Node access rights
872 * The node access system determines who can do what to which nodes.
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
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.
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.
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.
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.
915 * To see how to write a node access module of your own, see
916 * node_access_example.module.
920 * Implements hook_node_access().
922 function node_node_access(NodeInterface $node, $op, $account) {
923 $type = $node->bundle();
927 return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
930 if ($account->hasPermission('edit any ' . $type . ' content', $account)) {
931 return AccessResult::allowed()->cachePerPermissions();
934 return AccessResult::allowedIf($account->hasPermission('edit own ' . $type . ' content', $account) && ($account->id() == $node->getOwnerId()))->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
938 if ($account->hasPermission('delete any ' . $type . ' content', $account)) {
939 return AccessResult::allowed()->cachePerPermissions();
942 return AccessResult::allowedIf($account->hasPermission('delete own ' . $type . ' content', $account) && ($account->id() == $node->getOwnerId()))->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
947 return AccessResult::neutral();
952 * Fetches an array of permission IDs granted to the given user ID.
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
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.
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.
968 * An associative array in which the keys are realms, and the values are
969 * arrays of grants for those realms.
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);
977 return array_merge(['all' => [0]], $grants);
981 * Determines whether the user has a global viewing grant for all nodes.
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.
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.
993 * (optional) The user object for the user whose access is being checked. If
994 * omitted, the current user is used. Defaults to NULL.
997 * TRUE if 'view' access to all nodes is granted, FALSE otherwise.
999 * @see hook_node_grants()
1000 * @see node_query_node_access_alter()
1002 function node_access_view_all_nodes($account = NULL) {
1005 $account = \Drupal::currentUser();
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()];
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;
1019 $access[$account->id()] = \Drupal::entityManager()->getAccessControlHandler('node')->checkAllGrants($account);
1022 return $access[$account->id()];
1027 * Implements hook_query_TAG_alter().
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').
1034 * Queries tagged with 'node_access' that are not against the {node} table
1035 * must add the base table as metadata. For example:
1038 * ->addTag('node_access')
1039 * ->addMetaData('base_table', 'taxonomy_index');
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();
1047 if (!$op = $query->getMetaData('op')) {
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')) {
1057 if (!count(\Drupal::moduleHandler()->getImplementations('node_grants'))) {
1060 if ($op == 'view' && node_access_view_all_nodes($account)) {
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.
1068 /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
1069 $table_mapping = \Drupal::entityTypeManager()->getStorage('node')->getTableMapping();
1070 $node_base_tables = $table_mapping->getTableNames();
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;
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;
1089 // Bail out if the base table is missing.
1091 throw new Exception(t('Query tagged for node access but there is no node table, specify the base_table using meta data.'));
1095 // Update the query for the given storage method.
1096 \Drupal::service('node.grant_storage')->alterQuery($query, $tables, $op, $account, $base_table);
1098 // Bubble the 'user.node_grants:$op' cache context to the current render
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);
1109 * Toggles or reads the value of a flag for rebuilding the node access grants.
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.
1117 * When unsure if the current user is an administrator, node_access_rebuild()
1118 * should be used instead.
1121 * (optional) The boolean value to be written.
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.
1127 * @see node_access_rebuild()
1129 function node_access_needs_rebuild($rebuild = NULL) {
1130 if (!isset($rebuild)) {
1131 return \Drupal::state()->get('node.node_access_needs_rebuild') ?: FALSE;
1134 \Drupal::state()->set('node.node_access_needs_rebuild', TRUE);
1137 \Drupal::state()->delete('node.node_access_needs_rebuild');
1142 * Rebuilds the node access database.
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.
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.
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.
1161 * @see node_access_needs_rebuild()
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'))) {
1172 'title' => t('Rebuilding content access permissions'),
1174 ['_node_access_rebuild_batch_operation', []],
1176 'finished' => '_node_access_rebuild_batch_finished'
1181 // Try to allocate enough time to rebuild node grants
1182 drupal_set_time_limit(240);
1184 // Rebuild newest nodes first so that recent content becomes available
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);
1207 // Not using any node_access modules. Add the default grant.
1208 $access_control_handler->writeDefaultGrant();
1211 if (!isset($batch)) {
1212 drupal_set_message(t('Content permissions have been rebuilt.'));
1213 node_access_needs_rebuild(FALSE);
1218 * Implements callback_batch_operation().
1220 * Performs batch operation for node_access_rebuild().
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.
1226 * @param array $context
1227 * An array of contextual key/value information for rebuild batch process.
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();
1238 // Process the next 20 nodes.
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)
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);
1261 $context['sandbox']['progress']++;
1262 $context['sandbox']['current_node'] = $nid;
1265 // Multistep processing : report progress.
1266 if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
1267 $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
1272 * Implements callback_batch_finished().
1274 * Performs post-processing for node_access_rebuild().
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).
1283 function _node_access_rebuild_batch_finished($success, $results, $operations) {
1285 drupal_set_message(t('The content access permissions have been rebuilt.'));
1286 node_access_needs_rebuild(FALSE);
1289 drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
1294 * @} End of "defgroup node_access".
1298 * Implements hook_modules_installed().
1300 function node_modules_installed($modules) {
1301 // Check if any of the newly enabled modules require the node_access table to
1303 if (!node_access_needs_rebuild() && array_intersect($modules, \Drupal::moduleHandler()->getImplementations('node_grants'))) {
1304 node_access_needs_rebuild(TRUE);
1309 * Implements hook_modules_uninstalled().
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);
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();
1333 * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'.
1335 function node_configurable_language_delete(ConfigurableLanguageInterface $language) {
1336 // On nodes with this language, unset the language.
1337 \Drupal::entityManager()->getStorage('node')->clearRevisionsLanguage($language);
1341 * Marks a node to be re-indexed by the node_search plugin.
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);
1354 * Implements hook_ENTITY_TYPE_insert() for comment entities.
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());
1364 * Implements hook_ENTITY_TYPE_update() for comment entities.
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());
1374 * Implements hook_ENTITY_TYPE_delete() for comment entities.
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());
1384 * Implements hook_config_translation_info_alter().
1386 function node_config_translation_info_alter(&$info) {
1387 $info['node_type']['class'] = 'Drupal\node\ConfigTranslation\NodeTypeMapper';