<?php

/**
 * @file
 * Provides geographical location for Drupal log event's hostname 
 * (Recent log messages and Recent hits).
 *
 * @author Roland Michael dela Peņa.
 */
 
define('GEOLOCATE_LOGS_DEFAULT_WHOIS_SOURCE', 'http://whois.domaintools.com');
 
/******************************************************************************
 * Drupal Hooks                                                               *
 ******************************************************************************/
/**
 * Implements hook_help().
 */
function geolocate_logs_help($path, $arg) {
  switch ($path) {
    case 'admin/help#geolocate_logs':
      return '<p>' . 
      t("Provides geographical location for Drupal log event's hostname
      (!dblog and !stat) and whois lookup for hostname using any free external 
      site offering whois service (like http://whois.sc or http://whois.domaintools.com). 
      This module uses the IP to geographical location (longitude/latitude), country, 
      region, city and postal code capability of Smart IP..", array(
        '!dblog' => l(t('Recent log messages'), 'admin/reports/dblog'),
        '!stat'  => l(t('Recent hits'), 'admin/reports/hits'),
      )) . '</p>';
      break;
  }
}

/**
 * Implements hook_form_alter()
 */
function geolocate_logs_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'smart_ip_admin_settings') {
    $form['smart_ip_preferences']['geolocate_logs_whois_source'] = array(
      '#title'         => t("Whois source for Drupal log event's hostname lookup"),
      '#type'          => 'textfield',
      '#size'          => 120,
      '#description'   => t('Enter a valid URL. Ex. %url', array('%url' => GEOLOCATE_LOGS_DEFAULT_WHOIS_SOURCE)),
      '#default_value' => variable_get('geolocate_logs_whois_source', GEOLOCATE_LOGS_DEFAULT_WHOIS_SOURCE),
    );
    $form['#validate'][] = '_geolocate_logs_url_validate';
  }
}

/**
 * Validation handler.
 */
function _geolocate_logs_url_validate($form, &$form_state) {
  if (!valid_url($form_state['values']['geolocate_logs_whois_source'])) {
    form_set_error('geolocate_logs_whois_source', t('Whois source URL format is not valid'));
  }
  else {
    $form_state['values']['geolocate_logs_whois_source'] = rtrim(check_url($form_state['values']['geolocate_logs_whois_source']), '/');
  }
}

/**
 * Implements hook_theme()
 */
function geolocate_logs_theme() {
  return array(
    'geolocate_logs_event_log' => array(
      'render element' => 'log_row_build',
      'template'       => 'geolocate-logs-event-log',
      'path'           => drupal_get_path('module', 'geolocate_logs') . '/theme',
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function geolocate_logs_menu_alter(&$items) {
  $items['admin/reports/event/%']['page callback']  = 'geolocate_logs_dblog_event';
  $items['admin/reports/access/%']['page callback'] = 'geolocate_logs_statistics_access_log';
}

/**
 * An override of dblog_event() at modules/dblog/dblog.admin.inc
 * Menu callback; displays details about a log message.
 *
 * @see dblog_event()
 */
function geolocate_logs_dblog_event($id) {
  if (function_exists('dblog_event')) {
    module_load_include('inc', 'dblog', 'dblog.admin');
  }
  $log_build = dblog_event($id);
  $log_build['dblog_table']['#rows'] = geolocate_logs_build_log($log_build['dblog_table']['#rows']);
  return $log_build;
}

/**
 * An override of statistics_access_log() at modules/statistics/statistics.admin.inc
 * Page callback: Gathers page access statistics suitable for rendering.
 *
 * @param $aid
 *   The unique accesslog ID.
 *
 * @return
 *   A render array containing page access statistics. If information for the
 *   page was not found, drupal_not_found() is called.
 * @see statistics_access_log()
 */
function geolocate_logs_statistics_access_log($aid) {
  if (function_exists('statistics_access_log')) {
    module_load_include('inc', 'statistics', 'statistics.admin');
  }
  $log_build = statistics_access_log($aid);
  $log_build['statistics_table']['#rows'] = geolocate_logs_build_log($log_build['statistics_table']['#rows']);
  return $log_build;
}

/******************************************************************************
 * Helper Functions                                                           *
 ******************************************************************************/

/**
 * Include Geolocation details of hostname.
 */
function geolocate_logs_build_log($rows) {
  foreach ($rows as &$row) { 
    foreach ($row as $index => $details) {
      if (isset($details['data']) && $details['data'] == t('Hostname')) {        
        $hostname = $row[1];
        $location = smart_ip_get_location($hostname);
        $row[1]   = theme('geolocate_logs_event_log', array(
            'log_row_build' => array(
              'hostname' => $hostname,
              'location' => $location,
              'whois_source' => variable_get('geolocate_logs_whois_source', GEOLOCATE_LOGS_DEFAULT_WHOIS_SOURCE),
            ),
          ));
      }
    }
  }
  return $rows;
}