You are here

class FileUploadForm in Ubercart 8.4

Performs a file upload action.

Hierarchy

Expanded class hierarchy of FileUploadForm

1 string reference to 'FileUploadForm'
uc_file.routing.yml in uc_file/uc_file.routing.yml
uc_file/uc_file.routing.yml

File

uc_file/src/Form/FileUploadForm.php, line 14

Namespace

Drupal\uc_file\Form
View source
class FileUploadForm extends ConfirmFormBase {

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Form constructor.
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   */
  public function __construct(ModuleHandlerInterface $module_handler) {
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('module_handler'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this
      ->t('Upload file');
  }

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

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this
      ->t('Upload file');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelText() {
    return $this
      ->t('Cancel');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return Url::fromRoute('uc_file.downloads');
  }

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

    // Calculate the maximum size of uploaded files in bytes.
    $post_max_size = ini_get('post_max_size');
    if (is_numeric($post_max_size)) {

      // Handle the case where 'post_max_size' has no suffix.
      // An explicit cast is needed because floats are not allowed.
      $max_bytes = (int) $post_max_size;
    }
    else {

      // Handle the case where 'post_max_size' has a suffix of
      // 'M', 'K', or 'G' (case insensitive).
      $max_bytes = (int) substr($post_max_size, 0, -1);
      $suffix = strtolower(substr($post_max_size, -1));
      switch ($suffix) {
        case 'k':
          $max_bytes *= 1024;
          break;
        case 'm':
          $max_bytes *= 1048576;
          break;
        case 'g':
          $max_bytes *= 1073741824;
          break;
      }
    }

    // Gather list of directories under the selected one(s).
    // '/' is always available.
    $directories = [
      '' => '/',
    ];
    $files = \Drupal::database()
      ->query('SELECT * FROM {uc_files}');
    foreach ($files as $file) {
      if (is_dir($this
        ->config('uc_file.settings')
        ->get('base_dir') . '/' . $file->filename)) {
        $directories[$file->filename] = $file->filename;
      }
    }
    $form['upload_dir'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Directory'),
      '#description' => $this
        ->t('The directory on the server where the file should be put. The default directory is the root of the file downloads directory.'),
      '#options' => $directories,
    ];
    $form['upload'] = [
      '#type' => 'file',
      '#title' => $this
        ->t('File'),
      '#multiple' => TRUE,
      '#description' => $this
        ->t("You may select more than one file by holding down the Cntrl key when you click the file name. The maximum file size that can be uploaded is %size bytes. You will need to use a different method to upload the file to the directory (e.g. (S)FTP, SCP) if your file exceeds this size. Files you upload using one of these alternate methods will be automatically detected. Note: A value of '0' means there is no size limit.", [
        '%size' => number_format($max_bytes),
      ]),
    ];

    // $form['#attributes']['class'][] = 'foo';
    // $form['#attributes']['enctype'] = 'multipart/form-data';
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $hooks = $this->moduleHandler
      ->getImplementations('uc_file_action');

    // Upload the files and get their objects.
    $temp_files = file_save_upload('upload', [
      'file_validate_extensions' => [],
    ]);
    foreach ($temp_files as $temp_file) {

      // Invoke any implemented hook_uc_file_action('upload_validate', $args).
      foreach ($hooks as $module) {
        $name = $module . '_uc_file_action';
        $name('upload_validate', [
          'file_object' => $temp_file,
          'form_id' => $form_id,
          'form_state' => $form_state,
        ]);
      }
    }

    // Save the uploaded file for later processing.
    $form_state
      ->set('temp_files', $temp_files);
  }

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

    // Build the destination location. We start with the base directory,
    // then add any directory which was explicitly selected.
    $dir = $this
      ->config('uc_file.settings')
      ->get('base_dir') . '/' . $form_state
      ->getValue('upload_dir');
    if (is_dir($dir)) {

      // Retrieve our uploaded files.
      $file_objects = $form_state
        ->get('temp_files');
      foreach ($file_objects as $file_object) {

        // Copy the file to its final location.
        if (copy($file_object
          ->getFileUri(), $dir . '/' . $file_object
          ->getFilename())) {

          // Check if any hook_uc_file_action('upload', $args) are implemented.
          foreach ($this->moduleHandler
            ->getImplementations('uc_file_action') as $module) {
            $name = $module . '_uc_file_action';
            $name('upload', [
              'file_object' => $file_object,
              'form_id' => $form_id,
              'form_state' => $form_state,
            ]);
          }

          // Update the file list.
          uc_file_refresh();
          $this
            ->messenger()
            ->addMessage($this
            ->t('The file %file has been uploaded to %dir', [
            '%file' => $file_object
              ->getFilename(),
            '%dir' => $dir,
          ]));
        }
        else {
          $this
            ->messenger()
            ->addError($this
            ->t('An error occurred while copying the file to %dir', [
            '%dir' => $dir,
          ]));
        }
      }
    }
    else {
      $this
        ->messenger()
        ->addError($this
        ->t('Can not move file to %dir', [
        '%dir' => $dir,
      ]));
    }
    $form_state
      ->setRedirectUrl($this
      ->getCancelUrl());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
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
FileUploadForm::$moduleHandler protected property The module handler.
FileUploadForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
FileUploadForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FileUploadForm::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormBase::getCancelText
FileUploadForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
FileUploadForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
FileUploadForm::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
FileUploadForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FileUploadForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
FileUploadForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FileUploadForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
FileUploadForm::__construct public function Form constructor.
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.