', array(), '301');
}
else {
$site_config = config('system.core');
$select = db_select('node', 'n')
->fields('n', array('nid', 'sticky', 'created'))
->condition('n.promote', 1)
->condition('n.status', 1)
->orderBy('n.sticky', 'DESC')
->orderBy('n.created', 'DESC')
->extend('PagerDefault')
->limit($site_config->get('default_nodes_main'))
->addTag('node_access');
$nids = $select->execute()->fetchCol();
if (!empty($nids)) {
$nodes = node_load_multiple($nids);
$build = node_view_multiple($nodes);
// 'rss.xml' is a path, not a file, registered in node_menu().
backdrop_add_feed('rss.xml', $site_config->getTranslated('site_name') . ' ' . t('RSS'));
$build['pager'] = array(
'#theme' => 'pager',
'#weight' => 5,
);
backdrop_set_title('');
}
else {
backdrop_set_title(t('Welcome to @site-name', array('@site-name' => $site_config->getTranslated('site_name'))), PASS_THROUGH);
$default_message = '' . t('No content has been promoted yet.') . '
';
$default_links = array();
if (_node_add_access()) {
$default_links[] = l(t('Add content'), 'node/add');
}
if (!empty($default_links)) {
$default_message .= theme('item_list', array('items' => $default_links));
}
$build['default_message'] = array(
'#markup' => $default_message,
'#prefix' => '',
'#suffix' => '
',
);
}
return $build;
}
}
/**
* Page callback: Displays a single node.
*
* @param Node $node
* The node entity.
*
* @return
* A page array suitable for use by backdrop_render().
*
* @see node_menu()
*/
function node_page_view(Node $node) {
// Determine if user has permission to view full page directly.
// Display "page not found" if not.
$type = node_type_get_type($node);
$bypass_hidden_path = user_access('view hidden paths');
if ($type->settings['hidden_path'] && !$bypass_hidden_path) {
backdrop_not_found();
backdrop_exit();
}
// If there is a menu link to this node, the link becomes the last part
// of the active trail, and the link name becomes the page title.
// Thus, we must explicitly set the page title to be the node title.
backdrop_set_title($node->title);
// Set the node path as the canonical URL to prevent duplicate content.
$uri = entity_uri('node', $node);
$canonical_secure = config_get('system.core', 'canonical_secure') ? TRUE : FALSE;
$uri_options = array('absolute' => TRUE, 'https' => $canonical_secure);
backdrop_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], array_merge($uri['options'], $uri_options))), TRUE);
return node_show($node);
}
/**
* Implements hook_update_index().
*/
function node_update_index() {
$limit = (int)config_get('search.settings', 'search_cron_limit');
$result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));
$nids = $result->fetchCol();
if (!$nids) {
return;
}
foreach (node_load_multiple($nids) as $node) {
_node_index_node($node);
}
}
/**
* Indexes a single node.
*
* @param Node $node
* The node to index.
*/
function _node_index_node(Node $node) {
// Save the changed time of the most recent indexed node, for the search
// results half-life calculation.
state_set('node_cron_last', $node->changed);
// Render the node.
$build = node_view($node, 'search_index');
unset($build['#theme']);
$node->rendered = backdrop_render($build);
$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);
}
/**
* Implements hook_form_FORM_ID_alter().
*
* @see node_search_validate()
*/
function node_form_search_form_alter(&$form, $form_state) {
if (isset($form['module']) && $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,
);
// Node types:
$types = array();
foreach (node_type_get_types() as $type => $detail) {
if (!$detail->settings['hidden_path'] || user_access('view hidden paths') ) {
$types[$type] = $detail->name;
}
}
$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' => '
',
'#weight' => 100,
);
// Languages:
$language_options = language_list(TRUE, TRUE);
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 validation handler for node_form_search_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 - Form 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_expression_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
}
}
if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
$keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
}
if (isset($form_state['values']['language']) && is_array($form_state['values']['language'])) {
$languages = array_filter($form_state['values']['language']);
if (count($languages)) {
$keys = search_expression_insert($keys, 'langcode', implode(',', $languages));
}
}
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']['processed_keys'], trim($keys), $form_state);
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Alters the theme form to use the admin theme on node editing.
*
* @see node_form_system_themes_admin_form_submit()
*/
function node_form_system_themes_admin_form_alter(&$form, &$form_state, $form_id) {
$form['admin_theme']['node_admin_theme'] = array(
'#type' => 'checkbox',
'#title' => t('Use the administration theme when editing or creating content'),
'#default_value' => config_get('system.core', 'node_admin_theme'),
'#states' => array(
'visible' => array(
array(
// Hide this checkbox if "Default theme" has been selected from the
// "Administration theme" dropdown menu.
':input[name="admin_theme"]' => array('!value' => 0),
),
),
),
);
$form['#submit'][] = 'node_form_system_themes_admin_form_submit';
}
/**
* Form submission handler for system_themes_admin_form().
*
* @see node_form_system_themes_admin_form_alter()
*/
function node_form_system_themes_admin_form_submit($form, &$form_state) {
config_set('system.core', 'node_admin_theme', $form_state['values']['node_admin_theme']);
}
/**
* @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 (lists of nodes generated from a select query, such as the
* default home page at path 'node', an RSS feed, a recent content block, etc.),
* 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". This will allow
* modules dealing with node access to ensure only nodes to which the user has
* access are retrieved, through the use of hook_query_TAG_alter(). Tagging a
* query with "node_access" does not check the published/unpublished status of
* nodes, so the base query is responsible for ensuring that unpublished nodes
* are not displayed to inappropriate users.
*
* 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 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.
*/
/**
* Access callback: Checks a user's permission for performing a node operation.
*
* @param string $op
* The operation to be performed on the node. Possible values are:
* - create
* - view
* - update
* - delete
* @param Node|string $node
* The node entity on which the operation is to be performed, or the node type
* (e.g., 'post') for the 'create' operation.
* @param User $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 bool
* TRUE if the operation may be performed, FALSE otherwise.
*
* @see node_menu()
*/
function node_access($op, $node, $account = NULL) {
if ($op == 'create') {
// In some cases a node object, rather than a bundle string is provided.
if (is_string($node)) {
$bundle = $node;
}
else {
$bundle = $node->bundle();
}
return Node::createAccess($bundle, $account);
}
elseif ($node instanceof Node) {
return $node->access($op, $account);
}
return FALSE;
}
/**
* Implements hook_node_access().
*
* @param Node|string $node
* The loaded Node object.
* @param string $op
* The operation to be performed on the node. Possible values are:
* - create
* - view
* - update
* - delete
* @param User $account
* The User account for the person performing the operation.
*
* @return string
*/
function node_node_access($node, $op, $account) {
$type = is_string($node) ? $node : $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);
// Build standard list of node permissions for this type.
$perms = array(
"create $type content" => array(
'title' => t('%type_name: Create new content', array('%type_name' => $info->name)),
),
"edit own $type content" => array(
'title' => t('%type_name: Edit own content', array('%type_name' => $info->name)),
),
"edit any $type content" => array(
'title' => t('%type_name: Edit any content', array('%type_name' => $info->name)),
),
"delete own $type content" => array(
'title' => t('%type_name: Delete own content', array('%type_name' => $info->name)),
),
"delete any $type content" => array(
'title' => t('%type_name: Delete any content', 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 ($info->settings['node_permissions']) {
$configured_types[] = $type;
}
}
return $configured_types;
}
/**
* Fetches 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
* (optional) 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.
backdrop_alter('node_grants', $grants, $account, $op);
return array_merge(array('all' => array(0)), $grants);
}
/**
* Determines whether the user has a global viewing grant for all nodes.
*
* Checks to see whether any module grants global 'view' access to a user
* account; global 'view' access is encoded in the {node_access} table as a
* grant with nid=0. If no node access modules are enabled, node.module defines
* such a global 'view' access grant.
*
* This function is called when a node listing query is tagged with
* 'node_access'; when this function returns TRUE, no node access joins are
* added to the query.
*
* @param $account
* (optional) The user object for the user whose access is being checked. If
* omitted, the current user is used.
*
* @return
* TRUE if 'view' access to all nodes is granted, FALSE otherwise.
*
* @see hook_node_grants()
* @see _node_query_node_access_alter()
*/
function node_access_view_all_nodes($account = NULL) {
global $user;
if (!$account) {
$account = $user;
}
// Statically cache results in an array keyed by $account->uid.
$access = &backdrop_static(__FUNCTION__);
if (isset($access[$account->uid])) {
return $access[$account->uid];
}
// If no modules implement the node access system, access is always TRUE.
if (!module_implements('node_grants')) {
$access[$account->uid] = 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', $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);
}
$access[$account->uid] = $query
->execute()
->fetchField();
}
return $access[$account->uid];
}
/**
* Implements hook_query_TAG_alter().
*
* This is the hook_query_alter() for queries tagged with 'node_access'. It adds
* node access checks for the user account given by the 'account' meta-data (or
* global $user if not provided), for an operation given by the 'op' meta-data
* (or 'view' if not provided; other possible values are 'update' and 'delete').
*/
function node_query_node_access_alter(QueryAlterableInterface $query) {
_node_query_node_access_alter($query, 'node');
if (module_exists('search')) {
_node_search_query_alter($query);
}
}
/**
* Implements hook_query_TAG_alter().
*
* This function implements the same functionality as
* node_query_node_access_alter() for the SQL field storage engine. Node access
* conditions are added for field values belonging to nodes only.
*/
function node_query_entity_field_access_alter(QueryAlterableInterface $query) {
_node_query_node_access_alter($query, 'entity');
}
/**
* Helper for node access functions.
*
* Queries tagged with 'node_access' that are not against the {node} table
* should add the base table as metadata. For example:
* @code
* $query
* ->addTag('node_access')
* ->addMetaData('base_table', 'taxonomy_index');
* @endcode
*
* Queries tagged with 'node_access' that are not against the {node} table
* must add the base table as metadata. For example:
* @code
* $query
* ->addTag('node_access')
* ->addMetaData('base_table', 'taxonomy_index');
* @endcode
*
* @param SelectQuery|QueryAlterableInterface $query
* The query to which conditions will be added.
* @param string $type
* Either 'node' or 'entity' depending on what sort of query it is. See
* node_query_node_access_alter() and node_query_entity_field_access_alter()
* for more.
*
* @throws Exception
* In the event that the query cannot be altered as expected.
*/
function _node_query_node_access_alter($query, $type) {
global $user;
// Read meta-data from query, if provided.
if (!$account = $query->getMetaData('account')) {
$account = $user;
}
if (!$op = $query->getMetaData('op')) {
$op = 'view';
}
// If $account can bypass node access, or there are no node access modules,
// or the operation is 'view' and the $account has a global view grant
// (such as a view grant for node ID 0), we don't need to alter the query.
if (user_access('bypass node access', $account)) {
return;
}
if (!count(module_implements('node_grants'))) {
return;
}
if ($op == 'view' && node_access_view_all_nodes($account)) {
return;
}
// Make sure the query returns nothing if the user is not permitted to view
// nodes.
if (!user_access('access content', $account)) {
$query->range(0, 0);
}
$tables = $query->getTables();
$base_table = $query->getMetaData('base_table');
// If no base table is specified explicitly, search for one.
if (!$base_table) {
$fallback = '';
foreach ($tables as $alias => $table_info) {
if (!($table_info instanceof SelectQueryInterface)) {
$table = $table_info['table'];
// If the node table is in the query, it wins immediately.
if ($table == 'node') {
$base_table = $table;
break;
}
// Check whether the table has a foreign key to node.nid. If it does,
// do not run this check again as we found a base table and only node
// can triumph that.
if (!$base_table) {
// The schema is cached.
$schema = backdrop_get_schema($table);
if (isset($schema['fields']['nid'])) {
if (isset($schema['foreign keys'])) {
foreach ($schema['foreign keys'] as $relation) {
if ($relation['table'] === 'node' && $relation['columns'] === array('nid' => 'nid')) {
$base_table = $table;
}
}
}
else {
// At least it's a nid. A table with a field called nid is very
// very likely to be a node.nid in a node access query.
$fallback = $table;
}
}
}
}
}
// If there is nothing else, use the fallback.
if (!$base_table) {
if ($fallback) {
watchdog('security', 'Your node listing query is using @fallback as a base table in a query tagged for node access. This might not be secure and might not even work. Specify foreign keys in your schema to node.nid ', array('@fallback' => $fallback), WATCHDOG_WARNING);
$base_table = $fallback;
}
else {
throw new Exception(t('Query tagged for node access but there is no nid. Add foreign keys to node.nid in schema to fix.'));
}
}
}
// Find all instances of the base table being joined -- could appear
// more than once in the query, and could be aliased. Join each one to
// the node_access table.
$grants = node_access_grants($op, $account);
if ($type == 'entity') {
// The original query looked something like:
// @code
// SELECT nid FROM sometable s
// INNER JOIN node_access na ON na.nid = s.nid
// WHERE ($node_access_conditions)
// @endcode
//
// Our query will look like:
// @code
// SELECT entity_type, entity_id
// FROM field_data_something s
// LEFT JOIN node_access na ON s.entity_id = na.nid
// WHERE (entity_type = 'node' AND $node_access_conditions) OR (entity_type <> 'node')
// @endcode
//
// So instead of directly adding to the query object, we need to collect
// all of the node access conditions in a separate db_and() object and
// then add it to the query at the end.
$node_conditions = db_and();
}
foreach ($tables as $nalias => $tableinfo) {
$table = $tableinfo['table'];
if (!($table instanceof SelectQueryInterface) && $table == $base_table) {
// Set the subquery.
$subquery = db_select('node_access', 'na')
->fields('na', array('nid'));
$grant_conditions = db_or();
// If any grant exists for the specified user, then user has access
// to the node for the specified operation.
foreach ($grants as $realm => $gids) {
foreach ($gids as $gid) {
$grant_conditions->condition(db_and()
->condition('na.gid', $gid)
->condition('na.realm', $realm)
);
}
}
// Attach conditions to the subquery for nodes.
if (count($grant_conditions->conditions())) {
$subquery->condition($grant_conditions);
}
$subquery->condition('na.grant_' . $op, 1, '>=');
$field = 'nid';
// Now handle entities.
if ($type == 'entity') {
// Set a common alias for entities.
$base_alias = $nalias;
$field = 'entity_id';
}
$subquery->where("$nalias.$field = na.nid");
// For an entity query, attach the subquery to entity conditions.
if (isset($node_conditions)) {
$node_conditions->exists($subquery);
}
// Otherwise attach it to the node query itself.
else {
$query->exists($subquery);
}
}
}
if (isset($node_conditions) && count($subquery->conditions())) {
// All the node access conditions are only for field values belonging to
// nodes.
$node_conditions->condition("$base_alias.entity_type", 'node');
$or = db_or();
$or->condition($node_conditions);
// If the field value belongs to a non-node entity type then this function
// does not do anything with it.
$or->condition("$base_alias.entity_type", 'node', '<>');
// Add the compiled set of rules to the query.
$query->condition($or);
}
}
/**
* Exclude nodes from the search query where the node has a hidden path
* and the current user doesn't have permission to bypass the restriction.
*/
function _node_search_query_alter(QueryAlterableInterface $query) {
global $user;
if (in_array('view hidden paths', user_role_permissions($user->roles))) {
return;
}
$search = FALSE;
$node = FALSE;
foreach ($query->getTables() as $alias => $table) {
if ($table['table'] == 'search_index') {
$search = $alias;
}
elseif ($table['table'] == 'node') {
$node = $alias;
}
}
if ($node && $search) {
$excluded_content_types = array();
foreach (node_type_get_types() as $type => $detail) {
if ($detail->settings['hidden_path']) {
$excluded_content_types[] = $type;
}
}
if (!empty($excluded_content_types)) {
$query->condition($node . '.type', array($excluded_content_types), 'NOT IN');
}
}
}
/**
* Gets the list of node access grants and writes them to the database.
*
* This function is called when a node is saved, and can also be called by
* modules if something other than a node save causes node access permissions to
* change. It collects all node access grants for the node from
* hook_node_access_records() implementations, allows these grants to be altered
* via hook_node_access_records_alter() implementations, and saves the collected
* and altered grants to the database.
*
* @param Node $node
* The $node to acquire grants for.
* @param $delete
* (optional) Whether to delete existing node access records before inserting
* new ones. Defaults to TRUE.
*/
function node_access_acquire_grants(Node $node, $delete = TRUE) {
$grants = module_invoke_all('node_access_records', $node);
// Let modules alter the grants.
backdrop_alter('node_access_records', $grants, $node);
// If no grants are set and the node is published, then use the default grant.
if (empty($grants) && !empty($node->status)) {
$grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0);
}
_node_access_write_grants($node, $grants, NULL, $delete);
}
/**
* Writes a list of grants to the database, deleting any previously saved ones.
*
* 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 that utilize
* node_access() can use this function when doing mass updates due to widespread
* permission changes.
*
* Note: Don't call this function directly from a contributed module. Call
* node_access_acquire_grants() instead.
*
* @param Node $node
* The node whose grants are being written. All that is necessary is that it
* contains 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
* (optional) If provided, read/write grants for that realm only.
* @param $delete
* (optional) If false, does not delete records. This is only for optimization
* purposes, and assumes the caller has already performed a mass delete of
* some form. Defaults to TRUE.
*/
function _node_access_write_grants(Node $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 (!empty($grants) && 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();
}
}
/**
* Toggles or reads the value of a flag for rebuilding the node access grants.
*
* 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 if the current user is an administrator, node_access_rebuild()
* should be used instead.
*
* @param $rebuild
* (optional) The boolean value to be written.
*
* @return bool|NULL
* The current value of the flag if no value was provided for $rebuild.
*
* @see node_access_rebuild()
*/
function node_access_needs_rebuild($rebuild = NULL) {
if (!isset($rebuild)) {
return state_get('node_access_needs_rebuild', FALSE);
}
elseif ($rebuild) {
state_set('node_access_needs_rebuild', TRUE);
}
else {
state_del('node_access_needs_rebuild');
}
}
/**
* Rebuilds the node access database.
*
* This rebuild 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.
*
* @param $batch_mode
* (optional) 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.
* @see node_access_needs_rebuild()
*/
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
backdrop_set_time_limit(240);
// Rebuild newest nodes first so that recent content becomes available quickly.
$nids = db_query("SELECT nid FROM {node} ORDER BY nid DESC")->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)) {
backdrop_set_message(t('Content permissions have been rebuilt.'));
node_access_needs_rebuild(FALSE);
cache_clear_all();
}
}
/**
* Performs batch operation for node_access_rebuild().
*
* 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.
*
* @param array $context
* An array of contextual key/value information for rebuild batch process.
*/
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(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", 0, $limit, array(':nid' => $context['sandbox']['current_node']))->fetchCol();
$nodes = node_load_multiple($nids, array(), TRUE);
foreach ($nodes as $nid => $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'] = $nid;
}
// Multistep processing : report progress.
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}
}
/**
* Performs post-processing for node_access_rebuild().
*
* @param bool $success
* A boolean indicating whether the re-build process has completed.
* @param array $results
* An array of results information.
* @param array $operations
* An array of function calls (not used in this function).
*/
function _node_access_rebuild_batch_finished($success, $results, $operations) {
if ($success) {
backdrop_set_message(t('The content access permissions have been rebuilt.'));
node_access_needs_rebuild(FALSE);
}
else {
backdrop_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
* @{
* Functions that implement hooks for user-created content types.
*/
/**
* Implements hook_form().
*/
function node_content_form(Node $node, $form_state) {
// It is impossible to define a content type without implementing hook_form()
// @todo: remove this requirement.
$form = array();
$type = node_type_get_type($node);
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,
'#attributes' => array(
'autofocus' => TRUE,
),
);
}
return $form;
}
/**
* @} End of "defgroup node_content".
*/
/**
* Implements 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;
}
/**
* Implements hook_action_info().
*/
function node_action_info() {
return array(
'node_publish_action' => array(
'type' => 'node',
'label' => t('Publish content'),
'callback' => 'node_publish_action'
),
'node_unpublish_action' => array(
'type' => 'node',
'label' => t('Unpublish content'),
'callback' => 'node_unpublish_action'
),
'node_make_sticky_action' => array(
'type' => 'node',
'label' => t('Make content sticky'),
'callback' => 'node_make_sticky_action',
),
'node_make_unsticky_action' => array(
'type' => 'node',
'label' => t('Make content unsticky'),
'callback' => 'node_make_unsticky_action',
),
'node_promote_action' => array(
'type' => 'node',
'label' => t('Promote content'),
'callback' => 'node_promote_action',
),
'node_unpromote_action' => array(
'type' => 'node',
'label' => t('Remove promotion'),
'callback' => 'node_unpromote_action',
),
'node_delete_action' => array(
'type' => 'node',
'label' => t('Delete content'),
'callback' => 'node_delete_action',
),
);
}
/**
* Sets the status of a node to 1 (published).
*
* @param Node $node
* A node entity.
* @param $context
* Contextual information about the triggered action.
*
* @ingroup actions
*/
function node_publish_action(Node $node, &$context) {
$node->status = NODE_PUBLISHED;
$node->save();
}
/**
* Sets the status of a node to 0 (unpublished).
*
* @param Node $node
* A node entity.
* @param $context
* Contextual information about the triggered action..
*
* @ingroup actions
*/
function node_unpublish_action(Node $node, &$context) {
$node->status = NODE_NOT_PUBLISHED;
$node->save();
}
/**
* Sets the sticky-at-top-of-list property of a node to 1.
*
* @param Node $node
* A node entity.
* @param $context
* Contextual information about the triggered action.
*
* @ingroup actions
*/
function node_make_sticky_action(Node $node, &$context) {
$node->sticky = NODE_STICKY;
$node->save();
}
/**
* Sets the sticky-at-top-of-list property of a node to 0.
*
* @param Node $node
* A node entity.
* @param $context
* Contextual information about the triggered action.
*
* @ingroup actions
*/
function node_make_unsticky_action(Node $node, &$context) {
$node->sticky = NODE_NOT_STICKY;
$node->save();
}
/**
* Sets the promote property of a node to 1.
*
* @param Node $node
* A node entity.
* @param $context
* Contextual information about the triggered action.
*
* @ingroup actions
*/
function node_promote_action(Node $node, &$context) {
$node->promote = NODE_PROMOTED;
$node->save();
}
/**
* Sets the promote property of a node to 0.
*
* @param Node $node
* A node entity.
* @param $context
* Contextual information about the triggered action.
*
* @ingroup actions
*/
function node_unpromote_action(Node $node, &$context) {
$node->promote = NODE_NOT_PROMOTED;
$node->save();
}
/**
* Queues a node for deletion.
*
* @param Node $node
* A node entity.
* @param $context
* Contextual information about the triggered action.
*
* @ingroup actions
*/
function node_delete_action(Node $node, &$context) {
// Save the list of nodes to be deleted in the session. Append to the existing
// list if within the last minute, otherwise start a new list of nodes.
$last_action_time = 0;
if (isset($_SESSION['node_delete_action'])) {
$last_action_time = $_SESSION['node_delete_action']['timestamp'];
}
if (REQUEST_TIME - $last_action_time > 60) {
$_SESSION['node_delete_action'] = array(
'timestamp' => REQUEST_TIME,
'nids' => array(),
);
}
$_SESSION['node_delete_action']['nids'][] = $node->nid;
$context['redirect'] = 'admin/content/node/delete';
}
/**
* Implements hook_requirements().
*/
function node_requirements($phase) {
$requirements = array();
if ($phase === 'runtime') {
// 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');
}
$value .= ' (' . l(t('Rebuild permissions'), 'admin/reports/status/rebuild') . ')';
$description = t('If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Rebuilding will remove all privileges to content and replace them with permissions based on the current modules and settings. Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed, content will automatically use the new permissions.');
$requirements['node_access'] = array(
'title' => t('Node Access Permissions'),
'value' => $value,
'description' => $description,
);
}
return $requirements;
}
/**
* Implements hook_modules_enabled().
*/
function node_modules_enabled($modules) {
// Check if any of the newly enabled modules require the node_access table to
// be rebuilt.
if (!node_access_needs_rebuild() && array_intersect($modules, module_implements('node_grants'))) {
node_access_needs_rebuild(TRUE);
}
// Clear the cache of available node types in the event a module shipped with
// a new node type configuration file.
node_type_cache_reset();
// Check if the enabled modules included any content types and enable the
// ones associated with it.
$node_types = node_type_get_types();
foreach ($node_types as $type) {
if (in_array($type->module, $modules)) {
$type->disabled = FALSE;
node_type_save($type);
}
}
}
/**
* Implements hook_modules_disabled().
*/
function node_modules_disabled($modules) {
// Check whether any of the disabled modules implemented hook_node_grants(),
// in which case the node access table needs to be rebuilt.
foreach ($modules as $module) {
// At this point, the module is already disabled, but its code is still
// loaded in memory. Module functions must no longer be called. We only
// check whether a hook implementation function exists and do not invoke it.
if (!node_access_needs_rebuild() && module_hook($module, 'node_grants')) {
node_access_needs_rebuild(TRUE);
}
}
// If there remains no more node_access module, rebuilding will be
// straightforward, we can do it right now.
if (node_access_needs_rebuild() && count(module_implements('node_grants')) == 0) {
node_access_rebuild();
}
// Check if the disabled modules included any content types and disable the
// ones associated with it.
$node_types = node_type_get_types();
foreach ($node_types as $type) {
if (in_array($type->module, $modules)) {
$type->disabled = TRUE;
node_type_save($type);
}
}
}
/**
* Implements hook_autoload_info().
*/
function node_autoload_info() {
return array(
'Node' => 'node.entity.inc',
'NodeStorageController' => 'node.entity.inc',
'NodeBlock' => 'node.block.inc',
// Views handlers.
'views_handler_argument_node_created_fulldate' => 'views/views_handler_argument_dates_various.inc',
'views_handler_argument_node_created_year' => 'views/views_handler_argument_dates_various.inc',
'views_handler_argument_node_created_year_month' => 'views/views_handler_argument_dates_various.inc',
'views_handler_argument_node_created_month' => 'views/views_handler_argument_dates_various.inc',
'views_handler_argument_node_created_day' => 'views/views_handler_argument_dates_various.inc',
'views_handler_argument_node_created_week' => 'views/views_handler_argument_dates_various.inc',
'views_handler_argument_node_language' => 'views/views_handler_argument_node_language.inc',
'views_handler_argument_node_nid' => 'views/views_handler_argument_node_nid.inc',
'views_handler_argument_node_type' => 'views/views_handler_argument_node_type.inc',
'views_handler_argument_node_vid' => 'views/views_handler_argument_node_vid.inc',
'views_handler_argument_node_uid_revision' => 'views/views_handler_argument_node_uid_revision.inc',
'views_handler_field_history_user_timestamp' => 'views/views_handler_field_history_user_timestamp.inc',
'views_handler_field_node' => 'views/views_handler_field_node.inc',
'views_handler_field_node_link' => 'views/views_handler_field_node_link.inc',
'views_handler_field_node_link_delete' => 'views/views_handler_field_node_link_delete.inc',
'views_handler_field_node_link_edit' => 'views/views_handler_field_node_link_edit.inc',
'views_handler_field_node_revision' => 'views/views_handler_field_node_revision.inc',
'views_handler_field_node_revision_link' => 'views/views_handler_field_node_revision_link.inc',
'views_handler_field_node_revision_link_delete' => 'views/views_handler_field_node_revision_link_delete.inc',
'views_handler_field_node_revision_link_revert' => 'views/views_handler_field_node_revision_link_revert.inc',
'views_handler_field_node_path' => 'views/views_handler_field_node_path.inc',
'views_handler_field_node_type' => 'views/views_handler_field_node_type.inc',
'views_handler_filter_history_user_timestamp' => 'views/views_handler_filter_history_user_timestamp.inc',
'views_handler_filter_node_access' => 'views/views_handler_filter_node_access.inc',
'views_handler_filter_node_hidden_path' => 'views/views_handler_filter_node_hidden_path.inc',
'views_handler_filter_node_status' => 'views/views_handler_filter_node_status.inc',
'views_handler_filter_node_type' => 'views/views_handler_filter_node_type.inc',
'views_handler_filter_node_uid_revision' => 'views/views_handler_filter_node_uid_revision.inc',
'views_plugin_argument_default_node' => 'views/views_plugin_argument_default_node.inc',
'views_plugin_argument_validate_node' => 'views/views_plugin_argument_validate_node.inc',
'views_plugin_row_node_rss' => 'views/views_plugin_row_node_rss.inc',
'views_plugin_row_node_view' => 'views/views_plugin_row_node_view.inc',
);
}
/**
* Implements hook_config_info().
*/
function node_config_info() {
$prefixes['node.type'] = array(
'name_key' => 'type',
'label_key' => 'name',
'group' => t('Node types'),
);
return $prefixes;
}
/**
* Implements hook_config_create_validate().
*/
function node_config_create_validate(Config $staging_config, $all_changes) {
$config_name = $staging_config->getName();
// Ensure entity types and bundles exist or will be imported.
if (strpos($config_name, 'field.instance.node.') === 0) {
list($node_type, $field_name) = explode('.', str_replace('field.instance.node.', '', $config_name));
// Check that the node type does or will exist.
$type_exists = (bool) node_type_get_type($node_type);
$type_created = $all_changes['node.type.' . $node_type];
if (!$type_exists && !$type_created) {
throw new ConfigValidateException(t('The field "@name" cannot be added because the node type "@type" does not exist.', array('@name' => $field_name, '@type' => $node_type)));
}
}
}
/**
* Implements hook_config_delete_validate().
*/
function node_config_delete_validate(Config $active_config, $all_changes) {
$config_name = $active_config->getName();
// Check config name for node type.
if (strpos($config_name, 'node.type.') === 0) {
// Check if node has content.
$node_type = explode('.', $config_name);
if (node_type_has_content($node_type[2])) {
throw new ConfigValidateException(t('The content type "@content_type" cannot be deleted with active content associated to it. Delete the content manually, then retry the import.', array('@content_type' => $node_type[2])));
}
}
}
/**
* Determine whether a node type has any data.
*
* @param $node_type
* Name of bundle to check for content.
* @return
* TRUE if the bundle has content associated to it; FALSE otherwise.
*/
function node_type_has_content($node_type) {
$query = new EntityFieldQuery();
$query = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', $node_type)
->range(0, 1)
->count()
// Neutralize the 'entity_field_access' query tag added by
// field_sql_storage_field_storage_query(). The result cannot depend on the
// access grants of the current user.
->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
return (bool) $query
->execute() || (bool) $query
->age(FIELD_LOAD_REVISION)
->execute();
}
/**
* Implements hook_file_download_access().
*/
function node_file_download_access($field, $entity_type, $entity) {
if ($entity_type == 'node') {
return node_access('view', $entity);
}
}
/**
* Implements hook_language_delete().
*/
function node_language_delete($language) {
// On nodes with this language, unset the language.
db_update('node')
->fields(array('langcode' => ''))
->condition('langcode', $language->langcode)
->execute();
}
/**
* Get a node from the tempstore.
*
* @param string $node_tempstore_id
* The tempstore ID of the node item to load.
*
* @return Node|FALSE
* A fully-populated node entity, or FALSE if the node is not found.
*
* @since 1.11.0
*/
function node_get_node_tempstore($node_tempstore_id) {
$caches = &backdrop_static(__FUNCTION__, array());
if (!isset($caches[$node_tempstore_id])) {
// Try loading from tempstore first to get in-progress changes.
$item = tempstore_get('node_tempstore', $node_tempstore_id);
$caches[$node_tempstore_id] = $item;
}
return $caches[$node_tempstore_id];
}
/**
* Store changes to a node or menu item in the temporary store.
*
* @param Node $item
* The node item to save into tempstore.
* @param string $node_tempstore_id
* The tempstore ID of the node being saved to the object cache.
*
* @since 1.11.0
*/
function node_set_node_tempstore($item, $node_tempstore_id) {
$item->locked = array(
'uid' => $GLOBALS['user']->uid,
'updated' => REQUEST_TIME,
);
// Keep previews for 24 hours.
tempstore_set('node_tempstore', $node_tempstore_id, $item, REQUEST_TIME + 86400);
}
/**
* Remove an item from the object cache.
*
* @param string $node_tempstore_id
* The tempstore ID of the node to be deleted from the object cache.
*
* @since 1.11.0
*/
function node_clear_node_tempstore($node_tempstore_id) {
tempstore_clear('node_tempstore', $node_tempstore_id);
}
/**
* Load a node from the tempstore.
*
* @param int $node_tempstore_id
* The ID of a tempstore object.
*
* @return Node|false
* A fully-populated node entity, or FALSE if the node is not found.
*
* @since 1.11.0
*/
function node_tempstore_load($node_tempstore_id) {
return node_get_node_tempstore($node_tempstore_id);
}
/**
* Build tempstore ID.
*
* @return string $node_tempstore_id
* A unique string, or the current tempstore ID if set in the URL.
*
* @since 1.11.0
*/
function node_build_tempstore_id() {
if (isset($_GET['node_tempstore_id'])) {
$node_tempstore_id = $_GET['node_tempstore_id'];
}
else {
$uuid = new Uuid();
$node_tempstore_id = $uuid->generate();
}
return $node_tempstore_id;
}