Node.php 14.5 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\node\Entity\Node.
6 7
 */

8
namespace Drupal\node\Entity;
9

10
use Drupal\Core\Entity\ContentEntityBase;
11
use Drupal\Core\Entity\EntityChangedTrait;
12
use Drupal\Core\Entity\EntityStorageInterface;
13
use Drupal\Core\Entity\EntityTypeInterface;
14
use Drupal\Core\Field\BaseFieldDefinition;
15
use Drupal\Core\Language\LanguageInterface;
16
use Drupal\Core\Session\AccountInterface;
17
use Drupal\node\NodeInterface;
18
use Drupal\user\UserInterface;
19 20 21

/**
 * Defines the node entity class.
22
 *
23
 * @ContentEntityType(
24
 *   id = "node",
25
 *   label = @Translation("Content"),
26
 *   bundle_label = @Translation("Content type"),
27
 *   handlers = {
28
 *     "storage" = "Drupal\node\NodeStorage",
29
 *     "storage_schema" = "Drupal\node\NodeStorageSchema",
30
 *     "view_builder" = "Drupal\node\NodeViewBuilder",
31
 *     "access" = "Drupal\node\NodeAccessControlHandler",
32
 *     "views_data" = "Drupal\node\NodeViewsData",
33
 *     "form" = {
34
 *       "default" = "Drupal\node\NodeForm",
35
 *       "delete" = "Drupal\node\Form\NodeDeleteForm",
36
 *       "edit" = "Drupal\node\NodeForm"
37
 *     },
38 39 40
 *     "route_provider" = {
 *       "html" = "Drupal\node\Entity\NodeRouteProvider",
 *     },
41
 *     "list_builder" = "Drupal\node\NodeListBuilder",
42
 *     "translation" = "Drupal\node\NodeTranslationHandler"
43 44
 *   },
 *   base_table = "node",
45
 *   data_table = "node_field_data",
46 47
 *   revision_table = "node_revision",
 *   revision_data_table = "node_field_revision",
48
 *   translatable = TRUE,
49
 *   list_cache_contexts = { "user.node_grants:view" },
50 51 52 53 54
 *   entity_keys = {
 *     "id" = "nid",
 *     "revision" = "vid",
 *     "bundle" = "type",
 *     "label" = "title",
55
 *     "langcode" = "langcode",
56 57 58
 *     "uuid" = "uuid",
 *     "status" = "status",
 *     "uid" = "uid",
59
 *   },
60
 *   bundle_entity_type = "node_type",
61
 *   field_ui_base_route = "entity.node_type.edit_form",
62
 *   common_reference_target = TRUE,
63 64
 *   permission_granularity = "bundle",
 *   links = {
65 66 67 68
 *     "canonical" = "/node/{node}",
 *     "delete-form" = "/node/{node}/delete",
 *     "edit-form" = "/node/{node}/edit",
 *     "version-history" = "/node/{node}/revisions",
69
 *     "revision" = "/node/{node}/revisions/{node_revision}/view",
70
 *   }
71
 * )
72
 */
73
class Node extends ContentEntityBase implements NodeInterface {
74

75 76
  use EntityChangedTrait;

77 78 79 80 81 82 83
  /**
   * Whether the node is being previewed or not.
   *
   * @var true|null
   */
  public $in_preview = NULL;

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);

    // If no owner has been set explicitly, make the current user the owner.
    if (!$this->getOwner()) {
      $this->setOwnerId(\Drupal::currentUser()->id());
    }
    // If no revision author has been set explicitly, make the node owner the
    // revision author.
    if (!$this->getRevisionAuthor()) {
      $this->setRevisionAuthorId($this->getOwnerId());
    }
  }

101
  /**
102
   * {@inheritdoc}
103
   */
104 105
  public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
    parent::preSaveRevision($storage, $record);
106

107
    if (!$this->isNewRevision() && isset($this->original) && (!isset($record->revision_log) || $record->revision_log === '')) {
108
      // If we are updating an existing node without adding a new revision, we
109
      // need to make sure $entity->revision_log is reset whenever it is empty.
110 111
      // Therefore, this code allows us to avoid clobbering an existing log
      // entry with an empty one.
112
      $record->revision_log = $this->original->revision_log->value;
113 114
    }
  }
