Coverage index

src/Controller/VisitorsController.php

Lines: 95.98%

LineHitsSource
1
<?php
2
3
namespace Drupal\visitors\Controller;
4
5
use Drupal\Component\Datetime\TimeInterface;
6
use Drupal\Component\Utility\Unicode;
7
use Drupal\Core\Config\ConfigFactoryInterface;
8
use Drupal\Core\Controller\ControllerBase;
9
use Drupal\Core\State\StateInterface;
10
use Drupal\visitors\Helper\IpAnonymizer;
11
use Drupal\visitors\Helper\UserIdAnonymizer;
12
use Drupal\visitors\Helper\VisitorsUrl;
13
use Drupal\visitors\VisitorsAiAgentInterface;
14
use Drupal\visitors\VisitorsAiAssistantsInterface;
15
use Drupal\visitors\VisitorsCampaignInterface;
16
use Drupal\visitors\VisitorsCookieInterface;
17
use Drupal\visitors\VisitorsCounterInterface;
18
use Drupal\visitors\VisitorsDeviceInterface;
19
use Drupal\visitors\VisitorsLocationResolverInterface;
20
use Drupal\visitors\VisitorsReferrerInterface;
21
use Drupal\visitors\VisitorsSearchEngineInterface;
22
use Drupal\visitors\VisitorsSiteSearchDetectorInterface;
23
use Drupal\visitors\VisitorsSocialNetworksInterface;
24
use Drupal\visitors\VisitorsSpamInterface;
25
use Drupal\visitors\VisitorsTrackerInterface;
26
use Psr\Log\LoggerInterface;
27
use Symfony\Component\DependencyInjection\ContainerInterface;
28
use Symfony\Component\HttpFoundation\Request;
29
use Symfony\Component\HttpFoundation\Response;
30
use Symfony\Component\HttpFoundation\ServerBag;
31
32
/**
33
 * Visitors tracking controller.
34
 */
