node.module

You are here

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

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

Functions

Namesort descending Description
node_access Determine whether the current user may perform the given operation on the specified node.
node_access_acquire_grants Gets the list of node access grants and writes them to the database.
node_access_grants Fetch an array of permission IDs granted to the given user ID.
node_access_needs_rebuild Flag / unflag the node access grants for rebuilding, or read the current value of the flag.
node_access_rebuild Rebuild the node access database. This is occasionally needed by modules that make system-wide changes to access levels.
node_access_view_all_nodes Determine whether the user has a global viewing grant for all nodes.
node_access_write_grants Writes a list of grants to the database, deleting any previously saved ones.
node_action_info Implementation of hook_action_info().
node_assign_owner_action Implementation 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_block Implementation of hook_block().
node_build_content Builds a structured array representing the node's content.
node_comment_mode Retrieve the comment mode for the given node ID (none, read, or read/write).
node_content_access Implementation of hook_access().
node_content_form Implementation of hook_form().
node_cron Implementation of hook_cron().
node_db_rewrite_sql Implementation of hook_db_rewrite_sql
node_delete Delete a node.
node_feed A generic function for generating RSS feeds from a set of nodes.
node_forms Implementation of hook_forms(). All node forms share the same form handler
node_form_alter Implementation of hook_form_alter().
node_get_types Builds a list of available node types, and returns all or part of this list.
node_help Implementation of hook_help().
node_hook Determine whether a node hook exists.
node_hook_info Implementation of hook_hook_info().
node_init Implementation of hook_init().
node_invoke Invoke a node hook.
node_invoke_nodeapi Invoke a hook_nodeapi() operation in all modules.
node_last_changed
node_last_viewed Retrieves the timestamp at which the current user last viewed the specified node.
node_link Implementation of hook_link().
node_load Load a node object from the database.
node_make_sticky_action Implementation of a Drupal action. Sets the sticky-at-top-of-list property of a node to 1.
node_make_unsticky_action Implementation of a Drupal action. Sets the sticky-at-top-of-list property of a node to 0.
node_mark Decide on the type of marker to be displayed for a given node.
node_menu Implementation of hook_menu().
node_page_default Menu callback; Generate a listing of promoted nodes.
node_page_title Title callback.
node_page_view Menu callback; view a single node.
node_perm Implementation of hook_perm().
node_prepare Apply filters and build the node's standard elements.
node_promote_action Implementation of a Drupal action. Sets the promote property of a node to 1.
node_publish_action Implementation of a Drupal action. Sets the status of a node to 1, meaning published.
node_revision_list Return a list of all the existing revision numbers.
node_save Save a node object into the database.
node_save_action Implementation of a Drupal action. Saves a node.
node_search Implementation of hook_search().
node_search_validate Form API callback for the search form. Registered in node_form_alter().
node_show Generate a page displaying a single node, along with its comments.
node_submit Prepares a node for saving by populating teaser, author, and creation date.
node_tag_new Update the 'last viewed' timestamp of the specified node for current user.
node_teaser Generate a teaser for a node body.
node_teaser_include_verify Ensure value of "teaser_include" checkbox is consistent with other form data.
node_teaser_js See if the user used JS to submit a teaser.
node_theme Implementation of hook_theme()
node_title_list Gather a listing of links to nodes.
node_types_rebuild Resets the database cache of node types, and saves all new or non-modified module-defined node types to the database.
node_type_delete Deletes a node type from the database.
node_type_save Saves a node type to the database.
node_type_update_nodes Updates all nodes of one type to be of another type.
node_unpromote_action Implementation of a Drupal action. Sets the promote property of a node to 0.
node_unpublish_action Implementation of a Drupal action. Sets the status of a node to 0, meaning unpublished.
node_unpublish_by_keyword_action Implementation 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_index Implementation of hook_update_index().
node_user Implementation of hook_user().
node_validate Perform validation checks on the given node.
node_view Generate a display of the given node.
theme_node_list Format a listing of links to nodes.
theme_node_log_message Theme a log message.
theme_node_search_admin Theme the content ranking part of the search settings admin page.
theme_node_submitted Format the "Submitted by username on date/time" for each node
_node_access_join_sql Generate an SQL join clause for use in fetching a node listing.
_node_access_rebuild_batch_finished Post-processing for node_access_rebuild_batch.
_node_access_rebuild_batch_operation Batch operation for node_access_rebuild_batch.
_node_access_where_sql Generate an SQL where clause for use in fetching a node listing.
_node_add_access
_node_index_node Index a single node.
_node_revision_access
_node_save_revision Helper function to save a revision with the uid of the current user.
_node_types_build Builds and returns the list of available node types.
_node_type_set_defaults Set default values for a node type defined through hook_node_info().

Constants

File

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