Verified Commit 9e837365 authored by Andrei Mateescu's avatar Andrei Mateescu
Browse files

task: #3620912 Deprecate user.module cancel methods

By: nicxvan
By: danielveza
By: godotislate
By: amateescu
parent 94a65fff
Loading
Loading
Loading
Loading
Loading
+12 −4
Original line number Diff line number Diff line
@@ -58,6 +58,7 @@
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Drupal\Core\Http\Exception\CacheableBadRequestHttpException;
use Drupal\user\AccountCancellation;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
@@ -91,7 +92,14 @@ public function __construct(
    protected TimeInterface $time,
    protected AccountInterface $user,
    protected EventDispatcherInterface $eventDispatcher,
  ) {}
    protected ?AccountCancellation $accountCancellation = NULL,
  ) {
    if ($accountCancellation === NULL) {
      @trigger_error('Calling ' . __METHOD__ . '() without the $accountCancellation argument is deprecated in drupal:11.5.0 and it will be required in drupal:12.0.0. See https://www.drupal.org/node/3620934', E_USER_DEPRECATED);
      $accountCancellation = \Drupal::service(AccountCancellation::class);
    }
    $this->accountCancellation = $accountCancellation;
  }

  /**
   * Gets the individual entity.
@@ -277,9 +285,9 @@ public function deleteIndividual(EntityInterface $entity) {

      // Allow other modules to act.

      user_cancel([], $entity->id(), $cancel_method);
      // Since user_cancel() is not invoked via Form API, batch processing
      // needs to be invoked manually.
      $this->accountCancellation->cancel([], $entity->id(), $cancel_method);
      // Since AccountCancellation::cancel() is not invoked via Form API, batch
      // processing needs to be invoked manually.
      $batch =& batch_get();
      // Mark this batch as non-progressive to bypass the progress bar and
      // redirect.
+231 −0
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\user;

use Drupal\Core\Batch\BatchBuilder;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Session\AnonymousUserSession;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\Attribute\AutowireServiceClosure;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

/**
 * User account cancellation service.
 */
class AccountCancellation {

  use StringTranslationTrait;

  public function __construct(
    protected readonly ModuleHandlerInterface $moduleHandler,
    protected readonly EntityTypeManagerInterface $entityTypeManager,
    protected readonly AccountProxyInterface $currentUser,
    protected readonly MessengerInterface $messenger,
    protected readonly NotificationHandler $notificationHandler,
    #[Autowire('@logger.channel.user')]
    protected readonly LoggerInterface $logger,
    protected readonly SessionInterface $session,
    /**
     * @var \Closure(): \Drupal\Core\Config\ConfigFactoryInterface
     */
    #[AutowireServiceClosure('config.factory')]
    protected \Closure $configFactoryClosure,
  ) {}

  /**
   * Cancel a user account.
   *
   * Since the user cancellation process needs to be run in a batch, either
   * Form API will invoke it, or batch_process() needs to be invoked after
   * calling this function and should define the path to redirect to.
   *
   * @param array $edit
   *   An array of submitted form values.
   * @param int $uid
   *   The user ID of the user account to cancel.
   * @param string $method
   *   The account cancellation method to use.
   *
   * @see static::cancelAccount()
   */
  public function cancel(array $edit, int $uid, string $method): void {
    $account = $this->entityTypeManager->getStorage('user')->load($uid);

    if (!$account) {
      $this->messenger->addError($this->t('The user account %id does not exist.', ['%id' => $uid]));
      $this->logger->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
      return;
    }

    // Initialize batch (to set title).
    $batchBuilder = (new BatchBuilder())
      ->setTitle($this->t('Cancelling account'));
    batch_set($batchBuilder->toArray());

    // When the 'user_cancel_delete' method is used, user_delete() is called,
    // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
    // for the user entity. Modules should use those hooks to respond to the
    // account deletion.
    if ($method != 'user_cancel_delete') {
      // Allow modules to add further sets to this batch.
      $this->moduleHandler->invokeAll('user_cancel', [$edit, $account, $method]);
    }

    // Finish the batch and actually cancel the account.
    $batchBuilder = (new BatchBuilder())
      ->setTitle($this->t('Cancelling user account'))
      ->addOperation(static::class . ':cancelAccount', [$edit, $account, $method]);

    // After cancelling account, ensure that user is logged out.
    if ($account->id() == $this->currentUser->id()) {
      // Batch API stores data in the session, so use the finished operation to
      // manipulate the current user's session id.
      $batchBuilder->setFinishCallback(static::class . ':regenerateSession');
    }

    batch_set($batchBuilder->toArray());

    // Batch processing is either handled via Form API or has to be invoked
    // manually.
  }

