CommentNotifySettings.php 14.2 KB
Newer Older
1 2 3 4 5
<?php

namespace Drupal\comment_notify\Form;

use Drupal\Component\Utility\Html;
6 7
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
8 9
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
10
use Drupal\Core\Link;
11
use Drupal\Core\Render\Markup;
12
use Drupal\field\Entity\FieldConfig;
13 14
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityFieldManager;
15
use Drupal\user\Entity\User;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17 18 19 20 21 22

/**
 * Settings form for the Comment Notify module.
 */
class CommentNotifySettings extends ConfigFormBase {

23 24 25 26 27 28 29 30 31 32 33 34 35 36
  /**
   * Entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManager
   */
  protected $fieldManager;

  /**
   * Module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

37 38 39 40 41 42 43 44 45 46 47 48 49 50
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'comment_notify_settings';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['comment_notify.settings'];
  }

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('entity_field.manager'),
      $container->get('module_handler')
    );
  }

  /**
   * CommentNotifySettings constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config factory.
   * @param \Drupal\Core\Entity\EntityFieldManager $field_manager
   *   The entity field manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityFieldManager $field_manager, ModuleHandlerInterface $module_handler) {
    parent::__construct($config_factory);
    $this->fieldManager = $field_manager;
    $this->moduleHandler = $module_handler;
  }

78 79 80
  /**
   * {@inheritdoc}
   */
81 82 83
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('comment_notify.settings');

84 85 86 87
    $bundle_checkboxes = $this->getCommentFieldIdentifiers();
    // Only perform comment_notify for certain bundle types.
    $enabled_bundles = $config->get('bundle_types');

88
    $anonymous_problems = [];
89 90 91 92 93 94 95 96 97 98 99 100
    // If they don't have the ability to leave contact info, then we make a
    // report.
    $entity_types = [];
    foreach ($bundle_checkboxes as $comment_field_identifier => $bundle_checkbox_label) {
      $comment_field_info = explode('--', $comment_field_identifier);
      $entity_type = $comment_field_info[0];
      $entity_bundle = $comment_field_info[1];
      $field_name = $comment_field_info[2];
      $entity_types[$entity_type][] = $comment_field_identifier;
      $comment_field = FieldConfig::loadByName($entity_type, $entity_bundle, $field_name);

      if (in_array($entity_type . '--' . $entity_bundle . '--' . $field_name, $enabled_bundles) && $comment_field && $comment_field->getSetting('anonymous') == COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
101
        if (User::getAnonymousUser()->hasPermission('subscribe to comments')) {
102 103 104 105 106 107 108 109
          // Provide a link if the field_ui module is installed.
          if ($this->moduleHandler->moduleExists('field_ui')) {
            $link = Link::fromTextAndUrl($comment_field_identifier, $comment_field->toUrl($entity_type . '-field-edit-form'));
            $no_allowed_contact_info_field[] = $link->toString();
          }
          else {
            $no_allowed_contact_info_field[] = $comment_field_identifier;
          }
110 111 112 113
        }
      }
    }

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    // If anonymous users can subscribe to comments they must be allowed to
    // post comments and leave their contact information.
    if (User::getAnonymousUser()->hasPermission('subscribe to comments')) {

      if (!User::getAnonymousUser()->hasPermission('post comments')) {
        $anonymous_problems = $this->t('Post comments');
      }
      elseif (!empty($no_allowed_contact_info_field)) {
        $markup = new Markup();
        $fields = $markup->create(implode('</li><li>', $no_allowed_contact_info_field));
        $anonymous_problems = $this->t("Leave their contact information on the following fields: <ul><li>@fields</li></ul>", ['@fields' => $fields]);
      }

      if (!empty($anonymous_problems)) {
        drupal_set_message($this->t('Anonymous commenters have the permission to subscribe to comments but they need to be allowed to:<br/>@anonymous_problems', ['@anonymous_problems' => $anonymous_problems]), 'warning', FALSE);
      }
130 131
    }

132
    $form['bundle_types'] = [
133
      '#type' => 'checkboxes',
134 135 136 137
      '#title' => $this->t('Bundles to enable for comment notification'),
      '#default_value' => $enabled_bundles,
      '#options' => $bundle_checkboxes,
      '#description' => $this->t('Comments on bundle types enabled here will have the option of comment notification. Written as "Entity Type: Bundle: Comment field".'),
138 139 140 141 142 143 144 145 146
    ];

