<?php

/**
 * @file
 * Installation code for Commerce Kickstart.
 */

/**
 * Implements hook_install_tasks().
 */
function commerce_kickstart_install_tasks() {
  // Increase maximum function nesting level to prevent install errors.
  $max_nesting_level = ini_get('xdebug.max_nesting_level');
  if ($max_nesting_level > 0 && $max_nesting_level <= '200') {
    ini_set('xdebug.max_nesting_level', 200);
  }

  // Remove any status messages that might have been set. They are unneeded.
  drupal_get_messages('status', TRUE);

  $tasks = array();
  $current_task = variable_get('install_task', 'done');
  $install_demo_store = variable_get('commerce_kickstart_demo_store', FALSE);

  $tasks['commerce_kickstart_configure_store_form'] = array(
    'display_name' => st('Configure store'),
    'type' => 'form',
  );
  $tasks['commerce_kickstart_install_additional_modules'] = array(
    'display_name' => $install_demo_store ? st('Install demo store') : st('Install additional functionality'),
    'type' => 'batch',
    // Show this task only after the Kickstart steps have bene reached.
    'display' => strpos($current_task, 'commerce_kickstart_') !== FALSE,
    'dfp_settings' => array(
      'dfp_unit' => 'Kickstart_Install_2',
    ),
  );
  $tasks['commerce_kickstart_import_content'] = array(
    'display_name' => st('Import content'),
    'type' => 'batch',
    // Show this task only after the Kickstart steps have bene reached.
    'display' => strpos($current_task, 'commerce_kickstart_') !== FALSE,
    'dfp_settings' => array(
      'dfp_unit' => 'Kickstart_Install_3',
    ),
  );

  return $tasks;
}

/**
 * Implements hook_install_tasks_alter().
 */
function commerce_kickstart_install_tasks_alter(&$tasks, $install_state) {
  $tasks['install_finished']['function'] = 'commerce_kickstart_install_finished';
  $tasks['install_select_profile']['display'] = FALSE;
  $tasks['install_select_locale']['display'] = FALSE;
  $tasks['install_select_locale']['run'] = INSTALL_TASK_SKIP;

  // The "Welcome" screen needs to come after the first two steps
  // (profile and language selection), despite the fact that they are disabled.
  $new_task['install_welcome'] = array(
    'display' => TRUE,
    'display_name' => st('Welcome'),
    'type' => 'form',
    'run' => isset($install_state['parameters']['welcome']) ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_REACHED,
  );
  $old_tasks = $tasks;
  $tasks = array_slice($old_tasks, 0, 2) + $new_task + array_slice($old_tasks, 2);

  // Set the installation theme.
  _commerce_kickstart_set_theme('commerce_kickstart_admin');
  // Test if the current task is a batch task.
  if (isset($tasks[$install_state['active_task']]['type']) && $tasks[$install_state['active_task']]['type'] == 'batch') {
    if (!isset($tasks[$install_state['active_task']]['dfp_settings'])) {
      $tasks[$install_state['active_task']]['dfp_settings'] = array();
    }
    // Default to Kickstart_Install dfp unit.
    $tasks[$install_state['active_task']]['dfp_settings'] += array(
      'dfp_unit' => 'Kickstart_Install',
    );
    $prefix = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') ? 'https://' : 'http://';
    drupal_add_js($prefix . 'www.googletagservices.com/tag/js/gpt.js');
    drupal_add_js(array(
      'dfp' => $tasks[$install_state['active_task']]['dfp_settings'],
    ), 'setting');
    drupal_add_js(drupal_get_path('profile', 'commerce_kickstart') . '/js/commerce_kickstart.js');
  }
}

/**
 * Force-set a theme at any point during the execution of the request.
 *
 * Drupal doesn't give us the option to set the theme during the installation
 * process and forces enable the maintenance theme too early in the request
 * for us to modify it in a clean way.
 */
function _commerce_kickstart_set_theme($target_theme) {
  if ($GLOBALS['theme'] != $target_theme) {
    unset($GLOBALS['theme']);

    drupal_static_reset();
    $GLOBALS['conf']['maintenance_theme'] = $target_theme;
    _drupal_maintenance_theme();
  }
}

/**
 * Task callback: shows the welcome screen.
 */
