node.module 51 KB

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