File: SiteContentDetector.php

package info (click to toggle)
matomo 5.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 95,068 kB
  • sloc: php: 289,425; xml: 127,249; javascript: 112,130; python: 202; sh: 178; makefile: 20; sql: 10
file content (410 lines) | stat: -rw-r--r-- 14,080 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
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik;

use Matomo\Cache\Lazy;
use Piwik\Config\GeneralConfig;
use Piwik\Container\StaticContainer;
use Piwik\Plugins\SitesManager\SiteContentDetection\ConsentManagerDetectionAbstract;
use Piwik\Plugins\SitesManager\SiteContentDetection\SiteContentDetectionAbstract;

/**
 * This class provides detection functions for specific content on a site. It can be used to easily detect the
 * presence of known third party code.
 *
 * Note: Calling the `detectContent()` method will create a HTTP request to the site to retrieve data, only the main site URL
 * will be checked
 *
 * Usage:
 *
 * $contentDetector = new SiteContentDetector();
 * $contentDetector->detectContent([GoogleAnalytics3::getId()]);
 * if ($contentDetector->ga3) {
 *      // site is using GA3
 * }
 *
 * @api
 */
class SiteContentDetector
{
    /**
     * @var array<string, array<string, SiteContentDetectionAbstract>>
     */
    public $detectedContent = [
        SiteContentDetectionAbstract::TYPE_TRACKER => [],
        SiteContentDetectionAbstract::TYPE_CMS => [],
        SiteContentDetectionAbstract::TYPE_JS_FRAMEWORK => [],
        SiteContentDetectionAbstract::TYPE_CONSENT_MANAGER => [],
        SiteContentDetectionAbstract::TYPE_JS_CRASH_ANALYTICS => [],
        SiteContentDetectionAbstract::TYPE_OTHER => [],
    ];

    public $connectedConsentManagers = [];

    private $siteResponse = [
        'data' => '',
        'headers' => [],
    ];

    /** @var Lazy */
    private $cache;

    public function __construct(?Lazy $cache = null)
    {
        if ($cache === null) {
            $this->cache = Cache::getLazyCache();
        } else {
            $this->cache = $cache;
        }
    }


    /**
     * @return array<string, SiteContentDetectionAbstract[]>
     */
    public static function getSiteContentDetectionsByType(): array
    {
        $instancesByType = [];
        $classes = self::getAllSiteContentDetectionClasses();

        foreach ($classes as $className) {
            $instancesByType[$className::getContentType()][] = StaticContainer::get($className);
        }

        return $instancesByType;
    }

    /**
     * Returns the site content detection object with the provided id, or null if it can't be found
     *
     */
    public function getSiteContentDetectionById(string $id): ?SiteContentDetectionAbstract
    {
        $classes = $this->getAllSiteContentDetectionClasses();

        foreach ($classes as $className) {
            if ($className::getId() === $id) {
                return StaticContainer::get($className);
            }
        }

        return null;
    }

    /**
     * @return string[]
     */
    protected static function getAllSiteContentDetectionClasses(): array
    {
        return Plugin\Manager::getInstance()->findMultipleComponents('SiteContentDetection', SiteContentDetectionAbstract::class);
    }

    /**
     * Reset the detections
     *
     */
    private function resetDetections(): void
    {
        $this->detectedContent          = [
            SiteContentDetectionAbstract::TYPE_TRACKER => [],
            SiteContentDetectionAbstract::TYPE_CMS => [],
            SiteContentDetectionAbstract::TYPE_JS_FRAMEWORK => [],
            SiteContentDetectionAbstract::TYPE_CONSENT_MANAGER => [],
            SiteContentDetectionAbstract::TYPE_JS_CRASH_ANALYTICS => [],
            SiteContentDetectionAbstract::TYPE_OTHER => [],
        ];
        $this->connectedConsentManagers = [];
    }

