node.module

  1. drupal
    1. 4.6 modules/node.module
    2. 4.7 modules/node.module
    3. 5 modules/node/node.module
    4. 6 modules/node/node.module
    5. 7 modules/node/node.module
    6. 8 core/modules/node/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.

Functions & methods

NameDescription
node_accessAccess callback: Checks a user's permission for performing a node operation.
node_access_acquire_grantsGets the list of node access grants and writes them to the database.
node_access_grantsFetches an array of permission IDs granted to the given user ID.
node_access_needs_rebuildToggles or reads the value of a flag for rebuilding the node access grants.
node_access_rebuildRebuilds the node access database.
node_access_view_all_nodesDetermines whether the user has a global viewing grant for all nodes.
node_action_infoImplements hook_action_info().
node_add_body_fieldAdds the default body field to a node type.
node_admin_pathsImplements hook_admin_paths().
node_assign_owner_actionAssigns ownership of a node to a user.
node_assign_owner_action_formForm constructor for the settings form for node_assign_owner_action().
node_assign_owner_action_submitForm submission handler for node_assign_owner_action_form().
node_assign_owner_action_validateForm validation handler for node_assign_owner_action_form().
node_block_configureImplements hook_block_configure().
node_block_infoImplements hook_block_info().
node_block_list_alterImplements hook_block_list_alter().
node_block_saveImplements hook_block_save().
node_block_viewImplements hook_block_view().
node_build_contentBuilds a structured array representing the node's content.
node_content_formImplements hook_form().
node_cronImplements hook_cron().
node_deleteDeletes a node.
node_delete_multipleDeletes multiple nodes.
node_entity_infoImplements hook_entity_info().
node_feedPage callback: Generates and prints an RSS feed.
node_field_display_node_alterImplements hook_field_display_ENTITY_TYPE_alter().
node_field_extra_fieldsImplements hook_field_extra_fields().
node_file_download_accessImplements hook_file_download_access().
node_formsImplements hook_forms().
node_form_block_add_block_form_alterImplements hook_form_FORM_ID_alter() for block_add_block_form().
node_form_block_admin_configure_alterImplements hook_form_FORM_ID_alter() for block_admin_configure().
node_form_block_admin_configure_submitForm submission handler for node_form_block_admin_configure_alter().
node_form_block_custom_block_delete_alterImplements hook_form_FORM_ID_alter() for block_custom_block_delete().
node_form_block_custom_block_delete_submitForm submission handler for node_form_block_custom_block_delete_alter().
node_form_search_form_alterImplements hook_form_FORM_ID_alter().
node_form_system_themes_admin_form_alterImplements hook_form_FORM_ID_alter().
node_form_system_themes_admin_form_submitForm submission handler for system_themes_admin_form().
node_get_recentFinds the most recently changed nodes that are available to the current user.
node_helpImplements hook_help().
node_hookDetermines whether a node hook exists.
node_invokeInvokes a node hook.
node_is_pageChecks whether the current page is the full page view of the passed-in node.
node_language_deleteImplements hook_language_delete().
node_last_changedFinds the last time a node was changed.
node_last_viewedRetrieves the timestamp for the current user's last view of a specified node.
node_list_permissionsHelper function to generate standard node permission list for a given type.
node_loadLoads a node entity from the database.
node_load_multipleLoads node entities from the database.
node_make_sticky_actionSets the sticky-at-top-of-list property of a node to 1.
node_make_unsticky_actionSets the sticky-at-top-of-list property of a node to 0.
node_markDecides on the type of marker to be displayed for a given node.
node_menuImplements hook_menu().
node_menu_local_tasks_alterImplements hook_menu_local_tasks_alter().
node_modules_disabledImplements hook_modules_disabled().
node_modules_enabledImplements hook_modules_enabled().
node_modules_uninstalledImplements hook_modules_uninstalled().
node_node_accessImplements hook_node_access().
node_object_preparePrepares a node entity for editing.
node_page_defaultPage callback: Generates a listing of promoted nodes.
node_page_titleTitle callback: Displays the node's title.
node_page_viewPage callback: Displays a single node.
node_permissionImplements hook_permission().
node_permissions_get_configured_typesReturns an array of node types that should be managed by permissions.
node_preprocess_blockImplements hook_preprocess_HOOK() for block.tpl.php.
node_promote_actionSets the promote property of a node to 1.
node_publish_actionSets the status of a node to 1 (published).
node_query_entity_field_access_alterImplements hook_query_TAG_alter().
node_query_node_access_alterImplements hook_query_TAG_alter().
node_rankingImplements hook_ranking().
node_rdf_mappingImplements hook_rdf_mapping().
node_rebuildImplements hook_rebuild().
node_requirementsImplements hook_requirements().
node_revision_deleteDeletes a node revision.
node_revision_listReturns a list of all the existing revision numbers for the node passed in.
node_saveSaves changes to a node or adds a new node.
node_save_actionSaves a node.
node_search_accessImplements hook_search_access().
node_search_adminImplements hook_search_admin().
node_search_executeImplements hook_search_execute().
node_search_infoImplements hook_search_info().
node_search_resetImplements hook_search_reset().
node_search_statusImplements hook_search_status().
node_search_validateForm validation handler for node_form_search_form_alter().
node_showPage callback: Generates an array which displays a node detail page.
node_submitPrepares a node for saving by populating the author and creation date.
node_tag_newUpdates the 'last viewed' timestamp of the specified node for current user.
node_themeImplements hook_theme().
node_title_listGathers a listing of links to nodes.
node_types_rebuildUpdates the database cache of node types.
node_type_cache_resetClears the node type cache.
node_type_deleteDeletes a node type from the database.
node_type_get_baseReturns the node type base of the passed node or node type string.
node_type_get_nameReturns the node type name of the passed node or node type string.
node_type_get_namesReturns a list of available node type names.
node_type_get_typesReturns a list of all the available node types.
node_type_loadMenu argument loader: Loads a node type by string.
node_type_page_titleTitle callback: Provides the title for a node type edit form.
node_type_saveSaves a node type to the database.
node_type_set_defaultsSets the default values for a node type.
node_type_update_nodesUpdates all nodes of one type to be of another type.
node_unpromote_actionSets the promote property of a node to 0.
node_unpublish_actionSets the status of a node to 0 (unpublished).
node_unpublish_by_keyword_actionUnpublishes a node containing certain keywords.
node_unpublish_by_keyword_action_formGenerates settings form for node_unpublish_by_keyword_action().
node_unpublish_by_keyword_action_submitForm submission handler for node_unpublish_by_keyword_action().
node_update_indexImplements hook_update_index().
node_uriEntity uri callback.
node_user_cancelImplements hook_user_cancel().
node_user_predeleteImplements hook_user_predelete().
node_validatePerforms validation checks on the given node.
node_viewGenerates an array for rendering the given node.
node_view_multipleConstructs a drupal_render() style array from an array of loaded nodes.
template_preprocess_nodeProcesses variables for node.tpl.php.
theme_node_recent_blockReturns HTML for a list of recent content.
theme_node_recent_contentReturns HTML for a recent node to be displayed in the recent content block.
theme_node_search_adminReturns HTML for the content ranking part of the search settings admin page.
_node_access_rebuild_batch_finishedPost-processing for node_access_rebuild_batch.
_node_access_rebuild_batch_operationBatch operation for node_access_rebuild_batch.
_node_access_write_grantsWrites a list of grants to the database, deleting any previously saved ones.
_node_add_accessAccess callback: Checks whether the user has permission to add a node.
_node_extract_typeExtracts the type name.
_node_index_nodeIndexes a single node.
_node_query_node_access_alterHelper for node access functions.
_node_rankingsGathers the rankings from the the hook_ranking() implementations.
_node_revision_accessAccess callback: Checks node revision access.
_node_types_buildBuilds and returns the list of available node types.

Constants

NameDescription
NODE_ACCESS_ALLOWDenotes that access is allowed for a node.
NODE_ACCESS_DENYDenotes that access is denied for a node.
NODE_ACCESS_IGNOREDenotes that access is unaffected for a node.
NODE_NEW_LIMITDenotes the time cutoff for nodes marked as read.
NODE_NOT_PROMOTEDDenotes that the node is not promoted to the front page.
NODE_NOT_PUBLISHEDDenotes that the node is not published.
NODE_NOT_STICKYDenotes that the node is not sticky at the top of the page.
NODE_PROMOTEDDenotes that the node is promoted to the front page.
NODE_PUBLISHEDDenotes that the node is published.
NODE_STICKYDenotes that the node is sticky at the top of the page.

File

