You are here

public function DownloadCountExportForm::downloadCountExportData in Download Count 8

Exports download count data.

1 call to DownloadCountExportForm::downloadCountExportData()
DownloadCountExportForm::submitForm in src/Form/DownloadCountExportForm.php
Form submission handler.

File

src/Form/DownloadCountExportForm.php, line 144

Class

DownloadCountExportForm
Implements the Export form controller.

Namespace

Drupal\download_count\Form

Code

public function downloadCountExportData($filename, $range, $file_info, $start, $end) {
  $response = new Response();
  $response->headers
    ->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
  $response->headers
    ->set('Content-Type', 'application/csv');
  $response
    ->sendHeaders();
  $connection = Database::getConnection();
  $query = $connection
    ->select('download_count', 'dc');
  $query
    ->join('file_managed', 'f', 'dc.fid = f.fid');
  $query
    ->join('users_field_data', 'u', 'dc.uid = u.uid');
  $query
    ->fields('dc', [
    'dcid',
    'fid',
    'type',
    'id',
    'uid',
    'ip_address',
    'referrer',
    'timestamp',
  ]);
  $query
    ->fields('f', [
    'filename',
    'filesize',
    'uri',
  ]);
  $query
    ->fields('u', [
    'name',
  ]);
  if ($file_info != 'all') {
    $query
      ->condition('dc.type', $file_info->type, '=');
    $query
      ->condition('dc.id', $file_info->id, '=');
    $query
      ->condition('dc.fid', $file_info->fid, '=');
  }
  if ($range > 0) {
    $from = mktime(0, 0, 0, date('m', strtotime($start)), date('d', strtotime($start)), date('Y', strtotime($start)));
    $to = mktime(23, 59, 59, date('m', strtotime($end)), date('d', strtotime($end)), date('Y', strtotime($end)));
    if ($from == $to) {
      $to += 86400;
    }
    $query
      ->condition('dc.timestamp', [
      $from,
      $to,
    ], 'BETWEEN');
  }
  $query
    ->orderBy('dc.timestamp', 'DESC');
  $result = $query
    ->execute();
  $column_names = '"Download count id","File id","File name","File URI","File size","Entity type","Entity id","Downloading user id","Downloading username","Downloading user ip address","HTTP referrer","Date time"' . "\n";
  echo $column_names;
  foreach ($result as $record) {
    $row = '"' . $record->dcid . '",';
    $row .= '"' . $record->fid . '",';
    $row .= '"' . $record->filename . '",';
    $row .= '"' . $record->uri . '",';
    $row .= '"' . $record->filesize . '",';
    $row .= '"' . $record->type . '",';
    $row .= '"' . $record->id . '",';
    $row .= '"' . $record->uid . '",';
    $row .= '"' . $record->name . '",';
    $row .= '"' . $record->ip_address . '",';
    $row .= '"' . $record->referrer . '",';
    $row .= '"' . date('Y-m-d H:i:s', $record->timestamp) . '"';
    $row .= "\n";
    echo $row;
  }
  exit;
}