node.module 51 KB

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