summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorgnuget2019-02-16 01:01:38 (GMT)
committerDavid Valdez2019-02-16 01:01:38 (GMT)
commit3597274c283a5a9050e86db4d1c7b3fd4765d627 (patch)
tree23f302aca2a1cb96cb6ae6474d4d7f4e3608c2ef
parent0546cd5f5f823c77b957779663639ef4bf7db67e (diff)
Issue #2618182 by DamienMcKenna, gnuget, ashrafabed, Silvan Wakker, toamit, Arla, peezy, nevergone: Support all entity types as commentable, not only nodes8.x-1.0-beta5
-rw-r--r--comment_notify.inc46
-rw-r--r--comment_notify.install76
-rw-r--r--comment_notify.module179
-rw-r--r--config/install/comment_notify.settings.yml68
-rw-r--r--config/schema/comment_notify.schema.yml40
-rw-r--r--src/Form/CommentNotifySettings.php348
-rw-r--r--tests/src/Functional/CommentNotifyAnonymousTest.php14
-rw-r--r--tests/src/Functional/CommentNotifyConfigPageTest.php75
-rw-r--r--tests/src/Functional/CommentNotifyNotificationsTest.php113
-rw-r--r--tests/src/Functional/CommentNotifyUserPreferencesTest.php16
10 files changed, 748 insertions, 227 deletions
diff --git a/comment_notify.inc b/comment_notify.inc
index db83951..3ad0f35 100644
--- a/comment_notify.inc
+++ b/comment_notify.inc
@@ -50,7 +50,7 @@ function comment_notify_get_user_notification_setting($uid) {
function comment_notify_get_default_notification_setting() {
return (object) [
'comment_notify' => \Drupal::config('comment_notify.settings')->get('enable_default.watcher'),
- 'node_notify' => \Drupal::config('comment_notify.settings')->get('enable_default.entity_author'),
+ 'entity_notify' => \Drupal::config('comment_notify.settings')->get('enable_default.entity_author'),
];
}
@@ -87,9 +87,9 @@ function comment_notify_get_user_comment_notify_preference($uid) {
}
/**
- * Get a user's default preference for node update notification.
+ * Get a user's default preference for entity update notification.
*
- * This is notification on nodes where the user is the author.
+ * This is notification on entity where the user is the author.
*
* @param int $uid
* The User ID.
@@ -97,12 +97,12 @@ function comment_notify_get_user_comment_notify_preference($uid) {
* @return int
* Return the node_notify value.
*/
-function comment_notify_get_user_node_notify_preference($uid) {
+function comment_notify_get_user_entity_notify_preference($uid) {
$setting = comment_notify_get_user_notification_setting($uid);
if (!$setting) {
$setting = comment_notify_get_default_notification_setting();
}
- return $setting->node_notify;
+ return $setting->entity_notify;
}
/**
@@ -110,22 +110,22 @@ function comment_notify_get_user_node_notify_preference($uid) {
*
* @param int $uid
* The User ID.
- * @param int $node_notification
- * The node notification value.
+ * @param int $entity_notification
+ * The entity notification value.
* @param int $comment_notification
* The comment notification value.
*
* @return bool
* TRUE if the notification was set correctly.
*/
-function comment_notify_set_user_notification_setting($uid, $node_notification = NULL, $comment_notification = NULL) {
+function comment_notify_set_user_notification_setting($uid, $entity_notification = NULL, $comment_notification = NULL) {
if (!$uid) {
throw new Exception('Cannot set user preference, uid missing');
}
$fields = ['uid' => $uid];
- if (!is_null($node_notification)) {
- $fields['node_notify'] = $node_notification;
+ if (!is_null($entity_notification)) {
+ $fields['entity_notify'] = $entity_notification;
}
if (!is_null($comment_notification)) {
$fields['comment_notify'] = $comment_notification;
@@ -243,19 +243,19 @@ function comment_notify_get_notification_type($cid) {
}
/**
- * Get a list of mails which need to be contacted for a node.
+ * Get a list of mails which need to be contacted for an entity.
*
- * @param int $nid
- * The node id.
+ * @param int $entity_id
+ * The entity id.
* @param string $comment_type
* The comment type.
*
* @return \Drupal\comment\CommentInterface[]
* A list of comment entities.
*/
-function comment_notify_get_watchers($nid, $comment_type) {
- $cids = db_query("SELECT c.cid FROM {comment_field_data} c INNER JOIN {comment_notify} cn ON c.cid = cn.cid LEFT JOIN {users_field_data} u ON c.uid = u.uid WHERE c.entity_id = :nid AND c.comment_type = :comment_type AND c.status = :status AND cn.notify <> :notify AND (u.uid = 0 OR u.status = 1)", [
- ':nid' => $nid,
+function comment_notify_get_watchers($entity_id, $comment_type) {
+ $cids = db_query("SELECT c.cid FROM {comment_field_data} c INNER JOIN {comment_notify} cn ON c.cid = cn.cid LEFT JOIN {users_field_data} u ON c.uid = u.uid WHERE c.entity_id = :entity_id AND c.comment_type = :comment_type AND c.status = :status AND cn.notify <> :notify AND (u.uid = 0 OR u.status = 1)", [
+ ':entity_id' => $entity_id,
':comment_type' => $comment_type,
':status' => CommentInterface::PUBLISHED,
':notify' => COMMENT_NOTIFY_DISABLED,
@@ -331,7 +331,7 @@ function comment_notify_unsubscribe_by_hash($hash) {
$query->condition('cn.notify_hash', $hash)
->condition('cn.notify', COMMENT_NOTIFY_DISABLED, '!=')
->fields('cn', ['cid', 'notify', 'notified'])
- ->fields('cf', ['entity_id', 'uid'])
+ ->fields('cf', ['entity_id', 'entity_type', 'uid'])
->execute()->fetchObject();
$notification = $query->execute()->fetchObject();
@@ -339,10 +339,14 @@ function comment_notify_unsubscribe_by_hash($hash) {
return FALSE;
}
- // If this notification is at the node level and the commenter has a Drupal
- // account, delete all notifications for this node.
- if (COMMENT_NOTIFY_NODE == $notification->notify && $notification->uid) {
- $result = db_query("SELECT cid FROM {comment_field_data} WHERE entity_id = :entity_id AND uid = :uid", [':entity_id' => $notification->entity_id, ':uid' => $notification->uid]);
+ // If this notification is at the entity level and the commenter has a Drupal
+ // account, delete all notifications for this entity.
+ if (COMMENT_NOTIFY_ENTITY == $notification->notify && $notification->uid) {
+ $result = db_query("SELECT cid FROM {comment_field_data} WHERE entity_id = :entity_id AND entity_type = :entity_type AND uid = :uid", [
+ ':entity_id' => $notification->entity_id,
+ ':entity_type' => $notification->entity_type,
+ ':uid' => $notification->uid,
+ ]);
$cids = $result->fetchCol();
// Update all comment notifications to be disabled.
diff --git a/comment_notify.install b/comment_notify.install
index ea6d041..6bc310b 100644
--- a/comment_notify.install
+++ b/comment_notify.install
@@ -79,7 +79,7 @@ function comment_notify_schema() {
'not null' => TRUE,
'disp-width' => '11',
],
- 'node_notify' => [
+ 'entity_notify' => [
'type' => 'int',
'description' => 'An integer indicating the default type of subscription: 0 means not subscribed, 1 means subscribed to all comments, and 2 means only subscribed to replies of this comment.',
'size' => 'tiny',
@@ -101,3 +101,77 @@ function comment_notify_schema() {
return $schema;
}
+
+/**
+ * Implementations of hook_update().
+ */
+
+/**
+ * Rename db column name from node_notify to entity_notify.
+ */
+function comment_notify_update_8001() {
+ $spec = [
+ 'type' => 'int',
+ 'description' => 'An integer indicating the default type of subscription: 0 means not subscribed, 1 means subscribed to all comments, and 2 means only subscribed to replies of this comment.',
+ 'size' => 'tiny',
+ 'not null' => TRUE,
+ 'default' => 0,
+ 'disp-width' => '11',
+ ];
+ db_change_field('comment_notify_user_settings', 'node_notify', 'entity_notify', $spec);
+}
+
+/**
+ * Preserve node notification settings.
+ */
+function comment_notify_update_8002() {
+ $node_values = \Drupal::config('comment_notify.settings')->get('node_types');
+ $bundle_types = [];
+ $field_manager = \Drupal::service('entity_field.manager');
+ $bundles_with_comment_fields = [];
+ $comment_field_map = $field_manager->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) {
+ $bundles_with_comment_fields[$field_bundle][] = $field_name;
+ }
+ }
+ }
+ foreach ($bundles_with_comment_fields as $bundle => $fields) {
+ if (!in_array($bundle, $node_values)) {
+ continue;
+ }
+ foreach ($fields as $field_name) {
+ $bundle_types[] = 'node--' . $bundle . '--' . $field_name;
+ }
+ }
+ \Drupal::configFactory()
+ ->getEditable('comment_notify.settings')
+ ->set('bundle_types', $bundle_types)
+ ->save();
+}
+
+/**
+ * Update settings for generic entity support.
+ */
+function comment_notify_update_8003() {
+ $config = \Drupal::service('config.factory')
+ ->getEditable('comment_notify.settings');
+
+ // Update the email settings.
+ $vars = [
+ 'mail_templates.watcher.subject' => 'mail_templates.watcher.node.subject',
+ 'mail_templates.watcher.body' => 'mail_templates.watcher.node.body',
+ 'mail_templates.entity_author.subject' => 'mail_templates.entity_author.node.subject',
+ 'mail_templates.entity_author.body' => 'mail_templates.entity_author.node.body',
+ ];
+
+ // Update the settings.
+ foreach ($vars as $old => $new) {
+ $value = $config->get($old);
+ $config->set($new, $value);
+ $config->clear($old);
+ }
+
+ $config->save();
+}
diff --git a/comment_notify.module b/comment_notify.module
index 8ea01d8..17353e3 100644
--- a/comment_notify.module
+++ b/comment_notify.module
@@ -9,6 +9,7 @@
use Drupal\Core\Entity\EntityInterface;
use Drupal\comment\CommentInterface;
+use Drupal\comment_notify\Form\CommentNotifySettings;
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
@@ -16,10 +17,10 @@ use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldConfig;
-use Drupal\node\Entity\NodeType;
+use Drupal\user\Entity\User;
define('COMMENT_NOTIFY_DISABLED', 0);
-define('COMMENT_NOTIFY_NODE', 1);
+define('COMMENT_NOTIFY_ENTITY', 1);
define('COMMENT_NOTIFY_COMMENT', 2);
/**
@@ -27,8 +28,8 @@ define('COMMENT_NOTIFY_COMMENT', 2);
*/
function _comment_notify_options() {
$total_options = [
- COMMENT_NOTIFY_NODE => t('All comments'),
- COMMENT_NOTIFY_COMMENT => t('Replies to my comment'),
+ COMMENT_NOTIFY_ENTITY => t('All comments'),
+ COMMENT_NOTIFY_COMMENT => t('Replies to my comment'),
];
$selected_options = array_filter(\Drupal::config('comment_notify.settings')->get('available_alerts'));
@@ -46,12 +47,13 @@ function comment_notify_form_comment_form_alter(&$form, FormStateInterface $form
return;
}
- /** @var \Drupal\Core\Entity\EntityInterface $commented_entity */
- $commented_entity = $form_state->getFormObject()->getEntity()->getCommentedEntity();
+ /** @var \Drupal\Core\Entity\EntityInterface $comment_entity */
+ $comment_entity = $form_state->getFormObject()->getEntity();
+ $field_identifier = CommentNotifySettings::getCommentFieldIdentifier($comment_entity);
// Only add the checkbox if this is an enabled content type.
- $enabled_types = \Drupal::config('comment_notify.settings')->get('node_types');
- if (!in_array($commented_entity->bundle(), $enabled_types)) {
+ $enabled_types = \Drupal::config('comment_notify.settings')->get('bundle_types');
+ if (!in_array($field_identifier, $enabled_types)) {
return;
}
@@ -96,7 +98,7 @@ function comment_notify_form_comment_form_alter(&$form, FormStateInterface $form
$notify = comment_notify_get_notification_type($comment->id());
$form['comment_notify_settings']['notify']['#default_value'] = (bool) $notify;
if (count($available_options) > 1) {
- $form['comment_notify_settings']['notify_type']['#default_value'] = empty($notify) ? COMMENT_NOTIFY_NODE : $notify;
+ $form['comment_notify_settings']['notify_type']['#default_value'] = empty($notify) ? COMMENT_NOTIFY_ENTITY : $notify;
}
else {
$form['comment_notify_settings']['notify_type']['#default_value'] = key($available_options);
@@ -199,6 +201,23 @@ function comment_notify_comment_delete(CommentInterface $comment) {
}
/**
+ * Returns array of comment notify enabled entity type & bundles.
+ */
+function _comment_notify_get_comment_enabled_bundles() {
+ $field_manager = \Drupal::service('entity_field.manager');
+ $bundles_with_comment_fields = [];
+ $comment_field_map = $field_manager->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) {
+ $bundles_with_comment_fields[$entity_type] = $field_bundle;
+ }
+ }
+ }
+ return $bundles_with_comment_fields;
+}
+
+/**
* Implements hook_form_alter().
*/
function comment_notify_form_user_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
@@ -208,18 +227,19 @@ function comment_notify_form_user_form_alter(&$form, FormStateInterface &$form_s
$user = $form_state->getFormObject()->getEntity();
$notify_settings = $user->id() && comment_notify_get_user_notification_setting($user->id()) ? comment_notify_get_user_notification_setting($user->id()) : comment_notify_get_default_notification_setting();
- // Only show the node followup UI if the user has permission to create nodes.
- $nodes = FALSE;
- foreach (node_type_get_names() as $type => $name) {
- if (\Drupal::entityManager()->getAccessControlHandler('node')->createAccess($type)) {
- $nodes = TRUE;
+ // Only show the entity followup UI if the user has permission to create
+ // entities.
+ $bundles = FALSE;
+ foreach (_comment_notify_get_comment_enabled_bundles() as $entity_type => $bundle) {
+ if (\Drupal::entityManager()->getAccessControlHandler($entity_type)->createAccess($bundle)) {
+ $bundles = TRUE;
break;
}
}
// If the user cannot create nodes nor has the 'subscribe to comments'
// permission then there is no need to alter the user_form.
- if ((!\Drupal::currentUser()->hasPermission('administer nodes') && $nodes === FALSE) && ($user->hasPermission('subscribe to comments') === FALSE)) {
+ if ((!\Drupal::currentUser()->hasPermission('administer nodes') && $bundles === FALSE) && ($user->hasPermission('subscribe to comments') === FALSE)) {
return;
}
@@ -230,8 +250,8 @@ function comment_notify_form_user_form_alter(&$form, FormStateInterface &$form_s
'#open' => TRUE,
];
- if (\Drupal::currentUser()->hasPermission('administer nodes') || $nodes) {
- $form['comment_notify_settings']['node_notify'] = [
+ if (\Drupal::currentUser()->hasPermission('administer nodes') || $bundles) {
+ $form['comment_notify_settings']['entity_notify'] = [
'#type' => 'checkbox',
'#title' => t('Receive content follow-up notification e-mails'),
'#default_value' => isset($notify_settings->node_notify) ? $notify_settings->node_notify : NULL,
@@ -239,7 +259,7 @@ function comment_notify_form_user_form_alter(&$form, FormStateInterface &$form_s
];
}
else {
- $form['comment_notify_settings']['node_notify'] = [
+ $form['comment_notify_settings']['entity_notify'] = [
'#type' => 'hidden',
'#value' => COMMENT_NOTIFY_DISABLED,
];
@@ -274,9 +294,9 @@ function _comment_notify_submit_user_form(array &$form, FormStateInterface $form
/** @var \Drupal\user\UserInterface $user */
$user = $form_state->getFormObject()->getEntity();
- if (!$user->isAnonymous() && is_numeric($form_state->getValue('node_notify')) && is_numeric($form_state->getValue('comment_notify'))) {
+ if (!$user->isAnonymous() && is_numeric($form_state->getValue('entity_notify')) && is_numeric($form_state->getValue('comment_notify'))) {
// Save the values to {comment_notify_user_settings}.
- comment_notify_set_user_notification_setting($user->id(), $form_state->getValue('node_notify'), $form_state->getValue('comment_notify'));
+ comment_notify_set_user_notification_setting($user->id(), $form_state->getValue('entity_notify'), $form_state->getValue('comment_notify'));
}
}
@@ -340,12 +360,14 @@ function comment_notify_comment_load($comments) {
* The comment entity.
*/
function _comment_notify_mailalert(CommentInterface $comment) {
-
module_load_include('inc', 'comment_notify', 'comment_notify');
$config = \Drupal::config('comment_notify.settings');
$user = \Drupal::currentUser();
- $nid = $comment->getCommentedEntityId();
+
+ $entity_id = $comment->getCommentedEntityId();
+ $entity_type = $comment->getCommentedEntityTypeId();
+ $field_identifier = CommentNotifySettings::getCommentFieldIdentifier($comment);
$comment_type = $comment->get('comment_type')->getString();
@@ -356,12 +378,12 @@ function _comment_notify_mailalert(CommentInterface $comment) {
return;
}
- /** @var \Drupal\node\NodeInterface $node */
- $node = \Drupal::entityManager()->getStorage('node')->load($nid);
+ /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
+ $entity = \Drupal::entityManager()->getStorage($entity_type)->load($entity_id);
// No mails if this is not an enabled content type.
- $enabled_types = $config->get('node_types');
- if (!in_array($node->bundle(), $enabled_types) && !empty($enabled_types)) {
+ $enabled_types = $config->get('bundle_types');
+ if (!empty($enabled_types) && !in_array($field_identifier, $enabled_types)) {
return;
}
@@ -376,37 +398,60 @@ function _comment_notify_mailalert(CommentInterface $comment) {
}
$sent_to = [];
- // Send to a subscribed author if they are not the current commenter.
- $author = $node->getOwner();
- $author_notify_settings = comment_notify_get_user_notification_setting($author->id()) ?: comment_notify_get_default_notification_setting();
-
- // Do they explicitly want this? Or is it default to send to users?
- // Is the comment author not the node author? Do they have access? Do they
- // have an email (e.g. anonymous)?
- if (
- (
- (!empty($author_notify_settings->node_notify) && $author_notify_settings->node_notify == 1)
- || ($config->get('enable_default.entity_author') == 1 && !isset($author_notify_settings->node_notify))
- )
- && $user->id() != $author->id()
- && $node->access('view', $author)
- && !empty($author->getEmail())
- ) {
- $raw_values = $config->get('mail_templates.entity_author');
- $token_data = ['comment' => $comment, 'node' => $node];
- $message['subject'] = PlainTextOutput::renderFromHtml(\Drupal::token()->replace($raw_values['subject'], $token_data));
- $message['body'] = \Drupal::token()->replace($raw_values['body'], $token_data);
-
- $language = $author->getPreferredLangcode();
- \Drupal::service('plugin.manager.mail')->mail('comment_notify', 'comment_notify_mail', $author->getEmail(), $language, $message);
- $sent_to[] = strtolower($author->getEmail());
+ // @todo Add hook to allow entity types to specify their type's author field?
+ $author_fields = ['uid', 'user_id'];
+ foreach ($author_fields as $author_field) {
+ // Send to a subscribed author if they are not the current commenter.
+ if ($entity->hasField($author_field)) {
+ // If the entity is a user object, then the user object is the "author'.
+ if ($entity instanceof User) {
+ $author = $entity;
+ }
+ // For now assume every other entity has an "owner".
+ else {
+ $author = $entity->getOwner();
+ }
+ $author_notify_settings = comment_notify_get_user_notification_setting($author->id()) ?: comment_notify_get_default_notification_setting();
+ $author_email = $author->getEmail();
+
+ // Do they explicitly want this? Or is it default to send to users? Is
+ // the comment author not the entity author? Do they have access? Do they
+ // have an email (e.g. anonymous)?
+ $entity_notify_a = !empty($author_notify_settings->entity_notify) && $author_notify_settings->entity_notify == 1;
+ $entity_notify_b = $config->get('enable_default.entity_author') == 1 && !isset($author_notify_settings->entity_notify);
+ if (!empty($author_email)
+ && ($entity_notify_a || $entity_notify_b)
+ && $user->id() != $author->id()
+ && $entity->access('view', $author)
+ ) {
+ if (in_array($author_email, $sent_to)) {
+ continue;
+ }
+ $raw_values = $config->get('mail_templates.entity_author.' . $entity->getEntityTypeId());
+ $token_data = [
+ 'comment' => $comment,
+ 'user' => $author,
+ ];
+ if ($entity_type == 'node') {
+ $token_data['node'] = $entity;
+ }
+ $message['subject'] = PlainTextOutput::renderFromHtml(\Drupal::token()->replace($raw_values['subject'], $token_data));
+ $message['body'] = \Drupal::token()->replace($raw_values['body'], $token_data);
+
+ $language = $author->getPreferredLangcode();
+ \Drupal::service('plugin.manager.mail')->mail('comment_notify', 'comment_notify_mail', $author->getEmail(), $language, $message);
+ $sent_to[] = strtolower($author->getEmail());
+ }
+ // This field existed, so there's no need to try again.
+ break;
+ }
}
// For "reply to my comments" notifications, figure out what thread this is.
$thread = $comment->getThread() ?: '';
// Get the list of commenters to notify.
- $watchers = comment_notify_get_watchers($nid, $comment_type);
+ $watchers = comment_notify_get_watchers($entity_id, $comment_type);
foreach ($watchers as $alert) {
// If the user is not anonymous, always load the current e-mail address
@@ -424,23 +469,26 @@ function _comment_notify_mailalert(CommentInterface $comment) {
if ($mail != $comment_mail && !in_array(strtolower($mail), $sent_to) && ($alert->getOwnerId() != $comment->getOwnerId() || $alert->getOwnerId() == 0)) {
$message = [];
- // Make sure they have access to this node before showing a bunch of node
- // information.
- if (!$node->access('view', $recipient_user)) {
+ // Make sure they have access to this entity before showing a bunch of
+ // entity information.
+ if (!$entity->access('view', $recipient_user)) {
continue;
}
- $raw_values = $config->get('mail_templates.watcher');
+ $raw_values = $config->get('mail_templates.watcher.' . $entity->getEntityTypeId());
$token_data = [
'comment' => $comment,
- 'node' => $node,
'comment-subscribed' => $alert,
];
+ if ($entity_type == 'node') {
+ $token_data['node'] = $entity;
+ }
$message['subject'] = PlainTextOutput::renderFromHtml(\Drupal::token()->replace($raw_values['subject'], $token_data));
$message['body'] = \Drupal::token()->replace($raw_values['body'], $token_data);
$language = !empty($alert->uid) ? $recipient_user->getPreferredLangcode() : LanguageInterface::LANGCODE_DEFAULT;
- \Drupal::service('plugin.manager.mail')->mail('comment_notify', 'comment_notify_mail', $mail, $language, $message);
+ \Drupal::service('plugin.manager.mail')
+ ->mail('comment_notify', 'comment_notify_mail', $mail, $language, $message);
$sent_to[] = strtolower($mail);
// Make the mail link to user's /edit, unless it's an anonymous user.
@@ -452,7 +500,12 @@ function _comment_notify_mailalert(CommentInterface $comment) {
}
// Add an entry to the watchdog log.
- \Drupal::logger('comment_notify')->notice('Notified: @user_mail', ['@user_mail' => $user_mail, 'link' => $alert->link(t('source comment'))]);
+ $args = [
+ '@user_mail' => $user_mail,
+ 'link' => $alert->link(t('source comment')),
+ ];
+ \Drupal::logger('comment_notify')
+ ->notice('Notified: @user_mail', $args);
}
}
// Record that a notification was sent for this comment so that
@@ -496,14 +549,18 @@ function comment_notify_get_unsubscribe_url(CommentInterface $comment) {
function comment_notify_entity_extra_field_info() {
module_load_include('inc', 'comment_notify', 'comment_notify');
$extras = [];
+ $config = \Drupal::config('comment_notify.settings');
- foreach (\Drupal::config('comment_notify.settings')->get('node_types') as $node_type) {
- $comment_field = FieldConfig::loadByName('node', $node_type, 'comment');
+ foreach ($config->get('bundle_types') as $bundle_type) {
+ $field_identifier = explode('--', $bundle_type);
+ $comment_field = FieldConfig::loadByName($field_identifier[0], $field_identifier[1], $field_identifier[2]);
if ($comment_field) {
+ $bundle_info = \Drupal::service("entity_type.bundle.info")->getBundleInfo($field_identifier[0]);
+ $bundle_label = $bundle_info[$field_identifier[1]]['label'];
$comment_type = $comment_field->getSetting('comment_type');
$extras['comment'][$comment_type]['form']['comment_notify_settings'] = [
'label' => t('Comment Notify settings'),
- 'description' => t('@node_type settings for Comment Notify', ['@node_type' => NodeType::load($node_type)->label()]),
+ 'description' => t('@bundle_type settings for Comment Notify', ['@bundle_type' => $bundle_label]),
'weight' => 1,
];
}
diff --git a/config/install/comment_notify.settings.yml b/config/install/comment_notify.settings.yml
index 3e0b22b..dbd4827 100644
--- a/config/install/comment_notify.settings.yml
+++ b/config/install/comment_notify.settings.yml
@@ -1,5 +1,5 @@
-node_types:
- - article
+bundle_types:
+ - node--article--comment
available_alerts:
1: true
2: true
@@ -8,46 +8,48 @@ enable_default:
entity_author: false
mail_templates:
watcher:
- subject: '[site:name] :: new comment on [node:title]'
- body: |
- Hi [comment-subscribed:author],
+ node:
+ subject: '[site:name] :: new comment on [node:title]'
+ body: |
+ Hi [comment-subscribed:author],
- [comment:author] has commented on: "[node:title]"
+ [comment:author] has commented on: "[node:title]"
- ----
- [comment:title]
- [comment:body]
- ----
+ ----
+ [comment:title]
+ [comment:body]
+ ----
- You can view the comment at the following url
- [comment:url]
+ You can view the comment at the following url
+ [comment:url]
- You can stop receiving emails when someone replies to this post,
- by going to [comment-subscribed:unsubscribe-url]
+ You can stop receiving emails when someone replies to this post,
+ by going to [comment-subscribed:unsubscribe-url]
- You can set up auto-following feature for all future posts
- by creating your own user with a few clicks here [site:login-url]
+ You can set up auto-following feature for all future posts
+ by creating your own user with a few clicks here [site:login-url]
- -- [site:name] team
- [site:url]
+ -- [site:name] team
+ [site:url]
entity_author:
- subject: '[site:name] :: new comment for your post'
- body: |
- Hi [node:author],
+ node:
+ subject: '[site:name] :: new comment for your post'
+ body: |
+ Hi [node:author],
- You have received a comment on: "[node:title]"
+ You have received a comment on: "[node:title]"
- ----
- [comment:title]
- [comment:body]
- ----
+ ----
+ [comment:title]
+ [comment:body]
+ ----
- You can view the comment at the following url
- [comment:url]
+ You can view the comment at the following url
+ [comment:url]
- You will receive emails like this for all replies to your posts. You can
- disable this by logging in and changing the settings on your user account at
- [node:author:edit-url].
+ You will receive emails like this for all replies to your posts. You can
+ disable this by logging in and changing the settings on your user account at
+ [node:author:edit-url].
- -- [site:name] team
- [site:url]
+ -- [site:name] team
+ [site:url]
diff --git a/config/schema/comment_notify.schema.yml b/config/schema/comment_notify.schema.yml
index 4105cfd..0dd7fc9 100644
--- a/config/schema/comment_notify.schema.yml
+++ b/config/schema/comment_notify.schema.yml
@@ -1,16 +1,16 @@
comment_notify.settings:
type: config_object
mapping:
- node_types:
+ bundle_types:
type: sequence
- label: Content types to enable for comment notification
+ label: Bundle types to enable for comment notification
sequence:
type: string
available_alerts:
type: mapping
label: Available subscription modes
mapping:
- # COMMENT_NOTIFY_NODE
+ # COMMENT_NOTIFY_ENTITY
1:
type: boolean
# COMMENT_NOTIFY_COMMENT
@@ -24,7 +24,7 @@ comment_notify.settings:
label: Default state for the notification selection box
entity_author:
type: boolean
- label: Subscribe users to their node follow-up notification emails by default
+ label: Subscribe users to their entity follow-up notification emails by default
mail_templates:
type: mapping
label: Default mail text for sending out notifications
@@ -33,19 +33,27 @@ comment_notify.settings:
type: mapping
label: Notifications to commenters
mapping:
- subject:
- type: label
- label: Subject
- body:
- type: text
- label: Body
+ node:
+ type: mapping
+ label: Default mail text for sending out notifications for nodes
+ mapping:
+ subject:
+ type: label
+ label: Subject
+ body:
+ type: text
+ label: Body
entity_author:
type: mapping
label: Notifications to owner of commented entity
mapping:
- subject:
- type: label
- label: Subject
- body:
- type: text
- label: Body
+ node:
+ type: mapping
+ label: Default mail text for sending out notifications for nodes
+ mapping:
+ subject:
+ type: label
+ label: Subject
+ body:
+ type: text
+ label: Body
diff --git a/src/Form/CommentNotifySettings.php b/src/Form/CommentNotifySettings.php
index cacd433..7bc1307 100644
--- a/src/Form/CommentNotifySettings.php
+++ b/src/Form/CommentNotifySettings.php
@@ -3,12 +3,17 @@
namespace Drupal\comment_notify\Form;
use Drupal\Component\Utility\Html;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Link;
use Drupal\Core\Render\Markup;
use Drupal\field\Entity\FieldConfig;
-use Drupal\node\Entity\NodeType;
+use Drupal\Core\Config\ConfigFactoryInterface;
+use Drupal\Core\Entity\EntityFieldManager;
use Drupal\user\Entity\User;
+use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Settings form for the Comment Notify module.
@@ -16,6 +21,20 @@ use Drupal\user\Entity\User;
class CommentNotifySettings extends ConfigFormBase {
/**
+ * Entity field manager.
+ *
+ * @var \Drupal\Core\Entity\EntityFieldManager
+ */
+ protected $fieldManager;
+
+ /**
+ * Module handler.
+ *
+ * @var \Drupal\Core\Extension\ModuleHandlerInterface
+ */
+ protected $moduleHandler;
+
+ /**
* {@inheritdoc}
*/
public function getFormId() {
@@ -32,40 +51,90 @@ class CommentNotifySettings extends ConfigFormBase {
/**
* {@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;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('comment_notify.settings');
- // Only perform comment_notify for certain node types.
- $enabled_types = $config->get('node_types');
+ $bundle_checkboxes = $this->getCommentFieldIdentifiers();
+ // Only perform comment_notify for certain bundle types.
+ $enabled_bundles = $config->get('bundle_types');
+
$anonymous_problems = [];
- $checkboxes = [];
- foreach (NodeType::loadMultiple() as $type_id => $type) {
- $checkboxes[$type_id] = Html::escape($type->label());
- $default[] = $type_id;
-
- // If they don't have the ability to leave contact info make a report.
- $comment_field = FieldConfig::loadByName('node', $type_id, 'comment');
- if (in_array($type_id, $enabled_types) && $comment_field && $comment_field->getSetting('anonymous') == COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
+ // 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) {
if (User::getAnonymousUser()->hasPermission('subscribe to comments')) {
- $anonymous_problems[] = $type->link($type->label());
+ // 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;
+ }
}
}
}
- if (!empty($anonymous_problems)) {
- $markup = new Markup();
- $types = $markup->create(implode(', ', $anonymous_problems));
- drupal_set_message($this->t('Anonymous commenters have the permission to subscribe to comments but cannot leave their contact information on the following content types: @types. You should either disable subscriptions on those types here, revoke the permission for anonymous users, or enable anonymous users to leave their contact information in the comment settings.', [
- '@types' => $types,
- ]), 'status', FALSE);
+ // 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);
+ }
}
- $form['node_types'] = [
+ $form['bundle_types'] = [
'#type' => 'checkboxes',
- '#title' => $this->t('Content types to enable for comment notification'),
- '#default_value' => $enabled_types,
- '#options' => $checkboxes,
- '#description' => $this->t('Comments on content types enabled here will have the option of comment notification.'),
+ '#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".'),
];
$form['available_alerts'] = [
@@ -75,7 +144,7 @@ class CommentNotifySettings extends ConfigFormBase {
'#default_value' => array_keys(array_filter($config->get('available_alerts'))),
'#description' => $this->t('Choose which notification subscription styles are available for users'),
'#options' => [
- COMMENT_NOTIFY_NODE => $this->t('All comments'),
+ COMMENT_NOTIFY_ENTITY => $this->t('All comments'),
COMMENT_NOTIFY_COMMENT => $this->t('Replies to my comment'),
],
];
@@ -99,54 +168,127 @@ class CommentNotifySettings extends ConfigFormBase {
$form['enable_default']['entity_author'] = [
'#type' => 'checkbox',
- '#title' => $this->t('Subscribe users to their node follow-up notification emails by default'),
+ '#title' => $this->t('Subscribe users to their entity follow-up notification emails by default'),
'#default_value' => $config->get('enable_default.entity_author'),
- '#description' => $this->t('If this is checked, new users will receive e-mail notifications for follow-ups on their nodes by default until they individually disable the feature.'),
+ '#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.'),
];
$form['mail_templates'] = [
'#type' => 'container',
'#tree' => TRUE,
];
-
$form['mail_templates']['watcher'] = [
'#type' => 'container',
'#tree' => TRUE,
];
- $form['mail_templates']['watcher']['body'] = [
- '#type' => 'textarea',
- '#title' => $this->t('Default mail text for sending out notifications to commenters'),
- '#default_value' => $config->get('mail_templates.watcher.body'),
- '#cols' => 80,
- '#rows' => 15,
- '#token_types' => [
- 'comment', 'node',
- ],
- '#element_validate' => ['token_element_validate'],
- ];
-
$form['mail_templates']['entity_author'] = [
'#type' => 'container',
'#tree' => TRUE,
];
- $form['mail_templates']['entity_author']['body'] = [
- '#type' => 'textarea',
- '#title' => $this->t('Default mail text for sending out the notifications to node authors'),
- '#default_value' => $config->get('mail_templates.entity_author.body'),
- '#cols' => 80,
- '#rows' => 15,
- '#token_types' => [
- 'comment', 'node',
- ],
- '#element_validate' => ['token_element_validate'],
- ];
+ // 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,
+ ],
+ ],
+ ],
+ ];
+ }
$form['token_help'] = [
'#theme' => 'token_tree_link',
'#token_types' => [
- 'comment', 'node',
+ 'comment', 'comment-subscribed', 'node', 'user',
],
];
@@ -154,6 +296,56 @@ class CommentNotifySettings extends ConfigFormBase {
}
/**
+ * 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;
+ }
+
+ /**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
@@ -166,25 +358,41 @@ class CommentNotifySettings extends ConfigFormBase {
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
- $this->config('comment_notify.settings')
- ->set('node_types', array_keys(array_filter($form_state->getValue('node_types'))))
- ->set('available_alerts', $form_state->getValue('available_alerts'))
- ->set('enable_default', $form_state->getValue('enable_default'))
- ->set('mail_templates.watcher.body', $form_state->getValue(
- [
- 'mail_templates',
- 'watcher',
- 'body',
- ]
- ))
- ->set('mail_templates.entity_author.body', $form_state->getValue(
- [
- 'mail_templates',
- 'entity_author',
- 'body',
- ]
- ))
- ->save();
+ $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();
parent::submitForm($form, $form_state);
}
diff --git a/tests/src/Functional/CommentNotifyAnonymousTest.php b/tests/src/Functional/CommentNotifyAnonymousTest.php
index 179b8b2..b2d14e8 100644
--- a/tests/src/Functional/CommentNotifyAnonymousTest.php
+++ b/tests/src/Functional/CommentNotifyAnonymousTest.php
@@ -37,7 +37,7 @@ class CommentNotifyAnonymousTest extends CommentNotifyTestBase {
/** @var \Drupal\node\Entity\Node $node */
$node = $this->drupalCreateNode(['type' => 'article']);
- $subscribe = ['notify' => TRUE, 'notify_type' => COMMENT_NOTIFY_NODE];
+ $subscribe = ['notify' => TRUE, 'notify_type' => COMMENT_NOTIFY_ENTITY];
$this->drupalGet($node->toUrl());
$this->postComment($node->toUrl()->toString(), $this->randomMachineName(), $this->randomMachineName(), $subscribe);
$this->assertTrue($this->getSession()->getPage()->hasContent(t('If you want to subscribe to comments you must supply a valid e-mail address.')));
@@ -49,7 +49,7 @@ class CommentNotifyAnonymousTest extends CommentNotifyTestBase {
public function testAnonymousAllCommentsTest() {
/** @var \Drupal\node\Entity\Node $node */
$node = $this->drupalCreateNode(['type' => 'article']);
- $subscribe = ['notify' => TRUE, 'notify_type' => COMMENT_NOTIFY_NODE];
+ $subscribe = ['notify' => TRUE, 'notify_type' => COMMENT_NOTIFY_ENTITY];
$contact = ['name' => $this->randomMachineName(), 'mail' => $this->getRandomEmailAddress()];
$comment = $this->postComment(
$node->toUrl()->toString(),
@@ -68,7 +68,7 @@ class CommentNotifyAnonymousTest extends CommentNotifyTestBase {
$node->toUrl()->toString(),
$this->randomMachineName(),
$this->randomMachineName(),
- ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_NODE],
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY],
['name' => $this->randomMachineName(), 'mail' => $this->getRandomEmailAddress()]
);
$this->assertMail('to', $contact['mail'], t('Message was sent to the anonymous user.'));
@@ -87,7 +87,7 @@ class CommentNotifyAnonymousTest extends CommentNotifyTestBase {
$node->toUrl()->toString(),
$this->randomMachineName(),
$this->randomMachineName(),
- ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_NODE],
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY],
['name' => $this->randomMachineName(), 'mail' => $this->getRandomEmailAddress()]
);
$captured_emails = $this->container->get('state')->get('system.test_mail_collector');
@@ -113,7 +113,7 @@ class CommentNotifyAnonymousTest extends CommentNotifyTestBase {
$node->toUrl()->toString(),
$this->randomMachineName(),
$this->randomMachineName(),
- ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_NODE],
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY],
['name' => $this->randomMachineName(), 'mail' => $this->getRandomEmailAddress()]
);
$captured_emails = $this->container->get('state')->get('system.test_mail_collector');
@@ -124,7 +124,7 @@ class CommentNotifyAnonymousTest extends CommentNotifyTestBase {
"/comment/reply/node/{$node->id()}/comment/{$comment['id']}",
$this->randomMachineName(),
$this->randomMachineName(),
- ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_NODE],
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY],
['name' => $this->randomMachineName(), 'mail' => $this->getRandomEmailAddress()]
);
$this->assertMail('to', $contact['mail'], t('Message was sent to the anonymous user.'));
@@ -143,7 +143,7 @@ class CommentNotifyAnonymousTest extends CommentNotifyTestBase {
"/comment/reply/node/{$node->id()}/comment/{$comment['id']}",
$this->randomMachineName(),
$this->randomMachineName(),
- ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_NODE],
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY],
['name' => $this->randomMachineName(), 'mail' => $this->getRandomEmailAddress()]
);
$captured_emails = $this->container->get('state')->get('system.test_mail_collector');
diff --git a/tests/src/Functional/CommentNotifyConfigPageTest.php b/tests/src/Functional/CommentNotifyConfigPageTest.php
index fd75c2d..31ab413 100644
--- a/tests/src/Functional/CommentNotifyConfigPageTest.php
+++ b/tests/src/Functional/CommentNotifyConfigPageTest.php
@@ -2,6 +2,10 @@
namespace Drupal\Tests\comment_notify\Functional;
+use Drupal\comment\CommentInterface;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\field\Entity\FieldConfig;
+
/**
* Tests for the comment_notify module.
*
@@ -21,11 +25,11 @@ class CommentNotifyConfigPageTest extends CommentNotifyTestBase {
$this->assertSession()->responseContains('The configuration options have been saved.');
// Test that the content types are saved correctly.
- $this->getSession()->getPage()->checkField('node_types[article]');
+ $this->getSession()->getPage()->checkField('bundle_types[node--article--comment]');
$this->submitForm([], 'Save configuration');
$this->assertSession()->responseContains('The configuration options have been saved.');
$this->drupalGet("admin/config/people/comment_notify");
- $this->assertTrue($this->getSession()->getPage()->hasCheckedField('node_types[article]'));
+ $this->assertTrue($this->getSession()->getPage()->hasCheckedField('bundle_types[node--article--comment]'));
// Test that Available subscription modes are saved correctly.
$this->getSession()->getPage()->checkField('available_alerts[1]');
@@ -99,17 +103,17 @@ class CommentNotifyConfigPageTest extends CommentNotifyTestBase {
$field = $this->getSession()->getPage()->findField('Default state for the notification selection box');
$this->assertTrue($field->getValue() == "2");
- $this->getSession()->getPage()->checkField('Subscribe users to their node follow-up notification emails by default');
+ $this->getSession()->getPage()->checkField('Subscribe users to their entity follow-up notification emails by default');
$this->submitForm([], 'Save configuration');
$this->assertSession()->responseContains('The configuration options have been saved.');
$this->drupalGet("admin/config/people/comment_notify");
- $this->assertTrue($this->getSession()->getPage()->hasCheckedField('Subscribe users to their node follow-up notification emails by default'));
+ $this->assertTrue($this->getSession()->getPage()->hasCheckedField('Subscribe users to their entity follow-up notification emails by default'));
- $this->getSession()->getPage()->uncheckField('Subscribe users to their node follow-up notification emails by default');
+ $this->getSession()->getPage()->uncheckField('Subscribe users to their entity follow-up notification emails by default');
$this->submitForm([], 'Save configuration');
$this->assertSession()->responseContains('The configuration options have been saved.');
$this->drupalGet("admin/config/people/comment_notify");
- $this->assertTrue($this->getSession()->getPage()->hasUncheckedField('Subscribe users to their node follow-up notification emails by default'));
+ $this->assertTrue($this->getSession()->getPage()->hasUncheckedField('Subscribe users to their entity follow-up notification emails by default'));
$this->getSession()->getPage()->fillField('Default mail text for sending out notifications to commenters', 'Hello');
$this->submitForm([], 'Save configuration');
@@ -118,14 +122,69 @@ class CommentNotifyConfigPageTest extends CommentNotifyTestBase {
$field = $this->getSession()->getPage()->findField('Default mail text for sending out notifications to commenters');
$this->assertTrue($field->getValue() == 'Hello');
- $this->getSession()->getPage()->fillField('Default mail text for sending out the notifications to node authors', 'Hello');
+ $this->getSession()->getPage()->fillField('Default mail text for sending out the notifications to entity authors', 'Hello');
$this->submitForm([], 'Save configuration');
$this->assertSession()->responseContains('The configuration options have been saved.');
$this->drupalGet("admin/config/people/comment_notify");
- $field = $this->getSession()->getPage()->findField('Default mail text for sending out the notifications to node authors');
+ $field = $this->getSession()->getPage()->findField('Default mail text for sending out the notifications to entity authors');
$this->assertTrue($field->getValue() == 'Hello');
$this->drupalLogout();
}
+ /**
+ * Tests the warning message when anonymous users have configuration problems.
+ */
+ public function testsAnonymousProblemsAreReported() {
+
+ // Tests that the anonymous users have the permission to use comment notify
+ // but aren't allowed to leave posts.
+ user_role_grant_permissions(
+ AccountInterface::ANONYMOUS_ROLE,
+ [
+ 'access comments',
+ 'access content',
+ 'subscribe to comments',
+ ]
+ );
+
+ $this->drupalLogin($this->adminUser);
+ $this->drupalGet("admin/config/people/comment_notify");
+
+ // Test that a warning error is displayed when anonymous users have the
+ // permission to use comment notify but cannot post posts.
+ $this->assertSession()->responseContains('Anonymous commenters have the permission to subscribe to comments but they need to be allowed to:');
+ $this->assertSession()->responseContains('Post comments');
+
+ user_role_grant_permissions(
+ AccountInterface::ANONYMOUS_ROLE,
+ [
+ 'post comments',
+ ]
+ );
+ $this->drupalGet("admin/config/people/comment_notify");
+ $this->assertSession()->responseNotContains('Anonymous commenters have the permission to subscribe to comments but they need to be allowed to:');
+ $this->assertSession()->responseNotContains('Post comments');
+
+ // Tests that a warning error is displayed when anonymous users haven't
+ // permission to leave their contact information.
+ $comment_field = FieldConfig::loadByName('node', 'article', 'comment');
+ $comment_field->setSetting('anonymous', CommentInterface::ANONYMOUS_MAYNOT_CONTACT);
+ $comment_field->save();
+ $this->drupalGet("admin/config/people/comment_notify");
+ $this->assertSession()->responseContains('Anonymous commenters have the permission to subscribe to comments but they need to be allowed to:');
+ $this->assertSession()->responseContains('Leave their contact information on the following fields:');
+ $this->assertSession()->responseContains('node--article--comment');
+
+ // If the field_ui module is installed then the field with the problem must
+ // be a link.
+ $this->container->get('module_installer')->install(['field_ui'], TRUE);
+ $this->rebuildContainer();
+ $this->drupalGet("admin/config/people/comment_notify");
+ $this->assertSession()->responseContains('Anonymous commenters have the permission to subscribe to comments but they need to be allowed to:');
+ $this->assertSession()->responseContains('Leave their contact information on the following fields:');
+ $this->assertSession()->responseContains('node--article--comment');
+ $this->assertSession()->linkByHrefExists('/admin/structure/types/manage/article/fields/node.article.comment');
+ }
+
}
diff --git a/tests/src/Functional/CommentNotifyNotificationsTest.php b/tests/src/Functional/CommentNotifyNotificationsTest.php
index 833f7fd..fe3e4fe 100644
--- a/tests/src/Functional/CommentNotifyNotificationsTest.php
+++ b/tests/src/Functional/CommentNotifyNotificationsTest.php
@@ -2,8 +2,12 @@
namespace Drupal\Tests\comment_notify\Functional;
+use Drupal\comment\CommentInterface;
use Drupal\comment\Entity\Comment;
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\field\Entity\FieldConfig;
+use Drupal\Tests\taxonomy\Functional\TaxonomyTestTrait;
/**
* Tests that all the notifications are sent as expected.
@@ -12,6 +16,21 @@ use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
*/
class CommentNotifyNotificationsTest extends CommentNotifyTestBase {
+ use TaxonomyTestTrait;
+
+ /**
+ * Modules to enable.
+ *
+ * @var array
+ */
+ public static $modules = [
+ 'comment_notify',
+ 'node',
+ 'comment',
+ 'token',
+ 'taxonomy',
+ ];
+
/**
* The permissions required by the tests.
*
@@ -31,7 +50,7 @@ class CommentNotifyNotificationsTest extends CommentNotifyTestBase {
*/
public function testCommentNotification() {
$user1 = $this->drupalCreateUser($this->permissions);
- comment_notify_set_user_notification_setting($user1->id(), COMMENT_NOTIFY_NODE, COMMENT_NOTIFY_COMMENT);
+ comment_notify_set_user_notification_setting($user1->id(), COMMENT_NOTIFY_ENTITY, COMMENT_NOTIFY_COMMENT);
$user2 = $this->drupalCreateUser($this->permissions);
$node = $this->drupalCreateNode(
[
@@ -44,7 +63,7 @@ class CommentNotifyNotificationsTest extends CommentNotifyTestBase {
$node->toUrl()->toString(),
$this->randomMachineName(),
$this->randomMachineName(),
- ['notify' => TRUE, 'notify_type' => COMMENT_NOTIFY_NODE]
+ ['notify' => TRUE, 'notify_type' => COMMENT_NOTIFY_ENTITY]
);
// Test that the notification was sent.
$this->assertMail('to', $user1->getEmail(), t('Message was sent to the user.'));
@@ -66,6 +85,10 @@ class CommentNotifyNotificationsTest extends CommentNotifyTestBase {
public function testCommentTypeNotification() {
// Add a second comment type.
$this->addDefaultCommentField('node', 'article', 'field_comment', CommentItemInterface::OPEN, 'comment_type_2');
+ /** @var \Drupal\Core\Config\Config $config */
+ $config = $this->container->get('config.factory')->getEditable('comment_notify.settings');
+ $config->set('bundle_types', ['node--article--comment', 'node--article--field_comment']);
+ $config->save();
$user1 = $this->drupalCreateUser($this->permissions);
$user2 = $this->drupalCreateUser($this->permissions);
@@ -144,4 +167,90 @@ class CommentNotifyNotificationsTest extends CommentNotifyTestBase {
}
+ /**
+ * Tests that the notifications are working on a different entity than a node.
+ */
+ public function testEntityNotification() {
+ /** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
+ $vocabulary = $this->createVocabulary();
+ $this->addDefaultCommentField('taxonomy_term', $vocabulary->id(), 'field_comment_taxonomy', CommentItemInterface::OPEN, 'comment_type_2');
+ $comment_field = FieldConfig::loadByName('taxonomy_term', $vocabulary->id(), 'field_comment_taxonomy');
+ $comment_field->setSetting('anonymous', CommentInterface::ANONYMOUS_MAY_CONTACT);
+ $comment_field->save();
+
+ /** @var \Drupal\Core\Config\Config $config */
+ $config = $this->container->get('config.factory')->getEditable('comment_notify.settings');
+ $config->set('bundle_types', ['taxonomy_term--' . $vocabulary->id() . '--field_comment_taxonomy']);
+ $config->save();
+
+ // Allow anonymous users to post comments and get notifications.
+ user_role_grant_permissions(
+ AccountInterface::ANONYMOUS_ROLE,
+ [
+ 'access comments',
+ 'access content',
+ 'post comments',
+ 'skip comment approval',
+ 'subscribe to comments',
+ ]
+ );
+
+ $permissions = array_merge($this->permissions, ['access user profiles']);
+ $user1 = $this->drupalCreateUser($permissions);
+ comment_notify_set_user_notification_setting($user1->id(), COMMENT_NOTIFY_DISABLED, COMMENT_NOTIFY_ENTITY);
+ $user2 = $this->drupalCreateUser($permissions);
+ comment_notify_set_user_notification_setting($user2->id(), COMMENT_NOTIFY_DISABLED, COMMENT_NOTIFY_COMMENT);
+
+ $term = $this->createTerm($vocabulary);
+ $term2 = $this->createTerm($vocabulary);
+
+ // User1 Should get notification for any new comment on the entity.
+ $this->drupalLogin($user1);
+ $this->postComment(
+ $term->toUrl()->toString(),
+ $this->randomMachineName(),
+ $this->randomMachineName(),
+ ['notify' => TRUE, 'notify_type' => COMMENT_NOTIFY_ENTITY]
+ );
+ $this->drupalLogout();
+ $this->postComment(
+ $term->toUrl()->toString(),
+ $this->randomMachineName(),
+ $this->randomMachineName(),
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY],
+ ['name' => $this->randomMachineName(), 'mail' => $this->getRandomEmailAddress()]
+ );
+ $this->assertMail('to', $user1->getEmail(), t('Message was sent to the user1 user.'));
+ $this->container->get('state')->set('system.test_mail_collector', []);
+
+ // User 2 should get a notification only when someone reply to its comment.
+ $this->drupalLogin($user2);
+ $comment = $this->postComment(
+ $term2->toUrl()->toString(),
+ $this->randomMachineName(),
+ $this->randomMachineName(),
+ ['notify' => TRUE, 'notify_type' => COMMENT_NOTIFY_COMMENT]
+ );
+ $this->drupalLogout();
+ $this->postComment(
+ $term2->toUrl()->toString(),
+ $this->randomMachineName(),
+ $this->randomMachineName(),
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY],
+ ['name' => $this->randomMachineName(), 'mail' => $this->getRandomEmailAddress()]
+ );
+ $this->assertEmpty($this->getMails(), 'No notification was sent');
+ $this->drupalGet('/comment/reply/taxonomy_term/' . $term2->id() . '/field_comment_taxonomy/' . $comment['id']);
+ // /comment/reply/taxonomy_term/1/field_comment_taxonomy/2.
+ $this->postComment(
+ '/comment/reply/taxonomy_term/' . $term2->id() . '/field_comment_taxonomy/' . $comment['id'],
+ $this->randomMachineName(),
+ $this->randomMachineName(),
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY],
+ ['name' => $this->randomMachineName(), 'mail' => $this->getRandomEmailAddress()]
+ );
+ $this->assertMail('to', $user2->getEmail(), t('Message was sent to the user1 user.'));
+ $this->container->get('state')->set('system.test_mail_collector', []);
+ }
+
}
diff --git a/tests/src/Functional/CommentNotifyUserPreferencesTest.php b/tests/src/Functional/CommentNotifyUserPreferencesTest.php
index f11644d..03d86ea 100644
--- a/tests/src/Functional/CommentNotifyUserPreferencesTest.php
+++ b/tests/src/Functional/CommentNotifyUserPreferencesTest.php
@@ -148,7 +148,7 @@ class CommentNotifyUserPreferencesTest extends CommentNotifyTestBase {
// Test the "All comments" option.
$this->drupalGet($this->authenticatedUser->toUrl('edit-form')->toString());
- $this->getSession()->getPage()->selectFieldOption('comment_notify', COMMENT_NOTIFY_NODE);
+ $this->getSession()->getPage()->selectFieldOption('comment_notify', COMMENT_NOTIFY_ENTITY);
$this->getSession()->getPage()->pressButton(t('Save'));
$this->drupalGet($node->toUrl()->toString());
$this->assertTrue($this->getSession()->getPage()->hascheckedField('Notify me when new comments are posted'));
@@ -187,8 +187,8 @@ class CommentNotifyUserPreferencesTest extends CommentNotifyTestBase {
$this->assertTrue($this->getSession()->getPage()->hasContent(t('Receive content follow-up notification e-mails')));
$this->getSession()->getPage()->checkField('Receive content follow-up notification e-mails');
$this->getSession()->getPage()->pressButton(t('Save'));
- $node_notify_preference = comment_notify_get_user_node_notify_preference($this->authenticatedUser->id());
- $this->assertEquals(COMMENT_NOTIFY_NODE, $node_notify_preference);
+ $node_notify_preference = comment_notify_get_user_entity_notify_preference($this->authenticatedUser->id());
+ $this->assertEquals(COMMENT_NOTIFY_ENTITY, $node_notify_preference);
$this->drupalLogout();
// Tests that the notification is sent when the content created by the user
@@ -214,7 +214,7 @@ class CommentNotifyUserPreferencesTest extends CommentNotifyTestBase {
$node->toUrl()->toString(),
$this->randomMachineName(),
$this->randomMachineName(),
- ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_NODE]
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY]
);
// Test that the notification was sent.
@@ -230,7 +230,7 @@ class CommentNotifyUserPreferencesTest extends CommentNotifyTestBase {
$this->assertTrue($this->getSession()->getPage()->hasUncheckedField('Receive content follow-up notification e-mails'));
$this->drupalLogout();
drupal_static_reset('comment_notify_get_user_notification_setting');
- $node_notify_preference = comment_notify_get_user_node_notify_preference($this->authenticatedUser->id());
+ $node_notify_preference = comment_notify_get_user_entity_notify_preference($this->authenticatedUser->id());
$this->assertEquals(COMMENT_NOTIFY_DISABLED, $node_notify_preference);
$this->container->get('state')->set('system.test_mail_collector', []);
@@ -244,7 +244,7 @@ class CommentNotifyUserPreferencesTest extends CommentNotifyTestBase {
$node->toUrl()->toString(),
$this->randomMachineName(),
$this->randomMachineName(),
- ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_NODE]
+ ['notify' => FALSE, 'notify_type' => COMMENT_NOTIFY_ENTITY]
);
$captured_emails = $this->container->get('state')->get('system.test_mail_collector');
$this->assertEmpty($captured_emails, 'No notifications has been sent.');
@@ -263,14 +263,14 @@ class CommentNotifyUserPreferencesTest extends CommentNotifyTestBase {
foreach ($cancel_method_options as $cancel_method_option) {
$user = $this->drupalCreateUser($this->permissions);
- comment_notify_set_user_notification_setting($user->id(), COMMENT_NOTIFY_NODE, COMMENT_NOTIFY_COMMENT);
+ comment_notify_set_user_notification_setting($user->id(), COMMENT_NOTIFY_ENTITY, COMMENT_NOTIFY_COMMENT);
user_cancel([], $user->id(), $cancel_method_option);
$this->assertTrue(is_null(comment_notify_get_user_notification_setting($user->id())));
}
// Delete Account.
$user = $this->drupalCreateUser($this->permissions);
- comment_notify_set_user_notification_setting($user->id(), COMMENT_NOTIFY_NODE, COMMENT_NOTIFY_COMMENT);
+ comment_notify_set_user_notification_setting($user->id(), COMMENT_NOTIFY_ENTITY, COMMENT_NOTIFY_COMMENT);
$user->delete();
$this->assertTrue(is_null(comment_notify_get_user_notification_setting($user->id())));
}