node.module 101 KB
Newer Older
Dries's avatar
 
Dries committed
1
<?php
2
// $Id$
Dries's avatar
 
Dries committed
3

Dries's avatar
 
Dries committed
4 5
/**
 * @file
6 7
 * The core that allows content to be submitted to the site. Modules and
 * scripts may programmatically submit nodes using the usual form API pattern.
Dries's avatar
 
Dries committed
8 9
 */

10 11 12 13 14 15
/**
 * Nodes changed before this time are always marked as read.
 *
 * Nodes changed after this time may be marked new, updated, or read, depending
 * on their state for the current user. Defaults to 30 days ago.
 */
16
define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
17

Dries's avatar
 
Dries committed
18
/**
19
 * Implement hook_help().
Dries's avatar
 
Dries committed
20
 */
21
function node_help($path, $arg) {
22 23 24
  // Remind site administrators about the {node_access} table being flagged
  // for rebuild. We don't need to issue the message on the confirm form, or
  // while the rebuild is being processed.
25
  if ($path != 'admin/reports/status/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
26
      && user_access('access administration pages') && node_access_needs_rebuild()) {
27
    if ($path == 'admin/reports/status') {
28 29 30
      $message = t('The content access permissions need to be rebuilt.');
    }
    else {
31
      $message = t('The content access permissions need to be rebuilt. Please visit <a href="@node_access_rebuild">this page</a>.', array('@node_access_rebuild' => url('admin/reports/status/rebuild')));
32 33 34 35
    }
    drupal_set_message($message, 'error');
  }

36
  switch ($path) {
Dries's avatar
 
Dries committed
37
    case 'admin/help#node':
38 39
      $output = '<p>' . t('The node module manages content on your site, and stores all posts (regardless of type) as a "node" . In addition to basic publishing settings, including whether the post has been published, promoted to the site front page, or should remain present (or sticky) at the top of lists, the node module also records basic information about the author of a post. Optional revision control over edits is available. For additional functionality, the node module is often extended by other modules.') . '</p>';
      $output .= '<p>' . t('Though each post on your site is a node, each post is also of a particular <a href="@content-type">content type</a>. <a href="@content-type">Content types</a> are used to define the characteristics of a post, including the title and description of the fields displayed on its add and edit pages. Each content type may have different default settings for <em>Publishing options</em> and other workflow controls. By default, the two content types in a standard Drupal installation are <em>Page</em> and <em>Story</em>. Use the <a href="@content-type">content types page</a> to add new or edit existing content types. Additional content types also become available as you enable additional core, contributed and custom modules.', array('@content-type' => url('admin/build/types'))) . '</p>';
40
      $output .= '<p>' . t('The administrative <a href="@content">content page</a> allows you to review and manage your site content. The node module makes a number of permissions available for each content type, which may be set by role on the <a href="@permissions">permissions page</a>.', array('@content' => url('admin/content/node'), '@permissions' => url('admin/user/permissions'))) . '</p>';
41
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@node">Node module</a>.', array('@node' => 'http://drupal.org/handbook/modules/node/')) . '</p>';
Dries's avatar
 
Dries committed
42
      return $output;
43 44
    case 'admin/content/node':
      return ' '; // Return a non-null value so that the 'more help' link is shown.
45
    case 'admin/build/types/add':
46
      return '<p>' . t('To create a new content type, enter the human-readable name, the machine-readable name, and all other relevant fields that are on this page. Once created, users of your site will be able to create posts that are instances of this content type.') . '</p>';
47
    case 'node/%/revisions':
48
      return '<p>' . t('The revisions let you track differences between multiple versions of a post.') . '</p>';
49 50
    case 'node/%/edit':
      $node = node_load($arg[1]);
51
      $type = node_type_get_type($node);
52
      return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
Dries's avatar
 
Dries committed
53
  }
Dries's avatar
 
Dries committed
54

55
  if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
56
    $type = node_type_get_type(str_replace('-', '_', $arg[2]));
57
    return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
58
  }
Dries's avatar
 
Dries committed
59 60
}

61
/**
62
 * Implement hook_theme().
63 64 65
 */
