Coverage index

src/Plugin/views/row/VisitLong.php

Lines: 81.71%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Plugin\views\row;
6
7
use DeviceDetector\Parser\Client\Browser;
8
use DeviceDetector\Parser\OperatingSystem;
9
use Drupal\Core\Config\ConfigFactoryInterface;
10
use Drupal\Core\Database\Connection;
11
use Drupal\Core\Datetime\DateFormatterInterface;
12
use Drupal\Core\Extension\ModuleExtensionList;
13
use Drupal\Core\StringTranslation\TranslatableMarkup;
14
use Drupal\views\Attribute\ViewsRow;
15
use Drupal\views\Plugin\views\query\Sql;
16
use Drupal\views\Plugin\views\row\RowPluginBase;
17
use Drupal\views\ResultRow;
18
use Drupal\visitors\VisitorsLocationInterface;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20
use Symfony\Component\HttpFoundation\RequestStack;
21
22
/**
23
 * Renders one visit as a visitor log card.
24
 */
25
#[ViewsRow(
26
  id: 'visitors_long',
27
  title: new TranslatableMarkup('Long'),
28
  help: new TranslatableMarkup('Shows one visit and the actions in that visit.'),
29
  display_types: ['normal'],
30
  base: ['visitors_visit'],
31
  register_theme: FALSE,
32
)]
33
final class VisitLong extends RowPluginBase {
34
35
  /**
36
   * {@inheritdoc}
37
   */
38
  protected $usesOptions = FALSE;
39
40
  /**
41
   * Visit columns the card reads.
42
   */
43
  private const FIELDS = [
44
    'id',
45
    'entry_time',
46
    'total_time',
47
    'returning',
48
    'total_visits',
49
    'referer_name',
50
    'referer_type',
51
    'referer_url',
52
    'location_country',
53
    'location_city',
54
    'config_browser_name',
55
    'config_os',
56
    'config_device_type',
57
    'uid',
58
  ];
59
60
  /**
61
   * Event columns loaded for the visits on the page.
62
   */
63
  private const EVENT_FIELDS = [
64
    'id',
65
    'visit_id',
66
    'page_view',
67
    'event',
68
    'title',
69
    'url',
70
    'url_prefix',
71
    'event_category',
72
    'event_action',
73
    'event_name',
74
    'created',
75
  ];
76
77
  /**
78
   * Query aliases keyed by column name.
79
   *
80
   * @var array<string, string>
81
   */
82
  protected array $aliases = [];
83
84
  /**
85
   * Actions keyed by visit id.
86
   *
87
   * @var array<int, array<int, array<string, mixed>>>
88
   */
89
  protected array $actions = [];
90
91
  /**
92
   * Root-relative path to the module.
93
   */
94
  protected string $iconBase;
95
96
  /**
97
   * Constructs a visit log row.
98
   *
99
   * @param array $configuration
100
   *   Plugin configuration.
101
   * @param string $plugin_id
102
   *   The plugin id.
103
   * @param mixed $plugin_definition
104
   *   The plugin definition.
105
   * @param \Drupal\Core\Database\Connection $database
106
   *   The database connection.
107
   * @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
108
   *   The date formatter.
109
   * @param \Drupal\Core\Extension\ModuleExtensionList $moduleExtensionList
110
   *   The module list.
111
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
112
   *   The request stack.
113
   * @param \Drupal\visitors\VisitorsLocationInterface $location
114
   *   The location service.
115
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
116
   *   The config factory.
117
   */
118
  public function __construct(
119
    array $configuration,
120
    $plugin_id,
121
    $plugin_definition,
122
    protected Connection $database,
123
    protected DateFormatterInterface $dateFormatter,
124
    ModuleExtensionList $moduleExtensionList,
125
    RequestStack $requestStack,
126
    protected VisitorsLocationInterface $location,
127
    protected ConfigFactoryInterface $configFactory,
128
  ) {
12911
    parent::__construct($configuration, $plugin_id, $plugin_definition);
13011
    $base_path = '';
13111
    $request = $requestStack->getCurrentRequest();
13211
    if ($request) {
13311
      $base_path = $request->getBasePath();
134
    }
13511
    $this->iconBase = $base_path . '/' . $moduleExtensionList->getPath('visitors');
136
  }
137
138
  /**
139
   * {@inheritdoc}
140
   */
141
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
14211
    return new self(
14311
      $configuration,
14411
      $plugin_id,
14511
      $plugin_definition,
14611
      $container->get('database'),
14711
      $container->get('date.formatter'),
14811
      $container->get('extension.list.module'),
14911
      $container->get('request_stack'),
15011
      $container->get('visitors.location'),
15111
      $container->get('config.factory'),
15211
    );
153
  }
