Skip to content
Snippets Groups Projects
Commit bc2b16ef authored by Adrian Lorenc's avatar Adrian Lorenc Committed by Claudiu Cristea
Browse files

Issue #3487705 by alorenc, claudiu.cristea: Refactor BanUserForm

parent 009cfd42
No related branches found
No related tags found
1 merge request!140Resolve #3487705 "Refactor banuserform"
Pipeline #342109 passed
(($, Drupal) => {
/**
* Override drupal selectHandler function
* @param {jQuery.Event} event The event
* @param {Object} ui UI
* @return {boolean} Members ban
*/
function membersBanSelectHandler(event, ui) {
let valueField = $(event.target);
if ($(event.target).hasClass('private-message-ban-autocomplete')) {
const valueFieldName = 'banned_user';
if ($(`input[name=${valueFieldName}]`).length > 0) {
valueField = $(`input[name=${valueFieldName}]`);
// Update the labels too.
const labels = Drupal.autocomplete.splitValues(event.target.value);
labels.pop();
labels.push(ui.item.label);
event.target.value = labels.join(', ');
}
}
const terms = Drupal.autocomplete.splitValues(valueField.val());
// Remove the current input.
terms.pop();
// Add the selected item.
terms.push(ui.item.value);
valueField.val(terms.join(', '));
// Return false to tell jQuery UI that we've filled in the value already.
return false;
}
Drupal.behaviors.privateMessageBan = {
attach() {
// Attach custom select handler to fields with class.
$('input.private-message-ban-autocomplete').autocomplete({
select: membersBanSelectHandler,
});
},
};
})(jQuery, Drupal);
......@@ -71,8 +71,3 @@ uninstall_page:
- core/jquery
- core/once
ban_autocomplete:
js:
js/private_message_ban_user_autocomplete.js: {}
dependencies:
- core/jquery
......@@ -147,15 +147,6 @@ private_message.ban_page:
requirements:
_permission: 'use private messaging system,access user profiles'
private_message.ban_autocomplete:
path: '/private-message/autocomplete/ban-members'
defaults:
_controller: '\Drupal\private_message\Controller\AjaxController::privateMessageBanMembersAutocomplete'
_format: json
requirements:
_user_is_logged_in: 'TRUE'
_permission: 'use private messaging system,access user profiles'
private_message.ban_user_form:
path: '/private-message/ban/{user}'
defaults:
......
......@@ -3,7 +3,6 @@
namespace Drupal\private_message\Controller;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\Tags;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\SettingsCommand;
use Drupal\Core\Config\ConfigFactoryInterface;
......@@ -25,8 +24,6 @@ use Drupal\private_message\Entity\PrivateMessageThread;
use Drupal\private_message\Service\PrivateMessageBanManagerInterface;
use Drupal\private_message\Service\PrivateMessageServiceInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
......@@ -244,30 +241,6 @@ class AjaxController extends ControllerBase implements AjaxControllerInterface {
return $response;
}
/**
* Handler for autocomplete request for banning people.
*/
public function privateMessageBanMembersAutocomplete(Request $request) {
$results = [];
if ($input = $request->query->get('q')) {
$typed_string = Tags::explode($input);
$typed_string = mb_strtolower(array_pop($typed_string));
$accounts = $this->privateMessageService->getUsersFromString($typed_string, self::AUTOCOMPLETE_COUNT);
foreach ($accounts as $account) {
if (!$this->privateMessageBanManager->isBanned($account->id())) {
$results[] = [
'value' => $account->id(),
'label' => $account->getDisplayName(),
];
}
}
}
return new JsonResponse($results);
}
/**
* Creates an Ajax Command containing new private message.
*
......
......@@ -70,7 +70,7 @@ class BanUserForm extends FormBase {
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
public static function create(ContainerInterface $container): self {
return new static(
$container->get('current_user'),
$container->get('entity_type.manager'),
......@@ -89,44 +89,24 @@ class BanUserForm extends FormBase {
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $target_id = NULL): array {
public function buildForm(array $form, FormStateInterface $form_state): array {
$config = $this->configFactory->get('private_message.settings');
if ($target_id === NULL) {
$form['user_name'] = [
'#title' => ('Select User'),
'#type' => 'textfield',
'#required' => FALSE,
'#attributes' => [
'class' => [
'private-message-ban-autocomplete',
],
],
'#autocomplete_route_name' => 'private_message.ban_autocomplete',
'#attached' => [
'library' => [
'private_message/ban_autocomplete',
],
],
];
}
$form['banned_user'] = [
'#type' => 'hidden',
'#title' => $this->t('Blocked User'),
'#default_value' => $target_id,
'#required' => FALSE,
'#title' => $this->t('Select User'),
'#required' => TRUE,
'#type' => 'entity_autocomplete',
'#target_type' => 'user',
'#tags' => FALSE,
'#selection_handler' => 'private_message:not_blocked_user',
'#selection_settings' => [
'include_anonymous' => FALSE,
],
];
$submitLabel = $config->get('ban_label');
if ($target_id && $this->privateMessageBanManager->isBanned($target_id)) {
$submitLabel = $config->get('unban_label');
}
$form['submit'] = [
'#type' => 'submit',
'#value' => $submitLabel,
'#value' => $config->get('ban_label'),
];
return $form;
......@@ -136,35 +116,30 @@ class BanUserForm extends FormBase {
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state): void {
$user_id_field = !empty($form_state->getValue('banned_user')) ? 'banned_user' : 'user_name';
$user_id = $form_state->getValue('banned_user');
$userId = $form_state->getValue('banned_user');
// Add security to prevent blocking ourselves.
if ($user_id === $this->currentUser->id()) {
$form_state->setErrorByName($user_id_field, $this->t("You can't block yourself."));
if ($userId === $this->currentUser->id()) {
$form_state->setErrorByName($userId, $this->t("You can't block yourself."));
}
// Add a security if the user id is unknown.
if (empty($user_id) ||
empty($this->entityTypeManager->getStorage('user')->load($user_id))) {
$form_state->setErrorByName($user_id_field, $this->t('The user id is unknown.'));
if (empty($userId) ||
empty($this->entityTypeManager->getStorage('user')->load($userId))) {
$form_state->setErrorByName($userId, $this->t('The user id is unknown.'));
}
if (!empty($userId) && $this->privateMessageBanManager->isBanned($userId)) {
$form_state->setErrorByName($userId, $this->t('The user is already blocked.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$target_id = $form_state->getValue('banned_user');
public function submitForm(array &$form, FormStateInterface $form_state): void {
$userId = $form_state->getValue('banned_user');
// Unban if already banned.
if ($this->privateMessageBanManager->isBanned($target_id)) {
$this->privateMessageBanManager->unbanUser($target_id);
}
// Ban if not banned.
else {
$this->privateMessageBanManager->banUser($target_id);
}
$this->privateMessageBanManager->banUser($userId);
}
}
<?php
declare(strict_types=1);
namespace Drupal\private_message\Plugin\EntityReferenceSelection;
use Drupal\Core\Entity\Attribute\EntityReferenceSelection;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\user\Plugin\EntityReferenceSelection\UserSelection;
/**
* Provides reference selection for not blocked users.
*/
#[EntityReferenceSelection(
id: "private_message:not_blocked_user",
label: new TranslatableMarkup("Not blocked user selection"),
group: "private_message",
weight: 3,
entity_types: ["user"]
)]
class NotBlockedUserSelection extends UserSelection {
/**
* {@inheritdoc}
*/
protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS'): QueryInterface {
$query = parent::buildEntityQuery($match, $match_operator);
$subquery = $this->connection->select('private_message_ban', 'pmb')
->fields('pmb', ['target']);
$subquery->condition('owner', $this->currentUser->id());
$query->condition('uid', $subquery, 'NOT IN');
return $query;
}
}
......@@ -88,6 +88,46 @@ class PrivateMessageUserBanTest extends BrowserTestBase {
$this->assertSession()->linkExists('Block');
}
/**
* Tests access to the ban listing.
*/
public function testBanPageRouteAccess() {
$this->drupalLogin($this->userA);
$this->drupalGet('/private-message/ban');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('Ban/Unban users');
$this->drupalLogout();
$this->drupalGet('/private-message/ban');
$this->assertSession()->statusCodeEquals(403);
}
/**
* Tests for BanUserForm.
*/
public function testBanUserFormSubmission() {
$this->drupalLogin($this->userA);
$this->drupalGet('/private-message/ban');
$edit = [
'banned_user' => $this->userA->getDisplayName() . ' (' . $this->userA->id() . ')',
];
$this->submitForm($edit, 'Block');
$this->assertSession()->statusMessageContains("You can't block yourself.", 'error');
$edit = [
'banned_user' => $this->userB->getDisplayName() . ' (' . $this->userB->id() . ')',
];
$this->submitForm($edit, 'Block');
$this->assertSession()->statusMessageContains("The user " . $this->userB->getDisplayName() . " has been banned.", 'status');
$edit = [
'banned_user' => $this->userB->getDisplayName() . ' (' . $this->userB->id() . ')',
];
$this->submitForm($edit, 'Block');
$this->assertSession()->statusMessageContains('The user is already blocked', 'error');
}
/**
* Returns a count of bans.
*/
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment