You are here

class MatomoReportsController in Matomo Reports 8

Class MatomoReportsController.

Hierarchy

Expanded class hierarchy of MatomoReportsController

File

src/Controller/MatomoReportsController.php, line 15

Namespace

Drupal\matomo_reports\Controller
View source
class MatomoReportsController extends ControllerBase {

  /**
   * The form builder service.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

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

  /**
   * Constructs a MatomoReportsController object.
   *
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder service.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(FormBuilderInterface $form_builder, MessengerInterface $messenger) {
    $this->formBuilder = $form_builder;
    $this->messenger = $messenger;
  }

  /**
   * Reports.
   *
   * @return array
   *   Return Reports render array.
   */
  public function reports(Request $request, $report) {
    $token_auth = MatomoData::getToken();
    $session = $request
      ->getSession();
    if (!$token_auth) {
      $session
        ->set('matomo_reports_site', '');
      $this->messenger
        ->addWarning($this
        ->t('A valid token authentication string has not been entered. Please check authentication string and permissions with your Matomo server administrator.'));
      return [];
    }
    else {
      $sites = MatomoData::getSites($token_auth);
      if (!$sites) {
        $this->messenger
          ->addWarning($this
          ->t('You cannot access any data on the selected Matomo server. Please check with your Matomo administrator for allowed sites.'));
        return [];
      }
    }
    $build['reports_form'] = $this->formBuilder
      ->getForm('Drupal\\matomo_reports\\Form\\ReportsForm', $sites = $sites);
    $matomo_site_id = $session
      ->get('matomo_reports_site');
    $period = $session
      ->get('matomo_reports_period') ?? 0;
    if ($period == 1) {

      // Special handling for "yesterday" = 1.
      // The yesterday date value is required.
      $date = $this
        ->selectPeriod($period);
    }
    else {

      // Otherwise it returns the today date value.
      $date = $this
        ->selectPeriod(0);
    }
    $period_name = $this
      ->getPeriodName($period);

    // Create an array of URL parameters for easier maintenance.
    $data_params[0] = [];
    $data_params[0]['idSite'] = $matomo_site_id;
    $data_params[0]['date'] = $date;
    $data_params[0]['period'] = $period_name;
    $data_params[0]['disableLink'] = 1;
    $data_params[0]['module'] = 'Widgetize';
    $data_params[0]['action'] = 'iframe';
    $data_params[0]['disableLink'] = 1;
    $data_params[0]['widget'] = 1;

    // $data_params[0]['loading'] = $this->t('Loading data...');.
    if (!empty($token_auth)) {
      $data_params[0]['token_auth'] = $token_auth;
    }
    switch ($report) {
      case 'visitors_overview':
        $iframe_height[0] = 950;
        $title[0] = '';
        $data_params[0]['moduleToWidgetize'] = 'VisitsSummary';
        $data_params[0]['actionToWidgetize'] = 'index';
        break;
      case 'visitors_times':
        $title[0] = $this
          ->t('Visits by Local Time');
        $data_params[0]['moduleToWidgetize'] = 'VisitTime';
        $data_params[0]['actionToWidgetize'] = 'getVisitInformationPerLocalTime';
        break;
      case 'visitors_settings':
        $data_params[0]['filter_limit'] = 6;
        $data_params[1] = $data_params[0];
        $data_params[2] = $data_params[0];
        $data_params[3] = $data_params[0];

        // Browser families.
        $title[0] = $this
          ->t('Browser families');
        $data_params[0]['moduleToWidgetize'] = 'DevicesDetection';
        $data_params[0]['actionToWidgetize'] = 'getBrowserEngines';

        // Screen resolutions.
        $title[1] = $this
          ->t('Screen resolution');
        $data_params[1]['moduleToWidgetize'] = 'Resolution';
        $data_params[1]['actionToWidgetize'] = 'getConfiguration';

        // Operating systems.
        $title[2] = $this
          ->t('Operating system');
        $data_params[2]['moduleToWidgetize'] = 'DevicesDetection';
        $data_params[2]['actionToWidgetize'] = 'getOsVersions';

        // Client configurations.
        $title[3] = $this
          ->t('Client configuration');
        $data_params[3]['moduleToWidgetize'] = 'Resolution';
        $data_params[3]['actionToWidgetize'] = 'getResolution';
        break;
      case 'visitors_locations':
        $title[0] = $this
          ->t('Visitors Countries');
        $iframe_height[0] = 750;
        $data_params[0]['moduleToWidgetize'] = 'UserCountry';
        $data_params[0]['actionToWidgetize'] = 'getCountry';
        $data_params[0]['filter_limit'] = 15;
        break;
      case 'visitors_variables':
        $title[0] = $this
          ->t('Custom Variables');
        $iframe_height[0] = 1000;
        $data_params[0]['moduleToWidgetize'] = 'CustomVariables';
        $data_params[0]['actionToWidgetize'] = 'getCustomVariables';
        $data_params[0]['filter_limit'] = 15;
        break;
      case 'actions_pages':
        $title[0] = $this
          ->t('Page Visits');
        $iframe_height[0] = 750;
        $data_params[0]['moduleToWidgetize'] = 'Actions';
        $data_params[0]['actionToWidgetize'] = 'getPageUrls';
        $data_params[0]['filter_limit'] = 15;
        break;
      case 'actions_entrypages':
        $title[0] = $this
          ->t('Entry Pages');
        $iframe_height[0] = 750;
        $data_params[0]['moduleToWidgetize'] = 'Actions';
        $data_params[0]['actionToWidgetize'] = 'getEntryPageUrls';
        $data_params[0]['filter_limit'] = 15;
        break;
      case 'actions_exitpages':
        $title[0] = $this
          ->t('Exit Pages');
        $iframe_height[0] = 750;
        $data_params[0]['moduleToWidgetize'] = 'Actions';
        $data_params[0]['actionToWidgetize'] = 'getExitPageUrls';
        $data_params[0]['filter_limit'] = 15;
        break;
      case 'actions_sitesearch':
        $data_params[1] = $data_params[0];
        $data_params[2] = $data_params[0];
        $data_params[3] = $data_params[0];
        $title[0] = $this
          ->t('Site Search Keywords');
        $iframe_height[0] = 750;
        $data_params[0]['moduleToWidgetize'] = 'Actions';
        $data_params[0]['actionToWidgetize'] = 'getSiteSearchKeywords';
        $data_params[0]['filter_limit'] = 15;

        // Pages following search.
        $title[1] = $this
          ->t('Pages Following a Site Search');
        $data_params[1]['moduleToWidgetize'] = 'Actions';
        $data_params[1]['actionToWidgetize'] = 'getPageUrlsFollowingSiteSearch';

        // No results.
        $title[2] = $this
          ->t('Site Search No Result Keyword');
        $data_params[2]['moduleToWidgetize'] = 'Actions';
        $data_params[2]['actionToWidgetize'] = 'getSiteSearchNoResultKeywords';

        // Categories.
        $title[3] = $this
          ->t('Site Search Categories');
        $data_params[3]['moduleToWidgetize'] = 'Actions';
        $data_params[3]['actionToWidgetize'] = 'getSiteSearchCategories';
        break;
      case 'actions_outlinks':
        $title[0] = $this
          ->t('Outlinks');
        $iframe_height[0] = 750;
        $data_params[0]['moduleToWidgetize'] = 'Actions';
        $data_params[0]['actionToWidgetize'] = 'getOutlinks';
        $data_params[0]['filter_limit'] = 15;
        break;
      case 'actions_downloads':
        $title[0] = $this
          ->t('Downloads');
        $iframe_height[0] = 750;
        $data_params[0]['moduleToWidgetize'] = 'Actions';
        $data_params[0]['actionToWidgetize'] = 'getDownloads';
        $data_params[0]['filter_limit'] = 15;
        break;
      case 'referrers_overview':
        $iframe_height[0] = 550;
        $title[0] = '';
        $data_params[0]['moduleToWidgetize'] = 'Referrers';
        $data_params[0]['actionToWidgetize'] = 'index';
        break;
      case 'referrers_allreferrers':
        $data_params[1] = $data_params[0];

        // Types.
        $title[0] = $this
          ->t('Referrer Types');
        $iframe_height[0] = 250;
        $data_params[0]['moduleToWidgetize'] = 'Referrers';
        $data_params[0]['actionToWidgetize'] = 'getReferrerType';

        // Referrers.
        $title[1] = $this
          ->t('Referrers');
        $data_params[1]['moduleToWidgetize'] = 'Referrers';
        $data_params[1]['actionToWidgetize'] = 'getAll';
        break;
      case 'referrers_search':
        $data_params[1] = $data_params[0];
        $title[0] = $this
          ->t('Search Engines');
        $data_params[0]['moduleToWidgetize'] = 'Referrers';
        $data_params[0]['actionToWidgetize'] = 'getSearchEngines';
        $title[1] = $this
          ->t('Keywords');
        $data_params[1]['moduleToWidgetize'] = 'Referrers';
        $data_params[1]['actionToWidgetize'] = 'getKeywords';
        break;
      case 'referrers_websites':
        $data_params[1] = $data_params[0];
        $title[0] = $this
          ->t('Websites');
        $iframe_height[0] = 1020;
        $data_params[0]['moduleToWidgetize'] = 'Referrers';
        $data_params[0]['actionToWidgetize'] = 'getWebsites';
        $title[1] = $this
          ->t('Social Networks');
        $data_params[1]['moduleToWidgetize'] = 'Referrers';
        $data_params[1]['actionToWidgetize'] = 'getSocials';
        break;
      case 'referrers_campaigns':
        $title[0] = $this
          ->t('Campaigns');
        $data_params[0]['moduleToWidgetize'] = 'Referrers';
        $data_params[0]['actionToWidgetize'] = 'getCampaigns';
        break;
      case 'goals':
        $goals = $this
          ->getGoals($token_auth, $session
          ->get('matomo_reports_site'));
        if (count($goals) == 0) {
          $empty_text = $this
            ->t('No goals have been set. Check with your Matomo server administrator if you desire some.');
          $title[0] = NULL;
          break;
        }
        $common_data_params = $data_params[0];
        $i = 0;
        foreach ($goals as $goal) {
          $title[$i] = $goal['name'];
          $data_params[$i] = $common_data_params;
          $data_params[$i]['moduleToWidgetize'] = 'Goals';
          $data_params[$i]['actionToWidgetize'] = 'widgetGoalReport';
          $data_params[$i]['idGoal'] = $goal['idgoal'];
          $i++;
        }
        break;
    }
    $request
      ->setSession($session);

    // Build the data URL with all params and urlencode it.
    foreach ($data_params as $key => $data) {
      $theme_args[] = [
        'url' => MatomoData::getUrl() . 'index.php?' . http_build_query($data),
        'title' => $title[$key],
        'iframe_height' => isset($iframe_height[$key]) && $iframe_height[$key] > 0 ? $iframe_height[$key] : 400,
        'empty_text' => isset($empty_text) ? $empty_text : NULL,
      ];
    }
    $build['content'] = [
      '#theme' => 'matomo_reports',
      '#data_url' => $theme_args,
    ];
    return $build;
  }

