Chris@0: hasPermission('access administration pages') && node_access_needs_rebuild()) { Chris@0: if ($route_name == 'system.status') { Chris@0: $message = t('The content access permissions need to be rebuilt.'); Chris@0: } Chris@0: else { Chris@18: $message = t('The content access permissions need to be rebuilt. Rebuild permissions.', [':node_access_rebuild' => Url::fromRoute('node.configure_rebuild_confirm')->toString()]); Chris@0: } Chris@17: \Drupal::messenger()->addError($message); Chris@0: } Chris@0: Chris@0: switch ($route_name) { Chris@0: case 'help.page.node': Chris@0: $output = ''; Chris@0: $output .= '

' . t('About') . '

'; Chris@18: $output .= '

' . 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 Field module). For more information, see the online documentation for the Node module.', [':node' => 'https://www.drupal.org/documentation/modules/node', ':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString()]) . '

'; Chris@0: $output .= '

' . t('Uses') . '

'; Chris@0: $output .= '
'; Chris@0: $output .= '
' . t('Creating content') . '
'; Chris@18: $output .= '
' . t('When new content is created, the Node module records basic information about the content, including the author, date of creation, and the Content type. It also manages the publishing options, 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 type of content on your site.', [':content-type' => Url::fromRoute('entity.node_type.collection')->toString()]) . '
'; Chris@0: $output .= '
' . t('Creating custom content types') . '
'; Chris@18: $output .= '
' . t('The Node module gives users with the Administer content types permission the ability to create new content types in addition to the default ones already configured. Creating custom content types gives you the flexibility to add fields and configure default settings that suit the differing needs of various site content.', [':content-new' => Url::fromRoute('node.type_add')->toString(), ':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString()]) . '
'; Chris@0: $output .= '
' . t('Administering content') . '
'; Chris@18: $output .= '
' . t('The Content page lists your content, allowing you add new content, filter, edit or delete existing content, or perform bulk operations on existing content.', [':content' => Url::fromRoute('system.admin_content')->toString()]) . '
'; Chris@0: $output .= '
' . t('Creating revisions') . '
'; Chris@0: $output .= '
' . t('The Node module also enables you to create multiple versions of any content, and revert to older versions using the Revision information settings.') . '
'; Chris@0: $output .= '
' . t('User permissions') . '
'; Chris@18: $output .= '
' . t('The Node module makes a number of permissions available for each content type, which can be set by role on the permissions page.', [':permissions' => Url::fromRoute('user.admin_permissions', [], ['fragment' => 'module-node'])->toString()]) . '
'; Chris@0: $output .= '
'; Chris@0: return $output; Chris@0: Chris@0: case 'node.type_add': Chris@0: return '

' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '

'; Chris@0: Chris@0: case 'entity.entity_form_display.node.default': Chris@0: case 'entity.entity_form_display.node.form_mode': Chris@0: $type = $route_match->getParameter('node_type'); Chris@12: return '

' . 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()]) . '

'; Chris@0: Chris@0: case 'entity.entity_view_display.node.default': Chris@0: case 'entity.entity_view_display.node.view_mode': Chris@0: $type = $route_match->getParameter('node_type'); Chris@0: return '

' . t('Content items can be displayed using different view modes: Teaser, Full content, Print, RSS, etc. Teaser is a short format that is typically used in lists of multiple content items. Full content is typically used when the content is displayed on its own page.') . '

' . Chris@0: '

' . 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()]) . '

'; Chris@0: Chris@0: case 'entity.node.version_history': Chris@0: return '

' . t('Revisions allow you to track differences between multiple versions of your content, and revert to older versions.') . '

