File: AbstractParser.php

package info (click to toggle)
matomo-device-detector 6.4.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 19,124 kB
  • sloc: php: 7,493; xml: 79; makefile: 15; sh: 3
file content (494 lines) | stat: -rw-r--r-- 13,369 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<?php

/**
 * Device Detector - The Universal Device Detection library for parsing User Agents
 *
 * @link https://matomo.org
 *
 * @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
 */

declare(strict_types=1);

namespace DeviceDetector\Parser;

use DeviceDetector\Cache\CacheInterface;
use DeviceDetector\Cache\StaticCache;
use DeviceDetector\ClientHints;
use DeviceDetector\DeviceDetector;
use DeviceDetector\Yaml\ParserInterface as YamlParser;
use DeviceDetector\Yaml\Spyc;

/**
 * Class AbstractParser
 */
abstract class AbstractParser
{
    /**
     * Holds the path to the yml file containing regexes
     * @var string
     */
    protected $fixtureFile;

    /**
     * Holds the internal name of the parser
     * Used for caching
     * @var string
     */
    protected $parserName;

    /**
     * Holds the user agent to be parsed
     * @var string
     */
    protected $userAgent;

    /**
     * Holds the client hints to be parsed
     * @var ?ClientHints
     */
    protected $clientHints = null;

    /**
     * Contains a list of mappings from names we use to known client hint values
     * @var array<string, array<string>>
     */
    protected static $clientHintMapping = [];

    /**
     * Holds an array with method that should be available global
     * @var array
     */
    protected $globalMethods;

    /**
     * Holds an array with regexes to parse, if already loaded
     * @var array
     */
    protected $regexList;

    /**
     * Holds the concatenated regex for all items in regex list
     * @var string
     */
    protected $overAllMatch;

    /**
     * Indicates how deep versioning will be detected
     * if $maxMinorParts is 0 only the major version will be returned
     * @var int
     */
    protected static $maxMinorParts = 1;

    /**
     * Versioning constant used to set max versioning to major version only
     * Version examples are: 3, 5, 6, 200, 123, ...
     */
    public const VERSION_TRUNCATION_MAJOR = 0;

    /**
     * Versioning constant used to set max versioning to minor version
     * Version examples are: 3.4, 5.6, 6.234, 0.200, 1.23, ...
     */
    public const VERSION_TRUNCATION_MINOR = 1;

    /**
     * Versioning constant used to set max versioning to path level
     * Version examples are: 3.4.0, 5.6.344, 6.234.2, 0.200.3, 1.2.3, ...
     */
    public const VERSION_TRUNCATION_PATCH = 2;

    /**
     * Versioning constant used to set versioning to build number
     * Version examples are: 3.4.0.12, 5.6.334.0, 6.234.2.3, 0.200.3.1, 1.2.3.0, ...
     */
    public const VERSION_TRUNCATION_BUILD = 3;

    /**
     * Versioning constant used to set versioning to unlimited (no truncation)
     */
    public const VERSION_TRUNCATION_NONE = -1;

    /**
     * @var CacheInterface|null
     */
    protected $cache = null;

    /**
     * @var YamlParser|null
     */
    protected $yamlParser = null;

    /**
     * parses the currently set useragents and returns possible results
     *
     * @return array|null
     */
    abstract public function parse(): ?array;

    /**
     * AbstractParser constructor.
     *
     * @param string       $ua
     * @param ?ClientHints $clientHints
     */
    public function __construct(string $ua = '', ?ClientHints $clientHints = null)
    {
        $this->setUserAgent($ua);
        $this->setClientHints($clientHints);
    }

    /**
     * @inheritdoc
     */
    public function restoreUserAgentFromClientHints(): void
    {
        if (null === $this->clientHints) {
            return;
        }

        $deviceModel = $this->clientHints->getModel();

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

        // Restore Android User Agent
        if ($this->hasUserAgentClientHintsFragment()) {
            $osVersion = $this->clientHints->getOperatingSystemVersion();
            $this->setUserAgent((string) \preg_replace(
                '(Android (?:10[.\d]*; K|1[1-5]))',
                \sprintf('Android %s; %s', '' !== $osVersion ? $osVersion : '10', $deviceModel),
                $this->userAgent
            ));
        }

        // Restore Desktop User Agent
        if (!$this->hasDesktopFragment()) {
            return;
        }

        $this->setUserAgent((string) \preg_replace(
            '(X11; Linux x86_64)',
            \sprintf('X11; Linux x86_64; %s', $deviceModel),
            $this->userAgent
        ));
    }

