domain_source.module 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 = array(
  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' => array(
  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. if ($display = \Drupal::entityTypeManager()->getStorage('entity_form_display')->load($entity_type . '.' . $bundle . '.default')) {
  52. $display->setComponent(DOMAIN_SOURCE_FIELD, [
  53. 'type' => 'options_select',
  54. 'weight' => 42,
  55. ])->save();
  56. }
  57. }
  58. /**
  59. * Implements hook_ENTITY_TYPE_insert().
  60. *
  61. * Creates our fields when new node types are created.
  62. *
  63. * @TODO: Make this possible for all entity types.
  64. */
  65. function domain_source_node_type_insert(EntityInterface $entity) {
  66. /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */
  67. if (!$entity->isSyncing()) {
  68. // Do not fire hook when config sync in progress.
  69. domain_source_confirm_fields('node', $entity->id());
  70. }
  71. }
  72. /**
  73. * Returns the source domain associated to an entity.
  74. *
  75. * @param Drupal\Core\Entity\EntityInterface $entity
  76. * The entity to check.
  77. *
  78. * @return string|NULL
  79. * The value assigned to the entity, either a domain id string or NULL.
  80. */
  81. function domain_source_get(EntityInterface $entity) {
  82. $source = NULL;
  83. if (!isset($entity->{DOMAIN_SOURCE_FIELD})) {
  84. return $source;
  85. }
  86. $value = $entity->get(DOMAIN_SOURCE_FIELD)->offsetGet(0);
  87. if (!empty($value)) {
  88. $target_id = $value->target_id;
  89. if ($domain = \Drupal::service('entity_type.manager')->getStorage('domain')->load($target_id)) {
  90. $source = $domain->id();
  91. }
  92. }
  93. return $source;
  94. }
  95. /**
  96. * Implements hook_form_alter().
  97. *
  98. * Find forms that contain the domain source field and allow those to handle
  99. * redirects properly.
  100. */
  101. function domain_source_form_alter(&$form, &$form_state, $form_id) {
  102. $object = $form_state->getFormObject();
  103. // Set up our TrustedRedirect handler for form saves.
  104. if (isset($form[DOMAIN_SOURCE_FIELD]) && !empty($object) && is_callable([$object, 'getEntity']) && $entity = $object->getEntity()) {
  105. foreach ($form['actions'] as $key => $element) {
  106. // Redirect submit handlers, but not the preview button.
  107. if ($key != 'preview' && isset($element['#type']) && $element['#type'] == 'submit') {
  108. $form['actions'][$key]['#submit'][] = 'domain_source_form_submit';
  109. }
  110. }
  111. }
  112. }
  113. /**
  114. * Validate form submissions.
  115. */
  116. function domain_source_form_validate($element, \Drupal\Core\Form\FormStateInterface $form_state) {
  117. $values = $form_state->getValues();
  118. // This is only run if Domain Access is present.
  119. if (isset($values[DOMAIN_SOURCE_FIELD]) && is_array($values[DOMAIN_SOURCE_FIELD]) && isset($values[DOMAIN_ACCESS_FIELD])) {
  120. $access_values = $values[DOMAIN_ACCESS_FIELD];
  121. $source_value = current($values[DOMAIN_SOURCE_FIELD]);
  122. }
  123. // If no value is selected, that's acceptable. Else run through a check.
  124. // Note that the _none selection returns as [FALSE].
  125. $source_set = empty($source_value);
  126. foreach ($access_values as $value) {
  127. // Core is inconsistent depending on the field order.
  128. // See https://www.drupal.org/project/domain/issues/2945771#comment-12493199
  129. if (is_array($value) && $value == $source_value) {
  130. $source_set = TRUE;
  131. }
  132. elseif (is_string($value) && !empty($source_value['target_id']) && $value == $source_value['target_id']) {
  133. $source_set = TRUE;
  134. }
  135. }
  136. if (!$source_set) {
  137. $form_state->setError($element, t('The source domain must be selected as a publishing option.'));
  138. }
  139. }
  140. /**
  141. * Redirect form submissions to other domains.
  142. */
  143. function domain_source_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  144. // Ensure that we have saved an entity.
  145. if ($object = $form_state->getFormObject()) {
  146. $url = $object->getEntity()->url();
  147. }
  148. // Validate that the URL will be considered "external" by Drupal, which means
  149. // that a scheme value will be present.
  150. if (!empty($url)) {
  151. $uri_parts = parse_url($url);
  152. // If necessary and secure, issue a TrustedRedirectResponse to the new URL.
  153. if (!empty($uri_parts['host'])) {
  154. // Pass a redirect if necessary.
  155. if (DomainRedirectResponse::checkTrustedHost($uri_parts['host'])) {
  156. $response = new TrustedRedirectResponse($url);
  157. $form_state->setResponse($response);
  158. }
  159. }
  160. }
  161. }
  162. /**
  163. * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
  164. */
  165. function domain_source_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  166. // Add the options hidden from the user silently to the form.
  167. $manager = \Drupal::service('domain_source.element_manager');
  168. $hide = TRUE;
  169. $form = $manager->setFormOptions($form, $form_state, DOMAIN_SOURCE_FIELD, $hide);
  170. // Add validation if Domain Access is installed.
  171. if (defined('DOMAIN_ACCESS_FIELD') && isset($form[DOMAIN_ACCESS_FIELD])) {
  172. $form[DOMAIN_SOURCE_FIELD]['#element_validate'] = array('domain_source_form_validate');
  173. // If using a select field, load the JS to show/hide options.
  174. if ($form[DOMAIN_SOURCE_FIELD]['widget']['#type'] == 'select') {
  175. $form['#attached']['library'][] = 'domain_source/drupal.domain_source';
  176. }
  177. }
  178. }
  179. /**
  180. * Implements hook_views_data_alter.
  181. */
  182. function domain_source_views_data_alter(array &$data) {
  183. $table = 'node__' . DOMAIN_SOURCE_FIELD;
  184. $data[$table][DOMAIN_SOURCE_FIELD]['field']['id'] = 'domain_source';
  185. $data[$table][DOMAIN_SOURCE_FIELD . '_target_id']['filter']['id'] = 'domain_source';
  186. // Since domains are not stored in the database, relationships cannot be used.
  187. unset($data[$table][DOMAIN_SOURCE_FIELD]['relationship']);
  188. }
  189. /**
  190. * Implements hook_form_FORM_ID_alter().
  191. *
  192. * Add options for domain source when using Devel Generate.
  193. */
  194. function domain_source_form_devel_generate_form_content_alter(&$form, &$form_state, $form_id) {
  195. // Add our element to the Devel generate form.
  196. $list = ['_derive' => t('Derive from domain selection')];
  197. $list += \Drupal::service('entity_type.manager')->getStorage('domain')->loadOptionsList();
  198. $form['domain_source'] = array(
  199. '#title' => t('Domain source'),
  200. '#type' => 'checkboxes',
  201. '#options' => $list,
  202. '#weight' => 4,
  203. '#multiple' => TRUE,
  204. '#size' => count($list) > 5 ? 5 : count($list),
  205. '#default_value' => ['_derive'],
  206. '#description' => t('Sets the source domain for created nodes.'),
  207. );
  208. }
  209. /**
  210. * Implements hook_ENTITY_TYPE_presave().
  211. *
  212. * Fires only if Devel Generate module is present, to assign test nodes to
  213. * domains.
  214. */
  215. function domain_source_node_presave(EntityInterface $node) {
  216. domain_source_presave_generate($node);
  217. }
  218. /**
  219. * Handles presave operations for devel generate.
  220. */
  221. function domain_source_presave_generate(EntityInterface $entity) {
  222. // Handle devel module settings.
  223. $exists = \Drupal::moduleHandler()->moduleExists('devel_generate');
  224. $values = [];
  225. $selections = [];
  226. if ($exists && isset($entity->devel_generate)) {
  227. // If set by the form.
  228. if (isset($entity->devel_generate['domain_access'])) {
  229. $selection = array_filter($entity->devel_generate['domain_access']);
  230. if (isset($selection['random-selection'])) {
  231. $domains = \Drupal::service('entity_type.manager')->getStorage('domain')->loadMultiple();
  232. $selections = array_rand($domains, ceil(rand(1, count($domains))));
  233. }
  234. else {
  235. $selections = array_keys($selection);
  236. }
  237. }
  238. if (isset($entity->devel_generate['domain_source'])) {
  239. $selection = $entity->devel_generate['domain_source'];
  240. if ($selection == '_derive') {
  241. if (!empty($selections)) {
  242. $values[DOMAIN_SOURCE_FIELD] = current($selections);
  243. }
  244. else {
  245. $values[DOMAIN_SOURCE_FIELD] = NULL;
  246. }
  247. }
  248. foreach ($values as $name => $value) {
  249. $entity->set($name, $value);
  250. }
  251. }
  252. }
  253. }