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 * @see https://www.drupal.org/node/2316145
40 const NODE_NOT_PUBLISHED = 0;
43 * Denotes that the node is published.
45 * @deprecated Scheduled for removal in Drupal 9.0.x.
46 * Use \Drupal\node\NodeInterface::PUBLISHED instead.
48 * @see https://www.drupal.org/node/2316145
50 const NODE_PUBLISHED = 1;
53 * Denotes that the node is not promoted to the front page.
55 * @deprecated Scheduled for removal in Drupal 9.0.x.
56 * Use \Drupal\node\NodeInterface::NOT_PROMOTED instead.
58 * @see https://www.drupal.org/node/2316145
60 const NODE_NOT_PROMOTED = 0;
63 * Denotes that the node is promoted to the front page.
65 * @deprecated Scheduled for removal in Drupal 9.0.x.
66 * Use \Drupal\node\NodeInterface::PROMOTED instead.
68 * @see https://www.drupal.org/node/2316145
70 const NODE_PROMOTED = 1;
73 * Denotes that the node is not sticky at the top of the page.
75 * @deprecated Scheduled for removal in Drupal 9.0.x.
76 * Use \Drupal\node\NodeInterface::NOT_STICKY instead.
78 * @see https://www.drupal.org/node/2316145
80 const NODE_NOT_STICKY = 0;
83 * Denotes that the node is sticky at the top of the page.
85 * @deprecated Scheduled for removal in Drupal 9.0.x.
86 * Use \Drupal\node\NodeInterface::STICKY instead.
88 * @see https://www.drupal.org/node/2316145
90 const NODE_STICKY = 1;
93 * Implements hook_help().
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.');
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')]);
107 drupal_set_message($message, 'error');
110 switch ($route_name) {
111 case 'help.page.node':
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>';
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>';
130 case 'node.type_add':
131 return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
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>';
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>';
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>';
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) : '');
154 $type = $route_match->getParameter('node_type');
155 $help = $type->getHelp();
156 return (!empty($help) ? Xss::filterAdmin($help) : '');
161 * Implements hook_theme().
163 function node_theme() {
166 'render element' => 'elements',
169 'variables' => ['content' => NULL],
171 'node_edit_form' => [
172 'render element' => 'form',
174 'field__node__title' => [
175 'base hook' => 'field',
177 'field__node__uid' => [
178 'base hook' => 'field',
180 'field__node__created' => [
181 'base hook' => 'field',
187 * Implements hook_entity_view_display_alter().
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);
204 * Gathers a listing of links to nodes.
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
212 * (optional) A heading for the resulting list.
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.
218 function node_title_list(StatementInterface $result, $title = NULL) {
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.
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));
231 return $num_rows ? ['#theme' => 'item_list__node', '#items' => $items, '#title' => $title, '#cache' => ['tags' => Cache::mergeTags(['node_list'], Cache::buildTags('node', $nids))]] : FALSE;
235 * Determines the type of marker to be displayed for a given node.
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.
243 * One of the MARK constants.
245 function node_mark($nid, $timestamp) {
247 $cache = &drupal_static(__FUNCTION__, []);
249 if (\Drupal::currentUser()->isAnonymous() || !\Drupal::moduleHandler()->moduleExists('history')) {
252 if (!isset($cache[$nid])) {
253 $cache[$nid] = history_read($nid);
255 if ($cache[$nid] == 0 && $timestamp > HISTORY_READ_LIMIT) {
258 elseif ($timestamp > $cache[$nid] && $timestamp > HISTORY_READ_LIMIT) {
265 * Returns a list of all the available node types.
267 * This list can include types that are queued for addition or deletion.
269 * @return \Drupal\node\NodeTypeInterface[]
270 * An array of node type entities, keyed by ID.
272 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
273 * Use \Drupal\node\Entity\NodeType::loadMultiple().
275 * @see \Drupal\node\Entity\NodeType::load()
277 function node_type_get_types() {
278 return NodeType::loadMultiple();
282 * Returns a list of available node type names.
284 * This list can include types that are queued for addition or deletion.
287 * An array of node type labels, keyed by the node type name.
289 function node_type_get_names() {
290 return array_map(function ($bundle_info) {
291 return $bundle_info['label'];
292 }, \Drupal::entityManager()->getBundleInfo('node'));
296 * Returns the node type label for the passed node.
298 * @param \Drupal\node\NodeInterface $node
299 * A node entity to return the node type's label for.
301 * @return string|false
302 * The node type label or FALSE if the node type is not found.
304 * @todo Add this as generic helper method for config entities representing
307 function node_get_type_label(NodeInterface $node) {
308 $type = NodeType::load($node->bundle());
309 return $type ? $type->label() : FALSE;
313 * Description callback: Returns the node type description.
315 * @param \Drupal\node\NodeTypeInterface $node_type
316 * The node type object.
319 * The node type description.
321 function node_type_get_description(NodeTypeInterface $node_type) {
322 return $node_type->getDescription();
326 * Menu argument loader: Loads a node type by string.
329 * The machine name of a node type to load.
331 * @return \Drupal\node\NodeTypeInterface
332 * A node type object or NULL if $name does not exist.
334 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
335 * Use \Drupal\node\Entity\NodeType::load().
337 function node_type_load($name) {
338 return NodeType::load($name);
342 * Adds the default body field to a node type.
344 * @param \Drupal\node\NodeTypeInterface $type
345 * A node type object.
346 * @param string $label
347 * (optional) The label for the body instance.
349 * @return \Drupal\field\Entity\FieldConfig
350 * A Body field object.
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');
357 $field = FieldConfig::create([
358 'field_storage' => $field_storage,
359 'bundle' => $type->id(),
361 'settings' => ['display_summary' => TRUE],
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',
372 // Assign display settings for the 'default' and 'teaser' view modes.
373 entity_get_display('node', $type->id(), 'default')
374 ->setComponent('body', [
376 'type' => 'text_default',
380 // The teaser view mode is created by the Standard profile and therefore
382 $view_modes = \Drupal::entityManager()->getViewModes('node');
383 if (isset($view_modes['teaser'])) {
384 entity_get_display('node', $type->id(), 'teaser')
385 ->setComponent('body', [
387 'type' => 'text_summary_or_trimmed',
397 * Implements hook_entity_extra_field_info().
399 function node_entity_extra_field_info() {
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,
415 * Updates all nodes of one type to be of another type.
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.
423 * The number of nodes whose node type field was modified.
425 function node_type_update_nodes($old_id, $new_id) {
426 return \Drupal::entityManager()->getStorage('node')->updateType($old_id, $new_id);
430 * Loads node entities from the database.
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.
437 * (optional) An array of entity IDs. If omitted, all entities are loaded.
439 * (optional) Whether to reset the internal node_load() cache. Defaults to
442 * @return \Drupal\node\NodeInterface[]
443 * An array of node entities indexed by nid.
445 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
446 * Use \Drupal\node\Entity\Node::loadMultiple().
448 * @see entity_load_multiple()
449 * @see \Drupal\Core\Entity\Query\EntityQueryInterface
451 function node_load_multiple(array $nids = NULL, $reset = FALSE) {
453 \Drupal::entityManager()->getStorage('node')->resetCache($nids);
455 return Node::loadMultiple($nids);
459 * Loads a node entity from the database.
464 * (optional) Whether to reset the node_load_multiple() cache. Defaults to
467 * @return \Drupal\node\NodeInterface|null
468 * A fully-populated node entity, or NULL if the node is not found.
470 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
471 * Use \Drupal\node\Entity\Node::load().
473 function node_load($nid = NULL, $reset = FALSE) {
475 \Drupal::entityManager()->getStorage('node')->resetCache([$nid]);
477 return Node::load($nid);
481 * Loads a node revision from the database.
484 * The node revision id.
486 * @return \Drupal\node\NodeInterface|null
487 * A fully-populated node entity, or NULL if the node is not found.
489 function node_revision_load($vid = NULL) {
490 return \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);
494 * Deletes a node revision.
496 * @param int $revision_id
497 * The revision ID to delete.
499 function node_revision_delete($revision_id) {
500 \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id);
504 * Checks whether the current page is the full page view of the passed-in node.
506 * @param \Drupal\node\NodeInterface $node
510 * The ID of the node if this is a full page view, otherwise FALSE.
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');
517 return (!empty($page_node) ? $page_node->id() == $node->id() : FALSE);
521 * Prepares variables for list of available node type templates.
523 * Default template: node-add-list.html.twig.
525 * @param array $variables
526 * An associative array containing:
527 * - content: An array of content types.
529 * @see node_add_page()
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()])),
539 '#markup' => $type->getDescription(),
547 * Implements hook_preprocess_HOOK() for HTML document templates.
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();
557 * Implements hook_preprocess_HOOK() for block templates.
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';
570 * Implements hook_theme_suggestions_HOOK().
572 function node_theme_suggestions_node(array $variables) {
574 $node = $variables['elements']['#node'];
575 $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
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;
587 * Prepares variables for node templates.
589 * Default template: node.html.twig.
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.
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.
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']);
613 $variables['url'] = $node->url('canonical', [
614 'language' => $node->language(),
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'])));
623 // Helpful $content variable for templates.
624 $variables += ['content' => []];
625 foreach (Element::children($variables['elements']) as $key) {
626 $variables['content'][$key] = $variables['elements'][$key];
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');
643 // Add article ARIA role.
644 $variables['attributes']['role'] = 'article';
648 * Implements hook_cron().
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
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)
661 if (isset($result[0])) {
662 // Make an array with definite keys and store it in the state system.
664 'min_created' => $result[0][$min_alias],
665 'max_created' => $result[0][$max_alias],
667 \Drupal::state()->set('node.min_max_update_time', $array);
673 * Implements hook_ranking().
675 function node_ranking() {
676 // Create the ranking array and add the basic ranking options.
679 'title' => t('Keyword relevance'),
680 // Average relevance values hover around 0.15
681 'score' => 'i.relevance',
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',
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',
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))',
702 ':node_oldest' => $node_min_max['min_created'],
703 ':node_range' => max($node_min_max['max_created'] - $node_min_max['min_created'], 1),
711 * Implements hook_user_cancel().
713 function node_user_cancel($edit, $account, $method) {
715 case 'user_cancel_block_unpublish':
716 // Unpublish nodes (current revisions).
717 $nids = \Drupal::entityQuery('node')
718 ->condition('uid', $account->id())
720 module_load_include('inc', 'node', 'node.admin');
721 node_mass_update($nids, ['status' => 0], NULL, TRUE);
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, [
731 ], NULL, TRUE, TRUE);
737 * Implements hook_ENTITY_TYPE_predelete() for user entities.
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())
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);
756 * Finds the most recently changed nodes that are available to the current user.
759 * (optional) The maximum number of nodes to find. Defaults to 10.
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.
765 function node_get_recent($number = 10) {
766 $account = \Drupal::currentUser();
767 $query = \Drupal::entityQuery('node');
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');
782 // If not, restrict the query to published nodes.
783 $query->condition('status', NodeInterface::PUBLISHED);
787 ->sort('changed', 'DESC')
789 ->addTag('node_access')
792 $nodes = Node::loadMultiple($nids);
794 return $nodes ? $nodes : [];
798 * Generates an array for rendering the given node.
800 * @param \Drupal\node\NodeInterface $node
803 * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'full.'
805 * (optional) A language code to use for rendering. Defaults to NULL which is
806 * the global content language of the current request.
809 * An array as expected by drupal_render().
811 function node_view(NodeInterface $node, $view_mode = 'full', $langcode = NULL) {
812 return entity_view($node, $view_mode, $langcode);
816 * Constructs a drupal_render() style array from an array of loaded nodes.
819 * An array of nodes as returned by Node::loadMultiple().
821 * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
823 * (optional) A language code to use for rendering. Defaults to the global
824 * content language of the current request.
827 * An array in the format expected by drupal_render().
829 function node_view_multiple($nodes, $view_mode = 'teaser', $langcode = NULL) {
830 return entity_view_multiple($nodes, $view_mode, $langcode);
834 * Implements hook_page_top().
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',
843 'class' => ['node-preview-container', 'container-inline']
847 $form = \Drupal::formBuilder()->getForm('\Drupal\node\Form\NodePreviewForm', $route_match->getParameter('node_preview'));
848 $page['page_top']['node_preview']['view_mode'] = $form;
853 * Implements hook_form_FORM_ID_alter().
855 * Alters the theme form to use the admin theme on node editing.
857 * @see node_form_system_themes_admin_form_submit()
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'),
866 $form['#submit'][] = 'node_form_system_themes_admin_form_submit';
870 * Form submission handler for system_themes_admin_form().
872 * @see node_form_system_themes_admin_form_alter()
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'))
878 \Drupal::service('router.builder')->setRebuildNeeded();
882 * @defgroup node_access Node access rights
884 * The node access system determines who can do what to which nodes.
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
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.
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.
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.
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.
927 * To see how to write a node access module of your own, see
928 * node_access_example.module.
932 * Implements hook_node_access().
934 function node_node_access(NodeInterface $node, $op, $account) {
935 $type = $node->bundle();
939 return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
942 if ($account->hasPermission('edit any ' . $type . ' content', $account)) {
943 return AccessResult::allowed()->cachePerPermissions();
946 return AccessResult::allowedIf($account->hasPermission('edit own ' . $type . ' content', $account) && ($account->id() == $node->getOwnerId()))->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
950 if ($account->hasPermission('delete any ' . $type . ' content', $account)) {
951 return AccessResult::allowed()->cachePerPermissions();
954 return AccessResult::allowedIf($account->hasPermission('delete own ' . $type . ' content', $account) && ($account->id() == $node->getOwnerId()))->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
959 return AccessResult::neutral();
964 * Fetches an array of permission IDs granted to the given user ID.
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
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.
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.
980 * An associative array in which the keys are realms, and the values are
981 * arrays of grants for those realms.
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);
989 return array_merge(['all' => [0]], $grants);
993 * Determines whether the user has a global viewing grant for all nodes.
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.
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.
1005 * (optional) The user object for the user whose access is being checked. If
1006 * omitted, the current user is used. Defaults to NULL.
1009 * TRUE if 'view' access to all nodes is granted, FALSE otherwise.
1011 * @see hook_node_grants()
1012 * @see node_query_node_access_alter()
1014 function node_access_view_all_nodes($account = NULL) {
1017 $account = \Drupal::currentUser();
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()];
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;
1031 $access[$account->id()] = \Drupal::entityManager()->getAccessControlHandler('node')->checkAllGrants($account);
1034 return $access[$account->id()];
1039 * Implements hook_query_TAG_alter().
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').
1046 * Queries tagged with 'node_access' that are not against the {node} table
1047 * must add the base table as metadata. For example:
1050 * ->addTag('node_access')
1051 * ->addMetaData('base_table', 'taxonomy_index');
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();
1059 if (!$op = $query->getMetaData('op')) {
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')) {
1069 if (!count(\Drupal::moduleHandler()->getImplementations('node_grants'))) {
1072 if ($op == 'view' && node_access_view_all_nodes($account)) {
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.
1080 /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
1081 $table_mapping = \Drupal::entityTypeManager()->getStorage('node')->getTableMapping();
1082 $node_base_tables = $table_mapping->getTableNames();
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;
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;
1101 // Bail out if the base table is missing.
1103 throw new Exception(t('Query tagged for node access but there is no node table, specify the base_table using meta data.'));
1107 // Update the query for the given storage method.
1108 \Drupal::service('node.grant_storage')->alterQuery($query, $tables, $op, $account, $base_table);
1110 // Bubble the 'user.node_grants:$op' cache context to the current render
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);
1121 * Toggles or reads the value of a flag for rebuilding the node access grants.
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.
1129 * When unsure if the current user is an administrator, node_access_rebuild()
1130 * should be used instead.
1133 * (optional) The boolean value to be written.
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.
1139 * @see node_access_rebuild()
1141 function node_access_needs_rebuild($rebuild = NULL) {
1142 if (!isset($rebuild)) {
1143 return \Drupal::state()->get('node.node_access_needs_rebuild') ?: FALSE;
1146 \Drupal::state()->set('node.node_access_needs_rebuild', TRUE);
1149 \Drupal::state()->delete('node.node_access_needs_rebuild');
1154 * Rebuilds the node access database.
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.
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.
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.
1173 * @see node_access_needs_rebuild()
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'))) {
1184 'title' => t('Rebuilding content access permissions'),
1186 ['_node_access_rebuild_batch_operation', []],
1188 'finished' => '_node_access_rebuild_batch_finished'
1193 // Try to allocate enough time to rebuild node grants
1194 drupal_set_time_limit(240);
1196 // Rebuild newest nodes first so that recent content becomes available
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);
1219 // Not using any node_access modules. Add the default grant.
1220 $access_control_handler->writeDefaultGrant();
1223 if (!isset($batch)) {
1224 drupal_set_message(t('Content permissions have been rebuilt.'));
1225 node_access_needs_rebuild(FALSE);
1230 * Implements callback_batch_operation().
1232 * Performs batch operation for node_access_rebuild().
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.
1238 * @param array $context
1239 * An array of contextual key/value information for rebuild batch process.
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();
1250 // Process the next 20 nodes.
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)
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);
1273 $context['sandbox']['progress']++;
1274 $context['sandbox']['current_node'] = $nid;
1277 // Multistep processing : report progress.
1278 if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
1279 $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
1284 * Implements callback_batch_finished().
1286 * Performs post-processing for node_access_rebuild().
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).
1295 function _node_access_rebuild_batch_finished($success, $results, $operations) {
1297 drupal_set_message(t('The content access permissions have been rebuilt.'));
1298 node_access_needs_rebuild(FALSE);
1301 drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
1306 * @} End of "defgroup node_access".
1310 * Implements hook_modules_installed().
1312 function node_modules_installed($modules) {
1313 // Check if any of the newly enabled modules require the node_access table to
1315 if (!node_access_needs_rebuild() && array_intersect($modules, \Drupal::moduleHandler()->getImplementations('node_grants'))) {
1316 node_access_needs_rebuild(TRUE);
1321 * Implements hook_modules_uninstalled().
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);
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();
1345 * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'.
1347 function node_configurable_language_delete(ConfigurableLanguageInterface $language) {
1348 // On nodes with this language, unset the language.
1349 \Drupal::entityManager()->getStorage('node')->clearRevisionsLanguage($language);
1353 * Marks a node to be re-indexed by the node_search plugin.
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);
1366 * Implements hook_ENTITY_TYPE_insert() for comment entities.
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());
1376 * Implements hook_ENTITY_TYPE_update() for comment entities.
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());
1386 * Implements hook_ENTITY_TYPE_delete() for comment entities.
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());
1396 * Implements hook_config_translation_info_alter().
1398 function node_config_translation_info_alter(&$info) {
1399 $info['node_type']['class'] = 'Drupal\node\ConfigTranslation\NodeTypeMapper';