You are here

GoogleUniversalAnalyticsService.php in Analytics 7

File

analytics_google/src/GoogleUniversalAnalyticsService.php
View source
<?php

class GoogleUniversalAnalyticsService extends AnalyticsService {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return array(
      'id' => NULL,
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm($form, &$form_state) {
    $options['id'] = array(
      '#title' => t('Tracking ID'),
      '#type' => 'textfield',
      '#default_value' => $this
        ->getConfiguration()['id'],
      '#element_validate' => array(
        '_analytics_google_validate_id',
      ),
      '#required' => TRUE,
      '#size' => 15,
    );
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function getOutput(array $context) {

    // Support AMP analytics
    if (module_exists('amp') && amp_is_amp_request()) {
      $settings = array();
      $settings['config_json'] = array();
      $settings['config_json'] = array();
      $settings['config_json']['vars']['account'] = $this
        ->getConfiguration()['id'];
      $settings['config_json']['triggers']['track'] = array(
        'on' => 'visible',
        'request' => 'pageview',
      );
      $settings['type'] = 'googleanalytics';
      $output = $this
        ->getAmpOutput($settings, $context);
      return $output;
    }
    $actions = array();
    $actions[] = array(
      'create',
      $this
        ->getConfiguration()['id'],
      'auto',
      array(
        'name' => $this
          ->getMachineName(),
      ),
    );
    if (variable_get('analytics_privacy_anonymize_ip', FALSE)) {
      $actions[] = array(
        $this
          ->getMachineName() . '.set',
        'anonymizeIp',
        TRUE,
      );
    }
    $actions[] = array(
      $this
        ->getMachineName() . '.send',
      'pageview',
    );
    $actions = array_merge($actions, module_invoke_all('analytics_google_universal_actions', $this, $context));
    drupal_alter('analytics_google_universal_actions', $actions, $this, $context);
    $code = theme('analytics_google_universal_js', array(
      'actions' => $actions,
      'service' => $this,
    ));
    $output = array();
    $output['#attached']['js'][] = array(
      'data' => $code,
      'type' => 'inline',
      //'weight' => 100000,
      'preprocess' => FALSE,
      'scope' => 'footer',
    );
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableUrls() {
    $urls = array();

    // if ($this->service->options['cache']) {
    $urls[] = 'https://www.google-analytics.com/analytics.js';

    // }
    return $urls;
  }

}