Drupal investigation

node.module 50KB

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