You are here

WebformProtectedDownloadsHandler.php in Webform Protected Downloads 8

File

src/Plugin/WebformHandler/WebformProtectedDownloadsHandler.php
View source
<?php

namespace Drupal\webform_protected_downloads\Plugin\WebformHandler;

use Drupal\Component\Utility\Crypt;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\FileInterface;
use Drupal\file\FileStorageInterface;
use Drupal\file\FileUsage\FileUsageInterface;
use Drupal\webform\Annotation\WebformHandler;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform_protected_downloads\Entity\WebformProtectedDownloads;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Handler for protected downloads
 *
 * @WebformHandler(
 *   id = "webform_protected_downloads",
 *   label = @Translation("Webform Protected Downloads (DO NOT USE)"),
 *   category = @Translation("Downloads"),
 *   description = @Translation("Provides an access controlled link to a file/page of files."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_IGNORED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class WebformProtectedDownloadsHandler extends WebformHandlerBase {

  /**
   * @var FileStorageInterface
   */
  protected $fileStorage;

  /**
   * @var FileUsageInterface
   */
  protected $fileUsage;
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $entityTypeManager = $container
      ->get('entity_type.manager');
    $instance->fileStorage = $entityTypeManager
      ->getStorage('file');
    $instance->fileUsage = $container
      ->get('file.usage');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'expiration_one_time' => false,
      'expiration_time' => 0,
      'expiration_page' => 'page_reload',
      'expiration_page_custom' => '',
      'expiration_error_message' => 'This link has expired.',
      'token_text' => 'Download',
      'protected_files' => [],
      'protected_files_allowed_extensions' => 'gif png jpg jpeg',
      'debug' => false,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getSummary() {
    $configuration = $this
      ->getConfiguration();
    $settings = $configuration['settings'];
    return [
      '#settings' => $settings,
    ] + parent::getSummary();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {

    // Expiration
    $form['expiration'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Expiration'),
      '#open' => TRUE,
    ];
    $form['expiration']['expiration_onetime'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('One time visit link'),
      '#default_value' => $this->configuration['expiration_onetime'],
    ];
    $form['expiration']['expiration_time'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Expire after X minutes'),
      '#default_value' => $this->configuration['expiration_time'],
      '#required' => TRUE,
      '#description' => 'Set this to 0 for unlimited.',
    ];
    $options = [
      '404' => $this
        ->t('404 page'),
      'homepage' => $this
        ->t('Homepage with error message'),
      'page_reload' => $this
        ->t('Form page with error message'),
      'custom' => $this
        ->t('Custom page'),
    ];
    $form['expiration']['expiration_page'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Link expired page'),
      '#required' => TRUE,
      '#description' => t('Select a page to be routed when link expires.'),
      '#options' => $options,
      '#default_value' => $this->configuration['expiration_page'],
      '#attributes' => [
        'name' => 'field_expiration_page',
      ],
    ];
    $form['expiration']['expiration_page_custom'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Custom link page'),
      '#options' => $options,
      '#default_value' => $this->configuration['expiration_page_custom'],
      '#states' => [
        'visible' => [
          ':input[name="field_expiration_page"]' => [
            'value' => 'custom',
          ],
        ],
        'required' => [
          ':input[name="field_expiration_page"]' => [
            'value' => 'custom',
          ],
        ],
      ],
    ];
    $form['expiration']['expiration_error_message'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Error message'),
      '#description' => $this
        ->t('Error message to display.'),
      '#default_value' => $this->configuration['expiration_error_message'],
      '#states' => [
        'visible' => [
          ':input[name="field_expiration_page"]' => [
            [
              'value' => 'homepage',
            ],
            [
              'value' => 'page_reload',
            ],
          ],
        ],
        'required' => [
          ':input[name="field_expiration_page"]' => [
            [
              'value' => 'homepage',
            ],
            [
              'value' => 'page_reload',
            ],
          ],
        ],
      ],
    );

    // Tokens
    $form['token'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Tokens'),
      '#open' => TRUE,
    ];
    $form['token']['token_text'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Token text title'),
      '#description' => $this
        ->t('This title will be shown when token is replaced, default title is Download'),
      '#default_value' => $this->configuration['token_text'],
    ];

    // Files
    $form['protected'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Protected Files'),
      '#open' => TRUE,
    ];
    $form['protected']['protected_files'] = [
      '#name' => 'protected_files',
      '#type' => 'managed_file',
      '#title' => $this
        ->t('Choose file(s) for protected download'),
      '#multiple' => TRUE,
      '#upload_validators' => [
        'file_validate_extensions' => $this->configuration['protected_files_allowed_extensions'],
      ],
      '#upload_location' => 'private://webform_protected_downloads/[date:custom:Y]-[date:custom:m]',
      '#default_value' => $this->configuration['protected_files'],
    ];
    $form['protected']['protected_files_allowed_extensions'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Valid File extensions'),
      '#description' => $this
        ->t("Separate extensions with a space."),
      '#default_value' => $this->configuration['protected_files_allowed_extensions'],
      '#required' => TRUE,
    ];

    // Development.
    $form['development'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Development settings'),
      '#open' => true,
    ];
    $form['development']['debug'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable debugging'),
      '#description' => $this
        ->t('If checked, debugging will be displayed onscreen to all users.'),
      '#return_value' => true,
      '#default_value' => $this->configuration['debug'],
    ];
    return $this
      ->setSettingsParents($form);
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration = $this
      ->defaultConfiguration();
    parent::submitConfigurationForm($form, $form_state);
    $this
      ->applyFormStateToConfiguration($form_state);

    // Set the files as permanent through file usage
    $protectedFiles = $form_state
      ->getValue('protected_files');
    foreach ($protectedFiles as $protectedFile) {

      /** @var FileInterface $file */
      $file = $this->fileStorage
        ->load($protectedFile);
      if (!empty($file)) {
        $this->fileUsage
          ->add($file, 'webform_protected_downloads', 'webform', $this
          ->getWebform()
          ->id());
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {

    // only act on the insert
    if (!$update) {
      return;
    }

    // only process if there are files added to the configuration
    if (count($this->configuration['protected_files']) > 0) {
      return;
    }
    $expiration = 0;
    if ($this->configuration['expiration_time'] > 0) {
      $expiration = time() + $this->configuration['expiration_time'] * 60;
    }

    // TODO
    //    $webformProtectedDownload = WebformProtectedDownloads::create([
    //      'webform_submission' => $webform_submission,
    //      'files' => $this->con,
    //      'hash' => Crypt::hashBase64($webform_submission->uuid() . time()),
    //      'active' => TRUE,
    //      'expire' => $expiration,
    //      'onetime' => $this->configuration['expiration_onetime'],
    //    ]);
    //
    //    $webformProtectedDownload->save();
  }

}

Classes

Namesort descending Description
WebformProtectedDownloadsHandler Handler for protected downloads