user.module 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  1. <?php
  2. /**
  3. * @file
  4. * Enables the user registration and login system.
  5. */
  6. use Drupal\Component\Utility\Crypt;
  7. use Drupal\Component\Render\PlainTextOutput;
  8. use Drupal\Component\Utility\Unicode;
  9. use Drupal\Core\Access\AccessibleInterface;
  10. use Drupal\Core\Asset\AttachedAssetsInterface;
  11. use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
  12. use Drupal\Core\Field\BaseFieldDefinition;
  13. use Drupal\Core\Form\FormStateInterface;
  14. use Drupal\Core\Render\Element;
  15. use Drupal\Core\Routing\RouteMatchInterface;
  16. use Drupal\Core\Session\AccountInterface;
  17. use Drupal\Core\Session\AnonymousUserSession;
  18. use Drupal\Core\Site\Settings;
  19. use Drupal\Core\Url;
  20. use Drupal\image\Plugin\Field\FieldType\ImageItem;
  21. use Drupal\system\Entity\Action;
  22. use Drupal\user\Entity\Role;
  23. use Drupal\user\Entity\User;
  24. use Drupal\user\RoleInterface;
  25. use Drupal\user\UserInterface;
  26. /**
  27. * Maximum length of username text field.
  28. *
  29. * Keep this under 191 characters so we can use a unique constraint in MySQL.
  30. *
  31. * @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0.
  32. * Use \Drupal\user\UserInterface::USERNAME_MAX_LENGTH instead.
  33. *
  34. * @see https://www.drupal.org/node/2831620
  35. */
  36. const USERNAME_MAX_LENGTH = 60;
  37. /**
  38. * Only administrators can create user accounts.
  39. *
  40. * @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0.
  41. * Use \Drupal\user\UserInterface::REGISTER_ADMINISTRATORS_ONLY instead.
  42. *
  43. * @see https://www.drupal.org/node/2831620
  44. */
  45. const USER_REGISTER_ADMINISTRATORS_ONLY = 'admin_only';
  46. /**
  47. * Visitors can create their own accounts.
  48. *
  49. * @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0.
  50. * Use \Drupal\user\UserInterface::REGISTER_VISITORS instead.
  51. *
  52. * @see https://www.drupal.org/node/2831620
  53. */
  54. const USER_REGISTER_VISITORS = 'visitors';
  55. /**
  56. * Visitors can create accounts, but they don't become active without
  57. * administrative approval.
  58. *
  59. * @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0.
  60. * Use \Drupal\user\UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL
  61. * instead.
  62. *
  63. * @see https://www.drupal.org/node/2831620
  64. */
  65. const USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL = 'visitors_admin_approval';
  66. /**
  67. * Implements hook_help().
  68. */
  69. function user_help($route_name, RouteMatchInterface $route_match) {
  70. switch ($route_name) {
  71. case 'help.page.user':
  72. $output = '';
  73. $output .= '<h3>' . t('About') . '</h3>';
  74. $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>';
  75. $output .= '<h3>' . t('Uses') . '</h3>';
  76. $output .= '<dl>';
  77. $output .= '<dt>' . t('Creating and managing users') . '</dt>';
  78. $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>';
  79. $output .= '<dt>' . t('Configuring user roles') . '</dt>';
  80. $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>';
  81. $output .= '<dt>' . t('Setting permissions') . '</dt>';
  82. $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>';
  83. $output .= '<dt>' . t('Managing account settings') . '</dt>';
  84. $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>';
  85. $output .= '<dt>' . t('Managing user account fields') . '</dt>';
  86. $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>';
  87. $output .= '</dl>';
  88. return $output;
  89. case 'user.admin_create':
  90. return '<p>' . t("This web page allows administrators to register new users. Users' email addresses and usernames must be unique.") . '</p>';
  91. case 'user.admin_permissions':
  92. 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>';
  93. case 'entity.user_role.collection':
  94. 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>';
  95. case 'entity.user.field_ui_fields':
  96. return '<p>' . t('This form lets administrators add and edit fields for storing user data.') . '</p>';
  97. case 'entity.entity_form_display.user.default':
  98. return '<p>' . t('This form lets administrators configure how form fields should be displayed when editing a user profile.') . '</p>';
  99. case 'entity.entity_view_display.user.default':
  100. return '<p>' . t('This form lets administrators configure how fields should be displayed when rendering a user profile page.') . '</p>';
  101. }
  102. }
  103. /**
  104. * Implements hook_theme().
  105. */
  106. function user_theme() {
  107. return [
  108. 'user' => [
  109. 'render element' => 'elements',
  110. ],
  111. 'username' => [
  112. 'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
  113. ],
  114. ];
  115. }
  116. /**
  117. * Implements hook_js_settings_alter().
  118. */
  119. function user_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
  120. // Provide the user ID in drupalSettings to allow JavaScript code to customize
  121. // the experience for the end user, rather than the server side, which would
  122. // break the render cache.
  123. // Similarly, provide a permissions hash, so that permission-dependent data
  124. // can be reliably cached on the client side.
  125. $user = \Drupal::currentUser();
  126. $settings['user']['uid'] = $user->id();
  127. $settings['user']['permissionsHash'] = \Drupal::service('user_permissions_hash_generator')->generate($user);
  128. }
  129. /**
  130. * Returns whether this site supports the default user picture feature.
  131. *
  132. * This approach preserves compatibility with node/comment templates. Alternate
  133. * user picture implementations (e.g., Gravatar) should provide their own
  134. * add/edit/delete forms and populate the 'picture' variable during the
  135. * preprocess stage.
  136. */
  137. function user_picture_enabled() {
  138. $field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user');
  139. return isset($field_definitions['user_picture']);
  140. }
  141. /**
  142. * Implements hook_entity_extra_field_info().
  143. */
  144. function user_entity_extra_field_info() {
  145. $fields['user']['user']['form']['account'] = [
  146. 'label' => t('User name and password'),
  147. 'description' => t('User module account form elements.'),
  148. 'weight' => -10,
  149. ];
  150. $fields['user']['user']['form']['language'] = [
  151. 'label' => t('Language settings'),
  152. 'description' => t('User module form element.'),
  153. 'weight' => 0,
  154. ];
  155. if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
  156. $fields['user']['user']['form']['timezone'] = [
  157. 'label' => t('Timezone'),
  158. 'description' => t('System module form element.'),
  159. 'weight' => 6,
  160. ];
  161. }
  162. $fields['user']['user']['display']['member_for'] = [
  163. 'label' => t('Member for'),
  164. 'description' => t("User module 'member for' view element."),
  165. 'weight' => 5,
  166. ];
  167. return $fields;
  168. }
  169. /**
  170. * Implements hook_ENTITY_TYPE_presave() for user entities.
  171. *
  172. * @todo https://www.drupal.org/project/drupal/issues/3112704 Move to
  173. * \Drupal\user\Entity\User::preSave().
  174. */
  175. function user_user_presave(UserInterface $account) {
  176. $config = \Drupal::config('system.date');
  177. if ($config->get('timezone.user.configurable') && !$account->getTimeZone() && !$config->get('timezone.user.default')) {
  178. $account->timezone = $config->get('timezone.default');
  179. }
  180. }
  181. /**
  182. * Loads multiple users based on certain conditions.
  183. *
  184. * This function should be used whenever you need to load more than one user
  185. * from the database. Users are loaded into memory and will not require
  186. * database access if loaded again during the same page request.
  187. *
  188. * @param array $uids
  189. * (optional) An array of entity IDs. If omitted, all entities are loaded.
  190. * @param bool $reset
  191. * A boolean indicating that the internal cache should be reset. Use this if
  192. * loading a user object which has been altered during the page request.
  193. *
  194. * @return array
  195. * An array of user objects, indexed by uid.
  196. *
  197. * @deprecated in drupal:8.0.0 and is removed from drupal:9.0.0. Use
  198. * \Drupal\user\Entity\User::loadMultiple().
  199. *
  200. * @see https://www.drupal.org/node/2266845
  201. */
  202. function user_load_multiple(array $uids = NULL, $reset = FALSE) {
  203. @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);
  204. if ($reset) {
  205. \Drupal::entityTypeManager()->getStorage('user')->resetCache($uids);
  206. }
  207. return User::loadMultiple($uids);
  208. }
  209. /**
  210. * Loads a user object.
  211. *
  212. * @param int $uid
  213. * Integer specifying the user ID to load.
  214. * @param bool $reset
  215. * TRUE to reset the internal cache and load from the database; FALSE
  216. * (default) to load from the internal cache, if set.
  217. *
  218. * @return \Drupal\user\UserInterface
  219. * A fully-loaded user object upon successful user load, or NULL if the user
  220. * cannot be loaded.
  221. *
  222. * @deprecated in drupal:8.0.0 and is removed from drupal:9.0.0. Use
  223. * Drupal\user\Entity\User::load().
  224. *
  225. * @see https://www.drupal.org/node/2266845
  226. */
  227. function user_load($uid, $reset = FALSE) {
  228. @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);
  229. if ($reset) {
  230. \Drupal::entityTypeManager()->getStorage('user')->resetCache([$uid]);
  231. }
  232. return User::load($uid);
  233. }
  234. /**
  235. * Fetches a user object by email address.
  236. *
  237. * @param string $mail
  238. * String with the account's email address.
  239. *
  240. * @return \Drupal\user\UserInterface|false
  241. * A user entity upon successful user load, or FALSE if user cannot be loaded.
  242. *
  243. * @see \Drupal\user\Entity\User::loadMultiple()
  244. */
  245. function user_load_by_mail($mail) {
  246. $users = \Drupal::entityTypeManager()->getStorage('user')
  247. ->loadByProperties(['mail' => $mail]);
  248. return $users ? reset($users) : FALSE;
  249. }
  250. /**
  251. * Fetches a user object by account name.
  252. *
  253. * @param string $name
  254. * String with the account's user name.
  255. *
  256. * @return \Drupal\user\UserInterface|false
  257. * A user entity upon successful user load, or FALSE if user cannot be loaded.
  258. *
  259. * @see \Drupal\user\Entity\User::loadMultiple()
  260. */
  261. function user_load_by_name($name) {
  262. $users = \Drupal::entityTypeManager()->getStorage('user')
  263. ->loadByProperties(['name' => $name]);
  264. return $users ? reset($users) : FALSE;
  265. }
  266. /**
  267. * Verify the syntax of the given name.
  268. *
  269. * @param string $name
  270. * The user name to validate.
  271. *
  272. * @return string|null
  273. * A translated violation message if the name is invalid or NULL if the name
  274. * is valid.
  275. */
  276. function user_validate_name($name) {
  277. $definition = BaseFieldDefinition::create('string')
  278. ->addConstraint('UserName', []);
  279. $data = \Drupal::typedDataManager()->create($definition);
  280. $data->setValue($name);
  281. $violations = $data->validate();
  282. if (count($violations) > 0) {
  283. return $violations[0]->getMessage();
  284. }
  285. }
  286. /**
  287. * Generate a random alphanumeric password.
  288. *
  289. * @param int $length
  290. * The desired password length, in characters.
  291. *
  292. * @return string
  293. * The generated random password.
  294. */
  295. function user_password($length = 10) {
  296. // This variable contains the list of allowed characters for the password.
  297. // Note that the number 0 and the letter 'O' have been removed to avoid
  298. // confusion between the two. The same is true of 'I', 1, and 'l'.
  299. $allowed_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  300. // The maximum integer we want from random_int().
  301. $max = strlen($allowed_characters) - 1;
  302. $pass = '';
  303. for ($i = 0; $i < $length; $i++) {
  304. $pass .= $allowed_characters[random_int(0, $max)];
  305. }
  306. return $pass;
  307. }
  308. /**
  309. * Determine the permissions for one or more roles.
  310. *
  311. * @param array $roles
  312. * An array of role IDs.
  313. *
  314. * @return array
  315. * An array indexed by role ID. Each value is an array of permission strings
  316. * for the given role.
  317. */
  318. function user_role_permissions(array $roles) {
  319. if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
  320. return _user_role_permissions_update($roles);
  321. }
  322. $entities = Role::loadMultiple($roles);
  323. $role_permissions = [];
  324. foreach ($roles as $rid) {
  325. $role_permissions[$rid] = isset($entities[$rid]) ? $entities[$rid]->getPermissions() : [];
  326. }
  327. return $role_permissions;
  328. }
  329. /**
  330. * Determine the permissions for one or more roles during update.
  331. *
  332. * A separate version is needed because during update the entity system can't
  333. * be used and in non-update situations the entity system is preferred because
  334. * of the hook system.
  335. *
  336. * @param array $roles
  337. * An array of role IDs.
  338. *
  339. * @return array
  340. * An array indexed by role ID. Each value is an array of permission strings
  341. * for the given role.
  342. */
  343. function _user_role_permissions_update($roles) {
  344. $role_permissions = [];
  345. foreach ($roles as $rid) {
  346. $role_permissions[$rid] = \Drupal::config("user.role.$rid")->get('permissions') ?: [];
  347. }
  348. return $role_permissions;
  349. }
  350. /**
  351. * Checks for usernames blocked by user administration.
  352. *
  353. * @param string $name
  354. * A string containing a name of the user.
  355. *
  356. * @return bool
  357. * TRUE if the user is blocked, FALSE otherwise.
  358. */
  359. function user_is_blocked($name) {
  360. return (bool) \Drupal::entityQuery('user')
  361. ->condition('name', $name)
  362. ->condition('status', 0)
  363. ->execute();
  364. }
  365. /**
  366. * Implements hook_ENTITY_TYPE_view() for user entities.
  367. */
  368. function user_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
  369. if ($display->getComponent('member_for')) {
  370. $build['member_for'] = [
  371. '#type' => 'item',
  372. '#markup' => '<h4 class="label">' . t('Member for') . '</h4> ' . \Drupal::service('date.formatter')->formatTimeDiffSince($account->getCreatedTime()),
  373. ];
  374. }
  375. }
  376. /**
  377. * Implements hook_ENTITY_TYPE_view_alter() for user entities.
  378. *
  379. * This function adds a default alt tag to the user_picture field to maintain
  380. * accessibility.
  381. */
  382. function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
  383. if (!empty($build['user_picture']) && user_picture_enabled()) {
  384. foreach (Element::children($build['user_picture']) as $key) {
  385. if (!isset($build['user_picture'][$key]['#item']) || !($build['user_picture'][$key]['#item'] instanceof ImageItem)) {
  386. // User picture field is provided by standard profile install. If the
  387. // display is configured to use a different formatter, the #item render
  388. // key may not exist, or may not be an image field.
  389. continue;
  390. }
  391. /** @var \Drupal\image\Plugin\Field\FieldType\ImageItem $item */
  392. $item = $build['user_picture'][$key]['#item'];
  393. if (!$item->get('alt')->getValue()) {
  394. $item->get('alt')->setValue(\Drupal::translation()->translate('Profile picture for user @username', ['@username' => $account->getAccountName()]));
  395. }
  396. }
  397. }
  398. }
  399. /**
  400. * Implements hook_preprocess_HOOK() for block templates.
  401. */
  402. function user_preprocess_block(&$variables) {
  403. if ($variables['configuration']['provider'] == 'user') {
  404. switch ($variables['elements']['#plugin_id']) {
  405. case 'user_login_block':
  406. $variables['attributes']['role'] = 'form';
  407. break;
  408. }
  409. }
  410. }
  411. /**
  412. * Format a username.
  413. *
  414. * @param \Drupal\Core\Session\AccountInterface $account
  415. * The account object for the user whose name is to be formatted.
  416. *
  417. * @return string
  418. * An unsanitized string with the username to display.
  419. *
  420. * @deprecated in drupal:8.0.0 and is removed from drupal:9.0.0.
  421. * Use $account->label() or $account->getDisplayName() instead
  422. *
  423. * @see https://www.drupal.org/node/3050794
  424. */
  425. function user_format_name(AccountInterface $account) {
  426. @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);
  427. return $account->getDisplayName();
  428. }
  429. /**
  430. * Implements hook_template_preprocess_default_variables_alter().
  431. *
  432. * @see user_user_login()
  433. * @see user_user_logout()
  434. */
  435. function user_template_preprocess_default_variables_alter(&$variables) {
  436. $user = \Drupal::currentUser();
  437. $variables['user'] = clone $user;
  438. // Remove password and session IDs, since themes should not need nor see them.
  439. unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
  440. $variables['is_admin'] = $user->hasPermission('access administration pages');
  441. $variables['logged_in'] = $user->isAuthenticated();
  442. }
  443. /**
  444. * Prepares variables for username templates.
  445. *
  446. * Default template: username.html.twig.
  447. *
  448. * Modules that make any changes to variables like 'name' or 'extra' must ensure
  449. * that the final string is safe.
  450. *
  451. * @param array $variables
  452. * An associative array containing:
  453. * - account: The user account (\Drupal\Core\Session\AccountInterface).
  454. */
  455. function template_preprocess_username(&$variables) {
  456. $account = $variables['account'] ?: new AnonymousUserSession();
  457. $variables['extra'] = '';
  458. $variables['uid'] = $account->id();
  459. if (empty($variables['uid'])) {
  460. if (theme_get_setting('features.comment_user_verification')) {
  461. $variables['extra'] = ' (' . t('not verified') . ')';
  462. }
  463. }
  464. // Set the name to a formatted name that is safe for printing and
  465. // that won't break tables by being too long. Keep an unshortened,
  466. // unsanitized version, in case other preprocess functions want to implement
  467. // their own shortening logic or add markup. If they do so, they must ensure
  468. // that $variables['name'] is safe for printing.
  469. $name = $account->getDisplayName();
  470. $variables['name_raw'] = $account->getAccountName();
  471. if (mb_strlen($name) > 20) {
  472. $name = Unicode::truncate($name, 15, FALSE, TRUE);
  473. $variables['truncated'] = TRUE;
  474. }
  475. else {
  476. $variables['truncated'] = FALSE;
  477. }
  478. $variables['name'] = $name;
  479. if ($account instanceof AccessibleInterface) {
  480. $variables['profile_access'] = $account->access('view');
  481. }
  482. else {
  483. $variables['profile_access'] = \Drupal::currentUser()->hasPermission('access user profiles');
  484. }
  485. $external = FALSE;
  486. // Populate link path and attributes if appropriate.
  487. if ($variables['uid'] && $variables['profile_access']) {
  488. // We are linking to a local user.
  489. $variables['attributes']['title'] = t('View user profile.');
  490. $variables['link_path'] = 'user/' . $variables['uid'];
  491. }
  492. elseif (!empty($account->homepage)) {
  493. // Like the 'class' attribute, the 'rel' attribute can hold a
  494. // space-separated set of values, so initialize it as an array to make it
  495. // easier for other preprocess functions to append to it.
  496. $variables['attributes']['rel'] = 'nofollow';
  497. $variables['link_path'] = $account->homepage;
  498. $variables['homepage'] = $account->homepage;
  499. $external = TRUE;
  500. }
  501. // We have a link path, so we should generate a URL.
  502. if (isset($variables['link_path'])) {
  503. if ($external) {
  504. $variables['attributes']['href'] = Url::fromUri($variables['link_path'], $variables['link_options'])
  505. ->toString();
  506. }
  507. else {
  508. $variables['attributes']['href'] = Url::fromRoute('entity.user.canonical', [
  509. 'user' => $variables['uid'],
  510. ])->toString();
  511. }
  512. }
  513. }
  514. /**
  515. * Finalizes the login process and logs in a user.
  516. *
  517. * The function logs in the user, records a watchdog message about the new
  518. * session, saves the login timestamp, calls hook_user_login(), and generates a
  519. * new session.
  520. *
  521. * The current user is replaced with the passed in account.
  522. *
  523. * @param \Drupal\user\UserInterface $account
  524. * The account to log in.
  525. *
  526. * @see hook_user_login()
  527. */
  528. function user_login_finalize(UserInterface $account) {
  529. \Drupal::currentUser()->setAccount($account);
  530. \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getAccountName()]);
  531. // Update the user table timestamp noting user has logged in.
  532. // This is also used to invalidate one-time login links.
  533. $account->setLastLoginTime(REQUEST_TIME);
  534. \Drupal::entityTypeManager()
  535. ->getStorage('user')
  536. ->updateLastLoginTimestamp($account);
  537. // Regenerate the session ID to prevent against session fixation attacks.
  538. // This is called before hook_user_login() in case one of those functions
  539. // fails or incorrectly does a redirect which would leave the old session
  540. // in place.
  541. \Drupal::service('session')->migrate();
  542. \Drupal::service('session')->set('uid', $account->id());
  543. \Drupal::moduleHandler()->invokeAll('user_login', [$account]);
  544. }
  545. /**
  546. * Implements hook_user_login().
  547. */
  548. function user_user_login(UserInterface $account) {
  549. // Reset static cache of default variables in template_preprocess() to reflect
  550. // the new user.
  551. drupal_static_reset('template_preprocess');
  552. // If the user has a NULL time zone, notify them to set a time zone.
  553. $config = \Drupal::config('system.date');
  554. if (!$account->getTimezone() && $config->get('timezone.user.configurable') && $config->get('timezone.user.warn')) {
  555. \Drupal::messenger()
  556. ->addStatus(t('Configure your <a href=":user-edit">account time zone setting</a>.', [
  557. ':user-edit' => $account->toUrl('edit-form', [
  558. 'query' => \Drupal::destination()->getAsArray(),
  559. 'fragment' => 'edit-timezone',
  560. ])->toString(),
  561. ]));
  562. }
  563. }
  564. /**
  565. * Implements hook_user_logout().
  566. */
  567. function user_user_logout(AccountInterface $account) {
  568. // Reset static cache of default variables in template_preprocess() to reflect
  569. // the new user.
  570. drupal_static_reset('template_preprocess');
  571. }
  572. /**
  573. * Generates a unique URL for a user to log in and reset their password.
  574. *
  575. * @param \Drupal\user\UserInterface $account
  576. * An object containing the user account.
  577. * @param array $options
  578. * (optional) A keyed array of settings. Supported options are:
  579. * - langcode: A language code to be used when generating locale-sensitive
  580. * URLs. If langcode is NULL the users preferred language is used.
  581. *
  582. * @return string
  583. * A unique URL that provides a one-time log in for the user, from which
  584. * they can change their password.
  585. */
  586. function user_pass_reset_url($account, $options = []) {
  587. $timestamp = REQUEST_TIME;
  588. $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
  589. return Url::fromRoute('user.reset',
  590. [
  591. 'uid' => $account->id(),
  592. 'timestamp' => $timestamp,
  593. 'hash' => user_pass_rehash($account, $timestamp),
  594. ],
  595. [
  596. 'absolute' => TRUE,
  597. 'language' => \Drupal::languageManager()->getLanguage($langcode),
  598. ]
  599. )->toString();
  600. }
  601. /**
  602. * Generates a URL to confirm an account cancellation request.
  603. *
  604. * @param \Drupal\user\UserInterface $account
  605. * The user account object.
  606. * @param array $options
  607. * (optional) A keyed array of settings. Supported options are:
  608. * - langcode: A language code to be used when generating locale-sensitive
  609. * URLs. If langcode is NULL the users preferred language is used.
  610. *
  611. * @return string
  612. * A unique URL that may be used to confirm the cancellation of the user
  613. * account.
  614. *
  615. * @see user_mail_tokens()
  616. * @see \Drupal\user\Controller\UserController::confirmCancel()
  617. */
  618. function user_cancel_url(UserInterface $account, $options = []) {
  619. $timestamp = REQUEST_TIME;
  620. $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
  621. $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)];
  622. return Url::fromRoute('user.cancel_confirm', [
  623. 'user' => $account->id(),
  624. 'timestamp' => $timestamp,
  625. 'hashed_pass' => user_pass_rehash($account, $timestamp),
  626. ], $url_options)->toString();
  627. }
  628. /**
  629. * Creates a unique hash value for use in time-dependent per-user URLs.
  630. *
  631. * This hash is normally used to build a unique and secure URL that is sent to
  632. * the user by email for purposes such as resetting the user's password. In
  633. * order to validate the URL, the same hash can be generated again, from the
  634. * same information, and compared to the hash value from the URL. The hash
  635. * contains the time stamp, the user's last login time, the numeric user ID,
  636. * and the user's email address.
  637. * For a usage example, see user_cancel_url() and
  638. * \Drupal\user\Controller\UserController::confirmCancel().
  639. *
  640. * @param \Drupal\user\UserInterface $account
  641. * An object containing the user account.
  642. * @param int $timestamp
  643. * A UNIX timestamp, typically REQUEST_TIME.
  644. *
  645. * @return string
  646. * A string that is safe for use in URLs and SQL statements.
  647. */
  648. function user_pass_rehash(UserInterface $account, $timestamp) {
  649. $data = $timestamp;
  650. $data .= $account->getLastLoginTime();
  651. $data .= $account->id();
  652. $data .= $account->getEmail();
  653. return Crypt::hmacBase64($data, Settings::getHashSalt() . $account->getPassword());
  654. }
  655. /**
  656. * Cancel a user account.
  657. *
  658. * Since the user cancellation process needs to be run in a batch, either
  659. * Form API will invoke it, or batch_process() needs to be invoked after calling
  660. * this function and should define the path to redirect to.
  661. *
  662. * @param array $edit
  663. * An array of submitted form values.
  664. * @param int $uid
  665. * The user ID of the user account to cancel.
  666. * @param string $method
  667. * The account cancellation method to use.
  668. *
  669. * @see _user_cancel()
  670. */
  671. function user_cancel($edit, $uid, $method) {
  672. $account = User::load($uid);
  673. if (!$account) {
  674. \Drupal::messenger()->addError(t('The user account %id does not exist.', ['%id' => $uid]));
  675. \Drupal::logger('user')->error('Attempted to cancel non-existing user account: %id.', ['%id' => $uid]);
  676. return;
  677. }
  678. // Initialize batch (to set title).
  679. $batch = [
  680. 'title' => t('Cancelling account'),
  681. 'operations' => [],
  682. ];
  683. batch_set($batch);
  684. // When the 'user_cancel_delete' method is used, user_delete() is called,
  685. // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
  686. // for the user entity. Modules should use those hooks to respond to the
  687. // account deletion.
  688. if ($method != 'user_cancel_delete') {
  689. // Allow modules to add further sets to this batch.
  690. \Drupal::moduleHandler()->invokeAll('user_cancel', [$edit, $account, $method]);
  691. }
  692. // Finish the batch and actually cancel the account.
  693. $batch = [
  694. 'title' => t('Cancelling user account'),
  695. 'operations' => [
  696. ['_user_cancel', [$edit, $account, $method]],
  697. ],
  698. ];
  699. // After cancelling account, ensure that user is logged out.
  700. if ($account->id() == \Drupal::currentUser()->id()) {
  701. // Batch API stores data in the session, so use the finished operation to
  702. // manipulate the current user's session id.
  703. $batch['finished'] = '_user_cancel_session_regenerate';
  704. }
  705. batch_set($batch);
  706. // Batch processing is either handled via Form API or has to be invoked
  707. // manually.
  708. }
  709. /**
  710. * Implements callback_batch_operation().
  711. *
  712. * Last step for cancelling a user account.
  713. *
  714. * Since batch and session API require a valid user account, the actual
  715. * cancellation of a user account needs to happen last.
  716. * @param array $edit
  717. * An array of submitted form values.
  718. * @param \Drupal\user\UserInterface $account
  719. * The user ID of the user account to cancel.
  720. * @param string $method
  721. * The account cancellation method to use.
  722. *
  723. * @see user_cancel()
  724. */
  725. function _user_cancel($edit, $account, $method) {
  726. $logger = \Drupal::logger('user');
  727. switch ($method) {
  728. case 'user_cancel_block':
  729. case 'user_cancel_block_unpublish':
  730. default:
  731. // Send account blocked notification if option was checked.
  732. if (!empty($edit['user_cancel_notify'])) {
  733. _user_mail_notify('status_blocked', $account);
  734. }
  735. $account->block();
  736. $account->save();
  737. \Drupal::messenger()->addStatus(t('%name has been disabled.', ['%name' => $account->getDisplayName()]));
  738. $logger->notice('Blocked user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
  739. break;
  740. case 'user_cancel_reassign':
  741. case 'user_cancel_delete':
  742. // Send account canceled notification if option was checked.
  743. if (!empty($edit['user_cancel_notify'])) {
  744. _user_mail_notify('status_canceled', $account);
  745. }
  746. $account->delete();
  747. \Drupal::messenger()->addStatus(t('%name has been deleted.', ['%name' => $account->getDisplayName()]));
  748. $logger->notice('Deleted user: %name %email.', ['%name' => $account->getAccountName(), '%email' => '<' . $account->getEmail() . '>']);
  749. break;
  750. }
  751. // After cancelling account, ensure that user is logged out. We can't destroy
  752. // their session though, as we might have information in it, and we can't
  753. // regenerate it because batch API uses the session ID, we will regenerate it
  754. // in _user_cancel_session_regenerate().
  755. if ($account->id() == \Drupal::currentUser()->id()) {
  756. \Drupal::currentUser()->setAccount(new AnonymousUserSession());
  757. }
  758. }
  759. /**
  760. * Implements callback_batch_finished().
  761. *
  762. * Finished batch processing callback for cancelling a user account.
  763. *
  764. * @see user_cancel()
  765. */
  766. function _user_cancel_session_regenerate() {
  767. // Regenerate the users session instead of calling session_destroy() as we
  768. // want to preserve any messages that might have been set.
  769. \Drupal::service('session')->migrate();
  770. }
  771. /**
  772. * Helper function to return available account cancellation methods.
  773. *
  774. * See documentation of hook_user_cancel_methods_alter().
  775. *
  776. * @return array
  777. * An array containing all account cancellation methods as form elements.
  778. *
  779. * @see hook_user_cancel_methods_alter()
  780. * @see user_admin_settings()
  781. */
  782. function user_cancel_methods() {
  783. $user_settings = \Drupal::config('user.settings');
  784. $anonymous_name = $user_settings->get('anonymous');
  785. $methods = [
  786. 'user_cancel_block' => [
  787. 'title' => t('Disable the account and keep its content.'),
  788. '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.'),
  789. ],
  790. 'user_cancel_block_unpublish' => [
  791. 'title' => t('Disable the account and unpublish its content.'),
  792. '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.'),
  793. ],
  794. 'user_cancel_reassign' => [
  795. 'title' => t('Delete the account and make its content belong to the %anonymous-name user.', ['%anonymous-name' => $anonymous_name]),
  796. '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]),
  797. ],
  798. 'user_cancel_delete' => [
  799. 'title' => t('Delete the account and its content.'),
  800. 'description' => t('Your account will be removed and all account information deleted. All of your content will also be deleted.'),
  801. 'access' => \Drupal::currentUser()->hasPermission('administer users'),
  802. ],
  803. ];
  804. // Allow modules to customize account cancellation methods.
  805. \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
  806. // Turn all methods into real form elements.
  807. $form = [
  808. '#options' => [],
  809. '#default_value' => $user_settings->get('cancel_method'),
  810. ];
  811. foreach ($methods as $name => $method) {
  812. $form['#options'][$name] = $method['title'];
  813. // Add the description for the confirmation form. This description is never
  814. // shown for the cancel method option, only on the confirmation form.
  815. // Therefore, we use a custom #confirm_description property.
  816. if (isset($method['description'])) {
  817. $form[$name]['#confirm_description'] = $method['description'];
  818. }
  819. if (isset($method['access'])) {
  820. $form[$name]['#access'] = $method['access'];
  821. }
  822. }
  823. return $form;
  824. }
  825. /**
  826. * Delete a user.
  827. *
  828. * @param int $uid
  829. * A user ID.
  830. *
  831. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use the user
  832. * entity's delete method to delete the user.
  833. * @code
  834. * Drupal::entityTypeManager->getStorage('user')->load($uid)->delete();
  835. * @endcode
  836. *
  837. * @see https://www.drupal.org/node/3051463
  838. */
  839. function user_delete($uid) {
  840. @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);
  841. user_delete_multiple([$uid]);
  842. }
  843. /**
  844. * Delete multiple user accounts.
  845. *
  846. * @param int[] $uids
  847. * An array of user IDs.
  848. *
  849. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use the
  850. * entity storage system to delete the users.
  851. * @code
  852. * $storage_handler = \Drupal::entityTypeManager()->getStorage('user');
  853. * $users = $storage_handler->loadMultiple($uids);
  854. * $storage_handler->delete($users);
  855. * @endcode
  856. *
  857. * @see https://www.drupal.org/node/3051463
  858. */
  859. function user_delete_multiple(array $uids) {
  860. @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);
  861. entity_delete_multiple('user', $uids);
  862. }
  863. /**
  864. * Generate an array for rendering the given user.
  865. *
  866. * When viewing a user profile, the $page array contains:
  867. *
  868. * - $page['content']['member_for']:
  869. * Contains the default "Member for" profile data for a user.
  870. * - $page['content']['#user']:
  871. * The user account of the profile being viewed.
  872. *
  873. * To theme user profiles, copy core/modules/user/templates/user.html.twig
  874. * to your theme directory, and edit it as instructed in that file's comments.
  875. *
  876. * @param \Drupal\user\UserInterface $account
  877. * A user object.
  878. * @param string $view_mode
  879. * View mode, e.g. 'full'.
  880. * @param string|null $langcode
  881. * (optional) A language code to use for rendering. Defaults to the global
  882. * content language of the current request.
  883. *
  884. * @return array
  885. * An array as expected by \Drupal\Core\Render\RendererInterface::render().
  886. *
  887. * @deprecated in drupal:8.7.0 and is removed from drupal:9.0.0. Use
  888. * \Drupal::entityTypeManager()->getViewBuilder('user')->view() instead.
  889. *
  890. * @see https://www.drupal.org/node/3033656
  891. */
  892. function user_view($account, $view_mode = 'full', $langcode = NULL) {
  893. @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);
  894. return \Drupal::entityTypeManager()
  895. ->getViewBuilder('user')
  896. ->view($account, $view_mode, $langcode);
  897. }
  898. /**
  899. * Constructs a drupal_render() style array from an array of loaded users.
  900. *
  901. * @param \Drupal\user\UserInterface[] $accounts
  902. * An array of user accounts as returned by User::loadMultiple().
  903. * @param string $view_mode
  904. * (optional) View mode, e.g., 'full', 'teaser', etc. Defaults to 'teaser.'
  905. * @param string|null $langcode
  906. * (optional) A language code to use for rendering. Defaults to the global
  907. * content language of the current request.
  908. *
  909. * @return array
  910. * An array in the format expected by
  911. * \Drupal\Core\Render\RendererInterface::render().
  912. *
  913. * @deprecated in drupal:8.7.0 and is removed from drupal:9.0.0. Use
  914. * \Drupal::entityTypeManager()->getViewBuilder('user')->viewMultiple()
  915. * instead.
  916. *
  917. * @see https://www.drupal.org/node/3033656
  918. */
  919. function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
  920. @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);
  921. return \Drupal::entityTypeManager()
  922. ->getViewBuilder('user')
  923. ->viewMultiple($accounts, $view_mode, $langcode);
  924. }
  925. /**
  926. * Implements hook_mail().
  927. */
  928. function user_mail($key, &$message, $params) {
  929. $token_service = \Drupal::token();
  930. $language_manager = \Drupal::languageManager();
  931. $langcode = $message['langcode'];
  932. $variables = ['user' => $params['account']];
  933. $language = $language_manager->getLanguage($params['account']->getPreferredLangcode());
  934. $original_language = $language_manager->getConfigOverrideLanguage();
  935. $language_manager->setConfigOverrideLanguage($language);
  936. $mail_config = \Drupal::config('user.mail');
  937. $token_options = ['langcode' => $langcode, 'callback' => 'user_mail_tokens', 'clear' => TRUE];
  938. $message['subject'] .= PlainTextOutput::renderFromHtml($token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options));
  939. $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
  940. $language_manager->setConfigOverrideLanguage($original_language);
  941. }
  942. /**
  943. * Token callback to add unsafe tokens for user mails.
  944. *
  945. * This function is used by \Drupal\Core\Utility\Token::replace() to set up
  946. * some additional tokens that can be used in email messages generated by
  947. * user_mail().
  948. *
  949. * @param array $replacements
  950. * An associative array variable containing mappings from token names to
  951. * values (for use with strtr()).
  952. * @param array $data
  953. * An associative array of token replacement values. If the 'user' element
  954. * exists, it must contain a user account object with the following
  955. * properties:
  956. * - login: The UNIX timestamp of the user's last login.
  957. * - pass: The hashed account login password.
  958. * @param array $options
  959. * A keyed array of settings and flags to control the token replacement
  960. * process. See \Drupal\Core\Utility\Token::replace().
  961. */
  962. function user_mail_tokens(&$replacements, $data, $options) {
  963. if (isset($data['user'])) {
  964. $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
  965. $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
  966. }
  967. }
  968. /**
  969. * Retrieves the names of roles matching specified conditions.
  970. *
  971. * @param bool $membersonly
  972. * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
  973. * FALSE.
  974. * @param string|null $permission
  975. * (optional) A string containing a permission. If set, only roles
  976. * containing that permission are returned. Defaults to NULL, which
  977. * returns all roles.
  978. *
  979. * @return array
  980. * An associative array with the role id as the key and the role name as
  981. * value.
  982. */
  983. function user_role_names($membersonly = FALSE, $permission = NULL) {
  984. return array_map(function ($item) {
  985. return $item->label();
  986. }, user_roles($membersonly, $permission));
  987. }
  988. /**
  989. * Implements hook_ENTITY_TYPE_insert() for user_role entities.
  990. */
  991. function user_user_role_insert(RoleInterface $role) {
  992. // Ignore the authenticated and anonymous roles or the role is being synced.
  993. if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
  994. return;
  995. }
  996. $add_id = 'user_add_role_action.' . $role->id();
  997. if (!Action::load($add_id)) {
  998. $action = Action::create([
  999. 'id' => $add_id,
  1000. 'type' => 'user',
  1001. 'label' => t('Add the @label role to the selected user(s)', ['@label' => $role->label()]),
  1002. 'configuration' => [
  1003. 'rid' => $role->id(),
  1004. ],
  1005. 'plugin' => 'user_add_role_action',
  1006. ]);
  1007. $action->trustData()->save();
  1008. }
  1009. $remove_id = 'user_remove_role_action.' . $role->id();
  1010. if (!Action::load($remove_id)) {
  1011. $action = Action::create([
  1012. 'id' => $remove_id,
  1013. 'type' => 'user',
  1014. 'label' => t('Remove the @label role from the selected user(s)', ['@label' => $role->label()]),
  1015. 'configuration' => [
  1016. 'rid' => $role->id(),
  1017. ],
  1018. 'plugin' => 'user_remove_role_action',
  1019. ]);
  1020. $action->trustData()->save();
  1021. }
  1022. }
  1023. /**
  1024. * Implements hook_ENTITY_TYPE_delete() for user_role entities.
  1025. */
  1026. function user_user_role_delete(RoleInterface $role) {
  1027. // Delete role references for all users.
  1028. $user_storage = \Drupal::entityTypeManager()->getStorage('user');
  1029. $user_storage->deleteRoleReferences([$role->id()]);
  1030. // Ignore the authenticated and anonymous roles or the role is being synced.
  1031. if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
  1032. return;
  1033. }
  1034. $actions = Action::loadMultiple([
  1035. 'user_add_role_action.' . $role->id(),
  1036. 'user_remove_role_action.' . $role->id(),
  1037. ]);
  1038. foreach ($actions as $action) {
  1039. $action->delete();
  1040. }
  1041. }
  1042. /**
  1043. * Retrieve an array of roles matching specified conditions.
  1044. *
  1045. * @param bool $membersonly
  1046. * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
  1047. * FALSE.
  1048. * @param string|null $permission
  1049. * (optional) A string containing a permission. If set, only roles
  1050. * containing that permission are returned. Defaults to NULL, which
  1051. * returns all roles.
  1052. *
  1053. * @return \Drupal\user\RoleInterface[]
  1054. * An associative array with the role id as the key and the role object as
  1055. * value.
  1056. */
  1057. function user_roles($membersonly = FALSE, $permission = NULL) {
  1058. $roles = Role::loadMultiple();
  1059. if ($membersonly) {
  1060. unset($roles[RoleInterface::ANONYMOUS_ID]);
  1061. }
  1062. if (!empty($permission)) {
  1063. $roles = array_filter($roles, function ($role) use ($permission) {
  1064. return $role->hasPermission($permission);
  1065. });
  1066. }
  1067. return $roles;
  1068. }
  1069. /**
  1070. * Fetches a user role by role ID.
  1071. *
  1072. * @param string $rid
  1073. * A string representing the role ID.
  1074. *
  1075. * @return \Drupal\user\RoleInterface|null
  1076. * A fully-loaded role object if a role with the given ID exists, or NULL
  1077. * otherwise.
  1078. *
  1079. * @deprecated in drupal:8.0.0 and is removed from drupal:9.0.0.
  1080. * Use \Drupal\user\Entity\Role::load().
  1081. */
  1082. function user_role_load($rid) {
  1083. return Role::load($rid);
  1084. }
  1085. /**
  1086. * Change permissions for a user role.
  1087. *
  1088. * This function may be used to grant and revoke multiple permissions at once.
  1089. * For example, when a form exposes checkboxes to configure permissions for a
  1090. * role, the form submit handler may directly pass the submitted values for the
  1091. * checkboxes form element to this function.
  1092. *
  1093. * @param mixed $rid
  1094. * The ID of a user role to alter.
  1095. * @param array $permissions
  1096. * (optional) An associative array, where the key holds the permission name
  1097. * and the value determines whether to grant or revoke that permission. Any
  1098. * value that evaluates to TRUE will cause the permission to be granted.
  1099. * Any value that evaluates to FALSE will cause the permission to be
  1100. * revoked.
  1101. * @code
  1102. * array(
  1103. * 'administer nodes' => 0, // Revoke 'administer nodes'
  1104. * 'administer blocks' => FALSE, // Revoke 'administer blocks'
  1105. * 'access user profiles' => 1, // Grant 'access user profiles'
  1106. * 'access content' => TRUE, // Grant 'access content'
  1107. * 'access comments' => 'access comments', // Grant 'access comments'
  1108. * )
  1109. * @endcode
  1110. * Existing permissions are not changed, unless specified in $permissions.
  1111. *
  1112. * @see user_role_grant_permissions()
  1113. * @see user_role_revoke_permissions()
  1114. */
  1115. function user_role_change_permissions($rid, array $permissions = []) {
  1116. // Grant new permissions for the role.
  1117. $grant = array_filter($permissions);
  1118. if (!empty($grant)) {
  1119. user_role_grant_permissions($rid, array_keys($grant));
  1120. }
  1121. // Revoke permissions for the role.
  1122. $revoke = array_diff_assoc($permissions, $grant);
  1123. if (!empty($revoke)) {
  1124. user_role_revoke_permissions($rid, array_keys($revoke));
  1125. }
  1126. }
  1127. /**
  1128. * Grant permissions to a user role.
  1129. *
  1130. * @param mixed $rid
  1131. * The ID of a user role to alter.
  1132. * @param array $permissions
  1133. * (optional) A list of permission names to grant.
  1134. *
  1135. * @see user_role_change_permissions()
  1136. * @see user_role_revoke_permissions()
  1137. */
  1138. function user_role_grant_permissions($rid, array $permissions = []) {
  1139. // Grant new permissions for the role.
  1140. if ($role = Role::load($rid)) {
  1141. foreach ($permissions as $permission) {
  1142. $role->grantPermission($permission);
  1143. }
  1144. $role->trustData()->save();
  1145. }
  1146. }
  1147. /**
  1148. * Revoke permissions from a user role.
  1149. *
  1150. * @param mixed $rid
  1151. * The ID of a user role to alter.
  1152. * @param array $permissions
  1153. * (optional) A list of permission names to revoke.
  1154. *
  1155. * @see user_role_change_permissions()
  1156. * @see user_role_grant_permissions()
  1157. */
  1158. function user_role_revoke_permissions($rid, array $permissions = []) {
  1159. // Revoke permissions for the role.
  1160. $role = Role::load($rid);
  1161. foreach ($permissions as $permission) {
  1162. $role->revokePermission($permission);
  1163. }
  1164. $role->trustData()->save();
  1165. }
  1166. /**
  1167. * Conditionally create and send a notification email when a certain
  1168. * operation happens on the given user account.
  1169. *
  1170. * @param string $op
  1171. * The operation being performed on the account. Possible values:
  1172. * - 'register_admin_created': Welcome message for user created by the admin.
  1173. * - 'register_no_approval_required': Welcome message when user
  1174. * self-registers.
  1175. * - 'register_pending_approval': Welcome message, user pending admin
  1176. * approval.
  1177. * - 'password_reset': Password recovery request.
  1178. * - 'status_activated': Account activated.
  1179. * - 'status_blocked': Account blocked.
  1180. * - 'cancel_confirm': Account cancellation request.
  1181. * - 'status_canceled': Account canceled.
  1182. *
  1183. * @param \Drupal\Core\Session\AccountInterface $account
  1184. * The user object of the account being notified. Must contain at
  1185. * least the fields 'uid', 'name', and 'mail'.
  1186. * @param string $langcode
  1187. * (optional) Language code to use for the notification, overriding account
  1188. * language.
  1189. *
  1190. * @return array
  1191. * An array containing various information about the message.
  1192. * See \Drupal\Core\Mail\MailManagerInterface::mail() for details.
  1193. *
  1194. * @see user_mail_tokens()
  1195. */
  1196. function _user_mail_notify($op, AccountInterface $account, $langcode = NULL) {
  1197. if (\Drupal::config('user.settings')->get('notify.' . $op)) {
  1198. $params['account'] = $account;
  1199. $langcode = $langcode ? $langcode : $account->getPreferredLangcode();
  1200. // Get the custom site notification email to use as the from email address
  1201. // if it has been set.
  1202. $site_mail = \Drupal::config('system.site')->get('mail_notification');
  1203. // If the custom site notification email has not been set, we use the site
  1204. // default for this.
  1205. if (empty($site_mail)) {
  1206. $site_mail = \Drupal::config('system.site')->get('mail');
  1207. }
  1208. if (empty($site_mail)) {
  1209. $site_mail = ini_get('sendmail_from');
  1210. }
  1211. $mail = \Drupal::service('plugin.manager.mail')->mail('user', $op, $account->getEmail(), $langcode, $params, $site_mail);
  1212. if ($op == 'register_pending_approval') {
  1213. // If a user registered requiring admin approval, notify the admin, too.
  1214. // We use the site default language for this.
  1215. \Drupal::service('plugin.manager.mail')->mail('user', 'register_pending_approval_admin', $site_mail, \Drupal::languageManager()->getDefaultLanguage()->getId(), $params);
  1216. }
  1217. }
  1218. return empty($mail) ? NULL : $mail['result'];
  1219. }
  1220. /**
  1221. * Implements hook_element_info_alter().
  1222. */
  1223. function user_element_info_alter(array &$types) {
  1224. if (isset($types['password_confirm'])) {
  1225. $types['password_confirm']['#process'][] = 'user_form_process_password_confirm';
  1226. }
  1227. }
  1228. /**
  1229. * Form element process handler for client-side password validation.
  1230. *
  1231. * This #process handler is automatically invoked for 'password_confirm' form
  1232. * elements to add the JavaScript and string translations for dynamic password
  1233. * validation.
  1234. */
  1235. function user_form_process_password_confirm($element) {
  1236. $password_settings = [
  1237. 'confirmTitle' => t('Passwords match:'),
  1238. 'confirmSuccess' => t('yes'),
  1239. 'confirmFailure' => t('no'),
  1240. 'showStrengthIndicator' => FALSE,
  1241. ];
  1242. if (\Drupal::config('user.settings')->get('password_strength')) {
  1243. $password_settings['showStrengthIndicator'] = TRUE;
  1244. $password_settings += [
  1245. 'strengthTitle' => t('Password strength:'),
  1246. 'hasWeaknesses' => t('Recommendations to make your password stronger:'),
  1247. 'tooShort' => t('Make it at least 12 characters'),
  1248. 'addLowerCase' => t('Add lowercase letters'),
  1249. 'addUpperCase' => t('Add uppercase letters'),
  1250. 'addNumbers' => t('Add numbers'),
  1251. 'addPunctuation' => t('Add punctuation'),
  1252. 'sameAsUsername' => t('Make it different from your username'),
  1253. 'weak' => t('Weak'),
  1254. 'fair' => t('Fair'),
  1255. 'good' => t('Good'),
  1256. 'strong' => t('Strong'),
  1257. 'username' => \Drupal::currentUser()->getAccountName(),
  1258. ];
  1259. }
  1260. $element['#attached']['library'][] = 'user/drupal.user';
  1261. $element['#attached']['drupalSettings']['password'] = $password_settings;
  1262. return $element;
  1263. }
  1264. /**
  1265. * Implements hook_modules_uninstalled().
  1266. */
  1267. function user_modules_uninstalled($modules) {
  1268. // Remove any potentially orphan module data stored for users.
  1269. \Drupal::service('user.data')->delete($modules);
  1270. }
  1271. /**
  1272. * Saves visitor information as a cookie so it can be reused.
  1273. *
  1274. * @param array $values
  1275. * An array of key/value pairs to be saved into a cookie.
  1276. */
  1277. function user_cookie_save(array $values) {
  1278. foreach ($values as $field => $value) {
  1279. // Set cookie for 365 days.
  1280. setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  1281. }
  1282. }
  1283. /**
  1284. * Delete a visitor information cookie.
  1285. *
  1286. * @param string $cookie_name
  1287. * A cookie name such as 'homepage'.
  1288. */
  1289. function user_cookie_delete($cookie_name) {
  1290. setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
  1291. }
  1292. /**
  1293. * Implements hook_toolbar().
  1294. */
  1295. function user_toolbar() {
  1296. $user = \Drupal::currentUser();
  1297. $items['user'] = [
  1298. '#type' => 'toolbar_item',
  1299. 'tab' => [
  1300. '#type' => 'link',
  1301. '#title' => $user->getDisplayName(),
  1302. '#url' => Url::fromRoute('user.page'),
  1303. '#attributes' => [
  1304. 'title' => t('My account'),
  1305. 'class' => ['toolbar-icon', 'toolbar-icon-user'],
  1306. ],
  1307. '#cache' => [
  1308. // Vary cache for anonymous and authenticated users.
  1309. 'contexts' => ['user.roles:anonymous'],
  1310. ],
  1311. ],
  1312. 'tray' => [
  1313. '#heading' => t('User account actions'),
  1314. ],
  1315. '#weight' => 100,
  1316. '#attached' => [
  1317. 'library' => [
  1318. 'user/drupal.user.icons',
  1319. ],
  1320. ],
  1321. ];
  1322. if ($user->isAnonymous()) {
  1323. $links = [
  1324. 'login' => [
  1325. 'title' => t('Log in'),
  1326. 'url' => Url::fromRoute('user.page'),
  1327. ],
  1328. ];
  1329. $items['user']['tray']['user_links'] = [
  1330. '#theme' => 'links__toolbar_user',
  1331. '#links' => $links,
  1332. '#attributes' => [
  1333. 'class' => ['toolbar-menu'],
  1334. ],
  1335. ];
  1336. }
  1337. else {
  1338. $items['user']['tab']['#title'] = [
  1339. '#lazy_builder' => ['user.toolbar_link_builder:renderDisplayName', []],
  1340. '#create_placeholder' => TRUE,
  1341. ];
  1342. $items['user']['tray']['user_links'] = [
  1343. '#lazy_builder' => ['user.toolbar_link_builder:renderToolbarLinks', []],
  1344. '#create_placeholder' => TRUE,
  1345. ];
  1346. }
  1347. return $items;
  1348. }
  1349. /**
  1350. * Logs the current user out.
  1351. */
  1352. function user_logout() {
  1353. $user = \Drupal::currentUser();
  1354. \Drupal::logger('user')->notice('Session closed for %name.', ['%name' => $user->getAccountName()]);
  1355. \Drupal::moduleHandler()->invokeAll('user_logout', [$user]);
  1356. // Destroy the current session, and reset $user to the anonymous user.
  1357. // Note: In Symfony the session is intended to be destroyed with
  1358. // Session::invalidate(). Regrettably this method is currently broken and may
  1359. // lead to the creation of spurious session records in the database.
  1360. // @see https://github.com/symfony/symfony/issues/12375
  1361. \Drupal::service('session_manager')->destroy();
  1362. $user->setAccount(new AnonymousUserSession());
  1363. }
  1364. /**
  1365. * Prepares variables for user templates.
  1366. *
  1367. * Default template: user.html.twig.
  1368. *
  1369. * @param array $variables
  1370. * An associative array containing:
  1371. * - elements: An associative array containing the user information and any
  1372. * fields attached to the user. Properties used:
  1373. * - #user: A \Drupal\user\Entity\User object. The user account of the
  1374. * profile being viewed.
  1375. * - attributes: HTML attributes for the containing element.
  1376. */
  1377. function template_preprocess_user(&$variables) {
  1378. $variables['user'] = $variables['elements']['#user'];
  1379. // Helpful $content variable for templates.
  1380. foreach (Element::children($variables['elements']) as $key) {
  1381. $variables['content'][$key] = $variables['elements'][$key];
  1382. }
  1383. }
  1384. /**
  1385. * Implements hook_form_FORM_ID_alter() for \Drupal\system\Form\RegionalForm.
  1386. */
  1387. function user_form_system_regional_settings_alter(&$form, FormStateInterface $form_state) {
  1388. $config = \Drupal::config('system.date');
  1389. $form['timezone']['configurable_timezones'] = [
  1390. '#type' => 'checkbox',
  1391. '#title' => t('Users may set their own time zone'),
  1392. '#default_value' => $config->get('timezone.user.configurable'),
  1393. ];
  1394. $form['timezone']['configurable_timezones_wrapper'] = [
  1395. '#type' => 'container',
  1396. '#states' => [
  1397. // Hide the user configured timezone settings when users are forced to use
  1398. // the default setting.
  1399. 'invisible' => [
  1400. 'input[name="configurable_timezones"]' => ['checked' => FALSE],
  1401. ],
  1402. ],
  1403. ];
  1404. $form['timezone']['configurable_timezones_wrapper']['empty_timezone_message'] = [
  1405. '#type' => 'checkbox',
  1406. '#title' => t('Remind users at login if their time zone is not set'),
  1407. '#default_value' => $config->get('timezone.user.warn'),
  1408. '#description' => t('Only applied if users may set their own time zone.'),
  1409. ];
  1410. $form['timezone']['configurable_timezones_wrapper']['user_default_timezone'] = [
  1411. '#type' => 'radios',
  1412. '#title' => t('Time zone for new users'),
  1413. '#default_value' => $config->get('timezone.user.default'),
  1414. '#options' => [
  1415. UserInterface::TIMEZONE_DEFAULT => t('Default time zone'),
  1416. UserInterface::TIMEZONE_EMPTY => t('Empty time zone'),
  1417. UserInterface::TIMEZONE_SELECT => t('Users may set their own time zone at registration'),
  1418. ],
  1419. '#description' => t('Only applied if users may set their own time zone.'),
  1420. ];
  1421. $form['#submit'][] = 'user_form_system_regional_settings_submit';
  1422. }
  1423. /**
  1424. * Additional submit handler for \Drupal\system\Form\RegionalForm.
  1425. */
  1426. function user_form_system_regional_settings_submit($form, FormStateInterface $form_state) {
  1427. \Drupal::configFactory()->getEditable('system.date')
  1428. ->set('timezone.user.configurable', $form_state->getValue('configurable_timezones'))
  1429. ->set('timezone.user.warn', $form_state->getValue('empty_timezone_message'))
  1430. ->set('timezone.user.default', $form_state->getValue('user_default_timezone'))
  1431. ->save();
  1432. }