    $form['available_alerts'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Available subscription modes'),
      '#return_value' => 1,
      '#default_value' => array_keys(array_filter($config->get('available_alerts'))),
      '#description' => $this->t('Choose which notification subscription styles are available for users'),
      '#options' => [
147
        COMMENT_NOTIFY_ENTITY => $this->t('All comments'),
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
        COMMENT_NOTIFY_COMMENT => $this->t('Replies to my comment'),
      ],
    ];

    $available_options[COMMENT_NOTIFY_DISABLED] = $this->t('No notifications');
    $available_options += _comment_notify_options();

    $form['enable_default'] = [
      '#type' => 'container',
      '#tree' => TRUE,
    ];

    $form['enable_default']['watcher'] = [
      '#type' => 'select',
      '#title' => $this->t('Default state for the notification selection box'),
      '#return_value' => 1,
      '#default_value' => $config->get('enable_default.watcher'),
      '#description' => $this->t('This flag presets the flag for the follow-up notification on the form that users will see when posting a comment'),
      '#options' => $available_options,
    ];

    $form['enable_default']['entity_author'] = [
      '#type' => 'checkbox',
171
      '#title' => $this->t('Subscribe users to their entity follow-up notification emails by default'),
172
      '#default_value' => $config->get('enable_default.entity_author'),
173
      '#description' => $this->t('If this is checked, new users will receive e-mail notifications for follow-ups on their entities by default until they individually disable the feature.'),
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    ];

    $form['mail_templates'] = [
      '#type' => 'container',
      '#tree' => TRUE,
    ];
    $form['mail_templates']['watcher'] = [
      '#type' => 'container',
      '#tree' => TRUE,
    ];

