You are here

class UserForm in Ubercart 8.4

Creates or edits a file feature for a product.

Hierarchy

Expanded class hierarchy of UserForm

File

uc_file/src/Form/UserForm.php, line 16

Namespace

Drupal\uc_file\Form
View source
class UserForm extends FormBase {

  /**
   * The user account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $account;

  /**
   * The datetime.time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * The date.formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * Form constructor.
   *
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The datetime.time service.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date.formatter service.
   */
  public function __construct(TimeInterface $time, DateFormatterInterface $date_formatter) {
    $this->time = $time;
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('datetime.time'), $container
      ->get('date.formatter'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, AccountInterface $account = NULL) {
    $this->account = $account;
    $form['file'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Administration'),
    ];

    // Drop out early if we don't even have any files uploaded.
    if (!\Drupal::database()
      ->queryRange('SELECT 1 FROM {uc_files}', 0, 1)
      ->fetchField()) {
      $form['file']['file_message'] = [
        '#prefix' => '<p>',
        '#markup' => $this
          ->t('You must add files at the <a href=":url">Ubercart file download administration page</a> in order to attach them to a user.', [
          ':url' => Url::fromRoute('uc_file.downloads', [], [
            'query' => [
              'destination' => 'user/' . $account
                ->id() . '/edit',
            ],
          ])
            ->toString(),
        ]),
        '#suffix' => '</p>',
      ];
      return $form;
    }

    // Table displaying current downloadable files and limits.
    $form['file']['download']['#theme'] = 'uc_file_hook_user_file_downloads';
    $form['file']['download']['file_download']['#tree'] = TRUE;
    $form['#attached']['library'][] = 'uc_file/uc_file.scripts';
    $form['#attached']['library'][] = 'uc_file/uc_file.styles';
    $downloadable_files = [];
    $file_downloads = \Drupal::database()
      ->query('SELECT * FROM {uc_file_users} ufu INNER JOIN {uc_files} uf ON ufu.fid = uf.fid WHERE ufu.uid = :uid ORDER BY uf.filename ASC', [
      ':uid' => $account
        ->id(),
    ]);
    $behavior = 0;
    foreach ($file_downloads as $file_download) {

      // Store a flat array so we can array_diff the ones already allowed when
      // building the list of which can be attached.
      $downloadable_files[$file_download->fid] = $file_download->filename;
      $form['file']['download']['file_download'][$file_download->fid] = [
        'fuid' => [
          '#type' => 'value',
          '#value' => $file_download->fuid,
        ],
        'expiration' => [
          '#type' => 'value',
          '#value' => $file_download->expiration,
        ],
        'remove' => [
          '#type' => 'checkbox',
        ],
        'filename' => [
          '#markup' => $file_download->filename,
        ],
        'expires' => [
          '#markup' => $file_download->expiration ? $this->dateFormatter
            ->format($file_download->expiration, 'short') : $this
            ->t('Never'),
        ],
        'time_polarity' => [
          '#type' => 'select',
          '#default_value' => '+',
          '#options' => [
            '+' => '+',
            '-' => '-',
          ],
        ],
        'time_quantity' => [
          '#type' => 'textfield',
          '#size' => 2,
          '#maxlength' => 2,
        ],
        'time_granularity' => [
          '#type' => 'select',
          '#default_value' => 'day',
          '#options' => [
            'never' => $this
              ->t('never'),
            'day' => $this
              ->t('day(s)'),
            'week' => $this
              ->t('week(s)'),
            'month' => $this
              ->t('month(s)'),
            'year' => $this
              ->t('year(s)'),
          ],
        ],
        'downloads_in' => [
          '#markup' => $file_download->accessed,
        ],
        'download_limit' => [
          '#type' => 'textfield',
          '#maxlength' => 3,
          '#size' => 3,
          '#default_value' => $file_download->download_limit ? $file_download->download_limit : NULL,
        ],
        'addresses_in' => [
          '#markup' => count(unserialize($file_download->addresses)),
        ],
        'address_limit' => [
          '#type' => 'textfield',
          '#maxlength' => 2,
          '#size' => 2,
          '#default_value' => $file_download->address_limit ? $file_download->address_limit : NULL,
        ],
      ];

      // Incrementally add behaviors.
      // @todo _uc_file_download_table_behavior($behavior++, $file_download->fid);
      $form['#attached']['drupalSettings']['behavior'][$behavior++] = $file_download->fid;

      // Store old values for comparing to see if we actually made any changes.
      $less_reading =& $form['file']['download']['file_download'][$file_download->fid];
      $less_reading['download_limit_old'] = [
        '#type' => 'value',
        '#value' => $less_reading['download_limit']['#default_value'],
      ];
      $less_reading['address_limit_old'] = [
        '#type' => 'value',
        '#value' => $less_reading['address_limit']['#default_value'],
      ];
      $less_reading['expiration_old'] = [
        '#type' => 'value',
        '#value' => $less_reading['expiration']['#value'],
      ];
    }

    // Create the list of files able to be attached to this user.
    $available_files = [];
    $files = \Drupal::database()
      ->query('SELECT * FROM {uc_files} ORDER BY filename ASC');
    foreach ($files as $file) {
      if (substr($file->filename, -1) != '/' && substr($file->filename, -1) != '\\') {
        $available_files[$file->fid] = $file->filename;
      }
    }

    // Dialog for uploading new files.
    $available_files = array_diff($available_files, $downloadable_files);
    if (count($available_files)) {
      $form['file']['file_add'] = [
        '#type' => 'select',
        '#multiple' => TRUE,
        '#size' => 6,
        '#title' => $this
          ->t('Add file'),
        '#description' => [
          '#markup' => $this
            ->t('Select a file to add as a download. Newly added files will inherit the settings at the <a href=":url">Ubercart products settings page</a>.', [
            ':url' => Url::fromRoute('uc_product.settings')
              ->toString(),
          ]),
        ],
        '#options' => $available_files,
        '#tree' => TRUE,
      ];
    }
    $form['file']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $edit = $form_state
      ->getValues();

    // Determine if any downloads were modified.
    if (isset($edit['file_download'])) {
      foreach ((array) $edit['file_download'] as $key => $download_modification) {

        // We don't care... it's about to be deleted.
        if ($download_modification['remove']) {
          continue;
        }
        if ($download_modification['download_limit'] < 0) {
          $form_state
            ->setErrorByName('file_download][' . $key . '][download_limit', $this
            ->t('A negative download limit does not make sense. Please enter a positive integer, or leave empty for no limit.'));
        }
        if ($download_modification['address_limit'] < 0) {
          $form_state
            ->setErrorByName('file_download][' . $key . '][address_limit', $this
            ->t('A negative address limit does not make sense. Please enter a positive integer, or leave empty for no limit.'));
        }

        // Some expirations don't need any validation...
        if ($download_modification['time_granularity'] == 'never' || !$download_modification['time_quantity']) {
          continue;
        }

        // Either use the current expiration, or if there's none,
        // start from right now.
        $new_expiration = _uc_file_expiration_date($download_modification, $download_modification['expiration']);
        if ($new_expiration <= $this->time
          ->getRequestTime()) {
          $form_state
            ->setErrorByName('file_download][' . $key . '][time_quantity', $this
            ->t('The date %date has already occurred.', [
            '%date' => $this->dateFormatter
              ->format($new_expiration, 'short'),
          ]));
        }
        if ($download_modification['time_quantity'] < 0) {
          $form_state
            ->setErrorByName('file_download][' . $key . '][time_quantity', $this
            ->t('A negative expiration quantity does not make sense. Use the polarity control to determine if the time should be added or subtracted.'));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $edit = $form_state
      ->getValues();

    // Check out if any downloads were modified.
    if (isset($edit['file_download'])) {
      foreach ((array) $edit['file_download'] as $fid => $download_modification) {

        // Remove this user download?
        if ($download_modification['remove']) {
          uc_file_remove_user_file_by_id($this->account, $fid);
        }
        else {

          // Calculate the new expiration.
          $download_modification['expiration'] = _uc_file_expiration_date($download_modification, $download_modification['expiration']);

          // Don't touch anything if everything's the same.
          if ($download_modification['download_limit'] == $download_modification['download_limit_old'] && $download_modification['address_limit'] == $download_modification['address_limit_old'] && $download_modification['expiration'] == $download_modification['expiration_old']) {
            continue;
          }

          // Renew. (Explicit overwrite.)
          uc_file_user_renew($fid, $this->account, NULL, $download_modification, TRUE);
        }
      }
    }

    // Check out if any downloads were added. We pass NULL to file_user_renew,
    // because this shouldn't be associated with a random product.
    if (isset($edit['file_add'])) {
      $file_config = $this
        ->config('uc_file.settings');
      foreach ((array) $edit['file_add'] as $fid => $data) {
        $download_modification['download_limit'] = $file_config
          ->get('download_limit_number');
        $download_modification['address_limit'] = $file_config
          ->get('download_limit_addresses');
        $download_modification['expiration'] = _uc_file_expiration_date([
          'time_polarity' => '+',
          'time_quantity' => $file_config
            ->get('duration_qty'),
          'time_granularity' => $file_config
            ->get('duration_granularity'),
        ], $this->time
          ->getRequestTime());

        // Renew. (Explicit overwrite.)
        uc_file_user_renew($fid, $this->account, NULL, $download_modification, TRUE);
      }
    }
  }

}

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
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::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.
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.
UserForm::$account protected property The user account.
UserForm::$dateFormatter protected property The date.formatter service.
UserForm::$time protected property The datetime.time service.
UserForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
UserForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UserForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UserForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
UserForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
UserForm::__construct public function Form constructor.