Drupal PHP Cross Reference Content Management Systems

Source: /modules/node/node.module - 4185 lines - 138686 bytes - Summary - Text - Print

   1  <?php
   2  
   3  /**
   4   * @file
   5   * The core that allows content to be submitted to the site. Modules and
   6   * scripts may programmatically submit nodes using the usual form API pattern.
   7   */
   8  
   9  /**
  10   * Node is not published.
  11   */
  12  define('NODE_NOT_PUBLISHED', 0);
  13  
  14  /**
  15   * Node is published.
  16   */
  17  define('NODE_PUBLISHED', 1);
  18  
  19  /**
  20   * Node is not promoted to front page.
  21   */
  22  define('NODE_NOT_PROMOTED', 0);
  23  
  24  /**
  25   * Node is promoted to front page.
  26   */
  27  define('NODE_PROMOTED', 1);
  28  
  29  /**
  30   * Node is not sticky at top of the page.
  31   */
  32  define('NODE_NOT_STICKY', 0);
  33  
  34  /**
  35   * Node is sticky at top of the page.
  36   */
  37  define('NODE_STICKY', 1);
  38  
  39  /**
  40   * Nodes changed before this time are always marked as read.
  41   *
  42   * Nodes changed after this time may be marked new, updated, or read, depending
  43   * on their state for the current user. Defaults to 30 days ago.
  44   */
  45  define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
  46  
  47  /**
  48   * Modules should return this value from hook_node_access() to allow access to a node.
  49   */
  50  define('NODE_ACCESS_ALLOW', 'allow');
  51  
  52  /**
  53   * Modules should return this value from hook_node_access() to deny access to a node.
  54   */
  55  define('NODE_ACCESS_DENY', 'deny');
  56  
  57  /**
  58   * Modules should return this value from hook_node_access() to not affect node access.
  59   */
  60  define('NODE_ACCESS_IGNORE', NULL);
  61  
  62  /**
  63   * Implements hook_help().
  64   */
  65  function node_help($path, $arg) {
  66    // Remind site administrators about the {node_access} table being flagged
  67    // for rebuild. We don't need to issue the message on the confirm form, or
  68    // while the rebuild is being processed.
  69    if ($path != 'admin/reports/status/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
  70        && user_access('access administration pages') && node_access_needs_rebuild()) {
  71      if ($path == 'admin/reports/status') {
  72        $message = t('The content access permissions need to be rebuilt.');
  73      }
  74      else {
  75        $message = t('The content access permissions need to be rebuilt. <a href="@node_access_rebuild">Rebuild permissions</a>.', array('@node_access_rebuild' => url('admin/reports/status/rebuild')));
  76      }
  77      drupal_set_message($message, 'error');
  78    }
  79  
  80    switch ($path) {
  81      case 'admin/help#node':
  82        $output = '';
  83        $output .= '<h3>' . t('About') . '</h3>';
  84        $output .= '<p>' . t('The Node module manages the creation, editing, deletion, settings, and display of the main site content. Content items managed by the Node module are typically displayed as pages on your site, and include a title, some meta-data (author, creation time, content type, etc.), and optional fields containing text or other data (fields are managed by the <a href="@field">Field module</a>). For more information, see the online handbook entry for <a href="@node">Node module</a>.', array('@node' => 'http://drupal.org/documentation/modules/node', '@field' => url('admin/help/field'))) . '</p>';
  85        $output .= '<h3>' . t('Uses') . '</h3>';
  86        $output .= '<dl>';
  87        $output .= '<dt>' . t('Creating content') . '</dt>';
  88        $output .= '<dd>' . t('When new content is created, the Node module records basic information about the content, including the author, date of creation, and the <a href="@content-type">Content type</a>. It also manages the <em>publishing options</em>, which define whether or not the content is published, promoted to the front page of the site, and/or sticky at the top of content lists. Default settings can be configured for each <a href="@content-type">type of content</a> on your site.', array('@content-type' => url('admin/structure/types'))) . '</dd>';
  89        $output .= '<dt>' . t('Creating custom content types') . '</dt>';
  90        $output .= '<dd>' . t('The Node module gives users with the <em>Administer content types</em> permission the ability to <a href="@content-new">create new content types</a> in addition to the default ones already configured. Creating custom content types allows you the flexibility to add <a href="@field">fields</a> and configure default settings that suit the differing needs of various site content.', array('@content-new' => url('admin/structure/types/add'), '@field' => url('admin/help/field'))) . '</dd>';
  91        $output .= '<dt>' . t('Administering content') . '</dt>';
  92        $output .= '<dd>' . t('The <a href="@content">Content administration page</a> allows you to review and bulk manage your site content.', array('@content' => url('admin/content'))) . '</dd>';
  93        $output .= '<dt>' . t('Creating revisions') . '</dt>';
  94        $output .= '<dd>' . t('The Node module also enables you to create multiple versions of any content, and revert to older versions using the <em>Revision information</em> settings.') . '</dd>';
  95        $output .= '<dt>' . t('User permissions') . '</dt>';
  96        $output .= '<dd>' . t('The Node module makes a number of permissions available for each content type, which can be set by role on the <a href="@permissions">permissions page</a>.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-node')))) . '</dd>';
  97        $output .= '</dl>';
  98        return $output;
  99  
 100      case 'admin/structure/types/add':
 101        return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
 102  
 103      case 'admin/structure/types/manage/%/display':
 104        return '<p>' . t('Content items can be displayed using different view modes: Teaser, Full content, Print, RSS, etc. <em>Teaser</em> is a short format that is typically used in lists of multiple content items. <em>Full content</em> is typically used when the content is displayed on its own page.') . '</p>' .
 105          '<p>' . t('Here, you can define which fields are shown and hidden when %type content is displayed in each view mode, and define how the fields are displayed in each view mode.', array('%type' => node_type_get_name($arg[4]))) . '</p>';
 106  
 107      case 'node/%/revisions':
 108        return '<p>' . t('Revisions allow you to track differences between multiple versions of your content, and revert back to older versions.') . '</p>';
 109  
 110      case 'node/%/edit':
 111        $node = node_load($arg[1]);
 112        $type = node_type_get_type($node);
 113        return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
 114    }
 115  
 116    if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
 117      $type = node_type_get_type(str_replace('-', '_', $arg[2]));
 118      return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
 119    }
 120  }
 121  
 122  /**
 123   * Implements hook_theme().
 124   */
 125  function node_theme() {
 126    return array(
 127      'node' => array(
 128        'render element' => 'elements',
 129        'template' => 'node',
 130      ),
 131      'node_search_admin' => array(
 132        'render element' => 'form',
 133      ),
 134      'node_add_list' => array(
 135        'variables' => array('content' => NULL),
 136        'file' => 'node.pages.inc',
 137      ),
 138      'node_preview' => array(
 139        'variables' => array('node' => NULL),
 140        'file' => 'node.pages.inc',
 141      ),
 142      'node_admin_overview' => array(
 143        'variables' => array('name' => NULL, 'type' => NULL),
 144        'file' => 'content_types.inc',
 145      ),
 146      'node_recent_block' => array(
 147        'variables' => array('nodes' => NULL),
 148      ),
 149      'node_recent_content' => array(
 150        'variables' => array('node' => NULL),
 151      ),
 152    );
 153  }
 154  
 155  /**
 156   * Implements hook_cron().
 157   */
 158  function node_cron() {
 159    db_delete('history')
 160      ->condition('timestamp', NODE_NEW_LIMIT, '<')
 161      ->execute();
 162  }
 163  
 164  /**
 165   * Implements hook_entity_info().
 166   */
 167  function node_entity_info() {
 168    $return = array(
 169      'node' => array(
 170        'label' => t('Node'),
 171        'controller class' => 'NodeController',
 172        'base table' => 'node',
 173        'revision table' => 'node_revision',
 174        'uri callback' => 'node_uri',
 175        'fieldable' => TRUE,
 176        'entity keys' => array(
 177          'id' => 'nid',
 178          'revision' => 'vid',
 179          'bundle' => 'type',
 180          'label' => 'title',
 181          'language' => 'language',
 182        ),
 183        'bundle keys' => array(
 184          'bundle' => 'type',
 185        ),
 186        'bundles' => array(),
 187        'view modes' => array(
 188          'full' => array(
 189            'label' => t('Full content'),
 190            'custom settings' => FALSE,
 191          ),
 192          'teaser' => array(
 193            'label' => t('Teaser'),
 194            'custom settings' => TRUE,
 195          ),
 196          'rss' => array(
 197            'label' => t('RSS'),
 198            'custom settings' => FALSE,
 199          ),
 200        ),
 201      ),
 202    );
 203  
 204    // Search integration is provided by node.module, so search-related view modes
 205    // for nodes are defined here and not in search.module.
 206    if (module_exists('search')) {
 207      $return['node']['view modes'] += array(
 208        'search_index' => array(
 209          'label' => t('Search index'),
 210          'custom settings' => FALSE,
 211        ),
 212        'search_result' => array(
 213          'label' => t('Search result'),
 214          'custom settings' => FALSE,
 215        ),
 216      );
 217    }
 218  
 219    // Bundles must provide a human readable name so we can create help and error
 220    // messages, and the path to attach Field admin pages to.
 221    foreach (node_type_get_names() as $type => $name) {
 222      $return['node']['bundles'][$type] = array(
 223        'label' => $name,
 224        'admin' => array(
 225          'path' => 'admin/structure/types/manage/%node_type',
 226          'real path' => 'admin/structure/types/manage/' . str_replace('_', '-', $type),
 227          'bundle argument' => 4,
 228          'access arguments' => array('administer content types'),
 229        ),
 230      );
 231    }
 232  
 233    return $return;
 234  }
 235  
 236  /**
 237   * Implements hook_field_display_ENTITY_TYPE_alter().
 238   */
 239  function node_field_display_node_alter(&$display, $context) {
 240    // Hide field labels in search index.
 241    if ($context['view_mode'] == 'search_index') {
 242      $display['label'] = 'hidden';
 243    }
 244  }
 245  
 246  /**
 247   * Implements callback_entity_info_uri().
 248   */
 249  function node_uri($node) {
 250    return array(
 251      'path' => 'node/' . $node->nid,
 252    );
 253  }
 254  
 255  /**
 256   * Implements hook_admin_paths().
 257   */
 258  function node_admin_paths() {
 259    if (variable_get('node_admin_theme')) {
 260      $paths = array(
 261        'node/*/edit' => TRUE,
 262        'node/*/delete' => TRUE,
 263        'node/*/revisions' => TRUE,
 264        'node/*/revisions/*/revert' => TRUE,
 265        'node/*/revisions/*/delete' => TRUE,
 266        'node/add' => TRUE,
 267        'node/add/*' => TRUE,
 268      );
 269      return $paths;
 270    }
 271  }
 272  
 273  /**
 274   * Gathers a listing of links to nodes.
 275   *
 276   * @param $result
 277   *   A database result object from a query to fetch node entities. If your
 278   *   query joins the {node_comment_statistics} table so that the comment_count
 279   *   field is available, a title attribute will be added to show the number of
 280   *   comments.
 281   * @param $title
 282   *   A heading for the resulting list.
 283   *
 284   * @return
 285   *   A renderable array containing a list of linked node titles fetched from
 286   *   $result, or FALSE if there are no rows in $result.
 287   */
 288  function node_title_list($result, $title = NULL) {
 289    $items = array();
 290    $num_rows = FALSE;
 291    foreach ($result as $node) {
 292      $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());
 293      $num_rows = TRUE;
 294    }
 295  
 296    return $num_rows ? array('#theme' => 'item_list__node', '#items' => $items, '#title' => $title) : FALSE;
 297  }
 298  
 299  /**
 300   * Updates the 'last viewed' timestamp of the specified node for current user.
 301   *
 302   * @param $node
 303   *   A node object.
 304   */
 305  function node_tag_new($node) {
 306    global $user;
 307    if ($user->uid) {
 308      db_merge('history')
 309        ->key(array(
 310          'uid' => $user->uid,
 311          'nid' => $node->nid,
 312        ))
 313        ->fields(array('timestamp' => REQUEST_TIME))
 314        ->execute();
 315     }
 316  }
 317  
 318  /**
 319   * Retrieves the timestamp for the current user's last view of a specified node.
 320   *
 321   * @param $nid
 322   *   A node ID.
 323   *
 324   * @return
 325   *   If a node has been previously viewed by the user, the timestamp in seconds
 326   *   of when the last view occurred; otherwise, zero.
 327   */
 328  function node_last_viewed($nid) {
 329    global $user;
 330    $history = &drupal_static(__FUNCTION__, array());
 331  
 332    if (!isset($history[$nid])) {
 333      $history[$nid] = db_query("SELECT timestamp FROM {history} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $nid))->fetchObject();
 334    }
 335  
 336    return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
 337  }
 338  
 339  /**
 340   * Determines the type of marker to be displayed for a given node.
 341   *
 342   * @param $nid
 343   *   Node ID whose history supplies the "last viewed" timestamp.
 344   * @param $timestamp
 345   *   Time which is compared against node's "last viewed" timestamp.
 346   *
 347   * @return
 348   *   One of the MARK constants.
 349   */
 350  function node_mark($nid, $timestamp) {
 351    global $user;
 352    $cache = &drupal_static(__FUNCTION__, array());
 353  
 354    if (!$user->uid) {
 355      return MARK_READ;
 356    }
 357    if (!isset($cache[$nid])) {
 358      $cache[$nid] = node_last_viewed($nid);
 359    }
 360    if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
 361      return MARK_NEW;
 362    }
 363    elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
 364      return MARK_UPDATED;
 365    }
 366    return MARK_READ;
 367  }
 368  
 369  /**
 370   * Extracts the type name.
 371   *
 372   * @param $node
 373   *   Either a string or object, containing the node type information.
 374   *
 375   * @return
 376   *   Node type of the passed-in data.
 377   */
 378  function _node_extract_type($node) {
 379    return is_object($node) ? $node->type : $node;
 380  }
 381  
 382  /**
 383   * Returns a list of all the available node types.
 384   *
 385   * This list can include types that are queued for addition or deletion.
 386   * See _node_types_build() for details.
 387   *
 388   * @return
 389   *   An array of node types, as objects, keyed by the type.
 390   *
 391   * @see node_type_get_type()
 392   */
 393  function node_type_get_types() {
 394    return _node_types_build()->types;
 395  }
 396  
 397  /**
 398   * Returns the node type of the passed node or node type string.
 399   *
 400   * @param $node
 401   *   A node object or string that indicates the node type to return.
 402   *
 403   * @return
 404   *   A single node type, as an object, or FALSE if the node type is not found.
 405   *   The node type is an object containing fields from hook_node_info() return
 406   *   values, as well as the field 'type' (the machine-readable type) and other
 407   *   fields used internally and defined in _node_types_build(),
 408   *   hook_node_info(), and node_type_set_defaults().
 409   */
 410  function node_type_get_type($node) {
 411    $type = _node_extract_type($node);
 412    $types = _node_types_build()->types;
 413    return isset($types[$type]) ? $types[$type] : FALSE;
 414  }
 415  
 416  /**
 417   * Returns the node type base of the passed node or node type string.
 418   *
 419   * The base indicates which module implements this node type and is used to
 420   * execute node-type-specific hooks. For types defined in the user interface
 421   * and managed by node.module, the base is 'node_content'.
 422   *
 423   * @param $node
 424   *   A node object or string that indicates the node type to return.
 425   *
 426   * @return
 427   *   The node type base or FALSE if the node type is not found.
 428   *
 429   * @see node_invoke()
 430   */
 431  function node_type_get_base($node) {
 432    $type = _node_extract_type($node);
 433    $types = _node_types_build()->types;
 434    return isset($types[$type]) && isset($types[$type]->base) ? $types[$type]->base : FALSE;
 435  }
 436  
 437  /**
 438   * Returns a list of available node type names.
 439   *
 440   * This list can include types that are queued for addition or deletion.
 441   * See _node_types_build() for details.
 442   *
 443   * @return
 444   *   An array of node type names, keyed by the type.
 445   */
 446  function node_type_get_names() {
 447    return _node_types_build()->names;
 448  }
 449  
 450  /**
 451   * Returns the node type name of the passed node or node type string.
 452   *
 453   * @param $node
 454   *   A node object or string that indicates the node type to return.
 455   *
 456   * @return
 457   *   The node type name or FALSE if the node type is not found.
 458   */
 459  function node_type_get_name($node) {
 460    $type = _node_extract_type($node);
 461    $types = _node_types_build()->names;
 462    return isset($types[$type]) ? $types[$type] : FALSE;
 463  }
 464  
 465  /**
 466   * Updates the database cache of node types.
 467   *
 468   * All new module-defined node types are saved to the database via a call to
 469   * node_type_save(), and obsolete ones are deleted via a call to
 470   * node_type_delete(). See _node_types_build() for an explanation of the new
 471   * and obsolete types.
 472   *
 473   * @see _node_types_build()
 474   */
 475  function node_types_rebuild() {
 476    _node_types_build(TRUE);
 477  }
 478  
 479  /**
 480   * Menu argument loader: loads a node type by string.
 481   *
 482   * @param $name
 483   *   The machine-readable name of a node type to load, where '_' is replaced
 484   *   with '-'.
 485   *
 486   * @return
 487   *   A node type object or FALSE if $name does not exist.
 488   */
 489  function node_type_load($name) {
 490    return node_type_get_type(strtr($name, array('-' => '_')));
 491  }
 492  
 493  /**
 494   * Saves a node type to the database.
 495   *
 496   * @param object $info
 497   *   The node type to save; an object with the following properties:
 498   *   - type: A string giving the machine name of the node type.
 499   *   - name: A string giving the human-readable name of the node type.
 500   *   - base: A string that indicates the base string for hook functions. For
 501   *     example, 'node_content' is the value used by the UI when creating a new
 502   *     node type.
 503   *   - description: A string that describes the node type.
 504   *   - help: A string giving the help information shown to the user when
 505   *     creating a node of this type.
 506   *   - custom: TRUE or FALSE indicating whether this type is defined by a module
 507   *     (FALSE) or by a user (TRUE) via Add Content Type.
 508   *   - modified: TRUE or FALSE indicating whether this type has been modified by
 509   *     an administrator. Currently not used in any way.
 510   *   - locked: TRUE or FALSE indicating whether the administrator can change the
 511   *     machine name of this type.
 512   *   - disabled: TRUE or FALSE indicating whether this type has been disabled.
 513   *   - has_title: TRUE or FALSE indicating whether this type uses the node title
 514   *     field.
 515   *   - title_label: A string containing the label for the title.
 516   *   - module: A string giving the module defining this type of node.
 517   *   - orig_type: A string giving the original machine-readable name of this
 518   *     node type. This may be different from the current type name if the
 519   *     'locked' key is FALSE.
 520   *
 521   * @return int
 522   *   A status flag indicating the outcome of the operation, either SAVED_NEW or
 523   *   SAVED_UPDATED.
 524   */
 525  function node_type_save($info) {
 526    $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
 527    $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', 0, 1, array(':type' => $existing_type))->fetchField();
 528    $type = node_type_set_defaults($info);
 529  
 530    $fields = array(
 531      'type' => (string) $type->type,
 532      'name' => (string) $type->name,
 533      'base' => (string) $type->base,
 534      'has_title' => (int) $type->has_title,
 535      'title_label' => (string) $type->title_label,
 536      'description' => (string) $type->description,
 537      'help' => (string) $type->help,
 538      'custom' => (int) $type->custom,
 539      'modified' => (int) $type->modified,
 540      'locked' => (int) $type->locked,
 541      'disabled' => (int) $type->disabled,
 542      'module' => $type->module,
 543    );
 544  
 545    if ($is_existing) {
 546      db_update('node_type')
 547        ->fields($fields)
 548        ->condition('type', $existing_type)
 549        ->execute();
 550  
 551      if (!empty($type->old_type) && $type->old_type != $type->type) {
 552        field_attach_rename_bundle('node', $type->old_type, $type->type);
 553      }
 554      module_invoke_all('node_type_update', $type);
 555      $status = SAVED_UPDATED;
 556    }
 557    else {
 558      $fields['orig_type'] = (string) $type->orig_type;
 559      db_insert('node_type')
 560        ->fields($fields)
 561        ->execute();
 562  
 563      field_attach_create_bundle('node', $type->type);
 564  
 565      module_invoke_all('node_type_insert', $type);
 566      $status = SAVED_NEW;
 567    }
 568  
 569    // Clear the node type cache.
 570    node_type_cache_reset();
 571  
 572    return $status;
 573  }
 574  
 575  /**
 576   * Adds default body field to a node type.
 577   *
 578   * @param $type
 579   *   A node type object.
 580   * @param $label
 581   *   The label for the body instance.
 582   *
 583   * @return
 584   *   Body field instance.
 585   */
 586  function node_add_body_field($type, $label = 'Body') {
 587     // Add or remove the body field, as needed.
 588    $field = field_info_field('body');
 589    $instance = field_info_instance('node', 'body', $type->type);
 590    if (empty($field)) {
 591      $field = array(
 592        'field_name' => 'body',
 593        'type' => 'text_with_summary',
 594        'entity_types' => array('node'),
 595      );
 596      $field = field_create_field($field);
 597    }
 598    if (empty($instance)) {
 599      $instance = array(
 600        'field_name' => 'body',
 601        'entity_type' => 'node',
 602        'bundle' => $type->type,
 603        'label' => $label,
 604        'widget' => array('type' => 'text_textarea_with_summary'),
 605        'settings' => array('display_summary' => TRUE),
 606        'display' => array(
 607          'default' => array(
 608            'label' => 'hidden',
 609            'type' => 'text_default',
 610          ),
 611          'teaser' => array(
 612            'label' => 'hidden',
 613            'type' => 'text_summary_or_trimmed',
 614          ),
 615        ),
 616      );
 617      $instance = field_create_instance($instance);
 618    }
 619    return $instance;
 620  }
 621  
 622  /**
 623   * Implements hook_field_extra_fields().
 624   */
 625  function node_field_extra_fields() {
 626    $extra = array();
 627  
 628    foreach (node_type_get_types() as $type) {
 629      if ($type->has_title) {
 630        $extra['node'][$type->type] = array(
 631          'form' => array(
 632            'title' => array(
 633              'label' => $type->title_label,
 634              'description' => t('Node module element'),
 635              'weight' => -5,
 636            ),
 637          ),
 638        );
 639      }
 640    }
 641  
 642    return $extra;
 643  }
 644  
 645  /**
 646   * Deletes a node type from the database.
 647   *
 648   * @param $type
 649   *   The machine-readable name of the node type to be deleted.
 650   */
 651  function node_type_delete($type) {
 652    $info = node_type_get_type($type);
 653    db_delete('node_type')
 654      ->condition('type', $type)
 655      ->execute();
 656    field_attach_delete_bundle('node', $type);
 657    module_invoke_all('node_type_delete', $info);
 658  
 659    // Clear the node type cache.
 660    node_type_cache_reset();
 661  }
 662  
 663  /**
 664   * Updates all nodes of one type to be of another type.
 665   *
 666   * @param $old_type
 667   *   The current node type of the nodes.
 668   * @param $type
 669   *   The new node type of the nodes.
 670   *
 671   * @return
 672   *   The number of nodes whose node type field was modified.
 673   */
 674  function node_type_update_nodes($old_type, $type) {
 675    return db_update('node')
 676      ->fields(array('type' => $type))
 677      ->condition('type', $old_type)
 678      ->execute();
 679  }
 680  
 681  /**
 682   * Builds and returns the list of available node types.
 683   *
 684   * The list of types is built by invoking hook_node_info() on all modules and
 685   * comparing this information with the node types in the {node_type} table.
 686   * These two information sources are not synchronized during module installation
 687   * until node_types_rebuild() is called.
 688   *
 689   * @param $rebuild
 690   *  TRUE to rebuild node types. Equivalent to calling node_types_rebuild().
 691   *
 692   * @return
 693   *   An object with two properties:
 694   *   - names: Associative array of the names of node types, keyed by the type.
 695   *   - types: Associative array of node type objects, keyed by the type.
 696   *   Both of these arrays will include new types that have been defined by
 697   *   hook_node_info() implementations but not yet saved in the {node_type}
 698   *   table. These are indicated in the type object by $type->is_new being set
 699   *   to the value 1. These arrays will also include obsolete types: types that
 700   *   were previously defined by modules that have now been disabled, or for
 701   *   whatever reason are no longer being defined in hook_node_info()
 702   *   implementations, but are still in the database. These are indicated in the
 703   *   type object by $type->disabled being set to TRUE.
 704   */
 705  function _node_types_build($rebuild = FALSE) {
 706    $cid = 'node_types:' . $GLOBALS['language']->language;
 707  
 708    if (!$rebuild) {
 709      $_node_types = &drupal_static(__FUNCTION__);
 710      if (isset($_node_types)) {
 711        return $_node_types;
 712      }
 713      if ($cache = cache_get($cid)) {
 714        $_node_types = $cache->data;
 715        return $_node_types;
 716      }
 717    }
 718  
 719    $_node_types = (object) array('types' => array(), 'names' => array());
 720  
 721    foreach (module_implements('node_info') as $module) {
 722      $info_array = module_invoke($module, 'node_info');
 723      foreach ($info_array as $type => $info) {
 724        $info['type'] = $type;
 725        $_node_types->types[$type] = node_type_set_defaults($info);
 726        $_node_types->types[$type]->module = $module;
 727        $_node_types->names[$type] = $info['name'];
 728      }
 729    }
 730    $query = db_select('node_type', 'nt')
 731      ->addTag('translatable')
 732      ->addTag('node_type_access')
 733      ->fields('nt')
 734      ->orderBy('nt.type', 'ASC');
 735    if (!$rebuild) {
 736      $query->condition('disabled', 0);
 737    }
 738    foreach ($query->execute() as $type_object) {
 739      $type_db = $type_object->type;
 740      // Original disabled value.
 741      $disabled = $type_object->disabled;
 742      // Check for node types from disabled modules and mark their types for removal.
 743      // Types defined by the node module in the database (rather than by a separate
 744      // module using hook_node_info) have a base value of 'node_content'. The isset()
 745      // check prevents errors on old (pre-Drupal 7) databases.
 746      if (isset($type_object->base) && $type_object->base != 'node_content' && empty($_node_types->types[$type_db])) {
 747        $type_object->disabled = TRUE;
 748      }
 749      if (isset($_node_types->types[$type_db])) {
 750        $type_object->disabled = FALSE;
 751      }
 752      if (!isset($_node_types->types[$type_db]) || $type_object->modified) {
 753        $_node_types->types[$type_db] = $type_object;
 754        $_node_types->names[$type_db] = $type_object->name;
 755  
 756        if ($type_db != $type_object->orig_type) {
 757          unset($_node_types->types[$type_object->orig_type]);
 758          unset($_node_types->names[$type_object->orig_type]);
 759        }
 760      }
 761      $_node_types->types[$type_db]->disabled = $type_object->disabled;
 762      $_node_types->types[$type_db]->disabled_changed = $disabled != $type_object->disabled;
 763    }
 764  
 765    if ($rebuild) {
 766      foreach ($_node_types->types as $type => $type_object) {
 767        if (!empty($type_object->is_new) || !empty($type_object->disabled_changed)) {
 768          node_type_save($type_object);
 769        }
 770      }
 771    }
 772  
 773    asort($_node_types->names);
 774  
 775    cache_set($cid, $_node_types);
 776  
 777    return $_node_types;
 778  }
 779  
 780  /**
 781   * Clears the node type cache.
 782   */
 783  function node_type_cache_reset() {
 784    cache_clear_all('node_types:', 'cache', TRUE);
 785    drupal_static_reset('_node_types_build');
 786  }
 787  
 788  /**
 789   * Sets the default values for a node type.
 790   *
 791   * The defaults are appropriate for a type defined through hook_node_info(),
 792   * since 'custom' is TRUE for types defined in the user interface, and FALSE
 793   * for types defined by modules. (The 'custom' flag prevents types from being
 794   * deleted through the user interface.) Also, the default for 'locked' is TRUE,
 795   * which prevents users from changing the machine name of the type.
 796   *
 797   * @param $info
 798   *   (optional) An object or array containing values to override the defaults.
 799   *   See hook_node_info() for details on what the array elements mean. Defaults
 800   *   to an empty array.
 801   *
 802   * @return
 803   *   A node type object, with missing values in $info set to their defaults.
 804   */
 805  function node_type_set_defaults($info = array()) {
 806    $info = (array) $info;
 807    $new_type = $info + array(
 808      'type' => '',
 809      'name' => '',
 810      'base' => '',
 811      'description' => '',
 812      'help' => '',
 813      'custom' => 0,
 814      'modified' => 0,
 815      'locked' => 1,
 816      'disabled' => 0,
 817      'is_new' => 1,
 818      'has_title' => 1,
 819      'title_label' => 'Title',
 820    );
 821    $new_type = (object) $new_type;
 822  
 823    // If the type has no title, set an empty label.
 824    if (!$new_type->has_title) {
 825      $new_type->title_label = '';
 826    }
 827    if (empty($new_type->module)) {
 828      $new_type->module = $new_type->base == 'node_content' ? 'node' : '';
 829    }
 830    $new_type->orig_type = isset($info['type']) ? $info['type'] : '';
 831  
 832    return $new_type;
 833  }
 834  
 835  /**
 836   * Implements hook_rdf_mapping().
 837   */
 838  function node_rdf_mapping() {
 839    return array(
 840      array(
 841        'type' => 'node',
 842        'bundle' => RDF_DEFAULT_BUNDLE,
 843        'mapping' => array(
 844          'rdftype' => array('sioc:Item', 'foaf:Document'),
 845          'title' => array(
 846            'predicates' => array('dc:title'),
 847          ),
 848          'created' => array(
 849            'predicates' => array('dc:date', 'dc:created'),
 850            'datatype' => 'xsd:dateTime',
 851            'callback' => 'date_iso8601',
 852          ),
 853          'changed' => array(
 854            'predicates' => array('dc:modified'),
 855            'datatype' => 'xsd:dateTime',
 856            'callback' => 'date_iso8601',
 857          ),
 858          'body' => array(
 859            'predicates' => array('content:encoded'),
 860          ),
 861          'uid' => array(
 862            'predicates' => array('sioc:has_creator'),
 863            'type' => 'rel',
 864          ),
 865          'name' => array(
 866            'predicates' => array('foaf:name'),
 867          ),
 868          'comment_count' => array(
 869            'predicates' => array('sioc:num_replies'),
 870            'datatype' => 'xsd:integer',
 871          ),
 872          'last_activity' => array(
 873            'predicates' => array('sioc:last_activity_date'),
 874            'datatype' => 'xsd:dateTime',
 875            'callback' => 'date_iso8601',
 876          ),
 877        ),
 878      ),
 879    );
 880  }
 881  
 882  /**
 883   * Determines whether a node hook exists.
 884   *
 885   * @param $node
 886   *   A node object or a string containing the node type.
 887   * @param $hook
 888   *   A string containing the name of the hook.
 889   *
 890   * @return
 891   *   TRUE if the $hook exists in the node type of $node.
 892   */
 893  function node_hook($node, $hook) {
 894    $base = node_type_get_base($node);
 895    return module_hook($base, $hook);
 896  }
 897  
 898  /**
 899   * Invokes a node hook.
 900   *
 901   * @param $node
 902   *   A node object or a string containing the node type.
 903   * @param $hook
 904   *   A string containing the name of the hook.
 905   * @param $a2, $a3, $a4
 906   *   Arguments to pass on to the hook, after the $node argument.
 907   *
 908   * @return
 909   *   The returned value of the invoked hook.
 910   */
 911  function node_invoke($node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
 912    if (node_hook($node, $hook)) {
 913      $base = node_type_get_base($node);
 914      $function = $base . '_' . $hook;
 915      return ($function($node, $a2, $a3, $a4));
 916    }
 917  }
 918  
 919  /**
 920   * Loads node entities from the database.
 921   *
 922   * This function should be used whenever you need to load more than one node
 923   * from the database. Nodes are loaded into memory and will not require database
 924   * access if loaded again during the same page request.
 925   *
 926   * @see entity_load()
 927   * @see EntityFieldQuery
 928   *
 929   * @param $nids
 930   *   An array of node IDs.
 931   * @param $conditions
 932   *   (deprecated) An associative array of conditions on the {node}
 933   *   table, where the keys are the database fields and the values are the
 934   *   values those fields must have. Instead, it is preferable to use
 935   *   EntityFieldQuery to retrieve a list of entity IDs loadable by
 936   *   this function.
 937   * @param $reset
 938   *   Whether to reset the internal node_load cache.
 939   *
 940   * @return
 941   *   An array of node objects indexed by nid.
 942   *
 943   * @todo Remove $conditions in Drupal 8.
 944   */
 945  function node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE) {
 946    return entity_load('node', $nids, $conditions, $reset);
 947  }
 948  
 949  /**
 950   * Loads a node object from the database.
 951   *
 952   * @param $nid
 953   *   The node ID.
 954   * @param $vid
 955   *   The revision ID.
 956   * @param $reset
 957   *   Whether to reset the node_load_multiple cache.
 958   *
 959   * @return
 960   *   A fully-populated node object, or FALSE if the node is not found.
 961   */
 962  function node_load($nid = NULL, $vid = NULL, $reset = FALSE) {
 963    $nids = (isset($nid) ? array($nid) : array());
 964    $conditions = (isset($vid) ? array('vid' => $vid) : array());
 965    $node = node_load_multiple($nids, $conditions, $reset);
 966    return $node ? reset($node) : FALSE;
 967  }
 968  
 969  /**
 970   * Prepares a node object for editing.
 971   *
 972   * Fills in a few default values, and then invokes hook_prepare() on the node
 973   * type module, and hook_node_prepare() on all modules.
 974   *
 975   * @param $node
 976   *   A node object.
 977   */
 978  function node_object_prepare($node) {
 979    // Set up default values, if required.
 980    $node_options = variable_get('node_options_' . $node->type, array('status', 'promote'));
 981    // If this is a new node, fill in the default values.
 982    if (!isset($node->nid) || isset($node->is_new)) {
 983      foreach (array('status', 'promote', 'sticky') as $key) {
 984        // Multistep node forms might have filled in something already.
 985        if (!isset($node->$key)) {
 986          $node->$key = (int) in_array($key, $node_options);
 987        }
 988      }
 989      global $user;
 990      $node->uid = $user->uid;
 991      $node->created = REQUEST_TIME;
 992    }
 993    else {
 994      $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
 995      // Remove the log message from the original node object.
 996      $node->log = NULL;
 997    }
 998    // Always use the default revision setting.
 999    $node->revision = in_array('revision', $node_options);
1000  
1001    node_invoke($node, 'prepare');
1002    module_invoke_all('node_prepare', $node);
1003  }
1004  
1005  /**
1006   * Implements hook_validate().
1007   *
1008   * Performs validation checks on the given node.
1009   */
1010  function node_validate($node, $form, &$form_state) {
1011    if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
1012      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.'));
1013    }
1014  
1015    // Validate the "authored by" field.
1016    if (!empty($node->name) && !($account = user_load_by_name($node->name))) {
1017      // The use of empty() is mandatory in the context of usernames
1018      // as the empty string denotes the anonymous user. In case we
1019      // are dealing with an anonymous user we set the user ID to 0.
1020      form_set_error('name', t('The username %name does not exist.', array('%name' => $node->name)));
1021    }
1022  
1023    // Validate the "authored on" field.
1024    if (!empty($node->date) && strtotime($node->date) === FALSE) {
1025      form_set_error('date', t('You have to specify a valid date.'));
1026    }
1027  
1028    // Invoke hook_validate() for node type specific validation and
1029    // hook_node_validate() for miscellaneous validation needed by modules. Can't
1030    // use node_invoke() or module_invoke_all(), because $form_state must be
1031    // receivable by reference.
1032    $function = node_type_get_base($node) . '_validate';
1033    if (function_exists($function)) {
1034      $function($node, $form, $form_state);
1035    }
1036    foreach (module_implements('node_validate') as $module) {
1037      $function = $module . '_node_validate';
1038      $function($node, $form, $form_state);
1039    }
1040  }
1041  
1042  /**
1043   * Prepares node for saving by populating author and creation date.
1044   *
1045   * @param $node
1046   *   A node object.
1047   *
1048   * @return
1049   *   An updated node object.
1050   */
1051  function node_submit($node) {
1052    // A user might assign the node author by entering a user name in the node
1053    // form, which we then need to translate to a user ID.
1054    if (isset($node->name)) {
1055      if ($account = user_load_by_name($node->name)) {
1056        $node->uid = $account->uid;
1057      }
1058      else {
1059        $node->uid = 0;
1060      }
1061    }
1062  
1063    $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME;
1064    $node->validated = TRUE;
1065  
1066    return $node;
1067  }
1068  
1069  /**
1070   * Saves changes to a node or adds a new node.
1071   *
1072   * @param $node
1073   *   The $node object to be saved. If $node->nid is
1074   *   omitted (or $node->is_new is TRUE), a new node will be added.
1075   */
1076  function node_save($node) {
1077    $transaction = db_transaction();
1078  
1079    try {
1080      // Load the stored entity, if any.
1081      if (!empty($node->nid) && !isset($node->original)) {
1082        $node->original = entity_load_unchanged('node', $node->nid);
1083      }
1084  
1085      field_attach_presave('node', $node);
1086      global $user;
1087  
1088      // Determine if we will be inserting a new node.
1089      if (!isset($node->is_new)) {
1090        $node->is_new = empty($node->nid);
1091      }
1092  
1093      // Set the timestamp fields.
1094      if (empty($node->created)) {
1095        $node->created = REQUEST_TIME;
1096      }
1097      // The changed timestamp is always updated for bookkeeping purposes,
1098      // for example: revisions, searching, etc.
1099      $node->changed = REQUEST_TIME;
1100  
1101      $node->timestamp = REQUEST_TIME;
1102      $update_node = TRUE;
1103  
1104      // Let modules modify the node before it is saved to the database.
1105      module_invoke_all('node_presave', $node);
1106      module_invoke_all('entity_presave', $node, 'node');
1107  
1108      if ($node->is_new || !empty($node->revision)) {
1109        // When inserting either a new node or a new node revision, $node->log
1110        // must be set because {node_revision}.log is a text column and therefore
1111        // cannot have a default value. However, it might not be set at this
1112        // point (for example, if the user submitting a node form does not have
1113        // permission to create revisions), so we ensure that it is at least an
1114        // empty string in that case.
1115        // @todo: Make the {node_revision}.log column nullable so that we can
1116        // remove this check.
1117        if (!isset($node->log)) {
1118          $node->log = '';
1119        }
1120      }
1121      elseif (!isset($node->log) || $node->log === '') {
1122        // If we are updating an existing node without adding a new revision, we
1123        // need to make sure $node->log is unset whenever it is empty. As long as
1124        // $node->log is unset, drupal_write_record() will not attempt to update
1125        // the existing database column when re-saving the revision; therefore,
1126        // this code allows us to avoid clobbering an existing log entry with an
1127        // empty one.
1128        unset($node->log);
1129      }
1130  
1131      // When saving a new node revision, unset any existing $node->vid so as to
1132      // ensure that a new revision will actually be created, then store the old
1133      // revision ID in a separate property for use by node hook implementations.
1134      if (!$node->is_new && !empty($node->revision) && $node->vid) {
1135        $node->old_vid = $node->vid;
1136        unset($node->vid);
1137      }
1138  
1139      // Save the node and node revision.
1140      if ($node->is_new) {
1141        // For new nodes, save new records for both the node itself and the node
1142        // revision.
1143        drupal_write_record('node', $node);
1144        _node_save_revision($node, $user->uid);
1145        $op = 'insert';
1146      }
1147      else {
1148        // For existing nodes, update the node record which matches the value of
1149        // $node->nid.
1150        drupal_write_record('node', $node, 'nid');
1151        // Then, if a new node revision was requested, save a new record for
1152        // that; otherwise, update the node revision record which matches the
1153        // value of $node->vid.
1154        if (!empty($node->revision)) {
1155          _node_save_revision($node, $user->uid);
1156        }
1157        else {
1158          _node_save_revision($node, $user->uid, 'vid');
1159          $update_node = FALSE;
1160        }
1161        $op = 'update';
1162      }
1163      if ($update_node) {
1164        db_update('node')
1165          ->fields(array('vid' => $node->vid))
1166          ->condition('nid', $node->nid)
1167          ->execute();
1168      }
1169  
1170      // Call the node specific callback (if any). This can be
1171      // node_invoke($node, 'insert') or
1172      // node_invoke($node, 'update').
1173      node_invoke($node, $op);
1174  
1175      // Save fields.
1176      $function = "field_attach_$op";
1177      $function('node', $node);
1178  
1179      module_invoke_all('node_' . $op, $node);
1180      module_invoke_all('entity_' . $op, $node, 'node');
1181  
1182      // Update the node access table for this node.
1183      node_access_acquire_grants($node);
1184  
1185      // Clear internal properties.
1186      unset($node->is_new);
1187      unset($node->original);
1188      // Clear the static loading cache.
1189      entity_get_controller('node')->resetCache(array($node->nid));
1190  
1191      // Ignore slave server temporarily to give time for the
1192      // saved node to be propagated to the slave.
1193      db_ignore_slave();
1194    }
1195    catch (Exception $e) {
1196      $transaction->rollback();
1197      watchdog_exception('node', $e);
1198      throw $e;
1199    }
1200  }
1201  
1202  /**
1203   * Helper function to save a revision with the uid of the current user.
1204   *
1205   * The resulting revision ID is available afterward in $node->vid.
1206   *
1207   * @param $node
1208   *   A node object.
1209   * @param $uid
1210   *   The current user's UID.
1211   * @param $update
1212   *   (optional) An array of primary keys' field names to update.
1213   */
1214  function _node_save_revision($node, $uid, $update = NULL) {
1215    $temp_uid = $node->uid;
1216    $node->uid = $uid;
1217    if (isset($update)) {
1218      drupal_write_record('node_revision', $node, $update);
1219    }
1220    else {
1221      drupal_write_record('node_revision', $node);
1222    }
1223    // Have node object still show node owner's uid, not revision author's.
1224    $node->uid = $temp_uid;
1225  }
1226  
1227  /**
1228   * Deletes a node.
1229   *
1230   * @param $nid
1231   *   A node ID.
1232   */
1233  function node_delete($nid) {
1234    node_delete_multiple(array($nid));
1235  }
1236  
1237  /**
1238   * Deletes multiple nodes.
1239   *
1240   * @param $nids
1241   *   An array of node IDs.
1242   */
1243  function node_delete_multiple($nids) {
1244    $transaction = db_transaction();
1245    if (!empty($nids)) {
1246      $nodes = node_load_multiple($nids, array());
1247  
1248      try {
1249        foreach ($nodes as $nid => $node) {
1250          // Call the node-specific callback (if any):
1251          node_invoke($node, 'delete');
1252          module_invoke_all('node_delete', $node);
1253          module_invoke_all('entity_delete', $node, 'node');
1254          field_attach_delete('node', $node);
1255  
1256          // Remove this node from the search index if needed.
1257          // This code is implemented in node module rather than in search module,
1258          // because node module is implementing search module's API, not the other
1259          // way around.
1260          if (module_exists('search')) {
1261            search_reindex($nid, 'node');
1262          }
1263        }
1264  
1265        // Delete after calling hooks so that they can query node tables as needed.
1266        db_delete('node')
1267          ->condition('nid', $nids, 'IN')
1268          ->execute();
1269        db_delete('node_revision')
1270          ->condition('nid', $nids, 'IN')
1271          ->execute();
1272        db_delete('history')
1273          ->condition('nid', $nids, 'IN')
1274          ->execute();
1275        db_delete('node_access')
1276         ->condition('nid', $nids, 'IN')
1277         ->execute();
1278      }
1279      catch (Exception $e) {
1280        $transaction->rollback();
1281        watchdog_exception('node', $e);
1282        throw $e;
1283      }
1284  
1285      // Clear the page and block and node_load_multiple caches.
1286      entity_get_controller('node')->resetCache();
1287    }
1288  }
1289  
1290  /**
1291   * Deletes a node revision.
1292   *
1293   * @param $revision_id
1294   *   The revision ID to delete.
1295   */
1296  function node_revision_delete($revision_id) {
1297    if ($revision = node_load(NULL, $revision_id)) {
1298      // Prevent deleting the current revision.
1299      $node = node_load($revision->nid);
1300      if ($revision_id == $node->vid) {
1301        return FALSE;
1302      }
1303  
1304      db_delete('node_revision')
1305        ->condition('nid', $revision->nid)
1306        ->condition('vid', $revision->vid)
1307        ->execute();
1308      module_invoke_all('node_revision_delete', $revision);
1309      field_attach_delete_revision('node', $revision);
1310      return TRUE;
1311    }
1312    return FALSE;
1313  }
1314  
1315  /**
1316   * Generates an array for rendering the given node.
1317   *
1318   * @param $node
1319   *   A node object.
1320   * @param $view_mode
1321   *   View mode, e.g. 'full', 'teaser'...
1322   * @param $langcode
1323   *   (optional) A language code to use for rendering. Defaults to the global
1324   *   content language of the current request.
1325   *
1326   * @return
1327   *   An array as expected by drupal_render().
1328   */
1329  function node_view($node, $view_mode = 'full', $langcode = NULL) {
1330    if (!isset($langcode)) {
1331      $langcode = $GLOBALS['language_content']->language;
1332    }
1333  
1334    // Populate $node->content with a render() array.
1335    node_build_content($node, $view_mode, $langcode);
1336  
1337    $build = $node->content;
1338    // We don't need duplicate rendering info in node->content.
1339    unset($node->content);
1340  
1341    $build += array(
1342      '#theme' => 'node',
1343      '#node' => $node,
1344      '#view_mode' => $view_mode,
1345      '#language' => $langcode,
1346    );
1347  
1348    // Add contextual links for this node, except when the node is already being
1349    // displayed on its own page. Modules may alter this behavior (for example,
1350    // to restrict contextual links to certain view modes) by implementing
1351    // hook_node_view_alter().
1352    if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node))) {
1353      $build['#contextual_links']['node'] = array('node', array($node->nid));
1354    }
1355  
1356    // Allow modules to modify the structured node.
1357    $type = 'node';
1358    drupal_alter(array('node_view', 'entity_view'), $build, $type);
1359  
1360    return $build;
1361  }
1362  
1363  /**
1364   * Builds a structured array representing the node's content.
1365   *
1366   * The content built for the node (field values, comments, file attachments or
1367   * other node components) will vary depending on the $view_mode parameter.
1368   *
1369   * Drupal core defines the following view modes for nodes, with the following
1370   * default use cases:
1371   *   - full (default): node is being displayed on its own page (node/123)
1372   *   - teaser: node is being displayed on the default home page listing, on
1373   *     taxonomy listing pages, or on blog listing pages.
1374   *   - rss: node displayed in an RSS feed.
1375   *   If search.module is enabled:
1376   *   - search_index: node is being indexed for search.
1377   *   - search_result: node is being displayed as a search result.
1378   *   If book.module is enabled:
1379   *   - print: node is being displayed in print-friendly mode.
1380   * Contributed modules might define additional view modes, or use existing
1381   * view modes in additional contexts.
1382   *
1383   * @param $node
1384   *   A node object.
1385   * @param $view_mode
1386   *   View mode, e.g. 'full', 'teaser'...
1387   * @param $langcode
1388   *   (optional) A language code to use for rendering. Defaults to the global
1389   *   content language of the current request.
1390   */
1391  function node_build_content($node, $view_mode = 'full', $langcode = NULL) {
1392    if (!isset($langcode)) {
1393      $langcode = $GLOBALS['language_content']->language;
1394    }
1395  
1396    // Remove previously built content, if exists.
1397    $node->content = array();
1398  
1399    // Allow modules to change the view mode.
1400    $context = array(
1401      'entity_type' => 'node',
1402      'entity' => $node,
1403      'langcode' => $langcode,
1404    );
1405    drupal_alter('entity_view_mode', $view_mode, $context);
1406  
1407    // The 'view' hook can be implemented to overwrite the default function
1408    // to display nodes.
1409    if (node_hook($node, 'view')) {
1410      $node = node_invoke($node, 'view', $view_mode, $langcode);
1411    }
1412  
1413    // Build fields content.
1414    // In case of a multiple view, node_view_multiple() already ran the
1415    // 'prepare_view' step. An internal flag prevents the operation from running
1416    // twice.
1417    field_attach_prepare_view('node', array($node->nid => $node), $view_mode, $langcode);
1418    entity_prepare_view('node', array($node->nid => $node), $langcode);
1419    $node->content += field_attach_view('node', $node, $view_mode, $langcode);
1420  
1421    // Always display a read more link on teasers because we have no way to know
1422    // when a teaser view is different than a full view.
1423    $links = array();
1424    $node->content['links'] = array(
1425      '#theme' => 'links__node',
1426      '#pre_render' => array('drupal_pre_render_links'),
1427      '#attributes' => array('class' => array('links', 'inline')),
1428    );
1429    if ($view_mode == 'teaser') {
1430      $node_title_stripped = strip_tags($node->title);
1431      $links['node-readmore'] = array(
1432        'title' => t('Read more<span class="element-invisible"> about @title</span>', array('@title' => $node_title_stripped)),
1433        'href' => 'node/' . $node->nid,
1434        'html' => TRUE,
1435        'attributes' => array('rel' => 'tag', 'title' => $node_title_stripped),
1436      );
1437    }
1438    $node->content['links']['node'] = array(
1439      '#theme' => 'links__node__node',
1440      '#links' => $links,
1441      '#attributes' => array('class' => array('links', 'inline')),
1442    );
1443  
1444    // Allow modules to make their own additions to the node.
1445    module_invoke_all('node_view', $node, $view_mode, $langcode);
1446    module_invoke_all('entity_view', $node, 'node', $view_mode, $langcode);
1447  
1448    // Make sure the current view mode is stored if no module has already
1449    // populated the related key.
1450    $node->content += array('#view_mode' => $view_mode);
1451  }
1452  
1453  /**
1454   * Generates an array which displays a node detail page.
1455   *
1456   * @param $node
1457   *   A node object.
1458   * @param $message
1459   *   A flag which sets a page title relevant to the revision being viewed.
1460   *
1461   * @return
1462   *   A $page element suitable for use by drupal_render().
1463   */
1464  function node_show($node, $message = FALSE) {
1465    if ($message) {
1466      drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
1467    }
1468  
1469    // For markup consistency with other pages, use node_view_multiple() rather than node_view().
1470    $nodes = node_view_multiple(array($node->nid => $node), 'full');
1471  
1472    // Update the history table, stating that this user viewed this node.
1473    node_tag_new($node);
1474  
1475    return $nodes;
1476  }
1477  
1478  /**
1479   * Returns whether the current page is the full page view of the passed-in node.
1480   *
1481   * @param $node
1482   *   A node object.
1483   *
1484   * @return
1485   *   The ID of the node if this is a full page view, otherwise FALSE.
1486   */
1487  function node_is_page($node) {
1488    $page_node = menu_get_object();
1489    return (!empty($page_node) ? $page_node->nid == $node->nid : FALSE);
1490  }
1491  
1492  /**
1493   * Processes variables for node.tpl.php
1494   *
1495   * Most themes utilize their own copy of node.tpl.php. The default is located
1496   * inside "modules/node/node.tpl.php". Look in there for the full list of
1497   * variables.
1498   *
1499   * The $variables array contains the following arguments:
1500   * - $node
1501   * - $view_mode
1502   * - $page
1503   *
1504   * @see node.tpl.php
1505   */
1506  function template_preprocess_node(&$variables) {
1507    $variables['view_mode'] = $variables['elements']['#view_mode'];
1508    // Provide a distinct $teaser boolean.
1509    $variables['teaser'] = $variables['view_mode'] == 'teaser';
1510    $variables['node'] = $variables['elements']['#node'];
1511    $node = $variables['node'];
1512  
1513    $variables['date']      = format_date($node->created);
1514    $variables['name']      = theme('username', array('account' => $node));
1515  
1516    $uri = entity_uri('node', $node);
1517    $variables['node_url']  = url($uri['path'], $uri['options']);
1518    $variables['title']     = check_plain($node->title);
1519    $variables['page']      = $variables['view_mode'] == 'full' && node_is_page($node);
1520  
1521    // Flatten the node object's member fields.
1522    $variables = array_merge((array) $node, $variables);
1523  
1524    // Helpful $content variable for templates.
1525    $variables += array('content' => array());
1526    foreach (element_children($variables['elements']) as $key) {
1527      $variables['content'][$key] = $variables['elements'][$key];
1528    }
1529  
1530    // Make the field variables available with the appropriate language.
1531    field_attach_preprocess('node', $node, $variables['content'], $variables);
1532  
1533    // Display post information only on certain node types.
1534    if (variable_get('node_submitted_' . $node->type, TRUE)) {
1535      $variables['display_submitted'] = TRUE;
1536      $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
1537      $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
1538    }
1539    else {
1540      $variables['display_submitted'] = FALSE;
1541      $variables['submitted'] = '';
1542      $variables['user_picture'] = '';
1543    }
1544  
1545    // Gather node classes.
1546    $variables['classes_array'][] = drupal_html_class('node-' . $node->type);
1547    if ($variables['promote']) {
1548      $variables['classes_array'][] = 'node-promoted';
1549    }
1550    if ($variables['sticky']) {
1551      $variables['classes_array'][] = 'node-sticky';
1552    }
1553    if (!$variables['status']) {
1554      $variables['classes_array'][] = 'node-unpublished';
1555    }
1556    if ($variables['teaser']) {
1557      $variables['classes_array'][] = 'node-teaser';
1558    }
1559    if (isset($variables['preview'])) {
1560      $variables['classes_array'][] = 'node-preview';
1561    }
1562  
1563    // Clean up name so there are no underscores.
1564    $variables['theme_hook_suggestions'][] = 'node__' . $node->type;
1565    $variables['theme_hook_suggestions'][] = 'node__' . $node->nid;
1566  }
1567  
1568  /**
1569   * Implements hook_permission().
1570   */
1571  function node_permission() {
1572    $perms = array(
1573      'bypass node access' => array(
1574        'title' => t('Bypass content access control'),
1575        'description' => t('View, edit and delete all content regardless of permission restrictions.'),
1576        'restrict access' => TRUE,
1577      ),
1578      'administer content types' => array(
1579        'title' => t('Administer content types'),
1580        'restrict access' => TRUE,
1581      ),
1582      'administer nodes' => array(
1583        'title' => t('Administer content'),
1584        'restrict access' => TRUE,
1585      ),
1586      'access content overview' => array(
1587        'title' => t('Access the content overview page'),
1588        'description' => user_access('access content overview')
1589          ? t('Get an overview of <a href="@url">all content</a>.', array('@url' => url('admin/content')))
1590          : t('Get an overview of all content.'),
1591      ),
1592      'access content' => array(
1593        'title' => t('View published content'),
1594      ),
1595      'view own unpublished content' => array(
1596        'title' => t('View own unpublished content'),
1597      ),
1598      'view revisions' => array(
1599        'title' => t('View content revisions'),
1600      ),
1601      'revert revisions' => array(
1602        'title' => t('Revert content revisions'),
1603      ),
1604      'delete revisions' => array(
1605        'title' => t('Delete content revisions'),
1606      ),
1607    );
1608  
1609    // Generate standard node permissions for all applicable node types.
1610    foreach (node_permissions_get_configured_types() as $type) {
1611      $perms += node_list_permissions($type);
1612    }
1613  
1614    return $perms;
1615  }
1616  
1617  /**
1618   * Gathers the rankings from the the hook_ranking() implementations.
1619   *
1620   * @param $query
1621   *   A query object that has been extended with the Search DB Extender.
1622   */
1623  function _node_rankings(SelectQueryExtender $query) {
1624    if ($ranking = module_invoke_all('ranking')) {
1625      $tables = &$query->getTables();
1626      foreach ($ranking as $rank => $values) {
1627        if ($node_rank = variable_get('node_rank_' . $rank, 0)) {
1628          // If the table defined in the ranking isn't already joined, then add it.
1629          if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
1630            $query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
1631          }
1632          $arguments = isset($values['arguments']) ? $values['arguments'] : array();
1633          $query->addScore($values['score'], $arguments, $node_rank);
1634        }
1635      }
1636    }
1637  }
1638  
1639  /**
1640   * Implements hook_search_info().
1641   */
1642  function node_search_info() {
1643    return array(
1644      'title' => 'Content',
1645      'path' => 'node',
1646    );
1647  }
1648  
1649  /**
1650   * Implements hook_search_access().
1651   */
1652  function node_search_access() {
1653    return user_access('access content');
1654  }
1655  
1656  /**
1657   * Implements hook_search_reset().
1658   */
1659  function node_search_reset() {
1660    db_update('search_dataset')
1661      ->fields(array('reindex' => REQUEST_TIME))
1662      ->condition('type', 'node')
1663      ->execute();
1664  }
1665  
1666  /**
1667   * Implements hook_search_status().
1668   */
1669  function node_search_status() {
1670    $total = db_query('SELECT COUNT(*) FROM {node}')->fetchField();
1671    $remaining = db_query("SELECT COUNT(*) 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")->fetchField();
1672    return array('remaining' => $remaining, 'total' => $total);
1673  }
1674  
1675  /**
1676   * Implements hook_search_admin().
1677   */
1678  function node_search_admin() {
1679    // Output form for defining rank factor weights.
1680    $form['content_ranking'] = array(
1681      '#type' => 'fieldset',
1682      '#title' => t('Content ranking'),
1683    );
1684    $form['content_ranking']['#theme'] = 'node_search_admin';
1685    $form['content_ranking']['info'] = array(
1686      '#markup' => '<p><em>' . t('Influence is a numeric multiplier used in ordering search results. A higher number means the corresponding factor has more influence on search results; zero means the factor is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em></p>'
1687    );
1688  
1689    // Note: reversed to reflect that higher number = higher ranking.
1690    $options = drupal_map_assoc(range(0, 10));
1691    foreach (module_invoke_all('ranking') as $var => $values) {
1692      $form['content_ranking']['factors']['node_rank_' . $var] = array(
1693        '#title' => $values['title'],
1694        '#type' => 'select',
1695        '#options' => $options,
1696        '#default_value' => variable_get('node_rank_' . $var, 0),
1697      );
1698    }
1699    return $form;
1700  }
1701  
1702  /**
1703   * Implements hook_search_execute().
1704   */
1705  function node_search_execute($keys = NULL, $conditions = NULL) {
1706    // Build matching conditions
1707    $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
1708    $query->join('node', 'n', 'n.nid = i.sid');
1709    $query
1710      ->condition('n.status', 1)
1711      ->addTag('node_access')
1712      ->searchExpression($keys, 'node');
1713  
1714    // Insert special keywords.
1715    $query->setOption('type', 'n.type');
1716    $query->setOption('language', 'n.language');
1717    if ($query->setOption('term', 'ti.tid')) {
1718      $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
1719    }
1720    // Only continue if the first pass query matches.
1721    if (!$query->executeFirstPass()) {
1722      return array();
1723    }
1724  
1725    // Add the ranking expressions.
1726    _node_rankings($query);
1727  
1728    // Load results.
1729    $find = $query
1730      ->limit(10)
1731      ->execute();
1732    $results = array();
1733    foreach ($find as $item) {
1734      // Render the node.
1735      $node = node_load($item->sid);
1736      $build = node_view($node, 'search_result');
1737      unset($build['#theme']);
1738      $node->rendered = drupal_render($build);
1739  
1740      // Fetch comments for snippet.
1741      $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
1742  
1743      $extra = module_invoke_all('node_search_result', $node);
1744  
1745      $uri = entity_uri('node', $node);
1746      $results[] = array(
1747        'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
1748        'type' => check_plain(node_type_get_name($node)),
1749        'title' => $node->title,
1750        'user' => theme('username', array('account' => $node)),
1751        'date' => $node->changed,
1752        'node' => $node,
1753        'extra' => $extra,
1754        'score' => $item->calculated_score,
1755        'snippet' => search_excerpt($keys, $node->rendered),
1756        'language' => entity_language('node', $node),
1757      );
1758    }
1759    return $results;
1760  }
1761  
1762  /**
1763   * Implements hook_ranking().
1764   */
1765  function node_ranking() {
1766    // Create the ranking array and add the basic ranking options.
1767    $ranking = array(
1768      'relevance' => array(
1769        'title' => t('Keyword relevance'),
1770        // Average relevance values hover around 0.15
1771        'score' => 'i.relevance',
1772      ),
1773      'sticky' => array(
1774        'title' => t('Content is sticky at top of lists'),
1775        // The sticky flag is either 0 or 1, which is automatically normalized.
1776        'score' => 'n.sticky',
1777      ),
1778      'promote' => array(
1779        'title' => t('Content is promoted to the front page'),
1780        // The promote flag is either 0 or 1, which is automatically normalized.
1781        'score' => 'n.promote',
1782      ),
1783    );
1784  
1785    // Add relevance based on creation or changed date.
1786    if ($node_cron_last = variable_get('node_cron_last', 0)) {
1787      $ranking['recent'] = array(
1788        'title' => t('Recently posted'),
1789        // Exponential decay with half-life of 6 months, starting at last indexed node
1790        'score' => 'POW(2.0, (GREATEST(n.created, n.changed) - :node_cron_last) * 6.43e-8)',
1791        'arguments' => array(':node_cron_last' => $node_cron_last),
1792      );
1793    }
1794    return $ranking;
1795  }
1796  
1797  /**
1798   * Implements hook_user_cancel().
1799   */
1800  function node_user_cancel($edit, $account, $method) {
1801    switch ($method) {
1802      case 'user_cancel_block_unpublish':
1803        // Unpublish nodes (current revisions).
1804        module_load_include('inc', 'node', 'node.admin');
1805        $nodes = db_select('node', 'n')
1806          ->fields('n', array('nid'))
1807          ->condition('uid', $account->uid)
1808          ->execute()
1809          ->fetchCol();
1810        node_mass_update($nodes, array('status' => 0));
1811        break;
1812  
1813      case 'user_cancel_reassign':
1814        // Anonymize nodes (current revisions).
1815        module_load_include('inc', 'node', 'node.admin');
1816        $nodes = db_select('node', 'n')
1817          ->fields('n', array('nid'))
1818          ->condition('uid', $account->uid)
1819          ->execute()
1820          ->fetchCol();
1821        node_mass_update($nodes, array('uid' => 0));
1822        // Anonymize old revisions.
1823        db_update('node_revision')
1824          ->fields(array('uid' => 0))
1825          ->condition('uid', $account->uid)
1826          ->execute();
1827        // Clean history.
1828        db_delete('history')
1829          ->condition('uid', $account->uid)
1830          ->execute();
1831        break;
1832    }
1833  }
1834  
1835  /**
1836   * Implements hook_user_delete().
1837   */
1838  function node_user_delete($account) {
1839    // Delete nodes (current revisions).
1840    // @todo Introduce node_mass_delete() or make node_mass_update() more flexible.
1841    $nodes = db_select('node', 'n')
1842      ->fields('n', array('nid'))
1843      ->condition('uid', $account->uid)
1844      ->execute()
1845      ->fetchCol();
1846    node_delete_multiple($nodes);
1847    // Delete old revisions.
1848    $revisions = db_query('SELECT vid FROM {node_revision} WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol();
1849    foreach ($revisions as $revision) {
1850      node_revision_delete($revision);
1851    }
1852    // Clean history.
1853    db_delete('history')
1854      ->condition('uid', $account->uid)
1855      ->execute();
1856  }
1857  
1858  /**
1859   * Returns HTML for the content ranking part of the search settings admin page.
1860   *
1861   * @param $variables
1862   *   An associative array containing:
1863   *   - form: A render element representing the form.
1864   *
1865   * @see node_search_admin()
1866   * @ingroup themeable
1867   */
1868  function theme_node_search_admin($variables) {
1869    $form = $variables['form'];
1870  
1871    $output = drupal_render($form['info']);
1872  
1873    $header = array(t('Factor'), t('Influence'));
1874    foreach (element_children($form['factors']) as $key) {
1875      $row = array();
1876      $row[] = $form['factors'][$key]['#title'];
1877      $form['factors'][$key]['#title_display'] = 'invisible';
1878      $row[] = drupal_render($form['factors'][$key]);
1879      $rows[] = $row;
1880    }
1881    $output .= theme('table', array('header' => $header, 'rows' => $rows));
1882  
1883    $output .= drupal_render_children($form);
1884    return $output;
1885  }
1886  
1887  /**
1888   * Access callback: Checks node revision access.
1889   *
1890   * @param $node
1891   *   The node to check.
1892   * @param $op
1893   *   (optional) The specific operation being checked. Defaults to 'view.'
1894   * @param object $account
1895   *   (optional) A user object representing the user for whom the operation is
1896   *   to be performed. Determines access for a user other than the current user.
1897   *
1898   * @return
1899   *   TRUE if the operation may be performed, FALSE otherwise.
1900   *
1901   * @see node_menu()
1902   */
1903  function _node_revision_access($node, $op = 'view', $account = NULL) {
1904    $access = &drupal_static(__FUNCTION__, array());
1905  
1906    $map = array(
1907      'view' => 'view revisions',
1908      'update' => 'revert revisions',
1909      'delete' => 'delete revisions',
1910    );
1911  
1912    if (!$node || !isset($map[$op])) {
1913      // If there was no node to check against, or the $op was not one of the
1914      // supported ones, we return access denied.
1915      return FALSE;
1916    }
1917  
1918    if (!isset($account)) {
1919      $account = $GLOBALS['user'];
1920    }
1921  
1922    // Statically cache access by revision ID, user account ID, and operation.
1923    $cid = $node->vid . ':' . $account->uid . ':' . $op;
1924  
1925    if (!isset($access[$cid])) {
1926      // Perform basic permission checks first.
1927      if (!user_access($map[$op], $account) && !user_access('administer nodes', $account)) {
1928        return $access[$cid] = FALSE;
1929      }
1930  
1931      $node_current_revision = node_load($node->nid);
1932      $is_current_revision = $node_current_revision->vid == $node->vid;
1933  
1934      // There should be at least two revisions. If the vid of the given node and
1935      // the vid of the current revision differ, then we already have two
1936      // different revisions so there is no need for a separate database check.
1937      // Also, if you try to revert to or delete the current revision, that's not
1938      // good.
1939      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')) {
1940        $access[$cid] = FALSE;
1941      }
1942      elseif (user_access('administer nodes', $account)) {
1943        $access[$cid] = TRUE;
1944      }
1945      else {
1946        // First check the access to the current revision and finally, if the node
1947        // passed in is not the current revision then access to that, too.
1948        $access[$cid] = node_access($op, $node_current_revision, $account) && ($is_current_revision || node_access($op, $node, $account));
1949      }
1950    }
1951  
1952    return $access[$cid];
1953  }
1954  
1955  /**
1956   * Access callback: Checks whether the user has permission to add a node.
1957   *
1958   * @return
1959   *   TRUE if the user has add permission, otherwise FALSE.
1960   *
1961   * @see node_menu()
1962   */
1963  function _node_add_access() {
1964    $types = node_type_get_types();
1965    foreach ($types as $type) {
1966      if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
1967        return TRUE;
1968      }
1969    }
1970    if (user_access('administer content types')) {
1971      // There are no content types defined that the user has permission to create,
1972      // but the user does have the permission to administer the content types, so
1973      // grant them access to the page anyway.
1974      return TRUE;
1975    }
1976    return FALSE;
1977  }
1978  
1979  /**
1980   * Implements hook_menu().
1981   */
1982  function node_menu() {
1983    $items['admin/content'] = array(
1984      'title' => 'Content',
1985      'description' => 'Find and manage content.',
1986      'page callback' => 'drupal_get_form',
1987      'page arguments' => array('node_admin_content'),
1988      'access arguments' => array('access content overview'),
1989      'weight' => -10,
1990      'file' => 'node.admin.inc',
1991    );
1992    $items['admin/content/node'] = array(
1993      'title' => 'Content',
1994      'type' => MENU_DEFAULT_LOCAL_TASK,
1995      'weight' => -10,
1996    );
1997  
1998    $items['admin/reports/status/rebuild'] = array(
1999      'title' => 'Rebuild permissions',
2000      'page callback' => 'drupal_get_form',
2001      'page arguments' => array('node_configure_rebuild_confirm'),
2002      // Any user than can potentially trigger a node_access_needs_rebuild(TRUE)
2003      // has to be allowed access to the 'node access rebuild' confirm form.
2004      'access arguments' => array('access administration pages'),
2005      'type' => MENU_CALLBACK,
2006      'file' => 'node.admin.inc',
2007    );
2008  
2009    $items['admin/structure/types'] = array(
2010      'title' => 'Content types',
2011      'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
2012      'page callback' => 'node_overview_types',
2013      'access arguments' => array('administer content types'),
2014      'file' => 'content_types.inc',
2015    );
2016    $items['admin/structure/types/list'] = array(
2017      'title' => 'List',
2018      'type' => MENU_DEFAULT_LOCAL_TASK,
2019      'weight' => -10,
2020    );
2021    $items['admin/structure/types/add'] = array(
2022      'title' => 'Add content type',
2023      'page callback' => 'drupal_get_form',
2024      'page arguments' => array('node_type_form'),
2025      'access arguments' => array('administer content types'),
2026      'type' => MENU_LOCAL_ACTION,
2027      'file' => 'content_types.inc',
2028    );
2029    $items['admin/structure/types/manage/%node_type'] = array(
2030      'title' => 'Edit content type',
2031      'title callback' => 'node_type_page_title',
2032      'title arguments' => array(4),
2033      'page callback' => 'drupal_get_form',
2034      'page arguments' => array('node_type_form', 4),
2035      'access arguments' => array('administer content types'),
2036      'file' => 'content_types.inc',
2037    );
2038    $items['admin/structure/types/manage/%node_type/edit'] = array(
2039      'title' => 'Edit',
2040      'type' => MENU_DEFAULT_LOCAL_TASK,
2041    );
2042    $items['admin/structure/types/manage/%node_type/delete'] = array(
2043      'title' => 'Delete',
2044      'page arguments' => array('node_type_delete_confirm', 4),
2045      'access arguments' => array('administer content types'),
2046      'file' => 'content_types.inc',
2047    );
2048  
2049    $items['node'] = array(
2050      'page callback' => 'node_page_default',
2051      'access arguments' => array('access content'),
2052      'menu_name' => 'navigation',
2053      'type' => MENU_CALLBACK,
2054    );
2055    $items['node/add'] = array(
2056      'title' => 'Add content',
2057      'page callback' => 'node_add_page',
2058      'access callback' => '_node_add_access',
2059      'file' => 'node.pages.inc',
2060    );
2061    $items['rss.xml'] = array(
2062      'title' => 'RSS feed',
2063      'page callback' => 'node_feed',
2064      'access arguments' => array('access content'),
2065      'type' => MENU_CALLBACK,
2066      // Pass a FALSE and array argument to ensure that additional path components
2067      // are not passed to node_feed().
2068      'page arguments' => array(FALSE, array()),
2069    );
2070    // @todo Remove this loop when we have a 'description callback' property.
2071    // Reset internal static cache of _node_types_build(), forces to rebuild the
2072    // node type information.
2073    node_type_cache_reset();
2074    foreach (node_type_get_types() as $type) {
2075      $type_url_str = str_replace('_', '-', $type->type);
2076      $items['node/add/' . $type_url_str] = array(
2077        'title' => $type->name,
2078        'title callback' => 'check_plain',
2079        'page callback' => 'node_add',
2080        'page arguments' => array($type->type),
2081        'access callback' => 'node_access',
2082        'access arguments' => array('create', $type->type),
2083        'description' => $type->description,
2084        'file' => 'node.pages.inc',
2085      );
2086    }
2087    $items['node/%node'] = array(
2088      'title callback' => 'node_page_title',
2089      'title arguments' => array(1),
2090      // The page callback also invokes drupal_set_title() in case
2091      // the menu router's title is overridden by a menu link.
2092      'page callback' => 'node_page_view',
2093      'page arguments' => array(1),
2094      'access callback' => 'node_access',
2095      'access arguments' => array('view', 1),
2096    );
2097    $items['node/%node/view'] = array(
2098      'title' => 'View',
2099      'type' => MENU_DEFAULT_LOCAL_TASK,
2100      'weight' => -10,
2101    );
2102    $items['node/%node/edit'] = array(
2103      'title' => 'Edit',
2104      'page callback' => 'node_page_edit',
2105      'page arguments' => array(1),
2106      'access callback' => 'node_access',
2107      'access arguments' => array('update', 1),
2108      'weight' => 0,
2109      'type' => MENU_LOCAL_TASK,
2110      'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
2111      'file' => 'node.pages.inc',
2112    );
2113    $items['node/%node/delete'] = array(
2114      'title' => 'Delete',
2115      'page callback' => 'drupal_get_form',
2116      'page arguments' => array('node_delete_confirm', 1),
2117      'access callback' => 'node_access',
2118      'access arguments' => array('delete', 1),
2119      'weight' => 1,
2120      'type' => MENU_LOCAL_TASK,
2121      'context' => MENU_CONTEXT_INLINE,
2122      'file' => 'node.pages.inc',
2123    );
2124    $items['node/%node/revisions'] = array(
2125      'title' => 'Revisions',
2126      'page callback' => 'node_revision_overview',
2127      'page arguments' => array(1),
2128      'access callback' => '_node_revision_access',
2129      'access arguments' => array(1),
2130      'weight' => 2,
2131      'type' => MENU_LOCAL_TASK,
2132      'file' => 'node.pages.inc',
2133    );
2134    $items['node/%node/revisions/%/view'] = array(
2135      'title' => 'Revisions',
2136      'load arguments' => array(3),
2137      'page callback' => 'node_show',
2138      'page arguments' => array(1, TRUE),
2139      'access callback' => '_node_revision_access',
2140      'access arguments' => array(1),
2141    );
2142    $items['node/%node/revisions/%/revert'] = array(
2143      'title' => 'Revert to earlier revision',
2144      'load arguments' => array(3),
2145      'page callback' => 'drupal_get_form',
2146      'page arguments' => array('node_revision_revert_confirm', 1),
2147      'access callback' => '_node_revision_access',
2148      'access arguments' => array(1, 'update'),
2149      'file' => 'node.pages.inc',
2150    );
2151    $items['node/%node/revisions/%/delete'] = array(
2152      'title' => 'Delete earlier revision',
2153      'load arguments' => array(3),
2154      'page callback' => 'drupal_get_form',
2155      'page arguments' => array('node_revision_delete_confirm', 1),
2156      'access callback' => '_node_revision_access',
2157      'access arguments' => array(1, 'delete'),
2158      'file' => 'node.pages.inc',
2159    );
2160    return $items;
2161  }
2162  
2163  /**
2164   * Implements hook_menu_local_tasks_alter().
2165   */
2166  function node_menu_local_tasks_alter(&$data, $router_item, $root_path) {
2167    // Add action link to 'node/add' on 'admin/content' page.
2168    if ($root_path == 'admin/content') {
2169      $item = menu_get_item('node/add');
2170      if ($item['access']) {
2171        $data['actions']['output'][] = array(
2172          '#theme' => 'menu_local_action',
2173          '#link' => $item,
2174        );
2175      }
2176    }
2177  }
2178  
2179  /**
2180   * Title callback: Returns the unsanitized title of the node type edit form.
2181   *
2182   * @param $type
2183   *   The node type object.
2184   *
2185   * @return string
2186   *   An unsanitized string that is the title of the node type edit form.
2187   *
2188   * @see node_menu()
2189   */
2190  function node_type_page_title($type) {
2191    return $type->name;
2192  }
2193  
2194  /**
2195   * Title callback: Returns the title of the node.
2196   *
2197   * @param $node
2198   *   The node object.
2199   *
2200   * @return
2201   *   An unsanitized string that is the title of the node.
2202   *
2203   * @see node_menu()
2204   */
2205  function node_page_title($node) {
2206    return $node->title;
2207  }
2208  
2209  /**
2210   * Finds the last time a node was changed.
2211   *
2212   * @param $nid
2213   *   The ID of a node.
2214   *
2215   * @return
2216   *   A unix timestamp indicating the last time the node was changed.
2217   */
2218  function node_last_changed($nid) {
2219    return db_query('SELECT changed FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetch()->changed;
2220  }
2221  
2222  /**
2223   * Returns a list of all the existing revision numbers.
2224   *
2225   * @param $node
2226   *   The node object.
2227   *
2228   * @return
2229   *   An associative array keyed by node revision number.
2230   */
2231  function node_revision_list($node) {
2232    $revisions = array();
2233    $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.vid DESC', array(':nid' => $node->nid));
2234    foreach ($result as $revision) {
2235      $revisions[$revision->vid] = $revision;
2236    }
2237  
2238    return $revisions;
2239  }
2240  
2241  /**
2242   * Implements hook_block_info().
2243   */
2244  function node_block_info() {
2245    $blocks['syndicate']['info'] = t('Syndicate');
2246    // Not worth caching.
2247    $blocks['syndicate']['cache'] = DRUPAL_NO_CACHE;
2248  
2249    $blocks['recent']['info'] = t('Recent content');
2250    $blocks['recent']['properties']['administrative'] = TRUE;
2251  
2252    return $blocks;
2253  }
2254  
2255  /**
2256   * Implements hook_block_view().
2257   */
2258  function node_block_view($delta = '') {
2259    $block = array();
2260  
2261    switch ($delta) {
2262      case 'syndicate':
2263        $block['subject'] = t('Syndicate');
2264        $block['content'] = theme('feed_icon', array('url' => 'rss.xml', 'title' => t('Syndicate')));
2265        break;
2266  
2267      case 'recent':
2268        if (user_access('access content')) {
2269          $block['subject'] = t('Recent content');
2270          if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
2271            $block['content'] = theme('node_recent_block', array(
2272              'nodes' => $nodes,
2273            ));
2274          } else {
2275            $block['content'] = t('No content available.');
2276          }
2277        }
2278        break;
2279    }
2280    return $block;
2281  }
2282  
2283  /**
2284   * Implements hook_block_configure().
2285   */
2286  function node_block_configure($delta = '') {
2287    $form = array();
2288    if ($delta == 'recent') {
2289      $form['node_recent_block_count'] = array(
2290        '#type' => 'select',
2291        '#title' => t('Number of recent content items to display'),
2292        '#default_value' => variable_get('node_recent_block_count', 10),
2293        '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30)),
2294      );
2295    }
2296    return $form;
2297  }
2298  
2299  /**
2300   * Implements hook_block_save().
2301   */
2302  function node_block_save($delta = '', $edit = array()) {
2303    if ($delta == 'recent') {
2304      variable_set('node_recent_block_count', $edit['node_recent_block_count']);
2305    }
2306  }
2307  
2308  /**
2309   * Finds the most recently changed nodes that are available to the current user.
2310   *
2311   * @param $number
2312   *   (optional) The maximum number of nodes to find. Defaults to 10.
2313   *
2314   * @return
2315   *   An array of node entities or an empty array if there are no recent nodes
2316   *   visible to the current user.
2317   */
2318  function node_get_recent($number = 10) {
2319    $query = db_select('node', 'n');
2320  
2321    if (!user_access('bypass node access')) {
2322      // If the user is able to view their own unpublished nodes, allow them to
2323      // see these in addition to published nodes. Check that they actually have
2324      // some unpublished nodes to view before adding the condition.
2325      if (user_access('view own unpublished content') && $own_unpublished = db_query('SELECT nid FROM {node} WHERE uid = :uid AND status = :status', array(':uid' => $GLOBALS['user']->uid, ':status' => NODE_NOT_PUBLISHED))->fetchCol()) {
2326        $query->condition(db_or()
2327          ->condition('n.status', NODE_PUBLISHED)
2328          ->condition('n.nid', $own_unpublished, 'IN')
2329        );
2330      }
2331      else {
2332        // If not, restrict the query to published nodes.
2333        $query->condition('n.status', NODE_PUBLISHED);
2334      }
2335    }
2336    $nids = $query
2337      ->fields('n', array('nid'))
2338      ->orderBy('n.changed', 'DESC')
2339      ->range(0, $number)
2340      ->addTag('node_access')
2341      ->execute()
2342      ->fetchCol();
2343  
2344    $nodes = node_load_multiple($nids);
2345  
2346    return $nodes ? $nodes : array();
2347  }
2348  
2349  /**
2350   * Returns HTML for a list of recent content.
2351   *
2352   * @param $variables
2353   *   An associative array containing:
2354   *   - nodes: An array of recent node objects.
2355   *
2356   * @ingroup themeable
2357   */
2358  function theme_node_recent_block($variables) {
2359    $rows = array();
2360    $output = '';
2361  
2362    $l_options = array('query' => drupal_get_destination());
2363    foreach ($variables['nodes'] as $node) {
2364      $row = array();
2365      $row[] = array(
2366        'data' => theme('node_recent_content', array('node' => $node)),
2367        'class' => 'title-author',
2368      );
2369      $row[] = array(
2370        'data' => node_access('update', $node) ? l(t('edit'), 'node/' . $node->nid . '/edit', $l_options) : '',
2371        'class' => 'edit',
2372      );
2373      $row[] = array(
2374        'data' => node_access('delete', $node) ? l(t('delete'), 'node/' . $node->nid . '/delete', $l_options) : '',
2375        'class' => 'delete',
2376      );
2377      $rows[] = $row;
2378    }
2379  
2380    if ($rows) {
2381      $output = theme('table', array('rows' => $rows));
2382      if (user_access('access content overview')) {
2383        $output .= theme('more_link', array('url' => 'admin/content', 'title' => t('Show more content')));
2384      }
2385    }
2386  
2387    return $output;
2388  }
2389  
2390  /**
2391   * Returns HTML for a recent node to be displayed in the recent content block.
2392   *
2393   * @param $variables
2394   *   An associative array containing:
2395   *   - node: A node object.
2396   *
2397   * @ingroup themeable
2398   */
2399  function theme_node_recent_content($variables) {
2400    $node = $variables['node'];
2401  
2402    $output = '<div class="node-title">';
2403    $output .= l($node->title, 'node/' . $node->nid);
2404    $output .= theme('mark', array('type' => node_mark($node->nid, $node->changed)));
2405    $output .= '</div><div class="node-author">';
2406    $output .= theme('username', array('account' => user_load($node->uid)));
2407    $output .= '</div>';
2408  
2409    return $output;
2410  }
2411  
2412  /**
2413   * Implements hook_form_FORMID_alter().
2414   *
2415   * Adds node-type specific visibility options to add block form.
2416   *
2417   * @see block_add_block_form()
2418   */
2419  function node_form_block_add_block_form_alter(&$form, &$form_state) {
2420    node_form_block_admin_configure_alter($form, $form_state);
2421  }
2422  
2423  /**
2424   * Implements hook_form_FORMID_alter().
2425   *
2426   * Adds node-type specific visibility options to block configuration form.
2427   *
2428   * @see block_admin_configure()
2429   */
2430  function node_form_block_admin_configure_alter(&$form, &$form_state) {
2431    $default_type_options = db_query("SELECT type FROM {block_node_type} WHERE module = :module AND delta = :delta", array(
2432      ':module' => $form['module']['#value'],
2433      ':delta' => $form['delta']['#value'],
2434    ))->fetchCol();
2435    $form['visibility']['node_type'] = array(
2436      '#type' => 'fieldset',
2437      '#title' => t('Content types'),
2438      '#collapsible' => TRUE,
2439      '#collapsed' => TRUE,
2440      '#group' => 'visibility',
2441      '#weight' => 5,
2442    );
2443    $form['visibility']['node_type']['types'] = array(
2444      '#type' => 'checkboxes',
2445      '#title' => t('Show block for specific content types'),
2446      '#default_value' => $default_type_options,
2447      '#options' => node_type_get_names(),
2448      '#description' => t('Show this block only on pages that display content of the given type(s). If you select no types, there will be no type-specific limitation.'),
2449    );
2450    $form['#submit'][] = 'node_form_block_admin_configure_submit';
2451  }
2452  
2453  /**
2454   * Form submission handler for node_form_block_admin_configure_alter().
2455   *
2456   * @see node_form_block_admin_configure_alter()
2457   */
2458  function node_form_block_admin_configure_submit($form, &$form_state) {
2459    db_delete('block_node_type')
2460      ->condition('module', $form_state['values']['module'])
2461      ->condition('delta', $form_state['values']['delta'])
2462      ->execute();
2463    $query = db_insert('block_node_type')->fields(array('type', 'module', 'delta'));
2464    foreach (array_filter($form_state['values']['types']) as $type) {
2465      $query->values(array(
2466        'type' => $type,
2467        'module' => $form_state['values']['module'],
2468        'delta' => $form_state['values']['delta'],
2469      ));
2470    }
2471    $query->execute();
2472  }
2473  
2474  /**
2475   * Implements hook_form_FORMID_alter().
2476   *
2477   * Adds node specific submit handler to delete custom block form.
2478   *
2479   * @see block_custom_block_delete()
2480   */
2481  function node_form_block_custom_block_delete_alter(&$form, &$form_state) {
2482    $form['#submit'][] = 'node_form_block_custom_block_delete_submit';
2483  }
2484  
2485  /**
2486   * Form submission handler for node_form_block_custom_block_delete_alter().
2487   *
2488   * @see node_form_block_custom_block_delete_alter()
2489   */
2490  function node_form_block_custom_block_delete_submit($form, &$form_state) {
2491    db_delete('block_node_type')
2492      ->condition('module', 'block')
2493      ->condition('delta', $form_state['values']['bid'])
2494      ->execute();
2495  }
2496  
2497  /**
2498   * Implements hook_modules_uninstalled().
2499   *
2500   * Cleanup {block_node_type} table from modules' blocks.
2501   */
2502  function node_modules_uninstalled($modules) {
2503    db_delete('block_node_type')
2504      ->condition('module', $modules, 'IN')
2505      ->execute();
2506  }
2507  
2508  /**
2509   * Implements hook_block_list_alter().
2510   *
2511   * Check the content type specific visibilty settings. Remove the block if the
2512   * visibility conditions are not met.
2513   */
2514  function node_block_list_alter(&$blocks) {
2515    global $theme_key;
2516  
2517    // Build an array of node types for each block.
2518    $block_node_types = array();
2519    $result = db_query('SELECT module, delta, type FROM {block_node_type}');
2520    foreach ($result as $record) {
2521      $block_node_types[$record->module][$record->delta][$record->type] = TRUE;
2522    }
2523  
2524    $node = menu_get_object();
2525    $node_types = node_type_get_types();
2526    if (arg(0) == 'node' && arg(1) == 'add' && arg(2)) {
2527      $node_add_arg = strtr(arg(2), '-', '_');
2528    }
2529    foreach ($blocks as $key => $block) {
2530      if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
2531        // This block was added by a contrib module, leave it in the list.
2532        continue;
2533      }
2534  
2535      // If a block has no node types associated, it is displayed for every type.
2536      // For blocks with node types associated, if the node type does not match
2537      // the settings from this block, remove it from the block list.
2538      if (isset($block_node_types[$block->module][$block->delta])) {
2539        if (!empty($node)) {
2540          // This is a node or node edit page.
2541          if (!isset($block_node_types[$block->module][$block->delta][$node->type])) {
2542            // This block should not be displayed for this node type.
2543            unset($blocks[$key]);
2544            continue;
2545          }
2546        }
2547        elseif (isset($node_add_arg) && isset($node_types[$node_add_arg])) {
2548          // This is a node creation page
2549          if (!isset($block_node_types[$block->module][$block->delta][$node_add_arg])) {
2550            // This block should not be displayed for this node type.
2551            unset($blocks[$key]);
2552            continue;
2553          }
2554        }
2555        else {
2556          // This is not a node page, remove the block.
2557          unset($blocks[$key]);
2558          continue;
2559        }
2560      }
2561    }
2562  }
2563  
2564  /**
2565   * Generates and prints an RSS feed.
2566   *
2567   * Generates an RSS feed from an array of node IDs, and prints it with an HTTP
2568   * header, with Content Type set to RSS/XML.
2569   *
2570   * @param $nids
2571   *   An array of node IDs (nid). Defaults to FALSE so empty feeds can be
2572   *   generated with passing an empty array, if no items are to be added
2573   *   to the feed.
2574   * @param $channel
2575   *   An associative array containing title, link, description and other keys,
2576   *   to be parsed by format_rss_channel() and format_xml_elements().
2577   *   A list of channel elements can be found at the
2578   *   @link http://cyber.law.harvard.edu/rss/rss.html RSS 2.0 Specification. @endlink
2579   *   The link should be an absolute URL.
2580   */
2581  function node_feed($nids = FALSE, $channel = array()) {
2582    global $base_url, $language_content;
2583  
2584    if ($nids === FALSE) {
2585      $nids = db_select('node', 'n')
2586        ->fields('n', array('nid', 'created'))
2587        ->condition('n.promote', 1)
2588        ->condition('n.status', 1)
2589        ->orderBy('n.created', 'DESC')
2590        ->range(0, variable_get('feed_default_items', 10))
2591        ->addTag('node_access')
2592        ->execute()
2593        ->fetchCol();
2594    }
2595  
2596    $item_length = variable_get('feed_item_length', 'fulltext');
2597    $namespaces = array('xmlns:dc' => 'http://purl.org/dc/elements/1.1/');
2598  
2599    // Load all nodes to be rendered.
2600    $nodes = node_load_multiple($nids);
2601    $items = '';
2602    foreach ($nodes as $node) {
2603      $item_text = '';
2604  
2605      $node->link = url("node/$node->nid", array('absolute' => TRUE));
2606      $node->rss_namespaces = array();
2607      $node->rss_elements = array(
2608        array('key' => 'pubDate', 'value' => gmdate('r', $node->created)),
2609        array('key' => 'dc:creator', 'value' => $node->name),
2610        array('key' => 'guid', 'value' => $node->nid . ' at ' . $base_url, 'attributes' => array('isPermaLink' => 'false'))
2611      );
2612  
2613      // The node gets built and modules add to or modify $node->rss_elements
2614      // and $node->rss_namespaces.
2615      $build = node_view($node, 'rss');
2616      unset($build['#theme']);
2617  
2618      if (!empty($node->rss_namespaces)) {
2619        $namespaces = array_merge($namespaces, $node->rss_namespaces);
2620      }
2621  
2622      if ($item_length != 'title') {
2623        // We render node contents and force links to be last.
2624        $build['links']['#weight'] = 1000;
2625        $item_text .= drupal_render($build);
2626      }
2627  
2628      $items .= format_rss_item($node->title, $node->link, $item_text, $node->rss_elements);
2629    }
2630  
2631    $channel_defaults = array(
2632      'version'     => '2.0',
2633      'title'       => variable_get('site_name', 'Drupal'),
2634      'link'        => $base_url,
2635      'description' => variable_get('feed_description', ''),
2636      'language'    => $language_content->language
2637    );
2638    $channel_extras = array_diff_key($channel, $channel_defaults);
2639    $channel = array_merge($channel_defaults, $channel);
2640  
2641    $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
2642    $output .= "<rss version=\"" . $channel["version"] . "\" xml:base=\"" . $base_url . "\" " . drupal_attributes($namespaces) . ">\n";
2643    $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language'], $channel_extras);
2644    $output .= "</rss>\n";
2645  
2646    drupal_add_http_header('Content-Type', 'application/rss+xml; charset=utf-8');
2647    print $output;
2648  }
2649  
2650  /**
2651   * Constructs a drupal_render() style array from an array of loaded nodes.
2652   *
2653   * @param $nodes
2654   *   An array of nodes as returned by node_load_multiple().
2655   * @param $view_mode
2656   *   View mode, e.g. 'full', 'teaser'...
2657   * @param $weight
2658   *   An integer representing the weight of the first node in the list.
2659   * @param $langcode
2660   *   (optional) A language code to use for rendering. Defaults to NULL which is
2661   *   the global content language of the current request.
2662   *
2663   * @return
2664   *   An array in the format expected by drupal_render().
2665   */
2666  function node_view_multiple($nodes, $view_mode = 'teaser', $weight = 0, $langcode = NULL) {
2667    field_attach_prepare_view('node', $nodes, $view_mode, $langcode);
2668    entity_prepare_view('node', $nodes, $langcode);
2669    $build = array();
2670    foreach ($nodes as $node) {
2671      $build['nodes'][$node->nid] = node_view($node, $view_mode, $langcode);
2672      $build['nodes'][$node->nid]['#weight'] = $weight;
2673      $weight++;
2674    }
2675    $build['nodes']['#sorted'] = TRUE;
2676    return $build;
2677  }
2678  
2679  /**
2680   * Menu callback: Generates a listing of promoted nodes.
2681   *
2682   * @return array
2683   *   An array in the format expected by drupal_render().
2684   *
2685   * @see node_menu()
2686   */
2687  function node_page_default() {
2688    $select = db_select('node', 'n')
2689      ->fields('n', array('nid', 'sticky', 'created'))
2690      ->condition('n.promote', 1)
2691      ->condition('n.status', 1)
2692      ->orderBy('n.sticky', 'DESC')
2693      ->orderBy('n.created', 'DESC')
2694      ->extend('PagerDefault')
2695      ->limit(variable_get('default_nodes_main', 10))
2696      ->addTag('node_access');
2697  
2698    $nids = $select->execute()->fetchCol();
2699  
2700    if (!empty($nids)) {
2701      $nodes = node_load_multiple($nids);
2702      $build = node_view_multiple($nodes);
2703  
2704      // 'rss.xml' is a path, not a file, registered in node_menu().
2705      drupal_add_feed('rss.xml', variable_get('site_name', 'Drupal') . ' ' . t('RSS'));
2706      $build['pager'] = array(
2707        '#theme' => 'pager',
2708        '#weight' => 5,
2709      );
2710      drupal_set_title('');
2711    }
2712    else {
2713      drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);
2714  
2715      $default_message = '<p>' . t('No front page content has been created yet.') . '</p>';
2716  
2717      $default_links = array();
2718      if (_node_add_access()) {
2719        $default_links[] = l(t('Add new content'), 'node/add');
2720      }
2721      if (!empty($default_links)) {
2722        $default_message .= theme('item_list', array('items' => $default_links));
2723      }
2724  
2725      $build['default_message'] = array(
2726        '#markup' => $default_message,
2727        '#prefix' => '<div id="first-time">',
2728        '#suffix' => '</div>',
2729      );
2730    }
2731    return $build;
2732  }
2733  
2734  /**
2735   * Menu callback: Displays a single node.
2736   *
2737   * @param $node
2738   *   The node object.
2739   *
2740   * @return
2741   *   A page array suitable for use by drupal_render().
2742   *
2743   * @see node_menu()
2744   */
2745  function node_page_view($node) {
2746    // If there is a menu link to this node, the link becomes the last part
2747    // of the active trail, and the link name becomes the page title.
2748    // Thus, we must explicitly set the page title to be the node title.
2749    drupal_set_title($node->title);
2750    $uri = entity_uri('node', $node);
2751    // Set the node path as the canonical URL to prevent duplicate content.
2752    drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
2753    // Set the non-aliased path as a default shortlink.
2754    drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
2755    return node_show($node);
2756  }
2757  
2758  /**
2759   * Implements hook_update_index().
2760   */
2761  function node_update_index() {
2762    $limit = (int)variable_get('search_cron_limit', 100);
2763  
2764    $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'));
2765  
2766    foreach ($result as $node) {
2767      _node_index_node($node);
2768    }
2769  }
2770  
2771  /**
2772   * Indexes a single node.
2773   *
2774   * @param $node
2775   *   The node to index.
2776   */
2777  function _node_index_node($node) {
2778    $node = node_load($node->nid);
2779  
2780    // Save the changed time of the most recent indexed node, for the search
2781    // results half-life calculation.
2782    variable_set('node_cron_last', $node->changed);
2783  
2784    // Render the node.
2785    $build = node_view($node, 'search_index');
2786    unset($build['#theme']);
2787    $node->rendered = drupal_render($build);
2788  
2789    $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->rendered;
2790  
2791    // Fetch extra data normally not visible
2792    $extra = module_invoke_all('node_update_index', $node);
2793    foreach ($extra as $t) {
2794      $text .= $t;
2795    }
2796  
2797    // Update index
2798    search_index($node->nid, 'node', $text);
2799  }
2800  
2801  /**
2802   * Implements hook_form_FORM_ID_alter().
2803   */
2804  function node_form_search_form_alter(&$form, $form_state) {
2805    if (isset($form['module']) && $form['module']['#value'] == 'node' && user_access('use advanced search')) {
2806      // Keyword boxes:
2807      $form['advanced'] = array(
2808        '#type' => 'fieldset',
2809        '#title' => t('Advanced search'),
2810        '#collapsible' => TRUE,
2811        '#collapsed' => TRUE,
2812        '#attributes' => array('class' => array('search-advanced')),
2813      );
2814      $form['advanced']['keywords'] = array(
2815        '#prefix' => '<div class="criterion">',
2816        '#suffix' => '</div>',
2817      );
2818      $form['advanced']['keywords']['or'] = array(
2819        '#type' => 'textfield',
2820        '#title' => t('Containing any of the words'),
2821        '#size' => 30,
2822        '#maxlength' => 255,
2823      );
2824      $form['advanced']['keywords']['phrase'] = array(
2825        '#type' => 'textfield',
2826        '#title' => t('Containing the phrase'),
2827        '#size' => 30,
2828        '#maxlength' => 255,
2829      );
2830      $form['advanced']['keywords']['negative'] = array(
2831        '#type' => 'textfield',
2832        '#title' => t('Containing none of the words'),
2833        '#size' => 30,
2834        '#maxlength' => 255,
2835      );
2836  
2837      // Node types:
2838      $types = array_map('check_plain', node_type_get_names());
2839      $form['advanced']['type'] = array(
2840        '#type' => 'checkboxes',
2841        '#title' => t('Only of the type(s)'),
2842        '#prefix' => '<div class="criterion">',
2843        '#suffix' => '</div>',
2844        '#options' => $types,
2845      );
2846      $form['advanced']['submit'] = array(
2847        '#type' => 'submit',
2848        '#value' => t('Advanced search'),
2849        '#prefix' => '<div class="action">',
2850        '#suffix' => '</div>',
2851        '#weight' => 100,
2852      );
2853  
2854      // Languages:
2855      $language_options = array();
2856      foreach (language_list('language') as $key => $entity) {
2857        if ($entity->enabled) {
2858          $language_options[$key] = $entity->name;
2859        }
2860      }
2861      if (count($language_options) > 1) {
2862        $form['advanced']['language'] = array(
2863          '#type' => 'checkboxes',
2864          '#title' => t('Languages'),
2865          '#prefix' => '<div class="criterion">',
2866          '#suffix' => '</div>',
2867          '#options' => $language_options,
2868        );
2869      }
2870  
2871      $form['#validate'][] = 'node_search_validate';
2872    }
2873  }
2874  
2875  /**
2876   * Form validation handler for node_form_alter().
2877   */
2878  function node_search_validate($form, &$form_state) {
2879    // Initialize using any existing basic search keywords.
2880    $keys = $form_state['values']['processed_keys'];
2881  
2882    // Insert extra restrictions into the search keywords string.
2883    if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) {
2884      // Retrieve selected types - Form API sets the value of unselected
2885      // checkboxes to 0.
2886      $form_state['values']['type'] = array_filter($form_state['values']['type']);
2887      if (count($form_state['values']['type'])) {
2888        $keys = search_expression_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
2889      }
2890    }
2891  
2892    if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
2893      $keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
2894    }
2895    if (isset($form_state['values']['language']) && is_array($form_state['values']['language'])) {
2896      $languages = array_filter($form_state['values']['language']);
2897      if (count($languages)) {
2898        $keys = search_expression_insert($keys, 'language', implode(',', $languages));
2899      }
2900    }
2901    if ($form_state['values']['or'] != '') {
2902      if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['or'], $matches)) {
2903        $keys .= ' ' . implode(' OR ', $matches[1]);
2904      }
2905    }
2906    if ($form_state['values']['negative'] != '') {
2907      if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['negative'], $matches)) {
2908        $keys .= ' -' . implode(' -', $matches[1]);
2909      }
2910    }
2911    if ($form_state['values']['phrase'] != '') {
2912      $keys .= ' "' . str_replace('"', ' ', $form_state['values']['phrase']) . '"';
2913    }
2914    if (!empty($keys)) {
2915      form_set_value($form['basic']['processed_keys'], trim($keys), $form_state);
2916    }
2917  }
2918  
2919  /**
2920   * @defgroup node_access Node access rights
2921   * @{
2922   * The node access system determines who can do what to which nodes.
2923   *
2924   * In determining access rights for a node, node_access() first checks whether
2925   * the user has the "bypass node access" permission. Such users have
2926   * unrestricted access to all nodes. user 1 will always pass this check.
2927   *
2928   * Next, all implementations of hook_node_access() will be called. Each
2929   * implementation may explicitly allow, explicitly deny, or ignore the access
2930   * request. If at least one module says to deny the request, it will be rejected.
2931   * If no modules deny the request and at least one says to allow it, the request
2932   * will be permitted.
2933   *
2934   * If all modules ignore the access request, then the node_access table is used
2935   * to determine access. All node access modules are queried using
2936   * hook_node_grants() to assemble a list of "grant IDs" for the user. This list
2937   * is compared against the table. If any row contains the node ID in question
2938   * (or 0, which stands for "all nodes"), one of the grant IDs returned, and a
2939   * value of TRUE for the operation in question, then access is granted. Note
2940   * that this table is a list of grants; any matching row is sufficient to
2941   * grant access to the node.
2942   *
2943   * In node listings (lists of nodes generated from a select query, such as the
2944   * default home page at path 'node', an RSS feed, a recent content block, etc.),
2945   * the process above is followed except that hook_node_access() is not called on
2946   * each node for performance reasons and for proper functioning of the pager
2947   * system. When adding a node listing to your module, be sure to use a dynamic
2948   * query created by db_select() and add a tag of "node_access". This will allow
2949   * modules dealing with node access to ensure only nodes to which the user has
2950   * access are retrieved, through the use of hook_query_TAG_alter().
2951   *
2952   * Note: Even a single module returning NODE_ACCESS_DENY from hook_node_access()
2953   * will block access to the node. Therefore, implementers should take care to
2954   * not deny access unless they really intend to. Unless a module wishes to
2955   * actively deny access it should return NODE_ACCESS_IGNORE (or simply return
2956   * nothing) to allow other modules or the node_access table to control access.
2957   *
2958   * To see how to write a node access module of your own, see
2959   * node_access_example.module.
2960   */
2961  
2962  /**
2963   * Determines whether the current user may perform the operation on the node.
2964   *
2965   * @param $op
2966   *   The operation to be performed on the node. Possible values are:
2967   *   - "view"
2968   *   - "update"
2969   *   - "delete"
2970   *   - "create"
2971   * @param $node
2972   *   The node object on which the operation is to be performed, or node type
2973   *   (e.g. 'forum') for "create" operation.
2974   * @param $account
2975   *   Optional, a user object representing the user for whom the operation is to
2976   *   be performed. Determines access for a user other than the current user.
2977   *
2978   * @return
2979   *   TRUE if the operation may be performed, FALSE otherwise.
2980   */
2981  function node_access($op, $node, $account = NULL) {
2982    $rights = &drupal_static(__FUNCTION__, array());
2983  
2984    if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
2985      // If there was no node to check against, or the $op was not one of the
2986      // supported ones, we return access denied.
2987      return FALSE;
2988    }
2989    // If no user object is supplied, the access check is for the current user.
2990    if (empty($account)) {
2991      $account = $GLOBALS['user'];
2992    }
2993  
2994    // $node may be either an object or a node type. Since node types cannot be
2995    // an integer, use either nid or type as the static cache id.
2996  
2997    $cid = is_object($node) ? $node->nid : $node;
2998  
2999    // If we've already checked access for this node, user and op, return from
3000    // cache.
3001    if (isset($rights[$account->uid][$cid][$op])) {
3002      return $rights[$account->uid][$cid][$op];
3003    }
3004  
3005    if (user_access('bypass node access', $account)) {
3006      $rights[$account->uid][$cid][$op] = TRUE;
3007      return TRUE;
3008    }
3009    if (!user_access('access content', $account)) {
3010      $rights[$account->uid][$cid][$op] = FALSE;
3011      return FALSE;
3012    }
3013  
3014    // We grant access to the node if both of the following conditions are met:
3015    // - No modules say to deny access.
3016    // - At least one module says to grant access.
3017    // If no module specified either allow or deny, we fall back to the
3018    // node_access table.
3019    $access = module_invoke_all('node_access', $node, $op, $account);
3020    if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
3021      $rights[$account->uid][$cid][$op] = FALSE;
3022      return FALSE;
3023    }
3024    elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
3025      $rights[$account->uid][$cid][$op] = TRUE;
3026      return TRUE;
3027    }
3028  
3029    // Check if authors can view their own unpublished nodes.
3030    if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
3031      $rights[$account->uid][$cid][$op] = TRUE;
3032      return TRUE;
3033    }
3034  
3035    // If the module did not override the access rights, use those set in the
3036    // node_access table.
3037    if ($op != 'create' && $node->nid) {
3038      if (module_implements('node_grants')) {
3039        $query = db_select('node_access');
3040        $query->addExpression('1');
3041        $query->condition('grant_' . $op, 1, '>=');
3042        $nids = db_or()->condition('nid', $node->nid);
3043        if ($node->status) {
3044          $nids->condition('nid', 0);
3045        }
3046        $query->condition($nids);
3047        $query->range(0, 1);
3048  
3049        $grants = db_or();
3050        foreach (node_access_grants($op, $account) as $realm => $gids) {
3051          foreach ($gids as $gid) {
3052            $grants->condition(db_and()
3053              ->condition('gid', $gid)
3054              ->condition('realm', $realm)
3055            );
3056          }
3057        }
3058        if (count($grants) > 0) {
3059          $query->condition($grants);
3060        }
3061        $result =  (bool) $query
3062          ->execute()
3063          ->fetchField();
3064        $rights[$account->uid][$cid][$op] = $result;
3065        return $result;
3066      }
3067      elseif (is_object($node) && $op == 'view' && $node->status) {
3068        // If no modules implement hook_node_grants(), the default behavior is to
3069        // allow all users to view published nodes, so reflect that here.
3070        $rights[$account->uid][$cid][$op] = TRUE;
3071        return TRUE;
3072      }
3073    }
3074  
3075    return FALSE;
3076  }
3077  
3078  /**
3079   * Implements hook_node_access().
3080   */
3081  function node_node_access($node, $op, $account) {
3082    $type = is_string($node) ? $node : $node->type;
3083  
3084    if (in_array($type, node_permissions_get_configured_types())) {
3085      if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
3086        return NODE_ACCESS_ALLOW;
3087      }
3088  
3089      if ($op == 'update') {
3090        if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
3091          return NODE_ACCESS_ALLOW;
3092        }
3093      }
3094  
3095      if ($op == 'delete') {
3096        if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
3097          return NODE_ACCESS_ALLOW;
3098        }
3099      }
3100    }
3101  
3102    return NODE_ACCESS_IGNORE;
3103  }
3104  
3105  /**
3106   * Helper function to generate standard node permission list for a given type.
3107   *
3108   * @param $type
3109   *   The machine-readable name of the node type.
3110   *
3111   * @return array
3112   *   An array of permission names and descriptions.
3113   */
3114  function node_list_permissions($type) {
3115    $info = node_type_get_type($type);
3116  
3117    // Build standard list of node permissions for this type.
3118    $perms = array(
3119      "create $type content" => array(
3120        'title' => t('%type_name: Create new content', array('%type_name' => $info->name)),
3121      ),
3122      "edit own $type content" => array(
3123        'title' => t('%type_name: Edit own content', array('%type_name' => $info->name)),
3124      ),
3125      "edit any $type content" => array(
3126        'title' => t('%type_name: Edit any content', array('%type_name' => $info->name)),
3127      ),
3128      "delete own $type content" => array(
3129        'title' => t('%type_name: Delete own content', array('%type_name' => $info->name)),
3130      ),
3131      "delete any $type content" => array(
3132        'title' => t('%type_name: Delete any content', array('%type_name' => $info->name)),
3133      ),
3134    );
3135  
3136    return $perms;
3137  }
3138  
3139  /**
3140   * Returns an array of node types that should be managed by permissions.
3141   *
3142   * By default, this will include all node types in the system. To exclude a
3143   * specific node from getting permissions defined for it, set the
3144   * node_permissions_$type variable to 0. Core does not provide an interface for
3145   * doing so. However, contrib modules may exclude their own nodes in
3146   * hook_install(). Alternatively, contrib modules may configure all node types
3147   * at once, or decide to apply some other hook_node_access() implementation to
3148   * some or all node types.
3149   *
3150   * @return
3151   *   An array of node types managed by this module.
3152   */
3153  function node_permissions_get_configured_types() {
3154  
3155    $configured_types = array();
3156  
3157    foreach (node_type_get_types() as $type => $info) {
3158      if (variable_get('node_permissions_' . $type, 1)) {
3159        $configured_types[] = $type;
3160      }
3161    }
3162  
3163    return $configured_types;
3164  }
3165  
3166  /**
3167   * Fetches an array of permission IDs granted to the given user ID.
3168   *
3169   * The implementation here provides only the universal "all" grant. A node
3170   * access module should implement hook_node_grants() to provide a grant list for
3171   * the user.
3172   *
3173   * After the default grants have been loaded, we allow modules to alter the
3174   * grants array by reference. This hook allows for complex business logic to be
3175   * applied when integrating multiple node access modules.
3176   *
3177   * @param $op
3178   *   The operation that the user is trying to perform.
3179   * @param $account
3180   *   The user object for the user performing the operation. If omitted, the
3181   *   current user is used.
3182   *
3183   * @return
3184   *   An associative array in which the keys are realms, and the values are
3185   *   arrays of grants for those realms.
3186   */
3187  function node_access_grants($op, $account = NULL) {
3188  
3189    if (!isset($account)) {
3190      $account = $GLOBALS['user'];
3191    }
3192  
3193    // Fetch node access grants from other modules.
3194    $grants = module_invoke_all('node_grants', $account, $op);
3195    // Allow modules to alter the assigned grants.
3196    drupal_alter('node_grants', $grants, $account, $op);
3197  
3198    return array_merge(array('all' => array(0)), $grants);
3199  }
3200  
3201  /**
3202   * Determines whether the user has a global viewing grant for all nodes.
3203   *
3204   * Checks to see whether any module grants global 'view' access to a user
3205   * account; global 'view' access is encoded in the {node_access} table as a
3206   * grant with nid=0. If no node access modules are enabled, node.module defines
3207   * such a global 'view' access grant.
3208   *
3209   * This function is called when a node listing query is tagged with
3210   * 'node_access'; when this function returns TRUE, no node access joins are
3211   * added to the query.
3212   *
3213   * @param $account
3214   *   The user object for the user whose access is being checked. If omitted,
3215   *   the current user is used.
3216   *
3217   * @return
3218   *   TRUE if 'view' access to all nodes is granted, FALSE otherwise.
3219   *
3220   * @see hook_node_grants()
3221   * @see _node_query_node_access_alter()
3222   */
3223  function node_access_view_all_nodes($account = NULL) {
3224    global $user;
3225    if (!$account) {
3226      $account = $user;
3227    }
3228  
3229    // Statically cache results in an array keyed by $account->uid.
3230    $access = &drupal_static(__FUNCTION__);
3231    if (isset($access[$account->uid])) {
3232      return $access[$account->uid];
3233    }
3234  
3235    // If no modules implement the node access system, access is always TRUE.
3236    if (!module_implements('node_grants')) {
3237      $access[$account->uid] = TRUE;
3238    }
3239    else {
3240      $query = db_select('node_access');
3241      $query->addExpression('COUNT(*)');
3242      $query
3243        ->condition('nid', 0)
3244        ->condition('grant_view', 1, '>=');
3245  
3246      $grants = db_or();
3247      foreach (node_access_grants('view', $account) as $realm => $gids) {
3248        foreach ($gids as $gid) {
3249          $grants->condition(db_and()
3250            ->condition('gid', $gid)
3251            ->condition('realm', $realm)
3252          );
3253        }
3254      }
3255      if (count($grants) > 0 ) {
3256        $query->condition($grants);
3257      }
3258      $access[$account->uid] = $query
3259        ->execute()
3260        ->fetchField();
3261    }
3262  
3263    return $access[$account->uid];
3264  }
3265  
3266  
3267  /**
3268   * Implements hook_query_TAG_alter().
3269   *
3270   * This is the hook_query_alter() for queries tagged with 'node_access'. It adds
3271   * node access checks for the user account given by the 'account' meta-data (or
3272   * global $user if not provided), for an operation given by the 'op' meta-data
3273   * (or 'view' if not provided; other possible values are 'update' and 'delete').
3274   */
3275  function node_query_node_access_alter(QueryAlterableInterface $query) {
3276    _node_query_node_access_alter($query, 'node');
3277  }
3278  
3279  /**
3280   * Implements hook_query_TAG_alter().
3281   *
3282   * This function implements the same functionality as
3283   * node_query_node_access_alter() for the SQL field storage engine. Node access
3284   * conditions are added for field values belonging to nodes only.
3285   */
3286  function node_query_entity_field_access_alter(QueryAlterableInterface $query) {
3287    _node_query_node_access_alter($query, 'entity');
3288  }
3289  
3290  /**
3291   * Helper for node access functions.
3292   *
3293   * Queries tagged with 'node_access' that are not against the {node} table
3294   * should add the base table as metadata. For example:
3295   * @code
3296   *   $query
3297   *     ->addTag('node_access')
3298   *     ->addMetaData('base_table', 'taxonomy_index');
3299   * @endcode
3300   * If the query is not against the {node} table, an attempt is made to guess
3301   * the table, but is not recommended to rely on this as it is deprecated and not
3302   * allowed in Drupal 8. It is always safer to provide the table.
3303   *
3304   * @param $query
3305   *   The query to add conditions to.
3306   * @param $type
3307   *   Either 'node' or 'entity' depending on what sort of query it is. See
3308   *   node_query_node_access_alter() and node_query_entity_field_access_alter()
3309   *   for more.
3310   */
3311  function _node_query_node_access_alter($query, $type) {
3312    global $user;
3313  
3314    // Read meta-data from query, if provided.
3315    if (!$account = $query->getMetaData('account')) {
3316      $account = $user;
3317    }
3318    if (!$op = $query->getMetaData('op')) {
3319      $op = 'view';
3320    }
3321  
3322    // If $account can bypass node access, or there are no node access modules,
3323    // or the operation is 'view' and the $account has a global view grant
3324    // (such as a view grant for node ID 0), we don't need to alter the query.
3325    if (user_access('bypass node access', $account)) {
3326      return;
3327    }
3328    if (!count(module_implements('node_grants'))) {
3329      return;
3330    }
3331    if ($op == 'view' && node_access_view_all_nodes($account)) {
3332      return;
3333    }
3334  
3335    $tables = $query->getTables();
3336    $base_table = $query->getMetaData('base_table');
3337    // If no base table is specified explicitly, search for one.
3338    if (!$base_table) {
3339      $fallback = '';
3340      foreach ($tables as $alias => $table_info) {
3341        if (!($table_info instanceof SelectQueryInterface)) {
3342          $table = $table_info['table'];
3343          // If the node table is in the query, it wins immediately.
3344          if ($table == 'node') {
3345            $base_table = $table;
3346            break;
3347          }
3348          // Check whether the table has a foreign key to node.nid. If it does,
3349          // do not run this check again as we found a base table and only node
3350          // can triumph that.
3351          if (!$base_table) {
3352            // The schema is cached.
3353            $schema = drupal_get_schema($table);
3354            if (isset($schema['fields']['nid'])) {
3355              if (isset($schema['foreign keys'])) {
3356                foreach ($schema['foreign keys'] as $relation) {
3357                  if ($relation['table'] === 'node' && $relation['columns'] === array('nid' => 'nid')) {
3358                    $base_table = $table;
3359                  }
3360                }
3361              }
3362              else {
3363                // At least it's a nid. A table with a field called nid is very
3364                // very likely to be a node.nid in a node access query.
3365                $fallback = $table;
3366              }
3367            }
3368          }
3369        }
3370      }
3371      // If there is nothing else, use the fallback.
3372      if (!$base_table) {
3373        if ($fallback) {
3374          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);
3375          $base_table = $fallback;
3376        }
3377        else {
3378          throw new Exception(t('Query tagged for node access but there is no nid. Add foreign keys to node.nid in schema to fix.'));
3379        }
3380      }
3381    }
3382  
3383    // Find all instances of the base table being joined -- could appear
3384    // more than once in the query, and could be aliased. Join each one to
3385    // the node_access table.
3386  
3387    $grants = node_access_grants($op, $account);
3388    if ($type == 'entity') {
3389      // The original query looked something like:
3390      // @code
3391      //  SELECT nid FROM sometable s
3392      //  INNER JOIN node_access na ON na.nid = s.nid
3393      //  WHERE ($node_access_conditions)
3394      // @endcode
3395      //
3396      // Our query will look like:
3397      // @code
3398      //  SELECT entity_type, entity_id
3399      //  FROM field_data_something s
3400      //  LEFT JOIN node_access na ON s.entity_id = na.nid
3401      //  WHERE (entity_type = 'node' AND $node_access_conditions) OR (entity_type <> 'node')
3402      // @endcode
3403      //
3404      // So instead of directly adding to the query object, we need to collect
3405      // all of the node access conditions in a separate db_and() object and
3406      // then add it to the query at the end.
3407      $node_conditions = db_and();
3408    }
3409    foreach ($tables as $nalias => $tableinfo) {
3410      $table = $tableinfo['table'];
3411      if (!($table instanceof SelectQueryInterface) && $table == $base_table) {
3412        // Set the subquery.
3413        $subquery = db_select('node_access', 'na')
3414         ->fields('na', array('nid'));
3415  
3416        $grant_conditions = db_or();
3417        // If any grant exists for the specified user, then user has access
3418        // to the node for the specified operation.
3419        foreach ($grants as $realm => $gids) {
3420          foreach ($gids as $gid) {
3421            $grant_conditions->condition(db_and()
3422              ->condition('na.gid', $gid)
3423              ->condition('na.realm', $realm)
3424            );
3425          }
3426        }
3427  
3428        // Attach conditions to the subquery for nodes.
3429        if (count($grant_conditions->conditions())) {
3430          $subquery->condition($grant_conditions);
3431        }
3432        $subquery->condition('na.grant_' . $op, 1, '>=');
3433        $field = 'nid';
3434        // Now handle entities.
3435        if ($type == 'entity') {
3436          // Set a common alias for entities.
3437          $base_alias = $nalias;
3438          $field = 'entity_id';
3439        }
3440        $subquery->where("$nalias.$field = na.nid");
3441  
3442        // For an entity query, attach the subquery to entity conditions.
3443        if ($type == 'entity') {
3444          $node_conditions->exists($subquery);
3445        }
3446        // Otherwise attach it to the node query itself.
3447        else {
3448          $query->exists($subquery);
3449        }
3450      }
3451    }
3452  
3453    if ($type == 'entity' && count($subquery->conditions())) {
3454      // All the node access conditions are only for field values belonging to
3455      // nodes.
3456      $node_conditions->condition("$base_alias.entity_type", 'node');
3457      $or = db_or();
3458      $or->condition($node_conditions);
3459      // If the field value belongs to a non-node entity type then this function
3460      // does not do anything with it.
3461      $or->condition("$base_alias.entity_type", 'node', '<>');
3462      // Add the compiled set of rules to the query.
3463      $query->condition($or);
3464    }
3465  
3466  }
3467  
3468  /**
3469   * Gets the list of node access grants and writes them to the database.
3470   *
3471   * This function is called when a node is saved, and can also be called by
3472   * modules if something other than a node save causes node access permissions to
3473   * change. It collects all node access grants for the node from
3474   * hook_node_access_records() implementations, allows these grants to be altered
3475   * via hook_node_access_records_alter() implementations, and saves the collected
3476   * and altered grants to the database.
3477   *
3478   * @param $node
3479   *   The $node to acquire grants for.
3480   *
3481   * @param $delete
3482   *   Whether to delete existing node access records before inserting new ones.
3483   *   Defaults to TRUE.
3484   */
3485  function node_access_acquire_grants($node, $delete = TRUE) {
3486    $grants = module_invoke_all('node_access_records', $node);
3487    // Let modules alter the grants.
3488    drupal_alter('node_access_records', $grants, $node);
3489    // If no grants are set and the node is published, then use the default grant.
3490    if (empty($grants) && !empty($node->status)) {
3491      $grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0);
3492    }
3493    else {
3494      // Retain grants by highest priority.
3495      $grant_by_priority = array();
3496      foreach ($grants as $g) {
3497        $grant_by_priority[intval($g['priority'])][] = $g;
3498      }
3499      krsort($grant_by_priority);
3500      $grants = array_shift($grant_by_priority);
3501    }
3502  
3503    node_access_write_grants($node, $grants, NULL, $delete);
3504  }
3505  
3506  /**
3507   * Writes a list of grants to the database, deleting any previously saved ones.
3508   *
3509   * If a realm is provided, it will only delete grants from that realm, but it
3510   * will always delete a grant from the 'all' realm. Modules that utilize
3511   * node_access() can use this function when doing mass updates due to widespread
3512   * permission changes.
3513   *
3514   * Note: Don't call this function directly from a contributed module. Call
3515   * node_access_acquire_grants() instead.
3516   *
3517   * @param $node
3518   *   The node whose grants are being written.
3519   * @param $grants
3520   *   A list of grants to write. Each grant is an array that must contain the
3521   *   following keys: realm, gid, grant_view, grant_update, grant_delete.
3522   *   The realm is specified by a particular module; the gid is as well, and
3523   *   is a module-defined id to define grant privileges. each grant_* field
3524   *   is a boolean value.
3525   * @param $realm
3526   *   (optional) If provided, read/write grants for that realm only. Defaults to
3527   *   NULL.
3528   * @param $delete
3529   *   (optional) If false, does not delete records. This is only for optimization
3530   *   purposes, and assumes the caller has already performed a mass delete of
3531   *   some form. Defaults to TRUE.
3532   *
3533   * @see node_access_acquire_grants()
3534   */
3535  function node_access_write_grants($node, $grants, $realm = NULL, $delete = TRUE) {
3536    if ($delete) {
3537      $query = db_delete('node_access')->condition('nid', $node->nid);
3538      if ($realm) {
3539        $query->condition('realm', array($realm, 'all'), 'IN');
3540      }
3541      $query->execute();
3542    }
3543  
3544    // Only perform work when node_access modules are active.
3545    if (!empty($grants) && count(module_implements('node_grants'))) {
3546      $query = db_insert('node_access')->fields(array('nid', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete'));
3547      foreach ($grants as $grant) {
3548        if ($realm && $realm != $grant['realm']) {
3549          continue;
3550        }
3551        // Only write grants; denies are implicit.
3552        if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
3553          $grant['nid'] = $node->nid;
3554          $query->values($grant);
3555        }
3556      }
3557      $query->execute();
3558    }
3559  }
3560  
3561  /**
3562   * Flags or unflags the node access grants for rebuilding.
3563   *
3564   * If the argument isn't specified, the current value of the flag is returned.
3565   * When the flag is set, a message is displayed to users with 'access
3566   * administration pages' permission, pointing to the 'rebuild' confirm form.
3567   * This can be used as an alternative to direct node_access_rebuild calls,
3568   * allowing administrators to decide when they want to perform the actual
3569   * (possibly time consuming) rebuild. When unsure if the current user is an
3570   * administrator, node_access_rebuild() should be used instead.
3571   *
3572   * @param $rebuild
3573   *   (Optional) The boolean value to be written.
3574   *
3575   * @return
3576   *   The current value of the flag if no value was provided for $rebuild.
3577   *
3578   * @see node_access_rebuild()
3579   */
3580  function node_access_needs_rebuild($rebuild = NULL) {
3581    if (!isset($rebuild)) {
3582      return variable_get('node_access_needs_rebuild', FALSE);
3583    }
3584    elseif ($rebuild) {
3585      variable_set('node_access_needs_rebuild', TRUE);
3586    }
3587    else {
3588      variable_del('node_access_needs_rebuild');
3589    }
3590  }
3591  
3592  /**
3593   * Rebuilds the node access database.
3594   *
3595   * This is occasionally needed by modules that make system-wide changes to
3596   * access levels. When the rebuild is required by an admin-triggered action (e.g
3597   * module settings form), calling node_access_needs_rebuild(TRUE) instead of
3598   * node_access_rebuild() lets the user perform his changes and actually
3599   * rebuild only once he is done.
3600   *
3601   * Note: As of Drupal 6, node access modules are not required to (and actually
3602   * should not) call node_access_rebuild() in hook_enable/disable anymore.
3603   *
3604   * @see node_access_needs_rebuild()
3605   *
3606   * @param $batch_mode
3607   *   Set to TRUE to process in 'batch' mode, spawning processing over several
3608   *   HTTP requests (thus avoiding the risk of PHP timeout if the site has a
3609   *   large number of nodes).
3610   *   hook_update_N and any form submit handler are safe contexts to use the
3611   *   'batch mode'. Less decidable cases (such as calls from hook_user,
3612   *   hook_taxonomy, etc...) might consider using the non-batch mode.
3613   */
3614  function node_access_rebuild($batch_mode = FALSE) {
3615    db_delete('node_access')->execute();
3616    // Only recalculate if the site is using a node_access module.
3617    if (count(module_implements('node_grants'))) {
3618      if ($batch_mode) {
3619        $batch = array(
3620          'title' => t('Rebuilding content access permissions'),
3621          'operations' => array(
3622            array('_node_access_rebuild_batch_operation', array()),
3623          ),
3624          'finished' => '_node_access_rebuild_batch_finished'
3625        );
3626        batch_set($batch);
3627      }
3628      else {
3629        // Try to allocate enough time to rebuild node grants
3630        drupal_set_time_limit(240);
3631  
3632        $nids = db_query("SELECT nid FROM {node}")->fetchCol();
3633        foreach ($nids as $nid) {
3634          $node = node_load($nid, NULL, TRUE);
3635          // To preserve database integrity, only acquire grants if the node
3636          // loads successfully.
3637          if (!empty($node)) {
3638            node_access_acquire_grants($node);
3639          }
3640        }
3641      }
3642    }
3643    else {
3644      // Not using any node_access modules. Add the default grant.
3645      db_insert('node_access')
3646        ->fields(array(
3647          'nid' => 0,
3648          'realm' => 'all',
3649          'gid' => 0,
3650          'grant_view' => 1,
3651          'grant_update' => 0,
3652          'grant_delete' => 0,
3653        ))
3654        ->execute();
3655    }
3656  
3657    if (!isset($batch)) {
3658      drupal_set_message(t('Content permissions have been rebuilt.'));
3659      node_access_needs_rebuild(FALSE);
3660      cache_clear_all();
3661    }
3662  }
3663  
3664  /**
3665   * Performs batch operation for node_access_rebuild().
3666   *
3667   * This is a multistep operation: we go through all nodes by packs of 20. The
3668   * batch processing engine interrupts processing and sends progress feedback
3669   * after 1 second execution time.
3670   *
3671   * @param array $context
3672   *   An array of contextual key/value information for rebuild batch process.
3673   */
3674  function _node_access_rebuild_batch_operation(&$context) {
3675    if (empty($context['sandbox'])) {
3676      // Initiate multistep processing.
3677      $context['sandbox']['progress'] = 0;
3678      $context['sandbox']['current_node'] = 0;
3679      $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
3680    }
3681  
3682    // Process the next 20 nodes.
3683    $limit = 20;
3684    $nids = db_query_range("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, array(':nid' => $context['sandbox']['current_node']))->fetchCol();
3685    $nodes = node_load_multiple($nids, array(), TRUE);
3686    foreach ($nodes as $nid => $node) {
3687      // To preserve database integrity, only acquire grants if the node
3688      // loads successfully.
3689      if (!empty($node)) {
3690        node_access_acquire_grants($node);
3691      }
3692      $context['sandbox']['progress']++;
3693      $context['sandbox']['current_node'] = $nid;
3694    }
3695  
3696    // Multistep processing : report progress.
3697    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
3698      $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
3699    }
3700  }
3701  
3702  /**
3703   * Performs post-processing for node_access_rebuild().
3704   *
3705   * @param bool $success
3706   *   A boolean indicating whether the re-build process has completed.
3707   * @param array $results
3708   *   An array of results information.
3709   * @param array $operations
3710   *   An array of function calls (not used in this function).
3711   */
3712  function _node_access_rebuild_batch_finished($success, $results, $operations) {
3713    if ($success) {
3714      drupal_set_message(t('The content access permissions have been rebuilt.'));
3715      node_access_needs_rebuild(FALSE);
3716    }
3717    else {
3718      drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
3719    }
3720    cache_clear_all();
3721  }
3722  
3723  /**
3724   * @} End of "defgroup node_access".
3725   */
3726  
3727  /**
3728   * @defgroup node_content Hook implementations for user-created content types
3729   * @{
3730   * Functions that implement hooks for user-created content types.
3731   */
3732  
3733  /**
3734   * Implements hook_form().
3735   */
3736  function node_content_form($node, $form_state) {
3737    // It is impossible to define a content type without implementing hook_form()
3738    // @todo: remove this requirement.
3739    $form = array();
3740    $type = node_type_get_type($node);
3741  
3742    if ($type->has_title) {
3743      $form['title'] = array(
3744        '#type' => 'textfield',
3745        '#title' => check_plain($type->title_label),
3746        '#required' => TRUE,
3747        '#default_value' => $node->title,
3748        '#maxlength' => 255,
3749        '#weight' => -5,
3750      );
3751    }
3752  
3753    return $form;
3754  }
3755  
3756  /**
3757   * @} End of "defgroup node_content".
3758   */
3759  
3760  /**
3761   * Implements hook_forms().
3762   *
3763   * All node forms share the same form handler.
3764   */
3765  function node_forms() {
3766    $forms = array();
3767    if ($types = node_type_get_types()) {
3768      foreach (array_keys($types) as $type) {
3769        $forms[$type . '_node_form']['callback'] = 'node_form';
3770      }
3771    }
3772    return $forms;
3773  }
3774  
3775  /**
3776   * Implements hook_action_info().
3777   */
3778  function node_action_info() {
3779    return array(
3780      'node_publish_action' => array(
3781        'type' => 'node',
3782        'label' => t('Publish content'),
3783        'configurable' => FALSE,
3784        'behavior' => array('changes_property'),
3785        'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3786      ),
3787      'node_unpublish_action' => array(
3788        'type' => 'node',
3789        'label' => t('Unpublish content'),
3790        'configurable' => FALSE,
3791        'behavior' => array('changes_property'),
3792        'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3793      ),
3794      'node_make_sticky_action' => array(
3795        'type' => 'node',
3796        'label' => t('Make content sticky'),
3797        'configurable' => FALSE,
3798        'behavior' => array('changes_property'),
3799        'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3800      ),
3801      'node_make_unsticky_action' => array(
3802        'type' => 'node',
3803        'label' => t('Make content unsticky'),
3804        'configurable' => FALSE,
3805        'behavior' => array('changes_property'),
3806        'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3807      ),
3808      'node_promote_action' => array(
3809        'type' => 'node',
3810        'label' => t('Promote content to front page'),
3811        'configurable' => FALSE,
3812        'behavior' => array('changes_property'),
3813        'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3814      ),
3815      'node_unpromote_action' => array(
3816        'type' => 'node',
3817        'label' => t('Remove content from front page'),
3818        'configurable' => FALSE,
3819        'behavior' => array('changes_property'),
3820        'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3821      ),
3822      'node_assign_owner_action' => array(
3823        'type' => 'node',
3824        'label' => t('Change the author of content'),
3825        'configurable' => TRUE,
3826        'behavior' => array('changes_property'),
3827        'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3828      ),
3829      'node_save_action' => array(
3830        'type' => 'node',
3831        'label' => t('Save content'),
3832        'configurable' => FALSE,
3833        'triggers' => array('comment_insert', 'comment_update', 'comment_delete'),
3834      ),
3835      'node_unpublish_by_keyword_action' => array(
3836        'type' => 'node',
3837        'label' => t('Unpublish content containing keyword(s)'),
3838        'configurable' => TRUE,
3839        'triggers' => array('node_presave', 'node_insert', 'node_update'),
3840      ),
3841    );
3842  }
3843  
3844  /**
3845   * Sets the status of a node to 1 (published).
3846   *
3847   * @param $node
3848   *   A node object.
3849   * @param $context
3850   *   (optional) Array of additional information about what triggered the action.
3851   *   Not used for this action.
3852   *
3853   * @ingroup actions
3854   */
3855  function node_publish_action($node, $context = array()) {
3856    $node->status = NODE_PUBLISHED;
3857    watchdog('action', 'Set @type %title to published.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3858  }
3859  
3860  /**
3861   * Sets the status of a node to 0 (unpublished).
3862   *
3863   * @param $node
3864   *   A node object.
3865   * @param $context
3866   *   (optional) Array of additional information about what triggered the action.
3867   *   Not used for this action.
3868   *
3869   * @ingroup actions
3870   */
3871  function node_unpublish_action($node, $context = array()) {
3872    $node->status = NODE_NOT_PUBLISHED;
3873    watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3874  }
3875  
3876  /**
3877   * Sets the sticky-at-top-of-list property of a node to 1.
3878   *
3879   * @param $node
3880   *   A node object.
3881   * @param $context
3882   *   (optional) Array of additional information about what triggered the action.
3883   *   Not used for this action.
3884   *
3885   * @ingroup actions
3886   */
3887  function node_make_sticky_action($node, $context = array()) {
3888    $node->sticky = NODE_STICKY;
3889    watchdog('action', 'Set @type %title to sticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3890  }
3891  
3892  /**
3893   * Sets the sticky-at-top-of-list property of a node to 0.
3894   *
3895   * @param $node
3896   *   A node object.
3897   * @param $context
3898   *   (optional) Array of additional information about what triggered the action.
3899   *   Not used for this action.
3900   *
3901   * @ingroup actions
3902   */
3903  function node_make_unsticky_action($node, $context = array()) {
3904    $node->sticky = NODE_NOT_STICKY;
3905    watchdog('action', 'Set @type %title to unsticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3906  }
3907  
3908  /**
3909   * Sets the promote property of a node to 1.
3910   *
3911   * @param $node
3912   *   A node object.
3913   * @param $context
3914   *   (optional) Array of additional information about what triggered the action.
3915   *   Not used for this action.
3916   *
3917   * @ingroup actions
3918   */
3919  function node_promote_action($node, $context = array()) {
3920    $node->promote = NODE_PROMOTED;
3921    watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3922  }
3923  
3924  /**
3925   * Sets the promote property of a node to 0.
3926   *
3927   * @param $node
3928   *   A node object.
3929   * @param $context
3930   *   (optional) Array of additional information about what triggered the action.
3931   *   Not used for this action.
3932   *
3933   * @ingroup actions
3934   */
3935  function node_unpromote_action($node, $context = array()) {
3936    $node->promote = NODE_NOT_PROMOTED;
3937    watchdog('action', 'Removed @type %title from front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3938  }
3939  
3940  /**
3941   * Saves a node.
3942   *
3943   * @param $node
3944   *   The node to be saved.
3945   *
3946   * @ingroup actions
3947   */
3948  function node_save_action($node) {
3949    node_save($node);
3950    watchdog('action', 'Saved @type %title', array('@type' => node_type_get_name($node), '%title' => $node->title));
3951  }
3952  
3953  /**
3954   * Assigns ownership of a node to a user.
3955   *
3956   * @param $node
3957   *   A node object to modify.
3958   * @param $context
3959   *   Array with the following elements:
3960   *   - 'owner_uid': User ID to assign to the node.
3961   *
3962   * @see node_assign_owner_action_form()
3963   * @see node_assign_owner_action_validate()
3964   * @see node_assign_owner_action_submit()
3965   * @ingroup actions
3966   */
3967  function node_assign_owner_action($node, $context) {
3968    $node->uid = $context['owner_uid'];
3969    $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
3970    watchdog('action', 'Changed owner of @type %title to uid %name.', array('@type' =>  node_type_get_name($node), '%title' => $node->title, '%name' => $owner_name));
3971  }
3972  
3973  /**
3974   * Generates the settings form for node_assign_owner_action().
3975   *
3976   * @param $context
3977   *   Array of additional information about what triggered the action. Includes
3978   *   the following elements:
3979   *   - 'owner_uid': User ID to assign to the node.
3980   *
3981   * @see node_assign_owner_action_submit()
3982   * @see node_assign_owner_action_validate()
3983   *
3984   * @ingroup forms
3985   */
3986  function node_assign_owner_action_form($context) {
3987    $description = t('The username of the user to which you would like to assign ownership.');
3988    $count = db_query("SELECT COUNT(*) FROM {users}")->fetchField();
3989    $owner_name = '';
3990    if (isset($context['owner_uid'])) {
3991      $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
3992    }
3993  
3994    // Use dropdown for fewer than 200 users; textbox for more than that.
3995    if (intval($count) < 200) {
3996      $options = array();
3997      $result = db_query("SELECT uid, name FROM {users} WHERE uid > 0 ORDER BY name");
3998      foreach ($result as $data) {
3999        $options[$data->name] = $data->name;
4000      }
4001      $form['owner_name'] = array(
4002        '#type' => 'select',
4003        '#title' => t('Username'),
4004        '#default_value' => $owner_name,
4005        '#options' => $options,
4006        '#description' => $description,
4007      );
4008    }
4009    else {
4010      $form['owner_name'] = array(
4011        '#type' => 'textfield',
4012        '#title' => t('Username'),
4013        '#default_value' => $owner_name,
4014        '#autocomplete_path' => 'user/autocomplete',
4015        '#size' => '6',
4016        '#maxlength' => '60',
4017        '#description' => $description,
4018      );
4019    }
4020    return $form;
4021  }
4022  
4023  /**
4024   * Validates settings form for node_assign_owner_action().
4025   *
4026   * @see node_assign_owner_action_submit()
4027   */
4028  function node_assign_owner_action_validate($form, $form_state) {
4029    $exists = (bool) db_query_range('SELECT 1 FROM {users} WHERE name = :name', 0, 1, array(':name' => $form_state['values']['owner_name']))->fetchField();
4030    if (!$exists) {
4031      form_set_error('owner_name', t('Enter a valid username.'));
4032    }
4033  }
4034  
4035  /**
4036   * Saves settings form for node_assign_owner_action().
4037   *
4038   * @see node_assign_owner_action_validate()
4039   */
4040  function node_assign_owner_action_submit($form, $form_state) {
4041    // Username can change, so we need to store the ID, not the username.
4042    $uid = db_query('SELECT uid from {users} WHERE name = :name', array(':name' => $form_state['values']['owner_name']))->fetchField();
4043    return array('owner_uid' => $uid);
4044  }
4045  
4046  /**
4047   * Generates settings form for node_unpublish_by_keyword_action().
4048   *
4049   * @param array $context
4050   *   Array of additional information about what triggered this action.
4051   *
4052   * @return array
4053   *   A form array.
4054   *
4055   * @see node_unpublish_by_keyword_action_submit()
4056   */
4057  function node_unpublish_by_keyword_action_form($context) {
4058    $form['keywords'] = array(
4059      '#title' => t('Keywords'),
4060      '#type' => 'textarea',
4061      '#description' => t('The content 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."'),
4062      '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
4063    );
4064    return $form;
4065  }
4066  
4067  /**
4068   * Saves settings form for node_unpublish_by_keyword_action().
4069   */
4070  function node_unpublish_by_keyword_action_submit($form, $form_state) {
4071    return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
4072  }
4073  
4074  /**
4075   * Unpublishes a node containing certain keywords.
4076   *
4077   * @param $node
4078   *   A node object to modify.
4079   * @param $context
4080   *   Array with the following elements:
4081   *   - 'keywords': Array of keywords. If any keyword is present in the rendered
4082   *     node, the node's status flag is set to unpublished.
4083   *
4084   * @ingroup actions
4085   */
4086  function node_unpublish_by_keyword_action($node, $context) {
4087    foreach ($context['keywords'] as $keyword) {
4088      $elements = node_view(clone $node);
4089      if (strpos(drupal_render($elements), $keyword) !== FALSE || strpos($node->title, $keyword) !== FALSE) {
4090        $node->status = NODE_NOT_PUBLISHED;
4091        watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
4092        break;
4093      }
4094    }
4095  }
4096  
4097  /**
4098   * Implements hook_requirements().
4099   */
4100  function node_requirements($phase) {
4101    $requirements = array();
4102    if ($phase === 'runtime') {
4103      // Only show rebuild button if there are either 0, or 2 or more, rows
4104      // in the {node_access} table, or if there are modules that
4105      // implement hook_node_grants().
4106      $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField();
4107      if ($grant_count != 1 || count(module_implements('node_grants')) > 0) {
4108        $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count));
4109      }
4110      else {
4111        $value = t('Disabled');
4112      }
4113      $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.');
4114  
4115      $requirements['node_access'] = array(
4116        'title' => t('Node Access Permissions'),
4117        'value' => $value,
4118        'description' => $description . ' ' . l(t('Rebuild permissions'), 'admin/reports/status/rebuild'),
4119      );
4120    }
4121    return $requirements;
4122  }
4123  
4124  /**
4125   * Implements hook_modules_enabled().
4126   */
4127  function node_modules_enabled($modules) {
4128    // Check if any of the newly enabled modules require the node_access table to
4129    // be rebuilt.
4130    if (!node_access_needs_rebuild() && array_intersect($modules, module_implements('node_grants'))) {
4131      node_access_needs_rebuild(TRUE);
4132    }
4133  }
4134  
4135  /**
4136   * Controller class for nodes.
4137   *
4138   * This extends the DrupalDefaultEntityController class, adding required
4139   * special handling for node objects.
4140   */
4141  class NodeController extends DrupalDefaultEntityController {
4142  
4143    protected function attachLoad(&$nodes, $revision_id = FALSE) {
4144      // Create an array of nodes for each content type and pass this to the
4145      // object type specific callback.
4146      $typed_nodes = array();
4147      foreach ($nodes as $id => $entity) {
4148        $typed_nodes[$entity->type][$id] = $entity;
4149      }
4150  
4151      // Call object type specific callbacks on each typed array of nodes.
4152      foreach ($typed_nodes as $node_type => $nodes_of_type) {
4153        if (node_hook($node_type, 'load')) {
4154          $function = node_type_get_base($node_type) . '_load';
4155          $function($nodes_of_type);
4156        }
4157      }
4158      // Besides the list of nodes, pass one additional argument to
4159      // hook_node_load(), containing a list of node types that were loaded.
4160      $argument = array_keys($typed_nodes);
4161      $this->hookLoadArguments = array($argument);
4162      parent::attachLoad($nodes, $revision_id);
4163    }
4164  
4165    protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
4166      // Ensure that uid is taken from the {node} table,
4167      // alias timestamp to revision_timestamp and add revision_uid.
4168      $query = parent::buildQuery($ids, $conditions, $revision_id);
4169      $fields =& $query->getFields();
4170      unset($fields['timestamp']);
4171      $query->addField('revision', 'timestamp', 'revision_timestamp');
4172      $fields['uid']['table'] = 'base';
4173      $query->addField('revision', 'uid', 'revision_uid');
4174      return $query;
4175    }
4176  }
4177  
4178  /**
4179   * Implements hook_file_download_access().
4180   */
4181  function node_file_download_access($field, $entity_type, $entity) {
4182    if ($entity_type == 'node') {
4183      return node_access('view', $entity);
4184    }
4185  }

title

Description

title

Description

title

Description

title

title

Body