comment.tokens.inc 9.23 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Builds placeholder replacement tokens for comment-related data.
 */

8
use Drupal\Component\Utility\SafeMarkup;
9
use Drupal\Component\Utility\Xss;
10 11
use Drupal\Core\Datetime\Entity\DateFormat;
use Drupal\Core\Render\BubbleableMetadata;
12

13
/**
14
 * Implements hook_token_info().
15 16 17 18 19 20 21 22
 */
function comment_token_info() {
  $type = array(
    'name' => t('Comments'),
    'description' => t('Tokens for comments posted on the site.'),
    'needs-data' => 'comment',
  );

23
  // @todo Make this work per field. See https://www.drupal.org/node/2031903.
24
  $entity['comment-count'] = array(
25
    'name' => t("Comment count"),
26
    'description' => t("The number of comments posted on an entity."),
27
  );
28
  $entity['comment-count-new'] = array(
29
    'name' => t("New comment count"),
30
    'description' => t("The number of comments posted on an entity since the reader last viewed it."),
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
  );

  // Core comment tokens
  $comment['cid'] = array(
    'name' => t("Comment ID"),
    'description' => t("The unique ID of the comment."),
  );
  $comment['hostname'] = array(
    'name' => t("IP Address"),
    'description' => t("The IP address of the computer the comment was posted from."),
  );
  $comment['mail'] = array(
    'name' => t("Email address"),
    'description' => t("The email address left by the comment author."),
  );
  $comment['homepage'] = array(
    'name' => t("Home page"),
    'description' => t("The home page URL left by the comment author."),
  );
  $comment['title'] = array(
    'name' => t("Title"),
    'description' => t("The title of the comment."),
  );
  $comment['body'] = array(
    'name' => t("Content"),
    'description' => t("The formatted content of the comment itself."),
  );
58 59 60 61
  $comment['langcode'] = array(
    'name' => t('Language code'),
    'description' => t('The language code of the language the comment is written in.'),
  );
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  $comment['url'] = array(
    'name' => t("URL"),
    'description' => t("The URL of the comment."),
  );
  $comment['edit-url'] = array(
    'name' => t("Edit URL"),
    'description' => t("The URL of the comment's edit page."),
  );

  // Chained tokens for comments
  $comment['created'] = array(
    'name' => t("Date created"),
    'description' => t("The date the comment was posted."),
    'type' => 'date',
  );
77 78 79 80 81
  $comment['changed'] = array(
    'name' => t("Date changed"),
    'description' => t("The date the comment was most recently updated."),
    'type' => 'date',
  );
82 83 84 85 86
  $comment['parent'] = array(
    'name' => t("Parent"),
    'description' => t("The comment's parent, if comment threading is active."),
    'type' => 'comment',
  );
87 88 89 90 91
  $comment['entity'] = array(
    'name' => t("Entity"),
    'description' => t("The entity the comment was posted to."),
    'type' => 'entity',
  );
92 93
  $comment['author'] = array(
    'name' => t("Author"),
94
    'description' => t("The author name of the comment."),
95 96 97 98 99 100
    'type' => 'user',
  );

  return array(
    'types' => array('comment' => $type),
    'tokens' => array(
101
      'entity' => $entity,
102 103 104 105 106 107
      'comment' => $comment,
    ),
  );
}

/**
108
 * Implements hook_tokens().
109
 */
110
function comment_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
111
  $token_service = \Drupal::token();
112

113
  $url_options = array('absolute' => TRUE);
