_dbf_headers

geo/includes/shp2sql.inc, line 123

Versions
6
_dbf_headers(&$fp, &$schema)

Code

<?php
function _dbf_headers(&$fp, &$schema) {

  // Crack open the dbf file for processing.
  $data = zip_entry_read($fp, 32);

  // Set basic headers.
  $headers = unpack('H2db_id/Cy/Cm/Cd/Lcount/Sheader_size/Srecord_size', $data);
  $date = $headers['m'] .'/'. $headers['d'] .'/'. $headers['y'] + 1900;
  $headers['date'] = strtotime($date);

  // Get the remainder of the dbf headers.
  $field_data = zip_entry_read($fp, $headers['header_size'] - 32);

  $type_map = array(
    'C' => 'char',
    'N' => 'int',
    'L' => 'int',
    'D' => 'date',
    'M' => 'text',
    'F' => 'float',
    'B' => 'blob',
    'Y' => 'decimal',
    'P' => 'blob',
    'I' => 'int',
    'Y' => 'decimal',
    'T' => 'datetime',
    'V' => 'varchar',
    'X' => 'varchar',
    '@' => 'timestamp',
    '0' => 'decimal',
    '+' => 'serial',
  );

  // Gather the column definitions from the field headers.
  $mask = 'A11name/Atype/x4/Clength/Cprecision';
  while (strlen($field_data) >= 32) {
    $d = unpack($mask, $field_data);
    $field_data = substr($field_data, 32);

    // Field name.
    $name = drupal_convert_to_utf8(strtolower(trim($d['name'])), 'ascii');
    $name = preg_replace('/[^a-z0-9_]/', '', $name);

    // Datatype.
    $type = isset($type_map[$d['type']]) ? $type_map[$d['type']] : 'varchar';
    if ($type == 'char' && $d['length'] > 3) $type = 'varchar';

    // Default data processing function, which will escape and UTF8 convert.
    $filter = '_shp_data_text';

    // Use all-purpose PHP functions for standard numeric types.
    if (in_array($type, array('float', 'decimal'))) $filter = 'floatval';
    if (in_array($type, array('int', 'timestamp', 'serial'))) $filter = 'intval';
    if ($type == 'date') $filter = '_shp_data_date';

    // Special case for boolean, convert to int.
    if ($d['type'] == 'L') $filter = '_shp_data_bool';

    $headers['field_filters'][$name] = $filter;

    // Datatype futzing.
    $schema['fields'][$name] = array('type' => $type, 'length' => $d['length']);
    if ($d['precision']) {
      $schema['fields'][$name]['not null'] = TRUE;
      $schema['fields'][$name]['default'] = 0.0;
    }

    // Remove precision from simple types.
    if (in_array($type, array('int', 'float', 'real', 'timestamp'))) {
      unset($schema['fields'][$name]['length']);
    }

    // Store field length for processing.
    $headers['field_lengths'][$name] = $d['length'];
  }

  unset($headers['y'], $headers['m'], $headers['d'], $headers['header_size']);
  return $headers;
}
?>