core/modules/node/node.module
View source
  1. <?php
  2. use DrupalCoreDatabaseQueryAlterableInterface;
  3. use DrupalCoreDatabaseQuerySelectExtender;
  4. use DrupalCoreDatabaseQuerySelectInterface;
  5. use DrupalnodeNode;
  6. /**
  7. * @file
  8. * The core module that allows content to be submitted to the site.
  9. *
  10. * Modules and scripts may programmatically submit nodes using the usual form
  11. * API pattern.
  12. */
  13. /**
  14. * Denotes that the node is not published.
  15. */
  16. const NODE_NOT_PUBLISHED = 0;
  17. /**
  18. * Denotes that the node is published.
  19. */
  20. const NODE_PUBLISHED = 1;
  21. /**
  22. * Denotes that the node is not promoted to the front page.
  23. */
  24. const NODE_NOT_PROMOTED = 0;
  25. /**
  26. * Denotes that the node is promoted to the front page.
  27. */
  28. const NODE_PROMOTED = 1;
  29. /**
  30. * Denotes that the node is not sticky at the top of the page.
  31. */
  32. const NODE_NOT_STICKY = 0;
  33. /**
  34. * Denotes that the node is sticky at the top of the page.
  35. */
  36. const NODE_STICKY = 1;
  37. /**
  38. * Denotes the time cutoff for nodes marked as read.
  39. *
  40. * Nodes changed before this time are always marked as read. Nodes changed after
  41. * this time may be marked new, updated, or read, depending on their state for
  42. * the current user. Defaults to 30 days ago.
  43. */
  44. define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
  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 = 'allow';
  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 = 'deny';
  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_name($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. ),
  148. 'node_recent_block' => array(
  149. 'variables' => array('nodes' => NULL),
  150. ),
  151. 'node_recent_content' => array(
  152. 'variables' => array('node' => NULL),
  153. ),
  154. );
  155. }
  156. /**
  157. * Implements hook_cron().
  158. */
  159. function node_cron() {
  160. db_delete('history')
  161. ->condition('timestamp', NODE_NEW_LIMIT, '<')
  162. ->execute();
  163. }
  164. /**
  165. * Implements hook_entity_info().
  166. */
  167. function node_entity_info() {
  168. $return = array(
  169. 'node' => array(
  170. 'label' => t('Node'),
  171. 'controller class' => 'Drupal\node\NodeStorageController',
  172. 'entity class' => 'Drupal\node\Node',
  173. 'base table' => 'node',
  174. 'revision table' => 'node_revision',
  175. 'uri callback' => 'node_uri',
  176. 'fieldable' => TRUE,
  177. 'entity keys' => array(
  178. 'id' => 'nid',
  179. 'revision' => 'vid',
  180. 'bundle' => 'type',
  181. 'label' => 'title',
  182. ),
  183. 'bundle keys' => array(
  184. 'bundle' => 'type',
  185. ),
  186. 'bundles' => array(),
  187. 'view modes' => array(
  188. 'full' => array(
  189. 'label' => t('Full content'),
  190. 'custom settings' => FALSE,
  191. ),
  192. 'teaser' => array(
  193. 'label' => t('Teaser'),
  194. 'custom settings' => TRUE,
  195. ),
  196. 'rss' => array(
  197. 'label' => t('RSS'),
  198. 'custom settings' => FALSE,
  199. ),
  200. ),
  201. ),
  202. );
  203. // Search integration is provided by node.module, so search-related
  204. // view modes for nodes are defined here and not in search.module.
  205. if (module_exists('search')) {
  206. $return['node']['view modes'] += array(
  207. 'search_index' => array(
  208. 'label' => t('Search index'),
  209. 'custom settings' => FALSE,
  210. ),
  211. 'search_result' => array(
  212. 'label' => t('Search result'),
  213. 'custom settings' => FALSE,
  214. ),
  215. );
  216. }
  217. // Bundles must provide a human readable name so we can create help and error
  218. // messages, and the path to attach Field admin pages to.
  219. node_type_cache_reset();
  220. foreach (node_type_get_names() as $type => $name) {
  221. $return['node']['bundles'][$type] = array(
  222. 'label' => $name,
  223. 'admin' => array(
  224. 'path' => 'admin/structure/types/manage/%node_type',
  225. 'real path' => 'admin/structure/types/manage/' . $type,
  226. 'bundle argument' => 4,
  227. 'access arguments' => array('administer content types'),
  228. ),
  229. );
  230. }
  231. return $return;
  232. }
  233. /**
  234. * Implements hook_field_display_ENTITY_TYPE_alter().
  235. */
  236. function node_field_display_node_alter(&$display, $context) {
  237. // Hide field labels in search index.
  238. if ($context['view_mode'] == 'search_index') {
  239. $display['label'] = 'hidden';
  240. }
  241. }
  242. /**
  243. * Entity uri callback.
  244. *
  245. * @param Drupal\node\Node $node
  246. * A node entity.
  247. */
  248. function node_uri(Node $node) {
  249. return array(
  250. 'path' => 'node/' . $node->nid,
  251. );
  252. }
  253. /**
  254. * Implements hook_admin_paths().
  255. */
  256. function node_admin_paths() {
  257. if (variable_get('node_admin_theme')) {
  258. $paths = array(
  259. 'node/*/edit' => TRUE,
  260. 'node/*/delete' => TRUE,
  261. 'node/*/revisions' => TRUE,
  262. 'node/*/revisions/*/revert' => TRUE,
  263. 'node/*/revisions/*/delete' => TRUE,
  264. 'node/add' => TRUE,
  265. 'node/add/*' => TRUE,
  266. );
  267. return $paths;
  268. }
  269. }
  270. /**
  271. * Gathers a listing of links to nodes.
  272. *
  273. * @param $result
  274. * A database result object from a query to fetch node entities. If your
  275. * query joins the {node_comment_statistics} table so that the comment_count
  276. * field is available, a title attribute will be added to show the number of
  277. * comments.
  278. * @param $title
  279. * (optional) A heading for the resulting list.
  280. *
  281. * @return
  282. * A renderable array containing a list of linked node titles fetched from
  283. * $result, or FALSE if there are no rows in $result.
  284. */
  285. function node_title_list($result, $title = NULL) {
  286. $items = array();
  287. $num_rows = FALSE;
  288. foreach ($result as $node) {
  289. $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());
  290. $num_rows = TRUE;
  291. }
  292. return $num_rows ? array('#theme' => 'item_list__node', '#items' => $items, '#title' => $title) : FALSE;
  293. }
  294. /**
  295. * Updates the 'last viewed' timestamp of the specified node for current user.
  296. *
  297. * @param Drupal\node\Node $node
  298. * A node entity.
  299. */
  300. function node_tag_new(Node $node) {
  301. global $user;
  302. if ($user->uid) {
  303. db_merge('history')
  304. ->key(array(
  305. 'uid' => $user->uid,
  306. 'nid' => $node->nid,
  307. ))
  308. ->fields(array('timestamp' => REQUEST_TIME))
  309. ->execute();
  310. }
  311. }
  312. /**
  313. * Retrieves the timestamp for the current user's last view of a specified node.
  314. */
  315. function node_last_viewed($nid) {
  316. global $user;
  317. $history = &drupal_static(__FUNCTION__, array());
  318. if (!isset($history[$nid])) {
  319. $history[$nid] = db_query("SELECT timestamp FROM {history} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $nid))->fetchObject();
  320. }
  321. return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
  322. }
  323. /**
  324. * Decides on the type of marker to be displayed for a given node.
  325. *
  326. * @param $nid
  327. * Node ID whose history supplies the "last viewed" timestamp.
  328. * @param $timestamp
  329. * Time which is compared against node's "last viewed" timestamp.
  330. *
  331. * @return
  332. * One of the MARK constants.
  333. */
  334. function node_mark($nid, $timestamp) {
  335. global $user;
  336. $cache = &drupal_static(__FUNCTION__, array());
  337. if (!$user->uid) {
  338. return MARK_READ;
  339. }
  340. if (!isset($cache[$nid])) {
  341. $cache[$nid] = node_last_viewed($nid);
  342. }
  343. if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
  344. return MARK_NEW;
  345. }
  346. elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
  347. return MARK_UPDATED;
  348. }
  349. return MARK_READ;
  350. }
  351. /**
  352. * Extracts the type name.
  353. *
  354. * @param Drupal\node\Node|string $node
  355. * Either a string or object, containing the node type information.
  356. *
  357. * @return
  358. * Node type of the passed-in data.
  359. */
  360. function _node_extract_type($node) {
  361. return is_object($node) ? $node->type : $node;
  362. }
  363. /**
  364. * Returns a list of all the available node types.
  365. *
  366. * This list can include types that are queued for addition or deletion.
  367. * See _node_types_build() for details.
  368. *
  369. * @return
  370. * An array of node types, as objects, keyed by the type.
  371. *
  372. * @see node_type_load()
  373. */
  374. function node_type_get_types() {
  375. return _node_types_build()->types;
  376. }
  377. /**
  378. * Returns the node type base of the passed node or node type string.
  379. *
  380. * The base indicates which module implements this node type and is used to
  381. * execute node-type-specific hooks. For types defined in the user interface
  382. * and managed by node.module, the base is 'node_content'.
  383. *
  384. * @param Drupal\node\Node|string $node
  385. * A node entity or string that indicates the node type to return.
  386. *
  387. * @return
  388. * The node type base or FALSE if the node type is not found.
  389. *
  390. * @see node_invoke()
  391. */
  392. function node_type_get_base($node) {
  393. $type = _node_extract_type($node);
  394. $types = _node_types_build()->types;
  395. return isset($types[$type]) && isset($types[$type]->base) ? $types[$type]->base : FALSE;
  396. }
  397. /**
  398. * Returns a list of available node type names.
  399. *
  400. * This list can include types that are queued for addition or deletion.
  401. * See _node_types_build() for details.
  402. *
  403. * @return
  404. * An array of node type names, keyed by the type.
  405. */
  406. function node_type_get_names() {
  407. return _node_types_build()->names;
  408. }
  409. /**
  410. * Returns the node type name of the passed node or node type string.
  411. *
  412. * @param Drupal\node\Node|string $node
  413. * A node entity or string that indicates the node type to return.
  414. *
  415. * @return
  416. * The node type name or FALSE if the node type is not found.
  417. */
  418. function node_type_get_name($node) {
  419. $type = _node_extract_type($node);
  420. $types = _node_types_build()->names;
  421. return isset($types[$type]) ? $types[$type] : FALSE;
  422. }
  423. /**
  424. * Updates the database cache of node types.
  425. *
  426. * All new module-defined node types are saved to the database via a call to
  427. * node_type_save(), and obsolete ones are deleted via a call to
  428. * node_type_delete(). See _node_types_build() for an explanation of the new
  429. * and obsolete types.
  430. */
  431. function node_types_rebuild() {
  432. _node_types_build(TRUE);
  433. }
  434. /**
  435. * Menu argument loader: Loads a node type by string.
  436. *
  437. * @param $name
  438. * The machine name of a node type to load.
  439. *
  440. * @return
  441. * A node type object or FALSE if $name does not exist.
  442. */
  443. function node_type_load($name) {
  444. $types = _node_types_build()->types;
  445. return isset($types[$name]) ? $types[$name] : FALSE;
  446. }
  447. /**
  448. * Saves a node type to the database.
  449. *
  450. * @param $info
  451. * The node type to save, as an object.
  452. *
  453. * @return
  454. * Status flag indicating outcome of the operation.
  455. */
  456. function node_type_save($info) {
  457. $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
  458. $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', 0, 1, array(':type' => $existing_type))->fetchField();
  459. $type = node_type_set_defaults($info);
  460. $fields = array(
  461. 'type' => (string) $type->type,
  462. 'name' => (string) $type->name,
  463. 'base' => (string) $type->base,
  464. 'has_title' => (int) $type->has_title,
  465. 'title_label' => (string) $type->title_label,
  466. 'description' => (string) $type->description,
  467. 'help' => (string) $type->help,
  468. 'custom' => (int) $type->custom,
  469. 'modified' => (int) $type->modified,
  470. 'locked' => (int) $type->locked,
  471. 'disabled' => (int) $type->disabled,
  472. 'module' => $type->module,
  473. );
  474. if ($is_existing) {
  475. db_update('node_type')
  476. ->fields($fields)
  477. ->condition('type', $existing_type)
  478. ->execute();
  479. if (!empty($type->old_type) && $type->old_type != $type->type) {
  480. field_attach_rename_bundle('node', $type->old_type, $type->type);
  481. }
  482. module_invoke_all('node_type_update', $type);
  483. $status = SAVED_UPDATED;
  484. }
  485. else {
  486. $fields['orig_type'] = (string) $type->orig_type;
  487. db_insert('node_type')
  488. ->fields($fields)
  489. ->execute();
  490. field_attach_create_bundle('node', $type->type);
  491. module_invoke_all('node_type_insert', $type);
  492. $status = SAVED_NEW;
  493. }
  494. // Clear the node type cache.
  495. node_type_cache_reset();
  496. return $status;
  497. }
  498. /**
  499. * Adds the default body field to a node type.
  500. *
  501. * @param $type
  502. * A node type object.
  503. * @param $label
  504. * (optional) The label for the body instance.
  505. *
  506. * @return
  507. * Body field instance.
  508. */
  509. function node_add_body_field($type, $label = 'Body') {
  510. // Add or remove the body field, as needed.
  511. $field = field_info_field('body');
  512. $instance = field_info_instance('node', 'body', $type->type);
  513. if (empty($field)) {
  514. $field = array(
  515. 'field_name' => 'body',
  516. 'type' => 'text_with_summary',
  517. 'entity_types' => array('node'),
  518. );
  519. $field = field_create_field($field);
  520. }
  521. if (empty($instance)) {
  522. $instance = array(
  523. 'field_name' => 'body',
  524. 'entity_type' => 'node',
  525. 'bundle' => $type->type,
  526. 'label' => $label,
  527. 'widget' => array('type' => 'text_textarea_with_summary'),
  528. 'settings' => array('display_summary' => TRUE),
  529. 'display' => array(
  530. 'default' => array(
  531. 'label' => 'hidden',
  532. 'type' => 'text_default',
  533. ),
  534. 'teaser' => array(
  535. 'label' => 'hidden',
  536. 'type' => 'text_summary_or_trimmed',
  537. ),
  538. ),
  539. );
  540. $instance = field_create_instance($instance);
  541. }
  542. return $instance;
  543. }
  544. /**
  545. * Implements hook_field_extra_fields().
  546. */
  547. function node_field_extra_fields() {
  548. $extra = array();
  549. $module_language_enabled = module_exists('language');
  550. $description = t('Node module element');
  551. foreach (node_type_get_types() as $bundle) {
  552. if ($bundle->has_title) {
  553. $extra['node'][$bundle->type]['form']['title'] = array(
  554. 'label' => $bundle->title_label,
  555. 'description' => $description,
  556. 'weight' => -5,
  557. );
  558. }
  559. // Add also the 'language' select if Language module is enabled and the
  560. // bundle has multilingual support.
  561. if ($module_language_enabled && variable_get('node_type_language_' . $bundle->type, 0)) {
  562. $extra['node'][$bundle->type]['form']['language'] = array(
  563. 'label' => t('Language'),
  564. 'description' => $description,
  565. 'weight' => 0,
  566. );
  567. }
  568. }
  569. return $extra;
  570. }
  571. /**
  572. * Deletes a node type from the database.
  573. *
  574. * @param $name
  575. * The machine name of the node type to delete.
  576. */
  577. function node_type_delete($name) {
  578. $type = node_type_load($name);
  579. db_delete('node_type')
  580. ->condition('type', $name)
  581. ->execute();
  582. field_attach_delete_bundle('node', $name);
  583. module_invoke_all('node_type_delete', $type);
  584. // Clear the node type cache.
  585. node_type_cache_reset();
  586. }
  587. /**
  588. * Updates all nodes of one type to be of another type.
  589. *
  590. * @param $old_type
  591. * The current node type of the nodes.
  592. * @param $type
  593. * The new node type of the nodes.
  594. *
  595. * @return
  596. * The number of nodes whose node type field was modified.
  597. */
  598. function node_type_update_nodes($old_type, $type) {
  599. return db_update('node')
  600. ->fields(array('type' => $type))
  601. ->condition('type', $old_type)
  602. ->execute();
  603. }
  604. /**
  605. * Builds and returns the list of available node types.
  606. *
  607. * The list of types is built by invoking hook_node_info() on all modules and
  608. * comparing this information with the node types in the {node_type} table.
  609. * These two information sources are not synchronized during module installation
  610. * until node_types_rebuild() is called.
  611. *
  612. * @param $rebuild
  613. * TRUE to rebuild node types. Equivalent to calling node_types_rebuild().
  614. *
  615. * @return
  616. * Associative array with two components:
  617. * - names: Associative array of the names of node types, keyed by the type.
  618. * - types: Associative array of node type objects, keyed by the type.
  619. * Both of these arrays will include new types that have been defined by
  620. * hook_node_info() implementations but not yet saved in the {node_type}
  621. * table. These are indicated in the type object by $type->is_new being set
  622. * to the value 1. These arrays will also include obsolete types: types that
  623. * were previously defined by modules that have now been disabled, or for
  624. * whatever reason are no longer being defined in hook_node_info()
  625. * implementations, but are still in the database. These are indicated in the
  626. * type object by $type->disabled being set to TRUE.
  627. */
  628. function _node_types_build($rebuild = FALSE) {
  629. $cid = 'node_types:' . $GLOBALS['language_interface']->langcode;
  630. if (!$rebuild) {
  631. $_node_types = &drupal_static(__FUNCTION__);
  632. if (isset($_node_types)) {
  633. return $_node_types;
  634. }
  635. if ($cache = cache()->get($cid)) {
  636. $_node_types = $cache->data;
  637. return $_node_types;
  638. }
  639. }
  640. $_node_types = (object) array('types' => array(), 'names' => array());
  641. foreach (module_implements('node_info') as $module) {
  642. $info_array = module_invoke($module, 'node_info');
  643. foreach ($info_array as $type => $info) {
  644. $info['type'] = $type;
  645. $_node_types->types[$type] = node_type_set_defaults($info);
  646. $_node_types->types[$type]->module = $module;
  647. $_node_types->names[$type] = $info['name'];
  648. }
  649. }
  650. $query = db_select('node_type', 'nt')
  651. ->addTag('translatable')
  652. ->addTag('node_type_access')
  653. ->fields('nt')
  654. ->orderBy('nt.type', 'ASC');
  655. if (!$rebuild) {
  656. $query->condition('disabled', 0);
  657. }
  658. foreach ($query->execute() as $type_object) {
  659. $type_db = $type_object->type;
  660. // Original disabled value.
  661. $disabled = $type_object->disabled;
  662. // Check for node types from disabled modules and mark their types for removal.
  663. // Types defined by the node module in the database (rather than by a separate
  664. // module using hook_node_info) have a base value of 'node_content'. The isset()
  665. // check prevents errors on old (pre-Drupal 7) databases.
  666. if (isset($type_object->base) && $type_object->base != 'node_content' && empty($_node_types->types[$type_db])) {
  667. $type_object->disabled = TRUE;
  668. }
  669. if (isset($_node_types->types[$type_db])) {
  670. $type_object->disabled = FALSE;
  671. }
  672. if (!isset($_node_types->types[$type_db]) || $type_object->modified) {
  673. $_node_types->types[$type_db] = $type_object;
  674. $_node_types->names[$type_db] = $type_object->name;
  675. if ($type_db != $type_object->orig_type) {
  676. unset($_node_types->types[$type_object->orig_type]);
  677. unset($_node_types->names[$type_object->orig_type]);
  678. }
  679. }
  680. $_node_types->types[$type_db]->disabled = $type_object->disabled;
  681. $_node_types->types[$type_db]->disabled_changed = $disabled != $type_object->disabled;
  682. }
  683. if ($rebuild) {
  684. foreach ($_node_types->types as $type => $type_object) {
  685. if (!empty($type_object->is_new) || !empty($type_object->disabled_changed)) {
  686. node_type_save($type_object);
  687. }
  688. }
  689. }
  690. asort($_node_types->names);
  691. cache()->set($cid, $_node_types);
  692. return $_node_types;
  693. }
  694. /**
  695. * Clears the node type cache.
  696. */
  697. function node_type_cache_reset() {
  698. cache()->deletePrefix('node_types:');
  699. drupal_static_reset('_node_types_build');
  700. }
  701. /**
  702. * Sets the default values for a node type.
  703. *
  704. * The defaults are appropriate for a type defined through hook_node_info(),
  705. * since 'custom' is TRUE for types defined in the user interface, and FALSE
  706. * for types defined by modules. (The 'custom' flag prevents types from being
  707. * deleted through the user interface.) Also, the default for 'locked' is TRUE,
  708. * which prevents users from changing the machine name of the type.
  709. *
  710. * @param $info
  711. * (optional) An object or array containing values to override the defaults.
  712. * See hook_node_info() for details on what the array elements mean.
  713. *
  714. * @return
  715. * A node type object, with missing values in $info set to their defaults.
  716. */
  717. function node_type_set_defaults($info = array()) {
  718. $info = (array) $info;
  719. $new_type = $info + array(
  720. 'type' => '',
  721. 'name' => '',
  722. 'base' => '',
  723. 'description' => '',
  724. 'help' => '',
  725. 'custom' => 0,
  726. 'modified' => 0,
  727. 'locked' => 1,
  728. 'disabled' => 0,
  729. 'is_new' => 1,
  730. 'has_title' => 1,
  731. 'title_label' => 'Title',
  732. );
  733. $new_type = (object) $new_type;
  734. // If the type has no title, set an empty label.
  735. if (!$new_type->has_title) {
  736. $new_type->title_label = '';
  737. }
  738. if (empty($new_type->module)) {
  739. $new_type->module = $new_type->base == 'node_content' ? 'node' : '';
  740. }
  741. $new_type->orig_type = isset($info['type']) ? $info['type'] : '';
  742. return $new_type;
  743. }
  744. /**
  745. * Implements hook_rdf_mapping().
  746. */
  747. function node_rdf_mapping() {
  748. return array(
  749. array(
  750. 'type' => 'node',
  751. 'bundle' => RDF_DEFAULT_BUNDLE,
  752. 'mapping' => array(
  753. 'rdftype' => array('sioc:Item', 'foaf:Document'),
  754. 'title' => array(
  755. 'predicates' => array('dc:title'),
  756. ),
  757. 'created' => array(
  758. 'predicates' => array('dc:date', 'dc:created'),
  759. 'datatype' => 'xsd:dateTime',
  760. 'callback' => 'date_iso8601',
  761. ),
  762. 'changed' => array(
  763. 'predicates' => array('dc:modified'),
  764. 'datatype' => 'xsd:dateTime',
  765. 'callback' => 'date_iso8601',
  766. ),
  767. 'body' => array(
  768. 'predicates' => array('content:encoded'),
  769. ),
  770. 'uid' => array(
  771. 'predicates' => array('sioc:has_creator'),
  772. 'type' => 'rel',
  773. ),
  774. 'name' => array(
  775. 'predicates' => array('foaf:name'),
  776. ),
  777. 'comment_count' => array(
  778. 'predicates' => array('sioc:num_replies'),
  779. 'datatype' => 'xsd:integer',
  780. ),
  781. 'last_activity' => array(
  782. 'predicates' => array('sioc:last_activity_date'),
  783. 'datatype' => 'xsd:dateTime',
  784. 'callback' => 'date_iso8601',
  785. ),
  786. ),
  787. ),
  788. );
  789. }
  790. /**
  791. * Determines whether a node hook exists.
  792. *
  793. * @param Drupal\node\Node|string $node
  794. * A node entity or a string containing the node type.
  795. * @param $hook
  796. * A string containing the name of the hook.
  797. *
  798. * @return
  799. * TRUE if the $hook exists in the node type of $node.
  800. */
  801. function node_hook($node, $hook) {
  802. $base = node_type_get_base($node);
  803. return module_hook($base, $hook);
  804. }
  805. /**
  806. * Invokes a node hook.
  807. *
  808. * @param Drupal\node\Node|string $node
  809. * A node entity or a string containing the node type.
  810. * @param $hook
  811. * A string containing the name of the hook.
  812. * @param $a2, $a3, $a4
  813. * Arguments to pass on to the hook, after the $node argument.
  814. *
  815. * @return
  816. * The returned value of the invoked hook.
  817. */
  818. function node_invoke($node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
  819. if (node_hook($node, $hook)) {
  820. $base = node_type_get_base($node);
  821. $function = $base . '_' . $hook;
  822. return ($function($node, $a2, $a3, $a4));
  823. }
  824. }
  825. /**
  826. * Loads node entities from the database.
  827. *
  828. * This function should be used whenever you need to load more than one node
  829. * from the database. Nodes are loaded into memory and will not require
  830. * database access if loaded again during the same page request.
  831. *
  832. * @param array|bool $nids
  833. * (optional) An array of node IDs, or FALSE to load all nodes.
  834. * @param array $conditions
  835. * (deprecated) An associative array of conditions on the {node}
  836. * table, where the keys are the database fields and the values are the
  837. * values those fields must have. Instead, it is preferable to use
  838. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  839. * this function.
  840. * @param bool $reset
  841. * (optional) Whether to reset the internal node_load() cache.
  842. *
  843. * @return array
  844. * An array of node entities indexed by nid.
  845. *
  846. * @todo Remove $conditions in Drupal 8.
  847. *
  848. * @see entity_load_multiple()
  849. * @see EntityFieldQuery
  850. */
  851. function node_load_multiple($nids = array(), array $conditions = array(), $reset = FALSE) {
  852. return entity_load_multiple('node', $nids, $conditions, $reset);
  853. }
  854. /**
  855. * Loads a node entity from the database.
  856. *
  857. * @param int $nid
  858. * (optional) The node ID.
  859. * @param int $vid
  860. * (optional) The revision ID.
  861. * @param bool $reset
  862. * (optional) Whether to reset the node_load_multiple() cache.
  863. *
  864. * @return Drupal\node\Node|false
  865. * A fully-populated node entity, or FALSE if the node is not found.
  866. */
  867. function node_load($nid = NULL, $vid = NULL, $reset = FALSE) {
  868. $nids = (isset($nid) ? array($nid) : array());
  869. $conditions = (isset($vid) ? array('vid' => $vid) : array());
  870. $node = node_load_multiple($nids, $conditions, $reset);
  871. return $node ? reset($node) : FALSE;
  872. }
  873. /**
  874. * Prepares a node entity for editing.
  875. *
  876. * Fills in a few default values, and then invokes hook_prepare() on the node
  877. * type module, and hook_node_prepare() on all modules.
  878. *
  879. * @param Drupal\node\Node $node
  880. * The node entity.
  881. */
  882. function node_object_prepare(Node $node) {
  883. // Set up default values, if required.
  884. $node_options = variable_get('node_options_' . $node->type, array('status', 'promote'));
  885. // If this is a new node, fill in the default values.
  886. if (!isset($node->nid) || isset($node->is_new)) {
  887. foreach (array('status', 'promote', 'sticky') as $key) {
  888. // Multistep node forms might have filled in something already.
  889. if (!isset($node->$key)) {
  890. $node->$key = (int) in_array($key, $node_options);
  891. }
  892. }
  893. global $user;
  894. $node->uid = $user->uid;
  895. $node->created = REQUEST_TIME;
  896. }
  897. else {
  898. $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
  899. // Remove the log message from the original node entity.
  900. $node->log = NULL;
  901. }
  902. // Always use the default revision setting.
  903. $node->revision = in_array('revision', $node_options);
  904. node_invoke($node, 'prepare');
  905. module_invoke_all('node_prepare', $node);
  906. }
  907. /**
  908. * Performs validation checks on the given node.
  909. *
  910. * @see node_form_validate()
  911. */
  912. function node_validate(Node $node, $form, &$form_state) {
  913. $type = node_type_load($node->type);
  914. if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  915. form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
  916. }
  917. // Validate the "authored by" field.
  918. if (!empty($node->name) && !($account = user_load_by_name($node->name))) {
  919. // The use of empty() is mandatory in the context of usernames
  920. // as the empty string denotes the anonymous user. In case we
  921. // are dealing with an anonymous user we set the user ID to 0.
  922. form_set_error('name', t('The username %name does not exist.', array('%name' => $node->name)));
  923. }
  924. // Validate the "authored on" field.
  925. if (!empty($node->date) && strtotime($node->date) === FALSE) {
  926. form_set_error('date', t('You have to specify a valid date.'));
  927. }
  928. // Invoke hook_validate() for node type specific validation and
  929. // hook_node_validate() for miscellaneous validation needed by modules. Can't
  930. // use node_invoke() or module_invoke_all(), because $form_state must be
  931. // receivable by reference.
  932. $function = node_type_get_base($node) . '_validate';
  933. if (function_exists($function)) {
  934. $function($node, $form, $form_state);
  935. }
  936. foreach (module_implements('node_validate') as $module) {
  937. $function = $module . '_node_validate';
  938. $function($node, $form, $form_state);
  939. }
  940. }
  941. /**
  942. * Prepares a node for saving by populating the author and creation date.
  943. */
  944. function node_submit($node) {
  945. global $user;
  946. // A user might assign the node author by entering a user name in the node
  947. // form, which we then need to translate to a user ID.
  948. if (isset($node->name)) {
  949. if ($account = user_load_by_name($node->name)) {
  950. $node->uid = $account->uid;
  951. }
  952. else {
  953. $node->uid = 0;
  954. }
  955. }
  956. // If a new revision is created, save the current user as revision author.
  957. if (!empty($node->revision)) {
  958. $node->revision_uid = $user->uid;
  959. }
  960. $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME;
  961. $node->validated = TRUE;
  962. return $node;
  963. }
  964. /**
  965. * Saves changes to a node or adds a new node.
  966. *
  967. * @param Drupal\node\Node $node
  968. * The $node entity to be saved. If $node->nid is
  969. * omitted (or $node->is_new is TRUE), a new node will be added.
  970. */
  971. function node_save(Node $node) {
  972. $node->save();
  973. }
  974. /**
  975. * Deletes a node.
  976. *
  977. * @param $nid
  978. * A node ID.
  979. */
  980. function node_delete($nid) {
  981. node_delete_multiple(array($nid));
  982. }
  983. /**
  984. * Deletes multiple nodes.
  985. *
  986. * @param $nids
  987. * An array of node IDs.
  988. *
  989. * @see hook_node_predelete()
  990. * @see hook_node_delete()
  991. */
  992. function node_delete_multiple($nids) {
  993. entity_delete_multiple('node', $nids);
  994. }
  995. /**
  996. * Deletes a node revision.
  997. *
  998. * @param $revision_id
  999. * The revision ID to delete.
  1000. *
  1001. * @return
  1002. * TRUE if the revision deletion was successful.
  1003. */
  1004. function node_revision_delete($revision_id) {
  1005. if ($revision = node_load(NULL, $revision_id)) {
  1006. // Prevent deleting the current revision.
  1007. $node = node_load($revision->nid);
  1008. if ($revision_id == $node->vid) {
  1009. return FALSE;
  1010. }
  1011. db_delete('node_revision')
  1012. ->condition('nid', $revision->nid)
  1013. ->condition('vid', $revision->vid)
  1014. ->execute();
  1015. module_invoke_all('node_revision_delete', $revision);
  1016. field_attach_delete_revision('node', $revision);
  1017. return TRUE;
  1018. }
  1019. return FALSE;
  1020. }
  1021. /**
  1022. * Generates an array for rendering the given node.
  1023. *
  1024. * @param Drupal\node\Node $node
  1025. * A node entity.
  1026. * @param $view_mode
  1027. * (optional) View mode, e.g., 'full', 'teaser'... Defaults to 'full.'
  1028. * @param $langcode
  1029. * (optional) A language code to use for rendering. Defaults to the global
  1030. * content language of the current request.
  1031. *
  1032. * @return
  1033. * An array as expected by drupal_render().
  1034. */
  1035. function node_view(Node $node, $view_mode = 'full', $langcode = NULL) {
  1036. if (!isset($langcode)) {
  1037. $langcode = $GLOBALS['language_content']->langcode;
  1038. }
  1039. // Populate $node->content with a render() array.
  1040. node_build_content($node, $view_mode, $langcode);
  1041. $build = $node->content;
  1042. // We don't need duplicate rendering info in node->content.
  1043. unset($node->content);
  1044. $build += array(
  1045. '#theme' => 'node',
  1046. '#node' => $node,
  1047. '#view_mode' => $view_mode,
  1048. '#langcode' => $langcode,
  1049. );
  1050. // Add contextual links for this node, except when the node is already being
  1051. // displayed on its own page. Modules may alter this behavior (for example,
  1052. // to restrict contextual links to certain view modes) by implementing
  1053. // hook_node_view_alter().
  1054. if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node))) {
  1055. $build['#contextual_links']['node'] = array('node', array($node->nid));
  1056. }
  1057. // Allow modules to modify the structured node.
  1058. $type = 'node';
  1059. drupal_alter(array('node_view', 'entity_view'), $build, $type);
  1060. return $build;
  1061. }
  1062. /**
  1063. * Builds a structured array representing the node's content.
  1064. *
  1065. * The content built for the node (field values, comments, file attachments or
  1066. * other node components) will vary depending on the $view_mode parameter.
  1067. *
  1068. * Drupal core defines the following view modes for nodes, with the following
  1069. * default use cases:
  1070. * - full (default): node is being displayed on its own page (node/123)
  1071. * - teaser: node is being displayed on the default home page listing, or on
  1072. * taxonomy listing pages.
  1073. * - rss: node displayed in an RSS feed.
  1074. * If search.module is enabled:
  1075. * - search_index: node is being indexed for search.
  1076. * - search_result: node is being displayed as a search result.
  1077. * If book.module is enabled:
  1078. * - print: node is being displayed in print-friendly mode.
  1079. * Contributed modules might define additional view modes, or use existing
  1080. * view modes in additional contexts.
  1081. *
  1082. * @param Drupal\node\Node $node
  1083. * A node entity.
  1084. * @param $view_mode
  1085. * (optional) View mode, e.g., 'full', 'teaser'... Defaults to 'full.'
  1086. * @param $langcode
  1087. * (optional) A language code to use for rendering. Defaults to the global
  1088. * content language of the current request.
  1089. */
  1090. function node_build_content(Node $node, $view_mode = 'full', $langcode = NULL) {
  1091. if (!isset($langcode)) {
  1092. $langcode = $GLOBALS['language_content']->langcode;
  1093. }
  1094. // Remove previously built content, if exists.
  1095. $node->content = array();
  1096. // The 'view' hook can be implemented to overwrite the default function
  1097. // to display nodes.
  1098. if (node_hook($node, 'view')) {
  1099. $node = node_invoke($node, 'view', $view_mode, $langcode);
  1100. }
  1101. // Build fields content.
  1102. // In case of a multiple view, node_view_multiple() already ran the
  1103. // 'prepare_view' step. An internal flag prevents the operation from running
  1104. // twice.
  1105. field_attach_prepare_view('node', array($node->nid => $node), $view_mode, $langcode);
  1106. entity_prepare_view('node', array($node->nid => $node), $langcode);
  1107. $node->content += field_attach_view('node', $node, $view_mode, $langcode);
  1108. // Always display a read more link on teasers because we have no way
  1109. // to know when a teaser view is different than a full view.
  1110. $links = array();
  1111. $node->content['links'] = array(
  1112. '#theme' => 'links__node',
  1113. '#pre_render' => array('drupal_pre_render_links'),
  1114. '#attributes' => array('class' => array('links', 'inline')),
  1115. );
  1116. if ($view_mode == 'teaser') {
  1117. $node_title_stripped = strip_tags($node->title);
  1118. $links['node-readmore'] = array(
  1119. 'title' => t('Read more<span class="element-invisible"> about @title</span>', array('@title' => $node_title_stripped)),
  1120. 'href' => 'node/' . $node->nid,
  1121. 'html' => TRUE,
  1122. 'attributes' => array('rel' => 'tag', 'title' => $node_title_stripped),
  1123. );
  1124. }
  1125. $node->content['links']['node'] = array(
  1126. '#theme' => 'links__node__node',
  1127. '#links' => $links,
  1128. '#attributes' => array('class' => array('links', 'inline')),
  1129. );
  1130. // Allow modules to make their own additions to the node.
  1131. module_invoke_all('node_view', $node, $view_mode, $langcode);
  1132. module_invoke_all('entity_view', $node, 'node', $view_mode, $langcode);
  1133. }
  1134. /**
  1135. * Page callback: Generates an array which displays a node detail page.
  1136. *
  1137. * @param Drupal\node\Node $node
  1138. * A node entity.
  1139. * @param $message
  1140. * (optional) A flag which sets a page title relevant to the revision being
  1141. * viewed.
  1142. *
  1143. * @return
  1144. * A $page element suitable for use by drupal_render().
  1145. *
  1146. * @see node_menu()
  1147. */
  1148. function node_show(Node $node, $message = FALSE) {
  1149. if ($message) {
  1150. drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
  1151. }
  1152. // For markup consistency with other pages, use node_view_multiple() rather than node_view().
  1153. $nodes = node_view_multiple(array($node->nid => $node), 'full');
  1154. // Update the history table, stating that this user viewed this node.
  1155. node_tag_new($node);
  1156. return $nodes;
  1157. }
  1158. /**
  1159. * Checks whether the current page is the full page view of the passed-in node.
  1160. *
  1161. * @param Drupal\node\Node $node
  1162. * A node entity.
  1163. *
  1164. * @return
  1165. * The ID of the node if this is a full page view, otherwise FALSE.
  1166. */
  1167. function node_is_page(Node $node) {
  1168. $page_node = menu_get_object();
  1169. return (!empty($page_node) ? $page_node->nid == $node->nid : FALSE);
  1170. }
  1171. /**
  1172. * Implements hook_preprocess_HOOK() for block.tpl.php.
  1173. */
  1174. function node_preprocess_block(&$variables) {
  1175. if ($variables['block']->module == 'node') {
  1176. switch ($variables['block']->delta) {
  1177. case 'syndicate':
  1178. $variables['attributes_array']['role'] = 'complementary';
  1179. break;
  1180. case 'recent':
  1181. $variables['attributes_array']['role'] = 'navigation';
  1182. break;
  1183. }
  1184. }
  1185. }
  1186. /**
  1187. * Processes variables for node.tpl.php.
  1188. *
  1189. * Most themes utilize their own copy of node.tpl.php. The default is located
  1190. * inside "modules/node/node.tpl.php". Look in there for the full list of
  1191. * variables.
  1192. *
  1193. * @param $variables
  1194. * An array containing the following arguments:
  1195. * - $node
  1196. * - $view_mode
  1197. * - $page
  1198. *
  1199. * @see node.tpl.php
  1200. */
  1201. function template_preprocess_node(&$variables) {
  1202. $variables['view_mode'] = $variables['elements']['#view_mode'];
  1203. // Provide a distinct $teaser boolean.
  1204. $variables['teaser'] = $variables['view_mode'] == 'teaser';
  1205. $variables['node'] = $variables['elements']['#node'];
  1206. $node = $variables['node'];
  1207. $variables['date'] = format_date($node->created);
  1208. $variables['name'] = theme('username', array(
  1209. 'account' => $node,
  1210. 'link_attributes' => array('rel' => 'author'),
  1211. ));
  1212. $uri = entity_uri('node', $node);
  1213. $variables['node_url'] = url($uri['path'], $uri['options']);
  1214. $variables['title'] = check_plain($node->title);
  1215. $variables['page'] = $variables['view_mode'] == 'full' && node_is_page($node);
  1216. // Flatten the node entity's member fields.
  1217. $variables = array_merge((array) $node, $variables);
  1218. // Helpful $content variable for templates.
  1219. $variables += array('content' => array());
  1220. foreach (element_children($variables['elements']) as $key) {
  1221. $variables['content'][$key] = $variables['elements'][$key];
  1222. }
  1223. // Make the field variables available with the appropriate language.
  1224. field_attach_preprocess('node', $node, $variables['content'], $variables);
  1225. // Display post information only on certain node types.
  1226. if (variable_get('node_submitted_' . $node->type, TRUE)) {
  1227. $variables['display_submitted'] = TRUE;
  1228. $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
  1229. $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
  1230. }
  1231. else {
  1232. $variables['display_submitted'] = FALSE;
  1233. $variables['submitted'] = '';
  1234. $variables['user_picture'] = '';
  1235. }
  1236. // Add article ARIA role.
  1237. $variables['attributes_array']['role'] = 'article';
  1238. // Gather node classes.
  1239. $variables['classes_array'][] = drupal_html_class('node-' . $node->type);
  1240. if ($variables['promote']) {
  1241. $variables['classes_array'][] = 'promoted';
  1242. }
  1243. if ($variables['sticky']) {
  1244. $variables['classes_array'][] = 'sticky';
  1245. }
  1246. if (!$variables['status']) {
  1247. $variables['classes_array'][] = 'unpublished';
  1248. }
  1249. if ($variables['view_mode']) {
  1250. $variables['classes_array'][] = drupal_html_class('view-mode-' . $variables['view_mode']);
  1251. }
  1252. if (isset($variables['preview'])) {
  1253. $variables['classes_array'][] = 'preview';
  1254. }
  1255. // Clean up name so there are no underscores.
  1256. $variables['theme_hook_suggestions'][] = 'node__' . $node->type;
  1257. $variables['theme_hook_suggestions'][] = 'node__' . $node->nid;
  1258. }
  1259. /**
  1260. * Implements hook_permission().
  1261. */
  1262. function node_permission() {
  1263. $perms = array(
  1264. 'bypass node access' => array(
  1265. 'title' => t('Bypass content access control'),
  1266. 'description' => t('View, edit and delete all content regardless of permission restrictions.'),
  1267. 'restrict access' => TRUE,
  1268. ),
  1269. 'administer content types' => array(
  1270. 'title' => t('Administer content types'),
  1271. 'restrict access' => TRUE,
  1272. ),
  1273. 'administer nodes' => array(
  1274. 'title' => t('Administer content'),
  1275. 'restrict access' => TRUE,
  1276. ),
  1277. 'access content overview' => array(
  1278. 'title' => t('Access the content overview page'),
  1279. ),
  1280. 'access content' => array(
  1281. 'title' => t('View published content'),
  1282. ),
  1283. 'view own unpublished content' => array(
  1284. 'title' => t('View own unpublished content'),
  1285. ),
  1286. 'view revisions' => array(
  1287. 'title' => t('View content revisions'),
  1288. ),
  1289. 'revert revisions' => array(
  1290. 'title' => t('Revert content revisions'),
  1291. ),
  1292. 'delete revisions' => array(
  1293. 'title' => t('Delete content revisions'),
  1294. ),
  1295. );
  1296. // Generate standard node permissions for all applicable node types.
  1297. foreach (node_permissions_get_configured_types() as $name => $type) {
  1298. $perms += node_list_permissions($type);
  1299. }
  1300. return $perms;
  1301. }
  1302. /**
  1303. * Gathers the rankings from the the hook_ranking() implementations.
  1304. *
  1305. * @param $query
  1306. * A query object that has been extended with the Search DB Extender.
  1307. */
  1308. function _node_rankings(SelectExtender $query) {
  1309. if ($ranking = module_invoke_all('ranking')) {
  1310. $tables = &$query->getTables();
  1311. foreach ($ranking as $rank => $values) {
  1312. if ($node_rank = variable_get('node_rank_' . $rank, 0)) {
  1313. // If the table defined in the ranking isn't already joined, then add it.
  1314. if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
  1315. $query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
  1316. }
  1317. $arguments = isset($values['arguments']) ? $values['arguments'] : array();
  1318. $query->addScore($values['score'], $arguments, $node_rank);
  1319. }
  1320. }
  1321. }
  1322. }
  1323. /**
  1324. * Implements hook_search_info().
  1325. */
  1326. function node_search_info() {
  1327. return array(
  1328. 'title' => 'Content',
  1329. 'path' => 'node',
  1330. );
  1331. }
  1332. /**
  1333. * Implements hook_search_access().
  1334. */
  1335. function node_search_access() {
  1336. return user_access('access content');
  1337. }
  1338. /**
  1339. * Implements hook_search_reset().
  1340. */
  1341. function node_search_reset() {
  1342. db_update('search_dataset')
  1343. ->fields(array('reindex' => REQUEST_TIME))
  1344. ->condition('type', 'node')
  1345. ->execute();
  1346. }
  1347. /**
  1348. * Implements hook_search_status().
  1349. */
  1350. function node_search_status() {
  1351. $total = db_query('SELECT COUNT(*) FROM {node}')->fetchField();
  1352. $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();
  1353. return array('remaining' => $remaining, 'total' => $total);
  1354. }
  1355. /**
  1356. * Implements hook_search_admin().
  1357. */
  1358. function node_search_admin() {
  1359. // Output form for defining rank factor weights.
  1360. $form['content_ranking'] = array(
  1361. '#type' => 'fieldset',
  1362. '#title' => t('Content ranking'),
  1363. );
  1364. $form['content_ranking']['#theme'] = 'node_search_admin';
  1365. $form['content_ranking']['info'] = array(
  1366. '#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>'
  1367. );
  1368. // Note: reversed to reflect that higher number = higher ranking.
  1369. $options = drupal_map_assoc(range(0, 10));
  1370. foreach (module_invoke_all('ranking') as $var => $values) {
  1371. $form['content_ranking']['factors']['node_rank_' . $var] = array(
  1372. '#title' => $values['title'],
  1373. '#type' => 'select',
  1374. '#options' => $options,
  1375. '#default_value' => variable_get('node_rank_' . $var, 0),
  1376. );
  1377. }
  1378. return $form;
  1379. }
  1380. /**
  1381. * Implements hook_search_execute().
  1382. */
  1383. function node_search_execute($keys = NULL, $conditions = NULL) {
  1384. // Build matching conditions
  1385. $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('Drupal\search\SearchQuery')->extend('PagerDefault');
  1386. $query->join('node', 'n', 'n.nid = i.sid');
  1387. $query
  1388. ->condition('n.status', 1)
  1389. ->addTag('node_access')
  1390. ->searchExpression($keys, 'node');
  1391. // Insert special keywords.
  1392. $query->setOption('type', 'n.type');
  1393. $query->setOption('langcode', 'n.langcode');
  1394. if ($query->setOption('term', 'ti.tid')) {
  1395. $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  1396. }
  1397. // Only continue if the first pass query matches.
  1398. if (!$query->executeFirstPass()) {
  1399. return array();
  1400. }
  1401. // Add the ranking expressions.
  1402. _node_rankings($query);
  1403. // Load results.
  1404. $find = $query
  1405. ->limit(10)
  1406. ->execute();
  1407. $results = array();
  1408. foreach ($find as $item) {
  1409. // Render the node.
  1410. $node = node_load($item->sid);
  1411. $build = node_view($node, 'search_result');
  1412. unset($build['#theme']);
  1413. $node->rendered = drupal_render($build);
  1414. // Fetch comments for snippet.
  1415. $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
  1416. $extra = module_invoke_all('node_search_result', $node);
  1417. $uri = entity_uri('node', $node);
  1418. $results[] = array(
  1419. 'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
  1420. 'type' => check_plain(node_type_get_name($node)),
  1421. 'title' => $node->title,
  1422. 'user' => theme('username', array('account' => $node)),
  1423. 'date' => $node->changed,
  1424. 'node' => $node,
  1425. 'extra' => $extra,
  1426. 'score' => $item->calculated_score,
  1427. 'snippet' => search_excerpt($keys, $node->rendered),
  1428. 'langcode' => $node->langcode,
  1429. );
  1430. }
  1431. return $results;
  1432. }
  1433. /**
  1434. * Implements hook_ranking().
  1435. */
  1436. function node_ranking() {
  1437. // Create the ranking array and add the basic ranking options.
  1438. $ranking = array(
  1439. 'relevance' => array(
  1440. 'title' => t('Keyword relevance'),
  1441. // Average relevance values hover around 0.15
  1442. 'score' => 'i.relevance',
  1443. ),
  1444. 'sticky' => array(
  1445. 'title' => t('Content is sticky at top of lists'),
  1446. // The sticky flag is either 0 or 1, which is automatically normalized.
  1447. 'score' => 'n.sticky',
  1448. ),
  1449. 'promote' => array(
  1450. 'title' => t('Content is promoted to the front page'),
  1451. // The promote flag is either 0 or 1, which is automatically normalized.
  1452. 'score' => 'n.promote',
  1453. ),
  1454. );
  1455. // Add relevance based on creation or changed date.
  1456. if ($node_cron_last = variable_get('node_cron_last', 0)) {
  1457. $ranking['recent'] = array(
  1458. 'title' => t('Recently posted'),
  1459. // Exponential decay with half-life of 6 months, starting at last indexed node
  1460. 'score' => 'POW(2.0, (GREATEST(n.created, n.changed) - :node_cron_last) * 6.43e-8)',
  1461. 'arguments' => array(':node_cron_last' => $node_cron_last),
  1462. );
  1463. }
  1464. return $ranking;
  1465. }
  1466. /**
  1467. * Implements hook_user_cancel().
  1468. */
  1469. function node_user_cancel($edit, $account, $method) {
  1470. switch ($method) {
  1471. case 'user_cancel_block_unpublish':
  1472. // Unpublish nodes (current revisions).
  1473. module_load_include('inc', 'node', 'node.admin');
  1474. $nodes = db_select('node', 'n')
  1475. ->fields('n', array('nid'))
  1476. ->condition('uid', $account->uid)
  1477. ->execute()
  1478. ->fetchCol();
  1479. node_mass_update($nodes, array('status' => 0));
  1480. break;
  1481. case 'user_cancel_reassign':
  1482. // Anonymize nodes (current revisions).
  1483. module_load_include('inc', 'node', 'node.admin');
  1484. $nodes = db_select('node', 'n')
  1485. ->fields('n', array('nid'))
  1486. ->condition('uid', $account->uid)
  1487. ->execute()
  1488. ->fetchCol();
  1489. node_mass_update($nodes, array('uid' => 0));
  1490. // Anonymize old revisions.
  1491. db_update('node_revision')
  1492. ->fields(array('uid' => 0))
  1493. ->condition('uid', $account->uid)
  1494. ->execute();
  1495. // Clean history.
  1496. db_delete('history')
  1497. ->condition('uid', $account->uid)
  1498. ->execute();
  1499. break;
  1500. }
  1501. }
  1502. /**
  1503. * Implements hook_user_predelete().
  1504. */
  1505. function node_user_predelete($account) {
  1506. // Delete nodes (current revisions).
  1507. // @todo Introduce node_mass_delete() or make node_mass_update() more flexible.
  1508. $nodes = db_select('node', 'n')
  1509. ->fields('n', array('nid'))
  1510. ->condition('uid', $account->uid)
  1511. ->execute()
  1512. ->fetchCol();
  1513. node_delete_multiple($nodes);
  1514. // Delete old revisions.
  1515. $revisions = db_query('SELECT vid FROM {node_revision} WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol();
  1516. foreach ($revisions as $revision) {
  1517. node_revision_delete($revision);
  1518. }
  1519. // Clean history.
  1520. db_delete('history')
  1521. ->condition('uid', $account->uid)
  1522. ->execute();
  1523. }
  1524. /**
  1525. * Returns HTML for the content ranking part of the search settings admin page.
  1526. *
  1527. * @param $variables
  1528. * An associative array containing:
  1529. * - form: A render element representing the form.
  1530. *
  1531. * @see node_search_admin()
  1532. * @ingroup themeable
  1533. */
  1534. function theme_node_search_admin($variables) {
  1535. $form = $variables['form'];
  1536. $output = drupal_render($form['info']);
  1537. $header = array(t('Factor'), t('Weight'));
  1538. foreach (element_children($form['factors']) as $key) {
  1539. $row = array();
  1540. $row[] = $form['factors'][$key]['#title'];
  1541. $form['factors'][$key]['#title_display'] = 'invisible';
  1542. $row[] = drupal_render($form['factors'][$key]);
  1543. $rows[] = $row;
  1544. }
  1545. $output .= theme('table', array('header' => $header, 'rows' => $rows));
  1546. $output .= drupal_render_children($form);
  1547. return $output;
  1548. }
  1549. /**
  1550. * Access callback: Checks node revision access.
  1551. *
  1552. * @param Drupal\node\Node $node
  1553. * The node to check.
  1554. * @param $op
  1555. * (optional) The specific operation being checked. Defaults to 'view.'
  1556. * @param object $account
  1557. * (optional) A user object representing the user for whom the operation is
  1558. * to be performed. Determines access for a user other than the current user.
  1559. *
  1560. * @return
  1561. * TRUE if the operation may be performed, FALSE otherwise.
  1562. *
  1563. * @see node_menu()
  1564. */
  1565. function _node_revision_access(Node $node, $op = 'view', $account = NULL) {
  1566. $access = &drupal_static(__FUNCTION__, array());
  1567. $map = array(
  1568. 'view' => 'view revisions',
  1569. 'update' => 'revert revisions',
  1570. 'delete' => 'delete revisions',
  1571. );
  1572. if (!$node || !isset($map[$op])) {
  1573. // If there was no node to check against, or the $op was not one of the
  1574. // supported ones, we return access denied.
  1575. return FALSE;
  1576. }
  1577. if (!isset($account)) {
  1578. $account = $GLOBALS['user'];
  1579. }
  1580. // Statically cache access by revision ID, user account ID, and operation.
  1581. $cid = $node->vid . ':' . $account->uid . ':' . $op;
  1582. if (!isset($access[$cid])) {
  1583. // Perform basic permission checks first.
  1584. if (!user_access($map[$op], $account) && !user_access('administer nodes', $account)) {
  1585. return $access[$cid] = FALSE;
  1586. }
  1587. $node_current_revision = node_load($node->nid);
  1588. $is_current_revision = $node_current_revision->vid == $node->vid;
  1589. // There should be at least two revisions. If the vid of the given node
  1590. // and the vid of the current revision differ, then we already have two
  1591. // different revisions so there is no need for a separate database check.
  1592. // Also, if you try to revert to or delete the current revision, that's
  1593. // not good.
  1594. if ($is_current_revision && (db_query('SELECT COUNT(vid) FROM {node_revision} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField() == 1 || $op == 'update' || $op == 'delete')) {
  1595. $access[$cid] = FALSE;
  1596. }
  1597. elseif (user_access('administer nodes', $account)) {
  1598. $access[$cid] = TRUE;
  1599. }
  1600. else {
  1601. // First check the access to the current revision and finally, if the
  1602. // node passed in is not the current revision then access to that, too.
  1603. $access[$cid] = node_access($op, $node_current_revision, $account) && ($is_current_revision || node_access($op, $node, $account));
  1604. }
  1605. }
  1606. return $access[$cid];
  1607. }
  1608. /**
  1609. * Access callback: Checks whether the user has permission to add a node.
  1610. *
  1611. * @return
  1612. * TRUE if the user has permission, otherwise FALSE.
  1613. *
  1614. * @see node_menu()
  1615. */
  1616. function _node_add_access() {
  1617. $types = node_type_get_types();
  1618. foreach ($types as $type) {
  1619. if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
  1620. return TRUE;
  1621. }
  1622. }
  1623. if (user_access('administer content types')) {
  1624. // There are no content types defined that the user has permission to create,
  1625. // but the user does have the permission to administer the content types, so
  1626. // grant them access to the page anyway.
  1627. return TRUE;
  1628. }
  1629. return FALSE;
  1630. }
  1631. /**
  1632. * Implements hook_menu().
  1633. */
  1634. function node_menu() {
  1635. $items['admin/content'] = array(
  1636. 'title' => 'Content',
  1637. 'description' => 'Find and manage content.',
  1638. 'page callback' => 'drupal_get_form',
  1639. 'page arguments' => array('node_admin_content'),
  1640. 'access arguments' => array('access content overview'),
  1641. 'weight' => -10,
  1642. 'file' => 'node.admin.inc',
  1643. );
  1644. $items['admin/content/node'] = array(
  1645. 'title' => 'Content',
  1646. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1647. 'weight' => -10,
  1648. );
  1649. $items['admin/reports/status/rebuild'] = array(
  1650. 'title' => 'Rebuild permissions',
  1651. 'page callback' => 'drupal_get_form',
  1652. 'page arguments' => array('node_configure_rebuild_confirm'),
  1653. // Any user than can potentially trigger a node_access_needs_rebuild(TRUE)
  1654. // has to be allowed access to the 'node access rebuild' confirm form.
  1655. 'access arguments' => array('access administration pages'),
  1656. 'type' => MENU_CALLBACK,
  1657. 'file' => 'node.admin.inc',
  1658. );
  1659. $items['admin/structure/types'] = array(
  1660. 'title' => 'Content types',
  1661. 'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
  1662. 'page callback' => 'node_overview_types',
  1663. 'access arguments' => array('administer content types'),
  1664. 'file' => 'content_types.inc',
  1665. );
  1666. $items['admin/structure/types/list'] = array(
  1667. 'title' => 'List',
  1668. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1669. 'weight' => -10,
  1670. );
  1671. $items['admin/structure/types/add'] = array(
  1672. 'title' => 'Add content type',
  1673. 'page callback' => 'drupal_get_form',
  1674. 'page arguments' => array('node_type_form'),
  1675. 'access arguments' => array('administer content types'),
  1676. 'type' => MENU_LOCAL_ACTION,
  1677. 'file' => 'content_types.inc',
  1678. );
  1679. $items['admin/structure/types/manage/%node_type'] = array(
  1680. 'title' => 'Edit content type',
  1681. 'title callback' => 'node_type_page_title',
  1682. 'title arguments' => array(4),
  1683. 'page callback' => 'drupal_get_form',
  1684. 'page arguments' => array('node_type_form', 4),
  1685. 'access arguments' => array('administer content types'),
  1686. 'file' => 'content_types.inc',
  1687. );
  1688. $items['admin/structure/types/manage/%node_type/edit'] = array(
  1689. 'title' => 'Edit',
  1690. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1691. );
  1692. $items['admin/structure/types/manage/%node_type/delete'] = array(
  1693. 'title' => 'Delete',
  1694. 'page arguments' => array('node_type_delete_confirm', 4),
  1695. 'access arguments' => array('administer content types'),
  1696. 'file' => 'content_types.inc',
  1697. );
  1698. $items['node'] = array(
  1699. 'page callback' => 'node_page_default',
  1700. 'access arguments' => array('access content'),
  1701. 'menu_name' => 'navigation',
  1702. 'type' => MENU_CALLBACK,
  1703. );
  1704. $items['node/add'] = array(
  1705. 'title' => 'Add content',
  1706. 'page callback' => 'node_add_page',
  1707. 'access callback' => '_node_add_access',
  1708. 'file' => 'node.pages.inc',
  1709. );
  1710. $items['rss.xml'] = array(
  1711. 'title' => 'RSS feed',
  1712. 'page callback' => 'node_feed',
  1713. 'access arguments' => array('access content'),
  1714. 'type' => MENU_CALLBACK,
  1715. );
  1716. // @todo Remove this loop when we have a 'description callback' property.
  1717. foreach (node_type_get_types() as $type) {
  1718. $items['node/add/' . $type->type] = array(
  1719. 'title' => $type->name,
  1720. 'title callback' => 'check_plain',
  1721. 'page callback' => 'node_add',
  1722. 'page arguments' => array($type->type),
  1723. 'access callback' => 'node_access',
  1724. 'access arguments' => array('create', $type->type),
  1725. 'description' => $type->description,
  1726. 'file' => 'node.pages.inc',
  1727. );
  1728. }
  1729. $items['node/%node'] = array(
  1730. 'title callback' => 'node_page_title',
  1731. 'title arguments' => array(1),
  1732. // The page callback also invokes drupal_set_title() in case
  1733. // the menu router's title is overridden by a menu link.
  1734. 'page callback' => 'node_page_view',
  1735. 'page arguments' => array(1),
  1736. 'access callback' => 'node_access',
  1737. 'access arguments' => array('view', 1),
  1738. );
  1739. $items['node/%node/view'] = array(
  1740. 'title' => 'View',
  1741. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1742. 'weight' => -10,
  1743. );
  1744. $items['node/%node/edit'] = array(
  1745. 'title' => 'Edit',
  1746. 'page callback' => 'node_page_edit',
  1747. 'page arguments' => array(1),
  1748. 'access callback' => 'node_access',
  1749. 'access arguments' => array('update', 1),
  1750. 'weight' => 0,
  1751. 'type' => MENU_LOCAL_TASK,
  1752. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  1753. 'file' => 'node.pages.inc',
  1754. );
  1755. $items['node/%node/delete'] = array(
  1756. 'title' => 'Delete',
  1757. 'page callback' => 'drupal_get_form',
  1758. 'page arguments' => array('node_delete_confirm', 1),
  1759. 'access callback' => 'node_access',
  1760. 'access arguments' => array('delete', 1),
  1761. 'weight' => 1,
  1762. 'type' => MENU_LOCAL_TASK,
  1763. 'context' => MENU_CONTEXT_INLINE,
  1764. 'file' => 'node.pages.inc',
  1765. );
  1766. $items['node/%node/revisions'] = array(
  1767. 'title' => 'Revisions',
  1768. 'page callback' => 'node_revision_overview',
  1769. 'page arguments' => array(1),
  1770. 'access callback' => '_node_revision_access',
  1771. 'access arguments' => array(1),
  1772. 'weight' => 2,
  1773. 'type' => MENU_LOCAL_TASK,
  1774. 'file' => 'node.pages.inc',
  1775. );
  1776. $items['node/%node/revisions/%/view'] = array(
  1777. 'title' => 'Revisions',
  1778. 'load arguments' => array(3),
  1779. 'page callback' => 'node_show',
  1780. 'page arguments' => array(1, TRUE),
  1781. 'access callback' => '_node_revision_access',
  1782. 'access arguments' => array(1),
  1783. );
  1784. $items['node/%node/revisions/%/revert'] = array(
  1785. 'title' => 'Revert to earlier revision',
  1786. 'load arguments' => array(3),
  1787. 'page callback' => 'drupal_get_form',
  1788. 'page arguments' => array('node_revision_revert_confirm', 1),
  1789. 'access callback' => '_node_revision_access',
  1790. 'access arguments' => array(1, 'update'),
  1791. 'file' => 'node.pages.inc',
  1792. );
  1793. $items['node/%node/revisions/%/delete'] = array(
  1794. 'title' => 'Delete earlier revision',
  1795. 'load arguments' => array(3),
  1796. 'page callback' => 'drupal_get_form',
  1797. 'page arguments' => array('node_revision_delete_confirm', 1),
  1798. 'access callback' => '_node_revision_access',
  1799. 'access arguments' => array(1, 'delete'),
  1800. 'file' => 'node.pages.inc',
  1801. );
  1802. return $items;
  1803. }
  1804. /**
  1805. * Implements hook_menu_local_tasks_alter().
  1806. */
  1807. function node_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  1808. // Add action link to 'node/add' on 'admin/content' page.
  1809. if ($root_path == 'admin/content') {
  1810. $item = menu_get_item('node/add');
  1811. if ($item['access']) {
  1812. $data['actions']['output'][] = array(
  1813. '#theme' => 'menu_local_action',
  1814. '#link' => $item,
  1815. );
  1816. }
  1817. }
  1818. }
  1819. /**
  1820. * Title callback: Provides the title for a node type edit form.
  1821. *
  1822. * @param $type
  1823. * The node type object.
  1824. *
  1825. * @see node_menu()
  1826. */
  1827. function node_type_page_title($type) {
  1828. return $type->name;
  1829. }
  1830. /**
  1831. * Title callback: Displays the node's title.
  1832. *
  1833. * @param Drupal\node\Node $node
  1834. * The node entity.
  1835. *
  1836. * @see node_menu()
  1837. */
  1838. function node_page_title(Node $node) {
  1839. return $node->title;
  1840. }
  1841. /**
  1842. * Finds the last time a node was changed.
  1843. *
  1844. * @param $nid
  1845. * The ID of a node.
  1846. *
  1847. * @return
  1848. * A unix timestamp indicating the last time the node was changed.
  1849. */
  1850. function node_last_changed($nid) {
  1851. return db_query('SELECT changed FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetch()->changed;
  1852. }
  1853. /**
  1854. * Returns a list of all the existing revision numbers for the node passed in.
  1855. *
  1856. * @param Drupal\node\Node $node
  1857. * The node entity.
  1858. */
  1859. function node_revision_list(Node $node) {
  1860. $revisions = array();
  1861. $result = db_query('SELECT r.vid, r.title, r.log, r.uid, n.vid AS current_vid, r.timestamp, u.name FROM {node_revision} r LEFT JOIN {node} n ON n.vid = r.vid INNER JOIN {users} u ON u.uid = r.uid WHERE r.nid = :nid ORDER BY r.vid DESC', array(':nid' => $node->nid));
  1862. foreach ($result as $revision) {
  1863. $revisions[$revision->vid] = $revision;
  1864. }
  1865. return $revisions;
  1866. }
  1867. /**
  1868. * Implements hook_block_info().
  1869. */
  1870. function node_block_info() {
  1871. $blocks['syndicate']['info'] = t('Syndicate');
  1872. // Not worth caching.
  1873. $blocks['syndicate']['cache'] = DRUPAL_NO_CACHE;
  1874. $blocks['recent']['info'] = t('Recent content');
  1875. $blocks['recent']['properties']['administrative'] = TRUE;
  1876. return $blocks;
  1877. }
  1878. /**
  1879. * Implements hook_block_view().
  1880. */
  1881. function node_block_view($delta = '') {
  1882. $block = array();
  1883. switch ($delta) {
  1884. case 'syndicate':
  1885. $block['subject'] = t('Syndicate');
  1886. $block['content'] = array(
  1887. '#theme' => 'feed_icon',
  1888. '#url' => 'rss.xml',
  1889. '#title' => t('Syndicate'),
  1890. );
  1891. break;
  1892. case 'recent':
  1893. if (user_access('access content')) {
  1894. $block['subject'] = t('Recent content');
  1895. if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
  1896. $block['content'] = array(
  1897. '#theme' => 'node_recent_block',
  1898. '#nodes' => $nodes,
  1899. );
  1900. } else {
  1901. $block['content'] = t('No content available.');
  1902. }
  1903. }
  1904. break;
  1905. }
  1906. return $block;
  1907. }
  1908. /**
  1909. * Implements hook_block_configure().
  1910. */
  1911. function node_block_configure($delta = '') {
  1912. $form = array();
  1913. if ($delta == 'recent') {
  1914. $form['node_recent_block_count'] = array(
  1915. '#type' => 'select',
  1916. '#title' => t('Number of recent content items to display'),
  1917. '#default_value' => variable_get('node_recent_block_count', 10),
  1918. '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30)),
  1919. );
  1920. }
  1921. return $form;
  1922. }
  1923. /**
  1924. * Implements hook_block_save().
  1925. */
  1926. function node_block_save($delta = '', $edit = array()) {
  1927. if ($delta == 'recent') {
  1928. variable_set('node_recent_block_count', $edit['node_recent_block_count']);
  1929. }
  1930. }
  1931. /**
  1932. * Finds the most recently changed nodes that are available to the current user.
  1933. *
  1934. * @param $number
  1935. * (optional) The maximum number of nodes to find. Defaults to 10.
  1936. *
  1937. * @return
  1938. * An array of node entities or an empty array if there are no recent
  1939. * nodes visible to the current user.
  1940. */
  1941. function node_get_recent($number = 10) {
  1942. $query = db_select('node', 'n');
  1943. if (!user_access('bypass node access')) {
  1944. // If the user is able to view their own unpublished nodes, allow them
  1945. // to see these in addition to published nodes. Check that they actually
  1946. // have some unpublished nodes to view before adding the condition.
  1947. if (user_access('view own unpublished content') && $own_unpublished = db_query('SELECT nid FROM {node} WHERE uid = :uid AND status = :status', array(':uid' => $GLOBALS['user']->uid, ':status' => NODE_NOT_PUBLISHED))->fetchCol()) {
  1948. $query->condition(db_or()
  1949. ->condition('n.status', NODE_PUBLISHED)
  1950. ->condition('n.nid', $own_unpublished, 'IN')
  1951. );
  1952. }
  1953. else {
  1954. // If not, restrict the query to published nodes.
  1955. $query->condition('n.status', NODE_PUBLISHED);
  1956. }
  1957. }
  1958. $nids = $query
  1959. ->fields('n', array('nid'))
  1960. ->orderBy('n.changed', 'DESC')
  1961. ->range(0, $number)
  1962. ->addTag('node_access')
  1963. ->execute()
  1964. ->fetchCol();
  1965. $nodes = node_load_multiple($nids);
  1966. return $nodes ? $nodes : array();
  1967. }
  1968. /**
  1969. * Returns HTML for a list of recent content.
  1970. *
  1971. * @param $variables
  1972. * An associative array containing:
  1973. * - nodes: An array of recent node entities.
  1974. *
  1975. * @ingroup themeable
  1976. */
  1977. function theme_node_recent_block($variables) {
  1978. $rows = array();
  1979. $output = '';
  1980. $l_options = array('query' => drupal_get_destination());
  1981. foreach ($variables['nodes'] as $node) {
  1982. $row = array();
  1983. $row[] = array(
  1984. 'data' => theme('node_recent_content', array('node' => $node)),
  1985. 'class' => 'title-author',
  1986. );
  1987. $row[] = array(
  1988. 'data' => node_access('update', $node) ? l(t('edit'), 'node/' . $node->nid . '/edit', $l_options) : '',
  1989. 'class' => 'edit',
  1990. );
  1991. $row[] = array(
  1992. 'data' => node_access('delete', $node) ? l(t('delete'), 'node/' . $node->nid . '/delete', $l_options) : '',
  1993. 'class' => 'delete',
  1994. );
  1995. $rows[] = $row;
  1996. }
  1997. if ($rows) {
  1998. $output = theme('table', array('rows' => $rows));
  1999. if (user_access('access content overview')) {
  2000. $output .= theme('more_link', array('url' => 'admin/content', 'title' => t('Show more content')));
  2001. }
  2002. }
  2003. return $output;
  2004. }
  2005. /**
  2006. * Returns HTML for a recent node to be displayed in the recent content block.
  2007. *
  2008. * @param $variables
  2009. * An associative array containing:
  2010. * - node: A node entity.
  2011. *
  2012. * @ingroup themeable
  2013. */
  2014. function theme_node_recent_content($variables) {
  2015. $node = $variables['node'];
  2016. $output = '<div class="node-title">';
  2017. $output .= l($node->title, 'node/' . $node->nid);
  2018. $output .= theme('mark', array('type' => node_mark($node->nid, $node->changed)));
  2019. $output .= '</div><div class="node-author">';
  2020. $output .= theme('username', array('account' => user_load($node->uid)));
  2021. $output .= '</div>';
  2022. return $output;
  2023. }
  2024. /**
  2025. * Implements hook_form_FORM_ID_alter() for block_add_block_form().
  2026. *
  2027. * Adds node-type specific visibility options to add block form.
  2028. */
  2029. function node_form_block_add_block_form_alter(&$form, &$form_state) {
  2030. node_form_block_admin_configure_alter($form, $form_state);
  2031. }
  2032. /**
  2033. * Implements hook_form_FORM_ID_alter() for block_admin_configure().
  2034. *
  2035. * Adds node-type specific visibility options to block configuration form.
  2036. *
  2037. * @see node_form_block_admin_configure_submit()
  2038. */
  2039. function node_form_block_admin_configure_alter(&$form, &$form_state) {
  2040. $default_type_options = db_query("SELECT type FROM {block_node_type} WHERE module = :module AND delta = :delta", array(
  2041. ':module' => $form['module']['#value'],
  2042. ':delta' => $form['delta']['#value'],
  2043. ))->fetchCol();
  2044. $form['visibility']['node_type'] = array(
  2045. '#type' => 'fieldset',
  2046. '#title' => t('Content types'),
  2047. '#collapsible' => TRUE,
  2048. '#collapsed' => TRUE,
  2049. '#group' => 'visibility',
  2050. '#weight' => 5,
  2051. );
  2052. $form['visibility']['node_type']['types'] = array(
  2053. '#type' => 'checkboxes',
  2054. '#title' => t('Show block for specific content types'),
  2055. '#default_value' => $default_type_options,
  2056. '#options' => node_type_get_names(),
  2057. '#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.'),
  2058. );
  2059. $form['#submit'][] = 'node_form_block_admin_configure_submit';
  2060. }
  2061. /**
  2062. * Form submission handler for node_form_block_admin_configure_alter().
  2063. */
  2064. function node_form_block_admin_configure_submit($form, &$form_state) {
  2065. db_delete('block_node_type')
  2066. ->condition('module', $form_state['values']['module'])
  2067. ->condition('delta', $form_state['values']['delta'])
  2068. ->execute();
  2069. $query = db_insert('block_node_type')->fields(array('type', 'module', 'delta'));
  2070. foreach (array_filter($form_state['values']['types']) as $type) {
  2071. $query->values(array(
  2072. 'type' => $type,
  2073. 'module' => $form_state['values']['module'],
  2074. 'delta' => $form_state['values']['delta'],
  2075. ));
  2076. }
  2077. $query->execute();
  2078. }
  2079. /**
  2080. * Implements hook_form_FORM_ID_alter() for block_custom_block_delete().
  2081. *
  2082. * Adds node specific submit handler to delete custom block form.
  2083. *
  2084. * @see node_form_block_custom_block_delete_submit()
  2085. */
  2086. function node_form_block_custom_block_delete_alter(&$form, &$form_state) {
  2087. $form['#submit'][] = 'node_form_block_custom_block_delete_submit';
  2088. }
  2089. /**
  2090. * Form submission handler for node_form_block_custom_block_delete_alter().
  2091. */
  2092. function node_form_block_custom_block_delete_submit($form, &$form_state) {
  2093. db_delete('block_node_type')
  2094. ->condition('module', 'block')
  2095. ->condition('delta', $form_state['values']['bid'])
  2096. ->execute();
  2097. }
  2098. /**
  2099. * Implements hook_modules_uninstalled().
  2100. *
  2101. * Cleans up the {block_node_type} table from modules' blocks.
  2102. */
  2103. function node_modules_uninstalled($modules) {
  2104. db_delete('block_node_type')
  2105. ->condition('module', $modules, 'IN')
  2106. ->execute();
  2107. }
  2108. /**
  2109. * Implements hook_block_list_alter().
  2110. *
  2111. * Checks the content type specific visibility settings and removes the block
  2112. * if the visibility conditions are not met.
  2113. */
  2114. function node_block_list_alter(&$blocks) {
  2115. global $theme_key;
  2116. // Build an array of node types for each block.
  2117. $block_node_types = array();
  2118. $result = db_query('SELECT module, delta, type FROM {block_node_type}');
  2119. foreach ($result as $record) {
  2120. $block_node_types[$record->module][$record->delta][$record->type] = TRUE;
  2121. }
  2122. $node = menu_get_object();
  2123. $node_types = node_type_get_types();
  2124. if (arg(0) == 'node' && arg(1) == 'add' && arg(2)) {
  2125. $node_add_arg = strtr(arg(2), '-', '_');
  2126. }
  2127. foreach ($blocks as $key => $block) {
  2128. if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
  2129. // This block was added by a contrib module, leave it in the list.
  2130. continue;
  2131. }
  2132. // If a block has no node types associated, it is displayed for every type.
  2133. // For blocks with node types associated, if the node type does not match
  2134. // the settings from this block, remove it from the block list.
  2135. if (isset($block_node_types[$block->module][$block->delta])) {
  2136. if (!empty($node)) {
  2137. // This is a node or node edit page.
  2138. if (!isset($block_node_types[$block->module][$block->delta][$node->type])) {
  2139. // This block should not be displayed for this node type.
  2140. unset($blocks[$key]);
  2141. continue;
  2142. }
  2143. }
  2144. elseif (isset($node_add_arg) && isset($node_types[$node_add_arg])) {
  2145. // This is a node creation page
  2146. if (!isset($block_node_types[$block->module][$block->delta][$node_add_arg])) {
  2147. // This block should not be displayed for this node type.
  2148. unset($blocks[$key]);
  2149. continue;
  2150. }
  2151. }
  2152. else {
  2153. // This is not a node page, remove the block.
  2154. unset($blocks[$key]);
  2155. continue;
  2156. }
  2157. }
  2158. }
  2159. }
  2160. /**
  2161. * Page callback: Generates and prints an RSS feed.
  2162. *
  2163. * Generates an RSS feed from an array of node IDs, and prints it with an HTTP
  2164. * header, with Content Type set to RSS/XML.
  2165. *
  2166. * @param $nids
  2167. * (optional) An array of node IDs (nid). Defaults to FALSE so empty feeds can
  2168. * be generated with passing an empty array, if no items are to be added
  2169. * to the feed.
  2170. * @param $channel
  2171. * (optional) An associative array containing 'title', 'link', 'description',
  2172. * and other keys, to be parsed by format_rss_channel() and
  2173. * format_xml_elements(). A list of channel elements can be found at the
  2174. * @link http://cyber.law.harvard.edu/rss/rss.html RSS 2.0 Specification. @endlink
  2175. * The link should be an absolute URL.
  2176. *
  2177. * @see node_menu()
  2178. */
  2179. function node_feed($nids = FALSE, $channel = array()) {
  2180. global $base_url, $language_content;
  2181. if ($nids === FALSE) {
  2182. $nids = db_select('node', 'n')
  2183. ->fields('n', array('nid', 'created'))
  2184. ->condition('n.promote', 1)
  2185. ->condition('n.status', 1)
  2186. ->orderBy('n.created', 'DESC')
  2187. ->range(0, variable_get('feed_default_items', 10))
  2188. ->addTag('node_access')
  2189. ->execute()
  2190. ->fetchCol();
  2191. }
  2192. $item_length = variable_get('feed_item_length', 'fulltext');
  2193. $namespaces = array('xmlns:dc' => 'http://purl.org/dc/elements/1.1/');
  2194. $teaser = ($item_length == 'teaser');
  2195. // Load all nodes to be rendered.
  2196. $nodes = node_load_multiple($nids);
  2197. $items = '';
  2198. foreach ($nodes as $node) {
  2199. $item_text = '';
  2200. $node->link = url("node/$node->nid", array('absolute' => TRUE));
  2201. $node->rss_namespaces = array();
  2202. $node->rss_elements = array(
  2203. array('key' => 'pubDate', 'value' => gmdate('r', $node->created)),
  2204. array('key' => 'dc:creator', 'value' => $node->name),
  2205. array('key' => 'guid', 'value' => $node->nid . ' at ' . $base_url, 'attributes' => array('isPermaLink' => 'false'))
  2206. );
  2207. // The node gets built and modules add to or modify $node->rss_elements
  2208. // and $node->rss_namespaces.
  2209. $build = node_view($node, 'rss');
  2210. unset($build['#theme']);
  2211. if (!empty($node->rss_namespaces)) {
  2212. $namespaces = array_merge($namespaces, $node->rss_namespaces);
  2213. }
  2214. if ($item_length != 'title') {
  2215. // We render node contents and force links to be last.
  2216. $build['links']['#weight'] = 1000;
  2217. $item_text .= drupal_render($build);
  2218. }
  2219. $items .= format_rss_item($node->title, $node->link, $item_text, $node->rss_elements);
  2220. }
  2221. $channel_defaults = array(
  2222. 'version' => '2.0',
  2223. 'title' => variable_get('site_name', 'Drupal'),
  2224. 'link' => $base_url,
  2225. 'description' => variable_get('feed_description', ''),
  2226. 'language' => $language_content->langcode
  2227. );
  2228. $channel_extras = array_diff_key($channel, $channel_defaults);
  2229. $channel = array_merge($channel_defaults, $channel);
  2230. $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  2231. $output .= "<rss version=\"" . $channel["version"] . "\" xml:base=\"" . $base_url . "\" " . drupal_attributes($namespaces) . ">\n";
  2232. $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language'], $channel_extras);
  2233. $output .= "</rss>\n";
  2234. drupal_add_http_header('Content-Type', 'application/rss+xml; charset=utf-8');
  2235. print $output;
  2236. }
  2237. /**
  2238. * Constructs a drupal_render() style array from an array of loaded nodes.
  2239. *
  2240. * @param $nodes
  2241. * An array of nodes as returned by node_load_multiple().
  2242. * @param $view_mode
  2243. * (optional) View mode, e.g., 'full', 'teaser'... Defaults to 'teaser.'
  2244. * @param $weight
  2245. * (optional) Integer representing the weight of the first node in the list.
  2246. * @param $langcode
  2247. * (optional) A language code to use for rendering. Defaults to the global
  2248. * content language of the current request.
  2249. *
  2250. * @return
  2251. * An array in the format expected by drupal_render().
  2252. */
  2253. function node_view_multiple($nodes, $view_mode = 'teaser', $weight = 0, $langcode = NULL) {
  2254. field_attach_prepare_view('node', $nodes, $view_mode, $langcode);
  2255. entity_prepare_view('node', $nodes, $langcode);
  2256. $build = array();
  2257. foreach ($nodes as $node) {
  2258. $build['nodes'][$node->nid] = node_view($node, $view_mode, $langcode);
  2259. $build['nodes'][$node->nid]['#weight'] = $weight;
  2260. $weight++;
  2261. }
  2262. $build['nodes']['#sorted'] = TRUE;
  2263. return $build;
  2264. }
  2265. /**
  2266. * Page callback: Generates a listing of promoted nodes.
  2267. *
  2268. * @see node_menu()
  2269. */
  2270. function node_page_default() {
  2271. $select = db_select('node', 'n')
  2272. ->fields('n', array('nid', 'sticky', 'created'))
  2273. ->condition('promote', 1)
  2274. ->condition('status', 1)
  2275. ->orderBy('sticky', 'DESC')
  2276. ->orderBy('created', 'DESC')
  2277. ->extend('PagerDefault')
  2278. ->limit(variable_get('default_nodes_main', 10))
  2279. ->addTag('node_access');
  2280. $nids = $select->execute()->fetchCol();
  2281. if (!empty($nids)) {
  2282. $nodes = node_load_multiple($nids);
  2283. $build = node_view_multiple($nodes);
  2284. // 'rss.xml' is a path, not a file, registered in node_menu().
  2285. drupal_add_feed('rss.xml', variable_get('site_name', 'Drupal') . ' ' . t('RSS'));
  2286. $build['pager'] = array(
  2287. '#theme' => 'pager',
  2288. '#weight' => 5,
  2289. );
  2290. drupal_set_title('');
  2291. }
  2292. else {
  2293. drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);
  2294. $default_message = '<p>' . t('No front page content has been created yet.') . '</p>';
  2295. $default_links = array();
  2296. if (_node_add_access()) {
  2297. $default_links[] = l(t('Add new content'), 'node/add');
  2298. }
  2299. if (!empty($default_links)) {
  2300. $default_message .= theme('item_list', array('items' => $default_links));
  2301. }
  2302. $build['default_message'] = array(
  2303. '#markup' => $default_message,
  2304. '#prefix' => '<div id="first-time">',
  2305. '#suffix' => '</div>',
  2306. );
  2307. }
  2308. return $build;
  2309. }
  2310. /**
  2311. * Page callback: Displays a single node.
  2312. *
  2313. * @param Drupal\node\Node $node
  2314. * The node entity.
  2315. *
  2316. * @see node_menu()
  2317. */
  2318. function node_page_view(Node $node) {
  2319. // If there is a menu link to this node, the link becomes the last part
  2320. // of the active trail, and the link name becomes the page title.
  2321. // Thus, we must explicitly set the page title to be the node title.
  2322. drupal_set_title($node->title);
  2323. $uri = entity_uri('node', $node);
  2324. // Set the node path as the canonical URL to prevent duplicate content.
  2325. drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  2326. // Set the non-aliased path as a default shortlink.
  2327. drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  2328. return node_show($node);
  2329. }
  2330. /**
  2331. * Implements hook_update_index().
  2332. */
  2333. function node_update_index() {
  2334. $limit = (int)variable_get('search_cron_limit', 100);
  2335. $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'));
  2336. $nids = $result->fetchCol();
  2337. if (!$nids) {
  2338. return;
  2339. }
  2340. foreach (node_load_multiple($nids) as $node) {
  2341. _node_index_node($node);
  2342. }
  2343. }
  2344. /**
  2345. * Indexes a single node.
  2346. *
  2347. * @param Drupal\node\Node $node
  2348. * The node to index.
  2349. */
  2350. function _node_index_node(Node $node) {
  2351. // Save the changed time of the most recent indexed node, for the search
  2352. // results half-life calculation.
  2353. variable_set('node_cron_last', $node->changed);
  2354. // Render the node.
  2355. $build = node_view($node, 'search_index');
  2356. unset($build['#theme']);
  2357. $node->rendered = drupal_render($build);
  2358. $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->rendered;
  2359. // Fetch extra data normally not visible
  2360. $extra = module_invoke_all('node_update_index', $node);
  2361. foreach ($extra as $t) {
  2362. $text .= $t;
  2363. }
  2364. // Update index
  2365. search_index($node->nid, 'node', $text);
  2366. }
  2367. /**
  2368. * Implements hook_form_FORM_ID_alter().
  2369. *
  2370. * @see node_search_validate()
  2371. */
  2372. function node_form_search_form_alter(&$form, $form_state) {
  2373. if (isset($form['module']) && $form['module']['#value'] == 'node' && user_access('use advanced search')) {
  2374. // Keyword boxes:
  2375. $form['advanced'] = array(
  2376. '#type' => 'fieldset',
  2377. '#title' => t('Advanced search'),
  2378. '#collapsible' => TRUE,
  2379. '#collapsed' => TRUE,
  2380. '#attributes' => array('class' => array('search-advanced')),
  2381. );
  2382. $form['advanced']['keywords'] = array(
  2383. '#prefix' => '<div class="criterion">',
  2384. '#suffix' => '</div>',
  2385. );
  2386. $form['advanced']['keywords']['or'] = array(
  2387. '#type' => 'textfield',
  2388. '#title' => t('Containing any of the words'),
  2389. '#size' => 30,
  2390. '#maxlength' => 255,
  2391. );
  2392. $form['advanced']['keywords']['phrase'] = array(
  2393. '#type' => 'textfield',
  2394. '#title' => t('Containing the phrase'),
  2395. '#size' => 30,
  2396. '#maxlength' => 255,
  2397. );
  2398. $form['advanced']['keywords']['negative'] = array(
  2399. '#type' => 'textfield',
  2400. '#title' => t('Containing none of the words'),
  2401. '#size' => 30,
  2402. '#maxlength' => 255,
  2403. );
  2404. // Node types:
  2405. $types = array_map('check_plain', node_type_get_names());
  2406. $form['advanced']['type'] = array(
  2407. '#type' => 'checkboxes',
  2408. '#title' => t('Only of the type(s)'),
  2409. '#prefix' => '<div class="criterion">',
  2410. '#suffix' => '</div>',
  2411. '#options' => $types,
  2412. );
  2413. $form['advanced']['submit'] = array(
  2414. '#type' => 'submit',
  2415. '#value' => t('Advanced search'),
  2416. '#prefix' => '<div class="action">',
  2417. '#suffix' => '</div>',
  2418. '#weight' => 100,
  2419. );
  2420. // Languages:
  2421. $language_options = array();
  2422. foreach (language_list() as $langcode => $language) {
  2423. $language_options[$langcode] = $language->name;
  2424. }
  2425. if (count($language_options) > 1) {
  2426. $form['advanced']['language'] = array(
  2427. '#type' => 'checkboxes',
  2428. '#title' => t('Languages'),
  2429. '#prefix' => '<div class="criterion">',
  2430. '#suffix' => '</div>',
  2431. '#options' => $language_options,
  2432. );
  2433. }
  2434. $form['#validate'][] = 'node_search_validate';
  2435. }
  2436. }
  2437. /**
  2438. * Form validation handler for node_form_search_form_alter().
  2439. */
  2440. function node_search_validate($form, &$form_state) {
  2441. // Initialize using any existing basic search keywords.
  2442. $keys = $form_state['values']['processed_keys'];
  2443. // Insert extra restrictions into the search keywords string.
  2444. if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) {
  2445. // Retrieve selected types - Forms API sets the value of unselected
  2446. // checkboxes to 0.
  2447. $form_state['values']['type'] = array_filter($form_state['values']['type']);
  2448. if (count($form_state['values']['type'])) {
  2449. $keys = search_expression_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
  2450. }
  2451. }
  2452. if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
  2453. $keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
  2454. }
  2455. if (isset($form_state['values']['language']) && is_array($form_state['values']['language'])) {
  2456. $languages = array_filter($form_state['values']['language']);
  2457. if (count($languages)) {
  2458. $keys = search_expression_insert($keys, 'language', implode(',', $languages));
  2459. }
  2460. }
  2461. if ($form_state['values']['or'] != '') {
  2462. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['or'], $matches)) {
  2463. $keys .= ' ' . implode(' OR ', $matches[1]);
  2464. }
  2465. }
  2466. if ($form_state['values']['negative'] != '') {
  2467. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['negative'], $matches)) {
  2468. $keys .= ' -' . implode(' -', $matches[1]);
  2469. }
  2470. }
  2471. if ($form_state['values']['phrase'] != '') {
  2472. $keys .= ' "' . str_replace('"', ' ', $form_state['values']['phrase']) . '"';
  2473. }
  2474. if (!empty($keys)) {
  2475. form_set_value($form['basic']['processed_keys'], trim($keys), $form_state);
  2476. }
  2477. }
  2478. /**
  2479. * Implements hook_form_FORM_ID_alter().
  2480. *
  2481. * Alters the theme form to use the admin theme on node editing.
  2482. *
  2483. * @see node_form_system_themes_admin_form_submit()
  2484. */
  2485. function node_form_system_themes_admin_form_alter(&$form, &$form_state, $form_id) {
  2486. $form['admin_theme']['node_admin_theme'] = array(
  2487. '#type' => 'checkbox',
  2488. '#title' => t('Use the administration theme when editing or creating content'),
  2489. '#default_value' => variable_get('node_admin_theme', '0'),
  2490. );
  2491. $form['#submit'][] = 'node_form_system_themes_admin_form_submit';
  2492. }
  2493. /**
  2494. * Form submission handler for system_themes_admin_form().
  2495. *
  2496. * @see node_form_system_themes_admin_form_alter()
  2497. */
  2498. function node_form_system_themes_admin_form_submit($form, &$form_state) {
  2499. variable_set('node_admin_theme', $form_state['values']['node_admin_theme']);
  2500. }
  2501. /**
  2502. * @defgroup node_access Node access rights
  2503. * @{
  2504. * The node access system determines who can do what to which nodes.
  2505. *
  2506. * In determining access rights for a node, node_access() first checks
  2507. * whether the user has the "bypass node access" permission. Such users have
  2508. * unrestricted access to all nodes. user 1 will always pass this check.
  2509. *
  2510. * Next, all implementations of hook_node_access() will be called. Each
  2511. * implementation may explicitly allow, explicitly deny, or ignore the access
  2512. * request. If at least one module says to deny the request, it will be rejected.
  2513. * If no modules deny the request and at least one says to allow it, the request
  2514. * will be permitted.
  2515. *
  2516. * If all modules ignore the access request, then the node_access table is used
  2517. * to determine access. All node access modules are queried using
  2518. * hook_node_grants() to assemble a list of "grant IDs" for the user. This list
  2519. * is compared against the table. If any row contains the node ID in question
  2520. * (or 0, which stands for "all nodes"), one of the grant IDs returned, and a
  2521. * value of TRUE for the operation in question, then access is granted. Note
  2522. * that this table is a list of grants; any matching row is sufficient to
  2523. * grant access to the node.
  2524. *
  2525. * In node listings (lists of nodes generated from a select query, such as the
  2526. * default home page at path 'node', an RSS feed, a recent content block, etc.),
  2527. * the process above is followed except that hook_node_access() is not called on
  2528. * each node for performance reasons and for proper functioning of the pager
  2529. * system. When adding a node listing to your module, be sure to use a dynamic
  2530. * query created by db_select() and add a tag of "node_access". This will allow
  2531. * modules dealing with node access to ensure only nodes to which the user has
  2532. * access are retrieved, through the use of hook_query_TAG_alter().
  2533. *
  2534. * Note: Even a single module returning NODE_ACCESS_DENY from hook_node_access()
  2535. * will block access to the node. Therefore, implementers should take care to
  2536. * not deny access unless they really intend to. Unless a module wishes to
  2537. * actively deny access it should return NODE_ACCESS_IGNORE (or simply return
  2538. * nothing) to allow other modules or the node_access table to control access.
  2539. *
  2540. * To see how to write a node access module of your own, see
  2541. * node_access_example.module.
  2542. */
  2543. /**
  2544. * Access callback: Checks a user's permission for performing a node operation.
  2545. *
  2546. * @param $op
  2547. * The operation to be performed on the node. Possible values are:
  2548. * - "view"
  2549. * - "update"
  2550. * - "delete"
  2551. * - "create"
  2552. * @param Drupal\node\Node|string $node
  2553. * The node entity on which the operation is to be performed, or the node type
  2554. * (e.g., 'forum') for the 'create' operation.
  2555. * @param $account
  2556. * (optional) A user object representing the user for whom the operation is to
  2557. * be performed. Determines access for a user other than the current user.
  2558. *
  2559. * @return
  2560. * TRUE if the operation may be performed, FALSE otherwise.
  2561. *
  2562. * @see node_menu()
  2563. */
  2564. function node_access($op, $node, $account = NULL) {
  2565. $rights = &drupal_static(__FUNCTION__, array());
  2566. if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
  2567. // If there was no node to check against, or the $op was not one of the
  2568. // supported ones, we return access denied.
  2569. return FALSE;
  2570. }
  2571. // If no user object is supplied, the access check is for the current user.
  2572. if (empty($account)) {
  2573. $account = $GLOBALS['user'];
  2574. }
  2575. // $node may be either an object or a node type. Since node types cannot be
  2576. // an integer, use either nid or type as the static cache id.
  2577. $cid = is_object($node) ? $node->nid : $node;
  2578. // If we've already checked access for this node, user and op, return from
  2579. // cache.
  2580. if (isset($rights[$account->uid][$cid][$op])) {
  2581. return $rights[$account->uid][$cid][$op];
  2582. }
  2583. if (user_access('bypass node access', $account)) {
  2584. $rights[$account->uid][$cid][$op] = TRUE;
  2585. return TRUE;
  2586. }
  2587. if (!user_access('access content', $account)) {
  2588. $rights[$account->uid][$cid][$op] = FALSE;
  2589. return FALSE;
  2590. }
  2591. // We grant access to the node if both of the following conditions are met:
  2592. // - No modules say to deny access.
  2593. // - At least one module says to grant access.
  2594. // If no module specified either allow or deny, we fall back to the
  2595. // node_access table.
  2596. $access = module_invoke_all('node_access', $node, $op, $account);
  2597. if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
  2598. $rights[$account->uid][$cid][$op] = FALSE;
  2599. return FALSE;
  2600. }
  2601. elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
  2602. $rights[$account->uid][$cid][$op] = TRUE;
  2603. return TRUE;
  2604. }
  2605. // Check if authors can view their own unpublished nodes.
  2606. if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
  2607. $rights[$account->uid][$cid][$op] = TRUE;
  2608. return TRUE;
  2609. }
  2610. // If the module did not override the access rights, use those set in the
  2611. // node_access table.
  2612. if ($op != 'create' && $node->nid) {
  2613. if (module_implements('node_grants')) {
  2614. $query = db_select('node_access');
  2615. $query->addExpression('1');
  2616. $query->condition('grant_' . $op, 1, '>=');
  2617. $nids = db_or()->condition('nid', $node->nid);
  2618. if ($node->status) {
  2619. $nids->condition('nid', 0);
  2620. }
  2621. $query->condition($nids);
  2622. $query->range(0, 1);
  2623. $grants = db_or();
  2624. foreach (node_access_grants($op, $account) as $realm => $gids) {
  2625. foreach ($gids as $gid) {
  2626. $grants->condition(db_and()
  2627. ->condition('gid', $gid)
  2628. ->condition('realm', $realm)
  2629. );
  2630. }
  2631. }
  2632. if (count($grants) > 0) {
  2633. $query->condition($grants);
  2634. }
  2635. $result = (bool) $query
  2636. ->execute()
  2637. ->fetchField();
  2638. $rights[$account->uid][$cid][$op] = $result;
  2639. return $result;
  2640. }
  2641. elseif (is_object($node) && $op == 'view' && $node->status) {
  2642. // If no modules implement hook_node_grants(), the default behavior is to
  2643. // allow all users to view published nodes, so reflect that here.
  2644. $rights[$account->uid][$cid][$op] = TRUE;
  2645. return TRUE;
  2646. }
  2647. }
  2648. return FALSE;
  2649. }
  2650. /**
  2651. * Implements hook_node_access().
  2652. */
  2653. function node_node_access($node, $op, $account) {
  2654. $type = is_string($node) ? $node : $node->type;
  2655. $configured_types = node_permissions_get_configured_types();
  2656. if (isset($configured_types[$type])) {
  2657. if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
  2658. return NODE_ACCESS_ALLOW;
  2659. }
  2660. if ($op == 'update') {
  2661. if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
  2662. return NODE_ACCESS_ALLOW;
  2663. }
  2664. }
  2665. if ($op == 'delete') {
  2666. if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
  2667. return NODE_ACCESS_ALLOW;
  2668. }
  2669. }
  2670. }
  2671. return NODE_ACCESS_IGNORE;
  2672. }
  2673. /**
  2674. * Helper function to generate standard node permission list for a given type.
  2675. *
  2676. * @param $name
  2677. * The machine name of the node type.
  2678. *
  2679. * @return array
  2680. * An array of permission names and descriptions.
  2681. */
  2682. function node_list_permissions($type) {
  2683. // Build standard list of node permissions for this type.
  2684. $perms = array(
  2685. "create $type->type content" => array(
  2686. 'title' => t('%type_name: Create new content', array('%type_name' => $type->name)),
  2687. ),
  2688. "edit own $type->type content" => array(
  2689. 'title' => t('%type_name: Edit own content', array('%type_name' => $type->name)),
  2690. ),
  2691. "edit any $type->type content" => array(
  2692. 'title' => t('%type_name: Edit any content', array('%type_name' => $type->name)),
  2693. ),
  2694. "delete own $type->type content" => array(
  2695. 'title' => t('%type_name: Delete own content', array('%type_name' => $type->name)),
  2696. ),
  2697. "delete any $type->type content" => array(
  2698. 'title' => t('%type_name: Delete any content', array('%type_name' => $type->name)),
  2699. ),
  2700. );
  2701. return $perms;
  2702. }
  2703. /**
  2704. * Returns an array of node types that should be managed by permissions.
  2705. *
  2706. * By default, this will include all node types in the system. To exclude a
  2707. * specific node from getting permissions defined for it, set the
  2708. * node_permissions_$type variable to 0. Core does not provide an interface
  2709. * for doing so, however, contrib modules may exclude their own nodes in
  2710. * hook_install(). Alternatively, contrib modules may configure all node types
  2711. * at once, or decide to apply some other hook_node_access() implementation
  2712. * to some or all node types.
  2713. *
  2714. * @return
  2715. * An array of node types managed by this module.
  2716. */
  2717. function node_permissions_get_configured_types() {
  2718. $configured_types = array();
  2719. foreach (node_type_get_types() as $name => $type) {
  2720. if (variable_get('node_permissions_' . $name, 1)) {
  2721. $configured_types[$name] = $type;
  2722. }
  2723. }
  2724. return $configured_types;
  2725. }
  2726. /**
  2727. * Fetches an array of permission IDs granted to the given user ID.
  2728. *
  2729. * The implementation here provides only the universal "all" grant. A node
  2730. * access module should implement hook_node_grants() to provide a grant
  2731. * list for the user.
  2732. *
  2733. * After the default grants have been loaded, we allow modules to alter
  2734. * the grants array by reference. This hook allows for complex business
  2735. * logic to be applied when integrating multiple node access modules.
  2736. *
  2737. * @param $op
  2738. * The operation that the user is trying to perform.
  2739. * @param $account
  2740. * (optional) The user object for the user performing the operation. If
  2741. * omitted, the current user is used.
  2742. *
  2743. * @return
  2744. * An associative array in which the keys are realms, and the values are
  2745. * arrays of grants for those realms.
  2746. */
  2747. function node_access_grants($op, $account = NULL) {
  2748. if (!isset($account)) {
  2749. $account = $GLOBALS['user'];
  2750. }
  2751. // Fetch node access grants from other modules.
  2752. $grants = module_invoke_all('node_grants', $account, $op);
  2753. // Allow modules to alter the assigned grants.
  2754. drupal_alter('node_grants', $grants, $account, $op);
  2755. return array_merge(array('all' => array(0)), $grants);
  2756. }
  2757. /**
  2758. * Determines whether the user has a global viewing grant for all nodes.
  2759. *
  2760. * Checks to see whether any module grants global 'view' access to a user
  2761. * account; global 'view' access is encoded in the {node_access} table as a
  2762. * grant with nid=0. If no node access modules are enabled, node.module defines
  2763. * such a global 'view' access grant.
  2764. *
  2765. * This function is called when a node listing query is tagged with
  2766. * 'node_access'; when this function returns TRUE, no node access joins are
  2767. * added to the query.
  2768. *
  2769. * @param $account
  2770. * (optional) The user object for the user whose access is being checked. If
  2771. * omitted, the current user is used.
  2772. *
  2773. * @return
  2774. * TRUE if 'view' access to all nodes is granted, FALSE otherwise.
  2775. *
  2776. * @see hook_node_grants()
  2777. * @see _node_query_node_access_alter()
  2778. */
  2779. function node_access_view_all_nodes($account = NULL) {
  2780. global $user;
  2781. if (!$account) {
  2782. $account = $user;
  2783. }
  2784. // Statically cache results in an array keyed by $account->uid.
  2785. $access = &drupal_static(__FUNCTION__);
  2786. if (isset($access[$account->uid])) {
  2787. return $access[$account->uid];
  2788. }
  2789. // If no modules implement the node access system, access is always TRUE.
  2790. if (!module_implements('node_grants')) {
  2791. $access[$account->uid] = TRUE;
  2792. }
  2793. else {
  2794. $query = db_select('node_access');
  2795. $query->addExpression('COUNT(*)');
  2796. $query
  2797. ->condition('nid', 0)
  2798. ->condition('grant_view', 1, '>=');
  2799. $grants = db_or();
  2800. foreach (node_access_grants('view', $account) as $realm => $gids) {
  2801. foreach ($gids as $gid) {
  2802. $grants->condition(db_and()
  2803. ->condition('gid', $gid)
  2804. ->condition('realm', $realm)
  2805. );
  2806. }
  2807. }
  2808. if (count($grants) > 0 ) {
  2809. $query->condition($grants);
  2810. }
  2811. $access[$account->uid] = $query
  2812. ->execute()
  2813. ->fetchField();
  2814. }
  2815. return $access[$account->uid];
  2816. }
  2817. /**
  2818. * Implements hook_query_TAG_alter().
  2819. *
  2820. * This is the hook_query_alter() for queries tagged with 'node_access'.
  2821. * It adds node access checks for the user account given by the 'account'
  2822. * meta-data (or global $user if not provided), for an operation given by
  2823. * the 'op' meta-data (or 'view' if not provided; other possible values are
  2824. * 'update' and 'delete').
  2825. */
  2826. function node_query_node_access_alter(AlterableInterface $query) {
  2827. _node_query_node_access_alter($query, 'node');
  2828. }
  2829. /**
  2830. * Implements hook_query_TAG_alter().
  2831. *
  2832. * This function implements the same functionality as
  2833. * node_query_node_access_alter() for the SQL field storage engine. Node access
  2834. * conditions are added for field values belonging to nodes only.
  2835. */
  2836. function node_query_entity_field_access_alter(AlterableInterface $query) {
  2837. _node_query_node_access_alter($query, 'entity');
  2838. }
  2839. /**
  2840. * Helper for node access functions.
  2841. *
  2842. * @param $query
  2843. * The query to add conditions to.
  2844. * @param $type
  2845. * Either 'node' or 'entity' depending on what sort of query it is. See
  2846. * node_query_node_access_alter() and node_query_entity_field_access_alter()
  2847. * for more.
  2848. */
  2849. function _node_query_node_access_alter($query, $type) {
  2850. global $user;
  2851. // Read meta-data from query, if provided.
  2852. if (!$account = $query->getMetaData('account')) {
  2853. $account = $user;
  2854. }
  2855. if (!$op = $query->getMetaData('op')) {
  2856. $op = 'view';
  2857. }
  2858. // If $account can bypass node access, or there are no node access modules,
  2859. // or the operation is 'view' and the $acount has a global view grant (i.e.,
  2860. // a view grant for node ID 0), we don't need to alter the query.
  2861. if (user_access('bypass node access', $account)) {
  2862. return;
  2863. }
  2864. if (!count(module_implements('node_grants'))) {
  2865. return;
  2866. }
  2867. if ($op == 'view' && node_access_view_all_nodes($account)) {
  2868. return;
  2869. }
  2870. $tables = $query->getTables();
  2871. $base_table = $query->getMetaData('base_table');
  2872. // If no base table is specified explicitly, search for one.
  2873. if (!$base_table) {
  2874. $fallback = '';
  2875. foreach ($tables as $alias => $table_info) {
  2876. if (!($table_info instanceof SelectInterface)) {
  2877. $table = $table_info['table'];
  2878. // If the node table is in the query, it wins immediately.
  2879. if ($table == 'node') {
  2880. $base_table = $table;
  2881. break;
  2882. }
  2883. // Check whether the table has a foreign key to node.nid. If it does,
  2884. // do not run this check again as we found a base table and only node
  2885. // can triumph that.
  2886. if (!$base_table) {
  2887. // The schema is cached.
  2888. $schema = drupal_get_schema($table);
  2889. if (isset($schema['fields']['nid'])) {
  2890. if (isset($schema['foreign keys'])) {
  2891. foreach ($schema['foreign keys'] as $relation) {
  2892. if ($relation['table'] === 'node' && $relation['columns'] === array('nid' => 'nid')) {
  2893. $base_table = $table;
  2894. }
  2895. }
  2896. }
  2897. else {
  2898. // At least it's a nid. A table with a field called nid is very
  2899. // very likely to be a node.nid in a node access query.
  2900. $fallback = $table;
  2901. }
  2902. }
  2903. }
  2904. }
  2905. }
  2906. // If there is nothing else, use the fallback.
  2907. if (!$base_table) {
  2908. if ($fallback) {
  2909. watchdog('security', 'Your node listing query is using @fallback as a base table in a query tagged for node access. This might not be secure and might not even work. Specify foreign keys in your schema to node.nid ', array('@fallback' => $fallback), WATCHDOG_WARNING);
  2910. $base_table = $fallback;
  2911. }
  2912. else {
  2913. throw new Exception(t('Query tagged for node access but there is no nid. Add foreign keys to node.nid in schema to fix.'));
  2914. }
  2915. }
  2916. }
  2917. // Find all instances of the base table being joined -- could appear
  2918. // more than once in the query, and could be aliased. Join each one to
  2919. // the node_access table.
  2920. $grants = node_access_grants($op, $account);
  2921. if ($type == 'entity') {
  2922. // The original query looked something like:
  2923. // @code
  2924. // SELECT nid FROM sometable s
  2925. // INNER JOIN node_access na ON na.nid = s.nid
  2926. // WHERE ($node_access_conditions)
  2927. // @endcode
  2928. //
  2929. // Our query will look like:
  2930. // @code
  2931. // SELECT entity_type, entity_id
  2932. // FROM field_data_something s
  2933. // LEFT JOIN node_access na ON s.entity_id = na.nid
  2934. // WHERE (entity_type = 'node' AND $node_access_conditions) OR (entity_type <> 'node')
  2935. // @endcode
  2936. //
  2937. // So instead of directly adding to the query object, we need to collect
  2938. // in a separate db_and() object and then at the end add it to the query.
  2939. $entity_conditions = db_and();
  2940. }
  2941. foreach ($tables as $nalias => $tableinfo) {
  2942. $table = $tableinfo['table'];
  2943. if (!($table instanceof SelectInterface) && $table == $base_table) {
  2944. // Set the subquery.
  2945. $subquery = db_select('node_access', 'na')
  2946. ->fields('na', array('nid'));
  2947. $grant_conditions = db_or();
  2948. // If any grant exists for the specified user, then user has access
  2949. // to the node for the specified operation.
  2950. foreach ($grants as $realm => $gids) {
  2951. foreach ($gids as $gid) {
  2952. $grant_conditions->condition(db_and()
  2953. ->condition('na.gid', $gid)
  2954. ->condition('na.realm', $realm)
  2955. );
  2956. }
  2957. }
  2958. // Attach conditions to the subquery for nodes.
  2959. if (count($grant_conditions->conditions())) {
  2960. $subquery->condition($grant_conditions);
  2961. }
  2962. $subquery->condition('na.grant_' . $op, 1, '>=');
  2963. $field = 'nid';
  2964. // Now handle entities.
  2965. if ($type == 'entity') {
  2966. // Set a common alias for entities.
  2967. $base_alias = $nalias;
  2968. $field = 'entity_id';
  2969. }
  2970. $subquery->where("$nalias.$field = na.nid");
  2971. $query->exists($subquery);
  2972. }
  2973. }
  2974. if ($type == 'entity' && count($subquery->conditions())) {
  2975. // All the node access conditions are only for field values belonging to
  2976. // nodes.
  2977. $entity_conditions->condition("$base_alias.entity_type", 'node');
  2978. $or = db_or();
  2979. $or->condition($entity_conditions);
  2980. // If the field value belongs to a non-node entity type then this function
  2981. // does not do anything with it.
  2982. $or->condition("$base_alias.entity_type", 'node', '<>');
  2983. // Add the compiled set of rules to the query.
  2984. $query->condition($or);
  2985. }
  2986. }
  2987. /**
  2988. * Gets the list of node access grants and writes them to the database.
  2989. *
  2990. * This function is called when a node is saved, and can also be called by
  2991. * modules if something other than a node save causes node access permissions to
  2992. * change. It collects all node access grants for the node from
  2993. * hook_node_access_records() implementations, allows these grants to be altered
  2994. * via hook_node_access_records_alter() implementations, and saves the collected
  2995. * and altered grants to the database.
  2996. *
  2997. * @param Drupal\node\Node $node
  2998. * The $node to acquire grants for.
  2999. * @param $delete
  3000. * (optional) Whether to delete existing node access records before inserting
  3001. * new ones. Defaults to TRUE.
  3002. */
  3003. function node_access_acquire_grants(Node $node, $delete = TRUE) {
  3004. $grants = module_invoke_all('node_access_records', $node);
  3005. // Let modules alter the grants.
  3006. drupal_alter('node_access_records', $grants, $node);
  3007. // If no grants are set and the node is published, then use the default grant.
  3008. if (empty($grants) && !empty($node->status)) {
  3009. $grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0);
  3010. }
  3011. _node_access_write_grants($node, $grants, NULL, $delete);
  3012. }
  3013. /**
  3014. * Writes a list of grants to the database, deleting any previously saved ones.
  3015. *
  3016. * If a realm is provided, it will only delete grants from that realm, but it
  3017. * will always delete a grant from the 'all' realm. Modules that utilize
  3018. * node_access can use this function when doing mass updates due to widespread
  3019. * permission changes.
  3020. *
  3021. * Note: Don't call this function directly from a contributed module. Call
  3022. * node_access_acquire_grants() instead.
  3023. *
  3024. * @param Drupal\node\Node $node
  3025. * The $node being written to. All that is necessary is that it contains a
  3026. * nid.
  3027. * @param $grants
  3028. * A list of grants to write. Each grant is an array that must contain the
  3029. * following keys: realm, gid, grant_view, grant_update, grant_delete.
  3030. * The realm is specified by a particular module; the gid is as well, and
  3031. * is a module-defined id to define grant privileges. each grant_* field
  3032. * is a boolean value.
  3033. * @param $realm
  3034. * (optional) If provided, read/write grants for that realm only.
  3035. * @param $delete
  3036. * (optional) If false, does not delete records. This is only for optimization
  3037. * purposes, and assumes the caller has already performed a mass delete of
  3038. * some form.
  3039. */
  3040. function _node_access_write_grants(Node $node, $grants, $realm = NULL, $delete = TRUE) {
  3041. if ($delete) {
  3042. $query = db_delete('node_access')->condition('nid', $node->nid);
  3043. if ($realm) {
  3044. $query->condition('realm', array($realm, 'all'), 'IN');
  3045. }
  3046. $query->execute();
  3047. }
  3048. // Only perform work when node_access modules are active.
  3049. if (!empty($grants) && count(module_implements('node_grants'))) {
  3050. $query = db_insert('node_access')->fields(array('nid', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete'));
  3051. foreach ($grants as $grant) {
  3052. if ($realm && $realm != $grant['realm']) {
  3053. continue;
  3054. }
  3055. // Only write grants; denies are implicit.
  3056. if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
  3057. $grant['nid'] = $node->nid;
  3058. $query->values($grant);
  3059. }
  3060. }
  3061. $query->execute();
  3062. }
  3063. }
  3064. /**
  3065. * Toggles or reads the value of a flag for rebuilding the node access grants.
  3066. *
  3067. * When the flag is set, a message is displayed to users with 'access
  3068. * administration pages' permission, pointing to the 'rebuild' confirm form.
  3069. * This can be used as an alternative to direct node_access_rebuild calls,
  3070. * allowing administrators to decide when they want to perform the actual
  3071. * (possibly time consuming) rebuild.
  3072. * When unsure the current user is an administrator, node_access_rebuild
  3073. * should be used instead.
  3074. *
  3075. * @param $rebuild
  3076. * (optional) The boolean value to be written.
  3077. *
  3078. * @return
  3079. * The current value of the flag if no value was provided for $rebuild.
  3080. */
  3081. function node_access_needs_rebuild($rebuild = NULL) {
  3082. if (!isset($rebuild)) {
  3083. return variable_get('node_access_needs_rebuild', FALSE);
  3084. }
  3085. elseif ($rebuild) {
  3086. variable_set('node_access_needs_rebuild', TRUE);
  3087. }
  3088. else {
  3089. variable_del('node_access_needs_rebuild');
  3090. }
  3091. }
  3092. /**
  3093. * Rebuilds the node access database.
  3094. *
  3095. * This rebuild is occasionally needed by modules that make system-wide changes
  3096. * to access levels. When the rebuild is required by an admin-triggered action
  3097. * (e.g module settings form), calling node_access_needs_rebuild(TRUE) instead
  3098. * of node_access_rebuild() lets the user perform his changes and actually
  3099. * rebuild only once he is done.
  3100. *
  3101. * Note : As of Drupal 6, node access modules are not required to (and actually
  3102. * should not) call node_access_rebuild() in hook_enable/disable anymore.
  3103. *
  3104. * @param $batch_mode
  3105. * (optional) Set to TRUE to process in 'batch' mode, spawning processing over
  3106. * several HTTP requests (thus avoiding the risk of PHP timeout if the site
  3107. * has a large number of nodes). hook_update_N() and any form submit handler
  3108. * are safe contexts to use the 'batch mode'. Less decidable cases (such as
  3109. * calls from hook_user(), hook_taxonomy(), etc.) might consider using the
  3110. * non-batch mode.
  3111. * @see node_access_needs_rebuild()
  3112. */
  3113. function node_access_rebuild($batch_mode = FALSE) {
  3114. db_delete('node_access')->execute();
  3115. // Only recalculate if the site is using a node_access module.
  3116. if (count(module_implements('node_grants'))) {
  3117. if ($batch_mode) {
  3118. $batch = array(
  3119. 'title' => t('Rebuilding content access permissions'),
  3120. 'operations' => array(
  3121. array('_node_access_rebuild_batch_operation', array()),
  3122. ),
  3123. 'finished' => '_node_access_rebuild_batch_finished'
  3124. );
  3125. batch_set($batch);
  3126. }
  3127. else {
  3128. // Try to allocate enough time to rebuild node grants
  3129. drupal_set_time_limit(240);
  3130. $nids = db_query("SELECT nid FROM {node}")->fetchCol();
  3131. foreach ($nids as $nid) {
  3132. $node = node_load($nid, NULL, TRUE);
  3133. // To preserve database integrity, only acquire grants if the node
  3134. // loads successfully.
  3135. if (!empty($node)) {
  3136. node_access_acquire_grants($node);
  3137. }
  3138. }
  3139. }
  3140. }
  3141. else {
  3142. // Not using any node_access modules. Add the default grant.
  3143. db_insert('node_access')
  3144. ->fields(array(
  3145. 'nid' => 0,
  3146. 'realm' => 'all',
  3147. 'gid' => 0,
  3148. 'grant_view' => 1,
  3149. 'grant_update' => 0,
  3150. 'grant_delete' => 0,
  3151. ))
  3152. ->execute();
  3153. }
  3154. if (!isset($batch)) {
  3155. drupal_set_message(t('Content permissions have been rebuilt.'));
  3156. node_access_needs_rebuild(FALSE);
  3157. cache_clear_all();
  3158. }
  3159. }
  3160. /**
  3161. * Batch operation for node_access_rebuild_batch.
  3162. *
  3163. * This is a multistep operation : we go through all nodes by packs of 20.
  3164. * The batch processing engine interrupts processing and sends progress
  3165. * feedback after 1 second execution time.
  3166. */
  3167. function _node_access_rebuild_batch_operation(&$context) {
  3168. if (empty($context['sandbox'])) {
  3169. // Initiate multistep processing.
  3170. $context['sandbox']['progress'] = 0;
  3171. $context['sandbox']['current_node'] = 0;
  3172. $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
  3173. }
  3174. // Process the next 20 nodes.
  3175. $limit = 20;
  3176. $nids = db_query_range("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, array(':nid' => $context['sandbox']['current_node']))->fetchCol();
  3177. $nodes = node_load_multiple($nids, array(), TRUE);
  3178. foreach ($nodes as $nid => $node) {
  3179. // To preserve database integrity, only acquire grants if the node
  3180. // loads successfully.
  3181. if (!empty($node)) {
  3182. node_access_acquire_grants($node);
  3183. }
  3184. $context['sandbox']['progress']++;
  3185. $context['sandbox']['current_node'] = $nid;
  3186. }
  3187. // Multistep processing : report progress.
  3188. if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  3189. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  3190. }
  3191. }
  3192. /**
  3193. * Post-processing for node_access_rebuild_batch.
  3194. */
  3195. function _node_access_rebuild_batch_finished($success, $results, $operations) {
  3196. if ($success) {
  3197. drupal_set_message(t('The content access permissions have been rebuilt.'));
  3198. node_access_needs_rebuild(FALSE);
  3199. }
  3200. else {
  3201. drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
  3202. }
  3203. cache_clear_all();
  3204. }
  3205. /**
  3206. * @} End of "defgroup node_access".
  3207. */
  3208. /**
  3209. * @defgroup node_content Hook implementations for user-created content types
  3210. * @{
  3211. * Functions that implement hooks for user-created content types.
  3212. */
  3213. /**
  3214. * Implements hook_form().
  3215. */
  3216. function node_content_form(Node $node, $form_state) {
  3217. // @todo It is impossible to define a content type without implementing
  3218. // hook_form(). Remove this requirement.
  3219. $form = array();
  3220. $type = node_type_load($node->type);
  3221. if ($type->has_title) {
  3222. $form['title'] = array(
  3223. '#type' => 'textfield',
  3224. '#title' => check_plain($type->title_label),
  3225. '#required' => TRUE,
  3226. '#default_value' => $node->title,
  3227. '#maxlength' => 255,
  3228. '#weight' => -5,
  3229. );
  3230. }
  3231. return $form;
  3232. }
  3233. /**
  3234. * @} End of "defgroup node_content".
  3235. */
  3236. /**
  3237. * Implements hook_forms().
  3238. *
  3239. * All node forms share the same form handler.
  3240. */
  3241. function node_forms() {
  3242. $forms = array();
  3243. if ($types = node_type_get_types()) {
  3244. foreach (array_keys($types) as $type) {
  3245. $forms[$type . '_node_form']['callback'] = 'node_form';
  3246. }
  3247. }
  3248. return $forms;
  3249. }
  3250. /**
  3251. * Implements hook_action_info().
  3252. */
  3253. function node_action_info() {
  3254. return array(
  3255. 'node_publish_action' => array(
  3256. 'type' => 'node',
  3257. 'label' => t('Publish content'),
  3258. 'configurable' => FALSE,
  3259. 'behavior' => array('changes_property'),
  3260. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3261. ),
  3262. 'node_unpublish_action' => array(
  3263. 'type' => 'node',
  3264. 'label' => t('Unpublish content'),
  3265. 'configurable' => FALSE,
  3266. 'behavior' => array('changes_property'),
  3267. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3268. ),
  3269. 'node_make_sticky_action' => array(
  3270. 'type' => 'node',
  3271. 'label' => t('Make content sticky'),
  3272. 'configurable' => FALSE,
  3273. 'behavior' => array('changes_property'),
  3274. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3275. ),
  3276. 'node_make_unsticky_action' => array(
  3277. 'type' => 'node',
  3278. 'label' => t('Make content unsticky'),
  3279. 'configurable' => FALSE,
  3280. 'behavior' => array('changes_property'),
  3281. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3282. ),
  3283. 'node_promote_action' => array(
  3284. 'type' => 'node',
  3285. 'label' => t('Promote content to front page'),
  3286. 'configurable' => FALSE,
  3287. 'behavior' => array('changes_property'),
  3288. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3289. ),
  3290. 'node_unpromote_action' => array(
  3291. 'type' => 'node',
  3292. 'label' => t('Remove content from front page'),
  3293. 'configurable' => FALSE,
  3294. 'behavior' => array('changes_property'),
  3295. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3296. ),
  3297. 'node_assign_owner_action' => array(
  3298. 'type' => 'node',
  3299. 'label' => t('Change the author of content'),
  3300. 'configurable' => TRUE,
  3301. 'behavior' => array('changes_property'),
  3302. 'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
  3303. ),
  3304. 'node_save_action' => array(
  3305. 'type' => 'node',
  3306. 'label' => t('Save content'),
  3307. 'configurable' => FALSE,
  3308. 'triggers' => array('comment_insert', 'comment_update', 'comment_delete'),
  3309. ),
  3310. 'node_unpublish_by_keyword_action' => array(
  3311. 'type' => 'node',
  3312. 'label' => t('Unpublish content containing keyword(s)'),
  3313. 'configurable' => TRUE,
  3314. 'triggers' => array('node_presave', 'node_insert', 'node_update'),
  3315. ),
  3316. );
  3317. }
  3318. /**
  3319. * Sets the status of a node to 1 (published).
  3320. *
  3321. * @param Drupal\node\Node $node
  3322. * A node entity.
  3323. * @param $context
  3324. * (optional) Array of additional information about what triggered the action.
  3325. * Not used for this action.
  3326. *
  3327. * @ingroup actions
  3328. */
  3329. function node_publish_action(Node $node, $context = array()) {
  3330. $node->status = NODE_PUBLISHED;
  3331. watchdog('action', 'Set @type %title to published.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3332. }
  3333. /**
  3334. * Sets the status of a node to 0 (unpublished).
  3335. *
  3336. * @param Drupal\node\Node $node
  3337. * A node entity.
  3338. * @param $context
  3339. * (optional) Array of additional information about what triggered the action.
  3340. * Not used for this action.
  3341. *
  3342. * @ingroup actions
  3343. */
  3344. function node_unpublish_action(Node $node, $context = array()) {
  3345. $node->status = NODE_NOT_PUBLISHED;
  3346. watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3347. }
  3348. /**
  3349. * Sets the sticky-at-top-of-list property of a node to 1.
  3350. *
  3351. * @param Drupal\node\Node $node
  3352. * A node entity.
  3353. * @param $context
  3354. * (optional) Array of additional information about what triggered the action.
  3355. * Not used for this action.
  3356. *
  3357. * @ingroup actions
  3358. */
  3359. function node_make_sticky_action(Node $node, $context = array()) {
  3360. $node->sticky = NODE_STICKY;
  3361. watchdog('action', 'Set @type %title to sticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3362. }
  3363. /**
  3364. * Sets the sticky-at-top-of-list property of a node to 0.
  3365. *
  3366. * @param Drupal\node\Node $node
  3367. * A node entity.
  3368. * @param $context
  3369. * (optional) Array of additional information about what triggered the action.
  3370. * Not used for this action.
  3371. *
  3372. * @ingroup actions
  3373. */
  3374. function node_make_unsticky_action(Node $node, $context = array()) {
  3375. $node->sticky = NODE_NOT_STICKY;
  3376. watchdog('action', 'Set @type %title to unsticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3377. }
  3378. /**
  3379. * Sets the promote property of a node to 1.
  3380. *
  3381. * @param Drupal\node\Node $node
  3382. * A node entity.
  3383. * @param $context
  3384. * (optional) Array of additional information about what triggered the action.
  3385. * Not used for this action.
  3386. *
  3387. * @ingroup actions
  3388. */
  3389. function node_promote_action(Node $node, $context = array()) {
  3390. $node->promote = NODE_PROMOTED;
  3391. watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3392. }
  3393. /**
  3394. * Sets the promote property of a node to 0.
  3395. *
  3396. * @param Drupal\node\Node $node
  3397. * A node entity.
  3398. * @param $context
  3399. * (optional) Array of additional information about what triggered the action.
  3400. * Not used for this action.
  3401. *
  3402. * @ingroup actions
  3403. */
  3404. function node_unpromote_action(Node $node, $context = array()) {
  3405. $node->promote = NODE_NOT_PROMOTED;
  3406. watchdog('action', 'Removed @type %title from front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3407. }
  3408. /**
  3409. * Saves a node.
  3410. *
  3411. * @param Drupal\node\Node $node
  3412. * The node to be saved.
  3413. *
  3414. * @ingroup actions
  3415. */
  3416. function node_save_action(Node $node) {
  3417. $node->save();
  3418. watchdog('action', 'Saved @type %title', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3419. }
  3420. /**
  3421. * Assigns ownership of a node to a user.
  3422. *
  3423. * @param Drupal\node\Node $node
  3424. * A node entity to modify.
  3425. * @param $context
  3426. * Array of additional information about what triggered the action. Includes
  3427. * the following elements:
  3428. * - owner_uid: User ID to assign to the node.
  3429. *
  3430. * @see node_assign_owner_action_form()
  3431. * @see node_assign_owner_action_validate()
  3432. * @see node_assign_owner_action_submit()
  3433. * @ingroup actions
  3434. */
  3435. function node_assign_owner_action(Node $node, $context) {
  3436. $node->uid = $context['owner_uid'];
  3437. $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
  3438. watchdog('action', 'Changed owner of @type %title to uid %name.', array('@type' => node_type_get_name($node), '%title' => $node->title, '%name' => $owner_name));
  3439. }
  3440. /**
  3441. * Form constructor for the settings form for node_assign_owner_action().
  3442. *
  3443. * @param $context
  3444. * Array of additional information about what triggered the action. Includes
  3445. * the following elements:
  3446. * - owner_uid: User ID to assign to the node.
  3447. *
  3448. * @see node_assign_owner_action_submit()
  3449. * @see node_assign_owner_action_validate()
  3450. * @ingroup forms
  3451. */
  3452. function node_assign_owner_action_form($context) {
  3453. $description = t('The username of the user to which you would like to assign ownership.');
  3454. $count = db_query("SELECT COUNT(*) FROM {users}")->fetchField();
  3455. $owner_name = '';
  3456. if (isset($context['owner_uid'])) {
  3457. $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
  3458. }
  3459. // Use dropdown for fewer than 200 users; textbox for more than that.
  3460. if (intval($count) < 200) {
  3461. $options = array();
  3462. $result = db_query("SELECT uid, name FROM {users} WHERE uid > 0 ORDER BY name");
  3463. foreach ($result as $data) {
  3464. $options[$data->name] = $data->name;
  3465. }
  3466. $form['owner_name'] = array(
  3467. '#type' => 'select',
  3468. '#title' => t('Username'),
  3469. '#default_value' => $owner_name,
  3470. '#options' => $options,
  3471. '#description' => $description,
  3472. );
  3473. }
  3474. else {
  3475. $form['owner_name'] = array(
  3476. '#type' => 'textfield',
  3477. '#title' => t('Username'),
  3478. '#default_value' => $owner_name,
  3479. '#autocomplete_path' => 'user/autocomplete',
  3480. '#size' => '6',
  3481. '#maxlength' => '60',
  3482. '#description' => $description,
  3483. );
  3484. }
  3485. return $form;
  3486. }
  3487. /**
  3488. * Form validation handler for node_assign_owner_action_form().
  3489. *
  3490. * @see node_assign_owner_action_submit()
  3491. */
  3492. function node_assign_owner_action_validate($form, $form_state) {
  3493. $exists = (bool) db_query_range('SELECT 1 FROM {users} WHERE name = :name', 0, 1, array(':name' => $form_state['values']['owner_name']))->fetchField();
  3494. if (!$exists) {
  3495. form_set_error('owner_name', t('Enter a valid username.'));
  3496. }
  3497. }
  3498. /**
  3499. * Form submission handler for node_assign_owner_action_form().
  3500. *
  3501. * @see node_assign_owner_action_validate()
  3502. */
  3503. function node_assign_owner_action_submit($form, $form_state) {
  3504. // Username can change, so we need to store the ID, not the username.
  3505. $uid = db_query('SELECT uid from {users} WHERE name = :name', array(':name' => $form_state['values']['owner_name']))->fetchField();
  3506. return array('owner_uid' => $uid);
  3507. }
  3508. /**
  3509. * Generates settings form for node_unpublish_by_keyword_action().
  3510. */
  3511. function node_unpublish_by_keyword_action_form($context) {
  3512. $form['keywords'] = array(
  3513. '#title' => t('Keywords'),
  3514. '#type' => 'textarea',
  3515. '#description' => t('The content will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'),
  3516. '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
  3517. );
  3518. return $form;
  3519. }
  3520. /**
  3521. * Form submission handler for node_unpublish_by_keyword_action().
  3522. */
  3523. function node_unpublish_by_keyword_action_submit($form, $form_state) {
  3524. return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
  3525. }
  3526. /**
  3527. * Unpublishes a node containing certain keywords.
  3528. *
  3529. * @param Drupal\node\Node $node
  3530. * A node entity to modify.
  3531. * @param $context
  3532. * Array of additional information about what triggered the action. Includes
  3533. * the following elements:
  3534. * - keywords: Array of keywords. If any keyword is present in the rendered
  3535. * node, the node's status flag is set to unpublished.
  3536. *
  3537. * @see node_unpublish_by_keyword_action_form()
  3538. * @see node_unpublish_by_keyword_action_submit()
  3539. *
  3540. * @ingroup actions
  3541. */
  3542. function node_unpublish_by_keyword_action(Node $node, $context) {
  3543. foreach ($context['keywords'] as $keyword) {
  3544. $elements = node_view(clone $node);
  3545. if (strpos(drupal_render($elements), $keyword) !== FALSE || strpos($node->title, $keyword) !== FALSE) {
  3546. $node->status = NODE_NOT_PUBLISHED;
  3547. watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
  3548. break;
  3549. }
  3550. }
  3551. }
  3552. /**
  3553. * Implements hook_requirements().
  3554. */
  3555. function node_requirements($phase) {
  3556. $requirements = array();
  3557. // Ensure translations don't break at install time
  3558. $t = get_t();
  3559. // Only show rebuild button if there are either 0, or 2 or more, rows
  3560. // in the {node_access} table, or if there are modules that
  3561. // implement hook_node_grants().
  3562. $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField();
  3563. if ($grant_count != 1 || count(module_implements('node_grants')) > 0) {
  3564. $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count));
  3565. } else {
  3566. $value = $t('Disabled');
  3567. }
  3568. $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.');
  3569. $requirements['node_access'] = array(
  3570. 'title' => $t('Node Access Permissions'),
  3571. 'value' => $value,
  3572. 'description' => $description . ' ' . l(t('Rebuild permissions'), 'admin/reports/status/rebuild'),
  3573. );
  3574. return $requirements;
  3575. }
  3576. /**
  3577. * Implements hook_modules_enabled().
  3578. */
  3579. function node_modules_enabled($modules) {
  3580. // Check if any of the newly enabled modules require the node_access table to
  3581. // be rebuilt.
  3582. if (!node_access_needs_rebuild() && array_intersect($modules, module_implements('node_grants'))) {
  3583. node_access_needs_rebuild(TRUE);
  3584. }
  3585. }
  3586. /**
  3587. * Implements hook_modules_disabled().
  3588. */
  3589. function node_modules_disabled($modules) {
  3590. // Check whether any of the disabled modules implemented hook_node_grants(),
  3591. // in which case the node access table needs to be rebuilt.
  3592. foreach ($modules as $module) {
  3593. // At this point, the module is already disabled, but its code is still
  3594. // loaded in memory. Module functions must no longer be called. We only
  3595. // check whether a hook implementation function exists and do not invoke it.
  3596. if (!node_access_needs_rebuild() && module_hook($module, 'node_grants')) {
  3597. node_access_needs_rebuild(TRUE);
  3598. }
  3599. }
  3600. // If there remains no more node_access module, rebuilding will be
  3601. // straightforward, we can do it right now.
  3602. if (node_access_needs_rebuild() && count(module_implements('node_grants')) == 0) {
  3603. node_access_rebuild();
  3604. }
  3605. }
  3606. /**
  3607. * Implements hook_file_download_access().
  3608. */
  3609. function node_file_download_access($field, $entity_type, $entity) {
  3610. if ($entity_type == 'node') {
  3611. return node_access('view', $entity);
  3612. }
  3613. }
  3614. /**
  3615. * Implements hook_language_delete().
  3616. */
  3617. function node_language_delete($language) {
  3618. // On nodes with this language, unset the language.
  3619. db_update('node')
  3620. ->fields(array('langcode' => ''))
  3621. ->condition('langcode', $language->langcode)
  3622. ->execute();
  3623. }
Login or register to post comments