Node.php 13.1 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\FieldDefinition;
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
 *   controllers = {
27
 *     "storage" = "Drupal\node\NodeStorage",
28
 *     "view_builder" = "Drupal\node\NodeViewBuilder",
29 30
 *     "access" = "Drupal\node\NodeAccessController",
 *     "form" = {
31
 *       "default" = "Drupal\node\NodeForm",
32
 *       "delete" = "Drupal\node\Form\NodeDeleteForm",
33
 *       "edit" = "Drupal\node\NodeForm"
34
 *     },
35
 *     "list_builder" = "Drupal\node\NodeListBuilder",
36
 *     "translation" = "Drupal\node\NodeTranslationHandler"
37 38
 *   },
 *   base_table = "node",
39
 *   data_table = "node_field_data",
40 41
 *   revision_table = "node_revision",
 *   revision_data_table = "node_field_revision",
42 43
 *   uri_callback = "node_uri",
 *   fieldable = TRUE,
44
 *   translatable = TRUE,
45 46 47 48 49 50 51
 *   entity_keys = {
 *     "id" = "nid",
 *     "revision" = "vid",
 *     "bundle" = "type",
 *     "label" = "title",
 *     "uuid" = "uuid"
 *   },
52
 *   bundle_entity_type = "node_type",
53 54
 *   permission_granularity = "bundle",
 *   links = {
55
 *     "canonical" = "node.view",
56
 *     "delete-form" = "node.delete_confirm",
57
 *     "edit-form" = "node.page_edit",
58 59
 *     "version-history" = "node.revision_overview",
 *     "admin-form" = "node.type_edit"
60
 *   }
61
 * )
62
 */
63
class Node extends ContentEntityBase implements NodeInterface {
64

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  /**
   * {@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());
    }
  }

82
  /**
83
   * {@inheritdoc}
84
   */
85 86
  public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
    parent::preSaveRevision($storage, $record);
87

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

  /**
98
   * {@inheritdoc}
99
   */
100 101
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);
102

103 104 105 106
    // 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()) {
107
      \Drupal::entityManager()->getAccessController('node')->writeGrants($this, $update);
108
    }
109 110 111 112 113 114

    // 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());
    }
115
  }
116 117

  /**
118
   * {@inheritdoc}
119
   */
120 121
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    parent::preDelete($storage, $entities);
122

123 124
    // Assure that all nodes deleted are removed from the search index.
    if (\Drupal::moduleHandler()->moduleExists('search')) {
125
      foreach ($entities as $entity) {
126
        search_reindex($entity->nid->value, 'node_search');
127 128 129
      }
    }
  }
130

131 132 133
  /**
   * {@inheritdoc}
   */
134 135
  public static function postDelete(EntityStorageInterface $storage, array $nodes) {
    parent::postDelete($storage, $nodes);
136 137 138
    \Drupal::service('node.grant_storage')->deleteNodeRecords(array_keys($nodes));
  }

139 140 141 142 143 144 145
  /**
   * {@inheritdoc}
   */
  public function getType() {
    return $this->bundle();
  }

146 147 148 149 150 151 152 153 154
  /**
   * {@inheritdoc}
   */
  public function access($operation = 'view', AccountInterface $account = NULL) {
    if ($operation == 'create') {
      return parent::access($operation, $account);
    }

    return \Drupal::entityManager()
155
      ->getAccessController($this->entityTypeId)
156 157 158 159 160 161 162 163 164 165 166 167 168 169
      ->access($this, $operation, $this->prepareLangcode(), $account);
  }

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


180 181 182 183 184 185 186
  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    return $this->get('title')->value;
  }

187
  /**
188
   * {@inheritdoc}
189
   */
190 191 192 193
  public function setTitle($title) {
    $this->set('title', $title);
    return $this;
  }
194 195

  /**
196
   * {@inheritdoc}
197
   */
198 199 200
  public function getCreatedTime() {
    return $this->get('created')->value;
  }
201 202 203


  /**
204
   * {@inheritdoc}
205
   */
206 207 208 209
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }
210 211

  /**
212
   * {@inheritdoc}
213
   */
214 215 216
  public function getChangedTime() {
    return $this->get('changed')->value;
  }
217 218

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

  /**
226
   * {@inheritdoc}
227
   */
228
  public function setPromoted($promoted) {
229
    $this->set('promote', $promoted ? NODE_PROMOTED : NODE_NOT_PROMOTED);
230 231
    return $this;
  }
232 233

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

  /**
241
   * {@inheritdoc}
242
   */
243 244 245 246
  public function setSticky($sticky) {
    $this->set('sticky', $sticky ? NODE_STICKY : NODE_NOT_STICKY);
    return $this;
  }
247
  /**
248
   * {@inheritdoc}
249
   */
250 251 252
  public function isPublished() {
    return (bool) $this->get('status')->value;
  }
253

254
  /**
255
   * {@inheritdoc}
256
   */
257 258 259
  public function setPublished($published) {
    $this->set('status', $published ? NODE_PUBLISHED : NODE_NOT_PUBLISHED);
    return $this;
260 261 262
  }

  /**
263
   * {@inheritdoc}
264
   */
265
  public function getOwner() {
266
    return $this->get('uid')->entity;
267
  }
268 269

  /**
270
   * {@inheritdoc}
271
   */
272
  public function getOwnerId() {
273
    return $this->get('uid')->target_id;
274
  }
275

276 277 278
  /**
   * {@inheritdoc}
   */
279
  public function setOwnerId($uid) {
280 281
    $this->set('uid', $uid);
    return $this;
282 283
  }

284 285 286 287 288 289 290 291
  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('uid', $account->id());
    return $this;
  }

292 293 294
  /**
   * {@inheritdoc}
   */
295 296
  public function getRevisionCreationTime() {
    return $this->get('revision_timestamp')->value;
297 298 299 300 301
  }

  /**
   * {@inheritdoc}
   */
302 303 304
  public function setRevisionCreationTime($timestamp) {
    $this->set('revision_timestamp', $timestamp);
    return $this;
305 306
  }

307 308 309
  /**
   * {@inheritdoc}
   */
310 311
  public function getRevisionAuthor() {
    return $this->get('revision_uid')->entity;
312 313
  }

314 315 316
  /**
   * {@inheritdoc}
   */
317 318 319
  public function setRevisionAuthorId($uid) {
    $this->set('revision_uid', $uid);
    return $this;
320 321
  }

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

    $fields['uuid'] = FieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The node UUID.'))
      ->setReadOnly(TRUE);

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

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

    $fields['langcode'] = FieldDefinition::create('language')
      ->setLabel(t('Language code'))
351 352
      ->setDescription(t('The node language code.'))
      ->setRevisionable(TRUE);
353

354
    $fields['title'] = FieldDefinition::create('string')
355 356 357 358
      ->setLabel(t('Title'))
      ->setDescription(t('The title of this node, always treated as non-markup plain text.'))
      ->setRequired(TRUE)
      ->setTranslatable(TRUE)
359
      ->setRevisionable(TRUE)
360
      ->setDefaultValue('')
361
      ->setSetting('max_length', 255)
362 363
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
364
        'type' => 'string',
365 366 367
        'weight' => -5,
      ))
      ->setDisplayOptions('form', array(
368
        'type' => 'string',
369 370 371
        'weight' => -5,
      ))
      ->setDisplayConfigurable('form', TRUE);
372 373

    $fields['uid'] = FieldDefinition::create('entity_reference')
374 375
      ->setLabel(t('Author'))
      ->setDescription(t('The user that is the node author.'))
376
      ->setRevisionable(TRUE)
377
      ->setSetting('target_type', 'user')
378
      ->setTranslatable(TRUE);
379 380 381

    $fields['status'] = FieldDefinition::create('boolean')
      ->setLabel(t('Publishing status'))
382
      ->setDescription(t('A boolean indicating whether the node is published.'))
383 384
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);
385

386
    $fields['created'] = FieldDefinition::create('created')
387
      ->setLabel(t('Created'))
388
      ->setDescription(t('The time that the node was created.'))
389 390
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);
391

392
    $fields['changed'] = FieldDefinition::create('changed')
393
      ->setLabel(t('Changed'))
394
      ->setDescription(t('The time that the node was last edited.'))
395 396
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);
397 398 399

    $fields['promote'] = FieldDefinition::create('boolean')
      ->setLabel(t('Promote'))
400
      ->setDescription(t('A boolean indicating whether the node should be displayed on the front page.'))
401 402
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);
403 404 405

    $fields['sticky'] = FieldDefinition::create('boolean')
      ->setLabel(t('Sticky'))
406
      ->setDescription(t('A boolean indicating whether the node should be displayed at the top of lists in which it appears.'))
407 408
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);
409

410
    $fields['revision_timestamp'] = FieldDefinition::create('created')
411 412
      ->setLabel(t('Revision timestamp'))
      ->setDescription(t('The time that the current revision was created.'))
413 414
      ->setQueryable(FALSE)
      ->setRevisionable(TRUE);
415 416 417 418

    $fields['revision_uid'] = FieldDefinition::create('entity_reference')
      ->setLabel(t('Revision user ID'))
      ->setDescription(t('The user ID of the author of the current revision.'))
419
      ->setSetting('target_type', 'user')
420 421
      ->setQueryable(FALSE)
      ->setRevisionable(TRUE);
422

423 424
    $fields['revision_log'] = FieldDefinition::create('string_long')
      ->setLabel(t('Revision log message'))
425
      ->setDescription(t('The log entry explaining the changes in this revision.'))
426 427
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);
428 429

    return $fields;
430 431
  }

432 433 434 435 436 437
  /**
   * {@inheritdoc}
   */
  public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
    $node_type = node_type_load($bundle);
    $fields = array();
438 439 440 441 442 443 444 445 446 447 448

    // When deleting a node type the corresponding node displays are deleted as
    // well. In order to be deleted, they need to be loaded first. Entity
    // displays, however, fetch the field definitions of the respective entity
    // type to fill in their defaults. Therefore this function ends up being
    // called with a non-existing bundle.
    // @todo Fix this in https://drupal.org/node/2248795
    if (!$node_type) {
      return $fields;
    }

449 450 451 452
    if (isset($node_type->title_label)) {
      $fields['title'] = clone $base_field_definitions['title'];
      $fields['title']->setLabel($node_type->title_label);
    }
453 454 455

    $options = $node_type->getModuleSettings('node')['options'];
    $fields['status'] = clone $base_field_definitions['status'];
456
    $fields['status']->setDefaultValue(!empty($options['status']) ? NODE_PUBLISHED : NODE_NOT_PUBLISHED);
457
    $fields['promote'] = clone $base_field_definitions['promote'];
458
    $fields['promote']->setDefaultValue(!empty($options['promote']) ? NODE_PROMOTED : NODE_NOT_PROMOTED);
459
    $fields['sticky'] = clone $base_field_definitions['sticky'];
460
    $fields['sticky']->setDefaultValue(!empty($options['sticky']) ? NODE_STICKY : NODE_NOT_STICKY);
461

462 463 464
    return $fields;
  }

465
}