    /**
     * Set how DeviceDetector should return versions
     * @param int $type Any of the VERSION_TRUNCATION_* constants
     */
    public static function setVersionTruncation(int $type): void
    {
        if (!\in_array($type, [
            self::VERSION_TRUNCATION_BUILD,
            self::VERSION_TRUNCATION_NONE,
            self::VERSION_TRUNCATION_MAJOR,
            self::VERSION_TRUNCATION_MINOR,
            self::VERSION_TRUNCATION_PATCH,
        ])
        ) {
            return;
        }

        static::$maxMinorParts = $type;
    }

    /**
     * Sets the user agent to parse
     *
     * @param string $ua user agent
     */
    public function setUserAgent(string $ua): void
    {
        $this->userAgent = $ua;
    }

    /**
     * Sets the client hints to parse
     *
     * @param ?ClientHints $clientHints client hints
     */
    public function setClientHints(?ClientHints $clientHints): void
    {
        $this->clientHints = $clientHints;
    }

    /**
     * Returns the internal name of the parser
     *
     * @return string
     */
    public function getName(): string
    {
        return $this->parserName;
    }

    /**
     * Sets the Cache class
     *
     * @param CacheInterface $cache
     */
    public function setCache(CacheInterface $cache): void
    {
        $this->cache = $cache;
    }

    /**
     * Returns Cache object
     *
     * @return CacheInterface
     */
    public function getCache(): CacheInterface
    {
        if (!empty($this->cache)) {
            return $this->cache;
        }

        return new StaticCache();
    }

    /**
     * Sets the YamlParser class
     *
     * @param YamlParser $yamlParser
     */
    public function setYamlParser(YamlParser $yamlParser): void
    {
        $this->yamlParser = $yamlParser;
    }

    /**
     * Returns YamlParser object
     *
     * @return YamlParser
     */
    public function getYamlParser(): YamlParser
    {
        if (!empty($this->yamlParser)) {
            return $this->yamlParser;
        }

        return new Spyc();
    }

    /**
     * Returns the result of the parsed yml file defined in $fixtureFile
     *
     * @return array
     */
    protected function getRegexes(): array
    {
        if (empty($this->regexList)) {
            $cacheKey     = 'DeviceDetector-' . DeviceDetector::VERSION . 'regexes-' . $this->getName();
            $cacheKey     = (string) \preg_replace('/([^a-z0-9_-]+)/i', '', $cacheKey);
            $cacheContent = $this->getCache()->fetch($cacheKey);

            if (\is_array($cacheContent)) {
                $this->regexList = $cacheContent;
            }

            if (empty($this->regexList)) {
                $parsedContent = $this->getYamlParser()->parseFile(
                    $this->getRegexesDirectory() . DIRECTORY_SEPARATOR . $this->fixtureFile
                );

                if (!\is_array($parsedContent)) {
                    $parsedContent = [];
                }

                $this->regexList = $parsedContent;
                $this->getCache()->save($cacheKey, $this->regexList);
            }
        }

        return $this->regexList;
    }

    /**
     * Returns the provided name after applying client hint mappings.
     * This is used to map names provided in client hints to the names we use.
     *
     * @param string $name
     *
     * @return string
     */
    protected function applyClientHintMapping(string $name): string
    {
        foreach (static::$clientHintMapping as $mappedName => $clientHints) {
            foreach ($clientHints as $clientHint) {
                if (\strtolower($name) === \strtolower($clientHint)) {
                    return $mappedName;
                }
            }
        }

        return $name;
    }

    /**
     * @return string
     */
    protected function getRegexesDirectory(): string
    {
        return \dirname(__DIR__);
    }

    /**
     * Returns if the parsed UA contains the 'Windows NT;' or 'X11; Linux x86_64' fragments
     *
     * @return bool
     */
    protected function hasDesktopFragment(): bool
    {
        $regexExcludeDesktopFragment = \implode('|', [
            'CE-HTML',
            ' Mozilla/|Andr[o0]id|Tablet|Mobile|iPhone|Windows Phone|ricoh|OculusBrowser',
            'PicoBrowser|Lenovo|compatible; MSIE|Trident/|Tesla/|XBOX|FBMD/|ARM; ?([^)]+)',
        ]);

        return
            $this->matchUserAgent('(?:Windows (?:NT|IoT)|X11; Linux x86_64)') &&
            !$this->matchUserAgent($regexExcludeDesktopFragment);
    }