154
155
  /**
156
   * {@inheritdoc}
157
   */
158
  public function query() {
1593
    $query = $this->view->query;
1603
    if (!$query instanceof Sql) {
1610
      return;
162
    }
1633
    foreach (self::FIELDS as $field) {
1643
      $this->aliases[$field] = $query->addField('visitors_visit', $field);
165
    }
166
  }
167
168
  /**
169
   * {@inheritdoc}
170
   */
171
  public function preRender($result) {
1723
    $this->actions = [];
1733
    $ids = [];
1743
    foreach ($result as $row) {
1753
      $id = (int) $this->column($row, 'id');
1763
      if ($id > 0) {
1773
        $ids[] = $id;
178
      }
179
    }
1803
    if ($ids === []) {
1810
      return;
182
    }
183
1843
    $query = $this->database->select('visitors_event', 'e');
1853
    $query->fields('e', self::EVENT_FIELDS);
1863
    $query->condition('visit_id', $ids, 'IN');
1873
    $query->orderBy('created');
1883
    $query->orderBy('id');
1893
    $by_visit = [];
1903
    foreach ($query->execute() as $event) {
1913
      $by_visit[(int) $event->visit_id][] = $event;
192
    }
1933
    foreach ($by_visit as $visit_id => $events) {
1943
      $this->actions[$visit_id] = $this->groupActions($events);
195
    }
196
  }
197
198
  /**
199
   * {@inheritdoc}
200
   */
201
  public function render($row) {
2023
    $visit_id = (int) $this->column($row, 'id');
2033
    $actions = $this->actions[$visit_id] ?? [];
2043
    return [
2053
      '#theme' => 'visitors_visit_long',
2063
      '#visit' => $this->visit($row, $this->countActions($actions)),
2073
      '#actions' => $actions,
2083
      '#attached' => [
2093
        'library' => ['visitors/visitors.report'],
2103
      ],
2113
    ];
212
  }
213
214
  /**
215
   * Builds the visit values for the template.
216
   *
217
   * @param \Drupal\views\ResultRow $row
218
   *   The visit row.
219
   * @param int $count
220
   *   The number of actions in the visit.
221
   *
222
   * @return array<string, mixed>
223
   *   Template values.
224
   */
225
  private function visit(ResultRow $row, int $count): array {
2263
    $seconds = (int) $this->column($row, 'total_time');
2273
    $summary = $this->formatPlural($count, '1 Action', '@count Actions');
2283
    if ($seconds > 0) {
2293
      $summary = $this->t('@actions - @duration', [
2303
        '@actions' => $summary,
2313
        '@duration' => $this->formatDuration($seconds),
2323
      ]);
233
    }
234
2353
    $referrer = $this->referrer($row);
2363
    $entry = (int) $this->column($row, 'entry_time');
2373
    return [
2383
      'datetime' => $entry > 0
2393
        ? $this->dateFormatter->format($entry, 'custom', 'l, F j, Y - H:i:s')
2403
        : '',
2413
      'site_name' => (string) $this->configFactory->get('system.site')->get('name'),
2423
      'referrer_label' => $referrer['label'],
2433
      'referrer_url' => $referrer['url'],
2443
      'visitor_type' => $this->visitorType($row),
2453
      'user' => $this->userLabel($row),
2463
      'icons' => $this->icons($row),
2473
      'summary' => $summary,
2483
    ];
249
  }
250
251
  /**
252
   * Reads one selected visit column.
253
   *
254
   * @param \Drupal\views\ResultRow $row
255
   *   The visit row.
256
   * @param string $field
257
   *   The column name.
258
   *
259
   * @return mixed
260
   *   The column value, or NULL when it was not selected.
261
   */
262
  private function column(ResultRow $row, string $field): mixed {
2633
    $alias = $this->aliases[$field] ?? '';
2643
    if ($alias === '' || !isset($row->{$alias})) {
2650
      return NULL;
266
    }
2673
    return $row->{$alias};
268
  }
269
270
  /**
271
   * Builds the referrer label and a safe link.
272
   *
273
   * @param \Drupal\views\ResultRow $row
274
   *   The visit row.
275
   *
276
   * @return array{label: string, url: string}
277
   *   The label and an http(s) URL, or an empty URL.
278
   */
