node.module

The core module that allows content to be submitted to the site.

Modules and scripts may programmatically submit nodes using the usual form API pattern.

File

drupal/core/modules/node/node.module
View source
  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\Core\Language\Language;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Drupal\Core\Cache\CacheBackendInterface;
  12. use Drupal\Core\Database\Query\AlterableInterface;
  13. use Drupal\Core\Database\Query\SelectExtender;
  14. use Drupal\Core\Database\Query\SelectInterface;
  15. use Drupal\Core\Datetime\DrupalDateTime;
  16. use Drupal\Core\Entity\EntityInterface;
  17. use Drupal\Core\Template\Attribute;
  18. use Drupal\entity\Plugin\Core\Entity\EntityDisplay;
  19. use Drupal\file\Plugin\Core\Entity\File;
  20. use Drupal\user\UserInterface;
  21. /**
  22. * Denotes that the node is not published.
  23. */
  24. const NODE_NOT_PUBLISHED = 0;
  25. /**
  26. * Denotes that the node is published.
  27. */
  28. const NODE_PUBLISHED = 1;
  29. /**
  30. * Denotes that the node is not promoted to the front page.
  31. */
  32. const NODE_NOT_PROMOTED = 0;
  33. /**
  34. * Denotes that the node is promoted to the front page.
  35. */
  36. const NODE_PROMOTED = 1;
  37. /**
  38. * Denotes that the node is not sticky at the top of the page.
  39. */
  40. const NODE_NOT_STICKY = 0;
  41. /**
  42. * Denotes that the node is sticky at the top of the page.
  43. */
  44. const NODE_STICKY = 1;
  45. /**
  46. * Denotes that access is allowed for a node.
  47. *
  48. * Modules should return this value from hook_node_access() to allow access to a
  49. * node.
  50. */
  51. const NODE_ACCESS_ALLOW = TRUE;
  52. /**
  53. * Denotes that access is denied for a node.
  54. *
  55. * Modules should return this value from hook_node_access() to deny access to a
  56. * node.
  57. */
  58. const NODE_ACCESS_DENY = FALSE;
  59. /**
  60. * Denotes that access is unaffected for a node.
  61. *
  62. * Modules should return this value from hook_node_access() to indicate no
  63. * effect on node access.
  64. */
  65. const NODE_ACCESS_IGNORE = NULL;
  66. /**
  67. * Implements hook_rebuild().
  68. */
  69. function node_rebuild() {
  70. node_types_rebuild();
  71. }
  72. /**
  73. * Implements hook_help().
  74. */
  75. function node_help($path, $arg) {
  76. // Remind site administrators about the {node_access} table being flagged
  77. // for rebuild. We don't need to issue the message on the confirm form, or
  78. // while the rebuild is being processed.
  79. if ($path != 'admin/reports/status/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
  80. && user_access('access administration pages') && node_access_needs_rebuild()) {
  81. if ($path == 'admin/reports/status') {
  82. $message = t('The content access permissions need to be rebuilt.');
  83. }
  84. else {
  85. $message = t('The content access permissions need to be rebuilt. <a href="@node_access_rebuild">Rebuild permissions</a>.', array('@node_access_rebuild' => url('admin/reports/status/rebuild')));
  86. }
  87. drupal_set_message($message, 'error');
  88. }
  89. switch ($path) {
  90. case 'admin/help#node':
  91. $output = '';
  92. $output .= '<h3>' . t('About') . '</h3>';
  93. $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 online handbook entry for <a href="@node">Node module</a>.', array('@node' => 'http://drupal.org/documentation/modules/node', '@field' => url('admin/help/field'))) . '</p>';
  94. $output .= '<h3>' . t('Uses') . '</h3>';
  95. $output .= '<dl>';
  96. $output .= '<dt>' . t('Creating content') . '</dt>';
  97. $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.', array('@content-type' => url('admin/structure/types'))) . '</dd>';
  98. $output .= '<dt>' . t('Creating custom content types') . '</dt>';
  99. $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 allows you the flexibility to add <a href="@field">fields</a> and configure default settings that suit the differing needs of various site content.', array('@content-new' => url('admin/structure/types/add'), '@field' => url('admin/help/field'))) . '</dd>';
  100. $output .= '<dt>' . t('Administering content') . '</dt>';
  101. $output .= '<dd>' . t('The <a href="@content">Content administration page</a> allows you to review and bulk manage your site content.', array('@content' => url('admin/content'))) . '</dd>';
  102. $output .= '<dt>' . t('Creating revisions') . '</dt>';
  103. $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>';
  104. $output .= '<dt>' . t('User permissions') . '</dt>';
  105. $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>.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-node')))) . '</dd>';
  106. $output .= '</dl>';
  107. return $output;
  108. case 'admin/structure/types/add':
  109. return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
  110. case 'admin/structure/types/manage/%/display':
  111. 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>' .
  112. '<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.', array('%type' => node_type_get_label($arg[4]))) . '</p>';
  113. case 'node/%/revisions':
  114. return '<p>' . t('Revisions allow you to track differences between multiple versions of your content, and revert back to older versions.') . '</p>';
  115. case 'node/%/edit':
  116. $node = node_load($arg[1]);
  117. $type = node_type_load($node->type);
  118. return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
  119. }
  120. if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
  121. $type = node_type_load($arg[2]);
  122. return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
  123. }
  124. }
  125. /**
  126. * Implements hook_theme().
  127. */
  128. function node_theme() {
  129. return array(
  130. 'node' => array(
  131. 'render element' => 'elements',
  132. 'template' => 'node',
  133. ),
  134. 'node_search_admin' => array(
  135. 'render element' => 'form',
  136. ),
  137. 'node_add_list' => array(
  138. 'variables' => array('content' => NULL),
  139. 'file' => 'node.pages.inc',
  140. ),
  141. 'node_preview' => array(
  142. 'variables' => array('node' => NULL),
  143. 'file' => 'node.pages.inc',
  144. ),
  145. 'node_admin_overview' => array(
  146. 'variables' => array('name' => NULL, 'type' => NULL),
  147. 'file' => 'content_types.inc',
  148. ),
  149. 'node_recent_block' => array(
  150. 'variables' => array('nodes' => NULL),
  151. ),
  152. 'node_recent_content' => array(
  153. 'variables' => array('node' => NULL),
  154. ),
  155. 'node_edit_form' => array(
  156. 'render element' => 'form',
  157. 'template' => 'node-edit-form',
  158. ),
  159. );
  160. }
  161. /**
  162. * Implements hook_entity_bundle_info().
  163. */
  164. function node_entity_bundle_info() {
  165. $bundles = array();
  166. // Bundles must provide a human readable name so we can create help and error
  167. // messages.
  168. node_type_cache_reset();
  169. foreach (node_type_get_names() as $type => $name) {
  170. $bundles['node'][$type]['label'] = $name;
  171. }
  172. return $bundles;
  173. }
  174. /**
  175. * Implements hook_entity_display_alter().
  176. */
  177. function node_entity_display_alter(EntityDisplay $display, $context) {
  178. // Hide field labels in search index.
  179. if ($context['entity_type'] == 'node' && $context['view_mode'] == 'search_index') {
  180. foreach ($display->getComponents() as $name => $options) {
  181. if (isset($options['label'])) {
  182. $options['label'] = 'hidden';
  183. $display->setComponent($name, $options);
  184. }
  185. }
  186. }
  187. }
  188. /**
  189. * Entity URI callback.
  190. *
  191. * @param \Drupal\Core\Entity\EntityInterface $node
  192. * A node entity.
  193. *
  194. * @return array
  195. * An array with 'path' as the key and the path to the node as its value.
  196. */
  197. function node_uri(EntityInterface $node) {
  198. return array(
  199. 'path' => 'node/' . $node->nid->value,
  200. );
  201. }
  202. /**
  203. * Implements hook_admin_paths().
  204. */
  205. function node_admin_paths() {
  206. if (variable_get('node_admin_theme')) {
  207. $paths = array(
  208. 'node/*/edit' => TRUE,
  209. 'node/*/delete' => TRUE,
  210. 'node/*/revisions' => TRUE,
  211. 'node/*/revisions/*/revert' => TRUE,
  212. 'node/*/revisions/*/delete' => TRUE,
  213. 'node/*/translations' => TRUE,
  214. 'node/*/translations/*' => TRUE,
  215. 'node/add' => TRUE,
  216. 'node/add/*' => TRUE,
  217. );
  218. return $paths;
  219. }
  220. }
  221. /**
  222. * Gathers a listing of links to nodes.
  223. *
  224. * @param $result
  225. * A database result object from a query to fetch node entities. If your
  226. * query joins the {node_comment_statistics} table so that the comment_count
  227. * field is available, a title attribute will be added to show the number of
  228. * comments.
  229. * @param $title
  230. * (optional) A heading for the resulting list.
  231. *
  232. * @return
  233. * A renderable array containing a list of linked node titles fetched from
  234. * $result, or FALSE if there are no rows in $result.
  235. */
  236. function node_title_list($result, $title = NULL) {
  237. $items = array();
  238. $num_rows = FALSE;
  239. foreach ($result as $node) {
  240. // Do not use $node->label() here, because $node comes from the database.
  241. $items[] = l($node->title, 'node/' . $node->nid, !empty($node->comment_count) ? array('attributes' => array('title' => format_plural($node->comment_count, '1 comment', '@count comments'))) : array());
  242. $num_rows = TRUE;
  243. }
  244. return $num_rows ? array('#theme' => 'item_list__node', '#items' => $items, '#title' => $title) : FALSE;
  245. }
  246. /**
  247. * Determines the type of marker to be displayed for a given node.
  248. *
  249. * @param $nid
  250. * Node ID whose history supplies the "last viewed" timestamp.
  251. * @param $timestamp
  252. * Time which is compared against node's "last viewed" timestamp.
  253. *
  254. * @return
  255. * One of the MARK constants.
  256. */
  257. function node_mark($nid, $timestamp) {
  258. global $user;
  259. $cache = &drupal_static(__FUNCTION__, array());
  260. if (!$user->uid || !module_exists('history')) {
  261. return MARK_READ;
  262. }
  263. if (!isset($cache[$nid])) {
  264. $cache[$nid] = history_read($nid);
  265. }
  266. if ($cache[$nid] == 0 && $timestamp > HISTORY_READ_LIMIT) {
  267. return MARK_NEW;
  268. }
  269. elseif ($timestamp > $cache[$nid] && $timestamp > HISTORY_READ_LIMIT) {
  270. return MARK_UPDATED;
  271. }
  272. return MARK_READ;
  273. }
  274. /**
  275. * Returns a list of all the available node types.
  276. *
  277. * This list can include types that are queued for addition or deletion.
  278. * See _node_types_build() for details.
  279. *
  280. * @return
  281. * An array of node types, as objects, keyed by the type.
  282. *
  283. * @see _node_types_build()
  284. * @see node_type_load()
  285. */
  286. function node_type_get_types() {
  287. return _node_types_build()->types;
  288. }
  289. /**
  290. * Returns the node type base of the passed node or node type string.
  291. *
  292. * The base indicates which module implements this node type and is used to
  293. * execute node-type-specific hooks. For types defined in the user interface
  294. * and managed by node.module, the base is 'node_content'.
  295. *
  296. * @param string $type
  297. * A string that indicates the node type to return.
  298. *
  299. * @return string|false
  300. * The node type base or FALSE if the node type is not found.
  301. *
  302. * @see node_invoke()
  303. */
  304. function node_type_get_base($type) {
  305. $types = _node_types_build()->types;
  306. return isset($types[$type]) && isset($types[$type]->base) ? $types[$type]->base : FALSE;
  307. }
  308. /**
  309. * Returns a list of available node type names.
  310. *
  311. * This list can include types that are queued for addition or deletion.
  312. * See _node_types_build() for details.
  313. *
  314. * @return
  315. * An array of node type labels, keyed by the node type name.
  316. *
  317. * @see _node_types_build()
  318. */
  319. function node_type_get_names() {
  320. return _node_types_build()->names;
  321. }
  322. /**
  323. * Returns the node type label for the passed node type name.
  324. *
  325. * @param string $name
  326. * The machine name of a node type.
  327. *
  328. * @return string|false
  329. * The node type label or FALSE if the node type is not found.
  330. */
  331. function node_type_get_label($name) {
  332. $types = _node_types_build()->names;
  333. return isset($types[$name]) ? $types[$name] : FALSE;
  334. }
  335. /**
  336. * Returns the node type label for the passed node.
  337. *
  338. * @param \Drupal\Core\Entity\EntityInterface $node
  339. * A node entity to return the node type's label for.
  340. *
  341. * @return string|false
  342. * The node type label or FALSE if the node type is not found.
  343. */
  344. function node_get_type_label(EntityInterface $node) {
  345. $types = _node_types_build()->names;
  346. return isset($types[$node->type]) ? $types[$node->type] : FALSE;
  347. }
  348. /**
  349. * Title callback: Returns the sanitized node type name.
  350. *
  351. * @param $node_type
  352. * The node type object.
  353. *
  354. * @return
  355. * The node type name that is safe for printing.
  356. */
  357. function node_type_get_clean_name($node_type) {
  358. return check_plain($node_type->name);
  359. }
  360. /**
  361. * Description callback: Returns the node type description.
  362. *
  363. * @param $node_type
  364. * The node type object.
  365. *
  366. * @return
  367. * The node type description.
  368. */
  369. function node_type_get_description($node_type) {
  370. return $node_type->description;
  371. }
  372. /**
  373. * Updates the database cache of node types.
  374. *
  375. * All new module-defined node types are saved to the database via a call to
  376. * node_type_save(), and obsolete ones are deleted via a call to
  377. * node_type_delete(). See _node_types_build() for an explanation of the new
  378. * and obsolete types.
  379. *
  380. * @see _node_types_build()
  381. */
  382. function node_types_rebuild() {
  383. _node_types_build(TRUE);
  384. }
  385. /**
  386. * Menu argument loader: Loads a node type by string.
  387. *
  388. * @param $name
  389. * The machine name of a node type to load.
  390. *
  391. * @return
  392. * A node type object or FALSE if $name does not exist.
  393. */
  394. function node_type_load($name) {
  395. $types = _node_types_build()->types;
  396. return isset($types[$name]) ? $types[$name] : FALSE;
  397. }
  398. /**
  399. * Saves a node type to the database.
  400. *
  401. * @param object $info
  402. * The node type to save; an object with the following properties:
  403. * - type: A string giving the machine name of the node type.
  404. * - name: A string giving the human-readable name of the node type.
  405. * - base: A string that indicates the base string for hook functions. For
  406. * example, 'node_content' is the value used by the UI when creating a new
  407. * node type.
  408. * - description: A string that describes the node type.
  409. * - help: A string giving the help information shown to the user when
  410. * creating a node of this type.
  411. * - custom: TRUE or FALSE indicating whether this type is defined by a module
  412. * (FALSE) or by a user (TRUE) via Add Content Type.
  413. * - modified: TRUE or FALSE indicating whether this type has been modified by
  414. * an administrator. Currently not used in any way.
  415. * - locked: TRUE or FALSE indicating whether the administrator can change the
  416. * machine name of this type.
  417. * - disabled: TRUE or FALSE indicating whether this type has been disabled.
  418. * - has_title: TRUE or FALSE indicating whether this type uses the node title
  419. * field.
  420. * - title_label: A string containing the label for the title.
  421. * - module: A string giving the module defining this type of node.
  422. * - orig_type: A string giving the original machine-readable name of this
  423. * node type. This may be different from the current type name if the locked
  424. * field is 0.
  425. *
  426. * @return int
  427. * A status flag indicating the outcome of the operation, either SAVED_NEW or
  428. * SAVED_UPDATED.
  429. */
  430. function node_type_save($info) {
  431. $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
  432. $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', 0, 1, array(':type' => $existing_type))->fetchField();
  433. $type = node_type_set_defaults($info);
  434. $fields = array(
  435. 'type' => (string) $type->type,
  436. 'name' => (string) $type->name,
  437. 'base' => (string) $type->base,
  438. 'has_title' => (int) $type->has_title,
  439. 'title_label' => (string) $type->title_label,
  440. 'description' => (string) $type->description,
  441. 'help' => (string) $type->help,
  442. 'custom' => (int) $type->custom,
  443. 'modified' => (int) $type->modified,
  444. 'locked' => (int) $type->locked,
  445. 'disabled' => (int) $type->disabled,
  446. 'module' => $type->module,
  447. );
  448. if ($is_existing) {
  449. db_update('node_type')
  450. ->fields($fields)
  451. ->condition('type', $existing_type)
  452. ->execute();
  453. if (!empty($type->old_type) && $type->old_type != $type->type) {
  454. entity_invoke_bundle_hook('rename', 'node', $type->old_type, $type->type);
  455. }
  456. module_invoke_all('node_type_update', $type);
  457. $status = SAVED_UPDATED;
  458. }
  459. else {
  460. $fields['orig_type'] = (string) $type->orig_type;
  461. db_insert('node_type')
  462. ->fields($fields)
  463. ->execute();
  464. entity_invoke_bundle_hook('create', 'node', $type->type);
  465. module_invoke_all('node_type_insert', $type);
  466. $status = SAVED_NEW;
  467. }
  468. // Clear the node type cache.
  469. node_type_cache_reset();
  470. return $status;
  471. }
  472. /**
  473. * Adds the default body field to a node type.
  474. *
  475. * @param $type
  476. * A node type object.
  477. * @param $label
  478. * (optional) The label for the body instance.
  479. *
  480. * @return
  481. * Body field instance.
  482. */
  483. function node_add_body_field($type, $label = 'Body') {
  484. // Add or remove the body field, as needed.
  485. $field = field_info_field('body');
  486. $instance = field_info_instance('node', 'body', $type->type);
  487. if (empty($field)) {
  488. $field = array(
  489. 'field_name' => 'body',
  490. 'type' => 'text_with_summary',
  491. 'entity_types' => array('node'),
  492. );
  493. $field = field_create_field($field);
  494. }
  495. if (empty($instance)) {
  496. $instance = array(
  497. 'field_name' => 'body',
  498. 'entity_type' => 'node',
  499. 'bundle' => $type->type,
  500. 'label' => $label,
  501. 'settings' => array('display_summary' => TRUE),
  502. );
  503. $instance = field_create_instance($instance);
  504. // Assign widget settings for the 'default' form mode.
  505. entity_get_form_display('node', $type->type, 'default')
  506. ->setComponent($field['field_name'], array(
  507. 'type' => 'text_textarea_with_summary',
  508. ))
  509. ->save();
  510. // Assign display settings for the 'default' and 'teaser' view modes.
  511. entity_get_display('node', $type->type, 'default')
  512. ->setComponent($field['field_name'], array(
  513. 'label' => 'hidden',
  514. 'type' => 'text_default',
  515. ))
  516. ->save();
  517. entity_get_display('node', $type->type, 'teaser')
  518. ->setComponent($field['field_name'], array(
  519. 'label' => 'hidden',
  520. 'type' => 'text_summary_or_trimmed',
  521. ))
  522. ->save();
  523. }
  524. return $instance;
  525. }
  526. /**
  527. * Implements hook_field_extra_fields().
  528. */
  529. function node_field_extra_fields() {
  530. $extra = array();
  531. $module_language_enabled = module_exists('language');
  532. $description = t('Node module element');
  533. foreach (node_type_get_types() as $bundle) {
  534. if ($bundle->has_title) {
  535. $extra['node'][$bundle->type]['form']['title'] = array(
  536. 'label' => $bundle->title_label,
  537. 'description' => $description,
  538. 'weight' => -5,
  539. );
  540. }
  541. // Add also the 'language' select if Language module is enabled and the
  542. // bundle has multilingual support.
  543. // Visibility of the ordering of the language selector is the same as on the
  544. // node/add form.
  545. if ($module_language_enabled) {
  546. $configuration = language_get_default_configuration('node', $bundle->type);
  547. if ($configuration['language_show']) {
  548. $extra['node'][$bundle->type]['form']['language'] = array(
  549. 'label' => t('Language'),
  550. 'description' => $description,
  551. 'weight' => 0,
  552. );
  553. }
  554. }
  555. $extra['node'][$bundle->type]['display']['language'] = array(
  556. 'label' => t('Language'),
  557. 'description' => $description,
  558. 'weight' => 0,
  559. 'visible' => FALSE,
  560. );
  561. }
  562. return $extra;
  563. }
  564. /**
  565. * Deletes a node type from the database.
  566. *
  567. * @param $name
  568. * The machine name of the node type to delete.
  569. */
  570. function node_type_delete($name) {
  571. $type = node_type_load($name);
  572. db_delete('node_type')
  573. ->condition('type', $name)
  574. ->execute();
  575. entity_invoke_bundle_hook('delete', 'node', $name);
  576. module_invoke_all('node_type_delete', $type);
  577. // Clear the node type cache.
  578. node_type_cache_reset();
  579. }
  580. /**
  581. * Updates all nodes of one type to be of another type.
  582. *
  583. * @param $old_type
  584. * The current node type of the nodes.
  585. * @param $type
  586. * The new node type of the nodes.
  587. *
  588. * @return
  589. * The number of nodes whose node type field was modified.
  590. */
  591. function node_type_update_nodes($old_type, $type) {
  592. return db_update('node')
  593. ->fields(array('type' => $type))
  594. ->condition('type', $old_type)
  595. ->execute();
  596. }
  597. /**
  598. * Builds and returns the list of available node types.
  599. *
  600. * The list of types is built by invoking hook_node_info() on all modules and
  601. * comparing this information with the node types in the {node_type} table.
  602. * These two information sources are not synchronized during module installation
  603. * until node_types_rebuild() is called.
  604. *
  605. * @param $rebuild
  606. * (optional) TRUE to rebuild node types. Equivalent to calling
  607. * node_types_rebuild(). Defaults to FALSE.
  608. *
  609. * @return
  610. * An object with two properties:
  611. * - names: Associative array of the names of node types, keyed by the type.
  612. * - types: Associative array of node type objects, keyed by the type.
  613. * Both of these arrays will include new types that have been defined by
  614. * hook_node_info() implementations but not yet saved in the {node_type}
  615. * table. These are indicated in the type object by $type->is_new being set
  616. * to the value 1. These arrays will also include obsolete types: types that
  617. * were previously defined by modules that have now been disabled, or for
  618. * whatever reason are no longer being defined in hook_node_info()
  619. * implementations, but are still in the database. These are indicated in the
  620. * type object by $type->disabled being set to TRUE.
  621. */
  622. function _node_types_build($rebuild = FALSE) {
  623. $cid = 'node_types:' . language(Language::TYPE_INTERFACE)->langcode;
  624. if (!$rebuild) {
  625. $_node_types = &drupal_static(__FUNCTION__);
  626. if (isset($_node_types)) {
  627. return $_node_types;
  628. }
  629. if ($cache = cache()->get($cid)) {
  630. $_node_types = $cache->data;
  631. return $_node_types;
  632. }
  633. }
  634. $_node_types = (object) array('types' => array(), 'names' => array());
  635. foreach (module_implements('node_info') as $module) {
  636. $info_array = module_invoke($module, 'node_info');
  637. foreach ($info_array as $type => $info) {
  638. $info['type'] = $type;
  639. $_node_types->types[$type] = node_type_set_defaults($info);
  640. $_node_types->types[$type]->module = $module;
  641. $_node_types->names[$type] = $info['name'];
  642. }
  643. }
  644. $query = db_select('node_type', 'nt')
  645. ->addTag('node_type_access')
  646. ->fields('nt')
  647. ->orderBy('nt.type', 'ASC');
  648. if (!$rebuild) {
  649. $query->condition('disabled', 0);
  650. }
  651. foreach ($query->execute() as $type_object) {
  652. $type_db = $type_object->type;
  653. // Original disabled value.
  654. $disabled = $type_object->disabled;
  655. // Check for node types from disabled modules and mark their types for removal.
  656. // Types defined by the node module in the database (rather than by a separate
  657. // module using hook_node_info) have a base value of 'node_content'. The isset()
  658. // check prevents errors on old (pre-Drupal 7) databases.
  659. if (isset($type_object->base) && $type_object->base != 'node_content' && empty($_node_types->types[$type_db])) {
  660. $type_object->disabled = TRUE;
  661. }
  662. if (isset($_node_types->types[$type_db])) {
  663. $type_object->disabled = FALSE;
  664. }
  665. if (!isset($_node_types->types[$type_db]) || $type_object->modified) {
  666. $_node_types->types[$type_db] = $type_object;
  667. $_node_types->names[$type_db] = $type_object->name;
  668. if ($type_db != $type_object->orig_type) {
  669. unset($_node_types->types[$type_object->orig_type]);
  670. unset($_node_types->names[$type_object->orig_type]);
  671. }
  672. }
  673. $_node_types->types[$type_db]->disabled = $type_object->disabled;
  674. $_node_types->types[$type_db]->disabled_changed = $disabled != $type_object->disabled;
  675. }
  676. if ($rebuild) {
  677. foreach ($_node_types->types as $type => $type_object) {
  678. if (!empty($type_object->is_new) || !empty($type_object->disabled_changed)) {
  679. node_type_save($type_object);
  680. }
  681. }
  682. }
  683. asort($_node_types->names);
  684. cache()->set($cid, $_node_types, CacheBackendInterface::CACHE_PERMANENT, array('node_types' => TRUE));
  685. return $_node_types;
  686. }
  687. /**
  688. * Clears the node type cache.
  689. */
  690. function node_type_cache_reset() {
  691. cache()->deleteTags(array('node_types' => TRUE));
  692. drupal_static_reset('_node_types_build');
  693. }
  694. /**
  695. * Sets the default values for a node type.
  696. *
  697. * The defaults are appropriate for a type defined through hook_node_info(),
  698. * since 'custom' is TRUE for types defined in the user interface, and FALSE
  699. * for types defined by modules. (The 'custom' flag prevents types from being
  700. * deleted through the user interface.) Also, the default for 'locked' is TRUE,
  701. * which prevents users from changing the machine name of the type.
  702. *
  703. * @param $info
  704. * (optional) An object or array containing values to override the defaults.
  705. * See hook_node_info() for details on what the array elements mean. Defaults
  706. * to an empty array.
  707. *
  708. * @return
  709. * A node type object, with missing values in $info set to their defaults.
  710. *
  711. * @see hook_node_info()
  712. */
  713. function node_type_set_defaults($info = array()) {
  714. $info = (array) $info;
  715. $new_type = $info + array(
  716. 'type' => '',
  717. 'name' => '',
  718. 'base' => '',
  719. 'description' => '',
  720. 'help' => '',
  721. 'custom' => 0,
  722. 'modified' => 0,
  723. 'locked' => 1,
  724. 'disabled' => 0,
  725. 'is_new' => 1,
  726. 'has_title' => 1,
  727. 'title_label' => 'Title',
  728. );
  729. $new_type = (object) $new_type;
  730. // If the type has no title, set an empty label.
  731. if (!$new_type->has_title) {
  732. $new_type->title_label = '';
  733. }
  734. if (empty($new_type->module)) {
  735. $new_type->module = $new_type->base == 'node_content' ? 'node' : '';
  736. }
  737. $new_type->orig_type = isset($info['type']) ? $info['type'] : '';
  738. return $new_type;
  739. }
  740. /**
  741. * Implements hook_rdf_mapping().
  742. */
  743. function node_rdf_mapping() {
  744. return array(
  745. array(
  746. 'type' => 'node',
  747. 'bundle' => RDF_DEFAULT_BUNDLE,
  748. 'mapping' => array(
  749. 'rdftype' => array('sioc:Item', 'foaf:Document'),
  750. 'title' => array(
  751. 'predicates' => array('dc:title'),
  752. ),
  753. 'created' => array(
  754. 'predicates' => array('dc:date', 'dc:created'),
  755. 'datatype' => 'xsd:dateTime',
  756. 'callback' => 'date_iso8601',
  757. ),
  758. 'changed' => array(
  759. 'predicates' => array('dc:modified'),
  760. 'datatype' => 'xsd:dateTime',
  761. 'callback' => 'date_iso8601',
  762. ),
  763. 'body' => array(
  764. 'predicates' => array('content:encoded'),
  765. ),
  766. 'uid' => array(
  767. 'predicates' => array('sioc:has_creator'),
  768. 'type' => 'rel',
  769. ),
  770. 'name' => array(
  771. 'predicates' => array('foaf:name'),
  772. ),
  773. 'comment_count' => array(
  774. 'predicates' => array('sioc:num_replies'),
  775. 'datatype' => 'xsd:integer',
  776. ),
  777. 'last_activity' => array(
  778. 'predicates' => array('sioc:last_activity_date'),
  779. 'datatype' => 'xsd:dateTime',
  780. 'callback' => 'date_iso8601',
  781. ),
  782. ),
  783. ),
  784. );
  785. }
  786. /**
  787. * Determines whether a node hook exists.
  788. *
  789. * @param string $type
  790. * A string containing the node type.
  791. * @param $hook
  792. * A string containing the name of the hook.
  793. *
  794. * @return string|false
  795. * A string containing the function name or FALSE if it isn't found.
  796. */
  797. function node_hook($type, $hook) {
  798. $base = node_type_get_base($type);
  799. return module_hook($base, $hook) ? $base . '_' . $hook : FALSE;
  800. }
  801. /**
  802. * Invokes a node hook.
  803. *
  804. * @param \Drupal\Core\Entity\EntityInterface $node
  805. * A Node entity.
  806. * @param $hook
  807. * A string containing the name of the hook.
  808. * @param $a2, $a3, $a4
  809. * (optional) Arguments to pass on to the hook, after the $node argument. All
  810. * default to NULL.
  811. *
  812. * @return
  813. * The returned value of the invoked hook.
  814. */
  815. function node_invoke(EntityInterface $node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
  816. if ($function = node_hook($node->type, $hook)) {
  817. return $function($node, $a2, $a3, $a4);
  818. }
  819. }
  820. /**
  821. * Loads node entities from the database.
  822. *
  823. * This function should be used whenever you need to load more than one node
  824. * from the database. Nodes are loaded into memory and will not require database
  825. * access if loaded again during the same page request.
  826. *
  827. * @param array $nids
  828. * (optional) An array of entity IDs. If omitted, all entities are loaded.
  829. * @param bool $reset
  830. * (optional) Whether to reset the internal node_load() cache. Defaults to
  831. * FALSE.
  832. *
  833. * @return array
  834. * An array of node entities indexed by nid.
  835. *
  836. * @see entity_load_multiple()
  837. * @see Drupal\Core\Entity\Query\EntityQueryInterface
  838. */
  839. function node_load_multiple(array $nids = NULL, $reset = FALSE) {
  840. $entities = entity_load_multiple('node', $nids, $reset);
  841. // Return BC-entities.
  842. foreach ($entities as $id => $entity) {
  843. $entities[$id] = $entity->getBCEntity();
  844. }
  845. return $entities;
  846. }
  847. /**
  848. * Loads a node entity from the database.
  849. *
  850. * @param int $nid
  851. * The node ID.
  852. * @param bool $reset
  853. * (optional) Whether to reset the node_load_multiple() cache. Defaults to
  854. * FALSE.
  855. *
  856. * @return Drupal\node\Node|false
  857. * A fully-populated node entity, or FALSE if the node is not found.
  858. */
  859. function node_load($nid = NULL, $reset = FALSE) {
  860. $entity = entity_load('node', $nid, $reset);
  861. return $entity ? $entity->getBCEntity() : FALSE;
  862. }
  863. /**
  864. * Loads a node revision from the database.
  865. *
  866. * @param int $nid
  867. * The node revision id.
  868. *
  869. * @return Drupal\node\Node|false
  870. * A fully-populated node entity, or FALSE if the node is not found.
  871. */
  872. function node_revision_load($vid = NULL) {
  873. return entity_revision_load('node', $vid);
  874. }
  875. /**
  876. * Prepares a node for saving by populating the author and creation date.
  877. *
  878. * @param \Drupal\Core\Entity\EntityInterface $node
  879. * A node object.
  880. *
  881. * @return Drupal\node\Node
  882. * An updated node object.
  883. */
  884. function node_submit(EntityInterface $node) {
  885. global $user;
  886. // A user might assign the node author by entering a user name in the node
  887. // form, which we then need to translate to a user ID.
  888. if (isset($node->name)) {
  889. if ($account = user_load_by_name($node->name)) {
  890. $node->uid = $account->uid;
  891. }
  892. else {
  893. $node->uid = 0;
  894. }
  895. }
  896. // If a new revision is created, save the current user as revision author.
  897. if ($node->isNewRevision()) {
  898. $node->revision_uid = $user->uid;
  899. $node->revision_timestamp = REQUEST_TIME;
  900. }
  901. $node->created = !empty($node->date) && $node->date instanceOf DrupalDateTime ? $node->date->getTimestamp() : REQUEST_TIME;
  902. $node->validated = TRUE;
  903. return $node;
  904. }
  905. /**
  906. * Deletes a node revision.
  907. *
  908. * @param $revision_id
  909. * The revision ID to delete.
  910. *
  911. * @return
  912. * TRUE if the revision deletion was successful; otherwise, FALSE.
  913. */
  914. function node_revision_delete($revision_id) {
  915. entity_revision_delete('node', $revision_id);
  916. }
  917. /**
  918. * Page callback: Generates an array which displays a node detail page.
  919. *
  920. * @param \Drupal\Core\Entity\EntityInterface $node
  921. * A node entity.
  922. * @param $message
  923. * (optional) A flag which sets a page title relevant to the revision being
  924. * viewed. Default is FALSE.
  925. *
  926. * @return
  927. * A $page element suitable for use by drupal_render().
  928. *
  929. * @see node_menu()
  930. */
  931. function node_show(EntityInterface $node, $message = FALSE) {
  932. if ($message) {
  933. drupal_set_title(t('Revision of %title from %date', array('%title' => $node->label(), '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
  934. }
  935. // For markup consistency with other pages, use node_view_multiple() rather than node_view().
  936. $nodes = array('nodes' => node_view_multiple(array($node->nid => $node), 'full'));
  937. // Update the history table, stating that this user viewed this node.
  938. if (module_exists('history')) {
  939. history_write($node->nid);
  940. }
  941. return $nodes;
  942. }
  943. /**
  944. * Checks whether the current page is the full page view of the passed-in node.
  945. *
  946. * @param \Drupal\Core\Entity\EntityInterface $node
  947. * A node entity.
  948. *
  949. * @return
  950. * The ID of the node if this is a full page view, otherwise FALSE.
  951. */
  952. function node_is_page(EntityInterface $node) {
  953. $page_node = menu_get_object();
  954. return (!empty($page_node) ? $page_node->nid == $node->nid : FALSE);
  955. }
  956. /**
  957. * Implements hook_preprocess_HOOK() for block.html.twig.
  958. */
  959. function node_preprocess_block(&$variables) {
  960. if ($variables['configuration']['module'] == 'node') {
  961. switch ($variables['elements']['#plugin_id']) {
  962. case 'node_syndicate_block':
  963. $variables['attributes']['role'] = 'complementary';
  964. break;
  965. case 'node_recent_block':
  966. $variables['attributes']['role'] = 'navigation';
  967. break;
  968. }
  969. }
  970. }
  971. /**
  972. * Prepares variables for node templates.
  973. *
  974. * Default template: node.html.twig.
  975. *
  976. * Most themes utilize their own copy of node.html.twig. The default is located
  977. * inside "/core/modules/node/templates/node.html.twig". Look in there for the full
  978. * list of variables.
  979. *
  980. * @param array $variables
  981. * An associative array containing:
  982. * - elements: An array of elements to display in view mode.
  983. * - node: The node object.
  984. * - view_mode: View mode; e.g., 'full', 'teaser'...
  985. */
  986. function template_preprocess_node(&$variables) {
  987. $variables['view_mode'] = $variables['elements']['#view_mode'];
  988. // Provide a distinct $teaser boolean.
  989. $variables['teaser'] = $variables['view_mode'] == 'teaser';
  990. $variables['node'] = $variables['elements']['#node'];
  991. $node = $variables['node'];
  992. $variables['date'] = format_date($node->created);
  993. // @todo Change 'name' to 'author' and also convert to a render array pending
  994. // http://drupal.org/node/1941286.
  995. $username = array(
  996. '#theme' => 'username',
  997. '#account' => $node,
  998. '#link_options' => array('attributes' => array('rel' => 'author')),
  999. );
  1000. $variables['name'] = drupal_render($username);
  1001. $uri = $node->uri();
  1002. $variables['node_url'] = url($uri['path'], $uri['options']);
  1003. $variables['label'] = check_plain($node->label());
  1004. $variables['page'] = $variables['view_mode'] == 'full' && node_is_page($node);
  1005. // Helpful $content variable for templates.
  1006. $variables += array('content' => array());
  1007. foreach (element_children($variables['elements']) as $key) {
  1008. $variables['content'][$key] = $variables['elements'][$key];
  1009. }
  1010. // Make the field variables available with the appropriate language.
  1011. field_attach_preprocess($node, $variables['content'], $variables);
  1012. // Display post information only on certain node types.
  1013. if (variable_get('node_submitted_' . $node->type, TRUE)) {
  1014. $variables['display_submitted'] = TRUE;
  1015. $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
  1016. if (theme_get_setting('features.node_user_picture')) {
  1017. // To change user picture settings (e.g. image style), edit the 'compact'
  1018. // view mode on the User entity. Note that the 'compact' view mode might
  1019. // not be configured, so remember to always check the theme setting first.
  1020. $variables['user_picture'] = user_view($node->account, 'compact');
  1021. }
  1022. else {
  1023. $variables['user_picture'] = array();
  1024. }
  1025. }
  1026. else {
  1027. $variables['display_submitted'] = FALSE;
  1028. $variables['submitted'] = '';
  1029. $variables['user_picture'] = '';
  1030. }
  1031. // Add article ARIA role.
  1032. $variables['attributes']['role'] = 'article';
  1033. // Gather node classes.
  1034. $variables['attributes']['class'][] = 'node';
  1035. $variables['attributes']['class'][] = drupal_html_class('node-' . $node->type);
  1036. if ($node->promote) {
  1037. $variables['attributes']['class'][] = 'promoted';
  1038. }
  1039. if ($node->sticky) {
  1040. $variables['attributes']['class'][] = 'sticky';
  1041. }
  1042. if (!$node->status) {
  1043. $variables['attributes']['class'][] = 'unpublished';
  1044. }
  1045. if ($variables['view_mode']) {
  1046. $variables['attributes']['class'][] = drupal_html_class('view-mode-' . $variables['view_mode']);
  1047. }
  1048. if (isset($variables['preview'])) {
  1049. $variables['attributes']['class'][] = 'preview';
  1050. }
  1051. // Clean up name so there are no underscores.
  1052. $variables['theme_hook_suggestions'][] = 'node__' . $node->type;
  1053. $variables['theme_hook_suggestions'][] = 'node__' . $node->nid;
  1054. $variables['content_attributes']['class'][] = 'content';
  1055. }
  1056. /**
  1057. * Implements hook_permission().
  1058. */
  1059. function node_permission() {
  1060. $perms = array(
  1061. 'bypass node access' => array(
  1062. 'title' => t('Bypass content access control'),
  1063. 'description' => t('View, edit and delete all content regardless of permission restrictions.'),
  1064. 'restrict access' => TRUE,
  1065. ),
  1066. 'administer content types' => array(
  1067. 'title' => t('Administer content types'),
  1068. 'restrict access' => TRUE,
  1069. ),
  1070. 'administer nodes' => array(
  1071. 'title' => t('Administer content'),
  1072. 'restrict access' => TRUE,
  1073. ),
  1074. 'access content overview' => array(
  1075. 'title' => t('Access the Content overview page'),
  1076. 'description' => user_access('access content overview')
  1077. ? t('Get an overview of <a href="@url">all content</a>.', array('@url' => url('admin/content')))
  1078. : t('Get an overview of all content.'),
  1079. ),
  1080. 'access content' => array(
  1081. 'title' => t('View published content'),
  1082. ),
  1083. 'view own unpublished content' => array(
  1084. 'title' => t('View own unpublished content'),
  1085. ),
  1086. 'view all revisions' => array(
  1087. 'title' => t('View all revisions'),
  1088. ),
  1089. 'revert all revisions' => array(
  1090. 'title' => t('Revert all revisions'),
  1091. 'description' => t('Role requires permission <em>view revisions</em> and <em>edit rights</em> for nodes in question, or <em>administer nodes</em>.'),
  1092. ),
  1093. 'delete all revisions' => array(
  1094. 'title' => t('Delete all revisions'),
  1095. 'description' => t('Role requires permission to <em>view revisions</em> and <em>delete rights</em> for nodes in question, or <em>administer nodes</em>.'),
  1096. ),
  1097. );
  1098. // Generate standard node permissions for all applicable node types.
  1099. foreach (node_permissions_get_configured_types() as $name => $type) {
  1100. $perms += node_list_permissions($type);
  1101. }
  1102. return $perms;
  1103. }
  1104. /**
  1105. * Gathers the rankings from the the hook_ranking() implementations.
  1106. *
  1107. * @param $query
  1108. * A query object that has been extended with the Search DB Extender.
  1109. */
  1110. function _node_rankings(SelectExtender $query) {
  1111. if ($ranking = module_invoke_all('ranking')) {
  1112. $tables = &$query->getTables();
  1113. foreach ($ranking as $rank => $values) {
  1114. if ($node_rank = variable_get('node_rank_' . $rank, 0)) {
  1115. // If the table defined in the ranking isn't already joined, then add it.
  1116. if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
  1117. $query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
  1118. }
  1119. $arguments = isset($values['arguments']) ? $values['arguments'] : array();
  1120. $query->addScore($values['score'], $arguments, $node_rank);
  1121. }
  1122. }
  1123. }
  1124. }
  1125. /**
  1126. * Implements hook_search_info().
  1127. */
  1128. function node_search_info() {
  1129. return array(
  1130. 'title' => 'Content',
  1131. 'path' => 'node',
  1132. );
  1133. }
  1134. /**
  1135. * Implements hook_search_access().
  1136. */
  1137. function node_search_access() {
  1138. return user_access('access content');
  1139. }
  1140. /**
  1141. * Implements hook_search_reset().
  1142. */
  1143. function node_search_reset() {
  1144. db_update('search_dataset')
  1145. ->fields(array('reindex' => REQUEST_TIME))
  1146. ->condition('type', 'node')
  1147. ->execute();
  1148. }
  1149. /**
  1150. * Implements hook_search_status().
  1151. */
  1152. function node_search_status() {
  1153. $total = db_query('SELECT COUNT(*) FROM {node}')->fetchField();
  1154. $remaining = db_query("SELECT COUNT(*) FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0")->fetchField();
  1155. return array('remaining' => $remaining, 'total' => $total);
  1156. }
  1157. /**
  1158. * Implements hook_search_admin().
  1159. */
  1160. function node_search_admin() {
  1161. // Output form for defining rank factor weights.
  1162. $form['content_ranking'] = array(
  1163. '#type' => 'details',
  1164. '#title' => t('Content ranking'),
  1165. );
  1166. $form['content_ranking']['#theme'] = 'node_search_admin';
  1167. $form['content_ranking']['info'] = array(
  1168. '#value' => '<em>' . t('The following numbers control which properties the content search should favor when ordering the results. Higher numbers mean more influence, zero means the property is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em>'
  1169. );
  1170. // Note: reversed to reflect that higher number = higher ranking.
  1171. $options = drupal_map_assoc(range(0, 10));
  1172. foreach (module_invoke_all('ranking') as $var => $values) {
  1173. $form['content_ranking']['factors']['node_rank_' . $var] = array(
  1174. '#title' => $values['title'],
  1175. '#type' => 'select',
  1176. '#options' => $options,
  1177. '#default_value' => variable_get('node_rank_' . $var, 0),
  1178. );
  1179. }
  1180. return $form;
  1181. }
  1182. /**
  1183. * Implements hook_search_execute().
  1184. */
  1185. function node_search_execute($keys = NULL, $conditions = NULL) {
  1186. // Build matching conditions
  1187. $query = db_select('search_index', 'i', array('target' => 'slave'))
  1188. ->extend('Drupal\search\SearchQuery')
  1189. ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
  1190. $query->join('node_field_data', 'n', 'n.nid = i.sid');
  1191. $query
  1192. ->condition('n.status', 1)
  1193. ->addTag('node_access')
  1194. ->searchExpression($keys, 'node');
  1195. // Insert special keywords.
  1196. $query->setOption('type', 'n.type');
  1197. $query->setOption('langcode', 'n.langcode');
  1198. if ($query->setOption('term', 'ti.tid')) {
  1199. $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  1200. }
  1201. // Only continue if the first pass query matches.
  1202. if (!$query->executeFirstPass()) {
  1203. return array();
  1204. }
  1205. // Add the ranking expressions.
  1206. _node_rankings($query);
  1207. // Load results.
  1208. $find = $query
  1209. // Add the language code of the indexed item to the result of the query,
  1210. // since the node will be rendered using the respective language.
  1211. ->fields('i', array('langcode'))
  1212. ->limit(10)
  1213. ->execute();
  1214. $results = array();
  1215. foreach ($find as $item) {
  1216. // Render the node.
  1217. $node = node_load($item->sid);
  1218. $build = node_view($node, 'search_result', $item->langcode);
  1219. unset($build['#theme']);
  1220. $node->rendered = drupal_render($build);
  1221. // Fetch comments for snippet.
  1222. $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node, $item->langcode);
  1223. $extra = module_invoke_all('node_search_result', $node, $item->langcode);
  1224. $language = language_load($item->langcode);
  1225. $uri = $node->uri();
  1226. $username = array(
  1227. '#theme' => 'username',
  1228. '#account' => $node,
  1229. );
  1230. $results[] = array(
  1231. 'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE, 'language' => $language))),
  1232. 'type' => check_plain(node_get_type_label($node)),
  1233. 'title' => $node->label($item->langcode),
  1234. 'user' => drupal_render($username),
  1235. 'date' => $node->changed,
  1236. 'node' => $node,
  1237. 'extra' => $extra,
  1238. 'score' => $item->calculated_score,
  1239. 'snippet' => search_excerpt($keys, $node->rendered, $item->langcode),
  1240. 'langcode' => $node->langcode,
  1241. );
  1242. }
  1243. return $results;
  1244. }
  1245. /**
  1246. * Implements hook_ranking().
  1247. */
  1248. function node_ranking() {
  1249. // Create the ranking array and add the basic ranking options.
  1250. $ranking = array(
  1251. 'relevance' => array(
  1252. 'title' => t('Keyword relevance'),
  1253. // Average relevance values hover around 0.15
  1254. 'score' => 'i.relevance',
  1255. ),
  1256. 'sticky' => array(
  1257. 'title' => t('Content is sticky at top of lists'),
  1258. // The sticky flag is either 0 or 1, which is automatically normalized.
  1259. 'score' => 'n.sticky',
  1260. ),
  1261. 'promote' => array(
  1262. 'title' => t('Content is promoted to the front page'),
  1263. // The promote flag is either 0 or 1, which is automatically normalized.
  1264. 'score' => 'n.promote',
  1265. ),
  1266. );
  1267. // Add relevance based on creation or changed date.
  1268. if ($node_cron_last = Drupal::state()->get('node.cron_last')) {
  1269. $ranking['recent'] = array(
  1270. 'title' => t('Recently posted'),
  1271. // Exponential decay with half-life of 6 months, starting at last indexed node
  1272. 'score' => 'POW(2.0, (GREATEST(n.created, n.changed) - :node_cron_last) * 6.43e-8)',
  1273. 'arguments' => array(':node_cron_last' => $node_cron_last),
  1274. );
  1275. }
  1276. return $ranking;
  1277. }
  1278. /**
  1279. * Implements hook_user_cancel().
  1280. */
  1281. function node_user_cancel($edit, $account, $method) {
  1282. switch ($method) {
  1283. case 'user_cancel_block_unpublish':
  1284. // Unpublish nodes (current revisions).
  1285. module_load_include('inc', 'node', 'node.admin');
  1286. $nodes = db_select('node_field_data', 'n')
  1287. ->distinct()
  1288. ->fields('n', array('nid'))
  1289. ->condition('uid', $account->uid)
  1290. ->execute()
  1291. ->fetchCol();
  1292. node_mass_update($nodes, array('status' => 0), NULL, TRUE);
  1293. break;
  1294. case 'user_cancel_reassign':
  1295. // Anonymize nodes (current revisions).
  1296. module_load_include('inc', 'node', 'node.admin');
  1297. $nodes = db_select('node_field_data', 'n')
  1298. ->distinct()
  1299. ->fields('n', array('nid'))
  1300. ->condition('uid', $account->uid)
  1301. ->execute()
  1302. ->fetchCol();
  1303. node_mass_update($nodes, array('uid' => 0), NULL, TRUE);
  1304. // Anonymize old revisions.
  1305. db_update('node_field_revision')
  1306. ->fields(array('uid' => 0))
  1307. ->condition('uid', $account->uid)
  1308. ->execute();
  1309. break;
  1310. }
  1311. }
  1312. /**
  1313. * Implements hook_user_predelete().
  1314. */
  1315. function node_user_predelete($account) {
  1316. // Delete nodes (current revisions).
  1317. // @todo Introduce node_mass_delete() or make node_mass_update() more flexible.
  1318. $nodes = db_select('node_field_data', 'n')
  1319. ->distinct()
  1320. ->fields('n', array('nid'))
  1321. ->condition('uid', $account->uid)
  1322. ->execute()
  1323. ->fetchCol();
  1324. entity_delete_multiple('node', $nodes);
  1325. // Delete old revisions.
  1326. $revisions = db_query('SELECT DISTINCT vid FROM {node_field_revision} WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol();
  1327. foreach ($revisions as $revision) {
  1328. node_revision_delete($revision);
  1329. }
  1330. }
  1331. /**
  1332. * Returns HTML for the content ranking part of the search settings admin page.
  1333. *
  1334. * @param $variables
  1335. * An associative array containing:
  1336. * - form: A render element representing the form.
  1337. *
  1338. * @see node_search_admin()
  1339. * @ingroup themeable
  1340. */
  1341. function theme_node_search_admin($variables) {
  1342. $form = $variables['form'];
  1343. $output = drupal_render($form['info']);
  1344. $header = array(t('Factor'), t('Weight'));
  1345. foreach (element_children($form['factors']) as $key) {
  1346. $row = array();
  1347. $row[] = $form['factors'][$key]['#title'];
  1348. $form['factors'][$key]['#title_display'] = 'invisible';
  1349. $row[] = drupal_render($form['factors'][$key]);
  1350. $rows[] = $row;
  1351. }
  1352. $table = array(
  1353. '#theme' => 'table',
  1354. '#header' => $header,
  1355. '#rows' => $rows,
  1356. );
  1357. $output .= drupal_render($table);
  1358. $output .= drupal_render_children($form);
  1359. return $output;
  1360. }
  1361. /**
  1362. * Access callback: Checks node revision access.
  1363. *
  1364. * @param \Drupal\Core\Entity\EntityInterface $node
  1365. * The node to check.
  1366. * @param $op
  1367. * (optional) The specific operation being checked. Defaults to 'view.'
  1368. * @param object $account
  1369. * (optional) A user object representing the user for whom the operation is
  1370. * to be performed. Determines access for a user other than the current user.
  1371. * Defaults to NULL.
  1372. * @param $langcode
  1373. * (optional) Language code for the variant of the node. Different language
  1374. * variants might have different permissions associated. If NULL, the
  1375. * original langcode of the node is used. Defaults to NULL.
  1376. *
  1377. * @return
  1378. * TRUE if the operation may be performed, FALSE otherwise.
  1379. *
  1380. * @see node_menu()
  1381. */
  1382. function _node_revision_access(EntityInterface $node, $op = 'view', $account = NULL, $langcode = NULL) {
  1383. $access = &drupal_static(__FUNCTION__, array());
  1384. $map = array(
  1385. 'view' => 'view all revisions',
  1386. 'update' => 'revert all revisions',
  1387. 'delete' => 'delete all revisions',
  1388. );
  1389. $type_map = array(
  1390. 'view' => "view $node->type revisions",
  1391. 'update' => "revert $node->type revisions",
  1392. 'delete' => "delete $node->type revisions",
  1393. );
  1394. if (!$node || !isset($map[$op]) || !isset($type_map[$op])) {
  1395. // If there was no node to check against, or the $op was not one of the
  1396. // supported ones, we return access denied.
  1397. return FALSE;
  1398. }
  1399. if (!isset($account)) {
  1400. $account = $GLOBALS['user'];
  1401. }
  1402. // If no language code was provided, default to the node revision's langcode.
  1403. if (empty($langcode)) {
  1404. $langcode = $node->langcode;
  1405. }
  1406. // Statically cache access by revision ID, language code, user account ID,
  1407. // and operation.
  1408. $cid = $node->vid . ':' . $langcode . ':' . $account->uid . ':' . $op;
  1409. if (!isset($access[$cid])) {
  1410. // Perform basic permission checks first.
  1411. if (!user_access($map[$op], $account) && !user_access($type_map[$op], $account) && !user_access('administer nodes', $account)) {
  1412. return $access[$cid] = FALSE;
  1413. }
  1414. // There should be at least two revisions. If the vid of the given node
  1415. // and the vid of the default revision differ, then we already have two
  1416. // different revisions so there is no need for a separate database check.
  1417. // Also, if you try to revert to or delete the default revision, that's
  1418. // not good.
  1419. if ($node->isDefaultRevision() && (db_query('SELECT COUNT(*) FROM {node_field_revision} WHERE nid = :nid AND default_langcode = 1', array(':nid' => $node->nid))->fetchField() == 1 || $op == 'update' || $op == 'delete')) {
  1420. $access[$cid] = FALSE;
  1421. }
  1422. elseif (user_access('administer nodes', $account)) {
  1423. $access[$cid] = TRUE;
  1424. }
  1425. else {
  1426. // First check the access to the default revision and finally, if the
  1427. // node passed in is not the default revision then access to that, too.
  1428. $access[$cid] = node_access($op, node_load($node->nid), $account, $langcode) && ($node->isDefaultRevision() || node_access($op, $node, $account, $langcode));
  1429. }
  1430. }
  1431. return $access[$cid];
  1432. }
  1433. /**
  1434. * Access callback: Checks whether the user has permission to add a node.
  1435. *
  1436. * @return
  1437. * TRUE if the user has add permission, otherwise FALSE.
  1438. *
  1439. * @see node_menu()
  1440. */
  1441. function _node_add_access() {
  1442. $types = node_type_get_types();
  1443. foreach ($types as $type) {
  1444. if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
  1445. return TRUE;
  1446. }
  1447. }
  1448. if (user_access('administer content types')) {
  1449. // There are no content types defined that the user has permission to create,
  1450. // but the user does have the permission to administer the content types, so
  1451. // grant them access to the page anyway.
  1452. return TRUE;
  1453. }
  1454. return FALSE;
  1455. }
  1456. /**
  1457. * Implements hook_menu().
  1458. */
  1459. function node_menu() {
  1460. $items['admin/content'] = array(
  1461. 'title' => 'Content',
  1462. 'description' => 'Find and manage content.',
  1463. 'page callback' => 'node_admin_nodes',
  1464. 'access arguments' => array('access content overview'),
  1465. 'weight' => -10,
  1466. 'file' => 'node.admin.inc',
  1467. );
  1468. $items['admin/content/node'] = array(
  1469. 'title' => 'Content',
  1470. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1471. );
  1472. $items['admin/reports/status/rebuild'] = array(
  1473. 'title' => 'Rebuild permissions',
  1474. 'page callback' => 'drupal_get_form',
  1475. 'page arguments' => array('node_configure_rebuild_confirm'),
  1476. // Any user than can potentially trigger a node_access_needs_rebuild(TRUE)
  1477. // has to be allowed access to the 'node access rebuild' confirm form.
  1478. 'access arguments' => array('access administration pages'),
  1479. 'type' => MENU_CALLBACK,
  1480. 'file' => 'node.admin.inc',
  1481. );
  1482. $items['admin/structure/types'] = array(
  1483. 'title' => 'Content types',
  1484. 'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
  1485. 'page callback' => 'node_overview_types',
  1486. 'access arguments' => array('administer content types'),
  1487. 'file' => 'content_types.inc',
  1488. );
  1489. $items['admin/structure/types/list'] = array(
  1490. 'title' => 'List',
  1491. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1492. );
  1493. $items['admin/structure/types/add'] = array(
  1494. 'title' => 'Add content type',
  1495. 'page callback' => 'drupal_get_form',
  1496. 'page arguments' => array('node_type_form'),
  1497. 'access arguments' => array('administer content types'),
  1498. 'type' => MENU_LOCAL_ACTION,
  1499. 'file' => 'content_types.inc',
  1500. );
  1501. $items['admin/structure/types/manage/%node_type'] = array(
  1502. 'title' => 'Edit content type',
  1503. 'title callback' => 'node_type_page_title',
  1504. 'title arguments' => array(4),
  1505. 'page callback' => 'drupal_get_form',
  1506. 'page arguments' => array('node_type_form', 4),
  1507. 'access arguments' => array('administer content types'),
  1508. 'file' => 'content_types.inc',
  1509. );
  1510. $items['admin/structure/types/manage/%node_type/edit'] = array(
  1511. 'title' => 'Edit',
  1512. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1513. );
  1514. $items['admin/structure/types/manage/%node_type/delete'] = array(
  1515. 'title' => 'Delete',
  1516. 'page arguments' => array('node_type_delete_confirm', 4),
  1517. 'access arguments' => array('administer content types'),
  1518. 'file' => 'content_types.inc',
  1519. );
  1520. $items['node/add'] = array(
  1521. 'title' => 'Add content',
  1522. 'page callback' => 'node_add_page',
  1523. 'access callback' => '_node_add_access',
  1524. 'file' => 'node.pages.inc',
  1525. );
  1526. $items['node/add/%node_type'] = array(
  1527. 'title callback' => 'node_type_get_clean_name',
  1528. 'title arguments' => array(2),
  1529. 'page callback' => 'node_add',
  1530. 'page arguments' => array(2),
  1531. 'access callback' => 'node_access',
  1532. 'access arguments' => array('create', 2),
  1533. 'description callback' => 'node_type_get_description',
  1534. 'description arguments' => array(2),
  1535. 'file' => 'node.pages.inc',
  1536. );
  1537. $items['node/%node'] = array(
  1538. 'title callback' => 'node_page_title',
  1539. 'title arguments' => array(1),
  1540. // The page callback also invokes drupal_set_title() in case
  1541. // the menu router's title is overridden by a menu link.
  1542. 'page callback' => 'node_page_view',
  1543. 'page arguments' => array(1),
  1544. 'access callback' => 'node_access',
  1545. 'access arguments' => array('view', 1),
  1546. );
  1547. $items['node/%node/view'] = array(
  1548. 'title' => 'View',
  1549. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1550. );
  1551. $items['node/%node/edit'] = array(
  1552. 'title' => 'Edit',
  1553. 'route_name' => 'node_page_edit',
  1554. 'type' => MENU_LOCAL_TASK,
  1555. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  1556. );
  1557. $items['node/%node/delete'] = array(
  1558. 'title' => 'Delete',
  1559. 'page callback' => 'drupal_get_form',
  1560. 'page arguments' => array('node_delete_confirm', 1),
  1561. 'access callback' => 'node_access',
  1562. 'access arguments' => array('delete', 1),
  1563. 'weight' => 10,
  1564. 'type' => MENU_LOCAL_TASK,
  1565. 'context' => MENU_CONTEXT_INLINE,
  1566. 'file' => 'node.pages.inc',
  1567. );
  1568. $items['node/%node/revisions'] = array(
  1569. 'title' => 'Revisions',
  1570. 'page callback' => 'node_revision_overview',
  1571. 'page arguments' => array(1),
  1572. 'access callback' => '_node_revision_access',
  1573. 'access arguments' => array(1),
  1574. 'weight' => 20,
  1575. 'type' => MENU_LOCAL_TASK,
  1576. 'file' => 'node.pages.inc',
  1577. );
  1578. $items['node/%node/revisions/%node_revision/view'] = array(
  1579. 'title' => 'Revisions',
  1580. 'page callback' => 'node_show',
  1581. 'page arguments' => array(3, TRUE),
  1582. 'access callback' => '_node_revision_access',
  1583. 'access arguments' => array(3),
  1584. );
  1585. $items['node/%node/revisions/%node_revision/revert'] = array(
  1586. 'title' => 'Revert to earlier revision',
  1587. 'page callback' => 'drupal_get_form',
  1588. 'page arguments' => array('node_revision_revert_confirm', 3),
  1589. 'access callback' => '_node_revision_access',
  1590. 'access arguments' => array(3, 'update'),
  1591. 'file' => 'node.pages.inc',
  1592. );
  1593. $items['node/%node/revisions/%node_revision/delete'] = array(
  1594. 'title' => 'Delete earlier revision',
  1595. 'page callback' => 'drupal_get_form',
  1596. 'page arguments' => array('node_revision_delete_confirm', 3),
  1597. 'access callback' => '_node_revision_access',
  1598. 'access arguments' => array(3, 'delete'),
  1599. 'file' => 'node.pages.inc',
  1600. );
  1601. return $items;
  1602. }
  1603. /**
  1604. * Implements hook_menu_local_tasks().
  1605. */
  1606. function node_menu_local_tasks(&$data, $router_item, $root_path) {
  1607. // Add action link to 'node/add' on 'admin/content' page.
  1608. if ($root_path == 'admin/content') {
  1609. $item = menu_get_item('node/add');
  1610. if ($item['access']) {
  1611. $data['actions'][] = array(
  1612. '#theme' => 'menu_local_action',
  1613. '#link' => $item,
  1614. );
  1615. }
  1616. }
  1617. }
  1618. /**
  1619. * Title callback: Provides the title for a node type edit form.
  1620. *
  1621. * @param $type
  1622. * The node type object.
  1623. *
  1624. * @return string
  1625. * An unsanitized string that is the title of the node type edit form.
  1626. *
  1627. * @see node_menu()
  1628. */
  1629. function node_type_page_title($type) {
  1630. return $type->name;
  1631. }
  1632. /**
  1633. * Title callback: Displays the node's title.
  1634. *
  1635. * @param \Drupal\Core\Entity\EntityInterface $node
  1636. * The node entity.
  1637. *
  1638. * @return
  1639. * An unsanitized string that is the title of the node.
  1640. *
  1641. * @see node_menu()
  1642. */
  1643. function node_page_title(EntityInterface $node) {
  1644. return $node->label();
  1645. }
  1646. /**
  1647. * Finds the last time a node was changed.
  1648. *
  1649. * @param $nid
  1650. * The ID of a node.
  1651. * @param string $langcode
  1652. * (optional) The language the node has been last modified in. Defaults to the
  1653. * node language.
  1654. *
  1655. * @return string
  1656. * A unix timestamp indicating the last time the node was changed.
  1657. */
  1658. function node_last_changed($nid, $langcode = NULL) {
  1659. $language_clause = isset($langcode) ? 'langcode = :langcode' : 'default_langcode = 1';
  1660. $result = db_query('SELECT changed FROM {node_field_data} WHERE nid = :nid AND ' . $language_clause, array(':nid' => $nid, ':langcode' => $langcode))->fetch();
  1661. return is_object($result) ? $result->changed : FALSE;
  1662. }
  1663. /**
  1664. * Returns a list of all the existing revision numbers for the node passed in.
  1665. *
  1666. * @param \Drupal\Core\Entity\EntityInterface $node
  1667. * The node entity.
  1668. *
  1669. * @return
  1670. * An associative array keyed by node revision number.
  1671. */
  1672. function node_revision_list(EntityInterface $node) {
  1673. $revisions = array();
  1674. $result = db_query('SELECT nfr.vid, nfr.title, nfr.log, nfr.revision_uid AS uid, n.vid AS current_vid, nfr.revision_timestamp, u.name FROM {node_field_revision} nfr LEFT JOIN {node} n ON n.vid = nfr.vid INNER JOIN {users} u ON u.uid = nfr.revision_uid WHERE nfr.nid = :nid AND nfr.default_langcode = 1 ORDER BY nfr.vid DESC', array(':nid' => $node->nid));
  1675. foreach ($result as $revision) {
  1676. $revisions[$revision->vid] = $revision;
  1677. }
  1678. return $revisions;
  1679. }
  1680. /**
  1681. * Finds the most recently changed nodes that are available to the current user.
  1682. *
  1683. * @param $number
  1684. * (optional) The maximum number of nodes to find. Defaults to 10.
  1685. *
  1686. * @return
  1687. * An array of node entities or an empty array if there are no recent nodes
  1688. * visible to the current user.
  1689. */
  1690. function node_get_recent($number = 10) {
  1691. $query = db_select('node_field_data', 'n');
  1692. if (!user_access('bypass node access')) {
  1693. // If the user is able to view their own unpublished nodes, allow them
  1694. // to see these in addition to published nodes. Check that they actually
  1695. // have some unpublished nodes to view before adding the condition.
  1696. if (user_access('view own unpublished content') && $own_unpublished = db_query('SELECT DISTINCT nid FROM {node_field_data} WHERE uid = :uid AND status = :status', array(':uid' => $GLOBALS['user']->uid, ':status' => NODE_NOT_PUBLISHED))->fetchCol()) {
  1697. $query->condition(db_or()
  1698. ->condition('n.status', NODE_PUBLISHED)
  1699. ->condition('n.nid', $own_unpublished, 'IN')
  1700. );
  1701. }
  1702. else {
  1703. // If not, restrict the query to published nodes.
  1704. $query->condition('n.status', NODE_PUBLISHED);
  1705. }
  1706. }
  1707. $nids = $query
  1708. ->distinct()
  1709. ->fields('n', array('nid'))
  1710. ->orderBy('n.changed', 'DESC')
  1711. ->range(0, $number)
  1712. ->addTag('node_access')
  1713. ->execute()
  1714. ->fetchCol();
  1715. $nodes = node_load_multiple($nids);
  1716. return $nodes ? $nodes : array();
  1717. }
  1718. /**
  1719. * Returns HTML for a list of recent content.
  1720. *
  1721. * @param $variables
  1722. * An associative array containing:
  1723. * - nodes: An array of recent node entities.
  1724. *
  1725. * @ingroup themeable
  1726. */
  1727. function theme_node_recent_block($variables) {
  1728. $rows = array();
  1729. $output = '';
  1730. $l_options = array('query' => drupal_get_destination());
  1731. foreach ($variables['nodes'] as $node) {
  1732. $row = array();
  1733. $node_recent_content = array(
  1734. '#theme' => 'node_recent_content',
  1735. '#node' => $node,
  1736. );
  1737. $row[] = array(
  1738. 'data' => drupal_render($node_recent_content),
  1739. 'class' => 'title-author',
  1740. );
  1741. if (node_access('update', $node)) {
  1742. $row[] = array(
  1743. 'data' => l(t('edit'), 'node/' . $node->nid . '/edit', $l_options),
  1744. 'class' => 'edit',
  1745. );
  1746. }
  1747. if (node_access('delete', $node)) {
  1748. $row[] = array(
  1749. 'data' => l(t('delete'), 'node/' . $node->nid . '/delete', $l_options),
  1750. 'class' => 'delete',
  1751. );
  1752. }
  1753. $rows[] = $row;
  1754. }
  1755. if ($rows) {
  1756. $table = array(
  1757. '#theme' => 'table',
  1758. '#rows' => $rows,
  1759. );
  1760. $output = drupal_render($table);
  1761. if (user_access('access content overview')) {
  1762. $more_link = array(
  1763. '#theme' => 'more_link',
  1764. '#url' => 'admin/content',
  1765. '#title' => t('Show more content'),
  1766. );
  1767. $output .= drupal_render($more_link);
  1768. }
  1769. }
  1770. return $output;
  1771. }
  1772. /**
  1773. * Returns HTML for a recent node to be displayed in the recent content block.
  1774. *
  1775. * @param $variables
  1776. * An associative array containing:
  1777. * - node: A node entity.
  1778. *
  1779. * @ingroup themeable
  1780. */
  1781. function theme_node_recent_content($variables) {
  1782. $node = $variables['node'];
  1783. $output = '<div class="node-title">';
  1784. $output .= l($node->label(), 'node/' . $node->nid);
  1785. $mark = array(
  1786. '#theme' => 'mark',
  1787. '#mark_type' => node_mark($node->nid, $node->changed),
  1788. );
  1789. $output .= drupal_render($mark);
  1790. $output .= '</div><div class="node-author">';
  1791. $username = array(
  1792. '#theme' => 'username',
  1793. '#account' => user_load($node->uid),
  1794. );
  1795. $output .= drupal_render($username);
  1796. $output .= '</div>';
  1797. return $output;
  1798. }
  1799. /**
  1800. * Implements hook_form_FORM_ID_alter() for block_form().
  1801. *
  1802. * Adds node-type specific visibility options to block configuration form.
  1803. */
  1804. function node_form_block_form_alter(&$form, &$form_state) {
  1805. $block = $form_state['controller']->getEntity();
  1806. $visibility = $block->get('visibility');
  1807. $form['visibility']['node_type'] = array(
  1808. '#type' => 'details',
  1809. '#title' => t('Content types'),
  1810. '#collapsed' => TRUE,
  1811. '#group' => 'visibility',
  1812. '#weight' => 5,
  1813. );
  1814. $form['visibility']['node_type']['types'] = array(
  1815. '#type' => 'checkboxes',
  1816. '#title' => t('Show block for specific content types'),
  1817. '#default_value' => !empty($visibility['node_type']['types']) ? $visibility['node_type']['types'] : array(),
  1818. '#options' => node_type_get_names(),
  1819. '#description' => t('Show this block only on pages that display content of the given type(s). If you select no types, there will be no type-specific limitation.'),
  1820. );
  1821. }
  1822. /**
  1823. * Implements hook_block_access().
  1824. *
  1825. * Checks the content type specific visibility settings and removes the block
  1826. * if the visibility conditions are not met.
  1827. */
  1828. function node_block_access($block) {
  1829. $visibility = $block->get('visibility');
  1830. if (!empty($visibility)) {
  1831. if (!empty($visibility['node_type']['types'])) {
  1832. $allowed_types = array_filter($visibility['node_type']['types']);
  1833. }
  1834. if (empty($allowed_types)) {
  1835. // There are no node types selected in visibility settings so there is
  1836. // nothing to do.
  1837. // @see node_form_block_form_alter()
  1838. return;
  1839. }
  1840. $node = menu_get_object();
  1841. $node_types = node_type_get_types();
  1842. if (arg(0) == 'node' && arg(1) == 'add' && arg(2)) {
  1843. $node_add_arg = strtr(arg(2), '-', '_');
  1844. }
  1845. // For blocks with node types associated, if the node type does not match
  1846. // the settings from this block, deny access to it.
  1847. if (!empty($node)) {
  1848. // This is a node or node edit page.
  1849. return in_array($node->type, $allowed_types);
  1850. }
  1851. elseif (isset($node_add_arg) && isset($node_types[$node_add_arg])) {
  1852. // This is a node creation page
  1853. return in_array($node_add_arg, $allowed_types);
  1854. }
  1855. else {
  1856. // This page does not match the $allowed_types so deny access.
  1857. return FALSE;
  1858. }
  1859. }
  1860. }
  1861. /**
  1862. * Page callback: Generates and prints an RSS feed.
  1863. *
  1864. * Generates an RSS feed from an array of node IDs, and prints it with an HTTP
  1865. * header, with Content Type set to RSS/XML.
  1866. *
  1867. * @param $nids
  1868. * (optional) An array of node IDs (nid). Defaults to FALSE so empty feeds can
  1869. * be generated with passing an empty array, if no items are to be added
  1870. * to the feed.
  1871. * @param $channel
  1872. * (optional) An associative array containing 'title', 'link', 'description',
  1873. * and other keys, to be parsed by format_rss_channel() and
  1874. * format_xml_elements(). A list of channel elements can be found at the
  1875. * @link http://cyber.law.harvard.edu/rss/rss.html RSS 2.0 Specification. @endlink
  1876. * The link should be an absolute URL.
  1877. *
  1878. * @todo Convert taxonomy_term_feed() to a view, so this method is not needed
  1879. * anymore.
  1880. *
  1881. * @return Symfony\Component\HttpFoundation\Response
  1882. * A response object.
  1883. *
  1884. * @see node_menu()
  1885. */
  1886. function node_feed($nids = FALSE, $channel = array()) {
  1887. global $base_url;
  1888. $language_content = language(Language::TYPE_CONTENT);
  1889. $rss_config = config('system.rss');
  1890. if ($nids === FALSE) {
  1891. $nids = db_select('node_field_data', 'n')
  1892. ->distinct()
  1893. ->fields('n', array('nid'))
  1894. ->condition('n.promote', 1)
  1895. ->condition('n.status', 1)
  1896. ->orderBy('n.created', 'DESC')
  1897. ->range(0, $rss_config->get('items.limit'))
  1898. ->addTag('node_access')
  1899. ->execute()
  1900. ->fetchCol();
  1901. }
  1902. $item_length = $rss_config->get('items.view_mode');
  1903. $namespaces = array('xmlns:dc' => 'http://purl.org/dc/elements/1.1/');
  1904. // Load all nodes to be rendered.
  1905. $nodes = node_load_multiple($nids);
  1906. $items = '';
  1907. foreach ($nodes as $node) {
  1908. $item_text = '';
  1909. $node->link = url("node/$node->nid", array('absolute' => TRUE));
  1910. $node->rss_namespaces = array();
  1911. $node->rss_elements = array(
  1912. array('key' => 'pubDate', 'value' => gmdate('r', $node->created)),
  1913. array('key' => 'dc:creator', 'value' => $node->name),
  1914. array('key' => 'guid', 'value' => $node->nid . ' at ' . $base_url, 'attributes' => array('isPermaLink' => 'false'))
  1915. );
  1916. // The node gets built and modules add to or modify $node->rss_elements
  1917. // and $node->rss_namespaces.
  1918. $build = node_view($node, 'rss');
  1919. unset($build['#theme']);
  1920. if (!empty($node->rss_namespaces)) {
  1921. $namespaces = array_merge($namespaces, $node->rss_namespaces);
  1922. }
  1923. if ($item_length != 'title') {
  1924. // We render node contents and force links to be last.
  1925. $build['links']['#weight'] = 1000;
  1926. $item_text .= drupal_render($build);
  1927. }
  1928. $items .= format_rss_item($node->label(), $node->link, $item_text, $node->rss_elements);
  1929. }
  1930. $channel_defaults = array(
  1931. 'version' => '2.0',
  1932. 'title' => config('system.site')->get('name'),
  1933. 'link' => $base_url,
  1934. 'description' => $rss_config->get('channel.description'),
  1935. 'language' => $language_content->langcode
  1936. );
  1937. $channel_extras = array_diff_key($channel, $channel_defaults);
  1938. $channel = array_merge($channel_defaults, $channel);
  1939. $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  1940. $output .= "<rss version=\"" . $channel["version"] . "\" xml:base=\"" . $base_url . "\" " . new Attribute($namespaces) . ">\n";
  1941. $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language'], $channel_extras);
  1942. $output .= "</rss>\n";
  1943. return new Response($output, 200, array('Content-Type' => 'application/rss+xml; charset=utf-8'));
  1944. }
  1945. /**
  1946. * Generates an array for rendering the given node.
  1947. *
  1948. * @param \Drupal\Core\Entity\EntityInterface $node
  1949. * A node entity.
  1950. * @param $view_mode
  1951. * (optional) View mode, e.g., 'full', 'teaser'... Defaults to 'full.'
  1952. * @param $langcode
  1953. * (optional) A language code to use for rendering. Defaults to NULL which is
  1954. * the global content language of the current request.
  1955. *
  1956. * @return
  1957. * An array as expected by drupal_render().
  1958. */
  1959. function node_view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
  1960. return entity_view($node, $view_mode, $langcode);
  1961. }
  1962. /**
  1963. * Constructs a drupal_render() style array from an array of loaded nodes.
  1964. *
  1965. * @param $nodes
  1966. * An array of nodes as returned by node_load_multiple().
  1967. * @param $view_mode
  1968. * (optional) View mode, e.g., 'full', 'teaser'... Defaults to 'teaser.'
  1969. * @param $langcode
  1970. * (optional) A language code to use for rendering. Defaults to the global
  1971. * content language of the current request.
  1972. *
  1973. * @return
  1974. * An array in the format expected by drupal_render().
  1975. */
  1976. function node_view_multiple($nodes, $view_mode = 'teaser', $langcode = NULL) {
  1977. return entity_view_multiple($nodes, $view_mode, $langcode);
  1978. }
  1979. /**
  1980. * Page callback: Displays a single node.
  1981. *
  1982. * @param \Drupal\Core\Entity\EntityInterface $node
  1983. * The node entity.
  1984. *
  1985. * @return
  1986. * A page array suitable for use by drupal_render().
  1987. *
  1988. * @see node_menu()
  1989. */
  1990. function node_page_view(EntityInterface $node) {
  1991. // If there is a menu link to this node, the link becomes the last part
  1992. // of the active trail, and the link name becomes the page title.
  1993. // Thus, we must explicitly set the page title to be the node title.
  1994. drupal_set_title($node->label());
  1995. foreach ($node->uriRelationships() as $rel) {
  1996. $uri = $node->uri($rel);
  1997. // Set the node path as the canonical URL to prevent duplicate content.
  1998. drupal_add_html_head_link(array('rel' => $rel, 'href' => url($uri['path'], $uri['options'])), TRUE);
  1999. if ($rel == 'canonical') {
  2000. // Set the non-aliased canonical path as a default shortlink.
  2001. drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  2002. }
  2003. }
  2004. return node_show($node);
  2005. }
  2006. /**
  2007. * Implements hook_update_index().
  2008. */
  2009. function node_update_index() {
  2010. $limit = (int) config('search.settings')->get('index.cron_limit');
  2011. $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));
  2012. $nids = $result->fetchCol();
  2013. if (!$nids) {
  2014. return;
  2015. }
  2016. // The indexing throttle should be aware of the number of language variants
  2017. // of a node.
  2018. $counter = 0;
  2019. foreach (node_load_multiple($nids) as $node) {
  2020. // Determine when the maximum number of indexable items is reached.
  2021. $counter += count($node->getTranslationLanguages());
  2022. if ($counter > $limit) {
  2023. break;
  2024. }
  2025. _node_index_node($node);
  2026. }
  2027. }
  2028. /**
  2029. * Indexes a single node.
  2030. *
  2031. * @param \Drupal\Core\Entity\EntityInterface $node
  2032. * The node to index.
  2033. */
  2034. function _node_index_node(EntityInterface $node) {
  2035. // Save the changed time of the most recent indexed node, for the search
  2036. // results half-life calculation.
  2037. Drupal::state()->set('node.cron_last', $node->changed);
  2038. $languages = $node->getTranslationLanguages();
  2039. foreach ($languages as $language) {
  2040. // Render the node.
  2041. $build = node_view($node, 'search_index', $language->langcode);
  2042. unset($build['#theme']);
  2043. $node->rendered = drupal_render($build);
  2044. $text = '<h1>' . check_plain($node->label($language->langcode)) . '</h1>' . $node->rendered;
  2045. // Fetch extra data normally not visible.
  2046. $extra = module_invoke_all('node_update_index', $node, $language->langcode);
  2047. foreach ($extra as $t) {
  2048. $text .= $t;
  2049. }
  2050. // Update index.
  2051. search_index($node->nid, 'node', $text, $language->langcode);
  2052. }
  2053. }
  2054. /**
  2055. * Implements hook_form_FORM_ID_alter().
  2056. *
  2057. * @see node_search_validate()
  2058. */
  2059. function node_form_search_form_alter(&$form, $form_state) {
  2060. if (isset($form['module']) && $form['module']['#value'] == 'node' && user_access('use advanced search')) {
  2061. // Keyword boxes:
  2062. $form['advanced'] = array(
  2063. '#type' => 'details',
  2064. '#title' => t('Advanced search'),
  2065. '#collapsed' => TRUE,
  2066. '#attributes' => array('class' => array('search-advanced')),
  2067. );
  2068. $form['advanced']['keywords-fieldset'] = array(
  2069. '#type' => 'fieldset',
  2070. '#title' => t('Keywords'),
  2071. '#collapsible' => FALSE,
  2072. );
  2073. $form['advanced']['keywords'] = array(
  2074. '#prefix' => '<div class="criterion">',
  2075. '#suffix' => '</div>',
  2076. );
  2077. $form['advanced']['keywords-fieldset']['keywords']['or'] = array(
  2078. '#type' => 'textfield',
  2079. '#title' => t('Containing any of the words'),
  2080. '#size' => 30,
  2081. '#maxlength' => 255,
  2082. );
  2083. $form['advanced']['keywords-fieldset']['keywords']['phrase'] = array(
  2084. '#type' => 'textfield',
  2085. '#title' => t('Containing the phrase'),
  2086. '#size' => 30,
  2087. '#maxlength' => 255,
  2088. );
  2089. $form['advanced']['keywords-fieldset']['keywords']['negative'] = array(
  2090. '#type' => 'textfield',
  2091. '#title' => t('Containing none of the words'),
  2092. '#size' => 30,
  2093. '#maxlength' => 255,
  2094. );
  2095. // Node types:
  2096. $types = array_map('check_plain', node_type_get_names());
  2097. $form['advanced']['types-fieldset'] = array(
  2098. '#type' => 'fieldset',
  2099. '#title' => t('Types'),
  2100. '#collapsible' => FALSE,
  2101. );
  2102. $form['advanced']['types-fieldset']['type'] = array(
  2103. '#type' => 'checkboxes',
  2104. '#title' => t('Only of the type(s)'),
  2105. '#prefix' => '<div class="criterion">',
  2106. '#suffix' => '</div>',
  2107. '#options' => $types,
  2108. );
  2109. $form['advanced']['submit'] = array(
  2110. '#type' => 'submit',
  2111. '#value' => t('Advanced search'),
  2112. '#prefix' => '<div class="action">',
  2113. '#suffix' => '</div>',
  2114. '#weight' => 100,
  2115. );
  2116. // Languages:
  2117. $language_options = array();
  2118. foreach (language_list(Language::STATE_ALL) as $langcode => $language) {
  2119. // Make locked languages appear special in the list.
  2120. $language_options[$langcode] = $language->locked ? t('- @name -', array('@name' => $language->name)) : $language->name;
  2121. }
  2122. if (count($language_options) > 1) {
  2123. $form['advanced']['lang-fieldset'] = array(
  2124. '#type' => 'fieldset',
  2125. '#title' => t('Languages'),
  2126. '#collapsible' => FALSE,
  2127. '#collapsed' => FALSE,
  2128. );
  2129. $form['advanced']['lang-fieldset']['language'] = array(
  2130. '#type' => 'checkboxes',
  2131. '#title' => t('Languages'),
  2132. '#prefix' => '<div class="criterion">',
  2133. '#suffix' => '</div>',
  2134. '#options' => $language_options,
  2135. );
  2136. }
  2137. $form['#validate'][] = 'node_search_validate';
  2138. }
  2139. }
  2140. /**
  2141. * Form validation handler for node_form_search_form_alter().
  2142. */
  2143. function node_search_validate($form, &$form_state) {
  2144. // Initialize using any existing basic search keywords.
  2145. $keys = $form_state['values']['processed_keys'];
  2146. // Insert extra restrictions into the search keywords string.
  2147. if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) {
  2148. // Retrieve selected types - Form API sets the value of unselected
  2149. // checkboxes to 0.
  2150. $form_state['values']['type'] = array_filter($form_state['values']['type']);
  2151. if (count($form_state['values']['type'])) {
  2152. $keys = search_expression_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
  2153. }
  2154. }
  2155. if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
  2156. $keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
  2157. }
  2158. if (isset($form_state['values']['language']) && is_array($form_state['values']['language'])) {
  2159. $languages = array_filter($form_state['values']['language']);
  2160. if (count($languages)) {
  2161. $keys = search_expression_insert($keys, 'language', implode(',', $languages));
  2162. }
  2163. }
  2164. if ($form_state['values']['or'] != '') {
  2165. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['or'], $matches)) {
  2166. $keys .= ' ' . implode(' OR ', $matches[1]);
  2167. }
  2168. }
  2169. if ($form_state['values']['negative'] != '') {
  2170. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['negative'], $matches)) {
  2171. $keys .= ' -' . implode(' -', $matches[1]);
  2172. }
  2173. }
  2174. if ($form_state['values']['phrase'] != '') {
  2175. $keys .= ' "' . str_replace('"', ' ', $form_state['values']['phrase']) . '"';
  2176. }
  2177. if (!empty($keys)) {
  2178. form_set_value($form['basic']['processed_keys'], trim($keys), $form_state);
  2179. }
  2180. }
  2181. /**
  2182. * Implements hook_form_FORM_ID_alter().
  2183. *
  2184. * Alters the System module's site information settings form to add a global
  2185. * default setting for number of posts to show on node listing pages.
  2186. *
  2187. * @see node_page_default()
  2188. * @see taxonomy_term_page()
  2189. * @see node_form_system_site_information_settings_form_submit()
  2190. */
  2191. function node_form_system_site_information_settings_form_alter(&$form, &$form_state, $form_id) {
  2192. $form['front_page']['default_nodes_main'] = array(
  2193. '#type' => 'select',
  2194. '#title' => t('Number of posts on front page'),
  2195. '#default_value' => config('node.settings')->get('items_per_page'),
  2196. '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30)),
  2197. '#access' => (config('system.site')->get('page.front') == 'node'),
  2198. '#description' => t('The maximum number of posts displayed on overview pages such as the front page.'),
  2199. );
  2200. $form['#submit'][] = 'node_form_system_site_information_settings_form_submit';
  2201. }
  2202. /**
  2203. * Form submission handler for system_site_information_settings().
  2204. *
  2205. * @see node_form_system_site_information_settings_form_alter()
  2206. */
  2207. function node_form_system_site_information_settings_form_submit($form, &$form_state) {
  2208. config('node.settings')
  2209. ->set('items_per_page', $form_state['values']['default_nodes_main'])
  2210. ->save();
  2211. }
  2212. /**
  2213. * Implements hook_form_FORM_ID_alter().
  2214. *
  2215. * Alters the theme form to use the admin theme on node editing.
  2216. *
  2217. * @see node_form_system_themes_admin_form_submit()
  2218. */
  2219. function node_form_system_themes_admin_form_alter(&$form, &$form_state, $form_id) {
  2220. $form['admin_theme']['node_admin_theme'] = array(
  2221. '#type' => 'checkbox',
  2222. '#title' => t('Use the administration theme when editing or creating content'),
  2223. '#default_value' => variable_get('node_admin_theme', '0'),
  2224. );
  2225. $form['#submit'][] = 'node_form_system_themes_admin_form_submit';
  2226. }
  2227. /**
  2228. * Form submission handler for system_themes_admin_form().
  2229. *
  2230. * @see node_form_system_themes_admin_form_alter()
  2231. */
  2232. function node_form_system_themes_admin_form_submit($form, &$form_state) {
  2233. variable_set('node_admin_theme', $form_state['values']['node_admin_theme']);
  2234. }
  2235. /**
  2236. * @defgroup node_access Node access rights
  2237. * @{
  2238. * The node access system determines who can do what to which nodes.
  2239. *
  2240. * In determining access rights for a node, node_access() first checks whether
  2241. * the user has the "bypass node access" permission. Such users have
  2242. * unrestricted access to all nodes. user 1 will always pass this check.
  2243. *
  2244. * Next, all implementations of hook_node_access() will be called. Each
  2245. * implementation may explicitly allow, explicitly deny, or ignore the access
  2246. * request. If at least one module says to deny the request, it will be rejected.
  2247. * If no modules deny the request and at least one says to allow it, the request
  2248. * will be permitted.
  2249. *
  2250. * If all modules ignore the access request, then the node_access table is used
  2251. * to determine access. All node access modules are queried using
  2252. * hook_node_grants() to assemble a list of "grant IDs" for the user. This list
  2253. * is compared against the table. If any row contains the node ID in question
  2254. * (or 0, which stands for "all nodes"), one of the grant IDs returned, and a
  2255. * value of TRUE for the operation in question, then access is granted. Note
  2256. * that this table is a list of grants; any matching row is sufficient to grant
  2257. * access to the node.
  2258. *
  2259. * In node listings (lists of nodes generated from a select query, such as the
  2260. * default home page at path 'node', an RSS feed, a recent content block, etc.),
  2261. * the process above is followed except that hook_node_access() is not called on
  2262. * each node for performance reasons and for proper functioning of the pager
  2263. * system. When adding a node listing to your module, be sure to use a dynamic
  2264. * query created by db_select() and add a tag of "node_access". This will allow
  2265. * modules dealing with node access to ensure only nodes to which the user has
  2266. * access are retrieved, through the use of hook_query_TAG_alter().
  2267. *
  2268. * Note: Even a single module returning NODE_ACCESS_DENY from hook_node_access()
  2269. * will block access to the node. Therefore, implementers should take care to
  2270. * not deny access unless they really intend to. Unless a module wishes to
  2271. * actively deny access it should return NODE_ACCESS_IGNORE (or simply return
  2272. * nothing) to allow other modules or the node_access table to control access.
  2273. *
  2274. * To see how to write a node access module of your own, see
  2275. * node_access_example.module.
  2276. */
  2277. /**
  2278. * Access callback: Checks a user's permission for performing a node operation.
  2279. *
  2280. * @param $op
  2281. * The operation to be performed on the node. Possible values are:
  2282. * - "view"
  2283. * - "update"
  2284. * - "delete"
  2285. * - "create"
  2286. * @param Drupal\Core\Entity\EntityInterface|string|stdClass $node
  2287. * The node entity on which the operation is to be performed, or the node type
  2288. * object, or node type string (e.g., 'forum') for the 'create' operation.
  2289. * @param $account
  2290. * (optional) A user object representing the user for whom the operation is to
  2291. * be performed. Determines access for a user other than the current user.
  2292. * Defaults to NULL.
  2293. * @param $langcode
  2294. * (optional) Language code for the variant of the node. Different language
  2295. * variants might have different permissions associated. If NULL, the
  2296. * original langcode of the node is used. Defaults to NULL.
  2297. *
  2298. * @return
  2299. * TRUE if the operation may be performed, FALSE otherwise.
  2300. *
  2301. * @see node_menu()
  2302. */
  2303. function node_access($op, $node, $account = NULL, $langcode = NULL) {
  2304. if (!$node instanceof EntityInterface) {
  2305. $type = is_object($node) ? $node->type : $node;
  2306. $node = entity_create('node', array('type' => $type));
  2307. }
  2308. // If no language code was provided, default to the node's langcode.
  2309. if (empty($langcode)) {
  2310. $langcode = $node->langcode;
  2311. // If the Language module is enabled, try to use the language from content
  2312. // negotiation.
  2313. if (module_exists('language')) {
  2314. // Load languages the node exists in.
  2315. $node_translations = $node->getTranslationLanguages();
  2316. // Load the language from content negotiation.
  2317. $content_negotiation_langcode = language(Language::TYPE_CONTENT)->langcode;
  2318. // If there is a translation available, use it.
  2319. if (isset($node_translations[$content_negotiation_langcode])) {
  2320. $langcode = $content_negotiation_langcode;
  2321. }
  2322. }
  2323. }
  2324. // Make sure that if an account is passed, that it is a fully loaded user
  2325. // object.
  2326. if ($account && !($account instanceof UserInterface)) {
  2327. $account = user_load($account->uid);
  2328. }
  2329. return entity_access_controller('node')->access($node, $op, $langcode, $account);
  2330. }
  2331. /**
  2332. * Implements hook_node_access().
  2333. */
  2334. function node_node_access($node, $op, $account) {
  2335. $type = $node->bundle();
  2336. $configured_types = node_permissions_get_configured_types();
  2337. if (isset($configured_types[$type])) {
  2338. if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
  2339. return NODE_ACCESS_ALLOW;
  2340. }
  2341. if ($op == 'update') {
  2342. if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
  2343. return NODE_ACCESS_ALLOW;
  2344. }
  2345. }
  2346. if ($op == 'delete') {
  2347. if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
  2348. return NODE_ACCESS_ALLOW;
  2349. }
  2350. }
  2351. }
  2352. return NODE_ACCESS_IGNORE;
  2353. }
  2354. /**
  2355. * Helper function to generate standard node permission list for a given type.
  2356. *
  2357. * @param $name
  2358. * The machine name of the node type.
  2359. *
  2360. * @return array
  2361. * An array of permission names and descriptions.
  2362. */
  2363. function node_list_permissions($type) {
  2364. // Build standard list of node permissions for this type.
  2365. $perms = array(
  2366. "create $type->type content" => array(
  2367. 'title' => t('%type_name: Create new content', array('%type_name' => $type->name)),
  2368. ),
  2369. "edit own $type->type content" => array(
  2370. 'title' => t('%type_name: Edit own content', array('%type_name' => $type->name)),
  2371. ),
  2372. "edit any $type->type content" => array(
  2373. 'title' => t('%type_name: Edit any content', array('%type_name' => $type->name)),
  2374. ),
  2375. "delete own $type->type content" => array(
  2376. 'title' => t('%type_name: Delete own content', array('%type_name' => $type->name)),
  2377. ),
  2378. "delete any $type->type content" => array(
  2379. 'title' => t('%type_name: Delete any content', array('%type_name' => $type->name)),
  2380. ),
  2381. "view $type->type revisions" => array(
  2382. 'title' => t('%type_name: View revisions', array('%type_name' => $type->name)),
  2383. ),
  2384. "revert $type->type revisions" => array(
  2385. 'title' => t('%type_name: Revert revisions', array('%type_name' => $type->name)),
  2386. 'description' => t('Role requires permission <em>view revisions</em> and <em>edit rights</em> for nodes in question, or <em>administer nodes</em>.'),
  2387. ),
  2388. "delete $type->type revisions" => array(
  2389. 'title' => t('%type_name: Delete revisions', array('%type_name' => $type->name)),
  2390. 'description' => t('Role requires permission to <em>view revisions</em> and <em>delete rights</em> for nodes in question, or <em>administer nodes</em>.'),
  2391. ),
  2392. );
  2393. return $perms;
  2394. }
  2395. /**
  2396. * Returns an array of node types that should be managed by permissions.
  2397. *
  2398. * By default, this will include all node types in the system. To exclude a
  2399. * specific node from getting permissions defined for it, set the
  2400. * node_permissions_$type variable to 0. Core does not provide an interface for
  2401. * doing so. However, contrib modules may exclude their own nodes in
  2402. * hook_install(). Alternatively, contrib modules may configure all node types
  2403. * at once, or decide to apply some other hook_node_access() implementation to
  2404. * some or all node types.
  2405. *
  2406. * @return
  2407. * An array of node types managed by this module.
  2408. */
  2409. function node_permissions_get_configured_types() {
  2410. $configured_types = array();
  2411. foreach (node_type_get_types() as $name => $type) {
  2412. if (variable_get('node_permissions_' . $name, 1)) {
  2413. $configured_types[$name] = $type;
  2414. }
  2415. }
  2416. return $configured_types;
  2417. }
  2418. /**
  2419. * Fetches an array of permission IDs granted to the given user ID.
  2420. *
  2421. * The implementation here provides only the universal "all" grant. A node
  2422. * access module should implement hook_node_grants() to provide a grant list for
  2423. * the user.
  2424. *
  2425. * After the default grants have been loaded, we allow modules to alter the
  2426. * grants array by reference. This hook allows for complex business logic to be
  2427. * applied when integrating multiple node access modules.
  2428. *
  2429. * @param $op
  2430. * The operation that the user is trying to perform.
  2431. * @param $account
  2432. * (optional) The user object for the user performing the operation. If
  2433. * omitted, the current user is used. Defaults to NULL.
  2434. *
  2435. * @return
  2436. * An associative array in which the keys are realms, and the values are
  2437. * arrays of grants for those realms.
  2438. */
  2439. function node_access_grants($op, $account = NULL) {
  2440. if (!isset($account)) {
  2441. $account = $GLOBALS['user'];
  2442. }
  2443. // Fetch node access grants from other modules.
  2444. $grants = module_invoke_all('node_grants', $account, $op);
  2445. // Allow modules to alter the assigned grants.
  2446. drupal_alter('node_grants', $grants, $account, $op);
  2447. return array_merge(array('all' => array(0)), $grants);
  2448. }
  2449. /**
  2450. * Determines whether the user has a global viewing grant for all nodes.
  2451. *
  2452. * Checks to see whether any module grants global 'view' access to a user
  2453. * account; global 'view' access is encoded in the {node_access} table as a
  2454. * grant with nid=0. If no node access modules are enabled, node.module defines
  2455. * such a global 'view' access grant.
  2456. *
  2457. * This function is called when a node listing query is tagged with
  2458. * 'node_access'; when this function returns TRUE, no node access joins are
  2459. * added to the query.
  2460. *
  2461. * @param $account
  2462. * (optional) The user object for the user whose access is being checked. If
  2463. * omitted, the current user is used. Defaults to NULL.
  2464. *
  2465. * @return
  2466. * TRUE if 'view' access to all nodes is granted, FALSE otherwise.
  2467. *
  2468. * @see hook_node_grants()
  2469. * @see node_query_node_access_alter()
  2470. */
  2471. function node_access_view_all_nodes($account = NULL) {
  2472. global $user;
  2473. if (!$account) {
  2474. $account = $user;
  2475. }
  2476. // Statically cache results in an array keyed by $account->uid.
  2477. $access = &drupal_static(__FUNCTION__);
  2478. if (isset($access[$account->uid])) {
  2479. return $access[$account->uid];
  2480. }
  2481. // If no modules implement the node access system, access is always TRUE.
  2482. if (!module_implements('node_grants')) {
  2483. $access[$account->uid] = TRUE;
  2484. }
  2485. else {
  2486. $query = db_select('node_access');
  2487. $query->addExpression('COUNT(*)');
  2488. $query
  2489. ->condition('nid', 0)
  2490. ->condition('grant_view', 1, '>=');
  2491. $grants = db_or();
  2492. foreach (node_access_grants('view', $account) as $realm => $gids) {
  2493. foreach ($gids as $gid) {
  2494. $grants->condition(db_and()
  2495. ->condition('gid', $gid)
  2496. ->condition('realm', $realm)
  2497. );
  2498. }
  2499. }
  2500. if (count($grants) > 0 ) {
  2501. $query->condition($grants);
  2502. }
  2503. $access[$account->uid] = $query
  2504. ->execute()
  2505. ->fetchField();
  2506. }
  2507. return $access[$account->uid];
  2508. }
  2509. /**
  2510. * Implements hook_query_TAG_alter().
  2511. *
  2512. * This is the hook_query_alter() for queries tagged with 'node_access'. It adds
  2513. * node access checks for the user account given by the 'account' meta-data (or
  2514. * global $user if not provided), for an operation given by the 'op' meta-data
  2515. * (or 'view' if not provided; other possible values are 'update' and 'delete').
  2516. *
  2517. * Queries tagged with 'node_access' that are not against the {node} table
  2518. * must add the base table as metadata. For example:
  2519. * @code
  2520. * $query
  2521. * ->addTag('node_access')
  2522. * ->addMetaData('base_table', 'taxonomy_index');
  2523. * @endcode
  2524. */
  2525. function node_query_node_access_alter(AlterableInterface $query) {
  2526. global $user;
  2527. // Read meta-data from query, if provided.
  2528. if (!$account = $query->getMetaData('account')) {
  2529. $account = $user;
  2530. }
  2531. if (!$op = $query->getMetaData('op')) {
  2532. $op = 'view';
  2533. }
  2534. if (!$langcode = $query->getMetaData('langcode')) {
  2535. $langcode = FALSE;
  2536. }
  2537. // If $account can bypass node access, or there are no node access modules,
  2538. // or the operation is 'view' and the $account has a global view grant
  2539. // (such as a view grant for node ID 0), we don't need to alter the query.
  2540. if (user_access('bypass node access', $account)) {
  2541. return;
  2542. }
  2543. if (!count(module_implements('node_grants'))) {
  2544. return;
  2545. }
  2546. if ($op == 'view' && node_access_view_all_nodes($account)) {
  2547. return;
  2548. }
  2549. $tables = $query->getTables();
  2550. $base_table = $query->getMetaData('base_table');
  2551. // If the base table is not given, default to node if present.
  2552. if (!$base_table) {
  2553. foreach ($tables as $table_info) {
  2554. if (!($table_info instanceof SelectInterface)) {
  2555. $table = $table_info['table'];
  2556. // If the node table is in the query, it wins immediately.
  2557. if ($table == 'node' || $table == 'node_field_data') {
  2558. $base_table = $table;
  2559. break;
  2560. }
  2561. }
  2562. }
  2563. // Bail out if the base table is missing.
  2564. if (!$base_table) {
  2565. throw new Exception(t('Query tagged for node access but there is no node table, specify the base_table using meta data.'));
  2566. }
  2567. }
  2568. // Find all instances of the base table being joined -- could appear
  2569. // more than once in the query, and could be aliased. Join each one to
  2570. // the node_access table.
  2571. $grants = node_access_grants($op, $account);
  2572. $base_table_found = FALSE;
  2573. foreach ($tables as $nalias => $tableinfo) {
  2574. $table = $tableinfo['table'];
  2575. if (!($table instanceof SelectInterface) && $table == $base_table) {
  2576. $base_table_found = TRUE;
  2577. // Set the subquery.
  2578. $subquery = db_select('node_access', 'na')
  2579. ->fields('na', array('nid'));
  2580. $grant_conditions = db_or();
  2581. // If any grant exists for the specified user, then user has access to the
  2582. // node for the specified operation.
  2583. foreach ($grants as $realm => $gids) {
  2584. foreach ($gids as $gid) {
  2585. $grant_conditions->condition(db_and()
  2586. ->condition('na.gid', $gid)
  2587. ->condition('na.realm', $realm)
  2588. );
  2589. }
  2590. }
  2591. // Attach conditions to the subquery for nodes.
  2592. if (count($grant_conditions->conditions())) {
  2593. $subquery->condition($grant_conditions);
  2594. }
  2595. $subquery->condition('na.grant_' . $op, 1, '>=');
  2596. // Add langcode-based filtering if this is a multilingual site.
  2597. if (language_multilingual()) {
  2598. // If no specific langcode to check for is given, use the grant entry
  2599. // which is set as a fallback.
  2600. // If a specific langcode is given, use the grant entry for it.
  2601. if ($langcode === FALSE) {
  2602. $subquery->condition('na.fallback', 1, '=');
  2603. }
  2604. else {
  2605. $subquery->condition('na.langcode', $langcode, '=');
  2606. }
  2607. }
  2608. $field = 'nid';
  2609. // Now handle entities.
  2610. $subquery->where("$nalias.$field = na.nid");
  2611. $query->exists($subquery);
  2612. }
  2613. }
  2614. // If we reached this point and did not find the defined base table, throw
  2615. // an exception.
  2616. if (!$base_table_found) {
  2617. throw new Exception(t('Query tagged for node access but the defined base_table @base_table was not found', array('@base_table' => $base_table)));
  2618. }
  2619. }
  2620. /**
  2621. * Gets the list of node access grants and writes them to the database.
  2622. *
  2623. * This function is called when a node is saved, and can also be called by
  2624. * modules if something other than a node save causes node access permissions to
  2625. * change. It collects all node access grants for the node from
  2626. * hook_node_access_records() implementations, allows these grants to be altered
  2627. * via hook_node_access_records_alter() implementations, and saves the collected
  2628. * and altered grants to the database.
  2629. *
  2630. * @param \Drupal\Core\Entity\EntityInterface $node
  2631. * The $node to acquire grants for.
  2632. * @param $delete
  2633. * (optional) Whether to delete existing node access records before inserting
  2634. * new ones. Defaults to TRUE.
  2635. */
  2636. function node_access_acquire_grants(EntityInterface $node, $delete = TRUE) {
  2637. $grants = module_invoke_all('node_access_records', $node);
  2638. // Let modules alter the grants.
  2639. drupal_alter('node_access_records', $grants, $node);
  2640. // If no grants are set and the node is published, then use the default grant.
  2641. if (empty($grants) && !empty($node->status)) {
  2642. $grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0);
  2643. }
  2644. _node_access_write_grants($node, $grants, NULL, $delete);
  2645. }
  2646. /**
  2647. * Writes a list of grants to the database, deleting any previously saved ones.
  2648. *
  2649. * If a realm is provided, it will only delete grants from that realm, but it
  2650. * will always delete a grant from the 'all' realm. Modules that utilize
  2651. * node_access() can use this function when doing mass updates due to widespread
  2652. * permission changes.
  2653. *
  2654. * Note: Don't call this function directly from a contributed module. Call
  2655. * node_access_acquire_grants() instead.
  2656. *
  2657. * @param \Drupal\Core\Entity\EntityInterface $node
  2658. * The node whose grants are being written.
  2659. * @param $grants
  2660. * A list of grants to write. See hook_node_access_records() for the
  2661. * expected structure of the grants array.
  2662. * @param $realm
  2663. * (optional) If provided, read/write grants for that realm only. Defaults to
  2664. * NULL.
  2665. * @param $delete
  2666. * (optional) If false, does not delete records. This is only for optimization
  2667. * purposes, and assumes the caller has already performed a mass delete of
  2668. * some form. Defaults to TRUE.
  2669. *
  2670. * @see node_access_acquire_grants()
  2671. */
  2672. function _node_access_write_grants(EntityInterface $node, $grants, $realm = NULL, $delete = TRUE) {
  2673. if ($delete) {
  2674. $query = db_delete('node_access')->condition('nid', $node->nid);
  2675. if ($realm) {
  2676. $query->condition('realm', array($realm, 'all'), 'IN');
  2677. }
  2678. $query->execute();
  2679. }
  2680. // Only perform work when node_access modules are active.
  2681. if (!empty($grants) && count(module_implements('node_grants'))) {
  2682. $query = db_insert('node_access')->fields(array('nid', 'langcode', 'fallback', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete'));
  2683. // If we have defined a granted langcode, use it. But if not, add a grant
  2684. // for every language this node is translated to.
  2685. foreach ($grants as $grant) {
  2686. if ($realm && $realm != $grant['realm']) {
  2687. continue;
  2688. }
  2689. if (isset($grant['langcode'])) {
  2690. $grant_languages = array($grant['langcode'] => language_load($grant['langcode']));
  2691. }
  2692. else {
  2693. $grant_languages = $node->getTranslationLanguages(TRUE);
  2694. }
  2695. foreach ($grant_languages as $grant_langcode => $grant_language) {
  2696. // Only write grants; denies are implicit.
  2697. if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
  2698. $grant['nid'] = $node->nid;
  2699. $grant['langcode'] = $grant_langcode;
  2700. // The record with the original langcode is used as the fallback.
  2701. if ($grant['langcode'] == $node->langcode) {
  2702. $grant['fallback'] = 1;
  2703. }
  2704. else {
  2705. $grant['fallback'] = 0;
  2706. }
  2707. $query->values($grant);
  2708. }
  2709. }
  2710. }
  2711. $query->execute();
  2712. }
  2713. }
  2714. /**
  2715. * Toggles or reads the value of a flag for rebuilding the node access grants.
  2716. *
  2717. * When the flag is set, a message is displayed to users with 'access
  2718. * administration pages' permission, pointing to the 'rebuild' confirm form.
  2719. * This can be used as an alternative to direct node_access_rebuild calls,
  2720. * allowing administrators to decide when they want to perform the actual
  2721. * (possibly time consuming) rebuild.
  2722. *
  2723. * When unsure if the current user is an administrator, node_access_rebuild()
  2724. * should be used instead.
  2725. *
  2726. * @param $rebuild
  2727. * (optional) The boolean value to be written.
  2728. *
  2729. * @return
  2730. * The current value of the flag if no value was provided for $rebuild.
  2731. *
  2732. * @see node_access_rebuild()
  2733. */
  2734. function node_access_needs_rebuild($rebuild = NULL) {
  2735. if (!isset($rebuild)) {
  2736. return Drupal::state()->get('node.node_access_needs_rebuild') ?: FALSE;
  2737. }
  2738. elseif ($rebuild) {
  2739. Drupal::state()->set('node.node_access_needs_rebuild', TRUE);
  2740. }
  2741. else {
  2742. Drupal::state()->delete('node.node_access_needs_rebuild');
  2743. }
  2744. }
  2745. /**
  2746. * Rebuilds the node access database.
  2747. *
  2748. * This rebuild is occasionally needed by modules that make system-wide changes
  2749. * to access levels. When the rebuild is required by an admin-triggered action
  2750. * (e.g module settings form), calling node_access_needs_rebuild(TRUE) instead
  2751. * of node_access_rebuild() lets the user perform his changes and actually
  2752. * rebuild only once he is done.
  2753. *
  2754. * Note : As of Drupal 6, node access modules are not required to (and actually
  2755. * should not) call node_access_rebuild() in hook_enable/disable anymore.
  2756. *
  2757. * @param $batch_mode
  2758. * (optional) Set to TRUE to process in 'batch' mode, spawning processing over
  2759. * several HTTP requests (thus avoiding the risk of PHP timeout if the site
  2760. * has a large number of nodes). hook_update_N() and any form submit handler
  2761. * are safe contexts to use the 'batch mode'. Less decidable cases (such as
  2762. * calls from hook_user(), hook_taxonomy(), etc.) might consider using the
  2763. * non-batch mode. Defaults to FALSE.
  2764. *
  2765. * @see node_access_needs_rebuild()
  2766. */
  2767. function node_access_rebuild($batch_mode = FALSE) {
  2768. db_delete('node_access')->execute();
  2769. // Only recalculate if the site is using a node_access module.
  2770. if (count(module_implements('node_grants'))) {
  2771. if ($batch_mode) {
  2772. $batch = array(
  2773. 'title' => t('Rebuilding content access permissions'),
  2774. 'operations' => array(
  2775. array('_node_access_rebuild_batch_operation', array()),
  2776. ),
  2777. 'finished' => '_node_access_rebuild_batch_finished'
  2778. );
  2779. batch_set($batch);
  2780. }
  2781. else {
  2782. // Try to allocate enough time to rebuild node grants
  2783. drupal_set_time_limit(240);
  2784. // Rebuild newest nodes first so that recent content becomes available quickly.
  2785. $nids = db_query("SELECT nid FROM {node} ORDER BY nid DESC")->fetchCol();
  2786. foreach ($nids as $nid) {
  2787. $node = node_load($nid, TRUE);
  2788. // To preserve database integrity, only acquire grants if the node
  2789. // loads successfully.
  2790. if (!empty($node)) {
  2791. node_access_acquire_grants($node);
  2792. }
  2793. }
  2794. }
  2795. }
  2796. else {
  2797. // Not using any node_access modules. Add the default grant.
  2798. db_insert('node_access')
  2799. ->fields(array(
  2800. 'nid' => 0,
  2801. 'realm' => 'all',
  2802. 'gid' => 0,
  2803. 'grant_view' => 1,
  2804. 'grant_update' => 0,
  2805. 'grant_delete' => 0,
  2806. ))
  2807. ->execute();
  2808. }
  2809. if (!isset($batch)) {
  2810. drupal_set_message(t('Content permissions have been rebuilt.'));
  2811. node_access_needs_rebuild(FALSE);
  2812. cache_invalidate_tags(array('content' => TRUE));
  2813. }
  2814. }
  2815. /**
  2816. * Performs batch operation for node_access_rebuild().
  2817. *
  2818. * This is a multistep operation: we go through all nodes by packs of 20. The
  2819. * batch processing engine interrupts processing and sends progress feedback
  2820. * after 1 second execution time.
  2821. *
  2822. * @param array $context
  2823. * An array of contextual key/value information for rebuild batch process.
  2824. */
  2825. function _node_access_rebuild_batch_operation(&$context) {
  2826. if (empty($context['sandbox'])) {
  2827. // Initiate multistep processing.
  2828. $context['sandbox']['progress'] = 0;
  2829. $context['sandbox']['current_node'] = 0;
  2830. $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
  2831. }
  2832. // Process the next 20 nodes.
  2833. $limit = 20;
  2834. $nids = db_query_range("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, array(':nid' => $context['sandbox']['current_node']))->fetchCol();
  2835. $nodes = node_load_multiple($nids, TRUE);
  2836. foreach ($nodes as $nid => $node) {
  2837. // To preserve database integrity, only acquire grants if the node
  2838. // loads successfully.
  2839. if (!empty($node)) {
  2840. node_access_acquire_grants($node);
  2841. }
  2842. $context['sandbox']['progress']++;
  2843. $context['sandbox']['current_node'] = $nid;
  2844. }
  2845. // Multistep processing : report progress.
  2846. if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  2847. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  2848. }
  2849. }
  2850. /**
  2851. * Performs post-processing for node_access_rebuild().
  2852. *
  2853. * @param bool $success
  2854. * A boolean indicating whether the re-build process has completed.
  2855. * @param array $results
  2856. * An array of results information.
  2857. * @param array $operations
  2858. * An array of function calls (not used in this function).
  2859. */
  2860. function _node_access_rebuild_batch_finished($success, $results, $operations) {
  2861. if ($success) {
  2862. drupal_set_message(t('The content access permissions have been rebuilt.'));
  2863. node_access_needs_rebuild(FALSE);
  2864. }
  2865. else {
  2866. drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
  2867. }
  2868. cache_invalidate_tags(array('content' => TRUE));
  2869. }
  2870. /**
  2871. * @} End of "defgroup node_access".
  2872. */
  2873. /**
  2874. * @defgroup node_content Hook implementations for user-created content types
  2875. * @{
  2876. * Functions that implement hooks for user-created content types.
  2877. */
  2878. /**
  2879. * Implements hook_form().
  2880. */
  2881. function node_content_form(EntityInterface $node, $form_state) {
  2882. // @todo It is impossible to define a content type without implementing
  2883. // hook_form(). Remove this requirement.
  2884. $form = array();
  2885. $type = node_type_load($node->type);
  2886. if ($type->has_title) {
  2887. $form['title'] = array(
  2888. '#type' => 'textfield',
  2889. '#title' => check_plain($type->title_label),
  2890. '#required' => TRUE,
  2891. '#default_value' => $node->title,
  2892. '#maxlength' => 255,
  2893. '#weight' => -5,
  2894. );
  2895. }
  2896. return $form;
  2897. }
  2898. /**
  2899. * @} End of "defgroup node_content".
  2900. */
  2901. /**
  2902. * Implements hook_requirements().
  2903. */
  2904. function node_requirements($phase) {
  2905. $requirements = array();
  2906. if ($phase === 'runtime') {
  2907. // Only show rebuild button if there are either 0, or 2 or more, rows
  2908. // in the {node_access} table, or if there are modules that
  2909. // implement hook_node_grants().
  2910. $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField();
  2911. if ($grant_count != 1 || count(module_implements('node_grants')) > 0) {
  2912. $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count));
  2913. }
  2914. else {
  2915. $value = t('Disabled');
  2916. }
  2917. $description = t('If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Rebuilding will remove all privileges to content and replace them with permissions based on the current modules and settings. Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed, content will automatically use the new permissions.');
  2918. $requirements['node_access'] = array(
  2919. 'title' => t('Node Access Permissions'),
  2920. 'value' => $value,
  2921. 'description' => $description . ' ' . l(t('Rebuild permissions'), 'admin/reports/status/rebuild'),
  2922. );
  2923. }
  2924. return $requirements;
  2925. }
  2926. /**
  2927. * Implements hook_modules_enabled().
  2928. */
  2929. function node_modules_enabled($modules) {
  2930. // Check if any of the newly enabled modules require the node_access table to
  2931. // be rebuilt.
  2932. if (!node_access_needs_rebuild() && array_intersect($modules, module_implements('node_grants'))) {
  2933. node_access_needs_rebuild(TRUE);
  2934. }
  2935. }
  2936. /**
  2937. * Implements hook_modules_disabled().
  2938. */
  2939. function node_modules_disabled($modules) {
  2940. // Check whether any of the disabled modules implemented hook_node_grants(),
  2941. // in which case the node access table needs to be rebuilt.
  2942. foreach ($modules as $module) {
  2943. // At this point, the module is already disabled, but its code is still
  2944. // loaded in memory. Module functions must no longer be called. We only
  2945. // check whether a hook implementation function exists and do not invoke it.
  2946. // Node access also needs to be rebuilt if language module is disabled to
  2947. // remove any language-specific grants.
  2948. if (!node_access_needs_rebuild() && (module_hook($module, 'node_grants') || $module == 'language')) {
  2949. node_access_needs_rebuild(TRUE);
  2950. }
  2951. }
  2952. // If there remains no more node_access module, rebuilding will be
  2953. // straightforward, we can do it right now.
  2954. if (node_access_needs_rebuild() && count(module_implements('node_grants')) == 0) {
  2955. node_access_rebuild();
  2956. }
  2957. }
  2958. /**
  2959. * Implements hook_file_download_access().
  2960. */
  2961. function node_file_download_access($field, EntityInterface $entity, File $file) {
  2962. if ($entity->entityType() == 'node') {
  2963. return node_access('view', $entity);
  2964. }
  2965. }
  2966. /**
  2967. * Implements hook_language_delete().
  2968. */
  2969. function node_language_delete($language) {
  2970. // On nodes with this language, unset the language.
  2971. db_update('node')
  2972. ->fields(array('langcode' => ''))
  2973. ->condition('langcode', $language->langcode)
  2974. ->execute();
  2975. }
  2976. /**
  2977. * Implements hook_library_info().
  2978. */
  2979. function node_library_info() {
  2980. $libraries['drupal.node'] = array(
  2981. 'title' => 'Node',
  2982. 'version' => VERSION,
  2983. 'js' => array(
  2984. drupal_get_path('module', 'node') . '/node.js' => array(),
  2985. ),
  2986. 'dependencies' => array(
  2987. array('system', 'jquery'),
  2988. array('system', 'drupal'),
  2989. array('system', 'drupalSettings'),
  2990. array('system', 'drupal.form'),
  2991. ),
  2992. );
  2993. $libraries['drupal.node.preview'] = array(
  2994. 'title' => 'Node preview',
  2995. 'version' => VERSION,
  2996. 'js' => array(
  2997. drupal_get_path('module', 'node') . '/node.preview.js' => array(),
  2998. ),
  2999. 'dependencies' => array(
  3000. array('system', 'jquery'),
  3001. array('system', 'drupal'),
  3002. ),
  3003. );
  3004. $libraries['drupal.content_types'] = array(
  3005. 'title' => 'Content types',
  3006. 'version' => VERSION,
  3007. 'js' => array(
  3008. drupal_get_path('module', 'node') . '/content_types.js' => array(),
  3009. ),
  3010. 'dependencies' => array(
  3011. array('system', 'jquery'),
  3012. array('system', 'drupal'),
  3013. array('system', 'drupal.form'),
  3014. ),
  3015. );
  3016. return $libraries;
  3017. }
  3018. /**
  3019. * Implements hook_system_info_alter().
  3020. *
  3021. * The Content Translation module is deprecated in Drupal 8 in favor of the
  3022. * Entity Translation and is planned for removal. Until an upgrade path is
  3023. * available, it will still be possible to enable it, if necessary, through the
  3024. * module API or by tweaking the system module list configuration by hand.
  3025. * Morever every D8 site where Content Translation is installed (not necessarily
  3026. * enabled) will still be able to see it as usual in the module page.
  3027. */
  3028. function node_system_info_alter(&$info, $file, $type) {
  3029. if ($type == 'module' && $file->name == 'translation') {
  3030. $info['hidden'] = !module_exists('translation') && config('system.module.disabled')->get('translation') === NULL;
  3031. }
  3032. }

