<?php
/**
 * @file
 * This module will make the alter the user and site timezone forms to
 * select a timezone name instead of a timezone offset.
 *
 * This module won't be needed once core starts tracking timezone names
 * instead of offsets.
 */

/**
 * Make sure a timezone has been selected.
 */
function date_timezone_init() {
  $tz_name = variable_get('date_default_timezone_name', NULL);
  if (!empty($user->uid) && $_GET['q'] != 'admin/settings/date-time' && empty($tz_name)) {
    drupal_set_message(t('The Date Timezone module requires you to <a href="@link">set the site timezone name</a>.', array('@link' => url('admin/settings/date-time'))), 'error');
  }
}

/**
 * Implementation of hook_menu().
 */
function date_timezone_menu() {
  $items = array();
  $items['user/timezone'] = array(
    'title' => 'User timezone',
    'page callback' => 'user_timezone',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implementation of hook_form_alter().
 *
 * Override system handling of user and site timezone selection.
 */
function date_timezone_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'system_date_time_settings') {
    date_timezone_site_form($form);
    if (!isset($form['#after_build'])) {
      $form['#after_build'] = array();
    }
    $form['#after_build'][] = 'date_timezone_site_form_after_build';
  }
  elseif ($form_id == 'user_profile_form' && variable_get('configurable_timezones', 1) && isset($form['timezone'])) {
    date_timezone_user_form($form);
    if (!isset($form['#after_build'])) {
      $form['#after_build'] = array();
    }
    $form['#after_build'][] = 'date_timezone_user_form_after_build';  
  }
}

/**
 * Create a form for the site timezone names.
 * Display a list of timezone names instead of offsets.
 */
