-
Notifications
You must be signed in to change notification settings - Fork 83
/
MatomoTracker.php
2581 lines (2226 loc) · 83.5 KB
/
MatomoTracker.php
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Matomo - free/libre analytics platform
*
* For more information, see README.md
*
* @license released under BSD License http://www.opensource.org/licenses/bsd-license.php
* @link https://matomo.org/docs/tracking-api/
*
* @category Matomo
* @package MatomoTracker
*/
/**
* MatomoTracker implements the Matomo Tracking Web API.
*
* For more information, see: https://github.com/matomo-org/matomo-php-tracker/
*
* @package MatomoTracker
* @api
*/
#[AllowDynamicProperties]
class MatomoTracker
{
/**
* Matomo base URL, for example http://example.org/matomo/
* Must be set before using the class by calling
* MatomoTracker::$URL = 'http://yourwebsite.org/matomo/';
*
* @var string
*/
static public $URL = '';
/**
* API Version
*
* @ignore
* @var int
*/
public const VERSION = 1;
/**
* @ignore
*/
public $DEBUG_APPEND_URL = '';
/**
* Visitor ID length
*
* @ignore
*/
public const LENGTH_VISITOR_ID = 16;
/**
* Charset
* @see setPageCharset
* @ignore
*/
public const DEFAULT_CHARSET_PARAMETER_VALUES = 'utf-8';
/**
* See matomo.js
*/
public const FIRST_PARTY_COOKIES_PREFIX = '_pk_';
/**
* Defines how many categories can be used max when calling addEcommerceItem().
* @var int
*/
public const MAX_NUM_ECOMMERCE_ITEM_CATEGORIES = 5;
public const DEFAULT_COOKIE_PATH = '/';
public $ecommerceItems = [];
public $attributionInfo = false;
public $eventCustomVar = [];
public $forcedDatetime = false;
public $forcedNewVisit = false;
public $networkTime = false;
public $serverTime = false;
public $transferTime = false;
public $domProcessingTime = false;
public $domCompletionTime = false;
public $onLoadTime = false;
public $pageCustomVar = [];
public $ecommerceView = [];
public $customParameters = [];
public $customDimensions = [];
public $customData = false;
public $hasCookies = false;
public $token_auth = false;
public $userAgent = false;
public $country = false;
public $region = false;
public $city = false;
public $lat = false;
public $long = false;
public $width = false;
public $height = false;
public $plugins = false;
public $localHour = false;
public $localMinute = false;
public $localSecond = false;
public $idPageview = false;
public $idPageviewSetManually = false;
public $idSite;
public $urlReferrer;
public $pageCharset = self::DEFAULT_CHARSET_PARAMETER_VALUES;
public $pageUrl;
public $ip;
public $acceptLanguage;
public $clientHints = [];
// Life of the visitor cookie (in sec)
public $configVisitorCookieTimeout = 33955200; // 13 months (365 + 28 days)
// Life of the session cookie (in sec)
public $configSessionCookieTimeout = 1800; // 30 minutes
// Life of the session cookie (in sec)
public $configReferralCookieTimeout = 15768000; // 6 months
// Visitor Ids in order
public $userId = false;
public $forcedVisitorId = false;
public $cookieVisitorId = false;
public $randomVisitorId = false;
public $configCookiesDisabled = false;
public $configCookiePath = self::DEFAULT_COOKIE_PATH;
public $configCookieDomain = '';
public $configCookieSameSite = '';
public $configCookieSecure = false;
public $configCookieHTTPOnly = false;
public $currentTs;
public $createTs;
// Allow debug while blocking the request
public $requestTimeout = 600;
public $requestConnectTimeout = 300;
public $doBulkRequests = false;
public $storedTrackingActions = [];
public $sendImageResponse = true;
public $outgoingTrackerCookies = [];
public $incomingTrackerCookies = [];
public $visitorCustomVar;
private $requestMethod = null;
/**
* Builds a MatomoTracker object, used to track visits, pages and Goal conversions
* for a specific website, by using the Matomo Tracking API.
*
* @param int $idSite Id site to be tracked
* @param string $apiUrl "http://example.org/matomo/" or "http://matomo.example.org/"
* If set, will overwrite MatomoTracker::$URL
*/
public function __construct(int $idSite, string $apiUrl = '')
{
$this->idSite = $idSite;
$this->urlReferrer = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : false;
$this->pageUrl = self::getCurrentUrl();
$this->ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
$this->acceptLanguage = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : false;
$this->userAgent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : false;
$this->setClientHints(
!empty($_SERVER['HTTP_SEC_CH_UA_MODEL']) ? $_SERVER['HTTP_SEC_CH_UA_MODEL'] : '',
!empty($_SERVER['HTTP_SEC_CH_UA_PLATFORM']) ? $_SERVER['HTTP_SEC_CH_UA_PLATFORM'] : '',
!empty($_SERVER['HTTP_SEC_CH_UA_PLATFORM_VERSION']) ? $_SERVER['HTTP_SEC_CH_UA_PLATFORM_VERSION'] : '',
!empty($_SERVER['HTTP_SEC_CH_UA_FULL_VERSION_LIST']) ? $_SERVER['HTTP_SEC_CH_UA_FULL_VERSION_LIST'] : '',
!empty($_SERVER['HTTP_SEC_CH_UA_FULL_VERSION']) ? $_SERVER['HTTP_SEC_CH_UA_FULL_VERSION'] : ''
);
if (!empty($apiUrl)) {
self::$URL = $apiUrl;
}
$this->setNewVisitorId();
$this->currentTs = time();
$this->createTs = $this->currentTs;
$this->visitorCustomVar = $this->getCustomVariablesFromCookie();
}
public function setApiUrl(string $url): void
{
self::$URL = $url;
}
/**
* By default, Matomo expects utf-8 encoded values, for example
* for the page URL parameter values, Page Title, etc.
* It is recommended to only send UTF-8 data to Matomo.
* If required though, you can also specify another charset using this function.
*
* @return $this
*/
public function setPageCharset(string $charset = '')
{
$this->pageCharset = $charset;
return $this;
}
/**
* Sets the current URL being tracked
*
* @param string $url Raw URL (not URL encoded)
* @return $this
*/
public function setUrl(string $url)
{
$this->pageUrl = $url;
return $this;
}
/**
* Sets the URL referrer used to track Referrers details for new visits.
*
* @param string $url Raw URL (not URL encoded)
* @return $this
*/
public function setUrlReferrer(string $url)
{
$this->urlReferrer = $url;
return $this;
}
/**
* This method is deprecated and does nothing. It used to set the time that it took to generate the document on the server side.
*
* @param int $timeMs Generation time in ms
* @return $this
*
* @deprecated this metric is deprecated please use performance timings instead
* @see setPerformanceTimings
*/
public function setGenerationTime(int $timeMs)
{
return $this;
}
/**
* Sets timings for various browser performance metrics.
* @see https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming
*
* @param null|int $network Network time in ms (connectEnd – fetchStart)
* @param null|int $server Server time in ms (responseStart – requestStart)
* @param null|int $transfer Transfer time in ms (responseEnd – responseStart)
* @param null|int $domProcessing DOM Processing to Interactive time in ms (domInteractive – domLoading)
* @param null|int $domCompletion DOM Interactive to Complete time in ms (domComplete – domInteractive)
* @param null|int $onload Onload time in ms (loadEventEnd – loadEventStart)
* @return $this
*/
public function setPerformanceTimings(
?int $network = null,
?int $server = null,
?int $transfer = null,
?int $domProcessing = null,
?int $domCompletion = null,
?int $onload = null
) {
$this->networkTime = $network;
$this->serverTime = $server;
$this->transferTime = $transfer;
$this->domProcessingTime = $domProcessing;
$this->domCompletionTime = $domCompletion;
$this->onLoadTime = $onload;
return $this;
}
/**
* Clear / reset all previously set performance metrics.
*/
public function clearPerformanceTimings(): void
{
$this->networkTime = false;
$this->serverTime = false;
$this->transferTime = false;
$this->domProcessingTime = false;
$this->domCompletionTime = false;
$this->onLoadTime = false;
}
/**
* @deprecated
* @ignore
*/
public function setUrlReferer(string $url)
{
$this->setUrlReferrer($url);
return $this;
}
/**
* Sets the attribution information to the visit, so that subsequent Goal conversions are
* properly attributed to the right Referrer URL, timestamp, Campaign Name & Keyword.
*
* This must be a JSON encoded string that would typically be fetched from the JS API:
* matomoTracker.getAttributionInfo() and that you have JSON encoded via JSON2.stringify()
*
* If you call enableCookies() then these referral attribution values will be set
* to the 'ref' first party cookie storing referral information.
*
* @param string $jsonEncoded JSON encoded array containing Attribution info
* @return $this
* @throws Exception
* @see function getAttributionInfo() in https://github.com/matomo-org/matomo/blob/master/js/matomo.js
*/
public function setAttributionInfo(string $jsonEncoded)
{
$decoded = json_decode($jsonEncoded, $assoc = true);
if (!is_array($decoded)) {
throw new Exception("setAttributionInfo() is expecting a JSON encoded string, $jsonEncoded given");
}
$this->attributionInfo = $decoded;
return $this;
}
/**
* Sets Visit Custom Variable.
* See https://matomo.org/docs/custom-variables/
*
* @param int $id Custom variable slot ID from 1-5
* @param string $name Custom variable name
* @param string $value Custom variable value
* @param string $scope Custom variable scope. Possible values: visit, page, event
* @return $this
* @throws Exception
*/
public function setCustomVariable(
int $id,
string $name,
string $value,
string $scope = 'visit'
) {
if ($scope === 'page') {
$this->pageCustomVar[$id] = array($name, $value);
} elseif ($scope === 'event') {
$this->eventCustomVar[$id] = array($name, $value);
} elseif ($scope === 'visit') {
$this->visitorCustomVar[$id] = array($name, $value);
} else {
throw new Exception("Invalid 'scope' parameter value");
}
return $this;
}
/**
* Returns the currently assigned Custom Variable.
*
* If scope is 'visit', it will attempt to read the value set in the first party cookie created by Matomo Tracker
* ($_COOKIE array).
*
* @param int $id Custom Variable integer index to fetch from cookie. Should be a value from 1 to 5
* @param string $scope Custom variable scope. Possible values: visit, page, event
*
* @throws Exception
* @return mixed An array with this format: array( 0 => CustomVariableName, 1 => CustomVariableValue ) or false
* @see matomo.js getCustomVariable()
*/
public function getCustomVariable(int $id, string $scope = 'visit')
{
if ($scope === 'page') {
return $this->pageCustomVar[$id] ?? false;
}
if ($scope === 'event') {
return $this->eventCustomVar[$id] ?? false;
}
if ($scope !== 'visit') {
throw new Exception("Invalid 'scope' parameter value");
}
if (!empty($this->visitorCustomVar[$id])) {
return $this->visitorCustomVar[$id];
}
$cookieDecoded = $this->getCustomVariablesFromCookie();
if (!is_array($cookieDecoded)
|| !isset($cookieDecoded[$id])
|| !is_array($cookieDecoded[$id])
|| count($cookieDecoded[$id]) !== 2
) {
return false;
}
return $cookieDecoded[$id];
}
/**
* Clears any Custom Variable that may be have been set.
*
* This can be useful when you have enabled bulk requests,
* and you wish to clear Custom Variables of 'visit' scope.
*/
public function clearCustomVariables(): void
{
$this->visitorCustomVar = [];
$this->pageCustomVar = [];
$this->eventCustomVar = [];
}
/**
* Sets a specific custom dimension
*
* @param int $id id of custom dimension
* @param string $value value for custom dimension
* @return $this
*/
public function setCustomDimension(int $id, string $value)
{
$this->customDimensions['dimension'.$id] = $value;
return $this;
}
/**
* Clears all previously set custom dimensions
*/
public function clearCustomDimensions(): void
{
$this->customDimensions = [];
}
/**
* Returns the value of the custom dimension with the given id
*
* @param int $id id of custom dimension
* @return string|null
*/
public function getCustomDimension(int $id): ?string
{
return $this->customDimensions['dimension'.$id] ?? null;
}
/**
* Sets a custom tracking parameter. This is useful if you need to send any tracking parameters for a 3rd party
* plugin that is not shipped with Matomo itself. Please note that custom parameters are cleared after each
* tracking request.
*
* @param string $trackingApiParameter The name of the tracking API parameter, eg 'bw_bytes'
* @param string $value Tracking parameter value that shall be sent for this tracking parameter.
* @return $this
* @throws Exception
*/
public function setCustomTrackingParameter(string $trackingApiParameter, string $value)
{
$matches = [];
if (preg_match('/^dimension([0-9]+)$/', $trackingApiParameter, $matches)) {
$this->setCustomDimension($matches[1], $value);
return $this;
}
$this->customParameters[$trackingApiParameter] = $value;
return $this;
}
/**
* Clear / reset all previously set custom tracking parameters.
*/
public function clearCustomTrackingParameters(): void
{
$this->customParameters = [];
}
/**
* Sets the current visitor ID to a random new one.
* @return $this
*/
public function setNewVisitorId()
{
$this->randomVisitorId = substr(md5(uniqid(rand(), true)), 0, self::LENGTH_VISITOR_ID);
$this->forcedVisitorId = false;
$this->cookieVisitorId = false;
return $this;
}
/**
* Sets the current site ID.
*
* @return $this
*/
public function setIdSite(int $idSite)
{
$this->idSite = $idSite;
return $this;
}
/**
* Sets the Browser language. Used to guess visitor countries when GeoIP is not enabled
*
* @param string $acceptLanguage For example "fr-fr"
* @return $this
*/
public function setBrowserLanguage(string $acceptLanguage)
{
$this->acceptLanguage = $acceptLanguage;
return $this;
}
/**
* Sets the user agent, used to detect OS and browser.
* If this function is not called, the User Agent will default to the current user agent.
*
* @param string $userAgent
* @return $this
*/
public function setUserAgent(string $userAgent)
{
$this->userAgent = $userAgent;
return $this;
}
/**
* Sets the client hints, used to detect OS and browser.
* If this function is not called, the client hints sent with the current request will be used.
*
* Supported as of Matomo 4.12.0
*
* @param string $model Value of the header 'HTTP_SEC_CH_UA_MODEL'
* @param string $platform Value of the header 'HTTP_SEC_CH_UA_PLATFORM'
* @param string $platformVersion Value of the header 'HTTP_SEC_CH_UA_PLATFORM_VERSION'
* @param string|array<string, mixed> $fullVersionList Value of header 'HTTP_SEC_CH_UA_FULL_VERSION_LIST'
* or an array containing all brands with the structure
* [['brand' => 'Chrome', 'version' => '10.0.2'], ['brand' => '...]
* @param string $uaFullVersion Value of the header 'HTTP_SEC_CH_UA_FULL_VERSION'
*
* @return $this
*/
public function setClientHints(
string $model = '',
string $platform = '',
string $platformVersion = '',
$fullVersionList = '',
string $uaFullVersion = ''
) {
if (is_string($fullVersionList)) {
$reg = '/^"([^"]+)"; ?v="([^"]+)"(?:, )?/';
$list = [];
while (\preg_match($reg, $fullVersionList, $matches)) {
$list[] = ['brand' => $matches[1], 'version' => $matches[2]];
$fullVersionList = \substr($fullVersionList, \strlen($matches[0]));
}
$fullVersionList = $list;
} elseif (!is_array($fullVersionList)) {
$fullVersionList = [];
}
$this->clientHints = array_filter([
'model' => $model,
'platform' => $platform,
'platformVersion' => $platformVersion,
'uaFullVersion' => $uaFullVersion,
'fullVersionList' => $fullVersionList,
]);
return $this;
}
/**
* Sets the country of the visitor. If not used, Matomo will try to find the country
* using either the visitor's IP address or language.
*
* Allowed only for Admin/Super User, must be used along with setTokenAuth().
*
* @return $this
*/
public function setCountry(string $country)
{
$this->country = $country;
return $this;
}
/**
* Sets the region of the visitor. If not used, Matomo may try to find the region
* using the visitor's IP address (if configured to do so).
*
* Allowed only for Admin/Super User, must be used along with setTokenAuth().
*
* @return $this
*/
public function setRegion(string $region)
{
$this->region = $region;
return $this;
}
/**
* Sets the city of the visitor. If not used, Matomo may try to find the city
* using the visitor's IP address (if configured to do so).
*
* Allowed only for Admin/Super User, must be used along with setTokenAuth().
*
* @return $this
*/
public function setCity(string $city)
{
$this->city = $city;
return $this;
}
/**
* Sets the latitude of the visitor. If not used, Matomo may try to find the visitor's
* latitude using the visitor's IP address (if configured to do so).
*
* Allowed only for Admin/Super User, must be used along with setTokenAuth().
*
* @return $this
*/
public function setLatitude(float $lat)
{
$this->lat = $lat;
return $this;
}
/**
* Sets the longitude of the visitor. If not used, Matomo may try to find the visitor's
* longitude using the visitor's IP address (if configured to do so).
*
* Allowed only for Admin/Super User, must be used along with setTokenAuth().
*
* @return $this
*/
public function setLongitude(float $long)
{
$this->long = $long;
return $this;
}
/**
* Enables the bulk request feature. When used, each tracking action is stored until the
* doBulkTrack method is called. This method will send all tracking data at once.
*/
public function enableBulkTracking(): void
{
$this->doBulkRequests = true;
}
/**
* Disables the bulk request feature. Make sure to call `doBulkTrack()` before disabling it if you have stored
* tracking actions previously as this method won't be sending any previously stored actions before disabling it.
*/
public function disableBulkTracking(): void
{
$this->doBulkRequests = false;
}
/**
* Enable Cookie Creation - this will cause a first party VisitorId cookie to be set when the VisitorId is set or reset
*
* @param string $domain (optional) Set first-party cookie domain.
* Accepted values: example.com, *.example.com (same as .example.com) or subdomain.example.com
* @param string $path (optional) Set first-party cookie path
* @param bool $secure (optional) Set secure flag for cookies
* @param bool $httpOnly (optional) Set HTTPOnly flag for cookies
* @param string $sameSite (optional) Set SameSite flag for cookies
*/
public function enableCookies(
string $domain = '',
string $path = '/',
bool $secure = false,
bool $httpOnly = false,
string $sameSite = ''
): void {
$this->configCookiesDisabled = false;
$this->configCookieDomain = self::domainFixup($domain);
$this->configCookiePath = $path;
$this->configCookieSecure = $secure;
$this->configCookieHTTPOnly = $httpOnly;
$this->configCookieSameSite = $sameSite;
}
/**
* If image response is disabled Matomo will respond with a HTTP 204 header instead of responding with a gif.
*/
public function disableSendImageResponse(): void
{
$this->sendImageResponse = false;
}
/**
* Fix-up domain
*/
protected static function domainFixup($domain)
{
if (strlen($domain) > 0) {
$dl = strlen($domain) - 1;
// remove trailing '.'
if ($domain[$dl] === '.') {
$domain = substr($domain, 0, $dl);
}
// remove leading '*'
if (substr($domain, 0, 2) === '*.') {
$domain = substr($domain, 1);
}
}
return $domain;
}
/**
* Get cookie name with prefix and domain hash
*/
protected function getCookieName(string $cookieName): string
{
// NOTE: If the cookie name is changed, we must also update the method in matomo.js with the same name.
$hash = substr(
sha1(
($this->configCookieDomain === ''
? self::getCurrentHost()
: $this->configCookieDomain
) . $this->configCookiePath
),
0,
4
);
return self::FIRST_PARTY_COOKIES_PREFIX . $cookieName . '.' . $this->idSite . '.' . $hash;
}
/**
* Tracks a page view
*
* @param string $documentTitle Page title as it will appear in the Actions > Page titles report
* @return mixed Response string or true if using bulk requests.
*/
public function doTrackPageView(string $documentTitle)
{
if (!$this->idPageviewSetManually) {
$this->generateNewPageviewId();
}
$url = $this->getUrlTrackPageView($documentTitle);
return $this->sendRequest($url);
}
/**
* Override PageView id for every use of `doTrackPageView()`. Do not use this if you call `doTrackPageView()`
* multiple times during tracking (if, for example, you are tracking a single page application).
*/
public function setPageviewId(string $idPageview): void
{
$this->idPageview = $idPageview;
$this->idPageviewSetManually = true;
}
/**
* Returns the PageView id. If the id was manually set using `setPageViewId()`, that id will be returned.
* If the id was not set manually, the id that was automatically generated in last `doTrackPageView()` will
* be returned. If there was no last page view, this will be false.
*
* @return string|false The PageView id as string or false if there is none yet.
*/
public function getPageviewId()
{
return $this->idPageview;
}
private function generateNewPageviewId(): void
{
$this->idPageview = substr(md5(uniqid(rand(), true)), 0, 6);
}
/**
* Tracks an event
*
* @param string $category The Event Category (Videos, Music, Games...)
* @param string $action The Event's Action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...)
* @param string|bool $name (optional) The Event's object Name (a particular Movie name, or Song name, or File name...)
* @param float|bool $value (optional) The Event's value
* @return mixed Response string or true if using bulk requests.
*/
public function doTrackEvent(
string $category,
string $action,
$name = false,
$value = false
) {
$url = $this->getUrlTrackEvent($category, $action, $name, $value);
return $this->sendRequest($url);
}
/**
* Tracks a content impression
*
* @param string $contentName The name of the content. For instance 'Ad Foo Bar'
* @param string $contentPiece The actual content. For instance the path to an image, video, audio, any text
* @param string|bool $contentTarget (optional) The target of the content. For instance the URL of a landing page.
* @return mixed Response string or true if using bulk requests.
*/
public function doTrackContentImpression(
string $contentName,
string $contentPiece = 'Unknown',
$contentTarget = false
) {
$url = $this->getUrlTrackContentImpression($contentName, $contentPiece, $contentTarget);
return $this->sendRequest($url);
}
/**
* Tracks a content interaction. Make sure you have tracked a content impression using the same content name and
* content piece, otherwise it will not count. To do so you should call the method doTrackContentImpression();
*
* @param string $interaction The name of the interaction with the content. For instance a 'click'
* @param string $contentName The name of the content. For instance 'Ad Foo Bar'
* @param string $contentPiece The actual content. For instance the path to an image, video, audio, any text
* @param string|bool $contentTarget (optional) The target the content leading to when an interaction occurs. For instance the URL of a landing page.
* @return mixed Response string or true if using bulk requests.
*/
public function doTrackContentInteraction(
string $interaction,
string $contentName,
string $contentPiece = 'Unknown',
$contentTarget = false
) {
$url = $this->getUrlTrackContentInteraction($interaction, $contentName, $contentPiece, $contentTarget);
return $this->sendRequest($url);
}
/**
* Tracks an internal Site Search query, and optionally tracks the Search Category, and Search results Count.
* These are used to populate reports in Actions > Site Search.
*
* @param string $keyword Searched query on the site
* @param string $category (optional) Search engine category if applicable
* @param bool|int $countResults (optional) results displayed on the search result page. Used to track "zero result" keywords.
*
* @return mixed Response or true if using bulk requests.
*/
public function doTrackSiteSearch(
string $keyword,
string $category = '',
$countResults = false
) {
$url = $this->getUrlTrackSiteSearch($keyword, $category, $countResults);
return $this->sendRequest($url);
}
/**
* Records a Goal conversion
*
* @param int $idGoal Id Goal to record a conversion
* @param float $revenue Revenue for this conversion
* @return mixed Response or true if using bulk request
*/
public function doTrackGoal(int $idGoal, float $revenue = 0.0)
{
$url = $this->getUrlTrackGoal($idGoal, $revenue);
return $this->sendRequest($url);
}
/**
* Tracks a download or outlink
*
* @param string $actionUrl URL of the download or outlink
* @param string $actionType Type of the action: 'download' or 'link'
* @return mixed Response or true if using bulk request
*/
public function doTrackAction(string $actionUrl, string $actionType)
{
// Referrer could be udpated to be the current URL temporarily (to mimic JS behavior)
$url = $this->getUrlTrackAction($actionUrl, $actionType);
return $this->sendRequest($url);
}
/**
* Adds an item in the Ecommerce order.
*
* This should be called before doTrackEcommerceOrder(), or before doTrackEcommerceCartUpdate().
* This function can be called for all individual products in the cart (or order).
* SKU parameter is mandatory. Other parameters are optional (set to false if value not known).
* Ecommerce items added via this function are automatically cleared when doTrackEcommerceOrder() or getUrlTrackEcommerceOrder() is called.
*
* @param string $sku (required) SKU, Product identifier
* @param string $name (optional) Product name
* @param string|array $category (optional) Product category, or array of product categories (up to 5 categories can be specified for a given product)
* @param float|int $price (optional) Individual product price (supports integer and decimal prices)
* @param int $quantity (optional) Product quantity. If not specified, will default to 1 in the Reports
* @throws Exception
* @return $this
*/
public function addEcommerceItem(
string $sku,
string $name = '',
$category = '',
$price = 0.0,
int $quantity = 1
) {
if (empty($sku)) {
throw new Exception("You must specify a SKU for the Ecommerce item");
}
$price = $this->forceDotAsSeparatorForDecimalPoint($price);
$this->ecommerceItems[] = array($sku, $name, $category, $price, $quantity);
return $this;
}
/**
* Tracks a Cart Update (add item, remove item, update item).
*
* On every Cart update, you must call addEcommerceItem() for each item (product) in the cart,
* including the items that haven't been updated since the last cart update.
* Items which were in the previous cart and are not sent in later Cart updates will be deleted from the cart (in the database).
*
* @param float $grandTotal Cart grandTotal (typically the sum of all items' prices)
* @return mixed Response or true if using bulk request
*/
public function doTrackEcommerceCartUpdate(float $grandTotal)
{
$url = $this->getUrlTrackEcommerceCartUpdate($grandTotal);
return $this->sendRequest($url);
}
/**