You are here

function extlink_extra_page_attachments in External Links Extra 8

Implements hook_page_attachments().

File

./extlink_extra.module, line 25

Code

function extlink_extra_page_attachments(array &$attachments) {

  // Get configuration.
  $config = \Drupal::config('extlink_extra.settings');

  // Attach JavaScript scripts.
  $attachments['#attached']['library'][] = 'extlink_extra/extlink_extra';

  // If we are using Colorbox we will add colorbox=1 to the query string of the
  // alert page. This causes a premature exit which saves execution time and does
  // not render the rest of the page.
  $alert_type = $config
    ->get('extlink_alert_type') ?: 'confirm';
  $query = [];
  if ($alert_type == 'colorbox') {
    $query = [
      'colorbox' => 1,
    ];
  }

  // Get URL params if they exist.
  $url_params = [];
  $request = \Drupal::request();
  $external_url = $request->request
    ->get('external_url');
  if ($external_url && UrlHelper::isValid($external_url, TRUE)) {
    $url_params['external_url'] = UrlHelper::stripDangerousProtocols($external_url);
  }
  $back_url = $request->request
    ->get('back_url');
  if ($back_url && UrlHelper::isValid($back_url, TRUE)) {
    $url_params['back_url'] = UrlHelper::stripDangerousProtocols($back_url);
  }

  // Attach JavaScript settings.
  $alert_url = Url::fromRoute('extlink_extra.leaving')
    ->setOption('query', $query)
    ->setAbsolute();
  $attachments['#attached']['drupalSettings']['extlink_extra'] = [
    'extlink_alert_type' => $alert_type,
    'extlink_modal_width' => $config
      ->get('extlink_modal_width') ?: 0,
    'extlink_alert_timer' => $config
      ->get('extlink_alert_timer') ?: 0,
    'extlink_alert_url' => $alert_url
      ->toString(),
    'extlink_cache_fix' => $config
      ->get('extlink_cache_fix') ?: 0,
    'extlink_exclude_warning' => $config
      ->get('extlink_exclude_warning') ?: '',
    'extlink_508_fix' => $config
      ->get('extlink_508_fix') ?: 0,
    'extlink_508_text' => $config
      ->get('extlink_508_text') ?: EXTLINK_EXTRA_508_TEXT,
    'extlink_url_override' => $config
      ->get('extlink_url_override') ?: 0,
    'extlink_url_params' => $url_params,
  ];

  // Add an extra CSS file if our 508 fix option is on.
  $extlink_508_fix = $config
    ->get('extlink_508_fix') ?: 0;
  if ($extlink_508_fix) {
    $attachments['#attached']['library'][] = 'extlink_extra/extlink_508';
  }

  // Add colorbox library if applicable.
  $moduleHandler = \Drupal::service('module_handler');
  if ($alert_type == 'colorbox' && $moduleHandler
    ->moduleExists('colorbox')) {
    $attachments['#attached']['library'][] = 'colorbox/colorbox';
  }

  // Add ajax and dialog libraries if applicable.
  if ($alert_type == 'modal') {
    $attachments['#attached']['library'][] = 'core/drupal.dialog.ajax';
  }
}