You are here

environment_indicator.module in Environment Indicator 8.2

Module implementation file.

File

environment_indicator.module
View source
<?php

/**
 * @file
 * Module implementation file.
 */

/**
 * Implement hook_help().
 */
function environment_indicator_help($path, $arg) {
  switch ($path) {
    case 'admin/config/development/environment-indicator':
      return t('The Environment Indicator adds a coloured strip to the site informing you which environment you\'re currently in (Development, Staging Production etc). You may override these settings by adding a new environment based on the hostname being seen or with your settings.php file in each of your environments.');
    case 'admin/help#environment_indicator':
      $output = '<p>' . t('The Environment Indicator adds a coloured strip to the site informing you which environment you\'re currently in (Development, Staging Production etc') . '</p>';
      $output .= '<p>' . t('The Environment Indicator <a href="@settings">settings page</a> allows you to modify some elements of the indicator\'s behavior and appearance. Since the appearance of the indicator is dependent on your site theme, substantial customisations require modifications to your site\'s theme and CSS files.', array(
        '@settings' => url('admin/config/development/environment-indicator'),
      )) . '</p>';
      $output .= '<p>' . t('The Environment Indicator\'s visibility depends upon the permissions of the viewer. The <a href="@permissions">access environment indicator</a> permission must be enabled for a user role in order for users of that role to see the indicator.', array(
        '@permissions' => url('admin/people/permissions', array(
          'fragment' => 'module-environment_indicator',
        )),
      )) . '</p>';
      $output .= '<p>' . t('The settings for the Environment Indicator, such as the text to display and the color can be overridden for each of your specific environments using the configuration UI or in the site\'s settings.php file. You can also export this configuration to code, this allows you to customise the indicator for each environment without needing to make any changes in the database. This means that the Environment Indicator will always display correctly when moving your site from development to staging to production. If you choose to detect your environment using settings.php, then all configuration variables can be overridden in settings.php, but the most common three are:') . '</p>';
      $output .= '<dl>';
      $output .= '<dt><em>environment_indicator_overwrite</em></dt><dd>' . t('A boolean value indicating whether the Environment Indicator should use the settings.php variables for the indicator. On your production environment, you should probably set this to FALSE.') . '<br/>$conf[\'environment_indicator_overwrite\'] = FALSE;<br />* ' . t('This setting corresponds to the old %setting in version 1.x.', array(
        '%setting' => 'environment_indicator_enabled',
      )) . '</dd></dt>';
      $output .= '<dt><em>environment_indicator_overwritten_name</em></dt><dd>' . t('The text that will be displayed on the indicator.') . '<br/>$conf[\'environment_indicator_overwritten_name\'] = \'Staging\';<br />* ' . t('This setting corresponds to the old %setting in version 1.x.', array(
        '%setting' => 'environment_indicator_text',
      )) . '</dd></dt>';
      $output .= '<dt><em>environment_indicator_overwritten_color</em></dt><dd>' . t('A valid css color.') . '<br/>$conf[\'environment_indicator_overwritten_color\'] = \'#F55\';<br />* ' . t('This setting corresponds to the old %setting in version 1.x.', array(
        '%setting' => 'environment_indicator_color',
      )) . '</dd></dt>';
      $output .= '<dt><em>environment_indicator_overwritten_position</em></dt><dd>' . t('Where your indicator may appear. Allowed values are "top" and "bottom".') . '<br/>$conf[\'environment_indicator_overwritten_position\'] = \'top\';</dd></dt>';
      $output .= '<dt><em>environment_indicator_overwritten_fixed</em></dt><dd>' . t('A boolean value indicating whether the Environment Indicator should be visible at all times, fixed at the top/bottom of the screen.') . '<br/>$conf[\'environment_indicator_overwritten_fixed\'] = FALSE;</dd></dt>';
      $output .= '</dl>';
      return $output;
  }
}

/**
 * Implement hook_menu().
 */
function environment_indicator_menu() {
  $items = array();

  // This is your listing page.
  $items['admin/config/development/environment-indicator'] = array(
    'title' => 'Environment indicator',
    'description' => 'Configure the indicators for each environment.',
    'route_name' => 'environment_indicator.list',
  );
  $items['admin/config/development/environment-indicator/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/config/development/environment-indicator/settings'] = array(
    'title' => 'Settings',
    'descriptions' => 'Configure extra settings for the environment indicator.',
    'route_name' => 'environment_indicator.settings',
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/config/development/environment-indicator/add'] = array(
    'route_name' => 'environment_indicator.list',
    'type' => MENU_SIBLING_LOCAL_TASK,
  );
  return $items;
}

/**
 * Implements hook_menu_link_defaults().
 */
function environment_indicator_menu_link_defaults() {
  $items['environment_indicator.list'] = array(
    'link_title' => 'Environment Indicators',
    'parent' => 'system.admin.config.development',
    'description' => 'Configure the indicators for each environment.',
    'route_name' => 'environment_indicator.list',
  );
  return $items;
}

