Skip to content

Commit

Permalink
feat: use messenger to track proxied requests
Browse files Browse the repository at this point in the history
  • Loading branch information
tinect committed Apr 28, 2024
1 parent c573894 commit 0a8184b
Show file tree
Hide file tree
Showing 12 changed files with 234 additions and 72 deletions.
58 changes: 36 additions & 22 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
{
"name": "tinect/matomo",
"version": "4.2.0",
"description": "Matomo plugin for shopware 6",
"type": "shopware-platform-plugin",
"license": "MIT",
"autoload": {
"psr-4": {
"Tinect\\Matomo\\": "src/"
"name": "tinect/matomo",
"version": "4.2.0",
"description": "Matomo plugin for shopware 6",
"type": "shopware-platform-plugin",
"license": "MIT",
"autoload": {
"psr-4": {
"Tinect\\Matomo\\": "src/"
}
},
"require": {
"shopware/core": "~6.6.0",
"shopware/storefront": "*"
},
"require-dev": {
"phpstan/phpstan-deprecation-rules": "^1.1"
},
"conflict": {
"jinya/matomo-shopware-plugin": "*"
},
"extra": {
"shopware-plugin-class": "Tinect\\Matomo\\TinectMatomo",
"label": {
"de-DE": "Matomo Tracking",
"en-GB": "Matomo Tracking"
}
},
"config": {
"allow-plugins": {
"symfony/runtime": true
}
},
"scripts": {
"phpstan": [
"vendor/bin/phpstan analyze $1"
]
}
},
"require": {
"shopware/core": "~6.6.0"
},
"conflict": {
"jinya/matomo-shopware-plugin": "*"
},
"extra": {
"shopware-plugin-class": "Tinect\\Matomo\\TinectMatomo",
"label": {
"de-DE": "Matomo Tracking",
"en-GB": "Matomo Tracking"
}
}
}
19 changes: 19 additions & 0 deletions phpstan.dist.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
includes:
- vendor/phpstan/phpstan-deprecation-rules/rules.neon

parameters:
level: max
paths:
- src
checkGenericClassInNonGenericObjectType: false

excludePaths:
- ecs.php
- vendor
- **/tests/**

ignoreErrors:
-
message: """
#no value type specified in iterable type array#
"""
54 changes: 54 additions & 0 deletions src/MessageQueue/TrackHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php declare(strict_types=1);

namespace Tinect\Matomo\MessageQueue;

use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Tinect\Matomo\Service\StaticHelper;

#[AsMessageHandler]
class TrackHandler
{
public function __construct(
private readonly SystemConfigService $systemConfigService
) {
}

public function __invoke(TrackMessage $message): void
{
$authToken = $this->systemConfigService->getString('TinectMatomo.config.matomoauthtoken');

if ($authToken === '') {
return;
}

$matomoUrl = StaticHelper::getMatomoUrl($this->systemConfigService);

if ($matomoUrl === null) {
return;
}

$matomoUrl .= 'matomo.php?';

$parameter = $message->parameters;
$parameter['cdt'] = $message->unixTimestamp;
$parameter['token_auth'] = $authToken;

if (!empty($message->clientIp) && $message->clientIp !== '::1') {
$parameter['cip'] = $message->clientIp;
}

foreach ($parameter as $key => $value) {
$matomoUrl .= $key . '=' . urlencode((string) $value) . '&';
}

$stream_options = ['http' => [
'user_agent' => $message->userAgent,
'header' => 'Accept-Language: ' . str_replace(["\n", "\t", "\r"], '', $message->acceptLanguage) . "\r\n",
'timeout' => 5,
]];
$ctx = stream_context_create($stream_options);

file_get_contents($matomoUrl, false, $ctx);
}
}
17 changes: 17 additions & 0 deletions src/MessageQueue/TrackMessage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php declare(strict_types=1);

namespace Tinect\Matomo\MessageQueue;

use Shopware\Core\Framework\MessageQueue\LowPriorityMessageInterface;

class TrackMessage implements LowPriorityMessageInterface
{
public function __construct(
public readonly ?string $clientIp,
public readonly string $userAgent,
public readonly string $acceptLanguage,
public readonly int $unixTimestamp,
public readonly array $parameters,
) {
}
}
2 changes: 1 addition & 1 deletion src/Migration/Migration1710796428MigrateJinyaConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public function update(Connection $connection): void
{
$existingConfig = $connection->fetchAllAssociative('SELECT * FROM system_config WHERE configuration_key LIKE "JinyaMatomo.config.%"');

if (count($existingConfig) === 0) {
if (\count($existingConfig) === 0) {
return;
}

Expand Down
28 changes: 28 additions & 0 deletions src/Migration/Migration1714244310CompleteMatomoServer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Tinect\Matomo\Migration;

use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Migration\MigrationStep;

class Migration1714244310CompleteMatomoServer extends MigrationStep
{
public function getCreationTimestamp(): int
{
return 1714244310;
}

public function update(Connection $connection): void
{
$connection->executeStatement('UPDATE system_config SET
configuration_value = JSON_SET(configuration_value, "$._value", CONCAT("https://", JSON_UNQUOTE(JSON_EXTRACT(configuration_value, "$._value"))))
WHERE configuration_key = "TinectMatomo.config.matomoserver" AND
JSON_UNQUOTE(JSON_EXTRACT(configuration_value, "$._value")) NOT LIKE "http%"');
}

public function updateDestructive(Connection $connection): void
{
}
}
2 changes: 1 addition & 1 deletion src/Resources/config/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/shopware/trunk/src/Core/System/SystemConfig/Schema/config.xsd">
<card>
<title>Tinect Matomo Tracking</title>
<input-field>
<input-field type="url">
<name>matomoserver</name>
<label>Matomo Server</label>
<helpText>The server that is running your matomo instance</helpText>
Expand Down
6 changes: 6 additions & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,15 @@
<service id="Tinect\Matomo\Storefront\Controller\ProxyController" public="true">
<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
<argument type="service" id="cache.object"/>
<argument type="service" id="messenger.bus.shopware"/>
<call method="setContainer">
<argument type="service" id="service_container"/>
</call>
</service>

<service id="Tinect\Matomo\MessageQueue\TrackHandler">
<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
<tag name="messenger.message_handler" />
</service>
</services>
</container>
32 changes: 16 additions & 16 deletions src/Resources/views/storefront/base.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
window._paq.push(['enableHeartBeatTimer']);
{% if activeRoute == "frontend.detail.page" %}
{% if activeRoute == 'frontend.detail.page' %}
window._paq.push([
'setEcommerceView',
'{{ page.product.productNumber|escape('js') }}',
Expand All @@ -19,7 +19,7 @@
{% for item in page.cart.lineItems.elements %}
window._paq.push([
'addEcommerceItem',
'{{ item.payload["productNumber"] }}',
'{{ item.payload['productNumber'] }}',
'{{ item.label }}',
'',
{{ item.price.unitPrice }},
Expand All @@ -34,7 +34,7 @@
{% for item in page.order.lineItems.elements %}
window._paq.push([
'addEcommerceItem',
'{{ item.payload["productNumber"] }}',
'{{ item.payload['productNumber'] }}',
'{{ item.label }}',
'',
{{ item.unitPrice }},
Expand All @@ -52,37 +52,37 @@
]);
{% endif %}
{% set phpTrackingPath = config("TinectMatomo.config.phpTrackingPath") %}
{% set phpTrackingPath = config('TinectMatomo.config.phpTrackingPath') %}
{% if phpTrackingPath is empty %}
{% set phpTrackingPath = 'matomo.php' %}
{% endif %}
{% set jsTrackingPath = config("TinectMatomo.config.jsTrackingPath") %}
{% set jsTrackingPath = config('TinectMatomo.config.jsTrackingPath') %}
{% if jsTrackingPath is empty %}
{% set jsTrackingPath = 'matomo.js' %}
{% endif %}
window.mTrackCall = function() {
if (!window.matomoCookieActive) {
window._paq.push(["disableCookies"]);
window._paq.push(['disableCookies']);
}
window._paq.push(['trackPageView']);
window._paq.push(['enableLinkTracking']);
}
{% set matomoServer = config("TinectMatomo.config.matomoserver") %}
{% set proxyTracking = config("TinectMatomo.config.activateProxyTracking") %}
{% if proxyTracking %}
{% set trackerUrl = seoUrl('frontend.matomo.proxy') %}
{% set trackerJsSrc = seoUrl('frontend.matomo.proxy') %}
{% else %}
{% set trackerUrl = '//' ~ matomoServer ~ '/' ~ phpTrackingPath %}
{% set trackerJsSrc = '//' ~ matomoServer~ '/' ~ jsTrackingPath %}
{% endif %}
{% set matomoServer = config('TinectMatomo.config.matomoserver') %}
{% if matomoServer %}
{% if config('TinectMatomo.config.activateProxyTracking') %}
{% set trackerUrl = seoUrl('frontend.matomo.proxy') %}
{% set trackerJsSrc = seoUrl('frontend.matomo.proxy') %}
{% else %}
{% set trackerUrl = matomoServer ~ '/' ~ phpTrackingPath %}
{% set trackerJsSrc = matomoServer ~ '/' ~ jsTrackingPath %}
{% endif %}
window._paq.push(['setTrackerUrl', '{{ trackerUrl }}']);
window._paq.push(['setSiteId', '{{ config("TinectMatomo.config.matomosite") }}']);
window._paq.push(['setSiteId', '{{ config('TinectMatomo.config.matomosite') }}']);
(function () {
const d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0];
g.type = 'text/javascript';
Expand Down
8 changes: 6 additions & 2 deletions src/Service/CustomCookieProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,13 @@ public function getCookieGroups(): array
{
$cookieGroups = $this->originalService->getCookieGroups();

foreach ($cookieGroups as $key => $group) {
foreach ($cookieGroups as &$group) {
if (!\is_array($group) || !isset($group['snippet_name'])) {
continue;
}

if ($group['snippet_name'] === self::cookieGroup['snippet_name']) {
$cookieGroups[$key]['entries'] = array_merge(
$group['entries'] = array_merge(
$group['entries'],
self::cookieGroup['entries']
);
Expand Down
19 changes: 19 additions & 0 deletions src/Service/StaticHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php declare(strict_types=1);

namespace Tinect\Matomo\Service;

use Shopware\Core\System\SystemConfig\SystemConfigService;

class StaticHelper
{
public static function getMatomoUrl(SystemConfigService $systemConfigService): ?string
{
$matomoServer = $systemConfigService->getString('TinectMatomo.config.matomoserver');

if ($matomoServer === '') {
return null;
}

return \rtrim($matomoServer, '/') . '/';
}
}
Loading

0 comments on commit 0a8184b

Please sign in to comment.