function node_theme() {
  return array(
66
    'node' => array(
67
      'arguments' => array('elements' => NULL),
68
      'template' => 'node',
69
    ),
70 71 72 73 74 75 76 77
    'node_list' => array(
      'arguments' => array('items' => NULL, 'title' => NULL),
    ),
    'node_search_admin' => array(
      'arguments' => array('form' => NULL),
    ),
    'node_filter_form' => array(
      'arguments' => array('form' => NULL),
78
      'file' => 'node.admin.inc',
79 80 81
    ),
    'node_filters' => array(
      'arguments' => array('form' => NULL),
82
      'file' => 'node.admin.inc',
83 84 85
    ),
    'node_admin_nodes' => array(
      'arguments' => array('form' => NULL),
86
      'file' => 'node.admin.inc',
87 88 89
    ),
    'node_add_list' => array(
      'arguments' => array('content' => NULL),
90
      'file' => 'node.pages.inc',
91 92 93
    ),
    'node_form' => array(
      'arguments' => array('form' => NULL),
94
      'file' => 'node.pages.inc',
95 96 97
    ),
    'node_preview' => array(
      'arguments' => array('node' => NULL),
98
      'file' => 'node.pages.inc',
99 100 101 102
    ),
    'node_log_message' => array(
      'arguments' => array('log' => NULL),
    ),
103 104 105
    'node_submitted' => array(
      'arguments' => array('node' => NULL),
    ),
106 107 108
    'node_admin_overview' => array(
      'arguments' => array('name' => NULL, 'type' => NULL),
    ),
109 110 111
    'node_links' => array(
      'arguments' => array('element' => NULL),
    ),
112 113 114
  );
}

Dries's avatar
 
Dries committed
115
/**
116
 * Implement hook_cron().
Dries's avatar
 
Dries committed
117
 */
118
function node_cron() {
119 120 121
  db_delete('history')
    ->condition('timestamp', NODE_NEW_LIMIT, '<')
    ->execute();
122 123
}

Dries's avatar
 
Dries committed
124
/**
125
 * Implement hook_fieldable_info().
Dries's avatar
 
Dries committed
126 127 128 129 130 131 132 133 134 135 136 137
 */
function node_fieldable_info() {
  $return = array(
    'node' => array(
      'name' => t('Node'),
      'id key' => 'nid',
      'revision key' => 'vid',
      'bundle key' => 'type',
      // Node.module handles its own caching.
      // 'cacheable' => FALSE,
      // Bundles must provide human readable name so
      // we can create help and error messages about them.
138
      'bundles' => node_type_get_names(),
Dries's avatar
 
Dries committed
139 140 141 142 143 144 145
    ),
  );
  return $return;
}


/**
146
 * Implement hook_field_build_modes().
Dries's avatar
 
Dries committed
147 148 149 150 151 152 153
 */
function node_field_build_modes($obj_type) {
  $modes = array();
  if ($obj_type == 'node') {
    $modes = array(
      'teaser' => t('Teaser'),
      'full' => t('Full node'),
154
      'rss' => t('RSS'),
Dries's avatar
 
Dries committed
155
    );
156 157
    // Search integration is provided by node.module, so search-related
    // build-modes for nodes are defined here and not in search.module.
Dries's avatar
 
Dries committed
158 159
    if (module_exists('search')) {
      $modes += array(
160 161
        'search_index' => t('Search Index'),
        'search_result' => t('Search Result'),
Dries's avatar
 
Dries committed
162 163 164 165 166 167
      );
    }
  }
  return $modes;
}

Dries's avatar
 
Dries committed
168 169 170 171
/**
 * Gather a listing of links to nodes.
 *
 * @param $result
172 173 174 175
 *   A DB result object from a query to fetch node objects. If your query
 *   joins the <code>node_comment_statistics</code> table so that the
 *   <code>comment_count</code> field is available, a title attribute will
 *   be added to show the number of comments.
Dries's avatar
 
Dries committed
176 177 178 179
 * @param $title
 *   A heading for the resulting list.
 *
 * @return
180 181
 *   An HTML list suitable as content for a block, or FALSE if no result can
 *   fetch from DB result object.
Dries's avatar
 
Dries committed
182
 */
Dries's avatar
 
Dries committed
183
function node_title_list($result, $title = NULL) {
184
  $items = array();
185
  $num_rows = FALSE;
186
  foreach ($result as $node) {
187
    $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());
188
    $num_rows = TRUE;
Dries's avatar
 
Dries committed
189 190
  }

191
  return $num_rows ? theme('node_list', $items, $title) : FALSE;
Dries's avatar
 
Dries committed
192 193
}

Dries's avatar
 
Dries committed
194 195
/**
 * Format a listing of links to nodes.
196 197
 *
 * @ingroup themeable
Dries's avatar
 
Dries committed
198
 */
Dries's avatar
 
Dries committed
199
function theme_node_list($items, $title = NULL) {
Dries's avatar
 
Dries committed
200
  return theme('item_list', $items, $title);
Dries's avatar
 
Dries committed
201 202
}

