You are here

function mostpopular_ga_mostpopular_service in Drupal Most Popular 6

Implements hook_mostpopular_service().

See also

hook_mostpopular_service()

File

modules/mostpopular_ga/mostpopular_ga.module, line 24
This module uses the Google Analytics API to provide Most Popular data.

Code

function mostpopular_ga_mostpopular_service($op, $delta = 0, $options = array()) {
  switch ($op) {
    case 'list':
      return array(
        'viewed' => array(
          'name' => t('Google Analytics Most Viewed'),
          'title' => t('Viewed'),
        ),
      );
      break;
    case 'refresh':
      switch ($delta) {
        case 'viewed':

          // Google Analytics does not show data from today.
          // For a query for 24 hours or less, start at midnight last night.
          $now = time();
          if (strtotime('-2 days', $now) <= $options['ts']) {
            $end_ts = strtotime('-0 days 00:00:00', $now);
            $start_ts = $options['ts'] - ($now - $end_ts);
          }
          else {
            $start_ts = $options['ts'];
            $end_ts = $now;
          }

          // Issue a GAPI command

          /*
           * @param $request['#dimensions']  required
           * @param $request['#metrics']     required
           * @param $request['#sort_metric'] optional [default=none]
           * @param $request['#filter']      optional [default=none]
           * @param $request['#start_date']  optional [default=GA release date]
           * @param $request['#end_date']    optional [default=today]
           * @param $request['#start_index'] optional [default=1]
           * @param $request['#max_results'] optional [default=10,000]
           */
          $request = array(
            '#dimensions' => array(
              'pagePath',
            ),
            '#metrics' => 'pageviews',
            '#sort_metric' => '-pageviews',
            '#filter' => 'pagePath != / && pagePath !@ 404.html && pagePath !@ /user && pagePath !@ /admin',
            '#start_date' => $start_ts,
            '#end_date' => $end_ts,
          );
          $data = google_analytics_api_report_data($request);
          if ($data === FALSE) {
            static $message_printed;

            // Only print these error messages once
            if (!$message_printed) {

              // If the user has the appropriate permissions, the Analytics API must not be configured.
              if (user_access('administer Google Analytics settings')) {
                drupal_set_message(t('You must authenticate with the Google Analytics API'), 'error');
                watchdog('mostpopular_ga', 'You must authenticate with the Google Analytics API', NULL, WATCHDOG_WARNING, l('Authenticate', 'admin/settings/google-analytics-api'));
              }
              else {
                drupal_set_message(t("You must have the %perm permission to pull data from Google Analytics.", array(
                  '%perm' => 'administer Google Analytics settings',
                )), 'error');
                watchdog('mostpopular_ga', "You must have the %perm permission to pull data from Google Analytics.\n<p>This is necessary in order to use the Google Analytics Drupal Most Popular service.</p>\n<p>To run cron as an anonymous user, grant the %perm permission to anonymous users.  \nDespite its name, this is safe, at least for the <a href='!download_url'>%version version</a> of the <a href='!gapi_url'>google_analytics_api</a> module.</p>\n<p>Otherwise, you can create a new user and role for the cron script, give it the %perm permission, and <a href='!cron_url'>run cron as this user</a>.", array(
                  '%perm' => 'administer Google Analytics settings',
                  '%version' => '6.x-1.0-alpha1',
                  '!download_url' => 'http://drupal.org/node/557406',
                  '!gapi_url' => 'http://drupal.org/project/google_analytics_api',
                  '!cron_url' => 'http://drupal.org/cron',
                ), WATCHDOG_WARNING, l('Assign Permissions', 'admin/user/permissions'));
              }
              $message_printed = TRUE;
            }
            return FALSE;
          }
          $out = array();
          $urls = array();
          $status = '';
          foreach ($data as $v) {
            $metrics = $v
              ->getMetrics();
            $dimensions = $v
              ->getDimensions();
            $count = $metrics['pageviews'];
            $url = $dimensions['pagePath'];
            $status .= "{$url} ({$count})";

            // Match the URL to a node
            $obj = mostpopular_match_result_nodes($url, $count);
            if (isset($obj)) {

              // Do not allow duplicate URLs
              $url = $obj['url'];
              if (!isset($urls[$url])) {
                $out[] = $obj;
              }
              $urls[$url] = TRUE;
              $status .= " is a node: {$url}";
            }
            $status .= '<br>';

            // Return only the first results
            if (count($out) >= $options['max']) {
              break;
            }
          }
          watchdog('mostpopular_ga', 'Found %num items<br/>' . $status, array(
            '%num' => count($out),
          ), WATCHDOG_DEBUG);
          return $out;
      }
      return FALSE;
    case 'throttles':
      $out = array();
      foreach ($options as $iid => $ts) {

        // Determine the interval
        if ($ts >= strtotime('-2 days -10 minutes')) {
          $out[$iid] = '1 hour';
        }
        elseif ($ts <= strtotime('-2 years')) {
          $out[$iid] = '1 month';
        }
        elseif ($ts <= strtotime('-1 year')) {
          $out[$iid] = '1 week';
        }
        else {
          $out[$iid] = '1 day';
        }
      }
      return $out;
    case 'config':
      $form = array();
      $form['google_auth'] = array(
        '#type' => 'fieldset',
        '#title' => t('Authenticate with Google'),
        '#description' => l(t('Click here to authenticate and select a Google Analytics site to monitor.'), 'admin/settings/google-analytics-api', array(
          'query' => drupal_get_destination(),
        )),
      );
      return $form;
  }
}