Node.php 13.9 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\EntityStorageInterface;
12
use Drupal\Core\Entity\EntityTypeInterface;
13
use Drupal\Core\Field\BaseFieldDefinition;
14
use Drupal\Core\Language\LanguageInterface;
15
use Drupal\Core\Session\AccountInterface;
16
use Drupal\node\NodeInterface;
17
use Drupal\user\UserInterface;
18 19 20

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

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  /**
   * {@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());
    }
  }

87
  /**
88
   * {@inheritdoc}
89
   */
90 91
  public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
    parent::preSaveRevision($storage, $record);
92

93
    if (!$this->isNewRevision() && isset($this->original) && (!isset($record->revision_log) || $record->revision_log === '')) {
94
      // If we are updating an existing node without adding a new revision, we
95
      // need to make sure $entity->revision_log is reset whenever it is empty.
96 97
      // Therefore, this code allows us to avoid clobbering an existing log
      // entry with an empty one.
98
      $record->revision_log = $this->original->revision_log->value;
99 100
    }
  }
101 102

  /**
103
   * {@inheritdoc}
104
   */
105 106
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);
107

108 109 110 111
    // 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()) {
112
      \Drupal::entityManager()->getAccessControlHandler('node')->writeGrants($this, $update);
113
    }
114 115 116 117 118 119

    // 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());
    }
120
  }
121 122

  /**
123
   * {@inheritdoc}
124
   */
125 126
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    parent::preDelete($storage, $entities);
127

128
    // Ensure that all nodes deleted are removed from the search index.
129
    if (\Drupal::moduleHandler()->moduleExists('search')) {
130
      foreach ($entities as $entity) {
131
        search_index_clear('node_search', $entity->nid->value);
132 133 134
      }
    }
  }
135

136 137 138
  /**
   * {@inheritdoc}
   */
139 140
  public static function postDelete(EntityStorageInterface $storage, array $nodes) {
    parent::postDelete($storage, $nodes);
141 142 143
    \Drupal::service('node.grant_storage')->deleteNodeRecords(array_keys($nodes));
  }

144 145 146 147 148 149 150
  /**
   * {@inheritdoc}
   */
  public function getType() {
    return $this->bundle();
  }

151 152 153
  /**
   * {@inheritdoc}
   */
154
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
155
    if ($operation == 'create') {
156
      return parent::access($operation, $account, $return_as_object);
157 158 159
    }

    return \Drupal::entityManager()
160
      ->getAccessControlHandler($this->entityTypeId)
161
      ->access($this, $operation, $this->prepareLangcode(), $account, $return_as_object);
162 163 164 165 166 167
  }

  /**
   * {@inheritdoc}
   */
  public function prepareLangcode() {
168
    $langcode = $this->language()->getId();
169 170 171 172 173 174
    // 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.
175
      $content_negotiation_langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
176 177 178 179 180 181 182 183 184
      // If there is a translation available, use it.
      if (isset($node_translations[$content_negotiation_langcode])) {
        $langcode = $content_negotiation_langcode;
      }
    }
    return $langcode;
  }


185 186 187 188 189 190 191
  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    return $this->get('title')->value;
  }

192
  /**
193
   * {@inheritdoc}
194
   */
195 196 197 198
  public function setTitle($title) {
    $this->set('title', $title);
    return $this;
  }
199 200

  /**
201
   * {@inheritdoc}
202
   */
203 204 205
  public function getCreatedTime() {
    return $this->get('created')->value;
  }
206 207 208


  /**
209
   * {@inheritdoc}
210
   */
211 212 213 214
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }
215 216

  /**
217
   * {@inheritdoc}
218
   */
219 220 221
  public function getChangedTime() {
    return $this->get('changed')->value;
  }
222 223

  /**
224
   * {@inheritdoc}
225
   */
226 227 228
  public function isPromoted() {
    return (bool) $this->get('promote')->value;
  }
229 230

  /**
231
   * {@inheritdoc}
232
   */
