node.module 128 KB
Newer Older
Dries's avatar
 
Dries committed
1
2
<?php

Dries's avatar
   
Dries committed
3
4
/**
 * @file
5
6
7
8
 * The core module 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
9
10
 */

11
12
13
14
15
16
17
use Symfony\Component\HttpFoundation\Response;

use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\Database\Query\SelectExtender;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\node\Node;

18
/**
19
 * Denotes that the node is not published.
20
 */
21
const NODE_NOT_PUBLISHED = 0;
22
23

/**
24
 * Denotes that the node is published.
25
 */
26
const NODE_PUBLISHED = 1;
27
28

/**
29
 * Denotes that the node is not promoted to the front page.
30
 */
31
const NODE_NOT_PROMOTED = 0;
32
33

/**
34
 * Denotes that the node is promoted to the front page.
35
 */
36
const NODE_PROMOTED = 1;
37
38

/**
39
 * Denotes that the node is not sticky at the top of the page.
40
 */
41
const NODE_NOT_STICKY = 0;
42
43

/**
44
 * Denotes that the node is sticky at the top of the page.
45
 */
46
const NODE_STICKY = 1;
47

48
/**
49
 * Denotes the time cutoff for nodes marked as read.
50
 *
51
52
53
 * 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.
54
 */
55
define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
56

57
/**
58
59
60
61
 * Denotes that access is allowed for a node.
 *
 * Modules should return this value from hook_node_access() to allow access to a
 * node.
62
 */
63
const NODE_ACCESS_ALLOW = 'allow';
64
65

/**
66
67
68
69
 * Denotes that access is denied for a node.
 *
 * Modules should return this value from hook_node_access() to deny access to a
 * node.
70
 */
71
const NODE_ACCESS_DENY = 'deny';
72
73

/**
74
75
76
77
 * Denotes that access is unaffected for a node.
 *
 * Modules should return this value from hook_node_access() to indicate no
 * effect on node access.
78
 */
79
const NODE_ACCESS_IGNORE = NULL;
80

81
82
83
84
85
86
87
/**
 * Implements hook_rebuild().
 */
function node_rebuild() {
  node_types_rebuild();
}

Dries's avatar
   
Dries committed
88
/**
89
 * Implements hook_help().
Dries's avatar
   
Dries committed
90
 */
91
function node_help($path, $arg) {
92
93
94
  // 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.
95
  if ($path != 'admin/reports/status/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
96
      && user_access('access administration pages') && node_access_needs_rebuild()) {
97
    if ($path == 'admin/reports/status') {
98
99
100
      $message = t('The content access permissions need to be rebuilt.');
    }
    else {
101
      $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')));
102
103
104
105
    }
    drupal_set_message($message, 'error');
  }

106
  switch ($path) {
Dries's avatar
   
Dries committed
107
    case 'admin/help#node':
108
109
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
110
      $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>';
111
112
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
113
114
115
      $output .= '<dt>' . t('Creating content') . '</dt>';
      $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>';
      $output .= '<dt>' . t('Creating custom content types') . '</dt>';
116
      $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>';
117
      $output .= '<dt>' . t('Administering content') . '</dt>';
118
119
120
      $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>';
      $output .= '<dt>' . t('Creating revisions') . '</dt>';
      $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>';
121
      $output .= '<dt>' . t('User permissions') . '</dt>';
122
      $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>';
123
      $output .= '</dl>';
124
      return $output;
125

126
    case 'admin/structure/types/add':
127
      return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
128

129
130
131
    case 'admin/structure/types/manage/%/display':
      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>' .
        '<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>';
132

133
    case 'node/%/revisions':
134
      return '<p>' . t('Revisions allow you to track differences between multiple versions of your content, and revert back to older versions.') . '</p>';
135

136
137
    case 'node/%/edit':
      $node = node_load($arg[1]);
138
      $type = node_type_load($node->type);
139
      return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
Dries's avatar
   
Dries committed
140
  }
Dries's avatar
   
Dries committed
141

142
  if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
143
    $type = node_type_load($arg[2]);
144
    return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
145
  }
Dries's avatar
   
