1
|
|
|
<?php |
2
|
|
|
namespace Flynt\Features\GoogleAnalytics; |
3
|
|
|
|
4
|
|
|
use Timber\Timber; |
5
|
|
|
|
6
|
|
|
class GoogleAnalytics |
7
|
|
|
{ |
8
|
|
|
private $gaId; |
9
|
|
|
private $anonymizeIp; |
10
|
|
|
private $skippedUserRoles; |
11
|
|
|
private $skippedIps; |
12
|
|
|
|
13
|
|
|
public function __construct($options) |
14
|
|
|
{ |
15
|
|
|
$this->gaId = $options['gaId']; |
16
|
|
|
$this->anonymizeIp = $options['anonymizeIp']; |
17
|
|
|
$this->skippedUserRoles = $options['skippedUserRoles']; |
18
|
|
|
$this->skippedIps = $options['skippedIps']; |
19
|
|
|
|
20
|
|
|
if ($this->skippedIps) { |
21
|
|
|
$skippedIps = explode(',', $this->skippedIps); |
22
|
|
|
$this->skippedIps = array_map('trim', $skippedIps); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
if ($this->gaId && $this->isValidId($this->gaId)) { |
26
|
|
|
add_action('wp_footer', [$this, 'addScript'], 20, 1); |
27
|
|
|
} else if ($this->gaId != 1 && !isset($_POST['acf'])) { |
28
|
|
|
trigger_error("Invalid Google Analytics Id: {$this->gaId}", E_USER_WARNING); |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function addScript() |
33
|
|
|
{ |
34
|
|
|
$user = wp_get_current_user(); |
35
|
|
|
$trackingEnabled = !( |
36
|
|
|
$this->gaId === 'debug' // debug mode enabled |
37
|
|
|
|| $this->skippedUserRoles && array_intersect($this->skippedUserRoles, $user->roles) // current user role should be skipped |
38
|
|
|
|| is_array($this->skippedIps) && in_array($_SERVER['REMOTE_ADDR'], $this->skippedIps) // current ip should be skipped |
39
|
|
|
); |
40
|
|
|
Timber::render('script.twig', [ |
41
|
|
|
'gaId' => $this->gaId, |
42
|
|
|
'trackingEnabled' => $trackingEnabled, |
43
|
|
|
'anonymizeIp' => $this->anonymizeIp |
44
|
|
|
]); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function isValidId($gaId) |
48
|
|
|
{ |
49
|
|
|
if ($gaId === 'debug') { |
50
|
|
|
return true; |
51
|
|
|
} else { |
52
|
|
|
return preg_match('/^ua-\d{4,10}-\d{1,4}$/i', (string) $gaId); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|