Node.php 14.6 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
  /**
   * Whether the node is being previewed or not.
   *
80 81 82
   * The variable is set to public as it will give a considerable performance
   * improvement. See https://www.drupal.org/node/2498919.
   *
83
   * @var true|null
84
   *   TRUE if the node is being previewed and NULL if it is not.
85 86 87
   */
  public $in_preview = NULL;

88 89 90 91 92 93
  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);

94
    // If no owner has been set explicitly, make the anonymous user the owner.
95
    if (!$this->getOwner()) {
96
      $this->setOwnerId(0);
97 98 99 100 101 102 103 104
    }
    // If no revision author has been set explicitly, make the node owner the
    // revision author.
    if (!$this->getRevisionAuthor()) {
      $this->setRevisionAuthorId($this->getOwnerId());
    }
  }

105
  /**
106
   * {@inheritdoc}
107
   */
108 109
  public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
    parent::preSaveRevision($storage, $record);
110

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

  /**
121
   * {@inheritdoc}
122
   */
123 124
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);
125

126 127 128 129
    // 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()) {
130
      \Drupal::entityManager()->getAccessControlHandler('node')->writeGrants($this, $update);
131
    }
132 133 134 135 136 137

    // 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());
    }
138
  }
139 140

  /**
141
   * {@inheritdoc}
142
   */
143 144
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    parent::preDelete($storage, $entities);
145

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

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

162 163 164 165 166 167 168
  /**
   * {@inheritdoc}
   */
  public function getType() {
    return $this->bundle();
  }

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

    return \Drupal::entityManager()
178
      ->getAccessControlHandler($this->entityTypeId)
179
      ->access($this, $operation, $this->prepareLangcode(), $account, $return_as_object);
180 181 182 183 184 185
  }

  /**
   * {@inheritdoc}
   */
  public function prepareLangcode() {
186
    $langcode = $this->language()->getId();
187 188 189 190 191 192
    // 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.
193
      $content_negotiation_langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
194 195 196 197 198 199 200 201 202
      // If there is a translation available, use it.
      if (isset($node_translations[$content_negotiation_langcode])) {
        $langcode = $content_negotiation_langcode;
      }
    }
    return $langcode;
  }


203 204 205 206 207 208 209
  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    return $this->get('title')->value;
  }

210
  /**
211
   * {@inheritdoc}
212
   */
213 214 215 216
  public function setTitle($title) {
    $this->set('title', $title);
    return $this;
  }
217 218

  /**
219
   * {@inheritdoc}
220
   */
221 222 223
  public function getCreatedTime() {
    return $this->get('created')->value;
  }
224 225 226


  /**
227
   * {@inheritdoc}
228
   */
229 230 231 232
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }
233 234

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

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

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

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

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

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

  /**
286
   * {@inheritdoc}
287
   */
288
  public function getOwnerId() {
289
    return $this->getEntityKey('uid');
290
  }
291

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

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

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

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

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

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

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

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

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

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

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

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

395
    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
396
      ->setLabel(t('Authored by'))
397
      ->setDescription(t('The username of the content author.'))
398
      ->setRevisionable(TRUE)
399
      ->setSetting('target_type', 'user')
400
      ->setSetting('handler', 'default')
401
      ->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
      ->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);
418

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

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

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

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

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

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

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

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

503 504 505 506 507 508 509
    $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);

510
    return $fields;
511 512
  }

513 514 515 516 517 518 519 520 521 522 523 524
  /**
   * 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());
  }

525
}