Dries committed
146
147
}

148
/**
149
 * Implements hook_theme().
150
151
152
 */
function node_theme() {
  return array(
153
    'node' => array(
154
      'render element' => 'elements',
155
      'template' => 'node',
156
    ),
157
    'node_search_admin' => array(
158
      'render element' => 'form',
159
    ),
160
    'node_add_list' => array(
161
      'variables' => array('content' => NULL),
162
      'file' => 'node.pages.inc',
163
164
    ),
    'node_preview' => array(
165
      'variables' => array('node' => NULL),
166
      'file' => 'node.pages.inc',
167
    ),
168
    'node_admin_overview' => array(
169
      'variables' => array('name' => NULL, 'type' => NULL),
170
    ),
171
172
173
174
175
176
    'node_recent_block' => array(
      'variables' => array('nodes' => NULL),
    ),
    'node_recent_content' => array(
      'variables' => array('node' => NULL),
    ),
177
178
179
  );
}

Dries's avatar
   
Dries committed
180
/**
181
 * Implements hook_cron().
Dries's avatar
   
Dries committed
182
 */
183
function node_cron() {
184
185
186
  db_delete('history')
    ->condition('timestamp', NODE_NEW_LIMIT, '<')
    ->execute();
187
188
}

Dries's avatar
   
Dries committed
189
/**
190
 * Implements hook_entity_info().
Dries's avatar
   
Dries committed
191
 */
192
function node_entity_info() {
Dries's avatar
   
Dries committed
193
194
  $return = array(
    'node' => array(
195
      'label' => t('Node'),
196
197
      'controller class' => 'Drupal\node\NodeStorageController',
      'entity class' => 'Drupal\node\Node',
198
199
      'base table' => 'node',
      'revision table' => 'node_revision',
200
      'uri callback' => 'node_uri',
201
      'fieldable' => TRUE,
202
      'entity keys' => array(
203
204
205
        'id' => 'nid',
        'revision' => 'vid',
        'bundle' => 'type',
206
        'label' => 'title',
207
      ),
208
209
210
      'bundle keys' => array(
        'bundle' => 'type',
      ),
211
      'bundles' => array(),
212
213
      'view modes' => array(
        'full' => array(
214
          'label' => t('Full content'),
215
          'custom settings' => FALSE,
216
217
218
        ),
        'teaser' => array(
          'label' => t('Teaser'),
219
          'custom settings' => TRUE,
220
221
222
        ),
        'rss' => array(
          'label' => t('RSS'),
223
          'custom settings' => FALSE,
224
225
        ),
      ),
Dries's avatar
   
Dries committed
226
227
    ),
  );
228
229
230
231
232
233

  // Search integration is provided by node.module, so search-related
  // view modes for nodes are defined here and not in search.module.
  if (module_exists('search')) {
    $return['node']['view modes'] += array(
      'search_index' => array(
234
        'label' => t('Search index'),
235
        'custom settings' => FALSE,
236
237
      ),
      'search_result' => array(
238
        'label' => t('Search result'),
239
        'custom settings' => FALSE,
240
241
242
243
      ),
    );
  }

244
245
  // Bundles must provide a human readable name so we can create help and error
  // messages, and the path to attach Field admin pages to.
246
  node_type_cache_reset();
247
248
249
250
  foreach (node_type_get_names() as $type => $name) {
    $return['node']['bundles'][$type] = array(
      'label' => $name,
      'admin' => array(
251
        'path' => 'admin/structure/types/manage/%node_type',
252
        'real path' => 'admin/structure/types/manage/' . $type,
253
        'bundle argument' => 4,
254
255
256
257
        'access arguments' => array('administer content types'),
      ),
    );
  }
Dries's avatar
   
Dries committed
258

259
  return $return;
Dries's avatar
   
Dries committed
260
261
}

262
263
264
265
266
267
268
269
270
271
/**
 * Implements hook_field_display_ENTITY_TYPE_alter().
 */
function node_field_display_node_alter(&$display, $context) {
  // Hide field labels in search index.
  if ($context['view_mode'] == 'search_index') {
    $display['label'] = 'hidden';
  }
}