279
  private function referrer(ResultRow $row): array {
2803
    $name = trim((string) $this->column($row, 'referer_name'));
2813
    $label = $name !== '' ? $name : $this->channelLabel((string) $this->column($row, 'referer_type'));
2823
    $url = '';
2833
    if ($name !== '') {
2843
      $url = $this->safeUrl((string) $this->column($row, 'referer_url'));
285
    }
2863
    return [
2873
      'label' => $label,
2883
      'url' => $url,
2893
    ];
290
  }
291
292
  /**
293
   * Maps a referrer channel to the report label.
294
   *
295
   * @param string $type
296
   *   The stored referer_type.
297
   *
298
   * @return string
299
   *   The channel label, or an empty string when the type is empty.
300
   */
301
  private function channelLabel(string $type): string {
3020
    return match ($type) {
3030
      'direct' => (string) $this->t('Direct Entry'),
3040
      'website' => (string) $this->t('Website'),
3050
      'internal' => (string) $this->t('Internal'),
3060
      'search_engine' => (string) $this->t('Search Engine'),
3070
      'spam' => (string) $this->t('Spam'),
3080
      'social_network' => (string) $this->t('Social Network'),
3090
      'ai_assistant' => (string) $this->t('AI Assistant'),
3100
      'campaign' => (string) $this->t('Campaign'),
3110
      '' => '',
3120
      default => (string) $this->t('Unknown'),
3130
    };
314
  }
315
316
  /**
317
   * Returns New or Returning.
318
   *
319
   * @param \Drupal\views\ResultRow $row
320
   *   The visit row.
321
   *
322
   * @return string
323
   *   The visitor type label.
324
   */
325
  private function visitorType(ResultRow $row): string {
3263
    $returning = (int) $this->column($row, 'returning');
3273
    $visits = (int) $this->column($row, 'total_visits');
3283
    if ($returning === 1 || $visits > 1) {
3290
      return (string) $this->t('Returning');
330
    }
3313
    return (string) $this->t('New');
332
  }
333
334
  /**
335
   * Returns the stored user id when one was recorded.
336
   *
337
   * @param \Drupal\views\ResultRow $row
338
   *   The visit row.
339
   *
340
   * @return string
341
   *   The user id, or an empty string.
342
   */
343
  private function userLabel(ResultRow $row): string {
3443
    $uid = trim((string) $this->column($row, 'uid'));
3453
    if ($uid === '' || $uid === '0') {
3460
      return '';
347
    }
3483
    return $uid;
349
  }
350
351
  /**
352
   * Builds the device icon list.
353
   *
354
   * @param \Drupal\views\ResultRow $row
355
   *   The visit row.
356
   *
357
   * @return array<int, array{src: string, alt: string}>
358
   *   Icon URL and accessible name.
359
   */
360
  private function icons(ResultRow $row): array {
3613
    $icons = [];
3623
    $country = strtoupper(trim((string) $this->column($row, 'location_country')));
3633
    $flag = $this->iconFile('icons/flags', strtolower($country), 'png');
3643
    if ($flag !== NULL && $country !== '') {
3653
      $place = (string) $this->location->getCountryLabel($country);
3663
      $city = trim((string) $this->column($row, 'location_city'));
3673
      if ($city !== '') {
3680
        $place = $city . ', ' . $place;
369
      }
3703
      $icons[] = [
3713
        'src' => $flag,
3723
        'alt' => $place,
3733
      ];
374
    }
375
3763
    $browser_code = trim((string) $this->column($row, 'config_browser_name'));
3773
    $browser = $this->iconFile('icons/browsers', $browser_code, 'png');
3783
    if ($browser !== NULL) {
3793
      $names = Browser::getAvailableBrowsers();
3803
      $icons[] = [
3813
        'src' => $browser,
3823
        'alt' => (string) ($names[$browser_code] ?? $browser_code),
3833
      ];
384
    }
385
3863
    $os_code = trim((string) $this->column($row, 'config_os'));
3873
    $os = $this->iconFile('icons/os', $os_code, 'png');
3883
    if ($os !== NULL) {
3893
      $os_name = (string) OperatingSystem::getOsFamily($os_code);
3903
      $icons[] = [
3913
        'src' => $os,
3923
        'alt' => $os_name !== '' ? $os_name : $os_code,
3933
      ];
394
    }
395
3963
    $device_code = trim((string) $this->column($row, 'config_device_type'));
3973
    if ($device_code === '') {
3980
      $device_code = 'unknown';
399
    }
4003
    $device = $this->iconFile('icons/devices', $device_code, 'png');
4013
    if ($device !== NULL) {
4023
      $icons[] = [
4033
        'src' => $device,
4043
        'alt' => ucwords($device_code),
4053
      ];
406
    }
4073
    return $icons;
408
  }