/**
 * Implements hook_permission().
 */
function environment_indicator_permission() {
  $permissons = array(
    'administer environment indicator settings' => array(
      'title' => t('Administer environment_indicator settings'),
      'description' => t('Configure the environments and the colors to display.'),
    ),
    'access environment indicator' => array(
      'title' => t('See environment indicator'),
      'description' => t('See all the environment indicators in the site.'),
    ),
  );
  $environments = environment_indicator_get_all();
  foreach ($environments as $machine => $environment) {
    $permissons['access environment indicator ' . $environment->machine] = array(
      'title' => t('See environment indicator for %name', array(
        '%name' => $environment->name,
      )),
      'description' => t('See the evironment indicator if the user is in the %name environment.', array(
        '%name' => $environment->name,
      )),
    );
  }
  return $permissons;
}

/**
 * Load function for menu loaders.
 */
function environment_indicator_load($name) {
  return entity_load('environment_indicator', $name);
}

/**
 * Implements hook_page_build().
 */
function environment_indicator_page_build(&$page) {
  $page['#attached']['library'][] = 'environment_indicator/drupal.environment_indicator';
  if ($match = environment_indicator_get_active()) {
    if (environment_indicator_check_access($match)) {
      if (environment_indicator_needs_js()) {
        $page['#attached']['js'][] = array(
          'data' => array(
            'environment_indicator' => array(
              'toolbar-color' => $match['color'],
              'environment-indicator-name' => array(
                '#theme' => 'environment_indicator_indicator_name',
                '#name' => $match,
              ),
            ),
          ),
          'type' => 'setting',
        );
      }
      else {
        if (!(module_exists('admin_menu') && user_access('access administration menu'))) {
          environment_indicator_attach_indicator($match, $page);
        }
      }
    }
  }
}

/**
 * Implements hook_theme().
 */
function environment_indicator_theme($existing, $type, $theme, $path) {
  return array(
    'environment_indicator_indicator_name' => array(
      'variables' => array(
        'name' => NULL,
      ),
      'file' => 'environment_indicator.theme.inc',
    ),
    'environment_indicator_indicator_bar' => array(
      'variables' => array(
        'info' => NULL,
      ),
      'file' => 'environment_indicator.theme.inc',
    ),
    'environment_indicator_overritten_header' => array(
      'file' => 'environment_indicator.theme.inc',
    ),
  );
}

/**
 * Implements hook_admin_menu_output_alter().
 */
function environment_indicator_admin_menu_output_alter(&$content) {
  $environment_info = environment_indicator_get_active();
  if (!empty($environment_info)) {
    $content['environment_indicator'] = array(
      '#theme' => 'html_tag',
      '#tag' => 'div',
      '#value' => array(
        '#theme' => 'environment_indicator_indicator_name',
        '#name' => $environment_info,
      ),
      '#weight' => 50,
      '#attributes' => array(
        'id' => 'environment-indicator',
        'style' => 'background-color: ' . $environment_info['color'],
      ),
    );
  }
}

/**
 * Implements hook_toolbar().
 */
function environment_indicator_toolbar() {
  $environment = environment_indicator_get_active();
  $menu = _environment_indicator_switcher_menu();
  $items['environment_indicator'] = array(
    // Include the toolbar_tab_wrapper to style the link like a toolbar tab.
    // Exclude the theme wrapper if custom styling is desired.
    '#type' => 'toolbar_item',
    'tab' => array(
      '#type' => 'link',
      '#theme' => 'user_message_toolbar_tab',
      '#theme_wrappers' => array(),
      '#title' => t('@name', array(
        '@name' => $environment['name'],
      )),
      '#href' => '',
      '#options' => array(
        'attributes' => array(
          'title' => t('Environments'),
          'class' => array(
            'toolbar-icon',
            'toolbar-icon-environment',
          ),
        ),
      ),
    ),
    'tray' => $menu,
    '#weight' => 125,
  );
  return $items;
}

/**
 * Helper function to attach the indicator to the page.
 */
function environment_indicator_attach_indicator($environment_info, &$page) {
  $page['page_' . $environment_info['position']]['environment_indicator'] = array(
    '#theme' => 'environment_indicator_indicator_bar',
    '#info' => $environment_info,
  );
}

/**
 * Helper function to get the active indicator.
 */
function environment_indicator_get_active() {
  $env =& drupal_static(__FUNCTION__);
  if (isset($env)) {
    return $env;
  }
  $environments = environment_indicator_get_all();
  $matches = array();
  foreach ($environments as $machine => $environment) {

    // Check if the environment record has ben disabled. Then check the regex.
    if (environment_indicator_match_path($environment->regexurl)) {
      $matches[] = array(
        'name' => $environment->name,
        'machine' => $environment->machine,
        'weight' => $environment->weight,
        'color' => $environment->color,
        'position' => $environment->position,
        'fixed' => $environment->fixed,
      );
    }
  }
  uasort($matches, array(
    'Drupal\\Component\\Utility\\SortArray',
    'sortByWeightElement',
  ));
  $env = reset($matches);
  return $env;
}