Dries's avatar
 
Dries committed
203 204 205
/**
 * Update the 'last viewed' timestamp of the specified node for current user.
 */
Dries's avatar
 
Dries committed
206 207 208 209
function node_tag_new($nid) {
  global $user;

  if ($user->uid) {
210 211 212 213 214 215 216
    db_merge('history')
      ->key(array(
        'uid' => $user->uid,
        'nid' => $nid,
      ))
      ->fields(array('timestamp' => REQUEST_TIME))
      ->execute();
Dries's avatar
 
Dries committed
217 218 219
  }
}

Dries's avatar
 
Dries committed
220 221 222 223
/**
 * Retrieves the timestamp at which the current user last viewed the
 * specified node.
 */
Dries's avatar
 
Dries committed
224 225
function node_last_viewed($nid) {
  global $user;
Dries's avatar
 
Dries committed
226
  static $history;
Dries's avatar
 
Dries committed
227

Dries's avatar
 
Dries committed
228
  if (!isset($history[$nid])) {
229
    $history[$nid] = db_query("SELECT timestamp FROM {history} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $nid))->fetchObject();
Dries's avatar
 
Dries committed
230 231
  }

232
  return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
Dries's avatar
 
Dries committed
233 234 235
}

/**
236
 * Decide on the type of marker to be displayed for a given node.
Dries's avatar
 
Dries committed
237
 *
Dries's avatar
 
Dries committed
238 239 240 241
 * @param $nid
 *   Node ID whose history supplies the "last viewed" timestamp.
 * @param $timestamp
 *   Time which is compared against node's "last viewed" timestamp.
242 243
 * @return
 *   One of the MARK constants.
Dries's avatar
 
Dries committed
244
 */
245
function node_mark($nid, $timestamp) {
Dries's avatar
 
Dries committed
246 247 248
  global $user;
  static $cache;

249 250 251
  if (!$user->uid) {
    return MARK_READ;
  }
Dries's avatar
Dries committed
252
  if (!isset($cache[$nid])) {
253
    $cache[$nid] = node_last_viewed($nid);
Dries's avatar
 
Dries committed
254
  }
255 256 257 258 259 260 261
  if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
    return MARK_NEW;
  }
  elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
    return MARK_UPDATED;
  }
  return MARK_READ;
Dries's avatar
 
Dries committed
262 263
}

264
/**
265
 * Extract the type name.
266 267
 *
 * @param $node
268
 *   Either a string or object, containing the node type information.
269 270
 *
 * @return
271
 *   Node type of the passed in data.
272
 */
273 274 275
function _node_extract_type($node) {
  return is_object($node) ? $node->type : $node;
}
276

277 278 279 280 281 282
/**
 * Clear the statically cached node type information.
 */
function node_type_clear() {
  drupal_static_reset('_node_types_build');
}
283

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
/**
 * Returns a list of all the available node types.
 *
 * @return
 *   An array of node types, keyed by the type.
 * @see node_type_get_type()
 */
function node_type_get_types() {
  return _node_types_build()->types;
}

/**
 * Returns the node type of the passed node or node type string.
 *
 *@param $node
 *   A node object or string that indicates the node type to return.
 * @return
 *   A single node type, as an object or FALSE if the node type is not found.
 *   The node type is an array with following content:
 *
 *   @code
 *   array(
 *     'type' => 'Machine readable type name',
 *     'name' => 'Name of the node type',
 *     'base' => 'Indicates to which module this node type belongs',
 *     'description' => 'Description of the node type',
 *     // ...
 *   )
 *   @endcode
 */
function node_type_get_type($node) {
  $type = _node_extract_type($node);
  $types = _node_types_build()->types;
  return isset($types[$type]) ? $types[$type] : FALSE;
}

/**
 * Returns the node type base of the passed node or node type string.
 *
 * The base indicates which module implement this node type and is used to
 * execute node type specific hooks.
 *
 * @see node_invoke()
 *
 * @param $node
 *   A node object or string that indicates the node type to return.
 * @return
 *   The node type base or FALSE if the node type is not found.
 */
function node_type_get_base($node) {
  $type = _node_extract_type($node);
  $types = _node_types_build()->types;
  return isset($types[$type]) && isset($types[$type]->base) ? $types[$type]->base : FALSE;
}

/**
 * Returns a list of available node names.
 *
 * @return
 *   An array of node type names, keyed by the type.
 */
function node_type_get_names() {
  return _node_types_build()->names;
}