233
  public function setPromoted($promoted) {
234
    $this->set('promote', $promoted ? NODE_PROMOTED : NODE_NOT_PROMOTED);
235 236
    return $this;
  }
237 238

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

  /**
246
   * {@inheritdoc}
247
   */
248 249 250 251
  public function setSticky($sticky) {
    $this->set('sticky', $sticky ? NODE_STICKY : NODE_NOT_STICKY);
    return $this;
  }
252
  /**
253
   * {@inheritdoc}
254
   */
255 256 257
  public function isPublished() {
    return (bool) $this->get('status')->value;
  }
258

259
  /**
260
   * {@inheritdoc}
261
   */
262 263 264
  public function setPublished($published) {
    $this->set('status', $published ? NODE_PUBLISHED : NODE_NOT_PUBLISHED);
    return $this;
265 266 267
  }

  /**
268
   * {@inheritdoc}
269
   */
270
  public function getOwner() {
271
    return $this->get('uid')->entity;
272
  }
273 274

  /**
275
   * {@inheritdoc}
276
   */
277
  public function getOwnerId() {
278
    return $this->get('uid')->target_id;
279
  }
280

281 282 283
  /**
   * {@inheritdoc}
   */
284
  public function setOwnerId($uid) {
285 286
    $this->set('uid', $uid);
    return $this;
287 288
  }

289 290 291 292 293 294 295 296
  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('uid', $account->id());
    return $this;
  }

297 298 299
  /**
   * {@inheritdoc}
   */
300 301
  public function getRevisionCreationTime() {
    return $this->get('revision_timestamp')->value;
302 303 304 305 306
  }

  /**
   * {@inheritdoc}
   */
307 308 309
  public function setRevisionCreationTime($timestamp) {
    $this->set('revision_timestamp', $timestamp);
    return $this;
310 311
  }

312 313 314
  /**
   * {@inheritdoc}
   */
315 316
  public function getRevisionAuthor() {
    return $this->get('revision_uid')->entity;
317 318
  }

319 320 321
  /**
   * {@inheritdoc}
   */
322 323 324
  public function setRevisionAuthorId($uid) {
    $this->set('revision_uid', $uid);
    return $this;
325 326
  }

327 328 329
  /**
   * {@inheritdoc}
   */
330
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
331
    $fields['nid'] = BaseFieldDefinition::create('integer')
332 333
      ->setLabel(t('Node ID'))
      ->setDescription(t('The node ID.'))
334 335
      ->setReadOnly(TRUE)
      ->setSetting('unsigned', TRUE);
336

337
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
338 339 340 341
      ->setLabel(t('UUID'))
      ->setDescription(t('The node UUID.'))
      ->setReadOnly(TRUE);

342
    $fields['vid'] = BaseFieldDefinition::create('integer')
343 344
      ->setLabel(t('Revision ID'))
      ->setDescription(t('The node revision ID.'))
345 346
      ->setReadOnly(TRUE)
      ->setSetting('unsigned', TRUE);
347

348
    $fields['type'] = BaseFieldDefinition::create('entity_reference')
349 350
      ->setLabel(t('Type'))
      ->setDescription(t('The node type.'))
351
      ->setSetting('target_type', 'node_type')
352 353
      ->setReadOnly(TRUE);

354
    $fields['langcode'] = BaseFieldDefinition::create('language')
355
      ->setLabel(t('Language'))
356
      ->setDescription(t('The node language code.'))
357
      ->setTranslatable(TRUE)
358 359 360 361 362 363 364 365
      ->setRevisionable(TRUE)
      ->setDisplayOptions('view', array(
        'type' => 'hidden',
      ))
      ->setDisplayOptions('form', array(
        'type' => 'language_select',
        'weight' => 2,
      ));
366

367
    $fields['title'] = BaseFieldDefinition::create('string')
368 369 370
      ->setLabel(t('Title'))
      ->setRequired(TRUE)
      ->setTranslatable(TRUE)