115 116

  /**
117
   * {@inheritdoc}
118
   */
119 120
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);
121

122 123 124 125
    // Update the node access table for this node, but only if it is the
    // default revision. There's no need to delete existing records if the node
    // is new.
    if ($this->isDefaultRevision()) {
126
      \Drupal::entityManager()->getAccessControlHandler('node')->writeGrants($this, $update);
127
    }
128 129 130 131 132 133

    // Reindex the node when it is updated. The node is automatically indexed
    // when it is added, simply by being added to the node table.
    if ($update) {
      node_reindex_node_search($this->id());
    }
134
  }
135 136

  /**
137
   * {@inheritdoc}
138
   */
139 140
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    parent::preDelete($storage, $entities);
141

142
    // Ensure that all nodes deleted are removed from the search index.
143
    if (\Drupal::moduleHandler()->moduleExists('search')) {
144
      foreach ($entities as $entity) {
145
        search_index_clear('node_search', $entity->nid->value);
146 147 148
      }
    }
  }
149

150 151 152
  /**
   * {@inheritdoc}
   */
153 154
  public static function postDelete(EntityStorageInterface $storage, array $nodes) {
    parent::postDelete($storage, $nodes);
155 156 157
    \Drupal::service('node.grant_storage')->deleteNodeRecords(array_keys($nodes));
  }

158 159 160 161 162 163 164
  /**
   * {@inheritdoc}
   */
  public function getType() {
    return $this->bundle();
  }

165 166 167
  /**
   * {@inheritdoc}
   */
168
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
169
    if ($operation == 'create') {
170
      return parent::access($operation, $account, $return_as_object);
171 172 173
    }

    return \Drupal::entityManager()
174
      ->getAccessControlHandler($this->entityTypeId)
175
      ->access($this, $operation, $this->prepareLangcode(), $account, $return_as_object);
176 177 178 179 180 181
  }

  /**
   * {@inheritdoc}
   */
  public function prepareLangcode() {
182
    $langcode = $this->language()->getId();
183 184 185 186 187 188
    // If the Language module is enabled, try to use the language from content
    // negotiation.
    if (\Drupal::moduleHandler()->moduleExists('language')) {
      // Load languages the node exists in.
      $node_translations = $this->getTranslationLanguages();
      // Load the language from content negotiation.
189
      $content_negotiation_langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
190 191 192 193 194 195 196 197 198
      // If there is a translation available, use it.
      if (isset($node_translations[$content_negotiation_langcode])) {
        $langcode = $content_negotiation_langcode;
      }
    }
    return $langcode;
  }


199 200 201 202 203 204 205
  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    return $this->get('title')->value;
  }

206
  /**
207
   * {@inheritdoc}
208
   */
209 210 211 212
  public function setTitle($title) {
    $this->set('title', $title);
    return $this;
  }
213 214

  /**
215
   * {@inheritdoc}
216
   */
217 218 219
  public function getCreatedTime() {
    return $this->get('created')->value;
  }
220 221 222


  /**
223
   * {@inheritdoc}
224
   */
225 226 227 228
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }
229 230

  /**
231
   * {@inheritdoc}
232
   */
233 234 235
  public function getChangedTime() {
    return $this->get('changed')->value;
  }
236 237

  /**
238
   * {@inheritdoc}
239
   */
240 241 242
  public function isPromoted() {
    return (bool) $this->get('promote')->value;
  }
243 244

  /**
245
   * {@inheritdoc}
246
   */
247
  public function setPromoted($promoted) {
248
    $this->set('promote', $promoted ? NODE_PROMOTED : NODE_NOT_PROMOTED);
249 250
    return $this;
  }
251 252

  /**
253
   * {@inheritdoc}
254
   */
255 256 257
  public function isSticky() {
    return (bool) $this->get('sticky')->value;
  }
258 259

  /**
260
   * {@inheritdoc}
261
   */