'; Chris@0: Chris@0: case 'entity.node.edit_form': Chris@0: $node = $route_match->getParameter('node'); Chris@0: $type = NodeType::load($node->getType()); Chris@0: $help = $type->getHelp(); Chris@0: return (!empty($help) ? Xss::filterAdmin($help) : ''); Chris@0: Chris@0: case 'node.add': Chris@0: $type = $route_match->getParameter('node_type'); Chris@0: $help = $type->getHelp(); Chris@0: return (!empty($help) ? Xss::filterAdmin($help) : ''); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_theme(). Chris@0: */ Chris@0: function node_theme() { Chris@0: return [ Chris@0: 'node' => [ Chris@0: 'render element' => 'elements', Chris@0: ], Chris@0: 'node_add_list' => [ Chris@0: 'variables' => ['content' => NULL], Chris@0: ], Chris@0: 'node_edit_form' => [ Chris@0: 'render element' => 'form', Chris@0: ], Chris@0: 'field__node__title' => [ Chris@0: 'base hook' => 'field', Chris@0: ], Chris@0: 'field__node__uid' => [ Chris@0: 'base hook' => 'field', Chris@0: ], Chris@0: 'field__node__created' => [ Chris@0: 'base hook' => 'field', Chris@0: ], Chris@0: ]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_entity_view_display_alter(). Chris@0: */ Chris@0: function node_entity_view_display_alter(EntityViewDisplayInterface $display, $context) { Chris@0: if ($context['entity_type'] == 'node') { Chris@0: // Hide field labels in search index. Chris@0: if ($context['view_mode'] == 'search_index') { Chris@0: foreach ($display->getComponents() as $name => $options) { Chris@0: if (isset($options['label'])) { Chris@0: $options['label'] = 'hidden'; Chris@0: $display->setComponent($name, $options); Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gathers a listing of links to nodes. Chris@0: * Chris@0: * @param \Drupal\Core\Database\StatementInterface $result Chris@0: * A database result object from a query to fetch node entities. If your Chris@0: * query joins the {comment_entity_statistics} table so that the comment_count Chris@0: * field is available, a title attribute will be added to show the number of Chris@0: * comments. Chris@0: * @param $title Chris@0: * (optional) A heading for the resulting list. Chris@0: * Chris@0: * @return array|false Chris@0: * A renderable array containing a list of linked node titles fetched from Chris@0: * $result, or FALSE if there are no rows in $result. Chris@0: */ Chris@0: function node_title_list(StatementInterface $result, $title = NULL) { Chris@0: $items = []; Chris@0: $num_rows = FALSE; Chris@0: $nids = []; Chris@0: foreach ($result as $row) { Chris@18: // Do not use $node->label() or $node->toUrl() here, because we only have Chris@0: // database rows, not actual nodes. Chris@0: $nids[] = $row->nid; Chris@0: $options = !empty($row->comment_count) ? ['attributes' => ['title' => \Drupal::translation()->formatPlural($row->comment_count, '1 comment', '@count comments')]] : []; Chris@0: $items[] = \Drupal::l($row->title, new Url('entity.node.canonical', ['node' => $row->nid], $options)); Chris@0: $num_rows = TRUE; Chris@0: } Chris@0: Chris@0: return $num_rows ? ['#theme' => 'item_list__node', '#items' => $items, '#title' => $title, '#cache' => ['tags' => Cache::mergeTags(['node_list'], Cache::buildTags('node', $nids))]] : FALSE; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Determines the type of marker to be displayed for a given node. Chris@0: * Chris@0: * @param int $nid Chris@0: * Node ID whose history supplies the "last viewed" timestamp. Chris@0: * @param int $timestamp Chris@0: * Time which is compared against node's "last viewed" timestamp. Chris@0: * Chris@0: * @return int Chris@0: * One of the MARK constants. Chris@0: */ Chris@0: function node_mark($nid, $timestamp) { Chris@0: Chris@0: $cache = &drupal_static(__FUNCTION__, []); Chris@0: Chris@0: if (\Drupal::currentUser()->isAnonymous() || !\Drupal::moduleHandler()->moduleExists('history')) { Chris@0: return MARK_READ; Chris@0: } Chris@0: if (!isset($cache[$nid])) { Chris@0: $cache[$nid] = history_read($nid); Chris@0: } Chris@0: if ($cache[$nid] == 0 && $timestamp > HISTORY_READ_LIMIT) { Chris@0: return MARK_NEW; Chris@0: } Chris@0: elseif ($timestamp > $cache[$nid] && $timestamp > HISTORY_READ_LIMIT) { Chris@0: return MARK_UPDATED; Chris@0: } Chris@0: return MARK_READ; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a list of all the available node types. Chris@0: * Chris@0: * This list can include types that are queued for addition or deletion. Chris@0: * Chris@0: * @return \Drupal\node\NodeTypeInterface[] Chris@0: * An array of node type entities, keyed by ID. Chris@0: * Chris@0: * @deprecated in Drupal 8.x, will be removed before Drupal 9.0. Chris@0: * Use \Drupal\node\Entity\NodeType::loadMultiple(). Chris@0: * Chris@0: * @see \Drupal\node\Entity\NodeType::load() Chris@0: */ Chris@0: function node_type_get_types() { Chris@0: return NodeType::loadMultiple(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a list of available node type names. Chris@0: * Chris@0: * This list can include types that are queued for addition or deletion. Chris@0: * Chris@0: * @return string[] Chris@0: * An array of node type labels, keyed by the node type name. Chris@0: */ Chris@0: function node_type_get_names() { Chris@0: return array_map(function ($bundle_info) { Chris@0: return $bundle_info['label']; Chris@18: }, \Drupal::service('entity_type.bundle.info')->getBundleInfo('node')); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the node type label for the passed node. Chris@0: * Chris@0: * @param \Drupal\node\NodeInterface $node Chris@0: * A node entity to return the node type's label for. Chris@0: * Chris@0: * @return string|false Chris@0: * The node type label or FALSE if the node type is not found. Chris@0: * Chris@0: * @todo Add this as generic helper method for config entities representing Chris@0: * entity bundles. Chris@0: */ Chris@0: function node_get_type_label(NodeInterface $node) { Chris@0: $type = NodeType::load($node->bundle()); Chris@0: return $type ? $type->label() : FALSE; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Description callback: Returns the node type description. Chris@0: * Chris@0: * @param \Drupal\node\NodeTypeInterface $node_type Chris@0: * The node type object. Chris@0: * Chris@0: * @return string Chris@0: * The node type description. Chris@0: */ Chris@0: function node_type_get_description(NodeTypeInterface $node_type) { Chris@0: return $node_type->getDescription(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Menu argument loader: Loads a node type by string. Chris@0: * Chris@0: * @param $name Chris@0: * The machine name of a node type to load. Chris@0: * Chris@0: * @return \Drupal\node\NodeTypeInterface Chris@0: * A node type object or NULL if $name does not exist. Chris@0: * Chris@18: * @deprecated iin Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use Chris@18: * \Drupal\node\Entity\NodeType::load(). Chris@18: * Chris@18: * @see https://www.drupal.org/node/2266845 Chris@0: */ Chris@0: function node_type_load($name) { Chris@18: @trigger_error('node_type_load() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\node\Entity\NodeType::load(). See https://www.drupal.org/node/2266845', E_USER_DEPRECATED); Chris@0: return NodeType::load($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the default body field to a node type. Chris@0: * Chris@0: * @param \Drupal\node\NodeTypeInterface $type Chris@0: * A node type object. Chris@0: * @param string $label Chris@0: * (optional) The label for the body instance. Chris@0: * Chris@0: * @return \Drupal\field\Entity\FieldConfig Chris@0: * A Body field object. Chris@0: */ Chris@0: function node_add_body_field(NodeTypeInterface $type, $label = 'Body') { Chris@0: // Add or remove the body field, as needed. Chris@0: $field_storage = FieldStorageConfig::loadByName('node', 'body'); Chris@0: $field = FieldConfig::loadByName('node', $type->id(), 'body'); Chris@0: if (empty($field)) { Chris@0: $field = FieldConfig::create([ Chris@0: 'field_storage' => $field_storage, Chris@0: 'bundle' => $type->id(), Chris@0: 'label' => $label, Chris@0: 'settings' => ['display_summary' => TRUE], Chris@0: ]); Chris@0: $field->save(); Chris@0: Chris@0: // Assign widget settings for the 'default' form mode. Chris@0: entity_get_form_display('node', $type->id(), 'default') Chris@0: ->setComponent('body', [ Chris@0: 'type' => 'text_textarea_with_summary', Chris@0: ]) Chris@0: ->save(); Chris@0: Chris@0: // Assign display settings for the 'default' and 'teaser' view modes. Chris@0: entity_get_display('node', $type->id(), 'default') Chris@0: ->setComponent('body', [ Chris@0: 'label' => 'hidden', Chris@0: 'type' => 'text_default', Chris@0: ]) Chris@0: ->save(); Chris@0: Chris@0: // The teaser view mode is created by the Standard profile and therefore Chris@0: // might not exist. Chris@18: $view_modes = \Drupal::service('entity_display.repository')->getViewModes('node'); Chris@0: if (isset($view_modes['teaser'])) { Chris@0: entity_get_display('node', $type->id(), 'teaser') Chris@0: ->setComponent('body', [ Chris@0: 'label' => 'hidden', Chris@0: 'type' => 'text_summary_or_trimmed', Chris@0: ]) Chris@0: ->save(); Chris@0: } Chris@0: } Chris@0: Chris@0: return $field; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_entity_extra_field_info(). Chris@0: */ Chris@0: function node_entity_extra_field_info() { Chris@0: $extra = []; Chris@0: $description = t('Node module element'); Chris@0: foreach (NodeType::loadMultiple() as $bundle) { Chris@0: $extra['node'][$bundle->id()]['display']['links'] = [ Chris@0: 'label' => t('Links'), Chris@0: 'description' => $description, Chris@0: 'weight' => 100, Chris@0: 'visible' => TRUE, Chris@0: ]; Chris@0: } Chris@0: Chris@0: return $extra; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Updates all nodes of one type to be of another type. Chris@0: * Chris@0: * @param string $old_id Chris@0: * The current node type of the nodes. Chris@0: * @param string $new_id Chris@0: * The new node type of the nodes. Chris@0: * Chris@0: * @return Chris@0: * The number of nodes whose node type field was modified. Chris@0: */ Chris@0: function node_type_update_nodes($old_id, $new_id) { Chris@0: return \Drupal::entityManager()->getStorage('node')->updateType($old_id, $new_id); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Loads node entities from the database. Chris@0: * Chris@0: * This function should be used whenever you need to load more than one node Chris@0: * from the database. Nodes are loaded into memory and will not require database Chris@0: * access if loaded again during the same page request. Chris@0: * Chris@0: * @param array $nids Chris@0: * (optional) An array of entity IDs. If omitted, all entities are loaded. Chris@0: * @param bool $reset Chris@0: * (optional) Whether to reset the internal node_load() cache. Defaults to Chris@0: * FALSE. Chris@0: * Chris@0: * @return \Drupal\node\NodeInterface[] Chris@0: * An array of node entities indexed by nid. Chris@0: * Chris@18: * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use Chris@18: * \Drupal\node\Entity\Node::loadMultiple(). Chris@0: * Chris@18: * @see https://www.drupal.org/node/2266845 Chris@0: */ Chris@0: function node_load_multiple(array $nids = NULL, $reset = FALSE) { Chris@18: @trigger_error('node_load_multiple() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\node\Entity\Node::loadMultiple(). See https://www.drupal.org/node/2266845', E_USER_DEPRECATED); Chris@0: if ($reset) { Chris@0: \Drupal::entityManager()->getStorage('node')->resetCache($nids); Chris@0: } Chris@0: return Node::loadMultiple($nids); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Loads a node entity from the database. Chris@0: * Chris@0: * @param int $nid Chris@0: * The node ID. Chris@0: * @param bool $reset Chris@0: * (optional) Whether to reset the node_load_multiple() cache. Defaults to Chris@0: * FALSE. Chris@0: * Chris@0: * @return \Drupal\node\NodeInterface|null Chris@0: * A fully-populated node entity, or NULL if the node is not found. Chris@0: * Chris@18: * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use Chris@18: * \Drupal\node\Entity\Node::load(). Chris@18: * Chris@18: * @see https://www.drupal.org/node/2266845 Chris@0: */ Chris@0: function node_load($nid = NULL, $reset = FALSE) { Chris@18: @trigger_error('node_load() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\node\Entity\Node::load(). See https://www.drupal.org/node/2266845', E_USER_DEPRECATED); Chris@0: if ($reset) { Chris@0: \Drupal::entityManager()->getStorage('node')->resetCache([$nid]); Chris@0: } Chris@0: return Node::load($nid); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Loads a node revision from the database. Chris@0: * Chris@0: * @param int $vid Chris@0: * The node revision id. Chris@0: * Chris@0: * @return \Drupal\node\NodeInterface|null Chris@0: * A fully-populated node entity, or NULL if the node is not found. Chris@0: */ Chris@0: function node_revision_load($vid = NULL) { Chris@0: return \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Deletes a node revision. Chris@0: * Chris@0: * @param int $revision_id Chris@0: * The revision ID to delete. Chris@0: */ Chris@0: function node_revision_delete($revision_id) { Chris@0: \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks whether the current page is the full page view of the passed-in node. Chris@0: * Chris@0: * @param \Drupal\node\NodeInterface $node Chris@0: * A node entity. Chris@0: * Chris@0: * @return int|false Chris@0: * The ID of the node if this is a full page view, otherwise FALSE. Chris@0: */ Chris@0: function node_is_page(NodeInterface $node) { Chris@0: $route_match = \Drupal::routeMatch(); Chris@0: if ($route_match->getRouteName() == 'entity.node.canonical') { Chris@0: $page_node = $route_match->getParameter('node'); Chris@0: } Chris@0: return (!empty($page_node) ? $page_node->id() == $node->id() : FALSE); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares variables for list of available node type templates. Chris@0: * Chris@0: * Default template: node-add-list.html.twig. Chris@0: * Chris@0: * @param array $variables Chris@0: * An associative array containing: Chris@0: * - content: An array of content types. Chris@0: * Chris@18: * @see \Drupal\node\Controller\NodeController::addPage() Chris@0: */ Chris@0: function template_preprocess_node_add_list(&$variables) { Chris@0: $variables['types'] = []; Chris@0: if (!empty($variables['content'])) { Chris@0: foreach ($variables['content'] as $type) { Chris@0: $variables['types'][$type->id()] = [ Chris@0: 'type' => $type->id(), Chris@0: 'add_link' => \Drupal::l($type->label(), new Url('node.add', ['node_type' => $type->id()])), Chris@0: 'description' => [ Chris@0: '#markup' => $type->getDescription(), Chris@0: ], Chris@0: ]; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_preprocess_HOOK() for HTML document templates. Chris@0: */ Chris@0: function node_preprocess_html(&$variables) { Chris@17: // If on an individual node page or node preview page, add the node type to Chris@17: // the body classes. Chris@17: if (($node = \Drupal::routeMatch()->getParameter('node')) || ($node = \Drupal::routeMatch()->getParameter('node_preview'))) { Chris@17: if ($node instanceof NodeInterface) { Chris@17: $variables['node_type'] = $node->getType(); Chris@17: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_preprocess_HOOK() for block templates. Chris@0: */ Chris@0: function node_preprocess_block(&$variables) { Chris@0: if ($variables['configuration']['provider'] == 'node') { Chris@0: switch ($variables['elements']['#plugin_id']) { Chris@0: case 'node_syndicate_block': Chris@0: $variables['attributes']['role'] = 'complementary'; Chris@0: break; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_theme_suggestions_HOOK(). Chris@0: */ Chris@0: function node_theme_suggestions_node(array $variables) { Chris@0: $suggestions = []; Chris@0: $node = $variables['elements']['#node']; Chris@0: $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_'); Chris@0: Chris@0: $suggestions[] = 'node__' . $sanitized_view_mode; Chris@0: $suggestions[] = 'node__' . $node->bundle(); Chris@0: $suggestions[] = 'node__' . $node->bundle() . '__' . $sanitized_view_mode; Chris@0: $suggestions[] = 'node__' . $node->id(); Chris@0: $suggestions[] = 'node__' . $node->id() . '__' . $sanitized_view_mode; Chris@0: Chris@0: return $suggestions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares variables for node templates. Chris@0: * Chris@0: * Default template: node.html.twig. Chris@0: * Chris@0: * Most themes use their own copy of node.html.twig. The default is located Chris@0: * inside "/core/modules/node/templates/node.html.twig". Look in there for the Chris@0: * full list of variables. Chris@0: * Chris@18: * By default this function performs special preprocessing of some base fields Chris@18: * so they are available as variables in the template. For example 'title' Chris@18: * appears as 'label'. This preprocessing is skipped if: Chris@18: * - a module makes the field's display configurable via the field UI by means Chris@18: * of BaseFieldDefinition::setDisplayConfigurable() Chris@18: * - AND the additional entity type property Chris@18: * 'enable_base_field_custom_preprocess_skipping' has been set using Chris@18: * hook_entity_type_build(). Chris@18: * Chris@0: * @param array $variables Chris@0: * An associative array containing: Chris@0: * - elements: An array of elements to display in view mode. Chris@0: * - node: The node object. Chris@0: * - view_mode: View mode; e.g., 'full', 'teaser', etc. Chris@18: * Chris@18: * @see hook_entity_type_build() Chris@18: * @see \Drupal\Core\Field\BaseFieldDefinition::setDisplayConfigurable() Chris@0: */ Chris@0: function template_preprocess_node(&$variables) { Chris@0: $variables['view_mode'] = $variables['elements']['#view_mode']; Chris@0: // Provide a distinct $teaser boolean. Chris@0: $variables['teaser'] = $variables['view_mode'] == 'teaser'; Chris@0: $variables['node'] = $variables['elements']['#node']; Chris@0: /** @var \Drupal\node\NodeInterface $node */ Chris@0: $node = $variables['node']; Chris@18: $skip_custom_preprocessing = $node->getEntityType()->get('enable_base_field_custom_preprocess_skipping'); Chris@0: Chris@18: // Make created, uid and title fields available separately. Skip this custom Chris@18: // preprocessing if the field display is configurable and skipping has been Chris@18: // enabled. Chris@18: // @todo https://www.drupal.org/project/drupal/issues/3015623 Chris@18: // In D9 delete this code and matching template lines. Using Chris@18: // $variables['content'] is more flexible and consistent. Chris@18: $submitted_configurable = $node->getFieldDefinition('created')->isDisplayConfigurable('view') || $node->getFieldDefinition('uid')->isDisplayConfigurable('view'); Chris@18: if (!$skip_custom_preprocessing || !$submitted_configurable) { Chris@18: $variables['date'] = \Drupal::service('renderer')->render($variables['elements']['created']); Chris@18: unset($variables['elements']['created']); Chris@18: $variables['author_name'] = \Drupal::service('renderer')->render($variables['elements']['uid']); Chris@18: unset($variables['elements']['uid']); Chris@18: } Chris@18: Chris@18: if (!$skip_custom_preprocessing || !$node->getFieldDefinition('title')->isDisplayConfigurable('view')) { Chris@18: $variables['label'] = $variables['elements']['title']; Chris@18: unset($variables['elements']['title']); Chris@18: } Chris@18: Chris@18: $variables['url'] = !$node->isNew() ? $node->toUrl('canonical')->toString() : NULL; Chris@18: Chris@0: // The 'page' variable is set to TRUE in two occasions: Chris@0: // - The view mode is 'full' and we are on the 'node.view' route. Chris@0: // - The node is in preview and view mode is either 'full' or 'default'. Chris@0: $variables['page'] = ($variables['view_mode'] == 'full' && (node_is_page($node)) || (isset($node->in_preview) && in_array($node->preview_view_mode, ['full', 'default']))); Chris@0: Chris@0: // Helpful $content variable for templates. Chris@0: $variables += ['content' => []]; Chris@0: foreach (Element::children($variables['elements']) as $key) { Chris@0: $variables['content'][$key] = $variables['elements'][$key]; Chris@0: } Chris@0: Chris@18: if (isset($variables['date'])) { Chris@18: // Display post information on certain node types. This only occurs if Chris@18: // custom preprocessing occurred for both of the created and uid fields. Chris@18: // @todo https://www.drupal.org/project/drupal/issues/3015623 Chris@18: // In D9 delete this code and matching template lines. Using a field Chris@18: // formatter is more flexible and consistent. Chris@18: $node_type = $node->type->entity; Chris@18: // Used by RDF to add attributes around the author and date submitted. Chris@18: $variables['author_attributes'] = new Attribute(); Chris@18: $variables['display_submitted'] = $node_type->displaySubmitted(); Chris@18: if ($variables['display_submitted']) { Chris@18: if (theme_get_setting('features.node_user_picture')) { Chris@18: // To change user picture settings (e.g. image style), edit the Chris@18: // 'compact' view mode on the User entity. Note that the 'compact' Chris@18: // view mode might not be configured, so remember to always check the Chris@18: // theme setting first. Chris@18: $variables['author_picture'] = user_view($node->getOwner(), 'compact'); Chris@18: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Add article ARIA role. Chris@0: $variables['attributes']['role'] = 'article'; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_cron(). Chris@0: */ Chris@0: function node_cron() { Chris@0: // Calculate the oldest and newest node created times, for use in search Chris@0: // rankings. (Note that field aliases have to be variables passed by Chris@0: // reference.) Chris@0: if (\Drupal::moduleHandler()->moduleExists('search')) { Chris@0: $min_alias = 'min_created'; Chris@0: $max_alias = 'max_created'; Chris@0: $result = \Drupal::entityQueryAggregate('node') Chris@0: ->aggregate('created', 'MIN', NULL, $min_alias) Chris@0: ->aggregate('created', 'MAX', NULL, $max_alias) Chris@0: ->execute(); Chris@0: if (isset($result[0])) { Chris@0: // Make an array with definite keys and store it in the state system. Chris@0: $array = [ Chris@0: 'min_created' => $result[0][$min_alias], Chris@0: 'max_created' => $result[0][$max_alias], Chris@0: ]; Chris@0: \Drupal::state()->set('node.min_max_update_time', $array); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_ranking(). Chris@0: */ Chris@0: function node_ranking() { Chris@0: // Create the ranking array and add the basic ranking options. Chris@0: $ranking = [ Chris@0: 'relevance' => [ Chris@0: 'title' => t('Keyword relevance'), Chris@0: // Average relevance values hover around 0.15 Chris@0: 'score' => 'i.relevance', Chris@0: ], Chris@0: 'sticky' => [ Chris@0: 'title' => t('Content is sticky at top of lists'), Chris@0: // The sticky flag is either 0 or 1, which is automatically normalized. Chris@0: 'score' => 'n.sticky', Chris@0: ], Chris@0: 'promote' => [ Chris@0: 'title' => t('Content is promoted to the front page'), Chris@0: // The promote flag is either 0 or 1, which is automatically normalized. Chris@0: 'score' => 'n.promote', Chris@0: ], Chris@0: ]; Chris@0: // Add relevance based on updated date, but only if it the scale values have Chris@0: // been calculated in node_cron(). Chris@0: if ($node_min_max = \Drupal::state()->get('node.min_max_update_time')) { Chris@0: $ranking['recent'] = [ Chris@0: 'title' => t('Recently created'), Chris@0: // Exponential decay with half life of 14% of the age range of nodes. Chris@0: 'score' => 'EXP(-5 * (1 - (n.created - :node_oldest) / :node_range))', Chris@0: 'arguments' => [ Chris@0: ':node_oldest' => $node_min_max['min_created'], Chris@0: ':node_range' => max($node_min_max['max_created'] - $node_min_max['min_created'], 1), Chris@0: ], Chris@0: ]; Chris@0: } Chris@0: return $ranking; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_user_cancel(). Chris@0: */ Chris@17: function node_user_cancel($edit, UserInterface $account, $method) { Chris@0: switch ($method) { Chris@0: case 'user_cancel_block_unpublish': Chris@0: // Unpublish nodes (current revisions). Chris@0: $nids = \Drupal::entityQuery('node') Chris@0: ->condition('uid', $account->id()) Chris@0: ->execute(); Chris@0: module_load_include('inc', 'node', 'node.admin'); Chris@0: node_mass_update($nids, ['status' => 0], NULL, TRUE); Chris@0: break; Chris@0: Chris@0: case 'user_cancel_reassign': Chris@0: // Anonymize all of the nodes for this old account. Chris@0: module_load_include('inc', 'node', 'node.admin'); Chris@0: $vids = \Drupal::entityManager()->getStorage('node')->userRevisionIds($account); Chris@0: node_mass_update($vids, [ Chris@0: 'uid' => 0, Chris@0: 'revision_uid' => 0, Chris@0: ], NULL, TRUE, TRUE); Chris@0: break; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_ENTITY_TYPE_predelete() for user entities. Chris@0: */ Chris@0: function node_user_predelete($account) { Chris@0: // Delete nodes (current revisions). Chris@0: // @todo Introduce node_mass_delete() or make node_mass_update() more flexible. Chris@0: $nids = \Drupal::entityQuery('node') Chris@0: ->condition('uid', $account->id()) Chris@0: ->accessCheck(FALSE) Chris@0: ->execute(); Chris@0: entity_delete_multiple('node', $nids); Chris@0: // Delete old revisions. Chris@0: $storage_controller = \Drupal::entityManager()->getStorage('node'); Chris@0: $revisions = $storage_controller->userRevisionIds($account); Chris@0: foreach ($revisions as $revision) { Chris@0: node_revision_delete($revision); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Finds the most recently changed nodes that are available to the current user. Chris@0: * Chris@0: * @param $number Chris@0: * (optional) The maximum number of nodes to find. Defaults to 10. Chris@0: * Chris@0: * @return \Drupal\node\NodeInterface[] Chris@0: * An array of node entities or an empty array if there are no recent nodes Chris@0: * visible to the current user. Chris@0: */ Chris@0: function node_get_recent($number = 10) { Chris@0: $account = \Drupal::currentUser(); Chris@0: $query = \Drupal::entityQuery('node'); Chris@0: Chris@0: if (!$account->hasPermission('bypass node access')) { Chris@0: // If the user is able to view their own unpublished nodes, allow them Chris@0: // to see these in addition to published nodes. Check that they actually Chris@0: // have some unpublished nodes to view before adding the condition. Chris@0: $access_query = \Drupal::entityQuery('node') Chris@0: ->condition('uid', $account->id()) Chris@0: ->condition('status', NodeInterface::NOT_PUBLISHED); Chris@0: if ($account->hasPermission('view own unpublished content') && ($own_unpublished = $access_query->execute())) { Chris@0: $query->orConditionGroup() Chris@0: ->condition('status', NodeInterface::PUBLISHED) Chris@0: ->condition('nid', $own_unpublished, 'IN'); Chris@0: } Chris@0: else { Chris@0: // If not, restrict the query to published nodes. Chris@0: $query->condition('status', NodeInterface::PUBLISHED); Chris@0: } Chris@0: } Chris@0: $nids = $query Chris@0: ->sort('changed', 'DESC') Chris@0: ->range(0, $number) Chris@0: ->addTag('node_access') Chris@0: ->execute(); Chris@0: Chris@0: $nodes = Node::loadMultiple($nids); Chris@0: Chris@0: return $nodes ? $nodes : []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates an array for rendering the given node. Chris@0: * Chris@0: * @param \Drupal\node\NodeInterface $node Chris@0: * A node entity. Chris@0: * @param $view_mode Chris@0: * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'full.' Chris@0: * @param $langcode Chris@0: * (optional) A language code to use for rendering. Defaults to NULL which is Chris@0: * the global content language of the current request. Chris@0: * Chris@0: * @return array Chris@16: * An array as expected by \Drupal\Core\Render\RendererInterface::render(). Chris@0: */ Chris@0: function node_view(NodeInterface $node, $view_mode = 'full', $langcode = NULL) { Chris@0: return entity_view($node, $view_mode, $langcode); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Constructs a drupal_render() style array from an array of loaded nodes. Chris@0: * Chris@0: * @param $nodes Chris@0: * An array of nodes as returned by Node::loadMultiple(). Chris@0: * @param $view_mode Chris@0: * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.' Chris@0: * @param $langcode Chris@0: * (optional) A language code to use for rendering. Defaults to the global Chris@0: * content language of the current request. Chris@0: * Chris@0: * @return array Chris@16: * An array in the format expected by Chris@16: * \Drupal\Core\Render\RendererInterface::render(). Chris@0: */ Chris@0: function node_view_multiple($nodes, $view_mode = 'teaser', $langcode = NULL) { Chris@0: return entity_view_multiple($nodes, $view_mode, $langcode); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_page_top(). Chris@0: */ Chris@0: function node_page_top(array &$page) { Chris@0: // Add 'Back to content editing' link on preview page. Chris@0: $route_match = \Drupal::routeMatch(); Chris@0: if ($route_match->getRouteName() == 'entity.node.preview') { Chris@0: $page['page_top']['node_preview'] = [ Chris@0: '#type' => 'container', Chris@0: '#attributes' => [ Chris@17: 'class' => ['node-preview-container', 'container-inline'], Chris@0: ], Chris@0: ]; Chris@0: Chris@0: $form = \Drupal::formBuilder()->getForm('\Drupal\node\Form\NodePreviewForm', $route_match->getParameter('node_preview')); Chris@0: $page['page_top']['node_preview']['view_mode'] = $form; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_form_FORM_ID_alter(). Chris@0: * Chris@0: * Alters the theme form to use the admin theme on node editing. Chris@0: * Chris@0: * @see node_form_system_themes_admin_form_submit() Chris@0: */ Chris@0: function node_form_system_themes_admin_form_alter(&$form, FormStateInterface $form_state, $form_id) { Chris@0: $form['admin_theme']['use_admin_theme'] = [ Chris@0: '#type' => 'checkbox', Chris@0: '#title' => t('Use the administration theme when editing or creating content'), Chris@0: '#description' => t('Control which roles can "View the administration theme" on the Permissions page.', [':permissions' => Url::fromRoute('user.admin_permissions')->toString()]), Chris@0: '#default_value' => \Drupal::configFactory()->getEditable('node.settings')->get('use_admin_theme'), Chris@0: ]; Chris@0: $form['#submit'][] = 'node_form_system_themes_admin_form_submit'; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Form submission handler for system_themes_admin_form(). Chris@0: * Chris@0: * @see node_form_system_themes_admin_form_alter() Chris@0: */ Chris@0: function node_form_system_themes_admin_form_submit($form, FormStateInterface $form_state) { Chris@0: \Drupal::configFactory()->getEditable('node.settings') Chris@0: ->set('use_admin_theme', $form_state->getValue('use_admin_theme')) Chris@0: ->save(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * @defgroup node_access Node access rights Chris@0: * @{ Chris@0: * The node access system determines who can do what to which nodes. Chris@0: * Chris@0: * In determining access rights for a node, \Drupal\node\NodeAccessControlHandler Chris@0: * first checks whether the user has the "bypass node access" permission. Such Chris@0: * users have unrestricted access to all nodes. user 1 will always pass this Chris@0: * check. Chris@0: * Chris@0: * Next, all implementations of hook_node_access() will be called. Each Chris@0: * implementation may explicitly allow, explicitly forbid, or ignore the access Chris@0: * request. If at least one module says to forbid the request, it will be Chris@0: * rejected. If no modules deny the request and at least one says to allow it, Chris@0: * the request will be permitted. Chris@0: * Chris@0: * If all modules ignore the access request, then the node_access table is used Chris@0: * to determine access. All node access modules are queried using Chris@0: * hook_node_grants() to assemble a list of "grant IDs" for the user. This list Chris@0: * is compared against the table. If any row contains the node ID in question Chris@0: * (or 0, which stands for "all nodes"), one of the grant IDs returned, and a Chris@0: * value of TRUE for the operation in question, then access is granted. Note Chris@0: * that this table is a list of grants; any matching row is sufficient to grant Chris@0: * access to the node. Chris@0: * Chris@0: * In node listings (lists of nodes generated from a select query, such as the Chris@0: * default home page at path 'node', an RSS feed, a recent content block, etc.), Chris@0: * the process above is followed except that hook_node_access() is not called on Chris@0: * each node for performance reasons and for proper functioning of the pager Chris@0: * system. When adding a node listing to your module, be sure to use an entity Chris@0: * query, which will add a tag of "node_access". This will allow modules dealing Chris@0: * with node access to ensure only nodes to which the user has access are Chris@0: * retrieved, through the use of hook_query_TAG_alter(). See the Chris@0: * @link entity_api Entity API topic @endlink for more information on entity Chris@0: * queries. Tagging a query with "node_access" does not check the Chris@0: * published/unpublished status of nodes, so the base query is responsible Chris@0: * for ensuring that unpublished nodes are not displayed to inappropriate users. Chris@0: * Chris@0: * Note: Even a single module returning an AccessResultInterface object from Chris@0: * hook_node_access() whose isForbidden() method equals TRUE will block access Chris@0: * to the node. Therefore, implementers should take care to not deny access Chris@0: * unless they really intend to. Unless a module wishes to actively forbid Chris@0: * access it should return an AccessResultInterface object whose isAllowed() nor Chris@0: * isForbidden() methods return TRUE, to allow other modules or the node_access Chris@0: * table to control access. Chris@0: * Chris@0: * To see how to write a node access module of your own, see Chris@0: * node_access_example.module. Chris@0: */ Chris@0: Chris@0: /** Chris@0: * Implements hook_node_access(). Chris@0: */ Chris@18: function node_node_access(NodeInterface $node, $op, AccountInterface $account) { Chris@0: $type = $node->bundle(); Chris@18: $access = AccessResult::neutral(); Chris@0: Chris@0: switch ($op) { Chris@0: case 'create': Chris@18: $access = AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content'); Chris@0: Chris@0: case 'update': Chris@18: $access = AccessResult::allowedIfHasPermission($account, 'edit any ' . $type . ' content'); Chris@18: if (!$access->isAllowed() && $account->hasPermission('edit own ' . $type . ' content')) { Chris@18: $access = $access->orIf(AccessResult::allowedIf($account->id() == $node->getOwnerId())->cachePerUser()->addCacheableDependency($node)); Chris@0: } Chris@18: break; Chris@0: Chris@0: case 'delete': Chris@18: $access = AccessResult::allowedIfHasPermission($account, 'delete any ' . $type . ' content'); Chris@18: if (!$access->isAllowed() && $account->hasPermission('delete own ' . $type . ' content')) { Chris@18: $access = $access->orIf(AccessResult::allowedIf($account->id() == $node->getOwnerId()))->cachePerUser()->addCacheableDependency($node); Chris@0: } Chris@18: break; Chris@18: } Chris@0: Chris@18: return $access; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Fetches an array of permission IDs granted to the given user ID. Chris@0: * Chris@0: * The implementation here provides only the universal "all" grant. A node Chris@0: * access module should implement hook_node_grants() to provide a grant list for Chris@0: * the user. Chris@0: * Chris@0: * After the default grants have been loaded, we allow modules to alter the Chris@0: * grants array by reference. This hook allows for complex business logic to be Chris@0: * applied when integrating multiple node access modules. Chris@0: * Chris@0: * @param string $op Chris@0: * The operation that the user is trying to perform. Chris@0: * @param \Drupal\Core\Session\AccountInterface $account Chris@0: * The account object for the user performing the operation. Chris@0: * Chris@0: * @return array Chris@0: * An associative array in which the keys are realms, and the values are Chris@0: * arrays of grants for those realms. Chris@0: */ Chris@0: function node_access_grants($op, AccountInterface $account) { Chris@0: // Fetch node access grants from other modules. Chris@0: $grants = \Drupal::moduleHandler()->invokeAll('node_grants', [$account, $op]); Chris@0: // Allow modules to alter the assigned grants. Chris@0: \Drupal::moduleHandler()->alter('node_grants', $grants, $account, $op); Chris@0: Chris@0: return array_merge(['all' => [0]], $grants); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Determines whether the user has a global viewing grant for all nodes. Chris@0: * Chris@0: * Checks to see whether any module grants global 'view' access to a user Chris@0: * account; global 'view' access is encoded in the {node_access} table as a Chris@0: * grant with nid=0. If no node access modules are enabled, node.module defines Chris@0: * such a global 'view' access grant. Chris@0: * Chris@0: * This function is called when a node listing query is tagged with Chris@0: * 'node_access'; when this function returns TRUE, no node access joins are Chris@0: * added to the query. Chris@0: * Chris@0: * @param $account Chris@0: * (optional) The user object for the user whose access is being checked. If Chris@0: * omitted, the current user is used. Defaults to NULL. Chris@0: * Chris@0: * @return Chris@0: * TRUE if 'view' access to all nodes is granted, FALSE otherwise. Chris@0: * Chris@0: * @see hook_node_grants() Chris@0: * @see node_query_node_access_alter() Chris@0: */ Chris@0: function node_access_view_all_nodes($account = NULL) { Chris@0: Chris@0: if (!$account) { Chris@0: $account = \Drupal::currentUser(); Chris@0: } Chris@0: Chris@0: // Statically cache results in an array keyed by $account->id(). Chris@0: $access = &drupal_static(__FUNCTION__); Chris@0: if (isset($access[$account->id()])) { Chris@0: return $access[$account->id()]; Chris@0: } Chris@0: Chris@0: // If no modules implement the node access system, access is always TRUE. Chris@0: if (!\Drupal::moduleHandler()->getImplementations('node_grants')) { Chris@0: $access[$account->id()] = TRUE; Chris@0: } Chris@0: else { Chris@0: $access[$account->id()] = \Drupal::entityManager()->getAccessControlHandler('node')->checkAllGrants($account); Chris@0: } Chris@0: Chris@0: return $access[$account->id()]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_query_TAG_alter(). Chris@0: * Chris@0: * This is the hook_query_alter() for queries tagged with 'node_access'. It adds Chris@0: * node access checks for the user account given by the 'account' meta-data (or Chris@0: * current user if not provided), for an operation given by the 'op' meta-data Chris@0: * (or 'view' if not provided; other possible values are 'update' and 'delete'). Chris@0: * Chris@0: * Queries tagged with 'node_access' that are not against the {node} table Chris@0: * must add the base table as metadata. For example: Chris@0: * @code Chris@0: * $query Chris@0: * ->addTag('node_access') Chris@0: * ->addMetaData('base_table', 'taxonomy_index'); Chris@0: * @endcode Chris@0: */ Chris@0: function node_query_node_access_alter(AlterableInterface $query) { Chris@0: // Read meta-data from query, if provided. Chris@0: if (!$account = $query->getMetaData('account')) { Chris@0: $account = \Drupal::currentUser(); Chris@0: } Chris@0: if (!$op = $query->getMetaData('op')) { Chris@0: $op = 'view'; Chris@0: } Chris@0: Chris@0: // If $account can bypass node access, or there are no node access modules, Chris@0: // or the operation is 'view' and the $account has a global view grant Chris@0: // (such as a view grant for node ID 0), we don't need to alter the query. Chris@0: if ($account->hasPermission('bypass node access')) { Chris@0: return; Chris@0: } Chris@0: if (!count(\Drupal::moduleHandler()->getImplementations('node_grants'))) { Chris@0: return; Chris@0: } Chris@0: if ($op == 'view' && node_access_view_all_nodes($account)) { Chris@0: return; Chris@0: } Chris@0: Chris@0: $tables = $query->getTables(); Chris@0: $base_table = $query->getMetaData('base_table'); Chris@0: // If the base table is not given, default to one of the node base tables. Chris@0: if (!$base_table) { Chris@0: /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */ Chris@0: $table_mapping = \Drupal::entityTypeManager()->getStorage('node')->getTableMapping(); Chris@0: $node_base_tables = $table_mapping->getTableNames(); Chris@0: Chris@0: foreach ($tables as $table_info) { Chris@0: if (!($table_info instanceof SelectInterface)) { Chris@0: $table = $table_info['table']; Chris@0: // Ensure that 'node' and 'node_field_data' are always preferred over Chris@0: // 'node_revision' and 'node_field_revision'. Chris@0: if ($table == 'node' || $table == 'node_field_data') { Chris@0: $base_table = $table; Chris@0: break; Chris@0: } Chris@0: // If one of the node base tables are in the query, add it to the list Chris@0: // of possible base tables to join against. Chris@0: if (in_array($table, $node_base_tables)) { Chris@0: $base_table = $table; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Bail out if the base table is missing. Chris@0: if (!$base_table) { Chris@0: throw new Exception(t('Query tagged for node access but there is no node table, specify the base_table using meta data.')); Chris@0: } Chris@0: } Chris@0: Chris@0: // Update the query for the given storage method. Chris@0: \Drupal::service('node.grant_storage')->alterQuery($query, $tables, $op, $account, $base_table); Chris@0: Chris@0: // Bubble the 'user.node_grants:$op' cache context to the current render Chris@0: // context. Chris@0: $request = \Drupal::requestStack()->getCurrentRequest(); Chris@0: $renderer = \Drupal::service('renderer'); Chris@0: if ($request->isMethodCacheable() && $renderer->hasRenderContext()) { Chris@0: $build = ['#cache' => ['contexts' => ['user.node_grants:' . $op]]]; Chris@0: $renderer->render($build); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Toggles or reads the value of a flag for rebuilding the node access grants. Chris@0: * Chris@0: * When the flag is set, a message is displayed to users with 'access Chris@0: * administration pages' permission, pointing to the 'rebuild' confirm form. Chris@0: * This can be used as an alternative to direct node_access_rebuild calls, Chris@0: * allowing administrators to decide when they want to perform the actual Chris@0: * (possibly time consuming) rebuild. Chris@0: * Chris@0: * When unsure if the current user is an administrator, node_access_rebuild() Chris@0: * should be used instead. Chris@0: * Chris@0: * @param $rebuild Chris@0: * (optional) The boolean value to be written. Chris@0: * Chris@0: * @return bool|null Chris@0: * The current value of the flag if no value was provided for $rebuild. If a Chris@0: * value was provided for $rebuild, nothing (NULL) is returned. Chris@0: * Chris@0: * @see node_access_rebuild() Chris@0: */ Chris@0: function node_access_needs_rebuild($rebuild = NULL) { Chris@0: if (!isset($rebuild)) { Chris@0: return \Drupal::state()->get('node.node_access_needs_rebuild') ?: FALSE; Chris@0: } Chris@0: elseif ($rebuild) { Chris@0: \Drupal::state()->set('node.node_access_needs_rebuild', TRUE); Chris@0: } Chris@0: else { Chris@0: \Drupal::state()->delete('node.node_access_needs_rebuild'); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Rebuilds the node access database. Chris@0: * Chris@0: * This rebuild is occasionally needed by modules that make system-wide changes Chris@0: * to access levels. When the rebuild is required by an admin-triggered action Chris@0: * (e.g module settings form), calling node_access_needs_rebuild(TRUE) instead Chris@0: * of node_access_rebuild() lets the user perform his changes and actually Chris@0: * rebuild only once he is done. Chris@0: * Chris@0: * Note : As of Drupal 6, node access modules are not required to (and actually Chris@0: * should not) call node_access_rebuild() in hook_install/uninstall anymore. Chris@0: * Chris@0: * @param $batch_mode Chris@0: * (optional) Set to TRUE to process in 'batch' mode, spawning processing over Chris@0: * several HTTP requests (thus avoiding the risk of PHP timeout if the site Chris@0: * has a large number of nodes). hook_update_N() and any form submit handler Chris@0: * are safe contexts to use the 'batch mode'. Less decidable cases (such as Chris@0: * calls from hook_user(), hook_taxonomy(), etc.) might consider using the Chris@0: * non-batch mode. Defaults to FALSE. Chris@0: * Chris@0: * @see node_access_needs_rebuild() Chris@0: */ Chris@0: function node_access_rebuild($batch_mode = FALSE) { Chris@0: $node_storage = \Drupal::entityManager()->getStorage('node'); Chris@0: /** @var \Drupal\node\NodeAccessControlHandlerInterface $access_control_handler */ Chris@0: $access_control_handler = \Drupal::entityManager()->getAccessControlHandler('node'); Chris@0: $access_control_handler->deleteGrants(); Chris@0: // Only recalculate if the site is using a node_access module. Chris@0: if (count(\Drupal::moduleHandler()->getImplementations('node_grants'))) { Chris@0: if ($batch_mode) { Chris@0: $batch = [ Chris@0: 'title' => t('Rebuilding content access permissions'), Chris@0: 'operations' => [ Chris@0: ['_node_access_rebuild_batch_operation', []], Chris@0: ], Chris@17: 'finished' => '_node_access_rebuild_batch_finished', Chris@0: ]; Chris@0: batch_set($batch); Chris@0: } Chris@0: else { Chris@0: // Try to allocate enough time to rebuild node grants Chris@18: Environment::setTimeLimit(240); Chris@0: Chris@0: // Rebuild newest nodes first so that recent content becomes available Chris@0: // quickly. Chris@0: $entity_query = \Drupal::entityQuery('node'); Chris@0: $entity_query->sort('nid', 'DESC'); Chris@0: // Disable access checking since all nodes must be processed even if the Chris@0: // user does not have access. And unless the current user has the bypass Chris@0: // node access permission, no nodes are accessible since the grants have Chris@0: // just been deleted. Chris@0: $entity_query->accessCheck(FALSE); Chris@0: $nids = $entity_query->execute(); Chris@0: foreach ($nids as $nid) { Chris@0: $node_storage->resetCache([$nid]); Chris@0: $node = Node::load($nid); Chris@0: // To preserve database integrity, only write grants if the node Chris@0: // loads successfully. Chris@0: if (!empty($node)) { Chris@0: $grants = $access_control_handler->acquireGrants($node); Chris@0: \Drupal::service('node.grant_storage')->write($node, $grants); Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: else { Chris@0: // Not using any node_access modules. Add the default grant. Chris@0: $access_control_handler->writeDefaultGrant(); Chris@0: } Chris@0: Chris@0: if (!isset($batch)) { Chris@17: \Drupal::messenger()->addStatus(t('Content permissions have been rebuilt.')); Chris@0: node_access_needs_rebuild(FALSE); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements callback_batch_operation(). Chris@0: * Chris@0: * Performs batch operation for node_access_rebuild(). Chris@0: * Chris@0: * This is a multistep operation: we go through all nodes by packs of 20. The Chris@0: * batch processing engine interrupts processing and sends progress feedback Chris@0: * after 1 second execution time. Chris@0: * Chris@0: * @param array $context Chris@0: * An array of contextual key/value information for rebuild batch process. Chris@0: */ Chris@0: function _node_access_rebuild_batch_operation(&$context) { Chris@0: $node_storage = \Drupal::entityManager()->getStorage('node'); Chris@0: if (empty($context['sandbox'])) { Chris@0: // Initiate multistep processing. Chris@0: $context['sandbox']['progress'] = 0; Chris@0: $context['sandbox']['current_node'] = 0; Chris@0: $context['sandbox']['max'] = \Drupal::entityQuery('node')->accessCheck(FALSE)->count()->execute(); Chris@0: } Chris@0: Chris@0: // Process the next 20 nodes. Chris@0: $limit = 20; Chris@0: $nids = \Drupal::entityQuery('node') Chris@0: ->condition('nid', $context['sandbox']['current_node'], '>') Chris@0: ->sort('nid', 'ASC') Chris@0: // Disable access checking since all nodes must be processed even if the Chris@0: // user does not have access. And unless the current user has the bypass Chris@0: // node access permission, no nodes are accessible since the grants have Chris@0: // just been deleted. Chris@0: ->accessCheck(FALSE) Chris@0: ->range(0, $limit) Chris@0: ->execute(); Chris@0: $node_storage->resetCache($nids); Chris@0: $nodes = Node::loadMultiple($nids); Chris@0: foreach ($nodes as $nid => $node) { Chris@0: // To preserve database integrity, only write grants if the node Chris@0: // loads successfully. Chris@0: if (!empty($node)) { Chris@0: /** @var \Drupal\node\NodeAccessControlHandlerInterface $access_control_handler */ Chris@0: $access_control_handler = \Drupal::entityManager()->getAccessControlHandler('node'); Chris@0: $grants = $access_control_handler->acquireGrants($node); Chris@0: \Drupal::service('node.grant_storage')->write($node, $grants); Chris@0: } Chris@0: $context['sandbox']['progress']++; Chris@0: $context['sandbox']['current_node'] = $nid; Chris@0: } Chris@0: Chris@0: // Multistep processing : report progress. Chris@0: if ($context['sandbox']['progress'] != $context['sandbox']['max']) { Chris@0: $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max']; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements callback_batch_finished(). Chris@0: * Chris@0: * Performs post-processing for node_access_rebuild(). Chris@0: * Chris@0: * @param bool $success Chris@0: * A boolean indicating whether the re-build process has completed. Chris@0: * @param array $results Chris@0: * An array of results information. Chris@0: * @param array $operations Chris@0: * An array of function calls (not used in this function). Chris@0: */ Chris@0: function _node_access_rebuild_batch_finished($success, $results, $operations) { Chris@0: if ($success) { Chris@17: \Drupal::messenger()->addStatus(t('The content access permissions have been rebuilt.')); Chris@0: node_access_needs_rebuild(FALSE); Chris@0: } Chris@0: else { Chris@17: \Drupal::messenger()->addError(t('The content access permissions have not been properly rebuilt.')); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * @} End of "defgroup node_access". Chris@0: */ Chris@0: Chris@0: /** Chris@0: * Implements hook_modules_installed(). Chris@0: */ Chris@0: function node_modules_installed($modules) { Chris@0: // Check if any of the newly enabled modules require the node_access table to Chris@0: // be rebuilt. Chris@0: if (!node_access_needs_rebuild() && array_intersect($modules, \Drupal::moduleHandler()->getImplementations('node_grants'))) { Chris@0: node_access_needs_rebuild(TRUE); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_modules_uninstalled(). Chris@0: */ Chris@0: function node_modules_uninstalled($modules) { Chris@0: // Check whether any of the disabled modules implemented hook_node_grants(), Chris@0: // in which case the node access table needs to be rebuilt. Chris@0: foreach ($modules as $module) { Chris@0: // At this point, the module is already disabled, but its code is still Chris@0: // loaded in memory. Module functions must no longer be called. We only Chris@0: // check whether a hook implementation function exists and do not invoke it. Chris@0: // Node access also needs to be rebuilt if language module is disabled to Chris@0: // remove any language-specific grants. Chris@0: if (!node_access_needs_rebuild() && (\Drupal::moduleHandler()->implementsHook($module, 'node_grants') || $module == 'language')) { Chris@0: node_access_needs_rebuild(TRUE); Chris@0: } Chris@0: } Chris@0: Chris@0: // If there remains no more node_access module, rebuilding will be Chris@0: // straightforward, we can do it right now. Chris@0: if (node_access_needs_rebuild() && count(\Drupal::moduleHandler()->getImplementations('node_grants')) == 0) { Chris@0: node_access_rebuild(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'. Chris@0: */ Chris@0: function node_configurable_language_delete(ConfigurableLanguageInterface $language) { Chris@0: // On nodes with this language, unset the language. Chris@0: \Drupal::entityManager()->getStorage('node')->clearRevisionsLanguage($language); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Marks a node to be re-indexed by the node_search plugin. Chris@0: * Chris@0: * @param int $nid Chris@0: * The node ID. Chris@0: */ Chris@0: function node_reindex_node_search($nid) { Chris@0: if (\Drupal::moduleHandler()->moduleExists('search')) { Chris@0: // Reindex node context indexed by the node module search plugin. Chris@0: search_mark_for_reindex('node_search', $nid); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_ENTITY_TYPE_insert() for comment entities. Chris@0: */ Chris@0: function node_comment_insert($comment) { Chris@0: // Reindex the node when comments are added. Chris@0: if ($comment->getCommentedEntityTypeId() == 'node') { Chris@0: node_reindex_node_search($comment->getCommentedEntityId()); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_ENTITY_TYPE_update() for comment entities. Chris@0: */ Chris@0: function node_comment_update($comment) { Chris@0: // Reindex the node when comments are changed. Chris@0: if ($comment->getCommentedEntityTypeId() == 'node') { Chris@0: node_reindex_node_search($comment->getCommentedEntityId()); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_ENTITY_TYPE_delete() for comment entities. Chris@0: */ Chris@0: function node_comment_delete($comment) { Chris@0: // Reindex the node when comments are deleted. Chris@0: if ($comment->getCommentedEntityTypeId() == 'node') { Chris@0: node_reindex_node_search($comment->getCommentedEntityId()); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_config_translation_info_alter(). Chris@0: */ Chris@0: function node_config_translation_info_alter(&$info) { Chris@0: $info['node_type']['class'] = 'Drupal\node\ConfigTranslation\NodeTypeMapper'; Chris@0: }