You are here

function tablefield_export_csv in TableField 7.3

Same name and namespace in other branches
  1. 7.2 tablefield.module \tablefield_export_csv()

Menu callback to export a table as a CSV.

Parameters

string $entity_type: The type of entity, e.g. node.

string $entity_id: The id of the entity.

string $field_name: The machine name of the field to load.

string $langcode: The language code specified.

string $delta: The field delta to load.

1 string reference to 'tablefield_export_csv'
tablefield_menu in ./tablefield.module
Implements hook_menu().

File

./tablefield.module, line 98
Provides a set of fields that can be used to store tabular data with a node.

Code

function tablefield_export_csv($entity_type, $entity_id, $field_name, $langcode, $delta) {

  // Ensure this is a tablefield.
  $field_info = field_info_field($field_name);
  if (!$field_info || $field_info['type'] != 'tablefield') {
    return drupal_not_found();
  }

  // Attempt to load the entity.
  $entities = entity_load($entity_type, array(
    $entity_id,
  ));
  if (empty($entities)) {
    return MENU_NOT_FOUND;
  }
  $entity = reset($entities);

  // Ensure the user has access to view this field on this entity.
  if (!_tablefield_entity_access('view', $entity_type, $entity) || !field_access('view', $field_info, $entity_type, $entity)) {
    return MENU_ACCESS_DENIED;
  }
  $filename = sprintf('%s_%s_%s_%s_%s.csv', $entity_type, $entity_id, $field_name, $langcode, $delta);
  $uri = 'temporary://' . $filename;

  // Ensure that the data is available and that we can load a
  // temporary file to stream the data.
  if (isset($entity->{$field_name}[$langcode][$delta]['value']) && ($fp = fopen($uri, 'w+'))) {
    $table = unserialize($entity->{$field_name}[$langcode][$delta]['value']);

    // Save the data as a CSV file.
    foreach ($table['tabledata'] as $row) {

      // Remove the weight column.
      array_pop($row);
      fputcsv($fp, $row, variable_get('tablefield_csv_separator', ','));
    }
    fclose($fp);

    // Add basic HTTP headers.
    $http_headers = array(
      'Content-Type' => 'text/csv',
      'Content-Disposition' => 'attachment; filename="' . $filename . '"',
      'Content-Length' => filesize($uri),
    );

    // IE needs special headers.
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
      $http_headers['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0';
      $http_headers['Pragma'] = 'public';
    }
    else {
      $http_headers['Pragma'] = 'no-cache';
    }

    // Stream the download.
    file_transfer($uri, $http_headers);
  }

  // Something went wrong.
  drupal_add_http_header('Status', '500 Internal Server Error');
  print t('Error generating CSV.');
  drupal_exit();
}