Functions

Namesort descending Description
node_access Access callback: Checks a user's permission for performing a node operation.
node_access_acquire_grants Gets the list of node access grants and writes them to the database.
node_access_grants Fetches an array of permission IDs granted to the given user ID.
node_access_needs_rebuild Toggles or reads the value of a flag for rebuilding the node access grants.
node_access_rebuild Rebuilds the node access database.
node_access_view_all_nodes Determines whether the user has a global viewing grant for all nodes.
node_add_body_field Adds the default body field to a node type.
node_admin_paths Implements hook_admin_paths().
node_block_access Implements hook_block_access().
node_content_form Implements hook_form().
node_entity_bundle_info Implements hook_entity_bundle_info().
node_entity_display_alter Implements hook_entity_display_alter().
node_feed Page callback: Generates and prints an RSS feed.
node_field_extra_fields Implements hook_field_extra_fields().
node_file_download_access Implements hook_file_download_access().
node_form_block_form_alter Implements hook_form_FORM_ID_alter() for block_form().
node_form_search_form_alter Implements hook_form_FORM_ID_alter().
node_form_system_site_information_settings_form_alter Implements hook_form_FORM_ID_alter().
node_form_system_site_information_settings_form_submit Form submission handler for system_site_information_settings().
node_form_system_themes_admin_form_alter Implements hook_form_FORM_ID_alter().
node_form_system_themes_admin_form_submit Form submission handler for system_themes_admin_form().
node_get_recent Finds the most recently changed nodes that are available to the current user.
node_get_type_label Returns the node type label for the passed node.
node_help Implements hook_help().
node_hook Determines whether a node hook exists.
node_invoke Invokes a node hook.
node_is_page Checks whether the current page is the full page view of the passed-in node.
node_language_delete Implements hook_language_delete().
node_last_changed Finds the last time a node was changed.
node_library_info Implements hook_library_info().
node_list_permissions Helper function to generate standard node permission list for a given type.
node_load Loads a node entity from the database.
node_load_multiple Loads node entities from the database.
node_mark Determines the type of marker to be displayed for a given node.
node_menu Implements hook_menu().
node_menu_local_tasks Implements hook_menu_local_tasks().
node_modules_disabled Implements hook_modules_disabled().
node_modules_enabled Implements hook_modules_enabled().
node_node_access Implements hook_node_access().
node_page_title Title callback: Displays the node's title.
node_page_view Page callback: Displays a single node.
node_permission Implements hook_permission().
node_permissions_get_configured_types Returns an array of node types that should be managed by permissions.
node_preprocess_block Implements hook_preprocess_HOOK() for block.html.twig.
node_query_node_access_alter Implements hook_query_TAG_alter().
node_ranking Implements hook_ranking().
node_rdf_mapping Implements hook_rdf_mapping().
node_rebuild Implements hook_rebuild().
node_requirements Implements hook_requirements().
node_revision_delete Deletes a node revision.
node_revision_list Returns a list of all the existing revision numbers for the node passed in.
node_revision_load Loads a node revision from the database.
node_search_access Implements hook_search_access().
node_search_admin Implements hook_search_admin().
node_search_execute Implements hook_search_execute().
node_search_info Implements hook_search_info().
node_search_reset Implements hook_search_reset().
node_search_status Implements hook_search_status().
node_search_validate Form validation handler for node_form_search_form_alter().
node_show Page callback: Generates an array which displays a node detail page.
node_submit Prepares a node for saving by populating the author and creation date.
node_system_info_alter Implements hook_system_info_alter().
node_theme Implements hook_theme().
node_title_list Gathers a listing of links to nodes.
node_types_rebuild Updates the database cache of node types.
node_type_cache_reset Clears the node type cache.
node_type_delete Deletes a node type from the database.
node_type_get_base Returns the node type base of the passed node or node type string.
node_type_get_clean_name Title callback: Returns the sanitized node type name.
node_type_get_description Description callback: Returns the node type description.
node_type_get_label Returns the node type label for the passed node type name.
node_type_get_names Returns a list of available node type names.
node_type_get_types Returns a list of all the available node types.
node_type_load Menu argument loader: Loads a node type by string.
node_type_page_title Title callback: Provides the title for a node type edit form.
node_type_save Saves a node type to the database.
node_type_set_defaults Sets the default values for a node type.
node_type_update_nodes Updates all nodes of one type to be of another type.
node_update_index Implements hook_update_index().
node_uri Entity URI callback.
node_user_cancel Implements hook_user_cancel().
node_user_predelete Implements hook_user_predelete().
node_view Generates an array for rendering the given node.
node_view_multiple Constructs a drupal_render() style array from an array of loaded nodes.
template_preprocess_node Prepares variables for node templates.
theme_node_recent_block Returns HTML for a list of recent content.
theme_node_recent_content Returns HTML for a recent node to be displayed in the recent content block.
theme_node_search_admin Returns HTML for the content ranking part of the search settings admin page.
_node_access_rebuild_batch_finished Performs post-processing for node_access_rebuild().
_node_access_rebuild_batch_operation Performs batch operation for node_access_rebuild().
_node_access_write_grants Writes a list of grants to the database, deleting any previously saved ones.
_node_add_access Access callback: Checks whether the user has permission to add a node.
_node_index_node Indexes a single node.
_node_rankings Gathers the rankings from the the hook_ranking() implementations.
_node_revision_access Access callback: Checks node revision access.
_node_types_build Builds and returns the list of available node types.

Constants

Namesort descending Description
NODE_ACCESS_ALLOW Denotes that access is allowed for a node.
NODE_ACCESS_DENY Denotes that access is denied for a node.
NODE_ACCESS_IGNORE Denotes that access is unaffected for a node.
NODE_NOT_PROMOTED Denotes that the node is not promoted to the front page.
NODE_NOT_PUBLISHED Denotes that the node is not published.
NODE_NOT_STICKY Denotes that the node is not sticky at the top of the page.
NODE_PROMOTED Denotes that the node is promoted to the front page.
NODE_PUBLISHED Denotes that the node is published.
NODE_STICKY Denotes that the node is sticky at the top of the page.