    /**
     * This will query the site and populate the class properties with
     * the details of the detected content
     *
     * @param array       $detectContent Array of content type for which to check, defaults to all, limiting this list
     *                                   will speed up the detection check.
     *                                   Allowed values are:
     *                                   * empty array - to run all detections
     *                                   * an array containing ids of detections, e.g. Wordpress::getId() or any of the
     *                                     type constants, e.g. SiteContentDetectionAbstract::TYPE_TRACKER
     * @param ?int        $idSite        Override the site ID, will use the site from the current request if null
     * @param ?array      $siteResponse  String containing the site data to search, if blank then data will be retrieved
     *                                   from the current request site via an http request
     * @param int         $timeOut       How long to wait for the site to response, defaults to 5 seconds
     */
    public function detectContent(
        array $detectContent = [],
        ?int $idSite = null,
        ?array $siteResponse = null,
        int $timeOut = 5
    ): void {
        $this->resetDetections();

        // If site data was passed in, then just run the detection checks against it and return.
        if ($siteResponse) {
            $this->siteResponse = $siteResponse;
            $this->detectionChecks($detectContent);
            return;
        }

        // Get the site id from the request object if not explicitly passed
        if ($idSite === null) {
            $idSite = Request::fromRequest()->getIntegerParameter('idSite', 0);

            if (!$idSite) {
                return;
            }
        }

        $url = Site::getMainUrlFor($idSite);

        // Check and load previously cached site content detection data if it exists
        $cacheKey = 'SiteContentDetection_' . md5($url);
        $siteContentDetectionCache = $this->cache->fetch($cacheKey);

        if ($siteContentDetectionCache !== false) {
            if ($this->checkCacheHasRequiredProperties($detectContent, $siteContentDetectionCache)) {
                $this->detectedContent = $siteContentDetectionCache['detectedContent'];
                $this->connectedConsentManagers = $siteContentDetectionCache['connectedConsentManagers'];
                return;
            }
        }

        // No cache hit, no passed data, so make a request for the site content
        $siteResponse = $this->requestSiteResponse($url, $timeOut);

        // Abort if still no site data
        if (empty($siteResponse['data'])) {
            return;
        }

        $this->siteResponse = $siteResponse;

        // We now have site data to analyze, so run the detection checks
        $this->detectionChecks($detectContent);

        // A request was made to get this data and it isn't currently cached, so write it to the cache now
        $cacheLife = (60 * 60 * 24 * 7);
        $this->saveToCache($cacheKey, $cacheLife);
    }

    /**
     * Returns if the detection with the provided id was detected or not
     *
     * Note: self::detectContent needs to be called before.
     *
     */
    public function wasDetected(string $detectionClassId): bool
    {
        foreach ($this->detectedContent as $type => $detectedClassIds) {
            if (array_key_exists($detectionClassId, $detectedClassIds)) {
                return $detectedClassIds[$detectionClassId] ?? false;
            }
        }

        return false;
    }

    /**
     * Returns an array containing ids of all detected detections of the given type
     *
     * @param int $type One of the SiteContentDetectionAbstract::TYPE_* constants
     * @return array
     */
    public function getDetectsByType(int $type): array
    {
        $detected = [];

        foreach ($this->detectedContent[$type] as $objId => $wasDetected) {
            if (true === $wasDetected) {
                $detected[] = $objId;
            }
        }

        return $detected;
    }

    /**
     * Checks that all required detections are in the cache array
     *
     * @param array $detectContent
     * @param array $cache
     *
     */
    private function checkCacheHasRequiredProperties(array $detectContent, array $cache): bool
    {
        if (empty($detectContent)) {
            foreach (self::getSiteContentDetectionsByType() as $type => $entries) {
                foreach ($entries as $entry) {
                    if (!isset($cache['detectedContent'][$type][$entry::getId()])) {
                        return false; // random detection missing
                    }
                }
            }

            return true;
        }

        foreach ($detectContent as $requestedDetection) {
            if (is_string($requestedDetection)) { // specific detection
                $detectionObj = $this->getSiteContentDetectionById($requestedDetection);
                if (null !== $detectionObj && !isset($cache['detectedContent'][$detectionObj::getContentType()][$detectionObj::getId()])) {
                    return false; // specific detection was run before
                }
            } elseif (is_int($requestedDetection)) { // detection type requested
                $detectionsByType = self::getSiteContentDetectionsByType();
                if (isset($detectionsByType[$requestedDetection])) {
                    foreach ($detectionsByType[$requestedDetection] as $detectionObj) {
                        if (!isset($cache['detectedContent'][$requestedDetection][$detectionObj::getId()])) {
                            return false; // random detection missing
                        }
                    }
                }
            }
        }

        return true;
    }