272
/**
273
 * Entity uri callback.
274
275
276
 *
 * @param Drupal\node\Node $node
 *   A node entity.
277
 */
278
function node_uri(Node $node) {
279
280
281
  return array(
    'path' => 'node/' . $node->nid,
  );
282
283
}

284
/**
285
 * Implements hook_admin_paths().
286
287
 */
function node_admin_paths() {
288
289
290
291
292
293
294
295
296
297
298
299
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/edit' => TRUE,
      'node/*/delete' => TRUE,
      'node/*/revisions' => TRUE,
      'node/*/revisions/*/revert' => TRUE,
      'node/*/revisions/*/delete' => TRUE,
      'node/add' => TRUE,
      'node/add/*' => TRUE,
    );
    return $paths;
  }
300
301
}

Dries's avatar
   
Dries committed
302
/**
303
 * Gathers a listing of links to nodes.
Dries's avatar
   
Dries committed
304
305
 *
 * @param $result
306
307
308
309
 *   A database result object from a query to fetch node entities. If your
 *   query joins the {node_comment_statistics} table so that the comment_count
 *   field is available, a title attribute will be added to show the number of
 *   comments.
Dries's avatar
   
Dries committed
310
 * @param $title
311
 *   (optional) A heading for the resulting list.
Dries's avatar
   
Dries committed
312
313
 *
 * @return
314
315
 *   A renderable array containing a list of linked node titles fetched from
 *   $result, or FALSE if there are no rows in $result.
Dries's avatar
   
Dries committed
316
 */
Dries's avatar
   
Dries committed
317
function node_title_list($result, $title = NULL) {
318
  $items = array();
319
  $num_rows = FALSE;
320
  foreach ($result as $node) {
321
    $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());
322
    $num_rows = TRUE;
Dries's avatar
   
Dries committed
323
324
  }

325
  return $num_rows ? array('#theme' => 'item_list__node', '#items' => $items, '#title' => $title) : FALSE;
Dries's avatar
   
Dries committed
326
327
}

Dries's avatar
   
Dries committed
328
/**
329
 * Updates the 'last viewed' timestamp of the specified node for current user.
330
 *
331
332
 * @param Drupal\node\Node $node
 *   A node entity.
Dries's avatar
   
Dries committed
333
 */
334
function node_tag_new(Node $node) {
Dries's avatar
   
Dries committed
335
336
  global $user;
  if ($user->uid) {
337
338
339
340
341
342
343
    db_merge('history')
      ->key(array(
        'uid' => $user->uid,
        'nid' => $node->nid,
      ))
      ->fields(array('timestamp' => REQUEST_TIME))
      ->execute();
344
   }
Dries's avatar
   
Dries committed
345
346
}

Dries's avatar
   
Dries committed
347
/**
348
 * Retrieves the timestamp for the current user's last view of a specified node.
Dries's avatar
   
Dries committed
349
 */
Dries's avatar
   
Dries committed
350
351
function node_last_viewed($nid) {
  global $user;
352
  $history = &drupal_static(__FUNCTION__, array());
Dries's avatar
   
Dries committed
353

Dries's avatar
   
Dries committed
354
  if (!isset($history[$nid])) {
355
    $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
356
357
  }

358
  return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
Dries's avatar
   
Dries committed
359
360
361
}

/**
362
 * Decides on the type of marker to be displayed for a given node.
Dries's avatar
   
Dries committed
363
 *
Dries's avatar
   
Dries committed
364
365
366
367
 * @param $nid
 *   Node ID whose history supplies the "last viewed" timestamp.
 * @param $timestamp
 *   Time which is compared against node's "last viewed" timestamp.
368
 *
369
370
 * @return
 *   One of the MARK constants.
Dries's avatar
   
Dries committed
371
 */
372
function node_mark($nid, $timestamp) {
Dries's avatar
   
Dries committed
373
  global $user;
374
  $cache = &drupal_static(__FUNCTION__, array());
Dries's avatar
   
Dries committed
375

376
377
378
  if (!$user->uid) {
    return MARK_READ;
  }
Dries's avatar
Dries committed
379
  if (!isset($cache[$nid])) {
380
    $cache[$nid] = node_last_viewed($nid);
Dries's avatar
   
Dries committed
381
  }
382
383
384
385
386
387
388
  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
389
390
}