371
      ->setRevisionable(TRUE)
372
      ->setDefaultValue('')
373
      ->setSetting('max_length', 255)
374 375
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
376
        'type' => 'string',
377 378 379
        'weight' => -5,
      ))
      ->setDisplayOptions('form', array(
380
        'type' => 'string_textfield',
381 382 383
        'weight' => -5,
      ))
      ->setDisplayConfigurable('form', TRUE);
384

385
    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
386
      ->setLabel(t('Authored by'))
387
      ->setDescription(t('The username of the content author.'))
388
      ->setRevisionable(TRUE)
389
      ->setSetting('target_type', 'user')
390
      ->setSetting('handler', 'default')
391
      ->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
      ->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);
408

409
    $fields['status'] = BaseFieldDefinition::create('boolean')
410
      ->setLabel(t('Publishing status'))
411
      ->setDescription(t('A boolean indicating whether the node is published.'))
412
      ->setRevisionable(TRUE)
413 414
      ->setTranslatable(TRUE)
      ->setDefaultValue(TRUE);
415

416
    $fields['created'] = BaseFieldDefinition::create('created')
417
      ->setLabel(t('Authored on'))
418
      ->setDescription(t('The time that the node was created.'))
419
      ->setRevisionable(TRUE)
420 421 422 423 424 425 426 427 428 429 430
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'timestamp',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'datetime_timestamp',
        'weight' => 10,
      ))
      ->setDisplayConfigurable('form', TRUE);
431

432
    $fields['changed'] = BaseFieldDefinition::create('changed')
433
      ->setLabel(t('Changed'))
434
      ->setDescription(t('The time that the node was last edited.'))
435 436
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);
437

438
    $fields['promote'] = BaseFieldDefinition::create('boolean')
439
      ->setLabel(t('Promoted to front page'))
440
      ->setRevisionable(TRUE)
441
      ->setTranslatable(TRUE)
442 443 444 445 446 447 448 449 450
      ->setDefaultValue(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'boolean_checkbox',
        'settings' => array(
          'display_label' => TRUE,
        ),
        'weight' => 15,
      ))
      ->setDisplayConfigurable('form', TRUE);
451

452
    $fields['sticky'] = BaseFieldDefinition::create('boolean')
453
      ->setLabel(t('Sticky at top of lists'))
454
      ->setRevisionable(TRUE)
455
      ->setTranslatable(TRUE)
456
      ->setDefaultValue(FALSE)
457 458 459 460 461 462 463 464
      ->setDisplayOptions('form', array(
        'type' => 'boolean_checkbox',
        'settings' => array(
          'display_label' => TRUE,
        ),
        'weight' => 16,
      ))
      ->setDisplayConfigurable('form', TRUE);
465

466
    $fields['revision_timestamp'] = BaseFieldDefinition::create('created')
467 468
      ->setLabel(t('Revision timestamp'))
      ->setDescription(t('The time that the current revision was created.'))
469 470
      ->setQueryable(FALSE)
      ->setRevisionable(TRUE);
471

472
    $fields['revision_uid'] = BaseFieldDefinition::create('entity_reference')
473 474
      ->setLabel(t('Revision user ID'))
      ->setDescription(t('The user ID of the author of the current revision.'))
475
      ->setSetting('target_type', 'user')
476 477
      ->setQueryable(FALSE)
      ->setRevisionable(TRUE);
478

479
    $fields['revision_log'] = BaseFieldDefinition::create('string_long')
480
      ->setLabel(t('Revision log message'))
481
      ->setDescription(t('Briefly describe the changes you have made.'))
482
      ->setRevisionable(TRUE)
483 484 485 486 487 488 489 490
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'string_textarea',
        'weight' => 25,
        'settings' => array(
          'rows' => 4,
        ),
      ));
491 492

    return $fields;
493 494
  }

495 496 497 498 499 500 501 502 503 504 505 506
  /**
   * 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());
  }

507
}