this page.', array('@node_access_rebuild' => url('admin/reports/status/rebuild'))); } drupal_set_message($message, 'error'); } switch ($path) { case 'admin/help#node': $output = '

' . t('The node module manages content on your site, and stores all posts (regardless of type) as a "node" . In addition to basic publishing settings, including whether the post has been published, promoted to the site front page, or should remain present (or sticky) at the top of lists, the node module also records basic information about the author of a post. Optional revision control over edits is available. For additional functionality, the node module is often extended by other modules.') . '

'; $output .= '

' . t('Though each post on your site is a node, each post is also of a particular content type. Content types are used to define the characteristics of a post, including the title and description of the fields displayed on its add and edit pages. Each content type may have different default settings for Publishing options and other workflow controls. By default, the two content types in a standard Drupal installation are Page and Story. Use the content types page to add new or edit existing content types. Additional content types also become available as you enable additional core, contributed and custom modules.', array('@content-type' => url('admin/structure/types'))) . '

'; $output .= '

' . t('The administrative content page allows you to review and manage your site content. The node module makes a number of permissions available for each content type, which may be set by role on the permissions page.', array('@content' => url('admin/content'), '@permissions' => url('admin/config/people/permissions'))) . '

'; $output .= '

' . t('For more information, see the online handbook entry for Node module.', array('@node' => 'http://drupal.org/handbook/modules/node/')) . '

'; return $output; case 'admin/content': return ' '; // Return a non-null value so that the 'more help' link is shown. case 'admin/structure/types/add': return '

' . t('Each piece of content is of a specific content type. Each content type can have different fields, behaviors, and permissions assigned to it.') . '

'; case 'admin/structure/node-type/' . $arg[3] . '/fields': return '

' . t('This form lets you add, edit, and arrange fields within the %type content type.', array('%type' => node_type_get_name($arg[3]))) . '

'; case 'admin/structure/node-type/' . $arg[3] . '/display': return '

' . t('This form lets you configure how fields and labels are displayed when %type content is viewed in teaser and full-page mode.', array('%type' => node_type_get_name($arg[3]))) . '

'; case 'admin/structure/node-type/' . $arg[3] . '/display/' . $arg[5]: return '

' . t('This form lets you configure how fields should be displayed when rendered %type content in the following contexts.', array('%type' => node_type_get_name($arg[3]))) . '

'; case 'node/%/revisions': return '

' . t('The revisions let you track differences between multiple versions of a post.') . '

'; case 'node/%/edit': $node = node_load($arg[1]); $type = node_type_get_type($node); return (!empty($type->help) ? '

' . filter_xss_admin($type->help) . '

' : ''); } if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) { $type = node_type_get_type(str_replace('-', '_', $arg[2])); return (!empty($type->help) ? '

' . filter_xss_admin($type->help) . '

