<?php

/**
 * @file
 * Installation file for reCAPTCHA module.
 */

/**
 * Implements hook_uninstall().
 */
function recaptcha_uninstall() {
  variable_del('recaptcha_site_key');
  variable_del('recaptcha_secret_key');
  variable_del('recaptcha_theme');
  variable_del('recaptcha_type');
  variable_del('recaptcha_size');
  variable_del('recaptcha_tabindex');
  variable_del('recaptcha_noscript');
}

/**
 * Update variables from 7.x-1.x.
 */
function recaptcha_update_7200() {
  // Migrate the public key to site key.
  // Upgrade from 6.x-2.x to 7.x-2.x
  $site_key = variable_get('recaptcha_site_key', '');
  // Upgrade from 7.x-1.x to 7.x-2.x
  $public_key = variable_get('recaptcha_public_key', $site_key);
  variable_set('recaptcha_site_key', $public_key);
  variable_del('recaptcha_public_key');

  // Upgrade from 6.x-2.x to 7.x-2.x
  $secret_key = variable_get('recaptcha_secret_key', '');
  // Upgrade from 7.x-1.x to 7.x-2.x
  $private_key = variable_get('recaptcha_private_key', $secret_key);
  variable_set('recaptcha_secret_key', $private_key);
  variable_del('recaptcha_private_key');

  // Migrate previous 1.x themes to 2.x as good as possible.
  $recaptcha_themes = array(
    'red' => 'light',
    'white' => 'light',
    'blackglass' => 'dark',
    'clean' => 'light',
    'custom' => 'light',
  );
  // Upgrade from 6.x-2.x to 7.x-2.x
  $recaptcha_themes += array(
    'light' => 'light',
    'dark' => 'dark',
  );
  $recaptcha_theme = variable_get('recaptcha_theme', 'light');
  variable_set('recaptcha_theme', $recaptcha_themes[$recaptcha_theme]);

  // Delete obsolete variables.
  variable_del('recaptcha_ajax_api');
  variable_del('recaptcha_nocookies');
  variable_del('recaptcha_server_status_check_interval');

  // Remove stale variables not cleaned up properly in previous releases.
  variable_del('recaptcha_api_server');
  variable_del('recaptcha_api_secure_server');
  variable_del('recaptcha_secure_connection');
  variable_del('recaptcha_verify_server');

  // Mailhide module is not available, delete obsolete variables:
  // - recaptcha_mailhide_public_key
  // - recaptcha_mailhide_public_key_*
  // - recaptcha_mailhide_private_key
  // - recaptcha_mailhide_private_key_*
  db_delete('variable')
    ->condition('name', 'recaptcha_mailhide_%', 'LIKE')
    ->execute();
  cache_clear_all('variables', 'cache_bootstrap');

  return t('Migrated settings. You may need to create a new site key and secret key if it does not work.');
}

/**
 * Default empty tabindex to 0.
 */
function recaptcha_update_7201() {
  // Change an empty tabindex to value 0 for consistency with D8.
  $recaptcha_tabindex = variable_get('recaptcha_tabindex', '');
  if ($recaptcha_tabindex == '') {
    variable_set('recaptcha_tabindex', 0);
  }

  return t('Empty tabindex has been upgraded to 0.');
}
