Coverage index

src/Service/PageAttachmentsService.php

Lines: 94.17%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Service;
6
7
use Drupal\Component\Render\MarkupInterface;
8
use Drupal\Core\Access\AccessResult;
9
use Drupal\Core\Config\ConfigFactoryInterface;
10
use Drupal\Core\Controller\TitleResolverInterface;
11
use Drupal\Core\Extension\ModuleHandlerInterface;
12
use Drupal\Core\Path\CurrentPathStack;
13
use Drupal\Core\Routing\RouteMatchInterface;
14
use Drupal\Core\Session\AccountInterface;
15
use Drupal\Core\Url;
16
use Drupal\Core\Utility\Error;
17
use Drupal\visitors\VisitorsEventInterface;
18
use Drupal\visitors\VisitorsEventPluginManager;
19
use Drupal\visitors\VisitorsPageAttachmentsInterface;
20
use Drupal\visitors\VisitorsSiteSearchDetectorInterface;
21
use Drupal\visitors\VisitorsVisibilityInterface;
22
use Psr\Log\LoggerInterface;
23
use Symfony\Component\HttpFoundation\RequestStack;
24
25
/**
26
 * Visitors Page Attachments Service.
27
 */
28
class PageAttachmentsService implements VisitorsPageAttachmentsInterface {
29
30
  /**
31
   * The config factory.
32
   *
33
   * @var \Drupal\Core\Config\ConfigFactoryInterface
34
   */
35
  protected $configFactory;
36
37
  /**
38
   * The current user service.
39
   *
40
   * @var \Drupal\Core\Session\AccountInterface
41
   */
42
  protected $currentUser;
43
44
  /**
45
   * The module handler service.
46
   *
47
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
48
   */
49
  protected $moduleHandler;
50
51
  /**
52
   * The route match service.
53
   *
54
   * @var \Drupal\Core\Routing\ResettableStackedRouteMatchInterface
55
   */
56
  protected $routeMatch;
57
58
  /**
59
   * The request stack service.
60
   *
61
   * @var \Symfony\Component\HttpFoundation\RequestStack
62
   */
63
  protected $requestStack;
64
65
  /**
66
   * The visitors visibility service.
67
   *
68
   * @var \Drupal\visitors\VisitorsVisibilityInterface
69
   */
70
  protected $visibilityService;
71
72
  /**
73
   * The logger service.
74
   *
75
   * @var \Psr\Log\LoggerInterface
76
   */
77
  protected $logger;
78
79
  /**
80
   * The visitors event plugin manager.
81
   *
82
   * @var \Drupal\visitors\VisitorsEventPluginManager
83
   */
84
  protected $eventPluginManager;
85
86
  /**
87
   * The title resolver.
88
   *
89
   * @var \Drupal\Core\Controller\TitleResolverInterface
90
   */
91
  protected $titleResolver;
92
93
  /**
94
   * The current path.
95
   *
96
   * @var \Drupal\Core\Path\CurrentPathStack
97
   */
98
  protected $currentPath;
99
100
  /**
101
   * Custom events queued for this page.
102
   *
103
   * @var \Drupal\visitors\VisitorsEventInterface
104
   */
105
  protected $events;
106
107
  /**
108
   * The site search detector.
109
   *
110
   * @var \Drupal\visitors\VisitorsSiteSearchDetectorInterface
111
   */
112
  protected $siteSearch;
113
114
  /**
115
   * Constructs a new Page Attachments Service.
116
   *
117
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
118
   *   The config factory.
119
   * @param \Drupal\Core\Session\AccountInterface $current_user
120
   *   The current user service.
121
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
122
   *   The module handler service.
123
   * @param \Drupal\Core\Routing\ResettableStackedRouteMatchInterface $route_match
124
   *   The route match service.
125
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
126
   *   The request stack service.
127
   * @param \Drupal\visitors\VisitorsVisibilityInterface $visibility_service
128
   *   The visitors visibility service.
129
   * @param \Psr\Log\LoggerInterface $logger
130
   *   The logger service.
131
   * @param \Drupal\visitors\VisitorsEventPluginManager $event_plugin_manager
132
   *   The visitors event plugin manager.
133
   * @param \Drupal\Core\Controller\TitleResolverInterface $title_resolver
134
   *   The title resolver.
135
   * @param \Drupal\Core\Path\CurrentPathStack $current_path
136
   *   The current path.
137
   * @param \Drupal\visitors\VisitorsEventInterface $events
138
   *   Custom events queued for this page.
139
   * @param \Drupal\visitors\VisitorsSiteSearchDetectorInterface $siteSearch
140
   *   The site search detector.
141
   */
142
  public function __construct(
143
    ConfigFactoryInterface $config_factory,
144
    AccountInterface $current_user,
145
    ModuleHandlerInterface $module_handler,
146
    RouteMatchInterface $route_match,
147
    RequestStack $request_stack,
148
    VisitorsVisibilityInterface $visibility_service,
149
    LoggerInterface $logger,
150
    VisitorsEventPluginManager $event_plugin_manager,
151
    TitleResolverInterface $title_resolver,
152
    CurrentPathStack $current_path,
153
    VisitorsEventInterface $events,
154
    VisitorsSiteSearchDetectorInterface $siteSearch,
155
  ) {
15616
    $this->configFactory = $config_factory;
15716
    $this->currentUser = $current_user;
15816
    $this->moduleHandler = $module_handler;
15916
    $this->routeMatch = $route_match;
16016
    $this->requestStack = $request_stack;
16116
    $this->visibilityService = $visibility_service;
16216
    $this->logger = $logger;
16316
    $this->eventPluginManager = $event_plugin_manager;
16416
    $this->titleResolver = $title_resolver;
16516
    $this->currentPath = $current_path;
16616
    $this->events = $events;
16716
    $this->siteSearch = $siteSearch;
168
  }
169
170
  /**
171
   * {@inheritdoc}
172
   */
173
  public function pageAttachments(array &$page) {
1742
    $page['#cache']['tags'][] = 'user:' . $this->currentUser->id();
1752
    $page['#cache']['contexts'][] = 'user';
1762
    $page['#cache']['tags'][] = 'config:visitors.settings';
177
1782
    $this->attachToolbar($page);
179
180
    try {
1812
      if ($this->visibilityService->isVisible()) {
1821
        $this->attachMetaData($page);
1831
        $this->attachEntityCounter($page);
1841
        $this->processEvent($page);
185
      }
186
    }
1871
    catch (\Exception $e) {
1881
      Error::logException($this->logger, $e);
189
    }
190
  }
191
192
  /**
193
   * {@inheritdoc}
194
   */
195
  public function pageBottom(array &$page_bottom): void {
1964
    $page_bottom['visitors_noscript'] = [
1974
      '#cache' => [
1984
        'contexts' => ['user', 'url'],
1994
        'tags' => ['config:visitors.settings'],
2004
      ],
2014
    ];
202
203
    try {
2044
      if (!$this->visibilityService->isVisible()) {
2051
        return;
206
      }
2073
      $page_bottom['visitors_noscript'] += $this->buildNoScript();
2083
      $this->attachQueuedEvents($page_bottom);
209
    }
2100
    catch (\Exception $e) {
2110
      Error::logException($this->logger, $e);
212
    }
213
  }
214
215
  /**
216
   * Copies queued trackEvent calls into drupalSettings.
217
   *
218
   * @param array $page_bottom
219
   *   The page bottom render array.
220
   */
221
  protected function attachQueuedEvents(array &$page_bottom): void {
2223
    $events = $this->events->getQueuedEvents();
2233
    if ($events === []) {
2242
      return;
225
    }
2261
    $page_bottom['#attached']['drupalSettings']['visitors']['events'] = $events;
2271
    $page_bottom['#attached']['library'][] = 'visitors/visitors';
228
  }
229
230
  /**
231
   * Builds the noscript image beacon.
232
   *
233
   * Browsers that run JavaScript do not request this image.
234
   *
235
   * @return array
236
   *   The noscript render element, without cache metadata.
237
   */
238
  protected function buildNoScript(): array {
2393
    $request = $this->requestStack->getCurrentRequest();
2403
    $settings = $this->configFactory->get('visitors.settings');
2413
    $query = [
2423
      'send_image' => '1',
2433
      'rec' => '1',
2443
      'url' => $request ? $request->getUri() : '',
2453
      'action_name' => $this->getActionName(),
2463
      'cvar' => $this->getCustomVariables(),
2473
    ];
2483
    if ($settings->get('track.userid') !== FALSE) {
2491
      $query['uid'] = (string) $this->currentUser->id();
250
    }
2513
    $event_variables = $this->getEventVariables();
2523
    if ($event_variables !== NULL) {
2531
      $query['e_cvar'] = $event_variables;
254
    }
255
2563
    $url = Url::fromRoute('visitors.track', [], [
2573
      'query' => $query,
2583
    ])->toString();
259
2603
    return [
2613
      '#type' => 'html_tag',
2623
      '#tag' => 'noscript',
2633
      'paragraph' => [
2643
        '#type' => 'html_tag',
2653
        '#tag' => 'p',
2663
        'image' => [
2673
          '#type' => 'html_tag',
2683
          '#tag' => 'img',
2693
          '#attributes' => [
2703
            'src' => $url,
2713
            'style' => 'border:0',
2723
            'alt' => '',
2733
            'width' => '1',
2743
            'height' => '1',
2753
          ],
2763
        ],
2773
      ],
2783
    ];
279
  }
280
281
  /**
282
   * Page title sent as the tracking action name.
283
   *
284
   * @return string
285
   *   The plain-text page title, or an empty string.
286
   */
287
  protected function getActionName(): string {
2883
    $route = $this->routeMatch->getRouteObject();
2893
    $request = $this->requestStack->getCurrentRequest();
2903
    if (!$route || !$request) {
2911
      return '';
292
    }
293
2942
    $title = $this->titleResolver->getTitle($request, $route);
2952
    return $this->plainTitle($title);
296
  }
297
298
  /**
299
   * Converts a route title to plain text.
300
   *
301
   * @param mixed $title
302
   *   The title from the title resolver.
303
   */
304
  protected function plainTitle(mixed $title): string {
3052
    if ($title === NULL) {
3060
      return '';
307
    }
3082
    if (is_array($title)) {
3090
      if (isset($title['#plain_text'])) {
3100
        $title = $title['#plain_text'];
311
      }
3120
      elseif (isset($title['#markup'])) {
3130
        $title = $title['#markup'];
314
      }
315
      else {
3160
        return '';
317
      }
318
    }
3192
    $is_stringable = is_scalar($title)
3202
      || $title instanceof MarkupInterface
3212
      || $title instanceof \Stringable;
3222
    if (!$is_stringable) {
3230
      return '';
324
    }
325
3262
    return trim(strip_tags((string) $title));
327
  }
328
329
  /**
330
   * JSON page-scope custom variables for the image beacon.
331
   *
332
   * @return string
333
   *   The encoded custom variables.
334
   */
335
  protected function getCustomVariables(): string {
3363
    $path = $this->currentPath->getPath();
3373
    if ($path === '' || $path[0] !== '/') {
3380
      $path = '/' . $path;
339
    }
3403
    $server = gethostname();
341
3423
    $cvar = [
3433
      '1' => ['route', (string) $this->routeMatch->getRouteName()],
3443
      '2' => ['path', $path],
3453
      '3' => ['server', $server === FALSE ? '' : $server],
3463
    ];
3473
    $counter = $this->getEntityCounter();
3483
    if ($counter !== NULL) {
3491
      $cvar['4'] = ['viewed', $counter];
350
    }
351
3523
    return (string) json_encode(
3533
      $cvar,
3543
      JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
3553
    );
356
  }
357
358
  /**
359
   * JSON event-scope custom variables for the image beacon.
360
   *
361
   * Indexes match js/visitors.js: plugin is 5, event is 6, and
362
   * plugin variables start at 7.
363
   *
364
   * @return string|null
365
   *   The encoded event variables, or NULL when there is no event.
366
   */
367
  protected function getEventVariables(): ?string {
3683
    $event = $this->getEvent();
3693
    if ($event === NULL) {
3702
      return NULL;
371
    }
372
3731
    $e_cvar = [];
3741
    if (!empty($event['plugin'])) {
3751
      $e_cvar['5'] = ['plugin', $event['plugin']];
376
    }
3771
    if (!empty($event['event'])) {
3781
      $e_cvar['6'] = ['event', $event['event']];
379
    }
3801
    $variables = $event['variables'] ?? NULL;
3811
    if (is_array($variables) && $variables !== []) {
3821
      $index = 7;
3831
      foreach ($variables as $key => $value) {
3841
        $e_cvar[(string) $index] = [(string) $key, $value];
3851
        $index++;
386
      }
387
    }
3881
    if ($e_cvar === []) {
3890
      return NULL;
390
    }
391
3921
    return (string) json_encode(
3931
      $e_cvar,
3941
      JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
3951
    );
396
  }
397
398
  /**
399
   * Attach meta data to the page.
400
   *
401
   * @param array $page
402
   *   The page attachments array.
403
   */
404
  protected function attachMetaData(array &$page): void {
4053
    $route = $this->routeMatch->getRouteName();
4063
    $request = $this->requestStack->getCurrentRequest();
4073
    $base_path = $request->getBasePath();
4083
    $module_path = $this->moduleHandler->getModule('visitors')->getPath();
409
4103
    $settings = $this->configFactory->get('visitors.settings');
411
4123
    $visitors = &$page['#attached']['drupalSettings']['visitors'];
413
4143
    $visitors['module'] = "$base_path/$module_path";
4153
    $visitors['route'] = $route;
4163
    $visitors['server'] = gethostname();
4173
    $visitors['debug'] = (bool) $settings->get('client_debug');
4183
    if ($settings->get('scroll_depth')) {
4191
      $visitors['scroll_depth'] = TRUE;
420
    }
4213
    $javascript_errors = $settings->get('javascript_errors');
4223
    if (in_array($javascript_errors, ['activity', 'drupal'], TRUE)) {
4232
      $visitors['javascript_errors'] = TRUE;
424
    }
4253
    $visitors['track_downloads'] = (bool) ($settings->get('track_downloads') ?? TRUE);
4263
    $visitors['track_outlinks'] = (bool) ($settings->get('track_outlinks') ?? TRUE);
4273
    $visitors['track_media'] = (bool) ($settings->get('track_media') ?? TRUE);
4283
    $heartbeat = $this->heartbeatInterval($settings->get('heartbeat_interval'));
4293
    if ($heartbeat >= 5) {
4302
      $visitors['heartbeat_interval'] = $heartbeat;
431
    }
4323
    $visitors['track_userid'] = $settings->get('track.userid') !== FALSE;
4333
    $visitors['cookies'] = (bool) ($settings->get('cookies') ?? FALSE);
4343
    $search_count = $this->siteSearch->resultCount();
4353
    if ($search_count !== NULL) {
4360
      $visitors['search_count'] = $search_count;
437
    }
4383
    $page['#attached']['library'][] = 'visitors/visitors';
439
440
  }
441
442
  /**
443
   * Normalizes the heartbeat interval sent to the browser.
444
   *
445
   * A missing value is 15 seconds. Zero turns the heartbeat off.
446
   *
447
   * @param mixed $value
448
   *   The stored interval.
449
   *
450
   * @return int
451
   *   The interval in seconds.
452
   */
453
  protected function heartbeatInterval(mixed $value): int {
4543
    if ($value === NULL || $value === '') {
4552
      return 15;
456
    }
4571
    $interval = (int) $value;
4581
    if ($interval <= 0) {
4591
      return 0;
460
    }
4610
    return max(5, $interval);
462
  }
463
464
  /**
465
   * Visitors toolbar and navigation integration.
466
   *
467
   * @param array $page
468
   *   The page attachments array.
469
   */
470
  protected function attachToolbar(array &$page): void {
4716
    $toolbar_access = AccessResult::allowedIfHasPermissions($this->currentUser, [
4726
      'access visitors',
4736
      'access toolbar',
4746
    ]);
4756
    if ($toolbar_access->isAllowed()) {
4761
      $page['#attached']['library'][] = 'visitors/toolbar';
477
    }
478
4796
    if (!$this->moduleHandler->moduleExists('navigation')) {
4805
      return;
481
    }
482
4831
    $navigation_access = AccessResult::allowedIfHasPermissions($this->currentUser, [
4841
      'access visitors',
4851
      'access navigation',
4861
    ]);
4871
    if ($navigation_access->isAllowed()) {
4881
      $page['#attached']['library'][] = 'visitors/navigation';
489
    }
490
  }
491
492
  /**
493
   * Attach entity counter to the page.
494
   *
495
   * @param array $page
496
   *   The page attachments array.
497
   */
498
  protected function attachEntityCounter(array &$page): void {
4993
    $counter = $this->getEntityCounter();
5003
    if ($counter === NULL) {
5012
      return;
502
    }
5031
    $page['#attached']['drupalSettings']['visitors']['counter'] = $counter;
504
  }
505
506
  /**
507
   * Entity counter value for the current canonical route.
508
   *
509
   * @return string|null
510
   *   The entity type and id, or NULL when the counter does not apply.
511
   */
512
  protected function getEntityCounter(): ?string {
5136
    $route = $this->routeMatch->getRouteName() ?? '';
5146
    $route_array = explode('.', $route);
5156
    $is_canonical = count($route_array) == 3
5166
      && $route_array[0] == 'entity'
5176
      && $route_array[2] == 'canonical';
5186
    if (!$is_canonical) {
5191
      return NULL;
520
    }
521
5225
    $entity_type = $route_array[1];
5235
    $settings = $this->configFactory->get('visitors.settings');
5245
    $entity_types = $settings->get('counter.entity_types') ?? [];
5255
    if (!$settings->get('counter.enabled') || !in_array($entity_type, $entity_types)) {
5263
      return NULL;
527
    }
528
5292
    $entity_id = $this->routeMatch->getParameter($entity_type)->id();
5302
    return "$entity_type:$entity_id";
531
  }
532
533
  /**
534
   * Process visitor events.
535
   *
536
   * @param array $page
537
   *   The page attachments array.
538
   */
539
  protected function processEvent(array &$page): void {
5402
    $event = $this->getEvent();
5412
    if ($event === NULL) {
5421
      return;
543
    }
5441
    $page['#attached']['drupalSettings']['visitors']['event'] = $event;
545
  }
546
547
  /**
548
   * The first matching visitor event for this request.
549
   *
550
   * @return array|null
551
   *   Plugin id, event name, and variables, or NULL.
552
   */
553
  protected function getEvent(): ?array {
5545
    $route = $this->routeMatch->getRouteName();
5555
    $request = $this->requestStack->getCurrentRequest();
556
5575
    $path = $request->getPathInfo();
5585
    $context = [
5595
      'url' => $request->getUri(),
5605
      'path' => $path,
5615
      'route' => $route,
5625
      'uid' => $this->currentUser->id(),
5635
    ];
564
565
    // Get all plugins sorted by weight.
5665
    $definitions = $this->eventPluginManager->getDefinitions();
567
5685
    uasort($definitions, function ($a, $b) {
5691
      return ($a['weight'] ?? 0) <=> ($b['weight'] ?? 0);
5705
    });
571
572
    // Process each plugin until one returns an array.
5735
    foreach ($definitions as $plugin_id => $definition) {
5742
      $plugin = $this->eventPluginManager->createInstance($plugin_id);
5752
      $result = $plugin->process($context);
576
5772
      if ($result !== NULL) {
5782
        return [
5792
          'plugin' => $plugin->getPluginId(),
5802
          'event' => $result['event'],
5812
          'variables' => $result['variables'],
5822
        ];
583
      }
584
    }
585
5863
    return NULL;
587
  }
588
589
}