391
/**
392
 * Extracts the type name.
393
 *
394
 * @param Drupal\node\Node|string $node
395
 *   Either a string or object, containing the node type information.
396
397
 *
 * @return
398
 *   Node type of the passed-in data.
399
 */
400
401
402
function _node_extract_type($node) {
  return is_object($node) ? $node->type : $node;
}
403

404
405
406
/**
 * Returns a list of all the available node types.
 *
407
408
409
 * This list can include types that are queued for addition or deletion.
 * See _node_types_build() for details.
 *
410
 * @return
411
 *   An array of node types, as objects, keyed by the type.
412
 *
413
 * @see node_type_load()
414
415
416
417
418
419
420
421
 */
function node_type_get_types() {
  return _node_types_build()->types;
}

/**
 * Returns the node type base of the passed node or node type string.
 *
422
423
424
 * The base indicates which module implements this node type and is used to
 * execute node-type-specific hooks. For types defined in the user interface
 * and managed by node.module, the base is 'node_content'.
425
 *
426
427
 * @param Drupal\node\Node|string $node
 *   A node entity or string that indicates the node type to return.
428
 *
429
430
 * @return
 *   The node type base or FALSE if the node type is not found.
431
432
 *
 * @see node_invoke()
433
434
435
436
437
438
439
440
 */
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;
}

/**
441
442
443
444
 * Returns a list of available node type names.
 *
 * This list can include types that are queued for addition or deletion.
 * See _node_types_build() for details.
445
446
447
448
449
450
451
452
453
454
455
 *
 * @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.
 *
456
457
 * @param Drupal\node\Node|string $node
 *   A node entity or string that indicates the node type to return.
458
459
460
461
462
463
464
465
 *
 * @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;
466
467
468
}

/**
469
 * Updates the database cache of node types.
470
 *
471
472
 * All new module-defined node types are saved to the database via a call to
 * node_type_save(), and obsolete ones are deleted via a call to
473
 * node_type_delete(). See _node_types_build() for an explanation of the new
474
 * and obsolete types.
475
476
 */
function node_types_rebuild() {
477
  _node_types_build(TRUE);
478
479
}

480
/**
481
 * Menu argument loader: Loads a node type by string.
482
483
 *
 * @param $name
484
 *   The machine name of a node type to load.
485
486
487
488
489
 *
 * @return
 *   A node type object or FALSE if $name does not exist.
 */
function node_type_load($name) {
490
491
  $types = _node_types_build()->types;
  return isset($types[$name]) ? $types[$name] : FALSE;
492
493
}

494
/**
495
496
497
498
 * Saves a node type to the database.
 *
 * @param $info
 *   The node type to save, as an object.
Dries's avatar
   
Dries committed
499
500
 *
 * @return
501
 *   Status flag indicating outcome of the operation.
Dries's avatar
   
Dries committed
502
 */
503
504
function node_type_save($info) {
  $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
505
  $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', 0, 1, array(':type' => $existing_type))->fetchField();
506
507
508
509
510
511
512
513
514
515
516
517
518
  $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,
    'description' => (string) $type->description,
    'help' => (string) $type->help,
    'custom' => (int) $type->custom,
    'modified' => (int) $type->modified,
    'locked' => (int) $type->locked,
519
520
    'disabled' => (int) $type->disabled,
    'module' => $type->module,
521
  );
522
523

  if ($is_existing) {
524
525
526
527
    db_update('node_type')
      ->fields($fields)
      ->condition('type', $existing_type)
      ->execute();
528

Dries's avatar
   
Dries committed
529
    if (!empty($type->old_type) && $type->old_type != $type->type) {
530
      field_attach_rename_bundle('node', $type->old_type, $type->type);
Dries's avatar
   
Dries committed
531
    }
532
    module_invoke_all('node_type_update', $type);
533
    $status = SAVED_UPDATED;
534
535
  }
  else {
536
    $fields['orig_type'] = (string) $type->orig_type;
537
538
539
    db_insert('node_type')
      ->fields($fields)
      ->execute();
540

541
    field_attach_create_bundle('node', $type->type);
542

543
    module_invoke_all('node_type_insert', $type);
544
    $status = SAVED_NEW;
545
  }
