Skip navigation
Help

node.module

  1. drupal
    1. 6 drupal/modules/node/node.module
    2. 7 drupal/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.

Classes

NameDescription
NodeControllerController class for nodes.

Functions & methods

NameDescription
node_accessDetermine whether the current user may perform the given operation on the specified node.
node_access_acquire_grantsGets the list of node access grants and writes them to the database.
node_access_grantsFetch an array of permission IDs granted to the given user ID.
node_access_needs_rebuildFlag / unflag the node access grants for rebuilding, or read the current value of the flag.
node_access_rebuildRebuild the node access database. This is occasionally needed by modules that make system-wide changes to access levels.
node_access_view_all_nodesDetermines whether the user has a global viewing grant for all nodes.
node_access_write_grantsWrites a list of grants to the database, deleting any previously saved ones.
node_action_infoImplements hook_action_info().
node_add_body_fieldAdd default body field to a node type.
node_admin_pathsImplements hook_admin_paths().
node_assign_owner_actionAssigns ownership of a node to a user.
node_assign_owner_action_formGenerates the settings form for node_assign_owner_action().
node_assign_owner_action_submitSaves settings form for node_assign_owner_action().
node_assign_owner_action_validateValidates settings form for node_assign_owner_action().
node_block_configureImplements hook_block_configure().
node_block_infoImplements hook_block_info().
node_block_list_alterImplements hook_block_list_alter().
node_block_saveImplements hook_block_save().
node_block_viewImplements hook_block_view().
node_build_contentBuilds a structured array representing the node's content.
node_content_formImplements hook_form().
node_cronImplements hook_cron().
node_deleteDelete a node.
node_delete_multipleDelete multiple nodes.
node_entity_infoImplements hook_entity_info().
node_feedGenerates and prints an RSS feed.
node_field_display_node_alterImplements hook_field_display_ENTITY_TYPE_alter().
node_field_extra_fieldsImplements hook_field_extra_fields().
node_file_download_accessImplements hook_file_download_access().
node_formsImplements hook_forms(). All node forms share the same form handler.
node_form_block_add_block_form_alterImplements hook_form_FORMID_alter().
node_form_block_admin_configure_alterImplements hook_form_FORMID_alter().
node_form_block_admin_configure_submitForm submit handler for block configuration form.
node_form_block_custom_block_delete_alterImplements hook_form_FORMID_alter().
node_form_block_custom_block_delete_submitForm submit handler for custom block delete form.
node_form_search_form_alterImplements hook_form_FORM_ID_alter().
node_get_recentFinds the most recently changed nodes that are available to the current user.
node_helpImplements hook_help().
node_hookDetermine whether a node hook exists.
node_invokeInvoke a node hook.
node_is_pageReturns whether the current page is the full page view of the passed-in node.
node_last_changedFinds the last time a node was changed.
node_last_viewedRetrieves the timestamp at which the current user last viewed the specified node.
node_list_permissionsHelper function to generate standard node permission list for a given type.
node_loadLoad a node object from the database.
node_load_multipleLoad node entities from the database.
node_make_sticky_actionSets the sticky-at-top-of-list property of a node to 1.
node_make_unsticky_actionSets the sticky-at-top-of-list property of a node to 0.
node_markDecide on the type of marker to be displayed for a given node.
node_menuImplements hook_menu().
node_menu_local_tasks_alterImplements hook_menu_local_tasks_alter().
node_modules_enabledImplements hook_modules_enabled().
node_modules_uninstalledImplements hook_modules_uninstalled().
node_node_accessImplements hook_node_access().
node_object_preparePrepares a node object for editing.
node_page_defaultMenu callback; Generate a listing of promoted nodes.
node_page_titleTitle callback.
node_page_viewMenu callback; view a single node.
node_permissionImplements hook_permission().
node_permissions_get_configured_typesReturns an array of node types that should be managed by permissions.
node_promote_actionSets the promote property of a node to 1.
node_publish_actionSets the status of a node to 1 (published).
node_query_entity_field_access_alterImplements hook_query_TAG_alter().
node_query_node_access_alterImplements hook_query_TAG_alter().
node_rankingImplements hook_ranking().
node_rdf_mappingImplements hook_rdf_mapping().
node_requirementsImplements hook_requirements().
node_revision_deleteDelete a node revision.
node_revision_listReturn a list of all the existing revision numbers.
node_saveSave changes to a node or add a new node.
node_save_actionSaves a node.
node_search_accessImplements hook_search_access().
node_search_adminImplements hook_search_admin().
node_search_executeImplements hook_search_execute().
node_search_infoImplements hook_search_info().
node_search_resetImplements hook_search_reset().
node_search_statusImplements hook_search_status().
node_search_validateForm API callback for the search form. Registered in node_form_alter().
node_showGenerate an array which displays a node detail page.
node_submitPrepare node for saving by populating author and creation date.
node_tag_newUpdate the 'last viewed' timestamp of the specified node for current user.
node_themeImplements hook_theme().
node_title_listGathers a listing of links to nodes.
node_types_rebuildUpdates the database cache of node types.
node_type_cache_resetClears the node type cache.
node_type_deleteDeletes a node type from the database.
node_type_get_baseReturns the node type base of the passed node or node type string.
node_type_get_nameReturns the node type name of the passed node or node type string.
node_type_get_namesReturns a list of available node type names.
node_type_get_typeReturns the node type of the passed node or node type string.
node_type_get_typesReturns a list of all the available node types.
node_type_loadMenu argument loader: loads a node type by string.
node_type_page_titleTitle callback for a node type.
node_type_saveSaves a node type to the database.
node_type_set_defaultsSets the default values for a node type.
node_type_update_nodesUpdates all nodes of one type to be of another type.
node_unpromote_actionSets the promote property of a node to 0.
node_unpublish_actionSets the status of a node to 0 (unpublished).
node_unpublish_by_keyword_actionUnpublishes a node containing certain keywords.
node_unpublish_by_keyword_action_formGenerates settings form for node_unpublish_by_keyword_action().
node_unpublish_by_keyword_action_submitSaves settings form for node_unpublish_by_keyword_action().
node_update_indexImplements hook_update_index().
node_uriEntity uri callback.
node_user_cancelImplements hook_user_cancel().
node_user_deleteImplements hook_user_delete().
node_validatePerform validation checks on the given node.
node_viewGenerate an array for rendering the given node.
node_view_multipleConstruct a drupal_render() style array from an array of loaded nodes.
template_preprocess_nodeProcess variables for node.tpl.php
theme_node_recent_blockReturns HTML for a list of recent content.
theme_node_recent_contentReturns HTML for a recent node to be displayed in the recent content block.
theme_node_search_adminReturns HTML for the content ranking part of the search settings admin page.
_node_access_rebuild_batch_finishedPost-processing for node_access_rebuild_batch.
_node_access_rebuild_batch_operationBatch operation for node_access_rebuild_batch.
_node_add_access
_node_extract_typeExtract the type name.
_node_index_nodeIndex a single node.
_node_query_node_access_alterHelper for node access functions.
_node_rankingsGather the rankings from the the hook_ranking implementations.
_node_revision_access
_node_save_revisionHelper function to save a revision with the uid of the current user.
_node_types_buildBuilds and returns the list of available node types.

Constants

NameDescription
NODE_ACCESS_ALLOWModules should return this value from hook_node_access() to allow access to a node.
NODE_ACCESS_DENYModules should return this value from hook_node_access() to deny access to a node.
NODE_ACCESS_IGNOREModules should return this value from hook_node_access() to not affect node access.
NODE_NEW_LIMITNodes changed before this time are always marked as read.
NODE_NOT_PROMOTEDNode is not promoted to front page.
NODE_NOT_PUBLISHEDNode is not published.
NODE_NOT_STICKYNode is not sticky at top of the page.
NODE_PROMOTEDNode is promoted to front page.
NODE_PUBLISHEDNode is published.
NODE_STICKYNode is sticky at top of the page.

File

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