<?php
// $Id$

/**
 * @file
 *
 */

function bcd_settings() {
  
  include_once DRUPAL_ROOT . '/includes/locale.inc';
  $options[0] = t('- None -');
  $options += country_get_list();
  $form['bcd_country'] = array(
    '#type' => 'select',
    '#title' => t('Restrict maps to country'),
    '#options' => $options,
    '#default_value' => variable_get('bcd_country', FALSE),
  );
  
  $form['bcd_visitor_map_zoom'] = array(
    '#type' => 'select',
    '#title' => t('Zoom level for visitor map'),
    '#options' => array(
      1 => '1 world',
      2 => '2 continent',
      3 => '3 country - large',
      4 => '4 country - medium',
      5 => '5 country - small',
      6 => '6 state - large',
      7 => '7 state - medium',
      8 => '8 state - small',
      9 => '9 metro area',
      10 => '10 city - large',
      11 => '11 city - medium',
      12 => '12 city - small',
      13 => '13 town',
      14 => '14 street grid',
      15 => '15 street names',
      16 => '16 block',
      17 => '17 building',
    ),
    '#default_value' => variable_get('bcd_visitor_map_zoom', 8),
  );
  
// TODO: Re-integrate maxmind database after http://drupal.org/node/1085508
// TODO: AND make sure that it works on nginx or apache with other APIs installed
//  $geoip_status = bcd_geoip_status();
//  foreach ($geoip_status['warnings'] as $var => $text) {
//    if (!$geoip_status['checks'][$var]) {
//      drupal_set_message($text, 'warning', FALSE);
//    }
//  }
//  $output = '<style>.listing{width:95px;display:inline-block;}.bcd{font-weight:bold;padding-left:9px;}.ok{color:green}.warn{color:salmon;}</style>';
//  foreach ($geoip_status['output'] as $k => $v) {
//    $output .= "<span class='listing'>$k : </span>$v<br/>";
//  }
//  $form['maxmind'] = array(
//    '#type' => 'fieldset',
//    '#title' => t('Status of GeoIP File'),
//  );
//  $form['maxmind']['text'] = array(
//    '#type' => 'markup',
//    '#markup' => $output,
//  );
//  $form['maxmind']['updatemaxmind'] = array(
//    '#type' => 'submit',
//    '#value' => t('Update GeoLiteCity.dat'),
//  );
  $form = system_settings_form($form);
  return $form;
}

function bcd_settings_submit(&$form, &$form_state) {
  // Download and save the current version of the GeoLiteCity database from Maxmind
  if ($form_state['clicked_button']['#value'] == t('Update GeoLiteCity.dat')) {
    if (bcd_update_maxmind()) {
      variable_set('bcd_last_maxmind_update', format_date(REQUEST_TIME, 'custom', 'Y-m-d'));
      drupal_set_message(t('The GeoLiteCity database has been successfully updated.'));
    }
    else {
      drupal_set_message(t('The GeoLiteCity database update failed!'), 'warning');
    }
  }
}

// MAXMIND / GEOIP FUNCTIONS
/**
 * Gets the status of the maxmind geoip file.
 */
function bcd_geoip_status() {
  // check the location of the geoip data file
  if (module_exists('geoip')) {
    $geoip_file = geoip_data_file();
    if (!stripos($geoip_file, '://')) {
      $geoip_file = getcwd() . '/' . $geoip_file;
    }
  }
  $file = $path = 'public://GeoLiteCity.dat';
  $same = $geoip_file == $file;
  $fileok = is_writable($path);
  if ($fileok) {
    $size = filesize($file);
    $sizeok = ($size > 14000000);
    $time = filectime($file);
    $timeok = $time > (REQUEST_TIME - (60 * 60 * 24 * 36));
    $dir = $path = 'public://';
    $dirstat = file_prepare_directory($path);
    $dirok = ($dirstat != FALSE);
  }
  else {
    $size = 0;
    $sizeok = FALSE;
    $time = 0;
    $timeok = FALSE;
    $dir = $path = 'public://';
    $dirstat = file_prepare_directory($path);
    $dirok = ($dirstat != FALSE);
  }
  $update = variable_get('bcd_last_maxmind_update', 0);
  $update = ($update == 0) ? t('Never') : $update;
  $report = array(
    0 => '<span class="bcd warn">Warning!</span>',
    1 => '<span class="bcd ok">OK</span>',
  );
  $output = array(
    'Expected' => $file . $report[$fileok],
    'Actual' => $geoip_file . $report[$same],
    'Directory' => $dir . $report[$dirok],
    'Size' => round(($size / 1024000), 0) . ' Mb' . $report[$sizeok],
    'Time' => format_date($time, 'medium') . $report[$timeok],
    'Updated' => $update,
  );
  $warnings = array(
    'same' => t('Please check the geoip file location at <a href="/admin/settings/geoip">admin/settings/geoip</a>.'),
    'sizeok' => t('The GeoLiteCity.dat file appears to be too small.'),
    'timeok' => t('The GeoLiteCity.dat file needs to be updated.'),
    'dirok' => t('The directory for GeoLiteCity is not writeable.'),
    'fileok' => t('The GeoLiteCity.dat file is not writeable.'),
  );
  $ret = array(
    'status' => ($same && $sizeok && $timeok && $dirok && $fileok),
    'output' => $output,
    'warnings' => $warnings,
  );
  foreach (array('same', 'sizeok', 'timeok', 'dirok', 'fileok') as $var) {
    $ret['checks'][$var] = $$var;
  }
  return $ret;
}

/**
 * Updates the geoip database from maxmind.
 */
function bcd_update_maxmind() {
  $file = 'public://GeoLiteCity.dat';
  copy('compress.zlib://http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz', $file);
  chmod($file, 0777);
  if (is_writable($file)) {
    if (filesize($file) > 29000 && filectime($file) > (REQUEST_TIME - 60)) {
      return TRUE;
    }
  }
}
