user.module 57 KB

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