You are here

class PiwikReportsSettings in Piwik Reports 8

Class PiwikReportsSettings.

Hierarchy

Expanded class hierarchy of PiwikReportsSettings

1 string reference to 'PiwikReportsSettings'
piwik_reports.routing.yml in ./piwik_reports.routing.yml
piwik_reports.routing.yml

File

src/Form/PiwikReportsSettings.php, line 15

Namespace

Drupal\piwik_reports\Form
View source
class PiwikReportsSettings extends ConfigFormBase {

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('piwik_reports.piwikreportssettings');
    $form['piwik_reports_server'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Piwik report server'),
    ];
    $form['piwik_reports_server']['piwik_server_url'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Piwik Server URL'),
      '#description' => $this
        ->t('The URL to your Piwik base directory, e.g., "https://analytics.example.com/piwik/".'),
      '#maxlength' => 255,
      '#size' => 80,
      '#default_value' => $config
        ->get('piwik_server_url'),
    ];
    $form['token_auth'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Token auth'),
      '#description' => $this
        ->t('To see piwik reports in Drupal you need a <strong>token_auth</strong> value. You can find it in the  <strong>Users</strong> tab under the <strong>Settings</strong> link in your Piwik account or ask your Piwik server administrator.'),
    ];
    $form['token_auth']['piwik_reports_token_auth'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Piwik authentication string'),
      '#description' => $this
        ->t('Leave blank if you prefer each user setting their own, or paste it here to have a global <strong>token_auth</strong>. If anonymous users have view permissions in Piwik you can set this value to <strong>anonymous</strong>. Users still need &quot;Access Piwik reports&quot; permission to see the reports in Drupal.'),
      '#maxlength' => 40,
      '#size' => 40,
      '#default_value' => $config
        ->get('piwik_reports_token_auth'),
    ];
    $form['piwik_reports_sites'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Allowed sites'),
      '#description' => $this
        ->t('List sites you want restrict your users access to.'),
    ];
    $sites = PiwikData::getSites($config
      ->get('piwik_reports_token_auth'));
    $allowed_sites_desc = $this
      ->t('List accessible sites id separated by a comma. Example: &quot;1,4,12&quot;. Leave blank to let users see all sites accessible on piwik server with current token auth (highly recommended in case of per user token auth).');
    if (is_array($sites) && count($sites)) {
      if ($config
        ->get('piwik_reports_token_auth')) {
        $allowed_sites_desc .= ' ' . $this
          ->t('Sites currently accessible with global token_auth are:');
      }
      else {
        $allowed_sites_desc .= ' ' . $this
          ->t('Sites current accessible as anonymous are:');
      }
      foreach ($sites as $site) {
        $allowed_sites_desc .= '<br />' . (int) $site['idsite'] . ' - ' . Html::escape($site['name']);
      }
    }
    else {
      $allowed_sites_desc .= ' ' . $this
        ->t('No accessible sites are available with current global token auth. Please check your token auth is correct and that it has view permission on Piwik server.');
    }
    $form['piwik_reports_sites']['piwik_reports_allowed_sites'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Allowed sites'),
      '#description' => $allowed_sites_desc,
      '#maxlength' => 64,
      '#size' => 64,
      '#default_value' => $config
        ->get('piwik_reports_allowed_sites'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $url = $form_state
      ->getValue('piwik_server_url');
    if (!empty($url)) {
      if (substr($url, -1) !== '/') {
        $url .= '/';
        $form_state
          ->setValueForElement($form['piwik_reports_server']['piwik_server_url'], $url);
      }
      $url = $url . 'piwik.php';
      try {
        $result = \Drupal::httpClient()
          ->get($url);
        if ($result
          ->getStatusCode() != 200) {
          $form_state
            ->setErrorByName('piwik_server_url', $this
            ->t('The validation of "@url" failed with error "@error" (HTTP code @code).', [
            '@url' => UrlHelper::filterBadProtocol($url),
            '@error' => $result
              ->getReasonPhrase(),
            '@code' => $result
              ->getStatusCode(),
          ]));
        }
      } catch (RequestException $exception) {
        $form_state
          ->setErrorByName('piwik_server_url', $this
          ->t('The validation of "@url" failed with an exception "@error" (HTTP code @code).', [
          '@url' => UrlHelper::filterBadProtocol($url),
          '@error' => $exception
            ->getMessage(),
          '@code' => $exception
            ->getCode(),
        ]));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $this
      ->config('piwik_reports.piwikreportssettings')
      ->set('piwik_report_server', $form_state
      ->getValue('piwik_report_server'))
      ->set('piwik_server_url', $form_state
      ->getValue('piwik_server_url'))
      ->set('token_auth', $form_state
      ->getValue('token_auth'))
      ->set('piwik_reports_token_auth', $form_state
      ->getValue('piwik_reports_token_auth'))
      ->set('piwik_reports_sites', $form_state
      ->getValue('piwik_reports_sites'))
      ->set('piwik_reports_allowed_sites', $form_state
      ->getValue('piwik_reports_allowed_sites'))
      ->save();
  }

}

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.
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.
PiwikReportsSettings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
PiwikReportsSettings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
PiwikReportsSettings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
PiwikReportsSettings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
PiwikReportsSettings::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.