3 namespace Drupal\comment\Entity;
5 use Drupal\Component\Utility\Number;
6 use Drupal\Core\Cache\Cache;
7 use Drupal\Core\Entity\ContentEntityBase;
8 use Drupal\comment\CommentInterface;
9 use Drupal\Core\Entity\EntityChangedTrait;
10 use Drupal\Core\Entity\EntityPublishedTrait;
11 use Drupal\Core\Entity\EntityStorageInterface;
12 use Drupal\Core\Entity\EntityTypeInterface;
13 use Drupal\Core\Field\BaseFieldDefinition;
14 use Drupal\field\Entity\FieldStorageConfig;
15 use Drupal\user\Entity\User;
16 use Drupal\user\UserInterface;
19 * Defines the comment entity class.
23 * label = @Translation("Comment"),
24 * label_singular = @Translation("comment"),
25 * label_plural = @Translation("comments"),
26 * label_count = @PluralTranslation(
27 * singular = "@count comment",
28 * plural = "@count comments",
30 * bundle_label = @Translation("Comment type"),
32 * "storage" = "Drupal\comment\CommentStorage",
33 * "storage_schema" = "Drupal\comment\CommentStorageSchema",
34 * "access" = "Drupal\comment\CommentAccessControlHandler",
35 * "list_builder" = "Drupal\Core\Entity\EntityListBuilder",
36 * "view_builder" = "Drupal\comment\CommentViewBuilder",
37 * "views_data" = "Drupal\comment\CommentViewsData",
39 * "default" = "Drupal\comment\CommentForm",
40 * "delete" = "Drupal\comment\Form\DeleteForm"
42 * "translation" = "Drupal\comment\CommentTranslationHandler"
44 * base_table = "comment",
45 * data_table = "comment_field_data",
46 * uri_callback = "comment_uri",
47 * translatable = TRUE,
50 * "bundle" = "comment_type",
51 * "label" = "subject",
52 * "langcode" = "langcode",
54 * "published" = "status",
57 * "canonical" = "/comment/{comment}",
58 * "delete-form" = "/comment/{comment}/delete",
59 * "edit-form" = "/comment/{comment}/edit",
61 * bundle_entity_type = "comment_type",
62 * field_ui_base_route = "entity.comment_type.edit_form",
68 class Comment extends ContentEntityBase implements CommentInterface {
70 use EntityChangedTrait;
71 use EntityPublishedTrait;
74 * The thread for which a lock was acquired.
76 protected $threadLock = '';
81 public function preSave(EntityStorageInterface $storage) {
82 parent::preSave($storage);
85 // Add the comment to database. This next section builds the thread field.
86 // @see \Drupal\comment\CommentViewBuilder::buildComponents()
87 $thread = $this->getThread();
89 if ($this->threadLock) {
90 // Thread lock was not released after being set previously.
91 // This suggests there's a bug in code using this class.
92 throw new \LogicException('preSave() is called again without calling postSave() or releaseThreadLock()');
94 if (!$this->hasParentComment()) {
95 // This is a comment with no parent comment (depth 0): we start
96 // by retrieving the maximum thread level.
97 $max = $storage->getMaxThread($this);
98 // Strip the "/" from the end of the thread.
99 $max = rtrim($max, '/');
100 // We need to get the value at the correct depth.
101 $parts = explode('.', $max);
102 $n = Number::alphadecimalToInt($parts[0]);
106 // This is a comment with a parent comment, so increase the part of
107 // the thread value at the proper depth.
109 // Get the parent comment:
110 $parent = $this->getParentComment();
111 // Strip the "/" from the end of the parent thread.
112 $parent->setThread((string) rtrim((string) $parent->getThread(), '/'));
113 $prefix = $parent->getThread() . '.';
114 // Get the max value in *this* thread.
115 $max = $storage->getMaxThreadPerThread($this);
118 // First child of this parent. As the other two cases do an
119 // increment of the thread number before creating the thread
120 // string set this to -1 so it requires an increment too.
124 // Strip the "/" at the end of the thread.
125 $max = rtrim($max, '/');
126 // Get the value at the correct depth.
127 $parts = explode('.', $max);
128 $parent_depth = count(explode('.', $parent->getThread()));
129 $n = Number::alphadecimalToInt($parts[$parent_depth]);
132 // Finally, build the thread field for this new comment. To avoid
133 // race conditions, get a lock on the thread. If another process already
134 // has the lock, just move to the next integer.
136 $thread = $prefix . Number::intToAlphadecimal(++$n) . '/';
137 $lock_name = "comment:{$this->getCommentedEntityId()}:$thread";
138 } while (!\Drupal::lock()->acquire($lock_name));
139 $this->threadLock = $lock_name;
141 // We test the value with '===' because we need to modify anonymous
143 if ($this->getOwnerId() === \Drupal::currentUser()->id() && \Drupal::currentUser()->isAuthenticated()) {
144 $this->setAuthorName(\Drupal::currentUser()->getUsername());
146 $this->setThread($thread);
147 if (!$this->getHostname()) {
148 // Ensure a client host from the current request.
149 $this->setHostname(\Drupal::request()->getClientIP());
157 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
158 parent::postSave($storage, $update);
160 // Always invalidate the cache tag for the commented entity.
161 if ($commented_entity = $this->getCommentedEntity()) {
162 Cache::invalidateTags($commented_entity->getCacheTagsToInvalidate());
165 $this->releaseThreadLock();
166 // Update the {comment_entity_statistics} table prior to executing the hook.
167 \Drupal::service('comment.statistics')->update($this);
171 * Release the lock acquired for the thread in preSave().
173 protected function releaseThreadLock() {
174 if ($this->threadLock) {
175 \Drupal::lock()->release($this->threadLock);
176 $this->threadLock = '';
183 public static function postDelete(EntityStorageInterface $storage, array $entities) {
184 parent::postDelete($storage, $entities);
186 $child_cids = $storage->getChildCids($entities);
187 entity_delete_multiple('comment', $child_cids);
189 foreach ($entities as $id => $entity) {
190 \Drupal::service('comment.statistics')->update($entity);
197 public function referencedEntities() {
198 $referenced_entities = parent::referencedEntities();
199 if ($this->getCommentedEntityId()) {
200 $referenced_entities[] = $this->getCommentedEntity();
202 return $referenced_entities;
208 public function permalink() {
209 $uri = $this->urlInfo();
210 $uri->setOption('fragment', 'comment-' . $this->id());
217 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
218 /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
219 $fields = parent::baseFieldDefinitions($entity_type);
220 $fields += static::publishedBaseFieldDefinitions($entity_type);
222 $fields['cid']->setLabel(t('Comment ID'))
223 ->setDescription(t('The comment ID.'));
225 $fields['uuid']->setDescription(t('The comment UUID.'));
227 $fields['comment_type']->setLabel(t('Comment Type'))
228 ->setDescription(t('The comment type.'));
230 $fields['langcode']->setDescription(t('The comment language code.'));
232 // Set the default value callback for the status field.
233 $fields['status']->setDefaultValueCallback('Drupal\comment\Entity\Comment::getDefaultStatus');
235 $fields['pid'] = BaseFieldDefinition::create('entity_reference')
236 ->setLabel(t('Parent ID'))
237 ->setDescription(t('The parent comment ID if this is a reply to a comment.'))
238 ->setSetting('target_type', 'comment');
240 $fields['entity_id'] = BaseFieldDefinition::create('entity_reference')
241 ->setLabel(t('Entity ID'))
242 ->setDescription(t('The ID of the entity of which this comment is a reply.'))
245 $fields['subject'] = BaseFieldDefinition::create('string')
246 ->setLabel(t('Subject'))
247 ->setTranslatable(TRUE)
248 ->setSetting('max_length', 64)
249 ->setDisplayOptions('form', [
250 'type' => 'string_textfield',
251 // Default comment body field has weight 20.
254 ->setDisplayConfigurable('form', TRUE);
256 $fields['uid'] = BaseFieldDefinition::create('entity_reference')
257 ->setLabel(t('User ID'))
258 ->setDescription(t('The user ID of the comment author.'))
259 ->setTranslatable(TRUE)
260 ->setSetting('target_type', 'user')
261 ->setDefaultValue(0);
263 $fields['name'] = BaseFieldDefinition::create('string')
264 ->setLabel(t('Name'))
265 ->setDescription(t("The comment author's name."))
266 ->setTranslatable(TRUE)
267 ->setSetting('max_length', 60)
268 ->setDefaultValue('');
270 $fields['mail'] = BaseFieldDefinition::create('email')
271 ->setLabel(t('Email'))
272 ->setDescription(t("The comment author's email address."))
273 ->setTranslatable(TRUE);
275 $fields['homepage'] = BaseFieldDefinition::create('uri')
276 ->setLabel(t('Homepage'))
277 ->setDescription(t("The comment author's home page address."))
278 ->setTranslatable(TRUE)
279 // URIs are not length limited by RFC 2616, but we can only store 255
280 // characters in our comment DB schema.
281 ->setSetting('max_length', 255);
283 $fields['hostname'] = BaseFieldDefinition::create('string')
284 ->setLabel(t('Hostname'))
285 ->setDescription(t("The comment author's hostname."))
286 ->setTranslatable(TRUE)
287 ->setSetting('max_length', 128);
289 $fields['created'] = BaseFieldDefinition::create('created')
290 ->setLabel(t('Created'))
291 ->setDescription(t('The time that the comment was created.'))
292 ->setTranslatable(TRUE);
294 $fields['changed'] = BaseFieldDefinition::create('changed')
295 ->setLabel(t('Changed'))
296 ->setDescription(t('The time that the comment was last edited.'))
297 ->setTranslatable(TRUE);
299 $fields['thread'] = BaseFieldDefinition::create('string')
300 ->setLabel(t('Thread place'))
301 ->setDescription(t("The alphadecimal representation of the comment's place in a thread, consisting of a base 36 string prefixed by an integer indicating its length."))
302 ->setSetting('max_length', 255);
304 $fields['entity_type'] = BaseFieldDefinition::create('string')
305 ->setLabel(t('Entity type'))
306 ->setDescription(t('The entity type to which this comment is attached.'))
307 ->setSetting('is_ascii', TRUE)
308 ->setSetting('max_length', EntityTypeInterface::ID_MAX_LENGTH);
310 $fields['field_name'] = BaseFieldDefinition::create('string')
311 ->setLabel(t('Comment field name'))
312 ->setDescription(t('The field name through which this comment was added.'))
313 ->setSetting('is_ascii', TRUE)
314 ->setSetting('max_length', FieldStorageConfig::NAME_MAX_LENGTH);
322 public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
323 if ($comment_type = CommentType::load($bundle)) {
324 $fields['entity_id'] = clone $base_field_definitions['entity_id'];
325 $fields['entity_id']->setSetting('target_type', $comment_type->getTargetEntityTypeId());
334 public function hasParentComment() {
335 return (bool) $this->get('pid')->target_id;
341 public function getParentComment() {
342 return $this->get('pid')->entity;
348 public function getCommentedEntity() {
349 return $this->get('entity_id')->entity;
355 public function getCommentedEntityId() {
356 return $this->get('entity_id')->target_id;
362 public function getCommentedEntityTypeId() {
363 return $this->get('entity_type')->value;
369 public function setFieldName($field_name) {
370 $this->set('field_name', $field_name);
377 public function getFieldName() {
378 return $this->get('field_name')->value;
384 public function getSubject() {
385 return $this->get('subject')->value;
391 public function setSubject($subject) {
392 $this->set('subject', $subject);
399 public function getAuthorName() {
400 if ($this->get('uid')->target_id) {
401 return $this->get('uid')->entity->label();
403 return $this->get('name')->value ?: \Drupal::config('user.settings')->get('anonymous');
409 public function setAuthorName($name) {
410 $this->set('name', $name);
417 public function getAuthorEmail() {
418 $mail = $this->get('mail')->value;
420 if ($this->get('uid')->target_id != 0) {
421 $mail = $this->get('uid')->entity->getEmail();
430 public function getHomepage() {
431 return $this->get('homepage')->value;
437 public function setHomepage($homepage) {
438 $this->set('homepage', $homepage);
445 public function getHostname() {
446 return $this->get('hostname')->value;
452 public function setHostname($hostname) {
453 $this->set('hostname', $hostname);
460 public function getCreatedTime() {
461 if (isset($this->get('created')->value)) {
462 return $this->get('created')->value;
470 public function setCreatedTime($created) {
471 $this->set('created', $created);
478 public function getStatus() {
479 return $this->get('status')->value;
485 public function getThread() {
486 $thread = $this->get('thread');
487 if (!empty($thread->value)) {
488 return $thread->value;
495 public function setThread($thread) {
496 $this->set('thread', $thread);
503 public static function preCreate(EntityStorageInterface $storage, array &$values) {
504 if (empty($values['comment_type']) && !empty($values['field_name']) && !empty($values['entity_type'])) {
505 $field_storage = FieldStorageConfig::loadByName($values['entity_type'], $values['field_name']);
506 $values['comment_type'] = $field_storage->getSetting('comment_type');
513 public function getOwner() {
514 $user = $this->get('uid')->entity;
515 if (!$user || $user->isAnonymous()) {
516 $user = User::getAnonymousUser();
517 $user->name = $this->getAuthorName();
518 $user->homepage = $this->getHomepage();
526 public function getOwnerId() {
527 return $this->get('uid')->target_id;
533 public function setOwnerId($uid) {
534 $this->set('uid', $uid);
541 public function setOwner(UserInterface $account) {
542 $this->set('uid', $account->id());
547 * Get the comment type ID for this comment.
550 * The ID of the comment type.
552 public function getTypeId() {
553 return $this->bundle();
557 * Default value callback for 'status' base field definition.
559 * @see ::baseFieldDefinitions()
562 * TRUE if the comment should be published, FALSE otherwise.
564 public static function getDefaultStatus() {
565 return \Drupal::currentUser()->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;