546
547

  // Clear the node type cache.
548
  node_type_cache_reset();
549
550

  return $status;
551
}
552

553
/**
554
 * Adds the default body field to a node type.
555
 *
556
 * @param $type
557
 *   A node type object.
558
 * @param $label
559
 *   (optional) The label for the body instance.
560
561
562
 *
 * @return
 *   Body field instance.
563
 */
564
function node_add_body_field($type, $label = 'Body') {
565
566
   // Add or remove the body field, as needed.
  $field = field_info_field('body');
567
  $instance = field_info_instance('node', 'body', $type->type);
568
569
570
571
572
573
574
  if (empty($field)) {
    $field = array(
      'field_name' => 'body',
      'type' => 'text_with_summary',
      'entity_types' => array('node'),
    );
    $field = field_create_field($field);
575
  }
576
577
578
579
580
581
  if (empty($instance)) {
    $instance = array(
      'field_name' => 'body',
      'entity_type' => 'node',
      'bundle' => $type->type,
      'label' => $label,
582
      'widget' => array('type' => 'text_textarea_with_summary'),
583
584
      'settings' => array('display_summary' => TRUE),
      'display' => array(
585
        'default' => array(
586
587
588
589
590
591
592
593
594
          'label' => 'hidden',
          'type' => 'text_default',
        ),
        'teaser' => array(
          'label' => 'hidden',
          'type' => 'text_summary_or_trimmed',
        ),
      ),
    );
595
    $instance = field_create_instance($instance);
596
  }
597
  return $instance;
598
}
599

600
601
602
603
604
/**
 * Implements hook_field_extra_fields().
 */
function node_field_extra_fields() {
  $extra = array();
605
606
607
608
609
610
611
612
613
614
615
  $module_language_enabled = module_exists('language');
  $description = t('Node module element');

  foreach (node_type_get_types() as $bundle) {
    if ($bundle->has_title) {
      $extra['node'][$bundle->type]['form']['title'] = array(
        'label' => $bundle->title_label,
        'description' => $description,
        'weight' => -5,
      );
    }
616

617
618
619
620
621
622
623
    // Add also the 'language' select if Language module is enabled and the
    // bundle has multilingual support.
    if ($module_language_enabled && variable_get('node_type_language_' . $bundle->type, 0)) {
      $extra['node'][$bundle->type]['form']['language'] = array(
        'label' => t('Language'),
        'description' => $description,
        'weight' => 0,
624
625
626
      );
    }
  }
627
628

  return $extra;
629
630
}

631
632
633
/**
 * Deletes a node type from the database.
 *
634
635
 * @param $name
 *   The machine name of the node type to delete.
636
 */
637
638
function node_type_delete($name) {
  $type = node_type_load($name);
639
  db_delete('node_type')
640
    ->condition('type', $name)
641
    ->execute();
642
643
  field_attach_delete_bundle('node', $name);
  module_invoke_all('node_type_delete', $type);
644
645

  // Clear the node type cache.
646
  node_type_cache_reset();
647
648
}

649
/**
650
651
 * Updates all nodes of one type to be of another type.
 *
652
 * @param $old_type
653
654
655
 *   The current node type of the nodes.
 * @param $type
 *   The new node type of the nodes.
656
657
 *
 * @return
658
 *   The number of nodes whose node type field was modified.
659
 */
660
function node_type_update_nodes($old_type, $type) {
661
  return db_update('node')
662
663
664
    ->fields(array('type' => $type))
    ->condition('type', $old_type)
    ->execute();
Dries's avatar
   
Dries committed
665
}
Dries's avatar
   
Dries committed
666

