Die Echtzeit-Besucher stehen jetzt in einer eigenen Karte: Anzahl, Balken je Minute der letzten 30 Minuten, Geräte und eine Liste der gerade angesehenen Seiten (bis 10, mit Balken, ohne "| HifiPlanet"-Anhang). Die Karte holt sich über GET /analytics/realtime jede Minute neue Werte (nur bei sichtbarem Tab). Build neu. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TFDXmUdWg4Ai8x5ehhJvva
398 lines
17 KiB
PHP
398 lines
17 KiB
PHP
<?php
|
|
|
|
namespace App\Support;
|
|
|
|
/**
|
|
* Serverseitige Anbindung an die Google Analytics Data API (GA4), damit sich Kennzahlen
|
|
* im eigenen Admin-Dashboard anzeigen lassen - wie z.B. MonsterInsights das fuer WordPress
|
|
* macht. Authentifizierung per Service-Account (JWT-Bearer-Flow), bewusst ohne die grosse
|
|
* offizielle Google-API-PHP-Client-Bibliothek: nur ein signiertes JWT + zwei HTTP-Aufrufe,
|
|
* das reicht fuer diesen einen Report-Endpunkt komplett aus.
|
|
*/
|
|
class GoogleAnalyticsReporting
|
|
{
|
|
private const TOKEN_URI = 'https://oauth2.googleapis.com/token';
|
|
private const SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
|
|
private const API_BASE = 'https://analyticsdata.googleapis.com/v1beta';
|
|
|
|
public static function credentialsPath(): string
|
|
{
|
|
return __DIR__ . '/../../config/ga-service-account.json';
|
|
}
|
|
|
|
public static function hasCredentials(): bool
|
|
{
|
|
return is_file(self::credentialsPath());
|
|
}
|
|
|
|
private static function base64UrlEncode(string $data): string
|
|
{
|
|
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
|
|
}
|
|
|
|
private static function credentials(): array
|
|
{
|
|
$raw = file_get_contents(self::credentialsPath());
|
|
$data = json_decode((string) $raw, true);
|
|
if (!is_array($data) || empty($data['client_email']) || empty($data['private_key'])) {
|
|
throw new \RuntimeException('Service-Account-JSON ist unvollständig oder ungültig.');
|
|
}
|
|
return $data;
|
|
}
|
|
|
|
/**
|
|
* Server-zu-Server-Authentifizierung per JWT-Bearer-Flow - kein Nutzer-Login/Consent-Screen
|
|
* noetig, siehe https://developers.google.com/identity/protocols/oauth2/service-account.
|
|
*/
|
|
private static function fetchAccessToken(array $credentials): string
|
|
{
|
|
$now = time();
|
|
$header = self::base64UrlEncode(json_encode(['alg' => 'RS256', 'typ' => 'JWT']));
|
|
$claims = self::base64UrlEncode(json_encode([
|
|
'iss' => $credentials['client_email'],
|
|
'scope' => self::SCOPE,
|
|
'aud' => self::TOKEN_URI,
|
|
'iat' => $now,
|
|
'exp' => $now + 3600,
|
|
]));
|
|
|
|
$signatureInput = $header . '.' . $claims;
|
|
$privateKey = openssl_pkey_get_private($credentials['private_key']);
|
|
if ($privateKey === false) {
|
|
throw new \RuntimeException('Privater Schlüssel im Service-Account-JSON ist ungültig.');
|
|
}
|
|
openssl_sign($signatureInput, $signature, $privateKey, OPENSSL_ALGO_SHA256);
|
|
$jwt = $signatureInput . '.' . self::base64UrlEncode($signature);
|
|
|
|
$response = self::post(self::TOKEN_URI, http_build_query([
|
|
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
|
'assertion' => $jwt,
|
|
]), ['Content-Type: application/x-www-form-urlencoded']);
|
|
|
|
if (empty($response['access_token'])) {
|
|
throw new \RuntimeException('Google-Token-Anfrage fehlgeschlagen: ' . ($response['error_description'] ?? $response['error'] ?? 'unbekannter Fehler'));
|
|
}
|
|
|
|
return $response['access_token'];
|
|
}
|
|
|
|
private static function post(string $url, string $body, array $headers): array
|
|
{
|
|
$ch = curl_init($url);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_POST => true,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_HTTPHEADER => $headers,
|
|
CURLOPT_POSTFIELDS => $body,
|
|
CURLOPT_TIMEOUT => 15,
|
|
]);
|
|
$raw = curl_exec($ch);
|
|
if ($raw === false) {
|
|
$error = curl_error($ch);
|
|
curl_close($ch);
|
|
throw new \RuntimeException('Verbindung zu Google fehlgeschlagen: ' . $error);
|
|
}
|
|
curl_close($ch);
|
|
|
|
$data = json_decode((string) $raw, true);
|
|
return is_array($data) ? $data : [];
|
|
}
|
|
|
|
private static function runReport(string $propertyId, string $token, array $body): array
|
|
{
|
|
$response = self::post(
|
|
self::API_BASE . '/properties/' . $propertyId . ':runReport',
|
|
json_encode($body),
|
|
['Authorization: Bearer ' . $token, 'Content-Type: application/json']
|
|
);
|
|
|
|
if (isset($response['error'])) {
|
|
throw new \RuntimeException('Google Analytics Data API: ' . ($response['error']['message'] ?? 'unbekannter Fehler'));
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
|
|
/**
|
|
* Verbindungstest fuer System > Verbindungstest: holt ein Token und fragt einen
|
|
* winzigen Report ab - klappt das, funktioniert auch das Dashboard-Widget.
|
|
*/
|
|
public static function testConnection(string $propertyId): array
|
|
{
|
|
$credentials = self::credentials();
|
|
$token = self::fetchAccessToken($credentials);
|
|
$report = self::runReport($propertyId, $token, [
|
|
'dateRanges' => [['startDate' => '7daysAgo', 'endDate' => 'today']],
|
|
'metrics' => [['name' => 'activeUsers']],
|
|
]);
|
|
|
|
return [
|
|
'client_email' => $credentials['client_email'],
|
|
'users_7d' => (int) ($report['rows'][0]['metricValues'][0]['value'] ?? 0),
|
|
];
|
|
}
|
|
|
|
/** Nur die (nicht geheime) Service-Account-Adresse - fuer Hinweise im Verbindungstest. */
|
|
public static function clientEmail(): ?string
|
|
{
|
|
try {
|
|
return self::credentials()['client_email'];
|
|
} catch (\Throwable $e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Kennzahlen (Nutzer/Sitzungen/Seitenaufrufe je Tag) sowie die meistbesuchten Seiten
|
|
* der letzten $days Tage - genau das, was das Dashboard-Widget anzeigt.
|
|
*/
|
|
public static function fetchDashboardReport(string $propertyId, int $days = 7): array
|
|
{
|
|
$credentials = self::credentials();
|
|
$token = self::fetchAccessToken($credentials);
|
|
|
|
$daily = self::runReport($propertyId, $token, [
|
|
'dateRanges' => [['startDate' => $days . 'daysAgo', 'endDate' => 'today']],
|
|
'dimensions' => [['name' => 'date']],
|
|
'metrics' => [['name' => 'activeUsers'], ['name' => 'sessions'], ['name' => 'screenPageViews']],
|
|
'orderBys' => [['dimension' => ['dimensionName' => 'date']]],
|
|
]);
|
|
|
|
$topPages = self::runReport($propertyId, $token, [
|
|
'dateRanges' => [['startDate' => $days . 'daysAgo', 'endDate' => 'today']],
|
|
'dimensions' => [['name' => 'pagePath']],
|
|
'metrics' => [['name' => 'screenPageViews']],
|
|
'orderBys' => [['metric' => ['metricName' => 'screenPageViews'], 'desc' => true]],
|
|
'limit' => 5,
|
|
]);
|
|
|
|
$dailyRows = array_map(fn($row) => [
|
|
'date' => $row['dimensionValues'][0]['value'],
|
|
'users' => (int) $row['metricValues'][0]['value'],
|
|
'sessions' => (int) $row['metricValues'][1]['value'],
|
|
'pageviews' => (int) $row['metricValues'][2]['value'],
|
|
], $daily['rows'] ?? []);
|
|
|
|
$topPageRows = array_map(fn($row) => [
|
|
'path' => $row['dimensionValues'][0]['value'],
|
|
'pageviews' => (int) $row['metricValues'][0]['value'],
|
|
], $topPages['rows'] ?? []);
|
|
|
|
return [
|
|
'daily' => $dailyRows,
|
|
'top_pages' => $topPageRows,
|
|
'totals' => [
|
|
'users' => array_sum(array_column($dailyRows, 'users')),
|
|
'sessions' => array_sum(array_column($dailyRows, 'sessions')),
|
|
'pageviews' => array_sum(array_column($dailyRows, 'pageviews')),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function batchRunReports(string $propertyId, string $token, array $requests): array
|
|
{
|
|
$response = self::post(
|
|
self::API_BASE . '/properties/' . $propertyId . ':batchRunReports',
|
|
json_encode(['requests' => $requests]),
|
|
['Authorization: Bearer ' . $token, 'Content-Type: application/json']
|
|
);
|
|
|
|
if (isset($response['error'])) {
|
|
throw new \RuntimeException('Google Analytics Data API: ' . ($response['error']['message'] ?? 'unbekannter Fehler'));
|
|
}
|
|
|
|
return $response['reports'] ?? [];
|
|
}
|
|
|
|
/**
|
|
* Ausfuehrlicher Bericht fuer die Seite "Besucher" im Admin: Kennzahlen mit Vergleich zum
|
|
* vorherigen Zeitraum gleicher Laenge, Tagesverlauf beider Zeitraeume, Seiten, Kanaele,
|
|
* Quellen, Geraete, Orte, Interaktionen (eigene Events) und die Echtzeit-Besucher.
|
|
* Das Ergebnis (ohne Echtzeit) wird 5 Minuten zwischengespeichert, damit Umschalten und
|
|
* Neuladen nicht jedes Mal acht Abfragen an Google schicken.
|
|
*/
|
|
public static function fetchTrafficReport(string $propertyId, int $days, bool $refresh = false): array
|
|
{
|
|
$credentials = self::credentials();
|
|
$token = self::fetchAccessToken($credentials);
|
|
|
|
$cacheFile = sys_get_temp_dir() . '/hifi-ga-' . md5($propertyId . '|' . $days) . '.json';
|
|
$report = null;
|
|
if (!$refresh && is_file($cacheFile) && filemtime($cacheFile) > time() - 300) {
|
|
$report = json_decode((string) file_get_contents($cacheFile), true);
|
|
}
|
|
if (!is_array($report)) {
|
|
$report = self::buildTrafficReport($propertyId, $token, $days);
|
|
@file_put_contents($cacheFile, json_encode($report));
|
|
}
|
|
|
|
$report['realtime'] = self::fetchRealtime($propertyId, $token);
|
|
return $report;
|
|
}
|
|
|
|
private static function buildTrafficReport(string $propertyId, string $token, int $days): array
|
|
{
|
|
// Aktueller Zeitraum = die letzten $days Tage inkl. heute, Vergleich = die $days Tage davor.
|
|
$current = ['startDate' => ($days - 1) . 'daysAgo', 'endDate' => 'today', 'name' => 'current'];
|
|
$previous = ['startDate' => (2 * $days - 1) . 'daysAgo', 'endDate' => $days . 'daysAgo', 'name' => 'previous'];
|
|
$both = [$current, $previous];
|
|
|
|
$kpiMetrics = ['activeUsers', 'newUsers', 'sessions', 'screenPageViews', 'averageSessionDuration', 'engagementRate'];
|
|
|
|
$first = self::batchRunReports($propertyId, $token, [
|
|
['dateRanges' => $both, 'metrics' => array_map(fn($m) => ['name' => $m], $kpiMetrics)],
|
|
[
|
|
'dateRanges' => [['startDate' => (2 * $days - 1) . 'daysAgo', 'endDate' => 'today']],
|
|
'dimensions' => [['name' => 'date']],
|
|
'metrics' => [['name' => 'activeUsers'], ['name' => 'sessions'], ['name' => 'screenPageViews']],
|
|
'orderBys' => [['dimension' => ['dimensionName' => 'date']]],
|
|
],
|
|
self::breakdownRequest($both, 'pagePath', 'screenPageViews', 100),
|
|
self::breakdownRequest($both, 'sessionDefaultChannelGroup', 'sessions', 40),
|
|
self::breakdownRequest($both, 'deviceCategory', 'activeUsers', 20),
|
|
]);
|
|
|
|
$second = self::batchRunReports($propertyId, $token, [
|
|
self::breakdownRequest($both, 'sessionSource', 'sessions', 60),
|
|
self::breakdownRequest([$current], 'city', 'activeUsers', 10),
|
|
self::breakdownRequest($both, 'eventName', 'eventCount', 60),
|
|
self::breakdownRequest([$current], 'landingPage', 'sessions', 10),
|
|
]);
|
|
|
|
// KPIs: Zeilen tragen bei zwei Zeitraeumen deren Namen als letzte Dimension.
|
|
$kpis = [];
|
|
foreach ($kpiMetrics as $metric) {
|
|
$kpis[$metric] = ['current' => 0, 'previous' => 0];
|
|
}
|
|
foreach ($first[0]['rows'] ?? [] as $row) {
|
|
$range = end($row['dimensionValues'])['value'] ?? 'current';
|
|
foreach ($kpiMetrics as $i => $metric) {
|
|
$kpis[$metric][$range] = (float) ($row['metricValues'][$i]['value'] ?? 0);
|
|
}
|
|
}
|
|
|
|
// Tagesverlauf: fehlende Tage (ohne Besucher liefert GA keine Zeile) mit 0 auffuellen.
|
|
$byDate = [];
|
|
foreach ($first[1]['rows'] ?? [] as $row) {
|
|
$byDate[$row['dimensionValues'][0]['value']] = [
|
|
'users' => (int) $row['metricValues'][0]['value'],
|
|
'sessions' => (int) $row['metricValues'][1]['value'],
|
|
'pageviews' => (int) $row['metricValues'][2]['value'],
|
|
];
|
|
}
|
|
$series = ['current' => [], 'previous' => []];
|
|
$today = new \DateTimeImmutable('today');
|
|
for ($i = 2 * $days - 1; $i >= 0; $i--) {
|
|
$date = $today->modify("-{$i} days")->format('Ymd');
|
|
$point = ['date' => $date] + ($byDate[$date] ?? ['users' => 0, 'sessions' => 0, 'pageviews' => 0]);
|
|
$series[$i >= $days ? 'previous' : 'current'][] = $point;
|
|
}
|
|
|
|
return [
|
|
'days' => $days,
|
|
'kpis' => $kpis,
|
|
'daily' => $series,
|
|
'pages' => self::breakdownRows($first[2], 15),
|
|
'channels' => self::breakdownRows($first[3], 10),
|
|
'devices' => self::breakdownRows($first[4], 5),
|
|
'sources' => self::breakdownRows($second[0], 10),
|
|
'cities' => self::breakdownRows($second[1], 10),
|
|
'events' => self::breakdownRows($second[2], 30),
|
|
'landing_pages' => self::breakdownRows($second[3], 10),
|
|
'generated_at' => date('c'),
|
|
];
|
|
}
|
|
|
|
private static function breakdownRequest(array $ranges, string $dimension, string $metric, int $limit): array
|
|
{
|
|
return [
|
|
'dateRanges' => $ranges,
|
|
'dimensions' => [['name' => $dimension]],
|
|
'metrics' => [['name' => $metric]],
|
|
'orderBys' => [['metric' => ['metricName' => $metric], 'desc' => true]],
|
|
'limit' => $limit,
|
|
];
|
|
}
|
|
|
|
/** Fasst die Zeilen einer Aufschluesselung zu [name, current, previous] zusammen, sortiert nach aktuell. */
|
|
private static function breakdownRows(array $report, int $limit): array
|
|
{
|
|
$rows = [];
|
|
foreach ($report['rows'] ?? [] as $row) {
|
|
$name = $row['dimensionValues'][0]['value'] ?? '';
|
|
$range = count($row['dimensionValues']) > 1 ? end($row['dimensionValues'])['value'] : 'current';
|
|
$rows[$name] ??= ['name' => $name, 'current' => 0, 'previous' => 0];
|
|
$rows[$name][$range] = (int) ($row['metricValues'][0]['value'] ?? 0);
|
|
}
|
|
$rows = array_values(array_filter($rows, fn($r) => $r['current'] > 0));
|
|
usort($rows, fn($a, $b) => $b['current'] <=> $a['current']);
|
|
return array_slice($rows, 0, $limit);
|
|
}
|
|
|
|
/**
|
|
* Besucher der letzten 30 Minuten (Echtzeit-API): Gesamtzahl, auf welchen Seiten sie sind
|
|
* (Seitentitel - die Echtzeit-API kennt keinen Seitenpfad), Verlauf je Minute und Geraete.
|
|
* Faellt die Echtzeit-Abfrage aus, kommt null - der restliche Bericht bleibt nutzbar.
|
|
*/
|
|
private static function fetchRealtime(string $propertyId, string $token): ?array
|
|
{
|
|
$run = function (array $body) use ($propertyId, $token): array {
|
|
$response = self::post(
|
|
self::API_BASE . '/properties/' . $propertyId . ':runRealtimeReport',
|
|
json_encode($body),
|
|
['Authorization: Bearer ' . $token, 'Content-Type: application/json']
|
|
);
|
|
if (isset($response['error'])) {
|
|
throw new \RuntimeException($response['error']['message'] ?? 'Echtzeit-Fehler');
|
|
}
|
|
return $response;
|
|
};
|
|
$rows = fn(array $response) => array_map(fn($row) => [
|
|
'name' => $row['dimensionValues'][0]['value'],
|
|
'users' => (int) $row['metricValues'][0]['value'],
|
|
], $response['rows'] ?? []);
|
|
|
|
try {
|
|
$pages = $run([
|
|
'dimensions' => [['name' => 'unifiedScreenName']],
|
|
'metrics' => [['name' => 'activeUsers']],
|
|
'orderBys' => [['metric' => ['metricName' => 'activeUsers'], 'desc' => true]],
|
|
'limit' => 10,
|
|
'metricAggregations' => ['TOTAL'],
|
|
]);
|
|
$minutes = $run([
|
|
'dimensions' => [['name' => 'minutesAgo']],
|
|
'metrics' => [['name' => 'activeUsers']],
|
|
]);
|
|
$devices = $run([
|
|
'dimensions' => [['name' => 'deviceCategory']],
|
|
'metrics' => [['name' => 'activeUsers']],
|
|
]);
|
|
} catch (\Throwable $e) {
|
|
return null;
|
|
}
|
|
|
|
// minutesAgo kommt nur fuer Minuten mit Besuchern - auf 30 Werte (vor 29 Min. .. jetzt) auffuellen.
|
|
$perMinute = array_fill(0, 30, 0);
|
|
foreach ($rows($minutes) as $row) {
|
|
$ago = (int) $row['name'];
|
|
if ($ago >= 0 && $ago < 30) {
|
|
$perMinute[29 - $ago] = $row['users'];
|
|
}
|
|
}
|
|
|
|
return [
|
|
'users' => (int) ($pages['totals'][0]['metricValues'][0]['value'] ?? 0),
|
|
'pages' => $rows($pages),
|
|
'per_minute' => $perMinute,
|
|
'devices' => $rows($devices),
|
|
'fetched_at' => date('c'),
|
|
];
|
|
}
|
|
|
|
/** Nur die Echtzeit-Werte - fuer das automatische Aktualisieren der Live-Karte jede Minute. */
|
|
public static function fetchRealtimeReport(string $propertyId): ?array
|
|
{
|
|
return self::fetchRealtime($propertyId, self::fetchAccessToken(self::credentials()));
|
|
}
|
|
}
|