409
410
  /**
411
   * Groups hits that share a page view under that page view.
412
   *
413
   * @param array<int, object> $events
414
   *   Event rows in chronological order.
415
   *
416
   * @return array<int, array<string, mixed>>
417
   *   Top-level actions. Nested hits are in children.
418
   */
419
  private function groupActions(array $events): array {
4203
    $groups = [];
4213
    $index_by_page = [];
4223
    foreach ($events as $event) {
4233
      $item = $this->action($event);
4243
      $page_view = trim((string) ($event->page_view ?? ''));
4253
      if ($item['type'] === 'page') {
4263
        $groups[] = $item;
4273
        if ($page_view !== '' && !isset($index_by_page[$page_view])) {
4283
          $index_by_page[$page_view] = count($groups) - 1;
429
        }
4303
        continue;
431
      }
4323
      if ($page_view !== '' && isset($index_by_page[$page_view])) {
4333
        $groups[$index_by_page[$page_view]]['children'][] = $item;
4343
        continue;
435
      }
4363
      $groups[] = $item;
437
    }
4383
    return $groups;
439
  }
440
441
  /**
442
   * Builds one action for the template.
443
   *
444
   * @param object $event
445
   *   The event row.
446
   *
447
   * @return array<string, mixed>
448
   *   Action values, including an empty children list.
449
   */
450
  private function action(object $event): array {
4513
    $type = $this->actionType($event);
4523
    return [
4533
      'type' => $type,
4543
      'icon' => $this->iconBase . '/icons/actions/' . $this->actionIcon($type),
4553
      'alt' => $this->actionAlt($type),
4563
      'title' => $this->actionTitle($event, $type),
4573
      'url' => $this->actionUrl($event),
4583
      'children' => [],
4593
    ];
460
  }
461
462
  /**
463
   * Classifies an event row.
464
   *
465
   * @param object $event
466
   *   The event row.
467
   *
468
   * @return string
469
   *   page, download, outlink, search, or event.
470
   */
471
  private function actionType(object $event): string {
4723
    $name = strtolower(trim((string) ($event->event ?? '')));
4733
    if (in_array($name, ['download', 'outlink', 'search'], TRUE)) {
4743
      return $name;
475
    }
4763
    $category = trim((string) ($event->event_category ?? ''));
4773
    if ($category !== '' || $name !== '') {
4780
      return 'event';
479
    }
4803
    return 'page';
481
  }
482
483
  /**
484
   * Returns the action icon file name.
485
   *
486
   * @param string $type
487
   *   The action type.
488
   *
489
   * @return string
490
   *   The SVG file name.
491
   */
492
  private function actionIcon(string $type): string {
4933
    return match ($type) {
4943
      'download' => 'download.svg',
4953
      'outlink' => 'link.svg',
4960
      'search' => 'search.svg',
4970
      'event' => 'event.svg',
4983
      default => 'action.svg',
4993
    };
500
  }
501
502
  /**
503
   * Returns the accessible name for an action icon.
504
   *
505
   * @param string $type
506
   *   The action type.
507
   *
508
   * @return string
509
   *   The icon alt text.
510
   */
511
  private function actionAlt(string $type): string {
5123
    return match ($type) {
5133
      'download' => (string) $this->t('Download'),
5143
      'outlink' => (string) $this->t('Outlink'),
5150
      'search' => (string) $this->t('Search'),
5160
      'event' => (string) $this->t('Event'),
5173
      default => (string) $this->t('Page view'),
5183
    };
519
  }
520
521
  /**
522
   * Returns the visible title for an action.
523
   *
524
   * @param object $event
525
   *   The event row.
526
   * @param string $type
527
   *   The action type.
528
   *
529
   * @return string
530
   *   The title.
531
   */