  /**
   * Implements callback_batch_operation().
   *
   * Last step for cancelling a user account.
   *
   * Since batch and session API require a valid user account, the actual
   * cancellation of a user account needs to happen last.
   *
   * @param array $edit
   *   An array of submitted form values.
   * @param \Drupal\user\UserInterface $account
   *   The user account to cancel.
   * @param string $method
   *   The account cancellation method to use.
   *
   * @see AccountCancellation::cancel()
   *
   * @internal
   */
  public function cancelAccount(array $edit, UserInterface $account, string $method): void {
    switch ($method) {
      case 'user_cancel_block':
      case 'user_cancel_block_unpublish':
      default:
        // Send account blocked notification if option was checked.
        if (!empty($edit['user_cancel_notify'])) {
          $this->notificationHandler->sendStatusBlocked($account);
        }
        $account->block();
        $account->save();
        $this->messenger->addStatus($this->t('Account %name has been disabled.', ['%name' => $account->getDisplayName()]));
        $this->logger->notice('Blocked user: %name %email.', [
          '%name' => $account->getAccountName(),
          '%email' => '<' . $account->getEmail() . '>',
        ]);
        break;

      case 'user_cancel_reassign':
      case 'user_cancel_delete':
        // Send account canceled notification if option was checked.
        if (!empty($edit['user_cancel_notify'])) {
          $this->notificationHandler->sendStatusCancelled($account);
        }
        $account->delete();
        $this->messenger->addStatus($this->t('Account %name has been deleted.', ['%name' => $account->getDisplayName()]));
        $this->logger->notice('Deleted user: %name %email.', [
          '%name' => $account->getAccountName(),
          '%email' => '<' . $account->getEmail() . '>',
        ]);
        break;
    }

    // After cancelling account, ensure that user is logged out. We can't
    // destroy their session though, as we might have information in it, and we
    // can't regenerate it because batch API uses the session ID, we will
    // regenerate it in static::regenerateSession().
    if ($account->id() == $this->currentUser->id()) {
      $this->currentUser->setAccount(new AnonymousUserSession());
    }
  }

  /**
   * Implements callback_batch_finished().
   *
   * Finished batch processing callback for cancelling a user account.
   *
   * @see AccountCancellation::cancel()
   *
   * @internal
   */
  public function regenerateSession(): void {
    // Regenerate the users session instead of calling session_destroy() as we
    // want to preserve any messages that might have been set.
    $this->session->migrate();
  }