' : ''); } } /** * Implement hook_theme(). */ function node_theme() { return array( 'node' => array( 'arguments' => array('elements' => NULL), 'template' => 'node', ), 'node_list' => array( 'arguments' => array('items' => NULL, 'title' => NULL), ), 'node_search_admin' => array( 'arguments' => array('form' => NULL), ), 'node_filter_form' => array( 'arguments' => array('form' => NULL), 'file' => 'node.admin.inc', ), 'node_filters' => array( 'arguments' => array('form' => NULL), 'file' => 'node.admin.inc', ), 'node_admin_nodes' => array( 'arguments' => array('form' => NULL), 'file' => 'node.admin.inc', ), 'node_add_list' => array( 'arguments' => array('content' => NULL), 'file' => 'node.pages.inc', ), 'node_form' => array( 'arguments' => array('form' => NULL), 'file' => 'node.pages.inc', ), 'node_preview' => array( 'arguments' => array('node' => NULL), 'file' => 'node.pages.inc', ), 'node_log_message' => array( 'arguments' => array('log' => NULL), ), 'node_submitted' => array( 'arguments' => array('node' => NULL), ), 'node_admin_overview' => array( 'arguments' => array('name' => NULL, 'type' => NULL), ), ); } /** * Implement hook_cron(). */ function node_cron() { db_delete('history') ->condition('timestamp', NODE_NEW_LIMIT, '<') ->execute(); } /** * Implement hook_fieldable_info(). */ function node_fieldable_info() { $return = array( 'node' => array( 'label' => t('Node'), 'object keys' => array( 'id' => 'nid', 'revision' => 'vid', 'bundle' => 'type', ), // Node.module handles its own caching. // 'cacheable' => FALSE, 'bundles' => array(), ), ); // Bundles must provide a human readable name so we can create help and error // messages, and the path to attach Field admin pages to. foreach (node_type_get_names() as $type => $name) { $return['node']['bundles'][$type] = array( 'label' => $name, 'admin' => array( 'path' => 'admin/structure/node-type/' . str_replace('_', '-', $type), 'access arguments' => array('administer content types'), ), ); } return $return; } /** * Implement hook_field_build_modes(). */ function node_field_build_modes($obj_type) { $modes = array(); if ($obj_type == 'node') { $modes = array( 'teaser' => t('Teaser'), 'full' => t('Full node'), 'rss' => t('RSS'), ); // Search integration is provided by node.module, so search-related // build-modes for nodes are defined here and not in search.module. if (module_exists('search')) { $modes += array( 'search_index' => t('Search Index'), 'search_result' => t('Search Result'), ); } } return $modes; } /** * Implement hook_field_extra_fields(). */ function node_field_extra_fields($bundle) { $extra = array(); if ($type = node_type_get_type($bundle)) { if ($type->has_title) { $extra['title'] = array( 'label' => $type->title_label, 'description' => t('Node module element.'), 'weight' => -5, ); } } return $extra; } /** * Gather a listing of links to nodes. * * @param $result * A DB result object from a query to fetch node objects. If your query * joins the node_comment_statistics table so that the * comment_count field is available, a title attribute will * be added to show the number of comments. * @param $title * A heading for the resulting list. * * @return * An HTML list suitable as content for a block, or FALSE if no result can * fetch from DB result object. */ function node_title_list($result, $title = NULL) { $items = array(); $num_rows = FALSE; foreach ($result as $node) { $items[] = l($node->title, 'node/' . $node->nid, !empty($node->comment_count) ? array('attributes' => array('title' => format_plural($node->comment_count, '1 comment', '@count comments'))) : array()); $num_rows = TRUE; } return $num_rows ? theme('node_list', $items, $title) : FALSE; } /** * Format a listing of links to nodes. * * @ingroup themeable */ function theme_node_list($items, $title = NULL) { return theme('item_list', $items, $title); } /** * Update the 'last viewed' timestamp of the specified node for current user. */ function node_tag_new($nid) { global $user; if ($user->uid) { db_merge('history') ->key(array( 'uid' => $user->uid, 'nid' => $nid, )) ->fields(array('timestamp' => REQUEST_TIME)) ->execute(); } } /** * Retrieves the timestamp at which the current user last viewed the * specified node. */ function node_last_viewed($nid) { global $user; static $history; if (!isset($history[$nid])) { $history[$nid] = db_query("SELECT timestamp FROM {history} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $nid))->fetchObject(); } return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0); } /** * Decide on the type of marker to be displayed for a given node. * * @param $nid * Node ID whose history supplies the "last viewed" timestamp. * @param $timestamp * Time which is compared against node's "last viewed" timestamp. * @return * One of the MARK constants. */ function node_mark($nid, $timestamp) { global $user; static $cache; if (!$user->uid) { return MARK_READ; } if (!isset($cache[$nid])) { $cache[$nid] = node_last_viewed($nid); } if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) { return MARK_NEW; } elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) { return MARK_UPDATED; } return MARK_READ; } /** * Extract the type name. * * @param $node * Either a string or object, containing the node type information. * * @return * Node type of the passed in data. */ function _node_extract_type($node) { return is_object($node) ? $node->type : $node; } /** * Clear the statically cached node type information. */ function node_type_clear() { drupal_static_reset('_node_types_build'); } /** * Returns a list of all the available node types. * * @return * An array of node types, keyed by the type. * @see node_type_get_type() */ function node_type_get_types() { return _node_types_build()->types; } /** * Returns the node type of the passed node or node type string. * *@param $node * A node object or string that indicates the node type to return. * @return * A single node type, as an object or FALSE if the node type is not found. * The node type is an array with following content: * * @code * array( * 'type' => 'Machine readable type name', * 'name' => 'Name of the node type', * 'base' => 'Indicates to which module this node type belongs', * 'description' => 'Description of the node type', * // ... * ) * @endcode */ function node_type_get_type($node) { $type = _node_extract_type($node); $types = _node_types_build()->types; return isset($types[$type]) ? $types[$type] : FALSE; } /** * Returns the node type base of the passed node or node type string. * * The base indicates which module implement this node type and is used to * execute node type specific hooks. * * @see node_invoke() * * @param $node * A node object or string that indicates the node type to return. * @return * The node type base or FALSE if the node type is not found. */ function node_type_get_base($node) { $type = _node_extract_type($node); $types = _node_types_build()->types; return isset($types[$type]) && isset($types[$type]->base) ? $types[$type]->base : FALSE; } /** * Returns a list of available node names. * * @return * An array of node type names, keyed by the type. */ function node_type_get_names() { return _node_types_build()->names; } /** * Returns the node type name of the passed node or node type string. * * @param $node * A node object or string that indicates the node type to return. * * @return * The node type name or FALSE if the node type is not found. */ function node_type_get_name($node) { $type = _node_extract_type($node); $types = _node_types_build()->names; return isset($types[$type]) ? $types[$type] : FALSE; } /** * Resets the database cache of node types, and saves all new or non-modified * module-defined node types to the database. */ function node_types_rebuild() { // Reset and load updated node types. node_type_clear(); foreach (node_type_get_types() as $type => $info) { if (!empty($info->is_new)) { node_type_save($info); } if (!empty($info->disabled)) { node_type_delete($info->type); } } // Reset cached node type information so that the next access // will use the updated data. node_type_clear(); // This is required for proper menu items at node/add/type. menu_rebuild(); } /** * Saves a node type to the database. * * @param $info * The node type to save, as an object. * * @return * Status flag indicating outcome of the operation. */ function node_type_save($info) { $is_existing = FALSE; $existing_type = !empty($info->old_type) ? $info->old_type : $info->type; $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', array(':type' => $existing_type), 0, 1)->fetchField(); $type = node_type_set_defaults($info); $fields = array( 'type' => (string) $type->type, 'name' => (string) $type->name, 'base' => (string) $type->base, 'has_title' => (int) $type->has_title, 'title_label' => (string) $type->title_label, 'has_body' => (int) $type->has_body, 'body_label' => (string) $type->body_label, 'description' => (string) $type->description, 'help' => (string) $type->help, 'custom' => (int) $type->custom, 'modified' => (int) $type->modified, 'locked' => (int) $type->locked, ); if ($is_existing) { db_update('node_type') ->fields($fields) ->condition('type', $existing_type) ->execute(); if (!empty($type->old_type) && $type->old_type != $type->type) { field_attach_rename_bundle($type->old_type, $type->type); } node_configure_fields($type); module_invoke_all('node_type_update', $type); return SAVED_UPDATED; } else { $fields['orig_type'] = (string) $type->orig_type; db_insert('node_type') ->fields($fields) ->execute(); field_attach_create_bundle($type->type); node_configure_fields($type); module_invoke_all('node_type_insert', $type); return SAVED_NEW; } } /** * Manage the field(s) for a node type. * * Currently, the node module manages a single Field API field, * 'body'. If $type->has_body is true, this function ensures the * 'body' field exists and creates an instance of it for the bundle * $type->type (e.g. 'page', 'story', ...). If $type->has_body is * false, this function removes the instance (if it exists) for the * 'body' field on $type->type. */ function node_configure_fields($type) { // Add or remove the body field, as needed. $field = field_info_field('body'); $instance = field_info_instance('body', $type->type); if ($type->has_body) { if (empty($field)) { $field = array( 'field_name' => 'body', 'type' => 'text_with_summary', ); $field = field_create_field($field); } if (empty($instance)) { $instance = array( 'field_name' => 'body', 'bundle' => $type->type, 'label' => $type->body_label, 'widget_type' => 'text_textarea_with_summary', 'settings' => array('display_summary' => TRUE), // With no UI in core, we have to define default // formatters for the teaser and full view. // This may change if the method of handling displays // is changed or if a UI gets into core. 'display' => array( 'full' => array( 'label' => 'hidden', 'type' => 'text_default', ), 'teaser' => array( 'label' => 'hidden', 'type' => 'text_summary_or_trimmed', ), ), ); field_create_instance($instance); } else { $instance['label'] = $type->body_label; $instance['settings']['display_summary'] = TRUE; field_update_instance($instance); } } elseif (!empty($instance)) { field_delete_instance($instance); } } /** * Deletes a node type from the database. * * @param $type * The machine-readable name of the node type to be deleted. */ function node_type_delete($type) { $info = node_type_get_type($type); db_delete('node_type') ->condition('type', $type) ->execute(); module_invoke_all('node_type_delete', $info); } /** * Updates all nodes of one type to be of another type. * * @param $old_type * The current node type of the nodes. * @param $type * The new node type of the nodes. * * @return * The number of nodes whose node type field was modified. */ function node_type_update_nodes($old_type, $type) { return db_update('node') ->fields(array('type' => $type)) ->condition('type', $old_type) ->execute(); } /** * Builds and returns the list of available node types. * * The list of types is built by querying hook_node_info() in all modules, and * by comparing this information with the node types in the {node_type} table. * */ function _node_types_build() { $_node_types = &drupal_static(__FUNCTION__); if (is_object($_node_types)) { return $_node_types; } $_node_types = (object) array('types' => array(), 'names' => array()); $info_array = module_invoke_all('node_info'); foreach ($info_array as $type => $info) { $info['type'] = $type; $_node_types->types[$type] = node_type_set_defaults($info); $_node_types->names[$type] = $info['name']; } $type_result = db_select('node_type', 'nt') ->fields('nt') ->orderBy('nt.type', 'ASC') ->addTag('node_type_access') ->execute(); foreach ($type_result as $type_object) { // Check for node types from disabled modules and mark their types for removal. // Types defined by the node module in the database (rather than by a separate // module using hook_node_info) have a base value of 'node_content'. The isset() // check prevents errors on old (pre-Drupal 7) databases. if (isset($type_object->base) && $type_object->base != 'node_content' && empty($info_array[$type_object->type])) { $type_object->disabled = TRUE; } if (!isset($_node_types->types[$type_object->type]) || $type_object->modified) { $_node_types->types[$type_object->type] = $type_object; $_node_types->names[$type_object->type] = $type_object->name; if ($type_object->type != $type_object->orig_type) { unset($_node_types->types[$type_object->orig_type]); unset($_node_types->names[$type_object->orig_type]); } } } asort($_node_types->names); return $_node_types; } /** * Set the default values for a node type. * * The defaults are for a type defined through hook_node_info(). * When populating a custom node type $info should have the 'custom' * key set to 1. * * @param $info * An object or array containing values to override the defaults. * * @return * A node type object. */ function node_type_set_defaults($info = array()) { static $type; if (!isset($type)) { $type = new stdClass(); $type->type = ''; $type->name = ''; $type->base = ''; $type->description = ''; $type->help = ''; $type->has_title = 1; $type->has_body = 1; $type->title_label = t('Title'); $type->body_label = t('Body'); $type->custom = 0; $type->modified = 0; $type->locked = 1; $type->is_new = 1; } $new_type = clone $type; $info = (array) $info; foreach ($info as $key => $data) { $new_type->$key = $data; } // If the type has no title or body, set an empty label. if (!$new_type->has_title) { $new_type->title_label = ''; } if (!$new_type->has_body) { $new_type->body_label = ''; } $new_type->orig_type = isset($info['type']) ? $info['type'] : ''; return $new_type; } /** * Determine whether a node hook exists. * * @param $node * Either a node object, node array, or a string containing the node type. * @param $hook * A string containing the name of the hook. * @return * TRUE if the $hook exists in the node type of $node. */ function node_hook($node, $hook) { $base = node_type_get_base($node); return module_hook($base, $hook); } /** * Invoke a node hook. * * @param $node * Either a node object, node array, or a string containing the node type. * @param $hook * A string containing the name of the hook. * @param $a2, $a3, $a4 * Arguments to pass on to the hook, after the $node argument. * @return * The returned value of the invoked hook. */ function node_invoke($node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) { if (node_hook($node, $hook)) { $base = node_type_get_base($node); $function = $base . '_' . $hook; return ($function($node, $a2, $a3, $a4)); } } /** * Load node objects from the database. * * This function should be used whenever you need to load more than one node * from the database. Nodes are loaded into memory and will not require * database access if loaded again during the same page request. * * @param $nids * An array of node IDs. * @param $conditions * An array of conditions on the {node} table in the form 'field' => $value. * @param $reset * Whether to reset the internal node_load cache. * * @return * An array of node objects indexed by nid. */ function node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE) { $node_cache = &drupal_static(__FUNCTION__, array()); if ($reset) { $node_cache = array(); } $nodes = array(); // Create a new variable which is either a prepared version of the $nids // array for later comparison with the node cache, or FALSE if no $nids were // passed. The $nids array is reduced as items are loaded from cache, and we // need to know if it's empty for this reason to avoid querying the database // when all requested nodes are loaded from cache. $passed_nids = !empty($nids) ? array_flip($nids) : FALSE; // Revisions are not statically cached, and require a different query to // other conditions, so separate vid into its own variable. $vid = isset($conditions['vid']) ? $conditions['vid'] : FALSE; unset($conditions['vid']); // Load any available nodes from the internal cache. if ($node_cache && !$vid) { if ($nids) { $nodes += array_intersect_key($node_cache, $passed_nids); // If any nodes were loaded, remove them from the $nids still to load. $nids = array_keys(array_diff_key($passed_nids, $nodes)); } // If loading nodes only by conditions, fetch all available nodes from // the cache. Nodes which don't match are removed later. elseif ($conditions) { $nodes = $node_cache; } } // Exclude any nodes loaded from cache if they don't match $conditions. // This ensures the same behavior whether loading from memory or database. if ($conditions) { foreach ($nodes as $node) { $node_values = (array) $node; if (array_diff_assoc($conditions, $node_values)) { unset($nodes[$node->nid]); } } } // Load any remaining nodes from the database. This is the case if there are // any $nids left to load, if loading a revision, or if $conditions was // passed without $nids. if ($nids || $vid || ($conditions && !$passed_nids)) { $query = db_select('node', 'n'); if ($vid) { $query->join('node_revision', 'r', 'r.nid = n.nid AND r.vid = :vid', array(':vid' => $vid)); } else { $query->join('node_revision', 'r', 'r.vid = n.vid'); } // Add fields from the {node} table. $node_fields = drupal_schema_fields_sql('node'); // The columns vid, title, status, comment, promote, moderate, and sticky // are all provided by node_revision, so remove them. foreach (array('vid', 'title', 'status', 'comment', 'promote', 'moderate', 'sticky') as $column) { unset($node_fields[$column]); } $query->fields('n', $node_fields); // Add all fields from the {node_revision} table. $node_revision_fields = drupal_schema_fields_sql('node_revision'); // nid is provided by node, so remove it. unset($node_revision_fields['nid']); // Change timestamp to revision_timestamp before adding it to the query. unset($node_revision_fields['timestamp']); $query->addField('r', 'timestamp', 'revision_timestamp'); $query->fields('r', $node_revision_fields); if ($nids) { $query->condition('n.nid', $nids, 'IN'); } if ($conditions) { foreach ($conditions as $field => $value) { $query->condition('n.' . $field, $value); } } $queried_nodes = $query->execute()->fetchAllAssoc('nid'); } // Pass all nodes loaded from the database through the node type specific // callbacks and hook_node_load(), then add them to the internal cache. if (!empty($queried_nodes)) { // Create an array of nodes for each content type and pass this to the // node type specific callback. $typed_nodes = array(); foreach ($queried_nodes as $nid => $node) { $typed_nodes[$node->type][$nid] = $node; } // Call node type specific callbacks on each typed array of nodes. foreach ($typed_nodes as $type => $nodes_of_type) { if (node_hook($type, 'load')) { $function = node_type_get_base($type) . '_load'; $function($nodes_of_type); } } // Attach fields. if ($vid) { field_attach_load_revision('node', $queried_nodes); } else { field_attach_load('node', $queried_nodes); } // Call hook_node_load(), pass the node types so modules can return early // if not acting on types in the array. foreach (module_implements('node_load') as $module) { $function = $module . '_node_load'; $function($queried_nodes, array_keys($typed_nodes)); } $nodes += $queried_nodes; // Add nodes to the cache if we're not loading a revision. if (!$vid) { $node_cache += $queried_nodes; } } // Ensure that the returned array is ordered the same as the original $nids // array if this was passed in and remove any invalid nids. if ($passed_nids) { // Remove any invalid nids from the array. $passed_nids = array_intersect_key($passed_nids, $nodes); foreach ($nodes as $node) { $passed_nids[$node->nid] = $node; } $nodes = $passed_nids; } return $nodes; } /** * Load a node object from the database. * * @param $nid * The node ID. * @param $vid * The revision ID. * @param $reset * Whether to reset the node_load_multiple cache. * * @return * A fully-populated node object. */ function node_load($nid, $vid = array(), $reset = FALSE) { $vid = isset($vid) ? array('vid' => $vid) : NULL; $node = node_load_multiple(array($nid), $vid, $reset); return $node ? $node[$nid] : FALSE; } /** * Perform validation checks on the given node. */ function node_validate($node, $form = array()) { // Convert the node to an object, if necessary. $node = (object)$node; $type = node_type_get_type($node); if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) { form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.')); } if (user_access('administer nodes')) { // Validate the "authored by" field. if (!empty($node->name) && !($account = user_load_by_name($node->name))) { // The use of empty() is mandatory in the context of usernames // as the empty string denotes the anonymous user. In case we // are dealing with an anonymous user we set the user ID to 0. form_set_error('name', t('The username %name does not exist.', array('%name' => $node->name))); } // Validate the "authored on" field. if (!empty($node->date) && strtotime($node->date) === FALSE) { form_set_error('date', t('You have to specify a valid date.')); } } // Do node-type-specific validation checks. node_invoke($node, 'validate', $form); module_invoke_all('node_validate', $node, $form); } /** * Prepare node for save and allow modules to make changes. */ function node_submit($node) { global $user; // Convert the node to an object, if necessary. $node = (object)$node; if (user_access('administer nodes')) { // Populate the "authored by" field. if ($account = user_load_by_name($node->name)) { $node->uid = $account->uid; } else { $node->uid = 0; } } $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME; $node->validated = TRUE; return $node; } /** * Save changes to a node or add a new node. * * @param $node * The $node object to be saved. If $node->nid is * omitted (or $node->is_new is TRUE), a new node will be added. */ function node_save($node) { field_attach_presave('node', $node); // Let modules modify the node before it is saved to the database. module_invoke_all('node_presave', $node); global $user; if (!isset($node->is_new)) { $node->is_new = empty($node->nid); } // Apply filters to some default node fields: if ($node->is_new) { // Insert a new node. $node->is_new = TRUE; // When inserting a node, $node->log must be set because // {node_revision}.log does not (and cannot) have a default // value. If the user does not have permission to create // revisions, however, the form will not contain an element for // log so $node->log will be unset at this point. if (!isset($node->log)) { $node->log = ''; } } elseif (!empty($node->revision)) { $node->old_vid = $node->vid; unset($node->vid); } else { // When updating a node, avoid clobbering an existing log entry with an empty one. if (empty($node->log)) { unset($node->log); } } // Set some required fields: if (empty($node->created)) { $node->created = REQUEST_TIME; } // The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...) $node->changed = REQUEST_TIME; $node->timestamp = REQUEST_TIME; $update_node = TRUE; // Generate the node table query and the node_revisions table query. if ($node->is_new) { drupal_write_record('node', $node); _node_save_revision($node, $user->uid); $op = 'insert'; } else { drupal_write_record('node', $node, 'nid'); if (!empty($node->revision)) { _node_save_revision($node, $user->uid); } else { _node_save_revision($node, $user->uid, 'vid'); $update_node = FALSE; } $op = 'update'; } if ($update_node) { db_update('node') ->fields(array('vid' => $node->vid)) ->condition('nid', $node->nid) ->execute(); } // Call the node specific callback (if any). This can be // node_invoke($node, 'insert') or // node_invoke($node, 'update'). node_invoke($node, $op); // Save fields. $function = "field_attach_$op"; $function('node', $node); module_invoke_all('node_' . $op, $node); // Update the node access table for this node. node_access_acquire_grants($node); // Clear internal properties. unset($node->is_new); // Clear the page and block caches. cache_clear_all(); // Ignore slave server temporarily to give time for the // saved node to be propagated to the slave. db_ignore_slave(); } /** * Helper function to save a revision with the uid of the current user. * * Node is taken by reference, because drupal_write_record() updates the * $node with the revision id, and we need to pass that back to the caller. */ function _node_save_revision($node, $uid, $update = NULL) { $temp_uid = $node->uid; $node->uid = $uid; if (isset($update)) { drupal_write_record('node_revision', $node, $update); } else { drupal_write_record('node_revision', $node); } $node->uid = $temp_uid; } /** * Delete a node. * * @param $nid * A node ID. */ function node_delete($nid) { node_delete_multiple(array($nid)); } /** * Delete multiple nodes. * * @param $nids * An array of node IDs. */ function node_delete_multiple($nids) { $nodes = node_load_multiple($nids, array()); db_delete('node') ->condition('nid', $nids, 'IN') ->execute(); db_delete('node_revision') ->condition('nid', $nids, 'IN') ->execute(); db_delete('history') ->condition('nid', $nids, 'IN') ->execute(); foreach ($nodes as $nid => $node) { // Call the node-specific callback (if any): node_invoke($node, 'delete'); module_invoke_all('node_delete', $node); field_attach_delete('node', $node); // Remove this node from the search index if needed. // This code is implemented in node module rather than in search module, // because node module is implementing search module's API, not the other // way around. if (module_exists('search')) { search_reindex($nid, 'node'); } } // Clear the page and block and node_load_multiple caches. cache_clear_all(); drupal_static_reset('node_load_multiple'); } /** * Generate an array for rendering the given node. * * @param $node * A node array or node object. * @param $build_mode * Build mode, e.g. 'full', 'teaser'... * * @return * An array as expected by drupal_render(). */ function node_build($node, $build_mode = 'full') { $node = (object)$node; $node = node_build_content($node, $build_mode); $build = $node->content; $build += array( '#theme' => 'node', '#node' => $node, '#build_mode' => $build_mode, ); return $build; } /** * Builds a structured array representing the node's content. * * The content built for the node (field values, comments, file attachments or * other node components) will vary depending on the $build_mode parameter. * * Drupal core defines the following build modes for nodes, with the following * default use cases: * - full (default): node is being displayed on its own page (node/123) * - teaser: node is being displayed on the default home page listing, on * taxonomy listing pages, or on blog listing pages. * - rss: node displayed in an RSS feed. * If search.module is enabled: * - search_index: node is being indexed for search. * - search_result: node is being displayed as a search result. * If book.module is enabled: * - print: node is being displayed in print-friendly mode. * Contributed modules might define additional build modes, or use existing * build modes in additional contexts. * * @param $node * A node object. * @param $build_mode * Build mode, e.g. 'full', 'teaser'... * * @return * A structured array containing the individual elements * of the node's content. */ function node_build_content($node, $build_mode = 'full') { // The 'view' hook can be implemented to overwrite the default function // to display nodes. if (node_hook($node, 'view')) { $node = node_invoke($node, 'view', $build_mode); } // Build fields content. if (empty($node->content)) { $node->content = array(); }; $node->content += field_attach_view('node', $node, $build_mode); // Always display a read more link on teasers because we have no way // to know when a teaser view is different than a full view. $links = array(); if ($build_mode == 'teaser') { $links['node_readmore'] = array( 'title' => t('Read more'), 'href' => 'node/' . $node->nid, 'attributes' => array('rel' => 'tag', 'title' => strip_tags($node->title)) ); } $node->content['links']['node'] = array( '#theme' => 'links', '#links' => $links, '#attributes' => array('class' => array('links', 'inline')), ); // Allow modules to make their own additions to the node. module_invoke_all('node_view', $node, $build_mode); // Allow modules to modify the structured node. drupal_alter('node_build', $node, $build_mode); return $node; } /** * Generate an array which displays a node detail page. * * @param $node * A node object. * @param $message * A flag which sets a page title relevant to the revision being viewed. * @return * A $page element suitable for use by drupal_page_render(). */ function node_show($node, $message = FALSE) { if ($message) { drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH); } // Update the history table, stating that this user viewed this node. node_tag_new($node->nid); // For markup consistency with other pages, use node_build_multiple() rather than node_build(). return node_build_multiple(array($node), 'full'); } /** * Process variables for node.tpl.php * * Most themes utilize their own copy of node.tpl.php. The default is located * inside "modules/node/node.tpl.php". Look in there for the full list of * variables. * * The $variables array contains the following arguments: * - $node * - $build_mode * - $page * * @see node.tpl.php */ function template_preprocess_node(&$variables) { $variables['build_mode'] = $variables['elements']['#build_mode']; // Provide a distinct $teaser boolean. $variables['teaser'] = $variables['build_mode'] == 'teaser'; $variables['node'] = $variables['elements']['#node']; $node = $variables['node']; $variables['date'] = format_date($node->created); $variables['name'] = theme('username', $node); $variables['node_url'] = url('node/' . $node->nid); $variables['title'] = check_plain($node->title); $variables['page'] = (bool)menu_get_object(); if (!empty($node->in_preview)) { unset($node->content['links']); } // Flatten the node object's member fields. $variables = array_merge((array)$node, $variables); // Make the field variables available with the appropriate language. field_attach_preprocess('node', $node, $node->content, $variables); // Display post information only on certain node types. if (variable_get('node_submitted_' . $node->type, TRUE)) { $variables['submitted'] = theme('node_submitted', $node); $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', $node) : ''; } else { $variables['submitted'] = ''; $variables['user_picture'] = ''; } // Gather node classes. $variables['classes_array'][] = 'node-' . $node->type; if ($variables['promote']) { $variables['classes_array'][] = 'node-promoted'; } if ($variables['sticky']) { $variables['classes_array'][] = 'node-sticky'; } if (!$variables['status']) { $variables['classes_array'][] = 'node-unpublished'; } if ($variables['teaser']) { $variables['classes_array'][] = 'node-teaser'; } if (isset($variables['preview'])) { $variables['classes_array'][] = 'node-preview'; } // Clean up name so there are no underscores. $variables['template_files'][] = 'node-' . str_replace('_', '-', $node->type); $variables['template_files'][] = 'node-' . $node->nid; } /** * Theme a log message. * * @ingroup themeable */ function theme_node_log_message($log) { return '
' . t('Log') . ':
' . $log . '
'; } /** * Implement hook_permission(). */ function node_permission() { $perms = array( 'administer content types' => array( 'title' => t('Administer content types'), 'description' => t('Manage content types and content type administration settings.'), ), 'administer nodes' => array( 'title' => t('Administer nodes'), 'description' => t('Manage all information associated with site content, such as author, publication date and current revision. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))), ), 'access content' => array( 'title' => t('Access content'), 'description' => t('View published content.'), ), 'bypass node access' => array( 'title' => t('Bypass node access'), 'description' => t('View, edit and delete all site content. Users with this permission will bypass any content-related access control. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))), ), 'view revisions' => array( 'title' => t('View revisions'), 'description' => t('View content revisions.'), ), 'revert revisions' => array( 'title' => t('Revert revisions'), 'description' => t('Replace content with an older revision.'), ), 'delete revisions' => array( 'title' => t('Delete revisions'), 'description' => t('Delete content revisions.'), ), 'view own unpublished content' => array( 'title' => t('View own unpublished content'), 'description' => t('View unpublished content created by the user'), ), ); // Generate standard node permissions for all applicable node types. foreach (node_permissions_get_configured_types() as $type) { $perms += node_list_permissions($type); } return $perms; } /** * Gather the rankings from the the hook_ranking implementations. */ function _node_rankings() { $rankings = array( 'total' => 0, 'join' => array(), 'score' => array(), 'args' => array(), ); if ($ranking = module_invoke_all('ranking')) { foreach ($ranking as $rank => $values) { if ($node_rank = variable_get('node_rank_' . $rank, 0)) { // If the table defined in the ranking isn't already joined, then add it. if (isset($values['join']) && !isset($rankings['join'][$values['join']])) { $rankings['join'][$values['join']] = $values['join']; } // Add the rankings weighted score multiplier value, handling NULL gracefully. $rankings['score'][] = 'CAST(%f AS DECIMAL) * COALESCE((' . $values['score'] . '), 0)'; // Add the the administrator's weighted score multiplier value for this ranking. $rankings['total'] += $node_rank; $rankings['arguments'][] = $node_rank; // Add any additional arguments used by this ranking. if (isset($values['arguments'])) { $rankings['arguments'] = array_merge($rankings['arguments'], $values['arguments']); } } } } return $rankings; } /** * Implement hook_search(). */ function node_search($op = 'search', $keys = NULL) { switch ($op) { case 'name': return t('Content'); case 'reset': db_update('search_dataset') ->fields(array('reindex' => REQUEST_TIME)) ->condition('type', 'node') ->execute(); return; case 'status': $total = db_query('SELECT COUNT(*) FROM {node} WHERE status = 1')->fetchField(); $remaining = db_query("SELECT COUNT(*) FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE n.status = 1 AND d.sid IS NULL OR d.reindex <> 0")->fetchField(); return array('remaining' => $remaining, 'total' => $total); case 'admin': $form = array(); // Output form for defining rank factor weights. $form['content_ranking'] = array( '#type' => 'fieldset', '#title' => t('Content ranking'), ); $form['content_ranking']['#theme'] = 'node_search_admin'; $form['content_ranking']['info'] = array( '#value' => '' . 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.') . '' ); // Note: reversed to reflect that higher number = higher ranking. $options = drupal_map_assoc(range(0, 10)); foreach (module_invoke_all('ranking') as $var => $values) { $form['content_ranking']['factors']['node_rank_' . $var] = array( '#title' => $values['title'], '#type' => 'select', '#options' => $options, '#default_value' => variable_get('node_rank_' . $var, 0), ); } return $form; case 'search': // Build matching conditions list($join1, $where1) = _db_rewrite_sql(); $arguments1 = array(); $conditions1 = 'n.status = 1'; if ($type = search_query_extract($keys, 'type')) { $types = array(); foreach (explode(',', $type) as $t) { $types[] = "n.type = '%s'"; $arguments1[] = $t; } $conditions1 .= ' AND (' . implode(' OR ', $types) . ')'; $keys = search_query_insert($keys, 'type'); } if ($term = search_query_extract($keys, 'term')) { $terms = array(); foreach (explode(',', $term) as $c) { $terms[] = "tn.tid = %d"; $arguments1[] = $c; } $conditions1 .= ' AND (' . implode(' OR ', $terms) . ')'; $join1 .= ' INNER JOIN {taxonomy_term_node} tn ON n.vid = tn.vid'; $keys = search_query_insert($keys, 'term'); } if ($languages = search_query_extract($keys, 'language')) { $terms = array(); foreach (explode(',', $languages) as $l) { $terms[] = "n.language = '%s'"; $arguments1[] = $l; } $conditions1 .= ' AND (' . implode(' OR ', $terms) . ')'; $keys = search_query_insert($keys, 'language'); } // Get the ranking expressions. $rankings = _node_rankings(); // When all search factors are disabled (ie they have a weight of zero), // The default score is based only on keyword relevance. if ($rankings['total'] == 0) { $total = 1; $arguments2 = array(); $join2 = ''; $select2 = 'SUM(i.relevance) AS calculated_score'; } else { $total = $rankings['total']; $arguments2 = $rankings['arguments']; $join2 = implode(' ', $rankings['join']); $select2 = 'SUM(' . implode(' + ', $rankings['score']) . ') AS calculated_score'; } // Do search. $find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid ' . $join1, $conditions1 . (empty($where1) ? '' : ' AND ' . $where1), $arguments1, $select2, $join2, $arguments2); // Load results. $results = array(); foreach ($find as $item) { // Render the node. $node = node_load($item->sid); $node = node_build_content($node, 'search_result'); $node->rendered = drupal_render($node->content); // Fetch comments for snippet. $node->rendered .= module_invoke('comment', 'node_update_index', $node); // Fetch terms for snippet. $node->rendered .= module_invoke('taxonomy', 'node_update_index', $node); $extra = module_invoke_all('node_search_result', $node); $results[] = array( 'link' => url('node/' . $item->sid, array('absolute' => TRUE)), 'type' => check_plain(node_type_get_name($node)), 'title' => $node->title, 'user' => theme('username', $node), 'date' => $node->changed, 'node' => $node, 'extra' => $extra, 'score' => $total ? ($item->calculated_score / $total) : 0, 'snippet' => search_excerpt($keys, $node->rendered), ); } return $results; } } /** * Implement hook_ranking(). */ function node_ranking() { // Create the ranking array and add the basic ranking options. $ranking = array( 'relevance' => array( 'title' => t('Keyword relevance'), // Average relevance values hover around 0.15 'score' => 'i.relevance', ), 'sticky' => array( 'title' => t('Content is sticky at top of lists'), // The sticky flag is either 0 or 1, which is automatically normalized. 'score' => 'n.sticky', ), 'promote' => array( 'title' => t('Content is promoted to the front page'), // The promote flag is either 0 or 1, which is automatically normalized. 'score' => 'n.promote', ), ); // Add relevance based on creation or changed date. if ($node_cron_last = variable_get('node_cron_last', 0)) { $ranking['recent'] = array( 'title' => t('Recently posted'), // Exponential decay with half-life of 6 months, starting at last indexed node 'score' => 'POW(2.0, (GREATEST(n.created, n.changed) - %d) * 6.43e-8)', 'arguments' => array($node_cron_last), ); } return $ranking; } /** * Implement hook_user_cancel(). */ function node_user_cancel($edit, $account, $method) { switch ($method) { case 'user_cancel_block_unpublish': // Unpublish nodes (current revisions). module_load_include('inc', 'node', 'node.admin'); $nodes = db_select('node', 'n') ->fields('n', array('nid')) ->condition('uid', $account->uid) ->execute() ->fetchCol(); node_mass_update($nodes, array('status' => 0)); break; case 'user_cancel_reassign': // Anonymize nodes (current revisions). module_load_include('inc', 'node', 'node.admin'); $nodes = db_select('node', 'n') ->fields('n', array('nid')) ->condition('uid', $account->uid) ->execute() ->fetchCol(); node_mass_update($nodes, array('uid' => 0)); // Anonymize old revisions. db_update('node_revision') ->fields(array('uid' => 0)) ->condition('uid', $account->uid) ->execute(); // Clean history. db_delete('history') ->condition('uid', $account->uid) ->execute(); break; case 'user_cancel_delete': // Delete nodes (current revisions). // @todo Introduce node_mass_delete() or make node_mass_update() more flexible. $nodes = db_select('node', 'n') ->fields('n', array('nid')) ->condition('uid', $account->uid) ->execute() ->fetchCol(); foreach ($nodes as $nid) { node_delete($nid); } // Delete old revisions. db_delete('node_revision') ->condition('uid', $account->uid) ->execute(); // Clean history. db_delete('history') ->condition('uid', $account->uid) ->execute(); break; } } /** * Theme the content ranking part of the search settings admin page. * * @ingroup themeable */ function theme_node_search_admin($form) { $output = drupal_render($form['info']); $header = array(t('Factor'), t('Weight')); foreach (element_children($form['factors']) as $key) { $row = array(); $row[] = $form['factors'][$key]['#title']; unset($form['factors'][$key]['#title']); $row[] = drupal_render($form['factors'][$key]); $rows[] = $row; } $output .= theme('table', $header, $rows); $output .= drupal_render_children($form); return $output; } function _node_revision_access($node, $op = 'view') { $access = &drupal_static(__FUNCTION__, array()); if (!isset($access[$node->vid])) { $node_current_revision = node_load($node->nid); $is_current_revision = $node_current_revision->vid == $node->vid; // There should be at least two revisions. If the vid of the given node // and the vid of the current revision differs, then we already have two // different revisions so there is no need for a separate database check. // Also, if you try to revert to or delete the current revision, that's // not good. if ($is_current_revision && (db_query('SELECT COUNT(vid) FROM {node_revision} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField() == 1 || $op == 'update' || $op == 'delete')) { $access[$node->vid] = FALSE; } elseif (user_access('administer nodes')) { $access[$node->vid] = TRUE; } else { $map = array('view' => 'view revisions', 'update' => 'revert revisions', 'delete' => 'delete revisions'); // First check the user permission, second check the access to the // current revision and finally, if the node passed in is not the current // revision then access to that, too. $access[$node->vid] = isset($map[$op]) && user_access($map[$op]) && node_access($op, $node_current_revision) && ($is_current_revision || node_access($op, $node)); } } return $access[$node->vid]; } function _node_add_access() { $types = node_type_get_types(); foreach ($types as $type) { if (node_hook($type->type, 'form') && node_access('create', $type->type)) { return TRUE; } } if (user_access('administer content types')) { // There are no content types defined that the user has permission to create, // but the user does have the permission to administer the content types, so // grant them access to the page anyway. return TRUE; } return FALSE; } /** * Implement hook_menu(). */ function node_menu() { $items['admin/content'] = array( 'title' => 'Content', 'description' => 'Find and manage content and comments.', 'page callback' => 'drupal_get_form', 'page arguments' => array('node_admin_content'), 'access arguments' => array('administer nodes'), 'weight' => -10, 'file' => 'node.admin.inc', ); $items['admin/content/node'] = array( 'title' => 'Content', 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10, ); $items['admin/reports/status/rebuild'] = array( 'title' => 'Rebuild permissions', 'page callback' => 'drupal_get_form', 'page arguments' => array('node_configure_rebuild_confirm'), // Any user than can potentially trigger a node_access_needs_rebuild(TRUE) // has to be allowed access to the 'node access rebuild' confirm form. 'access arguments' => array('access administration pages'), 'type' => MENU_CALLBACK, 'file' => 'node.admin.inc', ); $items['admin/structure/types'] = array( 'title' => 'Content types', 'description' => 'Manage posts by content type, including default status, front page promotion, comment settings, etc.', 'page callback' => 'node_overview_types', 'access arguments' => array('administer content types'), 'file' => 'content_types.inc', ); $items['admin/structure/types/list'] = array( 'title' => 'List', 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10, ); $items['admin/structure/types/add'] = array( 'title' => 'Add content type', 'page callback' => 'drupal_get_form', 'page arguments' => array('node_type_form'), 'access arguments' => array('administer content types'), 'type' => MENU_LOCAL_ACTION, 'file' => 'content_types.inc', ); $items['node'] = array( 'title' => 'Content', 'page callback' => 'node_page_default', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK, ); $items['node/add'] = array( 'title' => 'Add new content', 'page callback' => 'node_add_page', 'access callback' => '_node_add_access', 'weight' => 1, 'menu_name' => 'management', 'file' => 'node.pages.inc', ); $items['rss.xml'] = array( 'title' => 'RSS feed', 'page callback' => 'node_feed', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK, ); // Reset internal static cache of _node_types_build, forces to rebuild the node type information. node_type_clear(); foreach (node_type_get_types() as $type) { $type_url_str = str_replace('_', '-', $type->type); $items['node/add/' . $type_url_str] = array( 'title' => $type->name, 'title callback' => 'check_plain', 'page callback' => 'node_add', 'page arguments' => array(2), 'access callback' => 'node_access', 'access arguments' => array('create', $type->type), 'description' => $type->description, 'file' => 'node.pages.inc', ); $items['admin/structure/node-type/' . $type_url_str] = array( 'title' => $type->name, 'page callback' => 'drupal_get_form', 'page arguments' => array('node_type_form', $type), 'access arguments' => array('administer content types'), 'type' => MENU_CALLBACK, 'file' => 'content_types.inc', ); $items['admin/structure/node-type/' . $type_url_str . '/edit'] = array( 'title' => 'Edit', 'type' => MENU_DEFAULT_LOCAL_TASK, ); $items['admin/structure/node-type/' . $type_url_str . '/delete'] = array( 'title' => 'Delete', 'page arguments' => array('node_type_delete_confirm', $type), 'access arguments' => array('administer content types'), 'type' => MENU_CALLBACK, 'file' => 'content_types.inc', ); } $items['node/%node'] = array( 'title callback' => 'node_page_title', 'title arguments' => array(1), 'page callback' => 'node_page_view', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('view', 1), 'type' => MENU_CALLBACK); $items['node/%node/view'] = array( 'title' => 'View', 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10); $items['node/%node/edit'] = array( 'title' => 'Edit', 'page callback' => 'node_page_edit', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'weight' => 1, 'type' => MENU_LOCAL_TASK, 'file' => 'node.pages.inc', ); $items['node/%node/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('node_delete_confirm', 1), 'access callback' => 'node_access', 'access arguments' => array('delete', 1), 'weight' => 1, 'type' => MENU_CALLBACK, 'file' => 'node.pages.inc', ); $items['node/%node/revisions'] = array( 'title' => 'Revisions', 'page callback' => 'node_revision_overview', 'page arguments' => array(1), 'access callback' => '_node_revision_access', 'access arguments' => array(1), 'weight' => 2, 'type' => MENU_LOCAL_TASK, 'file' => 'node.pages.inc', ); $items['node/%node/revisions/%/view'] = array( 'title' => 'Revisions', 'load arguments' => array(3), 'page callback' => 'node_show', 'page arguments' => array(1, TRUE), 'access callback' => '_node_revision_access', 'access arguments' => array(1), 'type' => MENU_CALLBACK, ); $items['node/%node/revisions/%/revert'] = array( 'title' => 'Revert to earlier revision', 'load arguments' => array(3), 'page callback' => 'drupal_get_form', 'page arguments' => array('node_revision_revert_confirm', 1), 'access callback' => '_node_revision_access', 'access arguments' => array(1, 'update'), 'type' => MENU_CALLBACK, 'file' => 'node.pages.inc', ); $items['node/%node/revisions/%/delete'] = array( 'title' => 'Delete earlier revision', 'load arguments' => array(3), 'page callback' => 'drupal_get_form', 'page arguments' => array('node_revision_delete_confirm', 1), 'access callback' => '_node_revision_access', 'access arguments' => array(1, 'delete'), 'type' => MENU_CALLBACK, 'file' => 'node.pages.inc', ); return $items; } /** * Title callback. */ function node_page_title($node) { return $node->title; } /** * Implement hook_init(). */ function node_init() { drupal_add_css(drupal_get_path('module', 'node') . '/node.css'); } function node_last_changed($nid) { return db_query('SELECT changed FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetch()->changed; } /** * Return a list of all the existing revision numbers. */ function node_revision_list($node) { $revisions = array(); $result = db_query('SELECT r.vid, r.title, r.log, r.uid, n.vid AS current_vid, r.timestamp, u.name FROM {node_revision} r LEFT JOIN {node} n ON n.vid = r.vid INNER JOIN {users} u ON u.uid = r.uid WHERE r.nid = :nid ORDER BY r.timestamp DESC', array(':nid' => $node->nid)); foreach ($result as $revision) { $revisions[$revision->vid] = $revision; } return $revisions; } /** * Implement hook_block_list(). */ function node_block_list() { $blocks['syndicate']['info'] = t('Syndicate'); // Not worth caching. $blocks['syndicate']['cache'] = BLOCK_NO_CACHE; return $blocks; } /** * Implement hook_block_view(). */ function node_block_view($delta = '') { $block['subject'] = t('Syndicate'); $block['content'] = theme('feed_icon', url('rss.xml'), t('Syndicate')); return $block; } /** * A generic function for generating RSS feeds from a set of nodes. * * @param $nids * An array of node IDs (nid). Defaults to FALSE so empty feeds can be * generated with passing an empty array, if no items are to be added * to the feed. * @param $channel * An associative array containing title, link, description and other keys. * The link should be an absolute URL. */ function node_feed($nids = FALSE, $channel = array()) { global $base_url, $language; if ($nids === FALSE) { $nids = db_select('node', 'n') ->fields('n', array('nid', 'created')) ->condition('n.promote', 1) ->condition('status', 1) ->orderBy('n.created', 'DESC') ->range(0, variable_get('feed_default_items', 10)) ->addTag('node_access') ->execute() ->fetchCol(); } $item_length = variable_get('feed_item_length', 'teaser'); $namespaces = array('xmlns:dc' => 'http://purl.org/dc/elements/1.1/'); $teaser = ($item_length == 'teaser'); // Load all nodes to be rendered. $nodes = node_load_multiple($nids); $items = ''; foreach ($nodes as $node) { $item_text = ''; $node->link = url("node/$node->nid", array('absolute' => TRUE)); $node->rss_namespaces = array(); $node->rss_elements = array( array('key' => 'pubDate', 'value' => gmdate('r', $node->created)), array('key' => 'dc:creator', 'value' => $node->name), array('key' => 'guid', 'value' => $node->nid . ' at ' . $base_url, 'attributes' => array('isPermaLink' => 'false')) ); // The node gets built and modules add to or modify $node->rss_elements // and $node->rss_namespaces. $node = node_build_content($node, 'rss'); if (!empty($node->rss_namespaces)) { $namespaces = array_merge($namespaces, $node->rss_namespaces); } if ($item_length != 'title' && !empty($node->content)) { // We render node contents and force links to be last. $links = drupal_render($node->content['links']); $item_text .= drupal_render($node->content) . $links; } $items .= format_rss_item($node->title, $node->link, $item_text, $node->rss_elements); } $channel_defaults = array( 'version' => '2.0', 'title' => variable_get('site_name', 'Drupal'), 'link' => $base_url, 'description' => variable_get('feed_description', ''), 'language' => $language->language ); $channel = array_merge($channel_defaults, $channel); $output = "\n"; $output .= "\n"; $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language']); $output .= "\n"; drupal_set_header('Content-Type', 'application/rss+xml; charset=utf-8'); print $output; } /** * Construct a drupal_render() style array from an array of loaded nodes. * * @param $nodes * An array of nodes as returned by node_load_multiple(). * @param $build_mode * Build mode, e.g. 'full', 'teaser'... * @param $weight * An integer representing the weight of the first node in the list. * @return * An array in the format expected by drupal_render(). */ function node_build_multiple($nodes, $build_mode = 'teaser', $weight = 0) { $build = array(); foreach ($nodes as $node) { $build['nodes'][$node->nid] = node_build($node, $build_mode); $build['nodes'][$node->nid]['#weight'] = $weight; $weight++; } $build['nodes']['#sorted'] = TRUE; return $build; } /** * Menu callback; Generate a listing of promoted nodes. */ function node_page_default() { $select = db_select('node', 'n') ->fields('n', array('nid')) ->condition('promote', 1) ->condition('status', 1) ->orderBy('sticky', 'DESC') ->orderBy('created', 'DESC') ->extend('PagerDefault') ->limit(variable_get('default_nodes_main', 10)) ->addTag('node_access'); $nids = $select->execute()->fetchCol(); if (!empty($nids)) { $nodes = node_load_multiple($nids); $build = node_build_multiple($nodes); $feed_url = url('rss.xml', array('absolute' => TRUE)); drupal_add_feed($feed_url, variable_get('site_name', 'Drupal') . ' ' . t('RSS')); $build['pager'] = array( '#theme' => 'pager', '#weight' => 5, ); drupal_set_title(''); } else { drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH); $default_message = '

' . t('No front page content has been created yet.') . '

'; $default_links = array(); if (_node_add_access()) { $default_links[] = l(t('Create content'), 'node/add'); } if (user_access('administer site configuration')) { $default_links[] = l(t('Change the default front page'), 'admin/settings/site-information'); } if (!empty($default_links)) { $default_message .= theme('item_list', $default_links); } $build['default_message'] = array( '#markup' => $default_message, '#prefix' => '
', '#suffix' => '
', ); } return $build; } /** * Menu callback; view a single node. */ function node_page_view($node) { drupal_set_title($node->title); return node_show($node); } /** * Implement hook_update_index(). */ function node_update_index() { $limit = (int)variable_get('search_cron_limit', 100); $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit); foreach ($result as $node) { _node_index_node($node); } } /** * Index a single node. * * @param $node * The node to index. */ function _node_index_node($node) { $node = node_load($node->nid); // Save the changed time of the most recent indexed node, for the search // results half-life calculation. variable_set('node_cron_last', $node->changed); // Render the node. $node = node_build_content($node, 'search_index'); $node->rendered = drupal_render($node->content); $text = '

' . check_plain($node->title) . '

' . $node->rendered; // Fetch extra data normally not visible $extra = module_invoke_all('node_update_index', $node); foreach ($extra as $t) { $text .= $t; } // Update index search_index($node->nid, 'node', $text); } /** * Implement hook_form_FORM_ID_alter(). */ function node_form_search_form_alter(&$form, $form_state) { if ($form['module']['#value'] == 'node' && user_access('use advanced search')) { // Keyword boxes: $form['advanced'] = array( '#type' => 'fieldset', '#title' => t('Advanced search'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#attributes' => array('class' => array('search-advanced')), ); $form['advanced']['keywords'] = array( '#prefix' => '
', '#suffix' => '
', ); $form['advanced']['keywords']['or'] = array( '#type' => 'textfield', '#title' => t('Containing any of the words'), '#size' => 30, '#maxlength' => 255, ); $form['advanced']['keywords']['phrase'] = array( '#type' => 'textfield', '#title' => t('Containing the phrase'), '#size' => 30, '#maxlength' => 255, ); $form['advanced']['keywords']['negative'] = array( '#type' => 'textfield', '#title' => t('Containing none of the words'), '#size' => 30, '#maxlength' => 255, ); // Taxonomy box: if ($taxonomy = module_invoke('taxonomy', 'form_all', 1)) { $form['advanced']['term'] = array( '#type' => 'select', '#title' => t('Only in the term(s)'), '#prefix' => '
', '#size' => 10, '#suffix' => '
', '#options' => $taxonomy, '#multiple' => TRUE, ); } // Node types: $types = array_map('check_plain', node_type_get_names()); $form['advanced']['type'] = array( '#type' => 'checkboxes', '#title' => t('Only of the type(s)'), '#prefix' => '
', '#suffix' => '
', '#options' => $types, ); $form['advanced']['submit'] = array( '#type' => 'submit', '#value' => t('Advanced search'), '#prefix' => '
', '#suffix' => '
', ); // Languages: $language_options = array(); foreach (language_list('language') as $key => $object) { $language_options[$key] = $object->name; } if (count($language_options) > 1) { $form['advanced']['language'] = array( '#type' => 'checkboxes', '#title' => t('Languages'), '#prefix' => '
', '#suffix' => '
', '#options' => $language_options, ); } $form['#validate'][] = 'node_search_validate'; } } /** * Form API callback for the search form. Registered in node_form_alter(). */ function node_search_validate($form, &$form_state) { // Initialize using any existing basic search keywords. $keys = $form_state['values']['processed_keys']; // Insert extra restrictions into the search keywords string. if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) { // Retrieve selected types - Forms API sets the value of unselected // checkboxes to 0. $form_state['values']['type'] = array_filter($form_state['values']['type']); if (count($form_state['values']['type'])) { $keys = search_query_insert($keys, 'type', implode(',', array_keys($form_state['values']['type']))); } } if (isset($form_state['values']['term']) && is_array($form_state['values']['term'])) { $keys = search_query_insert($keys, 'term', implode(',', $form_state['values']['term'])); } if (isset($form_state['values']['language']) && is_array($form_state['values']['language'])) { $keys = search_query_insert($keys, 'language', implode(',', array_filter($form_state['values']['language']))); } if ($form_state['values']['or'] != '') { if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['or'], $matches)) { $keys .= ' ' . implode(' OR ', $matches[1]); } } if ($form_state['values']['negative'] != '') { if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['negative'], $matches)) { $keys .= ' -' . implode(' -', $matches[1]); } } if ($form_state['values']['phrase'] != '') { $keys .= ' "' . str_replace('"', ' ', $form_state['values']['phrase']) . '"'; } if (!empty($keys)) { form_set_value($form['basic']['inline']['processed_keys'], trim($keys), $form_state); } } /** * @defgroup node_access Node access rights * @{ * The node access system determines who can do what to which nodes. * * In determining access rights for a node, node_access() first checks * whether the user has the "bypass node access" permission. Such users have * unrestricted access to all nodes. user 1 will always pass this check. * * Next, all implementations of hook_node_access() will be called. Each * implementation may explicitly allow, explicitly deny, or ignore the access * request. If at least one module says to deny the request, it will be rejected. * If no modules deny the request and at least one says to allow it, the request * will be permitted. * * If all modules ignore the access request, then the node_access table is used * to determine access. All node access modules are queried using * hook_node_grants() to assemble a list of "grant IDs" for the user. This list * is compared against the table. If any row contains the node ID in question * (or 0, which stands for "all nodes"), one of the grant IDs returned, and a * value of TRUE for the operation in question, then access is granted. Note * that this table is a list of grants; any matching row is sufficient to * grant access to the node. * * In node listings, the process above is followed except that * hook_node_access() is not called on each node for performance reasons and for * proper functioning of the pager system. When adding a node listing to your * module, be sure to use a dynamic query created by db_select() and add a tag * of "node_access" to ensure that only nodes to which the user has access * are retrieved. * * Note: Even a single module returning NODE_ACCESS_DENY from hook_node_access() * will block access to the node. Therefore, implementers should take care to * not deny access unless they really intend to. Unless a module wishes to * actively deny access it should return NODE_ACCESS_IGNORE (or simply return * nothing) to allow other modules or the node_access table to control access. * * To see how to write a node access module of your own, see * node_access_example.module. */ /** * Determine whether the current user may perform the given operation on the * specified node. * * @param $op * The operation to be performed on the node. Possible values are: * - "view" * - "update" * - "delete" * - "create" * @param $node * The node object (or node array) on which the operation is to be performed, * or node type (e.g. 'forum') for "create" operation. * @param $account * Optional, a user object representing the user for whom the operation is to * be performed. Determines access for a user other than the current user. * @return * TRUE if the operation may be performed. */ function node_access($op, $node, $account = NULL) { global $user; if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) { // If there was no node to check against, or the $op was not one of the // supported ones, we return access denied. return FALSE; } // Convert the node to an object if necessary: if ($op != 'create') { $node = (object)$node; } // If no user object is supplied, the access check is for the current user. if (empty($account)) { $account = $user; } if (user_access('bypass node access', $account)) { return TRUE; } if (!user_access('access content', $account)) { return FALSE; } // We grant access to the node if both of the following conditions are met: // - No modules say to deny access. // - At least one module says to grant access. // If no module specified either allow or deny, we fall back to the // node_access table. $access = module_invoke_all('node_access', $node, $op, $account); if (in_array(NODE_ACCESS_DENY, $access, TRUE)) { return FALSE; } elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) { return TRUE; } // Check if authors can view their own unpublished nodes. if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) { return TRUE; } // If the module did not override the access rights, use those set in the // node_access table. if ($op != 'create' && $node->nid) { $query = db_select('node_access'); $query->addExpression('COUNT(*)'); $query->condition('grant_' . $op, 1, '>='); $nids = db_or()->condition('nid', $node->nid); if ($node->status) { $nids->condition('nid', 0); } $query->condition($nids); $grants = db_or(); foreach (node_access_grants($op, $account) as $realm => $gids) { foreach ($gids as $gid) { $grants->condition(db_and() ->condition('gid', $gid) ->condition('realm', $realm) ); } } if (count($grants) > 0 ) { $query->condition($grants); } return $query ->execute() ->fetchField(); } return FALSE; } /** * Implement hook_node_access(). */ function node_node_access($node, $op, $account) { $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type); if (in_array($type, node_permissions_get_configured_types())) { if ($op == 'create' && user_access('create ' . $type . ' content', $account)) { return NODE_ACCESS_ALLOW; } if ($op == 'update') { if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) { return NODE_ACCESS_ALLOW; } } if ($op == 'delete') { if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) { return NODE_ACCESS_ALLOW; } } } return NODE_ACCESS_IGNORE; } /** * Helper function to generate standard node permission list for a given type. * * @param $type * The machine-readable name of the node type. * @return array * An array of permission names and descriptions. */ function node_list_permissions($type) { $info = node_type_get_type($type); $type = check_plain($info->type); // Build standard list of node permissions for this type. $perms = array( "create $type content" => array( 'title' => t('Create %type_name content', array('%type_name' => $info->name)), 'description' => t('Create new %type_name content.', array('%type_name' => $info->name)), ), "edit own $type content" => array( 'title' => t('Edit own %type_name content', array('%type_name' => $info->name)), 'description' => t('Edit %type_name content created by the user.', array('%type_name' => $info->name)), ), "edit any $type content" => array( 'title' => t('Edit any %type_name content', array('%type_name' => $info->name)), 'description' => t('Edit any %type_name content, regardless of its author.', array('%type_name' => $info->name)), ), "delete own $type content" => array( 'title' => t('Delete own %type_name content', array('%type_name' => $info->name)), 'description' => t('Delete %type_name content created by the user.', array('%type_name' => $info->name)), ), "delete any $type content" => array( 'title' => t('Delete any %type_name content', array('%type_name' => $info->name)), 'description' => t('Delete any %type_name content, regardless of its author.', array('%type_name' => $info->name)), ), ); return $perms; } /** * Returns an array of node types that should be managed by permissions. * * By default, this will include all node types in the system. To exclude a * specific node from getting permissions defined for it, set the * node_permissions_$type variable to 0. Core does not provide an interface * for doing so, however, contrib modules may exclude their own nodes in * hook_install(). Alternatively, contrib modules may configure all node types * at once, or decide to apply some other hook_node_access() implementation * to some or all node types. * * @return * An array of node types managed by this module. */ function node_permissions_get_configured_types() { $configured_types = array(); foreach (node_type_get_types() as $type => $info) { if (variable_get('node_permissions_' . $type, 1)) { $configured_types[] = $type; } } return $configured_types; } /** * Generate an SQL join clause for use in fetching a node listing. * * @param $node_alias * If the node table has been given an SQL alias other than the default * "n", that must be passed here. * @param $node_access_alias * If the node_access table has been given an SQL alias other than the default * "na", that must be passed here. * @return * An SQL join clause. */ function _node_access_join_sql($node_alias = 'n', $node_access_alias = 'na') { if (user_access('bypass node access')) { return ''; } return 'INNER JOIN {node_access} ' . $node_access_alias . ' ON ' . $node_access_alias . '.nid = ' . $node_alias . '.nid'; } /** * Generate an SQL where clause for use in fetching a node listing. * * @param $op * The operation that must be allowed to return a node. * @param $node_access_alias * If the node_access table has been given an SQL alias other than the default * "na", that must be passed here. * @param $account * The user object for the user performing the operation. If omitted, the * current user is used. * @return * An SQL where clause. */ function _node_access_where_sql($op = 'view', $node_access_alias = 'na', $account = NULL) { if (user_access('bypass node access')) { return; } $grants = array(); foreach (node_access_grants($op, $account) as $realm => $gids) { foreach ($gids as $gid) { $grants[] = "($node_access_alias.gid = $gid AND $node_access_alias.realm = '$realm')"; } } $grants_sql = ''; if (count($grants)) { $grants_sql = 'AND (' . implode(' OR ', $grants) . ')'; } $sql = "$node_access_alias.grant_$op >= 1 $grants_sql"; return $sql; } /** * Fetch an array of permission IDs granted to the given user ID. * * The implementation here provides only the universal "all" grant. A node * access module should implement hook_node_grants() to provide a grant * list for the user. * * After the default grants have been loaded, we allow modules to alter * the grants array by reference. This hook allows for complex business * logic to be applied when integrating multiple node access modules. * * @param $op * The operation that the user is trying to perform. * @param $account * The user object for the user performing the operation. If omitted, the * current user is used. * @return * An associative array in which the keys are realms, and the values are * arrays of grants for those realms. */ function node_access_grants($op, $account = NULL) { if (!isset($account)) { $account = $GLOBALS['user']; } // Fetch node access grants from other modules. $grants = module_invoke_all('node_grants', $account, $op); // Allow modules to alter the assigned grants. drupal_alter('node_grants', $grants, $account, $op); return array_merge(array('all' => array(0)), $grants); } /** * Determine whether the user has a global viewing grant for all nodes. */ function node_access_view_all_nodes() { static $access; if (!isset($access)) { // If no modules implement the node access system, access is always true. if (!module_implements('node_grants')) { $access = TRUE; } else { $query = db_select('node_access'); $query->addExpression('COUNT(*)'); $query ->condition('nid', 0) ->condition('grant_view', 1, '>='); $grants = db_or(); foreach (node_access_grants('view') as $realm => $gids) { foreach ($gids as $gid) { $grants->condition(db_and() ->condition('gid', $gid) ->condition('realm', $realm) ); } } if (count($grants) > 0 ) { $query->condition($grants); } $access = $query ->execute() ->fetchField(); } } return $access; } /** * Implement hook_db_rewrite_sql(). */ function node_db_rewrite_sql($query, $primary_table, $primary_field) { if ($primary_field == 'nid' && !node_access_view_all_nodes()) { $return['join'] = _node_access_join_sql($primary_table); $return['where'] = _node_access_where_sql(); $return['distinct'] = 1; return $return; } } /** * Implement hook_query_TAG_alter(). */ function node_query_node_access_alter(QueryAlterableInterface $query) { // Skip the extra expensive alterations if site has no node access control // modules. if (!node_access_view_all_nodes()) { // Prevent duplicate records. $query->distinct(); // The recognized operations are 'view', 'update', 'delete'. if (!$op = $query->getMetaData('op')) { $op = 'view'; } // Skip the extra joins and conditions for node admins. if (!user_access('bypass node access')) { // The node_access table has the access grants for any given node. $access_alias = $query->join('node_access', 'na', 'na.nid = n.nid'); $or = db_or(); // If any grant exists for the specified user, then user has access to the // node for the specified operation. foreach (node_access_grants($op, $query->getMetaData('account')) as $realm => $gids) { foreach ($gids as $gid) { $or->condition(db_and() ->condition("{$access_alias}.gid", $gid) ->condition("{$access_alias}.realm", $realm) ); } } if (count($or->conditions())) { $query->condition($or); } $query->condition("{$access_alias}.grant_$op", 1, '>='); } } } /** * This function will call module invoke to get a list of grants and then * write them to the database. It is called at node save, and should be * called by modules whenever something other than a node_save causes * the permissions on a node to change. * * After the default grants have been loaded, we allow modules to alter * the grants array by reference. This hook allows for complex business * logic to be applied when integrating multiple node access modules. * * @see hook_node_access_records() * * This function is the only function that should write to the node_access * table. * * @param $node * The $node to acquire grants for. */ function node_access_acquire_grants($node) { $grants = module_invoke_all('node_access_records', $node); // Let modules alter the grants. drupal_alter('node_access_records', $grants, $node); // If no grants are set, then use the default grant. if (empty($grants)) { $grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0); } else { // Retain grants by highest priority. $grant_by_priority = array(); foreach ($grants as $g) { $grant_by_priority[intval($g['priority'])][] = $g; } krsort($grant_by_priority); $grants = array_shift($grant_by_priority); } node_access_write_grants($node, $grants); } /** * This function will write a list of grants to the database, deleting * any pre-existing grants. If a realm is provided, it will only * delete grants from that realm, but it will always delete a grant * from the 'all' realm. Modules which utilize node_access can * use this function when doing mass updates due to widespread permission * changes. * * @param $node * The $node being written to. All that is necessary is that it contain a nid. * @param $grants * A list of grants to write. Each grant is an array that must contain the * following keys: realm, gid, grant_view, grant_update, grant_delete. * The realm is specified by a particular module; the gid is as well, and * is a module-defined id to define grant privileges. each grant_* field * is a boolean value. * @param $realm * If provided, only read/write grants for that realm. * @param $delete * If false, do not delete records. This is only for optimization purposes, * and assumes the caller has already performed a mass delete of some form. */ function node_access_write_grants($node, $grants, $realm = NULL, $delete = TRUE) { if ($delete) { $query = db_delete('node_access')->condition('nid', $node->nid); if ($realm) { $query->condition('realm', array($realm, 'all'), 'IN'); } $query->execute(); } // Only perform work when node_access modules are active. if (count(module_implements('node_grants'))) { $query = db_insert('node_access')->fields(array('nid', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete')); foreach ($grants as $grant) { if ($realm && $realm != $grant['realm']) { continue; } // Only write grants; denies are implicit. if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) { $grant['nid'] = $node->nid; $query->values($grant); } } $query->execute(); } } /** * Flag / unflag the node access grants for rebuilding, or read the current * value of the flag. * * When the flag is set, a message is displayed to users with 'access * administration pages' permission, pointing to the 'rebuild' confirm form. * This can be used as an alternative to direct node_access_rebuild calls, * allowing administrators to decide when they want to perform the actual * (possibly time consuming) rebuild. * When unsure the current user is an adminisrator, node_access_rebuild * should be used instead. * * @param $rebuild * (Optional) The boolean value to be written. * @return * (If no value was provided for $rebuild) The current value of the flag. */ function node_access_needs_rebuild($rebuild = NULL) { if (!isset($rebuild)) { return variable_get('node_access_needs_rebuild', FALSE); } elseif ($rebuild) { variable_set('node_access_needs_rebuild', TRUE); } else { variable_del('node_access_needs_rebuild'); } } /** * Rebuild the node access database. This is occasionally needed by modules * that make system-wide changes to access levels. * * When the rebuild is required by an admin-triggered action (e.g module * settings form), calling node_access_needs_rebuild(TRUE) instead of * node_access_rebuild() lets the user perform his changes and actually * rebuild only once he is done. * * Note : As of Drupal 6, node access modules are not required to (and actually * should not) call node_access_rebuild() in hook_enable/disable anymore. * * @see node_access_needs_rebuild() * * @param $batch_mode * Set to TRUE to process in 'batch' mode, spawning processing over several * HTTP requests (thus avoiding the risk of PHP timeout if the site has a * large number of nodes). * hook_update_N and any form submit handler are safe contexts to use the * 'batch mode'. Less decidable cases (such as calls from hook_user, * hook_taxonomy, etc...) might consider using the non-batch mode. */ function node_access_rebuild($batch_mode = FALSE) { db_delete('node_access')->execute(); // Only recalculate if the site is using a node_access module. if (count(module_implements('node_grants'))) { if ($batch_mode) { $batch = array( 'title' => t('Rebuilding content access permissions'), 'operations' => array( array('_node_access_rebuild_batch_operation', array()), ), 'finished' => '_node_access_rebuild_batch_finished' ); batch_set($batch); } else { // Try to allocate enough time to rebuild node grants drupal_set_time_limit(240); $nids = db_query("SELECT nid FROM {node}")->fetchCol(); foreach ($nids as $nid) { $node = node_load($nid, NULL, TRUE); // To preserve database integrity, only acquire grants if the node // loads successfully. if (!empty($node)) { node_access_acquire_grants($node); } } } } else { // Not using any node_access modules. Add the default grant. db_insert('node_access') ->fields(array( 'nid' => 0, 'realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0, )) ->execute(); } if (!isset($batch)) { drupal_set_message(t('Content permissions have been rebuilt.')); node_access_needs_rebuild(FALSE); cache_clear_all(); } } /** * Batch operation for node_access_rebuild_batch. * * This is a multistep operation : we go through all nodes by packs of 20. * The batch processing engine interrupts processing and sends progress * feedback after 1 second execution time. */ function _node_access_rebuild_batch_operation(&$context) { if (empty($context['sandbox'])) { // Initiate multistep processing. $context['sandbox']['progress'] = 0; $context['sandbox']['current_node'] = 0; $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField(); } // Process the next 20 nodes. $limit = 20; $nids = db_query_range("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", array(':nid' => $context['sandbox']['current_node']), 0, $limit)->fetchCol(); $nodes = node_load_multiple($nids, array(), TRUE); foreach ($nodes as $node) { // To preserve database integrity, only acquire grants if the node // loads successfully. if (!empty($node)) { node_access_acquire_grants($node); } $context['sandbox']['progress']++; $context['sandbox']['current_node'] = $node->nid; } // Multistep processing : report progress. if ($context['sandbox']['progress'] != $context['sandbox']['max']) { $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max']; } } /** * Post-processing for node_access_rebuild_batch. */ function _node_access_rebuild_batch_finished($success, $results, $operations) { if ($success) { drupal_set_message(t('The content access permissions have been rebuilt.')); node_access_needs_rebuild(FALSE); } else { drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error'); } cache_clear_all(); } /** * @} End of "defgroup node_access". */ /** * @defgroup node_content Hook implementations for user-created content types. * @{ */ /** * Implement hook_form(). */ function node_content_form($node, $form_state) { $type = node_type_get_type($node); $form = array(); if ($type->has_title) { $form['title'] = array( '#type' => 'textfield', '#title' => check_plain($type->title_label), '#required' => TRUE, '#default_value' => $node->title, '#maxlength' => 255, '#weight' => -5, ); } return $form; } /** * @} End of "defgroup node_content". */ /** * Implement hook_forms(). * All node forms share the same form handler. */ function node_forms() { $forms = array(); if ($types = node_type_get_types()) { foreach (array_keys($types) as $type) { $forms[$type . '_node_form']['callback'] = 'node_form'; } } return $forms; } /** * Format the "Submitted by username on date/time" for each node * * @ingroup themeable */ function theme_node_submitted($node) { return t('Submitted by !username on @datetime', array( '!username' => theme('username', $node), '@datetime' => format_date($node->created), )); } /** * Implement hook_hook_info(). */ function node_hook_info() { return array( 'node' => array( 'node' => array( 'presave' => array( 'runs when' => t('When either saving a new post or updating an existing post'), ), 'insert' => array( 'runs when' => t('After saving a new post'), ), 'update' => array( 'runs when' => t('After saving an updated post'), ), 'delete' => array( 'runs when' => t('After deleting a post') ), 'view' => array( 'runs when' => t('When content is viewed by an authenticated user') ), ), ), ); } /** * Implement hook_action_info(). */ function node_action_info() { return array( 'node_publish_action' => array( 'type' => 'node', 'description' => t('Publish post'), 'configurable' => FALSE, 'behavior' => array('changes_node_property'), 'hooks' => array( 'node' => array('presave'), 'comment' => array('insert', 'update'), ), ), 'node_unpublish_action' => array( 'type' => 'node', 'description' => t('Unpublish post'), 'configurable' => FALSE, 'behavior' => array('changes_node_property'), 'hooks' => array( 'node' => array('presave'), 'comment' => array('delete', 'insert', 'update'), ), ), 'node_make_sticky_action' => array( 'type' => 'node', 'description' => t('Make post sticky'), 'configurable' => FALSE, 'behavior' => array('changes_node_property'), 'hooks' => array( 'node' => array('presave'), 'comment' => array('insert', 'update'), ), ), 'node_make_unsticky_action' => array( 'type' => 'node', 'description' => t('Make post unsticky'), 'configurable' => FALSE, 'behavior' => array('changes_node_property'), 'hooks' => array( 'node' => array('presave'), 'comment' => array('delete', 'insert', 'update'), ), ), 'node_promote_action' => array( 'type' => 'node', 'description' => t('Promote post to front page'), 'configurable' => FALSE, 'behavior' => array('changes_node_property'), 'hooks' => array( 'node' => array('presave'), 'comment' => array('insert', 'update'), ), ), 'node_unpromote_action' => array( 'type' => 'node', 'description' => t('Remove post from front page'), 'configurable' => FALSE, 'behavior' => array('changes_node_property'), 'hooks' => array( 'node' => array('presave'), 'comment' => array('delete', 'insert', 'update'), ), ), 'node_assign_owner_action' => array( 'type' => 'node', 'description' => t('Change the author of a post'), 'configurable' => TRUE, 'behavior' => array('changes_node_property'), 'hooks' => array( 'any' => TRUE, 'node' => array('presave'), 'comment' => array('delete', 'insert', 'update'), ), ), 'node_save_action' => array( 'type' => 'node', 'description' => t('Save post'), 'configurable' => FALSE, 'hooks' => array( 'comment' => array('delete', 'insert', 'update'), ), ), 'node_unpublish_by_keyword_action' => array( 'type' => 'node', 'description' => t('Unpublish post containing keyword(s)'), 'configurable' => TRUE, 'hooks' => array( 'node' => array('presave', 'insert', 'update'), ), ), ); } /** * Implement a Drupal action. * Sets the status of a node to 1, meaning published. */ function node_publish_action($node, $context = array()) { $node->status = 1; watchdog('action', 'Set @type %title to published.', array('@type' => node_type_get_name($node), '%title' => $node->title)); } /** * Implement a Drupal action. * Sets the status of a node to 0, meaning unpublished. */ function node_unpublish_action($node, $context = array()) { $node->status = 0; watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title)); } /** * Implement a Drupal action. * Sets the sticky-at-top-of-list property of a node to 1. */ function node_make_sticky_action($node, $context = array()) { $node->sticky = 1; watchdog('action', 'Set @type %title to sticky.', array('@type' => node_type_get_name($node), '%title' => $node->title)); } /** * Implement a Drupal action. * Sets the sticky-at-top-of-list property of a node to 0. */ function node_make_unsticky_action($node, $context = array()) { $node->sticky = 0; watchdog('action', 'Set @type %title to unsticky.', array('@type' => node_type_get_name($node), '%title' => $node->title)); } /** * Implement a Drupal action. * Sets the promote property of a node to 1. */ function node_promote_action($node, $context = array()) { $node->promote = 1; watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title)); } /** * Implement a Drupal action. * Sets the promote property of a node to 0. */ function node_unpromote_action($node, $context = array()) { $node->promote = 0; watchdog('action', 'Removed @type %title from front page.', array('@type' => node_type_get_name($node), '%title' => $node->title)); } /** * Implement a Drupal action. * Saves a node. */ function node_save_action($node) { node_save($node); watchdog('action', 'Saved @type %title', array('@type' => node_type_get_name($node), '%title' => $node->title)); } /** * Implement a configurable Drupal action. * Assigns ownership of a node to a user. */ function node_assign_owner_action($node, $context) { $node->uid = $context['owner_uid']; $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField(); watchdog('action', 'Changed owner of @type %title to uid %name.', array('@type' => node_type_get_type($node), '%title' => $node->title, '%name' => $owner_name)); } function node_assign_owner_action_form($context) { $description = t('The username of the user to which you would like to assign ownership.'); $count = db_query("SELECT COUNT(*) FROM {users}")->fetchField(); $owner_name = ''; if (isset($context['owner_uid'])) { $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField(); } // Use dropdown for fewer than 200 users; textbox for more than that. if (intval($count) < 200) { $options = array(); $result = db_query("SELECT uid, name FROM {users} WHERE uid > 0 ORDER BY name"); foreach ($result as $data) { $options[$data->name] = $data->name; } $form['owner_name'] = array( '#type' => 'select', '#title' => t('Username'), '#default_value' => $owner_name, '#options' => $options, '#description' => $description, ); } else { $form['owner_name'] = array( '#type' => 'textfield', '#title' => t('Username'), '#default_value' => $owner_name, '#autocomplete_path' => 'user/autocomplete', '#size' => '6', '#maxlength' => '7', '#description' => $description, ); } return $form; } function node_assign_owner_action_validate($form, $form_state) { $exists = (bool) db_query_range('SELECT 1 FROM {users} WHERE name = :name', array(':name' => $form_state['values']['owner_name']), 0, 1)->fetchField(); if (!$exists) { form_set_error('owner_name', t('Please enter a valid username.')); } } function node_assign_owner_action_submit($form, $form_state) { // Username can change, so we need to store the ID, not the username. $uid = db_query('SELECT uid from {users} WHERE name = :name', array(':name' => $form_state['values']['owner_name']))->fetchField(); return array('owner_uid' => $uid); } function node_unpublish_by_keyword_action_form($context) { $form['keywords'] = array( '#title' => t('Keywords'), '#type' => 'textarea', '#description' => t('The post will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'), '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '', ); return $form; } function node_unpublish_by_keyword_action_submit($form, $form_state) { return array('keywords' => drupal_explode_tags($form_state['values']['keywords'])); } /** * Implement a configurable Drupal action. * Unpublish a node if it contains a certain string. * * @param $context * An array providing more information about the context of the call to this * action. * @param $comment * A node object. */ function node_unpublish_by_keyword_action($node, $context) { foreach ($context['keywords'] as $keyword) { if (strpos(drupal_render(node_build(clone $node)), $keyword) !== FALSE || strpos($node->title, $keyword) !== FALSE) { $node->status = 0; watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title)); break; } } } /** * Implement hook_requirements(). */ function node_requirements($phase) { $requirements = array(); // Ensure translations don't break at install time $t = get_t(); // Only show rebuild button if there are either 0, or 2 or more, rows // in the {node_access} table, or if there are modules that // implement hook_node_grants(). $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField(); if ($grant_count != 1 || count(module_implements('node_grants')) > 0) { $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count)); } else { $value = $t('Disabled'); } $description = $t('If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Rebuilding will remove all privileges to posts, and replace them with permissions based on the current modules and settings. Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed posts will automatically use the new permissions.'); $requirements['node_access'] = array( 'title' => $t('Node Access Permissions'), 'value' => $value, 'description' => $description . ' ' . l(t('Rebuild permissions'), 'admin/reports/status/rebuild'), ); return $requirements; }