forked from matomo-org/matomo-php-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MatomoTracker.php
2052 lines (1834 loc) · 67.8 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
*/
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
*/
const VERSION = 1;
/**
* @ignore
*/
public $DEBUG_APPEND_URL = '';
/**
* Visitor ID length
*
* @ignore
*/
const LENGTH_VISITOR_ID = 16;
/**
* Charset
* @see setPageCharset
* @ignore
*/
const DEFAULT_CHARSET_PARAMETER_VALUES = 'utf-8';
/**
* See matomo.js
*/
const FIRST_PARTY_COOKIES_PREFIX = '_pk_';
/**
* Ecommerce item page view tracking stores item's metadata in these Custom Variables slots.
*/
const CVAR_INDEX_ECOMMERCE_ITEM_PRICE = 2;
const CVAR_INDEX_ECOMMERCE_ITEM_SKU = 3;
const CVAR_INDEX_ECOMMERCE_ITEM_NAME = 4;
const CVAR_INDEX_ECOMMERCE_ITEM_CATEGORY = 5;
/**
* Defines how many categories can be used max when calling addEcommerceItem().
* @var int
*/
const MAX_NUM_ECOMMERCE_ITEM_CATEGORIES = 5;
const DEFAULT_COOKIE_PATH = '/';
/**
* 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($idSite, $apiUrl = '')
{
$this->ecommerceItems = array();
$this->attributionInfo = false;
$this->eventCustomVar = false;
$this->forcedDatetime = false;
$this->forcedNewVisit = false;
$this->generationTime = false;
$this->pageCustomVar = false;
$this->customParameters = array();
$this->customData = false;
$this->hasCookies = false;
$this->token_auth = false;
$this->userAgent = false;
$this->country = false;
$this->region = false;
$this->city = false;
$this->lat = false;
$this->long = false;
$this->width = false;
$this->height = false;
$this->plugins = false;
$this->localHour = false;
$this->localMinute = false;
$this->localSecond = false;
$this->idPageview = false;
$this->idSite = $idSite;
$this->urlReferrer = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : false;
$this->pageCharset = self::DEFAULT_CHARSET_PARAMETER_VALUES;
$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;
if (!empty($apiUrl)) {
self::$URL = $apiUrl;
}
// Life of the visitor cookie (in sec)
$this->configVisitorCookieTimeout = 33955200; // 13 months (365 + 28 days)
// Life of the session cookie (in sec)
$this->configSessionCookieTimeout = 1800; // 30 minutes
// Life of the session cookie (in sec)
$this->configReferralCookieTimeout = 15768000; // 6 months
// Visitor Ids in order
$this->userId = false;
$this->forcedVisitorId = false;
$this->cookieVisitorId = false;
$this->randomVisitorId = false;
$this->setNewVisitorId();
$this->configCookiesDisabled = false;
$this->configCookiePath = self::DEFAULT_COOKIE_PATH;
$this->configCookieDomain = '';
$this->currentTs = time();
$this->createTs = $this->currentTs;
$this->visitCount = 0;
$this->currentVisitTs = false;
$this->lastVisitTs = false;
$this->ecommerceLastOrderTimestamp = false;
// Allow debug while blocking the request
$this->requestTimeout = 600;
$this->doBulkRequests = false;
$this->storedTrackingActions = array();
$this->sendImageResponse = true;
$this->visitorCustomVar = $this->getCustomVariablesFromCookie();
$this->outgoingTrackerCookies = array();
$this->incomingTrackerCookies = array();
}
/**
* 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.
*
* @param string $charset
* @return $this
*/
public function setPageCharset($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($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($url)
{
$this->urlReferrer = $url;
return $this;
}
/**
* Sets the time that generating the document on the server side took.
*
* @param int $timeMs Generation time in ms
* @return $this
*/
public function setGenerationTime($timeMs)
{
$this->generationTime = $timeMs;
return $this;
}
/**
* @deprecated
* @ignore
*/
public function setUrlReferer($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($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($id, $name, $value, $scope = 'visit')
{
if (!is_int($id)) {
throw new Exception("Parameter id to setCustomVariable should be an integer");
}
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($id, $scope = 'visit')
{
if ($scope == 'page') {
return isset($this->pageCustomVar[$id]) ? $this->pageCustomVar[$id] : false;
} elseif ($scope == 'event') {
return isset($this->eventCustomVar[$id]) ? $this->eventCustomVar[$id] : false;
} else {
if ($scope != 'visit') {
throw new Exception("Invalid 'scope' parameter value");
}
}
if (!empty($this->visitorCustomVar[$id])) {
return $this->visitorCustomVar[$id];
}
$cookieDecoded = $this->getCustomVariablesFromCookie();
if (!is_int($id)) {
throw new Exception("Parameter to getCustomVariable should be an integer");
}
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()
{
$this->visitorCustomVar = array();
$this->pageCustomVar = array();
$this->eventCustomVar = array();
}
/**
* 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 'dimension1'
* @param string $value Tracking parameter value that shall be sent for this tracking parameter.
* @return $this
* @throws Exception
*/
public function setCustomTrackingParameter($trackingApiParameter, $value)
{
$this->customParameters[$trackingApiParameter] = $value;
return $this;
}
/**
* Clear / reset all previously set custom tracking parameters.
*/
public function clearCustomTrackingParameters()
{
$this->customParameters = array();
}
/**
* 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.
*
* @param int $idSite
* @return $this
*/
public function setIdSite($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($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($userAgent)
{
$this->userAgent = $userAgent;
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().
* @param string $country
* @return $this
*/
public function setCountry($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().
* @param string $region
* @return $this
*/
public function setRegion($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().
* @param string $city
* @return $this
*/
public function setCity($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().
* @param float $lat
* @return $this
*/
public function setLatitude($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().
* @param float $long
* @return $this
*/
public function setLongitude($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()
{
$this->doBulkRequests = true;
}
/**
* 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
*/
public function enableCookies($domain = '', $path = '/')
{
$this->configCookiesDisabled = false;
$this->configCookieDomain = self::domainFixup($domain);
$this->configCookiePath = $path;
}
/**
* If image response is disabled Matomo will respond with a HTTP 204 header instead of responding with a gif.
*/
public function disableSendImageResponse()
{
$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
* @param string $cookieName
* @return string
*/
protected function getCookieName($cookieName)
{
// 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($documentTitle)
{
$this->generateNewPageviewId();
$url = $this->getUrlTrackPageView($documentTitle);
return $this->sendRequest($url);
}
private function generateNewPageviewId()
{
$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($category, $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($contentName, $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(
$interaction,
$contentName,
$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($keyword, $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($idGoal, $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($actionUrl, $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($sku, $name = '', $category = '', $price = 0.0, $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($grandTotal)
{
$url = $this->getUrlTrackEcommerceCartUpdate($grandTotal);
return $this->sendRequest($url);
}
/**
* Sends all stored tracking actions at once. Only has an effect if bulk tracking is enabled.
*
* To enable bulk tracking, call enableBulkTracking().
*
* @throws Exception
* @return string Response
*/
public function doBulkTrack()
{
if (empty($this->storedTrackingActions)) {
throw new Exception(
"Error: you must call the function doTrackPageView or doTrackGoal from this class,
before calling this method doBulkTrack()"
);
}
$data = array('requests' => $this->storedTrackingActions);
// token_auth is not required by default, except if bulk_requests_require_authentication=1
if (!empty($this->token_auth)) {
$data['token_auth'] = $this->token_auth;
}
$postData = json_encode($data);
$response = $this->sendRequest($this->getBaseUrl(), 'POST', $postData, $force = true);
$this->storedTrackingActions = array();
return $response;
}
/**
* Tracks an Ecommerce order.
*
* If the Ecommerce order contains items (products), you must call first the addEcommerceItem() for each item in the order.
* All revenues (grandTotal, subTotal, tax, shipping, discount) will be individually summed and reported in Matomo reports.
* Only the parameters $orderId and $grandTotal are required.
*
* @param string|int $orderId (required) Unique Order ID.
* This will be used to count this order only once in the event the order page is reloaded several times.
* orderId must be unique for each transaction, even on different days, or the transaction will not be recorded by Matomo.
* @param float $grandTotal (required) Grand Total revenue of the transaction (including tax, shipping, etc.)
* @param float $subTotal (optional) Sub total amount, typically the sum of items prices for all items in this order (before Tax and Shipping costs are applied)
* @param float $tax (optional) Tax amount for this order
* @param float $shipping (optional) Shipping amount for this order
* @param float $discount (optional) Discounted amount in this order
* @return mixed Response or true if using bulk request
*/
public function doTrackEcommerceOrder(
$orderId,
$grandTotal,
$subTotal = 0.0,
$tax = 0.0,
$shipping = 0.0,
$discount = 0.0
)
{
$url = $this->getUrlTrackEcommerceOrder($orderId, $grandTotal, $subTotal, $tax, $shipping, $discount);
return $this->sendRequest($url);
}
/**
* Sends a ping request.
*
* Ping requests do not track new actions. If they are sent within the standard visit length (see global.ini.php),
* they will extend the existing visit and the current last action for the visit. If after the standard visit length,
* ping requests will create a new visit using the last action in the last known visit.
*
* @return mixed Response or true if using bulk request
*/
public function doPing()
{
$url = $this->getRequest($this->idSite);
$url .= '&ping=1';
return $this->sendRequest($url);
}
/**
* Sets the current page view as an item (product) page view, or an Ecommerce Category page view.
*
* This must be called before doTrackPageView() on this product/category page.
* It will set 3 custom variables of scope "page" with the SKU, Name and Category for this page view.
* Note: Custom Variables of scope "page" slots 3, 4 and 5 will be used.
*
* On a category page, you may set the parameter $category only and set the other parameters to false.
*
* Tracking Product/Category page views will allow Matomo to report on Product & Categories
* conversion rates (Conversion rate = Ecommerce orders containing this product or category / Visits to the product or category)
*
* @param string $sku Product SKU being viewed
* @param string $name Product Name being viewed
* @param string|array $category Category being viewed. On a Product page, this is the product's category.
* You can also specify an array of up to 5 categories for a given page view.
* @param float $price Specify the price at which the item was displayed
* @return $this
*/
public function setEcommerceView($sku = '', $name = '', $category = '', $price = 0.0)
{
if (!empty($category)) {
if (is_array($category)) {
$category = json_encode($category);
}
} else {
$category = "";
}
$this->pageCustomVar[self::CVAR_INDEX_ECOMMERCE_ITEM_CATEGORY] = array('_pkc', $category);
if (!empty($price)) {
$price = (float)$price;
$price = $this->forceDotAsSeparatorForDecimalPoint($price);
$this->pageCustomVar[self::CVAR_INDEX_ECOMMERCE_ITEM_PRICE] = array('_pkp', $price);
}
// On a category page, do not record "Product name not defined"
if (empty($sku) && empty($name)) {
return $this;
}
if (!empty($sku)) {
$this->pageCustomVar[self::CVAR_INDEX_ECOMMERCE_ITEM_SKU] = array('_pks', $sku);
}
if (empty($name)) {
$name = "";
}
$this->pageCustomVar[self::CVAR_INDEX_ECOMMERCE_ITEM_NAME] = array('_pkn', $name);
return $this;
}
/**
* Force the separator for decimal point to be a dot. See https://github.com/matomo-org/matomo/issues/6435
* If for instance a German locale is used it would be a comma otherwise.
*
* @param float|string $value
* @return string
*/
private function forceDotAsSeparatorForDecimalPoint($value)
{
if (null === $value || false === $value) {
return $value;
}
return str_replace(',', '.', $value);
}
/**
* Returns URL used to track Ecommerce Cart updates
* Calling this function will reinitializes the property ecommerceItems to empty array
* so items will have to be added again via addEcommerceItem()
* @ignore
*/
public function getUrlTrackEcommerceCartUpdate($grandTotal)
{
$url = $this->getUrlTrackEcommerce($grandTotal);
return $url;
}
/**
* Returns URL used to track Ecommerce Orders
* Calling this function will reinitializes the property ecommerceItems to empty array
* so items will have to be added again via addEcommerceItem()
* @ignore
*/
public function getUrlTrackEcommerceOrder(
$orderId,
$grandTotal,
$subTotal = 0.0,
$tax = 0.0,
$shipping = 0.0,
$discount = 0.0
)
{
if (empty($orderId)) {
throw new Exception("You must specifiy an orderId for the Ecommerce order");
}
$url = $this->getUrlTrackEcommerce($grandTotal, $subTotal, $tax, $shipping, $discount);
$url .= '&ec_id=' . urlencode($orderId);
$this->ecommerceLastOrderTimestamp = $this->getTimestamp();
return $url;
}
/**
* Returns URL used to track Ecommerce orders
*
* Calling this function will reinitializes the property ecommerceItems to empty array
* so items will have to be added again via addEcommerceItem()
*
* @ignore
*/
protected function getUrlTrackEcommerce($grandTotal, $subTotal = 0.0, $tax = 0.0, $shipping = 0.0, $discount = 0.0)
{
if (!is_numeric($grandTotal)) {
throw new Exception("You must specifiy a grandTotal for the Ecommerce order (or Cart update)");
}
$url = $this->getRequest($this->idSite);
$url .= '&idgoal=0';
if (!empty($grandTotal)) {
$grandTotal = $this->forceDotAsSeparatorForDecimalPoint($grandTotal);
$url .= '&revenue=' . $grandTotal;
}
if (!empty($subTotal)) {
$subTotal = $this->forceDotAsSeparatorForDecimalPoint($subTotal);
$url .= '&ec_st=' . $subTotal;
}
if (!empty($tax)) {
$tax = $this->forceDotAsSeparatorForDecimalPoint($tax);
$url .= '&ec_tx=' . $tax;
}
if (!empty($shipping)) {
$shipping = $this->forceDotAsSeparatorForDecimalPoint($shipping);
$url .= '&ec_sh=' . $shipping;
}
if (!empty($discount)) {
$discount = $this->forceDotAsSeparatorForDecimalPoint($discount);
$url .= '&ec_dt=' . $discount;
}
if (!empty($this->ecommerceItems)) {
$url .= '&ec_items=' . urlencode(json_encode($this->ecommerceItems));
}
$this->ecommerceItems = array();
return $url;
}
/**
* Builds URL to track a page view.
*
* @see doTrackPageView()
* @param string $documentTitle Page view name as it will appear in Matomo reports
* @return string URL to matomo.php with all parameters set to track the pageview
*/
public function getUrlTrackPageView($documentTitle = '')
{
$url = $this->getRequest($this->idSite);
if (strlen($documentTitle) > 0) {
$url .= '&action_name=' . urlencode($documentTitle);
}
return $url;
}
/**
* Builds URL to track a custom event.
*
* @see doTrackEvent()
* @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 string URL to matomo.php with all parameters set to track the pageview
* @throws
*/
public function getUrlTrackEvent($category, $action, $name = false, $value = false)
{
$url = $this->getRequest($this->idSite);
if (strlen($category) == 0) {
throw new Exception("You must specify an Event Category name (Music, Videos, Games...).");
}
if (strlen($action) == 0) {
throw new Exception("You must specify an Event action (click, view, add...).");
}
$url .= '&e_c=' . urlencode($category);
$url .= '&e_a=' . urlencode($action);
if (strlen($name) > 0) {
$url .= '&e_n=' . urlencode($name);
}
if (strlen($value) > 0) {
$value = $this->forceDotAsSeparatorForDecimalPoint($value);
$url .= '&e_v=' . $value;
}
return $url;
}
/**
* Builds URL to track a content impression.
*
* @see doTrackContentImpression()
* @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|false $contentTarget (optional) The target of the content. For instance the URL of a landing page.
* @throws Exception In case $contentName is empty