You are here

function smart_ip_update_database in Smart IP 7.2

Same name and namespace in other branches
  1. 6.2 includes/smart_ip.utility.inc \smart_ip_update_database()
  2. 6 includes/smart_ip.utility.inc \smart_ip_update_database()
  3. 7 includes/smart_ip.utility.inc \smart_ip_update_database()
2 string references to 'smart_ip_update_database'
smart_ip_update_db_batch in includes/smart_ip.utility.inc
Prepare a batch definition
_smart_ip_database_update_validate in includes/smart_ip.admin.inc
Validation handler to update the Smart IP database.

File

includes/smart_ip.utility.inc, line 250
Utility routines to load the Smart IP database.

Code

function smart_ip_update_database(&$context) {

  // If this update was aborted in a previous step, or has a dependency that
  // was aborted in a previous step, go no further.
  if (isset($context['results']['#abort'])) {
    return;
  }
  $fp = @fopen($context['results']['#blocks_csv_file'], 'r');
  if ($fp === FALSE) {
    unset($context['results']['#blocks_csv_file']);

    // Error occured then stop the process
    $message = t('Opening CSV file %file failed.', array(
      '%file' => $context['results']['#blocks_csv_file'],
    ));
    $context['results']['#abort'] = $message;
    $context['message'] = $message;
    unset($context['results']['#blocks_csv_file']);
    variable_set('smart_ip_extract_zip_done', FALSE);
    variable_set('smart_ip_get_zip_done', FALSE);
    variable_set('smart_ip_store_location_csv_done', FALSE);
  }
  else {
    if (!isset($context['sandbox']['#blocks_csv_pointer'])) {
      $blocks_csv_pointer = variable_get('smart_ip_blocks_csv_pointer', 0);
      if ($blocks_csv_pointer) {
        @fseek($fp, $blocks_csv_pointer);
      }
      else {
        if (db_table_exists('smart_ip_update_table')) {

          // The temporary working table for updating Smart IP database already exist, truncate it.
          $result = db_truncate('smart_ip_update_table')
            ->execute();
        }
        else {
          module_load_install('smart_ip');

          // Add temporary working table for updating Smart IP database.
          db_create_table('smart_ip_update_table', smart_ip_schema_definition_array());
        }

        // Record the last pointer
        $fp_check = @fopen($context['results']['#blocks_csv_file'], 'r');
        @fseek($fp_check, -1, SEEK_END);
        variable_set('smart_ip_blocks_csv_last_pointer', @ftell($fp_check));
      }
    }
    else {
      @fseek($fp, $context['sandbox']['#blocks_csv_pointer']);
    }
    $data = @fgetcsv($fp);
    $context['sandbox']['#blocks_csv_pointer'] = @ftell($fp);
    if (@feof($fp)) {
      @fclose($fp);

      // Update our progress information.
      $context['finished'] = TRUE;
      $context['message'] = t('Processing %blocks done', array(
        '%blocks' => basename($context['results']['#blocks_csv_file']),
      ));
      unset($context['results']['#blocks_csv_file']);

      // Tasks completed. Reset the recovery mode indicators.
      variable_set('smart_ip_get_zip_done', FALSE);
      variable_set('smart_ip_extract_zip_done', FALSE);
      variable_set('smart_ip_store_location_csv_done', FALSE);
    }
    else {
      $current_pointer = $context['sandbox']['#blocks_csv_pointer'];
      $last_pointer = variable_get('smart_ip_blocks_csv_last_pointer', 0);
      $estimated_progress = floor(100 * ($current_pointer / $last_pointer)) - 2;

      // Update our progress information.
      $context['finished'] = $estimated_progress / 100;
      $context['message'] = t('Parsing %blocks at file pointer number: @value of @end', array(
        '%blocks' => basename($context['results']['#blocks_csv_file']),
        '@value' => $current_pointer,
        '@end' => $last_pointer,
      ));
    }
    if (count($data) == 3 && is_numeric($data[2])) {
      variable_set('smart_ip_blocks_csv_pointer', $context['sandbox']['#blocks_csv_pointer']);
      $location = cache_get('smart_ip:' . $data[2], 'cache_smart_ip');
      if (isset($location->data['country_code'])) {
        try {

          // Insert GeoIP into the temporary working Smart IP database table
          db_insert('smart_ip_update_table')
            ->fields(array(
            'geoip_id',
            'ip_ref',
            'country_code',
            'region',
            'city',
            'zip',
            'latitude',
            'longitude',
          ))
            ->values(array(
            'geoip_id' => $data[2],
            'ip_ref' => min($data[0], $data[1]),
            'country_code' => strtoupper($location->data['country_code']),
            'region' => strtoupper($location->data['region']),
            'city' => $location->data['city'],
            'zip' => $location->data['zip'],
            'latitude' => $location->data['latitude'],
            'longitude' => $location->data['longitude'],
          ))
            ->execute();
        } catch (Exception $error) {
          db_update('smart_ip_update_table')
            ->fields(array(
            'geoip_id' => $data[2],
            'country_code' => strtoupper($location->data['country_code']),
            'region' => strtoupper($location->data['region']),
            'city' => $location->data['city'],
            'zip' => $location->data['zip'],
            'latitude' => $location->data['latitude'],
            'longitude' => $location->data['longitude'],
          ))
            ->condition('ip_ref', min($data[0], $data[1]))
            ->execute();
        }
      }
    }

    // This lines of code should be here to ensure cache_get()
    // above will return non-empty value
    if ($context['finished'] === TRUE) {

      // Clear the Smart IP production table
      db_drop_table('smart_ip');

      //db_query('TRUNCATE TABLE {smart_ip}');

      //db_truncate('smart_ip')->execute();

      // Rename temporary working Smart IP database table to production table name {smart_ip}
      db_rename_table('smart_ip_update_table', 'smart_ip');

      // 'RENAME TABLE {smart_ip_update_table} TO {smart_ip}'
      cache_clear_all('smart_ip:', 'cache_smart_ip', TRUE);
      variable_set('smart_ip_blocks_csv_pointer', 0);
      variable_set('smart_ip_last_update', REQUEST_TIME);
      watchdog('smart_ip', 'Smart IP Database successfuly updated from maxmind.com.');
    }
  }
}