262 263 264 265
  public function setSticky($sticky) {
    $this->set('sticky', $sticky ? NODE_STICKY : NODE_NOT_STICKY);
    return $this;
  }
266
  /**
267
   * {@inheritdoc}
268
   */
269
  public function isPublished() {
270
    return (bool) $this->getEntityKey('status');
271
  }
272

273
  /**
274
   * {@inheritdoc}
275
   */
276 277 278
  public function setPublished($published) {
    $this->set('status', $published ? NODE_PUBLISHED : NODE_NOT_PUBLISHED);
    return $this;
279 280 281
  }

  /**
282
   * {@inheritdoc}
283
   */
284
  public function getOwner() {
285
    return $this->get('uid')->entity;
286
  }
287 288

  /**
289
   * {@inheritdoc}
290
   */
291
  public function getOwnerId() {
292
    return $this->getEntityKey('uid');
293
  }
294

295 296 297
  /**
   * {@inheritdoc}
   */
298
  public function setOwnerId($uid) {
299 300
    $this->set('uid', $uid);
    return $this;
301 302
  }

303 304 305 306 307 308 309 310
  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('uid', $account->id());
    return $this;
  }

311 312 313
  /**
   * {@inheritdoc}
   */
314 315
  public function getRevisionCreationTime() {
    return $this->get('revision_timestamp')->value;
316 317 318 319 320
  }

  /**
   * {@inheritdoc}
   */
321 322 323
  public function setRevisionCreationTime($timestamp) {
    $this->set('revision_timestamp', $timestamp);
    return $this;
324 325
  }

326 327 328
  /**
   * {@inheritdoc}
   */
329 330
  public function getRevisionAuthor() {
    return $this->get('revision_uid')->entity;
331 332
  }

333 334 335
  /**
   * {@inheritdoc}
   */
336 337 338
  public function setRevisionAuthorId($uid) {
    $this->set('revision_uid', $uid);
    return $this;
339 340
  }

341 342 343
  /**
   * {@inheritdoc}
   */
344
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
345
    $fields['nid'] = BaseFieldDefinition::create('integer')
346 347
      ->setLabel(t('Node ID'))
      ->setDescription(t('The node ID.'))
348 349
      ->setReadOnly(TRUE)
      ->setSetting('unsigned', TRUE);
350

351
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
352 353 354 355
      ->setLabel(t('UUID'))
      ->setDescription(t('The node UUID.'))
      ->setReadOnly(TRUE);

356
    $fields['vid'] = BaseFieldDefinition::create('integer')
357 358
      ->setLabel(t('Revision ID'))
      ->setDescription(t('The node revision ID.'))
359 360
      ->setReadOnly(TRUE)
      ->setSetting('unsigned', TRUE);
361

362
    $fields['type'] = BaseFieldDefinition::create('entity_reference')
363 364
      ->setLabel(t('Type'))
      ->setDescription(t('The node type.'))
365
      ->setSetting('target_type', 'node_type')
366 367
      ->setReadOnly(TRUE);

368
    $fields['langcode'] = BaseFieldDefinition::create('language')
369
      ->setLabel(t('Language'))
370
      ->setDescription(t('The node language code.'))
371
      ->setTranslatable(TRUE)
372 373 374 375 376 377 378 379
      ->setRevisionable(TRUE)
      ->setDisplayOptions('view', array(
        'type' => 'hidden',
      ))
      ->setDisplayOptions('form', array(
        'type' => 'language_select',
        'weight' => 2,
      ));
380

381
    $fields['title'] = BaseFieldDefinition::create('string')
382 383 384
      ->setLabel(t('Title'))
      ->setRequired(TRUE)
      ->setTranslatable(TRUE)
385
      ->setRevisionable(TRUE)
386
      ->setDefaultValue('')
387
      ->setSetting('max_length', 255)
388 389
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
390
        'type' => 'string',
391 392 393
        'weight' => -5,
      ))
      ->setDisplayOptions('form', array(
394
        'type' => 'string_textfield',
395 396 397
        'weight' => -5,
      ))
      ->setDisplayConfigurable('form', TRUE);