114
  if (isset($options['langcode'])) {
115
    $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
116
    $langcode = $options['langcode'];
117 118
  }
  else {
119
    $langcode = NULL;
120 121 122 123 124 125
  }
  $sanitize = !empty($options['sanitize']);

  $replacements = array();

  if ($type == 'comment' && !empty($data['comment'])) {
126
    /** @var \Drupal\comment\CommentInterface $comment */
127 128 129 130 131 132
    $comment = $data['comment'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        // Simple key values on the comment.
        case 'cid':
133
          $replacements[$original] = $comment->id();
134 135
          break;

136
        // Poster identity information for comments.
137
        case 'hostname':
138
          $replacements[$original] = $sanitize ? SafeMarkup::checkPlain($comment->getHostname()) : $comment->getHostname();
139 140 141
          break;

        case 'mail':
142
          $mail = $comment->getAuthorEmail();
143 144 145 146 147
          // Add the user cacheability metadata in case the author of the comment
          // is not the anonymous user.
          if ($comment->getOwnerId()) {
            $bubbleable_metadata->addCacheableDependency($comment->getOwner());
          }
148
          $replacements[$original] = $sanitize ? SafeMarkup::checkPlain($mail) : $mail;
149 150 151
          break;

        case 'homepage':
152
          $replacements[$original] = $sanitize ? check_url($comment->getHomepage()) : $comment->getHomepage();
153 154 155
          break;

        case 'title':
156
          $replacements[$original] = $sanitize ? Xss::filter($comment->getSubject()) : $comment->getSubject();
157 158 159
          break;

        case 'body':
160
          $replacements[$original] = $sanitize ? $comment->comment_body->processed : $comment->comment_body->value;
161 162
          break;

163
        case 'langcode':
164
          $replacements[$original] = $sanitize ? SafeMarkup::checkPlain($comment->language()->getId()) : $comment->language()->getId();
165 166
          break;

167 168
        // Comment related URLs.
        case 'url':
169
          $url_options['fragment']  = 'comment-' . $comment->id();
170
          $replacements[$original] = $comment->url('canonical', $url_options);
171 172 173
          break;

        case 'edit-url':
174
          $url_options['fragment'] = NULL;
175
          $replacements[$original] = $comment->url('edit-form', $url_options);
176 177 178
          break;

        case 'author':
179
          $name = $comment->getAuthorName();
180 181 182 183 184
          // Add the user cacheability metadata in case the author of the comment
          // is not the anonymous user.
          if ($comment->getOwnerId()) {
            $bubbleable_metadata->addCacheableDependency($comment->getOwner());
          }
185
          $replacements[$original] = $sanitize ? Xss::filter($name) : $name;
186 187 188
          break;

        case 'parent':
189 190
          if ($comment->hasParentComment()) {
            $parent = $comment->getParentComment();
191
            $bubbleable_metadata->addCacheableDependency($parent);
192
            $replacements[$original] = $sanitize ? Xss::filter($parent->getSubject()) : $parent->getSubject();
193 194 195 196
          }
          break;

        case 'created':
197 198
          $date_format = DateFormat::load('medium');
          $bubbleable_metadata->addCacheableDependency($date_format);
199
          $replacements[$original] = format_date($comment->getCreatedTime(), 'medium', '', NULL, $langcode);
200 201 202
          break;

        case 'changed':
203 204
          $date_format = DateFormat::load('medium');
          $bubbleable_metadata->addCacheableDependency($date_format);
205
          $replacements[$original] = format_date($comment->getChangedTime(), 'medium', '', NULL, $langcode);
206 207
          break;

208
        case 'entity':
209
          $entity = $comment->getCommentedEntity();
210
          $bubbleable_metadata->addCacheableDependency($entity);
211
          $title = $entity->label();
212
          $replacements[$original] = $sanitize ? Xss::filter($title) : $title;
213 214 215 216 217
          break;
      }
    }

    // Chained token relationships.
218
    if ($entity_tokens = $token_service->findwithPrefix($tokens, 'entity')) {
219
      $entity = $comment->getCommentedEntity();
220
      $replacements += $token_service->generate($comment->getCommentedEntityTypeId(), $entity_tokens, array($comment->getCommentedEntityTypeId() => $entity), $options, $bubbleable_metadata);
221 222
    }

223
    if ($date_tokens = $token_service->findwithPrefix($tokens, 'created')) {
224
      $replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getCreatedTime()), $options, $bubbleable_metadata);
225 226
    }

227
    if ($date_tokens = $token_service->findwithPrefix($tokens, 'changed')) {
228
      $replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getChangedTime()), $options, $bubbleable_metadata);
229 230
    }

231
    if (($parent_tokens = $token_service->findwithPrefix($tokens, 'parent')) && $parent = $comment->getParentComment()) {
232
      $replacements += $token_service->generate('comment', $parent_tokens, array('comment' => $parent), $options, $bubbleable_metadata);
233 234
    }

235
    if (($author_tokens = $token_service->findwithPrefix($tokens, 'author')) && $account = $comment->getOwner()) {
236
      $replacements += $token_service->generate('user', $author_tokens, array('user' => $account), $options, $bubbleable_metadata);
237 238
    }
  }
239
  elseif ($type == 'entity' & !empty($data['entity'])) {
240
    /** @var $entity \Drupal\Core\Entity\FieldableEntityInterface */
241
    $entity = $data['entity'];
242 243

    foreach ($tokens as $name => $original) {
244
      switch ($name) {
245
        case 'comment-count':
246
          $count = 0;
247
          $fields = array_keys(\Drupal::service('comment.manager')->getFields($entity->getEntityTypeId()));
248
          $definitions = array_keys($entity->getFieldDefinitions());
249 250 251 252 253
          $valid_fields = array_intersect($fields, $definitions);
          foreach ($valid_fields as $field_name) {
            $count += $entity->get($field_name)->comment_count;
          }
          $replacements[$original] = $count;
254 255 256
          break;

        case 'comment-count-new':
257
          $replacements[$original] = \Drupal::service('comment.manager')->getCountNewComments($entity);
258 259 260 261 262 263 264
          break;
      }
    }
  }

  return $replacements;
}