Drupal investigation

profile.module 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. /**
  3. * @file
  4. * Support for configurable user profiles.
  5. */
  6. use Drupal\Core\Access\AccessResult;
  7. use Drupal\Core\Field\FieldDefinitionInterface;
  8. use Drupal\Core\Field\FieldItemListInterface;
  9. use Drupal\Core\Render\Element;
  10. use Drupal\Core\Session\AccountInterface;
  11. use Drupal\user\UserInterface;
  12. use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
  13. use Drupal\Core\Entity\Entity\EntityFormDisplay;
  14. use Drupal\Core\Entity\EntityInterface;
  15. use Drupal\profile\Entity\Profile;
  16. use Drupal\profile\Entity\ProfileType;
  17. use Drupal\field\FieldConfigInterface;
  18. use Drupal\Core\Routing\RouteMatchInterface;
  19. use Drupal\Core\Form\FormStateInterface;
  20. use Drupal\Core\Url;
  21. /**
  22. * Implements hook_help().
  23. */
  24. function profile_help($route_name, RouteMatchInterface $route_match) {
  25. switch ($route_name) {
  26. case 'help.page.profile':
  27. $output = '<h3>' . t('About') . '</h3>';
  28. $output .= '<p>' . t('The Profile module provides a fieldable entity, that allows administrators to define different sets of fields for user profiles, which are then displayed in the <a href="@user">My Account</a> section. This permits users of a site to share more information about themselves, and can help community-based sites organize users around specific information.', ['@user' => Url::fromRoute('user.page')->toString()]) . '</p>';
  29. $output .= '<dl>';
  30. $output .= '<dt>' . t('Types of profiles') . '</dt>';
  31. $output .= '<dd>' . t('Profile types provide a way of grouping similar data for user profiles e.g. Personal information, Work etc. A default "Personal information type is provided. You may create more types and manage fields for each type from the <a href="@profile-types">Profile types</a> admin page. When creating a new profile type, you will be able to specify whether a user may create multiple profiles or make the profile form available when registering a new user.', ['@profile-types' => Url::fromRoute('entity.profile_type.collection')->toString()]) . '</dd>';
  32. $output .= '<dt>' . t('Creating profiles') . '</dt>';
  33. $output .= '<dd>' . t('A user will see tabs they have access to, when editing their main user account e.g. "Add personal information profile". The visibility of a tab depends on whether they can create multiple profiles or if they haven\'t created a profile of the type that doesn\'t allow multiple instances.') . '</dd>';
  34. $output .= '</dl>';
  35. return $output;
  36. }
  37. }
  38. /**
  39. * Implements hook_entity_field_access().
  40. */
  41. function profile_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  42. if ($operation == 'view' && $items && $field_definition->getTargetEntityTypeId() == 'profile') {
  43. if ($field_definition instanceof FieldConfigInterface) {
  44. $is_private = $field_definition->getThirdPartySetting('profile', 'profile_private', FALSE);
  45. if ($is_private) {
  46. // Users may see their own private profile fields by default, so this
  47. // requires user granularity for caching.
  48. /** @var \Drupal\profile\Entity\ProfileInterface $profile */
  49. $profile = $items->getEntity();
  50. if ($account->id() === $profile->getOwnerId()) {
  51. return AccessResult::neutral();
  52. }
  53. return AccessResult::forbiddenIf(!$account->hasPermission('administer profile'));
  54. }
  55. }
  56. }
  57. return AccessResult::neutral();
  58. }
  59. /**
  60. * Implements hook_theme().
  61. */
  62. function profile_theme() {
  63. return [
  64. 'profile' => [
  65. 'render element' => 'elements',
  66. ],
  67. ];
  68. }
  69. /**
  70. * Prepares variables for profile templates.
  71. *
  72. * Default template: profile.html.twig.
  73. *
  74. * @param array $variables
  75. * An associative array containing:
  76. * - elements: An associative array containing rendered fields.
  77. * - attributes: HTML attributes for the containing element.
  78. */
  79. function template_preprocess_profile(array &$variables) {
  80. /** @var Drupal\profile\Entity\ProfileInterface $profile */
  81. $profile = $variables['elements']['#profile'];
  82. $variables['profile'] = $profile;
  83. $variables['url'] = $profile->toUrl();
  84. // Helpful $content variable for templates.
  85. $variables['content'] = [];
  86. foreach (Element::children($variables['elements']) as $key) {
  87. $variables['content'][$key] = $variables['elements'][$key];
  88. }
  89. }
  90. /**
  91. * Implements hook_user_view().
  92. */
  93. function profile_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display, $view_mode) {
  94. // Iterate through each bundle and see if it's component exists.
  95. foreach (ProfileType::loadMultiple() as $bundle) {
  96. $component_key = 'profile_' . $bundle->id();
  97. if ($display->getComponent($component_key)) {
  98. // Embed the view of active profiles for profile type.
  99. $build[$component_key] = [
  100. '#type' => 'view',
  101. '#name' => 'profiles',
  102. '#display_id' => 'user_view',
  103. '#arguments' => [$account->id(), $bundle->id(), 1],
  104. '#embed' => TRUE,
  105. '#title' => $bundle->label(),
  106. '#pre_render' => [
  107. ['\Drupal\views\Element\View', 'preRenderViewElement'],
  108. 'profile_views_add_title_pre_render',
  109. ],
  110. ];
  111. }
  112. }
  113. }
  114. /**
  115. * Implements hook_entity_extra_field_info().
  116. */
  117. function profile_entity_extra_field_info() {
  118. $extra = [];
  119. // Add each profile type as an extra field for display. Not enabled by default
  120. // as many sites will not need this and it otherwise also gets added
  121. // automatically to other view modes.
  122. /** @var \Drupal\profile\Entity\ProfileType $bundle */
  123. foreach (ProfileType::loadMultiple() as $bundle) {
  124. $extra['user']['user']['display']['profile_' . $bundle->id()] = array(
  125. 'label' => $bundle->label(),
  126. 'description' => t('Display @type profiles', ['@type' => $bundle->label()]),
  127. 'weight' => 10,
  128. 'visible' => FALSE,
  129. );
  130. }
  131. return $extra;
  132. }
  133. /**
  134. * Implements hook_user_delete().
  135. */
  136. function profile_user_delete(EntityInterface $entity) {
  137. $list = \Drupal::entityTypeManager()
  138. ->getStorage('profile')
  139. ->loadByProperties([
  140. 'uid' => $entity->id(),
  141. ]);
  142. foreach ($list as $profile) {
  143. $profile->delete();
  144. }
  145. }
  146. /**
  147. * Implements hook_form_FORM_ID_alter().
  148. */
  149. function profile_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  150. $field = $form_state->getFormObject()->getEntity();
  151. if ($field->getTargetEntityTypeId() != 'profile') {
  152. return;
  153. }
  154. $form['field']['profile']['profile_private'] = [
  155. '#type' => 'checkbox',
  156. '#title' => t('This is a private field.'),
  157. '#default_value' => $field->getThirdPartySetting('profile', 'profile_private', FALSE),
  158. ];
  159. $form['actions']['submit']['#submit'][] = 'profile_form_field_config_edit_form_submit';
  160. }
  161. /**
  162. * Form submission handler for profile_form_field_config_edit_form_alter.
  163. *
  164. * @param array $form
  165. * The form array.
  166. * @param FormStateInterface $form_state
  167. * The form state.
  168. */
  169. function profile_form_field_config_edit_form_submit(array $form, FormStateInterface $form_state) {
  170. $field = $form_state->getFormObject()->getEntity();
  171. $form_fields = &$form_state->getValues();
  172. // If the private option is checked, update settings.
  173. if ($form_fields['profile_private']) {
  174. $field->setThirdPartySetting('profile', 'profile_private', TRUE);
  175. $field->save();
  176. }
  177. else {
  178. $field->unsetThirdPartySetting('profile', 'profile_private');
  179. $field->save();
  180. }
  181. }
  182. /**
  183. * Implements hook_form_FORM_ID_alter().
  184. *
  185. * Add available profile forms to the user registration form.
  186. */
  187. function profile_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  188. $attached_profile_form = FALSE;
  189. $weight = 90;
  190. /** @var ProfileType[] $profile_types */
  191. $profile_types = ProfileType::loadMultiple();
  192. foreach ($profile_types as $profile_type) {
  193. $instances = array_filter(\Drupal::service('entity_field.manager')->getFieldDefinitions('profile', $profile_type->id()), function ($field_definition) {
  194. return $field_definition instanceof FieldConfigInterface;
  195. });
  196. if ($profile_type->getRegistration() === TRUE && count($instances)) {
  197. $property = ['profiles', $profile_type->id()];
  198. $profile = $form_state->get($property);
  199. if (empty($profile)) {
  200. $profile = Profile::create([
  201. 'type' => $profile_type->id(),
  202. 'langcode' => $profile_type->language() ?
  203. $profile_type->language() : \Drupal::languageManager()->getDefaultLanguage()->getId(),
  204. ]);
  205. // Attach profile entity form.
  206. $form_state->set($property, $profile);
  207. }
  208. $form_state->set('form_display_' . $profile_type->id(), EntityFormDisplay::collectRenderDisplay($profile, 'default'));
  209. $form['entity_' . $profile_type->id()] = [
  210. '#type' => 'details',
  211. '#title' => $profile_type->label(),
  212. '#tree' => TRUE,
  213. '#parents' => ['entity_' . $profile_type->id()],
  214. '#weight' => ++$weight,
  215. '#open' => TRUE,
  216. ];
  217. $form_state
  218. ->get('form_display_' . $profile_type->id())
  219. ->buildForm($profile, $form['entity_' . $profile_type->id()], $form_state);
  220. $attached_profile_form = TRUE;
  221. }
  222. }
  223. if ($attached_profile_form) {
  224. $form['actions']['submit']['#validate'][] = 'profile_form_user_register_form_validate';
  225. $form['actions']['submit']['#submit'][] = 'profile_form_user_register_form_submit';
  226. }
  227. }
  228. /**
  229. * Extra form validation handler for the user registration form.
  230. */
  231. function profile_form_user_register_form_validate(array &$form, FormStateInterface $form_state) {
  232. $profiles = $form_state->get('profiles');
  233. if (!empty($profiles)) {
  234. foreach ($profiles as $bundle => $entity) {
  235. /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
  236. $form_display = $form_state->get('form_display_' . $bundle);
  237. if (isset($form['entity_' . $bundle])) {
  238. $form_display->extractFormValues($entity, $form['entity_' . $bundle], $form_state);
  239. $form_display->validateFormValues($entity, $form['entity_' . $bundle], $form_state);
  240. }
  241. }
  242. }
  243. // Entity was validated in entityFormValidate(). This will prevent validation
  244. // exception from being thrown.
  245. $form_state->getFormObject()->validateForm($form, $form_state);
  246. }
  247. /**
  248. * Extra form submission handler for the user registration form.
  249. */
  250. function profile_form_user_register_form_submit(array &$form, FormStateInterface $form_state) {
  251. /** @var \Drupal\Core\Session\AccountInterface $account */
  252. $account = $form_state->getFormObject()->getEntity();
  253. $profiles = $form_state->get('profiles');
  254. if (!empty($profiles)) {
  255. foreach ($profiles as $bundle => $entity) {
  256. $entity->setOwnerId($account->id());
  257. $entity->setActive(TRUE);
  258. $entity->save();
  259. }
  260. }
  261. }
  262. /**
  263. * Pre render callback for profile embedded views to ensure a title is set.
  264. * @param $element
  265. *
  266. * @return mixed
  267. */
  268. function profile_views_add_title_pre_render($element) {
  269. /** @var \Drupal\views\ViewExecutable $view */
  270. if (isset($element['#title'])) {
  271. $view = $element['view_build']['#view'];
  272. $view->setTitle($element['#title']);
  273. }
  274. return $element;
  275. }
  276. /**
  277. * Implements hook_preprocess_HOOK().
  278. */
  279. function profile_preprocess_views_view(&$variables) {
  280. // We have to manually add back the title since it was removed by Views.
  281. // @see template_preprocess_views_view()
  282. /** @var \Drupal\views\ViewExecutable $view */
  283. $view = $variables['view'];
  284. if ($view->storage->id() == 'profiles' && !empty($view->result)) {
  285. // Test access to the profile.
  286. /** @var \Drupal\profile\Entity\profile $entity */
  287. $entity = reset($view->result)->_entity;
  288. if ($entity->access('view')) {
  289. $variables['title'] = $view->getTitle();
  290. }
  291. }
  292. }
  293. /**
  294. * Implements hook_views_data_alter().
  295. *
  296. * Adds a relationship from the user table to its' profile entity.
  297. */
  298. function profile_views_data_alter(&$data) {
  299. $data['users_field_data']['profile']['relationship'] = [
  300. 'title' => t('Profile'),
  301. 'label' => t('Profile'),
  302. 'group' => 'User',
  303. 'help' => t('Reference to the profile of a user.'),
  304. 'id' => 'standard',
  305. 'base' => 'profile',
  306. 'base field' => 'uid',
  307. 'field' => 'uid',
  308. ];
  309. }
  310. /**
  311. * Implements hook_theme_suggestions_HOOK().
  312. */
  313. function profile_theme_suggestions_profile(array $variables) {
  314. $original = $variables['theme_hook_original'];
  315. $entity = $variables['elements']['#profile'];
  316. $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  317. $suggestions = [];
  318. $suggestions[] = $original;
  319. $suggestions[] = $original . '__' . $sanitized_view_mode;
  320. $suggestions[] = $original . '__' . $entity->bundle();
  321. $suggestions[] = $original . '__' . $entity->bundle() . '__' . $sanitized_view_mode;
  322. $suggestions[] = $original . '__' . $entity->id();
  323. $suggestions[] = $original . '__' . $entity->id() . '__' . $sanitized_view_mode;
  324. return $suggestions;
  325. }