node.module

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

The core that allows content to be submitted to the site.

Functions & methods

NameDescription
node_accessDetermine whether the current user may perform the given operation on the specified node.
node_access_grantsFetch an array of permission IDs granted to the given user ID.
node_access_view_all_nodesDetermine whether the user has a global viewing grant for all nodes.
node_addPresent a node submission form or a set of links to such forms.
node_admin_nodesMenu callback: content administration.
node_admin_nodes_submitGenerate the content administration overview.
node_admin_nodes_validate
node_admin_search
node_blockImplementation of hook_block().
node_build_filter_queryBuild query for node administration filters based on session.
node_comment_modeRetrieve the comment mode for the given node ID (none, read, or read/write).
node_configureMenu callback; presents general node configuration options.
node_cronImplementation of hook_cron().
node_db_rewrite_sqlImplementation of hook_db_rewrite_sql
node_deleteDelete a node.
node_delete_confirmMenu callback -- ask for confirmation of node deletion
node_delete_confirm_submitExecute node deletion
node_feedA generic function for generating RSS feeds from a set of nodes.
node_filtersList node administration filters that can be applied.
node_filter_formReturn form for node administration filters.
node_filter_form_submitProcess result from node administration filter form.
node_formGenerate the node editing form.
node_form_add_preview
node_form_alterImplementation of hook_form_alter().
node_form_arrayGenerate the node editing form array.
node_form_submit
node_form_validate
node_get_baseDetermine the basename for hook_load etc.
node_get_nameDetermine the human readable name for a given type.
node_get_typesReturn the list of available node types.
node_helpImplementation of hook_help().
node_hookDetermine whether a node hook exists.
node_invokeInvoke a node hook.
node_invoke_nodeapiInvoke a hook_nodeapi() operation in all modules.
node_last_changed
node_last_viewedRetrieves the timestamp at which the current user last viewed the specified node.
node_linkImplementation of hook_link().
node_loadLoad a node object from the database.
node_markDecide on the type of marker to be displayed for a given node.
node_menuImplementation of hook_menu().
node_multiple_delete_confirm
node_multiple_delete_confirm_submit
node_object_prepare
node_operationsList node administration operations that can be performed.
node_pageMenu callback; dispatches control to the appropriate operation handler.
node_page_defaultGenerate a listing of promoted nodes.
node_permImplementation of hook_perm().
node_prepareApply filters to a node in preparation for theming.
node_previewGenerate a node preview.
node_revisionsMenu callback for revisions related activities.
node_revision_deleteDelete the revision with specified revision number. A "delete revision" nodeapi event is invoked when a revision is deleted.
node_revision_delete_confirm_submit
node_revision_listReturn a list of all the existing revision numbers.
node_revision_overviewGenerate an overview table of older revisions of a node.
node_revision_revertRevert to the revision with the specified revision number. A node and nodeapi "update" event is triggered (via the node_save() call) when a revision is reverted.
node_revision_revert_confirm_submit
node_saveSave a node object into the database.
node_searchImplementation of hook_search().
node_search_validateForm API callback for the search form. Registered in node_form_alter().
node_showGenerate a page displaying a single node, along with its comments.
node_submitPrepare node for save and allow modules to make changes.
node_tag_newUpdate the 'last viewed' timestamp of the specified node for current user.
node_teaserAutomatically generate a teaser for a node body in a given format.
node_title_listGather a listing of links to nodes.
node_types_configureMenu callback; presents each node type configuration page.
node_update_indexImplementation of hook_update_index().
node_update_shutdownshutdown function to make sure we always mark the last node processed.
node_userImplementation of hook_user().
node_validatePerform validation checks on the given node.
node_viewGenerate a display of the given node.
theme_node_admin_nodesTheme node administration overview.
theme_node_filtersTheme node administraton filter selector.
theme_node_filter_formTheme node administration filter form.
theme_node_form
theme_node_listFormat a listing of links to nodes.
theme_node_previewDisplay a node preview for display during node creation and editing.
theme_node_search_admin
_node_access_join_sqlGenerate an SQL join clause for use in fetching a node listing.
_node_access_where_sqlGenerate an SQL where clause for use in fetching a node listing.
_node_names

Constants

NameDescription
NODE_NEW_LIMIT

File