    /**
     * Returns if the parsed UA contains the 'Android 10 K;' or Android 10 K Build/` fragment
     *
     * @return bool
     */
    protected function hasUserAgentClientHintsFragment(): bool
    {
        return (bool) \preg_match('~Android (?:10[.\d]*; K(?: Build/|[;)])|1[1-5]\)) AppleWebKit~i', $this->userAgent);
    }

    /**
     * Matches the useragent against the given regex
     *
     * @param string $regex
     *
     * @return ?array
     *
     * @throws \Exception
     */
    protected function matchUserAgent(string $regex): ?array
    {
        $matches = [];

        // only match if useragent begins with given regex or there is no letter before it
        $regex = '/(?:^|[^A-Z0-9_-]|[^A-Z0-9-]_|sprd-|MZ-)(?:' . \str_replace('/', '\/', $regex) . ')/i';

        try {
            if (\preg_match($regex, $this->userAgent, $matches)) {
                return $matches;
            }
        } catch (\Exception $exception) {
            throw new \Exception(
                \sprintf("%s\nRegex: %s", $exception->getMessage(), $regex),
                $exception->getCode(),
                $exception
            );
        }

        return null;
    }

    /**
     * @param string $item
     * @param array  $matches
     *
     * @return string
     */
    protected function buildByMatch(string $item, array $matches): string
    {
        $search  = [];
        $replace = [];

        for ($nb = 1; $nb <= \count($matches); $nb++) {
            $search[]  = '$' . $nb;
            $replace[] = $matches[$nb] ?? '';
        }

        return \trim(\str_replace($search, $replace, $item));
    }

    /**
     * Builds the version with the given $versionString and $matches
     *
     * Example:
     * $versionString = 'v$2'
     * $matches = ['version_1_0_1', '1_0_1']
     * return value would be v1.0.1
     *
     * @param string $versionString
     * @param array  $matches
     *
     * @return string
     */
    protected function buildVersion(string $versionString, array $matches): string
    {
        $versionString = $this->buildByMatch($versionString, $matches);
        $versionString = \str_replace('_', '.', $versionString);

        if (self::VERSION_TRUNCATION_NONE !== static::$maxMinorParts
            && \substr_count($versionString, '.') > static::$maxMinorParts
        ) {
            $versionParts  = \explode('.', $versionString);
            $versionParts  = \array_slice($versionParts, 0, 1 + static::$maxMinorParts);
            $versionString = \implode('.', $versionParts);
        }

        return \trim($versionString, ' .');
    }

    /**
     * Tests the useragent against a combination of all regexes
     *
     * All regexes returned by getRegexes() will be reversed and concatenated with '|'
     * Afterwards the big regex will be tested against the user agent
     *
     * Method can be used to speed up detections by making a big check before doing checks for every single regex
     *
     * @return ?array
     */
    protected function preMatchOverall(): ?array
    {
        $regexes = $this->getRegexes();

        $cacheKey = $this->parserName . DeviceDetector::VERSION . '-all';
        $cacheKey = (string) \preg_replace('/([^a-z0-9_-]+)/i', '', $cacheKey);

        if (empty($this->overAllMatch)) {
            $overAllMatch = $this->getCache()->fetch($cacheKey);

            if (\is_string($overAllMatch)) {
                $this->overAllMatch = $overAllMatch;
            }
        }

        if (empty($this->overAllMatch)) {
            // reverse all regexes, so we have the generic one first, which already matches most patterns
            $this->overAllMatch = \array_reduce(\array_reverse($regexes), static function ($val1, $val2) {
                return !empty($val1) ? $val1 . '|' . $val2['regex'] : $val2['regex'];
            });
            $this->getCache()->save($cacheKey, $this->overAllMatch);
        }

        return $this->matchUserAgent($this->overAllMatch);
    }

    /**
     * Compares if two strings equals after lowering their case and removing spaces
     *
     * @param string $value1
     * @param string $value2
     *
     * @return bool
     */
    protected function fuzzyCompare(string $value1, string $value2): bool
    {
        return \str_replace(' ', '', \strtolower($value1)) ===
            \str_replace(' ', '', \strtolower($value2));
    }
}