    $form['mail_templates']['entity_author'] = [
      '#type' => 'container',
      '#tree' => TRUE,
    ];

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    // Create notification options for each supported entity type.
    foreach ($entity_types as $entity_type => $checkboxes) {
      // The #states logic is rather messy. It needs to allow any of the
      // checkboxes for a specific entity type to make the email fields visible
      // so each checkbox has to be part of a jQuery OR selector.
      $checkboxeses = [];
      foreach ($checkboxes as $checkbox) {
        $checkboxeses[] = ':input[name="bundle_types[' . $checkbox . ']"]';
      }
      $checkboxeses = implode(',', $checkboxeses);

      $form['mail_templates']['watcher'][$entity_type] = [
        '#type' => 'container',
        '#tree' => TRUE,
      ];
      $form['mail_templates']['watcher'][$entity_type]['subject'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Default mail subject for sending out :entity_type notifications to commenters', [':entity_type' => $entity_type]),
        '#default_value' => $config->get('mail_templates.watcher.' . $entity_type . '.subject'),
        '#token_types' => [
          'comment', 'comment-subscribed', $entity_type,
        ],
        '#element_validate' => ['token_element_validate'],
        '#states' => [
          'visible' => [
            $checkboxeses => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
      $form['mail_templates']['watcher'][$entity_type]['body'] = [
        '#type' => 'textarea',
        '#title' => $this->t('%label: Default mail text for sending out notifications to commenters', [
          '%label' => $entity_type,
        ]),
        '#default_value' => $config->get('mail_templates.watcher.' . $entity_type . '.body'),
        '#cols' => 80,
        '#rows' => 15,
        // @todo Change from 'node' to 'entity'.
        // See Issue #1061750 on Drupal.org
        '#token_types' => [
          'comment', 'comment-subscribed', $entity_type,
        ],
        '#element_validate' => ['token_element_validate'],
        '#states' => [
          'visible' => [
            $checkboxeses => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];

      $form['mail_templates']['entity_author'][$entity_type] = [
        '#type' => 'container',
        '#tree' => TRUE,
      ];
      $form['mail_templates']['entity_author'][$entity_type]['subject'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Default mail subject for sending out :entity_type notifications to authors', [':entity_type' => $entity_type]),
        '#default_value' => $config->get('mail_templates.entity_author.' . $entity_type . '.subject'),
        '#token_types' => [
          'comment', $entity_type, 'user',
        ],
        '#element_validate' => ['token_element_validate'],
        '#states' => [
          'visible' => [
            $checkboxeses => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
      $form['mail_templates']['entity_author'][$entity_type]['body'] = [
        '#type' => 'textarea',
        '#title' => $this->t('%label: Default mail text for sending out the notifications to entity authors', [
          '%label' => $entity_type,
        ]),
        '#default_value' => $config->get('mail_templates.entity_author.' . $entity_type . '.body'),
        '#cols' => 80,
        '#rows' => 15,
        // @todo: Change token from 'node' to 'entity'
        // See Issue #1061750 on Drupal.org
        '#token_types' => [
          'comment', $entity_type, 'user',
        ],
        '#element_validate' => ['token_element_validate'],
        '#states' => [
          'visible' => [
            $checkboxeses => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
    }
287 288

    $form['token_help'] = [
289
      '#theme' => 'token_tree_link',
290
      '#token_types' => [
291
        'comment', 'comment-subscribed', 'node', 'user',
292 293 294 295 296 297
      ],
    ];

    return parent::buildForm($form, $form_state);
  }

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
  /**
   * Returns array of constructed machine names for each comment field.
   *
   * Machine names used as array keys, checkbox labels used as values.
   *
   * @return array
   *   Identifier for each comment field, formatted:
   *   [entity_type]--[bundle]--[field_name].
   */
  public function getCommentFieldIdentifiers() {
    $bundle_checkboxes = [];
    // Provide all comment fields as options.
    $comment_field_map = $this->fieldManager->getFieldMapByFieldType('comment');
    foreach ($comment_field_map as $entity_type => $comment_fields) {
      foreach ($comment_fields as $field_name => $field_info) {
        foreach ($field_info['bundles'] as $field_bundle) {
          $bundle_checkboxes[$entity_type . '--' . $field_bundle . '--' . $field_name] = Html::escape($entity_type . ': ' . $field_bundle . ': ' . $field_name);
        }
      }
    }

    return $bundle_checkboxes;
  }

  /**
   * Get the field identifier machine name for a specific comment from config.
   *
   * Returns the machine name of field identifier from bundle_types config for a
   * specific comment.
   *
   * @param \Drupal\Core\Entity\EntityInterface $comment
   *   The comment entity.
   *
   * @return string
   *   Identifier for the comment field, formatted:
   *   [entity_type]--[bundle]--[field_name].
   */
  public static function getCommentFieldIdentifier(EntityInterface $comment) {
    $comment_on_entity_type = $comment->getCommentedEntityTypeId();
    $comment_on_bundle_type = $comment->getCommentedEntity()->bundle();
    $comment_on_field_name = $comment->getFieldName();
    $comment_on_identifier = implode('--', [
      $comment_on_entity_type,
      $comment_on_bundle_type,
      $comment_on_field_name,
    ]);

    return $comment_on_identifier;
  }

348 349 350
  /**
   * {@inheritdoc}
   */
351 352 353 354 355 356 357 358 359 360
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!array_filter($form_state->getValue('available_alerts'))) {
      $form_state->setErrorByName('available_alerts', 'You must enable at least one subscription mode.');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    $config = $this->config('comment_notify.settings');
    $config->set('bundle_types', array_keys(array_filter($form_state->getValue('bundle_types'))));
    $config->set('available_alerts', $form_state->getValue('available_alerts'));
    $config->set('enable_default', $form_state->getValue('enable_default'));
    $bundle_checkboxes = $this->getCommentFieldIdentifiers();

    foreach ($bundle_checkboxes as $identifier => $label) {
      $comment_field_info = explode('--', $identifier);
      $entity_type = $comment_field_info[0];
      $config->set("mail_templates.watcher.$entity_type.subject", $form_state->getValue([
        'mail_templates',
        'watcher',
        $entity_type,
        'subject',
      ]));
      $config->set("mail_templates.watcher.$entity_type.body", $form_state->getValue([
        'mail_templates',
        'watcher',
        $entity_type,
        'body',
      ]));
      $config->set("mail_templates.entity_author.$entity_type.subject", $form_state->getValue([
        'mail_templates',
        'entity_author',
        $entity_type,
        'subject',
      ]));
      $config->set("mail_templates.entity_author.$entity_type.body", $form_state->getValue([
        'mail_templates',
        'entity_author',
        $entity_type,
        'body',
      ]));
    }
    $config->save();
396 397 398 399
    parent::submitForm($form, $form_state);
  }

}