domain_source.module 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. <?php
  2. /**
  3. * @file
  4. * Domain-based path rewrites for content.
  5. */
  6. use Drupal\Core\Entity\EntityInterface;
  7. use Drupal\Core\Routing\TrustedRedirectResponse;
  8. use Drupal\Core\Form\FormStateInterface;
  9. use Drupal\domain\DomainRedirectResponse;
  10. /**
  11. * Defines the name of the source domain field.
  12. */
  13. const DOMAIN_SOURCE_FIELD = 'field_domain_source';
  14. /**
  15. * Creates our fields for an entity bundle.
  16. *
  17. * @param string $entity_type
  18. * The entity type being created. Node and user are supported.
  19. * @param string $bundle
  20. * The bundle being created.
  21. *
  22. * @see domain_source_node_type_insert()
  23. * @see domain_source_install()
  24. */
  25. function domain_source_confirm_fields($entity_type, $bundle) {
  26. $id = $entity_type . '.' . $bundle . '.' . DOMAIN_SOURCE_FIELD;
  27. $field_config_storage = \Drupal::entityTypeManager()->getStorage('field_config');
  28. if (!$field = $field_config_storage->load($id)) {
  29. $field = [
  30. 'field_name' => DOMAIN_SOURCE_FIELD,
  31. 'entity_type' => $entity_type,
  32. 'label' => 'Domain Source',
  33. 'bundle' => $bundle,
  34. 'required' => FALSE,
  35. 'description' => 'Select the canonical domain for this content.',
  36. 'settings' => [
  37. 'handler' => 'default:domain',
  38. // Handler_settings are deprecated but seem to be necessary here.
  39. 'handler_settings' => [
  40. 'target_bundles' => NULL,
  41. 'sort' => ['field' => 'weight', 'direction' => 'ASC'],
  42. ],
  43. 'target_bundles' => NULL,
  44. 'sort' => ['field' => 'weight', 'direction' => 'ASC'],
  45. ],
  46. ];
  47. $field_config = $field_config_storage->create($field);
  48. $field_config->save();
  49. }
  50. // Tell the form system how to behave. Default to radio buttons.
  51. $display = \Drupal::entityTypeManager()
  52. ->getStorage('entity_form_display')
  53. ->load($entity_type . '.' . $bundle . '.default');
  54. if ($display) {
  55. $display->setComponent(DOMAIN_SOURCE_FIELD, [
  56. 'type' => 'options_select',
  57. 'weight' => 42,
  58. ])->save();
  59. }
  60. }
  61. /**
  62. * Implements hook_ENTITY_TYPE_insert().
  63. *
  64. * Creates our fields when new node types are created.
  65. *
  66. * @TODO: Make this possible for all entity types.
  67. */
  68. function domain_source_node_type_insert(EntityInterface $entity) {
  69. /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */
  70. if (!$entity->isSyncing()) {
  71. // Do not fire hook when config sync in progress.
  72. domain_source_confirm_fields('node', $entity->id());
  73. }
  74. }
  75. /**
  76. * Implements hook_ENTITY_TYPE_insert().
  77. *
  78. * In some cases, form display modes are not set when the node type is created.
  79. * be sure to update our field definitions on creation of form_display for
  80. * node types.
  81. */
  82. function domain_source_entity_form_display_insert(EntityInterface $entity) {
  83. if (!$entity->isSyncing() && $entity->getTargetEntityTypeId() == 'node' && $bundle = $entity->getTargetBundle()) {
  84. domain_source_confirm_fields('node', $bundle);
  85. }
  86. }
  87. /**
  88. * Returns the source domain associated to an entity.
  89. *
  90. * @param Drupal\Core\Entity\EntityInterface $entity
  91. * The entity to check.
  92. *
  93. * @return string|null
  94. * The value assigned to the entity, either a domain id string or NULL.
  95. */
  96. function domain_source_get(EntityInterface $entity) {
  97. $source = NULL;
  98. if (!isset($entity->{DOMAIN_SOURCE_FIELD})) {
  99. return $source;
  100. }
  101. $value = $entity->get(DOMAIN_SOURCE_FIELD)->offsetGet(0);
  102. if (!empty($value)) {
  103. $target_id = $value->target_id;
  104. if ($domain = \Drupal::entityTypeManager()->getStorage('domain')->load($target_id)) {
  105. $source = $domain->id();
  106. }
  107. }
  108. return $source;
  109. }
  110. /**
  111. * Implements hook_form_alter().
  112. *
  113. * Find forms that contain the domain source field and allow those to handle
  114. * redirects properly.
  115. */
  116. function domain_source_form_alter(&$form, &$form_state, $form_id) {
  117. $object = $form_state->getFormObject();
  118. // Set up our TrustedRedirect handler for form saves.
  119. if (isset($form[DOMAIN_SOURCE_FIELD]) && !empty($object) && is_callable([$object, 'getEntity']) && $entity = $object->getEntity()) {
  120. foreach ($form['actions'] as $key => $element) {
  121. // Redirect submit handlers, but not the preview button.
  122. if ($key != 'preview' && isset($element['#type']) && $element['#type'] == 'submit') {
  123. $form['actions'][$key]['#submit'][] = 'domain_source_form_submit';
  124. }
  125. }
  126. }
  127. }
  128. /**
  129. * Validate form submissions.
  130. */
  131. function domain_source_form_validate($element, FormStateInterface $form_state) {
  132. $values = $form_state->getValues();
  133. // This is only run if Domain Access is present.
  134. if (isset($values[DOMAIN_SOURCE_FIELD]) && is_array($values[DOMAIN_SOURCE_FIELD]) && isset($values[DOMAIN_ACCESS_FIELD])) {
  135. $access_values = $values[DOMAIN_ACCESS_FIELD];
  136. $source_value = current($values[DOMAIN_SOURCE_FIELD]);
  137. }
  138. // If no value is selected, that's acceptable. Else run through a check.
  139. // Note that the _none selection returns as [FALSE].
  140. $source_set = empty($source_value);
  141. foreach ($access_values as $value) {
  142. // Core is inconsistent depending on the field order.
  143. // See https://www.drupal.org/project/domain/issues/2945771#comment-12493199
  144. if (is_array($value) && $value == $source_value) {
  145. $source_set = TRUE;
  146. }
  147. elseif (is_string($value) && !empty($source_value['target_id']) && $value == $source_value['target_id']) {
  148. $source_set = TRUE;
  149. }
  150. }
  151. if (!$source_set) {
  152. $form_state->setError($element, t('The source domain must be selected as a publishing option.'));
  153. }
  154. }
  155. /**
  156. * Redirect form submissions to other domains.
  157. */
  158. function domain_source_form_submit(&$form, FormStateInterface $form_state) {
  159. // Ensure that we have saved an entity.
  160. if ($object = $form_state->getFormObject()) {
  161. $url = $object->getEntity()->url();
  162. }
  163. // Validate that the URL will be considered "external" by Drupal, which means
  164. // that a scheme value will be present.
  165. if (!empty($url)) {
  166. $uri_parts = parse_url($url);
  167. // If necessary and secure, issue a TrustedRedirectResponse to the new URL.
  168. if (!empty($uri_parts['host'])) {
  169. // Pass a redirect if necessary.
  170. if (DomainRedirectResponse::checkTrustedHost($uri_parts['host'])) {
  171. $response = new TrustedRedirectResponse($url);
  172. $form_state->setResponse($response);
  173. }
  174. }
  175. }
  176. }
  177. /**
  178. * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
  179. */
  180. function domain_source_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  181. // Add the options hidden from the user silently to the form.
  182. $manager = \Drupal::service('domain_source.element_manager');
  183. $hide = TRUE;
  184. $form = $manager->setFormOptions($form, $form_state, DOMAIN_SOURCE_FIELD, $hide);
  185. // Check that our field is present and add validation if Domain Access is
  186. // installed. See https://www.drupal.org/node/2952535.
  187. if (isset($form[DOMAIN_SOURCE_FIELD]) && defined('DOMAIN_ACCESS_FIELD') && isset($form[DOMAIN_ACCESS_FIELD])) {
  188. $form[DOMAIN_SOURCE_FIELD]['#element_validate'] = ['domain_source_form_validate'];
  189. // If using a select field, load the JS to show/hide options.
  190. if ($form[DOMAIN_SOURCE_FIELD]['widget']['#type'] == 'select') {
  191. $form['#attached']['library'][] = 'domain_source/drupal.domain_source';
  192. }
  193. }
  194. }
  195. /**
  196. * Implements hook_views_data_alter().
  197. */
  198. function domain_source_views_data_alter(array &$data) {
  199. $table = 'node__' . DOMAIN_SOURCE_FIELD;
  200. $data[$table][DOMAIN_SOURCE_FIELD]['field']['id'] = 'domain_source';
  201. $data[$table][DOMAIN_SOURCE_FIELD . '_target_id']['filter']['id'] = 'domain_source';
  202. // Since domains are not stored in the database, relationships cannot be used.
  203. unset($data[$table][DOMAIN_SOURCE_FIELD]['relationship']);
  204. }
  205. /**
  206. * Implements hook_form_FORM_ID_alter().
  207. *
  208. * Add options for domain source when using Devel Generate.
  209. */
  210. function domain_source_form_devel_generate_form_content_alter(&$form, &$form_state, $form_id) {
  211. // Add our element to the Devel generate form.
  212. $list = ['_derive' => t('Derive from domain selection')];
  213. $list += \Drupal::entityTypeManager()->getStorage('domain')->loadOptionsList();
  214. $form['domain_source'] = [
  215. '#title' => t('Domain source'),
  216. '#type' => 'checkboxes',
  217. '#options' => $list,
  218. '#weight' => 4,
  219. '#multiple' => TRUE,
  220. '#size' => count($list) > 5 ? 5 : count($list),
  221. '#default_value' => ['_derive'],
  222. '#description' => t('Sets the source domain for created nodes.'),
  223. ];
  224. }
  225. /**
  226. * Implements hook_ENTITY_TYPE_presave().
  227. *
  228. * Fires only if Devel Generate module is present, to assign test nodes to
  229. * domains.
  230. */
  231. function domain_source_node_presave(EntityInterface $node) {
  232. domain_source_presave_generate($node);
  233. }
  234. /**
  235. * Handles presave operations for devel generate.
  236. */
  237. function domain_source_presave_generate(EntityInterface $entity) {
  238. // Handle devel module settings.
  239. $exists = \Drupal::moduleHandler()->moduleExists('devel_generate');
  240. $values = [];
  241. $selections = [];
  242. if ($exists && isset($entity->devel_generate)) {
  243. // If set by the form.
  244. if (isset($entity->devel_generate['domain_access'])) {
  245. $selection = array_filter($entity->devel_generate['domain_access']);
  246. if (isset($selection['random-selection'])) {
  247. $domains = \Drupal::entityTypeManager()->getStorage('domain')->loadMultiple();
  248. $selections = array_rand($domains, ceil(rand(1, count($domains))));
  249. }
  250. else {
  251. $selections = array_keys($selection);
  252. }
  253. }
  254. if (isset($entity->devel_generate['domain_source'])) {
  255. $selection = $entity->devel_generate['domain_source'];
  256. if ($selection == '_derive') {
  257. if (!empty($selections)) {
  258. $values[DOMAIN_SOURCE_FIELD] = current($selections);
  259. }
  260. else {
  261. $values[DOMAIN_SOURCE_FIELD] = NULL;
  262. }
  263. }
  264. foreach ($values as $name => $value) {
  265. $entity->set($name, $value);
  266. }
  267. }
  268. }
  269. }
  270. /**
  271. * Implements hook_hook_info().
  272. */
  273. function domain_source_hook_info() {
  274. $hooks['domain_source_alter'] = [
  275. 'group' => 'domain_source',
  276. ];
  277. $hooks['domain_source_path_alter'] = [
  278. 'group' => 'domain_source',
  279. ];
  280. return $hooks;
  281. }