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.

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_nodesDetermine 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_infoImplementation of hook_action_info().
node_assign_owner_actionImplementation of a configurable Drupal action. Assigns ownership of a node to a user.
node_assign_owner_action_form
node_assign_owner_action_submit
node_assign_owner_action_validate
node_blockImplementation of hook_block().
node_build_contentBuilds a structured array representing the node's content.
node_comment_modeRetrieve the comment mode for the given node ID (none, read, or read/write).
node_content_accessImplementation of hook_access().
node_content_formImplementation of hook_form().
node_cronImplementation of hook_cron().
node_db_rewrite_sqlImplementation of hook_db_rewrite_sql
node_deleteDelete a node.
node_feedA generic function for generating RSS feeds from a set of nodes.
node_formsImplementation of hook_forms(). All node forms share the same form handler
node_form_alterImplementation of hook_form_alter().
node_get_typesBuilds a list of available node types, and returns all of part of this list in the specified format.
node_helpImplementation of hook_help().
node_hookDetermine whether a node hook exists.
node_hook_infoImplementation of hook_hook_info().
node_initImplementation of hook_init().
node_invokeInvoke a node hook.
node_invoke_nodeapiInvoke a hook_nodeapi() operation in all modules.
node_last_changed
node_last_viewedRetrieves the timestamp at which the current user last viewed the specified node.
node_linkImplementation of hook_link().
node_loadLoad a node object from the database.
node_make_sticky_actionImplementation of a Drupal action. Sets the sticky-at-top-of-list property of a node to 1.
node_make_unsticky_actionImplementation of a Drupal action. Sets 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_menuImplementation of hook_menu().
node_page_defaultMenu callback; Generate a listing of promoted nodes.
node_page_titleTitle callback.
node_page_viewMenu callback; view a single node.
node_permImplementation of hook_perm().
node_prepareApply filters and build the node's standard elements.
node_promote_actionImplementation of a Drupal action. Sets the promote property of a node to 1.
node_publish_actionImplementation of a Drupal action. Sets the status of a node to 1, meaning published.
node_revision_listReturn a list of all the existing revision numbers.
node_saveSave a node object into the database.
node_save_actionImplementation of a Drupal action. Saves a node.
node_searchImplementation of hook_search().
node_search_validateForm API callback for the search form. Registered in node_form_alter().
node_showGenerate a page displaying a single node, along with its comments.
node_submitPrepares a node for saving by populating teaser, author, and creation date.
node_tag_newUpdate the 'last viewed' timestamp of the specified node for current user.
node_teaserGenerate a teaser for a node body.
node_teaser_include_verifyEnsure value of "teaser_include" checkbox is consistent with other form data.
node_teaser_jsSee if the user used JS to submit a teaser.
node_themeImplementation of hook_theme()
node_title_listGather a listing of links to nodes.
node_types_rebuildResets the database cache of node types, and saves all new or non-modified module-defined node types to the database.
node_type_deleteDeletes a node type from the database.
node_type_saveSaves a node type to the database.
node_type_update_nodesUpdates all nodes of one type to be of another type.
node_unpromote_actionImplementation of a Drupal action. Sets the promote property of a node to 0.
node_unpublish_actionImplementation of a Drupal action. Sets the status of a node to 0, meaning unpublished.
node_unpublish_by_keyword_actionImplementation of a configurable Drupal action. Unpublish a node if it contains a certain string.
node_unpublish_by_keyword_action_form
node_unpublish_by_keyword_action_submit
node_update_indexImplementation of hook_update_index().
node_userImplementation of hook_user().
node_validatePerform validation checks on the given node.
node_viewGenerate a display of the given node.
theme_node_listFormat a listing of links to nodes.
theme_node_log_messageTheme a log message.
theme_node_search_adminTheme the content ranking part of the search settings admin page.
theme_node_submittedFormat the "Submitted by username on date/time" for each node
_node_access_join_sqlGenerate an SQL join clause for use in fetching a node listing.
_node_access_rebuild_batch_finishedPost-processing for node_access_rebuild_batch.
_node_access_rebuild_batch_operationBatch operation for node_access_rebuild_batch.
_node_access_where_sqlGenerate an SQL where clause for use in fetching a node listing.
_node_add_access
_node_index_nodeIndex a single node.
_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.
_node_type_set_defaultsSet default values for a node type defined through hook_node_info().

Constants

