You are here

function countries_csv_updates in Countries 7

Same name and namespace in other branches
  1. 7.2 countries.admin.inc \countries_csv_updates()
1 call to countries_csv_updates()
countries_admin_import_form in ./countries.admin.inc
Menu callback to update the database from the CSV file.

File

./countries.admin.inc, line 445
Admin page callbacks for the Countries module.

Code

function countries_csv_updates($file = NULL) {
  if (!$file) {
    $file = drupal_get_path('module', 'countries') . '/countries.csv';
  }
  $countries = array();
  $handle = fopen($file, "r");
  $headers = fgetcsv($handle, 1024, ",");
  while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
    $row[0] = trim($row[0]);

    // iso2
    $row[1] = empty($row[1]) || $row[1] == 'NULL' ? '' : trim($row[1]);

    // iso3
    $row[2] = empty($row[2]) || $row[2] == 'NULL' ? '' : trim($row[2]);

    // name
    $row[3] = empty($row[3]) || $row[3] == 'NULL' ? '' : trim($row[3]);

    // official name
    $row[4] = empty($row[4]) || $row[4] == 'NULL' ? 0 : trim($row[4]);

    // number code
    $row[5] = empty($row[5]) || $row[5] == 'NULL' ? 'UN' : trim($row[5]);

    // continent
    $row[6] = empty($row[6]) || $row[6] == 'NULL' ? '0' : '1';

    // enabled
    if (!empty($row[0]) && $row[0] != 'NULL') {
      $countries[$row[0]] = array(
        'iso2' => $row[0],
        'iso3' => $row[1],
        'name' => $row[2],
        'official_name' => $row[3],
        'numcode' => $row[4],
        'continent' => $row[5],
        'enabled' => $row[6],
      );
    }
  }
  fclose($handle);
  $inserts = array();
  $updates = array();
  foreach ($countries as $country) {
    $country = (object) $country;
    if ($existing = country_load($country->iso2)) {
      foreach (array(
        'iso3',
        'name',
        'official_name',
        'numcode',
        'continent',
        'enabled',
      ) as $key) {
        if (empty($country->{$key}) && $country->{$key} !== '0') {
          continue;
        }
        if ($existing->{$key} !== $country->{$key}) {
          $updates[$country->iso2][$key] = array(
            'new' => $country->{$key},
            'old' => $existing->{$key},
          );
        }
      }
    }
    else {
      $inserts[$country->iso2] = $country;
    }
  }
  return array(
    'inserts' => $inserts,
    'updates' => $updates,
  );
}