1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546 |
- <?php
- use Drupal\Component\Utility\Crypt;
- use Drupal\Component\Render\PlainTextOutput;
- use Drupal\Component\Utility\Unicode;
- use Drupal\Core\Access\AccessibleInterface;
- use Drupal\Core\Asset\AttachedAssetsInterface;
- use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
- use Drupal\Core\Field\BaseFieldDefinition;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\Render\Element;
- use Drupal\Core\Routing\RouteMatchInterface;
- use Drupal\Core\Session\AccountInterface;
- use Drupal\Core\Session\AnonymousUserSession;
- use Drupal\Core\Site\Settings;
- use Drupal\Core\Url;
- use Drupal\image\Plugin\Field\FieldType\ImageItem;
- use Drupal\system\Entity\Action;
- use Drupal\user\Entity\Role;
- use Drupal\user\Entity\User;
- use Drupal\user\RoleInterface;
- use Drupal\user\UserInterface;
- const USERNAME_MAX_LENGTH = 60;
- const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
- const USER_REGISTER_VISITORS = 'visitors';
- const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
- function user_help($route_name, RouteMatchInterface $route_match) {
- switch ($route_name) {
- case 'help.page.user':
- $output = '';
- $output .= '<h3>' . t('About') . '</h3>';
- $output .= '<p>' . t('The User module allows users to register, log in, and log out. It also allows users with proper permissions to manage user roles and permissions. For more information, see the <a href=":user_docs">online documentation for the User module</a>.', [':user_docs' => 'https://www.drupal.org/documentation/modules/user']) . '</p>';
- $output .= '<h3>' . t('Uses') . '</h3>';
- $output .= '<dl>';
- $output .= '<dt>' . t('Creating and managing users') . '</dt>';
- $output .= '<dd>' . t('Through the <a href=":people">People administration page</a> you can add and cancel user accounts and assign users to roles. By editing one particular user you can change their username, email address, password, and information in other fields.', [':people' => Url::fromRoute('entity.user.collection')->toString()]) . '</dd>';
- $output .= '<dt>' . t('Configuring user roles') . '</dt>';
- $output .= '<dd>' . t('<em>Roles</em> are used to group and classify users; each user can be assigned one or more roles. Typically there are two pre-defined roles: <em>Anonymous user</em> (users that are not logged in), and <em>Authenticated user</em> (users that are registered and logged in). Depending on how your site was set up, an <em>Administrator</em> role may also be available: users with this role will automatically be assigned any new permissions whenever a module is enabled. You can create additional roles on the <a href=":roles">Roles administration page</a>.', [':roles' => Url::fromRoute('entity.user_role.collection')->toString()]) . '</dd>';
- $output .= '<dt>' . t('Setting permissions') . '</dt>';
- $output .= '<dd>' . t('After creating roles, you can set permissions for each role on the <a href=":permissions_user">Permissions page</a>. Granting a permission allows users who have been assigned a particular role to perform an action on the site, such as viewing content, editing or creating a particular type of content, administering settings for a particular module, or using a particular function of the site (such as search).', [':permissions_user' => Url::fromRoute('user.admin_permissions')->toString()]) . '</dd>';
- $output .= '<dt>' . t('Managing account settings') . '</dt>';
- $output .= '<dd>' . t('The <a href=":accounts">Account settings page</a> allows you to manage settings for the displayed name of the Anonymous user role, personal contact forms, user registration settings, and account cancellation settings. On this page you can also manage settings for account personalization, and adapt the text for the email messages that users receive when they register or request a password recovery. You may also set which role is automatically assigned new permissions whenever a module is enabled (the Administrator role).', [':accounts' => Url::fromRoute('entity.user.admin_form')->toString()]) . '</dd>';
- $output .= '<dt>' . t('Managing user account fields') . '</dt>';
- $output .= '<dd>' . t('Because User accounts are an entity type, you can extend them by adding fields through the Manage fields tab on the <a href=":accounts">Account settings page</a>. By adding fields for e.g., a picture, a biography, or address, you can a create a custom profile for the users of the website. For background information on entities and fields, see the <a href=":field_help">Field module help page</a>.', [':field_help' => (\Drupal::moduleHandler()->moduleExists('field')) ? Url::fromRoute('help.page', ['name' => 'field'])->toString() : '#', ':accounts' => Url::fromRoute('entity.user.admin_form')->toString()]) . '</dd>';
- $output .= '</dl>';
- return $output;
- case 'user.admin_create':
- return '<p>' . t("This web page allows administrators to register new users. Users' email addresses and usernames must be unique.") . '</p>';
- case 'user.admin_permissions':
- return '<p>' . t('Permissions let you control what users can do and see on your site. You can define a specific set of permissions for each role. (See the <a href=":role">Roles</a> page to create a role.) Any permissions granted to the Authenticated user role will be given to any user who is logged in to your site. From the <a href=":settings">Account settings</a> page, you can make any role into an Administrator role for the site, meaning that role will be granted all new permissions automatically. You should be careful to ensure that only trusted users are given this access and level of control of your site.', [':role' => Url::fromRoute('entity.user_role.collection')->toString(), ':settings' => Url::fromRoute('entity.user.admin_form')->toString()]) . '</p>';
- case 'entity.user_role.collection':
- return '<p>' . t('A role defines a group of users that have certain privileges. These privileges are defined on the <a href=":permissions">Permissions page</a>. Here, you can define the names and the display sort order of the roles on your site. It is recommended to order roles from least permissive (for example, Anonymous user) to most permissive (for example, Administrator user). Users who are not logged in have the Anonymous user role. Users who are logged in have the Authenticated user role, plus any other roles granted to their user account.', [':permissions' => Url::fromRoute('user.admin_permissions')->toString()]) . '</p>';
- case 'entity.user.field_ui_fields':
- return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
- case 'entity.entity_form_display.user.default':
- return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
- case 'entity.entity_view_display.user.default':
- return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
- }
- }
- function user_theme() {
- return [
- 'user' => [
- 'render element' => 'elements',
- ],
- 'username' => [
- 'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
- ],
- ];
- }
- function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
-
-
-
-
-
- $user = \Drupal::currentUser();
- $settings['user']['uid'] = $user->id();
- $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
- }
- function user_picture_enabled() {
- $field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user');
- return isset($field_definitions['user_picture']);
- }
- function user_entity_extra_field_info() {
- $fields['user']['user']['form']['account'] = [
- 'label' => t('User name and password'),
- 'description' => t('User module account form elements.'),
- 'weight' => -10,
- ];
- $fields['user']['user']['form']['language'] = [
- 'label' => t('Language settings'),
- 'description' => t('User module form element.'),
- 'weight' => 0,
- ];
- if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
- $fields['user']['user']['form']['timezone'] = [
- 'label' => t('Timezone'),
- 'description' => t('System module form element.'),
- 'weight' => 6,
- ];
- }
- $fields['user']['user']['display']['member_for'] = [
- 'label' => t('Member for'),
- 'description' => t("User module 'member for' view element."),
- 'weight' => 5,
- ];
- return $fields;
- }
- function user_user_presave(UserInterface $account) {
- $config = \Drupal::config('system.date');
- if ($config->get('timezone.user.configurable') && !$account->getTimeZone() && !$config->get('timezone.user.default')) {
- $account->timezone = $config->get('timezone.default');
- }
- }
- function user_load_multiple(array $uids = NULL, $reset = FALSE) {
- @trigger_error('user_load_multiple() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\user\Entity\User::loadMultiple(). See https://www.drupal.org/node/2266845', E_USER_DEPRECATED);
- if ($reset) {
- \Drupal::entityTypeManager()->getStorage('user')->resetCache($uids);
- }
- return User::loadMultiple($uids);
- }
- function user_load($uid, $reset = FALSE) {
- @trigger_error('user_load() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\user\Entity\User::load(). See https://www.drupal.org/node/2266845', E_USER_DEPRECATED);
- if ($reset) {
- \Drupal::entityTypeManager()->getStorage('user')->resetCache([$uid]);
- }
- return User::load($uid);
- }
- function user_load_by_mail($mail) {
- $users = \Drupal::entityTypeManager()->getStorage('user')
- ->loadByProperties(['mail' => $mail]);
- return $users ? reset($users) : FALSE;
- }
- function user_load_by_name($name) {
- $users = \Drupal::entityTypeManager()->getStorage('user')
- ->loadByProperties(['name' => $name]);
- return $users ? reset($users) : FALSE;
- }
- function user_validate_name($name) {
- $definition = BaseFieldDefinition::create('string')
- ->addConstraint('UserName', []);
- $data = \Drupal::typedDataManager()->create($definition);
- $data->setValue($name);
- $violations = $data->validate();
- if (count($violations) > 0) {
- return $violations[0]->getMessage();
- }
- }
- function user_password($length = 10) {
-
-
-
- $allowed_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
-
- $max = strlen($allowed_characters) - 1;
- $pass = '';
- for ($i = 0; $i < $length; $i++) {
- $pass .= $allowed_characters[random_int(0, $max)];
- }
- return $pass;
- }
- function user_role_permissions(array $roles) {
- if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
- return _user_role_permissions_update($roles);
- }
- $entities = Role::loadMultiple($roles);
- $role_permissions = [];
- foreach ($roles as $rid) {
- $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : [];
- }
- return $role_permissions;
- }
- function _user_role_permissions_update($roles) {
- $role_permissions = [];
- foreach ($roles as $rid) {
- $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: [];
- }
- return $role_permissions;
- }
- function user_is_blocked($name) {
- return (bool) \Drupal::entityQuery('user')
- ->condition('name', $name)
- ->condition('status', 0)
- ->execute();
- }
- function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
- if ($display->getComponent('member_for')) {
- $build['member_for'] = [
- '#type' => 'item',
- '#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
- ];
- }
- }
- function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
- if (!empty($build['user_picture']) && user_picture_enabled()) {
- foreach (Element::children($build['user_picture']) as $key) {
- if (!isset($build['user_picture'][$key]['#item']) || !($build['user_picture'][$key]['#item'] instanceof ImageItem)) {
-
-
-
- continue;
- }
-
- $item = $build['user_picture'][$key]['#item'];
- if (!$item->get('alt')->getValue()) {
- $item->get('alt')->setValue(\Drupal::translation()->translate('Profile picture for user @username', ['@username' => $account->getAccountName()]));
- }
- }
- }
- }
- function user_preprocess_block(&$variables) {
- if ($variables['configuration']['provider'] == 'user') {
- switch ($variables['elements']['#plugin_id']) {
- case 'user_login_block':
- $variables['attributes']['role'] = 'form';
- break;
- }
- }
- }
- function user_format_name(AccountInterface $account) {
- @trigger_error('user_format_name() is deprecated in drupal:8.0.0 and is removed from drupal:9.0.0. Use $account->label() or $account->getDisplayName() instead. See https://www.drupal.org/node/3050794', E_USER_DEPRECATED);
- return $account->getDisplayName();
- }
- function user_template_preprocess_default_variables_alter(&$variables) {
- $user = \Drupal::currentUser();
- $variables['user'] = clone $user;
-
- unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
- $variables['is_admin'] = $user->hasPermission('access administration pages');
- $variables['logged_in'] = $user->isAuthenticated();
- }
- function template_preprocess_username(&$variables) {
- $account = $variables['account'] ?: new AnonymousUserSession();
- $variables['extra'] = '';
- $variables['uid'] = $account->id();
- if (empty($variables['uid'])) {
- if (theme_get_setting('features.comment_user_verification')) {
- $variables['extra'] = ' (' . t('not verified') . ')';
- }
- }
-
-
-
-
-
- $name = $account->getDisplayName();
- $variables['name_raw'] = $account->getAccountName();
- if (mb_strlen($name) > 20) {
- $name = Unicode::truncate($name, 15, FALSE, TRUE);
- $variables['truncated'] = TRUE;
- }
- else {
- $variables['truncated'] = FALSE;
- }
- $variables['name'] = $name;
- if ($account instanceof AccessibleInterface) {
- $variables['profile_access'] = $account->access('view');
- }
- else {
- $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
- }
- $external = FALSE;
-
- if ($variables['uid'] && $variables['profile_access']) {
-
- $variables['attributes']['title'] = t('View user profile.');
- $variables['link_path'] = 'user/' . $variables['uid'];
- }
- elseif (!empty($account->homepage)) {
-
-
-
- $variables['attributes']['rel'] = 'nofollow';
- $variables['link_path'] = $account->homepage;
- $variables['homepage'] = $account->homepage;
- $external = TRUE;
- }
-
- if (isset($variables['link_path'])) {
- if ($external) {
- $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
- ->toString();
- }
- else {
- $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', [
- 'user' => $variables['uid'],
- ])->toString();
- }
- }
- }
- function user_login_finalize(UserInterface $account) {
- \Drupal::currentUser()->setAccount($account);
- \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getAccountName()]);
-
-
- $account->setLastLoginTime(REQUEST_TIME);
- \Drupal::entityTypeManager()
- ->getStorage('user')
- ->updateLastLoginTimestamp($account);
-
-
-
-
- \Drupal::service('session')->migrate();
- \Drupal::service('session')->set('uid', $account->id());
- \Drupal::moduleHandler()->invokeAll('user_login', [$account]);
- }
- function user_user_login(UserInterface $account) {
-
-
- drupal_static_reset('template_preprocess');
-
- $config = \Drupal::config('system.date');
- if (!$account->getTimezone() && $config->get('timezone.user.configurable') && $config->get('timezone.user.warn')) {
- \Drupal::messenger()
- ->addStatus(t('Configure your <a href=":user-edit">account time zone setting</a>.', [
- ':user-edit' => $account->toUrl('edit-form', [
- 'query' => \Drupal::destination()->getAsArray(),
- 'fragment' => 'edit-timezone',
- ])->toString(),
- ]));
- }
- }
- function user_user_logout(AccountInterface $account) {
-
-
- drupal_static_reset('template_preprocess');
- }
- function user_pass_reset_url($account, $options = []) {
- $timestamp = REQUEST_TIME;
- $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
- return Url::fromRoute('user.reset',
- [
- 'uid' => $account->id(),
- 'timestamp' => $timestamp,
- 'hash' => user_pass_rehash($account, $timestamp),
- ],
- [
- 'absolute' => TRUE,
- 'language' => \Drupal::languageManager()->getLanguage($langcode),
- ]
- )->toString();
- }
- function user_cancel_url(UserInterface $account, $options = []) {
- $timestamp = REQUEST_TIME;
- $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
- $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)];
- return Url::fromRoute('user.cancel_confirm', [
- 'user' => $account->id(),
- 'timestamp' => $timestamp,
- 'hashed_pass' => user_pass_rehash($account, $timestamp),
- ], $url_options)->toString();
- }
- function user_pass_rehash(UserInterface $account, $timestamp) {
- $data = $timestamp;
- $data .= $account->getLastLoginTime();
- $data .= $account->id();
- $data .= $account->getEmail();
- return Crypt::hmacBase64($data, Settings::getHashSalt() . $account->getPassword());
- }
- function user_cancel($edit, $uid, $method) {
- $account = User::load($uid);
- if (!$account) {
- \Drupal::messenger()->addError(t('The user account %id does not exist.', ['%id' => $uid]));
- \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
- return;
- }
-
- $batch = [
- 'title' => t('Cancelling account'),
- 'operations' => [],
- ];
- batch_set($batch);
-
-
-
-
- if ($method != 'user_cancel_delete') {
-
- \Drupal::moduleHandler()->invokeAll('user_cancel', [$edit, $account, $method]);
- }
-
- $batch = [
- 'title' => t('Cancelling user account'),
- 'operations' => [
- ['_user_cancel', [$edit, $account, $method]],
- ],
- ];
-
- if ($account->id() == \Drupal::currentUser()->id()) {
-
-
- $batch['finished'] = '_user_cancel_session_regenerate';
- }
- batch_set($batch);
-
-
- }
- function _user_cancel($edit, $account, $method) {
- $logger = \Drupal::logger('user');
- switch ($method) {
- case 'user_cancel_block':
- case 'user_cancel_block_unpublish':
- default:
-
- if (!empty($edit['user_cancel_notify'])) {
- _user_mail_notify('status_blocked', $account);
- }
- $account->block();
- $account->save();
- \Drupal::messenger()->addStatus(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
- $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
- break;
- case 'user_cancel_reassign':
- case 'user_cancel_delete':
-
- if (!empty($edit['user_cancel_notify'])) {
- _user_mail_notify('status_canceled', $account);
- }
- $account->delete();
- \Drupal::messenger()->addStatus(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
- $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
- break;
- }
-
-
-
-
- if ($account->id() == \Drupal::currentUser()->id()) {
- \Drupal::currentUser()->setAccount(new AnonymousUserSession());
- }
- }
- function _user_cancel_session_regenerate() {
-
-
- \Drupal::service('session')->migrate();
- }
- function user_cancel_methods() {
- $user_settings = \Drupal::config('user.settings');
- $anonymous_name = $user_settings->get('anonymous');
- $methods = [
- 'user_cancel_block' => [
- 'title' => t('Disable the account and keep its content.'),
- 'description' => 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' => t('Disable the account and unpublish its content.'),
- 'description' => 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' => t('Delete the account and make its content belong to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
- 'description' => 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' => t('Delete the account and its content.'),
- 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
- 'access' => \Drupal::currentUser()->hasPermission('administer users'),
- ],
- ];
-
- \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
-
- $form = [
- '#options' => [],
- '#default_value' => $user_settings->get('cancel_method'),
- ];
- foreach ($methods as $name => $method) {
- $form['#options'][$name] = $method['title'];
-
-
-
- if (isset($method['description'])) {
- $form[$name]['#confirm_description'] = $method['description'];
- }
- if (isset($method['access'])) {
- $form[$name]['#access'] = $method['access'];
- }
- }
- return $form;
- }
- function user_delete($uid) {
- @trigger_error("user_delete() is deprecated in drupal:8.8.0. Use the user entity's delete method to delete the user. See https://www.drupal.org/node/3051463", E_USER_DEPRECATED);
- user_delete_multiple([$uid]);
- }
- function user_delete_multiple(array $uids) {
- @trigger_error("user_delete_multiple() is deprecated in drupal:8.8.0. Use the entity storage system to delete the users. See https://www.drupal.org/node/3051463", E_USER_DEPRECATED);
- entity_delete_multiple('user', $uids);
- }
- function user_view($account, $view_mode = 'full', $langcode = NULL) {
- @trigger_error("user_view() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use \Drupal::entityTypeManager()->getViewBuilder('user')->view() instead. See https://www.drupal.org/node/3033656", E_USER_DEPRECATED);
- return \Drupal::entityTypeManager()
- ->getViewBuilder('user')
- ->view($account, $view_mode, $langcode);
- }
- function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
- @trigger_error("user_view_multiple() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use \Drupal::entityTypeManager()->getViewBuilder('user')->viewMultiple() instead. See https://www.drupal.org/node/3033656", E_USER_DEPRECATED);
- return \Drupal::entityTypeManager()
- ->getViewBuilder('user')
- ->viewMultiple($accounts, $view_mode, $langcode);
- }
- function user_mail($key, &$message, $params) {
- $token_service = \Drupal::token();
- $language_manager = \Drupal::languageManager();
- $langcode = $message['langcode'];
- $variables = ['user' => $params['account']];
- $language = $language_manager->getLanguage($params['account']->getPreferredLangcode());
- $original_language = $language_manager->getConfigOverrideLanguage();
- $language_manager->setConfigOverrideLanguage($language);
- $mail_config = \Drupal::config('user.mail');
- $token_options = ['langcode' => $langcode, 'callback' => 'user_mail_tokens', 'clear' => TRUE];
- $message['subject'] .= PlainTextOutput::renderFromHtml($token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options));
- $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
- $language_manager->setConfigOverrideLanguage($original_language);
- }
- function user_mail_tokens(&$replacements, $data, $options) {
- if (isset($data['user'])) {
- $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
- $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
- }
- }
- function user_role_names($membersonly = FALSE, $permission = NULL) {
- return array_map(function ($item) {
- return $item->label();
- }, user_roles($membersonly, $permission));
- }
- function user_user_role_insert(RoleInterface $role) {
-
- if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
- return;
- }
- $add_id = 'user_add_role_action.' . $role->id();
- if (!Action::load($add_id)) {
- $action = Action::create([
- 'id' => $add_id,
- 'type' => 'user',
- 'label' => t('Add the @label role to the selected user(s)', ['@label' => $role->label()]),
- 'configuration' => [
- 'rid' => $role->id(),
- ],
- 'plugin' => 'user_add_role_action',
- ]);
- $action->trustData()->save();
- }
- $remove_id = 'user_remove_role_action.' . $role->id();
- if (!Action::load($remove_id)) {
- $action = Action::create([
- 'id' => $remove_id,
- 'type' => 'user',
- 'label' => t('Remove the @label role from the selected user(s)', ['@label' => $role->label()]),
- 'configuration' => [
- 'rid' => $role->id(),
- ],
- 'plugin' => 'user_remove_role_action',
- ]);
- $action->trustData()->save();
- }
- }
- function user_user_role_delete(RoleInterface $role) {
-
- $user_storage = \Drupal::entityTypeManager()->getStorage('user');
- $user_storage->deleteRoleReferences([$role->id()]);
-
- if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
- return;
- }
- $actions = Action::loadMultiple([
- 'user_add_role_action.' . $role->id(),
- 'user_remove_role_action.' . $role->id(),
- ]);
- foreach ($actions as $action) {
- $action->delete();
- }
- }
- function user_roles($membersonly = FALSE, $permission = NULL) {
- $roles = Role::loadMultiple();
- if ($membersonly) {
- unset($roles[RoleInterface::ANONYMOUS_ID]);
- }
- if (!empty($permission)) {
- $roles = array_filter($roles, function ($role) use ($permission) {
- return $role->hasPermission($permission);
- });
- }
- return $roles;
- }
- function user_role_load($rid) {
- return Role::load($rid);
- }
- function user_role_change_permissions($rid, array $permissions = []) {
-
- $grant = array_filter($permissions);
- if (!empty($grant)) {
- user_role_grant_permissions($rid, array_keys($grant));
- }
-
- $revoke = array_diff_assoc($permissions, $grant);
- if (!empty($revoke)) {
- user_role_revoke_permissions($rid, array_keys($revoke));
- }
- }
- function user_role_grant_permissions($rid, array $permissions = []) {
-
- if ($role = Role::load($rid)) {
- foreach ($permissions as $permission) {
- $role->grantPermission($permission);
- }
- $role->trustData()->save();
- }
- }
- function user_role_revoke_permissions($rid, array $permissions = []) {
-
- $role = Role::load($rid);
- foreach ($permissions as $permission) {
- $role->revokePermission($permission);
- }
- $role->trustData()->save();
- }
- function _user_mail_notify($op, AccountInterface $account, $langcode = NULL) {
- if (\Drupal::config('user.settings')->get('notify.' . $op)) {
- $params['account'] = $account;
- $langcode = $langcode ? $langcode : $account->getPreferredLangcode();
-
-
- $site_mail = \Drupal::config('system.site')->get('mail_notification');
-
-
- if (empty($site_mail)) {
- $site_mail = \Drupal::config('system.site')->get('mail');
- }
- if (empty($site_mail)) {
- $site_mail = ini_get('sendmail_from');
- }
- $mail = \Drupal::service('plugin.manager.mail')->mail('user', $op, $account->getEmail(), $langcode, $params, $site_mail);
- if ($op == 'register_pending_approval') {
-
-
- \Drupal::service('plugin.manager.mail')->mail('user', 'register_pending_approval_admin', $site_mail, \Drupal::languageManager()->getDefaultLanguage()->getId(), $params);
- }
- }
- return empty($mail) ? NULL : $mail['result'];
- }
- function user_element_info_alter(array &$types) {
- if (isset($types['password_confirm'])) {
- $types['password_confirm']['#process'][] = 'user_form_process_password_confirm';
- }
- }
- function user_form_process_password_confirm($element) {
- $password_settings = [
- 'confirmTitle' => t('Passwords match:'),
- 'confirmSuccess' => t('yes'),
- 'confirmFailure' => t('no'),
- 'showStrengthIndicator' => FALSE,
- ];
- if (\Drupal::config('user.settings')->get('password_strength')) {
- $password_settings['showStrengthIndicator'] = TRUE;
- $password_settings += [
- 'strengthTitle' => t('Password strength:'),
- 'hasWeaknesses' => t('Recommendations to make your password stronger:'),
- 'tooShort' => t('Make it at least 12 characters'),
- 'addLowerCase' => t('Add lowercase letters'),
- 'addUpperCase' => t('Add uppercase letters'),
- 'addNumbers' => t('Add numbers'),
- 'addPunctuation' => t('Add punctuation'),
- 'sameAsUsername' => t('Make it different from your username'),
- 'weak' => t('Weak'),
- 'fair' => t('Fair'),
- 'good' => t('Good'),
- 'strong' => t('Strong'),
- 'username' => \Drupal::currentUser()->getAccountName(),
- ];
- }
- $element['#attached']['library'][] = 'user/drupal.user';
- $element['#attached']['drupalSettings']['password'] = $password_settings;
- return $element;
- }
- function user_modules_uninstalled($modules) {
-
- \Drupal::service('user.data')->delete($modules);
- }
- function user_cookie_save(array $values) {
- foreach ($values as $field => $value) {
-
- setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
- }
- }
- function user_cookie_delete($cookie_name) {
- setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
- }
- function user_toolbar() {
- $user = \Drupal::currentUser();
- $items['user'] = [
- '#type' => 'toolbar_item',
- 'tab' => [
- '#type' => 'link',
- '#title' => $user->getDisplayName(),
- '#url' => Url::fromRoute('user.page'),
- '#attributes' => [
- 'title' => t('My account'),
- 'class' => ['toolbar-icon', 'toolbar-icon-user'],
- ],
- '#cache' => [
-
- 'contexts' => ['user.roles:anonymous'],
- ],
- ],
- 'tray' => [
- '#heading' => t('User account actions'),
- ],
- '#weight' => 100,
- '#attached' => [
- 'library' => [
- 'user/drupal.user.icons',
- ],
- ],
- ];
- if ($user->isAnonymous()) {
- $links = [
- 'login' => [
- 'title' => t('Log in'),
- 'url' => Url::fromRoute('user.page'),
- ],
- ];
- $items['user']['tray']['user_links'] = [
- '#theme' => 'links__toolbar_user',
- '#links' => $links,
- '#attributes' => [
- 'class' => ['toolbar-menu'],
- ],
- ];
- }
- else {
- $items['user']['tab']['#title'] = [
- '#lazy_builder' => ['user.toolbar_link_builder:renderDisplayName', []],
- '#create_placeholder' => TRUE,
- ];
- $items['user']['tray']['user_links'] = [
- '#lazy_builder' => ['user.toolbar_link_builder:renderToolbarLinks', []],
- '#create_placeholder' => TRUE,
- ];
- }
- return $items;
- }
- function user_logout() {
- $user = \Drupal::currentUser();
- \Drupal::logger('user')->notice('Session closed for %name.', ['%name' => $user->getAccountName()]);
- \Drupal::moduleHandler()->invokeAll('user_logout', [$user]);
-
-
-
-
-
- \Drupal::service('session_manager')->destroy();
- $user->setAccount(new AnonymousUserSession());
- }
- function template_preprocess_user(&$variables) {
- $variables['user'] = $variables['elements']['#user'];
-
- foreach (Element::children($variables['elements']) as $key) {
- $variables['content'][$key] = $variables['elements'][$key];
- }
- }
- function user_form_system_regional_settings_alter(&$form, FormStateInterface $form_state) {
- $config = \Drupal::config('system.date');
- $form['timezone']['configurable_timezones'] = [
- '#type' => 'checkbox',
- '#title' => t('Users may set their own time zone'),
- '#default_value' => $config->get('timezone.user.configurable'),
- ];
- $form['timezone']['configurable_timezones_wrapper'] = [
- '#type' => 'container',
- '#states' => [
-
-
- 'invisible' => [
- 'input[name="configurable_timezones"]' => ['checked' => FALSE],
- ],
- ],
- ];
- $form['timezone']['configurable_timezones_wrapper']['empty_timezone_message'] = [
- '#type' => 'checkbox',
- '#title' => t('Remind users at login if their time zone is not set'),
- '#default_value' => $config->get('timezone.user.warn'),
- '#description' => t('Only applied if users may set their own time zone.'),
- ];
- $form['timezone']['configurable_timezones_wrapper']['user_default_timezone'] = [
- '#type' => 'radios',
- '#title' => t('Time zone for new users'),
- '#default_value' => $config->get('timezone.user.default'),
- '#options' => [
- UserInterface::TIMEZONE_DEFAULT => t('Default time zone'),
- UserInterface::TIMEZONE_EMPTY => t('Empty time zone'),
- UserInterface::TIMEZONE_SELECT => t('Users may set their own time zone at registration'),
- ],
- '#description' => t('Only applied if users may set their own time zone.'),
- ];
- $form['#submit'][] = 'user_form_system_regional_settings_submit';
- }
- function user_form_system_regional_settings_submit($form, FormStateInterface $form_state) {
- \Drupal::configFactory()->getEditable('system.date')
- ->set('timezone.user.configurable', $form_state->getValue('configurable_timezones'))
- ->set('timezone.user.warn', $form_state->getValue('empty_timezone_message'))
- ->set('timezone.user.default', $form_state->getValue('user_default_timezone'))
- ->save();
- }
|