View source  
  <?php
function _ga_stats_update_counts() {
  $client = ga_stats_get_client();
  if (isset($client)) {
    $data = ga_stats_collect_data($client);
  }
  
  if (!empty($data)) {
    db_query('DELETE FROM {ga_stats_count}');
    foreach ($data as $record) {
      ga_stats_write_count($record);
    }
    drupal_set_message(t('Counts Successfully Updated'));
    watchdog('ga_stats', 'Updated statistics for !count records.', array(
      '!count' => count($data),
    ));
    
    return ga_stats_schedule_update();
  }
  return FALSE;
}
function ga_stats_collect_data($client) {
  $data = array();
  $current = time();
  foreach (ga_stats_ga_metrics() as $metric => $title) {
    foreach (ga_stats_ga_timeframes() as $key => $timeframe) {
      $filter = isset($timeframe['filter']) ? $timeframe['filter'] : NULL;
      $results = ga_stats_ga_data($client, $metric, $current - $timeframe['secsToSub'], $current);
      $data = array_merge($data, ga_stats_transform_data($results, $metric, $key));
    }
  }
  return $data;
}
function ga_stats_transform_data($results, $metric, $timeframe = '') {
  $data = array();
  foreach ($results as $record) {
    $item = new stdClass();
    $item->url = $record['url'];
    $item->count = $record[$metric];
    $item->metric = $metric;
    $item->nid = FALSE;
    $item->timeframe = $timeframe;
    $item->nid = ga_stats_nid_from_url($record['url']);
    
    if ($item->nid) {
      $data[] = $item;
    }
  }
  return $data;
}
function ga_stats_nid_from_url($url) {
  $alias = preg_replace('/^\\//', '', $url);
  if (!preg_match('/^node\\/([0-9]*)/', $alias, $matches)) {
    $alias = drupal_lookup_path('source', $alias);
  }
  if (preg_match('/^node\\/([0-9]*)/', $alias, $matches)) {
    return $matches[1];
  }
  return FALSE;
}
function ga_stats_write_count($count) {
  drupal_write_record('ga_stats_count', $count);
}
function ga_stats_ga_data($client, $metrics, $start_date = 0, $end_date = 0, $filter = FALSE) {
  $url_dim = 'pagePath';
  if (!is_array($metrics)) {
    $metrics = array(
      $metrics,
    );
  }
  $request['dimensions'] = array(
    $url_dim,
  );
  $request['metrics'] = $metrics;
  $request['start_date'] = $start_date ? date('Y-m-d', $start_date) : NULL;
  $request['end_date'] = $end_date ? date('Y-m-d', $end_date) : NULL;
  $request['sort_metric'] = "-" . $metrics[0];
  $request['max_results'] = variable_get('ga_stats_max_results', "100");
  if ($filter) {
    $request['filter'] = $filter;
  }
  $data_raw = ga_stats_query_data($client, $request);
  
  if (empty($data_raw)) {
    drupal_set_message(t('Failed to retrieve data from Google Analytics.'), 'error', FALSE);
  }
  $data_array = ga_stats_ga_data_array($data_raw);
  foreach ($data_array as $k => $d) {
    $data_array[$k]['url'] = $d[$url_dim];
  }
  return $data_array;
}
function ga_stats_ga_data_array($data_in) {
  $data_all = array();
  foreach ($data_in as $d) {
    $metrics = $d
      ->getMetrics();
    $dimensions = $d
      ->getDimensions();
    $data_all[] = array_merge($metrics, $dimensions);
  }
  return $data_all;
}
function ga_stats_get_client($suppress = FALSE) {
  require_once 'gapi.class.php';
  $client = NULL;
  $user = variable_get('ga_stats_email', '');
  $p12_key = variable_get('ga_stats_private_key_p12', NULL);
  if ($user && $p12_key) {
    try {
      $client = new gapi($user, $p12_key);
    } catch (Exception $e) {
      $error = t('Invalid Google Analytics App authentication attempt.');
      watchdog('ga_stats', $e
        ->getMessage(), array(), WATCHDOG_ERROR);
    }
  }
  else {
    $error = t('Google Analytics API Email and p12 key are not set.');
    watchdog('ga_stats', 'Google Analytics API Email and p12 key are not set.', array(), WATCHDOG_ERROR);
  }
  if (!$suppress && isset($error)) {
    drupal_set_message($error, 'error');
  }
  if (!isset($error)) {
    watchdog('ga_stats', 'Successfully authenticated client with Google Analytics App.');
  }
  return $client;
}
function ga_stats_ga_get_accounts($client) {
  if (!isset($client)) {
    return array();
  }
  try {
    $accounts = $client
      ->requestAccountData(1, 5000);
  } catch (Exception $e) {
    drupal_set_message(t('Could not retrieve accounts from Google Analytics.'), 'error');
    watchdog('ga_stats', $e
      ->getMessage(), array(), WATCHDOG_ERROR);
    return array();
  }
  return $accounts;
}
function ga_stats_query_data($client, $request) {
  try {
    $data = $client
      ->requestReportData(variable_get('ga_stats_profile', ''), $request['dimensions'], $request['metrics'], $request['sort_metric'], NULL, $request['start_date'], $request['end_date'], 1, $request['max_results']);
  } catch (Exception $e) {
    watchdog('ga_stats', $e
      ->getMessage(), array(), WATCHDOG_ERROR);
    return array();
  }
  if (empty($data)) {
    
    watchdog('ga_stats', 'Successfully contacted Google Analytics, but an empty dataset was found for "!metric" between "!start" and "!end".', array(
      '!metric' => reset($request['metrics']),
      '!start' => $request['start_date'],
      '!end' => $request['end_date'],
    ), WATCHDOG_WARNING);
  }
  else {
    watchdog('ga_stats', 'Successfully retrieved data from Google Analytics.');
  }
  return $data;
}