/**
 * Helper function to match the path based on the regular expression.
 *
 * @param string $regexurl
 *   The regular expression to match against.
 * @return int
 *   Indicating if the environment was a match.
 */
function environment_indicator_match_path($regexurl) {

  // If the URL includes a non-scaped slash then an error will be thrown.
  $regexurl = preg_replace("/([^\\/])\\//", "\$1\\/", $regexurl);
  return preg_match("/{$regexurl}/", $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
}

/**
 * Helper function to get all environments.
 *
 * @param bool $fixed
 *   If TRUE it will only return fixed environments. Fixed environments are
 *   those that do not use a regular expression for detection.
 */
function environment_indicator_get_all($fixed = FALSE) {
  $environments = entity_load_multiple('environment_indicator');
  $environments = array_filter($environments, '_environment_indicator_active');

  // Check if the regular expression is a environment name.
  return $fixed ? array_filter($environments, '_environment_indicator_regex_filter') : $environments;
}

/**
 * Helper function to check access to show the indicator.
 *
 * @param array
 *   The environment info array.
 * @return boolean
 *   TRUE if the user can see the indicator.
 */
function environment_indicator_check_access($environment_info) {

  // Do not show the indicator on select pages.
  $supress_pages = \Drupal::config('environment_indicator.options')
    ->get('suppress_pages');

  // Compare with the internal and path alias (if any).
  $page_match = drupal_match_path(current_path(), $supress_pages);
  if ($page_match) {
    return FALSE;
  }
  return user_access('access environment indicator') || user_access('access environment indicator ' . $environment_info['machine']);
}

/**
 * Helper function to check if the JS needs to be included.
 *
 * @return boolean
 *   TRUE if the extra javascript is needed.
 */
function environment_indicator_needs_js() {
  return module_exists('toolbar') && user_access('access toolbar');
}

/**
 * Filter callback
 */
function _environment_indicator_regex_filter($item) {
  return !preg_match("/[\\*\\?\\[\\]\\(\\)]/", $item->regexurl);
}

/**
 * Helper function to generate a menu with the environments to switch to.
 */
function _environment_indicator_switcher_menu() {
  $element = array(
    '#heading' => t('Environment indicator'),
    'toolbar_indicators' => array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array(
          'toolbar-menu-environment-indicator',
        ),
      ),
      'indicator_menu' => array(
        '#sorted' => TRUE,
        '#theme_wrappers' => array(
          'menu_tree',
        ),
      ),
    ),
  );
  $environments = environment_indicator_get_all(TRUE);
  if (empty($environments)) {
    $element['toolbar_indicators']['indicator_menu']['empty'] = array(
      '#theme' => 'menu_link',
      '#title' => '- ' . t('There are no other environments available.') . ' -',
      '#href' => current_path(),
      '#localized_options' => array(
        'html' => TRUE,
      ),
      '#below' => array(),
      '#attributes' => array(
        'class' => array(
          'leaf',
        ),
      ),
    );
  }
  $current_environment = environment_indicator_get_active();
  foreach ($environments as $machine => $environment) {
    if ($machine != $current_environment['machine']) {
      $element['toolbar_indicators']['indicator_menu'][$environment
        ->id()] = array(
        '#theme' => 'menu_link',
        '#title' => t('Open in: %name', array(
          '%name' => $environment
            ->label(),
        )),
        '#href' => 'http://' . $environment
          ->get('regexurl') . '/' . current_path(),
        '#localized_options' => array(
          'html' => TRUE,
        ),
        '#below' => array(),
        '#attributes' => array(
          'class' => array(
            'leaf',
          ),
        ),
      );
    }
  }
  return $element;
}

/**
 * Filter callback
 */
function _environment_indicator_active($item) {

  // TODO: Implement an action for the configuration entity to disable it.
  return TRUE;
}

Functions

Namesort descending Description
environment_indicator_admin_menu_output_alter Implements hook_admin_menu_output_alter().
environment_indicator_attach_indicator Helper function to attach the indicator to the page.
environment_indicator_check_access Helper function to check access to show the indicator.
environment_indicator_get_active Helper function to get the active indicator.
environment_indicator_get_all Helper function to get all environments.
environment_indicator_help Implement hook_help().
environment_indicator_load Load function for menu loaders.
environment_indicator_match_path Helper function to match the path based on the regular expression.
environment_indicator_menu Implement hook_menu().
environment_indicator_menu_link_defaults Implements hook_menu_link_defaults().
environment_indicator_needs_js Helper function to check if the JS needs to be included.
environment_indicator_page_build Implements hook_page_build().
environment_indicator_permission Implements hook_permission().
environment_indicator_theme Implements hook_theme().
environment_indicator_toolbar Implements hook_toolbar().
_environment_indicator_active Filter callback
_environment_indicator_regex_filter Filter callback
_environment_indicator_switcher_menu Helper function to generate a menu with the environments to switch to.