function install_welcome($form, &$form_state, &$install_state) {
  drupal_set_title(st('Privacy Policy Summary'));
  $message = '<p>' . st('Thank you for choosing Commerce Kickstart, a product offered by Commerce Guys.') . '</p>';
  $eula = '<p>' . st('While we have a rather long, boring Privacy Policy just like any other technology company, here is a short summary of some key items we feel are important:') . '</p>';
  $items = array();
  $dfp_link = l("Google's DoubleClick for Publishers (\"DFP\")", "http://www.google.com/dfp/info/sb/index.html", array('attributes' => array('target' => '_blank')));
  $items[] = st("Commerce Kickstart makes use of !dfp;", array('!dfp' => $dfp_link));
  $items[] = st('We use DFP to show you content relevant to Drupal Commerce at various points and places in Commerce Kickstart, including during installation;');
  $items[] = st('DFP is a third-party technology. It uses audience management tags which collect and use certain data;');
  $items[] = st('Commerce Guys does not collect any personally identifiable information;');
  $items[] = st('If at any time after installation you do not want us to utilize DFP through Commerce Kickstart, you can easily opt out of it;');
  $eula .= theme('item_list', array('items' => $items));
  $eula_link = l('Privacy Policy and User Agreement', 'https://marketplace.commerceguys.com/privacy/commerce-kickstart', array('attributes' => array('target' => '_blank')));
  $eula .= '<p>' . st('That is it for the main points. The full !policy can be viewed on our website.  Thank you again for choosing Commerce Kickstart!', array('!policy' => $eula_link)) . '</p>';
  $form = array();
  $form['welcome_message'] = array(
    '#markup' => $message,
  );
  $form['eula'] = array(
    '#prefix' => '<div id="eula-installation-welcome">',
    '#markup' => $eula,
  );
  $form['eula-accept'] = array(
    '#title' => st('I agree to the Privacy Policy and User Agreement'),
    '#type' => 'checkbox',
    '#suffix' => '</div>',
  );
  $form['actions'] = array(
    '#type' => 'actions',
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => st("Let's Get Started!"),
    '#states' => array(
      'disabled' => array(
        ':input[name="eula-accept"]' => array('checked' => FALSE),
      ),
    ),
    '#weight' => 10,
  );
  return $form;
}

function install_welcome_submit($form, &$form_state) {
  global $install_state;

  $install_state['parameters']['welcome'] = 'done';
  $install_state['parameters']['locale'] = 'en';
}

/**
 * Task callback: returns the form allowing the user to add example store content on install.
 */
function commerce_kickstart_configure_store_form() {
  include_once DRUPAL_ROOT . '/includes/iso.inc';

  drupal_set_title(st('Configure store'));

  $form['country'] = array(
    '#type' => 'fieldset',
    '#title' => st('Country'),
  );
  $form['country']['country_list'] = array(
    '#title' => t('Default store country'),
    '#description' => t('Services specific to the selected country will be installed if they exist.'),
    '#options' => _country_get_predefined_list(),
    '#type' => 'select',
    '#default_value' => variable_get('site_default_country'),
    // This field is not required when installing through drush.
    '#required' => !drupal_is_cli(),
  );

  // Prepare all the options for sample content.
  $options = array(
    '1' => st('Yes'),
    '0' => st('No'),
  );
  $form['functionality'] = array(
    '#type' => 'fieldset',
    '#title' => st('Functionality'),
  );
  $form['functionality']['install_demo_store'] = array(
    '#type' => 'radios',
    '#title' => st('Do you want to install the demo store?'),
    '#description' => st('Shows you everything Commerce Kickstart can do. Includes a custom theme, sample content and products.'),
    '#options' => $options,
    '#default_value' => '1',
  );
  $form['localization'] = array(
    '#type' => 'fieldset',
    '#title' => st('Localization'),
  );
  $form['localization']['install_localization'] = array(
    '#type' => 'radios',
    '#title' => st('Do you want to be able to translate the interface of your store?'),
    '#options' => $options,
    '#default_value' => '0',
  );

  $options_selection = array(
    'anonymous_checkout' => 'Allow checkout for <strong>anonymous users</strong>.',
    'merchandising' => 'Additional <strong>blocks</strong> for featuring specific content.',
    'slideshow' => 'Frontpage <strong>slideshow</strong>.',
    'menus' => 'Custom <strong>admin menu</strong> designed for store owners.',
    'blog' => '<strong>Blog</strong> functionality.',
    'social' => '<strong>Social</strong> logins and links for sharing products via social networks.',
    'zoom_cloud' => '<strong>Zoom & Gallery</strong> mode for products.',
  );
  $form['functionality']['extras'] = array(
    '#type' => 'checkboxes',
    '#options' => $options_selection,
    '#title' => t("Install additional functionality"),
    '#states' => array(
      'visible' => array(
        ':input[name="install_demo_store"]' => array('value' => '0'),
      ),
    ),
  );

  // Build a currency options list from all defined currencies.
  $options = array();
  foreach (commerce_currencies(FALSE, TRUE) as $currency_code => $currency) {
    $options[$currency_code] = t('@code - !name', array(
      '@code' => $currency['code'],
      '@symbol' => $currency['symbol'],
      '!name' => $currency['name']
    ));

    if (!empty($currency['symbol'])) {
      $options[$currency_code] .= ' - ' . check_plain($currency['symbol']);
    }
  }

  $form['commerce_default_currency_wrapper'] = array(
    '#type' => 'fieldset',
    '#title' => st('Currency'),
  );
  $form['commerce_default_currency_wrapper']['commerce_default_currency'] = array(
    '#type' => 'select',
    '#title' => t('Default store currency'),
    '#options' => $options,
    '#default_value' => commerce_default_currency(),
  );

  // Prepare all the options for sample content.
  $options = array(
    'none' => st("No sample tax rate."),
    'us' => st('US - Sales taxes displayed in checkout'),
    'europe' => st('European - Inclusive tax rates (VAT)'),
  );
  $form['commerce_kickstart_tax_wrapper'] = array(
    '#type' => 'fieldset',
    '#title' => st('Tax Rate'),
  );
  $form['commerce_kickstart_tax_wrapper']['commerce_kickstart_choose_tax_country'] = array(
    '#type' => 'radios',
    '#title' => st('Tax rate examples'),
    '#description' => st('Example tax rates will be created in this style.'),
    '#options' => $options,
    '#default_value' => key($options),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => st('Create and Finish'),
    '#weight' => 15,
  );
  return $form;
}

