Coverage index

src/Service/Referrer.php

Lines: 79.37%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Service;
6
7
use Drupal\Component\Utility\Unicode;
8
use Drupal\path_alias\AliasManagerInterface;
9
use Drupal\visitors\VisitorsReferrerInterface;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\RequestStack;
12
use Symfony\Component\Routing\Exception\ExceptionInterface;
13
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
14
15
/**
16
 * Referrer url service.
17
 */
18
final class Referrer implements VisitorsReferrerInterface {
19
20
  /**
21
   * The URL.
22
   *
23
   * @var array
24
   */
25
  private $url;
26
27
  /**
28
   * The host of the page that was viewed.
29
   *
30
   * @var string
31
   */
32
  private $pageHost = '';
33
34
  /**
35
   * The router matcher.
36
   *
37
   * @var \Symfony\Component\Routing\Matcher\RequestMatcherInterface
38
   */
39
  private $routerMatcher;
40
41
  /**
42
   * The alias manager.
43
   *
44
   * @var \Drupal\path_alias\AliasManagerInterface|null
45
   */
46
  private $aliasManager;
47
48
  /**
49
   * The request stack.
50
   *
51
   * @var \Symfony\Component\HttpFoundation\RequestStack|null
52
   */
53
  private $requestStack;
54
55
  /**
56
   * Constructs a new Referrer.
57
   *
58
   * @param \Symfony\Component\Routing\Matcher\RequestMatcherInterface $router_matcher
59
   *   The router matcher.
60
   * @param \Drupal\path_alias\AliasManagerInterface|null $alias_manager
61
   *   The alias manager.
62
   * @param \Symfony\Component\HttpFoundation\RequestStack|null $request_stack
63
   *   The request stack. Used to remove the site base path.
64
   */
65
  public function __construct(RequestMatcherInterface $router_matcher, ?AliasManagerInterface $alias_manager, ?RequestStack $request_stack = NULL) {
6612
    $this->routerMatcher = $router_matcher;
6712
    $this->aliasManager = $alias_manager;
6812
    $this->requestStack = $request_stack;
6912
    $this->url = [];
70
  }
71
72
  /**
73
   * {@inheritdoc}
74
   */
75
  public function setUrl(string $url): void {
765
    $parsed = parse_url($url);
775
    $this->url = is_array($parsed) ? $parsed : [];
78
  }
79
80
  /**
81
   * {@inheritdoc}
82
   */
83
  public function setPageHost(string $host): void {
845
    $this->pageHost = $host;
85
  }
86
87
  /**
88
   * {@inheritdoc}
89
   */
90
  public function hostOf(string $url): string {
9112
    if ($url === '') {
920
      return '';
93
    }
9412
    $parts = parse_url($url);
9512
    if (!is_array($parts)) {
960
      return '';
97
    }
9812
    if (!empty($parts['host'])) {
9911
      return (string) $parts['host'];
100
    }
101
1021
    $path = (string) ($parts['path'] ?? '');
1031
    $slash = strpos($path, '/');
1041
    $host = $slash === FALSE ? $path : substr($path, 0, $slash);
1051
    $colon = strpos($host, ':');
1061
    if ($colon !== FALSE) {
1070
      $host = substr($host, 0, $colon);
108
    }
109
1101
    return $host;
111
  }
112
113
  /**
114
   * {@inheritdoc}
115
   */
116
  public function storageFields(string $referrer, string $page_host): array {
11712
    $empty = [
11812
      'referrer_url' => '',
11912
      'referrer_url_prefix' => NULL,
12012
      'referrer_internal' => 0,
12112
      'referrer_path' => '',
12212
      'referrer_route' => '',
12312
    ];
12412
    if ($referrer === '') {
12511
      return $empty;
126
    }
127
1285
    $this->setUrl($referrer);
1295
    $this->setPageHost($page_host);
1305
    $internal = $this->isInternal();
1315
    $path = '';
1325
    $route = '';
1335
    if ($internal) {
1344
      $path = Unicode::truncate($this->getPath() ?? '', 255, FALSE, FALSE);
1354
      $route = Unicode::truncate($this->getRoute() ?? '', 255, FALSE, FALSE);
136
    }
137
1385
    return [
1395
      'referrer_url' => $this->getUrl(),
1405
      'referrer_url_prefix' => $this->getPrefix(),
1415
      'referrer_internal' => $internal ? 1 : 0,
1425
      'referrer_path' => $path,
1435
      'referrer_route' => $route,
1445
    ];
145
  }
146
147
  /**
148
   * {@inheritdoc}
149
   */
150
  public function getPrefix(): ?int {
1515
    $prefix = NULL;
1525
    if (isset($this->url['scheme'])) {
1535
      switch ($this->url['scheme']) {
1545
        case 'http':
1554
          $prefix = 0;
1564
          break;
157
1585
        case 'https':
1595
          $prefix = 2;
1600
          break;
161
      }
162
    }
163
1645
    if (isset($this->url['host']) && str_starts_with($this->url['host'], 'www.')) {
1651
      $prefix = ($prefix ?? 0) + 1;
166
    }
167
1685
    return $prefix;
169
  }
170
171
  /**
172
   * {@inheritdoc}
173
   */
174
  public function getHost($ignore_www = TRUE): ?string {
1755
    $host = NULL;
1765
    if (isset($this->url['host'])) {
1775
      $host = $this->url['host'];
178
    }
179
    if (
1805
      $host
181
      && $ignore_www
1825
      && str_starts_with($host, 'www.')) {
1831
      $host = substr($host, 4);
184
    }
185
1865
    return $host;
187
  }
188
189
  /**
190
   * {@inheritdoc}
191
   */
192
  public function isInternal(): bool {
1935
    $host = $this->comparableHost($this->getHost(TRUE));
1945
    $page_host = $this->comparableHost($this->pageHost);
1955
    if ($host === '' || $page_host === '') {
1960
      return FALSE;
197
    }
198
1995
    return $host === $page_host;
200
  }
201
202
  /**
203
   * {@inheritdoc}
204
   */
205
  public function getType(): ?int {
2060
    $type = NULL;
2070
    if (empty($this->url['path'])) {
2080
      $type = 1;
209
    }
2100
    elseif ($this->isInternal()) {
2110
      $type = 3;
212
    }
213
2140
    return $type;
215
  }
216
217
  /**
218
   * {@inheritdoc}
219
   */
220
  public function getRoute(): ?string {
2214
    if (!$this->isInternal()) {
2220
      return NULL;
223
    }
2244
    $path = $this->getPath();
2254
    if ($path === NULL || $path === '') {
2260
      return NULL;
227
    }
2284
    if ($path[0] !== '/') {
2290
      $path = '/' . $path;
230
    }
231
232
    try {
2334
      $result = $this->routerMatcher->matchRequest(Request::create($path));
234
    }
2351
    catch (ExceptionInterface) {
2361
      return NULL;
237
    }
238
2393
    if (empty($result['_route'])) {
2400
      return NULL;
241
    }
242
2433
    return (string) $result['_route'];
244
  }
245
246
  /**
247
   * {@inheritdoc}
248
   */
249
  public function getPath(): ?string {
2504
    if (!$this->isInternal() || !isset($this->url['path']) || $this->url['path'] === '') {
2510
      return NULL;
252
    }
253
2544
    $path = $this->url['path'];
2554
    if ($path[0] !== '/') {
2560
      $path = '/' . $path;
257
    }
2584
    $path = $this->stripBasePath($path);
2594
    if ($this->aliasManager) {
2604
      $path = $this->aliasManager->getPathByAlias($path);
261
    }
262
2634
    return $path;
264
  }
265
266
  /**
267
   * Removes the site base path and front controller.
268
   *
269
   * @param string $path
270
   *   A path from the referrer URL.
271
   *
272
   * @return string
273
   *   The path Drupal routes against.
274
   */
275
  private function stripBasePath(string $path): string {
2764
    $request = $this->requestStack?->getCurrentRequest();
2774
    if ($request) {
2784
      $base = $request->getBasePath();
2794
      $prefixed = $base !== '' && str_starts_with($path, $base . '/');
2804
      if ($base !== '' && ($path === $base || $prefixed)) {
2812
        $path = substr($path, strlen($base));
282
      }
283
    }
2844
    if ($path === '/index.php' || str_starts_with($path, '/index.php/')) {
2851
      $path = substr($path, strlen('/index.php'));
286
    }
2874
    if ($path === '') {
2880
      $path = '/';
289
    }
290
2914
    return $path;
292
  }
293
294
  /**
295
   * {@inheritdoc}
296
   */
297
  public function getUrl(): string {
298
2995
    $host     = $this->getHost() ?? '';
3005
    $port     = isset($this->url['port']) ? ':' . $this->url['port'] : '';
3015
    $path     = $this->url['path'] ?? '';
3025
    $query    = isset($this->url['query']) ? '?' . $this->url['query'] : '';
3035
    $fragment = isset($this->url['fragment']) ? '#' . $this->url['fragment'] : '';
304
3055
    return "$host$port$path$query$fragment";
306
  }
307
308
  /**
309
   * {@inheritdoc}
310
   */
311
  public function getInternalKeyword(): ?string {
3120
    $keyword = NULL;
3130
    if (isset($this->url['query'])) {
3140
      $params = [];
3150
      parse_str($this->url['query'], $params);
3160
      $keyword = $params['keys'] ?? NULL;
317
    }
318
3190
    return $keyword;
320
  }
321
322
  /**
323
   * Host used when comparing a referrer with the viewed page.
324
   *
325
   * @param string|null $host
326
   *   The host.
327
   *
328
   * @return string
329
   *   The host without a leading www., lowercased.
330
   */
331
  private function comparableHost(?string $host): string {
3325
    if ($host === NULL || $host === '') {
3330
      return '';
334
    }
3355
    $host = strtolower($host);
3365
    if (str_starts_with($host, 'www.')) {
3370
      return substr($host, 4);
338
    }
339
3405
    return $host;
341
  }
342
343
}