user.module 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  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 (mb_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(UserInterface $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(AccountInterface $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::messenger()->addError(t('The user account %id does not exist.', ['%id' => $uid]));
  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::messenger()->addStatus(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::messenger()->addStatus(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\Core\Render\RendererInterface::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
  852. * \Drupal\Core\Render\RendererInterface::render().
  853. */
  854. function user_view_multiple($accounts, $view_mode = 'full', $langcode = NULL) {
  855. return entity_view_multiple($accounts, $view_mode, $langcode);
  856. }
  857. /**
  858. * Implements hook_mail().
  859. */
  860. function user_mail($key, &$message, $params) {
  861. $token_service = \Drupal::token();
  862. $language_manager = \Drupal::languageManager();
  863. $langcode = $message['langcode'];
  864. $variables = ['user' => $params['account']];
  865. $language = $language_manager->getLanguage($params['account']->getPreferredLangcode());
  866. $original_language = $language_manager->getConfigOverrideLanguage();
  867. $language_manager->setConfigOverrideLanguage($language);
  868. $mail_config = \Drupal::config('user.mail');
  869. $token_options = ['langcode' => $langcode, 'callback' => 'user_mail_tokens', 'clear' => TRUE];
  870. $message['subject'] .= PlainTextOutput::renderFromHtml($token_service->replace($mail_config->get($key . '.subject'), $variables, $token_options));
  871. $message['body'][] = $token_service->replace($mail_config->get($key . '.body'), $variables, $token_options);
  872. $language_manager->setConfigOverrideLanguage($original_language);
  873. }
  874. /**
  875. * Token callback to add unsafe tokens for user mails.
  876. *
  877. * This function is used by \Drupal\Core\Utility\Token::replace() to set up
  878. * some additional tokens that can be used in email messages generated by
  879. * user_mail().
  880. *
  881. * @param array $replacements
  882. * An associative array variable containing mappings from token names to
  883. * values (for use with strtr()).
  884. * @param array $data
  885. * An associative array of token replacement values. If the 'user' element
  886. * exists, it must contain a user account object with the following
  887. * properties:
  888. * - login: The UNIX timestamp of the user's last login.
  889. * - pass: The hashed account login password.
  890. * @param array $options
  891. * A keyed array of settings and flags to control the token replacement
  892. * process. See \Drupal\Core\Utility\Token::replace().
  893. */
  894. function user_mail_tokens(&$replacements, $data, $options) {
  895. if (isset($data['user'])) {
  896. $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user'], $options);
  897. $replacements['[user:cancel-url]'] = user_cancel_url($data['user'], $options);
  898. }
  899. }
  900. /*** Administrative features ***********************************************/
  901. /**
  902. * Retrieves the names of roles matching specified conditions.
  903. *
  904. * @param bool $membersonly
  905. * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
  906. * FALSE.
  907. * @param string|null $permission
  908. * (optional) A string containing a permission. If set, only roles
  909. * containing that permission are returned. Defaults to NULL, which
  910. * returns all roles.
  911. *
  912. * @return array
  913. * An associative array with the role id as the key and the role name as
  914. * value.
  915. */
  916. function user_role_names($membersonly = FALSE, $permission = NULL) {
  917. return array_map(function ($item) {
  918. return $item->label();
  919. }, user_roles($membersonly, $permission));
  920. }
  921. /**
  922. * Implements hook_ENTITY_TYPE_insert() for user_role entities.
  923. */
  924. function user_user_role_insert(RoleInterface $role) {
  925. // Ignore the authenticated and anonymous roles or the role is being synced.
  926. if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
  927. return;
  928. }
  929. $add_id = 'user_add_role_action.' . $role->id();
  930. if (!Action::load($add_id)) {
  931. $action = Action::create([
  932. 'id' => $add_id,
  933. 'type' => 'user',
  934. 'label' => t('Add the @label role to the selected user(s)', ['@label' => $role->label()]),
  935. 'configuration' => [
  936. 'rid' => $role->id(),
  937. ],
  938. 'plugin' => 'user_add_role_action',
  939. ]);
  940. $action->trustData()->save();
  941. }
  942. $remove_id = 'user_remove_role_action.' . $role->id();
  943. if (!Action::load($remove_id)) {
  944. $action = Action::create([
  945. 'id' => $remove_id,
  946. 'type' => 'user',
  947. 'label' => t('Remove the @label role from the selected user(s)', ['@label' => $role->label()]),
  948. 'configuration' => [
  949. 'rid' => $role->id(),
  950. ],
  951. 'plugin' => 'user_remove_role_action',
  952. ]);
  953. $action->trustData()->save();
  954. }
  955. }
  956. /**
  957. * Implements hook_ENTITY_TYPE_delete() for user_role entities.
  958. */
  959. function user_user_role_delete(RoleInterface $role) {
  960. // Delete role references for all users.
  961. $user_storage = \Drupal::entityManager()->getStorage('user');
  962. $user_storage->deleteRoleReferences([$role->id()]);
  963. // Ignore the authenticated and anonymous roles or the role is being synced.
  964. if (in_array($role->id(), [RoleInterface::AUTHENTICATED_ID, RoleInterface::ANONYMOUS_ID]) || $role->isSyncing()) {
  965. return;
  966. }
  967. $actions = Action::loadMultiple([
  968. 'user_add_role_action.' . $role->id(),
  969. 'user_remove_role_action.' . $role->id(),
  970. ]);
  971. foreach ($actions as $action) {
  972. $action->delete();
  973. }
  974. }
  975. /**
  976. * Retrieve an array of roles matching specified conditions.
  977. *
  978. * @param bool $membersonly
  979. * (optional) Set this to TRUE to exclude the 'anonymous' role. Defaults to
  980. * FALSE.
  981. * @param string|null $permission
  982. * (optional) A string containing a permission. If set, only roles
  983. * containing that permission are returned. Defaults to NULL, which
  984. * returns all roles.
  985. *
  986. * @return \Drupal\user\RoleInterface[]
  987. * An associative array with the role id as the key and the role object as
  988. * value.
  989. */
  990. function user_roles($membersonly = FALSE, $permission = NULL) {
  991. $roles = Role::loadMultiple();
  992. if ($membersonly) {
  993. unset($roles[RoleInterface::ANONYMOUS_ID]);
  994. }
  995. if (!empty($permission)) {
  996. $roles = array_filter($roles, function ($role) use ($permission) {
  997. return $role->hasPermission($permission);
  998. });
  999. }
  1000. return $roles;
  1001. }
  1002. /**
  1003. * Fetches a user role by role ID.
  1004. *
  1005. * @param string $rid
  1006. * A string representing the role ID.
  1007. *
  1008. * @return \Drupal\user\RoleInterface|null
  1009. * A fully-loaded role object if a role with the given ID exists, or NULL
  1010. * otherwise.
  1011. *
  1012. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  1013. * Use \Drupal\user\Entity\Role::load().
  1014. */
  1015. function user_role_load($rid) {
  1016. return Role::load($rid);
  1017. }
  1018. /**
  1019. * Change permissions for a user role.
  1020. *
  1021. * This function may be used to grant and revoke multiple permissions at once.
  1022. * For example, when a form exposes checkboxes to configure permissions for a
  1023. * role, the form submit handler may directly pass the submitted values for the
  1024. * checkboxes form element to this function.
  1025. *
  1026. * @param mixed $rid
  1027. * The ID of a user role to alter.
  1028. * @param array $permissions
  1029. * (optional) An associative array, where the key holds the permission name
  1030. * and the value determines whether to grant or revoke that permission. Any
  1031. * value that evaluates to TRUE will cause the permission to be granted.
  1032. * Any value that evaluates to FALSE will cause the permission to be
  1033. * revoked.
  1034. * @code
  1035. * array(
  1036. * 'administer nodes' => 0, // Revoke 'administer nodes'
  1037. * 'administer blocks' => FALSE, // Revoke 'administer blocks'
  1038. * 'access user profiles' => 1, // Grant 'access user profiles'
  1039. * 'access content' => TRUE, // Grant 'access content'
  1040. * 'access comments' => 'access comments', // Grant 'access comments'
  1041. * )
  1042. * @endcode
  1043. * Existing permissions are not changed, unless specified in $permissions.
  1044. *
  1045. * @see user_role_grant_permissions()
  1046. * @see user_role_revoke_permissions()
  1047. */
  1048. function user_role_change_permissions($rid, array $permissions = []) {
  1049. // Grant new permissions for the role.
  1050. $grant = array_filter($permissions);
  1051. if (!empty($grant)) {
  1052. user_role_grant_permissions($rid, array_keys($grant));
  1053. }
  1054. // Revoke permissions for the role.
  1055. $revoke = array_diff_assoc($permissions, $grant);
  1056. if (!empty($revoke)) {
  1057. user_role_revoke_permissions($rid, array_keys($revoke));
  1058. }
  1059. }
  1060. /**
  1061. * Grant permissions to a user role.
  1062. *
  1063. * @param mixed $rid
  1064. * The ID of a user role to alter.
  1065. * @param array $permissions
  1066. * (optional) A list of permission names to grant.
  1067. *
  1068. * @see user_role_change_permissions()
  1069. * @see user_role_revoke_permissions()
  1070. */
  1071. function user_role_grant_permissions($rid, array $permissions = []) {
  1072. // Grant new permissions for the role.
  1073. if ($role = Role::load($rid)) {
  1074. foreach ($permissions as $permission) {
  1075. $role->grantPermission($permission);
  1076. }
  1077. $role->trustData()->save();
  1078. }
  1079. }
  1080. /**
  1081. * Revoke permissions from a user role.
  1082. *
  1083. * @param mixed $rid
  1084. * The ID of a user role to alter.
  1085. * @param array $permissions
  1086. * (optional) A list of permission names to revoke.
  1087. *
  1088. * @see user_role_change_permissions()
  1089. * @see user_role_grant_permissions()
  1090. */
  1091. function user_role_revoke_permissions($rid, array $permissions = []) {
  1092. // Revoke permissions for the role.
  1093. $role = Role::load($rid);
  1094. foreach ($permissions as $permission) {
  1095. $role->revokePermission($permission);
  1096. }
  1097. $role->trustData()->save();
  1098. }
  1099. /**
  1100. * Conditionally create and send a notification email when a certain
  1101. * operation happens on the given user account.
  1102. *
  1103. * @param string $op
  1104. * The operation being performed on the account. Possible values:
  1105. * - 'register_admin_created': Welcome message for user created by the admin.
  1106. * - 'register_no_approval_required': Welcome message when user
  1107. * self-registers.
  1108. * - 'register_pending_approval': Welcome message, user pending admin
  1109. * approval.
  1110. * - 'password_reset': Password recovery request.
  1111. * - 'status_activated': Account activated.
  1112. * - 'status_blocked': Account blocked.
  1113. * - 'cancel_confirm': Account cancellation request.
  1114. * - 'status_canceled': Account canceled.
  1115. *
  1116. * @param \Drupal\Core\Session\AccountInterface $account
  1117. * The user object of the account being notified. Must contain at
  1118. * least the fields 'uid', 'name', and 'mail'.
  1119. * @param string $langcode
  1120. * (optional) Language code to use for the notification, overriding account
  1121. * language.
  1122. *
  1123. * @return array
  1124. * An array containing various information about the message.
  1125. * See \Drupal\Core\Mail\MailManagerInterface::mail() for details.
  1126. *
  1127. * @see user_mail_tokens()
  1128. */
  1129. function _user_mail_notify($op, $account, $langcode = NULL) {
  1130. if (\Drupal::config('user.settings')->get('notify.' . $op)) {
  1131. $params['account'] = $account;
  1132. $langcode = $langcode ? $langcode : $account->getPreferredLangcode();
  1133. // Get the custom site notification email to use as the from email address
  1134. // if it has been set.
  1135. $site_mail = \Drupal::config('system.site')->get('mail_notification');
  1136. // If the custom site notification email has not been set, we use the site
  1137. // default for this.
  1138. if (empty($site_mail)) {
  1139. $site_mail = \Drupal::config('system.site')->get('mail');
  1140. }
  1141. if (empty($site_mail)) {
  1142. $site_mail = ini_get('sendmail_from');
  1143. }
  1144. $mail = \Drupal::service('plugin.manager.mail')->mail('user', $op, $account->getEmail(), $langcode, $params, $site_mail);
  1145. if ($op == 'register_pending_approval') {
  1146. // If a user registered requiring admin approval, notify the admin, too.
  1147. // We use the site default language for this.
  1148. \Drupal::service('plugin.manager.mail')->mail('user', 'register_pending_approval_admin', $site_mail, \Drupal::languageManager()->getDefaultLanguage()->getId(), $params);
  1149. }
  1150. }
  1151. return empty($mail) ? NULL : $mail['result'];
  1152. }
  1153. /**
  1154. * Implements hook_element_info_alter().
  1155. */
  1156. function user_element_info_alter(array &$types) {
  1157. if (isset($types['password_confirm'])) {
  1158. $types['password_confirm']['#process'][] = 'user_form_process_password_confirm';
  1159. }
  1160. }
  1161. /**
  1162. * Form element process handler for client-side password validation.
  1163. *
  1164. * This #process handler is automatically invoked for 'password_confirm' form
  1165. * elements to add the JavaScript and string translations for dynamic password
  1166. * validation.
  1167. */
  1168. function user_form_process_password_confirm($element) {
  1169. $password_settings = [
  1170. 'confirmTitle' => t('Passwords match:'),
  1171. 'confirmSuccess' => t('yes'),
  1172. 'confirmFailure' => t('no'),
  1173. 'showStrengthIndicator' => FALSE,
  1174. ];
  1175. if (\Drupal::config('user.settings')->get('password_strength')) {
  1176. $password_settings['showStrengthIndicator'] = TRUE;
  1177. $password_settings += [
  1178. 'strengthTitle' => t('Password strength:'),
  1179. 'hasWeaknesses' => t('Recommendations to make your password stronger:'),
  1180. 'tooShort' => t('Make it at least 12 characters'),
  1181. 'addLowerCase' => t('Add lowercase letters'),
  1182. 'addUpperCase' => t('Add uppercase letters'),
  1183. 'addNumbers' => t('Add numbers'),
  1184. 'addPunctuation' => t('Add punctuation'),
  1185. 'sameAsUsername' => t('Make it different from your username'),
  1186. 'weak' => t('Weak'),
  1187. 'fair' => t('Fair'),
  1188. 'good' => t('Good'),
  1189. 'strong' => t('Strong'),
  1190. 'username' => \Drupal::currentUser()->getUsername(),
  1191. ];
  1192. }
  1193. $element['#attached']['library'][] = 'user/drupal.user';
  1194. $element['#attached']['drupalSettings']['password'] = $password_settings;
  1195. return $element;
  1196. }
  1197. /**
  1198. * Implements hook_modules_uninstalled().
  1199. */
  1200. function user_modules_uninstalled($modules) {
  1201. // Remove any potentially orphan module data stored for users.
  1202. \Drupal::service('user.data')->delete($modules);
  1203. }
  1204. /**
  1205. * Saves visitor information as a cookie so it can be reused.
  1206. *
  1207. * @param array $values
  1208. * An array of key/value pairs to be saved into a cookie.
  1209. */
  1210. function user_cookie_save(array $values) {
  1211. foreach ($values as $field => $value) {
  1212. // Set cookie for 365 days.
  1213. setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  1214. }
  1215. }
  1216. /**
  1217. * Delete a visitor information cookie.
  1218. *
  1219. * @param string $cookie_name
  1220. * A cookie name such as 'homepage'.
  1221. */
  1222. function user_cookie_delete($cookie_name) {
  1223. setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
  1224. }
  1225. /**
  1226. * Implements hook_toolbar().
  1227. */
  1228. function user_toolbar() {
  1229. $user = \Drupal::currentUser();
  1230. $items['user'] = [
  1231. '#type' => 'toolbar_item',
  1232. 'tab' => [
  1233. '#type' => 'link',
  1234. '#title' => $user->getDisplayName(),
  1235. '#url' => Url::fromRoute('user.page'),
  1236. '#attributes' => [
  1237. 'title' => t('My account'),
  1238. 'class' => ['toolbar-icon', 'toolbar-icon-user'],
  1239. ],
  1240. '#cache' => [
  1241. // Vary cache for anonymous and authenticated users.
  1242. 'contexts' => ['user.roles:anonymous'],
  1243. ],
  1244. ],
  1245. 'tray' => [
  1246. '#heading' => t('User account actions'),
  1247. ],
  1248. '#weight' => 100,
  1249. '#attached' => [
  1250. 'library' => [
  1251. 'user/drupal.user.icons',
  1252. ],
  1253. ],
  1254. ];
  1255. if ($user->isAnonymous()) {
  1256. $links = [
  1257. 'login' => [
  1258. 'title' => t('Log in'),
  1259. 'url' => Url::fromRoute('user.page'),
  1260. ],
  1261. ];
  1262. $items['user']['tray']['user_links'] = [
  1263. '#theme' => 'links__toolbar_user',
  1264. '#links' => $links,
  1265. '#attributes' => [
  1266. 'class' => ['toolbar-menu'],
  1267. ],
  1268. ];
  1269. }
  1270. else {
  1271. $items['user']['tab']['#title'] = [
  1272. '#lazy_builder' => ['user.toolbar_link_builder:renderDisplayName', []],
  1273. '#create_placeholder' => TRUE,
  1274. ];
  1275. $items['user']['tray']['user_links'] = [
  1276. '#lazy_builder' => ['user.toolbar_link_builder:renderToolbarLinks', []],
  1277. '#create_placeholder' => TRUE,
  1278. ];
  1279. }
  1280. return $items;
  1281. }
  1282. /**
  1283. * Logs the current user out.
  1284. */
  1285. function user_logout() {
  1286. $user = \Drupal::currentUser();
  1287. \Drupal::logger('user')->notice('Session closed for %name.', ['%name' => $user->getAccountName()]);
  1288. \Drupal::moduleHandler()->invokeAll('user_logout', [$user]);
  1289. // Destroy the current session, and reset $user to the anonymous user.
  1290. // Note: In Symfony the session is intended to be destroyed with
  1291. // Session::invalidate(). Regrettably this method is currently broken and may
  1292. // lead to the creation of spurious session records in the database.
  1293. // @see https://github.com/symfony/symfony/issues/12375
  1294. \Drupal::service('session_manager')->destroy();
  1295. $user->setAccount(new AnonymousUserSession());
  1296. }
  1297. /**
  1298. * Prepares variables for user templates.
  1299. *
  1300. * Default template: user.html.twig.
  1301. *
  1302. * @param array $variables
  1303. * An associative array containing:
  1304. * - elements: An associative array containing the user information and any
  1305. * fields attached to the user. Properties used:
  1306. * - #user: A \Drupal\user\Entity\User object. The user account of the
  1307. * profile being viewed.
  1308. * - attributes: HTML attributes for the containing element.
  1309. */
  1310. function template_preprocess_user(&$variables) {
  1311. $variables['user'] = $variables['elements']['#user'];
  1312. // Helpful $content variable for templates.
  1313. foreach (Element::children($variables['elements']) as $key) {
  1314. $variables['content'][$key] = $variables['elements'][$key];
  1315. }
  1316. }