/**
 * Submit callback: creates the requested sample content.
 */
function commerce_kickstart_configure_store_form_submit(&$form, &$form_state) {
  variable_set('commerce_kickstart_store_country', $form_state['values']['country_list']);
  variable_set('commerce_kickstart_demo_store', $form_state['values']['install_demo_store']);
  variable_set('commerce_kickstart_localization', $form_state['values']['install_localization']);
  variable_set('commerce_kickstart_selected_extras', $form_state['values']['extras']);
  variable_set('commerce_kickstart_choose_tax_country', $form_state['values']['commerce_kickstart_choose_tax_country']);
  variable_set('commerce_default_currency', $form_state['values']['commerce_default_currency']);
  variable_set('commerce_enabled_currencies', array($form_state['values']['commerce_default_currency'] => $form_state['values']['commerce_default_currency']));
}

/**
 * Task callback: uses Batch API to import modules based on user selection.
 * Installs all demo store modules if requested, or any modules providing
 * additional functionality to the base install.
 *
 * Any modules providing custom blocks should be enabled here, and not before
 * (as an install profile dependency), because the themes are setup during
 * commerce_kickstart_install(), which means region assignment can only happen
 * after that.
 */
function commerce_kickstart_install_additional_modules() {
  $install_demo_store = variable_get('commerce_kickstart_demo_store', FALSE);
  if ($install_demo_store) {
    $modules = array(
      'commerce_kickstart_reset',
      'commerce_kickstart_block',
      'commerce_kickstart_user',
      'commerce_checkout_redirect',
      'commerce_kickstart_social',
      'commerce_kickstart_product',
      'commerce_kickstart_product_ui',
      'commerce_kickstart_blog',
      'commerce_kickstart_slideshow',
      'commerce_kickstart_merchandising',
      'commerce_kickstart_menus',
      'commerce_kickstart_search',
      'commerce_kickstart_taxonomy',
    );
  }
  else {
    $modules = array(
      'commerce_kickstart_block',
      'commerce_kickstart_user',
      'commerce_kickstart_lite_product',
      'commerce_kickstart_product_ui',
      'commerce_kickstart_search',
      'commerce_kickstart_taxonomy',
    );
    $selected_extras = variable_get('commerce_kickstart_selected_extras', array());
    if (empty($selected_extras['anonymous_checkout'])) {
      $modules[] = 'commerce_checkout_redirect';
    }
    if (!empty($selected_extras['merchandising'])) {
      $modules[] = 'commerce_kickstart_merchandising';
    }
    if (!empty($selected_extras['slideshow'])) {
      $modules[] = 'commerce_kickstart_slideshow';
    }
    if (!empty($selected_extras['menus'])) {
      $modules[] = 'commerce_kickstart_menus';
    }
    if (!empty($selected_extras['blog'])) {
      $modules[] = 'commerce_kickstart_blog';
    }
    if (!empty($selected_extras['social'])) {
      $modules[] = 'commerce_kickstart_social';
    }
    if (!empty($selected_extras['zoom_cloud'])) {
      variable_set('commerce_kickstart_product_zoom_enabled', TRUE);
    }
  }

  $install_localization = variable_get('commerce_kickstart_localization', FALSE);
  if ($install_localization) {
    $modules[] = 'locale';
    $modules[] = 'variable';
    $modules[] = 'i18n';
    $modules[] = 'i18n_field';
  }

  $store_country = variable_get('commerce_kickstart_store_country', 'US');
  // Enable Commerce Moneybookers for Germany, France and the UK.
  if (in_array($store_country, array('GB', 'DE', 'FR'))) {
    $modules[] = 'commerce_moneybookers';
    $modules[] = 'commerce_moneybookers_quickcheckout';
  }
  // Enable kiala modules.
  if (in_array($store_country, array('FR', 'SP', 'BE', 'NL', 'LU'))) {
    $modules[] = 'colorbox';
    $modules[] = 'commerce_kiala_ps';
    $modules[] = 'commerce_kiala_track';
    variable_set('commerce_kiala_settings', array('ls_map_search_embed_type' => 'colorbox'));
    variable_set('colorbox_load', 1);
  }
  // Enable Payleap and Paypal for North America.
  if (in_array($store_country, array('CA', 'US'))) {
    $modules[] = 'commerce_payleap';
    $modules[] = 'commerce_payflow';
    $modules[] = 'commerce_paypal_ec';
  }
  $eu_country_codes = array(
    'AT',
    'BE',
    'BG',
    'CY',
    'CZ',
    'DE',
    'DK',
    'EE',
    'ES',
    'FI',
    'FR',
    'GB',
    'GR',
    'HU',
    'IE',
    'IT',
    'LT',
    'LU',
    'LV',
    'MT',
    'NL',
    'PL',
    'PT',
    'RO',
    'SE',
    'SI',
    'SK',
  );
  // Enable Commerce Paypal Express Checkout for Europe.
  if (in_array($store_country, $eu_country_codes)) {
    $modules[] = 'commerce_paypal_ec';
  }

  // Resolve the dependencies now, so that module_enable() doesn't need
  // to do it later for each individual module (which kills performance).
  $files = system_rebuild_module_data();
  $modules_sorted = array();
  foreach ($modules as $module) {
    if ($files[$module]->requires) {
      // Create a list of dependencies that haven't been installed yet.
      $dependencies = array_keys($files[$module]->requires);
      $dependencies = array_filter($dependencies, '_commerce_kickstart_filter_dependencies');
      // Add them to the module list.
      $modules = array_merge($modules, $dependencies);
    }
  }
  $modules = array_unique($modules);
  foreach ($modules as $module) {
    $modules_sorted[$module] = $files[$module]->sort;
  }
  arsort($modules_sorted);

  $operations = array();
  // Enable and set as default the correct theme.
  $theme = $install_demo_store ? 'commerce_kickstart_theme' : 'omega_kickstart';
  $operations[] = array('_commerce_kickstart_enable_theme', array($theme));
  // Enable the selected modules.
  foreach ($modules_sorted as $module => $weight) {
    $operations[] = array('_commerce_kickstart_enable_module', array($module, $files[$module]->info['name']));
  }
  if ($install_localization) {
    $operations[] = array('_commerce_kickstart_setup_localization', array(t('Configured localization.')));
  }
  $operations[] = array('_commerce_kickstart_flush_caches', array(t('Flushed caches.')));

  $batch = array(
    'title' => $install_demo_store ? t('Installing demo store') : t('Installing additional functionality'),
    'operations' => $operations,
    'file' => drupal_get_path('profile', 'commerce_kickstart') . '/commerce_kickstart.install_callbacks.inc',
  );

  return $batch;
}