398

399
    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
400
      ->setLabel(t('Authored by'))
401
      ->setDescription(t('The username of the content author.'))
402
      ->setRevisionable(TRUE)
403
      ->setSetting('target_type', 'user')
404
      ->setSetting('handler', 'default')
405
      ->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => array(
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'placeholder' => '',
        ),
      ))
      ->setDisplayConfigurable('form', TRUE);
422

423
    $fields['status'] = BaseFieldDefinition::create('boolean')
424
      ->setLabel(t('Publishing status'))
425
      ->setDescription(t('A boolean indicating whether the node is published.'))
426
      ->setRevisionable(TRUE)
427 428
      ->setTranslatable(TRUE)
      ->setDefaultValue(TRUE);
429

430
    $fields['created'] = BaseFieldDefinition::create('created')
431
      ->setLabel(t('Authored on'))
432
      ->setDescription(t('The time that the node was created.'))
433
      ->setRevisionable(TRUE)
434 435 436 437 438 439 440 441 442 443 444
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'timestamp',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'datetime_timestamp',
        'weight' => 10,
      ))
      ->setDisplayConfigurable('form', TRUE);
445

446
    $fields['changed'] = BaseFieldDefinition::create('changed')
447
      ->setLabel(t('Changed'))
448
      ->setDescription(t('The time that the node was last edited.'))
449 450
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);
451

452
    $fields['promote'] = BaseFieldDefinition::create('boolean')
453
      ->setLabel(t('Promoted to front page'))
454
      ->setRevisionable(TRUE)
455
      ->setTranslatable(TRUE)
456 457 458 459 460 461 462 463 464
      ->setDefaultValue(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'boolean_checkbox',
        'settings' => array(
          'display_label' => TRUE,
        ),
        'weight' => 15,
      ))
      ->setDisplayConfigurable('form', TRUE);
465

466
    $fields['sticky'] = BaseFieldDefinition::create('boolean')
467
      ->setLabel(t('Sticky at top of lists'))
468
      ->setRevisionable(TRUE)
469
      ->setTranslatable(TRUE)
470
      ->setDefaultValue(FALSE)
471 472 473 474 475 476 477 478
      ->setDisplayOptions('form', array(
        'type' => 'boolean_checkbox',
        'settings' => array(
          'display_label' => TRUE,
        ),
        'weight' => 16,
      ))
      ->setDisplayConfigurable('form', TRUE);
479

480
    $fields['revision_timestamp'] = BaseFieldDefinition::create('created')
481 482
      ->setLabel(t('Revision timestamp'))
      ->setDescription(t('The time that the current revision was created.'))
483 484
      ->setQueryable(FALSE)
      ->setRevisionable(TRUE);
485

486
    $fields['revision_uid'] = BaseFieldDefinition::create('entity_reference')
487 488
      ->setLabel(t('Revision user ID'))
      ->setDescription(t('The user ID of the author of the current revision.'))
489
      ->setSetting('target_type', 'user')
490 491
      ->setQueryable(FALSE)
      ->setRevisionable(TRUE);
492

493
    $fields['revision_log'] = BaseFieldDefinition::create('string_long')
494
      ->setLabel(t('Revision log message'))
495
      ->setDescription(t('Briefly describe the changes you have made.'))
496
      ->setRevisionable(TRUE)
497 498 499 500 501 502 503 504
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'string_textarea',
        'weight' => 25,
        'settings' => array(
          'rows' => 4,
        ),
      ));
505

506 507 508 509 510 511 512
    $fields['revision_translation_affected'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Revision translation affected'))
      ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
      ->setReadOnly(TRUE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

513
    return $fields;
514 515
  }

516 517 518 519 520 521 522 523 524 525 526 527
  /**
   * Default value callback for 'uid' base field definition.
   *
   * @see ::baseFieldDefinitions()
   *
   * @return array
   *   An array of default values.
   */
  public static function getCurrentUserId() {
    return array(\Drupal::currentUser()->id());
  }

528
}