Upgraded drupal core with security updates
[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  *   },
61  *   bundle_entity_type = "comment_type",
62  *   field_ui_base_route  = "entity.comment_type.edit_form",
63  *   constraints = {
64  *     "CommentName" = {}
65  *   }
66  * )
67  */
68 class Comment extends ContentEntityBase implements CommentInterface {
69
70   use EntityChangedTrait;
71   use EntityPublishedTrait;
72
73   /**
74    * The thread for which a lock was acquired.
75    */
76   protected $threadLock = '';
77
78   /**
79    * {@inheritdoc}
80    */
81   public function preSave(EntityStorageInterface $storage) {
82     parent::preSave($storage);
83
84     if ($this->isNew()) {
85       // Add the comment to database. This next section builds the thread field.
86       // @see \Drupal\comment\CommentViewBuilder::buildComponents()
87       $thread = $this->getThread();
88       if (empty($thread)) {
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()');
93         }
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]);
103           $prefix = '';
104         }
105         else {
106           // This is a comment with a parent comment, so increase the part of
107           // the thread value at the proper depth.
108
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);
116
117           if ($max == '') {
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.
121             $n = -1;
122           }
123           else {
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]);
130           }
131         }
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.
135         do {
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;
140       }
141       // We test the value with '===' because we need to modify anonymous
142       // users as well.
143       if ($this->getOwnerId() === \Drupal::currentUser()->id() && \Drupal::currentUser()->isAuthenticated()) {
144         $this->setAuthorName(\Drupal::currentUser()->getUsername());
145       }
146       $this->setThread($thread);
147       if (!$this->getHostname()) {
148         // Ensure a client host from the current request.
149         $this->setHostname(\Drupal::request()->getClientIP());
150       }
151     }
152   }
153
154   /**
155    * {@inheritdoc}
156    */
157   public function postSave(EntityStorageInterface $storage, $update = TRUE) {
158     parent::postSave($storage, $update);
159
160     // Always invalidate the cache tag for the commented entity.
161     if ($commented_entity = $this->getCommentedEntity()) {
162       Cache::invalidateTags($commented_entity->getCacheTagsToInvalidate());
163     }
164
165     $this->releaseThreadLock();
166     // Update the {comment_entity_statistics} table prior to executing the hook.
167     \Drupal::service('comment.statistics')->update($this);
168   }
169
170   /**
171    * Release the lock acquired for the thread in preSave().
172    */
173   protected function releaseThreadLock() {
174     if ($this->threadLock) {
175       \Drupal::lock()->release($this->threadLock);
176       $this->threadLock = '';
177     }
178   }
179
180   /**
181    * {@inheritdoc}
182    */
183   public static function postDelete(EntityStorageInterface $storage, array $entities) {
184     parent::postDelete($storage, $entities);
185
186     $child_cids = $storage->getChildCids($entities);
187     entity_delete_multiple('comment', $child_cids);
188
189     foreach ($entities as $id => $entity) {
190       \Drupal::service('comment.statistics')->update($entity);
191     }
192   }
193
194   /**
195    * {@inheritdoc}
196    */
197   public function referencedEntities() {
198     $referenced_entities = parent::referencedEntities();
199     if ($this->getCommentedEntityId()) {
200       $referenced_entities[] = $this->getCommentedEntity();
201     }
202     return $referenced_entities;
203   }
204
205   /**
206    * {@inheritdoc}
207    */
208   public function permalink() {
209     $uri = $this->urlInfo();
210     $uri->setOption('fragment', 'comment-' . $this->id());
211     return $uri;
212   }
213
214   /**
215    * {@inheritdoc}
216    */
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);
221
222     $fields['cid']->setLabel(t('Comment ID'))
223       ->setDescription(t('The comment ID.'));
224
225     $fields['uuid']->setDescription(t('The comment UUID.'));
226
227     $fields['comment_type']->setLabel(t('Comment Type'))
228       ->setDescription(t('The comment type.'));
229
230     $fields['langcode']->setDescription(t('The comment language code.'));
231
232     // Set the default value callback for the status field.
233     $fields['status']->setDefaultValueCallback('Drupal\comment\Entity\Comment::getDefaultStatus');
234
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');
239
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.'))
243       ->setRequired(TRUE);
244
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.
252         'weight' => 10,
253       ])
254       ->setDisplayConfigurable('form', TRUE);
255
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);
262
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('');
269
270     $fields['mail'] = BaseFieldDefinition::create('email')
271       ->setLabel(t('Email'))
272       ->setDescription(t("The comment author's email address."))
273       ->setTranslatable(TRUE);
274
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);
282
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);
288
289     $fields['created'] = BaseFieldDefinition::create('created')
290       ->setLabel(t('Created'))
291       ->setDescription(t('The time that the comment was created.'))
292       ->setTranslatable(TRUE);
293
294     $fields['changed'] = BaseFieldDefinition::create('changed')
295       ->setLabel(t('Changed'))
296       ->setDescription(t('The time that the comment was last edited.'))
297       ->setTranslatable(TRUE);
298
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);
303
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);
309
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);
315
316     return $fields;
317   }
318
319   /**
320    * {@inheritdoc}
321    */
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());
326       return $fields;
327     }
328     return [];
329   }
330
331   /**
332    * {@inheritdoc}
333    */
334   public function hasParentComment() {
335     return (bool) $this->get('pid')->target_id;
336   }
337
338   /**
339    * {@inheritdoc}
340    */
341   public function getParentComment() {
342     return $this->get('pid')->entity;
343   }
344
345   /**
346    * {@inheritdoc}
347    */
348   public function getCommentedEntity() {
349     return $this->get('entity_id')->entity;
350   }
351
352   /**
353    * {@inheritdoc}
354    */
355   public function getCommentedEntityId() {
356     return $this->get('entity_id')->target_id;
357   }
358
359   /**
360    * {@inheritdoc}
361    */
362   public function getCommentedEntityTypeId() {
363     return $this->get('entity_type')->value;
364   }
365
366   /**
367    * {@inheritdoc}
368    */
369   public function setFieldName($field_name) {
370     $this->set('field_name', $field_name);
371     return $this;
372   }
373
374   /**
375    * {@inheritdoc}
376    */
377   public function getFieldName() {
378     return $this->get('field_name')->value;
379   }
380
381   /**
382    * {@inheritdoc}
383    */
384   public function getSubject() {
385     return $this->get('subject')->value;
386   }
387
388   /**
389    * {@inheritdoc}
390    */
391   public function setSubject($subject) {
392     $this->set('subject', $subject);
393     return $this;
394   }
395
396   /**
397    * {@inheritdoc}
398    */
399   public function getAuthorName() {
400     if ($this->get('uid')->target_id) {
401       return $this->get('uid')->entity->label();
402     }
403     return $this->get('name')->value ?: \Drupal::config('user.settings')->get('anonymous');
404   }
405
406   /**
407    * {@inheritdoc}
408    */
409   public function setAuthorName($name) {
410     $this->set('name', $name);
411     return $this;
412   }
413
414   /**
415    * {@inheritdoc}
416    */
417   public function getAuthorEmail() {
418     $mail = $this->get('mail')->value;
419
420     if ($this->get('uid')->target_id != 0) {
421       $mail = $this->get('uid')->entity->getEmail();
422     }
423
424     return $mail;
425   }
426
427   /**
428    * {@inheritdoc}
429    */
430   public function getHomepage() {
431     return $this->get('homepage')->value;
432   }
433
434   /**
435    * {@inheritdoc}
436    */
437   public function setHomepage($homepage) {
438     $this->set('homepage', $homepage);
439     return $this;
440   }
441
442   /**
443    * {@inheritdoc}
444    */
445   public function getHostname() {
446     return $this->get('hostname')->value;
447   }
448
449   /**
450    * {@inheritdoc}
451    */
452   public function setHostname($hostname) {
453     $this->set('hostname', $hostname);
454     return $this;
455   }
456
457   /**
458    * {@inheritdoc}
459    */
460   public function getCreatedTime() {
461     if (isset($this->get('created')->value)) {
462       return $this->get('created')->value;
463     }
464     return NULL;
465   }
466
467   /**
468    * {@inheritdoc}
469    */
470   public function setCreatedTime($created) {
471     $this->set('created', $created);
472     return $this;
473   }
474
475   /**
476    * {@inheritdoc}
477    */
478   public function getStatus() {
479     return $this->get('status')->value;
480   }
481
482   /**
483    * {@inheritdoc}
484    */
485   public function getThread() {
486     $thread = $this->get('thread');
487     if (!empty($thread->value)) {
488       return $thread->value;
489     }
490   }
491
492   /**
493    * {@inheritdoc}
494    */
495   public function setThread($thread) {
496     $this->set('thread', $thread);
497     return $this;
498   }
499
500   /**
501    * {@inheritdoc}
502    */
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');
507     }
508   }
509
510   /**
511    * {@inheritdoc}
512    */
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();
519     }
520     return $user;
521   }
522
523   /**
524    * {@inheritdoc}
525    */
526   public function getOwnerId() {
527     return $this->get('uid')->target_id;
528   }
529
530   /**
531    * {@inheritdoc}
532    */
533   public function setOwnerId($uid) {
534     $this->set('uid', $uid);
535     return $this;
536   }
537
538   /**
539    * {@inheritdoc}
540    */
541   public function setOwner(UserInterface $account) {
542     $this->set('uid', $account->id());
543     return $this;
544   }
545
546   /**
547    * Get the comment type ID for this comment.
548    *
549    * @return string
550    *   The ID of the comment type.
551    */
552   public function getTypeId() {
553     return $this->bundle();
554   }
555
556   /**
557    * Default value callback for 'status' base field definition.
558    *
559    * @see ::baseFieldDefinitions()
560    *
561    * @return bool
562    *  TRUE if the comment should be published, FALSE otherwise.
563    */
564   public static function getDefaultStatus() {
565     return \Drupal::currentUser()->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;
566   }
567
568 }