domain_source.module 8.7 KB

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