/**
 * Returns the node type name of the passed node or node type string.
 *
 * @param $node
 *   A node object or string that indicates the node type to return.
 *
 * @return
 *   The node type name or FALSE if the node type is not found.
 */
function node_type_get_name($node) {
  $type = _node_extract_type($node);
  $types = _node_types_build()->names;
  return isset($types[$type]) ? $types[$type] : FALSE;
362 363 364 365 366 367 368
}

/**
 * Resets the database cache of node types, and saves all new or non-modified
 * module-defined node types to the database.
 */
function node_types_rebuild() {
369 370 371
  // Reset and load updated node types.
  node_type_clear();
  foreach (node_type_get_types() as $type => $info) {
372 373 374
    if (!empty($info->is_new)) {
      node_type_save($info);
    }
375 376 377
    if (!empty($info->disabled)) {
      node_type_delete($info->type);
    }
378
  }
379 380 381
  // Reset cached node type information so that the next access
  // will use the updated data.
  node_type_clear();
382 383
  // This is required for proper menu items at node/add/type.
  menu_rebuild();
384 385
}

386
/**
387 388 389 390
 * Saves a node type to the database.
 *
 * @param $info
 *   The node type to save, as an object.
Dries's avatar
 
Dries committed
391 392
 *
 * @return
393
 *   Status flag indicating outcome of the operation.
Dries's avatar
 
Dries committed
394
 */
395 396 397
function node_type_save($info) {
  $is_existing = FALSE;
  $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
398
  $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', array(':type' => $existing_type), 0, 1)->fetchField();
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
  $type = node_type_set_defaults($info);

  $fields = array(
    'type' => (string) $type->type,
    'name' => (string) $type->name,
    'base' => (string) $type->base,
    'has_title' => (int) $type->has_title,
    'title_label' => (string) $type->title_label,
    'has_body' => (int) $type->has_body,
    'body_label' => (string) $type->body_label,
    'description' => (string) $type->description,
    'help' => (string) $type->help,
    'min_word_count' => (int) $type->min_word_count,
    'custom' => (int) $type->custom,
    'modified' => (int) $type->modified,
    'locked' => (int) $type->locked,
  );
416 417

  if ($is_existing) {
418 419 420 421
    db_update('node_type')
      ->fields($fields)
      ->condition('type', $existing_type)
      ->execute();
422

Dries's avatar
 
Dries committed
423 424 425
    if (!empty($type->old_type) && $type->old_type != $type->type) {
      field_attach_rename_bundle($type->old_type, $type->type);
    }
426
    node_configure_fields($type);
427
    module_invoke_all('node_type', 'update', $type);
428 429 430
    return SAVED_UPDATED;
  }
  else {
431
    $fields['orig_type'] = (string) $type->orig_type;
432 433 434
    db_insert('node_type')
      ->fields($fields)
      ->execute();
435

Dries's avatar
 
Dries committed
436
    field_attach_create_bundle($type->type);
437
    node_configure_fields($type);
438
    module_invoke_all('node_type', 'insert', $type);
439 440
    return SAVED_NEW;
  }
441
}
442

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
/**
 * Manage the field(s) for a node type.
 *
 * Currently, the node module manages a single Field API field,
 * 'body'.  If $type->has_body is true, this function ensures the
 * 'body' field exists and creates an instance of it for the bundle
 * $type->type (e.g. 'page', 'story', ...).  If $type->has_body is
 * false, this function removes the instance (if it exists) for the
 * 'body' field on $type->type.
 */
function node_configure_fields($type) {
   // Add or remove the body field, as needed.
  $field = field_info_field('body');
  $instance = field_info_instance('body', $type->type);
  if ($type->has_body) {
    if (empty($field)) {
      $field = array(
        'field_name' => 'body',
        'type' => 'text_with_summary',
      );
      $field = field_create_field($field);
    }
    if (empty($instance)) {
      $instance = array(
        'field_name' => 'body',
        'bundle' => $type->type,
        'label' => $type->body_label,
        'widget_type' => 'text_textarea_with_summary',
        'settings' => array('display_summary' => TRUE),

        // With no UI in core, we have to define default
        // formatters for the teaser and full view.
        // This may change if the method of handling displays
        // is changed or if a UI gets into core.
        'display' => array(
          'full' => array(
            'label' => 'hidden',
            'type' => 'text_default',
481
          ),
482 483 484 485
          'teaser' => array(
            'label' => 'hidden',
            'type' => 'text_summary_or_trimmed',
          ),
486 487
        ),
      );
488 489 490 491 492 493 494 495 496 497 498 499 500 501
      field_create_instance($instance);
    }
    else {
      $instance['label'] = $type->body_label;
      $instance['settings']['display_summary'] = TRUE;
      field_update_instance($instance);
    }
  }
  elseif (!empty($instance)) {
    field_delete_instance($instance);
  }

}

