Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Google Analytics support #1058

Merged
merged 4 commits into from Aug 3, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
72 changes: 72 additions & 0 deletions includes/downloads.php
Expand Up @@ -23,6 +23,76 @@ function podlove_get_remote_addr() {
return $_SERVER['REMOTE_ADDR'];
}

function ga_track_download($request_id, $media_file, $ua_string, $ptm_context, $ptm_source) {
// GA Tracking
$debug_ga = false;
$ga_collect_endpoint = 'https://www.google-analytics.com/' . ($debug_ga ? 'debug/' : '') . 'collect';

$ga_tracking_id = trim(\Podlove\get_setting('tracking', 'ga'));
if (!$ga_tracking_id || $ga_tracking_id === '') {
return;
}

$ga_params = array(
// Basics
'v' => '1', // version
'tid' => $ga_tracking_id, // tracking id
'cid' => $request_id, // client id
'ua' => $ua_string, // user agent override
'uip' => podlove_get_remote_addr(), // IP override
'ds' => 'podlove', // data source

// We highjack the campaign fields for context/source data.
// Source / Medium maps to Podlove context / Podlove source.
// This way all Podlove sources can be easily grouped into GA Channels.
'cs' => $ptm_context, // campaign source
'cm' => $ptm_source, // campaign medium
'ci' => $media_file->episode()->number, // campaign id
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance concern: do $episode = $media_file->episode() once and use that instead of calling $media_file->episode() repeatedly as it does duplicate database requests each time.

'cn' => $media_file->episode()->title(), // campaign name

// Pageview params
't' => 'pageview', // hit type
'dh' => $_SERVER[HTTP_HOST], // document host
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing quotes here and on next line

'dp' => $_SERVER[REQUEST_URI], // document path
'dt' => $media_file->episode()->title(), // document title
);

$ga_param_fragments = array();
array_walk($ga_params, function($item, $key) use(&$ga_param_fragments) {
array_push($ga_param_fragments, sprintf('%s=%s', $key, rawurlencode($item)));
});

$body = implode('&', $ga_param_fragments);
$curl = new \Podlove\Http\Curl();
$curl->request( $ga_collect_endpoint, array(
'method' => 'POST',
'body' => $body,
));

if (!$curl->isSuccessful()) {
if ($debug_ga) {
header('x-ga-debug: http error');
}
\Podlove\Log::get()->addError('GA Measurement Protocol request failed.');
} else {
\Podlove\Log::get()->addInfo('GA Measurement Protocol request successful: ' . $body);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer addDebug in all success cases so the log isn't flooded with tracking requests.

if (!$debug_ga) {
return;
}

$response = json_decode($curl->get_response()['body'], true);
$hit_paring_result = $response['hitParsingResult'][0];
if ($hit_paring_result['valid']) {
header('x-ga-debug: valid');
\Podlove\Log::get()->addInfo('GA Measurement Protocol hit valid.');
} else {
$debug_message = sprintf('%s(%s): %s', $hit_paring_result['parserMessage'][0]['messageType'], $response['hitParsingResult'][0]['parserMessage'][0]['parameter'], $response['hitParsingResult'][0]['parserMessage'][0]['description']);
header(sprintf('x-ga-debug: ' . $debug_message ));
\Podlove\Log::get()->addError('GA Measurement Protocol hit invalid.', $hit_paring_result['parserMessage'][0]);
}
}
}

function podlove_handle_media_file_tracking(\Podlove\Model\MediaFile $media_file) {

if (\Podlove\get_setting('tracking', 'mode') !== "ptm_analytics")
Expand Down Expand Up @@ -68,6 +138,8 @@ function podlove_handle_media_file_tracking(\Podlove\Model\MediaFile $media_file
}

$intent->save();

ga_track_download($intent->request_id, $media_file, $ua_string, $ptm_context, $ptm_source);
}

function podlove_handle_media_file_download() {
Expand Down
22 changes: 22 additions & 0 deletions lib/settings/expert/tab/tracking.php
Expand Up @@ -93,6 +93,28 @@ public function init() {
/* $section */ 'podlove_settings_episode'
);

add_settings_field(
/* $id */ 'podlove_setting_tracking_google_analytics',
/* $title */ sprintf(
'<label for="mode">%s</label>',
__( 'Google Analytics Tracking ID', 'podlove-podcasting-plugin-for-wordpress' )
),
/* $callback */ function () {
?>

<div><input type="text" name="podlove_tracking[ga]" value="<?php echo(\Podlove\get_setting( 'tracking', 'ga' )) ?> " /></div>
<div>
<?php echo sprintf(
'<div>%s</div>',
__( 'Google Analytics Tracking ID. If entered, Podlove Publisher will log download intents to GA. Leave blank to deactivate GA reporting.', 'podlove-podcasting-plugin-for-wordpress' )
); ?>
</div>
<?php
},
/* $page */ Settings::$pagehook,
/* $section */ 'podlove_settings_episode'
);

add_settings_field(
/* $id */ 'podlove_status_location_database',
/* $title */ sprintf(
Expand Down