532
  private function actionTitle(object $event, string $type): string {
5333
    if ($type === 'page') {
5343
      return trim((string) ($event->title ?? ''));
535
    }
5363
    if ($type !== 'event') {
5373
      return $this->actionAlt($type);
538
    }
539
5400
    $parts = array_filter([
5410
      trim((string) ($event->event_category ?? '')),
5420
      trim((string) ($event->event_action ?? '')),
5430
    ], static fn (string $part): bool => $part !== '');
5440
    $label = implode(' - ', $parts);
5450
    $name = trim((string) ($event->event_name ?? ''));
5460
    if ($name !== '') {
5470
      $label = $label === '' ? $name : $label . ': ' . $name;
548
    }
5490
    if ($label !== '') {
5500
      return $label;
551
    }
5520
    $title = trim((string) ($event->title ?? ''));
5530
    if ($title !== '') {
5540
      return $title;
555
    }
5560
    return trim((string) ($event->event ?? ''));
557
  }
558
559
  /**
560
   * Rebuilds an event URL from the stored prefix.
561
   *
562
   * @param object $event
563
   *   The event row.
564
   *
565
   * @return string
566
   *   An http(s) URL, or an empty string.
567
   */
568
  private function actionUrl(object $event): string {
5693
    $url = trim((string) ($event->url ?? ''));
5703
    if ($url === '') {
5710
      return '';
572
    }
5733
    if (!preg_match('#^https?://#i', $url)) {
5743
      $url = $this->urlPrefix((int) ($event->url_prefix ?? 0)) . $url;
575
    }
5763
    return $this->safeUrl($url);
577
  }
578
579
  /**
580
   * Maps a stored URL prefix to a scheme and host prefix.
581
   *
582
   * @param int $prefix
583
   *   The visitors URL prefix.
584
   *
585
   * @return string
586
   *   The prefix to prepend.
587
   */
588
  private function urlPrefix(int $prefix): string {
5893
    return match ($prefix) {
5900
      3 => 'https://www.',
5913
      2 => 'https://',
5920
      1 => 'http://www.',
5933
      default => 'http://',
5943
    };
595
  }
596
597
  /**
598
   * Keeps only http and https URLs.
599
   *
600
   * @param string $url
601
   *   A candidate URL.
602
   *
603
   * @return string
604
   *   The URL, or an empty string when the scheme is not allowed.
605
   */
606
  private function safeUrl(string $url): string {
6073
    $url = trim($url);
6083
    $scheme = parse_url($url, PHP_URL_SCHEME);
6093
    if (!is_string($scheme)) {
6100
      return '';
611
    }
6123
    if (!in_array(strtolower($scheme), ['http', 'https'], TRUE)) {
6130
      return '';
614
    }
6153
    return $url;
616
  }
617
618
  /**
619
   * Builds a module icon URL when the name is a single path segment.
620
   *
621
   * @param string $directory
622
   *   The icon directory under the module.
623
   * @param string $name
624
   *   The file name without an extension.
625
   * @param string $extension
626
   *   The file extension.
627
   *
628
   * @return string|null
629
   *   The icon URL, or NULL when the name is empty or unsafe.
630
   */
631
  private function iconFile(string $directory, string $name, string $extension): ?string {
6323
    if ($name === '' || !preg_match('/^[A-Za-z0-9_-]+$/', $name)) {
6330
      return NULL;
634
    }
6353
    return $this->iconBase . '/' . $directory . '/' . $name . '.' . $extension;
636
  }
637
638
  /**
639
   * Formats a duration as seconds, minutes, and hours.
640
   *
641
   * @param int $seconds
642
   *   The duration in seconds.
643
   *
644
   * @return string
645
   *   A duration such as "49s" or "1 min 25s".
646
   */
647
  private function formatDuration(int $seconds): string {
6483
    $hours = intdiv($seconds, 3600);
6493
    $minutes = intdiv($seconds % 3600, 60);
6503
    $remainder = $seconds % 60;
6513
    $parts = [];
6523
    if ($hours > 0) {
6530
      $parts[] = $hours . ' ' . $this->t('h');
654
    }
6553
    if ($minutes > 0) {
6563
      $parts[] = $minutes . ' ' . $this->t('min');
657
    }
6583
    if ($remainder > 0 || $parts === []) {
6593
      $parts[] = $remainder . 's';
660
    }
6613
    return implode(' ', $parts);
662
  }
663
664
  /**
665
   * Counts actions, including hits nested under a page view.
666
   *
667
   * @param array<int, array<string, mixed>> $actions
668
   *   Top-level actions.
669
   *
670
   * @return int
671
   *   The number of actions.
672
   */
673
  private function countActions(array $actions): int {
6743
    $count = 0;
6753
    foreach ($actions as $action) {
6763
      $count++;
6773
      $children = $action['children'] ?? [];
6783
      if (is_array($children)) {
6793
        $count += count($children);
680
      }
681
    }
6823
    return $count;
683
  }
684
685
}