502 503 504 505 506 507 508
/**
 * Deletes a node type from the database.
 *
 * @param $type
 *   The machine-readable name of the node type to be deleted.
 */
function node_type_delete($type) {
509
  $info = node_type_get_type($type);
510 511 512
  db_delete('node_type')
    ->condition('type', $type)
    ->execute();
513 514 515
  module_invoke_all('node_type', 'delete', $info);
}

516
/**
517 518
 * Updates all nodes of one type to be of another type.
 *
519
 * @param $old_type
520 521 522
 *   The current node type of the nodes.
 * @param $type
 *   The new node type of the nodes.
523 524
 *
 * @return
525
 *   The number of nodes whose node type field was modified.
526
 */
527
function node_type_update_nodes($old_type, $type) {
528 529 530 531
  db_update('node')
    ->fields(array('type' => $type))
    ->condition('type', $old_type)
    ->execute();
532
  return db_affected_rows();
Dries's avatar
 
Dries committed
533
}
Dries's avatar
 
Dries committed
534

535
/**
536 537 538 539
 * Builds and returns the list of available node types.
 *
 * The list of types is built by querying hook_node_info() in all modules, and
 * by comparing this information with the node types in the {node_type} table.
Dries's avatar
 
Dries committed
540 541
 *
 */
542
function _node_types_build() {
543
  $_node_types = &drupal_static(__FUNCTION__);
544 545 546 547
  if (is_object($_node_types)) {
    return $_node_types;
  }
  $_node_types = (object) array('types' => array(), 'names' => array());
548 549 550 551

  $info_array = module_invoke_all('node_info');
  foreach ($info_array as $type => $info) {
    $info['type'] = $type;
552 553
    $_node_types->types[$type] = node_type_set_defaults($info);
    $_node_types->names[$type] = $info['name'];
554
  }
555 556 557 558 559 560
  $type_result = db_select('node_type', 'nt')
    ->fields('nt')
    ->orderBy('nt.type', 'ASC')
    ->addTag('node_type_access')
    ->execute();
  foreach ($type_result as $type_object) {
561 562
    // Check for node types from disabled modules and mark their types for removal.
    // Types defined by the node module in the database (rather than by a separate
563 564 565
    // module using hook_node_info) have a base value of 'node_content'. The isset()
    // check prevents errors on old (pre-Drupal 7) databases.
    if (isset($type_object->base) && $type_object->base != 'node_content' && empty($info_array[$type_object->type])) {
566
      $type_object->disabled = TRUE;
567
    }
568 569 570
    if (!isset($_node_types->types[$type_object->type]) || $type_object->modified) {
      $_node_types->types[$type_object->type] = $type_object;
      $_node_types->names[$type_object->type] = $type_object->name;
571 572

      if ($type_object->type != $type_object->orig_type) {
573 574
        unset($_node_types->types[$type_object->orig_type]);
        unset($_node_types->names[$type_object->orig_type]);
575 576 577 578
      }
    }
  }

579
  asort($_node_types->names);
580

581
  return $_node_types;
582 583 584
}

/**
585 586 587 588 589 590 591 592 593 594 595
 * Set the default values for a node type.
 *
 * The defaults are for a type defined through hook_node_info().
 * When populating a custom node type $info should have the 'custom'
 * key set to 1.
 *
 * @param $info
 *   An object or array containing values to override the defaults.
 *
 * @return
 *  A node type object.
596
 */
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
function node_type_set_defaults($info = array()) {
  static $type;

  if (!isset($type)) {
    $type = new stdClass();
    $type->type = '';
    $type->name = '';
    $type->base = '';
    $type->description = '';
    $type->help = '';
    $type->min_word_count = 0;
    $type->has_title = 1;
    $type->has_body = 1;
    $type->title_label = t('Title');
    $type->body_label = t('Body');
    $type->custom = 0;
    $type->modified = 0;
    $type->locked = 1;
    $type->is_new = 1;
  }

  $new_type = clone $type;
  $info = (array) $info;
  foreach ($info as $key => $data) {
    $new_type->$key = $data;
  }
  // If the type has no title or body, set an empty label.
  if (!$new_type->has_title) {
    $new_type->title_label = '';
  }
  if (!$new_type->has_body) {
    $new_type->body_label = '';
  }
  $new_type->orig_type = isset($info['type']) ? $info['type'] : '';

  return $new_type;
Dries's avatar
 
Dries committed
633
}
Dries's avatar
 