NameDescription
NODE_BUILD_NORMAL
NODE_BUILD_PREVIEW
NODE_BUILD_PRINT
NODE_BUILD_RSS
NODE_BUILD_SEARCH_INDEX
NODE_BUILD_SEARCH_RESULT
NODE_NEW_LIMITNodes changed before this time are always marked as read.

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 scripts may
  5. * programmatically submit nodes using the usual form API pattern.
  6. */
  7. /**
  8. * Nodes changed before this time are always marked as read.
  9. *
  10. * Nodes changed after this time may be marked new, updated, or read, depending
  11. * on their state for the current user. Defaults to 30 days ago.
  12. */
  13. define('NODE_NEW_LIMIT', time() - 30 * 24 * 60 * 60);
  14. define('NODE_BUILD_NORMAL', 0);
  15. define('NODE_BUILD_PREVIEW', 1);
  16. define('NODE_BUILD_SEARCH_INDEX', 2);
  17. define('NODE_BUILD_SEARCH_RESULT', 3);
  18. define('NODE_BUILD_RSS', 4);
  19. define('NODE_BUILD_PRINT', 5);
  20. /**
  21. * Implementation of hook_help().
  22. */
  23. function node_help($path, $arg) {
  24. // Remind site administrators about the {node_access} table being flagged
  25. // for rebuild. We don't need to issue the message on the confirm form, or
  26. // while the rebuild is being processed.
  27. if ($path != 'admin/content/node-settings/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
  28. && user_access('access administration pages') && node_access_needs_rebuild()) {
  29. if ($path == 'admin/content/node-settings') {
  30. $message = t('The content access permissions need to be rebuilt.');
  31. }
  32. else {
  33. $message = t('The content access permissions need to be rebuilt. Please visit <a href="@node_access_rebuild">this page</a>.', array('@node_access_rebuild' => url('admin/content/node-settings/rebuild')));
  34. }
  35. drupal_set_message($message, 'error');
  36. }
  37. switch ($path) {
  38. case 'admin/help#node':
  39. $output = '<p>'. t('The node module manages content on your site, and stores all posts (regardless of type) as a "node". In addition to basic publishing settings, including whether the post has been published, promoted to the site front page, or should remain present (or sticky) at the top of lists, the node module also records basic information about the author of a post. Optional revision control over edits is available. For additional functionality, the node module is often extended by other modules.') .'</p>';
  40. $output .= '<p>'. t('Though each post on your site is a node, each post is also of a particular <a href="@content-type">content type</a>. <a href="@content-type">Content types</a> are used to define the characteristics of a post, including the title and description of the fields displayed on its add and edit pages. Each content type may have different default settings for <em>Publishing options</em> and other workflow controls. By default, the two content types in a standard Drupal installation are <em>Page</em> and <em>Story</em>. Use the <a href="@content-type">content types page</a> to add new or edit existing content types. Additional content types also become available as you enable additional core, contributed and custom modules.', array('@content-type' => url('admin/content/types'))) .'</p>';
  41. $output .= '<p>'. t('The administrative <a href="@content">content page</a> allows you to review and manage your site content. The <a href="@post-settings">post settings page</a> sets certain options for the display of posts. The node module makes a number of permissions available for each content type, which may be set by role on the <a href="@permissions">permissions page</a>.', array('@content' => url('admin/content/node'), '@post-settings' => url('admin/content/node-settings'), '@permissions' => url('admin/user/permissions'))) .'</p>';
  42. $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@node">Node module</a>.', array('@node' => 'http://drupal.org/handbook/modules/node/')) .'</p>';
  43. return $output;
  44. case 'admin/content/node':
  45. return ' '; // Return a non-null value so that the 'more help' link is shown.
  46. case 'admin/content/types':
  47. return '<p>'. t('Below is a list of all the content types on your site. All posts that exist on your site are instances of one of these content types.') .'</p>';
  48. case 'admin/content/types/add':
  49. return '<p>'. t('To create a new content type, enter the human-readable name, the machine-readable name, and all other relevant fields that are on this page. Once created, users of your site will be able to create posts that are instances of this content type.') .'</p>';
  50. case 'node/%/revisions':
  51. return '<p>'. t('The revisions let you track differences between multiple versions of a post.') .'</p>';
  52. case 'node/%/edit':
  53. $node = node_load($arg[1]);
  54. $type = node_get_types('type', $node->type);
  55. return (!empty($type->help) ? '<p>'. filter_xss_admin($type->help) .'</p>' : '');
  56. }
  57. if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
  58. $type = node_get_types('type', str_replace('-', '_', $arg[2]));
  59. return (!empty($type->help) ? '<p>'. filter_xss_admin($type->help) .'</p>' : '');
  60. }
  61. }
  62. /**
  63. * Implementation of hook_theme()
  64. */
  65. function node_theme() {
  66. return array(
  67. 'node' => array(
  68. 'arguments' => array('node' => NULL, 'teaser' => FALSE, 'page' => FALSE),
  69. 'template' => 'node',
  70. ),
  71. 'node_list' => array(
  72. 'arguments' => array('items' => NULL, 'title' => NULL),
  73. ),
  74. 'node_search_admin' => array(
  75. 'arguments' => array('form' => NULL),
  76. ),
  77. 'node_filter_form' => array(
  78. 'arguments' => array('form' => NULL),
  79. 'file' => 'node.admin.inc',
  80. ),
  81. 'node_filters' => array(
  82. 'arguments' => array('form' => NULL),
  83. 'file' => 'node.admin.inc',
  84. ),
  85. 'node_admin_nodes' => array(
  86. 'arguments' => array('form' => NULL),
  87. 'file' => 'node.admin.inc',
  88. ),
  89. 'node_add_list' => array(
  90. 'arguments' => array('content' => NULL),
  91. 'file' => 'node.pages.inc',
  92. ),
  93. 'node_form' => array(
  94. 'arguments' => array('form' => NULL),
  95. 'file' => 'node.pages.inc',
  96. ),
  97. 'node_preview' => array(
  98. 'arguments' => array('node' => NULL),
  99. 'file' => 'node.pages.inc',
  100. ),
  101. 'node_log_message' => array(
  102. 'arguments' => array('log' => NULL),
  103. ),
  104. 'node_submitted' => array(
  105. 'arguments' => array('node' => NULL),
  106. ),
  107. );
  108. }
  109. /**
  110. * Implementation of hook_cron().
  111. */
  112. function node_cron() {
  113. db_query('DELETE FROM {history} WHERE timestamp < %d', NODE_NEW_LIMIT);
  114. }
  115. /**
  116. * Gather a listing of links to nodes.
  117. *
  118. * @param $result
  119. * A DB result object from a query to fetch node objects. If your query
  120. * joins the <code>node_comment_statistics</code> table so that the
  121. * <code>comment_count</code> field is available, a title attribute will
  122. * be added to show the number of comments.
  123. * @param $title
  124. * A heading for the resulting list.
  125. *
  126. * @return
  127. * An HTML list suitable as content for a block, or FALSE if no result can
  128. * fetch from DB result object.
  129. */
  130. function node_title_list($result, $title = NULL) {
  131. $items = array();
  132. $num_rows = FALSE;
  133. while ($node = db_fetch_object($result)) {
  134. $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());
  135. $num_rows = TRUE;
  136. }
  137. return $num_rows ? theme('node_list', $items, $title) : FALSE;
  138. }
  139. /**
  140. * Format a listing of links to nodes.
  141. *
  142. * @ingroup themeable
  143. */
  144. function theme_node_list($items, $title = NULL) {
  145. return theme('item_list', $items, $title);
  146. }
  147. /**
  148. * Update the 'last viewed' timestamp of the specified node for current user.
  149. */
  150. function node_tag_new($nid) {
  151. global $user;
  152. if ($user->uid) {
  153. if (node_last_viewed($nid)) {
  154. db_query('UPDATE {history} SET timestamp = %d WHERE uid = %d AND nid = %d', time(), $user->uid, $nid);
  155. }
  156. else {
  157. @db_query('INSERT INTO {history} (uid, nid, timestamp) VALUES (%d, %d, %d)', $user->uid, $nid, time());
  158. }
  159. }
  160. }
  161. /**
  162. * Retrieves the timestamp at which the current user last viewed the
  163. * specified node.
  164. */
  165. function node_last_viewed($nid) {
  166. global $user;
  167. static $history;
  168. if (!isset($history[$nid])) {
  169. $history[$nid] = db_fetch_object(db_query("SELECT timestamp FROM {history} WHERE uid = %d AND nid = %d", $user->uid, $nid));
  170. }
  171. return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
  172. }
  173. /**
  174. * Decide on the type of marker to be displayed for a given node.
  175. *
  176. * @param $nid
  177. * Node ID whose history supplies the "last viewed" timestamp.
  178. * @param $timestamp
  179. * Time which is compared against node's "last viewed" timestamp.
  180. * @return
  181. * One of the MARK constants.
  182. */
  183. function node_mark($nid, $timestamp) {
  184. global $user;
  185. static $cache;
  186. if (!$user->uid) {
  187. return MARK_READ;
  188. }
  189. if (!isset($cache[$nid])) {
  190. $cache[$nid] = node_last_viewed($nid);
  191. }
  192. if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
  193. return MARK_NEW;
  194. }
  195. elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
  196. return MARK_UPDATED;
  197. }
  198. return MARK_READ;
  199. }
  200. /**
  201. * See if the user used JS to submit a teaser.
  202. */
  203. function node_teaser_js(&$form, &$form_state) {
  204. if (isset($form['#post']['teaser_js'])) {
  205. // Glue the teaser to the body.
  206. if (trim($form_state['values']['teaser_js'])) {
  207. // Space the teaser from the body
  208. $body = trim($form_state['values']['teaser_js']) ."\r\n<!--break-->\r\n". trim($form_state['values']['body']);
  209. }
  210. else {
  211. // Empty teaser, no spaces.
  212. $body = '<!--break-->'. $form_state['values']['body'];
  213. }
  214. // Pass updated body value on to preview/submit form processing.
  215. form_set_value($form['body'], $body, $form_state);
  216. // Pass updated body value back onto form for those cases
  217. // in which the form is redisplayed.
  218. $form['body']['#value'] = $body;
  219. }
  220. return $form;
  221. }
  222. /**
  223. * Ensure value of "teaser_include" checkbox is consistent with other form data.
  224. *
  225. * This handles two situations in which an unchecked checkbox is rejected:
  226. *
  227. * 1. The user defines a teaser (summary) but it is empty;
  228. * 2. The user does not define a teaser (summary) (in this case an
  229. * unchecked checkbox would cause the body to be empty, or missing
  230. * the auto-generated teaser).
  231. *
  232. * If JavaScript is active then it is used to force the checkbox to be
  233. * checked when hidden, and so the second case will not arise.
  234. *
  235. * In either case a warning message is output.
  236. */
  237. function node_teaser_include_verify(&$form, &$form_state) {
  238. $message = '';
  239. // $form['#post'] is set only when the form is built for preview/submit.
  240. if (isset($form['#post']['body']) && isset($form_state['values']['teaser_include']) && !$form_state['values']['teaser_include']) {
  241. // "teaser_include" checkbox is present and unchecked.
  242. if (strpos($form_state['values']['body'], '<!--break-->') === 0) {
  243. // Teaser is empty string.
  244. $message = t('You specified that the summary should not be shown when this post is displayed in full view. This setting is ignored when the summary is empty.');
  245. }
  246. elseif (strpos($form_state['values']['body'], '<!--break-->') === FALSE) {
  247. // Teaser delimiter is not present in the body.
  248. $message = t('You specified that the summary should not be shown when this post is displayed in full view. This setting has been ignored since you have not defined a summary for the post. (To define a summary, insert the delimiter "&lt;!--break--&gt;" (without the quotes) in the Body of the post to indicate the end of the summary and the start of the main content.)');
  249. }
  250. if (!empty($message)) {
  251. drupal_set_message($message, 'warning');
  252. // Pass new checkbox value on to preview/submit form processing.
  253. form_set_value($form['teaser_include'], 1, $form_state);
  254. // Pass new checkbox value back onto form for those cases
  255. // in which form is redisplayed.
  256. $form['teaser_include']['#value'] = 1;
  257. }
  258. }
  259. return $form;
  260. }
  261. /**
  262. * Generate a teaser for a node body.
  263. *
  264. * If the end of the teaser is not indicated using the <!--break--> delimiter
  265. * then we generate the teaser automatically, trying to end it at a sensible
  266. * place such as the end of a paragraph, a line break, or the end of a
  267. * sentence (in that order of preference).
  268. *
  269. * @param $body
  270. * The content for which a teaser will be generated.
  271. * @param $format
  272. * The format of the content. If the content contains PHP code, we do not
  273. * split it up to prevent parse errors. If the line break filter is present
  274. * then we treat newlines embedded in $body as line breaks.
  275. * @param $size
  276. * The desired character length of the teaser. If omitted, the default
  277. * value will be used. Ignored if the special delimiter is present
  278. * in $body.
  279. * @return
  280. * The generated teaser.
  281. */
  282. function node_teaser($body, $format = NULL, $size = NULL) {
  283. if (!isset($size)) {
  284. $size = variable_get('teaser_length', 600);
  285. }
  286. // Find where the delimiter is in the body
  287. $delimiter = strpos($body, '<!--break-->');
  288. // If the size is zero, and there is no delimiter, the entire body is the teaser.
  289. if ($size == 0 && $delimiter === FALSE) {
  290. return $body;
  291. }
  292. // If a valid delimiter has been specified, use it to chop off the teaser.
  293. if ($delimiter !== FALSE) {
  294. return substr($body, 0, $delimiter);
  295. }
  296. // We check for the presence of the PHP evaluator filter in the current
  297. // format. If the body contains PHP code, we do not split it up to prevent
  298. // parse errors.
  299. if (isset($format)) {
  300. $filters = filter_list_format($format);
  301. if (isset($filters['php/0']) && strpos($body, '<?') !== FALSE) {
  302. return $body;
  303. }
  304. }
  305. // If we have a short body, the entire body is the teaser.
  306. if (drupal_strlen($body) <= $size) {
  307. return $body;
  308. }
  309. // If the delimiter has not been specified, try to split at paragraph or
  310. // sentence boundaries.
  311. // The teaser may not be longer than maximum length specified. Initial slice.
  312. $teaser = truncate_utf8($body, $size);
  313. // Store the actual length of the UTF8 string -- which might not be the same
  314. // as $size.
  315. $max_rpos = strlen($teaser);
  316. // How much to cut off the end of the teaser so that it doesn't end in the
  317. // middle of a paragraph, sentence, or word.
  318. // Initialize it to maximum in order to find the minimum.
  319. $min_rpos = $max_rpos;
  320. // Store the reverse of the teaser. We use strpos on the reversed needle and
  321. // haystack for speed and convenience.
  322. $reversed = strrev($teaser);
  323. // Build an array of arrays of break points grouped by preference.
  324. $break_points = array();
  325. // A paragraph near the end of sliced teaser is most preferable.
  326. $break_points[] = array('</p>' => 0);
  327. // If no complete paragraph then treat line breaks as paragraphs.
  328. $line_breaks = array('<br />' => 6, '<br>' => 4);
  329. // Newline only indicates a line break if line break converter
  330. // filter is present.
  331. if (isset($filters['filter/1'])) {
  332. $line_breaks["\n"] = 1;
  333. }
  334. $break_points[] = $line_breaks;
  335. // If the first paragraph is too long, split at the end of a sentence.
  336. $break_points[] = array('. ' => 1, '! ' => 1, '? ' => 1, '。' => 0, '؟ ' => 1);
  337. // Iterate over the groups of break points until a break point is found.
  338. foreach ($break_points as $points) {
  339. // Look for each break point, starting at the end of the teaser.
  340. foreach ($points as $point => $offset) {
  341. // The teaser is already reversed, but the break point isn't.
  342. $rpos = strpos($reversed, strrev($point));
  343. if ($rpos !== FALSE) {
  344. $min_rpos = min($rpos + $offset, $min_rpos);
  345. }
  346. }
  347. // If a break point was found in this group, slice and return the teaser.
  348. if ($min_rpos !== $max_rpos) {
  349. // Don't slice with length 0. Length must be <0 to slice from RHS.
  350. return ($min_rpos === 0) ? $teaser : substr($teaser, 0, 0 - $min_rpos);
  351. }
  352. }
  353. // If a break point was not found, still return a teaser.
  354. return $teaser;
  355. }
  356. /**
  357. * Builds a list of available node types, and returns all of part of this list
  358. * in the specified format.
  359. *
  360. * @param $op
  361. * The format in which to return the list. When this is set to 'type',
  362. * 'module', or 'name', only the specified node type is returned. When set to
  363. * 'types' or 'names', all node types are returned.
  364. * @param $node
  365. * A node object, array, or string that indicates the node type to return.
  366. * Leave at default value (NULL) to return a list of all node types.
  367. * @param $reset
  368. * Whether or not to reset this function's internal cache (defaults to
  369. * FALSE).
  370. *
  371. * @return
  372. * Either an array of all available node types, or a single node type, in a
  373. * variable format. Returns FALSE if the node type is not found.
  374. */
  375. function node_get_types($op = 'types', $node = NULL, $reset = FALSE) {
  376. static $_node_types, $_node_names;
  377. if ($reset || !isset($_node_types)) {
  378. list($_node_types, $_node_names) = _node_types_build();
  379. }
  380. if ($node) {
  381. if (is_array($node)) {
  382. $type = $node['type'];
  383. }
  384. elseif (is_object($node)) {
  385. $type = $node->type;
  386. }
  387. elseif (is_string($node)) {
  388. $type = $node;
  389. }
  390. if (!isset($_node_types[$type])) {
  391. return FALSE;
  392. }
  393. }
  394. switch ($op) {
  395. case 'types':
  396. return $_node_types;
  397. case 'type':
  398. return isset($_node_types[$type]) ? $_node_types[$type] : FALSE;
  399. case 'module':
  400. return isset($_node_types[$type]->module) ? $_node_types[$type]->module : FALSE;
  401. case 'names':
  402. return $_node_names;
  403. case 'name':
  404. return isset($_node_names[$type]) ? $_node_names[$type] : FALSE;
  405. }
  406. }
  407. /**
  408. * Resets the database cache of node types, and saves all new or non-modified
  409. * module-defined node types to the database.
  410. */
  411. function node_types_rebuild() {
  412. _node_types_build();
  413. $node_types = node_get_types('types', NULL, TRUE);
  414. foreach ($node_types as $type => $info) {
  415. if (!empty($info->is_new)) {
  416. node_type_save($info);
  417. }
  418. if (!empty($info->disabled)) {
  419. node_type_delete($info->type);
  420. }
  421. }
  422. _node_types_build();
  423. }
  424. /**
  425. * Saves a node type to the database.
  426. *
  427. * @param $info
  428. * The node type to save, as an object.
  429. *
  430. * @return
  431. * Status flag indicating outcome of the operation.
  432. */
  433. function node_type_save($info) {
  434. $is_existing = FALSE;
  435. $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
  436. $is_existing = db_result(db_query("SELECT COUNT(*) FROM {node_type} WHERE type = '%s'", $existing_type));
  437. if (!isset($info->help)) {
  438. $info->help = '';
  439. }
  440. if (!isset($info->min_word_count)) {
  441. $info->min_word_count = 0;
  442. }
  443. if (!isset($info->body_label)) {
  444. $info->body_label = '';
  445. }
  446. if ($is_existing) {
  447. db_query("UPDATE {node_type} SET type = '%s', name = '%s', module = '%s', has_title = %d, title_label = '%s', has_body = %d, body_label = '%s', description = '%s', help = '%s', min_word_count = %d, custom = %d, modified = %d, locked = %d WHERE type = '%s'", $info->type, $info->name, $info->module, $info->has_title, $info->title_label, $info->has_body, $info->body_label, $info->description, $info->help, $info->min_word_count, $info->custom, $info->modified, $info->locked, $existing_type);
  448. module_invoke_all('node_type', 'update', $info);
  449. return SAVED_UPDATED;
  450. }
  451. else {
  452. db_query("INSERT INTO {node_type} (type, name, module, has_title, title_label, has_body, body_label, description, help, min_word_count, custom, modified, locked, orig_type) VALUES ('%s', '%s', '%s', %d, '%s', %d, '%s', '%s', '%s', %d, %d, %d, %d, '%s')", $info->type, $info->name, $info->module, $info->has_title, $info->title_label, $info->has_body, $info->body_label, $info->description, $info->help, $info->min_word_count, $info->custom, $info->modified, $info->locked, $info->orig_type);
  453. module_invoke_all('node_type', 'insert', $info);
  454. return SAVED_NEW;
  455. }
  456. }
  457. /**
  458. * Deletes a node type from the database.
  459. *
  460. * @param $type
  461. * The machine-readable name of the node type to be deleted.
  462. */
  463. function node_type_delete($type) {
  464. $info = node_get_types('type', $type);
  465. db_query("DELETE FROM {node_type} WHERE type = '%s'", $type);
  466. module_invoke_all('node_type', 'delete', $info);
  467. }
  468. /**
  469. * Updates all nodes of one type to be of another type.
  470. *
  471. * @param $old_type
  472. * The current node type of the nodes.
  473. * @param $type
  474. * The new node type of the nodes.
  475. *
  476. * @return
  477. * The number of nodes whose node type field was modified.
  478. */
  479. function node_type_update_nodes($old_type, $type) {
  480. db_query("UPDATE {node} SET type = '%s' WHERE type = '%s'", $type, $old_type);
  481. return db_affected_rows();
  482. }
  483. /**
  484. * Builds and returns the list of available node types.
  485. *
  486. * The list of types is built by querying hook_node_info() in all modules, and
  487. * by comparing this information with the node types in the {node_type} table.
  488. *
  489. */
  490. function _node_types_build() {
  491. $_node_types = array();
  492. $_node_names = array();
  493. $info_array = module_invoke_all('node_info');
  494. foreach ($info_array as $type => $info) {
  495. $info['type'] = $type;
  496. $_node_types[$type] = (object) _node_type_set_defaults($info);
  497. $_node_names[$type] = $info['name'];
  498. }
  499. $type_result = db_query(db_rewrite_sql('SELECT nt.type, nt.* FROM {node_type} nt ORDER BY nt.type ASC', 'nt', 'type'));
  500. while ($type_object = db_fetch_object($type_result)) {
  501. // Check for node types from disabled modules and mark their types for removal.
  502. // Types defined by the node module in the database (rather than by a separate
  503. // module using hook_node_info) have a module value of 'node'.
  504. if ($type_object->module != 'node' && empty($info_array[$type_object->type])) {
  505. $type_object->disabled = TRUE;
  506. }
  507. if (!isset($_node_types[$type_object->type]) || $type_object->modified) {
  508. $_node_types[$type_object->type] = $type_object;
  509. $_node_names[$type_object->type] = $type_object->name;
  510. if ($type_object->type != $type_object->orig_type) {
  511. unset($_node_types[$type_object->orig_type]);
  512. unset($_node_names[$type_object->orig_type]);
  513. }
  514. }
  515. }
  516. asort($_node_names);
  517. return array($_node_types, $_node_names);
  518. }
  519. /**
  520. * Set default values for a node type defined through hook_node_info().
  521. */
  522. function _node_type_set_defaults($info) {
  523. if (!isset($info['has_title'])) {
  524. $info['has_title'] = TRUE;
  525. }
  526. if ($info['has_title'] && !isset($info['title_label'])) {
  527. $info['title_label'] = t('Title');
  528. }
  529. if (!isset($info['has_body'])) {
  530. $info['has_body'] = TRUE;
  531. }
  532. if ($info['has_body'] && !isset($info['body_label'])) {
  533. $info['body_label'] = t('Body');
  534. }
  535. if (!isset($info['help'])) {
  536. $info['help'] = '';
  537. }
  538. if (!isset($info['min_word_count'])) {
  539. $info['min_word_count'] = 0;
  540. }
  541. if (!isset($info['custom'])) {
  542. $info['custom'] = FALSE;
  543. }
  544. if (!isset($info['modified'])) {
  545. $info['modified'] = FALSE;
  546. }
  547. if (!isset($info['locked'])) {
  548. $info['locked'] = TRUE;
  549. }
  550. $info['orig_type'] = $info['type'];
  551. $info['is_new'] = TRUE;
  552. return $info;
  553. }
  554. /**
  555. * Determine whether a node hook exists.
  556. *
  557. * @param &$node
  558. * Either a node object, node array, or a string containing the node type.
  559. * @param $hook
  560. * A string containing the name of the hook.
  561. * @return
  562. * TRUE iff the $hook exists in the node type of $node.
  563. */
  564. function node_hook(&$node, $hook) {
  565. $module = node_get_types('module', $node);
  566. if ($module == 'node') {
  567. $module = 'node_content'; // Avoid function name collisions.
  568. }
  569. return module_hook($module, $hook);
  570. }
  571. /**
  572. * Invoke a node hook.
  573. *
  574. * @param &$node
  575. * Either a node object, node array, or a string containing the node type.
  576. * @param $hook
  577. * A string containing the name of the hook.
  578. * @param $a2, $a3, $a4
  579. * Arguments to pass on to the hook, after the $node argument.
  580. * @return
  581. * The returned value of the invoked hook.
  582. */
  583. function node_invoke(&$node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
  584. if (node_hook($node, $hook)) {
  585. $module = node_get_types('module', $node);
  586. if ($module == 'node') {
  587. $module = 'node_content'; // Avoid function name collisions.
  588. }
  589. $function = $module .'_'. $hook;
  590. return ($function($node, $a2, $a3, $a4));
  591. }
  592. }
  593. /**
  594. * Invoke a hook_nodeapi() operation in all modules.
  595. *
  596. * @param &$node
  597. * A node object.
  598. * @param $op
  599. * A string containing the name of the nodeapi operation.
  600. * @param $a3, $a4
  601. * Arguments to pass on to the hook, after the $node and $op arguments.
  602. * @return
  603. * The returned value of the invoked hooks.
  604. */
  605. function node_invoke_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  606. $return = array();
  607. foreach (module_implements('nodeapi') as $name) {
  608. $function = $name .'_nodeapi';
  609. $result = $function($node, $op, $a3, $a4);
  610. if (isset($result) && is_array($result)) {
  611. $return = array_merge($return, $result);
  612. }
  613. else if (isset($result)) {
  614. $return[] = $result;
  615. }
  616. }
  617. return $return;
  618. }
  619. /**
  620. * Load a node object from the database.
  621. *
  622. * @param $param
  623. * Either the nid of the node or an array of conditions to match against in the database query
  624. * @param $revision
  625. * Which numbered revision to load. Defaults to the current version.
  626. * @param $reset
  627. * Whether to reset the internal node_load cache.
  628. *
  629. * @return
  630. * A fully-populated node object.
  631. */
  632. function node_load($param = array(), $revision = NULL, $reset = NULL) {
  633. static $nodes = array();
  634. if ($reset) {
  635. $nodes = array();
  636. }
  637. $cachable = ($revision == NULL);
  638. $arguments = array();
  639. if (is_numeric($param)) {
  640. if ($cachable) {
  641. // Is the node statically cached?
  642. if (isset($nodes[$param])) {
  643. return is_object($nodes[$param]) ? drupal_clone($nodes[$param]) : $nodes[$param];
  644. }
  645. }
  646. $cond = 'n.nid = %d';
  647. $arguments[] = $param;
  648. }
  649. elseif (is_array($param)) {
  650. // Turn the conditions into a query.
  651. foreach ($param as $key => $value) {
  652. $cond[] = 'n.'. db_escape_table($key) ." = '%s'";
  653. $arguments[] = $value;
  654. }
  655. $cond = implode(' AND ', $cond);
  656. }
  657. else {
  658. return FALSE;
  659. }
  660. // Retrieve a field list based on the site's schema.
  661. $fields = drupal_schema_fields_sql('node', 'n');
  662. $fields = array_merge($fields, drupal_schema_fields_sql('node_revisions', 'r'));
  663. $fields = array_merge($fields, array('u.name', 'u.picture', 'u.data'));
  664. // Remove fields not needed in the query: n.vid and r.nid are redundant,
  665. // n.title is unnecessary because the node title comes from the
  666. // node_revisions table. We'll keep r.vid, r.title, and n.nid.
  667. $fields = array_diff($fields, array('n.vid', 'n.title', 'r.nid'));
  668. $fields = implode(', ', $fields);
  669. // Rename timestamp field for clarity.
  670. $fields = str_replace('r.timestamp', 'r.timestamp AS revision_timestamp', $fields);
  671. // Change name of revision uid so it doesn't conflict with n.uid.
  672. $fields = str_replace('r.uid', 'r.uid AS revision_uid', $fields);
  673. // Retrieve the node.
  674. // No db_rewrite_sql is applied so as to get complete indexing for search.
  675. if ($revision) {
  676. array_unshift($arguments, $revision);
  677. $node = db_fetch_object(db_query('SELECT '. $fields .' FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.nid = n.nid AND r.vid = %d WHERE '. $cond, $arguments));
  678. }
  679. else {
  680. $node = db_fetch_object(db_query('SELECT '. $fields .' FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.vid = n.vid WHERE '. $cond, $arguments));
  681. }
  682. if ($node && $node->nid) {
  683. // Call the node specific callback (if any) and piggy-back the
  684. // results to the node or overwrite some values.
  685. if ($extra = node_invoke($node, 'load')) {
  686. foreach ($extra as $key => $value) {
  687. $node->$key = $value;
  688. }
  689. }
  690. if ($extra = node_invoke_nodeapi($node, 'load')) {
  691. foreach ($extra as $key => $value) {
  692. $node->$key = $value;
  693. }
  694. }
  695. if ($cachable) {
  696. $nodes[$node->nid] = is_object($node) ? drupal_clone($node) : $node;
  697. }
  698. }
  699. return $node;
  700. }
  701. /**
  702. * Perform validation checks on the given node.
  703. */
  704. function node_validate($node, $form = array()) {
  705. // Convert the node to an object, if necessary.
  706. $node = (object)$node;
  707. $type = node_get_types('type', $node);
  708. // Make sure the body has the minimum number of words.
  709. // TODO : use a better word counting algorithm that will work in other languages
  710. if (!empty($type->min_word_count) && isset($node->body) && count(explode(' ', $node->body)) < $type->min_word_count) {
  711. form_set_error('body', t('The body of your @type is too short. You need at least %words words.', array('%words' => $type->min_word_count, '@type' => $type->name)));
  712. }
  713. if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  714. form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
  715. }
  716. if (user_access('administer nodes')) {
  717. // Validate the "authored by" field.
  718. if (!empty($node->name) && !($account = user_load(array('name' => $node->name)))) {
  719. // The use of empty() is mandatory in the context of usernames
  720. // as the empty string denotes the anonymous user. In case we
  721. // are dealing with an anonymous user we set the user ID to 0.
  722. form_set_error('name', t('The username %name does not exist.', array('%name' => $node->name)));
  723. }
  724. // Validate the "authored on" field. As of PHP 5.1.0, strtotime returns FALSE instead of -1 upon failure.
  725. if (!empty($node->date) && strtotime($node->date) <= 0) {
  726. form_set_error('date', t('You have to specify a valid date.'));
  727. }
  728. }
  729. // Do node-type-specific validation checks.
  730. node_invoke($node, 'validate', $form);
  731. node_invoke_nodeapi($node, 'validate', $form);
  732. }
  733. /**
  734. * Prepares a node for saving by populating teaser, author, and creation date.
  735. *
  736. * @param object|array $node
  737. * A node object or array.
  738. *
  739. * @return
  740. * A validated node object with a populated teaser, author, and creation date.
  741. */
  742. function node_submit($node) {
  743. global $user;
  744. // Convert the node to an object, if necessary.
  745. $node = (object)$node;
  746. // Generate the teaser, but only if it hasn't been set (e.g. by a
  747. // module-provided 'teaser' form item).
  748. if (!isset($node->teaser)) {
  749. if (isset($node->body)) {
  750. $node->teaser = node_teaser($node->body, isset($node->format) ? $node->format : NULL);
  751. // Chop off the teaser from the body if needed. The teaser_include
  752. // property might not be set (eg. in Blog API postings), so only act on
  753. // it, if it was set with a given value.
  754. if (isset($node->teaser_include) && !$node->teaser_include && $node->teaser == substr($node->body, 0, strlen($node->teaser))) {
  755. $node->body = substr($node->body, strlen($node->teaser));
  756. }
  757. }
  758. else {
  759. $node->teaser = '';
  760. $node->format = 0;
  761. }
  762. }
  763. if (user_access('administer nodes')) {
  764. // Populate the "authored by" field.
  765. if ($account = user_load(array('name' => $node->name))) {
  766. $node->uid = $account->uid;
  767. }
  768. else {
  769. $node->uid = 0;
  770. }
  771. }
  772. $node->created = !empty($node->date) ? strtotime($node->date) : time();
  773. $node->validated = TRUE;
  774. return $node;
  775. }
  776. /**
  777. * Save a node object into the database.
  778. */
  779. function node_save(&$node) {
  780. // Let modules modify the node before it is saved to the database.
  781. node_invoke_nodeapi($node, 'presave');
  782. global $user;
  783. // Insert a new node.
  784. $node->is_new = empty($node->nid);
  785. if ($node->is_new || !empty($node->revision)) {
  786. // When inserting a node, $node->log must be set because
  787. // {node_revisions}.log does not (and cannot) have a default
  788. // value. If the user does not have permission to create
  789. // revisions, however, the form will not contain an element for
  790. // log so $node->log will be unset at this point.
  791. if (!isset($node->log)) {
  792. $node->log = '';
  793. }
  794. }
  795. elseif (empty($node->log)) {
  796. // When updating a node, however, avoid clobbering an existing
  797. // log entry with an empty one.
  798. unset($node->log);
  799. }
  800. // For the same reasons, make sure we have $node->teaser and
  801. // $node->body set.
  802. if (!isset($node->teaser)) {
  803. $node->teaser = '';
  804. }
  805. if (!isset($node->body)) {
  806. $node->body = '';
  807. }
  808. // Save the old revision if needed.
  809. if (!$node->is_new && !empty($node->revision) && $node->vid) {
  810. $node->old_vid = $node->vid;
  811. }
  812. $time = time();
  813. if (empty($node->created)) {
  814. $node->created = $time;
  815. }
  816. // The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
  817. $node->changed = $time;
  818. $node->timestamp = $time;
  819. $node->format = isset($node->format) ? $node->format : FILTER_FORMAT_DEFAULT;
  820. // Generate the node table query and the node_revisions table query.
  821. if ($node->is_new) {
  822. _node_save_revision($node, $user->uid);
  823. drupal_write_record('node', $node);
  824. db_query('UPDATE {node_revisions} SET nid = %d WHERE vid = %d', $node->nid, $node->vid);
  825. $op = 'insert';
  826. }
  827. else {
  828. drupal_write_record('node', $node, 'nid');
  829. if (!empty($node->revision)) {
  830. _node_save_revision($node, $user->uid);
  831. db_query('UPDATE {node} SET vid = %d WHERE nid = %d', $node->vid, $node->nid);
  832. }
  833. else {
  834. _node_save_revision($node, $user->uid, 'vid');
  835. }
  836. $op = 'update';
  837. }
  838. // Call the node specific callback (if any).
  839. node_invoke($node, $op);
  840. node_invoke_nodeapi($node, $op);
  841. // Update the node access table for this node.
  842. node_access_acquire_grants($node);
  843. // Clear the page and block caches.
  844. cache_clear_all();
  845. }
  846. /**
  847. * Helper function to save a revision with the uid of the current user.
  848. *
  849. * Node is taken by reference, becuse drupal_write_record() updates the
  850. * $node with the revision id, and we need to pass that back to the caller.
  851. */
  852. function _node_save_revision(&$node, $uid, $update = NULL) {
  853. $temp_uid = $node->uid;
  854. $node->uid = $uid;
  855. if (isset($update)) {
  856. drupal_write_record('node_revisions', $node, $update);
  857. }
  858. else {
  859. drupal_write_record('node_revisions', $node);
  860. }
  861. $node->uid = $temp_uid;
  862. }
  863. /**
  864. * Delete a node.
  865. */
  866. function node_delete($nid) {
  867. // Clear the cache before the load, so if multiple nodes are deleted, the
  868. // memory will not fill up with nodes (possibly) already removed.
  869. $node = node_load($nid, NULL, TRUE);
  870. if (node_access('delete', $node)) {
  871. db_query('DELETE FROM {node} WHERE nid = %d', $node->nid);
  872. db_query('DELETE FROM {node_revisions} WHERE nid = %d', $node->nid);
  873. db_query('DELETE FROM {node_access} WHERE nid = %d', $node->nid);
  874. // Call the node-specific callback (if any):
  875. node_invoke($node, 'delete');
  876. node_invoke_nodeapi($node, 'delete');
  877. // Clear the page and block caches.
  878. cache_clear_all();
  879. // Remove this node from the search index if needed.
  880. if (function_exists('search_wipe')) {
  881. search_wipe($node->nid, 'node');
  882. }
  883. watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
  884. drupal_set_message(t('@type %title has been deleted.', array('@type' => node_get_types('name', $node), '%title' => $node->title)));
  885. }
  886. }
  887. /**
  888. * Generate a display of the given node.
  889. *
  890. * @param $node
  891. * A node array or node object.
  892. * @param $teaser
  893. * Whether to display the teaser only or the full form.
  894. * @param $page
  895. * Whether the node is being displayed by itself as a page.
  896. * @param $links
  897. * Whether or not to display node links. Links are omitted for node previews.
  898. *
  899. * @return
  900. * An HTML representation of the themed node.
  901. */
  902. function node_view($node, $teaser = FALSE, $page = FALSE, $links = TRUE) {
  903. $node = (object)$node;
  904. $node = node_build_content($node, $teaser, $page);
  905. if ($links) {
  906. $node->links = module_invoke_all('link', 'node', $node, $teaser);
  907. drupal_alter('link', $node->links, $node);
  908. }
  909. // Set the proper node part, then unset unused $node part so that a bad
  910. // theme can not open a security hole.
  911. $content = drupal_render($node->content);
  912. if ($teaser) {
  913. $node->teaser = $content;
  914. unset($node->body);
  915. }
  916. else {
  917. $node->body = $content;
  918. unset($node->teaser);
  919. }
  920. // Allow modules to modify the fully-built node.
  921. node_invoke_nodeapi($node, 'alter', $teaser, $page);
  922. return theme('node', $node, $teaser, $page);
  923. }
  924. /**
  925. * Apply filters and build the node's standard elements.
  926. */
  927. function node_prepare($node, $teaser = FALSE) {
  928. // First we'll overwrite the existing node teaser and body with
  929. // the filtered copies! Then, we'll stick those into the content
  930. // array and set the read more flag if appropriate.
  931. $node->readmore = $node->teaser != $node->body;
  932. if ($teaser == FALSE) {
  933. $node->body = check_markup($node->body, $node->format, FALSE);
  934. }
  935. else {
  936. $node->teaser = check_markup($node->teaser, $node->format, FALSE);
  937. }
  938. $node->content['body'] = array(
  939. '#value' => $teaser ? $node->teaser : $node->body,
  940. '#weight' => 0,
  941. );
  942. return $node;
  943. }
  944. /**
  945. * Builds a structured array representing the node's content.
  946. *
  947. * @param $node
  948. * A node object.
  949. * @param $teaser
  950. * Whether to display the teaser only, as on the main page.
  951. * @param $page
  952. * Whether the node is being displayed by itself as a page.
  953. *
  954. * @return
  955. * A node object with its content property set to a structured array
  956. * containing the individual elements of the node's body.
  957. */
  958. function node_build_content($node, $teaser = FALSE, $page = FALSE) {
  959. // The build mode identifies the target for which the node is built.
  960. if (!isset($node->build_mode)) {
  961. $node->build_mode = NODE_BUILD_NORMAL;
  962. }
  963. // Remove the delimiter (if any) that separates the teaser from the body.
  964. $node->body = isset($node->body) ? str_replace('<!--break-->', '', $node->body) : '';
  965. // The 'view' hook can be implemented to overwrite the default function
  966. // to display nodes.
  967. if (node_hook($node, 'view')) {
  968. $node = node_invoke($node, 'view', $teaser, $page);
  969. }
  970. else {
  971. $node = node_prepare($node, $teaser);
  972. }
  973. // Allow modules to make their own additions to the node.
  974. node_invoke_nodeapi($node, 'view', $teaser, $page);
  975. return $node;
  976. }
  977. /**
  978. * Generate a page displaying a single node, along with its comments.
  979. */
  980. function node_show($node, $cid, $message = FALSE) {
  981. if ($message) {
  982. drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))));
  983. }
  984. $output = node_view($node, FALSE, TRUE);
  985. if (function_exists('comment_render') && $node->comment) {
  986. $output .= comment_render($node, $cid);
  987. }
  988. // Update the history table, stating that this user viewed this node.
  989. node_tag_new($node->nid);
  990. return $output;
  991. }
  992. /**
  993. * Theme a log message.
  994. *
  995. * @ingroup themeable
  996. */
  997. function theme_node_log_message($log) {
  998. return '<div class="log"><div class="title">'. t('Log') .':</div>'. $log .'</div>';
  999. }
  1000. /**
  1001. * Implementation of hook_perm().
  1002. */
  1003. function node_perm() {
  1004. $perms = array('administer content types', 'administer nodes', 'access content', 'view revisions', 'revert revisions', 'delete revisions');
  1005. foreach (node_get_types() as $type) {
  1006. if ($type->module == 'node') {
  1007. $name = check_plain($type->type);
  1008. $perms[] = 'create '. $name .' content';
  1009. $perms[] = 'delete own '. $name .' content';
  1010. $perms[] = 'delete any '. $name .' content';
  1011. $perms[] = 'edit own '. $name .' content';
  1012. $perms[] = 'edit any '. $name .' content';
  1013. }
  1014. }
  1015. return $perms;
  1016. }
  1017. /**
  1018. * Implementation of hook_search().
  1019. */
  1020. function node_search($op = 'search', $keys = NULL) {
  1021. switch ($op) {
  1022. case 'name':
  1023. return t('Content');
  1024. case 'reset':
  1025. db_query("UPDATE {search_dataset} SET reindex = %d WHERE type = 'node'", time());
  1026. return;
  1027. case 'status':
  1028. $total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1'));
  1029. $remaining = db_result(db_query("SELECT COUNT(*) FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE n.status = 1 AND (d.sid IS NULL OR d.reindex <> 0)"));
  1030. return array('remaining' => $remaining, 'total' => $total);
  1031. case 'admin':
  1032. $form = array();
  1033. // Output form for defining rank factor weights.
  1034. $form['content_ranking'] = array(
  1035. '#type' => 'fieldset',
  1036. '#title' => t('Content ranking'),
  1037. );
  1038. $form['content_ranking']['#theme'] = 'node_search_admin';
  1039. $form['content_ranking']['info'] = array(
  1040. '#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>'
  1041. );
  1042. $ranking = array('node_rank_relevance' => t('Keyword relevance'),
  1043. 'node_rank_recent' => t('Recently posted'));
  1044. if (module_exists('comment')) {
  1045. $ranking['node_rank_comments'] = t('Number of comments');
  1046. }
  1047. if (module_exists('statistics') && variable_get('statistics_count_content_views', 0)) {
  1048. $ranking['node_rank_views'] = t('Number of views');
  1049. }
  1050. // Note: reversed to reflect that higher number = higher ranking.
  1051. $options = drupal_map_assoc(range(0, 10));
  1052. foreach ($ranking as $var => $title) {
  1053. $form['content_ranking']['factors'][$var] = array(
  1054. '#title' => $title,
  1055. '#type' => 'select',
  1056. '#options' => $options,
  1057. '#default_value' => variable_get($var, 5),
  1058. );
  1059. }
  1060. return $form;
  1061. case 'search':
  1062. // Build matching conditions
  1063. list($join1, $where1) = _db_rewrite_sql();
  1064. $arguments1 = array();
  1065. $conditions1 = 'n.status = 1';
  1066. if ($type = search_query_extract($keys, 'type')) {
  1067. $types = array();
  1068. foreach (explode(',', $type) as $t) {
  1069. $types[] = "n.type = '%s'";
  1070. $arguments1[] = $t;
  1071. }
  1072. $conditions1 .= ' AND ('. implode(' OR ', $types) .')';
  1073. $keys = search_query_insert($keys, 'type');
  1074. }
  1075. if ($category = search_query_extract($keys, 'category')) {
  1076. $categories = array();
  1077. foreach (explode(',', $category) as $c) {
  1078. $categories[] = "tn.tid = %d";
  1079. $arguments1[] = $c;
  1080. }
  1081. $conditions1 .= ' AND ('. implode(' OR ', $categories) .')';
  1082. $join1 .= ' INNER JOIN {term_node} tn ON n.vid = tn.vid';
  1083. $keys = search_query_insert($keys, 'category');
  1084. }
  1085. // Build ranking expression (we try to map each parameter to a
  1086. // uniform distribution in the range 0..1).
  1087. $ranking = array();
  1088. $arguments2 = array();
  1089. $join2 = '';
  1090. // Used to avoid joining on node_comment_statistics twice
  1091. $stats_join = FALSE;
  1092. $total = 0;
  1093. if ($weight = (int)variable_get('node_rank_relevance', 5)) {
  1094. // Average relevance values hover around 0.15
  1095. $ranking[] = '%d * i.relevance';
  1096. $arguments2[] = $weight;
  1097. $total += $weight;
  1098. }
  1099. if ($weight = (int)variable_get('node_rank_recent', 5)) {
  1100. // Exponential decay with half-life of 6 months, starting at last indexed node
  1101. // c.last_comment_timestamp may be NULL. Since both MAX(anynumber, NULL) and
  1102. // GREATEST(anynumber, NULL) return NULL, we use COALESCE(MAX(c.last_comment_timestamp), 0)
  1103. // to prevent it from being NULL.
  1104. $ranking[] = '%d * POW(2, (GREATEST(MAX(n.created), MAX(n.changed), COALESCE(MAX(c.last_comment_timestamp), 0)) - %d) * 6.43e-8)';
  1105. $arguments2[] = $weight;
  1106. $arguments2[] = (int)variable_get('node_cron_last', 0);
  1107. $join2 .= ' LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
  1108. $stats_join = TRUE;
  1109. $total += $weight;
  1110. }
  1111. if (module_exists('comment') && $weight = (int)variable_get('node_rank_comments', 5)) {
  1112. // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
  1113. $scale = variable_get('node_cron_comments_scale', 0.0);
  1114. $ranking[] = '%d * (2.0 - 2.0 / (1.0 + MAX(c.comment_count) * %f))';
  1115. $arguments2[] = $weight;
  1116. $arguments2[] = $scale;
  1117. if (!$stats_join) {
  1118. $join2 .= ' LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
  1119. }
  1120. $total += $weight;
  1121. }
  1122. if (module_exists('statistics') && variable_get('statistics_count_content_views', 0) &&
  1123. $weight = (int)variable_get('node_rank_views', 5)) {
  1124. // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
  1125. $scale = variable_get('node_cron_views_scale', 0.0);
  1126. $ranking[] = '%d * (2.0 - 2.0 / (1.0 + MAX(nc.totalcount) * %f))';
  1127. $arguments2[] = $weight;
  1128. $arguments2[] = $scale;
  1129. $join2 .= ' LEFT JOIN {node_counter} nc ON nc.nid = i.sid';
  1130. $total += $weight;
  1131. }
  1132. // When all search factors are disabled (ie they have a weight of zero),
  1133. // the default score is based only on keyword relevance and there is no need to
  1134. // adjust the score of each item.
  1135. if ($total == 0) {
  1136. $select2 = 'i.relevance AS score';
  1137. $total = 1;
  1138. }
  1139. else {
  1140. $select2 = implode(' + ', $ranking) . ' AS score';
  1141. }
  1142. // Do search.
  1143. $find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid '. $join1, $conditions1 . (empty($where1) ? '' : ' AND '. $where1), $arguments1, $select2, $join2, $arguments2);
  1144. // Load results.
  1145. $results = array();
  1146. foreach ($find as $item) {
  1147. // Build the node body.
  1148. $node = node_load($item->sid);
  1149. $node->build_mode = NODE_BUILD_SEARCH_RESULT;
  1150. $node = node_build_content($node, FALSE, FALSE);
  1151. $node->body = drupal_render($node->content);
  1152. // Fetch comments for snippet.
  1153. if (module_exists('comment')) {
  1154. $node->body .= comment_nodeapi($node, 'update index');
  1155. }
  1156. // Fetch terms for snippet.
  1157. if (module_exists('taxonomy')) {
  1158. $node->body .= taxonomy_nodeapi($node, 'update index');
  1159. }
  1160. $extra = node_invoke_nodeapi($node, 'search result');
  1161. $results[] = array(
  1162. 'link' => url('node/'. $item->sid, array('absolute' => TRUE)),
  1163. 'type' => check_plain(node_get_types('name', $node)),
  1164. 'title' => $node->title,
  1165. 'user' => theme('username', $node),
  1166. 'date' => $node->changed,
  1167. 'node' => $node,
  1168. 'extra' => $extra,
  1169. 'score' => $item->score / $total,
  1170. 'snippet' => search_excerpt($keys, $node->body),
  1171. );
  1172. }
  1173. return $results;
  1174. }
  1175. }
  1176. /**
  1177. * Implementation of hook_user().
  1178. */
  1179. function node_user($op, &$edit, &$user) {
  1180. if ($op == 'delete') {
  1181. db_query('UPDATE {node} SET uid = 0 WHERE uid = %d', $user->uid);
  1182. db_query('UPDATE {node_revisions} SET uid = 0 WHERE uid = %d', $user->uid);
  1183. }
  1184. }
  1185. /**
  1186. * Theme the content ranking part of the search settings admin page.
  1187. *
  1188. * @ingroup themeable
  1189. */
  1190. function theme_node_search_admin($form) {
  1191. $output = drupal_render($form['info']);
  1192. $header = array(t('Factor'), t('Weight'));
  1193. foreach (element_children($form['factors']) as $key) {
  1194. $row = array();
  1195. $row[] = $form['factors'][$key]['#title'];
  1196. unset($form['factors'][$key]['#title']);
  1197. $row[] = drupal_render($form['factors'][$key]);
  1198. $rows[] = $row;
  1199. }
  1200. $output .= theme('table', $header, $rows);
  1201. $output .= drupal_render($form);
  1202. return $output;
  1203. }
  1204. /**
  1205. * Retrieve the comment mode for the given node ID (none, read, or read/write).
  1206. */
  1207. function node_comment_mode($nid) {
  1208. static $comment_mode;
  1209. if (!isset($comment_mode[$nid])) {
  1210. $comment_mode[$nid] = db_result(db_query('SELECT comment FROM {node} WHERE nid = %d', $nid));
  1211. }
  1212. return $comment_mode[$nid];
  1213. }
  1214. /**
  1215. * Implementation of hook_link().
  1216. */
  1217. function node_link($type, $node = NULL, $teaser = FALSE) {
  1218. $links = array();
  1219. if ($type == 'node') {
  1220. if ($teaser == 1 && $node->teaser && !empty($node->readmore)) {
  1221. $links['node_read_more'] = array(
  1222. 'title' => t('Read more'),
  1223. 'href' => "node/$node->nid",
  1224. // The title attribute gets escaped when the links are processed, so
  1225. // there is no need to escape here.
  1226. 'attributes' => array('title' => t('Read the rest of !title.', array('!title' => $node->title)))
  1227. );
  1228. }
  1229. }
  1230. return $links;
  1231. }
  1232. function _node_revision_access($node, $op = 'view') {
  1233. static $access = array();
  1234. if (!isset($access[$node->vid])) {
  1235. $node_current_revision = node_load($node->nid);
  1236. $is_current_revision = $node_current_revision->vid == $node->vid;
  1237. // There should be at least two revisions. If the vid of the given node
  1238. // and the vid of the current revision differs, then we already have two
  1239. // different revisions so there is no need for a separate database check.
  1240. // Also, if you try to revert to or delete the current revision, that's
  1241. // not good.
  1242. if ($is_current_revision && (db_result(db_query('SELECT COUNT(vid) FROM {node_revisions} WHERE nid = %d', $node->nid)) == 1 || $op == 'update' || $op == 'delete')) {
  1243. $access[$node->vid] = FALSE;
  1244. }
  1245. elseif (user_access('administer nodes')) {
  1246. $access[$node->vid] = TRUE;
  1247. }
  1248. else {
  1249. $map = array('view' => 'view revisions', 'update' => 'revert revisions', 'delete' => 'delete revisions');
  1250. // First check the user permission, second check the access to the
  1251. // current revision and finally, if the node passed in is not the current
  1252. // revision then access to that, too.
  1253. $access[$node->vid] = isset($map[$op]) && user_access($map[$op]) && node_access($op, $node_current_revision) && ($is_current_revision || node_access($op, $node));
  1254. }
  1255. }
  1256. return $access[$node->vid];
  1257. }
  1258. function _node_add_access() {
  1259. $types = node_get_types();
  1260. foreach ($types as $type) {
  1261. if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
  1262. return TRUE;
  1263. }
  1264. }
  1265. return FALSE;
  1266. }
  1267. /**
  1268. * Implementation of hook_menu().
  1269. */
  1270. function node_menu() {
  1271. $items['admin/content/node'] = array(
  1272. 'title' => 'Content',
  1273. 'description' => "View, edit, and delete your site's content.",
  1274. 'page callback' => 'drupal_get_form',
  1275. 'page arguments' => array('node_admin_content'),
  1276. 'access arguments' => array('administer nodes'),
  1277. 'file' => 'node.admin.inc',
  1278. );
  1279. $items['admin/content/node/overview'] = array(
  1280. 'title' => 'List',
  1281. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1282. 'weight' => -10,
  1283. );
  1284. $items['admin/content/node-settings'] = array(
  1285. 'title' => 'Post settings',
  1286. 'description' => 'Control posting behavior, such as teaser length, requiring previews before posting, and the number of posts on the front page.',
  1287. 'page callback' => 'drupal_get_form',
  1288. 'page arguments' => array('node_configure'),
  1289. 'access arguments' => array('administer nodes'),
  1290. 'file' => 'node.admin.inc',
  1291. );
  1292. $items['admin/content/node-settings/rebuild'] = array(
  1293. 'title' => 'Rebuild permissions',
  1294. 'page arguments' => array('node_configure_rebuild_confirm'),
  1295. 'file' => 'node.admin.inc',
  1296. // Any user than can potentially trigger a node_acess_needs_rebuild(TRUE)
  1297. // has to be allowed access to the 'node access rebuild' confirm form.
  1298. 'access arguments' => array('access administration pages'),
  1299. 'type' => MENU_CALLBACK,
  1300. );
  1301. $items['admin/content/types'] = array(
  1302. 'title' => 'Content types',
  1303. 'description' => 'Manage posts by content type, including default status, front page promotion, etc.',
  1304. 'page callback' => 'node_overview_types',
  1305. 'access arguments' => array('administer content types'),
  1306. 'file' => 'content_types.inc',
  1307. );
  1308. $items['admin/content/types/list'] = array(
  1309. 'title' => 'List',
  1310. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1311. 'weight' => -10,
  1312. );
  1313. $items['admin/content/types/add'] = array(
  1314. 'title' => 'Add content type',
  1315. 'page callback' => 'drupal_get_form',
  1316. 'page arguments' => array('node_type_form'),
  1317. 'access arguments' => array('administer content types'),
  1318. 'file' => 'content_types.inc',
  1319. 'type' => MENU_LOCAL_TASK,
  1320. );
  1321. $items['node'] = array(
  1322. 'title' => 'Content',
  1323. 'page callback' => 'node_page_default',
  1324. 'access arguments' => array('access content'),
  1325. 'type' => MENU_CALLBACK,
  1326. );
  1327. $items['node/add'] = array(
  1328. 'title' => 'Create content',
  1329. 'page callback' => 'node_add_page',
  1330. 'access callback' => '_node_add_access',
  1331. 'weight' => 1,
  1332. 'file' => 'node.pages.inc',
  1333. );
  1334. $items['rss.xml'] = array(
  1335. 'title' => 'RSS feed',
  1336. 'page callback' => 'node_feed',
  1337. 'access arguments' => array('access content'),
  1338. 'type' => MENU_CALLBACK,
  1339. );
  1340. foreach (node_get_types('types', NULL, TRUE) as $type) {
  1341. $type_url_str = str_replace('_', '-', $type->type);
  1342. $items['node/add/'. $type_url_str] = array(
  1343. 'title' => drupal_ucfirst($type->name),
  1344. 'title callback' => 'check_plain',
  1345. 'page callback' => 'node_add',
  1346. 'page arguments' => array(2),
  1347. 'access callback' => 'node_access',
  1348. 'access arguments' => array('create', $type->type),
  1349. 'description' => $type->description,
  1350. 'file' => 'node.pages.inc',
  1351. );
  1352. $items['admin/content/node-type/'. $type_url_str] = array(
  1353. 'title' => $type->name,
  1354. 'page callback' => 'drupal_get_form',
  1355. 'page arguments' => array('node_type_form', $type),
  1356. 'access arguments' => array('administer content types'),
  1357. 'file' => 'content_types.inc',
  1358. 'type' => MENU_CALLBACK,
  1359. );
  1360. $items['admin/content/node-type/'. $type_url_str .'/edit'] = array(
  1361. 'title' => 'Edit',
  1362. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1363. );
  1364. $items['admin/content/node-type/'. $type_url_str .'/delete'] = array(
  1365. 'title' => 'Delete',
  1366. 'page arguments' => array('node_type_delete_confirm', $type),
  1367. 'access arguments' => array('administer content types'),
  1368. 'file' => 'content_types.inc',
  1369. 'type' => MENU_CALLBACK,
  1370. );
  1371. }
  1372. $items['node/%node'] = array(
  1373. 'title callback' => 'node_page_title',
  1374. 'title arguments' => array(1),
  1375. 'page callback' => 'node_page_view',
  1376. 'page arguments' => array(1),
  1377. 'access callback' => 'node_access',
  1378. 'access arguments' => array('view', 1),
  1379. 'type' => MENU_CALLBACK);
  1380. $items['node/%node/view'] = array(
  1381. 'title' => 'View',
  1382. 'type' => MENU_DEFAULT_LOCAL_TASK,
  1383. 'weight' => -10);
  1384. $items['node/%node/edit'] = array(
  1385. 'title' => 'Edit',
  1386. 'page callback' => 'node_page_edit',
  1387. 'page arguments' => array(1),
  1388. 'access callback' => 'node_access',
  1389. 'access arguments' => array('update', 1),
  1390. 'weight' => 1,
  1391. 'file' => 'node.pages.inc',
  1392. 'type' => MENU_LOCAL_TASK,
  1393. );
  1394. $items['node/%node/delete'] = array(
  1395. 'title' => 'Delete',
  1396. 'page callback' => 'drupal_get_form',
  1397. 'page arguments' => array('node_delete_confirm', 1),
  1398. 'access callback' => 'node_access',
  1399. 'access arguments' => array('delete', 1),
  1400. 'file' => 'node.pages.inc',
  1401. 'weight' => 1,
  1402. 'type' => MENU_CALLBACK);
  1403. $items['node/%node/revisions'] = array(
  1404. 'title' => 'Revisions',
  1405. 'page callback' => 'node_revision_overview',
  1406. 'page arguments' => array(1),
  1407. 'access callback' => '_node_revision_access',
  1408. 'access arguments' => array(1),
  1409. 'weight' => 2,
  1410. 'file' => 'node.pages.inc',
  1411. 'type' => MENU_LOCAL_TASK,
  1412. );
  1413. $items['node/%node/revisions/%/view'] = array(
  1414. 'title' => 'Revisions',
  1415. 'load arguments' => array(3),
  1416. 'page callback' => 'node_show',
  1417. 'page arguments' => array(1, NULL, TRUE),
  1418. 'access callback' => '_node_revision_access',
  1419. 'access arguments' => array(1),
  1420. 'type' => MENU_CALLBACK,
  1421. );
  1422. $items['node/%node/revisions/%/revert'] = array(
  1423. 'title' => 'Revert to earlier revision',
  1424. 'load arguments' => array(3),
  1425. 'page callback' => 'drupal_get_form',
  1426. 'page arguments' => array('node_revision_revert_confirm', 1),
  1427. 'access callback' => '_node_revision_access',
  1428. 'access arguments' => array(1, 'update'),
  1429. 'file' => 'node.pages.inc',
  1430. 'type' => MENU_CALLBACK,
  1431. );
  1432. $items['node/%node/revisions/%/delete'] = array(
  1433. 'title' => 'Delete earlier revision',
  1434. 'load arguments' => array(3),
  1435. 'page callback' => 'drupal_get_form',
  1436. 'page arguments' => array('node_revision_delete_confirm', 1),
  1437. 'access callback' => '_node_revision_access',
  1438. 'access arguments' => array(1, 'delete'),
  1439. 'file' => 'node.pages.inc',
  1440. 'type' => MENU_CALLBACK,
  1441. );
  1442. return $items;
  1443. }
  1444. /**
  1445. * Title callback.
  1446. */
  1447. function node_page_title($node) {
  1448. return $node->title;
  1449. }
  1450. /**
  1451. * Implementation of hook_init().
  1452. */
  1453. function node_init() {
  1454. drupal_add_css(drupal_get_path('module', 'node') .'/node.css');
  1455. }
  1456. function node_last_changed($nid) {
  1457. $node = db_fetch_object(db_query('SELECT changed FROM {node} WHERE nid = %d', $nid));
  1458. return ($node->changed);
  1459. }
  1460. /**
  1461. * Return a list of all the existing revision numbers.
  1462. */
  1463. function node_revision_list($node) {
  1464. $revisions = array();
  1465. $result = db_query('SELECT r.vid, r.title, r.log, r.uid, n.vid AS current_vid, r.timestamp, u.name FROM {node_revisions} r LEFT JOIN {node} n ON n.vid = r.vid INNER JOIN {users} u ON u.uid = r.uid WHERE r.nid = %d ORDER BY r.vid DESC', $node->nid);
  1466. while ($revision = db_fetch_object($result)) {
  1467. $revisions[$revision->vid] = $revision;
  1468. }
  1469. return $revisions;
  1470. }
  1471. /**
  1472. * Implementation of hook_block().
  1473. */
  1474. function node_block($op = 'list', $delta = 0) {
  1475. if ($op == 'list') {
  1476. $blocks[0]['info'] = t('Syndicate');
  1477. // Not worth caching.
  1478. $blocks[0]['cache'] = BLOCK_NO_CACHE;
  1479. return $blocks;
  1480. }
  1481. else if ($op == 'view') {
  1482. $block['subject'] = t('Syndicate');
  1483. $block['content'] = theme('feed_icon', url('rss.xml'), t('Syndicate'));
  1484. return $block;
  1485. }
  1486. }
  1487. /**
  1488. * A generic function for generating RSS feeds from a set of nodes.
  1489. *
  1490. * @param $nids
  1491. * An array of node IDs (nid). Defaults to FALSE so empty feeds can be
  1492. * generated with passing an empty array, if no items are to be added
  1493. * to the feed.
  1494. * @param $channel
  1495. * An associative array containing title, link, description and other keys.
  1496. * The link should be an absolute URL.
  1497. */
  1498. function node_feed($nids = FALSE, $channel = array()) {
  1499. global $base_url, $language;
  1500. if ($nids === FALSE) {
  1501. $nids = array();
  1502. $result = db_query_range(db_rewrite_sql('SELECT n.nid, n.created FROM {node} n WHERE n.promote = 1 AND n.status = 1 ORDER BY n.created DESC'), 0, variable_get('feed_default_items', 10));
  1503. while ($row = db_fetch_object($result)) {
  1504. $nids[] = $row->nid;
  1505. }
  1506. }
  1507. $item_length = variable_get('feed_item_length', 'teaser');
  1508. $namespaces = array('xmlns:dc' => 'http://purl.org/dc/elements/1.1/');
  1509. $items = '';
  1510. foreach ($nids as $nid) {
  1511. // Load the specified node:
  1512. $item = node_load($nid);
  1513. $item->build_mode = NODE_BUILD_RSS;
  1514. $item->link = url("node/$nid", array('absolute' => TRUE));
  1515. if ($item_length != 'title') {
  1516. $teaser = ($item_length == 'teaser') ? TRUE : FALSE;
  1517. // Filter and prepare node teaser
  1518. if (node_hook($item, 'view')) {
  1519. $item = node_invoke($item, 'view', $teaser, FALSE);
  1520. }
  1521. else {
  1522. $item = node_prepare($item, $teaser);
  1523. }
  1524. // Allow modules to change $node->content before the node is rendered.
  1525. node_invoke_nodeapi($item, 'view', $teaser, FALSE);
  1526. // Set the proper node property, then unset unused $node property so that a
  1527. // bad theme can not open a security hole.
  1528. $content = drupal_render($item->content);
  1529. if ($teaser) {
  1530. $item->teaser = $content;
  1531. unset($item->body);
  1532. }
  1533. else {
  1534. $item->body = $content;
  1535. unset($item->teaser);
  1536. }
  1537. // Allow modules to modify the fully-built node.
  1538. node_invoke_nodeapi($item, 'alter', $teaser, FALSE);
  1539. }
  1540. // Allow modules to add additional item fields and/or modify $item
  1541. $extra = node_invoke_nodeapi($item, 'rss item');
  1542. $extra = array_merge($extra, array(array('key' => 'pubDate', 'value' => gmdate('r', $item->created)), array('key' => 'dc:creator', 'value' => $item->name), array('key' => 'guid', 'value' => $item->nid .' at '. $base_url, 'attributes' => array('isPermaLink' => 'false'))));
  1543. foreach ($extra as $element) {
  1544. if (isset($element['namespace'])) {
  1545. $namespaces = array_merge($namespaces, $element['namespace']);
  1546. }
  1547. }
  1548. // Prepare the item description
  1549. switch ($item_length) {
  1550. case 'fulltext':
  1551. $item_text = $item->body;
  1552. break;
  1553. case 'teaser':
  1554. $item_text = $item->teaser;
  1555. if (!empty($item->readmore)) {
  1556. $item_text .= '<p>'. l(t('read more'), 'node/'. $item->nid, array('absolute' => TRUE, 'attributes' => array('target' => '_blank'))) .'</p>';
  1557. }
  1558. break;
  1559. case 'title':
  1560. $item_text = '';
  1561. break;
  1562. }
  1563. $items .= format_rss_item($item->title, $item->link, $item_text, $extra);
  1564. }
  1565. $channel_defaults = array(
  1566. 'version' => '2.0',
  1567. 'title' => variable_get('site_name', 'Drupal'),
  1568. 'link' => $base_url,
  1569. 'description' => variable_get('site_mission', ''),
  1570. 'language' => $language->language
  1571. );
  1572. $channel = array_merge($channel_defaults, $channel);
  1573. $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  1574. $output .= "<rss version=\"". $channel["version"] ."\" xml:base=\"". $base_url ."\" ". drupal_attributes($namespaces) .">\n";
  1575. $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language']);
  1576. $output .= "</rss>\n";
  1577. drupal_set_header('Content-Type: application/rss+xml; charset=utf-8');
  1578. print $output;
  1579. }
  1580. /**
  1581. * Menu callback; Generate a listing of promoted nodes.
  1582. */
  1583. function node_page_default() {
  1584. $result = pager_query(db_rewrite_sql('SELECT n.nid, n.sticky, n.created FROM {node} n WHERE n.promote = 1 AND n.status = 1 ORDER BY n.sticky DESC, n.created DESC'), variable_get('default_nodes_main', 10));
  1585. $output = '';
  1586. $num_rows = FALSE;
  1587. while ($node = db_fetch_object($result)) {
  1588. $output .= node_view(node_load($node->nid), 1);
  1589. $num_rows = TRUE;
  1590. }
  1591. if ($num_rows) {
  1592. $feed_url = url('rss.xml', array('absolute' => TRUE));
  1593. drupal_add_feed($feed_url, variable_get('site_name', 'Drupal') .' '. t('RSS'));
  1594. $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
  1595. }
  1596. else {
  1597. $default_message = t('<h1 class="title">Welcome to your new Drupal website!</h1><p>Please follow these steps to set up and start using your website:</p>');
  1598. $default_message .= '<ol>';
  1599. $default_message .= '<li>'. t('<strong>Configure your website</strong> Once logged in, visit the <a href="@admin">administration section</a>, where you can <a href="@config">customize and configure</a> all aspects of your website.', array('@admin' => url('admin'), '@config' => url('admin/settings'))) .'</li>';
  1600. $default_message .= '<li>'. t('<strong>Enable additional functionality</strong> Next, visit the <a href="@modules">module list</a> and enable features which suit your specific needs. You can find additional modules in the <a href="@download_modules">Drupal modules download section</a>.', array('@modules' => url('admin/build/modules'), '@download_modules' => 'http://drupal.org/project/modules')) .'</li>';
  1601. $default_message .= '<li>'. t('<strong>Customize your website design</strong> To change the "look and feel" of your website, visit the <a href="@themes">themes section</a>. You may choose from one of the included themes or download additional themes from the <a href="@download_themes">Drupal themes download section</a>.', array('@themes' => url('admin/build/themes'), '@download_themes' => 'http://drupal.org/project/themes')) .'</li>';
  1602. $default_message .= '<li>'. t('<strong>Start posting content</strong> Finally, you can <a href="@content">create content</a> for your website. This message will disappear once you have promoted a post to the front page.', array('@content' => url('node/add'))) .'</li>';
  1603. $default_message .= '</ol>';
  1604. $default_message .= '<p>'. t('For more information, please refer to the <a href="@help">help section</a>, or the <a href="@handbook">online Drupal handbooks</a>. You may also post at the <a href="@forum">Drupal forum</a>, or view the wide range of <a href="@support">other support options</a> available.', array('@help' => url('admin/help'), '@handbook' => 'http://drupal.org/handbooks', '@forum' => 'http://drupal.org/forum', '@support' => 'http://drupal.org/support')) .'</p>';
  1605. $output = '<div id="first-time">'. $default_message .'</div>';
  1606. }
  1607. drupal_set_title('');
  1608. return $output;
  1609. }
  1610. /**
  1611. * Menu callback; view a single node.
  1612. */
  1613. function node_page_view($node, $cid = NULL) {
  1614. drupal_set_title(check_plain($node->title));
  1615. return node_show($node, $cid);
  1616. }
  1617. /**
  1618. * Implementation of hook_update_index().
  1619. */
  1620. function node_update_index() {
  1621. $limit = (int)variable_get('search_cron_limit', 100);
  1622. // Store the maximum possible comments per thread (used for ranking by reply count)
  1623. variable_set('node_cron_comments_scale', 1.0 / max(1, db_result(db_query('SELECT MAX(comment_count) FROM {node_comment_statistics}'))));
  1624. variable_set('node_cron_views_scale', 1.0 / max(1, db_result(db_query('SELECT MAX(totalcount) FROM {node_counter}'))));
  1625. $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);
  1626. while ($node = db_fetch_object($result)) {
  1627. _node_index_node($node);
  1628. }
  1629. }
  1630. /**
  1631. * Index a single node.
  1632. *
  1633. * @param $node
  1634. * The node to index.
  1635. */
  1636. function _node_index_node($node) {
  1637. $node = node_load($node->nid);
  1638. // save the changed time of the most recent indexed node, for the search results half-life calculation
  1639. variable_set('node_cron_last', $node->changed);
  1640. // Build the node body.
  1641. $node->build_mode = NODE_BUILD_SEARCH_INDEX;
  1642. $node = node_build_content($node, FALSE, FALSE);
  1643. $node->body = drupal_render($node->content);
  1644. $text = '<h1>'. check_plain($node->title) .'</h1>'. $node->body;
  1645. // Fetch extra data normally not visible
  1646. $extra = node_invoke_nodeapi($node, 'update index');
  1647. foreach ($extra as $t) {
  1648. $text .= $t;
  1649. }
  1650. // Update index
  1651. search_index($node->nid, 'node', $text);
  1652. }
  1653. /**
  1654. * Implementation of hook_form_alter().
  1655. */
  1656. function node_form_alter(&$form, $form_state, $form_id) {
  1657. // Advanced node search form
  1658. if ($form_id == 'search_form' && $form['module']['#value'] == 'node' && user_access('use advanced search')) {
  1659. // Keyword boxes:
  1660. $form['advanced'] = array(
  1661. '#type' => 'fieldset',
  1662. '#title' => t('Advanced search'),
  1663. '#collapsible' => TRUE,
  1664. '#collapsed' => TRUE,
  1665. '#attributes' => array('class' => 'search-advanced'),
  1666. );
  1667. $form['advanced']['keywords'] = array(
  1668. '#prefix' => '<div class="criterion">',
  1669. '#suffix' => '</div>',
  1670. );
  1671. $form['advanced']['keywords']['or'] = array(
  1672. '#type' => 'textfield',
  1673. '#title' => t('Containing any of the words'),
  1674. '#size' => 30,
  1675. '#maxlength' => 255,
  1676. );
  1677. $form['advanced']['keywords']['phrase'] = array(
  1678. '#type' => 'textfield',
  1679. '#title' => t('Containing the phrase'),
  1680. '#size' => 30,
  1681. '#maxlength' => 255,
  1682. );
  1683. $form['advanced']['keywords']['negative'] = array(
  1684. '#type' => 'textfield',
  1685. '#title' => t('Containing none of the words'),
  1686. '#size' => 30,
  1687. '#maxlength' => 255,
  1688. );
  1689. // Taxonomy box:
  1690. if ($taxonomy = module_invoke('taxonomy', 'form_all', 1)) {
  1691. $form['advanced']['category'] = array(
  1692. '#type' => 'select',
  1693. '#title' => t('Only in the category(s)'),
  1694. '#prefix' => '<div class="criterion">',
  1695. '#size' => 10,
  1696. '#suffix' => '</div>',
  1697. '#options' => $taxonomy,
  1698. '#multiple' => TRUE,
  1699. );
  1700. }
  1701. // Node types:
  1702. $types = array_map('check_plain', node_get_types('names'));
  1703. $form['advanced']['type'] = array(
  1704. '#type' => 'checkboxes',
  1705. '#title' => t('Only of the type(s)'),
  1706. '#prefix' => '<div class="criterion">',
  1707. '#suffix' => '</div>',
  1708. '#options' => $types,
  1709. );
  1710. $form['advanced']['submit'] = array(
  1711. '#type' => 'submit',
  1712. '#value' => t('Advanced search'),
  1713. '#prefix' => '<div class="action">',
  1714. '#suffix' => '</div>',
  1715. );
  1716. $form['#validate'][] = 'node_search_validate';
  1717. }
  1718. }
  1719. /**
  1720. * Form API callback for the search form. Registered in node_form_alter().
  1721. */
  1722. function node_search_validate($form, &$form_state) {
  1723. // Initialise using any existing basic search keywords.
  1724. $keys = $form_state['values']['processed_keys'];
  1725. // Insert extra restrictions into the search keywords string.
  1726. if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) {
  1727. // Retrieve selected types - Forms API sets the value of unselected checkboxes to 0.
  1728. $form_state['values']['type'] = array_filter($form_state['values']['type']);
  1729. if (count($form_state['values']['type'])) {
  1730. $keys = search_query_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
  1731. }
  1732. }
  1733. if (isset($form_state['values']['category']) && is_array($form_state['values']['category'])) {
  1734. $keys = search_query_insert($keys, 'category', implode(',', $form_state['values']['category']));
  1735. }
  1736. if ($form_state['values']['or'] != '') {
  1737. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' '. $form_state['values']['or'], $matches)) {
  1738. $keys .= ' '. implode(' OR ', $matches[1]);
  1739. }
  1740. }
  1741. if ($form_state['values']['negative'] != '') {
  1742. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' '. $form_state['values']['negative'], $matches)) {
  1743. $keys .= ' -'. implode(' -', $matches[1]);
  1744. }
  1745. }
  1746. if ($form_state['values']['phrase'] != '') {
  1747. $keys .= ' "'. str_replace('"', ' ', $form_state['values']['phrase']) .'"';
  1748. }
  1749. if (!empty($keys)) {
  1750. form_set_value($form['basic']['inline']['processed_keys'], trim($keys), $form_state);
  1751. }
  1752. }
  1753. /**
  1754. * @defgroup node_access Node access rights
  1755. * @{
  1756. * The node access system determines who can do what to which nodes.
  1757. *
  1758. * In determining access rights for a node, node_access() first checks
  1759. * whether the user has the "administer nodes" permission. Such users have
  1760. * unrestricted access to all nodes. Then the node module's hook_access()
  1761. * is called, and a TRUE or FALSE return value will grant or deny access.
  1762. * This allows, for example, the blog module to always grant access to the
  1763. * blog author, and for the book module to always deny editing access to
  1764. * PHP pages.
  1765. *
  1766. * If node module does not intervene (returns NULL), then the
  1767. * node_access table is used to determine access. All node access
  1768. * modules are queried using hook_node_grants() to assemble a list of
  1769. * "grant IDs" for the user. This list is compared against the table.
  1770. * If any row contains the node ID in question (or 0, which stands for "all
  1771. * nodes"), one of the grant IDs returned, and a value of TRUE for the
  1772. * operation in question, then access is granted. Note that this table is a
  1773. * list of grants; any matching row is sufficient to grant access to the
  1774. * node.
  1775. *
  1776. * In node listings, the process above is followed except that
  1777. * hook_access() is not called on each node for performance reasons and for
  1778. * proper functioning of the pager system. When adding a node listing to your
  1779. * module, be sure to use db_rewrite_sql() to add
  1780. * the appropriate clauses to your query for access checks.
  1781. *
  1782. * To see how to write a node access module of your own, see
  1783. * node_access_example.module.
  1784. */
  1785. /**
  1786. * Determine whether the current user may perform the given operation on the
  1787. * specified node.
  1788. *
  1789. * @param $op
  1790. * The operation to be performed on the node. Possible values are:
  1791. * - "view"
  1792. * - "update"
  1793. * - "delete"
  1794. * - "create"
  1795. * @param $node
  1796. * The node object (or node array) on which the operation is to be performed,
  1797. * or node type (e.g. 'forum') for "create" operation.
  1798. * @param $account
  1799. * Optional, a user object representing the user for whom the operation is to
  1800. * be performed. Determines access for a user other than the current user.
  1801. * @return
  1802. * TRUE if the operation may be performed, or FALSE otherwise.
  1803. */
  1804. function node_access($op, $node, $account = NULL) {
  1805. global $user;
  1806. if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
  1807. // If there was no node to check against, or the $op was not one of the
  1808. // supported ones, we return access denied.
  1809. return FALSE;
  1810. }
  1811. // Convert the node to an object if necessary:
  1812. if ($op != 'create') {
  1813. $node = (object)$node;
  1814. }
  1815. // If no user object is supplied, the access check is for the current user.
  1816. if (empty($account)) {
  1817. $account = $user;
  1818. }
  1819. // If the node is in a restricted format, disallow editing.
  1820. if ($op == 'update' && !filter_access($node->format)) {
  1821. return FALSE;
  1822. }
  1823. if (user_access('administer nodes', $account)) {
  1824. return TRUE;
  1825. }
  1826. if (!user_access('access content', $account)) {
  1827. return FALSE;
  1828. }
  1829. // Can't use node_invoke(), because the access hook takes the $op parameter
  1830. // before the $node parameter.
  1831. $module = node_get_types('module', $node);
  1832. if ($module == 'node') {
  1833. $module = 'node_content'; // Avoid function name collisions.
  1834. }
  1835. $access = module_invoke($module, 'access', $op, $node, $account);
  1836. if (!is_null($access)) {
  1837. return $access;
  1838. }
  1839. // If the module did not override the access rights, use those set in the
  1840. // node_access table.
  1841. if ($op != 'create' && $node->nid && $node->status) {
  1842. $grants = array();
  1843. foreach (node_access_grants($op, $account) as $realm => $gids) {
  1844. foreach ($gids as $gid) {
  1845. $grants[] = "(gid = $gid AND realm = '$realm')";
  1846. }
  1847. }
  1848. $grants_sql = '';
  1849. if (count($grants)) {
  1850. $grants_sql = 'AND ('. implode(' OR ', $grants) .')';
  1851. }
  1852. $sql = "SELECT 1 FROM {node_access} WHERE (nid = 0 OR nid = %d) $grants_sql AND grant_$op >= 1";
  1853. $result = db_query_range($sql, $node->nid, 0, 1);
  1854. return (bool) db_result($result);
  1855. }
  1856. // Let authors view their own nodes.
  1857. if ($op == 'view' && $account->uid == $node->uid && $account->uid != 0) {
  1858. return TRUE;
  1859. }
  1860. return FALSE;
  1861. }
  1862. /**
  1863. * Generate an SQL join clause for use in fetching a node listing.
  1864. *
  1865. * @param $node_alias
  1866. * If the node table has been given an SQL alias other than the default
  1867. * "n", that must be passed here.
  1868. * @param $node_access_alias
  1869. * If the node_access table has been given an SQL alias other than the default
  1870. * "na", that must be passed here.
  1871. * @return
  1872. * An SQL join clause.
  1873. */
  1874. function _node_access_join_sql($node_alias = 'n', $node_access_alias = 'na') {
  1875. if (user_access('administer nodes')) {
  1876. return '';
  1877. }
  1878. return 'INNER JOIN {node_access} '. $node_access_alias .' ON '. $node_access_alias .'.nid = '. $node_alias .'.nid';
  1879. }
  1880. /**
  1881. * Generate an SQL where clause for use in fetching a node listing.
  1882. *
  1883. * @param $op
  1884. * The operation that must be allowed to return a node.
  1885. * @param $node_access_alias
  1886. * If the node_access table has been given an SQL alias other than the default
  1887. * "na", that must be passed here.
  1888. * @param $account
  1889. * The user object for the user performing the operation. If omitted, the
  1890. * current user is used.
  1891. * @return
  1892. * An SQL where clause.
  1893. */
  1894. function _node_access_where_sql($op = 'view', $node_access_alias = 'na', $account = NULL) {
  1895. if (user_access('administer nodes')) {
  1896. return;
  1897. }
  1898. $grants = array();
  1899. foreach (node_access_grants($op, $account) as $realm => $gids) {
  1900. foreach ($gids as $gid) {
  1901. $grants[] = "($node_access_alias.gid = $gid AND $node_access_alias.realm = '$realm')";
  1902. }
  1903. }
  1904. $grants_sql = '';
  1905. if (count($grants)) {
  1906. $grants_sql = 'AND ('. implode(' OR ', $grants) .')';
  1907. }
  1908. $sql = "$node_access_alias.grant_$op >= 1 $grants_sql";
  1909. return $sql;
  1910. }
  1911. /**
  1912. * Fetch an array of permission IDs granted to the given user ID.
  1913. *
  1914. * The implementation here provides only the universal "all" grant. A node
  1915. * access module should implement hook_node_grants() to provide a grant
  1916. * list for the user.
  1917. *
  1918. * @param $op
  1919. * The operation that the user is trying to perform.
  1920. * @param $account
  1921. * The user object for the user performing the operation. If omitted, the
  1922. * current user is used.
  1923. * @return
  1924. * An associative array in which the keys are realms, and the values are
  1925. * arrays of grants for those realms.
  1926. */
  1927. function node_access_grants($op, $account = NULL) {
  1928. if (!isset($account)) {
  1929. $account = $GLOBALS['user'];
  1930. }
  1931. return array_merge(array('all' => array(0)), module_invoke_all('node_grants', $account, $op));
  1932. }
  1933. /**
  1934. * Determine whether the user has a global viewing grant for all nodes.
  1935. */
  1936. function node_access_view_all_nodes() {
  1937. static $access;
  1938. if (!isset($access)) {
  1939. $grants = array();
  1940. foreach (node_access_grants('view') as $realm => $gids) {
  1941. foreach ($gids as $gid) {
  1942. $grants[] = "(gid = $gid AND realm = '$realm')";
  1943. }
  1944. }
  1945. $grants_sql = '';
  1946. if (count($grants)) {
  1947. $grants_sql = 'AND ('. implode(' OR ', $grants) .')';
  1948. }
  1949. $sql = "SELECT COUNT(*) FROM {node_access} WHERE nid = 0 $grants_sql AND grant_view >= 1";
  1950. $result = db_query($sql);
  1951. $access = db_result($result);
  1952. }
  1953. return $access;
  1954. }
  1955. /**
  1956. * Implementation of hook_db_rewrite_sql
  1957. */
  1958. function node_db_rewrite_sql($query, $primary_table, $primary_field) {
  1959. if ($primary_field == 'nid' && !node_access_view_all_nodes()) {
  1960. $return['join'] = _node_access_join_sql($primary_table);
  1961. $return['where'] = _node_access_where_sql();
  1962. $return['distinct'] = 1;
  1963. return $return;
  1964. }
  1965. }
  1966. /**
  1967. * Gets the list of node access grants and writes them to the database.
  1968. *
  1969. * This function is called when a node is saved, and can also be called by
  1970. * modules if something other than a node save causes node access permissions
  1971. * to change. It collects all node access grants for the node from
  1972. * hook_node_access_records() implementations and saves the collected
  1973. * grants to the database.
  1974. *
  1975. * @param $node
  1976. * The $node to acquire grants for.
  1977. */
  1978. function node_access_acquire_grants($node) {
  1979. $grants = module_invoke_all('node_access_records', $node);
  1980. if (empty($grants)) {
  1981. $grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0);
  1982. }
  1983. else {
  1984. // retain grants by highest priority
  1985. $grant_by_priority = array();
  1986. foreach ($grants as $g) {
  1987. $grant_by_priority[intval($g['priority'])][] = $g;
  1988. }
  1989. krsort($grant_by_priority);
  1990. $grants = array_shift($grant_by_priority);
  1991. }
  1992. node_access_write_grants($node, $grants);
  1993. }
  1994. /**
  1995. * Writes a list of grants to the database, deleting any previously saved ones.
  1996. *
  1997. * If a realm is provided, it will only delete grants from that realm, but it
  1998. * will always delete a grant from the 'all' realm. Modules that utilize
  1999. * node_access can use this function when doing mass updates due to widespread
  2000. * permission changes.
  2001. *
  2002. * @param $node
  2003. * The $node being written to. All that is necessary is that it contain a nid.
  2004. * @param $grants
  2005. * A list of grants to write. Each grant is an array that must contain the
  2006. * following keys: realm, gid, grant_view, grant_update, grant_delete.
  2007. * The realm is specified by a particular module; the gid is as well, and
  2008. * is a module-defined id to define grant privileges. each grant_* field
  2009. * is a boolean value.
  2010. * @param $realm
  2011. * If provided, only read/write grants for that realm.
  2012. * @param $delete
  2013. * If false, do not delete records. This is only for optimization purposes,
  2014. * and assumes the caller has already performed a mass delete of some form.
  2015. */
  2016. function node_access_write_grants($node, $grants, $realm = NULL, $delete = TRUE) {
  2017. if ($delete) {
  2018. $query = 'DELETE FROM {node_access} WHERE nid = %d';
  2019. if ($realm) {
  2020. $query .= " AND realm in ('%s', 'all')";
  2021. }
  2022. db_query($query, $node->nid, $realm);
  2023. }
  2024. // Only perform work when node_access modules are active.
  2025. if (count(module_implements('node_grants'))) {
  2026. foreach ($grants as $grant) {
  2027. if ($realm && $realm != $grant['realm']) {
  2028. continue;
  2029. }
  2030. // Only write grants; denies are implicit.
  2031. if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
  2032. db_query("INSERT INTO {node_access} (nid, realm, gid, grant_view, grant_update, grant_delete) VALUES (%d, '%s', %d, %d, %d, %d)", $node->nid, $grant['realm'], $grant['gid'], $grant['grant_view'], $grant['grant_update'], $grant['grant_delete']);
  2033. }
  2034. }
  2035. }
  2036. }
  2037. /**
  2038. * Flag / unflag the node access grants for rebuilding, or read the current
  2039. * value of the flag.
  2040. *
  2041. * When the flag is set, a message is displayed to users with 'access
  2042. * administration pages' permission, pointing to the 'rebuild' confirm form.
  2043. * This can be used as an alternative to direct node_access_rebuild calls,
  2044. * allowing administrators to decide when they want to perform the actual
  2045. * (possibly time consuming) rebuild.
  2046. * When unsure the current user is an adminisrator, node_access_rebuild
  2047. * should be used instead.
  2048. *
  2049. * @param $rebuild
  2050. * (Optional) The boolean value to be written.
  2051. * @return
  2052. * (If no value was provided for $rebuild) The current value of the flag.
  2053. */
  2054. function node_access_needs_rebuild($rebuild = NULL) {
  2055. if (!isset($rebuild)) {
  2056. return variable_get('node_access_needs_rebuild', FALSE);
  2057. }
  2058. elseif ($rebuild) {
  2059. variable_set('node_access_needs_rebuild', TRUE);
  2060. }
  2061. else {
  2062. variable_del('node_access_needs_rebuild');
  2063. }
  2064. }
  2065. /**
  2066. * Rebuild the node access database. This is occasionally needed by modules
  2067. * that make system-wide changes to access levels.
  2068. *
  2069. * When the rebuild is required by an admin-triggered action (e.g module
  2070. * settings form), calling node_access_needs_rebuild(TRUE) instead of
  2071. * node_access_rebuild() lets the user perform his changes and actually
  2072. * rebuild only once he is done.
  2073. *
  2074. * Note : As of Drupal 6, node access modules are not required to (and actually
  2075. * should not) call node_access_rebuild() in hook_enable/disable anymore.
  2076. *
  2077. * @see node_access_needs_rebuild()
  2078. *
  2079. * @param $batch_mode
  2080. * Set to TRUE to process in 'batch' mode, spawning processing over several
  2081. * HTTP requests (thus avoiding the risk of PHP timeout if the site has a
  2082. * large number of nodes).
  2083. * hook_update_N and any form submit handler are safe contexts to use the
  2084. * 'batch mode'. Less decidable cases (such as calls from hook_user,
  2085. * hook_taxonomy, hook_node_type...) might consider using the non-batch mode.
  2086. */
  2087. function node_access_rebuild($batch_mode = FALSE) {
  2088. db_query("DELETE FROM {node_access}");
  2089. // Only recalculate if the site is using a node_access module.
  2090. if (count(module_implements('node_grants'))) {
  2091. if ($batch_mode) {
  2092. $batch = array(
  2093. 'title' => t('Rebuilding content access permissions'),
  2094. 'operations' => array(
  2095. array('_node_access_rebuild_batch_operation', array()),
  2096. ),
  2097. 'finished' => '_node_access_rebuild_batch_finished'
  2098. );
  2099. batch_set($batch);
  2100. }
  2101. else {
  2102. // Try to allocate enough time to rebuild node grants
  2103. if (function_exists('set_time_limit')) {
  2104. @set_time_limit(240);
  2105. }
  2106. $result = db_query("SELECT nid FROM {node}");
  2107. while ($node = db_fetch_object($result)) {
  2108. $loaded_node = node_load($node->nid, NULL, TRUE);
  2109. // To preserve database integrity, only aquire grants if the node
  2110. // loads successfully.
  2111. if (!empty($loaded_node)) {
  2112. node_access_acquire_grants($loaded_node);
  2113. }
  2114. }
  2115. }
  2116. }
  2117. else {
  2118. // Not using any node_access modules. Add the default grant.
  2119. db_query("INSERT INTO {node_access} VALUES (0, 0, 'all', 1, 0, 0)");
  2120. }
  2121. if (!isset($batch)) {
  2122. drupal_set_message(t('Content permissions have been rebuilt.'));
  2123. node_access_needs_rebuild(FALSE);
  2124. cache_clear_all();
  2125. }
  2126. }
  2127. /**
  2128. * Batch operation for node_access_rebuild_batch.
  2129. *
  2130. * This is a mutlistep operation : we go through all nodes by packs of 20.
  2131. * The batch processing engine interrupts processing and sends progress
  2132. * feedback after 1 second execution time.
  2133. */
  2134. function _node_access_rebuild_batch_operation(&$context) {
  2135. if (empty($context['sandbox'])) {
  2136. // Initiate multistep processing.
  2137. $context['sandbox']['progress'] = 0;
  2138. $context['sandbox']['current_node'] = 0;
  2139. $context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT nid) FROM {node}'));
  2140. }
  2141. // Process the next 20 nodes.
  2142. $limit = 20;
  2143. $result = db_query_range("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC", $context['sandbox']['current_node'], 0, $limit);
  2144. while ($row = db_fetch_array($result)) {
  2145. $loaded_node = node_load($row['nid'], NULL, TRUE);
  2146. // To preserve database integrity, only aquire grants if the node
  2147. // loads successfully.
  2148. if (!empty($loaded_node)) {
  2149. node_access_acquire_grants($loaded_node);
  2150. }
  2151. $context['sandbox']['progress']++;
  2152. $context['sandbox']['current_node'] = $row['nid'];
  2153. }
  2154. // Multistep processing : report progress.
  2155. if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  2156. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  2157. }
  2158. }
  2159. /**
  2160. * Post-processing for node_access_rebuild_batch.
  2161. */
  2162. function _node_access_rebuild_batch_finished($success, $results, $operations) {
  2163. if ($success) {
  2164. drupal_set_message(t('The content access permissions have been rebuilt.'));
  2165. node_access_needs_rebuild(FALSE);
  2166. }
  2167. else {
  2168. drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
  2169. }
  2170. cache_clear_all();
  2171. }
  2172. /**
  2173. * @} End of "defgroup node_access".
  2174. */
  2175. /**
  2176. * @defgroup node_content Hook implementations for user-created content types.
  2177. * @{
  2178. */
  2179. /**
  2180. * Implementation of hook_access().
  2181. *
  2182. * Named so as not to conflict with node_access()
  2183. */
  2184. function node_content_access($op, $node, $account) {
  2185. $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type);
  2186. if ($op == 'create') {
  2187. return user_access('create '. $type .' content', $account);
  2188. }
  2189. if ($op == 'update') {
  2190. if (user_access('edit any '. $type .' content', $account) || (user_access('edit own '. $type .' content', $account) && ($account->uid == $node->uid))) {
  2191. return TRUE;
  2192. }
  2193. }
  2194. if ($op == 'delete') {
  2195. if (user_access('delete any '. $type .' content', $account) || (user_access('delete own '. $type .' content', $account) && ($account->uid == $node->uid))) {
  2196. return TRUE;
  2197. }
  2198. }
  2199. }
  2200. /**
  2201. * Implementation of hook_form().
  2202. */
  2203. function node_content_form($node, $form_state) {
  2204. $type = node_get_types('type', $node);
  2205. $form = array();
  2206. if ($type->has_title) {
  2207. $form['title'] = array(
  2208. '#type' => 'textfield',
  2209. '#title' => check_plain($type->title_label),
  2210. '#required' => TRUE,
  2211. '#default_value' => $node->title,
  2212. '#maxlength' => 255,
  2213. '#weight' => -5,
  2214. );
  2215. }
  2216. if ($type->has_body) {
  2217. $form['body_field'] = node_body_field($node, $type->body_label, $type->min_word_count);
  2218. }
  2219. return $form;
  2220. }
  2221. /**
  2222. * @} End of "defgroup node_content".
  2223. */
  2224. /**
  2225. * Implementation of hook_forms(). All node forms share the same form handler
  2226. */
  2227. function node_forms() {
  2228. $forms = array();
  2229. if ($types = node_get_types()) {
  2230. foreach (array_keys($types) as $type) {
  2231. $forms[$type .'_node_form']['callback'] = 'node_form';
  2232. }
  2233. }
  2234. return $forms;
  2235. }
  2236. /**
  2237. * Format the "Submitted by username on date/time" for each node
  2238. *
  2239. * @ingroup themeable
  2240. */
  2241. function theme_node_submitted($node) {
  2242. return t('Submitted by !username on @datetime',
  2243. array(
  2244. '!username' => theme('username', $node),
  2245. '@datetime' => format_date($node->created),
  2246. ));
  2247. }
  2248. /**
  2249. * Implementation of hook_hook_info().
  2250. */
  2251. function node_hook_info() {
  2252. return array(
  2253. 'node' => array(
  2254. 'nodeapi' => array(
  2255. 'presave' => array(
  2256. 'runs when' => t('When either saving a new post or updating an existing post'),
  2257. ),
  2258. 'insert' => array(
  2259. 'runs when' => t('After saving a new post'),
  2260. ),
  2261. 'update' => array(
  2262. 'runs when' => t('After saving an updated post'),
  2263. ),
  2264. 'delete' => array(
  2265. 'runs when' => t('After deleting a post')
  2266. ),
  2267. 'view' => array(
  2268. 'runs when' => t('When content is viewed by an authenticated user')
  2269. ),
  2270. ),
  2271. ),
  2272. );
  2273. }
  2274. /**
  2275. * Implementation of hook_action_info().
  2276. */
  2277. function node_action_info() {
  2278. return array(
  2279. 'node_publish_action' => array(
  2280. 'type' => 'node',
  2281. 'description' => t('Publish post'),
  2282. 'configurable' => FALSE,
  2283. 'behavior' => array('changes_node_property'),
  2284. 'hooks' => array(
  2285. 'nodeapi' => array('presave'),
  2286. 'comment' => array('insert', 'update'),
  2287. ),
  2288. ),
  2289. 'node_unpublish_action' => array(
  2290. 'type' => 'node',
  2291. 'description' => t('Unpublish post'),
  2292. 'configurable' => FALSE,
  2293. 'behavior' => array('changes_node_property'),
  2294. 'hooks' => array(
  2295. 'nodeapi' => array('presave'),
  2296. 'comment' => array('delete', 'insert', 'update'),
  2297. ),
  2298. ),
  2299. 'node_make_sticky_action' => array(
  2300. 'type' => 'node',
  2301. 'description' => t('Make post sticky'),
  2302. 'configurable' => FALSE,
  2303. 'behavior' => array('changes_node_property'),
  2304. 'hooks' => array(
  2305. 'nodeapi' => array('presave'),
  2306. 'comment' => array('insert', 'update'),
  2307. ),
  2308. ),
  2309. 'node_make_unsticky_action' => array(
  2310. 'type' => 'node',
  2311. 'description' => t('Make post unsticky'),
  2312. 'configurable' => FALSE,
  2313. 'behavior' => array('changes_node_property'),
  2314. 'hooks' => array(
  2315. 'nodeapi' => array('presave'),
  2316. 'comment' => array('delete', 'insert', 'update'),
  2317. ),
  2318. ),
  2319. 'node_promote_action' => array(
  2320. 'type' => 'node',
  2321. 'description' => t('Promote post to front page'),
  2322. 'configurable' => FALSE,
  2323. 'behavior' => array('changes_node_property'),
  2324. 'hooks' => array(
  2325. 'nodeapi' => array('presave'),
  2326. 'comment' => array('insert', 'update'),
  2327. ),
  2328. ),
  2329. 'node_unpromote_action' => array(
  2330. 'type' => 'node',
  2331. 'description' => t('Remove post from front page'),
  2332. 'configurable' => FALSE,
  2333. 'behavior' => array('changes_node_property'),
  2334. 'hooks' => array(
  2335. 'nodeapi' => array('presave'),
  2336. 'comment' => array('delete', 'insert', 'update'),
  2337. ),
  2338. ),
  2339. 'node_assign_owner_action' => array(
  2340. 'type' => 'node',
  2341. 'description' => t('Change the author of a post'),
  2342. 'configurable' => TRUE,
  2343. 'behavior' => array('changes_node_property'),
  2344. 'hooks' => array(
  2345. 'any' => TRUE,
  2346. 'nodeapi' => array('presave'),
  2347. 'comment' => array('delete', 'insert', 'update'),
  2348. ),
  2349. ),
  2350. 'node_save_action' => array(
  2351. 'type' => 'node',
  2352. 'description' => t('Save post'),
  2353. 'configurable' => FALSE,
  2354. 'hooks' => array(
  2355. 'comment' => array('delete', 'insert', 'update'),
  2356. ),
  2357. ),
  2358. 'node_unpublish_by_keyword_action' => array(
  2359. 'type' => 'node',
  2360. 'description' => t('Unpublish post containing keyword(s)'),
  2361. 'configurable' => TRUE,
  2362. 'hooks' => array(
  2363. 'nodeapi' => array('presave', 'insert', 'update'),
  2364. ),
  2365. ),
  2366. );
  2367. }
  2368. /**
  2369. * Implementation of a Drupal action.
  2370. * Sets the status of a node to 1, meaning published.
  2371. */
  2372. function node_publish_action(&$node, $context = array()) {
  2373. $node->status = 1;
  2374. watchdog('action', 'Set @type %title to published.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
  2375. }
  2376. /**
  2377. * Implementation of a Drupal action.
  2378. * Sets the status of a node to 0, meaning unpublished.
  2379. */
  2380. function node_unpublish_action(&$node, $context = array()) {
  2381. $node->status = 0;
  2382. watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
  2383. }
  2384. /**
  2385. * Implementation of a Drupal action.
  2386. * Sets the sticky-at-top-of-list property of a node to 1.
  2387. */
  2388. function node_make_sticky_action(&$node, $context = array()) {
  2389. $node->sticky = 1;
  2390. watchdog('action', 'Set @type %title to sticky.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
  2391. }
  2392. /**
  2393. * Implementation of a Drupal action.
  2394. * Sets the sticky-at-top-of-list property of a node to 0.
  2395. */
  2396. function node_make_unsticky_action(&$node, $context = array()) {
  2397. $node->sticky = 0;
  2398. watchdog('action', 'Set @type %title to unsticky.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
  2399. }
  2400. /**
  2401. * Implementation of a Drupal action.
  2402. * Sets the promote property of a node to 1.
  2403. */
  2404. function node_promote_action(&$node, $context = array()) {
  2405. $node->promote = 1;
  2406. watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
  2407. }
  2408. /**
  2409. * Implementation of a Drupal action.
  2410. * Sets the promote property of a node to 0.
  2411. */
  2412. function node_unpromote_action(&$node, $context = array()) {
  2413. $node->promote = 0;
  2414. watchdog('action', 'Removed @type %title from front page.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
  2415. }
  2416. /**
  2417. * Implementation of a Drupal action.
  2418. * Saves a node.
  2419. */
  2420. function node_save_action($node) {
  2421. node_save($node);
  2422. watchdog('action', 'Saved @type %title', array('@type' => node_get_types('name', $node), '%title' => $node->title));
  2423. }
  2424. /**
  2425. * Implementation of a configurable Drupal action.
  2426. * Assigns ownership of a node to a user.
  2427. */
  2428. function node_assign_owner_action(&$node, $context) {
  2429. $node->uid = $context['owner_uid'];
  2430. $owner_name = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $context['owner_uid']));
  2431. watchdog('action', 'Changed owner of @type %title to uid %name.', array('@type' => node_get_types('name', $node), '%title' => $node->title, '%name' => $owner_name));
  2432. }
  2433. function node_assign_owner_action_form($context) {
  2434. $description = t('The username of the user to which you would like to assign ownership.');
  2435. $count = db_result(db_query("SELECT COUNT(*) FROM {users}"));
  2436. $owner_name = '';
  2437. if (isset($context['owner_uid'])) {
  2438. $owner_name = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $context['owner_uid']));
  2439. }
  2440. // Use dropdown for fewer than 200 users; textbox for more than that.
  2441. if (intval($count) < 200) {
  2442. $options = array();
  2443. $result = db_query("SELECT uid, name FROM {users} WHERE uid > 0 ORDER BY name");
  2444. while ($data = db_fetch_object($result)) {
  2445. $options[$data->name] = $data->name;
  2446. }
  2447. $form['owner_name'] = array(
  2448. '#type' => 'select',
  2449. '#title' => t('Username'),
  2450. '#default_value' => $owner_name,
  2451. '#options' => $options,
  2452. '#description' => $description,
  2453. );
  2454. }
  2455. else {
  2456. $form['owner_name'] = array(
  2457. '#type' => 'textfield',
  2458. '#title' => t('Username'),
  2459. '#default_value' => $owner_name,
  2460. '#autocomplete_path' => 'user/autocomplete',
  2461. '#size' => '6',
  2462. '#maxlength' => '60',
  2463. '#description' => $description,
  2464. );
  2465. }
  2466. return $form;
  2467. }
  2468. function node_assign_owner_action_validate($form, $form_state) {
  2469. $count = db_result(db_query("SELECT COUNT(*) FROM {users} WHERE name = '%s'", $form_state['values']['owner_name']));
  2470. if (intval($count) != 1) {
  2471. form_set_error('owner_name', t('Please enter a valid username.'));
  2472. }
  2473. }
  2474. function node_assign_owner_action_submit($form, $form_state) {
  2475. // Username can change, so we need to store the ID, not the username.
  2476. $uid = db_result(db_query("SELECT uid from {users} WHERE name = '%s'", $form_state['values']['owner_name']));
  2477. return array('owner_uid' => $uid);
  2478. }
  2479. function node_unpublish_by_keyword_action_form($context) {
  2480. $form['keywords'] = array(
  2481. '#title' => t('Keywords'),
  2482. '#type' => 'textarea',
  2483. '#description' => t('The post will be unpublished if it contains any of the character sequences above. Use a comma-separated list of character sequences. Example: funny, bungee jumping, "Company, Inc.". Character sequences are case-sensitive.'),
  2484. '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
  2485. );
  2486. return $form;
  2487. }
  2488. function node_unpublish_by_keyword_action_submit($form, $form_state) {
  2489. return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
  2490. }
  2491. /**
  2492. * Implementation of a configurable Drupal action.
  2493. * Unpublish a node if it contains a certain string.
  2494. *
  2495. * @param $context
  2496. * An array providing more information about the context of the call to this action.
  2497. * @param $comment
  2498. * A node object.
  2499. */
  2500. function node_unpublish_by_keyword_action($node, $context) {
  2501. foreach ($context['keywords'] as $keyword) {
  2502. if (strstr(node_view(drupal_clone($node)), $keyword) || strstr($node->title, $keyword)) {
  2503. $node->status = 0;
  2504. watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_get_types('name', $node), '%title' => $node->title));
  2505. break;
  2506. }
  2507. }
  2508. }