You are here

class HtaccessConfirmForm in Htaccess 8.2

Defines a form to confirm Htaccess deployment or deletion

Hierarchy

Expanded class hierarchy of HtaccessConfirmForm

1 string reference to 'HtaccessConfirmForm'
htaccess.routing.yml in ./htaccess.routing.yml
htaccess.routing.yml

File

src/Form/HtaccessConfirmForm.php, line 23
Administration pages.

Namespace

Drupal\htaccess\Form
View source
class HtaccessConfirmForm extends ConfirmFormBase {

  /**
   * The ID htaccess configuration to delete or deploy
   *
   * @var string
   *
   * The Name of the htaccess configuration to delete or deploy
   *
   * @var string
   *
   * The action to take on the htaccess configuration.
   *
   * @var string
   */
  protected $id;
  protected $action;
  protected $name;

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {

    //the question to display to the user.
    return t('Are you sure you want to %action the htaccess profile %profile_name?', array(
      '%action' => $this->action,
      '%profile_name' => $this->name,
    ));
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {

    //this needs to be a valid route otherwise the cancel link won't appear
    return new Url('htaccess.admin_deployment');
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {

    //a brief desccription
    if ($this->action == 'Deploy') {
      return t('The htaccess %profile_name will be deployed.', array(
        '%profile_name' => $this->name,
      ));
    }
    elseif ($this->action == 'Delete') {
      return t('The htaccess %profile_name will be deleted. This action cannot be undone.', array(
        '%profile_name' => $this->name,
      ));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this
      ->t('%action', array(
      '%action' => $this->action,
    ));
  }

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

  /**
   * Admin htaccess confirm form
   */
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    $path = $request
      ->getPathInfo();
    $parts = explode('/', $path);
    $this->action = UCFirst($parts[6]);
    $this->id = $parts[7];
    $select = Database::getConnection()
      ->select('htaccess', 'h');
    $select
      ->fields('h');
    $select
      ->condition('id', $this->id);
    $results = $select
      ->execute();
    $result = $results
      ->fetch();
    $this->name = $result->name;
    return parent::buildForm($form, $form_state);
  }

  /**
   * Submit handler for confirm form
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    switch ($this->action) {
      case 'Deploy':
        $root_path = \Drupal::root();
        $htaccess_path = $root_path . '/.htaccess';
        $select = Database::getConnection()
          ->select('htaccess', 'h');
        $select
          ->fields('h');
        $select
          ->condition('id', $this->id);
        $results = $select
          ->execute();
        $result = $results
          ->fetch();
        $htaccess_content = $result->htaccess;

        // Remove utf8-BOM
        $htaccess_content = str_replace("", '', $htaccess_content);

        // Standardize the EOL.
        $htaccess_content = str_replace("\r\n", PHP_EOL, $htaccess_content);

        // Try to write to the .htaccess file
        if (file_put_contents($htaccess_path, $htaccess_content)) {
          \Drupal::service("file_system")
            ->chmod($htaccess_path, 0644);

          // Get the current htaccess deployed
          $htaccess_current = Database::getConnection()
            ->select('htaccess', 'h');
          $htaccess_current
            ->fields('h');
          $htaccess_current
            ->condition('deployed', 1);
          $results = $htaccess_current
            ->execute();
          $current = $results
            ->fetch();

          // If any, set the status to 0
          if ($current) {
            $disable = Database::getConnection()
              ->update('htaccess');
            $disable
              ->fields(array(
              'deployed' => 0,
            ));
            $disable
              ->condition('id', $current->id);
            $disable
              ->execute();
          }

          // Set the status to 1
          $deploy = Database::getConnection()
            ->update('htaccess');
          $deploy
            ->fields(array(
            'deployed' => 1,
          ));
          $deploy
            ->condition('id', $result->id);
          $deploy
            ->execute();
          drupal_set_message(t('Htaccess profile @profile has been deployed.', array(
            '@profile' => $result->name,
          )));
        }
        else {
          $variables = array(
            '%directory' => $root_path,
            '!htaccess' => '<br />' . nl2br(\Drupal\Component\Utility\SafeMarkup::checkPlain($htaccess_content)),
          );
          \Drupal::logger('security')
            ->error("Security warning: Couldn't write .htaccess file.", []);
          drupal_set_message(t('Error during deployment: couldn\'t write .htaccess file. You have to download it and manually put it in the root of your Drupal installation.'), 'error');
        }
        break;
      case 'Delete':

        // Check that the profile is not in use
        $htaccess_check = Database::getConnection()
          ->select('htaccess', 'h');
        $htaccess_check
          ->fields('h');
        $htaccess_check
          ->condition('deployed', 1);
        $htaccess_check
          ->condition('id', $this->id);
        $results = $htaccess_check
          ->execute();
        if (!empty($results
          ->fetchCol())) {
          drupal_set_message(t('This htaccess\'s profile is currently in use'), 'error');
        }
        else {
          $htaccess_get = Database::getConnection()
            ->delete('htaccess');
          $htaccess_get
            ->condition('id', $this->id);
          $htaccess_get
            ->execute();
          drupal_set_message(t('Htaccess profile has been removed.'));
        }
        break;
    }
    $form_state
      ->setRedirect('htaccess.admin_deployment');
  }

}

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
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
FormInterface::getFormId public function Returns a unique string identifying the form. 236
HtaccessConfirmForm::$action protected property
HtaccessConfirmForm::$id protected property The ID htaccess configuration to delete or deploy
HtaccessConfirmForm::$name protected property
HtaccessConfirmForm::buildForm public function Admin htaccess confirm form Overrides ConfirmFormBase::buildForm
HtaccessConfirmForm::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormBase::getCancelText
HtaccessConfirmForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
HtaccessConfirmForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
HtaccessConfirmForm::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
HtaccessConfirmForm::getFormID public function
HtaccessConfirmForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
HtaccessConfirmForm::submitForm public function Submit handler for confirm form Overrides FormInterface::submitForm
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.