You are here

class OperationsForm in Advanced CSS/JS Aggregation 8.2

Same name and namespace in other branches
  1. 8.4 src/Form/OperationsForm.php \Drupal\advagg\Form\OperationsForm
  2. 8.3 src/Form/OperationsForm.php \Drupal\advagg\Form\OperationsForm

Configure advagg settings for this site.

Hierarchy

Expanded class hierarchy of OperationsForm

1 string reference to 'OperationsForm'
advagg.routing.yml in ./advagg.routing.yml
advagg.routing.yml

File

src/Form/OperationsForm.php, line 19

Namespace

Drupal\advagg\Form
View source
class OperationsForm extends ConfigFormBase {

  /**
   * The private key service.
   *
   * @var \Drupal\Core\PrivateKey
   */
  protected $privateKey;

  /**
   * The CSS asset collection optimizer service.
   *
   * @var \Drupal\Core\Asset\AssetCollectionOptimizerInterface
   */
  protected $cssCollectionOptimizer;

  /**
   * The JavaScript asset collection optimizer service.
   *
   * @var \Drupal\Core\Asset\AssetCollectionOptimizerInterface
   */
  protected $jsCollectionOptimizer;

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

  /**
   * A state information store for the AdvAgg generated aggregates.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $advaggAggregates;

  /**
   * A state information store for the AdvAgg scanned files.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $advaggFiles;

  /**
   * Constructs the OperationsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\PrivateKey $private_key
   *   The private key service.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The Date formatter service.
   * @param \Drupal\Core\Asset\AssetCollectionOptimizerInterface $css_collection_optimizer
   *   The CSS asset collection optimizer service.
   * @param \Drupal\Core\Asset\AssetCollectionOptimizerInterface $js_collection_optimizer
   *   The JavaScript asset collection optimizer service.
   * @param \Drupal\Core\State\StateInterface $advagg_files
   *   A state information store for the AdvAgg scanned files.
   * @param \Drupal\Core\State\StateInterface $advagg_aggregates
   *   A state information store for the AdvAgg generated aggregates.
   */
  public function __construct(ConfigFactoryInterface $config_factory, PrivateKey $private_key, DateFormatterInterface $date_formatter, AssetCollectionOptimizerInterface $css_collection_optimizer, AssetCollectionOptimizerInterface $js_collection_optimizer, StateInterface $advagg_files, StateInterface $advagg_aggregates) {
    parent::__construct($config_factory);
    $this->privateKey = $private_key;
    $this->dateFormatter = $date_formatter;
    $this->cssCollectionOptimizer = $css_collection_optimizer;
    $this->jsCollectionOptimizer = $js_collection_optimizer;
    $this->advaggFiles = $advagg_files;
    $this->advaggAggregates = $advagg_aggregates;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('private_key'), $container
      ->get('date.formatter'), $container
      ->get('asset.css.collection_optimizer'), $container
      ->get('asset.js.collection_optimizer'), $container
      ->get('state.advagg.files'), $container
      ->get('state.advagg.aggregates'));
  }

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

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

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

    // Explain what can be done on this page.
    $form['tip'] = [
      '#markup' => '<p>' . $this
        ->t('This is a collection of commands to control the cache and to manage testing of this module. In general this page is useful when troubleshooting some aggregation issues. For normal operations, you do not need to do anything on this page below the Smart Cache Flush. There are no configuration options here.') . '</p>',
    ];
    $form['wrapper'] = [
      '#prefix' => "<div id='operations-wrapper'>",
      '#suffix' => "</div>",
    ];

    // Buttons to do stuff.
    // AdvAgg smart cache flushing.
    $form['smart_flush'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Smart Cache Flush'),
      '#description' => $this
        ->t('Scan all files referenced in aggregated files. If any of them have changed, clear that cache so the changes will go out.'),
    ];
    $form['smart_flush']['advagg_flush'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Flush AdvAgg Cache'),
      '#submit' => [
        '::flushCache',
      ],
      '#ajax' => [
        'callback' => '::tasksAjax',
        'wrapper' => 'operations-wrapper',
      ],
    ];

    // Set/Remove Bypass Cookie.
    $form['bypass'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Aggregation Bypass Cookie'),
      '#description' => $this
        ->t('This will set or remove a cookie that disables aggregation for a set period of time.'),
    ];
    $form['bypass']['timespan'] = [
      '#type' => 'select',
      '#title' => 'Bypass length',
      '#options' => [
        21600 => $this
          ->t('6 hours'),
        43200 => $this
          ->t('12 hours'),
        86400 => $this
          ->t('1 day'),
        172800 => $this
          ->t('2 days'),
        604800 => $this
          ->t('1 week'),
        2592000 => $this
          ->t('1 month'),
        31536000 => $this
          ->t('1 year'),
      ],
    ];
    $form['bypass']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Toggle The "aggregation bypass cookie" For This Browser'),
      '#attributes' => [
        'onclick' => 'javascript:return advagg_toggle_cookie()',
      ],
      '#submit' => [
        '::toggleBypassCookie',
      ],
    ];

    // Add in aggregation bypass cookie javascript.
    $form['#attached']['drupalSettings']['advagg'] = [
      'key' => Crypt::hashBase64($this->privateKey
        ->get()),
    ];
    $form['#attached']['library'][] = 'advagg/admin.operations';

    // Tasks run by cron.
    $form['cron'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Cron Maintenance Tasks'),
      'description' => [
        '#markup' => $this
          ->t('The following 3 operations are ran on cron but you can run them manually here.'),
      ],
    ];
    $form['cron']['wrapper'] = [
      '#prefix' => "<div id='cron-wrapper'>",
      '#suffix' => "</div>",
    ];
    $form['cron']['smart_file_flush'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Clear All Stale Files'),
      '#description' => $this
        ->t('Remove all stale files. Scan all files in the advagg_css/js directories and remove the ones that have not been accessed in the last 30 days.'),
    ];
    $form['cron']['smart_file_flush']['advagg_flush_stale_files'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Remove All Stale Files'),
      '#submit' => [
        '::clearStaleAggregates',
      ],
      '#ajax' => [
        'callback' => '::cronTasksAjax',
        'wrapper' => 'cron-wrapper',
      ],
    ];
    $form['cron']['remove_missing_files'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Clear Missing Files From Database'),
      '#description' => $this
        ->t('Scan for missing files and remove the associated entries from the database.'),
    ];
    $form['cron']['remove_missing_files']['advagg_remove_missing_files_from_db'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Clear Missing Files From Database'),
      '#submit' => [
        '::clearMissingFiles',
      ],
      '#ajax' => [
        'callback' => '::cronTasksAjax',
        'wrapper' => 'cron-wrapper',
      ],
    ];
    $form['cron']['remove_old_aggregates'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Delete Unused Aggregates From Database'),
      '#description' => $this
        ->t('Delete aggregates that have not been accessed in the last 6 weeks.'),
    ];
    $form['cron']['remove_old_aggregates']['advagg_remove_old_unused_aggregates'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Delete Unused Aggregates From Database'),
      '#submit' => [
        '::clearOldUnusedAggregates',
      ],
      '#ajax' => [
        'callback' => '::cronTasksAjax',
        'wrapper' => 'cron-wrapper',
      ],
    ];

    // Hide drastic measures as they should not be done unless really needed.
    $form['drastic_measures'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Drastic Measures'),
      '#description' => $this
        ->t('The options below should normally never need to be done.'),
    ];
    $form['drastic_measures']['wrapper'] = [
      '#prefix' => "<div id='drastic-measures-wrapper'>",
      '#suffix' => "</div>",
    ];
    $form['drastic_measures']['dumb_cache_flush'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Clear All Caches'),
      '#description' => $this
        ->t('Remove all entries from the advagg cache and file information stores. Useful if you suspect a cache is not getting cleared.'),
    ];
    $form['drastic_measures']['dumb_cache_flush']['advagg_flush_all_caches'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Clear All Caches & File Information'),
      '#submit' => [
        '::clearAll',
      ],
      '#ajax' => [
        'callback' => '::drasticTasksAjax',
        'wrapper' => 'drastic-measures-wrapper',
      ],
    ];
    $form['drastic_measures']['dumb_file_flush'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Clear All Files'),
      '#description' => $this
        ->t('Remove all generated files. Useful if you think some of the generated files got corrupted and thus need to be deleted.'),
    ];
    $form['drastic_measures']['dumb_file_flush']['advagg_flush_all_files'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Remove All Generated Files'),
      '#submit' => [
        '::clearAggregates',
      ],
      '#ajax' => [
        'callback' => '::drasticTasksAjax',
        'wrapper' => 'drastic-measures-wrapper',
      ],
    ];
    $form['drastic_measures']['force_change'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Force new aggregates'),
      '#description' => $this
        ->t('Force the creation of all new aggregates by incrementing a global counter. Current value of counter: %value. This is useful if a CDN has cached an aggregate incorrectly as it will force new ones to be used even if nothing else has changed.', [
        '%value' => advagg_get_global_counter(),
      ]),
    ];
    $form['drastic_measures']['force_change']['increment_global_counter'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Increment Global Counter'),
      '#submit' => [
        '::incrementCounter',
      ],
      '#ajax' => [
        'callback' => '::drasticTasksAjax',
        'wrapper' => 'drastic-measures-wrapper',
      ],
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * Perform a smart flush.
   */
  public function flushCache() {
    Cache::invalidateTags([
      'library_info',
      'advagg_css',
      'advagg_js',
    ]);
    if ($this
      ->config('advagg.settings')
      ->get('cache_level') >= 0) {

      // Display a simple message if not in Development mode.
      drupal_set_message($this
        ->t('Advagg Caches Cleared'));
    }
  }

  /**
   * Report results via Ajax.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   */
  public function tasksAjax(array &$form) {
    return $form['wrapper'];
  }

  /**
   * Clear out all advagg cache bins and clear out all advagg aggregated files.
   */
  public function clearAggregates() {

    // Clear out the cache.
    Cache::invalidateTags([
      'library_info',
      'advagg_css',
      'advagg_js',
    ]);
    $css_files = $this->cssCollectionOptimizer
      ->deleteAllReal();
    $js_files = $this->jsCollectionOptimizer
      ->deleteAllReal();

    // Report back the results.
    drupal_set_message($this
      ->t('All AdvAgg aggregates have been deleted. %css_count CSS files and %js_count JS files have been removed.', [
      '%css_count' => count($css_files),
      '%js_count' => count($js_files),
    ]));
  }

  /**
   * Clear ALL saved information and aggregates.
   */
  public function clearAll() {
    $this
      ->clearAggregates();
    $this->advaggAggregates
      ->deleteAll();
    $this->advaggFiles
      ->deleteAll();
    drupal_set_message($this
      ->t('All AdvAgg cached information and aggregates deleted.'));
  }

  /**
   * Clear out all stale advagg aggregated files.
   */
  public function clearStaleAggregates() {

    // Run the command.
    $css_count = count($this->cssCollectionOptimizer
      ->deleteStale());
    $js_count = count($this->jsCollectionOptimizer
      ->deleteStale());

    // Report back the results.
    if ($css_count || $js_count) {
      drupal_set_message($this
        ->t('All stale aggregates have been deleted. %css_count CSS files and %js_count JS files have been removed.', [
        '%css_count' => $css_count,
        '%js_count' => $js_count,
      ]));
    }
    else {
      drupal_set_message($this
        ->t('No stale aggregates found. Nothing was deleted.'));
    }
  }

  /**
   * Clear out all advagg cache bins and increment the counter.
   */
  public function incrementCounter() {

    // Clear out the cache and delete aggregates.
    $this
      ->clearAggregates();

    // Increment counter.
    $new_value = $this
      ->config('advagg.settings')
      ->get('global_counter') + 1;
    $this
      ->config('advagg.settings')
      ->set('global_counter', $new_value)
      ->save();
    drupal_set_message($this
      ->t('Global counter is now set to %new_value', [
      '%new_value' => $new_value,
    ]));
  }

  /**
   * Report results from the drastic measure tasks via Ajax.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   */
  public function drasticTasksAjax(array &$form) {
    return $form['drastic_measures']['wrapper'];
  }

  /**
   * Scan for missing files and remove the associated entries in the database.
   */
  public function clearMissingFiles() {
    $deleted = $this->advaggFiles
      ->clearMissingFiles();
    $this->advaggAggregates
      ->clearMissingFiles();
    if (empty($deleted)) {
      drupal_set_message($this
        ->t('No missing files found or they could not be safely cleared out of the database.'));
    }
    else {
      drupal_set_message($this
        ->t('Some missing files were found and could be safely cleared out of the database. <pre> @raw </pre>', [
        '@raw' => print_r($deleted, TRUE),
      ]));
    }
  }

  /**
   * Report results from the cron tasks via Ajax.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   */
  public function cronTasksAjax(array &$form) {
    return $form['cron']['wrapper'];
  }

  /**
   * Delete aggregates that have not been accessed in the last 6 weeks.
   */
  public function clearOldUnusedAggregates() {

    // Remove unused aggregates.
    $count = count($this->cssCollectionOptimizer
      ->deleteOld());
    $count += count($this->jsCollectionOptimizer
      ->deleteOld());
    if (empty($count)) {
      drupal_set_message($this
        ->t('No old and unused aggregates found. Nothing was deleted.'));
    }
    else {
      drupal_set_message($this
        ->t('Some old and unused aggregates were found. A total of %count database entries were removed.', [
        '%count' => $count,
      ]));
    }
  }

  /**
   * Set or remove the AdvAggDisabled cookie.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function toggleBypassCookie(array &$form, FormStateInterface $form_state) {
    $cookie_name = 'AdvAggDisabled';
    $key = Crypt::hashBase64($this->privateKey
      ->get());

    // If the cookie does exist then remove it.
    if (!empty($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name] == $key) {
      setcookie($cookie_name, '', -1, $GLOBALS['base_path'], '.' . $_SERVER['HTTP_HOST']);
      unset($_COOKIE[$cookie_name]);
      drupal_set_message($this
        ->t('AdvAgg Bypass Cookie Removed.'));
    }
    else {
      setcookie($cookie_name, $key, REQUEST_TIME + $form_state
        ->getValue('timespan'), $GLOBALS['base_path'], '.' . $_SERVER['HTTP_HOST']);
      $_COOKIE[$cookie_name] = $key;
      drupal_set_message($this
        ->t('AdvAgg Bypass Cookie Set for %time.', [
        '%time' => $this->dateFormatter
          ->formatInterval($form_state
          ->getValue('timespan')),
      ]));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm 26
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
OperationsForm::$advaggAggregates protected property A state information store for the AdvAgg generated aggregates.
OperationsForm::$advaggFiles protected property A state information store for the AdvAgg scanned files.
OperationsForm::$cssCollectionOptimizer protected property The CSS asset collection optimizer service.
OperationsForm::$dateFormatter protected property The date formatter service.
OperationsForm::$jsCollectionOptimizer protected property The JavaScript asset collection optimizer service.
OperationsForm::$privateKey protected property The private key service.
OperationsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
OperationsForm::clearAggregates public function Clear out all advagg cache bins and clear out all advagg aggregated files.
OperationsForm::clearAll public function Clear ALL saved information and aggregates.
OperationsForm::clearMissingFiles public function Scan for missing files and remove the associated entries in the database.
OperationsForm::clearOldUnusedAggregates public function Delete aggregates that have not been accessed in the last 6 weeks.
OperationsForm::clearStaleAggregates public function Clear out all stale advagg aggregated files.
OperationsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
OperationsForm::cronTasksAjax public function Report results from the cron tasks via Ajax.
OperationsForm::drasticTasksAjax public function Report results from the drastic measure tasks via Ajax.
OperationsForm::flushCache public function Perform a smart flush.
OperationsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
OperationsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
OperationsForm::incrementCounter public function Clear out all advagg cache bins and increment the counter.
OperationsForm::tasksAjax public function Report results via Ajax.
OperationsForm::toggleBypassCookie public function Set or remove the AdvAggDisabled cookie.
OperationsForm::__construct public function Constructs the OperationsForm object. Overrides ConfigFormBase::__construct
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.