<?php

/**
 * Implements hook_menu().
 */
function strongarm_menu() {
  $items = array();
  $items['admin/config/development/strongarm'] = array(
    'title' => 'Strongarm',
    'description' => 'Manage Drupal variable settings that have been strongarmed.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('strongarm_admin_form'),
    'access callback' => 'user_access',
    'access arguments' => array('administer site configuration'),
    'file' => 'strongarm.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Implements hook_form_alter() for system_module form().
 * Clear strongarm & variable caches on modules page.
 */
function strongarm_form_system_module_alter(&$form, &$form_state) {
  strongarm_flush_caches();
}

/**
 * Implements hook_theme().
 */
function strongarm_theme() {
  return array(
    'strongarm_admin_form' => array(
      'render element' => 'form',
      'file' => 'strongarm.admin.inc',
      'path' => drupal_get_path('module', 'strongarm'),
    ),
  );
}

/**
 * Implements hook_flush_caches().
 */
function strongarm_flush_caches() {
  cache_clear_all('variables', 'cache');
  cache_clear_all('strongarm', 'cache');
}

/**
 * Implements hook_schema_alter().
 * Makes the variables table usable by ctools' export.inc.
 */
function strongarm_schema_alter(&$schema) {
  $schema['variable']['export'] = array(
    'key' => 'name',
    'identifier' => 'strongarm',
    'default hook' => 'strongarm',
    'api' => array(
      'owner' => 'strongarm',
      'api' => 'strongarm',
      'minimum_version' => 1,
      'current_version' => 1,
    ),
  );
  $schema['variable']['fields']['value']['serialize'] = TRUE;
}

/**
 * Implementation hook_help().
 */
function strongarm_help($path, $arg) {
  switch ($path) {
    case 'admin/help#strongarm':
      $output = file_get_contents(drupal_get_path('module', 'strongarm') .'/README.txt');
      return module_exists('markdown') ? filter_xss_admin(module_invoke('markdown', 'filter', 'process', 0, -1, $output)) : '<pre>'. check_plain($output) .'</pre>';
    case 'admin/settings/strongarm':
      return '<p>'. t("Strongarm lets site builders manage default variable settings. All the default values provided by Strongarm are listed on this page. Any overridden value can be reverted to its default by selecting its checkbox and clicking 'Reset to defaults'.") .'</p>';
  }
}

/**
 * Load all variables (DB and Strongarmed).
 */
function strongarm_vars_load($sorted = TRUE, $reset = FALSE) {
  ctools_include('export');
  static $vars;

  // Ensure that the schema cache is not stale when trying to load.
  $schema = drupal_get_schema('variable');
  if (!isset($schema['export']) || $reset) {
    ctools_export_load_object_reset('variable');
    drupal_get_schema('variable', TRUE);
  }

  // Load vars.
  if (!isset($vars) || $reset) {
    $vars = ctools_export_load_object('variable');
    if ($sorted) {
      ksort($vars);
    }
  }
  return $vars;
}

/**
 * Implements hook_features_revert().
 */
if (!function_exists('variable_features_revert')) {
  function variable_features_revert($module) {
    $defaults = features_get_default('variable', $module);
    if (empty($defaults)) {
      return;
    }

    $vars = strongarm_vars_load(TRUE, TRUE);
    foreach ($defaults as $name => $default) {
      if (!empty($vars[$name]->in_code_only) || ($default->value !== $vars[$name]->value)) {
        variable_set($name, $default->value);
      }
    }
  }
}

 /**
 * Implements hook_features_rebuild().
 * Same as revert, but we only want to force variables only in code into the database
 */
function variable_features_rebuild($module) {
  $defaults = features_get_default('variable', $module);
  if (empty($defaults)) {
    return;
  }

  $vars = strongarm_vars_load(TRUE, TRUE);
  foreach ($defaults as $name => $default) {
    if (!empty($vars[$name]->in_code_only) || (drupal_installation_attempted() && $vars[$name]->export_type & EXPORT_IN_CODE)) {
      variable_set($name, $default->value);
    }
  }
}

/**
 * Implements hook_features_export().
 *
 * This is implemented to remove variables that are in code, but not DB.
 * This is a result of Strongarm vars now living in the DB, so unlike other
 * ctools components, an update of this Feature with a variable in code but
 * not the database, should remove the variable form the Feature.
 */
function variable_features_export($data, &$export, $module_name) {
  // First delegate to the Features ctools export
  $pipe = ctools_component_features_export('variable', $data, $export, $module_name);

  // Then remove any vars from the export that are only in code
  $vars = strongarm_vars_load(TRUE, TRUE);
  foreach ($data as $object_name) {
    if (!isset($vars[$object_name]) || !empty($vars[$object_name]->in_code_only)) {
      unset($export['features']['variable'][$object_name]);
    }
  }
  return $pipe;
}

/**
 * Implements hook_features_export_render().
 *
 * Loads default values from the DB since it is now the system of record.
 */
function variable_features_export_render($module, $data) {
  ctools_include('export');
  $schema = ctools_export_get_schema('variable');
  $code = '  $export = array();'."\n\n";
  $identifier = $schema['export']['identifier'];
  $result = db_select('variable', 'v')
    ->fields('v', array('name', 'value'))
    ->condition('name', $data, 'IN')
    ->orderBy('name')
    ->execute();
  foreach ($result as $object) {
    $object = _ctools_export_unpack_object($schema, $object);
    $code .= _ctools_features_export_crud_export('variable', $object, '  ');
    $code .= "  \$export[" . ctools_var_export($object->name) . "] = \${$identifier};\n\n";
  }
  $code .= '  return $export;';

  return array($schema['export']['default hook'] => $code);
}

/**
 * Implements hook_features_pipe_alter() for node component.
 * Add node type variables on behalf of core modules.
 */
function strongarm_features_pipe_node_alter(&$pipe, $data, $export) {
  if (!empty($data)) {
    $variables = array();
    if (module_exists('comment')) {
      $variables = array(
        'comment',
        'comment_anonymous',
        'comment_controls',
        'comment_default_mode',
        'comment_default_order',
        'comment_default_per_page',
        'comment_form_location',
        'comment_preview',
        'comment_subject_field',
      );
    }
    $variables = array_merge($variables, array(
      'field_bundle_settings_node_',
      'language_content_type',
      'menu_options',
      'menu_parent',
      'node_options',
      'node_preview',
      'node_submitted',
    ));
    foreach ($data as $node_type) {
      foreach ($variables as $variable_name) {
        $pipe['variable'][] = "{$variable_name}_{$node_type}";
      }
    }
  }
}
