forked from Woopra/woopra-php-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
woopra_tracker.php
496 lines (433 loc) · 14.2 KB
/
woopra_tracker.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
<?php
/**
* Woopra PHP SDK
* This class represents the PHP equivalent of the JavaScript Woopra Object.
* @version 1.0
* @author Antoine Chkaiban
*/
class WoopraTracker {
private static $SDK_ID = "php";
/**
* Default configuration.
* KEYS:
*
* domain (string) - Website hostname as added to Woopra
* cookie_name (string) - Name of the cookie used to identify the visitor
* cookie_domain (string) - Domain scope of the Woopra cookie
* cookie_path (string) - Directory scope of the Woopra cookie
* ping (boolean) - Ping woopra servers to ensure that the visitor is still on the webpage?
* ping_interval (integer) - Time interval in milliseconds between each ping
* idle_timeout (integer) - Idle time after which the user is considered offline
* download_tracking (boolean) - Track downloads on the web page
* outgoing_tracking (boolean) - Track external links clicks on the web page
* download_pause (integer) - Time in millisecond to pause the browser to ensure that the event is tracked when visitor clicks on a download url
* outgoing_pause (integer) - Time in millisecond to pause the browser to ensure that the event is tracked when visitor clicks on an outgoing url
* ignore_query_url (boolean) - Ignores the query part of the url when the standard pageviews tracking function track()
* hide_campaign (boolean) - Enabling this option will remove campaign properties from the URL when they’re captured (using HTML5 pushState)
* ip_address (string) - the IP address of the user viewing the page. If back-end processing, always set this manually.
* cookie_value (string) - the value of $_COOKIE["wooTracker"] if it has been set.
* @var array
*/
private static $default_config = array(
"domain" => "",
"cookie_name" => "wooTracker",
"cookie_domain" => "",
"cookie_path" => "/",
"ping" => true,
"ping_interval" => 12000,
"idle_timeout" => 300000,
"download_tracking" => true,
"outgoing_tracking" => true,
"download_pause" => 200,
"outgoing_pause" => 400,
"ignore_query_url" => true,
"hide_campaign" => false,
"ip_address" => "",
"cookie_value" => "",
"app" => "",
"woopra_url" => "https://www.woopra.com/track/",
'connect_timeout' => 2,
'timeout' => 4,
);
/**
* Custom configuration stack.
* If the user has set up custom configuration, store it in this array. It will be sent when the tracker is ready.
* @var array
*/
private $custom_config;
/**
* Current configuration
* Default configuration array, updated by Manual configurations.
* @var array
*/
private $current_config;
/**
* User array.
* If the user has been identified, store his information in this array
* KEYS:
* email (string) – Which displays the visitor’s email address and it will be used as a unique identifier instead of cookies.
* name (string) – Which displays the visitor’s full name
* company (string) – Which displays the company name or account of your customer
* avatar (string) – Which is a URL link to a visitor avatar
* other (string) - You can define any attribute you like and have that detail passed from within the visitor live stream data when viewing Woopra
* @var array
*/
private $user;
/**
* Has the latest information on the user been sent to woopra?
* @var boolean
*/
private $user_up_to_date;
/**
* Events array stack
* Each item of the stack is either:
* - an empty array (if pv event)
* - an array(2) (if custom event)
* O (string) - the name of the event
* 1 (array) - properties associated with that action
* @var array
*/
private $events;
/**
* Is JavaScript Tracker Ready?
* @var boolean
*/
private $tracker_ready;
private $httpHost;
private $httpUserAgent;
private $remoteAddress;
private $requestUri;
/**
* Woopra Analytics
* @param none
* @return none
* @constructor
*/
function __construct($config_params = null) {
$this->httpHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$this->httpUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$this->remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$this->requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
//Tracker is not ready yet
$this->tracker_ready = false;
//Current configuration is Default
$this->current_config = WoopraTracker::$default_config;
//Set the default IP
$this->current_config["ip_address"] = $this->get_client_ip();
//Set the domain name and the cookie_domain
$this->current_config["domain"] = $this->httpHost;
$this->current_config["cookie_domain"] = $this->httpHost;
//configure app ID
$this->current_config["app"] = WoopraTracker::$SDK_ID;
$this->custom_config = array("app" => WoopraTracker::$SDK_ID);
//If configuration array was passed, configure Woopra
if (isset($config_params)) {
$this->config($config_params);
}
//Get cookie or generate a random one
$this->current_config["cookie_value"] = isset($_COOKIE[$this->current_config["cookie_name"]]) ? $_COOKIE[$this->current_config["cookie_name"]] : WoopraTracker::RandomString();
//We don't have any info on the user yet, so he is up to date by default.
$this->user_up_to_date = true;
}
/**
* Echoes JS code to configure the tracker
* @return none
*/
private function print_javascript_configuration() {
if (isset($this->custom_config)) {
?>
woopra.config(<?php echo json_encode($this->custom_config); ?>);
<?php
//Configuration has been printed, reset the custom_configuration as an empty array
unset( $this->custom_config );
}
}
/**
* Echoes JS code to identify the user with the tracker
* @return none
*/
private function print_javascript_identification() {
if ( ! $this->user_up_to_date ) {
?>
woopra.identify(<?php echo json_encode($this->user); ?>);
<?php
$this->user_up_to_date = true;
}
}
/**
* Echoes JS code to track custom events
* @param none
* @return none
*/
private function print_javascript_events() {
if (isset($this->events)) {
foreach ($this->events as $event) {
if(empty($event)) {
?>
woopra.track();
<?php
} else {
?>
woopra.track(<?php echo json_encode($event[0]); ?>, <?php echo json_encode($event[1]); ?>);
<?php
}
}
//Events have been printed, reset the events as an empty array
unset( $this->events );
}
}
/**
* Random Cookie generator in case the user doesn't have a cookie yet. Better to use a hash of the email.
* @param none
* @return string
*/
private static function RandomString() {
$characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$randstring = "";
for ($i = 0; $i < 12; $i++) {
$randstring .= $characters[rand(0, strlen($characters)-1)];
}
return $randstring;
}
/**
* Prepares the http request and sends it.
* @param boolean Is this a tracking event or are we just identifying a user?
* @param (optional) array
* @return none
*/
private function woopra_http_request($is_tracking, $event = null) {
//Config params
$config_params = "?host=" . urlencode($this->current_config["domain"]);
$config_params .= "&cookie=" . urlencode($this->current_config["cookie_value"]);
$config_params .= "&ip=" . urlencode($this->current_config["ip_address"]);
$config_params .= "&timeout=" . urlencode($this->current_config["idle_timeout"]);
//User params
$user_params = "";
if ( isset($this->user) ) {
foreach($this->user as $option => $value) {
$user_params .= "&cv_" . urlencode($option) . "=" . urlencode($value);
}
}
//Just identifying
if ( ! $is_tracking ) {
$url = $this->current_config['woopra_url'] . "identify/" . $config_params . $user_params . "&ce_app=" . $this->current_config["app"];
//Tracking
} else {
//Event params
$event_params = "";
if ( $event != null ) {
$event_params .= "&ce_name=" . urlencode($event[0]);
foreach($event[1] as $option => $value) {
$event_params .= "&ce_" . urlencode($option) . "=" . urlencode($value);
}
} else {
$event_params .= "&ce_name=pv&ce_url=" . $this->httpHost . $this->requestUri;
}
$url = $this->current_config['woopra_url'] . "ce/" . $config_params . $user_params . $event_params . "&ce_app=" . $this->current_config["app"];
}
//Send the request
if (function_exists('curl_version')) {
$this->get_data($url);
} else {
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"User-Agent: ".$this->httpUserAgent
)
);
$context = stream_context_create($opts);
file_get_contents( $url, false, $context);
}
}
/**
* Echoes Woopra Widget JS code, and checks if there is any stored Configuration, Identification, or Custom events awaiting process and echoes it too.
* @param none
* @return Woopra object
*/
public function js_code() {
?>
<!-- Woopra code starts here -->
<script>
(function(){
var t,i,e,n=window,o=document,a=arguments,s="script",r=["config","track","identify","visit","push","call"],c=function(){var t,i=this;for(i._e=[],t=0;r.length>t;t++)(function(t){i[t]=function(){return i._e.push([t].concat(Array.prototype.slice.call(arguments,0))),i}})(r[t])};for(n._w=n._w||{},t=0;a.length>t;t++)n._w[a[t]]=n[a[t]]=n[a[t]]||new c;i=o.createElement(s),i.async=1,i.src="//static.woopra.com/js/w.js",e=o.getElementsByTagName(s)[0],e.parentNode.insertBefore(i,e)
})("woopra");
<?php
//The Tracker is now ready
$this->tracker_ready = true;
//Print Custom JavaScript Configuration Code
$this->print_javascript_configuration();
//Print JavaScript Identification Code
$this->print_javascript_identification();
//Print stored events
$this->print_javascript_events();
?>
</script>
<!-- Woopra code ends here -->
<?php
return $this;
}
/**
* Configures Woopra
* @param array
* @return Woopra object
*/
public function config($args) {
if (! isset($this->custom_config)) {
$this->custom_config = array();
}
foreach( $args as $option => $value) {
if ( array_key_exists($option, WoopraTracker::$default_config) ) {
if ( gettype($value) == gettype( WoopraTracker::$default_config[$option] ) ) {
if ($option != "ip_address" && $option != "cookie_value") {
$this->custom_config[$option] = $value;
}
$this->current_config[$option] = $value;
//If the user is customizing the name of the cookie, check again if the user already has one.
if ($option == "cookie_name") {
$this->current_config["cookie_value"] = isset($_COOKIE[$current_config["cookie_name"]]) ? $_COOKIE[$current_config["cookie_name"]] : $this->current_config["cookie_value"];
}
}
else {
trigger_error("Wrong value type in configuration array for parameter ".$option.". Recieved ".gettype($value).", expected ".gettype( WoopraTracker::$default_config[$option] ).".");
}
}
else {
trigger_error("Unexpected parameter in configuration array: ".$option.".");
}
}
return $this;
}
/**
* Identifies User
* @param array
* @return Woopra object
*/
public function identify($identified_user, $override = false) {
$this->user = $identified_user;
$this->user_up_to_date = false;
if (isset($identified_user["email"]) && ($override || !isset($_COOKIE[$this->current_config["cookie_name"]]))) {
$this->current_config["cookie_value"] = crc32($identified_user["email"]);
}
return $this;
}
/**
* Tracks Custom Event. If no parameters are specified, will simply track pageview.
* @param string
* @param array
* @param (optional) boolean
* @return Woopra object
*/
public function track($event = null, $args = array(), $back_end_processing = false) {
if ( $back_end_processing ) {
$http_event = null;
if ( $event != null ) {
$http_event = array($event, $args);
}
$this->woopra_http_request(true, $http_event);
return $this;
}
if ($event == null) {
if ( $this->tracker_ready ) {
?>
<script>
<?php
$this->print_javascript_configuration();
$this->print_javascript_identification();
?>
woopra.track();
</script>
<?php
} else {
if (! isset($this->events) ) {
$this->events = array();
}
array_push( $this->events, array());
}
return $this;
}
if (! isset($this->events) ) {
$this->events = array();
}
array_push( $this->events, array($event, $args) );
if ( $this->tracker_ready ) {
?>
<script>
<?php
$this->print_javascript_configuration();
$this->print_javascript_identification();
$this->print_javascript_events();
?>
</script>
<?php
}
return $this;
}
/**
* Pushes unprocessed actions
* @param none
* @param (optional) boolean
* @return none
*/
public function push($back_end_processing = false) {
if ( $back_end_processing ) {
$this->woopra_http_request(false);
$this->user_up_to_date = true;
} elseif($this->tracker_ready) {
?>
<script>
<?php
$this->print_javascript_configuration();
$this->print_javascript_identification();
?>
woopra.push();
</script>
<?php
}
}
/**
* Sets the Woopra cookie from the back-end. Call this function before any headers are sent (HTTP restrictions).
* @param none
* @return none
*/
public function set_woopra_cookie() {
setcookie( $this->current_config["cookie_name"], $this->current_config["cookie_value"], time()+(60*60*24*365*2), $this->current_config["cookie_path"], $this->current_config["cookie_domain"] );
}
/**
* Retrieves the user's IP address
* @param none
* @return String
*/
private function get_client_ip() {
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$ips = explode(",", $_SERVER["HTTP_X_FORWARDED_FOR"]);
return trim($ips[0]);
} else {
return $this->remoteAddr;
}
}
/**
* Gets the data from a URL using CURL
* @param String
* @return String
*/
private function get_data($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->current_config['connect_timeout']);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->current_config['timeout']);
curl_setopt($ch, CURLOPT_USERAGENT, $this->httpUserAgent);
$response = curl_exec($ch);
if (! $response) {
curl_close($ch);
throw new Exception('Could not connect. URL:' . $url, 0);
}
$responseInfo = curl_getinfo($ch);
if ($responseInfo['http_code'] < 200 || $responseInfo['http_code'] >= 300) {
curl_close($ch);
throw new Exception($response, $responseInfo['http_code']);
}
curl_close($ch);
return true;
}
}