Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / comment / src / Entity / Comment.php
1 <?php
2
3 namespace Drupal\comment\Entity;
4
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;
17
18 /**
19  * Defines the comment entity class.
20  *
21  * @ContentEntityType(
22  *   id = "comment",
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",
29  *   ),
30  *   bundle_label = @Translation("Comment type"),
31  *   handlers = {
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",
38  *     "form" = {
39  *       "default" = "Drupal\comment\CommentForm",
40  *       "delete" = "Drupal\comment\Form\DeleteForm"
41  *     },
42  *     "translation" = "Drupal\comment\CommentTranslationHandler"
43  *   },
44  *   base_table = "comment",
45  *   data_table = "comment_field_data",
46  *   uri_callback = "comment_uri",
47  *   translatable = TRUE,
48  *   entity_keys = {
49  *     "id" = "cid",
50  *     "bundle" = "comment_type",
51  *     "label" = "subject",
52  *     "langcode" = "langcode",
53  *     "uuid" = "uuid",
54  *     "published" = "status",
55  *   },
56  *   links = {
57  *     "canonical" = "/comment/{comment}",
58  *     "delete-form" = "/comment/{comment}/delete",
59  *     "edit-form" = "/comment/{comment}/edit",
60  *     "create" = "/comment",
61  *   },
62  *   bundle_entity_type = "comment_type",
63  *   field_ui_base_route  = "entity.comment_type.edit_form",
64  *   constraints = {
65  *     "CommentName" = {}
66  *   }
67  * )
68  */
69 class Comment extends ContentEntityBase implements CommentInterface {
70
71   use EntityChangedTrait;
72   use EntityPublishedTrait;
73
74   /**
75    * The thread for which a lock was acquired.
76    *
77    * @var string
78    */
79   protected $threadLock = '';
80
81   /**
82    * {@inheritdoc}
83    */
84   public function preSave(EntityStorageInterface $storage) {
85     parent::preSave($storage);
86
87     if ($this->isNew()) {
88       // Add the comment to database. This next section builds the thread field.
89       // @see \Drupal\comment\CommentViewBuilder::buildComponents()
90       $thread = $this->getThread();
91       if (empty($thread)) {
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()');
96         }
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]);
106           $prefix = '';
107         }
108         else {
109           // This is a comment with a parent comment, so increase the part of
110           // the thread value at the proper depth.
111
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);
119
120           if ($max == '') {
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.
124             $n = -1;
125           }
126           else {
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]);
133           }
134         }
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.
138         do {
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;
143       }
144       $this->setThread($thread);
145       if (!$this->getHostname()) {
146         // Ensure a client host from the current request.
147         $this->setHostname(\Drupal::request()->getClientIP());
148       }
149     }
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);
157     }
158   }
159
160   /**
161    * {@inheritdoc}
162    */
163   public function postSave(EntityStorageInterface $storage, $update = TRUE) {
164     parent::postSave($storage, $update);
165
166     // Always invalidate the cache tag for the commented entity.
167     if ($commented_entity = $this->getCommentedEntity()) {
168       Cache::invalidateTags($commented_entity->getCacheTagsToInvalidate());
169     }
170
171     $this->releaseThreadLock();
172     // Update the {comment_entity_statistics} table prior to executing the hook.
173     \Drupal::service('comment.statistics')->update($this);
174   }
175
176   /**
177    * Release the lock acquired for the thread in preSave().
178    */
179   protected function releaseThreadLock() {
180     if ($this->threadLock) {
181       \Drupal::lock()->release($this->threadLock);
182       $this->threadLock = '';
183     }
184   }
185
186   /**
187    * {@inheritdoc}
188    */
189   public static function postDelete(EntityStorageInterface $storage, array $entities) {
190     parent::postDelete($storage, $entities);
191
192     $child_cids = $storage->getChildCids($entities);
193     entity_delete_multiple('comment', $child_cids);
194
195     foreach ($entities as $id => $entity) {
196       \Drupal::service('comment.statistics')->update($entity);
197     }
198   }
199
200   /**
201    * {@inheritdoc}
202    */
203   public function referencedEntities() {
204     $referenced_entities = parent::referencedEntities();
205     if ($this->getCommentedEntityId()) {
206       $referenced_entities[] = $this->getCommentedEntity();
207     }
208     return $referenced_entities;
209   }
210
211   /**
212    * {@inheritdoc}
213    */
214   public function permalink() {
215     $uri = $this->urlInfo();
216     $uri->setOption('fragment', 'comment-' . $this->id());
217     return $uri;
218   }
219
220   /**
221    * {@inheritdoc}
222    */
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);
227
228     $fields['cid']->setLabel(t('Comment ID'))
229       ->setDescription(t('The comment ID.'));
230
231     $fields['uuid']->setDescription(t('The comment UUID.'));
232
233     $fields['comment_type']->setLabel(t('Comment Type'))
234       ->setDescription(t('The comment type.'));
235
236     $fields['langcode']->setDescription(t('The comment language code.'));
237
238     // Set the default value callback for the status field.
239     $fields['status']->setDefaultValueCallback('Drupal\comment\Entity\Comment::getDefaultStatus');
240
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');
245
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.'))
249       ->setRequired(TRUE);
250
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.
258         'weight' => 10,
259       ])
260       ->setDisplayConfigurable('form', TRUE);
261
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);
268
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('');
275
276     $fields['mail'] = BaseFieldDefinition::create('email')
277       ->setLabel(t('Email'))
278       ->setDescription(t("The comment author's email address."))
279       ->setTranslatable(TRUE);
280
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);
288
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);
294
295     $fields['created'] = BaseFieldDefinition::create('created')
296       ->setLabel(t('Created'))
297       ->setDescription(t('The time that the comment was created.'))
298       ->setTranslatable(TRUE);
299
300     $fields['changed'] = BaseFieldDefinition::create('changed')
301       ->setLabel(t('Changed'))
302       ->setDescription(t('The time that the comment was last edited.'))
303       ->setTranslatable(TRUE);
304
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);
309
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);
315
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);
321
322     return $fields;
323   }
324
325   /**
326    * {@inheritdoc}
327    */
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());
332       return $fields;
333     }
334     return [];
335   }
336
337   /**
338    * {@inheritdoc}
339    */
340   public function hasParentComment() {
341     return (bool) $this->get('pid')->target_id;
342   }
343
344   /**
345    * {@inheritdoc}
346    */
347   public function getParentComment() {
348     return $this->get('pid')->entity;
349   }
350
351   /**
352    * {@inheritdoc}
353    */
354   public function getCommentedEntity() {
355     return $this->get('entity_id')->entity;
356   }
357
358   /**
359    * {@inheritdoc}
360    */
361   public function getCommentedEntityId() {
362     return $this->get('entity_id')->target_id;
363   }
364
365   /**
366    * {@inheritdoc}
367    */
368   public function getCommentedEntityTypeId() {
369     return $this->get('entity_type')->value;
370   }
371
372   /**
373    * {@inheritdoc}
374    */
375   public function setFieldName($field_name) {
376     $this->set('field_name', $field_name);
377     return $this;
378   }
379
380   /**
381    * {@inheritdoc}
382    */
383   public function getFieldName() {
384     return $this->get('field_name')->value;
385   }
386
387   /**
388    * {@inheritdoc}
389    */
390   public function getSubject() {
391     return $this->get('subject')->value;
392   }
393
394   /**
395    * {@inheritdoc}
396    */
397   public function setSubject($subject) {
398     $this->set('subject', $subject);
399     return $this;
400   }
401
402   /**
403    * {@inheritdoc}
404    */
405   public function getAuthorName() {
406     if ($this->get('uid')->target_id) {
407       return $this->get('uid')->entity->label();
408     }
409     return $this->get('name')->value ?: \Drupal::config('user.settings')->get('anonymous');
410   }
411
412   /**
413    * {@inheritdoc}
414    */
415   public function setAuthorName($name) {
416     $this->set('name', $name);
417     return $this;
418   }
419
420   /**
421    * {@inheritdoc}
422    */
423   public function getAuthorEmail() {
424     $mail = $this->get('mail')->value;
425
426     if ($this->get('uid')->target_id != 0) {
427       $mail = $this->get('uid')->entity->getEmail();
428     }
429
430     return $mail;
431   }
432
433   /**
434    * {@inheritdoc}
435    */
436   public function getHomepage() {
437     return $this->get('homepage')->value;
438   }
439
440   /**
441    * {@inheritdoc}
442    */
443   public function setHomepage($homepage) {
444     $this->set('homepage', $homepage);
445     return $this;
446   }
447
448   /**
449    * {@inheritdoc}
450    */
451   public function getHostname() {
452     return $this->get('hostname')->value;
453   }
454
455   /**
456    * {@inheritdoc}
457    */
458   public function setHostname($hostname) {
459     $this->set('hostname', $hostname);
460     return $this;
461   }
462
463   /**
464    * {@inheritdoc}
465    */
466   public function getCreatedTime() {
467     if (isset($this->get('created')->value)) {
468       return $this->get('created')->value;
469     }
470     return NULL;
471   }
472
473   /**
474    * {@inheritdoc}
475    */
476   public function setCreatedTime($created) {
477     $this->set('created', $created);
478     return $this;
479   }
480
481   /**
482    * {@inheritdoc}
483    */
484   public function getStatus() {
485     return $this->get('status')->value;
486   }
487
488   /**
489    * {@inheritdoc}
490    */
491   public function getThread() {
492     $thread = $this->get('thread');
493     if (!empty($thread->value)) {
494       return $thread->value;
495     }
496   }
497
498   /**
499    * {@inheritdoc}
500    */
501   public function setThread($thread) {
502     $this->set('thread', $thread);
503     return $this;
504   }
505
506   /**
507    * {@inheritdoc}
508    */
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');
513     }
514   }
515
516   /**
517    * {@inheritdoc}
518    */
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();
525     }
526     return $user;
527   }
528
529   /**
530    * {@inheritdoc}
531    */
532   public function getOwnerId() {
533     return $this->get('uid')->target_id;
534   }
535
536   /**
537    * {@inheritdoc}
538    */
539   public function setOwnerId($uid) {
540     $this->set('uid', $uid);
541     return $this;
542   }
543
544   /**
545    * {@inheritdoc}
546    */
547   public function setOwner(UserInterface $account) {
548     $this->set('uid', $account->id());
549     return $this;
550   }
551
552   /**
553    * Get the comment type ID for this comment.
554    *
555    * @return string
556    *   The ID of the comment type.
557    */
558   public function getTypeId() {
559     return $this->bundle();
560   }
561
562   /**
563    * Default value callback for 'status' base field definition.
564    *
565    * @see ::baseFieldDefinitions()
566    *
567    * @return bool
568    *   TRUE if the comment should be published, FALSE otherwise.
569    */
570   public static function getDefaultStatus() {
571     return \Drupal::currentUser()->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;
572   }
573
574 }