You are here

function mostpopular_ga_refresh_viewed in Drupal Most Popular 7

Implements the 'refresh_delta' callback for the GA mostpopular viewed service.

Parameters

object $service The service definition.:

object $block The block definition. :

integer $span The number of seconds over which to search.:

integer $last_run the timestamp of the last time this service was run.:

File

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

Code

function mostpopular_ga_refresh_viewed($service, $block, $span, $last_run) {
  $now = time();

  // Google Analytics does not show data from today, so we must start from midnight last night.
  $end_ts = strtotime('-0 days 00:00:00', $now);
  $start_ts = $end_ts - $span;

  // 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(
      'ga:pagePath',
      'ga:pageTitle',
    ),
    'metrics' => 'ga:pageviews',
    'sort_metric' => '-ga:pageviews',
    'filter' => 'ga:pagePath!~' . mostpopular_ga_get_exclude_filter(),
    'start_date' => $start_ts,
    'end_date' => $end_ts,
  );
  $limit = $block->count;
  $data = google_analytics_api_report_data($request, array(
    'refresh' => TRUE,
  ));
  if (isset($data->error)) {
    drupal_set_message(t('Error in Google Analytics API: %error', array(
      '%error' => $data->error,
    )), 'error');
    watchdog('mostpopular_ga', 'Error in Google Analytics API: %error', array(
      '%error' => $data->error,
    ));
  }
  elseif ($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_reports</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;
    }
  }
  else {
    $out = array();
    $urls = array();
    $status = '';
    foreach ($data->results as $v) {
      $url = $v['pagePath'];
      $title = $v['pageTitle'];
      $count = $v['pageviews'];
      if (!isset($urls[$url])) {
        $urls[$url] = TRUE;

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

          // Do not allow duplicate URLs
          if (!isset($urls[$obj->path])) {
            $urls[$obj->path] = TRUE;
            if (empty($obj->title)) {
              $obj->title = str_replace(' | ' . variable_get('site_name', ''), '', $title);
            }
            $out[] = $obj;
            $status .= t('@url (@count)', array(
              '@url' => $url,
              '@count' => $count,
            ));
            if (isset($obj->entity_type)) {
              $status .= t(' is %entity: %id', array(
                '%entity' => $obj->entity_type,
                '%id' => $obj->entity_id,
              ));
            }
          }
        }
      }
      $status .= '<br>';

      // Return only the first results
      if (count($out) >= $limit) {
        break;
      }
    }
    watchdog('mostpopular_ga', 'Found %num items (of %count results)<br/>' . $status, array(
      '%num' => count($out),
      '%count' => count($data->results),
    ), WATCHDOG_DEBUG);
    return $out;
  }
  return FALSE;
}