"Fossies" - the Fresh Open Source Software Archive

Member "drupal-8.9.10/core/modules/node/node.api.php" (26 Nov 2020, 17764 Bytes) of package /linux/www/drupal-8.9.10.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) PHP source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 <?php
    2 
    3 /**
    4  * @file
    5  * Hooks specific to the Node module.
    6  */
    7 
    8 use Drupal\node\NodeInterface;
    9 use Drupal\Component\Utility\Html;
   10 use Drupal\Component\Utility\Xss;
   11 
   12 /**
   13  * @addtogroup hooks
   14  * @{
   15  */
   16 
   17 /**
   18  * Inform the node access system what permissions the user has.
   19  *
   20  * This hook is for implementation by node access modules. In this hook,
   21  * the module grants a user different "grant IDs" within one or more
   22  * "realms". In hook_node_access_records(), the realms and grant IDs are
   23  * associated with permission to view, edit, and delete individual nodes.
   24  *
   25  * The realms and grant IDs can be arbitrarily defined by your node access
   26  * module; it is common to use role IDs as grant IDs, but that is not required.
   27  * Your module could instead maintain its own list of users, where each list has
   28  * an ID. In that case, the return value of this hook would be an array of the
   29  * list IDs that this user is a member of.
   30  *
   31  * A node access module may implement as many realms as necessary to properly
   32  * define the access privileges for the nodes. Note that the system makes no
   33  * distinction between published and unpublished nodes. It is the module's
   34  * responsibility to provide appropriate realms to limit access to unpublished
   35  * content.
   36  *
   37  * Node access records are stored in the {node_access} table and define which
   38  * grants are required to access a node. There is a special case for the view
   39  * operation -- a record with node ID 0 corresponds to a "view all" grant for
   40  * the realm and grant ID of that record. If there are no node access modules
   41  * enabled, the core node module adds a node ID 0 record for realm 'all'. Node
   42  * access modules can also grant "view all" permission on their custom realms;
   43  * for example, a module could create a record in {node_access} with:
   44  * @code
   45  * $record = array(
   46  *   'nid' => 0,
   47  *   'gid' => 888,
   48  *   'realm' => 'example_realm',
   49  *   'grant_view' => 1,
   50  *   'grant_update' => 0,
   51  *   'grant_delete' => 0,
   52  * );
   53  * \Drupal::database()->insert('node_access')->fields($record)->execute();
   54  * @endcode
   55  * And then in its hook_node_grants() implementation, it would need to return:
   56  * @code
   57  * if ($op == 'view') {
   58  *   $grants['example_realm'] = array(888);
   59  * }
   60  * @endcode
   61  * If you decide to do this, be aware that the node_access_rebuild() function
   62  * will erase any node ID 0 entry when it is called, so you will need to make
   63  * sure to restore your {node_access} record after node_access_rebuild() is
   64  * called.
   65  *
   66  * For a detailed example, see node_access_example.module.
   67  *
   68  * @param \Drupal\Core\Session\AccountInterface $account
   69  *   The account object whose grants are requested.
   70  * @param string $op
   71  *   The node operation to be performed, such as 'view', 'update', or 'delete'.
   72  *
   73  * @return array
   74  *   An array whose keys are "realms" of grants, and whose values are arrays of
   75  *   the grant IDs within this realm that this user is being granted.
   76  *
   77  * @see node_access_view_all_nodes()
   78  * @see node_access_rebuild()
   79  * @ingroup node_access
   80  */
   81 function hook_node_grants(\Drupal\Core\Session\AccountInterface $account, $op) {
   82   if ($account->hasPermission('access private content')) {
   83     $grants['example'] = [1];
   84   }
   85   if ($account->id()) {
   86     $grants['example_author'] = [$account->id()];
   87   }
   88   return $grants;
   89 }
   90 
   91 /**
   92  * Set permissions for a node to be written to the database.
   93  *
   94  * When a node is saved, a module implementing hook_node_access_records() will
   95  * be asked if it is interested in the access permissions for a node. If it is
   96  * interested, it must respond with an array of permissions arrays for that
   97  * node.
   98  *
   99  * Node access grants apply regardless of the published or unpublished status
  100  * of the node. Implementations must make sure not to grant access to
  101  * unpublished nodes if they don't want to change the standard access control
  102  * behavior. Your module may need to create a separate access realm to handle
  103  * access to unpublished nodes.
  104  *
  105  * Note that the grant values in the return value from your hook must be
  106  * integers and not boolean TRUE and FALSE.
  107  *
  108  * Each permissions item in the array is an array with the following elements:
  109  * - 'realm': The name of a realm that the module has defined in
  110  *   hook_node_grants().
  111  * - 'gid': A 'grant ID' from hook_node_grants().
  112  * - 'grant_view': If set to 1 a user that has been identified as a member
  113  *   of this gid within this realm can view this node. This should usually be
  114  *   set to $node->isPublished(). Failure to do so may expose unpublished content
  115  *   to some users.
  116  * - 'grant_update': If set to 1 a user that has been identified as a member
  117  *   of this gid within this realm can edit this node.
  118  * - 'grant_delete': If set to 1 a user that has been identified as a member
  119  *   of this gid within this realm can delete this node.
  120  * - langcode: (optional) The language code of a specific translation of the
  121  *   node, if any. Modules may add this key to grant different access to
  122  *   different translations of a node, such that (e.g.) a particular group is
  123  *   granted access to edit the Catalan version of the node, but not the
  124  *   Hungarian version. If no value is provided, the langcode is set
  125  *   automatically from the $node parameter and the node's original language (if
  126  *   specified) is used as a fallback. Only specify multiple grant records with
  127  *   different languages for a node if the site has those languages configured.
  128  *
  129  * A "deny all" grant may be used to deny all access to a particular node or
  130  * node translation:
  131  * @code
  132  * $grants[] = array(
  133  *   'realm' => 'all',
  134  *   'gid' => 0,
  135  *   'grant_view' => 0,
  136  *   'grant_update' => 0,
  137  *   'grant_delete' => 0,
  138  *   'langcode' => 'ca',
  139  * );
  140  * @endcode
  141  * Note that another module node access module could override this by granting
  142  * access to one or more nodes, since grants are additive. To enforce that
  143  * access is denied in a particular case, use hook_node_access_records_alter().
  144  * Also note that a deny all is not written to the database; denies are
  145  * implicit.
  146  *
  147  * @param \Drupal\node\NodeInterface $node
  148  *   The node that has just been saved.
  149  *
  150  * @return
  151  *   An array of grants as defined above.
  152  *
  153  * @see hook_node_access_records_alter()
  154  * @ingroup node_access
  155  */
  156 function hook_node_access_records(\Drupal\node\NodeInterface $node) {
  157   // We only care about the node if it has been marked private. If not, it is
  158   // treated just like any other node and we completely ignore it.
  159   if ($node->private->value) {
  160     $grants = [];
  161     // Only published Catalan translations of private nodes should be viewable
  162     // to all users. If we fail to check $node->isPublished(), all users would be able
  163     // to view an unpublished node.
  164     if ($node->isPublished()) {
  165       $grants[] = [
  166         'realm' => 'example',
  167         'gid' => 1,
  168         'grant_view' => 1,
  169         'grant_update' => 0,
  170         'grant_delete' => 0,
  171         'langcode' => 'ca',
  172       ];
  173     }
  174     // For the example_author array, the GID is equivalent to a UID, which
  175     // means there are many groups of just 1 user.
  176     // Note that an author can always view nodes they own, even if they have
  177     // status unpublished.
  178     if ($node->getOwnerId()) {
  179       $grants[] = [
  180         'realm' => 'example_author',
  181         'gid' => $node->getOwnerId(),
  182         'grant_view' => 1,
  183         'grant_update' => 1,
  184         'grant_delete' => 1,
  185         'langcode' => 'ca',
  186       ];
  187     }
  188 
  189     return $grants;
  190   }
  191 }
  192 
  193 /**
  194  * Alter permissions for a node before it is written to the database.
  195  *
  196  * Node access modules establish rules for user access to content. Node access
  197  * records are stored in the {node_access} table and define which permissions
  198  * are required to access a node. This hook is invoked after node access modules
  199  * returned their requirements via hook_node_access_records(); doing so allows
  200  * modules to modify the $grants array by reference before it is stored, so
  201  * custom or advanced business logic can be applied.
  202  *
  203  * Upon viewing, editing or deleting a node, hook_node_grants() builds a
  204  * permissions array that is compared against the stored access records. The
  205  * user must have one or more matching permissions in order to complete the
  206  * requested operation.
  207  *
  208  * A module may deny all access to a node by setting $grants to an empty array.
  209  *
  210  * The preferred use of this hook is in a module that bridges multiple node
  211  * access modules with a configurable behavior, as shown in the example with the
  212  * 'is_preview' field.
  213  *
  214  * @param array $grants
  215  *   The $grants array returned by hook_node_access_records().
  216  * @param \Drupal\node\NodeInterface $node
  217  *   The node for which the grants were acquired.
  218  *
  219  * @see hook_node_access_records()
  220  * @see hook_node_grants()
  221  * @see hook_node_grants_alter()
  222  * @ingroup node_access
  223  */
  224 function hook_node_access_records_alter(&$grants, Drupal\node\NodeInterface $node) {
  225   // Our module allows editors to mark specific articles with the 'is_preview'
  226   // field. If the node being saved has a TRUE value for that field, then only
  227   // our grants are retained, and other grants are removed. Doing so ensures
  228   // that our rules are enforced no matter what priority other grants are given.
  229   if ($node->is_preview) {
  230     // Our module grants are set in $grants['example'].
  231     $temp = $grants['example'];
  232     // Now remove all module grants but our own.
  233     $grants = ['example' => $temp];
  234   }
  235 }
  236 
  237 /**
  238  * Alter user access rules when trying to view, edit or delete a node.
  239  *
  240  * Node access modules establish rules for user access to content.
  241  * hook_node_grants() defines permissions for a user to view, edit or delete
  242  * nodes by building a $grants array that indicates the permissions assigned to
  243  * the user by each node access module. This hook is called to allow modules to
  244  * modify the $grants array by reference, so the interaction of multiple node
  245  * access modules can be altered or advanced business logic can be applied.
  246  *
  247  * The resulting grants are then checked against the records stored in the
  248  * {node_access} table to determine if the operation may be completed.
  249  *
  250  * A module may deny all access to a user by setting $grants to an empty array.
  251  *
  252  * Developers may use this hook to either add additional grants to a user or to
  253  * remove existing grants. These rules are typically based on either the
  254  * permissions assigned to a user role, or specific attributes of a user
  255  * account.
  256  *
  257  * @param array $grants
  258  *   The $grants array returned by hook_node_grants().
  259  * @param \Drupal\Core\Session\AccountInterface $account
  260  *   The account requesting access to content.
  261  * @param string $op
  262  *   The operation being performed, 'view', 'update' or 'delete'.
  263  *
  264  * @see hook_node_grants()
  265  * @see hook_node_access_records()
  266  * @see hook_node_access_records_alter()
  267  * @ingroup node_access
  268  */
  269 function hook_node_grants_alter(&$grants, \Drupal\Core\Session\AccountInterface $account, $op) {
  270   // Our sample module never allows certain roles to edit or delete
  271   // content. Since some other node access modules might allow this
  272   // permission, we expressly remove it by returning an empty $grants
  273   // array for roles specified in our variable setting.
  274 
  275   // Get our list of banned roles.
  276   $restricted = \Drupal::config('example.settings')->get('restricted_roles');
  277 
  278   if ($op != 'view' && !empty($restricted)) {
  279     // Now check the roles for this account against the restrictions.
  280     foreach ($account->getRoles() as $rid) {
  281       if (in_array($rid, $restricted)) {
  282         $grants = [];
  283       }
  284     }
  285   }
  286 }
  287 
  288 /**
  289  * Act on a node being displayed as a search result.
  290  *
  291  * This hook is invoked from the node search plugin during search execution,
  292  * after loading and rendering the node.
  293  *
  294  * @param \Drupal\node\NodeInterface $node
  295  *   The node being displayed in a search result.
  296  *
  297  * @return array
  298  *   Extra information to be displayed with search result. This information
  299  *   should be presented as an associative array. It will be concatenated with
  300  *   the post information (last updated, author) in the default search result
  301  *   theming.
  302  *
  303  * @see template_preprocess_search_result()
  304  * @see search-result.html.twig
  305  *
  306  * @ingroup entity_crud
  307  */
  308 function hook_node_search_result(\Drupal\node\NodeInterface $node) {
  309   $rating = \Drupal::database()->query('SELECT SUM(points) FROM {my_rating} WHERE nid = :nid', ['nid' => $node->id()])->fetchField();
  310   return ['rating' => \Drupal::translation()->formatPlural($rating, '1 point', '@count points')];
  311 }
  312 
  313 /**
  314  * Act on a node being indexed for searching.
  315  *
  316  * This hook is invoked during search indexing, after loading, and after the
  317  * result of rendering is added as $node->rendered to the node object.
  318  *
  319  * @param \Drupal\node\NodeInterface $node
  320  *   The node being indexed.
  321  *
  322  * @return string
  323  *   Additional node information to be indexed.
  324  *
  325  * @ingroup entity_crud
  326  */
  327 function hook_node_update_index(\Drupal\node\NodeInterface $node) {
  328   $text = '';
  329   $ratings = \Drupal::database()->query('SELECT title, description FROM {my_ratings} WHERE nid = :nid', [':nid' => $node->id()]);
  330   foreach ($ratings as $rating) {
  331     $text .= '<h2>' . Html::escape($rating->title) . '</h2>' . Xss::filter($rating->description);
  332   }
  333   return $text;
  334 }
  335 
  336 /**
  337  * Provide additional methods of scoring for core search results for nodes.
  338  *
  339  * A node's search score is used to rank it among other nodes matched by the
  340  * search, with the highest-ranked nodes appearing first in the search listing.
  341  *
  342  * For example, a module allowing users to vote on content could expose an
  343  * option to allow search results' rankings to be influenced by the average
  344  * voting score of a node.
  345  *
  346  * All scoring mechanisms are provided as options to site administrators, and
  347  * may be tweaked based on individual sites or disabled altogether if they do
  348  * not make sense. Individual scoring mechanisms, if enabled, are assigned a
  349  * weight from 1 to 10. The weight represents the factor of magnification of
  350  * the ranking mechanism, with higher-weighted ranking mechanisms having more
  351  * influence. In order for the weight system to work, each scoring mechanism
  352  * must return a value between 0 and 1 for every node. That value is then
  353  * multiplied by the administrator-assigned weight for the ranking mechanism,
  354  * and then the weighted scores from all ranking mechanisms are added, which
  355  * brings about the same result as a weighted average.
  356  *
  357  * @return array
  358  *   An associative array of ranking data. The keys should be strings,
  359  *   corresponding to the internal name of the ranking mechanism, such as
  360  *   'recent', or 'comments'. The values should be arrays themselves, with the
  361  *   following keys available:
  362  *   - title: (required) The human readable name of the ranking mechanism.
  363  *   - join: (optional) An array with information to join any additional
  364  *     necessary table. This is not necessary if the table required is already
  365  *     joined to by the base query, such as for the {node} table. Other tables
  366  *     should use the full table name as an alias to avoid naming collisions.
  367  *   - score: (required) The part of a query string to calculate the score for
  368  *     the ranking mechanism based on values in the database. This does not need
  369  *     to be wrapped in parentheses, as it will be done automatically; it also
  370  *     does not need to take the weighted system into account, as it will be
  371  *     done automatically. It does, however, need to calculate a decimal between
  372  *     0 and 1; be careful not to cast the entire score to an integer by
  373  *     inadvertently introducing a variable argument.
  374  *   - arguments: (optional) If any arguments are required for the score, they
  375  *     can be specified in an array here.
  376  *
  377  * @ingroup entity_crud
  378  */
  379 function hook_ranking() {
  380   // If voting is disabled, we can avoid returning the array, no hard feelings.
  381   if (\Drupal::config('vote.settings')->get('node_enabled')) {
  382     return [
  383       'vote_average' => [
  384         'title' => t('Average vote'),
  385         // Note that we use i.sid, the search index's search item id, rather than
  386         // n.nid.
  387         'join' => [
  388           'type' => 'LEFT',
  389           'table' => 'vote_node_data',
  390           'alias' => 'vote_node_data',
  391           'on' => 'vote_node_data.nid = i.sid',
  392         ],
  393         // The highest possible score should be 1, and the lowest possible score,
  394         // always 0, should be 0.
  395         'score' => 'vote_node_data.average / CAST(%f AS DECIMAL)',
  396         // Pass in the highest possible voting score as a decimal argument.
  397         'arguments' => [\Drupal::config('vote.settings')->get('score_max')],
  398       ],
  399     ];
  400   }
  401 }
  402 
  403 /**
  404  * Alter the links of a node.
  405  *
  406  * @param array &$links
  407  *   A renderable array representing the node links.
  408  * @param \Drupal\node\NodeInterface $entity
  409  *   The node being rendered.
  410  * @param array &$context
  411  *   Various aspects of the context in which the node links are going to be
  412  *   displayed, with the following keys:
  413  *   - 'view_mode': the view mode in which the node is being viewed
  414  *   - 'langcode': the language in which the node is being viewed
  415  *
  416  * @see \Drupal\node\NodeViewBuilder::renderLinks()
  417  * @see \Drupal\node\NodeViewBuilder::buildLinks()
  418  * @see entity_crud
  419  */
  420 function hook_node_links_alter(array &$links, NodeInterface $entity, array &$context) {
  421   $links['mymodule'] = [
  422     '#theme' => 'links__node__mymodule',
  423     '#attributes' => ['class' => ['links', 'inline']],
  424     '#links' => [
  425       'node-report' => [
  426         'title' => t('Report'),
  427         'url' => Url::fromRoute('node_test.report', ['node' => $entity->id()], ['query' => ['token' => \Drupal::getContainer()->get('csrf_token')->get("node/{$entity->id()}/report")]]),
  428       ],
  429     ],
  430   ];
  431 }
  432 
  433 /**
  434  * @} End of "addtogroup hooks".
  435  */