You are here

comment_perm.module in Comment Permissions 8

Control commenting permissions per comment type.

File

comment_perm.module
View source
<?php

/**
 * @file
 * Control commenting permissions per comment type.
 */
use Drupal\Core\Database\Query\Select;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AnonymousUserSession;

/**
 * Implements hook_entity_type_alter().
 */
function comment_perm_entity_type_alter(array &$entity_types) {

  /** @var $entity_types \Drupal\Core\Entity\EntityType[] */
  if (isset($entity_types['comment'])) {
    $entity_types['comment']
      ->setClass('Drupal\\comment_perm\\Entity\\Comment');
    $entity_types['comment']
      ->setHandlerClass('access', 'Drupal\\comment_perm\\CommentTypeAccessControlHandler');
    $entity_types['comment']
      ->setHandlerClass('storage', 'Drupal\\comment_perm\\CommentStorage');
    $entity_types['comment']
      ->setFormClass('default', 'Drupal\\comment_perm\\CommentForm');
  }
}

/**
 * Implements hook_field_formatter_info_alter().
 */
function comment_perm_field_formatter_info_alter(array &$info) {
  if (isset($info['comment_default'])) {
    $info['comment_default']['class'] = 'Drupal\\comment_perm\\Plugin\\Field\\FieldFormatter\\CommentDefaultFormatter';
  }
}

/**
 * Implements hook_field_info_alter().
 */
function comment_perm_field_info_alter(array &$info) {
  if (isset($info['comment'])) {
    $info['comment']['list_class'] = 'Drupal\\comment_perm\\CommentFieldItemList';
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function comment_perm_form_field_config_edit_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $field_type = $form_state
    ->getFormObject()
    ->getEntity()
    ->get('field_type');
  if ($field_type != 'comment' || empty($form['settings']['anonymous'])) {
    return;
  }
  $anonymous_user = new AnonymousUserSession();
  $settings = $form_state
    ->getFormObject()
    ->getEntity()
    ->getSettings();
  $comment_type = $settings['comment_type'];
  $access = $anonymous_user
    ->hasPermission('post comments') || $anonymous_user
    ->hasPermission("post {$comment_type} comments");
  $form['settings']['anonymous']['#access'] = $access;
}

/**
 * Implements hook_entity_reference_selection_alter().
 */
function comment_perm_entity_reference_selection_alter(array &$selection) {
  if (!empty($selection['default:comment'])) {
    $selection['default:comment']['class'] = 'Drupal\\comment_perm\\Plugin\\EntityReferenceSelection\\CommentSelection';
  }
}

/**
 * Implements hook_query_TAG_alter().
 */
function comment_perm_query_comment_perm_access_alter(Select $query) {

  // See for more details in CommentSelection::buildEntityQuery().
  $conditions =& $query
    ->conditions();
  foreach ($conditions as $i => $condition) {
    if (isset($condition['field']) && $condition['field'] == 'comment_field_data.status') {
      unset($conditions[$i]);
    }
  }
}