Далі викачуємо GAPI, заливаємо в sites/default/libraries і створюємо модуль. Назвемо його «internetdevels_chart». У модулі оголошуємо hook_menu:
/**
* Implements hook_menu().
*/
function internetdevels_chart_menu() {
$items['chart'] = array(
'title' => 'Blog posts Statistics',
'page callback' => 'drupal_get_form',
'page arguments' => array('internetdevels_chart_form'),
'access callback' => TRUE,
);
return $items;
}
Функція генерації і обробки форми «internetdevels_chart_form»:
/**
* Generates chart form.
*/
function internetdevels_chart_form($form, $form_state) {
$from = isset($_GET['from']) && preg_match('/[\d-]+/', $_GET['from']) ? $_GET['from'] : '2011-03-30';
$to = isset($_GET['to']) && preg_match('/[\d-]+/', $_GET['to']) ? $_GET['to'] : format_date(REQUEST_TIME, 'custom', 'Y-m-d');
$form['from'] = array(
'#title' => t('From'),
'#type' => 'date_popup',
'#date_format' => 'd/m/Y',
'#default_value' => $from,
);
$form['to'] = array(
'#title' => t('To'),
'#type' => 'date_popup',
'#date_format' => 'd/m/Y',
'#default_value' => $to,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
require_once 'sites/all/libraries/gapi/gapi.class.php';
// We will display statistics only for active users.
$q = db_query("SELECT name FROM {users} WHERE uid > 0 AND status = 1");
$active_users = $authors = array();
foreach ($q as $row) {
$active_users[] = $row->name;
}
// Here you need to puy your google account credentials.
$ga = new gapi('your_email','your_pass');
// Your_profile_ID - the namespaced profile ID of the profile from which to request data.
$ga->requestReportData('Your_profile_ID', array('eventCategory', 'eventAction'), array('totalEvents'), '-totalEvents', 'eventCategory==Blog author', $from, $to);
$rows = array();
foreach($ga->getResults() as $result) {
$dimensions = $result->getDimesions();
$metrics = $result->getMetrics();
$rows[$dimensions['eventAction']] = $metrics['totalEvents'];
}
// Here I'm formatting results for correct displaying in chart.
arsort($rows);
$rows = array_filter($rows);
foreach ($rows as $k => $v) {
$authors[] = "['{$k}', $v]";
}
$tojs = implode(',', $authors);
$out = theme('internetdevels_chart_graph', array('rows' => $tojs));
$form['graph'] = array(
'#type' => 'item',
'#markup' => $out,
);
return $form;
}
/**
* Validate handler for chart form.
*/
function internetdevels_chart_form_validate($form, &$form_state) {
$fv = $form_state['values'];
if (strtotime($fv['from']) > strtotime($fv['to'])) {
form_set_error('from', t('From date cannot be greater then to date'));
}
if (strtotime($fv['to']) > REQUEST_TIME) {
form_set_error('to', t('To date cannot be greater then current date'));
}
}
/**
* Submit handler for chart form.
*/
function internetdevels_chart_form_submit($form, &$form_state) {
$fv = $form_state['values'];
$query = array();
if ($fv['from']) {
$query['from'] = $fv['from'];
}
if ($fv['to']) {
$query['to'] = $fv['to'];
}
$form_state['redirect'] = array(current_path(), array('query' => $query));
}
Для полегшення використання Google Charts API, оголосимо hook_theme:
/**
* Implements of hook_theme().
*/
function internetdevels_chart_theme() {
return array(
'internetdevels_chart_graph' => array(
'template' => 'internetdevels-chart-graph',
'path' => drupal_get_path('module', 'internetdevels_chart')
),
);
}
Як бачимо, результат буде друкуватися в internetdevels-chart-graph, tpl.php, в який буде міститити нехитрий код (javascript друкується без drupal_add_js для наочності):
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
<?php print $rows ?>
]);
// Set chart options
var options = {'width':1100,
'height':800,
'sliceVisibilityThreshold':1/999999,
'backgroundColor':'#F2F2F2'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="text-align:center;"></div>
Для виведення результатів я використав Pie Chart. Повний перелік доступних параметрів можна подивитися тут. Детально описувати не бачу сенсу, так як навіть домогосподарка розбереться, що треба просто скопіювати js-код і підставити свої параметри в масив options.
Результат роботи буде виглядати так:

P. S: Існує веб-інтерфейс для виконання запитів до GA API — Google Analytics Query Explorer 2.
Це посилання дуже корисне в процесі побудови запитів.