|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Drush\Listeners\sanitize; |
| 6 | + |
| 7 | +use Drupal\Core\Database\Connection; |
| 8 | +use Drupal\Core\Database\Query\SelectInterface; |
| 9 | +use Drupal\Core\Entity\EntityTypeManagerInterface; |
| 10 | +use Drupal\Core\Password\PasswordInterface; |
| 11 | +use Drush\Commands\AutowireTrait; |
| 12 | +use Drush\Commands\sql\sanitize\SanitizeCommand; |
| 13 | +use Drush\Event\ConsoleDefinitionsEvent; |
| 14 | +use Drush\Event\SanitizeConfirmsEvent; |
| 15 | +use Drush\Sql\SqlBase; |
| 16 | +use Drush\Utils\StringUtils; |
| 17 | +use Psr\Log\LoggerInterface; |
| 18 | +use Symfony\Component\Console\Event\ConsoleTerminateEvent; |
| 19 | +use Symfony\Component\Console\Input\InputOption; |
| 20 | +use Symfony\Component\EventDispatcher\Attribute\AsEventListener; |
| 21 | + |
| 22 | +/** |
| 23 | + * Sanitize emails and passwords. This also an example of how to write a |
| 24 | + * database sanitizer for sql:sync. |
| 25 | + */ |
| 26 | +#[AsEventListener(method: 'onDefinition')] |
| 27 | +#[AsEventListener(method: 'onSanitizeConfirm')] |
| 28 | +#[AsEventListener(method: 'onConsoleTerminate')] |
| 29 | +final class SanitizeUserTableListener |
| 30 | +{ |
| 31 | + use AutowireTrait; |
| 32 | + |
| 33 | + public function __construct( |
| 34 | + protected Connection $database, |
| 35 | + protected PasswordInterface $passwordHasher, |
| 36 | + protected EntityTypeManagerInterface $entityTypeManager, |
| 37 | + protected LoggerInterface $logger, |
| 38 | + ) { |
| 39 | + } |
| 40 | + |
| 41 | + public function onDefinition(ConsoleDefinitionsEvent $event): void |
| 42 | + { |
| 43 | + foreach ($event->getApplication()->all() as $id => $command) { |
| 44 | + if ($command->getName() === SanitizeCommand::NAME) { |
| 45 | + $command->addOption( |
| 46 | + 'sanitize-email', |
| 47 | + null, |
| 48 | + InputOption::VALUE_REQUIRED, |
| 49 | + 'The pattern for test email addresses in the sanitization operation, or <info>no</info> to keep email addresses unchanged. May contain replacement patterns <info>%uid</info>, <info>%mail</info> or <info>%name</info>.', |
| 50 | + |
| 51 | + ) |
| 52 | + ->addOption('sanitize-password', null, InputOption::VALUE_REQUIRED, 'By default, passwords are randomized. Specify <info>no</info> to disable that. Specify any other value to set all passwords to that value.') |
| 53 | + ->addOption('ignored-roles', null, InputOption::VALUE_REQUIRED, 'A comma delimited list of roles. Users with at least one of the roles will be exempt from sanitization.'); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public function onSanitizeConfirm(SanitizeConfirmsEvent $event): void |
| 59 | + { |
| 60 | + $options = $event->getInput()->getOptions(); |
| 61 | + if ($this->isEnabled($options['sanitize-password'])) { |
| 62 | + $event->addMessage(dt('Sanitize user passwords.')); |
| 63 | + } |
| 64 | + if ($this->isEnabled($options['sanitize-email'])) { |
| 65 | + $event->addMessage(dt('Sanitize user emails.')); |
| 66 | + } |
| 67 | + if (in_array('ignored-roles', $options)) { |
| 68 | + $event->addMessage(dt('Preserve user emails and passwords for the specified roles.')); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + public function onConsoleTerminate(ConsoleTerminateEvent $event): void |
| 73 | + { |
| 74 | + $options = $event->getInput()->getOptions(); |
| 75 | + $query = $this->database->update('users_field_data')->condition('uid', 0, '>'); |
| 76 | + $messages = []; |
| 77 | + |
| 78 | + // Sanitize passwords. |
| 79 | + if ($this->isEnabled($options['sanitize-password'])) { |
| 80 | + $password = $options['sanitize-password']; |
| 81 | + if (is_null($password)) { |
| 82 | + $password = StringUtils::generatePassword(); |
| 83 | + } |
| 84 | + |
| 85 | + // Mimic Drupal's /scripts/password-hash.sh |
| 86 | + $hash = $this->passwordHasher->hash($password); |
| 87 | + $query->fields(['pass' => $hash]); |
| 88 | + $messages[] = dt('User passwords sanitized.'); |
| 89 | + } |
| 90 | + |
| 91 | + // Sanitize email addresses. |
| 92 | + if ($this->isEnabled($options['sanitize-email'])) { |
| 93 | + if (str_contains($options['sanitize-email'], '%')) { |
| 94 | + // We need a different sanitization query for MSSQL, Postgres and Mysql. |
| 95 | + $sql = SqlBase::create($event->getInput()->getOptions()); |
| 96 | + $db_driver = $sql->scheme(); |
| 97 | + if ($db_driver === 'pgsql') { |
| 98 | + $email_map = ['%uid' => "' || uid || '", '%mail' => "' || replace(mail, '@', '_') || '", '%name' => "' || replace(name, ' ', '_') || '"]; |
| 99 | + $new_mail = "'" . str_replace(array_keys($email_map), array_values($email_map), $options['sanitize-email']) . "'"; |
| 100 | + } elseif ($db_driver === 'mssql') { |
| 101 | + $email_map = ['%uid' => "' + uid + '", '%mail' => "' + replace(mail, '@', '_') + '", '%name' => "' + replace(name, ' ', '_') + '"]; |
| 102 | + $new_mail = "'" . str_replace(array_keys($email_map), array_values($email_map), $options['sanitize-email']) . "'"; |
| 103 | + } else { |
| 104 | + $email_map = ['%uid' => "', uid, '", '%mail' => "', replace(mail, '@', '_'), '", '%name' => "', replace(name, ' ', '_'), '"]; |
| 105 | + $new_mail = "concat('" . str_replace(array_keys($email_map), array_values($email_map), $options['sanitize-email']) . "')"; |
| 106 | + } |
| 107 | + $query->expression('mail', $new_mail); |
| 108 | + $query->expression('init', $new_mail); |
| 109 | + } else { |
| 110 | + $query->fields(['mail' => $options['sanitize-email']]); |
| 111 | + } |
| 112 | + $messages[] = dt('User emails sanitized.'); |
| 113 | + } |
| 114 | + |
| 115 | + if (!empty($options['ignored-roles'])) { |
| 116 | + $roles = explode(',', $options['ignored-roles']); |
| 117 | + /** @var SelectInterface $roles_query */ |
| 118 | + $roles_query = $this->database->select('user__roles', 'ur'); |
| 119 | + $roles_query |
| 120 | + ->condition('roles_target_id', $roles, 'IN') |
| 121 | + ->fields('ur', ['entity_id']); |
| 122 | + $roles_query_results = $roles_query->execute(); |
| 123 | + $ignored_users = $roles_query_results->fetchCol(); |
| 124 | + |
| 125 | + if (!empty($ignored_users)) { |
| 126 | + $query->condition('uid', $ignored_users, 'NOT IN'); |
| 127 | + $messages[] = dt('User emails and passwords for the specified roles preserved.'); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + if ($messages) { |
| 132 | + $query->execute(); |
| 133 | + $this->entityTypeManager->getStorage('user')->resetCache(); |
| 134 | + foreach ($messages as $message) { |
| 135 | + $this->logger->success($message); |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + /** |
| 141 | + * Test an option value to see if it is disabled. |
| 142 | + */ |
| 143 | + protected function isEnabled(?string $value): bool |
| 144 | + { |
| 145 | + return $value != 'no' && $value != '0'; |
| 146 | + } |
| 147 | +} |
0 commit comments