You are here

class DownloadCountExportForm in Download Count 8

Implements the Export form controller.

Hierarchy

Expanded class hierarchy of DownloadCountExportForm

See also

\Drupal\Core\Form\FormBase

\Drupal\Core\Form\ConfigFormBase

1 string reference to 'DownloadCountExportForm'
download_count.routing.yml in ./download_count.routing.yml
download_count.routing.yml

File

src/Form/DownloadCountExportForm.php, line 18

Namespace

Drupal\download_count\Form
View source
class DownloadCountExportForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'download_count_export_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $download_count_entry = NULL) {
    if ($download_count_entry != NULL) {
      $connection = Database::getConnection();
      $query = $connection
        ->select('download_count', 'dc');
      $query
        ->join('file_managed', 'f', 'dc.fid = f.fid');
      $query
        ->fields('dc', [
        'dcid',
        'fid',
        'uid',
        'type',
        'id',
        'ip_address',
        'referrer',
        'timestamp',
      ]);
      $query
        ->fields('f', [
        'filename',
        'uri',
        'filemime',
        'filesize',
      ]);
      $query
        ->condition('dc.dcid', $download_count_entry);
      $dc_entry = $query
        ->execute()
        ->fetchObject();
    }
    else {
      $dc_entry = 'all';
    }
    $config = $this
      ->config('download_count.settings');
    $form['#attached']['library'][] = 'download_count/export-form-styling';
    if ($dc_entry == 'all') {
      $form['#title'] = $this
        ->t('Download Count Export CSV - All Files');
    }
    else {
      $form['#title'] = $this
        ->t("Download Count Export CSV - '@filename' from '@type' '@id'", [
        '@filename' => $dc_entry->filename,
        '@type' => $dc_entry->type,
        '@id' => $dc_entry->id,
      ]);
    }
    $form['download_count_export_note'] = [
      '#prefix' => '<div id="download-count-export-note">',
      '#suffix' => '</div>',
      '#markup' => Link::fromTextAndUrl($this
        ->t('Back to summary'), Url::fromRoute('download_count.reports', [
        'html' => TRUE,
      ]))
        ->toString() . '<br /><br />' . $this
        ->t('The following data will be exported:') . '<ul><li>' . $this
        ->t('Download count id') . '<li>' . $this
        ->t('File id') . '<li>' . $this
        ->t('File name') . '<li>' . $this
        ->t('File size') . '<li>' . $this
        ->t('Entity type') . '<li>' . $this
        ->t('Entity id') . '<li>' . $this
        ->t('Downloading user id') . '<li>' . $this
        ->t('Downloading username') . '<li>' . $this
        ->t('Downloading user ip address') . '<li>' . $this
        ->t('HTTP referrer') . '<li>' . $this
        ->t('Date - time (YYYY-MM-DD  HH:MM:SS)') . '</ul>',
    ];
    $form['download_count_export_range'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Export Range'),
      '#options' => [
        $this
          ->t('export all data'),
        $this
          ->t('export data for a specified date range'),
      ],
      '#default_value' => $config
        ->get('download_count_export_range') ? 1 : 0,
    ];
    $form['download_count_export_date_range_from'] = [
      '#type' => 'date',
      '#title' => $this
        ->t('Export Range From Date'),
      '#description' => $this
        ->t("This field will be ignored if the Export Range 'export all data' option is selected above."),
    ];
    $form['download_count_export_date_range_to'] = [
      '#type' => 'date',
      '#title' => $this
        ->t('Export Range To Date'),
      '#description' => $this
        ->t("This field will be ignored if the Export Range 'export all data' option is selected above."),
    ];
    $form['download_count_file_info'] = [
      '#type' => 'value',
      '#value' => $dc_entry,
    ];
    $form['download_count_export_submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Export'),
    ];
    $form['download_count_export_cancel'] = [
      '#value' => '<a href="javascript:history.back(-1)">' . $this
        ->t('Cancel') . '</a>',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->configFactory
      ->getEditable('download_count.settings')
      ->set('download_count_export_range', $form_state
      ->getValue('download_count_export_range'))
      ->save();
    $filename = 'download_count_export_' . $form_state
      ->getValue('download_count_file_info')->filename . '_' . date('Y-m-d') . '.csv';
    $range = $form_state
      ->getValue('download_count_export_range');
    $start = $end = '';
    if ($range > 0) {
      $start = $form_state
        ->getValue('download_count_export_date_range_from');
      $end = $form_state
        ->getValue('download_count_export_date_range_to');
      $file = $form_state
        ->getValue('download_count_file_info')->filename;
      $filename = 'download_count_export_' . $file . '_FROM-' . $start . '-TO-' . $end . '.csv';
    }
    $file_info = $form_state
      ->getValue('download_count_file_info');
    $this
      ->downloadCountExportData($filename, $range, $file_info, $start, $end);
    drupal_set_message($filename . ' has been successfully exported.', 'status');
  }

  /**
   * Exports download count data.
   */
  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;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DownloadCountExportForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
DownloadCountExportForm::downloadCountExportData public function Exports download count data.
DownloadCountExportForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DownloadCountExportForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.