Dries committed
634

635
/**
Dries's avatar
 
Dries committed
636 637
 * Determine whether a node hook exists.
 *
638
 * @param $node
Dries's avatar
 
Dries committed
639 640 641 642
 *   Either a node object, node array, or a string containing the node type.
 * @param $hook
 *   A string containing the name of the hook.
 * @return
643
 *   TRUE if the $hook exists in the node type of $node.
Dries's avatar
 
Dries committed
644
 */
645
function node_hook($node, $hook) {
646
  $base = node_type_get_base($node);
647
  return module_hook($base, $hook);
Dries's avatar
 
Dries committed
648 649
}

650
/**
Dries's avatar
 
Dries committed
651 652
 * Invoke a node hook.
 *
653
 * @param $node
Dries's avatar
 
Dries committed
654 655 656 657 658 659
 *   Either a node object, node array, or a string containing the node type.
 * @param $hook
 *   A string containing the name of the hook.
 * @param $a2, $a3, $a4
 *   Arguments to pass on to the hook, after the $node argument.
 * @return
Dries's avatar
 
Dries committed
660
 *   The returned value of the invoked hook.
Dries's avatar
 
Dries committed
661
 */
662
function node_invoke($node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
663
  if (node_hook($node, $hook)) {
664
    $base = node_type_get_base($node);
665
    $function = $base . '_' . $hook;
Dries's avatar
 
Dries committed
666
    return ($function($node, $a2, $a3, $a4));
Dries's avatar
 
Dries committed
667 668 669
  }
}

Dries's avatar
 
Dries committed
670
/**
671 672 673 674 675
 * Load node objects from the database.
 *
 * This function should be used whenever you need to load more than one node
 * from the database. Nodes are loaded into memory and will not require
 * database access if loaded again during the same page request.
Dries's avatar
 
Dries committed
676
 *
677 678 679 680
 * @param $nids
 *   An array of node IDs.
 * @param $conditions
 *   An array of conditions on the {node} table in the form 'field' => $value.
Dries's avatar
 
Dries committed
681 682
 * @param $reset
 *   Whether to reset the internal node_load cache.
Dries's avatar
 
Dries committed
683 684
 *
 * @return
685
 *   An array of node objects indexed by nid.
Dries's avatar
 
Dries committed
686
 */