35
final class VisitorsController extends ControllerBase {
36
37
  /**
38
   * Maximum hits accepted in one bulk body.
39
   *
40
   * Matomo's tracker sends at most 50 hits in one POST.
41
   */
42
  private const BULK_REQUEST_LIMIT = 50;
43
44
  /**
45
   * Maximum raw bulk body size, in bytes.
46
   *
47
   * 512 KiB covers 50 tracker query strings and rejects a body large
48
   * enough to be abusive.
49
   */
50
  private const BULK_BODY_LIMIT = 524288;
51
52
  /**
53
   * The time service.
54
   *
55
   * @var \Drupal\Component\Datetime\TimeInterface
56
   */
57
  protected $time;
58
59
  /**
60
   * The visitors settings.
61
   *
62
   * @var \Drupal\Core\Config\Config
63
   */
64
  protected $settings;
65
66
  /**
67
   * The logger service.
68
   *
69
   * @var \Psr\Log\LoggerInterface
70
   */
71
  protected $logger;
72
73
  /**
74
   * The counter service.
75
   *
76
   * @var \Drupal\visitors\VisitorsCounterInterface
77
   */
78
  protected $counter;
79
80
  /**
81
   * The cookie service.
82
   *
83
   * @var \Drupal\visitors\VisitorsCookieInterface
84
   */
85
  protected $cookie;
86
87
  /**
88
   * The device service.
89
   *
90
   * @var \Drupal\visitors\VisitorsDeviceInterface
91
   */
92
  protected $device;
93
94
  /**
95
   * The tracker service.
96
   *
97
   * @var \Drupal\visitors\VisitorsTrackerInterface
98
   */
99
  protected $tracker;
100
101
  /**
102
   * The search engine service.
103
   *
104
   * @var \Drupal\visitors\VisitorsSearchEngineInterface
105
   */
106
  protected $searchEngine;
107
108
  /**
109
   * The site search detector.
110
   *
111
   * @var \Drupal\visitors\VisitorsSiteSearchDetectorInterface
112
   */
113
  protected $siteSearch;
114
115
  /**
116
   * The spam service.
117
   *
118
   * @var \Drupal\visitors\VisitorsSpamInterface
119
   */
120
  protected $spamService;
121
122
  /**
123
   * The social networks service.
124
   *
125
   * @var \Drupal\visitors\VisitorsSocialNetworksInterface
126
   */
127
  protected $socialNetworksService;
128
129
  /**
130
   * The AI assistants service.
131
   *
132
   * @var \Drupal\visitors\VisitorsAiAssistantsInterface
133
   */
134
  protected $aiAssistantsService;
135
136
  /**
137
   * The AI agent detector.
138
   *
139
   * @var \Drupal\visitors\VisitorsAiAgentInterface
140
   */
141
  protected $aiAgent;
142
143
  /**
144
   * The campaign service.
145
   *
146
   * @var \Drupal\visitors\VisitorsCampaignInterface
147
   */
148
  protected $campaignService;
149
150
  /**
151
   * The referrer parser.
152
   *
153
   * @var \Drupal\visitors\VisitorsReferrerInterface
154
   */
155
  protected $referrer;
156
157
  /**
158
   * The location resolver.
159
   *
160
   * @var \Drupal\visitors\VisitorsLocationResolverInterface
161
   */
162
  protected $locationResolver;
163
164
  /**
165
   * The state service.
166
   *
167
   * @var \Drupal\Core\State\StateInterface
168
   */
169
  protected $state;
170
171
  /**
172
   * Visitor tracker.
173
   *
174
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
175
   *   The config factory service.
176
   * @param \Drupal\Component\Datetime\TimeInterface $time
177
   *   The time service.
178
   * @param \Psr\Log\LoggerInterface $logger
179
   *   The logger service.
180
   * @param \Drupal\visitors\VisitorsCounterInterface $counter
181
   *   The counter service.
182
   * @param \Drupal\visitors\VisitorsCookieInterface $cookie
183
   *   The cookie service.
184
   * @param \Drupal\visitors\VisitorsDeviceInterface $device
185
   *   The device service.
186
   * @param \Drupal\visitors\VisitorsTrackerInterface $tracker
187
   *   The date service.
188
   * @param \Drupal\visitors\VisitorsSearchEngineInterface $search_engine
189
   *   The search engine service.
190
   * @param \Drupal\visitors\VisitorsSiteSearchDetectorInterface $site_search
191
   *   The site search detector.
192
   * @param \Drupal\visitors\VisitorsSpamInterface $spam_service
193
   *   The spam service.
194
   * @param \Drupal\visitors\VisitorsSocialNetworksInterface $social_networks_service
195
   *   The social networks service.
196
   * @param \Drupal\visitors\VisitorsAiAssistantsInterface $ai_assistants_service
197
   *   The AI assistants service.
198
   * @param \Drupal\visitors\VisitorsAiAgentInterface $ai_agent
199
   *   The AI agent detector.
200
   * @param \Drupal\visitors\VisitorsCampaignInterface $campaign_service
201
   *   The campaign service.
202
   * @param \Drupal\visitors\VisitorsReferrerInterface $referrer
203
   *   The referrer parser.
204
   * @param \Drupal\Core\State\StateInterface $state
205
   *   The state service. Holds the user id salt.
206
   * @param \Drupal\visitors\VisitorsLocationResolverInterface $location_resolver
207
   *   The location resolver.
208
   */
209
  public function __construct(
210
    ConfigFactoryInterface $config_factory,
211
    TimeInterface $time,
212
    LoggerInterface $logger,
213
    VisitorsCounterInterface $counter,
214
    VisitorsCookieInterface $cookie,
215
    VisitorsDeviceInterface $device,
216
    VisitorsTrackerInterface $tracker,
217
    VisitorsSearchEngineInterface $search_engine,
218
    VisitorsSiteSearchDetectorInterface $site_search,
219
    VisitorsSpamInterface $spam_service,
220
    VisitorsSocialNetworksInterface $social_networks_service,
221
    VisitorsAiAssistantsInterface $ai_assistants_service,
222
    VisitorsAiAgentInterface $ai_agent,
223
    VisitorsCampaignInterface $campaign_service,
224
    VisitorsReferrerInterface $referrer,
225
    StateInterface $state,
226
    VisitorsLocationResolverInterface $location_resolver,
227
  ) {
228
22976
    $this->settings = $config_factory->get('visitors.settings');
230
23176
    $this->time = $time;
23276
    $this->logger = $logger;
23376
    $this->counter = $counter;
23476
    $this->cookie = $cookie;
23576
    $this->device = $device;
23676
    $this->tracker = $tracker;
23776
    $this->searchEngine = $search_engine;
23876
    $this->siteSearch = $site_search;
23976
    $this->spamService = $spam_service;
24076
    $this->socialNetworksService = $social_networks_service;
24176
    $this->aiAssistantsService = $ai_assistants_service;
24276
    $this->aiAgent = $ai_agent;
24376
    $this->campaignService = $campaign_service;
24476
    $this->referrer = $referrer;
24576
    $this->state = $state;
24676
    $this->locationResolver = $location_resolver;
247
  }
248
249
  /**
250
   * {@inheritdoc}
251
   */
252
  public static function create(ContainerInterface $container): VisitorsController {
25376
    return new self(
25476
      $container->get('config.factory'),
25576
      $container->get('datetime.time'),
25676
      $container->get('logger.channel.visitors'),
25776
      $container->get('visitors.counter'),
25876
      $container->get('visitors.cookie'),
25976
      $container->get('visitors.device'),
26076
      $container->get('visitors.tracker'),
26176
      $container->get('visitors.search_engine'),
26276
      $container->get('visitors.site_search'),
26376
      $container->get('visitors.spam'),
26476
      $container->get('visitors.social_networks'),
26576
      $container->get('visitors.ai_assistants'),
26676
      $container->get('visitors.ai_agent'),
26776
      $container->get('visitors.campaign'),
26876
      $container->get('visitors.referrer'),
26976
      $container->get('state'),
27076
      $container->get('visitors.location_resolver'),
27176
    );
272
273
  }
274
275
  /**
276
   * Tracks one hit, or a Matomo bulk body.
277
   *
278
   * A query string is one hit. A JSON body is bulk:
279
   * {"requests":["?rec=1&url=...",{"url":"..."}],"send_image":0}
280
   * Each requests entry is a query string or a parameter object.
281
   * More than 50 entries, or a body over 512 KiB, is ignored.
282
   * No session or token is required.
283
   *
284
   * @param \Symfony\Component\HttpFoundation\Request $request
285
   *   The tracking request.
286
   *
287
   * @return \Symfony\Component\HttpFoundation\Response
288
   *   A GIF when send_image is set, otherwise an empty 204.
289
   */
290
  public function track(Request $request): Response {
29175
    $bulk = $this->bulkTracking($request);
29275
    $send_image = $bulk['send_image'];
29375
    if (!is_scalar($send_image)) {
2940
      $send_image = FALSE;
295
    }
29675
    $response = $this->getResponse($send_image);
297
298
    // The script is still attached. The hit is dropped here.
299
    // A rejected bulk body must not fall through as a blank page view.
30075
    if ($bulk['rejected'] || $this->isDoNotTrack($request)) {
3018
      return $response;
302
    }
303
30467
    foreach ($bulk['queries'] as $query) {
30567
      $this->trackHit($request, $query);
306
    }
30767
    return $response;
308
  }
309
310
  /**
311
   * Stores one tracking hit.
312
   *
313
   * @param \Symfony\Component\HttpFoundation\Request $request
314
   *   The tracking request.
315
   * @param array $query
316
   *   The tracker parameters for this hit.
317
   */
318
  protected function trackHit(Request $request, array $query): void {
31967
    $server = $request->server;
320
321
    // A heartbeat extends the open visit. It is not another event.
32267
    if ($this->isPing($query)) {
3234
      $this->trackPing($request, $query);
3244
      return;
325
    }
326
327
    // A media ping is not a page view. Parse it before that decision.
32866
    $track_event = $this->trackEventFields($query);
329
    // JavaScript errors are optional. Off drops the beacon. Drupal log
330
    // writes it and does not store a visit or an event.
331
    if (
33266
      $track_event !== NULL
33311
      && $track_event['event_category'] === 'JavaScript Errors'
3343
      && !$this->recordJavaScriptError($track_event, $query)
335
    ) {
3362
      return;
337
    }
33865
    $media = $this->mediaFields($query, $track_event);
339
    if (
34065
      ($media !== NULL || $this->isMediaCategory($track_event))
3414
      && !$this->isTrackingEnabled('track_media')
342
    ) {
3431
      return;
344
    }
345
346
    // Downloads and outlinks share enableLinkTracking. Each is stored
347
    // only while its setting is on. A download wins when both are sent.
34864
    $download_url = $this->downloadUrl($query);
34964
    $outlink_url = $download_url === NULL ? $this->outlinkUrl($query) : NULL;
350
    if (
35164
      $download_url !== NULL
3523
      && !$this->isTrackingEnabled('track_downloads')
353
    ) {
3541
      return;
355
    }
356
    if (
35764
      $outlink_url !== NULL
3583
      && !$this->isTrackingEnabled('track_outlinks')
359
    ) {
3601
      return;
361
    }
362
363
    // A custom action without category and action is not a page view.
364
    // Matomo ignores that beacon, and so does this tracker.
36563
    $page_view = $download_url === NULL
36663
      && $outlink_url === NULL
36763
      && $track_event === NULL
36863
      && $media === NULL;
36963
    if ($page_view && $this->isCustomAction($query)) {
3701
      return;
371
    }
372
37362
    $request_time = $this->time->getRequestTime();
374
37562
    $visit = $this->getDefaultFields();
37662
    $visit['ai_agent'] = $this->aiAgent->isAgent($request) ? 1 : 0;
37762
    $log = [];
378
37962
    $ip = $request->getClientIp();
38062
    if (is_string($ip) && $this->settings->get('ip_anonymize')) {
3811
      $mask_length = (int) ($this->settings->get('ip_mask_length') ?? 1);
3821
      $ip = IpAnonymizer::apply($ip, $mask_length);
383
    }
38462
    $visit['location_ip'] = $ip;
38562
    $uid = $this->resolveUserId($query['uid'] ?? NULL);
38662
    $log['uid'] = $uid;
38762
    $visit['uid'] = $uid;
38862
    $visit['entry_time'] = $request_time;
38962
    $visit['exit_time'] = $request_time;
39062
    $visit['total_time'] = 0;
39162
    $visit['total_page_views'] = 0;
39262
    $visit['total_events'] = 0;
39362
    $visit['returning'] = 0;
39462
    $visit['total_visits'] = 1;
395
39662
    $log['title'] = $query['action_name'] ?? '';
39762
    $log['page_view'] = $query['pv_id'] ?? NULL;
39862
    $log['created'] = $request_time;
399
40062
    $bot_retention_log = $this->settings->get('bot_retention_log');
40162
    $discard_bot = ($bot_retention_log == -1);
40262
    $this->doDeviceDetect($visit, $server);
40362
    if ($discard_bot && $visit['bot']) {
4041
      return;
405
    }
406
40762
    $this->doVisitorId($visit, $query);
40862
    $this->doUrl($log, $query);
40962
    $this->doReferrer($log, $query);
410
41162
    $custom_page_var = $query['cvar'] ?? NULL;
41262
    $this->doCustom($log, $custom_page_var);
413
41462
    $custom_event_var = $query['e_cvar'] ?? NULL;
41562
    $this->doEvent($log, $custom_event_var);
41662
    if ($page_view) {
41752
      $this->doSiteSearch($log, $query);
418
    }
419
42062
    if ($download_url !== NULL) {
421
      // The file address is the hit URL. The page stays on the page view
422
      // that shares this page_view id. event marks the hit as a download.
4232
      $file = new VisitorsUrl($download_url);
4242
      $log['url'] = $file->getUrl();
4252
      $log['url_prefix'] = $file->getPrefix();
4262
      $log['event'] = 'download';
427
    }
42861
    elseif ($outlink_url !== NULL) {
429
      // The clicked address is the hit URL. The page stays on the page
430
      // view that shares this page_view id.
4312
      $link = new VisitorsUrl($outlink_url);
4322
      $log['url'] = $link->getUrl();
4332
      $log['url_prefix'] = $link->getPrefix();
4342
      $log['event'] = 'outlink';
435
    }
43660
    elseif ($track_event !== NULL) {
4379
      $log += $track_event;
438
    }
43954
    elseif ($media === NULL) {
44052
      $this->doCounter($custom_page_var);
441
    }
442
44362
    $this->doConfig($visit, $query);
44462
    $this->doPerformance($log, $query);
445
44662
    $this->doLocalTime($visit, $query);
447
44862
    $languages = $request->getLanguages() ?? [];
44962
    $this->doLanguage($visit, $languages);
45062
    $this->doLocation($visit, $ip, $languages);
451
45262
    $this->doRefererFields($visit, $query);
453
45462
    $visit_id = $this->tracker->getVisitId($visit, $request_time);
45562
    $log['visit_id'] = $visit_id;
456
457
    // A progress ping updates the media row and keeps the visit open.
458
    // It is not an action in the visit log.
45962
    $media_only = $media !== NULL
46062
      && $track_event === NULL
46162
      && $download_url === NULL
46262
      && $outlink_url === NULL;
46362
    if ($media_only) {
4642
      $media['page_view'] = $log['page_view'] ?? NULL;
4652
      $this->tracker->writeMedia($visit_id, $media, $request_time);
4662
      $this->tracker->touchVisit($visit_id, $request_time, $visit['uid'] ?? NULL);
4672
      return;
468
    }
469
470
    // Write fields to database.
47160
    $event_id = $this->tracker->writeEvent($log);
47260
    $page_view_id = $log['page_view'] ?? NULL;
47360
    $this->tracker->creditTime(
47460
      $visit_id,
47560
      $request_time,
47660
      is_string($page_view_id) && $page_view_id !== '' ? $page_view_id : NULL,
47760
      $event_id,
47860
    );
47960
    if ($media !== NULL) {
4801
      $media['page_view'] = $log['page_view'] ?? NULL;
4811
      $this->tracker->writeMedia($visit_id, $media, $request_time);
482
    }
483
48460
    $uid = $visit['uid'] ?? NULL;
48560
    $this->tracker->updateVisit(
48660
      $visit_id,
48760
      $event_id,
48860
      $request_time,
48960
      $uid,
49060
      $page_view,
49160
    );
492
  }
493
494
  /**
495
   * Reads the hits to store for this beacon.
496
   *
497
   * A body without a requests key is one query-string hit. A bulk body
498
   * that is too large, not JSON, or over the hit cap is rejected so it
499
   * cannot be stored as a blank page view.
500
   *
501
   * @param \Symfony\Component\HttpFoundation\Request $request
502
   *   The tracking request.
503
   *
504
   * @return array
505
   *   rejected: TRUE when nothing should be stored. send_image: the
506
   *   raw value for the beacon. queries: parameter arrays.
507
   */
508
  protected function bulkTracking(Request $request): array {
50975
    $content = $request->getContent();
51075
    if (!is_string($content) || !$this->isBulkBody($content)) {
51172
      $query = $request->query->all();
51272
      return [
51372
        'rejected'   => FALSE,
51472
        'send_image' => $query['send_image'] ?? FALSE,
51572
        'queries'    => [$query],
51672
      ];
517
    }
518
5193
    if (strlen($content) > self::BULK_BODY_LIMIT) {
5200
      return [
5210
        'rejected'   => TRUE,
5220
        'send_image' => FALSE,
5230
        'queries'    => [],
5240
      ];
525
    }
526
5273
    $json = json_decode($content, TRUE);
5283
    $requests = is_array($json) ? ($json['requests'] ?? NULL) : NULL;
5293
    if (!is_array($requests)) {
5301
      return [
5311
        'rejected'   => TRUE,
5321
        'send_image' => FALSE,
5331
        'queries'    => [],
5341
      ];
535
    }
536
5372
    $send_image = $json['send_image'] ?? FALSE;
5382
    if (count($requests) > self::BULK_REQUEST_LIMIT) {
5391
      return [
5401
        'rejected'   => TRUE,
5411
        'send_image' => $send_image,
5421
        'queries'    => [],
5431
      ];
544
    }
545
5461
    $queries = [];
5471
    foreach ($requests as $entry) {
5481
      $query = $this->bulkQuery($entry);
5491
      if ($query !== NULL) {
5501
        $queries[] = $query;
551
      }
552
    }
553
5541
    return [
5551
      'rejected'   => FALSE,
5561
      'send_image' => $send_image,
5571
      'queries'    => $queries,
5581
    ];
559
  }
560
561
  /**
562
   * Whether the raw body is a Matomo bulk tracking request.
563
   *
564
   * The tracker posts JSON with a form content type, so the body is
565
   * not in the query or request bags.
566
   *
567
   * @param string $content
568
   *   The raw request body.
569
   *
570
   * @return bool
571
   *   TRUE when the body contains a requests key.
572
   */
573
  protected function isBulkBody(string $content): bool {
57475
    return str_contains($content, '"requests"')
57575
      || str_contains($content, "'requests'");
576
  }
577
578
  /**
579
   * Reads one bulk entry into tracker parameters.
580
   *
581
   * A string is a query string, with or without a leading path. An
582
   * array is a parameter object. Anything else is skipped.
583
   *
584
   * @param mixed $entry
585
   *   One requests entry.
586
   *
587
   * @return array|null
588
   *   The parameters, or NULL when the entry has none.
589
   */
590
  protected function bulkQuery(mixed $entry): ?array {
5911
    if (is_string($entry)) {
5921
      $url = parse_url($entry);
593
      if (
5941
        !is_array($url)
5951
        || empty($url['query'])
5960
        || !is_string($url['query'])
597
      ) {
5981
        return NULL;
599
      }
6000
      $params = [];
6010
      parse_str($url['query'], $params);
6020
      return $params;
603
    }
6041
    if (!is_array($entry)) {
6050
      return NULL;
606
    }
6071
    return $entry;
608
  }
609
610
  /**
611
   * Resolves the user id stored on the visit and the event.
612
   *
613
   * Tracking off, an anonymous id, and an empty id are stored as NULL.
614
   * A plain id is stored as a string. A pseudonym is 32 hex characters.
615
   *
616
   * @param mixed $uid
617
   *   The user id from the tracking request.
618
   *
619
   * @return string|null
620
   *   The value to store, or NULL when the user is not tracked.
621
   */
622
  protected function resolveUserId(mixed $uid): ?string {
62362
    $track = $this->settings->get('track.userid') !== FALSE;
62462
    $anonymize = (bool) $this->settings->get('track.userid_anonymize');
62562
    $anonymous = $uid === NULL || $uid === '' || $uid === 0 || $uid === '0';
62662
    if (!$track || $anonymous) {
62760
      return NULL;
628
    }
629
6303
    $uid = (string) $uid;
6313
    if ($anonymize) {
6321
      return UserIdAnonymizer::apply($uid, $this->userIdSalt());
633
    }
634
6352
    return substr($uid, 0, 32);
636
  }
637
638
  /**
639
   * Returns the site salt used for user id pseudonyms.
640
   *
641
   * The salt is created once and kept in state so it is not exported
642
   * with configuration.
643
   *
644
   * @return string
645
   *   The salt.
646
   */
647
  protected function userIdSalt(): string {
6481
    $salt = $this->state->get('visitors.userid_salt');
6491
    if (is_string($salt) && $salt !== '') {
6501
      return $salt;
651
    }
652
6530
    $salt = bin2hex(random_bytes(20));
6540
    $this->state->set('visitors.userid_salt', $salt);
6550
    return $salt;
656
  }
657
658
  /**
659
   * Get the response.
660
   *
661
   * @param bool $send_image
662
   *   Whether to send the image.
663
   *
664
   * @return \Symfony\Component\HttpFoundation\Response
665
   *   The response.
666
   */
667
  protected function getResponse(bool $send_image): Response {
66875
    $headers = [
66975
      'Cache-Control' => 'no-cache, no-store, must-revalidate',
67075
      'Pragma' => 'no-cache',
67175
      'Expires' => '0',
67275
    ];
67375
    $content = '';
67475
    if ($send_image) {
6752
      $content = $this->getImageContent();
6762
      $headers['Content-Type'] = 'image/gif';
6772
      $headers['Content-Length'] = strlen($content);
678
    }
679
68075
    $response = new Response(
68175
      $content,
68275
      ($send_image) ? Response::HTTP_OK : Response::HTTP_NO_CONTENT,
68375
      $headers,
68475
    );
685
68675
    return $response;
687
  }
688
689
  /**
690
   * Whether this beacon is a heartbeat.
691
   *
692
   * @param array $query
693
   *   The tracker query parameters.
694
   *
695
   * @return bool
696
   *   TRUE when the tracker sent ping=1.
697
   */
698
  protected function isPing(array $query): bool {
69967
    return (string) ($query['ping'] ?? '') === '1';
700
  }
701
702
  /**
703
   * Extends the open visit without storing an event.
704
   *
705
   * A ping that arrives after the session window is ignored. It does
706
   * not open a new visit, bump the counter, or add an event.
707
   *
708
   * @param \Symfony\Component\HttpFoundation\Request $request
709
   *   The tracking request.
710
   * @param array $query
711
   *   The tracker query parameters.
712
   */
713
  protected function trackPing(Request $request, array $query): void {
7144
    $request_time = $this->time->getRequestTime();
7154
    $visit = $this->getDefaultFields();
7164
    $ip = $request->getClientIp();
7174
    if (is_string($ip) && $this->settings->get('ip_anonymize')) {
7180
      $mask_length = (int) ($this->settings->get('ip_mask_length') ?? 1);
7190
      $ip = IpAnonymizer::apply($ip, $mask_length);
720
    }
7214
    $visit['location_ip'] = $ip;
7224
    $this->doDeviceDetect($visit, $request->server);
7234
    $bot_retention_log = $this->settings->get('bot_retention_log');
7244
    if ($bot_retention_log == -1 && !empty($visit['bot'])) {
7250
      return;
726
    }
727
7284
    $this->doVisitorId($visit, $query);
7294
    $this->doConfig($visit, $query);
7304
    $languages = $request->getLanguages() ?? [];
7314
    $this->doLanguage($visit, $languages);
732
7334
    $visit_id = $this->tracker->findOpenVisitId($visit, $request_time);
7344
    if ($visit_id === NULL) {
7352
      return;
736
    }
737
7382
    $page_view = $query['pv_id'] ?? NULL;
7392
    $this->tracker->creditTime(
7402
      $visit_id,
7412
      $request_time,
7422
      is_string($page_view) && $page_view !== '' ? $page_view : NULL,
7432
      NULL,
7442
    );
7452
    $this->tracker->touchVisit(
7462
      $visit_id,
7472
      $request_time,
7482
      $this->resolveUserId($query['uid'] ?? NULL),
7492
    );
750
  }
751
752
  /**
753
   * Whether this beacon should be dropped for Do Not Track.
754
   *
755
   * @param \Symfony\Component\HttpFoundation\Request $request
756
   *   The tracking request.
757
   *
758
   * @return bool
759
   *   TRUE when the setting is on and a Do Not Track header is set.
760
   */
761
  protected function isDoNotTrack(Request $request): bool {
76273
    if (!$this->settings->get('honor_do_not_track')) {
76367
      return FALSE;
764
    }
765
7666
    foreach (['DNT', 'X-Do-Not-Track'] as $header) {
7676
      $value = $request->headers->get($header);
7686
      if (!is_string($value)) {
769
        continue;
770
      }
7716
      $normalized = strtolower(trim($value));
7726
      if ($normalized === '1' || $normalized === 'yes') {
7736
        return TRUE;
774
      }
775
    }
776
7770
    return FALSE;
778
  }
779
780
  /**
781
   * Get the image content.
782
   *
783
   * @return string
784
   *   The image content.
785
   */
786
  protected function getImageContent(): string {
7873
    return hex2bin('47494638396101000100800000000000FFFFFF21F9040100000000002C00000000010001000002024401003B');
788
  }
789
790
  /**
791
   * Get the default fields.
792
   *
793
   * @return array
794
   *   The default fields.
795
   */
796
  protected function getDefaultFields(): array {
79763
    $fields = [
79863
      'bot' => 0,
79963
      'ai_agent' => 0,
80063
    ];
801
80263
    return $fields;
803
  }
804
805
  /**
806
   * Detects the visitor url.
807
   *
808
   * @param string[] $fields
809
   *   The fields array.
810
   * @param string[] $query
811
   *   The query array.
812
   */
813
  protected function doUrl(array &$fields, array $query) {
81462
    $url = $query['url'] ?? '';
81562
    if (!is_string($url)) {
8160
      $url = '';
817
    }
818
    // Attribution reads the raw URL. The stored page drops campaign keys
819
    // so each ad click is not a distinct page.
82062
    $url = $this->campaignService->strip($url);
821
82262
    $visitors_url = new VisitorsUrl($url);
823
82462
    $fields['url'] = $visitors_url->getUrl();
82562
    $fields['url_prefix'] = $visitors_url->getPrefix();
826
  }
827
828
  /**
829
   * Detects the visitor id.
830
   *
831
   * @param string[] $fields
832
   *   The fields array.
833
   * @param string[] $query
834
   *   The query array.
835
   */
836
  protected function doVisitorId(array &$fields, array $query) {
83763
    $visitor_id = $query['_id'] ?? $this->cookie->getId();
83863
    $fields['visitor_id'] = $visitor_id;
839
  }
840
841
  /**
842
   * Detects the referrer.
843
   *
844
   * @param string[] $fields
845
   *   The fields array.
846
   * @param string[] $query
847
   *   The query array.
848
   */
849
  protected function doReferrer(array &$fields, array $query) {
85062
    $referrer = $query['urlref'] ?? '';
85162
    $page = $query['url'] ?? '';
85262
    $page_host = $this->referrer->hostOf(is_string($page) ? $page : '');
85362
    $fields += $this->referrer->storageFields(is_string($referrer) ? $referrer : '', $page_host);
854
  }
855
856
  /**
857
   * Detects the device.
858
   *
859
   * @param string[] $fields
860
   *   The fields array.
861
   * @param \Symfony\Component\HttpFoundation\ServerBag $server
862
   *   The server array.
863
   */
864
  protected function doDeviceDetect(array &$fields, ServerBag $server) {
86563
    if (!$this->device->hasLibrary()) {
8662
      return NULL;
867
    }
868
86963
    $user_agent = $server->get('HTTP_USER_AGENT', '');
87063
    $this->device->doDeviceFields($fields, $user_agent, $server->all());
871
872
  }
873
874
  /**
875
   * Set the fields with data in the custom variable.
876
   */
877
  protected function doCustom(array &$fields, $cvar = NULL) {
87862
    if (!is_null($cvar)) {
8796
      $custom = json_decode($cvar) ?? [];
8806
      foreach ($custom as $c) {
8816
        switch ($c[0]) {
8826
          case 'path':
8836
            $fields['path'] = $c[1];
8846
            break;
885
8866
          case 'route':
8876
            $fields['route'] = $c[1];
8886
            break;
889
8905
          case 'server':
8915
            $fields['server'] = $c[1];
892
            break;
893
894
        }
895
      }
896
    }
897
  }
898
899
  /**
900
   * Reads a Matomo download URL.
901
   *
902
   * The tracker sends the file address in download. The query string is
903
   * kept, matching Matomo, which does not strip parameters from downloads.
904
   *
905
   * @param array $query
906
   *   The tracker query parameters.
907
   *
908
   * @return string|null
909
   *   The file URL, or NULL when this hit is not a download.
910
   */
911
  protected function downloadUrl(array $query): ?string {
91264
    $download = $query['download'] ?? NULL;
91364
    if (!is_scalar($download)) {
91462
      return NULL;
915
    }
9164
    $download = trim((string) $download);
9174
    if ($download === '') {
9181
      return NULL;
919
    }
9203
    return $download;
921
  }
922
923
  /**
924
   * Whether the beacon is an outbound link click.
925
   *
926
   * Matomo sends those clicks as link. Downloads use download instead.
927
   *
928
   * @param array $query
929
   *   The tracker query parameters.
930
   *
931
   * @return bool
932
   *   TRUE when link is present and not blank.
933
   */
934
  protected function isOutlink(array $query): bool {
93563
    $link = $query['link'] ?? NULL;
93663
    if (!is_scalar($link)) {
93760
      return FALSE;
938
    }
9394
    return trim((string) $link) !== '';
940
  }
941
942
  /**
943
   * Reads a Matomo outbound link URL.
944
   *
945
   * The tracker sends the address in link. The query string is kept,
946
   * matching Matomo, which does not strip parameters from outlinks.
947
   *
948
   * @param array $query
949
   *   The tracker query parameters.
950
   *
951
   * @return string|null
952
   *   The link URL, or NULL when this hit is not an outlink.
953
   */
954
  protected function outlinkUrl(array $query): ?string {
95563
    if (!$this->isOutlink($query)) {
95661
      return NULL;
957
    }
9583
    return trim((string) $query['link']);
959
  }
960
961
  /**
962
   * Whether a tracking checkbox is on.
963
   *
964
   * A missing value is on, matching a site that has not saved the form.
965
   *
966
   * @param string $key
967
   *   The visitors.settings key.
968
   *
969
   * @return bool
970
   *   TRUE when the setting is on.
971
   */
972
  protected function isTrackingEnabled(string $key): bool {
9739
    return (bool) ($this->settings->get($key) ?? TRUE);
974
  }
975
976
  /**
977
   * Whether a JavaScript error hit should be stored.
978
   *
979
   * Off drops the beacon. Drupal log writes the message, source location,
980
   * and page URL, then drops the hit. Activity log stores it as an event.
981
   *
982
   * @param array $track_event
983
   *   The event columns for a JavaScript Errors hit.
984
   * @param array $query
985
   *   The tracker query parameters.
986
   *
987
   * @return bool
988
   *   TRUE when the hit should be stored.
989
   */
990
  protected function recordJavaScriptError(
991
    array $track_event,
992
    array $query,
993
  ): bool {
9943
    $mode = $this->settings->get('javascript_errors');
9953
    if ($mode === 'activity') {
9961
      return TRUE;
997
    }
9982
    if ($mode === 'drupal') {
9991
      $url = $query['url'] ?? '';
10001
      $this->logger->error('JavaScript error @message at @location on @url', [
10011
        '@message' => (string) ($track_event['event_name'] ?? ''),
10021
        '@location' => (string) ($track_event['event_action'] ?? ''),
10031
        '@url' => is_scalar($url) ? (string) $url : '',
10041
      ]);
1005
    }
10062
    return FALSE;
1007
  }
1008
1009
  /**
1010
   * Whether a trackEvent is a media interaction.
1011
   *
1012
   * @param array|null $track_event
1013
   *   The event columns, or NULL when this hit is not a trackEvent.
1014
   *
1015
   * @return bool
1016
   *   TRUE for MediaVideo and MediaAudio.
1017
   */
1018
  protected function isMediaCategory(?array $track_event): bool {
101965
    if ($track_event === NULL) {
102058
      return FALSE;
1021
    }
102210
    return in_array($track_event['event_category'], ['MediaVideo', 'MediaAudio'], TRUE);
1023
  }
1024
1025
  /**
1026
   * Reads Matomo media parameters.
1027
   *
1028
   * Ma_id, ma_re, and ma_mt are required. A play or finish on the same
1029
   * beacon increments the matching counter.
1030
   *
1031
   * @param array $query
1032
   *   The tracker query parameters.
1033
   * @param array|null $track_event
1034
   *   The event columns when this beacon is also a trackEvent.
1035
   *
1036
   * @return array|null
1037
   *   The media columns, or NULL when this hit is not media.
1038
   */
1039
  protected function mediaFields(array $query, ?array $track_event): ?array {
104065
    $media_id = $this->truncateMediaString($query['ma_id'] ?? NULL, 32);
104165
    $resource = $this->truncateMediaString($query['ma_re'] ?? NULL, 2000);
104265
    $type = strtolower($this->truncateMediaString($query['ma_mt'] ?? NULL, 16));
104365
    if ($media_id === '' || $resource === '' || !in_array($type, ['video', 'audio'], TRUE)) {
104462
      return NULL;
1045
    }
1046
10474
    $action = '';
10484
    if ($this->isMediaCategory($track_event)) {
10492
      $action = strtolower((string) $track_event['event_action']);
1050
    }
10514
    $player = $this->truncateMediaString($query['ma_pn'] ?? NULL, 32);
10524
    $segments = $this->truncateMediaString($query['ma_se'] ?? NULL, 10000);
1053
10544
    return [
10554
      'media_id' => $media_id,
10564
      'resource' => $resource,
10574
      'media_type' => $type,
10584
      'title' => $this->truncateMediaString($query['ma_ti'] ?? NULL, 255),
10594
      'player' => $player === '' ? 'html5' : $player,
10604
      'spent_time' => $this->mediaInt($query['ma_st'] ?? NULL) ?? 0,
10614
      'length' => $this->mediaInt($query['ma_le'] ?? NULL),
10624
      'progress' => $this->mediaInt($query['ma_ps'] ?? NULL),
10634
      'time_to_play' => $this->mediaInt($query['ma_ttp'] ?? NULL),
10644
      'width' => $this->mediaInt($query['ma_w'] ?? NULL),
10654
      'height' => $this->mediaInt($query['ma_h'] ?? NULL),
10664
      'fullscreen' => ($this->mediaInt($query['ma_fs'] ?? NULL) ?? 0) === 1 ? 1 : 0,
10674
      'segments' => $segments === '' ? NULL : $segments,
10684
      'play_count' => $action === 'play' ? 1 : 0,
10694
      'finish_count' => $action === 'finish' ? 1 : 0,
10704
    ];
1071
  }
1072
1073
  /**
1074
   * Trims and truncates a media string.
1075
   *
1076
   * @param mixed $value
1077
   *   The query value.
1078
   * @param int $length
1079
   *   The maximum stored length.
1080
   *
1081
   * @return string
1082
   *   The stored string, or an empty string when the value is blank.
1083
   */
1084
  protected function truncateMediaString(mixed $value, int $length): string {
108565
    if (!is_scalar($value)) {
108665
      return '';
1087
    }
10884
    $value = trim((string) $value);
10894
    if ($value === '') {
10900
      return '';
1091
    }
10924
    return Unicode::truncate($value, $length, FALSE, FALSE);
1093
  }
1094
1095
  /**
1096
   * Reads a non-negative media number.
1097
   *
1098
   * @param mixed $value
1099
   *   The query value.
1100
   *
1101
   * @return int|null
1102
   *   The rounded number, or NULL when it is missing or negative.
1103
   */
1104
  protected function mediaInt(mixed $value): ?int {
11054
    if (!is_scalar($value)) {
11064
      return NULL;
1107
    }
11084
    $value = trim((string) $value);
11094
    if ($value === '' || !is_numeric($value)) {
11100
      return NULL;
1111
    }
11124
    $number = (int) round((float) $value);
11134
    if ($number < 0) {
11140
      return NULL;
1115
    }
11164
    return $number;
1117
  }
1118
1119
  /**
1120
   * Reads Matomo trackEvent parameters.
1121
   *
1122
   * Category and action are required, matching Matomo. Name and value are
1123
   * optional. A missing or non-numeric value is stored as NULL.
1124
   *
1125
   * @param array $query
1126
   *   The tracker query parameters.
1127
   *
1128
   * @return array|null
1129
   *   The event columns, or NULL when this hit is not a trackEvent.
1130
   */
1131
  protected function trackEventFields(array $query): ?array {
113266
    $category = $this->truncateEventString($query['e_c'] ?? NULL);
113366
    $action = $this->truncateEventString($query['e_a'] ?? NULL);
113466
    if ($category === '' || $action === '') {
113558
      return NULL;
1136
    }
1137
113811
    $name = $this->truncateEventString($query['e_n'] ?? NULL);
1139
114011
    return [
114111
      'event_category' => $category,
114211
      'event_action' => $action,
114311
      'event_name' => ($name === '') ? NULL : $name,
114411
      'event_value' => $this->eventValue($query['e_v'] ?? NULL),
114511
    ];
1146
  }
1147
1148
  /**
1149
   * Whether the beacon is a Matomo custom action.
1150
   *
1151
   * A ca value of 0 is a page view. Any other integer is a custom action,
1152
   * matching Matomo, so the hit is not recorded as a page view.
1153
   *
1154
   * @param array $query
1155
   *   The tracker query parameters.
1156
   *
1157
   * @return bool
1158
   *   TRUE when ca is present and not 0.
1159
   */
1160
  protected function isCustomAction(array $query): bool {
116153
    $ca = $query['ca'] ?? 0;
116253
    return is_scalar($ca) && (int) $ca !== 0;
1163
  }
1164
1165
  /**
1166
   * Trims and truncates a Matomo event string to the column length.
1167
   *
1168
   * @param mixed $value
1169
   *   The query value.
1170
   *
1171
   * @return string
1172
   *   The stored string, or an empty string when the value is blank.
1173
   */
1174
  protected function truncateEventString(mixed $value): string {
117566
    if (!is_scalar($value)) {
117661
      return '';
1177
    }
117813
    $value = trim((string) $value);
117913
    if ($value === '') {
11802
      return '';
1181
    }
118213
    return Unicode::truncate($value, 255, FALSE, FALSE);
1183
  }
1184
1185
  /**
1186
   * Reads an optional Matomo event value.
1187
   *
1188
   * @param mixed $value
1189
   *   The query value.
1190
   *
1191
   * @return float|null
1192
   *   The value, or NULL when it is missing or not numeric.
1193
   */
1194
  protected function eventValue(mixed $value): ?float {
119511
    if (!is_scalar($value)) {
11968
      return NULL;
1197
    }
11984
    $value = trim((string) $value);
11994
    if ($value === '' || !is_numeric($value)) {
12001
      return NULL;
1201
    }
12024
    return (float) $value;
1203
  }
1204
1205
  /**
1206
   * Records a site search on a page view.
1207
   *
1208
   * Search columns replace plugin columns already set for this hit. A page
1209
   * that is not a search is left unchanged.
1210
   *
1211
   * @param array $fields
1212
   *   The event fields.
1213
   * @param array $query
1214
   *   The tracking query.
1215
   */
1216
  protected function doSiteSearch(array &$fields, array $query): void {
121752
    $url = is_string($query['url'] ?? NULL) ? $query['url'] : '';
121852
    $referrer = is_string($query['urlref'] ?? NULL) ? $query['urlref'] : '';
121952
    $search = $this->siteSearch->eventFields(
122052
      (string) ($fields['route'] ?? ''),
122152
      (string) ($fields['path'] ?? ''),
122252
      $url,
122352
      (string) ($fields['referrer_route'] ?? ''),
122452
      (string) ($fields['referrer_path'] ?? ''),
122552
      $referrer,
122652
      $query,
122752
    );
122852
    if ($search === NULL) {
122952
      return;
1230
    }
12315
    $fields = $search + $fields;
1232
  }
1233
1234
  /**
1235
   * Set the fields with data in the custom variable.
1236
   */
1237
  protected function doEvent(array &$fields, $cvar = NULL) {
123862
    if (!is_null($cvar)) {
12393
      $custom = json_decode($cvar);
12403
      foreach ($custom as $c) {
12413
        switch ($c[0]) {
12423
          case 'plugin':
12433
            $fields['plugin'] = $c[1];
12443
            break;
1245
12463
          case 'event':
12473
            $fields['event'] = $c[1];
12483
            break;
1249
12503
          case 'plugin_int_1':
12513
            $fields['plugin_int_1'] = $c[1];
12523
            if ($fields['plugin_int_1'] === 'null') {
12531
              $fields['plugin_int_1'] = NULL;
1254
            }
12551
            break;
1256
12573
          case 'plugin_int_2':
12582
            $fields['plugin_int_2'] = $c[1];
12592
            if ($fields['plugin_int_2'] === 'null') {
12601
              $fields['plugin_int_2'] = NULL;
1261
            }
12621
            break;
1263
12643
          case 'plugin_var_1':
12653
            $fields['plugin_var_1'] = $c[1];
12663
            break;
1267
12682
          case 'plugin_var_2':
12692
            $fields['plugin_var_2'] = $c[1];
12702
            break;
1271
12721
          case 'plugin_var_3':
12731
            $fields['plugin_var_3'] = $c[1];
12741
            break;
1275
12761
          case 'plugin_var_4':
12771
            $fields['plugin_var_4'] = $c[1];
1278
            break;
1279
        }
1280
      }
1281
    }
1282
  }
1283
1284
  /**
1285
   * Record the view of the entity.
1286
   */
1287
  protected function doCounter($cvar = NULL) {
1288
128952
    $viewed = NULL;
129052
    if (!is_null($cvar)) {
12916
      $custom = json_decode($cvar);
12926
      foreach ($custom as $c) {
12936
        if ($c[0] == 'viewed') {
12945
          $viewed = $c[1];
1295
        }
1296
      }
1297
    }
1298
129952
    if (!is_null($viewed)) {
13005
      [$type, $id] = explode(':', $viewed);
13015
      $this->counter->recordView($type, $id);
1302
    }
1303
  }
1304
1305
  /**
1306
   * Set the configuration fields.
1307
   */
1308
  protected function doConfig(array &$fields, array $query) {
1309
131063
    $fields['config_resolution']   = $query['res'] ?? NULL;
131163
    $fields['config_pdf']          = $query['pdf'] ?? NULL;
131263
    $fields['config_flash']        = $query['fla'] ?? NULL;
131363
    $fields['config_java']         = $query['java'] ?? NULL;
131463
    $fields['config_quicktime']    = $query['qt'] ?? NULL;
131563
    $fields['config_realplayer']   = $query['realp'] ?? NULL;
131663
    $fields['config_windowsmedia'] = $query['wma'] ?? NULL;
131763
    $fields['config_silverlight']  = $query['ag'] ?? NULL;
131863
    $fields['config_cookie']       = $query['cookie'] ?? NULL;
1319
  }
1320
1321
  /**
1322
   * Set the performance fields.
1323
   */
1324
  protected function doPerformance(array &$fields, array $query) {
132562
    $fields['pf_network']        = $query['pf_net'] ?? NULL;
132662
    $fields['pf_server']         = $query['pf_srv'] ?? NULL;
132762
    $fields['pf_transfer']       = $query['pf_tfr'] ?? NULL;
132862
    $fields['pf_dom_processing'] = $query['pf_dm1'] ?? NULL;
132962
    $fields['pf_dom_complete']   = $query['pf_dm2'] ?? NULL;
133062
    $fields['pf_on_load']        = $query['pf_onl'] ?? NULL;
1331
133262
    $fields['pf_total'] = ($fields['pf_network'] ?? 0)
133362
    + ($fields['pf_server'] ?? 0)
133462
    + ($fields['pf_transfer'] ?? 0)
133562
    + ($fields['pf_dom_processing'] ?? 0)
133662
    + ($fields['pf_dom_complete'] ?? 0)
133762
    + ($fields['pf_on_load'] ?? 0);
1338
  }
1339
1340
  /**
1341
   * Set the visitor's local time field.
1342
   */
1343
  protected function doLocalTime(array &$fields, array $query) {
134462
    $hours = $query['h'] ?? NULL;
134562
    $minutes = $query['m'] ?? NULL;
134662
    $seconds = $query['s'] ?? NULL;
1347
134862
    $has_null = is_null($hours) || is_null($minutes) || is_null($seconds);
134962
    if ($has_null) {
135061
      return NULL;
1351
    }
1352
13534
    $time = $hours * 3600 + $minutes * 60 + $seconds;
1354
13554
    $fields['localtime'] = $time;
1356
  }
1357
1358
  /**
1359
   * Set the language fields.
1360
   *
1361
   * Accepts only well-formed ISO 639-1 (2-letter) and ISO 639-2 (3-letter)
1362
   * primary tag. Malformed or single-letter tokens are discarded so
1363
   * that bad Accept-Language values never reach the database.
1364
   */
1365
  protected function doLanguage(array &$fields, array $languages) {
136663
    if (empty($languages)) {
13672
      return NULL;
1368
    }
1369
137063
    $language      = $languages[0] ?? '';
137163
    $lang          = explode('_', $language);
137263
    $language_code = strtolower((string) ($lang[0] ?? ''));
1373
137463
    if (!preg_match('/^[a-z]{2,3}$/', $language_code)) {
13752
      return NULL;
1376
    }
1377
137863
    $fields['location_browser_lang'] = $language_code;
1379
1380
    // $fields['location_language'] = $language;
1381
  }
1382
1383
  /**
1384
   * Set the location fields from the selected location plugin.
1385
   *
1386
   * The IP is the address stored on the visit. It may already be masked.
1387
   */
1388
  protected function doLocation(array &$fields, $ip_address, array $languages): void {
138962
    $ip = is_string($ip_address) ? $ip_address : '';
139062
    $place = $this->locationResolver->resolve($ip, $languages);
139162
    if ($place === NULL) {
13925
      return;
1393
    }
139462
    $values = [
139562
      'location_continent' => $place->continent,
139662
      'location_country'   => $place->country,
139762
      'location_region'    => $place->region,
139862
      'location_city'      => $place->city,
139962
      'location_latitude'  => $place->latitude,
140062
      'location_longitude' => $place->longitude,
140162
    ];
140262
    foreach ($values as $field => $value) {
140362
      if ($value !== NULL) {
140462
        $fields[$field] = $value;
1405
      }
1406
    }
1407
  }
1408
1409
  /**
1410
   * Sets the visit referrer fields.
1411
   *
1412
   * Campaign parameters are read from the landing page, then from the
1413
   * tracker's _rcn and _rck values. A campaign on the referrer does not
1414
   * win. A referrer whose host is the viewed page is direct entry.
1415
   */
1416
  protected function doRefererFields(array &$fields, array $query) {
1417
1418
    $referer = [];
141962
    $fields['referer_url'] = $query['urlref'] ?? '';
142062
    $url_ref_parts = parse_url(is_string($fields['referer_url']) ? $fields['referer_url'] : '');
142162
    $fields['referer_name'] = $url_ref_parts['host'] ?? '';
142262
    $url_parts = parse_url(is_string($query['url'] ?? NULL) ? $query['url'] : '');
142362
    $page_host = $url_parts['host'] ?? '';
142462
    $same_host = $page_host !== ''
142562
      && strcasecmp($page_host, (string) $fields['referer_name']) === 0;
1426
142762
    $campaign = $this->campaignFromRequest($query);
142862
    if (is_array($campaign) && $this->hasCampaignAttribution($campaign)) {
14296
      $referer['referer_type'] = 'campaign';
14306
      $referer['referer_name'] = $campaign['campaign'] ?? '';
14316
      $referer['referer_keyword'] = $campaign['keyword'] ?? '';
1432
      $dimensions = [
1433
        'source' => 'campaign_source',
1434
        'medium' => 'campaign_medium',
1435
        'content' => 'campaign_content',
1436
        'campaign_id' => 'campaign_id',
1437
        'group' => 'campaign_group',
1438
        'placement' => 'campaign_placement',
1439
      ];
14406
      foreach ($dimensions as $key => $column) {
14416
        $value = $campaign[$key] ?? NULL;
14426
        $referer[$column] = is_string($value) && $value !== '' ? $value : NULL;
1443
      }
1444
    }
144559
    elseif ($this->spamService->match($fields['referer_name'])) {
14461
      $referer['referer_type'] = 'spam';
1447
    }
144859
    elseif ($fields['referer_url'] === '' || $same_host) {
1449
      $referer['referer_type'] = 'direct';
1450
      $referer['referer_name'] = '';
145147
      $referer['referer_keyword'] = '';
1452
    }
145314
    elseif ($referer_name = $this->socialNetworksService->match($fields['referer_name'])) {
14545
      $referer['referer_type'] = 'social_network';
14555
      $referer['referer_name'] = $referer_name;
1456
    }
145711
    elseif ($referer_name = $this->aiAssistantsService->match($fields['referer_name'])) {
14582
      $referer['referer_type'] = 'ai_assistant';
14592
      $referer['referer_name'] = $referer_name;
1460
    }
14619
    elseif ($data = $this->searchEngine->match($fields['referer_url'])) {
14623
      $referer['referer_type'] = 'search_engine';
14633
      $referer['referer_name'] = $data['name'];
14643
      $referer['referer_keyword'] = $data['keyword'];
1465
    }
1466
    else {
14676
      $referer['referer_type'] = 'website';
1468
    }
1469
147062
    $fields = array_merge($fields, $referer);
1471
1472
  }
1473
1474
  /**
1475
   * Reads the campaign from the landing URL, then from tracker parameters.
1476
   *
1477
   * @param array $query
1478
   *   The tracking query.
1479
   *
1480
   * @return array|null
1481
   *   Parsed campaign values, or NULL when none are present.
1482
   */
1483
  protected function campaignFromRequest(array $query): ?array {
148462
    $landing = $query['url'] ?? NULL;
148562
    $campaign = $this->campaignService->parse(is_string($landing) ? $landing : NULL);
148662
    if ($this->hasCampaignAttribution($campaign)) {
14875
      return $campaign;
1488
    }
1489
149060
    $tracker = [];
149160
    foreach (['_rcn', '_rck'] as $key) {
149260
      $value = $query[$key] ?? NULL;
149360
      if (is_string($value) && $value !== '') {
14941
        $tracker[$key] = $value;
1495
      }
1496
    }
149760
    if ($tracker === []) {
149859
      return $campaign;
1499
    }
1500
15011
    return $this->campaignService->parse(http_build_query($tracker));
1502
  }
1503
1504
  /**
1505
   * Whether parsed campaign data includes a name or source.
1506
   *
1507
   * @param array|null $campaign
1508
   *   Parsed campaign values.
1509
   *
1510
   * @return bool
1511
   *   TRUE when the name or source is a non-empty string.
1512
   */
1513
  protected function hasCampaignAttribution(?array $campaign): bool {
151462
    if (!is_array($campaign)) {
151560
      return FALSE;
1516
    }
15176
    foreach (['campaign', 'source'] as $key) {
1518
      if (
15196
        isset($campaign[$key])
15206
        && is_string($campaign[$key])
15216
        && $campaign[$key] !== ''
1522
      ) {
15236
        return TRUE;
1524
      }
1525
    }
15260
    return FALSE;
1527
  }
1528
1529
}