function countries_csv_updates in Countries 7.2
Same name and namespace in other branches
- 7 countries.admin.inc \countries_csv_updates()
Parses the given CSV file.
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 431 - Admin page callbacks for the Countries module.
Code
function countries_csv_updates($file = NULL, $defaults = array()) {
if (!$file) {
$file = variable_get('countries_csv_datasource', drupal_get_path('module', 'countries') . '/countries.csv');
}
$defaults += array(
'name' => '',
'official_name' => '',
'enabled' => 0,
'iso2' => '',
'iso3' => '',
'numcode' => 0,
'continent' => 'UN',
);
$countries = array();
$inserts = array();
$updates = array();
$skipped = array();
if ($handle = @fopen($file, "r")) {
$headers = fgetcsv($handle, 1024, ",");
while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
$country = new StdClass();
$errors = array();
foreach ($row as $index => $value) {
if (!isset($defaults[$headers[$index]])) {
continue;
}
$key = $headers[$index];
$value = trim($value);
// We need special processing for the enabled key.
if ($key == 'enabled') {
if (strlen($value) && $value != 'NULL') {
$country->{$key} = empty($value) ? 0 : 1;
}
}
elseif (empty($value) || $value == 'NULL') {
// Skip setting defaults until we check existing countries later.
}
elseif ($error = countries_property_invalid($key, $value)) {
$errors[] = $error;
}
else {
if ($key == 'name' || $key == 'official_name') {
// Enable translation of country names during importation.
$value = t($value);
}
$country->{$key} = $value;
}
}
if (!empty($country->iso2)) {
// Validating the data as the source can not longer be trusted.
if (empty($errors)) {
$countries[$country->iso2] = $country;
}
else {
$skipped[$country->iso2] = $errors;
}
}
}
fclose($handle);
}
foreach ($countries as $country) {
if ($existing = country_load($country->iso2)) {
foreach ($defaults as $key => $default_value) {
// The only empty value we update is enabled.
if (empty($country->{$key}) && $key != 'enabled') {
continue;
}
if (!isset($existing->{$key})) {
continue;
}
if (!isset($country->{$key})) {
$country->{$key} = $existing ? $existing->{$key} : $default_value;
}
if ($key == 'name' || $key == 'official_name') {
$existing->{$key} = t($existing->{$key});
}
if ((string) $existing->{$key} !== (string) $country->{$key}) {
$updates[$country->iso2][$key] = array(
'new' => $country->{$key},
'old' => $existing->{$key},
);
}
}
}
else {
$country = (object) ((array) $country + $defaults);
$inserts[$country->iso2] = $country;
}
}
return array(
'inserts' => $inserts,
'updates' => $updates,
'skipped' => $skipped,
);
}