/**
 * array_filter() callback used to filter out already installed dependencies.
 */
function _commerce_kickstart_filter_dependencies($dependency) {
  return !module_exists($dependency);
}

/**
 * Task callback: return a batch API array with the products to be imported.
 */
function commerce_kickstart_import_content() {
  // Fixes problems when the CSV files used for importing have been created
  // on a Mac, by forcing PHP to detect the appropriate line endings.
  ini_set("auto_detect_line_endings", TRUE);

  $operations = array();
  $operations[] = array('_commerce_kickstart_example_taxes', array(t('Setting up taxes.')));

  $install_demo_store = variable_get('commerce_kickstart_demo_store', FALSE);
  $operations[] = array('_commerce_kickstart_taxonomy_menu', array(t('Setting up menus.')));

  // Run all available migrations.
  $migrations = migrate_migrations();
  foreach ($migrations as $machine_name => $migration) {
    $operations[] = array('_commerce_kickstart_import', array($machine_name, t('Importing content.')));
  }

  if ($install_demo_store) {
    $operations[] = array('_commerce_kickstart_example_user', array(t('Setting up users.')));
  }
  // Perform post-import tasks.
  $operations[] = array('_commerce_kickstart_post_import', array(t('Completing setup.')));

  $batch = array(
    'title' => t('Importing content'),
    'operations' => $operations,
    'file' => drupal_get_path('profile', 'commerce_kickstart') . '/commerce_kickstart.install_callbacks.inc',
  );

  return $batch;
}

/**
 * Custom installation task; perform final steps and redirect the user to the new site if there are no errors.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 *
 * @return
 *   A message informing the user about errors if there was some.
 */