function date_timezone_site_form(&$form) {
  drupal_add_js(drupal_get_path('module', 'date_timezone') .'/date_timezone.js');
  $form['locale']['#element_validate'] = array('date_timezone_update_site');

  $timezone = variable_get('date_default_timezone_name', NULL);
  $form['locale']['date_default_timezone_name'] = array(
    '#type' => 'select',
    '#title' => t('Default time zone'),
    '#default_value' => $timezone,
    '#options' => date_timezone_names(FALSE, TRUE), // Force an update before setting a site default.
    '#description' => t('Select the default site time zone. If in doubt, choose the timezone that is closest to your location which has the same rules for daylight saving time.'),
    '#weight' => -10,
    '#offset' => variable_get('date_default_timezone', 0),
  );
  // Add the JavaScript callback to automatically set the timezone.
  if (empty($timezone)) {
    drupal_add_js('
// Global Killswitch
if (Drupal.jsEnabled) {
  $(document).ready(function() {
    Drupal.setDefaultTimezone();
  });
}', 'inline');
  } 
  return $form;
}

/**
 * Hide the original form.
 * 
 * We have to do this in after_build in case the Event module
 * is enabled since the Event module will do its form_alter()
 * after the Date module.
 */
function date_timezone_site_form_after_build(&$form) {

  // Set the value, and make sure it's a legal value.
  $value = $form['locale']['date_default_timezone']['#default_value'];
  $options = $form['locale']['date_default_timezone']['#options'];
  if (!array_key_exists($value, $options)) {
    //$value = array_pop($options);
    $value = NULL;
  }
  $form['locale']['date_default_timezone']['#type'] = 'hidden';
  $form['locale']['date_default_timezone']['#value'] = $value;
  return $form;  
}

/**
 * Create a form for the site timezone names.
 * Display a list of timezone names instead of offsets.
 */
function date_timezone_user_form(&$form) {
  drupal_add_js(drupal_get_path('module', 'date_timezone') .'/date_timezone.js');

  $account = $form['_account']['#value'];
  $form['timezone']['#uid'] = $account->uid;
  $form['timezone']['#element_validate'] = array('date_timezone_update_user');

  $timezone = $account->timezone_name ? $account->timezone_name : variable_get('date_default_timezone_name', NULL);
  $form['timezone']['timezone_name'] = array(
    '#type' => 'select',
    '#title' => t('Default time zone'),
    '#default_value' => $timezone,
    '#options' => date_timezone_names(),
    '#description' => t('Select your current local time. If in doubt, choose the timezone that is closest to your location which has the same rules for daylight saving time. Dates and times throughout this site will be displayed using this time zone.'),
  );
  // Add the JavaScript callback to automatically set the timezone.
  if (empty($timezone)) {
    drupal_add_js('
// Global Killswitch
if (Drupal.jsEnabled) {
  $(document).ready(function() {
    Drupal.setDefaultTimezone();
  });
}', 'inline');
  }  
  return $form;
}

/**
 * Hide the original form.
 * 
 * We have to do this in after_build in case the Event module
 * is enabled since the Event module will do its form_alter()
 * after the Date module.
 */
function date_timezone_user_form_after_build($form) {
  // Set the value, and make sure it's a legal value.
  $value = $form['timezone']['timezone']['#default_value'];
  $options = $form['timezone']['timezone']['#options'];
  if (!array_key_exists($value, $options)) {
    //$value = array_pop($options);
    $value = NULL;
  }
  $form['timezone']['timezone']['#type'] = 'hidden';
  $form['timezone']['timezone']['#value'] = $value;
  return $form;
}

/**
 * Callback from site timezone settings form to update site timezone info.
 * When the timezone name is updated, update the offset as well.
 */
function date_timezone_update_site($element, &$form_state) {
  $timezone = $element['date_default_timezone_name']['#value'];
  if (empty($timezone)) {
    $offset = $element['date_default_timezone_name']['#offset'];
  }
  else {
    variable_set('date_default_timezone_name', $timezone);
    $date = date_make_date('now', $timezone);
    $offset = date_offset_get($date);
  }

  // Reset the original form to the expected value.
  if (module_exists('event') && db_table_exists('event_timezones')) {
    $event_zone = date_event_zonelist_by_name(str_replace('_', ' ', $timezone));
    // The event module will update the timezone and zone id, using this value.
    if (!empty($event_zone['timezone'])) {
        form_set_value($element['date_default_timezone'], $event_zone['timezone'] .'|'. $offset, $form_state);
    } else {
        form_set_value($element['date_default_timezone'], $offset, $form_state); 
    }
  }
  else {
    form_set_value($element['date_default_timezone'], $offset, $form_state);
  }
}

/**
 * Callback from user timezone settings form to update user timezone info.
 * When the timezone name is updated, update the offset as well.
 */
function date_timezone_update_user($element, &$form_state) {
  $timezone = $element['timezone_name']['#value'];
  if (!empty($timezone)) {
    $date = date_make_date('now', $timezone);
    $offset = date_offset_get($date);
  }

  // Reset the original form to the expected value.
  if (module_exists('event') && db_table_exists('event_timezones')) {
    $event_zone = date_event_zonelist_by_name(str_replace('_', ' ', $timezone));
    // The event module will update the timezone and zone id using this value.
    if (!empty($event_zone['timezone'])) {
        form_set_value($element['timezone'], $event_zone['timezone'] .'|'. $offset, $form_state);
    } else {
        form_set_value($element['timezone'], $offset, $form_state); 
    }
  }
  else {
    form_set_value($element['timezone'], $offset, $form_state);
  }
}

/**
 * Update the site timezone offset when cron runs.
 * 
 * This is to make sure that modules that rely on the timezone offset
 * have current information to process.
 */
function date_timezone_cron() {
  $date = date_now(variable_get('date_default_timezone_name', NULL));
  $offset = date_offset_get($date);
  if ($offset != variable_get('date_default_timezone', 0)) {
    variable_set('date_default_timezone', $offset);
  }
}

/**
 * Update user timezone information at login.
 * 
 * This is to make sure that modules that rely on the timezone offset
 * have current information to process.
 */
function date_timezone_user($op, &$edit, &$account, $category = NULL) {
  if (isset($account->uid) && $op == 'login' && variable_get('configurable_timezones', 1)) {
    if (strlen($account->timezone_name)) {
      $date = date_now($account->timezone_name);
      $offset = date_offset_get($date);
      if ($offset != $account->timezone) {
        $account->timezone = $offset;
        db_query("UPDATE {users} SET timezone='%s' WHERE uid = %d", $offset, $account->uid);
      }
    }
    else {
      // If the user doesn't already have a timezone name selected, 
      // default it to the site timezone name and offset.
      $timezone = variable_get('date_default_timezone_name', NULL);
      if (!empty($timezone)) {
        $date = date_now($timezone);
        $offset = date_offset_get($date);
        db_query("UPDATE {users} SET timezone_name = '%s', timezone='%s' WHERE uid = %d", $timezone, $offset, $account->uid);
      }
    }
  }
}

/**
 * Menu callback; Retrieve a JSON object containing a suggested time 
 * zone name.
 */
function user_timezone($abbreviation = '', $offset = -1, $is_daylight_saving_time = NULL) {
  // An abbreviation of "0" passed in the callback arguments should be 
  // interpreted as the empty string.
  $abbreviation = $abbreviation ? $abbreviation : '';
  $timezone = function_exists('timezone_name_from_abbr') ? timezone_name_from_abbr($abbreviation, intval($offset), $is_daylight_saving_time) : 'UTC';
  // The client date is passed in for debugging purposes.
  $date = isset($_GET['date']) ? $_GET['date'] : '';
  // Log a debug message.
  watchdog('timezone', 'Detected time zone: %timezone; client date: %date; abbreviation: %abbreviation; offset: %offset; daylight saving time: %is_daylight_saving_time.', array('%timezone' => $timezone, '%date' => $date, '%abbreviation' => $abbreviation, '%offset' => $offset, '%is_daylight_saving_time' => $is_daylight_saving_time));
  drupal_json($timezone);
}

/**
 * Create replacement values for deprecated timezone names.
 */
function date_timezone_replacement($old) {
  ('./'. drupal_get_path('module', 'date_timezone') .'/date_timezone.install');
  return _date_timezone_replacement($old);
}

/**
 * Helper function to update Event module timezone information.
 */
function date_event_zonelist_by_name($name) {
  if (!module_exists('event') || !db_table_exists('event_timezones')) {
    return array();
  }
  static $zone_names = array();

  if (!isset($zone_names[$name])) {
    $zone = db_fetch_array(db_query("SELECT * FROM {event_timezones} WHERE name = '%s'", $name));
    $zone_names[$name] = $zone;
  }

  return $zone_names[$name];
}
