-
Notifications
You must be signed in to change notification settings - Fork 293
/
Analytics.php
1639 lines (1472 loc) · 54 KB
/
Analytics.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
/**
* Class Google\Site_Kit\Modules\Analytics
*
* @package Google\Site_Kit
* @copyright 2019 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://sitekit.withgoogle.com
*/
namespace Google\Site_Kit\Modules;
use Google\Site_Kit\Core\Modules\Module;
use Google\Site_Kit\Core\Modules\Module_Settings;
use Google\Site_Kit\Core\Modules\Module_With_Admin_Bar;
use Google\Site_Kit\Core\Modules\Module_With_Debug_Fields;
use Google\Site_Kit\Core\Modules\Module_With_Screen;
use Google\Site_Kit\Core\Modules\Module_With_Screen_Trait;
use Google\Site_Kit\Core\Modules\Module_With_Scopes;
use Google\Site_Kit\Core\Modules\Module_With_Scopes_Trait;
use Google\Site_Kit\Core\Modules\Module_With_Settings;
use Google\Site_Kit\Core\Modules\Module_With_Settings_Trait;
use Google\Site_Kit\Core\Modules\Module_With_Assets;
use Google\Site_Kit\Core\Modules\Module_With_Assets_Trait;
use Google\Site_Kit\Core\REST_API\Exception\Invalid_Datapoint_Exception;
use Google\Site_Kit\Core\Authentication\Google_Proxy;
use Google\Site_Kit\Core\Assets\Asset;
use Google\Site_Kit\Core\Assets\Script;
use Google\Site_Kit\Core\Authentication\Clients\Google_Site_Kit_Client;
use Google\Site_Kit\Core\Permissions\Permissions;
use Google\Site_Kit\Core\REST_API\Data_Request;
use Google\Site_Kit\Core\Util\Debug_Data;
use Google\Site_Kit\Modules\Analytics\Google_Service_AnalyticsProvisioning;
use Google\Site_Kit\Modules\Analytics\Settings;
use Google\Site_Kit\Modules\Analytics\Proxy_AccountTicket;
use Google\Site_Kit\Modules\Analytics\Proxy_Provisioning;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_DateRangeValues;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_GetReportsResponse;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_Report;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_ReportData;
use Google\Site_Kit_Dependencies\Google_Service_Analytics;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_GetReportsRequest;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_ReportRequest;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_Dimension;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_DimensionFilter;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_DimensionFilterClause;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_DateRange;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_Metric;
use Google\Site_Kit_Dependencies\Google_Service_AnalyticsReporting_OrderBy;
use Google\Site_Kit_Dependencies\Google_Service_Analytics_Accounts;
use Google\Site_Kit_Dependencies\Google_Service_Analytics_Account;
use Google\Site_Kit_Dependencies\Google_Service_Analytics_Webproperties;
use Google\Site_Kit_Dependencies\Google_Service_Analytics_Webproperty;
use Google\Site_Kit_Dependencies\Google_Service_Analytics_Profile;
use Google\Site_Kit_Dependencies\Google_Service_Exception;
use Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface;
use WP_Error;
use Exception;
/**
* Class representing the Analytics module.
*
* @since 1.0.0
* @access private
* @ignore
*/
final class Analytics extends Module
implements Module_With_Screen, Module_With_Scopes, Module_With_Settings, Module_With_Assets, Module_With_Admin_Bar, Module_With_Debug_Fields {
use Module_With_Screen_Trait, Module_With_Scopes_Trait, Module_With_Settings_Trait, Module_With_Assets_Trait;
const PROVISION_ACCOUNT_TICKET_ID = 'googlesitekit_analytics_provision_account_ticket_id';
/**
* Registers functionality through WordPress hooks.
*
* @since 1.0.0
*/
public function register() {
$this->register_scopes_hook();
$this->register_screen_hook();
/**
* This filter only exists to be unhooked by the AdSense module if active.
*
* @see \Google\Site_Kit\Modules\Analytics\Settings::register
*/
add_filter( 'googlesitekit_analytics_adsense_linked', '__return_false' );
add_action( // For non-AMP.
'wp_enqueue_scripts',
function() {
$this->enqueue_gtag_js();
}
);
$print_amp_gtag = function() {
// This hook is only available in AMP plugin version >=1.3, so if it
// has already completed, do nothing.
if ( ! doing_action( 'amp_print_analytics' ) && did_action( 'amp_print_analytics' ) ) {
return;
}
$this->print_amp_gtag();
};
// Which actions are run depends on the version of the AMP Plugin
// (https://amp-wp.org/) available. Version >=1.3 exposes a
// new, `amp_print_analytics` action.
// For all AMP modes, AMP plugin version >=1.3.
add_action( 'amp_print_analytics', $print_amp_gtag );
// For AMP Standard and Transitional, AMP plugin version <1.3.
add_action( 'wp_footer', $print_amp_gtag, 20 );
// For AMP Reader, AMP plugin version <1.3.
add_action( 'amp_post_template_footer', $print_amp_gtag, 20 );
// For Web Stories plugin.
add_action( 'web_stories_print_analytics', $print_amp_gtag );
add_filter( // Load amp-analytics component for AMP Reader.
'amp_post_template_data',
function( $data ) {
return $this->amp_data_load_analytics_component( $data );
}
);
add_action(
'wp_head',
function () {
if ( $this->is_tracking_disabled() ) {
$this->print_tracking_opt_out();
}
},
0
);
add_action(
'admin_init',
function() {
$this->handle_provisioning_callback();
}
);
}
/**
* Checks whether or not tracking snippet should be contextually disabled for this request.
*
* @since 1.1.0
*
* @return bool
*/
protected function is_tracking_disabled() {
$exclusions = $this->get_data( 'tracking-disabled' );
$disabled = in_array( 'loggedinUsers', $exclusions, true ) && is_user_logged_in();
/**
* Filters whether or not the Analytics tracking snippet is output for the current request.
*
* @since 1.1.0
*
* @param $disabled bool Whether to disable tracking or not.
*/
return (bool) apply_filters( 'googlesitekit_analytics_tracking_disabled', $disabled );
}
/**
* Gets required Google OAuth scopes for the module.
*
* @since 1.0.0
*
* @return array List of Google OAuth scopes.
*/
public function get_scopes() {
return array(
'https://www.googleapis.com/auth/analytics.readonly',
);
}
/**
* Returns all module information data for passing it to JavaScript.
*
* @since 1.0.0
*
* @return array Module information data.
*/
public function prepare_info_for_js() {
$info = parent::prepare_info_for_js();
$info['provides'] = array(
__( 'Audience overview', 'google-site-kit' ),
__( 'Top pages', 'google-site-kit' ),
__( 'Top acquisition channels', 'google-site-kit' ),
);
return $info;
}
/**
* Checks whether the module is connected.
*
* A module being connected means that all steps required as part of its activation are completed.
*
* @since 1.0.0
*
* @return bool True if module is connected, false otherwise.
*/
public function is_connected() {
$connection = $this->get_data( 'connection' );
if ( is_wp_error( $connection ) ) {
return false;
}
foreach ( (array) $connection as $value ) {
if ( empty( $value ) ) {
return false;
}
}
return parent::is_connected();
}
/**
* Cleans up when the module is deactivated.
*
* @since 1.0.0
*/
public function on_deactivation() {
$this->get_settings()->delete();
$this->options->delete( 'googlesitekit_analytics_adsense_linked' );
}
/**
* Checks if the module is active in the admin bar for the given URL.
*
* @since 1.4.0
*
* @param string $url URL to determine active state for.
* @return bool
*/
public function is_active_in_admin_bar( $url ) {
if ( ! $this->is_connected() ) {
return false;
}
return $this->has_data_for_url( $url );
}
/**
* Gets an array of debug field definitions.
*
* @since 1.5.0
*
* @return array
*/
public function get_debug_fields() {
$settings = $this->get_settings()->get();
return array(
'analytics_account_id' => array(
'label' => __( 'Analytics account ID', 'google-site-kit' ),
'value' => $settings['accountID'],
'debug' => Debug_Data::redact_debug_value( $settings['accountID'] ),
),
'analytics_property_id' => array(
'label' => __( 'Analytics property ID', 'google-site-kit' ),
'value' => $settings['propertyID'],
'debug' => Debug_Data::redact_debug_value( $settings['propertyID'], 7 ),
),
'analytics_profile_id' => array(
'label' => __( 'Analytics view ID', 'google-site-kit' ),
'value' => $settings['profileID'],
'debug' => Debug_Data::redact_debug_value( $settings['profileID'] ),
),
'analytics_use_snippet' => array(
'label' => __( 'Analytics snippet placed', 'google-site-kit' ),
'value' => $settings['useSnippet'] ? __( 'Yes', 'google-site-kit' ) : __( 'No', 'google-site-kit' ),
'debug' => $settings['useSnippet'] ? 'yes' : 'no',
),
);
}
/**
* Outputs gtag snippet.
*
* @since 1.0.0
*/
protected function enqueue_gtag_js() {
// Bail early if we are checking for the tag presence from the back end.
if ( $this->context->input()->filter( INPUT_GET, 'tagverify', FILTER_VALIDATE_BOOLEAN ) ) {
return;
}
// On AMP, do not print the script tag.
if ( $this->context->is_amp() ) {
return;
}
$use_snippet = $this->get_data( 'use-snippet' );
if ( is_wp_error( $use_snippet ) || ! $use_snippet ) {
return;
}
$tracking_id = $this->get_data( 'property-id' );
if ( is_wp_error( $tracking_id ) ) {
return;
}
wp_enqueue_script( // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
'google_gtagjs',
'https://www.googletagmanager.com/gtag/js?id=' . esc_attr( $tracking_id ),
false,
null,
false
);
wp_script_add_data( 'google_gtagjs', 'script_execution', 'async' );
wp_add_inline_script(
'google_gtagjs',
'window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}'
);
$gtag_opt = array();
if ( $this->context->get_amp_mode() ) {
$gtag_opt['linker'] = array(
'domains' => array( $this->get_home_domain() ),
);
}
$anonymize_ip = $this->get_data( 'anonymize-ip' );
if ( ! is_wp_error( $anonymize_ip ) && $anonymize_ip ) {
// See https://developers.google.com/analytics/devguides/collection/gtagjs/ip-anonymization.
$gtag_opt['anonymize_ip'] = true;
}
/**
* Filters the gtag configuration options for the Analytics snippet.
*
* You can use the {@see 'googlesitekit_amp_gtag_opt'} filter to do the same for gtag in AMP.
*
* @since 1.0.0
*
* @see https://developers.google.com/gtagjs/devguide/configure
*
* @param array $gtag_opt gtag config options.
*/
$gtag_opt = apply_filters( 'googlesitekit_gtag_opt', $gtag_opt );
if ( ! empty( $gtag_opt['linker'] ) ) {
wp_add_inline_script(
'google_gtagjs',
'gtag(\'set\', \'linker\', ' . wp_json_encode( $gtag_opt['linker'] ) . ' );'
);
}
unset( $gtag_opt['linker'] );
wp_add_inline_script(
'google_gtagjs',
'gtag(\'js\', new Date());'
);
if ( empty( $gtag_opt ) ) {
wp_add_inline_script(
'google_gtagjs',
'gtag(\'config\', \'' . esc_attr( $tracking_id ) . '\');'
);
} else {
wp_add_inline_script(
'google_gtagjs',
'gtag(\'config\', \'' . esc_attr( $tracking_id ) . '\', ' . wp_json_encode( $gtag_opt ) . ' );'
);
}
}
/**
* Outputs gtag <amp-analytics> tag.
*
* @since 1.0.0
*/
protected function print_amp_gtag() {
// Bail early if we are checking for the tag presence from the back end.
if ( $this->context->input()->filter( INPUT_GET, 'tagverify', FILTER_VALIDATE_BOOLEAN ) ) {
return;
}
if ( ! $this->context->is_amp() ) {
return;
}
$use_snippet = $this->get_data( 'use-snippet' );
if ( is_wp_error( $use_snippet ) || ! $use_snippet ) {
return;
}
$tracking_id = $this->get_data( 'property-id' );
if ( is_wp_error( $tracking_id ) ) {
return;
}
$gtag_amp_opt = array(
'vars' => array(
'gtag_id' => $tracking_id,
'config' => array(
$tracking_id => array(
'groups' => 'default',
'linker' => array(
'domains' => array( $this->get_home_domain() ),
),
),
),
),
'optoutElementId' => '__gaOptOutExtension',
);
/**
* Filters the gtag configuration options for the amp-analytics tag.
*
* You can use the {@see 'googlesitekit_gtag_opt'} filter to do the same for gtag in non-AMP.
*
* @since 1.0.0
*
* @see https://developers.google.com/gtagjs/devguide/amp
*
* @param array $gtag_amp_opt gtag config options for AMP.
*/
$gtag_amp_opt_filtered = apply_filters( 'googlesitekit_amp_gtag_opt', $gtag_amp_opt );
// Ensure gtag_id is set to the correct value.
if ( ! is_array( $gtag_amp_opt_filtered ) ) {
$gtag_amp_opt_filtered = $gtag_amp_opt;
}
if ( ! isset( $gtag_amp_opt_filtered['vars'] ) || ! is_array( $gtag_amp_opt_filtered['vars'] ) ) {
$gtag_amp_opt_filtered['vars'] = $gtag_amp_opt['vars'];
}
$gtag_amp_opt_filtered['vars']['gtag_id'] = $tracking_id;
?>
<amp-analytics type="gtag" data-credentials="include">
<script type="application/json">
<?php echo wp_json_encode( $gtag_amp_opt_filtered ); ?>
</script>
</amp-analytics>
<?php
}
/**
* Loads AMP analytics script if opted in.
*
* This only affects AMP Reader mode, the others are automatically covered.
*
* @since 1.0.0
*
* @param array $data AMP template data.
* @return array Filtered $data.
*/
protected function amp_data_load_analytics_component( $data ) {
if ( isset( $data['amp_component_scripts']['amp-analytics'] ) ) {
return $data;
}
$use_snippet = $this->get_data( 'use-snippet' );
if ( is_wp_error( $use_snippet ) || ! $use_snippet ) {
return $data;
}
$tracking_id = $this->get_data( 'property-id' );
if ( is_wp_error( $tracking_id ) ) {
return $data;
}
$data['amp_component_scripts']['amp-analytics'] = 'https://cdn.ampproject.org/v0/amp-analytics-0.1.js';
return $data;
}
/**
* Handles the provisioning callback after the user completes the terms of service.
*
* @since 1.9.0
*/
protected function handle_provisioning_callback() {
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return;
}
if ( ! current_user_can( Permissions::MANAGE_OPTIONS ) ) {
return;
}
$input = $this->context->input();
if ( ! $input->filter( INPUT_GET, 'gatoscallback' ) ) {
return;
}
// The handler should check the received Account Ticket id parameter against the id stored in the provisioning step.
$account_ticket_id = $input->filter( INPUT_GET, 'accountTicketId', FILTER_SANITIZE_STRING );
$stored_account_ticket_id = get_transient( self::PROVISION_ACCOUNT_TICKET_ID . '::' . get_current_user_id() );
delete_transient( self::PROVISION_ACCOUNT_TICKET_ID . '::' . get_current_user_id() );
if ( $stored_account_ticket_id !== $account_ticket_id ) {
wp_safe_redirect(
$this->context->admin_url( 'module-analytics', array( 'error_code' => 'account_ticket_id_mismatch' ) )
);
exit;
}
// Check for a returned error.
$error = $input->filter( INPUT_GET, 'error', FILTER_SANITIZE_STRING );
if ( ! empty( $error ) ) {
wp_safe_redirect(
$this->context->admin_url( 'module-analytics', array( 'error_code' => $error ) )
);
exit;
}
$account_id = $input->filter( INPUT_GET, 'accountId', FILTER_SANITIZE_STRING );
$web_property_id = $input->filter( INPUT_GET, 'webPropertyId', FILTER_SANITIZE_STRING );
$profile_id = $input->filter( INPUT_GET, 'profileId', FILTER_SANITIZE_STRING );
if ( empty( $account_id ) || empty( $web_property_id ) || empty( $profile_id ) ) {
wp_safe_redirect(
$this->context->admin_url( 'module-analytics', array( 'error_code' => 'callback_missing_parameter' ) )
);
exit;
}
// Retrieve the internal web property id.
try {
$web_property = $this->get_service( 'analytics' )->management_webproperties->get( $account_id, $web_property_id );
} catch ( Exception $e ) {
wp_safe_redirect(
$this->context->admin_url( 'module-analytics', array( 'error_code' => 'property_not_found' ) )
);
exit;
}
$this->get_settings()->merge(
array(
'accountID' => $account_id,
'propertyID' => $web_property_id,
'profileID' => $profile_id,
'internalWebPropertyID' => $web_property->getInternalWebPropertyId(),
)
);
wp_safe_redirect(
$this->context->admin_url(
'dashboard',
array(
'notification' => 'authentication_success',
'slug' => 'analytics',
)
)
);
exit;
}
/**
* Gets map of datapoint to definition data for each.
*
* @since 1.9.0
*
* @return array Map of datapoints to their definitions.
*/
protected function get_datapoint_definitions() {
return array(
'GET:account-id' => array( 'service' => '' ),
'POST:account-id' => array( 'service' => '' ),
'GET:accounts-properties-profiles' => array( 'service' => 'analytics' ),
'GET:anonymize-ip' => array( 'service' => '' ),
'GET:connection' => array( 'service' => '' ),
'POST:connection' => array( 'service' => '' ),
'POST:create-account-ticket' => array(
'service' => 'analyticsprovisioning',
'scopes' => array( 'https://www.googleapis.com/auth/analytics.provision' ),
'request_scopes_message' => __( 'You’ll need to grant Site Kit permission to create a new Analytics account on your behalf.', 'google-site-kit' ),
),
'POST:create-profile' => array(
'service' => 'analytics',
'scopes' => array( 'https://www.googleapis.com/auth/analytics.edit' ),
'request_scopes_message' => __( 'You’ll need to grant Site Kit permission to create a new Analytics view on your behalf.', 'google-site-kit' ),
),
'POST:create-property' => array(
'service' => 'analytics',
'scopes' => array( 'https://www.googleapis.com/auth/analytics.edit' ),
'request_scopes_message' => __( 'You’ll need to grant Site Kit permission to create a new Analytics property on your behalf.', 'google-site-kit' ),
),
'GET:internal-web-property-id' => array( 'service' => '' ),
'POST:internal-web-property-id' => array( 'service' => '' ),
'GET:goals' => array( 'service' => 'analytics' ),
'GET:profile-id' => array( 'service' => '' ),
'POST:profile-id' => array( 'service' => '' ),
'GET:profiles' => array( 'service' => 'analytics' ),
'GET:properties-profiles' => array( 'service' => 'analytics' ),
'GET:property-id' => array( 'service' => '' ),
'POST:property-id' => array( 'service' => '' ),
'GET:report' => array( 'service' => 'analyticsreporting' ),
'GET:tag-permission' => array( 'service' => '' ),
'GET:tracking-disabled' => array( 'service' => '' ),
'GET:use-snippet' => array( 'service' => '' ),
'POST:use-snippet' => array( 'service' => '' ),
);
}
/**
* Creates a request object for the given datapoint.
*
* @since 1.0.0
*
* @param Data_Request $data Data request object.
* @return RequestInterface|callable|WP_Error Request object or callable on success, or WP_Error on failure.
*
* @throws Invalid_Datapoint_Exception Thrown if the datapoint does not exist.
*/
protected function create_data_request( Data_Request $data ) {
switch ( "{$data->method}:{$data->datapoint}" ) {
case 'GET:account-id':
return function() {
$option = $this->get_settings()->get();
if ( empty( $option['accountID'] ) ) {
return new WP_Error( 'account_id_not_set', __( 'Analytics account ID not set.', 'google-site-kit' ), array( 'status' => 404 ) );
}
return $option['accountID'];
};
case 'POST:account-id':
if ( ! isset( $data['accountID'] ) ) {
/* translators: %s: Missing parameter name */
return new WP_Error( 'missing_required_param', sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'accountID' ), array( 'status' => 400 ) );
}
return function() use ( $data ) {
$this->get_settings()->merge(
array(
'accountID' => $data['accountID'],
'adsenseLinked' => false,
)
);
return true;
};
case 'GET:accounts-properties-profiles':
return function () use ( $data ) {
$restore_defer = $this->with_client_defer( false );
try {
return $this->get_service( 'analytics' )->management_accounts->listManagementAccounts();
} catch ( Google_Service_Exception $exception ) {
// The exception message is a JSON object of all errors, so we'll convert it to our WP Error first.
$wp_error = $this->exception_to_error( $exception, $data->datapoint );
// Unfortunately there isn't a better way to identify this without checking the message.
if ( 'User does not have any Google Analytics account.' === $wp_error->get_error_message() ) {
return new Google_Service_Analytics_Accounts();
}
// If any other exception was caught, re-throw it.
throw $exception;
} finally {
$restore_defer(); // Will be called before returning in all cases.
}
};
case 'GET:anonymize-ip':
return function() {
$option = $this->get_settings()->get();
return (bool) $option['anonymizeIP'];
};
case 'GET:connection':
return function() {
$connection = array(
'accountID' => '',
'propertyID' => '',
'profileID' => '',
'internalWebPropertyID' => '',
);
$option = $this->get_settings()->get();
return array_intersect_key( $option, $connection );
};
case 'POST:connection':
return function() use ( $data ) {
$this->get_settings()->merge(
array(
'accountID' => $data['accountID'],
'propertyID' => $data['propertyID'],
'profileID' => $data['profileID'],
'internalWebPropertyID' => $data['internalWebPropertyID'],
'adsenseLinked' => false,
)
);
return true;
};
case 'POST:create-account-ticket':
if ( ! isset( $data['accountName'] ) ) {
/* translators: %s: Missing parameter name */
return new WP_Error( 'missing_required_param', sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'accountName' ), array( 'status' => 400 ) );
}
if ( ! isset( $data['propertyName'] ) ) {
/* translators: %s: Missing parameter name */
return new WP_Error( 'missing_required_param', sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'propertyName' ), array( 'status' => 400 ) );
}
if ( ! isset( $data['profileName'] ) ) {
/* translators: %s: Missing parameter name */
return new WP_Error( 'missing_required_param', sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'profileName' ), array( 'status' => 400 ) );
}
if ( ! isset( $data['timezone'] ) ) {
/* translators: %s: Missing parameter name */
return new WP_Error( 'missing_required_param', sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'timezone' ), array( 'status' => 400 ) );
}
if ( ! $this->authentication->credentials()->using_proxy() ) {
return new WP_Error( 'requires_service', __( 'Analytics provisioning requires connecting via the Site Kit Service.', 'google-site-kit' ), array( 'status' => 400 ) );
}
$account = new Google_Service_Analytics_Account();
$account->setName( $data['accountName'] );
$property = new Google_Service_Analytics_Webproperty();
$property->setName( $data['propertyName'] );
$property->setWebsiteUrl( $this->context->get_reference_site_url() );
$profile = new Google_Service_Analytics_Profile();
$profile->setName( $data['profileName'] );
$profile->setTimezone( $data['timezone'] );
$account_ticket = new Proxy_AccountTicket();
$account_ticket->setAccount( $account );
$account_ticket->setWebproperty( $property );
$account_ticket->setProfile( $profile );
$account_ticket->setRedirectUri( $this->get_provisioning_redirect_uri() );
// Add site id and secret.
$creds = $this->authentication->credentials()->get();
$account_ticket->setSiteId( $creds['oauth2_client_id'] );
$account_ticket->setSiteSecret( $creds['oauth2_client_secret'] );
return $this->get_service( 'analyticsprovisioning' )
->provisioning->createAccountTicket( $account_ticket );
case 'GET:goals':
$connection = $this->get_data( 'connection' );
if (
empty( $connection['accountID'] ) ||
empty( $connection['internalWebPropertyID'] ) ||
empty( $connection['profileID'] )
) {
// This is needed to return and emulate the same error format from Analytics API.
return function() {
return array(
'error' => array(
'code' => 400,
'message' => __( 'Analytics module needs to be configured.', 'google-site-kit' ),
'status' => 'INVALID_ARGUMENT',
),
);
};
}
$service = $this->get_service( 'analytics' );
return $service->management_goals->listManagementGoals( $connection['accountID'], $connection['propertyID'], $connection['profileID'] );
case 'GET:internal-web-property-id':
return function() {
$option = $this->get_settings()->get();
if ( empty( $option['internalWebPropertyID'] ) ) {
return new WP_Error( 'internal_web_property_id_not_set', __( 'Analytics internal web property ID not set.', 'google-site-kit' ), array( 'status' => 404 ) );
}
return $option['internalWebPropertyID'];
};
case 'POST:internal-web-property-id':
if ( ! isset( $data['internalWebPropertyID'] ) ) {
/* translators: %s: Missing parameter name */
return new WP_Error( 'missing_required_param', sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'internalWebPropertyID' ), array( 'status' => 400 ) );
}
return function() use ( $data ) {
$this->get_settings()->merge(
array(
'internalWebPropertyID' => $data['internalWebPropertyID'],
'adsenseLinked' => false,
)
);
return true;
};
case 'GET:profile-id':
return function() {
$option = $this->get_settings()->get();
if ( empty( $option['profileID'] ) ) {
return new WP_Error( 'profile_id_not_set', __( 'Analytics view ID not set.', 'google-site-kit' ), array( 'status' => 404 ) );
}
return $option['profileID'];
};
case 'POST:profile-id':
if ( ! isset( $data['profileID'] ) ) {
/* translators: %s: Missing parameter name */
return new WP_Error( 'missing_required_param', sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'profileID' ), array( 'status' => 400 ) );
}
return function() use ( $data ) {
$this->get_settings()->merge(
array(
'profileID' => $data['profileID'],
'adsenseLinked' => false,
)
);
return true;
};
case 'GET:profiles':
if ( ! isset( $data['accountID'] ) ) {
return new WP_Error(
'missing_required_param',
/* translators: %s: Missing parameter name */
sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'accountID' ),
array( 'status' => 400 )
);
}
if ( ! isset( $data['propertyID'] ) ) {
return new WP_Error(
'missing_required_param',
/* translators: %s: Missing parameter name */
sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'propertyID' ),
array( 'status' => 400 )
);
}
return $this->get_service( 'analytics' )->management_profiles->listManagementProfiles( $data['accountID'], $data['propertyID'] );
case 'GET:properties-profiles':
if ( ! isset( $data['accountID'] ) ) {
return new WP_Error(
'missing_required_param',
/* translators: %s: Missing parameter name */
sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'accountID' ),
array( 'status' => 400 )
);
}
return $this->get_service( 'analytics' )->management_webproperties->listManagementWebproperties( $data['accountID'] );
case 'GET:property-id':
return function() {
$option = $this->get_settings()->get();
if ( empty( $option['propertyID'] ) ) {
return new WP_Error( 'property_id_not_set', __( 'Analytics property ID not set.', 'google-site-kit' ), array( 'status' => 404 ) );
}
return $option['propertyID'];
};
case 'POST:property-id':
if ( ! isset( $data['propertyID'] ) ) {
/* translators: %s: Missing parameter name */
return new WP_Error( 'missing_required_param', sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'propertyID' ), array( 'status' => 400 ) );
}
return function() use ( $data ) {
$this->get_settings()->merge(
array(
'propertyID' => $data['propertyID'],
'adsenseLinked' => false,
)
);
return true;
};
case 'GET:report':
$request_args = array();
if ( empty( $data['metrics'] ) ) {
/* translators: %s: Missing parameter name */
return new WP_Error( 'missing_required_param', sprintf( __( 'Request parameter is empty: %s.', 'google-site-kit' ), 'metrics' ), array( 'status' => 400 ) );
}
if ( ! empty( $data['url'] ) ) {
$request_args['page'] = $data['url'];
}
if ( ! empty( $data['limit'] ) ) {
$request_args['row_limit'] = $data['limit'];
}
$dimensions = $data['dimensions'];
if ( ! empty( $dimensions ) && ( is_string( $dimensions ) || is_array( $dimensions ) ) ) {
if ( is_string( $dimensions ) ) {
$dimensions = explode( ',', $dimensions );
} elseif ( is_array( $dimensions ) && ! wp_is_numeric_array( $dimensions ) ) { // If single object is passed.
$dimensions = array( $dimensions );
}
$dimensions = array_filter(
array_map(
function ( $dimension_def ) {
$dimension = new Google_Service_AnalyticsReporting_Dimension();
if ( is_string( $dimension_def ) ) {
$dimension->setName( $dimension_def );
} elseif ( is_array( $dimension_def ) && ! empty( $dimension_def['name'] ) ) {
$dimension->setName( $dimension_def['name'] );
} else {
return null;
}
return $dimension;
},
array_filter( $dimensions )
)
);
if ( ! empty( $dimensions ) ) {
$request_args['dimensions'] = $dimensions;
}
}
$request = $this->create_analytics_site_data_request( $request_args );
if ( is_wp_error( $request ) ) {
return $request;
}
$date_ranges = array();
$start_date = $data['startDate'];
$end_date = $data['endDate'];
if ( strtotime( $start_date ) && strtotime( $end_date ) ) {
$date_ranges[] = array( $start_date, $end_date );
} else {
$date_range = $data['dateRange'] ?: 'last-28-days';
$date_ranges[] = $this->parse_date_range( $date_range, $data['compareDateRanges'] ? 2 : 1 );
// When using multiple date ranges, it changes the structure of the response,
// where each date range becomes an item in a list.
if ( ! empty( $data['multiDateRange'] ) ) {
$date_ranges[] = $this->parse_date_range( $date_range, 1, 1, true );
}
}
$date_ranges = array_map(
function ( $date_range ) {
list ( $start_date, $end_date ) = $date_range;
$date_range = new Google_Service_AnalyticsReporting_DateRange();
$date_range->setStartDate( $start_date );
$date_range->setEndDate( $end_date );
return $date_range;
},
$date_ranges
);
$request->setDateRanges( $date_ranges );
$metrics = $data['metrics'];
if ( is_string( $metrics ) || is_array( $metrics ) ) {
if ( is_string( $metrics ) ) {
$metrics = explode( ',', $data['metrics'] );
} elseif ( is_array( $metrics ) && ! wp_is_numeric_array( $metrics ) ) { // If single object is passed.
$metrics = array( $metrics );
}
$metrics = array_filter(
array_map(
function ( $metric_def ) {
$metric = new Google_Service_AnalyticsReporting_Metric();
if ( is_string( $metric_def ) ) {
$metric->setAlias( $metric_def );
$metric->setExpression( $metric_def );
} elseif ( is_array( $metric_def ) && ! empty( $metric_def['expression'] ) ) {
$metric->setExpression( $metric_def['expression'] );
$metric->setAlias( ! empty( $metric_def['alias'] ) ? $metric_def['alias'] : $metric_def['expression'] );
} else {
return null;
}
return $metric;
},
array_filter( $metrics )
)
);
if ( ! empty( $metrics ) ) {
$request->setMetrics( $metrics );
}
}
// Order by.
$orderby = $data['orderby'];
if ( ! empty( $orderby ) && is_array( $orderby ) ) {
// When just object is passed we need to convert it to an array of objects.
if ( ! wp_is_numeric_array( $orderby[0] ) ) {
$orderby = array( $orderby );
}
$orderby = array_filter(
array_map(
function ( $order_def ) {
$order_def = array_merge(
array(
'fieldName' => '',
'sortOrder' => 'DESCENDING',
),
(array) $order_def
);
if ( empty( $order_def['fieldName'] ) ) {
return null;
}
$order_by = new Google_Service_AnalyticsReporting_OrderBy();
$order_by->setFieldName( $order_def['fieldName'] );
$order_by->setSortOrder( $order_def['sortOrder'] );
return $order_by;