function commerce_kickstart_install_finished(&$install_state) {
  drupal_set_title(st('@drupal installation complete', array('@drupal' => drupal_install_profile_distribution_name())), PASS_THROUGH);
  $messages = drupal_set_message();

  // Remember the profile which was used.
  variable_set('install_profile', drupal_get_profile());
  variable_set('install_task', 'done');

  // Flush all caches to ensure that any full bootstraps during the installer
  // do not leave stale cached data, and that any content types or other items
  // registered by the install profile are registered correctly.
  drupal_flush_all_caches();

  // Install profiles are always loaded last
  db_update('system')
    ->fields(array('weight' => 1000))
    ->condition('type', 'module')
    ->condition('name', drupal_get_profile())
    ->execute();

  // Cache a fully-built schema.
  drupal_get_schema(NULL, TRUE);

  // Run cron to populate update status tables (if available) so that users
  // will be warned if they've installed an out of date Drupal version.
  // Will also trigger indexing of profile-supplied content or feeds.
  drupal_cron_run();

  if (isset($messages['error'])) {
    $output = '<p>' . (isset($messages['error']) ? st('Review the messages above before visiting <a href="@url">your new site</a>.', array('@url' => url(''))) : st('<a href="@url">Visit your new site</a>.', array('@url' => url('')))) . '</p>';
    return $output;
  }
  else {
    // Since any module can add a drupal_set_message, this can bug the user
    // when we redirect him to the front page. For a better user experience,
    // remove all the message that are only "notifications" message.
    drupal_get_messages('status', TRUE);
    drupal_get_messages('completed', TRUE);
    // Migrate adds its messages under the wrong type, see #1659150.
    drupal_get_messages('ok', TRUE);

    // If we don't install drupal using Drush, redirect the user to the front
    // page.
    if (!drupal_is_cli()) {
      if (module_exists('overlay')) {
        // Special case when no clean urls.
        $fragment = empty($GLOBALS['conf']['clean_url']) ? urlencode('?q=admin/help/getting-started') : 'admin/help/getting-started';
        drupal_goto('', array('fragment' => 'overlay=' . $fragment));
      }
      else {
        drupal_goto('admin/help/getting-started');
      }
    }
  }
}

/**
 * Implements hook_install().
 */
function commerce_kickstart_install() {
  // Add text formats.
  $filtered_html_format = array(
    'format' => 'filtered_html',
    'name' => 'Filtered HTML',
    'weight' => 0,
    'filters' => array(
      // URL filter.
      'filter_url' => array(
        'weight' => 0,
        'status' => 1,
      ),
      // HTML filter.
      'filter_html' => array(
        'weight' => 1,
        'status' => 1,
      ),
      // Line break filter.
      'filter_autop' => array(
        'weight' => 2,
        'status' => 1,
      ),
      // HTML corrector filter.
      'filter_htmlcorrector' => array(
        'weight' => 10,
        'status' => 1,
      ),
    ),
  );
  $filtered_html_format = (object) $filtered_html_format;
  filter_format_save($filtered_html_format);

  $full_html_format = array(
    'format' => 'full_html',
    'name' => 'Full HTML',
    'weight' => 1,
    'filters' => array(
      // URL filter.
      'filter_url' => array(
        'weight' => 0,
        'status' => 1,
      ),
      // Line break filter.
      'filter_autop' => array(
        'weight' => 1,
        'status' => 1,
      ),
      // HTML corrector filter.
      'filter_htmlcorrector' => array(
        'weight' => 10,
        'status' => 1,
      ),
    ),
  );
  $full_html_format = (object) $full_html_format;
  filter_format_save($full_html_format);

  // Enable the admin theme.
  $admin_theme = 'commerce_kickstart_admin';
  theme_enable(array($admin_theme));
  variable_set('admin_theme', $admin_theme);
  variable_set('node_admin_theme', '1');

  // Insert default pre-defined node types into the database.
  $types = array(
    array(
      'type' => 'page',
      'name' => st('Basic page'),
      'base' => 'node_content',
      'description' => st("Use <em>basic pages</em> for your static content, such as an 'About us' page."),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    ),
  );

  foreach ($types as $type) {
    $type = node_type_set_defaults($type);
    node_type_save($type);
    node_add_body_field($type);
  }

  // "Basic page" configuration.
  variable_set('node_options_page', array('status'));
  variable_set('comment_page', COMMENT_NODE_HIDDEN);
  variable_set('node_submitted_page', FALSE);
  variable_set('pathauto_node_page_pattern', '[node:title]');

  // Enable default permissions for system roles.
  $filtered_html_permission = filter_permission_name($filtered_html_format);
  user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('access content', 'access comments', 'access checkout', 'view own commerce_order entities', 'view any commerce_product entity', $filtered_html_permission));
  user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array('access content', 'access comments', 'access checkout', 'view own commerce_order entities', 'view any commerce_product entity', 'post comments', 'skip comment approval', $filtered_html_permission));

  // Create a default role for site administrators, with all available permissions assigned.
  $admin_role = new stdClass();
  $admin_role->name = 'administrator';
  $admin_role->weight = 2;
  user_role_save($admin_role);
  user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));
  // Set this as the administrator role.
  variable_set('user_admin_role', $admin_role->rid);

  // Assign user 1 the "administrator" role.
  db_insert('users_roles')
    ->fields(array('uid' => 1, 'rid' => $admin_role->rid))
    ->execute();

  // Update the menu router information.
  menu_rebuild();

  // Set Mimemail.
  variable_set('mimemail_format', 'full_html');
  // Set checkout progress.
  variable_set('commerce_checkout_progress_link', 0);
  variable_set('commerce_checkout_progress_list_type', 'ol');
  variable_set('commerce_checkout_progress_block_pages', array_keys(commerce_checkout_pages()));
  // Configure Chosen.
  variable_set('chosen_jquery_selector', '.view-filters .views-exposed-form select');
  variable_set('chosen_minimum', 0);
  variable_set('chosen_minimum_width', 200);
  variable_set('chosen_search_contains', TRUE);

  // Create the default Search API server.
  $values = array(
    'machine_name' => 'frontend',
    'name' => 'Frontend',
    'description' => '',
    'class' => 'search_api_db_service',
    'options' => array(
      'database' => 'default:default',
      'min_chars' => 3,
    ),
  );
  search_api_server_insert($values);

  // Enable automatic title replacement for node and commerce product bundles.
  foreach (array('node', 'commerce_product') as $entity_type) {
    $title_settings = array(
      'auto_attach' => array(
        'title' => 'title',
      ),
      'hide_label' => array(
        'entity' => 'entity',
        'page' => 0,
      ),
    );
    variable_set('title_' . $entity_type, $title_settings);
  }
  // Disable migrate autoregistration.
  variable_set('migrate_disable_autoregistration', TRUE);

  // Check DFP User Agreement.
  variable_set('commerce_kickstart_dfp_eula', TRUE);
}

/**
 * Disables the passed modules by removing their entries from the system table.
 *
 * Used for modules that have already disappeared from the filesystem.
 * Implemented in order to avoid the core issue described in #1081266.
 *
 * @param $modules
 *   The modules to disable.
 */
function _commerce_kickstart_disable_modules($modules) {
  // Disable the removed modules.
  db_update('system')
    ->fields(array('status' => 0))
    ->condition('name', $modules)
    ->condition('type', 'module')
    ->execute();
}

function commerce_kickstart_update_7100() {
  registry_rebuild();
}

/**
 * Update the admin theme from "Commerce Kickstart Admin Theme" to "Shiny".
 */
function commerce_kickstart_update_7200() {
  // Enable the new theme.
  theme_enable(array('shiny'));
  variable_set('admin_theme', 'shiny');
  drupal_static_reset();
  _block_rehash('shiny');

  // Disable all blocks in the content region except "Main page content".
  db_update('block')
    ->fields(array('region' => '-1'))
    ->condition('theme', 'shiny')
    ->condition('region', 'content')
    ->condition(db_and()
      ->condition('module', 'system', '<>')
      ->condition('delta', 'main', '<>')
    )
    ->execute();

  // Move help to the correct region.
  db_update('block')
    ->fields(array('region' => 'help'))
    ->condition('module', 'system')
    ->condition('delta', 'help')
    ->condition('theme', 'shiny')
    ->execute();

  // Disable the old theme.
  theme_disable(array('commerce_kickstart_admin'));
}

/**
 * Flush caches and rebuild features.
 */
function commerce_kickstart_update_7201() {
  // install_task wasn't set properly on older installs, which affects
  // feature rebuilding.
  variable_set('install_task', 'done');

  // Only non-overridden indexes get processed in 7202, no reason to do a
  // cache clear this early otherwise.
  $index = search_api_index_load('product_display');
  if (!empty($index) && !$index->hasStatus(ENTITY_OVERRIDDEN)) {
    entity_property_info_cache_clear();
    drupal_flush_all_caches();
  }
}

/**
 * Update Search API integration to work with Commerce 1.4
 */
function commerce_kickstart_update_7202() {
  // The price property has changed. A reindex is necessary.
  drupal_load('module', 'search_api');
  $index = search_api_index_load('product_display');
  if (!empty($index) && !$index->hasStatus(ENTITY_OVERRIDDEN)) {
    // Refresh the list of blocks and enable the new Price facet block.
    $default_theme = variable_get('theme_default', 'omega_kickstart');
    drupal_static_reset();
    _block_rehash($default_theme);
    db_update('block')
      ->fields(array('region' => 'sidebar_first', 'status' => 1, 'weight' => -1))
      ->condition('module', 'facetapi')
      ->condition('delta', 'TFVaQKSORCPdrULxfXDnLQZ40xH0Nper')
      ->condition('theme', $default_theme)
      ->execute();

    $index->clear();
    search_api_index_items($index, 100);
  }
  else {
    // The index is overridden and can't be modified, so point the user
    // to the documentation page.
    return '<strong style="color: red">' . t('Important: To complete the update process, please visit http://drupal.org/node/1819842 and follow the instructions.') . '</strong>';
  }
}

/**
 * Remove the old price sort.
 */
function commerce_kickstart_update_7203() {
  $sorts = entity_load('search_api_sort', FALSE, array('field' => 'field_product_commerce_price_amount_float_asc'));
  if (!empty($sorts)) {
    $sort = reset($sorts);
    $sort->delete();
  }
}

/**
 * Enable the commerce_backoffice_content module.
 */
function commerce_kickstart_update_7204() {
  _commerce_kickstart_disable_modules('commerce_kickstart_content_ui');
  drupal_flush_all_caches();
  module_enable(array('commerce_backoffice_content'));
}

/**
 * Replace the collection view by a view based on the product display index.
 */
function commerce_kickstart_update_7205(&$sandbox) {
  $install_demo_store = variable_get('commerce_kickstart_demo_store', FALSE);
  // Batching the update
  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 1;
    $sandbox['max'] = 6;
  }

  if ($sandbox['progress'] == 1) {
    // Enable commerce_kickstart_taxonomy.
    module_enable(array('commerce_kickstart_taxonomy'));
    menu_rebuild();

    $sandbox['progress']++;
  }
  elseif ($sandbox['progress'] == 2) {
    // Disable the old taxonomy/term/% view.
    $view = views_get_view('collection_taxonomy_term');
    if (isset($view->disabled) && $view->disabled === FALSE) {
      views_export_status($view, TRUE);
    }
    $default_theme = variable_get('theme_default', 'omega_kickstart');
    // Set the facets blocks only visibile on the "all products" view.
    db_update('block')
      ->fields(array('pages' => 'products', 'visibility' => BLOCK_VISIBILITY_LISTED))
      ->condition('module', array('facetapi', 'search_api_sorts'))
      ->condition('theme', $default_theme)
      ->execute();

    $sandbox['progress']++;
  }
  elseif ($sandbox['progress'] == 3) {
    // Set up taxonomy main menu..
    if ($install_demo_store) {
      $vocabulary_machine_name = 'collection';
    }
    else {
      $vocabulary_machine_name = 'product_category';
    }
    if (($collection = taxonomy_vocabulary_machine_name_load($vocabulary_machine_name)) && module_exists('taxonomy_menu')) {
      drupal_load('module', 'taxonomy_menu');
      $variable_name = _taxonomy_menu_build_variable('vocab_menu', $collection->vid);
      variable_set($variable_name, 'main-menu');
      $variable_name = _taxonomy_menu_build_variable('path', $collection->vid);
      variable_set($variable_name, 'commerce_kickstart_taxonomy_term_path');
      // Remove the previous menu entries.
      _taxonomy_menu_delete_all($collection->vid);
      // Taxonomy menu links
      $terms = taxonomy_get_tree($collection->vid, 0, 1);
      // Loop through $terms to process each term.
      foreach ($terms as $term) {
        $args = array(
          'term' => $term,
          'menu_name' => 'main-menu',
        );
        $mlid = taxonomy_menu_handler('insert', $args);
      }
    }

    $sandbox['progress']++;
  }
  elseif ($sandbox['progress'] == 4) {
    // Add fields to the index (Needed for the new view).
    drupal_load('module', 'search_api');
    $index = search_api_index_load('product_display');
    if (!empty($index)) {
      $indexed_fields = $index->getFields();
      $options = $index->options;
      if ($index->hasStatus(ENTITY_OVERRIDDEN)) {
        $options['fields'] += array(
          'status' => array(
            'type' => 'integer',
          ),
        );
        if ($install_demo_store) {
          $options['fields'] += array(
            'field_category:name' => array(
              'type' => 'string',
            ),
          );
        }
        if (!$index->update(array('options' => $options))) {
          $sandbox['error_message'] = '<strong style="color: red;">' . t("Important: We couldn't add the new fields to the index.") . '</strong>';
        }
      }
      // Schedule the reindexing.
      $index->clear();
      search_api_index_items($index, 100);
    }

    $sandbox['progress']++;
  }
  elseif ($sandbox['progress'] >= 5) {
    if (empty($sandbox['pathauto'])) {
      // Delete old pathauto aliases that are now no longer valid.
      db_delete('url_alias')
        ->condition('source', db_like('taxonomy/term/') . '%', 'LIKE')
        ->execute();

      $sandbox['pathauto'] = array(
        'sandbox'  => array(),
        'finished' => 0,
      );
    }

    // Generate new aliases by running the pathauto batch.
    module_load_include('inc', 'pathauto', 'pathauto.pathauto');
    taxonomy_pathauto_bulk_update_batch_process($sandbox['pathauto']);

    $sandbox['progress'] += $sandbox['pathauto']['finished'];
  }

  $sandbox['#finished'] = $sandbox['progress'] / $sandbox['max'];
  if (!empty($sandbox['error_message'])) {
    return $sandbox['error_message'];
  }
}

/**
 * Enable the commerce_kickstart_product_ui on the no demo store.
 */
function commerce_kickstart_update_7206() {
  if (!variable_get('commerce_kickstart_demo_store', FALSE)) {
    // Disable the removed lite modules.
    _commerce_kickstart_disable_modules(array('commerce_kickstart_lite_product_ui', 'commerce_kickstart_lite_product_zoom'));
    drupal_flush_all_caches();
    module_enable(array('commerce_kickstart_product_ui'));
  }
}

/**
 * Enable facetapi blocks + assign them in the sidebar_first region.
 */
function commerce_kickstart_update_7207() {
  $default_theme = variable_get('theme_default', 'omega_kickstart');
  _block_rehash($default_theme);
  // Put the facets blocks in the right place.
  db_update('block')
    ->fields(array(
      'region' => 'sidebar_first',
      'pages' => 'products',
      'visibility' => BLOCK_VISIBILITY_LISTED,
      'status' => (int) '1',
    ))
    ->condition('module', 'facetapi')
    ->condition('delta', '0', '<>')
    ->condition('theme', $default_theme)
    ->execute();
}

/**
 * Enable commerce_add_to_cart_confirmation.
 */
function commerce_kickstart_update_7208() {
  module_enable(array('commerce_add_to_cart_confirmation'));
}

/**
 * Check and remove sorts on non indexed fields.
 */
function commerce_kickstart_update_7209() {
  if ($index = search_api_index_load('product_display')) {
    $fields = $index->options['fields'];
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'search_api_sort')
      ->propertyCondition('field', array_keys($fields), 'NOT IN');
    $results = $query->execute();
    if (!empty($results['search_api_sort'])) {
      entity_delete_multiple('search_api_sort', array_keys($results['search_api_sort']));
    }
  }
}

/**
 * Enable automatic title replacement for node and commerce product bundles.
 */
function commerce_kickstart_update_7210() {
  foreach (array('node', 'commerce_product') as $entity_type) {
    $title_settings = array(
      'auto_attach' => array(
        'title' => 'title',
      ),
      'hide_label' => array(
        'entity' => 'entity',
        'page' => 0,
      ),
    );
    variable_set('title_' . $entity_type, $title_settings);
  }
}

/**
 * Enable commerce_message.
 */
function commerce_kickstart_update_7211() {
  module_enable(array('commerce_message'));
}

/**
 * Disable commerce_kickstart_checkout_redirect.
 */
function commerce_kickstart_update_7212() {
  _commerce_kickstart_disable_modules('commerce_kickstart_checkout_redirect');
}

/**
 * Update the admin theme from "Shiny" to "Commerce Kickstart Admin Theme".
 */
function commerce_kickstart_update_7213() {
  if (variable_get('admin_theme', 'shiny') == 'shiny') {
    // Enable the new theme.
    theme_enable(array('commerce_kickstart_admin'));
    variable_set('admin_theme', 'commerce_kickstart_admin');
    drupal_static_reset();
    _block_rehash('commerce_kickstart_admin');

    // Disable all blocks in the content region except "Main page content".
    db_update('block')
      ->fields(array('region' => '-1'))
      ->condition('theme', 'commerce_kickstart_admin')
      ->condition('region', 'content')
      ->condition(db_and()
        ->condition('module', 'system', '<>')
        ->condition('delta', 'main', '<>')
      )
      ->execute();

    // Move help to the correct region.
    db_update('block')
      ->fields(array('region' => 'help'))
      ->condition('module', 'system')
      ->condition('delta', 'help')
      ->condition('theme', 'commerce_kickstart_admin')
      ->execute();

    // Disable the old theme.
    theme_disable(array('shiny'));
  }
}

/**
 * Enable the Commerce Guys Marketplace module.
 */
function commerce_kickstart_update_7214() {
  module_enable(array('commerceguys_marketplace'));
}

/**
 * Disable commerce_kickstart_service_provider.
 */
function commerce_kickstart_update_7215() {
  _commerce_kickstart_disable_modules('commerce_kickstart_service_provider');
}

/**
 * Revert body field to text with summary type.
 */
function commerce_kickstart_update_7216() {
  if (db_table_exists('field_data_body') && !db_field_exists('field_data_body', 'body_summary')) {
    // Force field type change.
    db_update('field_config')
      ->fields(array('type' => 'text_with_summary'))
      ->condition('field_name', 'body')
      ->execute();
    // Add summary field to Body field tables.
    $summary_field = array(
      'type' => 'text',
      'size' => 'big',
      'not null' => FALSE,
    );
    db_add_field('field_data_body', 'body_summary', $summary_field);
    db_add_field('field_revision_body', 'body_summary', $summary_field);
    // Revert field components of features with body field features.
    $modules = array_filter(array('commerce_kickstart_product', 'commerce_kickstart_lite_product', 'commerce_kickstart_blog'), 'module_exists');
    $revert = array();
    foreach ($modules as $module) {
      $revert[$module][] = 'field';
    }
    if (!empty($revert)) {
      features_revert($revert);
    }
  }
}

/**
 * Enable Inline Conditions (Needed by Commerce Discount).
 */
function commerce_kickstart_update_7217() {
  if (module_exists('commerce_discount')) {
    module_enable(array('inline_conditions'));
  }
}

/**
 * Remove jirafe.
 */
function commerce_kickstart_update_7218() {
  _commerce_kickstart_disable_modules(array('jirafe'));
  variable_del('jirafe_config');
  variable_del('jirafe_create_account_link');
}