687
function node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE) {
688 689
  $node_cache = &drupal_static(__FUNCTION__, array());

Dries's avatar
 
Dries committed
690
  if ($reset) {
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    $node_cache = array();
  }
  $nodes = array();

  // Create a new variable which is either a prepared version of the $nids
  // array for later comparison with the node cache, or FALSE if no $nids were
  // passed. The $nids array is reduced as items are loaded from cache, and we
  // need to know if it's empty for this reason to avoid querying the database
  // when all requested nodes are loaded from cache.
  $passed_nids = !empty($nids) ? array_flip($nids) : FALSE;

  // Revisions are not statically cached, and require a different query to
  // other conditions, so separate vid into its own variable.
  $vid = isset($conditions['vid']) ? $conditions['vid'] : FALSE;
  unset($conditions['vid']);

  // Load any available nodes from the internal cache.
  if ($node_cache && !$vid) {
    if ($nids) {
      $nodes += array_intersect_key($node_cache, $passed_nids);
      // If any nodes were loaded, remove them from the $nids still to load.
      $nids = array_keys(array_diff_key($passed_nids, $nodes));
    }
    // If loading nodes only by conditions, fetch all available nodes from
    // the cache. Nodes which don't match are removed later.
    elseif ($conditions) {
      $nodes = $node_cache;
    }
Dries's avatar
 
Dries committed
719 720
  }

721
  // Exclude any nodes loaded from cache if they don't match $conditions.
722
  // This ensures the same behavior whether loading from memory or database.
723 724 725 726 727
  if ($conditions) {
    foreach ($nodes as $node) {
      $node_values = (array) $node;
      if (array_diff_assoc($conditions, $node_values)) {
        unset($nodes[$node->nid]);
728
      }
729
    }
Dries's avatar
 
Dries committed
730 731
  }

732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
  // Load any remaining nodes from the database. This is the case if there are
  // any $nids left to load, if loading a revision, or if $conditions was
  // passed without $nids.
  if ($nids || $vid || ($conditions && !$passed_nids)) {
    $query = db_select('node', 'n');

    if ($vid) {
      $query->join('node_revision', 'r', 'r.nid = n.nid AND r.vid = :vid', array(':vid' => $vid));
    }
    else {
      $query->join('node_revision', 'r', 'r.vid = n.vid');
    }

    // Add fields from the {node} table.
    $node_fields = drupal_schema_fields_sql('node');

    // vid and title are provided by node_revision, so remove them.
    unset($node_fields['vid']);
    unset($node_fields['title']);
    $query->fields('n', $node_fields);

    // Add all fields from the {node_revision} table.
    $node_revision_fields = drupal_schema_fields_sql('node_revision');

    // nid is provided by node, so remove it.
    unset($node_revision_fields['nid']);

    // Change timestamp to revision_timestamp before adding it to the query.
    unset($node_revision_fields['timestamp']);
    $query->addField('r', 'timestamp', 'revision_timestamp');
    $query->fields('r', $node_revision_fields);

    if ($nids) {
      $query->condition('n.nid', $nids, 'IN');
    }
    if ($conditions) {
      foreach ($conditions as $field => $value) {
        $query->condition('n.' . $field, $value);
770
      }
Dries's avatar
 
Dries committed
771
    }
772 773 774 775
    $queried_nodes = $query->execute()->fetchAllAssoc('nid');
  }

  // Pass all nodes loaded from the database through the node type specific
776
  // callbacks and hook_node_load(), then add them to the internal cache.
777 778 779 780 781 782 783
  if (!empty($queried_nodes)) {
    // Create an array of nodes for each content type and pass this to the
    // node type specific callback.
    $typed_nodes = array();
    foreach ($queried_nodes as $nid => $node) {
      $typed_nodes[$node->type][$nid] = $node;
    }
Dries's avatar
 
Dries committed
784

785 786 787
    // Call node type specific callbacks on each typed array of nodes.
    foreach ($typed_nodes as $type => $nodes_of_type) {
      if (node_hook($type, 'load')) {
788
        $function = node_type_get_base($type) . '_load';
789
        $function($nodes_of_type);
790 791
      }
    }
792

Dries's avatar
 
Dries committed
793 794 795 796 797 798 799 800
    // Attach fields.
    if ($vid) {
      field_attach_load_revision('node', $queried_nodes);
    }
    else {
      field_attach_load('node', $queried_nodes);
    }

801
    // Call hook_node_load(), pass the node types so modules can return early
802
    // if not acting on types in the array.
803 804
    foreach (module_implements('node_load') as $module) {
      $function = $module . '_node_load';
805 806 807 808 809 810
      $function($queried_nodes, array_keys($typed_nodes));
    }
    $nodes += $queried_nodes;
    // Add nodes to the cache if we're not loading a revision.
    if (!$vid) {
      $node_cache += $queried_nodes;
811
    }
Dries's avatar
 
Dries committed
812 813
  }

814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
  // Ensure that the returned array is ordered the same as the original $nids
  // array if this was passed in and remove any invalid nids.
  if ($passed_nids) {
    // Remove any invalid nids from the array.
    $passed_nids = array_intersect_key($passed_nids, $nodes);
    foreach ($nodes as $node) {
      $passed_nids[$node->nid] = $node;
    }
    $nodes = $passed_nids;
  }

  return $nodes;
}

/**
 * Load a node object from the database.
 *
 * @param $nid
 *   The node ID.
 * @param $vid
 *   The revision ID.
 * @param $reset
836
 *   Whether to reset the node_load_multiple cache.
837 838 839 840 841 842 843 844 845
 *
 * @return
 *   A fully-populated node object.
 */
function node_load($nid, $vid = array(), $reset = FALSE) {
  $vid = isset($vid) ? array('vid' => $vid) : NULL;
  $node = node_load_multiple(array($nid), $vid, $reset);

  return $node ? $node[$nid] : FALSE;
Dries's avatar
 
Dries committed
846 847
}

848 849 850 851 852 853
/**
 * Perform validation checks on the given node.
 */
function node_validate($node, $form = array()) {
  // Convert the node to an object, if necessary.
  $node = (object)$node;
854
  $type = node_type_get_type($node);
855 856

  // Make sure the body has the minimum number of words.
857
  // TODO : use a better word counting algorithm that will work in other languages
858 859
  if (!empty($type->min_word_count) && isset($node->body[0]['value']) && count(explode(' ', $node->body[0]['value'])) < $type->min_word_count) {
    // TODO: Use Field API to set this error.
860 861 862 863
    form_set_error('body', t('The body of your @type is too short. You need at least %words words.', array('%words' => $type->min_word_count, '@type' => $type->name)));
  }

  if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
864
    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.'));
865 866 867 868
  }

  if (user_access('administer nodes')) {
    // Validate the "authored by" field.
869
    if (!empty($node->name) && !($account = user_load_by_name($node->name))) {
870 871 872 873 874 875
      // The use of empty() is mandatory in the context of usernames
      // as the empty string denotes the anonymous user. In case we
      // are dealing with an anonymous user we set the user ID to 0.
      form_set_error('name', t('The username %name does not exist.', array('%name' => $node->name)));
    }

876 877
    // Validate the "authored on" field.
    if (!empty($node->date) && strtotime($node->date) === FALSE) {
878 879 880 881 882 883
      form_set_error('date', t('You have to specify a valid date.'));
    }
  }

  // Do node-type-specific validation checks.
  node_invoke($node, 'validate', $form);
884
  module_invoke_all('node_validate', $node, $form);
885 886 887 888 889 890 891 892 893 894 895 896 897
}

/**
 * Prepare node for save and allow modules to make changes.
 */
function node_submit($node) {
  global $user;

  // Convert the node to an object, if necessary.
  $node = (object)$node;

  if (user_access('administer nodes')) {
    // Populate the "authored by" field.
898
    if ($account = user_load_by_name($node->name)) {
899 900 901 902 903 904
      $node->uid = $account->uid;
    }
    else {
      $node->uid = 0;
    }
  }
905
  $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME;
906 907 908 909 910
  $node->validated = TRUE;

  return $node;
}

Dries's avatar
 
Dries committed
911
/**
912 913 914 915 916
 * Save changes to a node or add a new node.
 *
 * @param $node
 *   The $node object to be saved. If $node->nid is
 *   omitted (or $node->is_new is TRUE), a new node will be added.
Dries's avatar
 
Dries committed
917
 */
918
function node_save($node) {
Dries's avatar
 
Dries committed
919
  field_attach_presave('node', $node);
920
  // Let modules modify the node before it is saved to the database.
921
  module_invoke_all('node_presave', $node);
922
  global $user;
Dries's avatar
 
Dries committed
923

924
  if (!isset($node->is_new)) {
925
    $node->is_new = empty($node->nid);
926
  }
Dries's avatar
 
Dries committed
927

Dries's avatar
 
Dries committed
928
  // Apply filters to some default node fields:
929
  if ($node->is_new) {
Dries's avatar
 
Dries committed
930
    // Insert a new node.
931
    $node->is_new = TRUE;
932 933

    // When inserting a node, $node->log must be set because
934
    // {node_revision}.log does not (and cannot) have a default
935
    // value. If the user does not have permission to create
936 937 938 939 940
    // revisions, however, the form will not contain an element for
    // log so $node->log will be unset at this point.
    if (!isset($node->log)) {
      $node->log = '';
    }
941
  }
942 943
  elseif (!empty($node->revision)) {
    $node->old_vid = $node->vid;
944
    unset($node->vid);
945
  }
946
  else {
947
    // When updating a node, avoid clobbering an existing log entry with an empty one.
948 949
    if (empty($node->log)) {
      unset($node->log);
950
    }
Dries's avatar
 
Dries committed
951 952
  }

953 954
  // Set some required fields:
  if (empty($node->created)) {
955
    $node->created = REQUEST_TIME;
956
  }
957
  // The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
958
  $node->changed = REQUEST_TIME;
Dries's avatar
 
Dries committed
959

960
  $node->timestamp = REQUEST_TIME;
961
  $update_node = TRUE;
962

963
  // Generate the node table query and the node_revisions table query.
964
  if ($node->is_new) {
965
    drupal_write_record('node', $node);
966
    _node_save_revision($node, $user->uid);
967
    $op = 'insert';
968 969
  }
  else {
970
    drupal_write_record('node', $node, 'nid');
971
    if (!empty($node->revision)) {
972
      _node_save_revision($node, $user->uid);
973 974
    }
    else {
975
      _node_save_revision($node, $user->uid, 'vid');
976
      $update_node = FALSE;
Dries's avatar
 
Dries committed
977
    }
978
    $op = 'update';
979
  }
980
  if ($update_node) {
981 982 983 984
    db_update('node')
      ->fields(array('vid' => $node->vid))
      ->condition('nid', $node->nid)
      ->execute();
985 986
  }

987 988 989
  // Call the node specific callback (if any). This can be
  // node_invoke($node, 'insert') or
  // node_invoke($node, 'update').