-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgoogle_tag.module
334 lines (300 loc) · 9.6 KB
/
google_tag.module
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
<?php
/**
* @file
* Provides primary Drupal hook implementations.
*
* Adds a JavaScript snippet to selected page responses to trigger analytics and
* other tracking items configured using the Google Tag Manager.
*
* @author Jim Berry ("solotandem", http://drupal.org/user/240748)
*/
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Default for matching all items except listed.
*/
const GOOGLE_TAG_EXCLUDE_LISTED = 'exclude listed';
/**
* Default for matching only listed items.
*/
const GOOGLE_TAG_INCLUDE_LISTED = 'include listed';
/**
* Directory to output scripts.
*/
const GOOGLE_TAG_DIR = 'public://google_tag/js';
/**
* Implements hook_help().
*/
function google_tag_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.google_tag':
case 'google_tag.settings_form':
return t('<a href=":url">Google Tag Manager</a> is a free service (registration required) to manage the insertion of tags for capturing website analytics.', [':url' => 'https://tagmanager.google.com/']);
}
}
/**
* Implements hook_page_attachments().
*/
function google_tag_page_attachments(&$attachments) {
if (!google_tag_insert_snippet()) {
return;
}
$config = \Drupal::config('google_tag.settings');
$include_script_as_file = $config->get('include_file');
// Add data_layer and script snippets to head (no longer by default).
$weight = 9;
if ($include_script_as_file) {
foreach (['data_layer', 'script'] as $type) {
// @todo Will it matter if file is empty?
// @todo Check config for the whitelist and blacklist classes before adding.
$attachments['#attached']['html_head'][] = _google_tag_file_tag($type, $weight++);
}
}
else {
foreach (['data_layer', 'script'] as $type) {
// @see drupal_get_js() in 7.x core.
// For inline JavaScript to validate as XHTML, all JavaScript containing
// XHTML needs to be wrapped in CDATA.
$attachment = _google_tag_inline_tag($type, $weight++);
if (!empty($attachment)) {
$attachments['#attached']['html_head'][] = $attachment;
}
}
}
}
/**
* Returns tag array for the snippet type.
*
* @param string $type
* The snippet type.
* @param int $weight
* The weight of the item.
*
* @return array
* The tag array.
*/
function _google_tag_file_tag($type, $weight) {
$uri = _google_tag_get_js_dir() . "/google_tag.$type.js";
$url = file_url_transform_relative(file_create_url($uri));
$query_string = \Drupal::state()->get('system.css_js_query_string') ?: '0';
$attachment = [
[
'#type' => 'html_tag',
'#tag' => 'script',
'#attributes' => ['src' => $url . '?' . $query_string],
'#weight' => $weight,
],
"google_tag_{$type}_tag",
];
return $attachment;
}
/**
* Returns tag array for the snippet type.
*
* @param string $type
* The snippet type.
* @param int $weight
* The weight of the item.
*
* @return array
* The tag array.
*/
function _google_tag_inline_tag($type, $weight) {
$uri = _google_tag_get_js_dir() . "/google_tag.$type.js";
$url = \Drupal::service('file_system')->realpath($uri);
$contents = @file_get_contents($url);
$attachment = $contents ? [
[
'#type' => 'html_tag',
'#tag' => 'script',
'#value' => $contents,
'#weight' => $weight,
],
"google_tag_{$type}_tag",
] : [];
return $attachment;
}
/**
* Implements hook_page_top().
*/
function google_tag_page_top(&$page) {
if (!google_tag_insert_snippet()) {
return;
}
// Add noscript snippet to page_top region.
$uri = _google_tag_get_js_dir() . '/google_tag.noscript.js';
$url = \Drupal::service('file_system')->realpath($uri);
$contents = @file_get_contents($url);
// Note: depending on the theme, this may not place the snippet immediately
// after the body tag but should be close and it can be altered.
// @see https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/group/theme_render/8.2.x
// The markup is passed through \Drupal\Component\Utility\Xss::filterAdmin()
// which strips known vectors while allowing a permissive list of HTML tags
// that are not XSS vectors. (e.g., <script> and <style> are not allowed.)
// @todo Core is removing the 'style' attribute from the noscript snippet.
if ($contents) {
$page['google_tag_noscript_tag'] = [
'#markup' => $contents,
'#allowed_tags' => ['noscript', 'iframe'],
'#weight' => -10,
];
}
}
/**
* Determines whether to insert the snippet on the response.
*
* @return bool
* TRUE if the conditions are met; FALSE otherwise.
*/
function google_tag_insert_snippet() {
static $satisfied;
if (!isset($satisfied)) {
$config = \Drupal::config('google_tag.settings');
$id = $config->get('container_id');
if (empty($id)) {
// No container ID.
return FALSE;
}
$satisfied = TRUE;
if (!_google_tag_status_check() || !_google_tag_path_check() || !_google_tag_role_check()) {
// Omit snippet if any condition is not met.
$satisfied = FALSE;
}
// Allow other modules to alter the insertion criteria.
\Drupal::moduleHandler()->alter('google_tag_insert', $satisfied);
}
return $satisfied;
}
/**
* Determines whether to insert the snippet based on status code settings.
*
* @return bool
* TRUE if the status conditions are met; FALSE otherwise.
*/
function _google_tag_status_check() {
static $satisfied;
if (!isset($satisfied)) {
$config = \Drupal::config('google_tag.settings');
$toggle = $config->get('status_toggle');
$statuses = $config->get('status_list');
if (empty($statuses)) {
$satisfied = ($toggle == GOOGLE_TAG_EXCLUDE_LISTED);
}
else {
// Get the HTTP response status.
$request = \Drupal::request();
$status = '200';
if ($exception = $request->attributes->get('exception')) {
$status = $exception->getStatusCode();
}
$satisfied = strpos($statuses, (string) $status) !== FALSE;
$satisfied = ($toggle == GOOGLE_TAG_EXCLUDE_LISTED) ? !$satisfied : $satisfied;
}
}
return $satisfied;
}
/**
* Determines whether to insert the snippet based on the path settings.
*
* @return bool
* TRUE if the path conditions are met; FALSE otherwise.
*/
function _google_tag_path_check() {
static $satisfied;
if (!isset($satisfied)) {
$config = \Drupal::config('google_tag.settings');
$toggle = $config->get('path_toggle');
$paths = Unicode::strtolower($config->get('path_list'));
if (empty($paths)) {
$satisfied = ($toggle == GOOGLE_TAG_EXCLUDE_LISTED);
}
else {
$request = \Drupal::request();
$current_path = \Drupal::service('path.current');
$alias_manager = \Drupal::service('path.alias_manager');
$path_matcher = \Drupal::service('path.matcher');
// @todo Are not some paths case sensitive???
// Compare the lowercase path alias (if any) and internal path.
$path = rtrim($current_path->getPath($request), '/');
$path_alias = Unicode::strtolower($alias_manager->getAliasByPath($path));
$satisfied = $path_matcher->matchPath($path_alias, $paths) || (($path != $path_alias) && $path_matcher->matchPath($path, $paths));
$satisfied = ($toggle == GOOGLE_TAG_EXCLUDE_LISTED) ? !$satisfied : $satisfied;
}
}
return $satisfied;
}
/**
* Determines whether to insert the snippet based on the user role settings.
*
* @return bool
* TRUE if the role conditions are met; FALSE otherwise.
*/
function _google_tag_role_check() {
static $satisfied;
if (!isset($satisfied)) {
$config = \Drupal::config('google_tag.settings');
$toggle = $config->get('role_toggle');
$roles = $config->get('role_list');
$roles = array_filter($roles);
if (empty($roles)) {
$satisfied = ($toggle == GOOGLE_TAG_EXCLUDE_LISTED);
}
else {
$satisfied = FALSE;
// Check user roles against listed roles.
$satisfied = (bool) array_intersect($roles, \Drupal::currentUser()->getRoles());
$satisfied = ($toggle == GOOGLE_TAG_EXCLUDE_LISTED) ? !$satisfied : $satisfied;
}
}
return $satisfied;
}
/**
* Saves JS snippet files based on current settings.
*
* @return bool
* TRUE if at least some of the files were saved.
* This doesn't mean they were all saved.
*/
function google_tag_save_snippets() {
// Save the altered snippets after hook_google_tag_snippets_alter().
module_load_include('inc', 'google_tag', 'includes/snippet');
// If there is more than one snippet some may be saved and some may fail.
$saved = FALSE; $unsaved = FALSE;
$dir = _google_tag_get_js_dir();
$snippets = google_tag_snippets();
foreach ($snippets as $type => $snippet) {
if ($dir_exists = file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {
$path = file_unmanaged_save_data($snippet, "{$dir}/google_tag.{$type}.js", FILE_EXISTS_REPLACE);
}
if ($dir_exists === TRUE && $path !== FALSE) {
$saved = TRUE;
}
else {
$unsaved = TRUE;
}
}
if ($unsaved) {
drupal_set_message(t('An error occurred saving one or more snippet files. Please try again or contact the site administrator if it persists.'));
}
if ($saved) {
\Drupal::service('asset.js.collection_optimizer')->deleteAll();
_drupal_flush_css_js();
return TRUE;
}
return FALSE;
}
/**
* Implements hook_rebuild().
*/
function google_tag_rebuild() {
google_tag_save_snippets();
}
/**
* Get's the public directory for storing google_tag files
*/
function _google_tag_get_js_dir() {
$dir = GOOGLE_TAG_DIR;
// Allow other modules to alter the directory.
\Drupal::moduleHandler()->alter('google_tag_dir', $dir);
return $dir;
}