-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
TrackerClient.php
1245 lines (942 loc) · 38.3 KB
/
TrackerClient.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
namespace OwaSdk\Tracker;
use OwaSdk\Tracker\State;
use OwaSdk\OwaClient;
use OwaSdk\Tracker\TrackingEvent;
use OwaSdk\sdk as sdk;
/**
* Open Web Analytics - An Open Source Web Analytics Framework
* Licensed under GPL v2.0 http://www.gnu.org/copyleft/gpl.html
*
*/
/**
* Tracker Class
*
* @author Peter Adams <peter@openwebanalytics.com>
* @license http://www.gnu.org/copyleft/gpl.html GPL v2.0
*/
class TrackerClient extends OwaClient {
var $config;
var $state;
var $commerce_event;
var $pageview_event;
var $global_event_properties = array();
var $stateInit;
var $organicSearchEngines;
// set one traffic has been attributed.
var $isTrafficAttributed;
public function __construct($config = null) {
$defaults = [
'instance_url' => '',
'visitor_param' => 'v',
'campaign_params' => [
'campaign' => 'owa_campaign',
'medium' => 'owa_medium',
'source' => 'owa_source',
'search_terms' => 'owa_search_terms',
'ad' => 'owa_ad',
'ad_type' => 'owa_ad_type' ],
'trafficAttributionMode' => 'direct',
'campaignAttributionWindow' => 60,
'site_session_param' => 'ss',
'session_length' => 1800,
'maxCustomVars' => 5,
'max_prior_campaigns' => 5,
'trafficAttributionMode' => 'direct',
'campaignAttributionWindow' => 60,
'ns' => 'owa_',
'cookie_persistence' => true, // Controls persistence of cookies, only for use in europe needed
];
$client_config = array_merge( $defaults, $config );
// parent will override the default config with passed values.
parent::__construct($client_config);
$domain = '';
if (array_key_exists( 'cookie_domain', $config) ) {
$domain = $config['cookie_domain'];
}
// set the cookie domain
$this->setCookieDomain( $domain );
// inititiate state store
$state_config = [
'cookie_domain' => $this->getSetting( 'cookie_domain' ),
'ns' => $this->getSetting( 'ns' ),
'cookie_persistence' => $this->getSetting( 'cookie_persistence' )
];
$this->state = new State($state_config);
$this->pageview_event = $this->makeEvent();
$this->pageview_event->setEventType('base.page_request');
// Set the page url from environmental vars
$this->setGlobalEventProperty( 'page_url', $this->getCurrentUrl() );
$this->registerStateStore('v', time()+3600*24*365*10, '', 'assoc', 'cookie', true);
$this->registerStateStore('s', time()+3600*24*365*10, '', 'assoc', 'cookie', true);
$this->registerStateStore('b', null, '', 'json', 'cookie', true);
$cwindow = $this->getSetting( 'campaignAttributionWindow' );
$this->registerStateStore('c', time() + 3600 * 24 * $cwindow , '', 'json', 'cookie', true);
$this->organicSearchEngines = [
['d' => 'google', 'q' => 'q'],
['d' => 'yahoo', 'q' => 'p'],
['d' => 'msn', 'q' => 'q'],
['d' => 'bing', 'q' => 'q'],
['d' => 'images.google', 'q' => 'q'],
['d' => 'images.search.yahoo.com', 'q' => 'p'],
['d' => 'aol', 'q' => 'query'],
['d' => 'aol', 'q' => 'encquery'],
['d' => 'aol', 'q' => 'q'],
['d' => 'lycos', 'q' => 'query'],
['d' => 'ask', 'q' => 'q'],
['d' => 'altavista', 'q' => 'q'],
['d' => 'netscape', 'q' => 'query'],
['d' => 'cnn', 'q' => 'query'],
['d' => 'about', 'q' => 'terms'],
['d' => 'mamma', 'q' => 'q'],
['d' => 'daum', 'q' => 'q'],
['d' => 'eniro', 'q' => 'search_word'],
['d' => 'naver', 'q' => 'query'],
['d' => 'pchome', 'q' => 'q'],
['d' => 'alltheweb', 'q' => 'q'],
['d' => 'voila', 'q' => 'rdata'],
['d' => 'virgilio', 'q' => 'qs'],
['d' => 'live', 'q' => 'q'],
['d' => 'baidu', 'q' => 'wd'],
['d' => 'alice', 'q' => 'qs'],
['d' => 'yandex', 'q' => 'text'],
['d' => 'najdi', 'q' => 'q'],
['d' => 'mama', 'q' => 'query'],
['d' => 'seznam', 'q' => 'q'],
['d' => 'search', 'q' => 'q'],
['d' => 'wp', 'q' => 'szukaj'],
['d' => 'onet', 'q' => 'qt'],
['d' => 'szukacz', 'q' => 'q'],
['d' => 'yam', 'q' => 'k'],
['d' => 'kvasir', 'q' => 'q'],
['d' => 'sesam', 'q' => 'q'],
['d' => 'ozu', 'q' => 'q'],
['d' => 'terra', 'q' => 'query'],
['d' => 'mynet', 'q' => 'q'],
['d' => 'ekolay', 'q' => 'q'],
['d' => 'rambler', 'q' => 'query'],
['d' => 'rambler', 'q' => 'words'],
['d' => 'duckduckgo', 'q' => 'q'],
];
}
public function setPageTitle($value) {
$this->pageview_event->set('page_title', $value);
}
public function setPageType($value) {
$this->pageview_event->set('page_type', $value);
}
public function setProperty($name, $value) {
$this->setGlobalEventProperty($name, $value);
}
private function setGlobalEventProperty($name, $value) {
$this->global_event_properties[$name] = $value;
}
private function getGlobalEventProperty($name) {
if ( array_key_exists($name, $this->global_event_properties) ) {
return $this->global_event_properties[$name];
}
}
private function deleteGlobalEventProperty( $name ) {
if ( array_key_exists($name, $this->global_event_properties) ) {
unset($this->global_event_properties[$name]);
}
}
private function manageState( &$event ) {
if ( ! $this->stateInit ) {
$this->setVisitorId( $event );
$this->setFirstSessionTimestamp( $event );
$this->setLastRequestTime( $event );
$this->setSessionId( $event );
$this->setNumberPriorSessions( $event );
$this->setDaysSinceLastSession( $event );
$this->setTrafficAttribution( $event );
$this->stateInit = true;
}
}
private function setVisitorId( &$event ) {
$visitor_id = $this->state->get( 'v', 'vid' );
if ( ! $visitor_id ) {
$visitor_id = $this->state->get( 'v' );
$this->state->clear( 'v' );
$this->state->set( 'v', 'vid', $visitor_id, 'cookie', true );
}
if ( ! $visitor_id ) {
$visitor_id = $event->getSiteSpecificGuid( $this->getSiteId() );
$this->setGlobalEventProperty( 'is_new_visitor', true );
$this->state->set( 'v', 'vid', $visitor_id, 'cookie', true );
}
// set property on event object
$this->setGlobalEventProperty( 'visitor_id', $visitor_id );
}
private function setNumberPriorSessions( &$event ) {
// if check for nps value in vistor cookie.
$nps = $this->state->get('v', 'nps');
// if new session, increment visit count and persist to state store
if ( $this->getGlobalEventProperty('is_new_session' ) ) {
// set value to 0 if not found.
if ( ! $nps ) {
$nps = "0";
} else {
$nps = $nps + 1;
}
$this->state->set('v', 'nps', $nps, 'cookie', true);
}
// set property on the event object
$this->setGlobalEventProperty('nps', $nps);
}
private function setFirstSessionTimestamp( &$event ) {
$fsts = $this->state->get( 'v', 'fsts' );
if ( ! $fsts ) {
$fsts = $event->get('timestamp');
$this->state->set($this->getSetting('visitor_param'), 'fsts', $fsts , 'cookie', true);
}
$this->setGlobalEventProperty( 'fsts', $fsts );
// calc days since first session
$dsfs = round( ( $fsts - $event->get( 'timestamp' ) ) / ( 3600 * 24 ) ) ;
$this->state->set($this->getSetting( 'visitor_param' ), 'dsfs', $dsfs , 'cookie', true);
$this->setGlobalEventProperty( 'dsfs', $dsfs );
}
private function setDaysSinceLastSession( &$event ) {
sdk::debug('setting days since last session.');
$dsps = '';
if ( $this->getGlobalEventProperty( 'is_new_session' ) ) {
sdk::debug( 'timestamp: ' . $event->get( 'timestamp' ) );
$last_req = $this->getGlobalEventProperty( 'last_req' );
if ( ! $last_req ) {
$last_req = $event->get( 'timestamp' );
}
sdk::debug( 'last_req: ' . $last_req );
$dsps = round( ( $event->get( 'timestamp' ) - $last_req ) / ( 3600*24 ) );
$this->state->set('s', 'dsps', $dsps , 'cookie', true);
}
if ( ! $dsps ) {
$dsps = $this->state->get( 's', 'dsps' );
if ( ! $dsps ) {
$dsps = 0;
}
}
$this->setGlobalEventProperty( 'dsps', $dsps );
}
private function setSessionId( &$event ) {
$is_new_session = $this->isNewSession( $event->get( 'timestamp' ), $this->getGlobalEventProperty( 'last_req' ) );
// if its a new seession based on time or if there is no prior session ID found, make a new session
if ( $is_new_session || ! $this->getSessionId() ) {
sdk::debug("is new session");
//set prior_session_id
$prior_session_id = $this->getSessionId();
if ( ! $prior_session_id ) {
$state_store_name = sprintf('%s_%s', $this->getSetting('site_session_param'), $this->getSiteId() );
$prior_session_id = $this->state->get($state_store_name, 's');
} else {
$this->setGlobalEventProperty( 'prior_session_id', $prior_session_id );
}
$this->resetSessionState();
// generate new session id
$session_id = $event->getSiteSpecificGuid( $this->getSiteId() );
//mark new session flag on current request
$this->setGlobalEventProperty( 'is_new_session', true );
} else {
sdk::debug("is existing session");
// Must be an active session so just pull the session id from the state store
$session_id = $this->getSessionId();
}
// set global event property
$this->setGlobalEventProperty( 'session_id', $session_id );
// set sid state
$this->state->set( 's', 'sid', $session_id, 'cookie', true );
}
public function getSessionId() {
return $this->state->get('s', 'sid');
}
private function setLastRequestTime( &$event ) {
$last_req = $this->state->get('s', 'last_req');
// set property on event object
$this->setGlobalEventProperty( 'last_req', $last_req );
sdk::debug("setting last_req value of $last_req as global event property.");
// store new state value
$this->state->set( 's', 'last_req', $event->get( 'timestamp' ), 'cookie', true );
}
/**
* Check to see if request is a new or active session
*
* @return boolean
*/
private function isNewSession($timestamp = '', $last_req = 0) {
$is_new_session = false;
if ( ! $timestamp ) {
$timestamp = time();
}
$time_since_lastreq = $timestamp - $last_req;
$len = $this->getSetting( 'session_length' );
if ( $time_since_lastreq < $len ) {
sdk::debug("This request is part of an active session.");
return false;
} else {
//NEW SESSION. prev session expired, because no requests since some time.
sdk::debug("This request is the start of a new session. Prior session expired.");
return true;
}
}
/**
* Tracks Event with Full state and globals
*
* This function processes a tracking event by adding full state and global properties to it
* Typically used by syncronous events such as Pageviews
*
* @param object $event
* @return boolean
*/
public function trackEvent( $event ) {
// do not track anything if user is in overlay mode
if ($this->state->get('overlay')) {
return false;
}
$this->setGlobalEventProperty( 'HTTP_REFERER', $this->getServerParam('HTTP_REFERER') );
$this->setGlobalEventProperty( 'HTTP_USER_AGENT', $this->getServerParam('HTTP_USER_AGENT') );
// set various state properties.
$this->manageState( $event );
$event = $this->setAllGlobalEventProperties( $event );
// log event to server
return $this->logEvent($event->getEventType(), $event);
}
/**
* Tracks Event without state or globals
*
* This function processes a raw tracking event without any state or globals added to it
* Typically used by asyncronous events such as Delayed commerce transactions or programaticly derived events
*
* @param object $event
* @return boolean
*/
public function trackStatelessEvent( $event ) {
$event->set( 'site_id', $this->getSiteId() );
// log event to server.
return $this->logEvent( $event->getEventType(), $event );
}
/**
* Add Global properties to Tracking Event
*
* This function add global properties to the tracking event
*
* @param object $event
* @return $event
*/
public function setAllGlobalEventProperties( $event ) {
if ( ! $event->get('site_id') ) {
$event->set( 'site_id', $this->getSiteId() );
}
// add custom variables to global properties if not there already
for ( $i=1; $i <= $this->getSetting( 'maxCustomVars' ); $i++ ) {
$cv_param_name = 'cv' . $i;
$cv_value = '';
// if the custom var is not already a global property
if ( ! $this->getGlobalEventProperty( $cv_param_name ) ) {
// check to see if it exists
$cv_value = $this->getCustomVar( $i );
// if so add it
if ( $cv_value ) {
$this->setGlobalEventProperty( $cv_param_name, $cv_value );
}
}
}
// merge global event properties
$event->setNewProperties( $this->global_event_properties );
return $event;
}
public function getAllEventProperties( $event ) {
$event = $this->setAllGlobalEventProperties( $event );
return $event->getProperties();
}
public function trackPageview($event = '') {
if ($event) {
$event->setEventType('base.page_request');
$this->pageview_event = $event;
}
return $this->trackEvent($this->pageview_event);
}
public function trackSyndicationFeed( $feed_format = 'rss', $feed_subscription_id = '') {
$event = $this->makeEvent();
$event->setEventType('base.feed_request');
$event->set( 'feed_format', $feed_format );
$event->set( 'feed_subscription_id', $feed_subscription_id );
// track
return $this->trackEvent( $event );
}
public function trackAction($action_name, $action_group = '', $action_label = '', $numeric_value = 0) {
$event = $this->makeEvent();
$event->setEventType('track.action');
$event->set('action_group', $action_group);
$event->set('action_name', $action_name);
$event->set('action_label', $action_label);
$event->set('numeric_value', $numeric_value);
$event->set('site_id', $this->getSiteId());
return $this->trackEvent($event);
}
/**
* Creates a ecommerce Transaction event
*
* Creates a parent commerce.transaction event
*/
public function addTransaction(
$order_id,
$order_source = '',
$total = 0,
$tax = 0,
$shipping = 0,
$gateway = '',
$country = '',
$state = '',
$city = '',
$page_url = '',
$session_id = ''
) {
$this->commerce_event = $this->makeEvent();
$this->commerce_event->setEventType( 'ecommerce.transaction' );
$this->commerce_event->set( 'ct_order_id', $order_id );
$this->commerce_event->set( 'ct_order_source', $order_source );
$this->commerce_event->set( 'ct_total', $total );
$this->commerce_event->set( 'ct_tax', $tax );
$this->commerce_event->set( 'ct_shipping', $shipping );
$this->commerce_event->set( 'ct_gateway', $gateway );
$this->commerce_event->set( 'page_url', $page_url );
$this->commerce_event->set( 'ct_line_items', array() );
$this->commerce_event->set( 'country', $country );
$this->commerce_event->set( 'state', $state );
$this->commerce_event->set( 'city', $city );
if ( $session_id ) {
$this->commerce_event->set( 'original_session_id', $session_id );
}
}
/**
* Adds a line item to a commerce transaction
*
* Creates and a commerce.line_item event and adds it to the parent transaction event
*/
public function addTransactionLineItem($order_id, $sku = '', $product_name = '', $category = '', $unit_price = 0, $quantity = 0) {
if ( empty( $this->commerce_event ) ) {
$this->addTransaction('none set');
}
$li = array();
$li['li_order_id'] = $order_id ;
$li['li_sku'] = $sku ;
$li['li_product_name'] = $product_name ;
$li['li_category'] = $category ;
$li['li_unit_price'] = $unit_price ;
$li['li_quantity'] = $quantity ;
$items = $this->commerce_event->get( 'ct_line_items' );
$items[] = $li;
$this->commerce_event->set( 'ct_line_items', $items );
}
/**
* tracks a commerce events
*
* Tracks a parent transaction event by sending it to the event queue
*/
public function trackTransaction() {
if ( ! empty( $this->commerce_event ) ) {
if ( $this->commerce_event->get( 'original_session_id' ) ) {
$this->trackStatelessEvent( $this->commerce_event );
} else {
$this->trackEvent( $this->commerce_event );
}
$this->commerce_event = '';
}
}
public function createSiteId($value) {
return md5($value);
}
public function setCampaignNameKey( $key ) {
$campaign_params = $this->getSetting( 'campaign_params' );
$campaign_params[ 'campaign' ] = $key;
$this->setSetting('campaign_params', $campaign_params);
}
public function setCampaignMediumKey( $key ) {
$campaign_params = $this->getSetting( 'campaign_params' );
$campaign_params[ 'medium' ] = $key;
$this->setSetting('campaign_params', $campaign_params);
}
public function setCampaignSourceKey( $key ) {
$campaign_params = $this->getSetting( 'campaign_params' );
$campaign_params[ 'source' ] = $key;
$this->setSetting('campaign_params', $campaign_params);
}
public function setCampaignSearchTermsKey( $key ) {
$campaign_params = $this->getSetting( 'campaign_params' );
$campaign_params[ 'search_terms' ] = $key;
$this->setSetting('campaign_params', $campaign_params);
}
public function setCampaignAdKey( $key ) {
$campaign_params = $this->getSetting( 'campaign_params' );
$campaign_params[ 'ad' ] = $key;
$this->setSetting('campaign_params', $campaign_params);
}
public function setCampaignAdTypeKey( $key ) {
$campaign_params = $this->getSetting( 'campaign_params' );
$campaign_params[ 'ad_type' ] = $key;
$this->setSetting('campaign_params', $campaign_params);
}
public function setUserName( $value ) {
$this->setGlobalEventProperty( 'user_name', $value );
}
public function setUserEmail( $value ) {
$this->setGlobalEventProperty( 'user_email', $value );
}
function getCampaignProperties( $event ) {
$campaign_params = $this->getSetting( 'campaign_params' );
$campaign_properties = array();
$campaign_state = array();
foreach ( $campaign_params as $k => $param ) {
//look for property on the event
$property = $event->get( $param );
// look for property on the request scope.
if ( ! $property ) {
$property = $this->getRequestParam( $param );
}
if ( $property ) {
$campaign_properties[ $k ] = $property;
}
}
// backfill values for incomplete param combos
if (array_key_exists('ad_type', $campaign_properties) && !array_key_exists('ad', $campaign_properties)) {
$campaign_properties['ad'] = '(not set)';
}
if (array_key_exists('ad', $campaign_properties) && !array_key_exists('ad_type', $campaign_properties)) {
$campaign_properties['ad_type'] = '(not set)';
}
if (!empty($campaign_properties)) {
//$campaign_properties['ts'] = $event->get('timestamp');
}
sdk::debug('campaign properties: '. print_r($campaign_properties, true));
return $campaign_properties;
}
private function setCampaignSessionState( $properties ) {
$campaign_params = $this->getSetting( 'campaign_params' );
foreach ($campaign_params as $k => $v) {
if (array_key_exists( $k, $properties ) ) {
$this->state->set( 's', $k, $properties[$k] );
}
}
}
function directAttributionModel( &$campaign_properties ) {
// add new campaign info to existing campaign cookie.
if ( $campaign_properties ) {
// get prior campaing touches from c cookie
$campaign_state = $this->getCampaignState();
// add new campaign into state array
$campaign_state[] = (object) $campaign_properties;
// if more than x slice the first one off to make room
$count = count( $campaign_state );
$max = $this->getSetting( 'max_prior_campaigns' );
if ($count > $max ) {
array_shift( $campaign_state );
}
// reset state
$this->setCampaignCookie($campaign_state);
// set flag
$this->isTrafficAttributed = true;
// persist state to session store
$this->setCampaignSessionState( $campaign_properties );
}
}
function originalAttributionModel( &$campaign_properties ) {
$campaign_state = $this->getCampaignState();
// orignal touch was set previously. jus use that.
if (!empty($campaign_state)) {
// do nothing
// set the attributes from the first campaign touch
$campaign_properties = $campaign_state[0];
$this->isTrafficAttributed = true;
// no orginal touch, set one if it's a new campaign touch
} else {
if (!empty($campaign_properties)) {
// add timestamp
//$campaign_properties['ts'] = $event->get('timestamp');
sdk::debug('Setting original Campaign attrbution.');
$campaign_state[] = $campaign_properties;
// set cookie
$this->setCampaignCookie($campaign_state);
$this->isTrafficAttributed = true;
}
}
// persist state to session store
$this->setCampaignSessionState( $campaign_properties );
}
function getCampaignState() {
$campaign_state = $this->state->get( 'c', 'attribs' );
if ( ! $campaign_state ) {
$campaign_state = array();
}
return $campaign_state;
}
function setTrafficAttribution( &$event ) {
// if not then look for individual campaign params on the request.
// this happens when the client is php and the params are on the url
$campaign_properties = $this->getCampaignProperties( $event );
if ( $campaign_properties ) {
$campaign_properties['ts'] = $event->get('timestamp');
}
// choose attribution model.
$model = $this->getSetting( 'trafficAttributionMode' );
switch ( $model ) {
case 'direct':
sdk::debug( 'Applying "Direct" Traffic Attribution Model' );
$this->directAttributionModel( $campaign_properties );
break;
case 'original':
sdk::debug( 'Applying "Original" Traffic Attribution Model' );
$this->originalAttributionModel( $campaign_properties );
break;
default:
sdk::debug( 'Applying Default (Direct) Traffic Attribution Model' );
$this->directAttributionModel( $campaign_properties );
}
// if one of the attribution methods attributes the traffic them
// set attribution properties on the event object
if ( $this->isTrafficAttributed ) {
sdk::debug( 'Attributing Traffic to: %s', print_r($campaign_properties, true ) );
} else {
// infer the attribution from the referer
// if the request is the start of a new session
if ( $this->getGlobalEventProperty( 'is_new_session' ) ) {
sdk::debug( 'Inferring traffic attribution.' );
$this->inferTrafficAttribution();
}
}
// apply traffic attribution realted properties to events
// all properties should be set in the state store by this point.
$campaign_params = $this->getSetting('campaign_params');
foreach( $campaign_params as $k => $v ) {
$value = $this->state->get( 's', $k );
if ( $value ) {
$this->setGlobalEventProperty( $k, $value );
}
}
// set sesion referer
$session_referer = $this->state->get('s', 'referer');
if ( $session_referer ) {
$this->setGlobalEventProperty( 'session_referer', $session_referer );
}
// set campaign touches
$campaign_state = $this->state->get('c', 'attribs');
if ( $campaign_state ) {
$this->setGlobalEventProperty( 'attribs', json_encode( $campaign_state ));
}
}
private function inferTrafficAttribution() {
$ref = $this->getServerParam('HTTP_REFERER');
$medium = 'direct';
$source = '(none)';
$search_terms = '(none)';
$session_referer = '(none)';
if ( $ref ) {
$uri = $this->parse_url( $ref );
// check for external referer
$host = $this->getServerParam('HTTP_HOST');
if ( $host != $uri['host'] ) {
$medium = 'referral';
$source = $this->stripWwwFromDomain( $uri['host'] );
$engine = $this->isRefererSearchEngine( $uri );
$session_referer = $ref;
if ( $engine ) {
$medium = 'organic-search';
$search_terms = $engine['t'];
}
}
}
$this->state->set('s', 'referer', $session_referer);
$this->state->set('s', 'medium', $medium);
$this->state->set('s', 'source', $source);
$this->state->set('s', 'search_terms', $search_terms);
}
private function isRefererSearchEngine( $uri ) {
if ( !isset( $uri['host'] ) ) {
return null;
}
$host = $uri['host'];
$searchEngine = [];
foreach ( $this->organicSearchEngines as $engine ) {
$domain = $engine['d'];
if (strpos($host, $domain) === false) {
continue;
}
$query_param = $engine['q'];
$term = '';
if (isset($uri['query_params'][$query_param])) {
$term = $uri['query_params'][$query_param];
}
sdk::debug( 'Found search engine: %s with query param %s:, query term: %s', $domain, $query_param, $term);
$searchEngine = ['d' => $domain, 'q' => $query_param, 't' => $term];
break;
}
return $searchEngine;
}
function setCampaignCookie($values) {
// reset state
$this->state->set('c', 'attribs', $values);
}
// sets cookies domain
function setCookieDomain($domain) {
if (!empty($domain)) {
$this->setCookieDomainName($domain);
}
}
/**
* Set a custom variable
*
* @param slot int the identifying number for the custom variable. 1-5.
* @param name string the key of the custom variable.
* @param value string the value of the varible
* @param scope string the scope of the variable. can be page, session, or visitor
*/
public function setCustomVar( $slot, $name, $value, $scope = '' ) {
$cv_param_name = 'cv' . $slot;
$cv_param_value = $name . '=' . $value;
if ( strlen( $cv_param_value ) > 65 ) {
sdk::debug('Custom variable name + value is too large. Must be less than 64 characters.');
return;
}
switch ( $scope ) {
case 'session':
// store in session cookie
$this->state->set( 'b', $cv_param_name, $cv_param_value );
sdk::debug( 'just set custom var on session.' );
break;
case 'visitor':
// store in visitor cookie
$this->state->set( 'v', $cv_param_name, $cv_param_value );
// remove slot from session level cookie
$this->state->clear( 'b', $cv_param_name );
break;
}
$this->setGlobalEventProperty( $cv_param_name, $cv_param_value );
}
public function getCustomVar( $slot ) {
$cv_param_name = 'cv' . $slot;
$cv = '';
// check request/page level
$cv = $this->getGlobalEventProperty( $cv_param_name );
//check session store
if ( ! $cv ) {
$cv = $this->state->get( 'b', $cv_param_name );
}
// check visitor store
if ( ! $cv ) {
$cv = $this->state->get( 'v', $cv_param_name );
}
return $cv;
}
public function deleteCustomVar( $slot ) {
$cv_param_name = 'cv' . $slot;
//clear session level
$this->state->clear( 'b', $cv_param_name );
//clear visitor level
$this->state->clear( 'v', $cv_param_name );
// clear page level
$this->deleteGlobalEventProperty( $cv_param_name );
sdk::debug("Deleting custom variable named $cv_param_name in slot $slot.");
}
private function resetSessionState() {
$last_req = $this->state->get( 's', 'last_req' );
$this->state->clear( 's' );
$this->state->set( 's', 'last_req', $last_req);
}
public function addOrganicSearchEngine( $domain, $query_param, $prepend = '' ) {
$engine = array('d' => $domain, 'q' => $query_param);
if ( $prepend) {
array_unshift($this->organicSearchEngines, $engine );
} else {
$this->organicSearchEngines[] = $engine;
}
}
private function registerStateStore( $name, $expiration, $length = '', $format = '', $type = 'cookie', $cdh_required = '' ) {
return $this->state->registerStore( $name, $expiration, $length, $format, $type, $cdh_required );
}
/**
* sets and checks the cookie domain setting
*
* @param unknown_type $domain
*/
private function setCookieDomainName ($domain = '') {
$explicit = false;