  /**
   * Helper function to return available account cancellation methods.
   *
   * See documentation of hook_user_cancel_methods_alter().
   *
   * @return array
   *   An array containing all account cancellation methods as form elements.
   *
   * @see hook_user_cancel_methods_alter()
   * @see user_admin_settings()
   */
  public function cancelMethods(): array {
    $userSettings = ($this->configFactoryClosure)()->get('user.settings');
    $anonymous_name = $userSettings->get('anonymous');
    $methods = [
      'user_cancel_block' => [
        'title' => $this->t('Disable the account and keep its content.'),
        'description' => $this->t('Your account will be blocked and you will no longer be able to log in. All of your content will remain attributed to your username.'),
      ],
      'user_cancel_block_unpublish' => [
        'title' => $this->t('Disable the account and unpublish its content.'),
        'description' => $this->t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'),
      ],
      'user_cancel_reassign' => [
        'title' => $this->t('Delete the account and make its content belong to the %anonymous-name user. This action cannot be undone.', ['%anonymous-name' => $anonymous_name]),
        'description' => $this->t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
      ],
      'user_cancel_delete' => [
        'title' => $this->t('Delete the account and its content. This action cannot be undone.'),
        'description' => $this->t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
        'access' => $this->currentUser->hasPermission('administer users'),
      ],
    ];
    // Allow modules to customize account cancellation methods.
    $this->moduleHandler->alter('user_cancel_methods', $methods);

    // Turn all methods into real form elements.
    $form = [
      '#options' => [],
      '#default_value' => $userSettings->get('cancel_method'),
    ];
    foreach ($methods as $name => $method) {
      $form['#options'][$name] = $method['title'];
      // Add the description for the confirmation form. This description is
      // never shown for the cancel method option, only on the confirmation
      // form. Therefore, we use a custom #confirm_description property.
      if (isset($method['description'])) {
        $form[$name]['#confirm_description'] = $method['description'];
      }
      if (isset($method['access'])) {
        $form[$name]['#access'] = $method['access'];
      }
    }
    return $form;
  }

}
+14 −13
Original line number Diff line number Diff line
@@ -32,17 +32,12 @@ class AccountSettingsForm extends ConfigFormBase {
   */
  protected $roleStorage;

  /**
   * Constructs a \Drupal\user\AccountSettingsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typedConfigManager
   *   The typed config manager.
   * @param \Drupal\user\RoleStorageInterface|\Drupal\Core\Extension\ModuleHandlerInterface $role_storage
   *   The role storage.
   */
  public function __construct(ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typedConfigManager, RoleStorageInterface|ModuleHandlerInterface $role_storage) {
  public function __construct(
    ConfigFactoryInterface $config_factory,
    TypedConfigManagerInterface $typedConfigManager,
    RoleStorageInterface|ModuleHandlerInterface $role_storage,
    protected ?AccountCancellation $accountCancellation = NULL,
  ) {
    parent::__construct($config_factory, $typedConfigManager);

    $this->roleStorage = $role_storage;
@@ -51,6 +46,11 @@ public function __construct(ConfigFactoryInterface $config_factory, TypedConfigM
      $this->roleStorage = func_get_arg(3);
      @trigger_error('Calling ' . __METHOD__ . '() with the $module_handler argument is deprecated in drupal:11.4.0 and is removed from drupal:12.0.0. See https://www.drupal.org/node/3566911', E_USER_DEPRECATED);
    }
    if ($accountCancellation === NULL) {
      @trigger_error('Calling ' . __METHOD__ . '() without the $accountCancellation argument is deprecated in drupal:11.5.0 and it will be required in drupal:12.0.0. See https://www.drupal.org/node/3620934', E_USER_DEPRECATED);
      $accountCancellation = \Drupal::service(AccountCancellation::class);
    }
    $this->accountCancellation = $accountCancellation;
  }

  /**
@@ -60,7 +60,8 @@ public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('entity_type.manager')->getStorage('user_role')
      $container->get('entity_type.manager')->getStorage('user_role'),
      $container->get(AccountCancellation::class),
    );
  }

@@ -144,7 +145,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
          ->toString(),
      ]),
    ];
    $form['registration_cancellation']['user_cancel_method'] += user_cancel_methods();
    $form['registration_cancellation']['user_cancel_method'] += $this->accountCancellation->cancelMethods();
    foreach (Element::children($form['registration_cancellation']['user_cancel_method']) as $key) {
      // All account cancellation methods that specify #access cannot be
      // configured as default method.
+14 −1
Original line number Diff line number Diff line
@@ -10,6 +10,7 @@
use Drupal\Core\Flood\FloodInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\user\AccountCancellation;
use Drupal\user\Form\UserPasswordResetForm;
use Drupal\user\OneTimeAuthentication;
use Drupal\user\UserDataInterface;
@@ -79,6 +80,11 @@ class UserController extends ControllerBase {
   */
  protected LogoutFinalizer $logoutFinalizer;

  /**
   * The account cancellation service.
   */
  protected AccountCancellation $accountCancellation;

  public function __construct(
    DateFormatterInterface $date_formatter,
    UserStorageInterface $user_storage,
@@ -89,6 +95,7 @@ public function __construct(
    ?OneTimeAuthentication $one_time_authentication = NULL,
    ?LoginFinalizer $loginFinalizer = NULL,
    ?LogoutFinalizer $logoutFinalizer = NULL,
    ?AccountCancellation $accountCancellation = NULL,
  ) {
    $this->dateFormatter = $date_formatter;
    $this->userStorage = $user_storage;
@@ -109,6 +116,11 @@ public function __construct(
      $logoutFinalizer = \Drupal::service(LogoutFinalizer::class);
    }
    $this->logoutFinalizer = $logoutFinalizer;
    if ($accountCancellation === NULL) {
      @trigger_error('Calling ' . __METHOD__ . '() without the $accountCancellation argument is deprecated in drupal:11.5.0 and it will be required in drupal:12.0.0. See https://www.drupal.org/node/3620934', E_USER_DEPRECATED);
      $accountCancellation = \Drupal::service(AccountCancellation::class);
    }
    $this->accountCancellation = $accountCancellation;
  }

  /**
@@ -125,6 +137,7 @@ public static function create(ContainerInterface $container) {
      $container->get(OneTimeAuthentication::class),
      $container->get(LoginFinalizer::class),
      $container->get(LogoutFinalizer::class),
      $container->get(AccountCancellation::class),
    );
  }

@@ -524,7 +537,7 @@ public function confirmCancel(UserInterface $user, $timestamp = 0, $hashed_pass
        $edit = [
          'user_cancel_notify' => $account_data['cancel_notify'] ?? $this->config('user.settings')->get('notify.status_canceled'),
        ];
        user_cancel($edit, $user->id(), $account_data['cancel_method']);
        $this->accountCancellation->cancel($edit, $user->id(), $account_data['cancel_method']);
        // Since user_cancel() is not invoked via Form API, batch processing
        // needs to be invoked manually and should redirect to the front page
        // after completion.
+14 −5
Original line number Diff line number Diff line
@@ -7,6 +7,7 @@
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\AccountCancellation;
use Drupal\user\NotificationHandler;
use Symfony\Component\DependencyInjection\ContainerInterface;

@@ -48,12 +49,18 @@ public function __construct(
    EntityTypeBundleInfoInterface $entity_type_bundle_info,
    TimeInterface $time,
    ?NotificationHandler $notification_handler = NULL,
    protected ?AccountCancellation $accountCancellation = NULL,
  ) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    if ($notification_handler === NULL) {
      @trigger_error('Calling ' . __CLASS__ . ' constructor without the $notificationHandler argument is deprecated in drupal:11.5.0 and it will be required in drupal:12.0.0. See https://www.drupal.org/node/3539363', E_USER_DEPRECATED);
    }
    $this->notificationHandler = $notification_handler ?? \Drupal::service(NotificationHandler::class);
    if ($accountCancellation === NULL) {
      @trigger_error('Calling ' . __METHOD__ . '() without the $accountCancellation argument is deprecated in drupal:11.5.0 and it will be required in drupal:12.0.0. See https://www.drupal.org/node/3620934', E_USER_DEPRECATED);
      $accountCancellation = \Drupal::service(AccountCancellation::class);
    }
    $this->accountCancellation = $accountCancellation;
  }

  /**
@@ -65,6 +72,7 @@ public static function create(ContainerInterface $container): static {
      $container->get(EntityTypeBundleInfoInterface::class),
      $container->get(TimeInterface::class),
      $container->get(NotificationHandler::class),
      $container->get(AccountCancellation::class),
    );
  }

@@ -94,9 +102,10 @@ public function getDescription() {
    }
    $default_method = $this->config('user.settings')->get('cancel_method');
    $own_account = $this->entity->id() == $this->currentUser()->id();
    // Options supplied via user_cancel_methods() can have a custom
    // #confirm_description property for the confirmation form description. This
    // text refers to "Your account" so only user it if cancelling own account.
    // Options supplied via AccountCancellation::cancelMethods() can have a
    // custom #confirm_description property for the confirmation form
    // description. This text refers to "Your account" so only user it if
    // cancelling own account.
    if ($own_account && isset($this->cancelMethods[$default_method]['#confirm_description'])) {
      return $this->cancelMethods[$default_method]['#confirm_description'];
    }
@@ -116,7 +125,7 @@ public function getConfirmText() {
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $user = $this->currentUser();
    $this->cancelMethods = user_cancel_methods();
    $this->cancelMethods = $this->accountCancellation->cancelMethods();

    // Display account cancellation method selection, if allowed.
    $own_account = $this->entity->id() == $user->id();
@@ -172,7 +181,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
    // privileges, no confirmation mail shall be sent, and the user does not
    // attempt to cancel the own account.
    if (!$form_state->isValueEmpty('access') && $form_state->isValueEmpty('user_cancel_confirm') && $this->entity->id() != $this->currentUser()->id()) {
      user_cancel($form_state->getValues(), $this->entity->id(), $form_state->getValue('user_cancel_method'));
      $this->accountCancellation->cancel($form_state->getValues(), $this->entity->id(), $form_state->getValue('user_cancel_method'));

      $form_state->setRedirectUrl($this->entity->toUrl('collection'));
    }
Loading