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",
60 * "create" = "/comment",
62 * bundle_entity_type = "comment_type",
63 * field_ui_base_route = "entity.comment_type.edit_form",
69 class Comment extends ContentEntityBase implements CommentInterface {
71 use EntityChangedTrait;
72 use EntityPublishedTrait;
75 * The thread for which a lock was acquired.
79 protected $threadLock = '';
84 public function preSave(EntityStorageInterface $storage) {
85 parent::preSave($storage);
88 // Add the comment to database. This next section builds the thread field.
89 // @see \Drupal\comment\CommentViewBuilder::buildComponents()
90 $thread = $this->getThread();
92 if ($this->threadLock) {
93 // Thread lock was not released after being set previously.
94 // This suggests there's a bug in code using this class.
95 throw new \LogicException('preSave() is called again without calling postSave() or releaseThreadLock()');
97 if (!$this->hasParentComment()) {
98 // This is a comment with no parent comment (depth 0): we start
99 // by retrieving the maximum thread level.
100 $max = $storage->getMaxThread($this);
101 // Strip the "/" from the end of the thread.
102 $max = rtrim($max, '/');
103 // We need to get the value at the correct depth.
104 $parts = explode('.', $max);
105 $n = Number::alphadecimalToInt($parts[0]);
109 // This is a comment with a parent comment, so increase the part of
110 // the thread value at the proper depth.
112 // Get the parent comment:
113 $parent = $this->getParentComment();
114 // Strip the "/" from the end of the parent thread.
115 $parent->setThread((string) rtrim((string) $parent->getThread(), '/'));
116 $prefix = $parent->getThread() . '.';
117 // Get the max value in *this* thread.
118 $max = $storage->getMaxThreadPerThread($this);
121 // First child of this parent. As the other two cases do an
122 // increment of the thread number before creating the thread
123 // string set this to -1 so it requires an increment too.
127 // Strip the "/" at the end of the thread.
128 $max = rtrim($max, '/');
129 // Get the value at the correct depth.
130 $parts = explode('.', $max);
131 $parent_depth = count(explode('.', $parent->getThread()));
132 $n = Number::alphadecimalToInt($parts[$parent_depth]);
135 // Finally, build the thread field for this new comment. To avoid
136 // race conditions, get a lock on the thread. If another process already
137 // has the lock, just move to the next integer.
139 $thread = $prefix . Number::intToAlphadecimal(++$n) . '/';
140 $lock_name = "comment:{$this->getCommentedEntityId()}:$thread";
141 } while (!\Drupal::lock()->acquire($lock_name));
142 $this->threadLock = $lock_name;
144 $this->setThread($thread);
145 if (!$this->getHostname()) {
146 // Ensure a client host from the current request.
147 $this->setHostname(\Drupal::request()->getClientIP());
150 // The entity fields for name and mail have no meaning if the user is not
151 // Anonymous. Set them to NULL to make it clearer that they are not used.
152 // For anonymous users see \Drupal\comment\CommentForm::form() for mail,
153 // and \Drupal\comment\CommentForm::buildEntity() for name setting.
154 if (!$this->getOwner()->isAnonymous()) {
155 $this->set('name', NULL);
156 $this->set('mail', NULL);
163 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
164 parent::postSave($storage, $update);
166 // Always invalidate the cache tag for the commented entity.
167 if ($commented_entity = $this->getCommentedEntity()) {
168 Cache::invalidateTags($commented_entity->getCacheTagsToInvalidate());
171 $this->releaseThreadLock();
172 // Update the {comment_entity_statistics} table prior to executing the hook.
173 \Drupal::service('comment.statistics')->update($this);
177 * Release the lock acquired for the thread in preSave().
179 protected function releaseThreadLock() {
180 if ($this->threadLock) {
181 \Drupal::lock()->release($this->threadLock);
182 $this->threadLock = '';
189 public static function postDelete(EntityStorageInterface $storage, array $entities) {
190 parent::postDelete($storage, $entities);
192 $child_cids = $storage->getChildCids($entities);
193 entity_delete_multiple('comment', $child_cids);
195 foreach ($entities as $id => $entity) {
196 \Drupal::service('comment.statistics')->update($entity);
203 public function referencedEntities() {
204 $referenced_entities = parent::referencedEntities();
205 if ($this->getCommentedEntityId()) {
206 $referenced_entities[] = $this->getCommentedEntity();
208 return $referenced_entities;
214 public function permalink() {
215 $uri = $this->urlInfo();
216 $uri->setOption('fragment', 'comment-' . $this->id());
223 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
224 /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
225 $fields = parent::baseFieldDefinitions($entity_type);
226 $fields += static::publishedBaseFieldDefinitions($entity_type);
228 $fields['cid']->setLabel(t('Comment ID'))
229 ->setDescription(t('The comment ID.'));
231 $fields['uuid']->setDescription(t('The comment UUID.'));
233 $fields['comment_type']->setLabel(t('Comment Type'))
234 ->setDescription(t('The comment type.'));
236 $fields['langcode']->setDescription(t('The comment language code.'));
238 // Set the default value callback for the status field.
239 $fields['status']->setDefaultValueCallback('Drupal\comment\Entity\Comment::getDefaultStatus');
241 $fields['pid'] = BaseFieldDefinition::create('entity_reference')
242 ->setLabel(t('Parent ID'))
243 ->setDescription(t('The parent comment ID if this is a reply to a comment.'))
244 ->setSetting('target_type', 'comment');
246 $fields['entity_id'] = BaseFieldDefinition::create('entity_reference')
247 ->setLabel(t('Entity ID'))
248 ->setDescription(t('The ID of the entity of which this comment is a reply.'))
251 $fields['subject'] = BaseFieldDefinition::create('string')
252 ->setLabel(t('Subject'))
253 ->setTranslatable(TRUE)
254 ->setSetting('max_length', 64)
255 ->setDisplayOptions('form', [
256 'type' => 'string_textfield',
257 // Default comment body field has weight 20.
260 ->setDisplayConfigurable('form', TRUE);
262 $fields['uid'] = BaseFieldDefinition::create('entity_reference')
263 ->setLabel(t('User ID'))
264 ->setDescription(t('The user ID of the comment author.'))
265 ->setTranslatable(TRUE)
266 ->setSetting('target_type', 'user')
267 ->setDefaultValue(0);
269 $fields['name'] = BaseFieldDefinition::create('string')
270 ->setLabel(t('Name'))
271 ->setDescription(t("The comment author's name."))
272 ->setTranslatable(TRUE)
273 ->setSetting('max_length', 60)
274 ->setDefaultValue('');
276 $fields['mail'] = BaseFieldDefinition::create('email')
277 ->setLabel(t('Email'))
278 ->setDescription(t("The comment author's email address."))
279 ->setTranslatable(TRUE);
281 $fields['homepage'] = BaseFieldDefinition::create('uri')
282 ->setLabel(t('Homepage'))
283 ->setDescription(t("The comment author's home page address."))
284 ->setTranslatable(TRUE)
285 // URIs are not length limited by RFC 2616, but we can only store 255
286 // characters in our comment DB schema.
287 ->setSetting('max_length', 255);
289 $fields['hostname'] = BaseFieldDefinition::create('string')
290 ->setLabel(t('Hostname'))
291 ->setDescription(t("The comment author's hostname."))
292 ->setTranslatable(TRUE)
293 ->setSetting('max_length', 128);
295 $fields['created'] = BaseFieldDefinition::create('created')
296 ->setLabel(t('Created'))
297 ->setDescription(t('The time that the comment was created.'))
298 ->setTranslatable(TRUE);
300 $fields['changed'] = BaseFieldDefinition::create('changed')
301 ->setLabel(t('Changed'))
302 ->setDescription(t('The time that the comment was last edited.'))
303 ->setTranslatable(TRUE);
305 $fields['thread'] = BaseFieldDefinition::create('string')
306 ->setLabel(t('Thread place'))
307 ->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."))
308 ->setSetting('max_length', 255);
310 $fields['entity_type'] = BaseFieldDefinition::create('string')
311 ->setLabel(t('Entity type'))
312 ->setDescription(t('The entity type to which this comment is attached.'))
313 ->setSetting('is_ascii', TRUE)
314 ->setSetting('max_length', EntityTypeInterface::ID_MAX_LENGTH);
316 $fields['field_name'] = BaseFieldDefinition::create('string')
317 ->setLabel(t('Comment field name'))
318 ->setDescription(t('The field name through which this comment was added.'))
319 ->setSetting('is_ascii', TRUE)
320 ->setSetting('max_length', FieldStorageConfig::NAME_MAX_LENGTH);
328 public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
329 if ($comment_type = CommentType::load($bundle)) {
330 $fields['entity_id'] = clone $base_field_definitions['entity_id'];
331 $fields['entity_id']->setSetting('target_type', $comment_type->getTargetEntityTypeId());
340 public function hasParentComment() {
341 return (bool) $this->get('pid')->target_id;
347 public function getParentComment() {
348 return $this->get('pid')->entity;
354 public function getCommentedEntity() {
355 return $this->get('entity_id')->entity;
361 public function getCommentedEntityId() {
362 return $this->get('entity_id')->target_id;
368 public function getCommentedEntityTypeId() {
369 return $this->get('entity_type')->value;
375 public function setFieldName($field_name) {
376 $this->set('field_name', $field_name);
383 public function getFieldName() {
384 return $this->get('field_name')->value;
390 public function getSubject() {
391 return $this->get('subject')->value;
397 public function setSubject($subject) {
398 $this->set('subject', $subject);
405 public function getAuthorName() {
406 if ($this->get('uid')->target_id) {
407 return $this->get('uid')->entity->label();
409 return $this->get('name')->value ?: \Drupal::config('user.settings')->get('anonymous');
415 public function setAuthorName($name) {
416 $this->set('name', $name);
423 public function getAuthorEmail() {
424 $mail = $this->get('mail')->value;
426 if ($this->get('uid')->target_id != 0) {
427 $mail = $this->get('uid')->entity->getEmail();
436 public function getHomepage() {
437 return $this->get('homepage')->value;
443 public function setHomepage($homepage) {
444 $this->set('homepage', $homepage);
451 public function getHostname() {
452 return $this->get('hostname')->value;
458 public function setHostname($hostname) {
459 $this->set('hostname', $hostname);
466 public function getCreatedTime() {
467 if (isset($this->get('created')->value)) {
468 return $this->get('created')->value;
476 public function setCreatedTime($created) {
477 $this->set('created', $created);
484 public function getStatus() {
485 return $this->get('status')->value;
491 public function getThread() {
492 $thread = $this->get('thread');
493 if (!empty($thread->value)) {
494 return $thread->value;
501 public function setThread($thread) {
502 $this->set('thread', $thread);
509 public static function preCreate(EntityStorageInterface $storage, array &$values) {
510 if (empty($values['comment_type']) && !empty($values['field_name']) && !empty($values['entity_type'])) {
511 $field_storage = FieldStorageConfig::loadByName($values['entity_type'], $values['field_name']);
512 $values['comment_type'] = $field_storage->getSetting('comment_type');
519 public function getOwner() {
520 $user = $this->get('uid')->entity;
521 if (!$user || $user->isAnonymous()) {
522 $user = User::getAnonymousUser();
523 $user->name = $this->getAuthorName();
524 $user->homepage = $this->getHomepage();
532 public function getOwnerId() {
533 return $this->get('uid')->target_id;
539 public function setOwnerId($uid) {
540 $this->set('uid', $uid);
547 public function setOwner(UserInterface $account) {
548 $this->set('uid', $account->id());
553 * Get the comment type ID for this comment.
556 * The ID of the comment type.
558 public function getTypeId() {
559 return $this->bundle();
563 * Default value callback for 'status' base field definition.
565 * @see ::baseFieldDefinitions()
568 * TRUE if the comment should be published, FALSE otherwise.
570 public static function getDefaultStatus() {
571 return \Drupal::currentUser()->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;