user.module 51 KB

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