667
/**
668
669
 * Builds and returns the list of available node types.
 *
670
671
672
673
 * The list of types is built by invoking hook_node_info() on all modules and
 * comparing this information with the node types in the {node_type} table.
 * These two information sources are not synchronized during module installation
 * until node_types_rebuild() is called.
Dries's avatar
   
Dries committed
674
 *
675
676
 * @param $rebuild
 *  TRUE to rebuild node types. Equivalent to calling node_types_rebuild().
677
 *
678
 * @return
679
 *   An object with two properties:
680
681
682
683
684
685
686
687
688
689
 *   - names: Associative array of the names of node types, keyed by the type.
 *   - types: Associative array of node type objects, keyed by the type.
 *   Both of these arrays will include new types that have been defined by
 *   hook_node_info() implementations but not yet saved in the {node_type}
 *   table. These are indicated in the type object by $type->is_new being set
 *   to the value 1. These arrays will also include obsolete types: types that
 *   were previously defined by modules that have now been disabled, or for
 *   whatever reason are no longer being defined in hook_node_info()
 *   implementations, but are still in the database. These are indicated in the
 *   type object by $type->disabled being set to TRUE.
Dries's avatar
   
Dries committed
690
 */
691
function _node_types_build($rebuild = FALSE) {
692
  $cid = 'node_types:' . drupal_container()->get(LANGUAGE_TYPE_INTERFACE)->langcode;
693

694
695
  if (!$rebuild) {
    $_node_types = &drupal_static(__FUNCTION__);
696
697
698
    if (isset($_node_types)) {
      return $_node_types;
    }
699
    if ($cache = cache()->get($cid)) {
700
      $_node_types = $cache->data;
701
702
      return $_node_types;
    }
703
  }
704

705
  $_node_types = (object) array('types' => array(), 'names' => array());
706

707
708
709
710
711
712
713
714
  foreach (module_implements('node_info') as $module) {
    $info_array = module_invoke($module, 'node_info');
    foreach ($info_array as $type => $info) {
      $info['type'] = $type;
      $_node_types->types[$type] = node_type_set_defaults($info);
      $_node_types->types[$type]->module = $module;
      $_node_types->names[$type] = $info['name'];
    }
715
  }
716
  $query = db_select('node_type', 'nt')
717
718
    ->addTag('translatable')
    ->addTag('node_type_access')
719
    ->fields('nt')
720
721
722
723
724
725
726
727
    ->orderBy('nt.type', 'ASC');
  if (!$rebuild) {
    $query->condition('disabled', 0);
  }
  foreach ($query->execute() as $type_object) {
    $type_db = $type_object->type;
    // Original disabled value.
    $disabled = $type_object->disabled;
728
729
    // 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
730
731
    // module using hook_node_info) have a base value of 'node_content'. The isset()
    // check prevents errors on old (pre-Drupal 7) databases.
732
    if (isset($type_object->base) && $type_object->base != 'node_content' && empty($_node_types->types[$type_db])) {
733
      $type_object->disabled = TRUE;
734
    }
735
    if (isset($_node_types->types[$type_db])) {
736
737
738
739
740
      $type_object->disabled = FALSE;
    }
    if (!isset($_node_types->types[$type_db]) || $type_object->modified) {
      $_node_types->types[$type_db] = $type_object;
      $_node_types->names[$type_db] = $type_object->name;
741

742
      if ($type_db != $type_object->orig_type) {
743
744
        unset($_node_types->types[$type_object->orig_type]);
        unset($_node_types->names[$type_object->orig_type]);
745
746
      }
    }
747
748
749
750
751
752
753
754
755
756
    $_node_types->types[$type_db]->disabled = $type_object->disabled;
    $_node_types->types[$type_db]->disabled_changed = $disabled != $type_object->disabled;
  }

  if ($rebuild) {
    foreach ($_node_types->types as $type => $type_object) {
      if (!empty($type_object->is_new) || !empty($type_object->disabled_changed)) {
        node_type_save($type_object);
      }
    }
757
758
  }

759
  asort($_node_types->names);
760

761
  cache()->set($cid, $_node_types);
762

763
  return $_node_types;
764
765
}

766
767
768
769
/**
 * Clears the node type cache.
 */
function node_type_cache_reset() {
770
  cache()->deletePrefix('node_types:');
771
772
773
  drupal_static_reset('_node_types_build');
}

