diff --git a/README.md b/README.md index 882f5d4..f8ca507 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,19 @@ # Simple account policy -This module implements a simple account policy with the following configurable rules: +This module implements a simple account policy with the following +configurable rules: - Username email and username must match (enforces an email as username) -- Username allowed patterns (usernames must follow this pattern to be valid) -- Username ignore patterns (don't apply policy for usernames matching this pattern) +- Username allowed patterns (usernames must follow this pattern to be + valid) +- Username ignore patterns (don't apply policy for usernames matching + this pattern) - Email allowed patterns (email must follow this pattern to be valid) -- Cron check interval (interval at which module will check user policy on all users) -- The inactive period. When users don't login for this period of time, they will be blocked. -- Inactive warning period. If users are about to be blocked, send out a warning mail. +- Cron check interval (interval at which module will check user policy + on all users) +- The inactive period. When users don't login for this period of time, + they will be blocked. +- Inactive warning period. If users are about to be blocked, send out + a warning mail. - The warning mail message and subject. For a full description of the module, visit the @@ -24,8 +30,8 @@ This does not require any other module. ## Installation -Install as you would normally install a contributed Drupal module. For further -information, see +Install as you would normally install a contributed Drupal module. +For further information, see [Installing Drupal Modules](https://www.drupal.org/docs/extending-drupal/installing-drupal-modules). diff --git a/config/install/simple_account_policy.settings.yml b/config/install/simple_account_policy.settings.yml index 0132c58..0772401 100644 --- a/config/install/simple_account_policy.settings.yml +++ b/config/install/simple_account_policy.settings.yml @@ -17,4 +17,3 @@ inactive_warning_mail: -- [site:name] team subject: 'Account details for [user:display-name] at [site:name] (inactive)' - diff --git a/simple_account_policy.info.yml b/simple_account_policy.info.yml index ab98883..07a1d8f 100644 --- a/simple_account_policy.info.yml +++ b/simple_account_policy.info.yml @@ -1,7 +1,6 @@ name: 'Account policy' description: 'Provides and applies basic account policy rules.' package: 'Security' -version: '1.0.0' type: module core_version_requirement: ^8.8 || ^9 || ^10 'interface translation project': simple_account_policy diff --git a/simple_account_policy.module b/simple_account_policy.module index 5b36ea4..a3a162a 100644 --- a/simple_account_policy.module +++ b/simple_account_policy.module @@ -1,7 +1,18 @@ <?php -// TODO add extra email settings to the site.settings mail form (and store the input in our own config) +/** + * @file + * Module File. + * + * @todo add extra email settings to the site.settings mail form (and store the input in our own config) + */ +use Drupal\Core\Url; +use Drupal\user\UserInterface; +use Drupal\Core\Entity\EntityInterface; +use Drupal\Core\Form\FormState; +use Drupal\Core\Form\FormStateInterface; +use Drupal\user\Entity\User; use Drupal\Component\Render\PlainTextOutput; use Drupal\Core\Routing\RouteMatchInterface; @@ -15,14 +26,14 @@ function simple_account_policy_help($route_name, RouteMatchInterface $route_matc $output = ''; $output .= '<h3>' . t('About') . '</h3>'; $output .= '<p>' . t('This module implements a simple account policy with the following configurable rules:') . '</p>'; - $output .= '<ul>' . t('<li>Username email and username must match (enforces an email as username)</li>') . '</ul>'; + $output .= '<ul>' . t('<li>Username email and username must match (enforces an email as username)</li>') . '</ul>'; $output .= '<ul>' . t('<li>Username allowed patterns (usernames must follow this pattern to be valid)</li>') . '</ul>'; $output .= '<ul>' . t('<li>Username ignore patterns (do not apply policy for usernames matching this pattern)</li>') . '</ul>'; $output .= '<ul>' . t('<li>Email allowed patterns (email must follow this pattern to be valid)</li>') . '</ul>'; $output .= '<ul>' . t('<li>Cron check interval (interval at which module will check user policy on all users)</li>') . '</ul>'; - $output .= '<ul>' . t('<li>The inactive period. When users do not login for this period of time, they will be blocked.</li>') . '</ul>'; - $output .= '<ul>' . t('<li>Inactive warning period. If users are about to be blocked, send out a warning mail.</li>') . '</ul>'; - $output .= '<ul>' . t('<li>The warning mail message and subject.</li>') . '</ul>'; + $output .= '<ul>' . t('<li>The inactive period. When users do not login for this period of time, they will be blocked.</li>') . '</ul>'; + $output .= '<ul>' . t('<li>Inactive warning period. If users are about to be blocked, send out a warning mail.</li>') . '</ul>'; + $output .= '<ul>' . t('<li>The warning mail message and subject.</li>') . '</ul>'; return $output; default: @@ -35,19 +46,19 @@ function simple_account_policy_help($route_name, RouteMatchInterface $route_matc * Block users after a period of time (default 3 months). */ function simple_account_policy_cron() { - /** @var \Drupal\simple_account_policy\AccountPolicyInterface $account_policy */ - $account_policy = \Drupal::service('simple_account_policy'); + /** @var \Drupal\simple_account_policy\AccountPolicyInterface $accountPolicy */ + $accountPolicy = \Drupal::service('simple_account_policy'); $requestTime = \Drupal::time()->getRequestTime(); $last_run = \Drupal::state()->get('simple_account_policy.last_cron_run', FALSE); - $inactive_interval = $account_policy->inactiveInterval(); + $inactive_interval = $accountPolicy->inactiveInterval(); if (empty($inactive_interval) || ($last_run && ($requestTime - $last_run) < $inactive_interval)) { return FALSE; } - // TODO: we should do this with a queue to prevent - // issues on sites with lots of user. - $users = \Drupal\user\Entity\User::loadMultiple(); + // @todo we should do this with a queue to prevent + // issues on sites with lots of user. + $users = User::loadMultiple(); foreach ($users as $user) { /** @var \Drupal\user\Entity\User $user */ @@ -55,13 +66,13 @@ function simple_account_policy_cron() { continue; } - if ($account_policy->applyPolicy($user)) { - if ($account_policy->shouldIssueWarning($user)) { - $account_policy->issueWarning($user); + if ($accountPolicy->applyPolicy($user)) { + if ($accountPolicy->shouldIssueWarning($user)) { + $accountPolicy->issueWarning($user); } else { - if ($account_policy->isInactive($user)) { - $account_policy->block($user); + if ($accountPolicy->isInactive($user)) { + $accountPolicy->block($user); } } } @@ -74,7 +85,7 @@ function simple_account_policy_cron() { /** * Implements hook_form_FORM_ID_alter(). */ -function simple_account_policy_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { +function simple_account_policy_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id) { $build_info = $form_state->getBuildInfo(); /** @var \Drupal\user\ProfileForm $profileForm */ @@ -83,17 +94,17 @@ function simple_account_policy_form_user_form_alter(&$form, \Drupal\Core\Form\Fo /** @var \Drupal\user\Entity\User $currentUser */ $currentUser = $profileForm->getEntity(); - /** @var \Drupal\simple_account_policy\AccountPolicyInterface $account_policy */ - $account_policy = \Drupal::service('simple_account_policy'); + /** @var \Drupal\simple_account_policy\AccountPolicyInterface $accountPolicy */ + $accountPolicy = \Drupal::service('simple_account_policy'); // We need user input here, since fields are not in values (yet). $input = $form_state->getUserInput(); $data = [ 'mail' => $input['mail'] ?? '', - 'name' => $input['name'] ?? '' + 'name' => $input['name'] ?? '', ]; - $errors = empty($pass) ? [] : $account_policy->validate($currentUser, $data); - $policy = $account_policy->policy($currentUser, $errors); + $errors = empty($pass) ? [] : $accountPolicy->validate($currentUser, $data); + $policy = $accountPolicy->policy($currentUser, $errors); if (!empty($policy['mail'])) { $form['account']['mail']['#description'] = $policy['mail']; @@ -109,24 +120,24 @@ function simple_account_policy_form_user_form_alter(&$form, \Drupal\Core\Form\Fo /** * Validation function for User form. */ -function simple_account_policy_form_user_validate($form, \Drupal\Core\Form\FormState $form_state) { +function simple_account_policy_form_user_validate($form, FormState $form_state) { $build_info = $form_state->getBuildInfo(); $form = $build_info['callback_object']; /** @var \Drupal\user\Entity\User $currentUser */ $currentUser = $form->getEntity(); - /** @var \Drupal\simple_account_policy\AccountPolicyInterface $account_policy */ - $account_policy = \Drupal::service('simple_account_policy'); + /** @var \Drupal\simple_account_policy\AccountPolicyInterface $accountPolicy */ + $accountPolicy = \Drupal::service('simple_account_policy'); - if ($account_policy->applyPolicy($currentUser)) { + if ($accountPolicy->applyPolicy($currentUser)) { $values = [ 'mail' => $form_state->getValue('mail'), - 'name' => $form_state->getValue('name') + 'name' => $form_state->getValue('name'), ]; - $validation = $account_policy->validate($currentUser, $values); + $validation = $accountPolicy->validate($currentUser, $values); if (!empty($validation['mail'])) { $form_state->setErrorByName('mail', t("The email does not satisfy the account policy rules.")); @@ -144,28 +155,30 @@ function simple_account_policy_form_user_validate($form, \Drupal\Core\Form\FormS * Set an extra operations to activate users. * * @param array $operations + * Operations. * @param \Drupal\Core\Entity\EntityInterface $entity + * Entity. */ -function simple_account_policy_entity_operation_alter(array &$operations, \Drupal\Core\Entity\EntityInterface $entity) { +function simple_account_policy_entity_operation_alter(array &$operations, EntityInterface $entity) { $currentUser = \Drupal::currentUser(); if ($currentUser->hasPermission('account policy activate users') && $entity->getEntityTypeId() == 'user') { - if ($entity instanceof \Drupal\user\UserInterface && $entity->isBlocked()) { + if ($entity instanceof UserInterface && $entity->isBlocked()) { $operations['activate'] = [ 'title' => t('Activate'), 'weight' => 999, - 'url' => \Drupal\Core\Url::fromRoute('simple_account_policy.activate', ['user' => $entity->id()]), + 'url' => Url::fromRoute('simple_account_policy.activate', ['user' => $entity->id()]), ]; } } if ($currentUser->hasPermission('account policy block users') && $entity->getEntityTypeId() == 'user') { - if ($entity instanceof \Drupal\user\UserInterface && $entity->isActive()) { + if ($entity instanceof UserInterface && $entity->isActive()) { $operations['block'] = [ 'title' => t('Block'), 'weight' => 999, - 'url' => \Drupal\Core\Url::fromRoute('simple_account_policy.block', ['user' => $entity->id()]), + 'url' => Url::fromRoute('simple_account_policy.block', ['user' => $entity->id()]), ]; } } @@ -195,6 +208,7 @@ function simple_account_policy_mail($key, &$message, $params) { } if (!function_exists('time_ago')) { + /** * Helper to print out a readable time period in the past or future. * @@ -203,44 +217,72 @@ if (!function_exists('time_ago')) { * ... * * @param string|int $ts - * The timestamp to calculate against the current time. + * The timestamp to calculate against the current time. * @param string $future_txt - * Untranslated text to display if timestamp is in the future. Use @output to - * position the resulting period. + * Untranslated text to display if timestamp is in the future. + * Use @output to position the resulting period. * @param string $past_txt - * Untranslated text to display if timestamp is in the past. Use @output to - * position the resulting period. + * Untranslated text to display if timestamp is in the past. + * Use @output to position the resulting period. * @param string $langcode - * The langcode to translate the result in, if none given this is the current - * language. + * The langcode to translate the result in, if none given this + * is the current language. * * @return string + * String */ function time_ago($ts, $future_txt = "@output", $past_txt = "@output", $langcode = NULL): string { $langcode = $langcode ?? \Drupal::languageManager()->getCurrentLanguage()->getId(); - if(is_string($ts) && !ctype_digit($ts)) { + if (is_string($ts) && !ctype_digit($ts)) { $ts = strtotime($ts); } $diff = time() - $ts; - if($diff == 0) { + if ($diff == 0) { $output = t('now', [], ['langcode' => $langcode]); return (string) t($future_txt, ['@output' => $output], ['langcode' => $langcode]); } - elseif($diff > 0) { + elseif ($diff > 0) { $day_diff = floor($diff / 86400); - switch(true) { - case ($day_diff == 0 && $diff < 60): $output = t('just now', [], ['langcode' => $langcode]); break; - case ($day_diff == 0 && $diff < 120): $output = t('1 minute ago', [], ['langcode' => $langcode]); break; - case ($day_diff == 0 && $diff < 3600): $output = t('@time minutes ago', ['@time' => floor($diff / 60) ], ['langcode' => $langcode]); break; - case ($day_diff == 0 && $diff < 7200): $output = t('1 hour ago', [], ['langcode' => $langcode]); break; - case ($day_diff == 0 && $diff < 86400): $output = t('@time hours ago', ['@time' => floor($diff / 3600)], ['langcode' => $langcode]); break; - case ($day_diff == 1): $output = t('yesterday', [], ['langcode' => $langcode]); break; - case ($day_diff < 7): $output = t('@time days ago', ['@time' => $day_diff], ['langcode' => $langcode]); break; - case ($day_diff < 31): $output = t('@time weeks ago', ['@time' => ceil($day_diff / 7)], ['langcode' => $langcode]); break; - case ($day_diff < 60): $output = t('last month', [], ['langcode' => $langcode]); break; + switch (TRUE) { + case ($day_diff == 0 && $diff < 60): $output = t('just now', [], ['langcode' => $langcode]); + + break; + + case ($day_diff == 0 && $diff < 120): $output = t('1 minute ago', [], ['langcode' => $langcode]); + + break; + + case ($day_diff == 0 && $diff < 3600): $output = t('@time minutes ago', ['@time' => floor($diff / 60)], ['langcode' => $langcode]); + + break; + + case ($day_diff == 0 && $diff < 7200): $output = t('1 hour ago', [], ['langcode' => $langcode]); + + break; + + case ($day_diff == 0 && $diff < 86400): $output = t('@time hours ago', ['@time' => floor($diff / 3600)], ['langcode' => $langcode]); + + break; + + case ($day_diff == 1): $output = t('yesterday', [], ['langcode' => $langcode]); + + break; + + case ($day_diff < 7): $output = t('@time days ago', ['@time' => $day_diff], ['langcode' => $langcode]); + + break; + + case ($day_diff < 31): $output = t('@time weeks ago', ['@time' => ceil($day_diff / 7)], ['langcode' => $langcode]); + + break; + + case ($day_diff < 60): $output = t('last month', [], ['langcode' => $langcode]); + + break; + default: /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */ $date_formatter = \Drupal::service('date.formatter'); @@ -249,24 +291,48 @@ if (!function_exists('time_ago')) { return (string) t($past_txt, ['@output' => $output], ['langcode' => $langcode]); } - else - { + else { $diff = abs($diff); $day_diff = floor($diff / 86400); - switch(true) { - case ($day_diff == 0 && $diff < 120): $output = t('in a minute', [], ['langcode' => $langcode]); break; - case ($day_diff == 0 && $diff < 3600): $output = t('in @time minutes', ['@time' => floor($diff / 60)], ['langcode' => $langcode]); break; - case ($day_diff == 0 && $diff < 7200): $output = t('in an hour', [], ['langcode' => $langcode]); break; - case ($day_diff == 0 && $diff < 86400): $output = t('in @time hours', ['@time' => floor($diff / 3600) ], ['langcode' => $langcode]); break; - case ($day_diff == 1): $output = t('tomorrow', [], ['langcode' => $langcode]); break; - case ($day_diff < 4) : + switch (TRUE) { + case ($day_diff == 0 && $diff < 120): $output = t('in a minute', [], ['langcode' => $langcode]); + + break; + + case ($day_diff == 0 && $diff < 3600): $output = t('in @time minutes', ['@time' => floor($diff / 60)], ['langcode' => $langcode]); + + break; + + case ($day_diff == 0 && $diff < 7200): $output = t('in an hour', [], ['langcode' => $langcode]); + + break; + + case ($day_diff == 0 && $diff < 86400): $output = t('in @time hours', ['@time' => floor($diff / 3600)], ['langcode' => $langcode]); + + break; + + case ($day_diff == 1): $output = t('tomorrow', [], ['langcode' => $langcode]); + + break; + + case ($day_diff < 4): /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */ $date_formatter = \Drupal::service('date.formatter'); $output = $date_formatter->format($ts, 'custom', 'l'); break; - case ($day_diff < 7 + (7 - intval(date('w')))): $output = t('next week', [], ['langcode' => $langcode]); break; - case (ceil($day_diff / 7) < 4): $output = t('in @time weeks', ['@time' => ceil($day_diff / 7) ], ['langcode' => $langcode]); break; - case (date('n', $ts) == intval(date('n')) + 1): $output = t('next month', [], ['langcode' => $langcode]); break; + + case ($day_diff < 7 + (7 - intval(date('w')))): $output = t('next week', [], ['langcode' => $langcode]); + + break; + + case (ceil($day_diff / 7) < 4): $output = t('in @time weeks', ['@time' => ceil($day_diff / 7)], ['langcode' => $langcode]); + + break; + + case (date('n', $ts) == intval(date('n')) + 1): $output = t('next month', [], ['langcode' => $langcode]); + + break; + default: /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */ $date_formatter = \Drupal::service('date.formatter'); @@ -276,4 +342,5 @@ if (!function_exists('time_ago')) { return (string) t($future_txt, ['@output' => $output], ['langcode' => $langcode]); } } + } diff --git a/simple_account_policy.tokens.inc b/simple_account_policy.tokens.inc index a9a6803..1a21a46 100644 --- a/simple_account_policy.tokens.inc +++ b/simple_account_policy.tokens.inc @@ -1,5 +1,10 @@ <?php +/** + * @file + * Tokens. + */ + use Drupal\Core\Render\BubbleableMetadata; /** @@ -9,17 +14,17 @@ function simple_account_policy_token_info() { $types['account_policy'] = [ 'name' => t('Account policy'), 'description' => t('Tokens related to the account policy.'), - 'needs-data' => 'user' + 'needs-data' => 'user', ]; - $account_policy['block_period'] = [ + $accountPolicy['block_period'] = [ 'name' => t('Block period'), 'description' => t("The period after which the user will be blocked."), ]; return [ 'types' => $types, - 'tokens' => ['account_policy' => $account_policy], + 'tokens' => ['account_policy' => $accountPolicy], ]; } @@ -31,15 +36,15 @@ function simple_account_policy_tokens($type, $tokens, array $data, array $option $replacements = []; if ($type == 'account_policy') { - /** @var \Drupal\simple_account_policy\AccountPolicyInterface $account_policy */ - $account_policy = \Drupal::service('simple_account_policy'); + /** @var \Drupal\simple_account_policy\AccountPolicyInterface $accountPolicy */ + $accountPolicy = \Drupal::service('simple_account_policy'); foreach ($tokens as $name => $original) { switch ($name) { case 'block_period': /** @var \Drupal\user\UserInterface $user */ $user = $data['user']; - $block_time = $account_policy->getBlockTime($user); + $block_time = $accountPolicy->getBlockTime($user); $langcode = $user->getPreferredLangcode(); $replacements[$original] = time_ago($block_time, "@output", "", $langcode); break; diff --git a/src/AccountPolicy.php b/src/AccountPolicy.php index 5f1cf70..c0f1af4 100644 --- a/src/AccountPolicy.php +++ b/src/AccountPolicy.php @@ -1,4 +1,5 @@ <?php + namespace Drupal\simple_account_policy; use Drupal\simple_account_policy\Event\AccountPolicyActivateEvent; @@ -12,34 +13,68 @@ use Drupal\Core\StringTranslation\StringTranslationTrait; use Drupal\user\UserInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; +/** + * Account Policy. + */ class AccountPolicy implements AccountPolicyInterface { use StringTranslationTrait; - /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface */ + /** + * Event Dispatcher. + * + * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface + */ protected $event_dispatcher; - /** @var \Drupal\Core\Database\Connection $db */ + /** + * Connection. + * + * @var \Drupal\Core\Database\Connection + */ protected $db; - /** @var ConfigFactoryInterface $config_factory */ + /** + * Config Factory. + * + * @var \Drupal\Core\Config\ConfigFactoryInterface + */ protected $config_factory; - /** @var StateInterface $state */ + /** + * State Interface. + * + * @var \Drupal\Core\State\StateInterface + */ protected $state; - /** @var \Drupal\Core\Render\RendererInterface $renderer */ + /** + * Renderer Interface. + * + * @var \Drupal\Core\Render\RendererInterface + */ protected $renderer; - // Policy validation parameters. + /** + * Policy validation parameters. + * + * @var string + */ protected $config; /** * AccountPolicy constructor. * * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory + * Config Factory. * @param \Drupal\Core\Database\Connection $database + * Connection. + * @param \Drupal\Core\State\StateInterface $state + * State Interface. + * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher + * Event Dispatcher interface. * @param \Drupal\Core\Render\RendererInterface $renderer + * Renderer Interface. */ public function __construct(ConfigFactoryInterface $config_factory, Connection $database, StateInterface $state, EventDispatcherInterface $eventDispatcher, RendererInterface $renderer) { $this->config_factory = $config_factory; @@ -52,11 +87,11 @@ class AccountPolicy implements AccountPolicyInterface { } /** - * @inheritDoc + * {@inheritdoc} */ public function applyPolicy(UserInterface $user) { - $ignore_user = false; + $ignore_user = FALSE; $username_ignore_patterns = $this->config->get('username_ignore_patterns') ?? []; if (!empty($username_ignore_patterns)) { @@ -65,14 +100,14 @@ class AccountPolicy implements AccountPolicyInterface { } return $user - // Don't apply if user has bypass permission + // Don't apply if user has bypass permission. && !$user->hasPermission("bypass account policy") // Don't apply if user need to be ignored (by account name) && !$ignore_user; } /** - * @inheritDoc + * {@inheritdoc} */ public function validate(UserInterface $user, $data = []) { $errors = []; @@ -84,8 +119,8 @@ class AccountPolicy implements AccountPolicyInterface { $username = $data['name'] ?? $user->getAccountName(); // Check if username matches email. - $username_match_email = $this->config->get('username_match_email') ?? false; - if ($username_match_email !== false) { + $username_match_email = $this->config->get('username_match_email') ?? FALSE; + if ($username_match_email !== FALSE) { if ($mail !== $username) { $errors['name'][] = 'username_match_email'; } @@ -116,14 +151,14 @@ class AccountPolicy implements AccountPolicyInterface { } /** - * @inheritDoc + * {@inheritdoc} */ - public function policy(UserInterface $user = null, array $errors = []) { + public function policy(UserInterface $user = NULL, array $errors = []) { // Make sure we have the default field keys. $errors += [ 'mail' => [], - 'name' => [] + 'name' => [], ]; $policy = []; @@ -131,11 +166,11 @@ class AccountPolicy implements AccountPolicyInterface { if ($this->applyPolicy($user)) { // Check if username matches email. - $username_match_email = $this->config->get('username_match_email') ?? false; - if ($username_match_email !== false) { + $username_match_email = $this->config->get('username_match_email') ?? FALSE; + if ($username_match_email !== FALSE) { $policy['name'][] = [ '#wrapper_attributes' => ['class' => [in_array('username_match_email', $errors['name']) ? 'account-policy-invalid-rule marker' : 'account-policy-valid-rule']], - '#markup' => (string) $this->t("The username must match the email address.") + '#markup' => (string) $this->t("The username must match the email address."), ]; } @@ -145,7 +180,7 @@ class AccountPolicy implements AccountPolicyInterface { foreach ($username_match_patterns as $delta => $pattern) { $policy['name'][] = [ '#wrapper_attributes' => ['class' => [in_array('username_match_pattern_' . $delta, $errors['name']) ? 'account-policy-invalid-rule marker' : 'account-policy-valid-rule']], - '#markup' => (string) $this->patternToMessage($pattern) + '#markup' => (string) $this->patternToMessage($pattern), ]; } } @@ -156,7 +191,7 @@ class AccountPolicy implements AccountPolicyInterface { foreach ($email_match_patterns as $delta => $pattern) { $policy['mail'][] = [ '#wrapper_attributes' => ['class' => [in_array('email_match_pattern_' . $delta, $errors['name']) ? 'account-policy-invalid-rule marker' : 'account-policy-valid-rule']], - '#markup' => (string) $this->patternToMessage($pattern) + '#markup' => (string) $this->patternToMessage($pattern), ]; } } @@ -167,13 +202,13 @@ class AccountPolicy implements AccountPolicyInterface { '#markup' => (string) $this->formatPlural(count($policy['name']), "The username must satisfy the following account policy rule:", "The username must satisfy the following account policy rules:" - ) + ), ], 'rules' => [ '#theme' => 'item_list', '#list_type' => 'ul', - '#items' => $policy['name'] - ] + '#items' => $policy['name'], + ], ]; $policy['name'] = $this->renderer->renderPlain($elements); } @@ -184,13 +219,13 @@ class AccountPolicy implements AccountPolicyInterface { '#markup' => (string) $this->formatPlural(count($policy['mail']), "The email must satisfy the following account policy rule:", "The email must satisfy the following account policy rules:" - ) + ), ], 'rules' => [ '#theme' => 'item_list', '#list_type' => 'ul', - '#items' => $policy['mail'] - ] + '#items' => $policy['mail'], + ], ]; $policy['mail'] = $this->renderer->renderPlain($elements); } @@ -206,7 +241,7 @@ class AccountPolicy implements AccountPolicyInterface { } /** - * @inerhitDoc + * {@inheritdoc} */ public function getBlockTime(UserInterface $user) { $block_time = 0; @@ -232,7 +267,7 @@ class AccountPolicy implements AccountPolicyInterface { } /** - * @inerhitDoc + * {@inheritdoc} */ public function getWarningTime(UserInterface $user) { $warning_time = 0; @@ -257,30 +292,30 @@ class AccountPolicy implements AccountPolicyInterface { } /** - * @inerhitDoc + * {@inheritdoc} */ public function inactiveInterval() { return $this->config->get('inactive_interval') ?? 86400; } /** - * @inheritDoc + * {@inheritdoc} */ public function shouldIssueWarning(UserInterface $user) { $warning_time = $this->getWarningTime($user); - return ( $warning_time && !$this->warningIssued($user) && time() > $warning_time ); + return ($warning_time && !$this->warningIssued($user) && time() > $warning_time); } /** - * @inheritDoc + * {@inheritdoc} */ public function warningIssued(UserInterface $user) { $warned_users = $this->state->get('simple_account_policy.warned_users', []); - return key_exists($user->id(), $warned_users); + return array_key_exists($user->id(), $warned_users); } /** - * @inheritDoc + * {@inheritdoc} */ public function issueWarning(UserInterface $user) { // Keep track of issued warnings. @@ -293,6 +328,9 @@ class AccountPolicy implements AccountPolicyInterface { $this->event_dispatcher->dispatch($event, AccountPolicyWarningEvent::EVENT_NAME); } + /** + * {@inheritdoc} + */ public function isInactive(UserInterface $user) { $block_time = $this->getBlockTime($user); @@ -301,7 +339,7 @@ class AccountPolicy implements AccountPolicyInterface { } /** - * @inerhitDoc + * {@inheritdoc} */ public function block(UserInterface $user) { $event = new AccountPolicyBlockEvent($user, $this); @@ -309,7 +347,7 @@ class AccountPolicy implements AccountPolicyInterface { } /** - * @inerhitDoc + * {@inheritdoc} */ public function activate(UserInterface $user) { // Keep track of issued warnings. @@ -325,14 +363,16 @@ class AccountPolicy implements AccountPolicyInterface { /** * Pretty print a regular expression pattern. * - * @param $pattern + * @param array $pattern + * Pattern. * * @return \Drupal\Core\StringTranslation\TranslatableMarkup + * Return Statement. */ - protected function patternToMessage($pattern) { + protected function patternToMessage(array $pattern) { $beginsWithApostrophe = $pattern[0] == '^'; - $endsWithDollar = $pattern[strlen($pattern)-1] == '$'; + $endsWithDollar = $pattern[strlen($pattern) - 1] == '$'; if ($beginsWithApostrophe && $endsWithDollar) { $message = $this->t("Must match %pattern.", ['%pattern' => trim($pattern, "^$")]); @@ -340,7 +380,8 @@ class AccountPolicy implements AccountPolicyInterface { else { if ($beginsWithApostrophe) { $message = $this->t("Must begin with %pattern.", ['%pattern' => ltrim($pattern, "^")]); - } else if ($endsWithDollar) { + } + elseif ($endsWithDollar) { $message = $this->t("Must end with %pattern.", ['%pattern' => rtrim($pattern, "$")]); } else { diff --git a/src/AccountPolicyInterface.php b/src/AccountPolicyInterface.php index 53d1324..29944c5 100644 --- a/src/AccountPolicyInterface.php +++ b/src/AccountPolicyInterface.php @@ -1,16 +1,22 @@ <?php + namespace Drupal\simple_account_policy; use Drupal\user\UserInterface; +/** + * Implements interface. + */ interface AccountPolicyInterface { /** * Decide if the policy should be applied for this user or not. * * @param \Drupal\user\UserInterface $user + * User. * * @return bool + * Return statement */ public function applyPolicy(UserInterface $user); @@ -18,6 +24,7 @@ interface AccountPolicyInterface { * Validate an email string for a given user. * * @param \Drupal\user\UserInterface $user + * User. * @param array $data * An array containing the data to validate for the given user. * Should contain a 'mail' and 'name' key. @@ -25,15 +32,16 @@ interface AccountPolicyInterface { * @return array * An array of policy violations (errors) for 'mail' and 'name'. */ - public function validate(UserInterface $user, $data); + public function validate(UserInterface $user, array $data); /** * Return the policy that applies for the given user. * * @param \Drupal\user\UserInterface $user + * User. * * @return array - * Array containing a string describing the policy for 'mail' and 'name'. + * Array containing a string describing the policy for 'mail' and 'name'. */ public function policy(UserInterface $user); @@ -41,8 +49,10 @@ interface AccountPolicyInterface { * Get the timestamp an inactive user will get blocked. * * @param \Drupal\user\UserInterface $user + * User. * * @return int + * Return statement */ public function getBlockTime(UserInterface $user); @@ -50,8 +60,10 @@ interface AccountPolicyInterface { * Get the timestamp to warn an inactive user will get blocked. * * @param \Drupal\user\UserInterface $user + * User. * * @return int + * Return statement */ public function getWarningTime(UserInterface $user); @@ -59,6 +71,7 @@ interface AccountPolicyInterface { * The interval in seconds to check for inactive users. * * @return int + * Return statement */ public function inactiveInterval(); @@ -66,8 +79,10 @@ interface AccountPolicyInterface { * Decide if we need to issue a warning or not. * * @param \Drupal\user\UserInterface $user + * User. * * @return bool + * Return statement */ public function shouldIssueWarning(UserInterface $user); @@ -75,8 +90,10 @@ interface AccountPolicyInterface { * Check if a user already got a warning. * * @param \Drupal\user\UserInterface $user + * User. * * @return bool + * Return statement */ public function warningIssued(UserInterface $user); @@ -84,8 +101,10 @@ interface AccountPolicyInterface { * Send out a warning event. * * @param \Drupal\user\UserInterface $user + * User. * * @return bool + * Return statement */ public function issueWarning(UserInterface $user); @@ -93,6 +112,7 @@ interface AccountPolicyInterface { * Decide if user is considered active or not. * * @param \Drupal\user\UserInterface $user + * User. */ public function isInactive(UserInterface $user); @@ -100,20 +120,25 @@ interface AccountPolicyInterface { * Block a given user. * * @param \Drupal\user\UserInterface $user + * User. * * @return mixed + * Return statement */ public function block(UserInterface $user); /** * Make a given user active again. * - * The user will be reactivated and his last login date will be reset to today - * to prevent him being blocked again by cron. + * The user will be reactivated. + * And their last login date will be reset to today + * to prevent them being blocked again by cron. * * @param \Drupal\user\UserInterface $user + * User. * * @return mixed + * Return statement */ public function activate(UserInterface $user); diff --git a/src/Controller/AccountPolicyController.php b/src/Controller/AccountPolicyController.php index 6b4034c..27bda12 100644 --- a/src/Controller/AccountPolicyController.php +++ b/src/Controller/AccountPolicyController.php @@ -8,22 +8,22 @@ use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\RedirectResponse; /** - * Class AccountPolicyController + * Account Policy Controller. */ class AccountPolicyController extends ControllerBase { /** * The account policy. * - * @var AccountPolicyInterface + * @var \Drupal\simple_account_policy\AccountPolicyInterface */ - protected $account_policy; + protected $accountPolicy; /** * ModalFormContactController constructor. * - * @param \Drupal\Core\Form\FormBuilder $form_builder - * The form builder. + * @param \Drupal\simple_account_policy\AccountPolicyInterface $accountPolicy + * The account policy. */ public function __construct(AccountPolicyInterface $accountPolicy) { $this->account_policy = $accountPolicy; @@ -39,22 +39,24 @@ class AccountPolicyController extends ControllerBase { */ public static function create(ContainerInterface $container) { - /** @var \Drupal\simple_account_policy\AccountPolicyInterface $account_policy */ - $account_policy = $container->get('simple_account_policy'); + /** @var \Drupal\simple_account_policy\AccountPolicyInterface $accountPolicy */ + $accountPolicy = $container->get('simple_account_policy'); return new static( - $account_policy + $accountPolicy ); } /** * Activate the given user. * - * @param $user + * @param \Drupal\user\UserInterface $user + * User. * * @return \Symfony\Component\HttpFoundation\RedirectResponse + * Return statement. */ - public function activate($user) { + public function activate(UserInterface $user) { $this->account_policy->activate($user); @@ -64,14 +66,17 @@ class AccountPolicyController extends ControllerBase { /** * Block the given user. * - * @param $user + * @param \Drupal\user\UserInterface $user + * User. * * @return \Symfony\Component\HttpFoundation\RedirectResponse + * Return statement. */ - public function block($user) { + public function block(UserInterface $user) { $this->account_policy->block($user); return new RedirectResponse(\Drupal::destination()->get()); } + } diff --git a/src/Event/AccountPolicyActivateEvent.php b/src/Event/AccountPolicyActivateEvent.php index b79f8f7..3de0ccd 100644 --- a/src/Event/AccountPolicyActivateEvent.php +++ b/src/Event/AccountPolicyActivateEvent.php @@ -1,4 +1,5 @@ <?php + namespace Drupal\simple_account_policy\Event; use Drupal\simple_account_policy\AccountPolicyInterface; @@ -31,7 +32,6 @@ class AccountPolicyActivateEvent extends Event { * * @param \Drupal\user\UserInterface $account * The account of the user whos account is activated. - * * @param \Drupal\simple_account_policy\AccountPolicyInterface $policy * The account policy that triggered the event. */ diff --git a/src/Event/AccountPolicyBlockEvent.php b/src/Event/AccountPolicyBlockEvent.php index 8f5b5ca..e90a087 100644 --- a/src/Event/AccountPolicyBlockEvent.php +++ b/src/Event/AccountPolicyBlockEvent.php @@ -1,4 +1,5 @@ <?php + namespace Drupal\simple_account_policy\Event; use Drupal\simple_account_policy\AccountPolicyInterface; @@ -31,7 +32,6 @@ class AccountPolicyBlockEvent extends Event { * * @param \Drupal\user\UserInterface $account * The account of the user whos account is blocked. - * * @param \Drupal\simple_account_policy\AccountPolicyInterface $policy * The account policy that triggered the event. */ diff --git a/src/Event/AccountPolicyWarningEvent.php b/src/Event/AccountPolicyWarningEvent.php index e8b4d93..ef9084b 100644 --- a/src/Event/AccountPolicyWarningEvent.php +++ b/src/Event/AccountPolicyWarningEvent.php @@ -1,4 +1,5 @@ <?php + namespace Drupal\simple_account_policy\Event; use Drupal\simple_account_policy\AccountPolicyInterface; @@ -31,7 +32,6 @@ class AccountPolicyWarningEvent extends Event { * * @param \Drupal\user\UserInterface $account * The account of the user whos account is about to be deactivated. - * * @param \Drupal\simple_account_policy\AccountPolicyInterface $policy * The account policy that triggered the event. */ diff --git a/src/EventSubscriber/DefaultEventSubscriber.php b/src/EventSubscriber/DefaultEventSubscriber.php index 582bbdb..df1e3b1 100644 --- a/src/EventSubscriber/DefaultEventSubscriber.php +++ b/src/EventSubscriber/DefaultEventSubscriber.php @@ -40,6 +40,7 @@ class DefaultEventSubscriber implements EventSubscriberInterface { * Event callback to AccountPolicyActivateEvent. * * @param \Drupal\simple_account_policy\Event\AccountPolicyActivateEvent $event + * Event. */ public function accountPolicyActivateEvent(AccountPolicyActivateEvent $event) { @@ -48,11 +49,12 @@ class DefaultEventSubscriber implements EventSubscriberInterface { Database::getConnection()->delete('flood') ->condition('event', 'user.failed_login_user') ->condition('identifier', $event->account->id() . '-%', 'LIKE') - ->execute() - ; + ->execute(); } - // Make sure the account is active again, reset the last login date to now, so it wont be blocked again. + // Make sure the account is active again, + // reset the last login date to now, + // so it wont be blocked again. $event->account->activate(); $event->account->setLastAccessTime(time()); $event->account->save(); @@ -62,6 +64,7 @@ class DefaultEventSubscriber implements EventSubscriberInterface { * Event callback to AccountPolicyBlockEvent. * * @param \Drupal\simple_account_policy\Event\AccountPolicyBlockEvent $event + * Event. */ public function accountPolicyBlockEvent(AccountPolicyBlockEvent $event) { $event->account->block(); @@ -72,6 +75,7 @@ class DefaultEventSubscriber implements EventSubscriberInterface { * Event callback to AccountPolicyWarningEvent. * * @param \Drupal\simple_account_policy\Event\AccountPolicyWarningEvent $event + * Event. */ public function accountPolicyWarningEvent(AccountPolicyWarningEvent $event) { @@ -102,7 +106,7 @@ class DefaultEventSubscriber implements EventSubscriberInterface { $mail = \Drupal::service('plugin.manager.mail'); $mail->mail('simple_account_policy', 'inactive_warning_mail', $account->getEmail(), $langcode, $params, $site_mail); - /** The actual message is handled in @see simple_account_policy_mail. */ + // The actual message is handled in @see simple_account_policy_mail. } /** diff --git a/src/Form/AccountPolicyConfigForm.php b/src/Form/AccountPolicyConfigForm.php index 2ac76d6..6d42384 100644 --- a/src/Form/AccountPolicyConfigForm.php +++ b/src/Form/AccountPolicyConfigForm.php @@ -40,7 +40,7 @@ class AccountPolicyConfigForm extends ConfigFormBase { '#type' => 'details', '#title' => $this->t('Policy rules'), '#collapsible' => TRUE, - '#collapsed' => FALSE + '#collapsed' => FALSE, ]; $form['policy_rules']['username_match_email'] = [ @@ -68,7 +68,7 @@ class AccountPolicyConfigForm extends ConfigFormBase { '#type' => 'details', '#title' => $this->t('Policy bypass'), '#collapsible' => TRUE, - '#collapsed' => FALSE + '#collapsed' => FALSE, ]; $form['policy_bypass']['username_ignore_patterns'] = [ @@ -83,7 +83,7 @@ class AccountPolicyConfigForm extends ConfigFormBase { '#title' => $this->t('Scheduling'), '#description' => $this->t('Set timings on when users must be automatically blocked after long inactivity.'), '#collapsible' => TRUE, - '#collapsed' => FALSE + '#collapsed' => FALSE, ]; $form['inactive_scheduling']['inactive_interval'] = [ @@ -97,7 +97,7 @@ class AccountPolicyConfigForm extends ConfigFormBase { $form['inactive_scheduling']['inactive_period'] = [ '#type' => 'textfield', '#title' => $this->t('Inactive period'), - '#description' => $this->t('The time from the last login date for a user to be considered inactive. You can use strtotime notation e.g. "3 months" '), + '#description' => $this->t('The time from the last login date for a user to be considered inactive. You can use strtotime notation e.g. "3 months"'), '#default_value' => $config->get('inactive_period') ?? '3 months', '#maxlength' => 180, ]; @@ -115,7 +115,7 @@ class AccountPolicyConfigForm extends ConfigFormBase { '#title' => $this->t('Warning email'), '#description' => $this->t('Email send out when the inactive warning period has expired.'), '#collapsible' => TRUE, - '#collapsed' => FALSE + '#collapsed' => FALSE, ]; $form['inactive_warning_mail']['inactive_warning_mail_subject'] = [