modules/node.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * The core that allows content to be submitted to the site.
  5. */
  6. define('NODE_NEW_LIMIT', time() - 30 * 24 * 60 * 60);
  7. /**
  8. * Implementation of hook_help().
  9. */
  10. function node_help($section) {
  11. switch ($section) {
  12. case 'admin/help#node':
  13. $output = '<p>'. t('All content in a website is stored and treated as <b>nodes</b>. Therefore nodes are any postings such as blogs, stories, polls and forums. The node module manages these content types and is one of the strengths of Drupal over other content management systems.') .'</p>';
  14. $output .= '<p>'. t('Treating all content as nodes allows the flexibility of creating new types of content. It also allows you to painlessly apply new features or changes to all content. Comments are not stored as nodes but are always associated with a node.') .'</p>';
  15. $output .= t('<p>Node module features</p>
  16. <ul>
  17. <li>The list tab provides an interface to search and sort all content on your site.</li>
  18. <li>The configure settings tab has basic settings for content on your site.</li>
  19. <li>The configure content types tab lists all content types for your site and lets you configure their default workflow.</li>
  20. <li>The search tab lets you search all content on your site</li>
  21. </ul>
  22. ');
  23. $output .= t('<p>You can</p>
  24. <ul>
  25. <li>search for content at <a href="%search">search</a>.</li>
  26. <li>administer nodes at <a href="%admin-settings-content-types">administer &gt;&gt; settings &gt;&gt; content types</a>.</li>
  27. </ul>
  28. ', array('%search' => url('search'), '%admin-settings-content-types' => url('admin/settings/content-types')));
  29. $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%node">Node page</a>.', array('%node' => 'http://drupal.org/handbook/modules/node/')) .'</p>';
  30. return $output;
  31. case 'admin/modules#description':
  32. return t('Allows content to be submitted to the site and displayed on pages.');
  33. case 'admin/node/configure':
  34. case 'admin/node/configure/settings':
  35. return t('<p>Settings for the core of Drupal. Almost everything is a node so these settings will affect most of the site.</p>');
  36. case 'admin/node':
  37. return t('<p>Below is a list of all of the posts on your site. Other forms of content are listed elsewhere (e.g. <a href="%comments">comments</a>).</p><p>Clicking a title views the post, while clicking an author\'s name views their user information.</p>', array('%comments' => url('admin/comment')));
  38. case 'admin/node/search':
  39. return t('<p>Enter a simple pattern to search for a post. This can include the wildcard character *.<br />For example, a search for "br*" might return "bread bakers", "our daily bread" and "brenda".</p>');
  40. }
  41. if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'revisions' && !arg(3)) {
  42. return t('The revisions let you track differences between multiple versions of a post.');
  43. }
  44. if (arg(0) == 'node' && arg(1) == 'add' && $type = arg(2)) {
  45. return filter_xss_admin(variable_get($type .'_help', ''));
  46. }
  47. }
  48. /**
  49. * Implementation of hook_cron().
  50. */
  51. function node_cron() {
  52. db_query('DELETE FROM {history} WHERE timestamp < %d', NODE_NEW_LIMIT);
  53. }
  54. /**
  55. * Gather a listing of links to nodes.
  56. *
  57. * @param $result
  58. * A DB result object from a query to fetch node objects. If your query joins the <code>node_comment_statistics</code> table so that the <code>comment_count</code> field is available, a title attribute will be added to show the number of comments.
  59. * @param $title
  60. * A heading for the resulting list.
  61. *
  62. * @return
  63. * An HTML list suitable as content for a block.
  64. */
  65. function node_title_list($result, $title = NULL) {
  66. while ($node = db_fetch_object($result)) {
  67. $items[] = l($node->title, 'node/'. $node->nid, $node->comment_count ? array('title' => format_plural($node->comment_count, '1 comment', '%count comments')) : '');
  68. }
  69. return theme('node_list', $items, $title);
  70. }
  71. /**
  72. * Format a listing of links to nodes.
  73. */
  74. function theme_node_list($items, $title = NULL) {
  75. return theme('item_list', $items, $title);
  76. }
  77. /**
  78. * Update the 'last viewed' timestamp of the specified node for current user.
  79. */
  80. function node_tag_new($nid) {
  81. global $user;
  82. if ($user->uid) {
  83. if (node_last_viewed($nid)) {
  84. db_query('UPDATE {history} SET timestamp = %d WHERE uid = %d AND nid = %d', time(), $user->uid, $nid);
  85. }
  86. else {
  87. @db_query('INSERT INTO {history} (uid, nid, timestamp) VALUES (%d, %d, %d)', $user->uid, $nid, time());
  88. }
  89. }
  90. }
  91. /**
  92. * Retrieves the timestamp at which the current user last viewed the
  93. * specified node.
  94. */
  95. function node_last_viewed($nid) {
  96. global $user;
  97. static $history;
  98. if (!isset($history[$nid])) {
  99. $history[$nid] = db_fetch_object(db_query("SELECT timestamp FROM {history} WHERE uid = '$user->uid' AND nid = %d", $nid));
  100. }
  101. return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
  102. }
  103. /**
  104. * Decide on the type of marker to be displayed for a given node.
  105. *
  106. * @param $nid
  107. * Node ID whose history supplies the "last viewed" timestamp.
  108. * @param $timestamp
  109. * Time which is compared against node's "last viewed" timestamp.
  110. * @return
  111. * One of the MARK constants.
  112. */
  113. function node_mark($nid, $timestamp) {
  114. global $user;
  115. static $cache;
  116. if (!$user->uid) {
  117. return MARK_READ;
  118. }
  119. if (!isset($cache[$nid])) {
  120. $cache[$nid] = node_last_viewed($nid);
  121. }
  122. if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
  123. return MARK_NEW;
  124. }
  125. elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
  126. return MARK_UPDATED;
  127. }
  128. return MARK_READ;
  129. }
  130. /**
  131. * Automatically generate a teaser for a node body in a given format.
  132. */
  133. function node_teaser($body, $format = NULL) {
  134. $size = variable_get('teaser_length', 600);
  135. // find where the delimiter is in the body
  136. $delimiter = strpos($body, '<!--break-->');
  137. // If the size is zero, and there is no delimiter, the entire body is the teaser.
  138. if ($size == 0 && $delimiter === FALSE) {
  139. return $body;
  140. }
  141. // If a valid delimiter has been specified, use it to chop off the teaser.
  142. if ($delimiter !== FALSE) {
  143. return substr($body, 0, $delimiter);
  144. }
  145. // We check for the presence of the PHP evaluator filter in the current
  146. // format. If the body contains PHP code, we do not split it up to prevent
  147. // parse errors.
  148. if (isset($format)) {
  149. $filters = filter_list_format($format);
  150. if (isset($filters['filter/1']) && strpos($body, '<?') !== FALSE) {
  151. return $body;
  152. }
  153. }
  154. // If we have a short body, the entire body is the teaser.
  155. if (strlen($body) < $size) {
  156. return $body;
  157. }
  158. // The teaser may not be longer than maximum length specified. Initial slice.
  159. $teaser = truncate_utf8($body, $size);
  160. $position = 0;
  161. // Cache the reverse of the teaser.
  162. $reversed = strrev($teaser);
  163. // In some cases, no delimiter has been specified. In this case, we try to
  164. // split at paragraph boundaries.
  165. $breakpoints = array('</p>' => 0, '<br />' => 6, '<br>' => 4, "\n" => 1);
  166. // We use strpos on the reversed needle and haystack for speed.
  167. foreach ($breakpoints as $point => $offset) {
  168. $length = strpos($reversed, strrev($point));
  169. if ($length !== FALSE) {
  170. $position = - $length - $offset;
  171. return ($position == 0) ? $teaser : substr($teaser, 0, $position);
  172. }
  173. }
  174. // When even the first paragraph is too long, we try to split at the end of
  175. // the last full sentence.
  176. $breakpoints = array('. ' => 1, '! ' => 1, '? ' => 1, '。' => 0, '؟ ' => 1);
  177. $min_length = strlen($reversed);
  178. foreach ($breakpoints as $point => $offset) {
  179. $length = strpos($reversed, strrev($point));
  180. if ($length !== FALSE) {
  181. $min_length = min($length, $min_length);
  182. $position = 0 - $length - $offset;
  183. }
  184. }
  185. return ($position == 0) ? $teaser : substr($teaser, 0, $position);
  186. }
  187. function _node_names($op = '', $node = NULL) {
  188. static $node_names = array();
  189. static $node_list = array();
  190. if (empty($node_names)) {
  191. $node_names = module_invoke_all('node_info');
  192. foreach ($node_names as $type => $value) {
  193. $node_list[$type] = $value['name'];
  194. }
  195. }
  196. if ($node) {
  197. if (is_array($node)) {
  198. $type = $node['type'];
  199. }
  200. elseif (is_object($node)) {
  201. $type = $node->type;
  202. }
  203. elseif (is_string($node)) {
  204. $type = $node;
  205. }
  206. if (!isset($node_names[$type])) {
  207. return FALSE;
  208. }
  209. }
  210. switch ($op) {
  211. case 'base':
  212. return $node_names[$type]['base'];
  213. case 'list':
  214. return $node_list;
  215. case 'name':
  216. return $node_list[$type];
  217. }
  218. }
  219. /**
  220. * Determine the basename for hook_load etc.
  221. *
  222. * @param $node
  223. * Either a node object, a node array, or a string containing the node type.
  224. * @return
  225. * The basename for hook_load, hook_nodeapi etc.
  226. */
  227. function node_get_base($node) {
  228. return _node_names('base', $node);
  229. }
  230. /**
  231. * Determine the human readable name for a given type.
  232. *
  233. * @param $node
  234. * Either a node object, a node array, or a string containing the node type.
  235. * @return
  236. * The human readable name of the node type.
  237. */
  238. function node_get_name($node) {
  239. return _node_names('name', $node);
  240. }
  241. /**
  242. * Return the list of available node types.
  243. *
  244. * @return
  245. * An array consisting ('#type' => name) pairs.
  246. */
  247. function node_get_types() {
  248. return _node_names('list');
  249. }
  250. /**
  251. * Determine whether a node hook exists.
  252. *
  253. * @param &$node
  254. * Either a node object, node array, or a string containing the node type.
  255. * @param $hook
  256. * A string containing the name of the hook.
  257. * @return
  258. * TRUE iff the $hook exists in the node type of $node.
  259. */
  260. function node_hook(&$node, $hook) {
  261. return module_hook(node_get_base($node), $hook);
  262. }
  263. /**
  264. * Invoke a node hook.
  265. *
  266. * @param &$node
  267. * Either a node object, node array, or a string containing the node type.
  268. * @param $hook
  269. * A string containing the name of the hook.
  270. * @param $a2, $a3, $a4
  271. * Arguments to pass on to the hook, after the $node argument.
  272. * @return
  273. * The returned value of the invoked hook.
  274. */
  275. function node_invoke(&$node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
  276. if (node_hook($node, $hook)) {
  277. $function = node_get_base($node) ."_$hook";
  278. return ($function($node, $a2, $a3, $a4));
  279. }
  280. }
  281. /**
  282. * Invoke a hook_nodeapi() operation in all modules.
  283. *
  284. * @param &$node
  285. * A node object.
  286. * @param $op
  287. * A string containing the name of the nodeapi operation.
  288. * @param $a3, $a4
  289. * Arguments to pass on to the hook, after the $node and $op arguments.
  290. * @return
  291. * The returned value of the invoked hooks.
  292. */
  293. function node_invoke_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  294. $return = array();
  295. foreach (module_implements('nodeapi') as $name) {
  296. $function = $name .'_nodeapi';
  297. $result = $function($node, $op, $a3, $a4);
  298. if (isset($result) && is_array($result)) {
  299. $return = array_merge($return, $result);
  300. }
  301. else if (isset($result)) {
  302. $return[] = $result;
  303. }
  304. }
  305. return $return;
  306. }
  307. /**
  308. * Load a node object from the database.
  309. *
  310. * @param $param
  311. * Either the nid of the node or an array of conditions to match against in the database query
  312. * @param $revision
  313. * Which numbered revision to load. Defaults to the current version.
  314. * @param $reset
  315. * Whether to reset the internal node_load cache.
  316. *
  317. * @return
  318. * A fully-populated node object.
  319. */
  320. function node_load($param = array(), $revision = NULL, $reset = NULL) {
  321. static $nodes = array();
  322. if ($reset) {
  323. $nodes = array();
  324. }
  325. $cachable = ($revision == NULL);
  326. $arguments = array();
  327. if (is_numeric($param)) {
  328. if ($cachable && isset($nodes[$param])) {
  329. return is_object($nodes[$param]) ? drupal_clone($nodes[$param]) : $nodes[$param];
  330. }
  331. $cond = 'n.nid = %d';
  332. $arguments[] = $param;
  333. }
  334. else {
  335. // Turn the conditions into a query.
  336. foreach ($param as $key => $value) {
  337. $cond[] = 'n.'. db_escape_string($key) ." = '%s'";
  338. $arguments[] = $value;
  339. }
  340. $cond = implode(' AND ', $cond);
  341. }
  342. // Retrieve the node.
  343. // No db_rewrite_sql is applied so as to get complete indexing for search.
  344. if ($revision) {
  345. array_unshift($arguments, $revision);
  346. $node = db_fetch_object(db_query('SELECT n.nid, r.vid, n.type, n.status, n.created, n.changed, n.comment, n.promote, n.moderate, n.sticky, r.timestamp AS revision_timestamp, r.title, r.body, r.teaser, r.log, r.format, u.uid, u.name, u.picture, u.data 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));
  347. }
  348. else {
  349. $node = db_fetch_object(db_query('SELECT n.nid, n.vid, n.type, n.status, n.created, n.changed, n.comment, n.promote, n.moderate, n.sticky, r.timestamp AS revision_timestamp, r.title, r.body, r.teaser, r.log, r.format, u.uid, u.name, u.picture, u.data 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));
  350. }
  351. if ($node->nid) {
  352. // Call the node specific callback (if any) and piggy-back the
  353. // results to the node or overwrite some values.
  354. if ($extra = node_invoke($node, 'load')) {
  355. foreach ($extra as $key => $value) {
  356. $node->$key = $value;
  357. }
  358. }
  359. if ($extra = node_invoke_nodeapi($node, 'load')) {
  360. foreach ($extra as $key => $value) {
  361. $node->$key = $value;
  362. }
  363. }
  364. if ($cachable) {
  365. $nodes[$node->nid] = is_object($node) ? drupal_clone($node) : $node;
  366. }
  367. }
  368. return $node;
  369. }
  370. /**
  371. * Save a node object into the database.
  372. */
  373. function node_save(&$node) {
  374. global $user;
  375. $node->is_new = false;
  376. // Apply filters to some default node fields:
  377. if (empty($node->nid)) {
  378. // Insert a new node.
  379. $node->is_new = true;
  380. $node->nid = db_next_id('{node}_nid');
  381. $node->vid = db_next_id('{node_revisions}_vid');;
  382. }
  383. else {
  384. // We need to ensure that all node fields are filled.
  385. $node_current = node_load($node->nid);
  386. foreach ($node as $field => $data) {
  387. $node_current->$field = $data;
  388. }
  389. $node = $node_current;
  390. if ($node->revision) {
  391. $node->old_vid = $node->vid;
  392. $node->vid = db_next_id('{node_revisions}_vid');
  393. }
  394. }
  395. // Set some required fields:
  396. if (empty($node->created)) {
  397. $node->created = time();
  398. }
  399. // The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
  400. $node->changed = time();
  401. // Split off revisions data to another structure
  402. $revisions_table_values = array('nid' => $node->nid, 'vid' => $node->vid,
  403. 'title' => $node->title, 'body' => $node->body,
  404. 'teaser' => $node->teaser, 'log' => $node->log, 'timestamp' => $node->changed,
  405. 'uid' => $user->uid, 'format' => $node->format);
  406. $revisions_table_types = array('nid' => '%d', 'vid' => '%d',
  407. 'title' => "'%s'", 'body' => "'%s'",
  408. 'teaser' => "'%s'", 'log' => "'%s'", 'timestamp' => '%d',
  409. 'uid' => '%d', 'format' => '%d');
  410. $node_table_values = array('nid' => $node->nid, 'vid' => $node->vid,
  411. 'title' => $node->title, 'type' => $node->type, 'uid' => $node->uid,
  412. 'status' => $node->status, 'created' => $node->created,
  413. 'changed' => $node->changed, 'comment' => $node->comment,
  414. 'promote' => $node->promote, 'moderate' => $node->moderate,
  415. 'sticky' => $node->sticky);
  416. $node_table_types = array('nid' => '%d', 'vid' => '%d',
  417. 'title' => "'%s'", 'type' => "'%s'", 'uid' => '%d',
  418. 'status' => '%d', 'created' => '%d',
  419. 'changed' => '%d', 'comment' => '%d',
  420. 'promote' => '%d', 'moderate' => '%d',
  421. 'sticky' => '%d');
  422. //Generate the node table query and the
  423. //the node_revisions table query
  424. if ($node->is_new) {
  425. $node_query = 'INSERT INTO {node} ('. implode(', ', array_keys($node_table_types)) .') VALUES ('. implode(', ', $node_table_types) .')';
  426. $revisions_query = 'INSERT INTO {node_revisions} ('. implode(', ', array_keys($revisions_table_types)) .') VALUES ('. implode(', ', $revisions_table_types) .')';
  427. }
  428. else {
  429. $arr = array();
  430. foreach ($node_table_types as $key => $value) {
  431. $arr[] = $key .' = '. $value;
  432. }
  433. $node_table_values[] = $node->nid;
  434. $node_query = 'UPDATE {node} SET '. implode(', ', $arr) .' WHERE nid = %d';
  435. if ($node->revision) {
  436. $revisions_query = 'INSERT INTO {node_revisions} ('. implode(', ', array_keys($revisions_table_types)) .') VALUES ('. implode(', ', $revisions_table_types) .')';
  437. }
  438. else {
  439. $arr = array();
  440. foreach ($revisions_table_types as $key => $value) {
  441. $arr[] = $key .' = '. $value;
  442. }
  443. $revisions_table_values[] = $node->vid;
  444. $revisions_query = 'UPDATE {node_revisions} SET '. implode(', ', $arr) .' WHERE vid = %d';
  445. }
  446. }
  447. // Insert the node into the database:
  448. db_query($node_query, $node_table_values);
  449. db_query($revisions_query, $revisions_table_values);
  450. // Call the node specific callback (if any):
  451. if ($node->is_new) {
  452. node_invoke($node, 'insert');
  453. node_invoke_nodeapi($node, 'insert');
  454. }
  455. else {
  456. node_invoke($node, 'update');
  457. node_invoke_nodeapi($node, 'update');
  458. }
  459. // Clear the cache so an anonymous poster can see the node being added or updated.
  460. cache_clear_all();
  461. }
  462. /**
  463. * Generate a display of the given node.
  464. *
  465. * @param $node
  466. * A node array or node object.
  467. * @param $teaser
  468. * Whether to display the teaser only, as on the main page.
  469. * @param $page
  470. * Whether the node is being displayed by itself as a page.
  471. * @param $links
  472. * Whether or not to display node links. Links are omitted for node previews.
  473. *
  474. * @return
  475. * An HTML representation of the themed node.
  476. */
  477. function node_view($node, $teaser = FALSE, $page = FALSE, $links = TRUE) {
  478. $node = (object)$node;
  479. // Remove the delimiter (if any) that separates the teaser from the body.
  480. // TODO: this strips legitimate uses of '<!--break-->' also.
  481. $node->body = str_replace('<!--break-->', '', $node->body);
  482. if ($node->log != '' && !$teaser && $node->moderate) {
  483. $node->body .= '<div class="log"><div class="title">'. t('Log') .':</div>'. filter_xss($node->log) .'</div>';
  484. }
  485. // The 'view' hook can be implemented to overwrite the default function
  486. // to display nodes.
  487. if (node_hook($node, 'view')) {
  488. node_invoke($node, 'view', $teaser, $page);
  489. }
  490. else {
  491. $node = node_prepare($node, $teaser);
  492. }
  493. // Allow modules to change $node->body before viewing.
  494. node_invoke_nodeapi($node, 'view', $teaser, $page);
  495. if ($links) {
  496. $node->links = module_invoke_all('link', 'node', $node, !$page);
  497. }
  498. // unset unused $node part so that a bad theme can not open a security hole
  499. if ($teaser) {
  500. unset($node->body);
  501. }
  502. else {
  503. unset($node->teaser);
  504. }
  505. return theme('node', $node, $teaser, $page);
  506. }
  507. /**
  508. * Apply filters to a node in preparation for theming.
  509. */
  510. function node_prepare($node, $teaser = FALSE) {
  511. $node->readmore = (strlen($node->teaser) < strlen($node->body));
  512. if ($teaser == FALSE) {
  513. $node->body = check_markup($node->body, $node->format, FALSE);
  514. }
  515. else {
  516. $node->teaser = check_markup($node->teaser, $node->format, FALSE);
  517. }
  518. return $node;
  519. }
  520. /**
  521. * Generate a page displaying a single node, along with its comments.
  522. */
  523. function node_show($node, $cid) {
  524. $output = node_view($node, FALSE, TRUE);
  525. if (function_exists('comment_render') && $node->comment) {
  526. $output .= comment_render($node, $cid);
  527. }
  528. // Update the history table, stating that this user viewed this node.
  529. node_tag_new($node->nid);
  530. return $output;
  531. }
  532. /**
  533. * Implementation of hook_perm().
  534. */
  535. function node_perm() {
  536. return array('administer nodes', 'access content', 'view revisions', 'revert revisions');
  537. }
  538. /**
  539. * Implementation of hook_search().
  540. */
  541. function node_search($op = 'search', $keys = null) {
  542. switch ($op) {
  543. case 'name':
  544. return t('content');
  545. case 'reset':
  546. variable_del('node_cron_last');
  547. variable_del('node_cron_last_nid');
  548. return;
  549. case 'status':
  550. $last = variable_get('node_cron_last', 0);
  551. $last_nid = variable_get('node_cron_last_nid', 0);
  552. $total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1'));
  553. $remaining = db_result(db_query('SELECT COUNT(*) FROM {node} n LEFT JOIN {node_comment_statistics} c ON n.nid = c.nid WHERE n.status = 1 AND ((GREATEST(n.created, n.changed, c.last_comment_timestamp) = %d AND n.nid > %d ) OR (n.created > %d OR n.changed > %d OR c.last_comment_timestamp > %d))', $last, $last_nid, $last, $last, $last));
  554. return array('remaining' => $remaining, 'total' => $total);
  555. case 'admin':
  556. $form = array();
  557. // Output form for defining rank factor weights.
  558. $form['content_ranking'] = array('#type' => 'fieldset', '#title' => t('Content ranking'));
  559. $form['content_ranking']['#theme'] = 'node_search_admin';
  560. $form['content_ranking']['info'] = array('#type' => 'markup', '#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>');
  561. $ranking = array('node_rank_relevance' => t('Keyword relevance'),
  562. 'node_rank_recent' => t('Recently posted'));
  563. if (module_exist('comment')) {
  564. $ranking['node_rank_comments'] = t('Number of comments');
  565. }
  566. if (module_exist('statistics') && variable_get('statistics_count_content_views', 0)) {
  567. $ranking['node_rank_views'] = t('Number of views');
  568. }
  569. // Note: reversed to reflect that higher number = higher ranking.
  570. $options = drupal_map_assoc(range(0, 10));
  571. foreach ($ranking as $var => $title) {
  572. $form['content_ranking']['factors'][$var] = array('#title' => $title, '#type' => 'select', '#options' => $options, '#default_value' => variable_get($var, 5));
  573. }
  574. return $form;
  575. case 'search':
  576. // Build matching conditions
  577. list($join1, $where1) = _db_rewrite_sql();
  578. $arguments1 = array();
  579. $conditions1 = 'n.status = 1';
  580. if ($type = search_query_extract($keys, 'type')) {
  581. $types = array();
  582. foreach (explode(',', $type) as $t) {
  583. $types[] = "n.type = '%s'";
  584. $arguments1[] = $t;
  585. }
  586. $conditions1 .= ' AND ('. implode(' OR ', $types) .')';
  587. $keys = search_query_insert($keys, 'type');
  588. }
  589. if ($category = search_query_extract($keys, 'category')) {
  590. $categories = array();
  591. foreach (explode(',', $category) as $c) {
  592. $categories[] = "tn.tid = %d";
  593. $arguments1[] = $c;
  594. }
  595. $conditions1 .= ' AND ('. implode(' OR ', $categories) .')';
  596. $join1 .= ' INNER JOIN {term_node} tn ON n.nid = tn.nid';
  597. $keys = search_query_insert($keys, 'category');
  598. }
  599. // Build ranking expression (we try to map each parameter to a
  600. // uniform distribution in the range 0..1).
  601. $ranking = array();
  602. $arguments2 = array();
  603. $join2 = '';
  604. $total = 0;
  605. // Used to avoid joining on node_comment_statistics twice
  606. $stats_join = false;
  607. if ($weight = (int)variable_get('node_rank_relevance', 5)) {
  608. // Average relevance values hover around 0.15
  609. $ranking[] = '%d * i.relevance';
  610. $arguments2[] = $weight;
  611. $total += $weight;
  612. }
  613. if ($weight = (int)variable_get('node_rank_recent', 5)) {
  614. // Exponential decay with half-life of 6 months, starting at last indexed node
  615. $ranking[] = '%d * POW(2, (GREATEST(n.created, n.changed, c.last_comment_timestamp) - %d) * 6.43e-8)';
  616. $arguments2[] = $weight;
  617. $arguments2[] = (int)variable_get('node_cron_last', 0);
  618. $join2 .= ' INNER JOIN {node} n ON n.nid = i.sid LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
  619. $stats_join = true;
  620. $total += $weight;
  621. }
  622. if (module_exist('comment') && $weight = (int)variable_get('node_rank_comments', 5)) {
  623. // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
  624. $scale = variable_get('node_cron_comments_scale', 0.0);
  625. $ranking[] = '%d * (2.0 - 2.0 / (1.0 + c.comment_count * %f))';
  626. $arguments2[] = $weight;
  627. $arguments2[] = $scale;
  628. if (!$stats_join) {
  629. $join2 .= ' LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
  630. }
  631. $total += $weight;
  632. }
  633. if (module_exist('statistics') && variable_get('statistics_count_content_views', 0) &&
  634. $weight = (int)variable_get('node_rank_views', 5)) {
  635. // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
  636. $scale = variable_get('node_cron_views_scale', 0.0);
  637. $ranking[] = '%d * (2.0 - 2.0 / (1.0 + nc.totalcount * %f))';
  638. $arguments2[] = $weight;
  639. $arguments2[] = $scale;
  640. $join2 .= ' LEFT JOIN {node_counter} nc ON nc.nid = i.sid';
  641. $total += $weight;
  642. }
  643. $select2 = (count($ranking) ? implode(' + ', $ranking) : 'i.relevance') . ' AS score';
  644. // Do search
  645. $find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid '. $join1 .' INNER JOIN {users} u ON n.uid = u.uid', $conditions1 . (empty($where1) ? '' : ' AND '. $where1), $arguments1, $select2, $join2, $arguments2);
  646. // Load results
  647. $results = array();
  648. foreach ($find as $item) {
  649. $node = node_load($item->sid);
  650. // Get node output (filtered and with module-specific fields).
  651. if (node_hook($node, 'view')) {
  652. node_invoke($node, 'view', false, false);
  653. }
  654. else {
  655. $node = node_prepare($node, false);
  656. }
  657. // Allow modules to change $node->body before viewing.
  658. node_invoke_nodeapi($node, 'view', false, false);
  659. // Fetch comments for snippet
  660. $node->body .= module_invoke('comment', 'nodeapi', $node, 'update index');
  661. // Fetch terms for snippet
  662. $node->body .= module_invoke('taxonomy', 'nodeapi', $node, 'update index');
  663. $extra = node_invoke_nodeapi($node, 'search result');
  664. $results[] = array('link' => url('node/'. $item->sid),
  665. 'type' => node_get_name($node),
  666. 'title' => $node->title,
  667. 'user' => theme('username', $node),
  668. 'date' => $node->changed,
  669. 'node' => $node,
  670. 'extra' => $extra,
  671. 'score' => $item->score / $total,
  672. 'snippet' => search_excerpt($keys, $node->body));
  673. }
  674. return $results;
  675. }
  676. }
  677. /**
  678. * Implementation of hook_user().
  679. */
  680. function node_user($op, &$edit, &$user) {
  681. if ($op == 'delete') {
  682. db_query('UPDATE {node} SET uid = 0 WHERE uid = %d', $user->uid);
  683. db_query('UPDATE {node_revisions} SET uid = 0 WHERE uid = %d', $user->uid);
  684. }
  685. }
  686. function theme_node_search_admin($form) {
  687. $output = form_render($form['info']);
  688. $header = array(t('Factor'), t('Weight'));
  689. foreach (element_children($form['factors']) as $key) {
  690. $row = array();
  691. $row[] = $form['factors'][$key]['#title'];
  692. unset($form['factors'][$key]['#title']);
  693. $row[] = form_render($form['factors'][$key]);
  694. $rows[] = $row;
  695. }
  696. $output .= theme('table', $header, $rows);
  697. $output .= form_render($form);
  698. return $output;
  699. }
  700. /**
  701. * Menu callback; presents general node configuration options.
  702. */
  703. function node_configure() {
  704. $form['default_nodes_main'] = array(
  705. '#type' => 'select', '#title' => t('Number of posts on main page'), '#default_value' => variable_get('default_nodes_main', 10),
  706. '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30)),
  707. '#description' => t('The default maximum number of posts to display per page on overview pages such as the main page.')
  708. );
  709. $form['teaser_length'] = array(
  710. '#type' => 'select', '#title' => t('Length of trimmed posts'), '#default_value' => variable_get('teaser_length', 600),
  711. '#options' => array(0 => t('Unlimited'), 200 => t('200 characters'), 400 => t('400 characters'), 600 => t('600 characters'),
  712. 800 => t('800 characters'), 1000 => t('1000 characters'), 1200 => t('1200 characters'), 1400 => t('1400 characters'),
  713. 1600 => t('1600 characters'), 1800 => t('1800 characters'), 2000 => t('2000 characters')),
  714. '#description' => t("The maximum number of characters used in the trimmed version of a post. Drupal will use this setting to determine at which offset long posts should be trimmed. The trimmed version of a post is typically used as a teaser when displaying the post on the main page, in XML feeds, etc. To disable teasers, set to 'Unlimited'. Note that this setting will only affect new or updated content and will not affect existing teasers.")
  715. );
  716. $form['node_preview'] = array(
  717. '#type' => 'radios', '#title' => t('Preview post'), '#default_value' => variable_get('node_preview', 0),
  718. '#options' => array(t('Optional'), t('Required')), '#description' => t('Must users preview posts before submitting?')
  719. );
  720. return system_settings_form('node_configure', $form);
  721. }
  722. /**
  723. * Retrieve the comment mode for the given node ID (none, read, or read/write).
  724. */
  725. function node_comment_mode($nid) {
  726. static $comment_mode;
  727. if (!isset($comment_mode[$nid])) {
  728. $comment_mode[$nid] = db_result(db_query('SELECT comment FROM {node} WHERE nid = %d', $nid));
  729. }
  730. return $comment_mode[$nid];
  731. }
  732. /**
  733. * Implementation of hook_link().
  734. */
  735. function node_link($type, $node = 0, $main = 0) {
  736. $links = array();
  737. if ($type == 'node') {
  738. if ($main == 1 && $node->teaser && $node->readmore) {
  739. $links[] = l(t('read more'), "node/$node->nid", array('title' => t('Read the rest of this posting.'), 'class' => 'read-more'));
  740. }
  741. }
  742. return $links;
  743. }
  744. /**
  745. * Implementation of hook_menu().
  746. */
  747. function node_menu($may_cache) {
  748. $items = array();
  749. if ($may_cache) {
  750. $items[] = array('path' => 'admin/node', 'title' => t('content'),
  751. 'callback' => 'node_admin_nodes',
  752. 'access' => user_access('administer nodes'));
  753. $items[] = array('path' => 'admin/node/overview', 'title' => t('list'),
  754. 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
  755. if (module_exist('search')) {
  756. $items[] = array('path' => 'admin/node/search', 'title' => t('search'),
  757. 'callback' => 'node_admin_search',
  758. 'access' => user_access('administer nodes'),
  759. 'type' => MENU_LOCAL_TASK);
  760. }
  761. $items[] = array('path' => 'admin/settings/node', 'title' => t('posts'),
  762. 'callback' => 'node_configure',
  763. 'access' => user_access('administer nodes'));
  764. $items[] = array('path' => 'admin/settings/content-types', 'title' => t('content types'),
  765. 'callback' => 'node_types_configure',
  766. 'access' => user_access('administer nodes'));
  767. $items[] = array('path' => 'node', 'title' => t('content'),
  768. 'callback' => 'node_page',
  769. 'access' => user_access('access content'),
  770. 'type' => MENU_MODIFIABLE_BY_ADMIN);
  771. $items[] = array('path' => 'node/add', 'title' => t('create content'),
  772. 'callback' => 'node_page',
  773. 'access' => user_access('access content'),
  774. 'type' => MENU_ITEM_GROUPING,
  775. 'weight' => 1);
  776. $items[] = array('path' => 'rss.xml', 'title' => t('rss feed'),
  777. 'callback' => 'node_feed',
  778. 'access' => user_access('access content'),
  779. 'type' => MENU_CALLBACK);
  780. }
  781. else {
  782. if (arg(0) == 'node' && is_numeric(arg(1))) {
  783. $node = node_load(arg(1));
  784. if ($node->nid) {
  785. $items[] = array('path' => 'node/'. arg(1), 'title' => t('view'),
  786. 'callback' => 'node_page',
  787. 'access' => node_access('view', $node),
  788. 'type' => MENU_CALLBACK);
  789. $items[] = array('path' => 'node/'. arg(1) .'/view', 'title' => t('view'),
  790. 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
  791. $items[] = array('path' => 'node/'. arg(1) .'/edit', 'title' => t('edit'),
  792. 'callback' => 'node_page',
  793. 'access' => node_access('update', $node),
  794. 'weight' => 1,
  795. 'type' => MENU_LOCAL_TASK);
  796. $items[] = array('path' => 'node/'. arg(1) .'/delete', 'title' => t('delete'),
  797. 'callback' => 'node_delete_confirm',
  798. 'access' => node_access('delete', $node),
  799. 'weight' => 1,
  800. 'type' => MENU_CALLBACK);
  801. $revisions_access = ((user_access('view revisions') || user_access('administer nodes')) && node_access('view', $node) && db_result(db_query('SELECT COUNT(vid) FROM {node_revisions} WHERE nid = %d', arg(1))) > 1);
  802. $items[] = array('path' => 'node/'. arg(1) .'/revisions', 'title' => t('revisions'),
  803. 'callback' => 'node_revisions',
  804. 'access' => $revisions_access,
  805. 'weight' => 2,
  806. 'type' => MENU_LOCAL_TASK);
  807. $items[] = array('path' => 'node/'. arg(1) .'/revisions/' . arg(3) . '/delete',
  808. 'title' => t('revisions'),
  809. 'callback' => 'node_revisions',
  810. 'access' => $revisions_access,
  811. 'weight' => 2,
  812. 'type' => MENU_CALLBACK);
  813. $items[] = array('path' => 'node/'. arg(1) .'/revisions/' . arg(3) . '/revert',
  814. 'title' => t('revisions'),
  815. 'callback' => 'node_revisions',
  816. 'access' => $revisions_access,
  817. 'weight' => 2,
  818. 'type' => MENU_CALLBACK);
  819. }
  820. }
  821. else if (arg(0) == 'admin' && arg(1) == 'settings' && arg(2) == 'content-types' && is_string(arg(3))) {
  822. $items[] = array('path' => 'admin/settings/content-types/'. arg(3),
  823. 'title' => t("'%name' content type", array('%name' => node_get_name(arg(3)))),
  824. 'type' => MENU_CALLBACK);
  825. }
  826. }
  827. return $items;
  828. }
  829. function node_last_changed($nid) {
  830. $node = db_fetch_object(db_query('SELECT changed FROM {node} WHERE nid = %d', $nid));
  831. return ($node->changed);
  832. }
  833. /**
  834. * List node administration operations that can be performed.
  835. */
  836. function node_operations() {
  837. $operations = array(
  838. 'approve' => array(t('Approve the selected posts'), 'UPDATE {node} SET status = 1, moderate = 0 WHERE nid = %d'),
  839. 'promote' => array(t('Promote the selected posts'), 'UPDATE {node} SET status = 1, promote = 1, moderate = 0 WHERE nid = %d'),
  840. 'sticky' => array(t('Make the selected posts sticky'), 'UPDATE {node} SET status = 1, sticky = 1 WHERE nid = %d'),
  841. 'demote' => array(t('Demote the selected posts'), 'UPDATE {node} SET promote = 0 WHERE nid = %d'),
  842. 'unpublish' => array(t('Unpublish the selected posts'), 'UPDATE {node} SET status = 0 WHERE nid = %d'),
  843. 'delete' => array(t('Delete the selected posts'), '')
  844. );
  845. return $operations;
  846. }
  847. /**
  848. * List node administration filters that can be applied.
  849. */
  850. function node_filters() {
  851. // Regular filters
  852. $filters['status'] = array('title' => t('status'),
  853. 'options' => array('status-1' => t('published'), 'status-0' => t('not published'),
  854. 'moderate-1' => t('in moderation'), 'moderate-0' => t('not in moderation'),
  855. 'promote-1' => t('promoted'), 'promote-0' => t('not promoted'),
  856. 'sticky-1' => t('sticky'), 'sticky-0' => t('not sticky')));
  857. $filters['type'] = array('title' => t('type'), 'options' => node_get_types());
  858. // The taxonomy filter
  859. if ($taxonomy = module_invoke('taxonomy', 'form_all', 1)) {
  860. $filters['category'] = array('title' => t('category'), 'options' => $taxonomy);
  861. }
  862. return $filters;
  863. }
  864. /**
  865. * Build query for node administration filters based on session.
  866. */
  867. function node_build_filter_query() {
  868. $filters = node_filters();
  869. // Build query
  870. $where = $args = array();
  871. $join = '';
  872. foreach ($_SESSION['node_overview_filter'] as $index => $filter) {
  873. list($key, $value) = $filter;
  874. switch($key) {
  875. case 'status':
  876. // Note: no exploitable hole as $key/$value have already been checked when submitted
  877. list($key, $value) = explode('-', $value, 2);
  878. $where[] = 'n.'. $key .' = %d';
  879. break;
  880. case 'category':
  881. $table = "tn$index";
  882. $where[] = "$table.tid = %d";
  883. $join .= "INNER JOIN {term_node} $table ON n.nid = $table.nid ";
  884. break;
  885. case 'type':
  886. $where[] = "n.type = '%s'";
  887. }
  888. $args[] = $value;
  889. }
  890. $where = count($where) ? 'WHERE '. implode(' AND ', $where) : '';
  891. return array('where' => $where, 'join' => $join, 'args' => $args);
  892. }
  893. /**
  894. * Return form for node administration filters.
  895. */
  896. function node_filter_form() {
  897. $session = &$_SESSION['node_overview_filter'];
  898. $session = is_array($session) ? $session : array();
  899. $filters = node_filters();
  900. $i = 0;
  901. $form['filters'] = array('#type' => 'fieldset',
  902. '#title' => t('Show only items where'),
  903. '#theme' => 'node_filters',
  904. );
  905. foreach ($session as $filter) {
  906. list($type, $value) = $filter;
  907. if ($type == 'category') {
  908. // Load term name from DB rather than search and parse options array.
  909. $value = module_invoke('taxonomy', 'get_term', $value);
  910. $value = $value->name;
  911. }
  912. else {
  913. $value = $filters[$type]['options'][$value];
  914. }
  915. $string = ($i++ ? '<em>and</em> where <strong>%a</strong> is <strong>%b</strong>' : '<strong>%a</strong> is <strong>%b</strong>');
  916. $form['filters']['current'][] = array('#value' => t($string, array('%a' => $filters[$type]['title'] , '%b' => $value)));
  917. }
  918. foreach ($filters as $key => $filter) {
  919. $names[$key] = $filter['title'];
  920. $form['filters']['status'][$key] = array('#type' => 'select', '#options' => $filter['options']);
  921. }
  922. $form['filters']['filter'] = array('#type' => 'radios', '#options' => $names, '#default_value' => 'status');
  923. $form['filters']['buttons']['submit'] = array('#type' => 'submit', '#value' => (count($session) ? t('Refine') : t('Filter')));
  924. if (count($session)) {
  925. $form['filters']['buttons']['undo'] = array('#type' => 'submit', '#value' => t('Undo'));
  926. $form['filters']['buttons']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
  927. }
  928. return drupal_get_form('node_filter_form', $form);
  929. }
  930. /**
  931. * Theme node administration filter form.
  932. */
  933. function theme_node_filter_form(&$form) {
  934. $output .= '<div id="node-admin-filter">';
  935. $output .= form_render($form['filters']);
  936. $output .= '</div>';
  937. $output .= form_render($form);
  938. return $output;
  939. }
  940. /**
  941. * Theme node administraton filter selector.
  942. */
  943. function theme_node_filters(&$form) {
  944. $output .= '<ul>';
  945. if (sizeof($form['current'])) {
  946. foreach (element_children($form['current']) as $key) {
  947. $output .= '<li>' . form_render($form['current'][$key]) . '</li>';
  948. }
  949. }
  950. $output .= '<li><dl class="multiselect">' . (sizeof($form['current']) ? '<dt><em>'. t('and') .'</em> '. t('where') .'</dt>' : '') . '<dd class="a">';
  951. foreach (element_children($form['filter']) as $key) {
  952. $output .= form_render($form['filter'][$key]);
  953. }
  954. $output .= '</dd>';
  955. $output .= '<dt>'. t('is') .'</dt>' . '<dd class="b">';
  956. foreach (element_children($form['status']) as $key) {
  957. $output .= form_render($form['status'][$key]);
  958. }
  959. $output .= '</dd>';
  960. $output .= '</dl>';
  961. $output .= '<div class="container-inline" id="node-admin-buttons">'. form_render($form['buttons']) .'</div>';
  962. $output .= '</li></ul><br class="clear" />';
  963. return $output;
  964. }
  965. /**
  966. * Process result from node administration filter form.
  967. */
  968. function node_filter_form_submit() {
  969. global $form_values;
  970. $op = $_POST['op'];
  971. $filters = node_filters();
  972. switch ($op) {
  973. case t('Filter'):
  974. case t('Refine'):
  975. if (isset($form_values['filter'])) {
  976. $filter = $form_values['filter'];
  977. // Flatten the options array to accommodate hierarchical/nested options.
  978. $flat_options = form_options_flatten($filters[$filter]['options']);
  979. if (isset($flat_options[$form_values[$filter]])) {
  980. $_SESSION['node_overview_filter'][] = array($filter, $form_values[$filter]);
  981. }
  982. }
  983. break;
  984. case t('Undo'):
  985. array_pop($_SESSION['node_overview_filter']);
  986. break;
  987. case t('Reset'):
  988. $_SESSION['node_overview_filter'] = array();
  989. break;
  990. }
  991. }
  992. /**
  993. * Generate the content administration overview.
  994. */
  995. function node_admin_nodes_submit($form_id, $edit) {
  996. $operations = node_operations();
  997. if ($operations[$edit['operation']][1]) {
  998. // Flag changes
  999. $operation = $operations[$edit['operation']][1];
  1000. foreach ($edit['nodes'] as $nid => $value) {
  1001. if ($value) {
  1002. db_query($operation, $nid);
  1003. }
  1004. }
  1005. cache_clear_all();
  1006. drupal_set_message(t('The update has been performed.'));
  1007. }
  1008. }
  1009. function node_admin_nodes_validate($form_id, $edit) {
  1010. $edit['nodes'] = array_diff($edit['nodes'], array(0));
  1011. if (count($edit['nodes']) == 0) {
  1012. if ($edit['operation'] == 'delete') {
  1013. form_set_error('', t('Please select some items to perform the delete operation.'));
  1014. }
  1015. else {
  1016. form_set_error('', t('Please select some items to perform the update on.'));
  1017. }
  1018. }
  1019. }
  1020. /**
  1021. * Menu callback: content administration.
  1022. */
  1023. function node_admin_nodes() {
  1024. global $form_values;
  1025. $output = node_filter_form();
  1026. if ($_POST['edit']['operation'] == 'delete' && $_POST['edit']['nodes']) {
  1027. return node_multiple_delete_confirm();
  1028. }
  1029. $filter = node_build_filter_query();
  1030. $result = pager_query('SELECT n.*, u.name, u.uid FROM {node} n '. $filter['join'] .' INNER JOIN {users} u ON n.uid = u.uid '. $filter['where'] .' ORDER BY n.changed DESC', 50, 0, NULL, $filter['args']);
  1031. $form['options'] = array('#type' => 'fieldset',
  1032. '#title' => t('Update options'),
  1033. '#prefix' => '<div class="container-inline">',
  1034. '#suffix' => '</div>',
  1035. );
  1036. $options = array();
  1037. foreach (node_operations() as $key => $value) {
  1038. $options[$key] = $value[0];
  1039. }
  1040. $form['options']['operation'] = array('#type' => 'select', '#options' => $options, '#default_value' => 'approve');
  1041. $form['options']['submit'] = array('#type' => 'submit', '#value' => t('Update'));
  1042. $destination = drupal_get_destination();
  1043. while ($node = db_fetch_object($result)) {
  1044. $nodes[$node->nid] = '';
  1045. $form['title'][$node->nid] = array('#value' => l($node->title, 'node/'. $node->nid) .' '. theme('mark', node_mark($node->nid, $node->changed)));
  1046. $form['name'][$node->nid] = array('#value' => node_get_name($node));
  1047. $form['username'][$node->nid] = array('#value' => theme('username', $node));
  1048. $form['status'][$node->nid] = array('#value' => ($node->status ? t('published') : t('not published')));
  1049. $form['operations'][$node->nid] = array('#value' => l(t('edit'), 'node/'. $node->nid .'/edit', array(), $destination));
  1050. }
  1051. $form['nodes'] = array('#type' => 'checkboxes', '#options' => $nodes);
  1052. $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
  1053. // Call the form first, to allow for the form_values array to be populated.
  1054. $output .= drupal_get_form('node_admin_nodes', $form);
  1055. return $output;
  1056. }
  1057. /**
  1058. * Theme node administration overview.
  1059. */
  1060. function theme_node_admin_nodes($form) {
  1061. // Overview table:
  1062. $header = array(NULL, t('Title'), t('Type'), t('Author'), t('Status'), t('Operations'));
  1063. $output .= form_render($form['options']);
  1064. if (isset($form['title']) && is_array($form['title'])) {
  1065. foreach (element_children($form['title']) as $key) {
  1066. $row = array();
  1067. $row[] = form_render($form['nodes'][$key]);
  1068. $row[] = form_render($form['title'][$key]);
  1069. $row[] = form_render($form['name'][$key]);
  1070. $row[] = form_render($form['username'][$key]);
  1071. $row[] = form_render($form['status'][$key]);
  1072. $row[] = form_render($form['operations'][$key]);
  1073. $rows[] = $row;
  1074. }
  1075. }
  1076. else {
  1077. $rows[] = array(array('data' => t('No posts available.'), 'colspan' => '6'));
  1078. }
  1079. $output .= theme('table', $header, $rows);
  1080. if ($form['pager']['#value']) {
  1081. $output .= form_render($form['pager']);
  1082. }
  1083. $output .= form_render($form);
  1084. return $output;
  1085. }
  1086. function node_multiple_delete_confirm() {
  1087. $edit = $_POST['edit'];
  1088. $form['nodes'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  1089. // array_filter returns only elements with true values
  1090. foreach (array_filter($edit['nodes']) as $nid => $value) {
  1091. $title = db_result(db_query('SELECT title FROM {node} WHERE nid = %d', $nid));
  1092. $form['nodes'][$nid] = array('#type' => 'hidden', '#value' => $nid, '#prefix' => '<li>', '#suffix' => check_plain($title) ."</li>\n");
  1093. }
  1094. $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
  1095. return confirm_form('node_multiple_delete_confirm', $form,
  1096. t('Are you sure you want to delete these items?'),
  1097. 'admin/node', t('This action cannot be undone.'),
  1098. t('Delete all'), t('Cancel'));
  1099. }
  1100. function node_multiple_delete_confirm_submit($form_id, $edit) {
  1101. if ($edit['confirm']) {
  1102. foreach ($edit['nodes'] as $nid => $value) {
  1103. node_delete($nid);
  1104. }
  1105. drupal_set_message(t('The items have been deleted.'));
  1106. }
  1107. return 'admin/node';
  1108. }
  1109. /**
  1110. * Menu callback; presents each node type configuration page.
  1111. */
  1112. function node_types_configure($type = NULL) {
  1113. if (isset($type)) {
  1114. $node = new stdClass();
  1115. $node->type = $type;
  1116. $form['submission'] = array('#type' => 'fieldset', '#title' =>t('Submission form') );
  1117. $form['submission'][$type . '_help'] = array(
  1118. '#type' => 'textarea', '#title' => t('Explanation or submission guidelines'), '#default_value' => variable_get($type .'_help', ''),
  1119. '#description' => t('This text will be displayed at the top of the %type submission form. It is useful for helping or instructing your users.', array('%type' => node_get_name($type)))
  1120. );
  1121. $form['submission']['minimum_'. $type .'_size'] = array(
  1122. '#type' => 'select', '#title' => t('Minimum number of words'), '#default_value' => variable_get('minimum_'. $type .'_size', 0), '#options' => drupal_map_assoc(array(0, 10, 25, 50, 75, 100, 125, 150, 175, 200)),
  1123. '#description' => t('The minimum number of words a %type must be to be considered valid. This can be useful to rule out submissions that do not meet the site\'s standards, such as short test posts.', array('%type' => node_get_name($type)))
  1124. );
  1125. $form['workflow'] = array('#type' => 'fieldset', '#title' =>t('Workflow'));
  1126. $form['type'] = array('#type' => 'value', '#value' => $type);
  1127. $form['array_filter'] = array('#type' => 'value', '#value' => TRUE);
  1128. return system_settings_form($type .'_node_settings', $form);
  1129. }
  1130. else {
  1131. $header = array(t('Type'), t('Operations'));
  1132. $rows = array();
  1133. foreach (node_get_types() as $type => $name) {
  1134. $rows[] = array($name, l(t('configure'), 'admin/settings/content-types/'. $type));
  1135. }
  1136. return theme('table', $header, $rows);
  1137. }
  1138. }
  1139. /**
  1140. * Generate an overview table of older revisions of a node.
  1141. */
  1142. function node_revision_overview($node) {
  1143. drupal_set_title(t('Revisions for %title', array('%title' => check_plain($node->title))));
  1144. $header = array(t('Revision'), array('data' => t('Operations'), 'colspan' => 2));
  1145. $revisions = node_revision_list($node);
  1146. $rows = array();
  1147. $revert_permission = FALSE;
  1148. if ((user_access('revert revisions') || user_access('administer nodes')) && node_access('update', $node)) {
  1149. $revert_permission = TRUE;
  1150. }
  1151. $delete_permission = FALSE;
  1152. if (user_access('administer nodes')) {
  1153. $delete_permission = TRUE;
  1154. }
  1155. foreach ($revisions as $revision) {
  1156. $row = array();
  1157. $operations = array();
  1158. if ($revision->current_vid > 0) {
  1159. $row[] = array('data' => t('%date by %username', array('%date' => l(format_date($revision->timestamp, 'small'), "node/$node->nid"), '%username' => theme('username', $revision)))
  1160. . (($revision->log != '') ? '<p class="revision-log">'. filter_xss($revision->log) .'</p>' : ''),
  1161. 'class' => 'revision-current');
  1162. $operations[] = array('data' => theme('placeholder', t('current revision')), 'class' => 'revision-current', 'colspan' => 2);
  1163. }
  1164. else {
  1165. $row[] = t('%date by %username', array('%date' => l(format_date($revision->timestamp, 'small'), "node/$node->nid/revisions/$revision->vid/view"), '%username' => theme('username', $revision)))
  1166. . (($revision->log != '') ? '<p class="revision-log">'. filter_xss($revision->log) .'</p>' : '');
  1167. if ($revert_permission) {
  1168. $operations[] = l(t('revert'), "node/$node->nid/revisions/$revision->vid/revert");
  1169. }
  1170. if ($delete_permission) {
  1171. $operations[] = l(t('delete'), "node/$node->nid/revisions/$revision->vid/delete");
  1172. }
  1173. }
  1174. $rows[] = array_merge($row, $operations);
  1175. }
  1176. $output .= theme('table', $header, $rows);
  1177. return $output;
  1178. }
  1179. /**
  1180. * Revert to the revision with the specified revision number. A node and nodeapi "update" event is triggered
  1181. * (via the node_save() call) when a revision is reverted.
  1182. */
  1183. function node_revision_revert($nid, $revision) {
  1184. global $user;
  1185. $node = node_load($nid, $revision);
  1186. if ((user_access('revert revisions') || user_access('administer nodes')) && node_access('update', $node)) {
  1187. if ($node->vid) {
  1188. $form = array();
  1189. $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
  1190. $form['vid'] = array('#type' => 'value', '#value' => $node->vid);
  1191. return confirm_form('node_revision_revert_confirm', $form,
  1192. t('Are you sure you want to revert %title to the revision from %revision-date?', array('%title' => theme('placeholder', $node->title), '%revision-date' => theme('placeholder', format_date($node->revision_timestamp)))),
  1193. "node/$nid/revisions", ' ', t('Revert'), t('Cancel'));
  1194. }
  1195. else {
  1196. drupal_set_message(t('You tried to revert to an invalid revision.'), 'error');
  1197. }
  1198. drupal_goto('node/'. $nid .'/revisions');
  1199. }
  1200. drupal_access_denied();
  1201. }
  1202. function node_revision_revert_confirm_submit($form_id, $form_values) {
  1203. $nid = $form_values['nid'];
  1204. $revision = $form_values['vid'];
  1205. $node = node_load($nid, $revision);
  1206. $node->revision = 1;
  1207. $node->log = t('Copy of the revision from %date.', array('%date' => theme('placeholder', format_date($node->revision_timestamp))));
  1208. if (module_exist('taxonomy')) {
  1209. $node->taxonomy = array_keys($node->taxonomy);
  1210. }
  1211. node_save($node);
  1212. drupal_set_message(t('%title has been reverted back to the revision from %revision-date', array('%revision-date' => theme('placeholder', format_date($node->revision_timestamp)), '%title' => theme('placeholder', check_plain($node->title)))));
  1213. watchdog('content', t('%type: reverted %title revision %revision.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title), '%revision' => theme('placeholder', $revision))));
  1214. return 'node/'. $nid .'/revisions';
  1215. }
  1216. /**
  1217. * Delete the revision with specified revision number. A "delete revision" nodeapi event is invoked when a
  1218. * revision is deleted.
  1219. */
  1220. function node_revision_delete($nid, $revision) {
  1221. if (user_access('administer nodes')) {
  1222. $node = node_load($nid);
  1223. if (node_access('delete', $node)) {
  1224. // Don't delete the current revision
  1225. if ($revision != $node->vid) {
  1226. $node = node_load($nid, $revision);
  1227. $form = array();
  1228. $form['nid'] = array('#type' => 'value', '#value' => $nid);
  1229. $form['vid'] = array('#type' => 'value', '#value' => $revision);
  1230. return confirm_form('node_revision_delete_confirm', $form,
  1231. t('Are you sure you want to delete %title revision %revision?', array('%title' => theme('placeholder', $node->title), '%revision' => theme('placeholder', $revision))),
  1232. "node/$nid/revisions", '', t('Delete'), t('Cancel'));
  1233. }
  1234. else {
  1235. drupal_set_message(t('Deletion failed. You tried to delete the current revision.'));
  1236. }
  1237. if (db_result(db_query('SELECT COUNT(vid) FROM {node_revisions} WHERE nid = %d', $nid)) > 1) {
  1238. drupal_goto("node/$nid/revisions");
  1239. }
  1240. else {
  1241. drupal_goto("node/$nid");
  1242. }
  1243. }
  1244. }
  1245. drupal_access_denied();
  1246. }
  1247. function node_revision_delete_confirm_submit($form_id, $form_values) {
  1248. $node = node_load($form_values['nid'], $form_values['vid']);
  1249. db_query("DELETE FROM {node_revisions} WHERE nid = %d AND vid = %d", $node->nid, $node->vid);
  1250. node_invoke_nodeapi($node, 'delete revision');
  1251. drupal_set_message(t('Deleted %title revision %revision.', array('%title' => theme('placeholder', $node->title), '%revision' => theme('placeholder', $node->vid))));
  1252. watchdog('content', t('%type: deleted %title revision %revision.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title), '%revision' => theme('placeholder', $node->revision))));
  1253. if (db_result(db_query('SELECT COUNT(vid) FROM {node_revisions} WHERE nid = %d', $node->nid)) > 1) {
  1254. return "node/$node->nid/revisions";
  1255. }
  1256. return "node/$node->nid";
  1257. }
  1258. /**
  1259. * Return a list of all the existing revision numbers.
  1260. */
  1261. function node_revision_list($node) {
  1262. $revisions = array();
  1263. $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.timestamp DESC', $node->nid);
  1264. while ($revision = db_fetch_object($result)) {
  1265. $revisions[] = $revision;
  1266. }
  1267. return $revisions;
  1268. }
  1269. function node_admin_search() {
  1270. $output = search_form(url('admin/node/search'), $_POST['edit']['keys'], 'node') . search_data($_POST['edit']['keys'], 'node');
  1271. return $output;
  1272. }
  1273. /**
  1274. * Implementation of hook_block().
  1275. */
  1276. function node_block($op = 'list', $delta = 0) {
  1277. if ($op == 'list') {
  1278. $blocks[0]['info'] = t('Syndicate');
  1279. return $blocks;
  1280. }
  1281. else if ($op == 'view') {
  1282. $block['subject'] = t('Syndicate');
  1283. $block['content'] = theme('feed_icon', url('rss.xml'));
  1284. return $block;
  1285. }
  1286. }
  1287. /**
  1288. * A generic function for generating RSS feeds from a set of nodes.
  1289. *
  1290. * @param $nodes
  1291. * An object as returned by db_query() which contains the nid field.
  1292. * @param $channel
  1293. * An associative array containing title, link, description and other keys.
  1294. * The link should be an absolute URL.
  1295. */
  1296. function node_feed($nodes = 0, $channel = array()) {
  1297. global $base_url, $locale;
  1298. if (!$nodes) {
  1299. $nodes = 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));
  1300. }
  1301. $item_length = variable_get('feed_item_length', 'teaser');
  1302. $namespaces = array('xmlns:dc="http://purl.org/dc/elements/1.1/"');
  1303. while ($node = db_fetch_object($nodes)) {
  1304. // Load the specified node:
  1305. $item = node_load($node->nid);
  1306. $link = url("node/$node->nid", NULL, NULL, 1);
  1307. if ($item_length != 'title') {
  1308. $teaser = ($item_length == 'teaser') ? TRUE : FALSE;
  1309. // Filter and prepare node teaser
  1310. if (node_hook($item, 'view')) {
  1311. node_invoke($item, 'view', $teaser, FALSE);
  1312. }
  1313. else {
  1314. $item = node_prepare($item, $teaser);
  1315. }
  1316. // Allow modules to change $node->teaser before viewing.
  1317. node_invoke_nodeapi($item, 'view', $teaser, FALSE);
  1318. }
  1319. // Allow modules to add additional item fields
  1320. $extra = node_invoke_nodeapi($item, 'rss item');
  1321. $extra = array_merge($extra, array(array('key' => 'pubDate', 'value' => date('r', $item->created)), array('key' => 'dc:creator', 'value' => $item->name), array('key' => 'guid', 'value' => $item->nid . ' at ' . $base_url, 'attributes' => array('isPermaLink' => 'false'))));
  1322. foreach ($extra as $element) {
  1323. if ($element['namespace']) {
  1324. $namespaces = array_merge($namespaces, $element['namespace']);
  1325. }
  1326. }
  1327. // Prepare the item description
  1328. switch ($item_length) {
  1329. case 'fulltext':
  1330. $item_text = $item->body;
  1331. break;
  1332. case 'teaser':
  1333. $item_text = $item->teaser;
  1334. if ($item->readmore) {
  1335. $item_text .= '<p>'. l(t('read more'), 'node/'. $item->nid, NULL, NULL, NULL, TRUE) .'</p>';
  1336. }
  1337. break;
  1338. case 'title':
  1339. $item_text = '';
  1340. break;
  1341. }
  1342. $items .= format_rss_item($item->title, $link, $item_text, $extra);
  1343. }
  1344. $channel_defaults = array(
  1345. 'version' => '2.0',
  1346. 'title' => variable_get('site_name', 'drupal') .' - '. variable_get('site_slogan', ''),
  1347. 'link' => $base_url,
  1348. 'description' => variable_get('site_mission', ''),
  1349. 'language' => $locale
  1350. );
  1351. $channel = array_merge($channel_defaults, $channel);
  1352. $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  1353. $output .= "<rss version=\"". $channel["version"] . "\" xml:base=\"". $base_url ."\" ". implode(' ', $namespaces) .">\n";
  1354. $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language']);
  1355. $output .= "</rss>\n";
  1356. drupal_set_header('Content-Type: application/rss+xml; charset=utf-8');
  1357. print $output;
  1358. }
  1359. /**
  1360. * Prepare node for save and allow modules to make changes.
  1361. */
  1362. function node_submit($node) {
  1363. global $user;
  1364. // Convert the node to an object, if necessary.
  1365. $node = (object)$node;
  1366. // Auto-generate the teaser, but only if it hasn't been set (e.g. by a
  1367. // module-provided 'teaser' form item).
  1368. if (!isset($node->teaser)) {
  1369. $node->teaser = isset($node->body) ? node_teaser($node->body, isset($node->format) ? $node->format : NULL) : '';
  1370. }
  1371. $access = user_access('administer nodes');
  1372. if ($access) {
  1373. // Populate the "authored by" field.
  1374. if ($account = user_load(array('name' => $node->name))) {
  1375. $node->uid = $account->uid;
  1376. }
  1377. else {
  1378. $node->uid = 0;
  1379. }
  1380. $node->created = $node->date ? strtotime($node->date) : NULL;
  1381. }
  1382. // Force defaults in case people modify the form:
  1383. $node_options = variable_get('node_options_'. $node->type, array('status', 'promote'));
  1384. foreach (array('status', 'moderate', 'promote', 'sticky', 'revision') as $key) {
  1385. if (!$access || !isset($node->$key)) {
  1386. $node->$key = in_array($key, $node_options);
  1387. }
  1388. }
  1389. // Do node-type-specific validation checks.
  1390. node_invoke($node, 'submit');
  1391. node_invoke_nodeapi($node, 'submit');
  1392. $node->validated = TRUE;
  1393. return $node;
  1394. }
  1395. /**
  1396. * Perform validation checks on the given node.
  1397. */
  1398. function node_validate($node, $form = array()) {
  1399. // Convert the node to an object, if necessary.
  1400. $node = (object)$node;
  1401. // Make sure the body has the minimum number of words.
  1402. // todo use a better word counting algorithm that will work in other languages
  1403. if (isset($node->body) && count(explode(' ', $node->body)) < variable_get('minimum_'. $node->type .'_size', 0)) {
  1404. form_set_error('body', t('The body of your %type is too short. You need at least %words words.', array('%words' => variable_get('minimum_'. $node->type .'_size', 0), '%type' => node_get_name($node))));
  1405. }
  1406. if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  1407. form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
  1408. }
  1409. if (user_access('administer nodes')) {
  1410. // Validate the "authored by" field.
  1411. if (!empty($node->name) && !($account = user_load(array('name' => $node->name)))) {
  1412. // The use of empty() is mandatory in the context of usernames
  1413. // as the empty string denotes the anonymous user. In case we
  1414. // are dealing with an anonymous user we set the user ID to 0.
  1415. form_set_error('name', t('The username %name does not exist.', array ('%name' => theme('placeholder', $node->name))));
  1416. }
  1417. // Validate the "authored on" field. As of PHP 5.1.0, strtotime returns FALSE instead of -1 upon failure.
  1418. if (!empty($node->date) && strtotime($node->date) <= 0) {
  1419. form_set_error('date', t('You have to specify a valid date.'));
  1420. }
  1421. }
  1422. // Do node-type-specific validation checks.
  1423. node_invoke($node, 'validate', $form);
  1424. node_invoke_nodeapi($node, 'validate', $form);
  1425. }
  1426. function node_form_validate($form_id, $form_values, $form) {
  1427. node_validate($form_values, $form);
  1428. }
  1429. function node_object_prepare(&$node) {
  1430. if (user_access('administer nodes')) {
  1431. // Set up default values, if required.
  1432. if (!isset($node->created)) {
  1433. $node->created = time();
  1434. }
  1435. if (!isset($node->date)) {
  1436. $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
  1437. }
  1438. }
  1439. node_invoke($node, 'prepare');
  1440. node_invoke_nodeapi($node, 'prepare');
  1441. }
  1442. /**
  1443. * Generate the node editing form.
  1444. */
  1445. function node_form($node) {
  1446. $node = (object)$node;
  1447. $form = node_form_array($node);
  1448. return drupal_get_form($node->type .'_node_form', $form, 'node_form');
  1449. }
  1450. /**
  1451. * Generate the node editing form array.
  1452. */
  1453. function node_form_array($node) {
  1454. node_object_prepare($node);
  1455. // Set the id of the top-level form tag
  1456. $form['#id'] = 'node-form';
  1457. /**
  1458. * Basic node information.
  1459. * These elements are just values so they are not even sent to the client.
  1460. */
  1461. foreach (array('nid', 'vid', 'uid', 'created', 'type') as $key) {
  1462. $form[$key] = array('#type' => 'value', '#value' => $node->$key);
  1463. }
  1464. // Changed must be sent to the client, for later overwrite error checking.
  1465. $form['changed'] = array('#type' => 'hidden', '#default_value' => $node->changed);
  1466. // Get the node-specific bits.
  1467. $form = array_merge_recursive($form, node_invoke($node, 'form'));
  1468. if (!isset($form['title']['#weight'])) {
  1469. $form['title']['#weight'] = -5;
  1470. }
  1471. $node_options = variable_get('node_options_'. $node->type, array('status', 'promote'));
  1472. // If this is a new node, fill in the default values.
  1473. if (!isset($node->nid)) {
  1474. foreach (array('status', 'moderate', 'promote', 'sticky', 'revision') as $key) {
  1475. $node->$key = in_array($key, $node_options);
  1476. }
  1477. global $user;
  1478. $node->uid = $user->uid;
  1479. }
  1480. else {
  1481. // Nodes being edited should always be preset with the default revision setting.
  1482. $node->revision = in_array('revision', $node_options);
  1483. }
  1484. $form['#node'] = $node;
  1485. if (user_access('administer nodes')) {
  1486. // Node author information
  1487. $form['author'] = array('#type' => 'fieldset', '#title' => t('Authoring information'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#weight' => 20);
  1488. $form['author']['name'] = array('#type' => 'textfield', '#title' => t('Authored by'), '#maxlength' => 60, '#autocomplete_path' => 'user/autocomplete', '#default_value' => $node->name ? $node->name : '', '#weight' => -1, '#description' => t('Leave blank for %anonymous.', array('%anonymous' => theme('placeholder', variable_get('anonymous', 'Anonymous')))));
  1489. $form['author']['date'] = array('#type' => 'textfield', '#title' => t('Authored on'), '#maxlength' => 25, '#description' => t('Format: %time. Leave blank to use the time of form submission.', array('%time' => $node->date)));
  1490. if (isset($node->nid)) {
  1491. $form['author']['date']['#default_value'] = $node->date;
  1492. }
  1493. // Node options for administrators
  1494. $form['options'] = array('#type' => 'fieldset', '#title' => t('Publishing options'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#weight' => 25);
  1495. $form['options']['status'] = array('#type' => 'checkbox', '#title' => t('Published'), '#default_value' => $node->status);
  1496. $form['options']['moderate'] = array('#type' => 'checkbox', '#title' => t('In moderation queue'), '#default_value' => $node->moderate);
  1497. $form['options']['promote'] = array('#type' => 'checkbox', '#title' => t('Promoted to front page'), '#default_value' => $node->promote);
  1498. $form['options']['sticky'] = array('#type' => 'checkbox', '#title' => t('Sticky at top of lists'), '#default_value' => $node->sticky);
  1499. $form['options']['revision'] = array('#type' => 'checkbox', '#title' => t('Create new revision'), '#default_value' => $node->revision);
  1500. }
  1501. else {
  1502. // Put all of these through as values if the user doesn't have access to them.
  1503. foreach (array('uid', 'created') as $key) {
  1504. $form[$key] = array('#type' => 'value', '#value' => $node->$key);
  1505. }
  1506. }
  1507. // Add the buttons.
  1508. $form['preview'] = array('#type' => 'button', '#value' => t('Preview'), '#weight' => 40);
  1509. $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'), '#weight' => 45);
  1510. if ($node->nid && node_access('delete', $node)) {
  1511. $form['delete'] = array('#type' => 'button', '#value' => t('Delete'), '#weight' => 50);
  1512. }
  1513. $form['#after_build'] = array('node_form_add_preview');
  1514. return $form;
  1515. }
  1516. function node_form_add_preview($form) {
  1517. global $form_values;
  1518. $op = isset($_POST['op']) ? $_POST['op'] : '';
  1519. if ($op == t('Preview')) {
  1520. // Invoke full validation for the form, to protect against cross site
  1521. // request forgeries (CSRF) and setting arbitrary values for fields such as
  1522. // the input format. Preview the node only when form validation does not
  1523. // set any errors.
  1524. drupal_validate_form($form['form_id']['#value'], $form);
  1525. if (!form_get_errors()) {
  1526. // Because the node preview may display a form, we must render it
  1527. // outside the node submission form tags using the #prefix property
  1528. // (i.e. to prevent illegally nested forms).
  1529. // If the node form already has a #prefix, we must preserve it.
  1530. // In this case, we put the preview before the #prefix so we keep
  1531. // the #prefix as "close" to the rest of the form as possible,
  1532. // for example, to keep a <div> only around the form, not the
  1533. // preview. We pass the global $form_values here to preserve
  1534. // changes made during form validation.
  1535. $preview = node_preview((object)$form_values);
  1536. $form['#prefix'] = isset($form['#prefix']) ? $preview . $form['#prefix'] : $preview;
  1537. }
  1538. }
  1539. if (variable_get('node_preview', 0) && (form_get_errors() || $op != t('Preview'))) {
  1540. unset($form['submit']);
  1541. }
  1542. return $form;
  1543. }
  1544. function theme_node_form($form) {
  1545. $output = "\n<div class=\"node-form\">\n";
  1546. // Admin form fields and submit buttons must be rendered first, because
  1547. // they need to go to the bottom of the form, and so should not be part of
  1548. // the catch-all call to form_render().
  1549. $admin = '';
  1550. if (isset($form['author'])) {
  1551. $admin .= " <div class=\"authored\">\n";
  1552. $admin .= form_render($form['author']);
  1553. $admin .= " </div>\n";
  1554. }
  1555. if (isset($form['options'])) {
  1556. $admin .= " <div class=\"options\">\n";
  1557. $admin .= form_render($form['options']);
  1558. $admin .= " </div>\n";
  1559. }
  1560. $buttons = form_render($form['preview']);
  1561. $buttons .= form_render($form['submit']);
  1562. $buttons .= isset($form['delete']) ? form_render($form['delete']) : '';
  1563. // Everything else gets rendered here, and is displayed before the admin form
  1564. // field and the submit buttons.
  1565. $output .= " <div class=\"standard\">\n";
  1566. $output .= form_render($form);
  1567. $output .= " </div>\n";
  1568. if (!empty($admin)) {
  1569. $output .= " <div class=\"admin\">\n";
  1570. $output .= $admin;
  1571. $output .= " </div>\n";
  1572. }
  1573. $output .= $buttons;
  1574. $output .= "</div>\n";
  1575. return $output;
  1576. }
  1577. /**
  1578. * Present a node submission form or a set of links to such forms.
  1579. */
  1580. function node_add($type) {
  1581. global $user;
  1582. // If a node type has been specified, validate its existence.
  1583. if (array_key_exists($type, node_get_types()) && node_access('create', $type)) {
  1584. // Initialize settings:
  1585. $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => $type);
  1586. $output = node_form($node);
  1587. drupal_set_title(t('Submit %name', array('%name' => node_get_name($node))));
  1588. }
  1589. else {
  1590. // If no (valid) node type has been provided, display a node type overview.
  1591. foreach (node_get_types() as $type => $name) {
  1592. if (node_access('create', $type)) {
  1593. $out = '<dt>'. l($name, "node/add/$type", array('title' => t('Add a new %s.', array('%s' => $name)))) .'</dt>';
  1594. $out .= '<dd>'. implode("\n", module_invoke_all('help', 'node/add#'. $type)) .'</dd>';
  1595. $item[$name] = $out;
  1596. }
  1597. }
  1598. if (isset($item)) {
  1599. uksort($item, 'strnatcasecmp');
  1600. $output = t('Choose the appropriate item from the list:') .'<dl>'. implode('', $item) .'</dl>';
  1601. }
  1602. else {
  1603. $output = t('You are not allowed to create content.');
  1604. }
  1605. }
  1606. return $output;
  1607. }
  1608. /**
  1609. * Generate a node preview.
  1610. */
  1611. function node_preview($node) {
  1612. if (node_access('create', $node) || node_access('update', $node)) {
  1613. // Load the user's name when needed:
  1614. if (isset($node->name)) {
  1615. // The use of isset() is mandatory in the context of user IDs, because
  1616. // user ID 0 denotes the anonymous user.
  1617. if ($user = user_load(array('name' => $node->name))) {
  1618. $node->uid = $user->uid;
  1619. $node->picture = $user->picture;
  1620. }
  1621. else {
  1622. $node->uid = 0; // anonymous user
  1623. }
  1624. }
  1625. else if ($node->uid) {
  1626. $user = user_load(array('uid' => $node->uid));
  1627. $node->name = $user->name;
  1628. $node->picture = $user->picture;
  1629. }
  1630. // Set the timestamps when needed:
  1631. if ($node->date) {
  1632. $node->created = strtotime($node->date);
  1633. }
  1634. $node->changed = time();
  1635. // Extract a teaser, if it hasn't been set (e.g. by a module-provided
  1636. // 'teaser' form item).
  1637. if (!isset($node->teaser)) {
  1638. $node->teaser = node_teaser($node->body, $node->format);
  1639. }
  1640. // Display a preview of the node:
  1641. // Previewing alters $node so it needs to be cloned.
  1642. if (!form_get_errors()) {
  1643. $cloned_node = drupal_clone($node);
  1644. $cloned_node->in_preview = TRUE;
  1645. $output = theme('node_preview', $cloned_node);
  1646. }
  1647. drupal_set_title(t('Preview'));
  1648. drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('create content'), 'node/add'), l(t('Submit %name', array('%name' => node_get_name($node))), 'node/add/'. $node->type)));
  1649. return $output;
  1650. }
  1651. }
  1652. /**
  1653. * Display a node preview for display during node creation and editing.
  1654. *
  1655. * @param $node
  1656. * The node object which is being previewed.
  1657. */
  1658. function theme_node_preview($node) {
  1659. $output = '<div class="preview">';
  1660. if ($node->teaser && $node->teaser != $node->body) {
  1661. drupal_set_message(t('The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "&lt;!--break--&gt;" (without the quotes) to fine-tune where your post gets split.'));
  1662. $output .= '<h3>'. t('Preview trimmed version') .'</h3>';
  1663. $output .= node_view(drupal_clone($node), 1, FALSE, 0);
  1664. $output .= '<h3>'. t('Preview full version') .'</h3>';
  1665. $output .= node_view($node, 0, FALSE, 0);
  1666. }
  1667. else {
  1668. $output .= node_view($node, 0, FALSE, 0);
  1669. }
  1670. $output .= "</div>\n";
  1671. return $output;
  1672. }
  1673. function node_form_submit($form_id, $edit) {
  1674. global $user;
  1675. // Fix up the node when required:
  1676. $node = node_submit($edit);
  1677. // Prepare the node's body:
  1678. if ($node->nid) {
  1679. // Check whether the current user has the proper access rights to
  1680. // perform this operation:
  1681. $original_node = node_load($node->nid); //check access rights using the unmodified node
  1682. if (node_access('update', $original_node)) {
  1683. node_save($node);
  1684. watchdog('content', t('%type: updated %title.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title))), WATCHDOG_NOTICE, l(t('view'), 'node/'. $node->nid));
  1685. drupal_set_message(t('The %post was updated.', array ('%post' => node_get_name($node))));
  1686. }
  1687. }
  1688. else {
  1689. // Check whether the current user has the proper access rights to
  1690. // perform this operation:
  1691. if (node_access('create', $node)) {
  1692. node_save($node);
  1693. watchdog('content', t('%type: added %title.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title))), WATCHDOG_NOTICE, l(t('view'), "node/$node->nid"));
  1694. drupal_set_message(t('Your %post was created.', array ('%post' => node_get_name($node))));
  1695. }
  1696. }
  1697. if ($node->nid) {
  1698. if (node_access('view', $node)) {
  1699. return 'node/'. $node->nid;
  1700. }
  1701. else {
  1702. return '';
  1703. }
  1704. }
  1705. // it is very unlikely we get here
  1706. return FALSE;
  1707. }
  1708. /**
  1709. * Menu callback -- ask for confirmation of node deletion
  1710. */
  1711. function node_delete_confirm() {
  1712. $edit = $_POST['edit'];
  1713. $edit['nid'] = $edit['nid'] ? $edit['nid'] : arg(1);
  1714. $node = node_load($edit['nid']);
  1715. if (node_access('delete', $node)) {
  1716. $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
  1717. $output = confirm_form('node_delete_confirm', $form,
  1718. t('Are you sure you want to delete %title?', array('%title' => theme('placeholder', $node->title))),
  1719. $_GET['destination'] ? $_GET['destination'] : 'node/'. $node->nid, t('This action cannot be undone.'),
  1720. t('Delete'), t('Cancel') );
  1721. }
  1722. return $output;
  1723. }
  1724. /**
  1725. * Execute node deletion
  1726. */
  1727. function node_delete_confirm_submit($form_id, $form_values) {
  1728. if ($form_values['confirm']) {
  1729. node_delete($form_values['nid']);
  1730. }
  1731. return '';
  1732. }
  1733. /**
  1734. * Delete a node.
  1735. */
  1736. function node_delete($nid) {
  1737. $node = node_load($nid);
  1738. if (node_access('delete', $node)) {
  1739. db_query('DELETE FROM {node} WHERE nid = %d', $node->nid);
  1740. db_query('DELETE FROM {node_revisions} WHERE nid = %d', $node->nid);
  1741. // Call the node-specific callback (if any):
  1742. node_invoke($node, 'delete');
  1743. node_invoke_nodeapi($node, 'delete');
  1744. // Clear the cache so an anonymous poster can see the node being deleted.
  1745. cache_clear_all();
  1746. // Remove this node from the search index if needed.
  1747. if (function_exists('search_wipe')) {
  1748. search_wipe($node->nid, 'node');
  1749. }
  1750. drupal_set_message(t('%title has been deleted.', array('%title' => theme('placeholder', $node->title))));
  1751. watchdog('content', t('%type: deleted %title.', array('%type' => theme('placeholder', t($node->type)), '%title' => theme('placeholder', $node->title))));
  1752. }
  1753. }
  1754. /**
  1755. * Menu callback for revisions related activities.
  1756. */
  1757. function node_revisions() {
  1758. if (is_numeric(arg(1)) && arg(2) == 'revisions') {
  1759. $op = arg(4) ? arg(4) : 'overview';
  1760. switch ($op) {
  1761. case 'overview':
  1762. $node = node_load(arg(1));
  1763. if ((user_access('view revisions') || user_access('administer nodes')) && node_access('view', $node)) {
  1764. return node_revision_overview($node);
  1765. }
  1766. drupal_access_denied();
  1767. return;
  1768. case 'view':
  1769. if (is_numeric(arg(3))) {
  1770. $node = node_load(arg(1), arg(3));
  1771. if ($node->nid) {
  1772. if ((user_access('view revisions') || user_access('administer nodes')) && node_access('view', $node)) {
  1773. drupal_set_title(t('Revision of %title from %date', array('%title' => theme('placeholder', $node->title), '%date' => format_date($node->revision_timestamp))));
  1774. return node_show($node, arg(2));
  1775. }
  1776. drupal_access_denied();
  1777. return;
  1778. }
  1779. }
  1780. break;
  1781. case 'revert':
  1782. return node_revision_revert(arg(1), arg(3));
  1783. break;
  1784. case 'delete':
  1785. return node_revision_delete(arg(1), arg(3));
  1786. break;
  1787. }
  1788. }
  1789. drupal_not_found();
  1790. }
  1791. /**
  1792. * Generate a listing of promoted nodes.
  1793. */
  1794. function node_page_default() {
  1795. $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));
  1796. if (db_num_rows($result)) {
  1797. drupal_add_link(array('rel' => 'alternate',
  1798. 'type' => 'application/rss+xml',
  1799. 'title' => t('RSS'),
  1800. 'href' => url('rss.xml', NULL, NULL, TRUE)));
  1801. $output = '';
  1802. while ($node = db_fetch_object($result)) {
  1803. $output .= node_view(node_load($node->nid), 1);
  1804. }
  1805. $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
  1806. }
  1807. else {
  1808. $output = t('
  1809. <h1 class="title">Welcome to your new Drupal website!</h1>
  1810. <p>Please follow these steps to set up and start using your website:</p>
  1811. <ol>
  1812. <li>
  1813. <strong>Create your administrator account</strong>
  1814. To begin, <a href="%register">create the first account</a>. This account will have full administration rights and will allow you to configure your website.
  1815. </li>
  1816. <li>
  1817. <strong>Configure your website</strong>
  1818. 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.
  1819. </li>
  1820. <li>
  1821. <strong>Enable additional functionality</strong>
  1822. 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>.
  1823. </li>
  1824. <li>
  1825. <strong>Customize your website design</strong>
  1826. 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>.
  1827. </li>
  1828. <li>
  1829. <strong>Start posting content</strong>
  1830. Finally, you can <a href="%content">create content</a> for your website. This message will disappear once you have published your first post.
  1831. </li>
  1832. </ol>
  1833. <p>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.</p>',
  1834. array('%drupal' => 'http://drupal.org/', '%register' => url('user/register'), '%admin' => url('admin'), '%config' => url('admin/settings'), '%modules' => url('admin/modules'), '%download_modules' => 'http://drupal.org/project/modules', '%themes' => url('admin/themes'), '%download_themes' => 'http://drupal.org/project/themes', '%content' => url('node/add'), '%help' => url('admin/help'), '%handbook' => 'http://drupal.org/handbooks', '%forum' => 'http://drupal.org/forum', '%support' => 'http://drupal.org/support')
  1835. );
  1836. $output = '<div id="first-time">'. $output .'</div>';
  1837. }
  1838. return $output;
  1839. }
  1840. /**
  1841. * Menu callback; dispatches control to the appropriate operation handler.
  1842. */
  1843. function node_page() {
  1844. $op = arg(1);
  1845. if (is_numeric($op)) {
  1846. $op = (arg(2) && !is_numeric(arg(2))) ? arg(2) : 'view';
  1847. }
  1848. switch ($op) {
  1849. case 'view':
  1850. if (is_numeric(arg(1))) {
  1851. $node = node_load(arg(1));
  1852. if ($node->nid) {
  1853. drupal_set_title(check_plain($node->title));
  1854. return node_show($node, arg(2));
  1855. }
  1856. else if (db_result(db_query('SELECT nid FROM {node} WHERE nid = %d', arg(1)))) {
  1857. drupal_access_denied();
  1858. }
  1859. else {
  1860. drupal_not_found();
  1861. }
  1862. }
  1863. break;
  1864. case 'add':
  1865. return node_add(arg(2));
  1866. break;
  1867. case 'edit':
  1868. if ($_POST['op'] == t('Delete')) {
  1869. // Note: we redirect from node/uid/edit to node/uid/delete to make the tabs disappear.
  1870. if ($_REQUEST['destination']) {
  1871. $destination = drupal_get_destination();
  1872. unset($_REQUEST['destination']);
  1873. }
  1874. drupal_goto('node/'. arg(1) .'/delete', $destination);
  1875. }
  1876. if (is_numeric(arg(1))) {
  1877. $node = node_load(arg(1));
  1878. if ($node->nid) {
  1879. drupal_set_title(check_plain($node->title));
  1880. return node_form($node);
  1881. }
  1882. else if (db_result(db_query('SELECT nid FROM {node} WHERE nid = %d', arg(1)))) {
  1883. drupal_access_denied();
  1884. }
  1885. else {
  1886. drupal_not_found();
  1887. }
  1888. }
  1889. break;
  1890. default:
  1891. drupal_set_title('');
  1892. return node_page_default();
  1893. }
  1894. }
  1895. /**
  1896. * shutdown function to make sure we always mark the last node processed.
  1897. */
  1898. function node_update_shutdown() {
  1899. global $last_change, $last_nid;
  1900. if ($last_change && $last_nid) {
  1901. variable_set('node_cron_last', $last_change);
  1902. variable_set('node_cron_last_nid', $last_nid);
  1903. }
  1904. }
  1905. /**
  1906. * Implementation of hook_update_index().
  1907. */
  1908. function node_update_index() {
  1909. global $last_change, $last_nid;
  1910. register_shutdown_function('node_update_shutdown');
  1911. $last = variable_get('node_cron_last', 0);
  1912. $last_nid = variable_get('node_cron_last_nid', 0);
  1913. $limit = (int)variable_get('search_cron_limit', 100);
  1914. // Store the maximum possible comments per thread (used for ranking by reply count)
  1915. variable_set('node_cron_comments_scale', 1.0 / max(1, db_result(db_query('SELECT MAX(comment_count) FROM {node_comment_statistics}'))));
  1916. variable_set('node_cron_views_scale', 1.0 / max(1, db_result(db_query('SELECT MAX(totalcount) FROM {node_counter}'))));
  1917. $result = db_query_range('SELECT GREATEST(IF(c.last_comment_timestamp IS NULL, 0, c.last_comment_timestamp), n.changed) as last_change, n.nid FROM {node} n LEFT JOIN {node_comment_statistics} c ON n.nid = c.nid WHERE n.status = 1 AND ((GREATEST(n.changed, c.last_comment_timestamp) = %d AND n.nid > %d) OR (n.changed > %d OR c.last_comment_timestamp > %d)) ORDER BY GREATEST(n.changed, c.last_comment_timestamp) ASC, n.nid ASC', $last, $last_nid, $last, $last, $last, 0, $limit);
  1918. while ($node = db_fetch_object($result)) {
  1919. $last_change = $node->last_change;
  1920. $last_nid = $node->nid;
  1921. $node = node_load($node->nid);
  1922. // Get node output (filtered and with module-specific fields).
  1923. if (node_hook($node, 'view')) {
  1924. node_invoke($node, 'view', false, false);
  1925. }
  1926. else {
  1927. $node = node_prepare($node, false);
  1928. }
  1929. // Allow modules to change $node->body before viewing.
  1930. node_invoke_nodeapi($node, 'view', false, false);
  1931. $text = '<h1>'. check_plain($node->title) .'</h1>'. $node->body;
  1932. // Fetch extra data normally not visible
  1933. $extra = node_invoke_nodeapi($node, 'update index');
  1934. foreach ($extra as $t) {
  1935. $text .= $t;
  1936. }
  1937. // Update index
  1938. search_index($node->nid, 'node', $text);
  1939. }
  1940. }
  1941. /**
  1942. * Implementation of hook_form_alter().
  1943. */
  1944. function node_form_alter($form_id, &$form) {
  1945. // Node publishing options
  1946. if (isset($form['type']) && $form['type']['#value'] .'_node_settings' == $form_id) {
  1947. $form['workflow']['node_options_'. $form['type']['#value']] = array('#type' => 'checkboxes',
  1948. '#title' => t('Default options'),
  1949. '#default_value' => variable_get('node_options_'. $form['type']['#value'], array('status', 'promote')),
  1950. '#options' => array(
  1951. 'status' => t('Published'),
  1952. 'moderate' => t('In moderation queue'),
  1953. 'promote' => t('Promoted to front page'),
  1954. 'sticky' => t('Sticky at top of lists'),
  1955. 'revision' => t('Create new revision'),
  1956. ),
  1957. '#description' => t('Users with the <em>administer nodes</em> permission will be able to override these options.'),
  1958. );
  1959. }
  1960. // Advanced node search form
  1961. elseif ($form_id == 'search_form' && arg(1) == 'node') {
  1962. // Keyword boxes:
  1963. $form['advanced'] = array(
  1964. '#type' => 'fieldset',
  1965. '#title' => t('Advanced search'),
  1966. '#collapsible' => TRUE,
  1967. '#collapsed' => TRUE,
  1968. '#attributes' => array('class' => 'search-advanced'),
  1969. );
  1970. $form['advanced']['keywords'] = array(
  1971. '#prefix' => '<div class="criterion">',
  1972. '#suffix' => '</div>',
  1973. );
  1974. $form['advanced']['keywords']['or'] = array(
  1975. '#type' => 'textfield',
  1976. '#title' => t('Containing any of the words'),
  1977. '#size' => 30,
  1978. '#maxlength' => 255,
  1979. );
  1980. $form['advanced']['keywords']['phrase'] = array(
  1981. '#type' => 'textfield',
  1982. '#title' => t('Containing the phrase'),
  1983. '#size' => 30,
  1984. '#maxlength' => 255,
  1985. );
  1986. $form['advanced']['keywords']['negative'] = array(
  1987. '#type' => 'textfield',
  1988. '#title' => t('Containing none of the words'),
  1989. '#size' => 30,
  1990. '#maxlength' => 255,
  1991. );
  1992. // Taxonomy box:
  1993. if ($taxonomy = module_invoke('taxonomy', 'form_all', 1)) {
  1994. $form['advanced']['category'] = array(
  1995. '#type' => 'select',
  1996. '#title' => t('Only in the category(s)'),
  1997. '#prefix' => '<div class="criterion">',
  1998. '#size' => 10,
  1999. '#suffix' => '</div>',
  2000. '#options' => $taxonomy,
  2001. '#multiple' => TRUE,
  2002. );
  2003. }
  2004. // Node types:
  2005. $types = node_get_types();
  2006. $form['advanced']['type'] = array(
  2007. '#type' => 'checkboxes',
  2008. '#title' => t('Only of the type(s)'),
  2009. '#prefix' => '<div class="criterion">',
  2010. '#suffix' => '</div>',
  2011. '#options' => $types,
  2012. );
  2013. $form['advanced']['submit'] = array(
  2014. '#type' => 'submit',
  2015. '#value' => t('Advanced search'),
  2016. '#prefix' => '<div class="action">',
  2017. '#suffix' => '</div><br class="clear" />',
  2018. );
  2019. $form['#validate']['node_search_validate'] = array();
  2020. }
  2021. }
  2022. /**
  2023. * Form API callback for the search form. Registered in node_form_alter().
  2024. */
  2025. function node_search_validate($form_id, $form_values, $form) {
  2026. // Initialise using any existing basic search keywords.
  2027. $keys = $form_values['processed_keys'];
  2028. // Insert extra restrictions into the search keywords string.
  2029. if (isset($form_values['type']) && is_array($form_values['type'])) {
  2030. // Retrieve selected types - Forms API sets the value of unselected checkboxes to 0.
  2031. $form_values['type'] = array_filter($form_values['type']);
  2032. if (count($form_values['type'])) {
  2033. $keys = search_query_insert($keys, 'type', implode(',', array_keys($form_values['type'])));
  2034. }
  2035. }
  2036. if (isset($form_values['category']) && is_array($form_values['category'])) {
  2037. $keys = search_query_insert($keys, 'category', implode(',', $form_values['category']));
  2038. }
  2039. if ($form_values['or'] != '') {
  2040. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' '. $form_values['or'], $matches)) {
  2041. $keys .= ' '. implode(' OR ', $matches[1]);
  2042. }
  2043. }
  2044. if ($form_values['negative'] != '') {
  2045. if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' '. $form_values['negative'], $matches)) {
  2046. $keys .= ' -'. implode(' -', $matches[1]);
  2047. }
  2048. }
  2049. if ($form_values['phrase'] != '') {
  2050. $keys .= ' "'. str_replace('"', ' ', $form_values['phrase']) .'"';
  2051. }
  2052. if (!empty($keys)) {
  2053. form_set_value($form['basic']['inline']['processed_keys'], trim($keys));
  2054. }
  2055. }
  2056. /**
  2057. * @defgroup node_access Node access rights
  2058. * @{
  2059. * The node access system determines who can do what to which nodes.
  2060. *
  2061. * In determining access rights for a node, node_access() first checks
  2062. * whether the user has the "administer nodes" permission. Such users have
  2063. * unrestricted access to all nodes. Then the node module's hook_access()
  2064. * is called, and a TRUE or FALSE return value will grant or deny access.
  2065. * This allows, for example, the blog module to always grant access to the
  2066. * blog author, and for the book module to always deny editing access to
  2067. * PHP pages.
  2068. *
  2069. * If node module does not intervene (returns NULL), then the
  2070. * node_access table is used to determine access. All node access
  2071. * modules are queried using hook_node_grants() to assemble a list of
  2072. * "grant IDs" for the user. This list is compared against the table.
  2073. * If any row contains the node ID in question (or 0, which stands for "all
  2074. * nodes"), one of the grant IDs returned, and a value of TRUE for the
  2075. * operation in question, then access is granted. Note that this table is a
  2076. * list of grants; any matching row is sufficient to grant access to the
  2077. * node.
  2078. *
  2079. * In node listings, the process above is followed except that
  2080. * hook_access() is not called on each node for performance reasons and for
  2081. * proper functioning of the pager system. When adding a node listing to your
  2082. * module, be sure to use db_rewrite_sql() to add
  2083. * the appropriate clauses to your query for access checks.
  2084. *
  2085. * To see how to write a node access module of your own, see
  2086. * node_access_example.module.
  2087. */
  2088. /**
  2089. * Determine whether the current user may perform the given operation on the
  2090. * specified node.
  2091. *
  2092. * @param $op
  2093. * The operation to be performed on the node. Possible values are:
  2094. * - "view"
  2095. * - "update"
  2096. * - "delete"
  2097. * - "create"
  2098. * @param $node
  2099. * The node object (or node array) on which the operation is to be performed,
  2100. * or node type (e.g. 'forum') for "create" operation.
  2101. * @param $uid
  2102. * The user ID on which the operation is to be performed.
  2103. * @return
  2104. * TRUE if the operation may be performed.
  2105. */
  2106. function node_access($op, $node = NULL, $uid = NULL) {
  2107. // Convert the node to an object if necessary:
  2108. if ($op != 'create') {
  2109. $node = (object)$node;
  2110. }
  2111. // If the node is in a restricted format, disallow editing.
  2112. if ($op == 'update' && !filter_access($node->format)) {
  2113. return FALSE;
  2114. }
  2115. if (user_access('administer nodes')) {
  2116. return TRUE;
  2117. }
  2118. if (!user_access('access content')) {
  2119. return FALSE;
  2120. }
  2121. // Can't use node_invoke(), because the access hook takes the $op parameter
  2122. // before the $node parameter.
  2123. $access = module_invoke(node_get_base($node), 'access', $op, $node);
  2124. if (!is_null($access)) {
  2125. return $access;
  2126. }
  2127. // If the module did not override the access rights, use those set in the
  2128. // node_access table.
  2129. if ($op != 'create' && $node->nid && $node->status) {
  2130. $grants = array();
  2131. foreach (node_access_grants($op, $uid) as $realm => $gids) {
  2132. foreach ($gids as $gid) {
  2133. $grants[] = "(gid = $gid AND realm = '$realm')";
  2134. }
  2135. }
  2136. $grants_sql = '';
  2137. if (count($grants)) {
  2138. $grants_sql = 'AND ('. implode(' OR ', $grants) .')';
  2139. }
  2140. $sql = "SELECT COUNT(*) FROM {node_access} WHERE (nid = 0 OR nid = %d) $grants_sql AND grant_$op >= 1";
  2141. $result = db_query($sql, $node->nid);
  2142. return (db_result($result));
  2143. }
  2144. return FALSE;
  2145. }
  2146. /**
  2147. * Generate an SQL join clause for use in fetching a node listing.
  2148. *
  2149. * @param $node_alias
  2150. * If the node table has been given an SQL alias other than the default
  2151. * "n", that must be passed here.
  2152. * @param $node_access_alias
  2153. * If the node_access table has been given an SQL alias other than the default
  2154. * "na", that must be passed here.
  2155. * @return
  2156. * An SQL join clause.
  2157. */
  2158. function _node_access_join_sql($node_alias = 'n', $node_access_alias = 'na') {
  2159. if (user_access('administer nodes')) {
  2160. return '';
  2161. }
  2162. return 'INNER JOIN {node_access} '. $node_access_alias .' ON '. $node_access_alias .'.nid = '. $node_alias .'.nid';
  2163. }
  2164. /**
  2165. * Generate an SQL where clause for use in fetching a node listing.
  2166. *
  2167. * @param $op
  2168. * The operation that must be allowed to return a node.
  2169. * @param $node_access_alias
  2170. * If the node_access table has been given an SQL alias other than the default
  2171. * "na", that must be passed here.
  2172. * @return
  2173. * An SQL where clause.
  2174. */
  2175. function _node_access_where_sql($op = 'view', $node_access_alias = 'na', $uid = NULL) {
  2176. if (user_access('administer nodes')) {
  2177. return;
  2178. }
  2179. $grants = array();
  2180. foreach (node_access_grants($op, $uid) as $realm => $gids) {
  2181. foreach ($gids as $gid) {
  2182. $grants[] = "($node_access_alias.gid = $gid AND $node_access_alias.realm = '$realm')";
  2183. }
  2184. }
  2185. $grants_sql = '';
  2186. if (count($grants)) {
  2187. $grants_sql = 'AND ('. implode(' OR ', $grants) .')';
  2188. }
  2189. $sql = "$node_access_alias.grant_$op >= 1 $grants_sql";
  2190. return $sql;
  2191. }
  2192. /**
  2193. * Fetch an array of permission IDs granted to the given user ID.
  2194. *
  2195. * The implementation here provides only the universal "all" grant. A node
  2196. * access module should implement hook_node_grants() to provide a grant
  2197. * list for the user.
  2198. *
  2199. * @param $op
  2200. * The operation that the user is trying to perform.
  2201. * @param $uid
  2202. * The user ID performing the operation. If omitted, the current user is used.
  2203. * @return
  2204. * An associative array in which the keys are realms, and the values are
  2205. * arrays of grants for those realms.
  2206. */
  2207. function node_access_grants($op, $uid = NULL) {
  2208. global $user;
  2209. if (isset($uid)) {
  2210. $user_object = user_load(array('uid' => $uid));
  2211. }
  2212. else {
  2213. $user_object = $user;
  2214. }
  2215. return array_merge(array('all' => array(0)), module_invoke_all('node_grants', $user_object, $op));
  2216. }
  2217. /**
  2218. * Determine whether the user has a global viewing grant for all nodes.
  2219. */
  2220. function node_access_view_all_nodes() {
  2221. static $access;
  2222. if (!isset($access)) {
  2223. $grants = array();
  2224. foreach (node_access_grants('view') as $realm => $gids) {
  2225. foreach ($gids as $gid) {
  2226. $grants[] = "(gid = $gid AND realm = '$realm')";
  2227. }
  2228. }
  2229. $grants_sql = '';
  2230. if (count($grants)) {
  2231. $grants_sql = 'AND ('. implode(' OR ', $grants) .')';
  2232. }
  2233. $sql = "SELECT COUNT(*) FROM {node_access} WHERE nid = 0 $grants_sql AND grant_view >= 1";
  2234. $result = db_query($sql);
  2235. $access = db_result($result);
  2236. }
  2237. return $access;
  2238. }
  2239. /**
  2240. * Implementation of hook_db_rewrite_sql
  2241. */
  2242. function node_db_rewrite_sql($query, $primary_table, $primary_field) {
  2243. if ($primary_field == 'nid' && !node_access_view_all_nodes()) {
  2244. $return['join'] = _node_access_join_sql($primary_table);
  2245. $return['where'] = _node_access_where_sql();
  2246. $return['distinct'] = 1;
  2247. return $return;
  2248. }
  2249. }
  2250. /**
  2251. * @} End of "defgroup node_access".
  2252. */
Login or register to post comments