774
/**
775
 * Sets the default values for a node type.
776
 *
777
778
779
780
781
 * The defaults are appropriate for a type defined through hook_node_info(),
 * since 'custom' is TRUE for types defined in the user interface, and FALSE
 * for types defined by modules. (The 'custom' flag prevents types from being
 * deleted through the user interface.) Also, the default for 'locked' is TRUE,
 * which prevents users from changing the machine name of the type.
782
783
 *
 * @param $info
784
785
 *   (optional) An object or array containing values to override the defaults.
 *   See hook_node_info() for details on what the array elements mean.
786
787
 *
 * @return
788
 *   A node type object, with missing values in $info set to their defaults.
789
 */
790
791
function node_type_set_defaults($info = array()) {
  $info = (array) $info;
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
  $new_type = $info + array(
    'type' => '',
    'name' => '',
    'base' => '',
    'description' => '',
    'help' => '',
    'custom' => 0,
    'modified' => 0,
    'locked' => 1,
    'disabled' => 0,
    'is_new' => 1,
    'has_title' => 1,
    'title_label' => 'Title',
  );
  $new_type = (object) $new_type;

808
  // If the type has no title, set an empty label.
809
810
811
  if (!$new_type->has_title) {
    $new_type->title_label = '';
  }
812
813
814
  if (empty($new_type->module)) {
    $new_type->module = $new_type->base == 'node_content' ? 'node' : '';
  }
815
816
817
  $new_type->orig_type = isset($info['type']) ? $info['type'] : '';

  return $new_type;
Dries's avatar
   
Dries committed
818
}
Dries's avatar
   
Dries committed
819

820
/**
821
 * Implements hook_rdf_mapping().
822
823
824
825
826
827
828
829
 */
function node_rdf_mapping() {
  return array(
    array(
      'type' => 'node',
      'bundle' => RDF_DEFAULT_BUNDLE,
      'mapping' => array(
        'rdftype' => array('sioc:Item', 'foaf:Document'),
830
        'title' => array(
831
832
833
834
835
836
837
838
839
          'predicates' => array('dc:title'),
        ),
        'created' => array(
          'predicates' => array('dc:date', 'dc:created'),
          'datatype' => 'xsd:dateTime',
          'callback' => 'date_iso8601',
        ),
        'changed' => array(
          'predicates' => array('dc:modified'),
840
841
          'datatype' => 'xsd:dateTime',
          'callback' => 'date_iso8601',
842
        ),
843
        'body' => array(
844
845
          'predicates' => array('content:encoded'),
        ),
846
        'uid' => array(
847
          'predicates' => array('sioc:has_creator'),
848
          'type' => 'rel',
849
        ),
850
        'name' => array(
851
852
          'predicates' => array('foaf:name'),
        ),
853
854
        'comment_count' => array(
          'predicates' => array('sioc:num_replies'),
855
856
857
858
859
860
          'datatype' => 'xsd:integer',
        ),
        'last_activity' => array(
          'predicates' => array('sioc:last_activity_date'),
          'datatype' => 'xsd:dateTime',
          'callback' => 'date_iso8601',
861
        ),
862
863
864
865
866
      ),
    ),
  );
}

867
/**
868
 * Determines whether a node hook exists.
Dries's avatar
   
Dries committed
869
 *
870
871
 * @param Drupal\node\Node|string $node
 *   A node entity or a string containing the node type.
Dries's avatar
   
Dries committed
872
873
 * @param $hook
 *   A string containing the name of the hook.
874
 *
Dries's avatar
   
Dries committed
875
 * @return
876
 *   TRUE if the $hook exists in the node type of $node.
Dries's avatar
   
Dries committed
877
 */
878
function node_hook($node, $hook) {
879
  $base = node_type_get_base($node);
880
  return module_hook($base, $hook);
Dries's avatar
   
Dries committed
881
882
}

883
/**
884
 * Invokes a node hook.
Dries's avatar
   
Dries committed
885
 *
886
887
 * @param Drupal\node\Node|string $node
 *   A node entity or a string containing the node type.