  /**
   * Return a list of goals active on selected site.
   *
   * @param string $token_auth
   *   Matomo server token auth.
   * @param string $site
   *   Selected site id.
   *
   * @return array|string|bool
   *   Goals returned from Matomo reports API.
   */
  private function getGoals($token_auth, $site) {
    $matomo_url = MatomoData::getUrl();
    if ($matomo_url) {
      return MatomoData::getResponse($matomo_url . 'index.php?module=API&method=Goals.getGoals&idSite=' . (int) $site . '&format=JSON&token_auth=' . $token_auth);
    }
    else {
      return FALSE;
    }
  }

  /**
   * Helper function.
   *
   * Returns the starting and ending dates according to the selected period.
   *
   * @param int $period
   *   Selected period.
   *
   * @return string
   *   Formatted date.
   */
  private function selectPeriod($period) {
    switch ($period) {
      case 0:
        $date = date("Y-m-d");
        break;
      case 1:
        $d = mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"));
        $date = date("Y-m-d", $d);
        break;
      case 2:
        $d = mktime(0, 0, 0, date("m"), date("d") - 7, date("Y"));
        $date = date("Y-m-d", $d);
        break;
      case 3:
        $d = mktime(0, 0, 0, date("m") - 1, date("d"), date("Y"));
        $date = date("Y-m-d", $d);
        break;
      case 4:
        $d = mktime(0, 0, 0, date("m"), date("d"), date("Y") - 1);
        $date = date("Y-m-d", $d);
        break;
    }
    return $date;
  }

  /**
   * Helper function to return the name of the selected period.
   *
   * @param int $period
   *   Selected period.
   *
   * @return string
   *   Name of period.
   */
  private function getPeriodName($period) {

    // Possible periods are day, week, month, year.
    switch ($period) {
      case 0:
        $p = "day";
        break;
      case 1:
        $p = "day";
        break;
      case 2:
        $p = "week";
        break;
      case 3:
        $p = "month";
        break;
      case 4:
        $p = "year";
        break;
    }
    return $p;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
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.
MatomoReportsController::$formBuilder protected property The form builder service. Overrides ControllerBase::$formBuilder
MatomoReportsController::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
MatomoReportsController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
MatomoReportsController::getGoals private function Return a list of goals active on selected site.
MatomoReportsController::getPeriodName private function Helper function to return the name of the selected period.
MatomoReportsController::reports public function Reports.
MatomoReportsController::selectPeriod private function Helper function.
MatomoReportsController::__construct public function Constructs a MatomoReportsController object.
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.