1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| <?php
// CMS init...
// Ajout du chemin vers l'api si l'autoload de votre system ne le fait pas.
set_include_path("path/to/google-api-php-client/src/" . PATH_SEPARATOR . get_include_path());
try {
// Récupération de la conf (dans des simili fichiers ini pour moi)
$ini = INI::instance('client.ini');
$APPLICATION_NAME = $ini->variable('GoogleAnalytics', 'APPLICATION_NAME');
$SERVICE_ACCOUNT_KEY_FILE = $ini->variable('GoogleAnalytics', 'SERVICE_ACCOUNT_KEY_FILE'); // 'path/to/google-api-key/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12'
$SERVICE_ACCOUNT_NAME = $ini->variable('GoogleAnalytics', 'SERVICE_ACCOUNT_NAME'); // 'xxxxxxxxxx@developer.gserviceaccount.com';//Email address dans la console google
$GOOGLE_ANALYTICS_VIEW_ID = $ini->variable('GoogleAnalytics', 'GOOGLE_ANALYTICS_VIEW_ID');
$HOSTNAME = $ini->variable('GoogleAnalytics', 'HOSTNAME'); // 'www.monsite.com'
// Vérification de la conf
if(!($APPLICATION_NAME && $SERVICE_ACCOUNT_KEY_FILE && $SERVICE_ACCOUNT_NAME && $GOOGLE_ANALYTICS_VIEW_ID && $HOSTNAME)
|| strpos($APPLICATION_NAME.$SERVICE_ACCOUNT_KEY_FILE.$SERVICE_ACCOUNT_NAME.$GOOGLE_ANALYTICS_VIEW_ID.$HOSTNAME, 'TODO')) {
throw new Exception("La conf n'est pas finie.");
}
if (!is_file($SERVICE_ACCOUNT_KEY_FILE)) {
throw new Exception("le fichier '$SERVICE_ACCOUNT_KEY_FILE' n'existe pas !");
}
// Création du Google_Client et identification
$client = new Google_Client();
$client->setApplicationName($APPLICATION_NAME);
if (isset ( $_SESSION ['service_token'] )) {
$client->setAccessToken ( $_SESSION ['service_token'] );
}
$key = file_get_contents ( $SERVICE_ACCOUNT_KEY_FILE );
$client->setAssertionCredentials ( new Google_Auth_AssertionCredentials ( $SERVICE_ACCOUNT_NAME, array (
Google_Service_Analytics::ANALYTICS_READONLY
), $key ) );
$client->setAccessType('offline');
if ($client->getAuth ()->isAccessTokenExpired ()) {
$client->getAuth ()->refreshTokenWithAssertion ( $cred );
}
$_SESSION ['service_token'] = $client->getAccessToken ();
// Mon objet Google_Service_Analytics
$analytics = new Google_Service_Analytics($client);
// Un peut de doc
// http://ga-dev-tools.appspot.com/explorer/
// https://developers.google.com/analytics/devguides/reporting/core/v3/reference#filters
/**
* Returns Analytics data for a view (profile). (ga.get)
*
* @param string $ids
* Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is
* the Analytics view (profile) ID.
* @param string $startDate
* Start date for fetching Analytics data. Requests can specify a start date formatted as YYYY-MM-
* DD, or as a relative date (e.g., today, yesterday, or 7daysAgo). The default value is 7daysAgo.
* @param string $endDate
* End date for fetching Analytics data. Request can should specify an end date formatted as YYYY-
* MM-DD, or as a relative date (e.g., today, yesterday, or 7daysAgo). The default value is
* yesterday.
* @param string $metrics
* A comma-separated list of Analytics metrics. E.g., 'ga:visits,ga:pageviews'. At least one metric
* must be specified.
* @param array $optParams Optional parameters.
*
* @opt_param int maxResults
* The maximum number of entries to include in this feed.
* @opt_param string sort
* A comma-separated list of dimensions or metrics that determine the sort order for Analytics data.
* @opt_param string dimensions
* A comma-separated list of Analytics dimensions. E.g., 'ga:browser,ga:city'.
* @opt_param int startIndex
* An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
* @opt_param string segment
* An Analytics advanced segment to be applied to data.
* @opt_param string samplingLevel
* The desired sampling level.
* @opt_param string filters
* A comma-separated list of dimension or metric filters to be applied to Analytics data.
* @opt_param string output
* The selected format for the response. Default format is JSON.
*
* @return Google_Service_Analytics_GaData
*/
$r = $analytics->data_ga->get(
'ga:' . $GOOGLE_ANALYTICS_VIEW_ID,
'2014-01-01',
date('Y-m-d'),
'ga:visits,ga:pageviews',
array(
'max-results' => 1000,
//'sort'=>'', // Il faut que j'arrive à trier de façon à récupérer les pages vue récemment.
'dimensions' => 'ga:hostname,ga:pagePath',
'filters' => implode(';', array( // ',' => OR ';' => AND
'ga:hostname=='.$HOSTNAME,
'ga:pagePath=~^/Biens/.*', // Je ne m'interrese qu'aux pages commençant par '/Biens/'
))
)
);
if (! $r->getRows()) {
throw new Exception("Il n'y a aucun résultats !");
}
$sql_values = array();
foreach ($r->getRows() as $row) {
$pagePath = $row[1];
$viewCount = (int)$row[3];
$sql_values[] = "('$pagePath', $viewCount)";
}
$sql = 'INSERT INTO google_analytics_view_count (page_path,view_count) VALUES '.implode(', ',$sql_values).' ON DUPLICATE KEY UPDATE view_count=VALUES(view_count)';
// execution de la requete sql.
} catch (Exception $e) {
SLogger::exception($e);
}
?> |
Partager