You are here

class CreditSettingsForm in Ubercart 8.4

Credit card settings form.

Hierarchy

Expanded class hierarchy of CreditSettingsForm

1 string reference to 'CreditSettingsForm'
uc_credit.routing.yml in payment/uc_credit/uc_credit.routing.yml
payment/uc_credit/uc_credit.routing.yml

File

payment/uc_credit/src/Form/CreditSettingsForm.php, line 12

Namespace

Drupal\uc_credit\Form
View source
class CreditSettingsForm extends ConfigFormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $config = $this
      ->config('uc_credit.settings');
    $form['cc_security']['uc_credit_encryption_path'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Encryption key directory'),
      '#description' => $this
        ->t('The card type, expiration date and last four digits of the card number are encrypted and stored temporarily while the customer is in the process of checking out.<br /><b>You must enable encryption</b> by following the <a href=":url">encryption instructions</a> in order to accept credit card payments.<br />In short, you must enter the path of a directory outside of your document root where the encryption key may be stored.<br />Relative paths will be resolved relative to the Drupal installation directory.<br />Once this directory is set, you should not change it.', [
        ':url' => Url::fromUri('https://www.drupal.org/node/1309226')
          ->toString(),
      ]),
      '#default_value' => uc_credit_encryption_key() ? $config
        ->get('encryption_path') : $this
        ->t('Not configured.'),
    ];
    return $form;
  }

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

    /*
     * Check that the encryption key directory has been specified, that it
     * exists, and that it is readable.
     */

    // Trim trailing whitespace and any trailing / or \ from the key path name.
    $key_path = rtrim(trim($form_state
      ->getValue('uc_credit_encryption_path')), '/\\');

    // Test to see if a path was entered.
    if (empty($key_path)) {
      $form_state
        ->setErrorByName('uc_credit_encryption_path', $this
        ->t('Key path must be specified in security settings tab.'));
    }

    // Construct complete key file path.
    $key_file = $key_path . '/' . UC_CREDIT_KEYFILE_NAME;

    // Shortcut - test to see if we already have a usable key file.
    if (file_exists($key_file)) {
      if (is_readable($key_file)) {

        // Test contents - must contain 32-character hexadecimal string.
        $key = uc_credit_encryption_key();
        if ($key) {
          if (!preg_match("([0-9a-fA-F]{32})", $key)) {
            $form_state
              ->setErrorByName('uc_credit_encryption_path', $this
              ->t('Key file already exists in directory, but it contains an invalid key.'));
          }
          else {

            // Key file exists and is valid, save result of trim() back into
            // $form_state and proceed to submit handler.
            $form_state
              ->setValue('uc_credit_encryption_path', $key_path);
            return;
          }
        }
      }
      else {
        $form_state
          ->setErrorByName('uc_credit_encryption_path', $this
          ->t('Key file already exists in directory, but is not readable. Please verify the file permissions.'));
      }
    }

    // Check if directory exists and is writeable.
    if (is_dir($key_path)) {

      // The entered directory is valid and in need of a key file.
      // Flag this condition for the submit handler.
      $form_state
        ->setValue('update_cc_encrypt_dir', TRUE);

      // Can we open for writing?
      $file = @fopen($key_path . '/encrypt.test', 'w');
      if ($file === FALSE) {
        $form_state
          ->setErrorByName('uc_credit_encryption_path', $this
          ->t('Cannot write to directory, please verify the directory permissions.'));
        $form_state
          ->setValue('update_cc_encrypt_dir', FALSE);
      }
      else {

        // Can we actually write?
        if (@fwrite($file, '0123456789') === FALSE) {
          $form_state
            ->setErrorByName('uc_credit_encryption_path', $this
            ->t('Cannot write to directory, please verify the directory permissions.'));
          $form_state
            ->setValue('update_cc_encrypt_dir', FALSE);
          fclose($file);
        }
        else {

          // Can we read now?
          fclose($file);
          $file = @fopen($key_path . '/encrypt.test', 'r');
          if ($file === FALSE) {
            $form_state
              ->setErrorByName('uc_credit_encryption_path', $this
              ->t('Cannot read from directory, please verify the directory permissions.'));
            $form_state
              ->setValue('update_cc_encrypt_dir', FALSE);
          }
          else {
            fclose($file);
          }
        }
        unlink($key_path . '/encrypt.test');
      }
    }
    else {

      // Directory doesn't exist.
      $form_state
        ->setErrorByName('uc_credit_encryption_path', $this
        ->t('You have specified a non-existent directory.'));
    }

    // If validation succeeds, save result of trim() back into $form_state.
    $form_state
      ->setValue('uc_credit_encryption_path', $key_path);
  }

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

    // Check to see if we need to create an encryption key file.
    if ($form_state
      ->getValue('update_cc_encrypt_dir')) {
      $key_path = $form_state
        ->getValue('uc_credit_encryption_path');
      $key_file = $key_path . '/' . UC_CREDIT_KEYFILE_NAME;
      if (!file_exists($key_file)) {
        if (!($file = fopen($key_file, 'wb'))) {
          $this
            ->messenger()
            ->addError($this
            ->t('Credit card encryption key file creation failed for file @file. Check your filepath settings and directory permissions.', [
            '@file' => $key_file,
          ]));
          $this
            ->logger('uc_credit')
            ->error('Credit card encryption key file creation failed for file @file. Check your filepath settings and directory permissions.', [
            '@file' => $key_file,
          ]);
        }
        else {

          // Replacement key generation suggested by Barry Jaspan
          // for increased security.
          fwrite($file, md5(\Drupal::csrfToken()
            ->get(serialize($_REQUEST) . serialize($_SERVER) . REQUEST_TIME)));
          fclose($file);
          $this
            ->messenger()
            ->addMessage($this
            ->t('Credit card encryption key file generated. Card data will now be encrypted.'));
          $this
            ->logger('uc_credit')
            ->notice('Credit card encryption key file generated. Card data will now be encrypted.');
        }
      }
    }
    $this
      ->config('uc_credit.settings')
      ->set('encryption_path', $form_state
      ->getValue('uc_credit_encryption_path'))
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'uc_credit.settings',
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
CreditSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
CreditSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
CreditSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CreditSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
CreditSettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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::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.