node.module

You are here

  1. 7 modules/node/node.module
  2. 4.6 modules/node.module
  3. 4.7 modules/node.module
  4. 5 modules/node/node.module
  5. 6 modules/node/node.module
  6. 8 core/modules/node/node.module

The core that allows content to be submitted to the site. Modules and scripts may programmatically submit nodes using the usual form API pattern.

Functions

Namesort descending Description
node_access Determines whether the current user may perform the operation on the node.
node_access_acquire_grants Gets the list of node access grants and writes them to the database.
node_access_grants Fetches an array of permission IDs granted to the given user ID.
node_access_needs_rebuild Flags or unflags the node access grants for rebuilding.
node_access_rebuild Rebuilds the node access database.
node_access_view_all_nodes Determines whether the user has a global viewing grant for all nodes.
node_access_write_grants Writes a list of grants to the database, deleting any previously saved ones.
node_action_info Implements hook_action_info().
node_add_body_field Adds default body field to a node type.
node_admin_paths Implements hook_admin_paths().
node_assign_owner_action Assigns ownership of a node to a user.
node_assign_owner_action_form Generates the settings form for node_assign_owner_action().
node_assign_owner_action_submit Saves settings form for node_assign_owner_action().
node_assign_owner_action_validate Validates settings form for node_assign_owner_action().
node_block_configure Implements hook_block_configure().
node_block_info Implements hook_block_info().
node_block_list_alter Implements hook_block_list_alter().
node_block_save Implements hook_block_save().
node_block_view Implements hook_block_view().
node_build_content Builds a structured array representing the node's content.
node_content_form Implements hook_form().
node_cron Implements hook_cron().
node_delete Deletes a node.
node_delete_multiple Deletes multiple nodes.
node_entity_info Implements hook_entity_info().
node_feed Generates and prints an RSS feed.
node_field_display_node_alter Implements hook_field_display_ENTITY_TYPE_alter().
node_field_extra_fields Implements hook_field_extra_fields().
node_file_download_access Implements hook_file_download_access().
node_forms Implements hook_forms().
node_form_block_add_block_form_alter Implements hook_form_FORMID_alter().
node_form_block_admin_configure_alter Implements hook_form_FORMID_alter().
node_form_block_admin_configure_submit Form submission handler for node_form_block_admin_configure_alter().
node_form_block_custom_block_delete_alter Implements hook_form_FORMID_alter().
node_form_block_custom_block_delete_submit Form submission handler for node_form_block_custom_block_delete_alter().
node_form_search_form_alter Implements hook_form_FORM_ID_alter().
node_get_recent Finds the most recently changed nodes that are available to the current user.
node_help Implements hook_help().
node_hook Determines whether a node hook exists.
node_invoke Invokes a node hook.
node_is_page Returns whether the current page is the full page view of the passed-in node.
node_last_changed Finds the last time a node was changed.
node_last_viewed Retrieves the timestamp for the current user's last view of a specified node.
node_list_permissions Helper function to generate standard node permission list for a given type.
node_load Loads a node object from the database.
node_load_multiple Loads node entities from the database.
node_make_sticky_action Sets the sticky-at-top-of-list property of a node to 1.
node_make_unsticky_action Sets the sticky-at-top-of-list property of a node to 0.
node_mark Determines the type of marker to be displayed for a given node.
node_menu Implements hook_menu().
node_menu_local_tasks_alter Implements hook_menu_local_tasks_alter().
node_modules_enabled Implements hook_modules_enabled().
node_modules_uninstalled Implements hook_modules_uninstalled().
node_node_access Implements hook_node_access().
node_object_prepare Prepares a node object for editing.
node_page_default Menu callback: Generates a listing of promoted nodes.
node_page_title Title callback: Returns the title of the node.
node_page_view Menu callback: Displays a single node.
node_permission Implements hook_permission().
node_permissions_get_configured_types Returns an array of node types that should be managed by permissions.
node_promote_action Sets the promote property of a node to 1.
node_publish_action Sets the status of a node to 1 (published).
node_query_entity_field_access_alter Implements hook_query_TAG_alter().
node_query_node_access_alter Implements hook_query_TAG_alter().
node_ranking Implements hook_ranking().
node_rdf_mapping Implements hook_rdf_mapping().
node_requirements Implements hook_requirements().
node_revision_delete Deletes a node revision.
node_revision_list Returns a list of all the existing revision numbers.
node_save Saves changes to a node or adds a new node.
node_save_action Saves a node.
node_search_access Implements hook_search_access().
node_search_admin Implements hook_search_admin().
node_search_execute Implements hook_search_execute().
node_search_info Implements hook_search_info().
node_search_reset Implements hook_search_reset().
node_search_status Implements hook_search_status().
node_search_validate Form validation handler for node_form_alter().
node_show Generates an array which displays a node detail page.
node_submit Prepares node for saving by populating author and creation date.
node_tag_new Updates the 'last viewed' timestamp of the specified node for current user.
node_theme Implements hook_theme().
node_title_list Gathers a listing of links to nodes.
node_types_rebuild Updates the database cache of node types.
node_type_cache_reset Clears the node type cache.
node_type_delete Deletes a node type from the database.
node_type_get_base Returns the node type base of the passed node or node type string.
node_type_get_name Returns the node type name of the passed node or node type string.
node_type_get_names Returns a list of available node type names.
node_type_get_type Returns the node type of the passed node or node type string.
node_type_get_types Returns a list of all the available node types.
node_type_load Menu argument loader: loads a node type by string.
node_type_page_title Title callback: Returns the unsanitized title of the node type edit form.
node_type_save Saves a node type to the database.
node_type_set_defaults Sets the default values for a node type.
node_type_update_nodes Updates all nodes of one type to be of another type.
node_unpromote_action Sets the promote property of a node to 0.
node_unpublish_action Sets the status of a node to 0 (unpublished).
node_unpublish_by_keyword_action Unpublishes a node containing certain keywords.
node_unpublish_by_keyword_action_form Generates settings form for node_unpublish_by_keyword_action().
node_unpublish_by_keyword_action_submit Saves settings form for node_unpublish_by_keyword_action().
node_update_index Implements hook_update_index().
node_uri Implements callback_entity_info_uri().
node_user_cancel Implements hook_user_cancel().
node_user_delete Implements hook_user_delete().
node_validate Implements hook_validate().
node_view Generates an array for rendering the given node.
node_view_multiple Constructs a drupal_render() style array from an array of loaded nodes.
template_preprocess_node Processes variables for node.tpl.php
theme_node_recent_block Returns HTML for a list of recent content.
theme_node_recent_content Returns HTML for a recent node to be displayed in the recent content block.
theme_node_search_admin Returns HTML for the content ranking part of the search settings admin page.
_node_access_rebuild_batch_finished Performs post-processing for node_access_rebuild().
_node_access_rebuild_batch_operation Performs batch operation for node_access_rebuild().
_node_add_access Access callback: Checks whether the user has permission to add a node.
_node_extract_type Extracts the type name.
_node_index_node Indexes a single node.
_node_query_node_access_alter Helper for node access functions.
_node_rankings Gathers the rankings from the the hook_ranking() implementations.
_node_revision_access Access callback: Checks node revision access.
_node_save_revision Helper function to save a revision with the uid of the current user.
_node_types_build Builds and returns the list of available node types.

Constants

Namesort descending Description
NODE_ACCESS_ALLOW Modules should return this value from hook_node_access() to allow access to a node.
NODE_ACCESS_DENY Modules should return this value from hook_node_access() to deny access to a node.
NODE_ACCESS_IGNORE Modules should return this value from hook_node_access() to not affect node access.
NODE_NEW_LIMIT Nodes changed before this time are always marked as read.
NODE_NOT_PROMOTED Node is not promoted to front page.
NODE_NOT_PUBLISHED Node is not published.
NODE_NOT_STICKY Node is not sticky at top of the page.
NODE_PROMOTED Node is promoted to front page.
NODE_PUBLISHED Node is published.
NODE_STICKY Node is sticky at top of the page.

Classes

Namesort descending Description
NodeController Controller class for nodes.

File

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