mostpopular_ga.module in Drupal Most Popular 7
Same filename and directory in other branches
This module uses the Google Analytics API to provide Most Popular data.
File
modules/mostpopular_ga/mostpopular_ga.moduleView source
<?php
// $Id$
/*
* Drupal Most Popular - Showcase the most popular content across your Drupal website and engage your audience.
* Copyright © 2009-2012 New Signature
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
* You can contact New Signature by electronic mail at labs@newsignature.com �or- by U.S. Postal Service at 1100 H St. NW, Suite 940, Washington, DC 20005.
*/
/**
* @file
* This module uses the Google Analytics API to provide Most Popular data.
*/
/**
* Implements hook_mostpopular_service_info().
*
* @see hook_mostpopular_service_info()
*/
function mostpopular_ga_mostpopular_service_info() {
return array(
'viewed' => array(
'name' => t('Google Analytics Most Viewed'),
'title' => t('Viewed'),
'entity_types' => TRUE,
),
);
break;
}
function mostpopular_ga_get_exclude_filter() {
$filter =& drupal_static(__FUNCTION__);
if (!isset($filter)) {
$excludepaths = variable_get('mostpopular_exclude_paths', '');
// Convert path settings to a regular expression.
// Therefore replace newlines with a logical or, /* with asterisks and the <front> with the frontpage.
$to_replace = array(
'/(\\r\\n?|\\n)/',
// newlines
'/\\*/',
// asterisks
'/(^|\\|)<front>($|\\|)/',
);
$replacements = array(
'|',
'.*',
'\\1' . variable_get('site_frontpage', 'node') . '\\2',
);
$filter = '^' . url('') . '(|' . preg_replace($to_replace, $replacements, $excludepaths) . ')$';
}
return $filter;
}
/**
* Implements the 'refresh_delta' callback for the GA mostpopular viewed service.
*
* @param object $service The service definition.
* @param object $block The block definition.
* @param integer $span The number of seconds over which to search.
* @param integer $last_run the timestamp of the last time this service was run.
*/
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;
}
/**
* Implements the 'next_run' callback for the GA Viewed mostpopular service.
*
* Returns the timestamp at which to next refresh the data for this interval.
*
* @param array $service The service definition.
* @param integer $span The number of seconds representing the current interval.
* @param integer $last_run The timestamp at which this service was last run for this interval.
*/
function mostpopular_ga_next_run($service, $span, $last_run) {
// If the interval is 2 days or less, refresh once per hour
if ($span <= 60 * 60 * 24 * 2) {
return strtotime('1 hour', $last_run);
}
elseif ($span >= 60 * 60 * 24 * 365) {
return strtotime('1 week', $last_run);
}
// Otherwise, refresh once per day.
return strtotime('1 day', $last_run);
}
/**
* Implements the 'config_form' callback for the GA View mostpopular service.
*
* @param object $service The service definition.
* @param array $form_state The current state of the form.
*/
function mostpopular_ga_config_form($service, &$form_state) {
$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/config/system/google-analytics-reports'),
);
return $form;
}
Functions
Name | Description |
---|---|
mostpopular_ga_config_form | Implements the 'config_form' callback for the GA View mostpopular service. |
mostpopular_ga_get_exclude_filter | |
mostpopular_ga_mostpopular_service_info | Implements hook_mostpopular_service_info(). |
mostpopular_ga_next_run | Implements the 'next_run' callback for the GA Viewed mostpopular service. |
mostpopular_ga_refresh_viewed | Implements the 'refresh_delta' callback for the GA mostpopular viewed service. |