    /**
     * Save data to the cache
     *
     *
     */
    private function saveToCache(string $cacheKey, int $cacheLife): void
    {
        $cacheData = [
            'detectedContent' => [],
            'connectedConsentManagers' => [],
        ];

        // Load any existing cached values
        $siteContentDetectionCache = $this->cache->fetch($cacheKey);

        if (is_array($siteContentDetectionCache)) {
            $cacheData = $siteContentDetectionCache;
        }

        foreach ($this->detectedContent as $type => $detections) {
            if (!isset($cacheData['detectedContent'][$type])) {
                $cacheData['detectedContent'][$type] = [];
            }
            foreach ($detections as $detectionId => $wasDetected) {
                if (null !== $wasDetected) {
                    $cacheData['detectedContent'][$type][$detectionId] = $wasDetected;
                }
            }
        }

        $cacheData['connectedConsentManagers'] = array_merge($cacheData['connectedConsentManagers'], $this->connectedConsentManagers);

        $this->cache->save($cacheKey, $cacheData, $cacheLife);
    }

    /**
     * Run various detection checks for site content
     *
     * @param array $detectContent    Array of detection types used to filter the checks that are run
     *
     */
    private function detectionChecks(array $detectContent): void
    {
        $detections = $this->getSiteContentDetectionsByType();

        foreach ($detections as $type => $typeDetections) {
            foreach ($typeDetections as $typeDetection) {
                $this->detectedContent[$type][$typeDetection::getId()] = null;

                if (
                    in_array($type, $detectContent) ||
                    in_array($typeDetection::getId(), $detectContent) ||
                    empty($detectContent)
                ) {
                    $this->detectedContent[$type][$typeDetection::getId()] = false;

                    if ($typeDetection->isDetected($this->siteResponse['data'], $this->siteResponse['headers'])) {
                        if (
                            $typeDetection instanceof ConsentManagerDetectionAbstract
                            && $typeDetection->checkIsConnected($this->siteResponse['data'], $this->siteResponse['headers'])
                        ) {
                            $this->connectedConsentManagers[] = $typeDetection::getId();
                        }
                        $this->detectedContent[$type][$typeDetection::getId()] = true;
                    }
                }
            }
        }
    }

    /**
     * Retrieve data from the specified site using an HTTP request
     *
     *
     * @return array
     */
    private function requestSiteResponse(string $url, int $timeOut): array
    {
        if (!$url) {
            return [];
        }

        // If internet features are disabled, we don't try to fetch any site content
        if (0 === (int) GeneralConfig::getConfigValue('enable_internet_features')) {
            return [];
        }

        $siteData = [];

        try {
            $siteData = Http::sendHttpRequestBy(
                Http::getTransportMethod(),
                $url,
                $timeOut,
                null,
                null,
                null,
                0,
                false,
                true,
                false,
                true
            );
        } catch (\Exception $e) {
        }

        return $siteData;
    }

    /**
     * Return an array of consent manager definitions which can be used to detect their presence on the site and show
     * the associated guide links
     *
     * Note: This list is also used to display the known / supported consent managers on the "Ask for Consent" page
     * For adding a new consent manager to this page, it needs to be added here. If a consent manager can't be detected
     * automatically, simply leave the detections empty.
     *
     * @return array[]
     */
    public static function getKnownConsentManagers(): array
    {
        $detections = self::getSiteContentDetectionsByType();
        $cmDetections = $detections[SiteContentDetectionAbstract::TYPE_CONSENT_MANAGER];

        $consentManagers = [];

        foreach ($cmDetections as $detection) {
            $consentManagers[$detection::getId()] = [
                'name' => $detection::getName(),
                'instructionUrl' => $detection::getInstructionUrl(),
            ];
        }

        return $consentManagers;
    }
}