user.module 51 KB

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