1
|
|
|
<?php |
2
|
|
|
namespace Flynt\Features\GoogleAnalytics; |
3
|
|
|
|
4
|
|
|
class GoogleAnalytics |
5
|
|
|
{ |
6
|
|
|
public function __construct($options) |
7
|
|
|
{ |
8
|
|
|
$this->gaId = $options['gaId']; |
|
|
|
|
9
|
|
|
$this->anonymizeIp = $options['anonymizeIp']; |
|
|
|
|
10
|
|
|
$this->skippedUserRoles = $options['skippedUserRoles']; |
|
|
|
|
11
|
|
|
$this->skippedIps = $options['skippedIps']; |
|
|
|
|
12
|
|
|
|
13
|
|
|
if ($this->skippedIps) { |
14
|
|
|
$skippedIps = explode(',', $this->skippedIps); |
15
|
|
|
$this->skippedIps = array_map('trim', $skippedIps); |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
if ($this->gaId && $this->isValidId($this->gaId)) { |
19
|
|
|
add_action('wp_footer', [$this, 'addScript'], 20, 1); |
20
|
|
|
} else if ($this->gaId != 1 && !isset($_POST['acf'])) { |
21
|
|
|
trigger_error('Invalid Google Analytics Id: ' . $this->gaId, E_USER_WARNING); |
22
|
|
|
} |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function addScript() |
26
|
|
|
{ |
27
|
|
|
?> |
28
|
|
|
<script> |
29
|
|
|
<?php |
30
|
|
|
$user = wp_get_current_user(); |
31
|
|
|
$debugMode = $this->gaId === 'debug'; |
32
|
|
|
$isSkippedUser = $this->skippedUserRoles && array_intersect($this->skippedUserRoles, $user->roles); |
33
|
|
|
$isSkippedIp = is_array($this->skippedIps) && in_array($_SERVER['REMOTE_ADDR'], $this->skippedIps); |
34
|
|
|
if ($debugMode || $isSkippedUser || $isSkippedIp) : ?> |
35
|
|
|
function ga() { |
36
|
|
|
console.log('GoogleAnalytics: ' + [].slice.call(arguments)); |
37
|
|
|
} |
38
|
|
|
<?php |
39
|
|
|
else : ?> |
40
|
|
|
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ |
41
|
|
|
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), |
42
|
|
|
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) |
43
|
|
|
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); |
44
|
|
|
<?php |
45
|
|
|
endif; ?> |
46
|
|
|
ga('create','<?php echo $this->gaId; ?>','auto');ga('send','pageview'); |
47
|
|
|
<?php if ($this->anonymizeIp == 1) : ?> |
48
|
|
|
ga('set', 'anonymizeIp', true); |
49
|
|
|
<?php endif; ?> |
50
|
|
|
</script> |
51
|
|
|
<?php |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function isValidId($gaId) |
55
|
|
|
{ |
56
|
|
|
if ($gaId === 'debug') { |
57
|
|
|
return true; |
58
|
|
|
} else { |
59
|
|
|
return preg_match('/^ua-\d{4,10}-\d{1,4}$/i', (string) $gaId); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: