Google Analytics Dashboard for WP (GADWP) - Version 4.9.5

Version Description

  • Bug Fixes:
    • correction of some files with mixed endings, props by Edward Dekker
    • only load the necessary resources for frontend widget
    • corrected a JavaScript error on frontend sidebar widget
  • Enhancements:
    • introducing the gadwp_curl_options filter to allow changes on CURL options for the Google_IO_Curl class, props by Alexandre Simard
Download this release

Release Info

Developer deconf
Plugin Icon 128x128 Google Analytics Dashboard for WP (GADWP)
Version 4.9.5
Comparing to
See all releases

Code changes from version 4.9.4 to 4.9.5

Files changed (67) hide show
  1. admin/ajax-actions.php +133 -133
  2. admin/css/admin-widgets.css +191 -191
  3. admin/css/gadwp.css +205 -205
  4. admin/css/item-reports.css +123 -123
  5. admin/item-reports.php +56 -56
  6. admin/js/settings.js +39 -39
  7. admin/js/ui.js +25 -25
  8. admin/js/wp-color-picker-script.js +10 -10
  9. admin/settings.php +1358 -1358
  10. admin/setup.php +357 -357
  11. admin/widgets.php +65 -65
  12. common/ajax-actions.php +43 -43
  13. common/js/reports.js +1107 -1107
  14. config.php +422 -422
  15. front/ajax-actions.php +152 -152
  16. front/css/item-reports.css +184 -184
  17. front/css/widgets.css +74 -74
  18. front/item-reports.php +38 -38
  19. front/js/widgets.js +12 -12
  20. front/setup.php +123 -123
  21. front/tracking.php +64 -64
  22. front/tracking/code-classic.php +33 -33
  23. front/tracking/code-universal.php +138 -138
  24. front/tracking/events-classic.php +55 -55
  25. front/tracking/events-universal.php +67 -67
  26. front/widgets.php +194 -194
  27. gadwp.php +258 -258
  28. install/install.php +149 -149
  29. install/uninstall.php +34 -34
  30. readme.txt +9 -1
  31. tools/autoload.php +37 -37
  32. tools/gapi.php +867 -862
  33. tools/iso3166.php +254 -254
  34. tools/src/Google/Auth/Abstract.php +39 -39
  35. tools/src/Google/Auth/AppIdentity.php +100 -100
  36. tools/src/Google/Auth/AssertionCredentials.php +142 -142
  37. tools/src/Google/Auth/Exception.php +20 -20
  38. tools/src/Google/Auth/LoginTicket.php +75 -75
  39. tools/src/Google/Auth/OAuth2.php +546 -546
  40. tools/src/Google/Auth/Simple.php +64 -64
  41. tools/src/Google/Cache/Abstract.php +57 -57
  42. tools/src/Google/Cache/Apc.php +107 -107
  43. tools/src/Google/Cache/Exception.php +20 -20
  44. tools/src/Google/Cache/File.php +185 -185
  45. tools/src/Google/Cache/Memcache.php +177 -177
  46. tools/src/Google/Cache/Null.php +53 -53
  47. tools/src/Google/Client.php +760 -760
  48. tools/src/Google/Collection.php +92 -92
  49. tools/src/Google/Config.php +446 -446
  50. tools/src/Google/Exception.php +19 -19
  51. tools/src/Google/Http/Batch.php +137 -137
  52. tools/src/Google/Http/CacheParser.php +181 -181
  53. tools/src/Google/Http/MediaFileUpload.php +314 -314
  54. tools/src/Google/Http/REST.php +142 -142
  55. tools/src/Google/Http/Request.php +497 -497
  56. tools/src/Google/IO/Abstract.php +339 -339
  57. tools/src/Google/IO/Curl.php +152 -152
  58. tools/src/Google/IO/Exception.php +20 -20
  59. tools/src/Google/IO/Stream.php +201 -201
  60. tools/src/Google/Logger/Abstract.php +409 -409
  61. tools/src/Google/Logger/Exception.php +20 -20
  62. tools/src/Google/Logger/File.php +148 -148
  63. tools/src/Google/Logger/Null.php +39 -39
  64. tools/src/Google/Logger/Psr.php +92 -92
  65. tools/src/Google/Model.php +282 -282
  66. tools/src/Google/Service.php +44 -44
  67. tools/src/Google/Service/Analytics.php +0 -1483
admin/ajax-actions.php CHANGED
@@ -1,133 +1,133 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Backend_Ajax' ) ) {
15
-
16
- final class GADWP_Backend_Ajax {
17
-
18
- private $gadwp;
19
-
20
- public function __construct() {
21
- $this->gadwp = GADWP();
22
-
23
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && ( ( 1 == $this->gadwp->config->options['backend_item_reports'] ) || ( 1 == $this->gadwp->config->options['dashboard_widget'] ) ) ) {
24
- // Items action
25
- add_action( 'wp_ajax_gadwp_backend_item_reports', array( $this, 'ajax_item_reports' ) );
26
- }
27
- if ( current_user_can( 'manage_options' ) ) {
28
- // Admin Widget action
29
- add_action( 'wp_ajax_gadwp_dismiss_notices', array( $this, 'ajax_dismiss_notices' ) );
30
- }
31
- }
32
-
33
- /**
34
- * Ajax handler for Item Reports
35
- *
36
- * @return json|int
37
- */
38
- public function ajax_item_reports() {
39
- if ( ! isset( $_POST['gadwp_security_backend_item_reports'] ) || ! wp_verify_nonce( $_POST['gadwp_security_backend_item_reports'], 'gadwp_backend_item_reports' ) ) {
40
- wp_die( - 30 );
41
- }
42
- if ( isset( $_POST['projectId'] ) && $this->gadwp->config->options['switch_profile'] && $_POST['projectId'] !== 'false' ) {
43
- $projectId = $_POST['projectId'];
44
- } else {
45
- $projectId = false;
46
- }
47
- $from = $_POST['from'];
48
- $to = $_POST['to'];
49
- $query = $_POST['query'];
50
- if ( isset( $_POST['filter'] ) ) {
51
- $filter_id = $_POST['filter'];
52
- } else {
53
- $filter_id = false;
54
- }
55
- if ( ob_get_length() ) {
56
- ob_clean();
57
- }
58
-
59
- if ( ! ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && ( ( 1 == $this->gadwp->config->options['backend_item_reports'] ) || ( 1 == $this->gadwp->config->options['dashboard_widget'] ) ) ) ) {
60
- wp_die( - 31 );
61
- }
62
- if ( $this->gadwp->config->options['ga_dash_token'] && $this->gadwp->config->options['ga_dash_tableid_jail'] && $from && $to ) {
63
- if ( null === $this->gadwp->gapi_controller ) {
64
- $this->gadwp->gapi_controller = new GADWP_GAPI_Controller();
65
- }
66
- } else {
67
- wp_die( - 24 );
68
- }
69
- if ( $projectId == false ) {
70
- $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
71
- }
72
- $profile_info = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $projectId );
73
- if ( isset( $profile_info[4] ) ) {
74
- $this->gadwp->gapi_controller->timeshift = $profile_info[4];
75
- } else {
76
- $this->gadwp->gapi_controller->timeshift = (int) current_time( 'timestamp' ) - time();
77
- }
78
-
79
- if ( $filter_id ) {
80
- $uri_parts = explode( '/', get_permalink( $filter_id ), 4 );
81
-
82
- if ( isset( $uri_parts[3] ) ) {
83
- $uri = '/' . $uri_parts[3];
84
- } else {
85
- wp_die( - 25 );
86
- }
87
-
88
- // allow URL correction before sending an API request
89
- $filter = apply_filters( 'gadwp_backenditem_uri', $uri, $filter_id );
90
-
91
- $lastchar = substr( $filter, - 1 );
92
-
93
- if ( isset( $profile_info[6] ) && $profile_info[6] && $lastchar == '/' ) {
94
- $filter = $filter . $profile_info[6];
95
- }
96
-
97
- // Encode URL
98
- $filter = rawurlencode( rawurldecode( $filter ) );
99
- } else {
100
- $filter = false;
101
- }
102
-
103
- $queries = explode( ',', $query );
104
-
105
- $results = array();
106
-
107
- foreach ( $queries as $value ) {
108
- $results[] = $this->gadwp->gapi_controller->get( $projectId, $value, $from, $to, $filter );
109
- }
110
-
111
- wp_send_json( $results );
112
- }
113
-
114
- /**
115
- * Ajax handler for dismissing Admin notices
116
- *
117
- * @return json|int
118
- */
119
- public function ajax_dismiss_notices() {
120
- if ( ! isset( $_POST['gadwp_security_dismiss_notices'] ) || ! wp_verify_nonce( $_POST['gadwp_security_dismiss_notices'], 'gadwp_dismiss_notices' ) ) {
121
- wp_die( - 30 );
122
- }
123
-
124
- if ( ! current_user_can( 'manage_options' ) ) {
125
- wp_die( - 31 );
126
- }
127
-
128
- delete_option( 'gadwp_got_updated' );
129
-
130
- wp_die();
131
- }
132
- }
133
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Backend_Ajax' ) ) {
15
+
16
+ final class GADWP_Backend_Ajax {
17
+
18
+ private $gadwp;
19
+
20
+ public function __construct() {
21
+ $this->gadwp = GADWP();
22
+
23
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && ( ( 1 == $this->gadwp->config->options['backend_item_reports'] ) || ( 1 == $this->gadwp->config->options['dashboard_widget'] ) ) ) {
24
+ // Items action
25
+ add_action( 'wp_ajax_gadwp_backend_item_reports', array( $this, 'ajax_item_reports' ) );
26
+ }
27
+ if ( current_user_can( 'manage_options' ) ) {
28
+ // Admin Widget action
29
+ add_action( 'wp_ajax_gadwp_dismiss_notices', array( $this, 'ajax_dismiss_notices' ) );
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Ajax handler for Item Reports
35
+ *
36
+ * @return json|int
37
+ */
38
+ public function ajax_item_reports() {
39
+ if ( ! isset( $_POST['gadwp_security_backend_item_reports'] ) || ! wp_verify_nonce( $_POST['gadwp_security_backend_item_reports'], 'gadwp_backend_item_reports' ) ) {
40
+ wp_die( - 30 );
41
+ }
42
+ if ( isset( $_POST['projectId'] ) && $this->gadwp->config->options['switch_profile'] && $_POST['projectId'] !== 'false' ) {
43
+ $projectId = $_POST['projectId'];
44
+ } else {
45
+ $projectId = false;
46
+ }
47
+ $from = $_POST['from'];
48
+ $to = $_POST['to'];
49
+ $query = $_POST['query'];
50
+ if ( isset( $_POST['filter'] ) ) {
51
+ $filter_id = $_POST['filter'];
52
+ } else {
53
+ $filter_id = false;
54
+ }
55
+ if ( ob_get_length() ) {
56
+ ob_clean();
57
+ }
58
+
59
+ if ( ! ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && ( ( 1 == $this->gadwp->config->options['backend_item_reports'] ) || ( 1 == $this->gadwp->config->options['dashboard_widget'] ) ) ) ) {
60
+ wp_die( - 31 );
61
+ }
62
+ if ( $this->gadwp->config->options['ga_dash_token'] && $this->gadwp->config->options['ga_dash_tableid_jail'] && $from && $to ) {
63
+ if ( null === $this->gadwp->gapi_controller ) {
64
+ $this->gadwp->gapi_controller = new GADWP_GAPI_Controller();
65
+ }
66
+ } else {
67
+ wp_die( - 24 );
68
+ }
69
+ if ( $projectId == false ) {
70
+ $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
71
+ }
72
+ $profile_info = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $projectId );
73
+ if ( isset( $profile_info[4] ) ) {
74
+ $this->gadwp->gapi_controller->timeshift = $profile_info[4];
75
+ } else {
76
+ $this->gadwp->gapi_controller->timeshift = (int) current_time( 'timestamp' ) - time();
77
+ }
78
+
79
+ if ( $filter_id ) {
80
+ $uri_parts = explode( '/', get_permalink( $filter_id ), 4 );
81
+
82
+ if ( isset( $uri_parts[3] ) ) {
83
+ $uri = '/' . $uri_parts[3];
84
+ } else {
85
+ wp_die( - 25 );
86
+ }
87
+
88
+ // allow URL correction before sending an API request
89
+ $filter = apply_filters( 'gadwp_backenditem_uri', $uri, $filter_id );
90
+
91
+ $lastchar = substr( $filter, - 1 );
92
+
93
+ if ( isset( $profile_info[6] ) && $profile_info[6] && $lastchar == '/' ) {
94
+ $filter = $filter . $profile_info[6];
95
+ }
96
+
97
+ // Encode URL
98
+ $filter = rawurlencode( rawurldecode( $filter ) );
99
+ } else {
100
+ $filter = false;
101
+ }
102
+
103
+ $queries = explode( ',', $query );
104
+
105
+ $results = array();
106
+
107
+ foreach ( $queries as $value ) {
108
+ $results[] = $this->gadwp->gapi_controller->get( $projectId, $value, $from, $to, $filter );
109
+ }
110
+
111
+ wp_send_json( $results );
112
+ }
113
+
114
+ /**
115
+ * Ajax handler for dismissing Admin notices
116
+ *
117
+ * @return json|int
118
+ */
119
+ public function ajax_dismiss_notices() {
120
+ if ( ! isset( $_POST['gadwp_security_dismiss_notices'] ) || ! wp_verify_nonce( $_POST['gadwp_security_dismiss_notices'], 'gadwp_dismiss_notices' ) ) {
121
+ wp_die( - 30 );
122
+ }
123
+
124
+ if ( ! current_user_can( 'manage_options' ) ) {
125
+ wp_die( - 31 );
126
+ }
127
+
128
+ delete_option( 'gadwp_got_updated' );
129
+
130
+ wp_die();
131
+ }
132
+ }
133
+ }
admin/css/admin-widgets.css CHANGED
@@ -1,192 +1,192 @@
1
- /**
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
-
9
- /* Real-Time content */
10
- .gadwp-pline {
11
- width: 100%;
12
- margin: 0 0;
13
- padding: 5px 0 5px 0;
14
- background: #fff;
15
- -moz-box-shadow: 0px 0px 3px 0px #BBB;
16
- -webkit-box-shadow: 0px 0px 3px 0px #BBB;
17
- box-shadow: 0px 0px 3px 0px #BBB;
18
- display: table;
19
- overflow: hidden;
20
- }
21
-
22
- .gadwp-pleft {
23
- width: 90%;
24
- float: left;
25
- padding-left: 5px;
26
- }
27
-
28
- .gadwp-pright {
29
- width: 5%;
30
- float: right;
31
- padding-right: 5px;
32
- }
33
-
34
- [id^=gadwp-realtime-] {
35
- margin: 10px 0 0 0;
36
- width: 100%;
37
- }
38
-
39
- .gadwp-rt-box {
40
- width: 100%;
41
- margin: 0 0;
42
- background: #fff;
43
- text-align: center;
44
- -moz-box-shadow: 0px 0px 5px 0px #BBB;
45
- -webkit-box-shadow: 0px 0px 5px 0px #BBB;
46
- box-shadow: 0px 0px 5px 0px #BBB;
47
- display: table;
48
- }
49
-
50
- .gadwp-tdo-left {
51
- width: 60%;
52
- padding: 33px 0;
53
- float: left;
54
- text-align: center;
55
- }
56
-
57
- .gadwp-tdo-right {
58
- width: 35%;
59
- margin: 0px 10px 0px 0;
60
- text-align: left;
61
- font-weight: bold;
62
- vertical-align: middle;
63
- float: right;
64
- display: table;
65
- }
66
-
67
- .gadwp-online {
68
- font-size: 100px;
69
- font-weight: normal;
70
- line-height: 1em;
71
- margin: 0 auto;
72
- width: 80%;
73
- }
74
-
75
- .gadwp-bigtext {
76
- font-size: 14px;
77
- width: 100%;
78
- margin: 0 0;
79
- padding: 5px 5px 5px 5px;
80
- background: #fff;
81
- -moz-box-shadow: 0px 0px 3px 0px #BBB;
82
- -webkit-box-shadow: 0px 0px 3px 0px #BBB;
83
- box-shadow: 0px 0px 3px 0px #BBB;
84
- display: table;
85
- overflow: hidden;
86
- }
87
-
88
- .gadwp-bleft {
89
- float: left;
90
- width: 80%;
91
- }
92
-
93
- .gadwp-bright {
94
- float: right;
95
- width: 20%;
96
- }
97
-
98
- .gadwp-pgdetailsr {
99
- padding-left: 20px;
100
- text-align: right;
101
- }
102
-
103
- .gadwp-pgdetailsl {
104
- min-width: 250px;
105
- }
106
-
107
- [id^=gadwp-areachart-] {
108
- width: 98%;
109
- height: 100%;
110
- margin: 10px auto 10px 0;
111
- height: 250px;
112
- }
113
-
114
- .gadwp-floatwraper {
115
- display: table;
116
- width: 100%;
117
- height: 100%;
118
- }
119
-
120
- [id^=gadwp-piechart-].halfsize {
121
- width: 47%;
122
- margin: 10px 0 0 0;
123
- height: 200px;
124
- float: left;
125
- }
126
-
127
- [id^=gadwp-piechart-].floatleft {
128
- float: left;
129
- }
130
-
131
- [id^=gadwp-piechart-].floatright {
132
- float: right;
133
- }
134
-
135
- [id^=gadwp-tablechart-], [id^=gadwp-tablechart-] {
136
- width: 98%;
137
- height: 100%;
138
- margin: 10px auto 10px 0;
139
- }
140
-
141
- #dashboard-widgets-wrap .postbox {
142
- margin-right: 10px;
143
- }
144
-
145
- /* Admin Widget content */
146
- [id^=gadwp-progressbar-] {
147
- width: 100%;
148
- height: 3px;
149
- margin: 5px 0 0px 0;
150
- }
151
-
152
- [id^=gadwp-bottomstats-] {
153
- width: 100%;
154
- }
155
-
156
- [id^=gadwp-bottomstats-] .inside {
157
- display: table;
158
- margin: 0 auto;
159
- padding: 0px;
160
- }
161
-
162
- #gadwp-widget .inside .small-box {
163
- width: 30%;
164
- float: left;
165
- margin: 0 5px 10px 5px;
166
- background: #fff;
167
- text-align: center;
168
- -moz-box-shadow: 0px 0px 7px 0px #BBB;
169
- -webkit-box-shadow: 0px 0px 7px 0px #BBB;
170
- box-shadow: 0px 0px 7px 0px #BBB;
171
- }
172
-
173
- #gadwp-widget .inside .small-box h3 {
174
- font-size: 1em;
175
- color: #777;
176
- padding: 0px 5px 0px 5px;
177
- margin: 0px 0px 0px 0px;
178
- text-overflow: ellipsis;
179
- overflow: hidden;
180
- white-space: nowrap;
181
- }
182
-
183
- #gadwp-widget .inside .small-box p {
184
- font-size: 1.2em;
185
- margin: 0px 0px 2px 0px;
186
- }
187
-
188
- @media screen and (max-width: 410px) {
189
- [id^=gadwp-bottomstats-] .inside .small-box {
190
- width: 45%;
191
- }
192
  }
1
+ /**
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+
9
+ /* Real-Time content */
10
+ .gadwp-pline {
11
+ width: 100%;
12
+ margin: 0 0;
13
+ padding: 5px 0 5px 0;
14
+ background: #fff;
15
+ -moz-box-shadow: 0px 0px 3px 0px #BBB;
16
+ -webkit-box-shadow: 0px 0px 3px 0px #BBB;
17
+ box-shadow: 0px 0px 3px 0px #BBB;
18
+ display: table;
19
+ overflow: hidden;
20
+ }
21
+
22
+ .gadwp-pleft {
23
+ width: 90%;
24
+ float: left;
25
+ padding-left: 5px;
26
+ }
27
+
28
+ .gadwp-pright {
29
+ width: 5%;
30
+ float: right;
31
+ padding-right: 5px;
32
+ }
33
+
34
+ [id^=gadwp-realtime-] {
35
+ margin: 10px 0 0 0;
36
+ width: 100%;
37
+ }
38
+
39
+ .gadwp-rt-box {
40
+ width: 100%;
41
+ margin: 0 0;
42
+ background: #fff;
43
+ text-align: center;
44
+ -moz-box-shadow: 0px 0px 5px 0px #BBB;
45
+ -webkit-box-shadow: 0px 0px 5px 0px #BBB;
46
+ box-shadow: 0px 0px 5px 0px #BBB;
47
+ display: table;
48
+ }
49
+
50
+ .gadwp-tdo-left {
51
+ width: 60%;
52
+ padding: 33px 0;
53
+ float: left;
54
+ text-align: center;
55
+ }
56
+
57
+ .gadwp-tdo-right {
58
+ width: 35%;
59
+ margin: 0px 10px 0px 0;
60
+ text-align: left;
61
+ font-weight: bold;
62
+ vertical-align: middle;
63
+ float: right;
64
+ display: table;
65
+ }
66
+
67
+ .gadwp-online {
68
+ font-size: 100px;
69
+ font-weight: normal;
70
+ line-height: 1em;
71
+ margin: 0 auto;
72
+ width: 80%;
73
+ }
74
+
75
+ .gadwp-bigtext {
76
+ font-size: 14px;
77
+ width: 100%;
78
+ margin: 0 0;
79
+ padding: 5px 5px 5px 5px;
80
+ background: #fff;
81
+ -moz-box-shadow: 0px 0px 3px 0px #BBB;
82
+ -webkit-box-shadow: 0px 0px 3px 0px #BBB;
83
+ box-shadow: 0px 0px 3px 0px #BBB;
84
+ display: table;
85
+ overflow: hidden;
86
+ }
87
+
88
+ .gadwp-bleft {
89
+ float: left;
90
+ width: 80%;
91
+ }
92
+
93
+ .gadwp-bright {
94
+ float: right;
95
+ width: 20%;
96
+ }
97
+
98
+ .gadwp-pgdetailsr {
99
+ padding-left: 20px;
100
+ text-align: right;
101
+ }
102
+
103
+ .gadwp-pgdetailsl {
104
+ min-width: 250px;
105
+ }
106
+
107
+ [id^=gadwp-areachart-] {
108
+ width: 98%;
109
+ height: 100%;
110
+ margin: 10px auto 10px 0;
111
+ height: 250px;
112
+ }
113
+
114
+ .gadwp-floatwraper {
115
+ display: table;
116
+ width: 100%;
117
+ height: 100%;
118
+ }
119
+
120
+ [id^=gadwp-piechart-].halfsize {
121
+ width: 47%;
122
+ margin: 10px 0 0 0;
123
+ height: 200px;
124
+ float: left;
125
+ }
126
+
127
+ [id^=gadwp-piechart-].floatleft {
128
+ float: left;
129
+ }
130
+
131
+ [id^=gadwp-piechart-].floatright {
132
+ float: right;
133
+ }
134
+
135
+ [id^=gadwp-tablechart-], [id^=gadwp-tablechart-] {
136
+ width: 98%;
137
+ height: 100%;
138
+ margin: 10px auto 10px 0;
139
+ }
140
+
141
+ #dashboard-widgets-wrap .postbox {
142
+ margin-right: 10px;
143
+ }
144
+
145
+ /* Admin Widget content */
146
+ [id^=gadwp-progressbar-] {
147
+ width: 100%;
148
+ height: 3px;
149
+ margin: 5px 0 0px 0;
150
+ }
151
+
152
+ [id^=gadwp-bottomstats-] {
153
+ width: 100%;
154
+ }
155
+
156
+ [id^=gadwp-bottomstats-] .inside {
157
+ display: table;
158
+ margin: 0 auto;
159
+ padding: 0px;
160
+ }
161
+
162
+ #gadwp-widget .inside .small-box {
163
+ width: 30%;
164
+ float: left;
165
+ margin: 0 5px 10px 5px;
166
+ background: #fff;
167
+ text-align: center;
168
+ -moz-box-shadow: 0px 0px 7px 0px #BBB;
169
+ -webkit-box-shadow: 0px 0px 7px 0px #BBB;
170
+ box-shadow: 0px 0px 7px 0px #BBB;
171
+ }
172
+
173
+ #gadwp-widget .inside .small-box h3 {
174
+ font-size: 1em;
175
+ color: #777;
176
+ padding: 0px 5px 0px 5px;
177
+ margin: 0px 0px 0px 0px;
178
+ text-overflow: ellipsis;
179
+ overflow: hidden;
180
+ white-space: nowrap;
181
+ }
182
+
183
+ #gadwp-widget .inside .small-box p {
184
+ font-size: 1.2em;
185
+ margin: 0px 0px 2px 0px;
186
+ }
187
+
188
+ @media screen and (max-width: 410px) {
189
+ [id^=gadwp-bottomstats-] .inside .small-box {
190
+ width: 45%;
191
+ }
192
  }
admin/css/gadwp.css CHANGED
@@ -1,206 +1,206 @@
1
- /**
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
-
9
- /* Tab navigation */
10
- #gadwp-events, #gadwp-custom, #gadwp-advanced, #gadwp-exclude, #gadwp-config {
11
- display: none;
12
- }
13
-
14
- /* Options pages */
15
- table.gadwp-settings-options {
16
- padding-left: 10px;
17
- width: 100%;
18
- }
19
-
20
- .gadwp-settings-options td {
21
- padding: 0px 5px 5px 5px;
22
- }
23
-
24
- td.gadwp-settings-title, td.info {
25
- width: 130px;
26
- padding-left: 20px;
27
- }
28
-
29
- td.gadwp-settings-title-s {
30
- width: 300px;
31
- }
32
-
33
- .gadwp-help {
34
- padding-left: 15px;
35
- }
36
-
37
- td.gadwp-settings-info {
38
- padding-bottom: 15px;
39
- }
40
-
41
- td.gadwp-settings-title label {
42
- font-weight: bold;
43
- }
44
-
45
- .gadash-title {
46
- float: left;
47
- margin-right: 10px;
48
- margin-top: 2px;
49
- clear: left;
50
- }
51
-
52
- .gadash-desc {
53
- font-size: 1em;
54
- }
55
-
56
- .gadash-top {
57
- vertical-align: top;
58
- }
59
-
60
- pre.gadwp-settings-logdata {
61
- white-space: pre-wrap;
62
- }
63
-
64
- td.gadwp-settings-roles {
65
- padding-bottom: 15px;
66
- }
67
-
68
- #ga_speed_samplerate, #ga_realtime_pages {
69
- width: 50px;
70
- }
71
-
72
- #gapi-access-code {
73
- color: red !important;
74
- }
75
-
76
- #poststuff.gadwp h2 {
77
- padding-bottom: 0;
78
- font-size: 19.5px;
79
- font-weight: normal;
80
- padding: 0;
81
- margin: 20px 0 15px 0;
82
- }
83
-
84
- #poststuff.gadwp h2.nav-tab-wrapper {
85
- border-bottom: 1px solid #ccc;
86
- padding-bottom: 0;
87
- }
88
-
89
- /* Options pages ON/OFF Switch */
90
- .button-primary.gadwp-settings-switchoo {
91
- position: relative;
92
- width: 50px;
93
- float: left;
94
- border: none;
95
- padding: 0;
96
- height: 22px;
97
- -moz-box-shadow: none;
98
- -webkit-box-shadow: none;
99
- -o-box-shadow: none;
100
- box-shadow: none;
101
- -webkit-user-select: none;
102
- -moz-user-select: none;
103
- -ms-user-select: none;
104
- }
105
-
106
- input.gadwp-settings-switchoo-checkbox {
107
- display: none;
108
- }
109
-
110
- .gadwp-settings-switchoo-label {
111
- display: block;
112
- overflow: hidden;
113
- cursor: pointer;
114
- background: transparent;
115
- border: 1px solid #ddd;
116
- border-radius: 2px;
117
- text-shadow: none;
118
- }
119
-
120
- .gadwp-settings-switchoo-inner {
121
- width: 200%;
122
- margin-left: -100%;
123
- border-radius: 2px;
124
- -moz-transition: margin 0.2s ease-in 0s;
125
- -webkit-transition: margin 0.2s ease-in 0s;
126
- -o-transition: margin 0.2s ease-in 0s;
127
- transition: margin 0.2s ease-in 0s;
128
- }
129
-
130
- .gadwp-settings-switchoo-inner:before, .gadwp-settings-switchoo-inner:after {
131
- float: left;
132
- width: 50%;
133
- font-weight: normal;
134
- -moz-box-sizing: border-box;
135
- -webkit-box-sizing: border-box;
136
- -o-box-sizing: border-box;
137
- box-sizing: border-box;
138
- height: 22px;
139
- line-height: 22px;
140
- font-size: 12px;
141
- text-shadow: none;
142
- }
143
-
144
- .gadwp-settings-switchoo-inner:before {
145
- content: "On";
146
- padding-left: 5px;
147
- border-bottom: none;
148
- /* background-color: #00a0d2;
149
- color: #fff; /* inherit from button props */
150
- }
151
-
152
- .gadwp-settings-switchoo-inner:after {
153
- content: "Off";
154
- padding-right: 5px;
155
- background-color: #ddd;
156
- text-align: right;
157
- }
158
-
159
- .gadwp-settings-switchoo-switch {
160
- width: 22px;
161
- height: 22px;
162
- background: #fff;
163
- color: #ddd;
164
- border: 1px solid #ddd;
165
- border-radius: 2px;
166
- position: absolute;
167
- top: 0;
168
- bottom: 0;
169
- right: 27px;
170
- -moz-transition: all 0.2s ease-in 0s;
171
- -webkit-transition: all 0.2s ease-in 0s;
172
- -o-transition: all 0.2s ease-in 0s;
173
- transition: all 0.2s ease-in 0s;
174
- }
175
-
176
- .gadwp-settings-switchoo-switch:hover {
177
- color: #aaa;
178
- border-color: #aaa;
179
- }
180
-
181
- .gadwp-settings-switchoo-switch:after {
182
- margin: 0;
183
- outline: 0;
184
- display: inline-block;
185
- font: 400 16px/16px dashicons;
186
- content: "\f228";
187
- padding: 3px 0 0 3px;
188
- text-align: left;
189
- text-decoration: none;
190
- -webkit-font-smoothing: antialiased;
191
- -moz-osx-font-smoothing: grayscale;
192
- }
193
-
194
- .gadwp-settings-switchoo-checkbox:checked+.gadwp-settings-switchoo-label .gadwp-settings-switchoo-inner {
195
- margin-left: 0;
196
- }
197
-
198
- .gadwp-settings-switchoo-checkbox:checked+.gadwp-settings-switchoo-label .gadwp-settings-switchoo-switch {
199
- right: 0px;
200
- }
201
-
202
- .switch-desc {
203
- float: left;
204
- margin-left: 10px;
205
- line-height: 20px;
206
  }
1
+ /**
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+
9
+ /* Tab navigation */
10
+ #gadwp-events, #gadwp-custom, #gadwp-advanced, #gadwp-exclude, #gadwp-config {
11
+ display: none;
12
+ }
13
+
14
+ /* Options pages */
15
+ table.gadwp-settings-options {
16
+ padding-left: 10px;
17
+ width: 100%;
18
+ }
19
+
20
+ .gadwp-settings-options td {
21
+ padding: 0px 5px 5px 5px;
22
+ }
23
+
24
+ td.gadwp-settings-title, td.info {
25
+ width: 130px;
26
+ padding-left: 20px;
27
+ }
28
+
29
+ td.gadwp-settings-title-s {
30
+ width: 300px;
31
+ }
32
+
33
+ .gadwp-help {
34
+ padding-left: 15px;
35
+ }
36
+
37
+ td.gadwp-settings-info {
38
+ padding-bottom: 15px;
39
+ }
40
+
41
+ td.gadwp-settings-title label {
42
+ font-weight: bold;
43
+ }
44
+
45
+ .gadash-title {
46
+ float: left;
47
+ margin-right: 10px;
48
+ margin-top: 2px;
49
+ clear: left;
50
+ }
51
+
52
+ .gadash-desc {
53
+ font-size: 1em;
54
+ }
55
+
56
+ .gadash-top {
57
+ vertical-align: top;
58
+ }
59
+
60
+ pre.gadwp-settings-logdata {
61
+ white-space: pre-wrap;
62
+ }
63
+
64
+ td.gadwp-settings-roles {
65
+ padding-bottom: 15px;
66
+ }
67
+
68
+ #ga_speed_samplerate, #ga_realtime_pages {
69
+ width: 50px;
70
+ }
71
+
72
+ #gapi-access-code {
73
+ color: red !important;
74
+ }
75
+
76
+ #poststuff.gadwp h2 {
77
+ padding-bottom: 0;
78
+ font-size: 19.5px;
79
+ font-weight: normal;
80
+ padding: 0;
81
+ margin: 20px 0 15px 0;
82
+ }
83
+
84
+ #poststuff.gadwp h2.nav-tab-wrapper {
85
+ border-bottom: 1px solid #ccc;
86
+ padding-bottom: 0;
87
+ }
88
+
89
+ /* Options pages ON/OFF Switch */
90
+ .button-primary.gadwp-settings-switchoo {
91
+ position: relative;
92
+ width: 50px;
93
+ float: left;
94
+ border: none;
95
+ padding: 0;
96
+ height: 22px;
97
+ -moz-box-shadow: none;
98
+ -webkit-box-shadow: none;
99
+ -o-box-shadow: none;
100
+ box-shadow: none;
101
+ -webkit-user-select: none;
102
+ -moz-user-select: none;
103
+ -ms-user-select: none;
104
+ }
105
+
106
+ input.gadwp-settings-switchoo-checkbox {
107
+ display: none;
108
+ }
109
+
110
+ .gadwp-settings-switchoo-label {
111
+ display: block;
112
+ overflow: hidden;
113
+ cursor: pointer;
114
+ background: transparent;
115
+ border: 1px solid #ddd;
116
+ border-radius: 2px;
117
+ text-shadow: none;
118
+ }
119
+
120
+ .gadwp-settings-switchoo-inner {
121
+ width: 200%;
122
+ margin-left: -100%;
123
+ border-radius: 2px;
124
+ -moz-transition: margin 0.2s ease-in 0s;
125
+ -webkit-transition: margin 0.2s ease-in 0s;
126
+ -o-transition: margin 0.2s ease-in 0s;
127
+ transition: margin 0.2s ease-in 0s;
128
+ }
129
+
130
+ .gadwp-settings-switchoo-inner:before, .gadwp-settings-switchoo-inner:after {
131
+ float: left;
132
+ width: 50%;
133
+ font-weight: normal;
134
+ -moz-box-sizing: border-box;
135
+ -webkit-box-sizing: border-box;
136
+ -o-box-sizing: border-box;
137
+ box-sizing: border-box;
138
+ height: 22px;
139
+ line-height: 22px;
140
+ font-size: 12px;
141
+ text-shadow: none;
142
+ }
143
+
144
+ .gadwp-settings-switchoo-inner:before {
145
+ content: "On";
146
+ padding-left: 5px;
147
+ border-bottom: none;
148
+ /* background-color: #00a0d2;
149
+ color: #fff; /* inherit from button props */
150
+ }
151
+
152
+ .gadwp-settings-switchoo-inner:after {
153
+ content: "Off";
154
+ padding-right: 5px;
155
+ background-color: #ddd;
156
+ text-align: right;
157
+ }
158
+
159
+ .gadwp-settings-switchoo-switch {
160
+ width: 22px;
161
+ height: 22px;
162
+ background: #fff;
163
+ color: #ddd;
164
+ border: 1px solid #ddd;
165
+ border-radius: 2px;
166
+ position: absolute;
167
+ top: 0;
168
+ bottom: 0;
169
+ right: 27px;
170
+ -moz-transition: all 0.2s ease-in 0s;
171
+ -webkit-transition: all 0.2s ease-in 0s;
172
+ -o-transition: all 0.2s ease-in 0s;
173
+ transition: all 0.2s ease-in 0s;
174
+ }
175
+
176
+ .gadwp-settings-switchoo-switch:hover {
177
+ color: #aaa;
178
+ border-color: #aaa;
179
+ }
180
+
181
+ .gadwp-settings-switchoo-switch:after {
182
+ margin: 0;
183
+ outline: 0;
184
+ display: inline-block;
185
+ font: 400 16px/16px dashicons;
186
+ content: "\f228";
187
+ padding: 3px 0 0 3px;
188
+ text-align: left;
189
+ text-decoration: none;
190
+ -webkit-font-smoothing: antialiased;
191
+ -moz-osx-font-smoothing: grayscale;
192
+ }
193
+
194
+ .gadwp-settings-switchoo-checkbox:checked+.gadwp-settings-switchoo-label .gadwp-settings-switchoo-inner {
195
+ margin-left: 0;
196
+ }
197
+
198
+ .gadwp-settings-switchoo-checkbox:checked+.gadwp-settings-switchoo-label .gadwp-settings-switchoo-switch {
199
+ right: 0px;
200
+ }
201
+
202
+ .switch-desc {
203
+ float: left;
204
+ margin-left: 10px;
205
+ line-height: 20px;
206
  }
admin/css/item-reports.css CHANGED
@@ -1,124 +1,124 @@
1
- /**
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
-
9
- /* Backend Item Reports */
10
- .column-gadwp_stats {
11
- width: 70px;
12
- }
13
-
14
- .gadwp-icon {
15
- color: #555;
16
- }
17
-
18
- .gadwp-icon:hover {
19
- color: #2ea2cc;
20
- }
21
-
22
- .gadwp-icon-oldwp {
23
- padding-top: 5px;
24
- }
25
-
26
- [id^=gadwp-container-] {
27
- width: 480px;
28
- }
29
-
30
- [id^=gadwp-areachart-] {
31
- height: 280px;
32
- }
33
-
34
- [id^=gadwp-progressbar-] {
35
- width: 100%;
36
- height: 3px;
37
- margin: 5px 0 0px 0;
38
- }
39
-
40
- [id^=gadwp-bottomstats-] {
41
- width: 100%;
42
- }
43
-
44
- [id^=gadwp-bottomstats-] .inside {
45
- display: table;
46
- margin: 0 auto;
47
- padding: 0px;
48
- }
49
-
50
- [id^=gadwp-bottomstats-] .inside .small-box {
51
- width: 31.2%;
52
- float: left;
53
- margin: 10px 5px 10px 5px;
54
- background: #fff;
55
- text-align: center;
56
- -moz-box-shadow: 0px 0px 7px 0px #BBB;
57
- -webkit-box-shadow: 0px 0px 7px 0px #BBB;
58
- box-shadow: 0px 0px 7px 0px #BBB;
59
- }
60
-
61
- [id^=gadwp-bottomstats-] .inside .small-box h3 {
62
- font-family: 'Open Sans', sans-serif;
63
- font-size: 1em;
64
- color: #777;
65
- padding: 0px 5px 0px 5px;
66
- margin: 0px 0px 0px 0px;
67
- text-overflow: ellipsis;
68
- overflow: hidden;
69
- white-space: nowrap;
70
- }
71
-
72
- [id^=gadwp-bottomstats-] .inside .small-box p {
73
- font-size: 1.2em;
74
- margin: 0px 0px 2px 0px;
75
- }
76
-
77
- .gadwp-floatwraper {
78
- display: table;
79
- width: 100%;
80
- height: 100%;
81
- }
82
-
83
- [id^=gadwp-piechart-].halfsize {
84
- width: 47%;
85
- margin: 10px 0 0 0;
86
- height: 200px;
87
- float: left;
88
- }
89
-
90
- [id^=gadwp-piechart-].floatleft {
91
- float: left;
92
- }
93
-
94
- [id^=gadwp-piechart-].floatright {
95
- float: right;
96
- }
97
-
98
- [id^=gadwp-tablechart-], [id^=gadwp-tablechart-] {
99
- margin: 10px 0 0 0;
100
- }
101
-
102
- .gadwp .ui-dialog-titlebar {
103
- font-size: 1.1em;
104
- text-overflow: ellipsis;
105
- overflow: hidden;
106
- }
107
-
108
- @media screen and (max-width: 500px) {
109
- [id^=gadwp-container-] {
110
- width: 410px;
111
- }
112
- [id^=gadwp-bottomstats-] .inside .small-box {
113
- width: 30.8%;
114
- }
115
- }
116
-
117
- @media screen and (max-width: 410px) {
118
- [id^=gadwp-container-] {
119
- width: 260px;
120
- }
121
- [id^=gadwp-bottomstats-] .inside .small-box {
122
- width: 46%;
123
- }
124
  }
1
+ /**
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+
9
+ /* Backend Item Reports */
10
+ .column-gadwp_stats {
11
+ width: 70px;
12
+ }
13
+
14
+ .gadwp-icon {
15
+ color: #555;
16
+ }
17
+
18
+ .gadwp-icon:hover {
19
+ color: #2ea2cc;
20
+ }
21
+
22
+ .gadwp-icon-oldwp {
23
+ padding-top: 5px;
24
+ }
25
+
26
+ [id^=gadwp-container-] {
27
+ width: 480px;
28
+ }
29
+
30
+ [id^=gadwp-areachart-] {
31
+ height: 280px;
32
+ }
33
+
34
+ [id^=gadwp-progressbar-] {
35
+ width: 100%;
36
+ height: 3px;
37
+ margin: 5px 0 0px 0;
38
+ }
39
+
40
+ [id^=gadwp-bottomstats-] {
41
+ width: 100%;
42
+ }
43
+
44
+ [id^=gadwp-bottomstats-] .inside {
45
+ display: table;
46
+ margin: 0 auto;
47
+ padding: 0px;
48
+ }
49
+
50
+ [id^=gadwp-bottomstats-] .inside .small-box {
51
+ width: 31.2%;
52
+ float: left;
53
+ margin: 10px 5px 10px 5px;
54
+ background: #fff;
55
+ text-align: center;
56
+ -moz-box-shadow: 0px 0px 7px 0px #BBB;
57
+ -webkit-box-shadow: 0px 0px 7px 0px #BBB;
58
+ box-shadow: 0px 0px 7px 0px #BBB;
59
+ }
60
+
61
+ [id^=gadwp-bottomstats-] .inside .small-box h3 {
62
+ font-family: 'Open Sans', sans-serif;
63
+ font-size: 1em;
64
+ color: #777;
65
+ padding: 0px 5px 0px 5px;
66
+ margin: 0px 0px 0px 0px;
67
+ text-overflow: ellipsis;
68
+ overflow: hidden;
69
+ white-space: nowrap;
70
+ }
71
+
72
+ [id^=gadwp-bottomstats-] .inside .small-box p {
73
+ font-size: 1.2em;
74
+ margin: 0px 0px 2px 0px;
75
+ }
76
+
77
+ .gadwp-floatwraper {
78
+ display: table;
79
+ width: 100%;
80
+ height: 100%;
81
+ }
82
+
83
+ [id^=gadwp-piechart-].halfsize {
84
+ width: 47%;
85
+ margin: 10px 0 0 0;
86
+ height: 200px;
87
+ float: left;
88
+ }
89
+
90
+ [id^=gadwp-piechart-].floatleft {
91
+ float: left;
92
+ }
93
+
94
+ [id^=gadwp-piechart-].floatright {
95
+ float: right;
96
+ }
97
+
98
+ [id^=gadwp-tablechart-], [id^=gadwp-tablechart-] {
99
+ margin: 10px 0 0 0;
100
+ }
101
+
102
+ .gadwp .ui-dialog-titlebar {
103
+ font-size: 1.1em;
104
+ text-overflow: ellipsis;
105
+ overflow: hidden;
106
+ }
107
+
108
+ @media screen and (max-width: 500px) {
109
+ [id^=gadwp-container-] {
110
+ width: 410px;
111
+ }
112
+ [id^=gadwp-bottomstats-] .inside .small-box {
113
+ width: 30.8%;
114
+ }
115
+ }
116
+
117
+ @media screen and (max-width: 410px) {
118
+ [id^=gadwp-container-] {
119
+ width: 260px;
120
+ }
121
+ [id^=gadwp-bottomstats-] .inside .small-box {
122
+ width: 46%;
123
+ }
124
  }
admin/item-reports.php CHANGED
@@ -1,56 +1,56 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Backend_Item_Reports' ) ) {
15
-
16
- final class GADWP_Backend_Item_Reports {
17
-
18
- private $gadwp;
19
-
20
- public function __construct() {
21
- $this->gadwp = GADWP();
22
-
23
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && 1 == $this->gadwp->config->options['backend_item_reports'] ) {
24
- // Add custom column in Posts List
25
- add_filter( 'manage_posts_columns', array( $this, 'add_columns' ) );
26
-
27
- // Populate custom column in Posts List
28
- add_action( 'manage_posts_custom_column', array( $this, 'add_icons' ), 10, 2 );
29
-
30
- // Add custom column in Pages List
31
- add_filter( 'manage_pages_columns', array( $this, 'add_columns' ) );
32
-
33
- // Populate custom column in Pages List
34
- add_action( 'manage_pages_custom_column', array( $this, 'add_icons' ), 10, 2 );
35
- }
36
- }
37
-
38
- public function add_icons( $column, $id ) {
39
- global $wp_version;
40
-
41
- if ( $column != 'gadwp_stats' ) {
42
- return;
43
- }
44
-
45
- if ( version_compare( $wp_version, '3.8.0', '>=' ) ) {
46
- echo '<a id="gadwp-' . $id . '" title="' . get_the_title( $id ) . '" href="#' . $id . '" class="gadwp-icon dashicons-before dashicons-chart-area"></a>';
47
- } else {
48
- echo '<a id="gadwp-' . $id . '" title="' . get_the_title( $id ) . '" href="#' . $id . '"><img class="gadwp-icon-oldwp" src="' . GADWP_URL . 'admin/images/gadash-icon.png"</a>';
49
- }
50
- }
51
-
52
- public function add_columns( $columns ) {
53
- return array_merge( $columns, array( 'gadwp_stats' => __( 'Analytics', 'google-analytics-dashboard-for-wp' ) ) );
54
- }
55
- }
56
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Backend_Item_Reports' ) ) {
15
+
16
+ final class GADWP_Backend_Item_Reports {
17
+
18
+ private $gadwp;
19
+
20
+ public function __construct() {
21
+ $this->gadwp = GADWP();
22
+
23
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && 1 == $this->gadwp->config->options['backend_item_reports'] ) {
24
+ // Add custom column in Posts List
25
+ add_filter( 'manage_posts_columns', array( $this, 'add_columns' ) );
26
+
27
+ // Populate custom column in Posts List
28
+ add_action( 'manage_posts_custom_column', array( $this, 'add_icons' ), 10, 2 );
29
+
30
+ // Add custom column in Pages List
31
+ add_filter( 'manage_pages_columns', array( $this, 'add_columns' ) );
32
+
33
+ // Populate custom column in Pages List
34
+ add_action( 'manage_pages_custom_column', array( $this, 'add_icons' ), 10, 2 );
35
+ }
36
+ }
37
+
38
+ public function add_icons( $column, $id ) {
39
+ global $wp_version;
40
+
41
+ if ( $column != 'gadwp_stats' ) {
42
+ return;
43
+ }
44
+
45
+ if ( version_compare( $wp_version, '3.8.0', '>=' ) ) {
46
+ echo '<a id="gadwp-' . $id . '" title="' . get_the_title( $id ) . '" href="#' . $id . '" class="gadwp-icon dashicons-before dashicons-chart-area"></a>';
47
+ } else {
48
+ echo '<a id="gadwp-' . $id . '" title="' . get_the_title( $id ) . '" href="#' . $id . '"><img class="gadwp-icon-oldwp" src="' . GADWP_URL . 'admin/images/gadash-icon.png"</a>';
49
+ }
50
+ }
51
+
52
+ public function add_columns( $columns ) {
53
+ return array_merge( $columns, array( 'gadwp_stats' => __( 'Analytics', 'google-analytics-dashboard-for-wp' ) ) );
54
+ }
55
+ }
56
+ }
admin/js/settings.js CHANGED
@@ -1,40 +1,40 @@
1
- /*-
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
-
9
- /*
10
- * Navigation Tabs
11
- */
12
- jQuery( document ).ready( function () {
13
- if ( window.location.href.indexOf( "page=gadash_" ) != -1 ) {
14
- var ident = 'basic';
15
-
16
- if ( window.location.hash ) {
17
- ident = window.location.hash.split( '#' )[ 2 ].split( '-' )[ 1 ];
18
- } else if ( window.location.href.indexOf( "page=gadash_errors_debugging" ) != -1 ) {
19
- ident = 'errors';
20
- }
21
-
22
- jQuery( ".nav-tab-wrapper a" ).each( function ( index ) {
23
- jQuery( this ).removeClass( "nav-tab-active" );
24
- jQuery( "#" + this.hash.split( '#' )[ 2 ] ).hide();
25
- } );
26
- jQuery( "#tab-" + ident ).addClass( "nav-tab-active" );
27
- jQuery( "#gadwp-" + ident ).show();
28
- }
29
-
30
- jQuery( 'a[href^="#"]' ).click( function ( e ) {
31
- if ( window.location.href.indexOf( "page=gadash_" ) != -1 ) {
32
- jQuery( ".nav-tab-wrapper a" ).each( function ( index ) {
33
- jQuery( this ).removeClass( "nav-tab-active" );
34
- jQuery( "#" + this.hash.split( '#' )[ 2 ] ).hide();
35
- } );
36
- jQuery( this ).addClass( "nav-tab-active" );
37
- jQuery( "#" + this.hash.split( '#' )[ 2 ] ).show();
38
- }
39
- } );
40
  } );
1
+ /*-
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+
9
+ /*
10
+ * Navigation Tabs
11
+ */
12
+ jQuery( document ).ready( function () {
13
+ if ( window.location.href.indexOf( "page=gadash_" ) != -1 ) {
14
+ var ident = 'basic';
15
+
16
+ if ( window.location.hash ) {
17
+ ident = window.location.hash.split( '#' )[ 2 ].split( '-' )[ 1 ];
18
+ } else if ( window.location.href.indexOf( "page=gadash_errors_debugging" ) != -1 ) {
19
+ ident = 'errors';
20
+ }
21
+
22
+ jQuery( ".nav-tab-wrapper a" ).each( function ( index ) {
23
+ jQuery( this ).removeClass( "nav-tab-active" );
24
+ jQuery( "#" + this.hash.split( '#' )[ 2 ] ).hide();
25
+ } );
26
+ jQuery( "#tab-" + ident ).addClass( "nav-tab-active" );
27
+ jQuery( "#gadwp-" + ident ).show();
28
+ }
29
+
30
+ jQuery( 'a[href^="#"]' ).click( function ( e ) {
31
+ if ( window.location.href.indexOf( "page=gadash_" ) != -1 ) {
32
+ jQuery( ".nav-tab-wrapper a" ).each( function ( index ) {
33
+ jQuery( this ).removeClass( "nav-tab-active" );
34
+ jQuery( "#" + this.hash.split( '#' )[ 2 ] ).hide();
35
+ } );
36
+ jQuery( this ).addClass( "nav-tab-active" );
37
+ jQuery( "#" + this.hash.split( '#' )[ 2 ] ).show();
38
+ }
39
+ } );
40
  } );
admin/js/ui.js CHANGED
@@ -1,26 +1,26 @@
1
- /*-
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
-
9
- "use strict";
10
-
11
- jQuery( document ).ready( function () {
12
-
13
- var gadwp_ui = {
14
- action : 'gadwp_dismiss_notices',
15
- gadwp_security_dismiss_notices : gadwp_ui_data.security,
16
- }
17
-
18
- jQuery( "#gadwp-notice .notice-dismiss" ).click( function () {
19
- jQuery.post( gadwp_ui_data.ajaxurl, gadwp_ui );
20
- } );
21
-
22
- if ( gadwp_ui_data.ed_bubble != '' ) {
23
- jQuery( '#toplevel_page_gadash_settings li > a[href*="page=gadash_errors_debugging"]' ).append( '&nbsp;<span class="awaiting-mod count-1"><span class="pending-count" style="padding:0 7px;">' + gadwp_ui_data.ed_bubble + '</span></span>' );
24
- }
25
-
26
  } );
1
+ /*-
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+
9
+ "use strict";
10
+
11
+ jQuery( document ).ready( function () {
12
+
13
+ var gadwp_ui = {
14
+ action : 'gadwp_dismiss_notices',
15
+ gadwp_security_dismiss_notices : gadwp_ui_data.security,
16
+ }
17
+
18
+ jQuery( "#gadwp-notice .notice-dismiss" ).click( function () {
19
+ jQuery.post( gadwp_ui_data.ajaxurl, gadwp_ui );
20
+ } );
21
+
22
+ if ( gadwp_ui_data.ed_bubble != '' ) {
23
+ jQuery( '#toplevel_page_gadash_settings li > a[href*="page=gadash_errors_debugging"]' ).append( '&nbsp;<span class="awaiting-mod count-1"><span class="pending-count" style="padding:0 7px;">' + gadwp_ui_data.ed_bubble + '</span></span>' );
24
+ }
25
+
26
  } );
admin/js/wp-color-picker-script.js CHANGED
@@ -1,11 +1,11 @@
1
- /*-
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
-
9
- jQuery( document ).ready( function () {
10
- jQuery( '.ga_dash_style' ).wpColorPicker();
11
  } );
1
+ /*-
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+
9
+ jQuery( document ).ready( function () {
10
+ jQuery( '.ga_dash_style' ).wpColorPicker();
11
  } );
admin/settings.php CHANGED
@@ -1,1358 +1,1358 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- final class GADWP_Settings {
15
-
16
- private static function update_options( $who ) {
17
- $gadwp = GADWP();
18
- $network_settings = false;
19
- $options = $gadwp->config->options; // Get current options
20
- if ( isset( $_POST['options']['ga_dash_hidden'] ) && isset( $_POST['options'] ) && ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) && $who != 'Reset' ) {
21
- $new_options = $_POST['options'];
22
- if ( $who == 'tracking' ) {
23
- $options['ga_dash_anonim'] = 0;
24
- $options['ga_event_tracking'] = 0;
25
- $options['ga_enhanced_links'] = 0;
26
- $options['ga_dash_remarketing'] = 0;
27
- $options['ga_dash_adsense'] = 0;
28
- $options['ga_event_bouncerate'] = 0;
29
- $options['ga_crossdomain_tracking'] = 0;
30
- $options['ga_aff_tracking'] = 0;
31
- $options['ga_hash_tracking'] = 0;
32
- if ( isset( $_POST['options']['ga_tracking_code'] ) ) {
33
- $new_options['ga_tracking_code'] = trim( $new_options['ga_tracking_code'], "\t" );
34
- }
35
- if ( empty( $new_options['ga_track_exclude'] ) ) {
36
- $new_options['ga_track_exclude'] = array();
37
- }
38
- } else if ( $who == 'backend' ) {
39
- $options['switch_profile'] = 0;
40
- $options['backend_item_reports'] = 0;
41
- $options['dashboard_widget'] = 0;
42
- if ( empty( $new_options['ga_dash_access_back'] ) ) {
43
- $new_options['ga_dash_access_back'][] = 'administrator';
44
- }
45
- } else if ( $who == 'frontend' ) {
46
- $options['frontend_item_reports'] = 0;
47
- if ( empty( $new_options['ga_dash_access_front'] ) ) {
48
- $new_options['ga_dash_access_front'][] = 'administrator';
49
- }
50
- } else if ( $who == 'general' ) {
51
- $options['ga_dash_userapi'] = 0;
52
- if ( ! is_multisite() ) {
53
- $options['automatic_updates_minorversion'] = 0;
54
- }
55
- } else if ( $who == 'network' ) {
56
- $options['ga_dash_userapi'] = 0;
57
- $options['ga_dash_network'] = 0;
58
- $options['ga_dash_excludesa'] = 0;
59
- $options['automatic_updates_minorversion'] = 0;
60
- $network_settings = true;
61
- }
62
- $options = array_merge( $options, $new_options );
63
- $gadwp->config->options = $options;
64
- $gadwp->config->set_plugin_options( $network_settings );
65
- }
66
- return $options;
67
- }
68
-
69
- private static function navigation_tabs( $tabs ) {
70
- echo '<h2 class="nav-tab-wrapper">';
71
- foreach ( $tabs as $tab => $name ) {
72
- echo "<a class='nav-tab' id='tab-$tab' href='#top#gadwp-$tab'>$name</a>";
73
- }
74
- echo '</h2>';
75
- }
76
-
77
- public static function frontend_settings() {
78
- $gadwp = GADWP();
79
- if ( ! current_user_can( 'manage_options' ) ) {
80
- return;
81
- }
82
- $options = self::update_options( 'frontend' );
83
- if ( isset( $_POST['options']['ga_dash_hidden'] ) ) {
84
- $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
85
- if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
86
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
87
- }
88
- }
89
- if ( ! $gadwp->config->options['ga_dash_tableid_jail'] || ! $gadwp->config->options['ga_dash_token'] ) {
90
- $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
91
- }
92
- ?>
93
- <form name="ga_dash_form" method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
94
- <div class="wrap">
95
- <?php echo "<h2>" . __( "Google Analytics Frontend Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?><hr>
96
- </div>
97
- <div id="poststuff" class="gadwp">
98
- <div id="post-body" class="metabox-holder columns-2">
99
- <div id="post-body-content">
100
- <div class="settings-wrapper">
101
- <div class="inside">
102
- <?php if (isset($message)) echo $message; ?>
103
- <table class="gadwp-settings-options">
104
- <tr>
105
- <td colspan="2"><?php echo "<h2>" . __( "Permissions", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
106
- </tr>
107
- <tr>
108
- <td class="roles gadwp-settings-title"><label for="ga_dash_access_front"><?php _e("Show stats to:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
109
- <td class="gadwp-settings-roles">
110
- <?php
111
- if ( ! isset( $wp_roles ) ) {
112
- $wp_roles = new WP_Roles();
113
- }
114
- $i = 0;
115
- ?>
116
- <table>
117
- <tr>
118
- <?php
119
- foreach ( $wp_roles->role_names as $role => $name ) {
120
- if ( $role != 'subscriber' ) {
121
- $i++;
122
- ?>
123
- <td><label> <input type="checkbox" name="options[ga_dash_access_front][]" value="<?php echo $role; ?>" <?php if (in_array($role,$options['ga_dash_access_front']) || $role=='administrator') echo 'checked="checked"'; if ($role=='administrator') echo 'disabled="disabled"';?> /><?php echo $name; ?>
124
- </label></td>
125
- <?php
126
- }
127
- if ( $i % 4 == 0 ) {
128
- ?>
129
- </tr>
130
- <tr>
131
- <?php
132
- }
133
- }
134
- ?>
135
- </table>
136
- </td>
137
- </tr>
138
- <tr>
139
- <td colspan="2" class="gadwp-settings-title">
140
- <div class="button-primary gadwp-settings-switchoo">
141
- <input type="checkbox" name="options[frontend_item_reports]" value="1" class="gadwp-settings-switchoo-checkbox" id="frontend_item_reports" <?php checked( $options['frontend_item_reports'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="frontend_item_reports">
142
- <div class="gadwp-settings-switchoo-inner"></div>
143
- <div class="gadwp-settings-switchoo-switch"></div>
144
- </label>
145
- </div>
146
- <div class="switch-desc"><?php echo " ".__("enable web page reports on frontend", 'google-analytics-dashboard-for-wp' );?></div>
147
- </td>
148
- </tr>
149
- <tr>
150
- <td colspan="2"><hr></td>
151
- </tr>
152
- <tr>
153
- <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
154
- </tr>
155
- </table>
156
- <input type="hidden" name="options[ga_dash_hidden]" value="Y">
157
- <?php wp_nonce_field('gadash_form','gadash_security');?>
158
- </form>
159
- <?php
160
- self::output_sidebar();
161
- }
162
-
163
- public static function backend_settings() {
164
- $gadwp = GADWP();
165
- if ( ! current_user_can( 'manage_options' ) ) {
166
- return;
167
- }
168
- $options = self::update_options( 'backend' );
169
- if ( isset( $_POST['options']['ga_dash_hidden'] ) ) {
170
- $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
171
- if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
172
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
173
- }
174
- }
175
- if ( ! $gadwp->config->options['ga_dash_tableid_jail'] || ! $gadwp->config->options['ga_dash_token'] ) {
176
- $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
177
- }
178
- ?>
179
- <form name="ga_dash_form" method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
180
- <div class="wrap">
181
- <?php echo "<h2>" . __( "Google Analytics Backend Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?><hr>
182
- </div>
183
- <div id="poststuff" class="gadwp">
184
- <div id="post-body" class="metabox-holder columns-2">
185
- <div id="post-body-content">
186
- <div class="settings-wrapper">
187
- <div class="inside">
188
- <?php if (isset($message)) echo $message; ?>
189
- <table class="gadwp-settings-options">
190
- <tr>
191
- <td colspan="2"><?php echo "<h2>" . __( "Permissions", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
192
- </tr>
193
- <tr>
194
- <td class="roles gadwp-settings-title"><label for="ga_dash_access_back"><?php _e("Show stats to:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
195
- <td class="gadwp-settings-roles">
196
- <?php
197
- if ( ! isset( $wp_roles ) ) {
198
- $wp_roles = new WP_Roles();
199
- }
200
- $i = 0;
201
- ?>
202
- <table>
203
- <tr>
204
- <?php
205
-
206
- foreach ( $wp_roles->role_names as $role => $name ) {
207
- if ( $role != 'subscriber' ) {
208
- $i++;
209
- ?>
210
- <td><label> <input type="checkbox" name="options[ga_dash_access_back][]" value="<?php echo $role; ?>" <?php if (in_array($role,$options['ga_dash_access_back']) || $role=='administrator') echo 'checked="checked"'; if ($role=='administrator') echo 'disabled="disabled"';?> />
211
- <?php echo $name; ?>
212
- </label></td>
213
- <?php
214
- }
215
- if ( $i % 4 == 0 ) {
216
- ?>
217
- </tr>
218
- <tr>
219
- <?php
220
- }
221
- }
222
- ?>
223
- </table>
224
- </td>
225
- </tr>
226
- <tr>
227
- <td colspan="2" class="gadwp-settings-title">
228
- <div class="button-primary gadwp-settings-switchoo">
229
- <input type="checkbox" name="options[switch_profile]" value="1" class="gadwp-settings-switchoo-checkbox" id="switch_profile" <?php checked( $options['switch_profile'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="switch_profile">
230
- <div class="gadwp-settings-switchoo-inner"></div>
231
- <div class="gadwp-settings-switchoo-switch"></div>
232
- </label>
233
- </div>
234
- <div class="switch-desc"><?php _e ( "enable Switch View functionality", 'google-analytics-dashboard-for-wp' );?></div>
235
- </td>
236
- </tr>
237
- <tr>
238
- <td colspan="2" class="gadwp-settings-title">
239
- <div class="button-primary gadwp-settings-switchoo">
240
- <input type="checkbox" name="options[backend_item_reports]" value="1" class="gadwp-settings-switchoo-checkbox" id="backend_item_reports" <?php checked( $options['backend_item_reports'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="backend_item_reports">
241
- <div class="gadwp-settings-switchoo-inner"></div>
242
- <div class="gadwp-settings-switchoo-switch"></div>
243
- </label>
244
- </div>
245
- <div class="switch-desc"><?php _e ( "enable reports on Posts List and Pages List", 'google-analytics-dashboard-for-wp' );?></div>
246
- </td>
247
- </tr>
248
- <tr>
249
- <td colspan="2" class="gadwp-settings-title">
250
- <div class="button-primary gadwp-settings-switchoo">
251
- <input type="checkbox" name="options[dashboard_widget]" value="1" class="gadwp-settings-switchoo-checkbox" id="dashboard_widget" <?php checked( $options['dashboard_widget'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="dashboard_widget">
252
- <div class="gadwp-settings-switchoo-inner"></div>
253
- <div class="gadwp-settings-switchoo-switch"></div>
254
- </label>
255
- </div>
256
- <div class="switch-desc"><?php _e ( "enable the main Dashboard Widget", 'google-analytics-dashboard-for-wp' );?></div>
257
- </td>
258
- </tr>
259
- <tr>
260
- <td colspan="2"><hr><?php echo "<h2>" . __( "Real-Time Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
261
- </tr>
262
- <tr>
263
- <td colspan="2" class="gadwp-settings-title"> <?php _e("Maximum number of pages to display on real-time tab:", 'google-analytics-dashboard-for-wp'); ?>
264
- <input type="number" name="options[ga_realtime_pages]" id="ga_realtime_pages" value="<?php echo (int)$options['ga_realtime_pages']; ?>" size="3">
265
- </td>
266
- </tr>
267
- <tr>
268
- <td colspan="2"><hr><?php echo "<h2>" . __( "Location Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
269
- </tr>
270
- <tr>
271
- <td colspan="2" class="gadwp-settings-title">
272
- <?php echo __("Target Geo Map to country:", 'google-analytics-dashboard-for-wp'); ?>
273
- <input type="text" style="text-align: center;" name="options[ga_target_geomap]" value="<?php echo esc_attr($options['ga_target_geomap']); ?>" size="3">
274
- </td>
275
- </tr>
276
- <tr>
277
- <td colspan="2" class="gadwp-settings-title">
278
- <?php echo __("Maps API Key:", 'google-analytics-dashboard-for-wp'); ?>
279
- <input type="text" style="text-align: center;" name="options[maps_api_key]" value="<?php echo esc_attr($options['maps_api_key']); ?>" size="50">
280
- </td>
281
- </tr>
282
- <tr>
283
- <td colspan="2"><hr><?php echo "<h2>" . __( "404 Errors Report", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
284
- </tr>
285
- <tr>
286
- <td colspan="2" class="gadwp-settings-title">
287
- <?php echo __("404 Page Title contains:", 'google-analytics-dashboard-for-wp'); ?>
288
- <input type="text" style="text-align: center;" name="options[pagetitle_404]" value="<?php echo esc_attr($options['pagetitle_404']); ?>" size="20">
289
- </td>
290
- </tr>
291
- <tr>
292
- <td colspan="2"><hr></td>
293
- </tr>
294
- <tr>
295
- <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
296
- </tr>
297
- </table>
298
- <input type="hidden" name="options[ga_dash_hidden]" value="Y">
299
- <?php wp_nonce_field('gadash_form','gadash_security'); ?>
300
-
301
- </form>
302
- <?php
303
- self::output_sidebar();
304
- }
305
-
306
- public static function tracking_settings() {
307
- $gadwp = GADWP();
308
-
309
- if ( ! current_user_can( 'manage_options' ) ) {
310
- return;
311
- }
312
- $options = self::update_options( 'tracking' );
313
- if ( isset( $_POST['options']['ga_dash_hidden'] ) ) {
314
- $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
315
- if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
316
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
317
- }
318
- }
319
- if ( ! $gadwp->config->options['ga_dash_tableid_jail'] ) {
320
- $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
321
- }
322
- if ( ! $options['ga_dash_tracking'] ) {
323
- $message = "<div class='error'><p>" . __( "The tracking component is disabled. You should set <strong>Tracking Options</strong> to <strong>Enabled</strong>", 'google-analytics-dashboard-for-wp' ) . ".</p></div>";
324
- }
325
- ?>
326
- <form name="ga_dash_form" method="post" action="<?php esc_url($_SERVER['REQUEST_URI']); ?>">
327
- <div class="wrap">
328
- <?php echo "<h2>" . __( "Google Analytics Tracking Code", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?>
329
- </div>
330
- <div id="poststuff" class="gadwp">
331
- <div id="post-body" class="metabox-holder columns-2">
332
- <div id="post-body-content">
333
- <div class="settings-wrapper">
334
- <div class="inside">
335
- <?php
336
- $tabs = array( 'basic' => __( "Basic Settings", 'google-analytics-dashboard-for-wp' ), 'events' => __( "Events Tracking", 'google-analytics-dashboard-for-wp' ), 'custom' => __( "Custom Definitions", 'google-analytics-dashboard-for-wp' ), 'exclude' => __( "Exclude Tracking", 'google-analytics-dashboard-for-wp' ), 'advanced' => __( "Advanced Settings", 'google-analytics-dashboard-for-wp' ) );
337
- self::navigation_tabs( $tabs );
338
- if ( isset( $message ) )
339
- echo $message;
340
- ?>
341
- <div id="gadwp-basic">
342
- <table class="gadwp-settings-options">
343
- <tr>
344
- <td colspan="2"><?php echo "<h2>" . __( "Tracking Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
345
- </tr>
346
- <tr>
347
- <td class="gadwp-settings-title"><label for="ga_dash_tracking"><?php _e("Tracking Options:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
348
- <td><select id="ga_dash_tracking" name="options[ga_dash_tracking]" onchange="this.form.submit()">
349
- <option value="0" <?php selected( $options['ga_dash_tracking'], 0 ); ?>><?php _e("Disabled", 'google-analytics-dashboard-for-wp');?></option>
350
- <option value="1" <?php selected( $options['ga_dash_tracking'], 1 ); ?>><?php _e("Enabled", 'google-analytics-dashboard-for-wp');?></option>
351
- </select></td>
352
- </tr>
353
- <?php if ($options['ga_dash_tracking']) {?>
354
- <tr>
355
- <td class="gadwp-settings-title"></td>
356
- <td>
357
- <?php $profile_info = GADWP_Tools::get_selected_profile($gadwp->config->options['ga_dash_profile_list'], $gadwp->config->options['ga_dash_tableid_jail']); ?>
358
- <?php echo '<pre>' . __("View Name:", 'google-analytics-dashboard-for-wp') . "\t" . esc_html($profile_info[0]) . "<br />" . __("Tracking ID:", 'google-analytics-dashboard-for-wp') . "\t" . esc_html($profile_info[2]) . "<br />" . __("Default URL:", 'google-analytics-dashboard-for-wp') . "\t" . esc_html($profile_info[3]) . "<br />" . __("Time Zone:", 'google-analytics-dashboard-for-wp') . "\t" . esc_html($profile_info[5]) . '</pre>';?>
359
- </td>
360
- </tr>
361
- <?php }?>
362
- <tr>
363
- <td colspan="2"><hr><?php echo "<h2>" . __( "Basic Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
364
- </tr>
365
- <tr>
366
- <td class="gadwp-settings-title"><label for="ga_dash_tracking_type"><?php _e("Tracking Type:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
367
- <td><select id="ga_dash_tracking_type" name="options[ga_dash_tracking_type]">
368
- <option value="classic" <?php selected( $options['ga_dash_tracking_type'], 'classic' ); ?>><?php _e("Classic Analytics", 'google-analytics-dashboard-for-wp');?></option>
369
- <option value="universal" <?php selected( $options['ga_dash_tracking_type'], 'universal' ); ?>><?php _e("Universal Analytics", 'google-analytics-dashboard-for-wp');?></option>
370
- </select></td>
371
- </tr>
372
- <tr>
373
- <td colspan="2" class="gadwp-settings-title">
374
- <div class="button-primary gadwp-settings-switchoo">
375
- <input type="checkbox" name="options[ga_dash_anonim]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_anonim" <?php checked( $options['ga_dash_anonim'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_dash_anonim">
376
- <div class="gadwp-settings-switchoo-inner"></div>
377
- <div class="gadwp-settings-switchoo-switch"></div>
378
- </label>
379
- </div>
380
- <div class="switch-desc"><?php echo " ".__("anonymize IPs while tracking", 'google-analytics-dashboard-for-wp' );?></div>
381
- </td>
382
- </tr>
383
- <tr>
384
- <td colspan="2" class="gadwp-settings-title">
385
- <div class="button-primary gadwp-settings-switchoo">
386
- <input type="checkbox" name="options[ga_dash_remarketing]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_remarketing" <?php checked( $options['ga_dash_remarketing'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_dash_remarketing">
387
- <div class="gadwp-settings-switchoo-inner"></div>
388
- <div class="gadwp-settings-switchoo-switch"></div>
389
- </label>
390
- </div>
391
- <div class="switch-desc"><?php echo " ".__("enable remarketing, demographics and interests reports", 'google-analytics-dashboard-for-wp' );?></div>
392
- </td>
393
- </tr>
394
- </table>
395
- </div>
396
- <div id="gadwp-events">
397
- <table class="gadwp-settings-options">
398
- <tr>
399
- <td colspan="2"><?php echo "<h2>" . __( "Events Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
400
- </tr>
401
- <tr>
402
- <td colspan="2" class="gadwp-settings-title">
403
- <div class="button-primary gadwp-settings-switchoo">
404
- <input type="checkbox" name="options[ga_event_tracking]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_event_tracking" <?php checked( $options['ga_event_tracking'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_event_tracking">
405
- <div class="gadwp-settings-switchoo-inner"></div>
406
- <div class="gadwp-settings-switchoo-switch"></div>
407
- </label>
408
- </div>
409
- <div class="switch-desc"><?php echo " ".__("track downloads, mailto and outbound links", 'google-analytics-dashboard-for-wp' ); ?></div>
410
- </td>
411
- </tr>
412
- <tr>
413
- <td class="gadwp-settings-title"><label for="ga_event_downloads"><?php _e("Downloads Regex:", 'google-analytics-dashboard-for-wp'); ?></label></td>
414
- <td><input type="text" id="ga_event_downloads" name="options[ga_event_downloads]" value="<?php echo esc_attr($options['ga_event_downloads']); ?>" size="50"></td>
415
- </tr>
416
- <tr>
417
- <td colspan="2" class="gadwp-settings-title">
418
- <div class="button-primary gadwp-settings-switchoo">
419
- <input type="checkbox" name="options[ga_aff_tracking]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_aff_tracking" <?php checked( $options['ga_aff_tracking'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_aff_tracking">
420
- <div class="gadwp-settings-switchoo-inner"></div>
421
- <div class="gadwp-settings-switchoo-switch"></div>
422
- </label>
423
- </div>
424
- <div class="switch-desc"><?php echo " ".__("track affiliate links matching this regex", 'google-analytics-dashboard-for-wp' ); ?></div>
425
- </td>
426
- </tr>
427
- <tr>
428
- <td class="gadwp-settings-title"><label for="ga_event_affiliates"><?php _e("Affiliates Regex:", 'google-analytics-dashboard-for-wp'); ?></label></td>
429
- <td><input type="text" id="ga_event_affiliates" name="options[ga_event_affiliates]" value="<?php echo esc_attr($options['ga_event_affiliates']); ?>" size="50"></td>
430
- </tr>
431
- <tr>
432
- <td colspan="2" class="gadwp-settings-title">
433
- <div class="button-primary gadwp-settings-switchoo">
434
- <input type="checkbox" name="options[ga_hash_tracking]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_hash_tracking" <?php checked( $options['ga_hash_tracking'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_hash_tracking">
435
- <div class="gadwp-settings-switchoo-inner"></div>
436
- <div class="gadwp-settings-switchoo-switch"></div>
437
- </label>
438
- </div>
439
- <div class="switch-desc"><?php echo " ".__("track fragment identifiers, hashmarks (#) in URI links", 'google-analytics-dashboard-for-wp' ); ?></div>
440
- </td>
441
- </tr>
442
- </table>
443
- </div>
444
- <div id="gadwp-custom">
445
- <table class="gadwp-settings-options">
446
- <tr>
447
- <td colspan="2"><?php echo "<h2>" . __( "Custom Definitions", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
448
- </tr>
449
- <tr>
450
- <td class="gadwp-settings-title"><label for="ga_author_dimindex"><?php _e("Authors:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
451
- <td><select id="ga_author_dimindex" name="options[ga_author_dimindex]">
452
- <?php for ($i=0;$i<21;$i++){?>
453
- <option value="<?php echo $i;?>" <?php selected( $options['ga_author_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
454
- <?php }?>
455
- </select></td>
456
- </tr>
457
- <tr>
458
- <td class="gadwp-settings-title"><label for="ga_pubyear_dimindex"><?php _e("Publication Year:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
459
- <td><select id="ga_pubyear_dimindex" name="options[ga_pubyear_dimindex]">
460
- <?php for ($i=0;$i<21;$i++){?>
461
- <option value="<?php echo $i;?>" <?php selected( $options['ga_pubyear_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
462
- <?php }?>
463
- </select></td>
464
- </tr>
465
- <tr>
466
- <td class="gadwp-settings-title"><label for="ga_pubyearmonth_dimindex"><?php _e("Publication Month:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
467
- <td><select id="ga_pubyearmonth_dimindex" name="options[ga_pubyearmonth_dimindex]">
468
- <?php for ($i=0;$i<21;$i++){?>
469
- <option value="<?php echo $i;?>" <?php selected( $options['ga_pubyearmonth_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
470
- <?php }?>
471
- </select></td>
472
- </tr>
473
- <tr>
474
- <td class="gadwp-settings-title"><label for="ga_category_dimindex"><?php _e("Categories:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
475
- <td><select id="ga_category_dimindex" name="options[ga_category_dimindex]">
476
- <?php for ($i=0;$i<21;$i++){?>
477
- <option value="<?php echo $i;?>" <?php selected( $options['ga_category_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
478
- <?php }?>
479
- </select></td>
480
- </tr>
481
- <tr>
482
- <td class="gadwp-settings-title"><label for="ga_user_dimindex"><?php _e("User Type:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
483
- <td><select id="ga_user_dimindex" name="options[ga_user_dimindex]">
484
- <?php for ($i=0;$i<21;$i++){?>
485
- <option value="<?php echo $i;?>" <?php selected( $options['ga_user_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
486
- <?php }?>
487
- </select></td>
488
- </tr>
489
- <tr>
490
- <td class="gadwp-settings-title"><label for="ga_tag_dimindex"><?php _e("Tags:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
491
- <td><select id="ga_tag_dimindex" name="options[ga_tag_dimindex]">
492
- <?php for ($i=0;$i<21;$i++){?>
493
- <option value="<?php echo $i;?>" <?php selected( $options['ga_tag_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
494
- <?php }?>
495
- </select></td>
496
- </tr>
497
- </table>
498
- </div>
499
- <div id="gadwp-advanced">
500
- <table class="gadwp-settings-options">
501
- <tr>
502
- <td colspan="2"><?php echo "<h2>" . __( "Advanced Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
503
- </tr>
504
- <tr>
505
- <td class="gadwp-settings-title"><label for="ga_speed_samplerate"><?php _e("Page Speed SR:", 'google-analytics-dashboard-for-wp'); ?></label></td>
506
- <td><input type="number" id="ga_speed_samplerate" name="options[ga_speed_samplerate]" value="<?php echo (int)($options['ga_speed_samplerate']); ?>" max="100" min="1"> %</td>
507
- </tr>
508
- <tr>
509
- <td colspan="2" class="gadwp-settings-title">
510
- <div class="button-primary gadwp-settings-switchoo">
511
- <input type="checkbox" name="options[ga_event_bouncerate]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_event_bouncerate" <?php checked( $options['ga_event_bouncerate'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_event_bouncerate">
512
- <div class="gadwp-settings-switchoo-inner"></div>
513
- <div class="gadwp-settings-switchoo-switch"></div>
514
- </label>
515
- </div>
516
- <div class="switch-desc"><?php echo " ".__("exclude events from bounce-rate calculation", 'google-analytics-dashboard-for-wp' );?></div>
517
- </td>
518
- </tr>
519
- <tr>
520
- <td colspan="2" class="gadwp-settings-title">
521
- <div class="button-primary gadwp-settings-switchoo">
522
- <input type="checkbox" name="options[ga_enhanced_links]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_enhanced_links" <?php checked( $options['ga_enhanced_links'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_enhanced_links">
523
- <div class="gadwp-settings-switchoo-inner"></div>
524
- <div class="gadwp-settings-switchoo-switch"></div>
525
- </label>
526
- </div>
527
- <div class="switch-desc"><?php echo " ".__("enable enhanced link attribution", 'google-analytics-dashboard-for-wp' );?></div>
528
- </td>
529
- </tr>
530
- <tr>
531
- <td colspan="2" class="gadwp-settings-title">
532
- <div class="button-primary gadwp-settings-switchoo">
533
- <input type="checkbox" name="options[ga_dash_adsense]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_adsense" <?php checked( $options['ga_dash_adsense'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_dash_adsense">
534
- <div class="gadwp-settings-switchoo-inner"></div>
535
- <div class="gadwp-settings-switchoo-switch"></div>
536
- </label>
537
- </div>
538
- <div class="switch-desc"><?php echo " ".__("enable AdSense account linking", 'google-analytics-dashboard-for-wp' );?></div>
539
- </td>
540
- </tr>
541
- <tr>
542
- <td colspan="2"><?php echo "<h2>" . __( "Cross-domain Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
543
- </tr>
544
- <tr>
545
- <td colspan="2" class="gadwp-settings-title">
546
- <div class="button-primary gadwp-settings-switchoo">
547
- <input type="checkbox" name="options[ga_crossdomain_tracking]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_crossdomain_tracking" <?php checked( $options['ga_crossdomain_tracking'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_crossdomain_tracking">
548
- <div class="gadwp-settings-switchoo-inner"></div>
549
- <div class="gadwp-settings-switchoo-switch"></div>
550
- </label>
551
- </div>
552
- <div class="switch-desc"><?php echo " ".__("enable cross domain tracking", 'google-analytics-dashboard-for-wp' ); ?></div>
553
- </td>
554
- </tr>
555
- <tr>
556
- <td class="gadwp-settings-title"><label for="ga_crossdomain_list"><?php _e("Cross Domains:", 'google-analytics-dashboard-for-wp'); ?></label></td>
557
- <td><input type="text" id="ga_crossdomain_list" name="options[ga_crossdomain_list]" value="<?php echo esc_attr($options['ga_crossdomain_list']); ?>" size="50"></td>
558
- </tr>
559
- <tr>
560
- <td colspan="2"><?php echo "<h2>" . __( "Cookie Customization", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
561
- </tr>
562
- <tr>
563
- <td class="gadwp-settings-title"><label for="ga_cookiedomain"><?php _e("Cookie Domain:", 'google-analytics-dashboard-for-wp'); ?></label></td>
564
- <td><input type="text" id="ga_cookiedomain" name="options[ga_cookiedomain]" value="<?php echo esc_attr($options['ga_cookiedomain']); ?>" size="50"></td>
565
- </tr>
566
- <tr>
567
- <td class="gadwp-settings-title"><label for="ga_cookiename"><?php _e("Cookie Name:", 'google-analytics-dashboard-for-wp'); ?></label></td>
568
- <td><input type="text" id="ga_cookiename" name="options[ga_cookiename]" value="<?php echo esc_attr($options['ga_cookiename']); ?>" size="50"></td>
569
- </tr>
570
- <tr>
571
- <td class="gadwp-settings-title"><label for="ga_cookieexpires"><?php _e("Cookie Expires:", 'google-analytics-dashboard-for-wp'); ?></label></td>
572
- <td><input type="text" id="ga_cookieexpires" name="options[ga_cookieexpires]" value="<?php echo esc_attr($options['ga_cookieexpires']); ?>" size="10"> seconds</td>
573
- </tr>
574
- </table>
575
- </div>
576
- <div id="gadwp-exclude">
577
- <table class="gadwp-settings-options">
578
- <tr>
579
- <td colspan="2"><?php echo "<h2>" . __( "Exclude Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
580
- </tr>
581
- <tr>
582
- <td class="roles gadwp-settings-title"><label for="ga_track_exclude"><?php _e("Exclude tracking for:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
583
- <td class="gadwp-settings-roles">
584
- <?php
585
- if ( ! isset( $wp_roles ) ) {
586
- $wp_roles = new WP_Roles();
587
- }
588
- $i = 0;
589
- ?> <table>
590
- <tr>
591
- <?php
592
- foreach ( $wp_roles->role_names as $role => $name ) {
593
- $i++;
594
- ?>
595
- <td><label> <input type="checkbox" name="options[ga_track_exclude][]" value="<?php echo $role; ?>" <?php if (in_array($role,$options['ga_track_exclude'])) echo 'checked="checked"'; ?> />
596
- <?php echo $name; ?>
597
- </label></td>
598
- <?php
599
- if ( $i % 4 == 0 ) {
600
- ?>
601
- </tr>
602
- <tr>
603
- <?php
604
- }
605
- }
606
- ?>
607
- </table>
608
- </td>
609
- </tr>
610
- </table>
611
- </div>
612
- <table class="gadwp-settings-options">
613
- <tr>
614
- <td colspan="2"><hr></td>
615
- </tr>
616
- <tr>
617
- <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
618
- </tr>
619
- </table>
620
- <input type="hidden" name="options[ga_dash_hidden]" value="Y">
621
- <?php wp_nonce_field('gadash_form','gadash_security'); ?>
622
- </form>
623
- <?php
624
- self::output_sidebar();
625
- }
626
-
627
- public static function errors_debugging() {
628
- global $wp_version;
629
-
630
- $gadwp = GADWP();
631
-
632
- if ( ! current_user_can( 'manage_options' ) ) {
633
- return;
634
- }
635
-
636
- $anonim = $gadwp->config->options;
637
- $anonim['wp_version'] = $wp_version;
638
- $anonim['gadwp_version'] = GADWP_CURRENT_VERSION;
639
- if ( $anonim['ga_dash_token'] ) {
640
- $anonim['ga_dash_token'] = 'HIDDEN';
641
- }
642
- if ( $anonim['ga_dash_clientid'] ) {
643
- $anonim['ga_dash_clientid'] = 'HIDDEN';
644
- }
645
- if ( $anonim['ga_dash_clientsecret'] ) {
646
- $anonim['ga_dash_clientsecret'] = 'HIDDEN';
647
- }
648
- $options = self::update_options( 'frontend' );
649
- if ( ! $gadwp->config->options['ga_dash_tableid_jail'] || ! $gadwp->config->options['ga_dash_token'] ) {
650
- $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
651
- }
652
- ?>
653
- <div class="wrap">
654
- <?php echo "<h2>" . __( "Google Analytics Errors & Debugging", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?>
655
- </div>
656
- <div id="poststuff" class="gadwp">
657
- <div id="post-body" class="metabox-holder columns-2">
658
- <div id="post-body-content">
659
- <div class="settings-wrapper">
660
- <div class="inside">
661
- <?php if (isset($message)) echo $message; ?>
662
- <?php
663
- $tabs = array( 'errors' => __( "Errors & Details", 'google-analytics-dashboard-for-wp' ), 'config' => __( "Plugin Settings", 'google-analytics-dashboard-for-wp' ) );
664
- self::navigation_tabs( $tabs );
665
- ?>
666
- <div id="gadwp-errors">
667
- <table class="gadwp-settings-options">
668
- <tr>
669
- <td>
670
- <?php echo "<h2>" . __( "Last Error detected", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?>
671
- </td>
672
- </tr>
673
- <tr>
674
- <td>
675
- <?php
676
- $errors = print_r( GADWP_Tools::get_cache( 'last_error' ), true ) ? esc_html( print_r( GADWP_Tools::get_cache( 'last_error' ), true ) ) : __( "None", 'google-analytics-dashboard-for-wp' );
677
- echo '<pre class="gadwp-settings-logdata">Last Error: ';
678
- echo $errors;
679
- ?></pre>
680
- </td>
681
- </tr>
682
- <tr>
683
- <td colspan="2"><hr><?php echo "<h2>" . __( "Error Details", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
684
- </tr>
685
- <tr>
686
- <td>
687
- <?php
688
- echo '<pre class="gadwp-settings-logdata">Error Details: ';
689
- $error_details = print_r( GADWP_Tools::get_cache( 'gapi_errors' ), true ) ? "\n" . esc_html( print_r( GADWP_Tools::get_cache( 'last_error' ), true ) ) : __( "None", 'google-analytics-dashboard-for-wp' );
690
- echo $error_details;
691
- ?></pre><br />
692
- <hr>
693
- </td>
694
-
695
-
696
- <tr>
697
-
698
- </table>
699
- </div>
700
- <div id="gadwp-config">
701
- <table class="gadwp-settings-options">
702
- <tr>
703
- <td><?php echo "<h2>" . __( "Plugin Configuration", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
704
- </tr>
705
- <tr>
706
- <td><pre class="gadwp-settings-logdata"><?php echo esc_html(print_r($anonim, true));?></pre><br />
707
- <hr></td>
708
- </tr>
709
- </table>
710
- </div>
711
- <?php
712
- self::output_sidebar();
713
- }
714
-
715
- public static function general_settings() {
716
- $gadwp = GADWP();
717
-
718
- global $wp_version;
719
-
720
- if ( ! current_user_can( 'manage_options' ) ) {
721
- return;
722
- }
723
- $options = self::update_options( 'general' );
724
- printf( '<div id="gapi-warning" class="updated"><p>%1$s <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=general_screen&utm_campaign=gadwp">%2$s</a></p></div>', __( 'Loading the required libraries. If this results in a blank screen or a fatal error, try this solution:', 'google-analytics-dashboard-for-wp' ), __( 'Library conflicts between WordPress plugins', 'google-analytics-dashboard-for-wp' ) );
725
- if ( null === $gadwp->gapi_controller ) {
726
- $gadwp->gapi_controller = new GADWP_GAPI_Controller();
727
- }
728
- echo '<script type="text/javascript">jQuery("#gapi-warning").hide()</script>';
729
- if ( isset( $_POST['ga_dash_code'] ) ) {
730
- if ( ! stripos( 'x' . $_POST['ga_dash_code'], 'UA-', 1 ) == 1 ) {
731
- try {
732
- $gadwp->gapi_controller->client->authenticate( $_POST['ga_dash_code'] );
733
- $gadwp->config->options['ga_dash_token'] = $gadwp->gapi_controller->client->getAccessToken();
734
- $gadwp->config->options['automatic_updates_minorversion'] = 1;
735
- $gadwp->config->set_plugin_options();
736
- $options = self::update_options( 'general' );
737
- $message = "<div class='updated'><p>" . __( "Plugin authorization succeeded.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
738
- GADWP_Tools::delete_cache( 'gapi_errors' );
739
- GADWP_Tools::delete_cache( 'last_error' );
740
- if ( $gadwp->config->options['ga_dash_token'] && $gadwp->gapi_controller->client->getAccessToken() ) {
741
- if ( ! empty( $gadwp->config->options['ga_dash_profile_list'] ) ) {
742
- $profiles = $gadwp->config->options['ga_dash_profile_list'];
743
- } else {
744
- $profiles = $gadwp->gapi_controller->refresh_profiles();
745
- }
746
- if ( $profiles ) {
747
- $gadwp->config->options['ga_dash_profile_list'] = $profiles;
748
- if ( ! $gadwp->config->options['ga_dash_tableid_jail'] ) {
749
- $profile = GADWP_Tools::guess_default_domain( $profiles );
750
- $gadwp->config->options['ga_dash_tableid_jail'] = $profile;
751
- // $gadwp->config->options['ga_dash_tableid'] = $profile;
752
- }
753
- $gadwp->config->set_plugin_options();
754
- $options = self::update_options( 'general' );
755
- }
756
- }
757
- } catch ( Google_IO_Exception $e ) {
758
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $gadwp->gapi_controller->error_timeout );
759
- return false;
760
- } catch ( Google_Service_Exception $e ) {
761
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $gadwp->gapi_controller->error_timeout );
762
- GADWP_Tools::set_cache( 'gapi_errors', $e->getErrors(), $gadwp->gapi_controller->error_timeout );
763
- return $e->getCode();
764
- } catch ( Exception $e ) {
765
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ) . "\nResponseHttpCode:" . $e->getCode(), $gadwp->gapi_controller->error_timeout );
766
- $gadwp->gapi_controller->reset_token( false );
767
- }
768
- } else {
769
- $message = "<div class='error'><p>" . __( "The access code is <strong>NOT</strong> your <strong>Tracking ID</strong> (UA-XXXXX-X). Try again, and use the red link to get your access code", 'google-analytics-dashboard-for-wp' ) . ".</p></div>";
770
- }
771
- }
772
- if ( isset( $_POST['Clear'] ) ) {
773
- if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
774
- GADWP_Tools::clear_cache();
775
- $message = "<div class='updated'><p>" . __( "Cleared Cache.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
776
- } else {
777
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
778
- }
779
- }
780
- if ( isset( $_POST['Reset'] ) ) {
781
- if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
782
- $gadwp->gapi_controller->reset_token( true );
783
- GADWP_Tools::clear_cache();
784
- $message = "<div class='updated'><p>" . __( "Token Reseted and Revoked.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
785
- $options = self::update_options( 'Reset' );
786
- } else {
787
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
788
- }
789
- }
790
- if ( isset( $_POST['Reset_Err'] ) ) {
791
- if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
792
- GADWP_Tools::delete_cache( 'last_error' );
793
- GADWP_Tools::delete_cache( 'gapi_errors' );
794
- $message = "<div class='updated'><p>" . __( "All errors reseted.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
795
- } else {
796
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
797
- }
798
- }
799
- if ( isset( $_POST['options']['ga_dash_hidden'] ) && ! isset( $_POST['Clear'] ) && ! isset( $_POST['Reset'] ) && ! isset( $_POST['Reset_Err'] ) ) {
800
- $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
801
- if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
802
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
803
- }
804
- }
805
- if ( isset( $_POST['Hide'] ) ) {
806
- if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
807
- $message = "<div class='updated'><p>" . __( "All other domains/properties were removed.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
808
- $lock_profile = GADWP_Tools::get_selected_profile( $gadwp->config->options['ga_dash_profile_list'], $gadwp->config->options['ga_dash_tableid_jail'] );
809
- $gadwp->config->options['ga_dash_profile_list'] = array( $lock_profile );
810
- $options = self::update_options( 'general' );
811
- } else {
812
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
813
- }
814
- }
815
- ?>
816
- <div class="wrap">
817
- <?php echo "<h2>" . __( "Google Analytics Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?>
818
- <hr>
819
- </div>
820
- <div id="poststuff" class="gadwp">
821
- <div id="post-body" class="metabox-holder columns-2">
822
- <div id="post-body-content">
823
- <div class="settings-wrapper">
824
- <div class="inside">
825
- <?php
826
- if ( $gadwp->gapi_controller->gapi_errors_handler() || GADWP_Tools::get_cache( 'last_error' ) ) {
827
- $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
828
- }
829
- if ( isset( $_POST['Authorize'] ) ) {
830
- GADWP_Tools::clear_cache();
831
- $gadwp->gapi_controller->token_request();
832
- echo "<div class='updated'><p>" . __( "Use the red link (see below) to generate and get your access code!", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
833
- } else {
834
- if ( isset( $message ) ) {
835
- echo $message;
836
- }
837
- ?>
838
- <form name="ga_dash_form" method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
839
- <input type="hidden" name="options[ga_dash_hidden]" value="Y">
840
- <?php wp_nonce_field('gadash_form','gadash_security'); ?>
841
- <table class="gadwp-settings-options">
842
- <tr>
843
- <td colspan="2">
844
- <?php echo "<h2>" . __( "Plugin Authorization", 'google-analytics-dashboard-for-wp' ) . "</h2>";?>
845
- </td>
846
- </tr>
847
- <tr>
848
- <td colspan="2" class="gadwp-settings-info">
849
- <?php printf(__('You should watch the %1$s and read this %2$s before proceeding to authorization. This plugin requires a properly configured Google Analytics account!', 'google-analytics-dashboard-for-wp'), sprintf('<a href="%1$s" target="_blank">%2$s</a>', 'https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=top_video&utm_campaign=gadwp', __("video", 'google-analytics-dashboard-for-wp')), sprintf('<a href="%1$s" target="_blank">%2$s</a>', 'https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=top_tutorial&utm_campaign=gadwp', __("tutorial", 'google-analytics-dashboard-for-wp')));?>
850
- </td>
851
- </tr>
852
- <?php if (! $options['ga_dash_token'] || $options['ga_dash_userapi']) {?>
853
- <tr>
854
- <td colspan="2" class="gadwp-settings-info"><input name="options[ga_dash_userapi]" type="checkbox" id="ga_dash_userapi" value="1" <?php checked( $options['ga_dash_userapi'], 1 ); ?> onchange="this.form.submit()" <?php echo ($options['ga_dash_network'])?'disabled="disabled"':''; ?> /><?php echo " ".__("use your own API Project credentials", 'google-analytics-dashboard-for-wp' );?>
855
- </td>
856
- </tr>
857
- <?php } if ($options['ga_dash_userapi']) { ?>
858
- <tr>
859
- <td class="gadwp-settings-title"><label for="options[ga_dash_clientid]"><?php _e("Client ID:", 'google-analytics-dashboard-for-wp'); ?></label></td>
860
- <td><input type="text" name="options[ga_dash_clientid]" value="<?php echo esc_attr($options['ga_dash_clientid']); ?>" size="40" required="required"></td>
861
- </tr>
862
- <tr>
863
- <td class="gadwp-settings-title"><label for="options[ga_dash_clientsecret]"><?php _e("Client Secret:", 'google-analytics-dashboard-for-wp'); ?></label></td>
864
- <td><input type="text" name="options[ga_dash_clientsecret]" value="<?php echo esc_attr($options['ga_dash_clientsecret']); ?>" size="40" required="required"> <input type="hidden" name="options[ga_dash_hidden]" value="Y">
865
- <?php wp_nonce_field('gadash_form','gadash_security'); ?>
866
- </td>
867
- </tr>
868
- <?php
869
- }
870
- if ( $options['ga_dash_token'] ) {
871
- ?>
872
- <tr>
873
- <td colspan="2"><input type="submit" name="Reset" class="button button-secondary" value="<?php _e( "Clear Authorization", 'google-analytics-dashboard-for-wp' ); ?>" <?php echo $options['ga_dash_network']?'disabled="disabled"':''; ?> /> <input type="submit" name="Clear" class="button button-secondary" value="<?php _e( "Clear Cache", 'google-analytics-dashboard-for-wp' ); ?>" /> <input type="submit" name="Reset_Err" class="button button-secondary" value="<?php _e( "Reset Errors", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
874
- </tr>
875
- <tr>
876
- <td colspan="2"><hr></td>
877
- </tr>
878
- <tr>
879
- <td colspan="2"><?php echo "<h2>" . __( "General Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
880
- </tr>
881
- <tr>
882
- <td class="gadwp-settings-title"><label for="ga_dash_tableid_jail"><?php _e("Select View:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
883
- <td><select id="ga_dash_tableid_jail" <?php disabled(empty($options['ga_dash_profile_list']) || 1 == count($options['ga_dash_profile_list']), true); ?> name="options[ga_dash_tableid_jail]">
884
- <?php
885
- if ( ! empty( $options['ga_dash_profile_list'] ) ) {
886
- foreach ( $options['ga_dash_profile_list'] as $items ) {
887
- if ( $items[3] ) {
888
- echo '<option value="' . esc_attr( $items[1] ) . '" ' . selected( $items[1], $options['ga_dash_tableid_jail'], false );
889
- echo ' title="' . __( "View Name:", 'google-analytics-dashboard-for-wp' ) . ' ' . esc_attr( $items[0] ) . '">' . esc_html( GADWP_Tools::strip_protocol( $items[3] ) ) . ' &#8658; ' . esc_attr( $items[0] ) . '</option>';
890
- }
891
- }
892
- } else {
893
- echo '<option value="">' . __( "Property not found", 'google-analytics-dashboard-for-wp' ) . '</option>';
894
- }
895
- ?>
896
- </select>
897
- <?php
898
- if ( count( $options['ga_dash_profile_list'] ) > 1 ) {
899
- ?>&nbsp;<input type="submit" name="Hide" class="button button-secondary" value="<?php _e( "Lock Selection", 'google-analytics-dashboard-for-wp' ); ?>" /><?php
900
- }
901
- ?>
902
- </td>
903
- </tr>
904
- <?php
905
- if ( $options['ga_dash_tableid_jail'] ) {
906
- ?>
907
- <tr>
908
- <td class="gadwp-settings-title"></td>
909
- <td><?php
910
- $profile_info = GADWP_Tools::get_selected_profile( $gadwp->config->options['ga_dash_profile_list'], $gadwp->config->options['ga_dash_tableid_jail'] );
911
- echo '<pre>' . __( "View Name:", 'google-analytics-dashboard-for-wp' ) . "\t" . esc_html( $profile_info[0] ) . "<br />" . __( "Tracking ID:", 'google-analytics-dashboard-for-wp' ) . "\t" . esc_html( $profile_info[2] ) . "<br />" . __( "Default URL:", 'google-analytics-dashboard-for-wp' ) . "\t" . esc_html( $profile_info[3] ) . "<br />" . __( "Time Zone:", 'google-analytics-dashboard-for-wp' ) . "\t" . esc_html( $profile_info[5] ) . '</pre>';
912
- ?></td>
913
- </tr>
914
- <?php
915
- }
916
- ?>
917
- <tr>
918
- <td class="gadwp-settings-title"><label for="ga_dash_style"><?php _e("Theme Color:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
919
- <td><input type="text" id="ga_dash_style" class="ga_dash_style" name="options[ga_dash_style]" value="<?php echo esc_attr($options['ga_dash_style']); ?>" size="10"></td>
920
- </tr>
921
- <tr>
922
- <td colspan="2"><hr></td>
923
- </tr>
924
- <?php if ( !is_multisite()) {?>
925
- <tr>
926
- <td colspan="2"><?php echo "<h2>" . __( "Automatic Updates", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
927
- </tr>
928
- <tr>
929
- <td colspan="2" class="gadwp-settings-title">
930
- <div class="button-primary gadwp-settings-switchoo">
931
- <input type="checkbox" name="options[automatic_updates_minorversion]" value="1" class="gadwp-settings-switchoo-checkbox" id="automatic_updates_minorversion" <?php checked( $options['automatic_updates_minorversion'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="automatic_updates_minorversion">
932
- <div class="gadwp-settings-switchoo-inner"></div>
933
- <div class="gadwp-settings-switchoo-switch"></div>
934
- </label>
935
- </div>
936
- <div class="switch-desc"><?php echo " ".__( "automatic updates for minor versions (security and maintenance releases only)", 'google-analytics-dashboard-for-wp' );?></div>
937
- </td>
938
- </tr>
939
- <tr>
940
- <td colspan="2"><hr></td>
941
- </tr>
942
- <?php }?>
943
- <tr>
944
- <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
945
- </tr>
946
- <?php } else {?>
947
- <tr>
948
- <td colspan="2"><hr></td>
949
- </tr>
950
- <tr>
951
- <td colspan="2"><input type="submit" name="Authorize" class="button button-secondary" id="authorize" value="<?php _e( "Authorize Plugin", 'google-analytics-dashboard-for-wp' ); ?>" <?php echo $options['ga_dash_network']?'disabled="disabled"':''; ?> /> <input type="submit" name="Clear" class="button button-secondary" value="<?php _e( "Clear Cache", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
952
- </tr>
953
- <tr>
954
- <td colspan="2"><hr></td>
955
- </tr>
956
- </table>
957
- </form>
958
- <?php
959
- self::output_sidebar();
960
- return;
961
- }
962
- ?>
963
- </table>
964
- </form>
965
- <?php
966
- }
967
- self::output_sidebar();
968
- }
969
- // Network Settings
970
- public static function general_settings_network() {
971
- $gadwp = GADWP();
972
- global $wp_version;
973
-
974
- if ( ! current_user_can( 'manage_network_options' ) ) {
975
- return;
976
- }
977
- $options = self::update_options( 'network' );
978
- /*
979
- * Include GAPI
980
- */
981
- echo '<div id="gapi-warning" class="updated"><p>' . __( 'Loading the required libraries. If this results in a blank screen or a fatal error, try this solution:', 'google-analytics-dashboard-for-wp' ) . ' <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=general_screen&utm_campaign=gadwp">Library conflicts between WordPress plugins</a></p></div>';
982
-
983
- if ( null === $gadwp->gapi_controller ) {
984
- $gadwp->gapi_controller = new GADWP_GAPI_Controller();
985
- }
986
-
987
- echo '<script type="text/javascript">jQuery("#gapi-warning").hide()</script>';
988
- if ( isset( $_POST['ga_dash_code'] ) ) {
989
- if ( ! stripos( 'x' . $_POST['ga_dash_code'], 'UA-', 1 ) == 1 ) {
990
- try {
991
- $gadwp->gapi_controller->client->authenticate( $_POST['ga_dash_code'] );
992
- $gadwp->config->options['ga_dash_token'] = $gadwp->gapi_controller->client->getAccessToken();
993
- $gadwp->config->options['automatic_updates_minorversion'] = 1;
994
- $gadwp->config->set_plugin_options( true );
995
- $options = self::update_options( 'network' );
996
- $message = "<div class='updated'><p>" . __( "Plugin authorization succeeded.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
997
- if ( is_multisite() ) { // Cleanup errors on the entire network
998
- foreach ( GADWP_Tools::get_sites( array( 'limit' => apply_filters( 'gadwp_sites_limit', 100 ) ) ) as $blog ) {
999
- switch_to_blog( $blog['blog_id'] );
1000
- GADWP_Tools::delete_cache( 'gapi_errors' );
1001
- restore_current_blog();
1002
- }
1003
- } else {
1004
- GADWP_Tools::delete_cache( 'gapi_errors' );
1005
- }
1006
- if ( $gadwp->config->options['ga_dash_token'] && $gadwp->gapi_controller->client->getAccessToken() ) {
1007
- if ( ! empty( $gadwp->config->options['ga_dash_profile_list'] ) ) {
1008
- $profiles = $gadwp->config->options['ga_dash_profile_list'];
1009
- } else {
1010
- $profiles = $gadwp->gapi_controller->refresh_profiles();
1011
- }
1012
- if ( $profiles ) {
1013
- $gadwp->config->options['ga_dash_profile_list'] = $profiles;
1014
- if ( isset( $gadwp->config->options['ga_dash_tableid_jail'] ) && ! $gadwp->config->options['ga_dash_tableid_jail'] ) {
1015
- $profile = GADWP_Tools::guess_default_domain( $profiles );
1016
- $gadwp->config->options['ga_dash_tableid_jail'] = $profile;
1017
- // $gadwp->config->options['ga_dash_tableid'] = $profile;
1018
- }
1019
- $gadwp->config->set_plugin_options( true );
1020
- $options = self::update_options( 'network' );
1021
- }
1022
- }
1023
- } catch ( Google_IO_Exception $e ) {
1024
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $gadwp->gapi_controller->error_timeout );
1025
- return false;
1026
- } catch ( Google_Service_Exception $e ) {
1027
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $gadwp->gapi_controller->error_timeout );
1028
- GADWP_Tools::set_cache( 'gapi_errors', $e->getErrors(), $gadwp->gapi_controller->error_timeout );
1029
- return $e->getCode();
1030
- } catch ( Exception $e ) {
1031
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ) . "\nResponseHttpCode:" . $e->getCode(), $gadwp->gapi_controller->error_timeout );
1032
- $gadwp->gapi_controller->reset_token( false );
1033
- }
1034
- } else {
1035
- $message = "<div class='error'><p>" . __( "The access code is <strong>NOT</strong> your <strong>Tracking ID</strong> (UA-XXXXX-X). Try again, and use the red link to get your access code", 'google-analytics-dashboard-for-wp' ) . ".</p></div>";
1036
- }
1037
- }
1038
- if ( isset( $_POST['Refresh'] ) ) {
1039
- if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
1040
- $gadwp->config->options['ga_dash_profile_list'] = array();
1041
- $message = "<div class='updated'><p>" . __( "Properties refreshed.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1042
- $options = self::update_options( 'network' );
1043
- if ( $gadwp->config->options['ga_dash_token'] && $gadwp->gapi_controller->client->getAccessToken() ) {
1044
- if ( ! empty( $gadwp->config->options['ga_dash_profile_list'] ) ) {
1045
- $profiles = $gadwp->config->options['ga_dash_profile_list'];
1046
- } else {
1047
- $profiles = $gadwp->gapi_controller->refresh_profiles();
1048
- }
1049
- if ( $profiles ) {
1050
- $gadwp->config->options['ga_dash_profile_list'] = $profiles;
1051
- if ( isset( $gadwp->config->options['ga_dash_tableid_jail'] ) && ! $gadwp->config->options['ga_dash_tableid_jail'] ) {
1052
- $profile = GADWP_Tools::guess_default_domain( $profiles );
1053
- $gadwp->config->options['ga_dash_tableid_jail'] = $profile;
1054
- // $gadwp->config->options['ga_dash_tableid'] = $profile;
1055
- }
1056
- $gadwp->config->set_plugin_options( true );
1057
- $options = self::update_options( 'network' );
1058
- }
1059
- }
1060
- } else {
1061
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1062
- }
1063
- }
1064
- if ( isset( $_POST['Clear'] ) ) {
1065
- if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
1066
- GADWP_Tools::clear_cache();
1067
- $message = "<div class='updated'><p>" . __( "Cleared Cache.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1068
- } else {
1069
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1070
- }
1071
- }
1072
- if ( isset( $_POST['Reset'] ) ) {
1073
- if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
1074
- $gadwp->gapi_controller->reset_token( true );
1075
- GADWP_Tools::clear_cache();
1076
- $message = "<div class='updated'><p>" . __( "Token Reseted and Revoked.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1077
- $options = self::update_options( 'Reset' );
1078
- } else {
1079
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1080
- }
1081
- }
1082
- if ( isset( $_POST['options']['ga_dash_hidden'] ) && ! isset( $_POST['Clear'] ) && ! isset( $_POST['Reset'] ) && ! isset( $_POST['Refresh'] ) ) {
1083
- $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1084
- if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
1085
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1086
- }
1087
- }
1088
- if ( isset( $_POST['Hide'] ) ) {
1089
- if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
1090
- $message = "<div class='updated'><p>" . __( "All other domains/properties were removed.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1091
- $lock_profile = GADWP_Tools::get_selected_profile( $gadwp->config->options['ga_dash_profile_list'], $gadwp->config->options['ga_dash_tableid_jail'] );
1092
- $gadwp->config->options['ga_dash_profile_list'] = array( $lock_profile );
1093
- $options = self::update_options( 'network' );
1094
- } else {
1095
- $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1096
- }
1097
- }
1098
- ?>
1099
- <div class="wrap">
1100
- <?php echo "<h2>" . __( "Google Analytics Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?><hr>
1101
- </div>
1102
- <div id="poststuff" class="gadwp">
1103
- <div id="post-body" class="metabox-holder columns-2">
1104
- <div id="post-body-content">
1105
- <div class="settings-wrapper">
1106
- <div class="inside">
1107
- <?php
1108
- if ( $gadwp->gapi_controller->gapi_errors_handler() || GADWP_Tools::get_cache( 'last_error' ) ) {
1109
- $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
1110
- }
1111
- if ( isset( $_POST['Authorize'] ) ) {
1112
- GADWP_Tools::clear_cache();
1113
- $gadwp->gapi_controller->token_request();
1114
- echo "<div class='updated'><p>" . __( "Use the red link (see below) to generate and get your access code!", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1115
- } else {
1116
- if ( isset( $message ) ) {
1117
- echo $message;
1118
- }
1119
- ?>
1120
- <form name="ga_dash_form" method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
1121
- <input type="hidden" name="options[ga_dash_hidden]" value="Y">
1122
- <?php wp_nonce_field('gadash_form','gadash_security'); ?>
1123
- <table class="gadwp-settings-options">
1124
- <tr>
1125
- <td colspan="2"><?php echo "<h2>" . __( "Network Setup", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1126
- </tr>
1127
- <tr>
1128
- <td colspan="2" class="gadwp-settings-title">
1129
- <div class="button-primary gadwp-settings-switchoo">
1130
- <input type="checkbox" name="options[ga_dash_network]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_network" <?php checked( $options['ga_dash_network'], 1); ?> onchange="this.form.submit()"> <label class="gadwp-settings-switchoo-label" for="ga_dash_network">
1131
- <div class="gadwp-settings-switchoo-inner"></div>
1132
- <div class="gadwp-settings-switchoo-switch"></div>
1133
- </label>
1134
- </div>
1135
- <div class="switch-desc"><?php echo " ".__("use a single Google Analytics account for the entire network", 'google-analytics-dashboard-for-wp' );?></div>
1136
- </td>
1137
- </tr>
1138
- <?php if ($options['ga_dash_network']){ //Network Mode check?>
1139
- <tr>
1140
- <td colspan="2"><hr></td>
1141
- </tr>
1142
- <tr>
1143
- <td colspan="2"><?php echo "<h2>" . __( "Plugin Authorization", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1144
- </tr>
1145
- <tr>
1146
- <td colspan="2" class="gadwp-settings-info">
1147
- <?php printf(__('You should watch the %1$s and read this %2$s before proceeding to authorization. This plugin requires a properly configured Google Analytics account!', 'google-analytics-dashboard-for-wp'), sprintf('<a href="%1$s" target="_blank">%2$s</a>', 'https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=top_video&utm_campaign=gadwp', __("video", 'google-analytics-dashboard-for-wp')), sprintf('<a href="%1$s" target="_blank">%2$s</a>', 'https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=top_tutorial&utm_campaign=gadwp', __("tutorial", 'google-analytics-dashboard-for-wp')));?>
1148
- </td>
1149
- </tr>
1150
- <?php
1151
- if ( ! $options['ga_dash_token'] || $options['ga_dash_userapi'] ) {
1152
- ?>
1153
- <tr>
1154
- <td colspan="2" class="gadwp-settings-info"><input name="options[ga_dash_userapi]" type="checkbox" id="ga_dash_userapi" value="1" <?php checked( $options['ga_dash_userapi'], 1 ); ?> onchange="this.form.submit()" /><?php echo " ".__("use your own API Project credentials", 'google-analytics-dashboard-for-wp' );?>
1155
- </td>
1156
- </tr>
1157
- <?php
1158
- }
1159
- if ( $options['ga_dash_userapi'] ) {
1160
- ?>
1161
- <tr>
1162
- <td class="gadwp-settings-title"><label for="options[ga_dash_clientid]"><?php _e("Client ID:", 'google-analytics-dashboard-for-wp'); ?></label></td>
1163
- <td><input type="text" name="options[ga_dash_clientid]" value="<?php echo esc_attr($options['ga_dash_clientid']); ?>" size="40" required="required"></td>
1164
- </tr>
1165
- <tr>
1166
- <td class="gadwp-settings-title"><label for="options[ga_dash_clientsecret]"><?php _e("Client Secret:", 'google-analytics-dashboard-for-wp'); ?></label></td>
1167
- <td><input type="text" name="options[ga_dash_clientsecret]" value="<?php echo esc_attr($options['ga_dash_clientsecret']); ?>" size="40" required="required"> <input type="hidden" name="options[ga_dash_hidden]" value="Y">
1168
- <?php wp_nonce_field('gadash_form','gadash_security'); ?>
1169
- </td>
1170
- </tr>
1171
- <?php
1172
- }
1173
- if ( $options['ga_dash_token'] ) {
1174
- ?>
1175
- <tr>
1176
- <td colspan="2"><input type="submit" name="Reset" class="button button-secondary" value="<?php _e( "Clear Authorization", 'google-analytics-dashboard-for-wp' ); ?>" /> <input type="submit" name="Clear" class="button button-secondary" value="<?php _e( "Clear Cache", 'google-analytics-dashboard-for-wp' ); ?>" /> <input type="submit" name="Refresh" class="button button-secondary" value="<?php _e( "Refresh Properties", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
1177
- </tr>
1178
- <tr>
1179
- <td colspan="2"><hr></td>
1180
- </tr>
1181
- <tr>
1182
- <td colspan="2"><?php echo "<h2>" . __( "Properties/Views Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1183
- </tr>
1184
- <?php
1185
- if ( isset( $options['ga_dash_tableid_network'] ) ) {
1186
- $options['ga_dash_tableid_network'] = json_decode( json_encode( $options['ga_dash_tableid_network'] ), false );
1187
- }
1188
- foreach ( GADWP_Tools::get_sites( array( 'limit' => apply_filters( 'gadwp_sites_limit', 100 ) ) ) as $blog ) {
1189
- ?>
1190
- <tr>
1191
- <td class="gadwp-settings-title-s"><label for="ga_dash_tableid_network"><?php echo '<strong>'.$blog['domain'].$blog['path'].'</strong>: ';?></label></td>
1192
- <td><select id="ga_dash_tableid_network" <?php disabled(!empty($options['ga_dash_profile_list']),false);?> name="options[ga_dash_tableid_network][<?php echo $blog['blog_id'];?>]">
1193
- <?php
1194
- if ( ! empty( $options['ga_dash_profile_list'] ) ) {
1195
- foreach ( $options['ga_dash_profile_list'] as $items ) {
1196
- if ( $items[3] ) {
1197
- $temp_id = $blog['blog_id'];
1198
- echo '<option value="' . esc_attr( $items[1] ) . '" ' . selected( $items[1], isset( $options['ga_dash_tableid_network']->$temp_id ) ? $options['ga_dash_tableid_network']->$temp_id : '', false );
1199
- echo ' title="' . __( "View Name:", 'google-analytics-dashboard-for-wp' ) . ' ' . esc_attr( $items[0] ) . '">' . esc_html( GADWP_Tools::strip_protocol( $items[3] ) ) . ' &#8658; ' . esc_attr( $items[0] ) . '</option>';
1200
- }
1201
- }
1202
- } else {
1203
- echo '<option value="">' . __( "Property not found", 'google-analytics-dashboard-for-wp' ) . '</option>';
1204
- }
1205
- ?>
1206
- </select> <br /></td>
1207
- </tr>
1208
- <?php
1209
- }
1210
- ?>
1211
- <tr>
1212
- <td colspan="2"><?php echo "<h2>" . __( "Automatic Updates", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1213
- </tr>
1214
- <tr>
1215
- <td colspan="2" class="gadwp-settings-title">
1216
- <div class="button-primary gadwp-settings-switchoo">
1217
- <input type="checkbox" name="options[automatic_updates_minorversion]" value="1" class="gadwp-settings-switchoo-checkbox" id="automatic_updates_minorversion" <?php checked( $options['automatic_updates_minorversion'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="automatic_updates_minorversion">
1218
- <div class="gadwp-settings-switchoo-inner"></div>
1219
- <div class="gadwp-settings-switchoo-switch"></div>
1220
- </label>
1221
- </div>
1222
- <div class="switch-desc"><?php echo " ".__( "automatic updates for minor versions (security and maintenance releases only)", 'google-analytics-dashboard-for-wp' );?></div>
1223
- </td>
1224
- </tr>
1225
- <tr>
1226
- <td colspan="2"><hr><?php echo "<h2>" . __( "Exclude Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1227
- </tr>
1228
- <tr>
1229
- <td colspan="2" class="gadwp-settings-title">
1230
- <div class="button-primary gadwp-settings-switchoo">
1231
- <input type="checkbox" name="options[ga_dash_excludesa]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_excludesa"<?php checked( $options['ga_dash_excludesa'], 1); ?>"> <label class="gadwp-settings-switchoo-label" for="ga_dash_excludesa">
1232
- <div class="gadwp-settings-switchoo-inner"></div>
1233
- <div class="gadwp-settings-switchoo-switch"></div>
1234
- </label>
1235
- </div>
1236
- <div class="switch-desc"><?php echo " ".__("exclude Super Admin tracking for the entire network", 'google-analytics-dashboard-for-wp' );?></div>
1237
- </td>
1238
- </tr>
1239
- <tr>
1240
- <td colspan="2"><hr></td>
1241
- </tr>
1242
- <tr>
1243
- <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
1244
- </tr>
1245
- <?php
1246
- } else {
1247
- ?>
1248
- <tr>
1249
- <td colspan="2"><hr></td>
1250
- </tr>
1251
- <tr>
1252
- <td colspan="2"><input type="submit" name="Authorize" class="button button-secondary" id="authorize" value="<?php _e( "Authorize Plugin", 'google-analytics-dashboard-for-wp' ); ?>" /> <input type="submit" name="Clear" class="button button-secondary" value="<?php _e( "Clear Cache", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
1253
- </tr>
1254
- <?php } //Network Mode check?>
1255
- <tr>
1256
- <td colspan="2"><hr></td>
1257
- </tr>
1258
- </table>
1259
- </form>
1260
- <?php
1261
- self::output_sidebar();
1262
- return;
1263
- }
1264
- ?>
1265
- </table>
1266
- </form>
1267
- <?php
1268
- }
1269
- self::output_sidebar();
1270
- }
1271
-
1272
- public static function output_sidebar() {
1273
- global $wp_version;
1274
-
1275
- $gadwp = GADWP();
1276
- ?>
1277
- </div>
1278
- </div>
1279
- </div>
1280
- <div id="postbox-container-1" class="postbox-container">
1281
- <div class="meta-box-sortables">
1282
- <div class="postbox">
1283
- <h3>
1284
- <span><?php _e("Setup Tutorial & Demo",'google-analytics-dashboard-for-wp') ?></span>
1285
- </h3>
1286
- <div class="inside">
1287
- <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=video&utm_campaign=gadwp" target="_blank"><img src="<?php echo plugins_url( 'images/google-analytics-dashboard.png' , __FILE__ );?>" width="100%" alt="" /></a>
1288
- </div>
1289
- </div>
1290
- <div class="postbox">
1291
- <h3>
1292
- <span><?php _e("Follow & Review",'google-analytics-dashboard-for-wp')?></span>
1293
- </h3>
1294
- <div class="inside">
1295
- <div class="gadash-desc">
1296
- <div style="margin-left: -10px;">
1297
- <div class="g-page" data-width="273" data-href="//plus.google.com/+Deconfcom" data-layout="landscape" data-showtagline="false" data-showcoverphoto="false" data-rel="publisher"></div>
1298
- </div>
1299
- <script type="text/javascript">
1300
- (function() {
1301
- var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
1302
- po.src = 'https://apis.google.com/js/platform.js';
1303
- var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
1304
- })();
1305
- </script>
1306
- </div>
1307
- <br />
1308
- <div class="gadash-desc">
1309
- <a href="https://twitter.com/deconfcom" class="twitter-follow-button" data-show-count="false" data-size="large">Follow @deconfcom</a>
1310
- <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
1311
- </div>
1312
- <br />
1313
- <div class="gadash-title">
1314
- <a href="http://wordpress.org/support/view/plugin-reviews/google-analytics-dashboard-for-wp#plugin-info"><img src="<?php echo plugins_url( 'images/star.png' , __FILE__ ); ?>" /></a>
1315
- </div>
1316
- <div class="gadash-desc">
1317
- <?php printf(__('Your feedback and review are both important, %s!', 'google-analytics-dashboard-for-wp'), sprintf('<a href="http://wordpress.org/support/view/plugin-reviews/google-analytics-dashboard-for-wp#plugin-info">%s</a>', __('rate this plugin', 'google-analytics-dashboard-for-wp')));?>
1318
- </div>
1319
- </div>
1320
- </div>
1321
- <div class="postbox">
1322
- <h3>
1323
- <span><?php _e("Further Reading",'google-analytics-dashboard-for-wp')?></span>
1324
- </h3>
1325
- <div class="inside">
1326
- <div class="gadash-title">
1327
- <a href="https://deconf.com/clicky-web-analytics-review/?utm_source=gadwp_config&utm_medium=link&utm_content=clicky&utm_campaign=gadwp"><img src="<?php echo plugins_url( 'images/clicky.png' , __FILE__ ); ?>" /></a>
1328
- </div>
1329
- <div class="gadash-desc">
1330
- <?php printf(__('%s service with users tracking at IP level.', 'google-analytics-dashboard-for-wp'), sprintf('<a href="https://deconf.com/clicky-web-analytics-review/?utm_source=gadwp_config&utm_medium=link&utm_content=clicky&utm_campaign=gadwp">%s</a>', __('Web Analytics', 'google-analytics-dashboard-for-wp')));?>
1331
- </div>
1332
- <br />
1333
- <div class="gadash-title">
1334
- <a href="https://deconf.com/move-website-https-ssl/?utm_source=gadwp_config&utm_medium=link&utm_content=ssl&utm_campaign=gadwp"><img src="<?php echo plugins_url( 'images/ssl.png' , __FILE__ ); ?>" /></a>
1335
- </div>
1336
- <div class="gadash-desc">
1337
- <?php printf(__('%s by moving your website to HTTPS/SSL.', 'google-analytics-dashboard-for-wp'), sprintf('<a href="https://deconf.com/move-website-https-ssl/?utm_source=gadwp_config&utm_medium=link&utm_content=ssl&utm_campaign=gadwp">%s</a>', __('Improve search rankings', 'google-analytics-dashboard-for-wp')));?>
1338
- </div>
1339
- <br />
1340
- <div class="gadash-title">
1341
- <a href="https://deconf.com/wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=plugins&utm_campaign=gadwp"><img src="<?php echo plugins_url( 'images/wp.png' , __FILE__ ); ?>" /></a>
1342
- </div>
1343
- <div class="gadash-desc">
1344
- <?php printf(__('Other %s written by the same author', 'google-analytics-dashboard-for-wp'), sprintf('<a href="https://deconf.com/wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=plugins&utm_campaign=gadwp">%s</a>', __('WordPress Plugins', 'google-analytics-dashboard-for-wp')));?>
1345
- </div>
1346
- </div>
1347
- </div>
1348
- </div>
1349
- </div>
1350
- </div>
1351
- </div>
1352
- <?php
1353
- //Dismiss the admin update notice
1354
- if ( version_compare( $wp_version, '4.2', '<' ) && current_user_can('manage_options') ) {
1355
- delete_option('gadwp_got_updated');
1356
- }
1357
- }
1358
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ final class GADWP_Settings {
15
+
16
+ private static function update_options( $who ) {
17
+ $gadwp = GADWP();
18
+ $network_settings = false;
19
+ $options = $gadwp->config->options; // Get current options
20
+ if ( isset( $_POST['options']['ga_dash_hidden'] ) && isset( $_POST['options'] ) && ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) && $who != 'Reset' ) {
21
+ $new_options = $_POST['options'];
22
+ if ( $who == 'tracking' ) {
23
+ $options['ga_dash_anonim'] = 0;
24
+ $options['ga_event_tracking'] = 0;
25
+ $options['ga_enhanced_links'] = 0;
26
+ $options['ga_dash_remarketing'] = 0;
27
+ $options['ga_dash_adsense'] = 0;
28
+ $options['ga_event_bouncerate'] = 0;
29
+ $options['ga_crossdomain_tracking'] = 0;
30
+ $options['ga_aff_tracking'] = 0;
31
+ $options['ga_hash_tracking'] = 0;
32
+ if ( isset( $_POST['options']['ga_tracking_code'] ) ) {
33
+ $new_options['ga_tracking_code'] = trim( $new_options['ga_tracking_code'], "\t" );
34
+ }
35
+ if ( empty( $new_options['ga_track_exclude'] ) ) {
36
+ $new_options['ga_track_exclude'] = array();
37
+ }
38
+ } else if ( $who == 'backend' ) {
39
+ $options['switch_profile'] = 0;
40
+ $options['backend_item_reports'] = 0;
41
+ $options['dashboard_widget'] = 0;
42
+ if ( empty( $new_options['ga_dash_access_back'] ) ) {
43
+ $new_options['ga_dash_access_back'][] = 'administrator';
44
+ }
45
+ } else if ( $who == 'frontend' ) {
46
+ $options['frontend_item_reports'] = 0;
47
+ if ( empty( $new_options['ga_dash_access_front'] ) ) {
48
+ $new_options['ga_dash_access_front'][] = 'administrator';
49
+ }
50
+ } else if ( $who == 'general' ) {
51
+ $options['ga_dash_userapi'] = 0;
52
+ if ( ! is_multisite() ) {
53
+ $options['automatic_updates_minorversion'] = 0;
54
+ }
55
+ } else if ( $who == 'network' ) {
56
+ $options['ga_dash_userapi'] = 0;
57
+ $options['ga_dash_network'] = 0;
58
+ $options['ga_dash_excludesa'] = 0;
59
+ $options['automatic_updates_minorversion'] = 0;
60
+ $network_settings = true;
61
+ }
62
+ $options = array_merge( $options, $new_options );
63
+ $gadwp->config->options = $options;
64
+ $gadwp->config->set_plugin_options( $network_settings );
65
+ }
66
+ return $options;
67
+ }
68
+
69
+ private static function navigation_tabs( $tabs ) {
70
+ echo '<h2 class="nav-tab-wrapper">';
71
+ foreach ( $tabs as $tab => $name ) {
72
+ echo "<a class='nav-tab' id='tab-$tab' href='#top#gadwp-$tab'>$name</a>";
73
+ }
74
+ echo '</h2>';
75
+ }
76
+
77
+ public static function frontend_settings() {
78
+ $gadwp = GADWP();
79
+ if ( ! current_user_can( 'manage_options' ) ) {
80
+ return;
81
+ }
82
+ $options = self::update_options( 'frontend' );
83
+ if ( isset( $_POST['options']['ga_dash_hidden'] ) ) {
84
+ $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
85
+ if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
86
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
87
+ }
88
+ }
89
+ if ( ! $gadwp->config->options['ga_dash_tableid_jail'] || ! $gadwp->config->options['ga_dash_token'] ) {
90
+ $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
91
+ }
92
+ ?>
93
+ <form name="ga_dash_form" method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
94
+ <div class="wrap">
95
+ <?php echo "<h2>" . __( "Google Analytics Frontend Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?><hr>
96
+ </div>
97
+ <div id="poststuff" class="gadwp">
98
+ <div id="post-body" class="metabox-holder columns-2">
99
+ <div id="post-body-content">
100
+ <div class="settings-wrapper">
101
+ <div class="inside">
102
+ <?php if (isset($message)) echo $message; ?>
103
+ <table class="gadwp-settings-options">
104
+ <tr>
105
+ <td colspan="2"><?php echo "<h2>" . __( "Permissions", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
106
+ </tr>
107
+ <tr>
108
+ <td class="roles gadwp-settings-title"><label for="ga_dash_access_front"><?php _e("Show stats to:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
109
+ <td class="gadwp-settings-roles">
110
+ <?php
111
+ if ( ! isset( $wp_roles ) ) {
112
+ $wp_roles = new WP_Roles();
113
+ }
114
+ $i = 0;
115
+ ?>
116
+ <table>
117
+ <tr>
118
+ <?php
119
+ foreach ( $wp_roles->role_names as $role => $name ) {
120
+ if ( $role != 'subscriber' ) {
121
+ $i++;
122
+ ?>
123
+ <td><label> <input type="checkbox" name="options[ga_dash_access_front][]" value="<?php echo $role; ?>" <?php if (in_array($role,$options['ga_dash_access_front']) || $role=='administrator') echo 'checked="checked"'; if ($role=='administrator') echo 'disabled="disabled"';?> /><?php echo $name; ?>
124
+ </label></td>
125
+ <?php
126
+ }
127
+ if ( $i % 4 == 0 ) {
128
+ ?>
129
+ </tr>
130
+ <tr>
131
+ <?php
132
+ }
133
+ }
134
+ ?>
135
+ </table>
136
+ </td>
137
+ </tr>
138
+ <tr>
139
+ <td colspan="2" class="gadwp-settings-title">
140
+ <div class="button-primary gadwp-settings-switchoo">
141
+ <input type="checkbox" name="options[frontend_item_reports]" value="1" class="gadwp-settings-switchoo-checkbox" id="frontend_item_reports" <?php checked( $options['frontend_item_reports'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="frontend_item_reports">
142
+ <div class="gadwp-settings-switchoo-inner"></div>
143
+ <div class="gadwp-settings-switchoo-switch"></div>
144
+ </label>
145
+ </div>
146
+ <div class="switch-desc"><?php echo " ".__("enable web page reports on frontend", 'google-analytics-dashboard-for-wp' );?></div>
147
+ </td>
148
+ </tr>
149
+ <tr>
150
+ <td colspan="2"><hr></td>
151
+ </tr>
152
+ <tr>
153
+ <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
154
+ </tr>
155
+ </table>
156
+ <input type="hidden" name="options[ga_dash_hidden]" value="Y">
157
+ <?php wp_nonce_field('gadash_form','gadash_security');?>
158
+ </form>
159
+ <?php
160
+ self::output_sidebar();
161
+ }
162
+
163
+ public static function backend_settings() {
164
+ $gadwp = GADWP();
165
+ if ( ! current_user_can( 'manage_options' ) ) {
166
+ return;
167
+ }
168
+ $options = self::update_options( 'backend' );
169
+ if ( isset( $_POST['options']['ga_dash_hidden'] ) ) {
170
+ $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
171
+ if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
172
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
173
+ }
174
+ }
175
+ if ( ! $gadwp->config->options['ga_dash_tableid_jail'] || ! $gadwp->config->options['ga_dash_token'] ) {
176
+ $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
177
+ }
178
+ ?>
179
+ <form name="ga_dash_form" method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
180
+ <div class="wrap">
181
+ <?php echo "<h2>" . __( "Google Analytics Backend Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?><hr>
182
+ </div>
183
+ <div id="poststuff" class="gadwp">
184
+ <div id="post-body" class="metabox-holder columns-2">
185
+ <div id="post-body-content">
186
+ <div class="settings-wrapper">
187
+ <div class="inside">
188
+ <?php if (isset($message)) echo $message; ?>
189
+ <table class="gadwp-settings-options">
190
+ <tr>
191
+ <td colspan="2"><?php echo "<h2>" . __( "Permissions", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
192
+ </tr>
193
+ <tr>
194
+ <td class="roles gadwp-settings-title"><label for="ga_dash_access_back"><?php _e("Show stats to:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
195
+ <td class="gadwp-settings-roles">
196
+ <?php
197
+ if ( ! isset( $wp_roles ) ) {
198
+ $wp_roles = new WP_Roles();
199
+ }
200
+ $i = 0;
201
+ ?>
202
+ <table>
203
+ <tr>
204
+ <?php
205
+
206
+ foreach ( $wp_roles->role_names as $role => $name ) {
207
+ if ( $role != 'subscriber' ) {
208
+ $i++;
209
+ ?>
210
+ <td><label> <input type="checkbox" name="options[ga_dash_access_back][]" value="<?php echo $role; ?>" <?php if (in_array($role,$options['ga_dash_access_back']) || $role=='administrator') echo 'checked="checked"'; if ($role=='administrator') echo 'disabled="disabled"';?> />
211
+ <?php echo $name; ?>
212
+ </label></td>
213
+ <?php
214
+ }
215
+ if ( $i % 4 == 0 ) {
216
+ ?>
217
+ </tr>
218
+ <tr>
219
+ <?php
220
+ }
221
+ }
222
+ ?>
223
+ </table>
224
+ </td>
225
+ </tr>
226
+ <tr>
227
+ <td colspan="2" class="gadwp-settings-title">
228
+ <div class="button-primary gadwp-settings-switchoo">
229
+ <input type="checkbox" name="options[switch_profile]" value="1" class="gadwp-settings-switchoo-checkbox" id="switch_profile" <?php checked( $options['switch_profile'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="switch_profile">
230
+ <div class="gadwp-settings-switchoo-inner"></div>
231
+ <div class="gadwp-settings-switchoo-switch"></div>
232
+ </label>
233
+ </div>
234
+ <div class="switch-desc"><?php _e ( "enable Switch View functionality", 'google-analytics-dashboard-for-wp' );?></div>
235
+ </td>
236
+ </tr>
237
+ <tr>
238
+ <td colspan="2" class="gadwp-settings-title">
239
+ <div class="button-primary gadwp-settings-switchoo">
240
+ <input type="checkbox" name="options[backend_item_reports]" value="1" class="gadwp-settings-switchoo-checkbox" id="backend_item_reports" <?php checked( $options['backend_item_reports'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="backend_item_reports">
241
+ <div class="gadwp-settings-switchoo-inner"></div>
242
+ <div class="gadwp-settings-switchoo-switch"></div>
243
+ </label>
244
+ </div>
245
+ <div class="switch-desc"><?php _e ( "enable reports on Posts List and Pages List", 'google-analytics-dashboard-for-wp' );?></div>
246
+ </td>
247
+ </tr>
248
+ <tr>
249
+ <td colspan="2" class="gadwp-settings-title">
250
+ <div class="button-primary gadwp-settings-switchoo">
251
+ <input type="checkbox" name="options[dashboard_widget]" value="1" class="gadwp-settings-switchoo-checkbox" id="dashboard_widget" <?php checked( $options['dashboard_widget'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="dashboard_widget">
252
+ <div class="gadwp-settings-switchoo-inner"></div>
253
+ <div class="gadwp-settings-switchoo-switch"></div>
254
+ </label>
255
+ </div>
256
+ <div class="switch-desc"><?php _e ( "enable the main Dashboard Widget", 'google-analytics-dashboard-for-wp' );?></div>
257
+ </td>
258
+ </tr>
259
+ <tr>
260
+ <td colspan="2"><hr><?php echo "<h2>" . __( "Real-Time Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
261
+ </tr>
262
+ <tr>
263
+ <td colspan="2" class="gadwp-settings-title"> <?php _e("Maximum number of pages to display on real-time tab:", 'google-analytics-dashboard-for-wp'); ?>
264
+ <input type="number" name="options[ga_realtime_pages]" id="ga_realtime_pages" value="<?php echo (int)$options['ga_realtime_pages']; ?>" size="3">
265
+ </td>
266
+ </tr>
267
+ <tr>
268
+ <td colspan="2"><hr><?php echo "<h2>" . __( "Location Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
269
+ </tr>
270
+ <tr>
271
+ <td colspan="2" class="gadwp-settings-title">
272
+ <?php echo __("Target Geo Map to country:", 'google-analytics-dashboard-for-wp'); ?>
273
+ <input type="text" style="text-align: center;" name="options[ga_target_geomap]" value="<?php echo esc_attr($options['ga_target_geomap']); ?>" size="3">
274
+ </td>
275
+ </tr>
276
+ <tr>
277
+ <td colspan="2" class="gadwp-settings-title">
278
+ <?php echo __("Maps API Key:", 'google-analytics-dashboard-for-wp'); ?>
279
+ <input type="text" style="text-align: center;" name="options[maps_api_key]" value="<?php echo esc_attr($options['maps_api_key']); ?>" size="50">
280
+ </td>
281
+ </tr>
282
+ <tr>
283
+ <td colspan="2"><hr><?php echo "<h2>" . __( "404 Errors Report", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
284
+ </tr>
285
+ <tr>
286
+ <td colspan="2" class="gadwp-settings-title">
287
+ <?php echo __("404 Page Title contains:", 'google-analytics-dashboard-for-wp'); ?>
288
+ <input type="text" style="text-align: center;" name="options[pagetitle_404]" value="<?php echo esc_attr($options['pagetitle_404']); ?>" size="20">
289
+ </td>
290
+ </tr>
291
+ <tr>
292
+ <td colspan="2"><hr></td>
293
+ </tr>
294
+ <tr>
295
+ <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
296
+ </tr>
297
+ </table>
298
+ <input type="hidden" name="options[ga_dash_hidden]" value="Y">
299
+ <?php wp_nonce_field('gadash_form','gadash_security'); ?>
300
+
301
+ </form>
302
+ <?php
303
+ self::output_sidebar();
304
+ }
305
+
306
+ public static function tracking_settings() {
307
+ $gadwp = GADWP();
308
+
309
+ if ( ! current_user_can( 'manage_options' ) ) {
310
+ return;
311
+ }
312
+ $options = self::update_options( 'tracking' );
313
+ if ( isset( $_POST['options']['ga_dash_hidden'] ) ) {
314
+ $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
315
+ if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
316
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
317
+ }
318
+ }
319
+ if ( ! $gadwp->config->options['ga_dash_tableid_jail'] ) {
320
+ $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
321
+ }
322
+ if ( ! $options['ga_dash_tracking'] ) {
323
+ $message = "<div class='error'><p>" . __( "The tracking component is disabled. You should set <strong>Tracking Options</strong> to <strong>Enabled</strong>", 'google-analytics-dashboard-for-wp' ) . ".</p></div>";
324
+ }
325
+ ?>
326
+ <form name="ga_dash_form" method="post" action="<?php esc_url($_SERVER['REQUEST_URI']); ?>">
327
+ <div class="wrap">
328
+ <?php echo "<h2>" . __( "Google Analytics Tracking Code", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?>
329
+ </div>
330
+ <div id="poststuff" class="gadwp">
331
+ <div id="post-body" class="metabox-holder columns-2">
332
+ <div id="post-body-content">
333
+ <div class="settings-wrapper">
334
+ <div class="inside">
335
+ <?php
336
+ $tabs = array( 'basic' => __( "Basic Settings", 'google-analytics-dashboard-for-wp' ), 'events' => __( "Events Tracking", 'google-analytics-dashboard-for-wp' ), 'custom' => __( "Custom Definitions", 'google-analytics-dashboard-for-wp' ), 'exclude' => __( "Exclude Tracking", 'google-analytics-dashboard-for-wp' ), 'advanced' => __( "Advanced Settings", 'google-analytics-dashboard-for-wp' ) );
337
+ self::navigation_tabs( $tabs );
338
+ if ( isset( $message ) )
339
+ echo $message;
340
+ ?>
341
+ <div id="gadwp-basic">
342
+ <table class="gadwp-settings-options">
343
+ <tr>
344
+ <td colspan="2"><?php echo "<h2>" . __( "Tracking Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
345
+ </tr>
346
+ <tr>
347
+ <td class="gadwp-settings-title"><label for="ga_dash_tracking"><?php _e("Tracking Options:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
348
+ <td><select id="ga_dash_tracking" name="options[ga_dash_tracking]" onchange="this.form.submit()">
349
+ <option value="0" <?php selected( $options['ga_dash_tracking'], 0 ); ?>><?php _e("Disabled", 'google-analytics-dashboard-for-wp');?></option>
350
+ <option value="1" <?php selected( $options['ga_dash_tracking'], 1 ); ?>><?php _e("Enabled", 'google-analytics-dashboard-for-wp');?></option>
351
+ </select></td>
352
+ </tr>
353
+ <?php if ($options['ga_dash_tracking']) {?>
354
+ <tr>
355
+ <td class="gadwp-settings-title"></td>
356
+ <td>
357
+ <?php $profile_info = GADWP_Tools::get_selected_profile($gadwp->config->options['ga_dash_profile_list'], $gadwp->config->options['ga_dash_tableid_jail']); ?>
358
+ <?php echo '<pre>' . __("View Name:", 'google-analytics-dashboard-for-wp') . "\t" . esc_html($profile_info[0]) . "<br />" . __("Tracking ID:", 'google-analytics-dashboard-for-wp') . "\t" . esc_html($profile_info[2]) . "<br />" . __("Default URL:", 'google-analytics-dashboard-for-wp') . "\t" . esc_html($profile_info[3]) . "<br />" . __("Time Zone:", 'google-analytics-dashboard-for-wp') . "\t" . esc_html($profile_info[5]) . '</pre>';?>
359
+ </td>
360
+ </tr>
361
+ <?php }?>
362
+ <tr>
363
+ <td colspan="2"><hr><?php echo "<h2>" . __( "Basic Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
364
+ </tr>
365
+ <tr>
366
+ <td class="gadwp-settings-title"><label for="ga_dash_tracking_type"><?php _e("Tracking Type:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
367
+ <td><select id="ga_dash_tracking_type" name="options[ga_dash_tracking_type]">
368
+ <option value="classic" <?php selected( $options['ga_dash_tracking_type'], 'classic' ); ?>><?php _e("Classic Analytics", 'google-analytics-dashboard-for-wp');?></option>
369
+ <option value="universal" <?php selected( $options['ga_dash_tracking_type'], 'universal' ); ?>><?php _e("Universal Analytics", 'google-analytics-dashboard-for-wp');?></option>
370
+ </select></td>
371
+ </tr>
372
+ <tr>
373
+ <td colspan="2" class="gadwp-settings-title">
374
+ <div class="button-primary gadwp-settings-switchoo">
375
+ <input type="checkbox" name="options[ga_dash_anonim]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_anonim" <?php checked( $options['ga_dash_anonim'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_dash_anonim">
376
+ <div class="gadwp-settings-switchoo-inner"></div>
377
+ <div class="gadwp-settings-switchoo-switch"></div>
378
+ </label>
379
+ </div>
380
+ <div class="switch-desc"><?php echo " ".__("anonymize IPs while tracking", 'google-analytics-dashboard-for-wp' );?></div>
381
+ </td>
382
+ </tr>
383
+ <tr>
384
+ <td colspan="2" class="gadwp-settings-title">
385
+ <div class="button-primary gadwp-settings-switchoo">
386
+ <input type="checkbox" name="options[ga_dash_remarketing]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_remarketing" <?php checked( $options['ga_dash_remarketing'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_dash_remarketing">
387
+ <div class="gadwp-settings-switchoo-inner"></div>
388
+ <div class="gadwp-settings-switchoo-switch"></div>
389
+ </label>
390
+ </div>
391
+ <div class="switch-desc"><?php echo " ".__("enable remarketing, demographics and interests reports", 'google-analytics-dashboard-for-wp' );?></div>
392
+ </td>
393
+ </tr>
394
+ </table>
395
+ </div>
396
+ <div id="gadwp-events">
397
+ <table class="gadwp-settings-options">
398
+ <tr>
399
+ <td colspan="2"><?php echo "<h2>" . __( "Events Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
400
+ </tr>
401
+ <tr>
402
+ <td colspan="2" class="gadwp-settings-title">
403
+ <div class="button-primary gadwp-settings-switchoo">
404
+ <input type="checkbox" name="options[ga_event_tracking]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_event_tracking" <?php checked( $options['ga_event_tracking'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_event_tracking">
405
+ <div class="gadwp-settings-switchoo-inner"></div>
406
+ <div class="gadwp-settings-switchoo-switch"></div>
407
+ </label>
408
+ </div>
409
+ <div class="switch-desc"><?php echo " ".__("track downloads, mailto and outbound links", 'google-analytics-dashboard-for-wp' ); ?></div>
410
+ </td>
411
+ </tr>
412
+ <tr>
413
+ <td class="gadwp-settings-title"><label for="ga_event_downloads"><?php _e("Downloads Regex:", 'google-analytics-dashboard-for-wp'); ?></label></td>
414
+ <td><input type="text" id="ga_event_downloads" name="options[ga_event_downloads]" value="<?php echo esc_attr($options['ga_event_downloads']); ?>" size="50"></td>
415
+ </tr>
416
+ <tr>
417
+ <td colspan="2" class="gadwp-settings-title">
418
+ <div class="button-primary gadwp-settings-switchoo">
419
+ <input type="checkbox" name="options[ga_aff_tracking]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_aff_tracking" <?php checked( $options['ga_aff_tracking'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_aff_tracking">
420
+ <div class="gadwp-settings-switchoo-inner"></div>
421
+ <div class="gadwp-settings-switchoo-switch"></div>
422
+ </label>
423
+ </div>
424
+ <div class="switch-desc"><?php echo " ".__("track affiliate links matching this regex", 'google-analytics-dashboard-for-wp' ); ?></div>
425
+ </td>
426
+ </tr>
427
+ <tr>
428
+ <td class="gadwp-settings-title"><label for="ga_event_affiliates"><?php _e("Affiliates Regex:", 'google-analytics-dashboard-for-wp'); ?></label></td>
429
+ <td><input type="text" id="ga_event_affiliates" name="options[ga_event_affiliates]" value="<?php echo esc_attr($options['ga_event_affiliates']); ?>" size="50"></td>
430
+ </tr>
431
+ <tr>
432
+ <td colspan="2" class="gadwp-settings-title">
433
+ <div class="button-primary gadwp-settings-switchoo">
434
+ <input type="checkbox" name="options[ga_hash_tracking]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_hash_tracking" <?php checked( $options['ga_hash_tracking'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_hash_tracking">
435
+ <div class="gadwp-settings-switchoo-inner"></div>
436
+ <div class="gadwp-settings-switchoo-switch"></div>
437
+ </label>
438
+ </div>
439
+ <div class="switch-desc"><?php echo " ".__("track fragment identifiers, hashmarks (#) in URI links", 'google-analytics-dashboard-for-wp' ); ?></div>
440
+ </td>
441
+ </tr>
442
+ </table>
443
+ </div>
444
+ <div id="gadwp-custom">
445
+ <table class="gadwp-settings-options">
446
+ <tr>
447
+ <td colspan="2"><?php echo "<h2>" . __( "Custom Definitions", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
448
+ </tr>
449
+ <tr>
450
+ <td class="gadwp-settings-title"><label for="ga_author_dimindex"><?php _e("Authors:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
451
+ <td><select id="ga_author_dimindex" name="options[ga_author_dimindex]">
452
+ <?php for ($i=0;$i<21;$i++){?>
453
+ <option value="<?php echo $i;?>" <?php selected( $options['ga_author_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
454
+ <?php }?>
455
+ </select></td>
456
+ </tr>
457
+ <tr>
458
+ <td class="gadwp-settings-title"><label for="ga_pubyear_dimindex"><?php _e("Publication Year:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
459
+ <td><select id="ga_pubyear_dimindex" name="options[ga_pubyear_dimindex]">
460
+ <?php for ($i=0;$i<21;$i++){?>
461
+ <option value="<?php echo $i;?>" <?php selected( $options['ga_pubyear_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
462
+ <?php }?>
463
+ </select></td>
464
+ </tr>
465
+ <tr>
466
+ <td class="gadwp-settings-title"><label for="ga_pubyearmonth_dimindex"><?php _e("Publication Month:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
467
+ <td><select id="ga_pubyearmonth_dimindex" name="options[ga_pubyearmonth_dimindex]">
468
+ <?php for ($i=0;$i<21;$i++){?>
469
+ <option value="<?php echo $i;?>" <?php selected( $options['ga_pubyearmonth_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
470
+ <?php }?>
471
+ </select></td>
472
+ </tr>
473
+ <tr>
474
+ <td class="gadwp-settings-title"><label for="ga_category_dimindex"><?php _e("Categories:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
475
+ <td><select id="ga_category_dimindex" name="options[ga_category_dimindex]">
476
+ <?php for ($i=0;$i<21;$i++){?>
477
+ <option value="<?php echo $i;?>" <?php selected( $options['ga_category_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
478
+ <?php }?>
479
+ </select></td>
480
+ </tr>
481
+ <tr>
482
+ <td class="gadwp-settings-title"><label for="ga_user_dimindex"><?php _e("User Type:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
483
+ <td><select id="ga_user_dimindex" name="options[ga_user_dimindex]">
484
+ <?php for ($i=0;$i<21;$i++){?>
485
+ <option value="<?php echo $i;?>" <?php selected( $options['ga_user_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
486
+ <?php }?>
487
+ </select></td>
488
+ </tr>
489
+ <tr>
490
+ <td class="gadwp-settings-title"><label for="ga_tag_dimindex"><?php _e("Tags:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
491
+ <td><select id="ga_tag_dimindex" name="options[ga_tag_dimindex]">
492
+ <?php for ($i=0;$i<21;$i++){?>
493
+ <option value="<?php echo $i;?>" <?php selected( $options['ga_tag_dimindex'], $i ); ?>><?php echo $i==0?'Disabled':'dimension '.$i; ?></option>
494
+ <?php }?>
495
+ </select></td>
496
+ </tr>
497
+ </table>
498
+ </div>
499
+ <div id="gadwp-advanced">
500
+ <table class="gadwp-settings-options">
501
+ <tr>
502
+ <td colspan="2"><?php echo "<h2>" . __( "Advanced Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
503
+ </tr>
504
+ <tr>
505
+ <td class="gadwp-settings-title"><label for="ga_speed_samplerate"><?php _e("Page Speed SR:", 'google-analytics-dashboard-for-wp'); ?></label></td>
506
+ <td><input type="number" id="ga_speed_samplerate" name="options[ga_speed_samplerate]" value="<?php echo (int)($options['ga_speed_samplerate']); ?>" max="100" min="1"> %</td>
507
+ </tr>
508
+ <tr>
509
+ <td colspan="2" class="gadwp-settings-title">
510
+ <div class="button-primary gadwp-settings-switchoo">
511
+ <input type="checkbox" name="options[ga_event_bouncerate]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_event_bouncerate" <?php checked( $options['ga_event_bouncerate'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_event_bouncerate">
512
+ <div class="gadwp-settings-switchoo-inner"></div>
513
+ <div class="gadwp-settings-switchoo-switch"></div>
514
+ </label>
515
+ </div>
516
+ <div class="switch-desc"><?php echo " ".__("exclude events from bounce-rate calculation", 'google-analytics-dashboard-for-wp' );?></div>
517
+ </td>
518
+ </tr>
519
+ <tr>
520
+ <td colspan="2" class="gadwp-settings-title">
521
+ <div class="button-primary gadwp-settings-switchoo">
522
+ <input type="checkbox" name="options[ga_enhanced_links]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_enhanced_links" <?php checked( $options['ga_enhanced_links'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_enhanced_links">
523
+ <div class="gadwp-settings-switchoo-inner"></div>
524
+ <div class="gadwp-settings-switchoo-switch"></div>
525
+ </label>
526
+ </div>
527
+ <div class="switch-desc"><?php echo " ".__("enable enhanced link attribution", 'google-analytics-dashboard-for-wp' );?></div>
528
+ </td>
529
+ </tr>
530
+ <tr>
531
+ <td colspan="2" class="gadwp-settings-title">
532
+ <div class="button-primary gadwp-settings-switchoo">
533
+ <input type="checkbox" name="options[ga_dash_adsense]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_adsense" <?php checked( $options['ga_dash_adsense'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_dash_adsense">
534
+ <div class="gadwp-settings-switchoo-inner"></div>
535
+ <div class="gadwp-settings-switchoo-switch"></div>
536
+ </label>
537
+ </div>
538
+ <div class="switch-desc"><?php echo " ".__("enable AdSense account linking", 'google-analytics-dashboard-for-wp' );?></div>
539
+ </td>
540
+ </tr>
541
+ <tr>
542
+ <td colspan="2"><?php echo "<h2>" . __( "Cross-domain Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
543
+ </tr>
544
+ <tr>
545
+ <td colspan="2" class="gadwp-settings-title">
546
+ <div class="button-primary gadwp-settings-switchoo">
547
+ <input type="checkbox" name="options[ga_crossdomain_tracking]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_crossdomain_tracking" <?php checked( $options['ga_crossdomain_tracking'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="ga_crossdomain_tracking">
548
+ <div class="gadwp-settings-switchoo-inner"></div>
549
+ <div class="gadwp-settings-switchoo-switch"></div>
550
+ </label>
551
+ </div>
552
+ <div class="switch-desc"><?php echo " ".__("enable cross domain tracking", 'google-analytics-dashboard-for-wp' ); ?></div>
553
+ </td>
554
+ </tr>
555
+ <tr>
556
+ <td class="gadwp-settings-title"><label for="ga_crossdomain_list"><?php _e("Cross Domains:", 'google-analytics-dashboard-for-wp'); ?></label></td>
557
+ <td><input type="text" id="ga_crossdomain_list" name="options[ga_crossdomain_list]" value="<?php echo esc_attr($options['ga_crossdomain_list']); ?>" size="50"></td>
558
+ </tr>
559
+ <tr>
560
+ <td colspan="2"><?php echo "<h2>" . __( "Cookie Customization", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
561
+ </tr>
562
+ <tr>
563
+ <td class="gadwp-settings-title"><label for="ga_cookiedomain"><?php _e("Cookie Domain:", 'google-analytics-dashboard-for-wp'); ?></label></td>
564
+ <td><input type="text" id="ga_cookiedomain" name="options[ga_cookiedomain]" value="<?php echo esc_attr($options['ga_cookiedomain']); ?>" size="50"></td>
565
+ </tr>
566
+ <tr>
567
+ <td class="gadwp-settings-title"><label for="ga_cookiename"><?php _e("Cookie Name:", 'google-analytics-dashboard-for-wp'); ?></label></td>
568
+ <td><input type="text" id="ga_cookiename" name="options[ga_cookiename]" value="<?php echo esc_attr($options['ga_cookiename']); ?>" size="50"></td>
569
+ </tr>
570
+ <tr>
571
+ <td class="gadwp-settings-title"><label for="ga_cookieexpires"><?php _e("Cookie Expires:", 'google-analytics-dashboard-for-wp'); ?></label></td>
572
+ <td><input type="text" id="ga_cookieexpires" name="options[ga_cookieexpires]" value="<?php echo esc_attr($options['ga_cookieexpires']); ?>" size="10"> seconds</td>
573
+ </tr>
574
+ </table>
575
+ </div>
576
+ <div id="gadwp-exclude">
577
+ <table class="gadwp-settings-options">
578
+ <tr>
579
+ <td colspan="2"><?php echo "<h2>" . __( "Exclude Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
580
+ </tr>
581
+ <tr>
582
+ <td class="roles gadwp-settings-title"><label for="ga_track_exclude"><?php _e("Exclude tracking for:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
583
+ <td class="gadwp-settings-roles">
584
+ <?php
585
+ if ( ! isset( $wp_roles ) ) {
586
+ $wp_roles = new WP_Roles();
587
+ }
588
+ $i = 0;
589
+ ?> <table>
590
+ <tr>
591
+ <?php
592
+ foreach ( $wp_roles->role_names as $role => $name ) {
593
+ $i++;
594
+ ?>
595
+ <td><label> <input type="checkbox" name="options[ga_track_exclude][]" value="<?php echo $role; ?>" <?php if (in_array($role,$options['ga_track_exclude'])) echo 'checked="checked"'; ?> />
596
+ <?php echo $name; ?>
597
+ </label></td>
598
+ <?php
599
+ if ( $i % 4 == 0 ) {
600
+ ?>
601
+ </tr>
602
+ <tr>
603
+ <?php
604
+ }
605
+ }
606
+ ?>
607
+ </table>
608
+ </td>
609
+ </tr>
610
+ </table>
611
+ </div>
612
+ <table class="gadwp-settings-options">
613
+ <tr>
614
+ <td colspan="2"><hr></td>
615
+ </tr>
616
+ <tr>
617
+ <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
618
+ </tr>
619
+ </table>
620
+ <input type="hidden" name="options[ga_dash_hidden]" value="Y">
621
+ <?php wp_nonce_field('gadash_form','gadash_security'); ?>
622
+ </form>
623
+ <?php
624
+ self::output_sidebar();
625
+ }
626
+
627
+ public static function errors_debugging() {
628
+ global $wp_version;
629
+
630
+ $gadwp = GADWP();
631
+
632
+ if ( ! current_user_can( 'manage_options' ) ) {
633
+ return;
634
+ }
635
+
636
+ $anonim = $gadwp->config->options;
637
+ $anonim['wp_version'] = $wp_version;
638
+ $anonim['gadwp_version'] = GADWP_CURRENT_VERSION;
639
+ if ( $anonim['ga_dash_token'] ) {
640
+ $anonim['ga_dash_token'] = 'HIDDEN';
641
+ }
642
+ if ( $anonim['ga_dash_clientid'] ) {
643
+ $anonim['ga_dash_clientid'] = 'HIDDEN';
644
+ }
645
+ if ( $anonim['ga_dash_clientsecret'] ) {
646
+ $anonim['ga_dash_clientsecret'] = 'HIDDEN';
647
+ }
648
+ $options = self::update_options( 'frontend' );
649
+ if ( ! $gadwp->config->options['ga_dash_tableid_jail'] || ! $gadwp->config->options['ga_dash_token'] ) {
650
+ $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
651
+ }
652
+ ?>
653
+ <div class="wrap">
654
+ <?php echo "<h2>" . __( "Google Analytics Errors & Debugging", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?>
655
+ </div>
656
+ <div id="poststuff" class="gadwp">
657
+ <div id="post-body" class="metabox-holder columns-2">
658
+ <div id="post-body-content">
659
+ <div class="settings-wrapper">
660
+ <div class="inside">
661
+ <?php if (isset($message)) echo $message; ?>
662
+ <?php
663
+ $tabs = array( 'errors' => __( "Errors & Details", 'google-analytics-dashboard-for-wp' ), 'config' => __( "Plugin Settings", 'google-analytics-dashboard-for-wp' ) );
664
+ self::navigation_tabs( $tabs );
665
+ ?>
666
+ <div id="gadwp-errors">
667
+ <table class="gadwp-settings-options">
668
+ <tr>
669
+ <td>
670
+ <?php echo "<h2>" . __( "Last Error detected", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?>
671
+ </td>
672
+ </tr>
673
+ <tr>
674
+ <td>
675
+ <?php
676
+ $errors = print_r( GADWP_Tools::get_cache( 'last_error' ), true ) ? esc_html( print_r( GADWP_Tools::get_cache( 'last_error' ), true ) ) : __( "None", 'google-analytics-dashboard-for-wp' );
677
+ echo '<pre class="gadwp-settings-logdata">Last Error: ';
678
+ echo $errors;
679
+ ?></pre>
680
+ </td>
681
+ </tr>
682
+ <tr>
683
+ <td colspan="2"><hr><?php echo "<h2>" . __( "Error Details", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
684
+ </tr>
685
+ <tr>
686
+ <td>
687
+ <?php
688
+ echo '<pre class="gadwp-settings-logdata">Error Details: ';
689
+ $error_details = print_r( GADWP_Tools::get_cache( 'gapi_errors' ), true ) ? "\n" . esc_html( print_r( GADWP_Tools::get_cache( 'last_error' ), true ) ) : __( "None", 'google-analytics-dashboard-for-wp' );
690
+ echo $error_details;
691
+ ?></pre><br />
692
+ <hr>
693
+ </td>
694
+
695
+
696
+ <tr>
697
+
698
+ </table>
699
+ </div>
700
+ <div id="gadwp-config">
701
+ <table class="gadwp-settings-options">
702
+ <tr>
703
+ <td><?php echo "<h2>" . __( "Plugin Configuration", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
704
+ </tr>
705
+ <tr>
706
+ <td><pre class="gadwp-settings-logdata"><?php echo esc_html(print_r($anonim, true));?></pre><br />
707
+ <hr></td>
708
+ </tr>
709
+ </table>
710
+ </div>
711
+ <?php
712
+ self::output_sidebar();
713
+ }
714
+
715
+ public static function general_settings() {
716
+ $gadwp = GADWP();
717
+
718
+ global $wp_version;
719
+
720
+ if ( ! current_user_can( 'manage_options' ) ) {
721
+ return;
722
+ }
723
+ $options = self::update_options( 'general' );
724
+ printf( '<div id="gapi-warning" class="updated"><p>%1$s <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=general_screen&utm_campaign=gadwp">%2$s</a></p></div>', __( 'Loading the required libraries. If this results in a blank screen or a fatal error, try this solution:', 'google-analytics-dashboard-for-wp' ), __( 'Library conflicts between WordPress plugins', 'google-analytics-dashboard-for-wp' ) );
725
+ if ( null === $gadwp->gapi_controller ) {
726
+ $gadwp->gapi_controller = new GADWP_GAPI_Controller();
727
+ }
728
+ echo '<script type="text/javascript">jQuery("#gapi-warning").hide()</script>';
729
+ if ( isset( $_POST['ga_dash_code'] ) ) {
730
+ if ( ! stripos( 'x' . $_POST['ga_dash_code'], 'UA-', 1 ) == 1 ) {
731
+ try {
732
+ $gadwp->gapi_controller->client->authenticate( $_POST['ga_dash_code'] );
733
+ $gadwp->config->options['ga_dash_token'] = $gadwp->gapi_controller->client->getAccessToken();
734
+ $gadwp->config->options['automatic_updates_minorversion'] = 1;
735
+ $gadwp->config->set_plugin_options();
736
+ $options = self::update_options( 'general' );
737
+ $message = "<div class='updated'><p>" . __( "Plugin authorization succeeded.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
738
+ GADWP_Tools::delete_cache( 'gapi_errors' );
739
+ GADWP_Tools::delete_cache( 'last_error' );
740
+ if ( $gadwp->config->options['ga_dash_token'] && $gadwp->gapi_controller->client->getAccessToken() ) {
741
+ if ( ! empty( $gadwp->config->options['ga_dash_profile_list'] ) ) {
742
+ $profiles = $gadwp->config->options['ga_dash_profile_list'];
743
+ } else {
744
+ $profiles = $gadwp->gapi_controller->refresh_profiles();
745
+ }
746
+ if ( $profiles ) {
747
+ $gadwp->config->options['ga_dash_profile_list'] = $profiles;
748
+ if ( ! $gadwp->config->options['ga_dash_tableid_jail'] ) {
749
+ $profile = GADWP_Tools::guess_default_domain( $profiles );
750
+ $gadwp->config->options['ga_dash_tableid_jail'] = $profile;
751
+ // $gadwp->config->options['ga_dash_tableid'] = $profile;
752
+ }
753
+ $gadwp->config->set_plugin_options();
754
+ $options = self::update_options( 'general' );
755
+ }
756
+ }
757
+ } catch ( Google_IO_Exception $e ) {
758
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $gadwp->gapi_controller->error_timeout );
759
+ return false;
760
+ } catch ( Google_Service_Exception $e ) {
761
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $gadwp->gapi_controller->error_timeout );
762
+ GADWP_Tools::set_cache( 'gapi_errors', $e->getErrors(), $gadwp->gapi_controller->error_timeout );
763
+ return $e->getCode();
764
+ } catch ( Exception $e ) {
765
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ) . "\nResponseHttpCode:" . $e->getCode(), $gadwp->gapi_controller->error_timeout );
766
+ $gadwp->gapi_controller->reset_token( false );
767
+ }
768
+ } else {
769
+ $message = "<div class='error'><p>" . __( "The access code is <strong>NOT</strong> your <strong>Tracking ID</strong> (UA-XXXXX-X). Try again, and use the red link to get your access code", 'google-analytics-dashboard-for-wp' ) . ".</p></div>";
770
+ }
771
+ }
772
+ if ( isset( $_POST['Clear'] ) ) {
773
+ if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
774
+ GADWP_Tools::clear_cache();
775
+ $message = "<div class='updated'><p>" . __( "Cleared Cache.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
776
+ } else {
777
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
778
+ }
779
+ }
780
+ if ( isset( $_POST['Reset'] ) ) {
781
+ if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
782
+ $gadwp->gapi_controller->reset_token( true );
783
+ GADWP_Tools::clear_cache();
784
+ $message = "<div class='updated'><p>" . __( "Token Reseted and Revoked.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
785
+ $options = self::update_options( 'Reset' );
786
+ } else {
787
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
788
+ }
789
+ }
790
+ if ( isset( $_POST['Reset_Err'] ) ) {
791
+ if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
792
+ GADWP_Tools::delete_cache( 'last_error' );
793
+ GADWP_Tools::delete_cache( 'gapi_errors' );
794
+ $message = "<div class='updated'><p>" . __( "All errors reseted.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
795
+ } else {
796
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
797
+ }
798
+ }
799
+ if ( isset( $_POST['options']['ga_dash_hidden'] ) && ! isset( $_POST['Clear'] ) && ! isset( $_POST['Reset'] ) && ! isset( $_POST['Reset_Err'] ) ) {
800
+ $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
801
+ if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
802
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
803
+ }
804
+ }
805
+ if ( isset( $_POST['Hide'] ) ) {
806
+ if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
807
+ $message = "<div class='updated'><p>" . __( "All other domains/properties were removed.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
808
+ $lock_profile = GADWP_Tools::get_selected_profile( $gadwp->config->options['ga_dash_profile_list'], $gadwp->config->options['ga_dash_tableid_jail'] );
809
+ $gadwp->config->options['ga_dash_profile_list'] = array( $lock_profile );
810
+ $options = self::update_options( 'general' );
811
+ } else {
812
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
813
+ }
814
+ }
815
+ ?>
816
+ <div class="wrap">
817
+ <?php echo "<h2>" . __( "Google Analytics Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?>
818
+ <hr>
819
+ </div>
820
+ <div id="poststuff" class="gadwp">
821
+ <div id="post-body" class="metabox-holder columns-2">
822
+ <div id="post-body-content">
823
+ <div class="settings-wrapper">
824
+ <div class="inside">
825
+ <?php
826
+ if ( $gadwp->gapi_controller->gapi_errors_handler() || GADWP_Tools::get_cache( 'last_error' ) ) {
827
+ $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
828
+ }
829
+ if ( isset( $_POST['Authorize'] ) ) {
830
+ GADWP_Tools::clear_cache();
831
+ $gadwp->gapi_controller->token_request();
832
+ echo "<div class='updated'><p>" . __( "Use the red link (see below) to generate and get your access code!", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
833
+ } else {
834
+ if ( isset( $message ) ) {
835
+ echo $message;
836
+ }
837
+ ?>
838
+ <form name="ga_dash_form" method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
839
+ <input type="hidden" name="options[ga_dash_hidden]" value="Y">
840
+ <?php wp_nonce_field('gadash_form','gadash_security'); ?>
841
+ <table class="gadwp-settings-options">
842
+ <tr>
843
+ <td colspan="2">
844
+ <?php echo "<h2>" . __( "Plugin Authorization", 'google-analytics-dashboard-for-wp' ) . "</h2>";?>
845
+ </td>
846
+ </tr>
847
+ <tr>
848
+ <td colspan="2" class="gadwp-settings-info">
849
+ <?php printf(__('You should watch the %1$s and read this %2$s before proceeding to authorization. This plugin requires a properly configured Google Analytics account!', 'google-analytics-dashboard-for-wp'), sprintf('<a href="%1$s" target="_blank">%2$s</a>', 'https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=top_video&utm_campaign=gadwp', __("video", 'google-analytics-dashboard-for-wp')), sprintf('<a href="%1$s" target="_blank">%2$s</a>', 'https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=top_tutorial&utm_campaign=gadwp', __("tutorial", 'google-analytics-dashboard-for-wp')));?>
850
+ </td>
851
+ </tr>
852
+ <?php if (! $options['ga_dash_token'] || $options['ga_dash_userapi']) {?>
853
+ <tr>
854
+ <td colspan="2" class="gadwp-settings-info"><input name="options[ga_dash_userapi]" type="checkbox" id="ga_dash_userapi" value="1" <?php checked( $options['ga_dash_userapi'], 1 ); ?> onchange="this.form.submit()" <?php echo ($options['ga_dash_network'])?'disabled="disabled"':''; ?> /><?php echo " ".__("use your own API Project credentials", 'google-analytics-dashboard-for-wp' );?>
855
+ </td>
856
+ </tr>
857
+ <?php } if ($options['ga_dash_userapi']) { ?>
858
+ <tr>
859
+ <td class="gadwp-settings-title"><label for="options[ga_dash_clientid]"><?php _e("Client ID:", 'google-analytics-dashboard-for-wp'); ?></label></td>
860
+ <td><input type="text" name="options[ga_dash_clientid]" value="<?php echo esc_attr($options['ga_dash_clientid']); ?>" size="40" required="required"></td>
861
+ </tr>
862
+ <tr>
863
+ <td class="gadwp-settings-title"><label for="options[ga_dash_clientsecret]"><?php _e("Client Secret:", 'google-analytics-dashboard-for-wp'); ?></label></td>
864
+ <td><input type="text" name="options[ga_dash_clientsecret]" value="<?php echo esc_attr($options['ga_dash_clientsecret']); ?>" size="40" required="required"> <input type="hidden" name="options[ga_dash_hidden]" value="Y">
865
+ <?php wp_nonce_field('gadash_form','gadash_security'); ?>
866
+ </td>
867
+ </tr>
868
+ <?php
869
+ }
870
+ if ( $options['ga_dash_token'] ) {
871
+ ?>
872
+ <tr>
873
+ <td colspan="2"><input type="submit" name="Reset" class="button button-secondary" value="<?php _e( "Clear Authorization", 'google-analytics-dashboard-for-wp' ); ?>" <?php echo $options['ga_dash_network']?'disabled="disabled"':''; ?> /> <input type="submit" name="Clear" class="button button-secondary" value="<?php _e( "Clear Cache", 'google-analytics-dashboard-for-wp' ); ?>" /> <input type="submit" name="Reset_Err" class="button button-secondary" value="<?php _e( "Reset Errors", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
874
+ </tr>
875
+ <tr>
876
+ <td colspan="2"><hr></td>
877
+ </tr>
878
+ <tr>
879
+ <td colspan="2"><?php echo "<h2>" . __( "General Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
880
+ </tr>
881
+ <tr>
882
+ <td class="gadwp-settings-title"><label for="ga_dash_tableid_jail"><?php _e("Select View:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
883
+ <td><select id="ga_dash_tableid_jail" <?php disabled(empty($options['ga_dash_profile_list']) || 1 == count($options['ga_dash_profile_list']), true); ?> name="options[ga_dash_tableid_jail]">
884
+ <?php
885
+ if ( ! empty( $options['ga_dash_profile_list'] ) ) {
886
+ foreach ( $options['ga_dash_profile_list'] as $items ) {
887
+ if ( $items[3] ) {
888
+ echo '<option value="' . esc_attr( $items[1] ) . '" ' . selected( $items[1], $options['ga_dash_tableid_jail'], false );
889
+ echo ' title="' . __( "View Name:", 'google-analytics-dashboard-for-wp' ) . ' ' . esc_attr( $items[0] ) . '">' . esc_html( GADWP_Tools::strip_protocol( $items[3] ) ) . ' &#8658; ' . esc_attr( $items[0] ) . '</option>';
890
+ }
891
+ }
892
+ } else {
893
+ echo '<option value="">' . __( "Property not found", 'google-analytics-dashboard-for-wp' ) . '</option>';
894
+ }
895
+ ?>
896
+ </select>
897
+ <?php
898
+ if ( count( $options['ga_dash_profile_list'] ) > 1 ) {
899
+ ?>&nbsp;<input type="submit" name="Hide" class="button button-secondary" value="<?php _e( "Lock Selection", 'google-analytics-dashboard-for-wp' ); ?>" /><?php
900
+ }
901
+ ?>
902
+ </td>
903
+ </tr>
904
+ <?php
905
+ if ( $options['ga_dash_tableid_jail'] ) {
906
+ ?>
907
+ <tr>
908
+ <td class="gadwp-settings-title"></td>
909
+ <td><?php
910
+ $profile_info = GADWP_Tools::get_selected_profile( $gadwp->config->options['ga_dash_profile_list'], $gadwp->config->options['ga_dash_tableid_jail'] );
911
+ echo '<pre>' . __( "View Name:", 'google-analytics-dashboard-for-wp' ) . "\t" . esc_html( $profile_info[0] ) . "<br />" . __( "Tracking ID:", 'google-analytics-dashboard-for-wp' ) . "\t" . esc_html( $profile_info[2] ) . "<br />" . __( "Default URL:", 'google-analytics-dashboard-for-wp' ) . "\t" . esc_html( $profile_info[3] ) . "<br />" . __( "Time Zone:", 'google-analytics-dashboard-for-wp' ) . "\t" . esc_html( $profile_info[5] ) . '</pre>';
912
+ ?></td>
913
+ </tr>
914
+ <?php
915
+ }
916
+ ?>
917
+ <tr>
918
+ <td class="gadwp-settings-title"><label for="ga_dash_style"><?php _e("Theme Color:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
919
+ <td><input type="text" id="ga_dash_style" class="ga_dash_style" name="options[ga_dash_style]" value="<?php echo esc_attr($options['ga_dash_style']); ?>" size="10"></td>
920
+ </tr>
921
+ <tr>
922
+ <td colspan="2"><hr></td>
923
+ </tr>
924
+ <?php if ( !is_multisite()) {?>
925
+ <tr>
926
+ <td colspan="2"><?php echo "<h2>" . __( "Automatic Updates", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
927
+ </tr>
928
+ <tr>
929
+ <td colspan="2" class="gadwp-settings-title">
930
+ <div class="button-primary gadwp-settings-switchoo">
931
+ <input type="checkbox" name="options[automatic_updates_minorversion]" value="1" class="gadwp-settings-switchoo-checkbox" id="automatic_updates_minorversion" <?php checked( $options['automatic_updates_minorversion'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="automatic_updates_minorversion">
932
+ <div class="gadwp-settings-switchoo-inner"></div>
933
+ <div class="gadwp-settings-switchoo-switch"></div>
934
+ </label>
935
+ </div>
936
+ <div class="switch-desc"><?php echo " ".__( "automatic updates for minor versions (security and maintenance releases only)", 'google-analytics-dashboard-for-wp' );?></div>
937
+ </td>
938
+ </tr>
939
+ <tr>
940
+ <td colspan="2"><hr></td>
941
+ </tr>
942
+ <?php }?>
943
+ <tr>
944
+ <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
945
+ </tr>
946
+ <?php } else {?>
947
+ <tr>
948
+ <td colspan="2"><hr></td>
949
+ </tr>
950
+ <tr>
951
+ <td colspan="2"><input type="submit" name="Authorize" class="button button-secondary" id="authorize" value="<?php _e( "Authorize Plugin", 'google-analytics-dashboard-for-wp' ); ?>" <?php echo $options['ga_dash_network']?'disabled="disabled"':''; ?> /> <input type="submit" name="Clear" class="button button-secondary" value="<?php _e( "Clear Cache", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
952
+ </tr>
953
+ <tr>
954
+ <td colspan="2"><hr></td>
955
+ </tr>
956
+ </table>
957
+ </form>
958
+ <?php
959
+ self::output_sidebar();
960
+ return;
961
+ }
962
+ ?>
963
+ </table>
964
+ </form>
965
+ <?php
966
+ }
967
+ self::output_sidebar();
968
+ }
969
+ // Network Settings
970
+ public static function general_settings_network() {
971
+ $gadwp = GADWP();
972
+ global $wp_version;
973
+
974
+ if ( ! current_user_can( 'manage_network_options' ) ) {
975
+ return;
976
+ }
977
+ $options = self::update_options( 'network' );
978
+ /*
979
+ * Include GAPI
980
+ */
981
+ echo '<div id="gapi-warning" class="updated"><p>' . __( 'Loading the required libraries. If this results in a blank screen or a fatal error, try this solution:', 'google-analytics-dashboard-for-wp' ) . ' <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=general_screen&utm_campaign=gadwp">Library conflicts between WordPress plugins</a></p></div>';
982
+
983
+ if ( null === $gadwp->gapi_controller ) {
984
+ $gadwp->gapi_controller = new GADWP_GAPI_Controller();
985
+ }
986
+
987
+ echo '<script type="text/javascript">jQuery("#gapi-warning").hide()</script>';
988
+ if ( isset( $_POST['ga_dash_code'] ) ) {
989
+ if ( ! stripos( 'x' . $_POST['ga_dash_code'], 'UA-', 1 ) == 1 ) {
990
+ try {
991
+ $gadwp->gapi_controller->client->authenticate( $_POST['ga_dash_code'] );
992
+ $gadwp->config->options['ga_dash_token'] = $gadwp->gapi_controller->client->getAccessToken();
993
+ $gadwp->config->options['automatic_updates_minorversion'] = 1;
994
+ $gadwp->config->set_plugin_options( true );
995
+ $options = self::update_options( 'network' );
996
+ $message = "<div class='updated'><p>" . __( "Plugin authorization succeeded.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
997
+ if ( is_multisite() ) { // Cleanup errors on the entire network
998
+ foreach ( GADWP_Tools::get_sites( array( 'limit' => apply_filters( 'gadwp_sites_limit', 100 ) ) ) as $blog ) {
999
+ switch_to_blog( $blog['blog_id'] );
1000
+ GADWP_Tools::delete_cache( 'gapi_errors' );
1001
+ restore_current_blog();
1002
+ }
1003
+ } else {
1004
+ GADWP_Tools::delete_cache( 'gapi_errors' );
1005
+ }
1006
+ if ( $gadwp->config->options['ga_dash_token'] && $gadwp->gapi_controller->client->getAccessToken() ) {
1007
+ if ( ! empty( $gadwp->config->options['ga_dash_profile_list'] ) ) {
1008
+ $profiles = $gadwp->config->options['ga_dash_profile_list'];
1009
+ } else {
1010
+ $profiles = $gadwp->gapi_controller->refresh_profiles();
1011
+ }
1012
+ if ( $profiles ) {
1013
+ $gadwp->config->options['ga_dash_profile_list'] = $profiles;
1014
+ if ( isset( $gadwp->config->options['ga_dash_tableid_jail'] ) && ! $gadwp->config->options['ga_dash_tableid_jail'] ) {
1015
+ $profile = GADWP_Tools::guess_default_domain( $profiles );
1016
+ $gadwp->config->options['ga_dash_tableid_jail'] = $profile;
1017
+ // $gadwp->config->options['ga_dash_tableid'] = $profile;
1018
+ }
1019
+ $gadwp->config->set_plugin_options( true );
1020
+ $options = self::update_options( 'network' );
1021
+ }
1022
+ }
1023
+ } catch ( Google_IO_Exception $e ) {
1024
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $gadwp->gapi_controller->error_timeout );
1025
+ return false;
1026
+ } catch ( Google_Service_Exception $e ) {
1027
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $gadwp->gapi_controller->error_timeout );
1028
+ GADWP_Tools::set_cache( 'gapi_errors', $e->getErrors(), $gadwp->gapi_controller->error_timeout );
1029
+ return $e->getCode();
1030
+ } catch ( Exception $e ) {
1031
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ) . "\nResponseHttpCode:" . $e->getCode(), $gadwp->gapi_controller->error_timeout );
1032
+ $gadwp->gapi_controller->reset_token( false );
1033
+ }
1034
+ } else {
1035
+ $message = "<div class='error'><p>" . __( "The access code is <strong>NOT</strong> your <strong>Tracking ID</strong> (UA-XXXXX-X). Try again, and use the red link to get your access code", 'google-analytics-dashboard-for-wp' ) . ".</p></div>";
1036
+ }
1037
+ }
1038
+ if ( isset( $_POST['Refresh'] ) ) {
1039
+ if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
1040
+ $gadwp->config->options['ga_dash_profile_list'] = array();
1041
+ $message = "<div class='updated'><p>" . __( "Properties refreshed.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1042
+ $options = self::update_options( 'network' );
1043
+ if ( $gadwp->config->options['ga_dash_token'] && $gadwp->gapi_controller->client->getAccessToken() ) {
1044
+ if ( ! empty( $gadwp->config->options['ga_dash_profile_list'] ) ) {
1045
+ $profiles = $gadwp->config->options['ga_dash_profile_list'];
1046
+ } else {
1047
+ $profiles = $gadwp->gapi_controller->refresh_profiles();
1048
+ }
1049
+ if ( $profiles ) {
1050
+ $gadwp->config->options['ga_dash_profile_list'] = $profiles;
1051
+ if ( isset( $gadwp->config->options['ga_dash_tableid_jail'] ) && ! $gadwp->config->options['ga_dash_tableid_jail'] ) {
1052
+ $profile = GADWP_Tools::guess_default_domain( $profiles );
1053
+ $gadwp->config->options['ga_dash_tableid_jail'] = $profile;
1054
+ // $gadwp->config->options['ga_dash_tableid'] = $profile;
1055
+ }
1056
+ $gadwp->config->set_plugin_options( true );
1057
+ $options = self::update_options( 'network' );
1058
+ }
1059
+ }
1060
+ } else {
1061
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1062
+ }
1063
+ }
1064
+ if ( isset( $_POST['Clear'] ) ) {
1065
+ if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
1066
+ GADWP_Tools::clear_cache();
1067
+ $message = "<div class='updated'><p>" . __( "Cleared Cache.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1068
+ } else {
1069
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1070
+ }
1071
+ }
1072
+ if ( isset( $_POST['Reset'] ) ) {
1073
+ if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
1074
+ $gadwp->gapi_controller->reset_token( true );
1075
+ GADWP_Tools::clear_cache();
1076
+ $message = "<div class='updated'><p>" . __( "Token Reseted and Revoked.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1077
+ $options = self::update_options( 'Reset' );
1078
+ } else {
1079
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1080
+ }
1081
+ }
1082
+ if ( isset( $_POST['options']['ga_dash_hidden'] ) && ! isset( $_POST['Clear'] ) && ! isset( $_POST['Reset'] ) && ! isset( $_POST['Refresh'] ) ) {
1083
+ $message = "<div class='updated'><p>" . __( "Settings saved.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1084
+ if ( ! ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) ) {
1085
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1086
+ }
1087
+ }
1088
+ if ( isset( $_POST['Hide'] ) ) {
1089
+ if ( isset( $_POST['gadash_security'] ) && wp_verify_nonce( $_POST['gadash_security'], 'gadash_form' ) ) {
1090
+ $message = "<div class='updated'><p>" . __( "All other domains/properties were removed.", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1091
+ $lock_profile = GADWP_Tools::get_selected_profile( $gadwp->config->options['ga_dash_profile_list'], $gadwp->config->options['ga_dash_tableid_jail'] );
1092
+ $gadwp->config->options['ga_dash_profile_list'] = array( $lock_profile );
1093
+ $options = self::update_options( 'network' );
1094
+ } else {
1095
+ $message = "<div class='error'><p>" . __( "Cheating Huh?", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1096
+ }
1097
+ }
1098
+ ?>
1099
+ <div class="wrap">
1100
+ <?php echo "<h2>" . __( "Google Analytics Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?><hr>
1101
+ </div>
1102
+ <div id="poststuff" class="gadwp">
1103
+ <div id="post-body" class="metabox-holder columns-2">
1104
+ <div id="post-body-content">
1105
+ <div class="settings-wrapper">
1106
+ <div class="inside">
1107
+ <?php
1108
+ if ( $gadwp->gapi_controller->gapi_errors_handler() || GADWP_Tools::get_cache( 'last_error' ) ) {
1109
+ $message = sprintf( '<div class="error"><p>%s</p></div>', sprintf( __( 'Something went wrong, check %1$s or %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_errors_debugging', false ), __( 'Errors & Debug', 'google-analytics-dashboard-for-wp' ) ), sprintf( '<a href="%1$s">%2$s</a>', menu_page_url( 'gadash_settings', false ), __( 'authorize the plugin', 'google-analytics-dashboard-for-wp' ) ) ) );
1110
+ }
1111
+ if ( isset( $_POST['Authorize'] ) ) {
1112
+ GADWP_Tools::clear_cache();
1113
+ $gadwp->gapi_controller->token_request();
1114
+ echo "<div class='updated'><p>" . __( "Use the red link (see below) to generate and get your access code!", 'google-analytics-dashboard-for-wp' ) . "</p></div>";
1115
+ } else {
1116
+ if ( isset( $message ) ) {
1117
+ echo $message;
1118
+ }
1119
+ ?>
1120
+ <form name="ga_dash_form" method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
1121
+ <input type="hidden" name="options[ga_dash_hidden]" value="Y">
1122
+ <?php wp_nonce_field('gadash_form','gadash_security'); ?>
1123
+ <table class="gadwp-settings-options">
1124
+ <tr>
1125
+ <td colspan="2"><?php echo "<h2>" . __( "Network Setup", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1126
+ </tr>
1127
+ <tr>
1128
+ <td colspan="2" class="gadwp-settings-title">
1129
+ <div class="button-primary gadwp-settings-switchoo">
1130
+ <input type="checkbox" name="options[ga_dash_network]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_network" <?php checked( $options['ga_dash_network'], 1); ?> onchange="this.form.submit()"> <label class="gadwp-settings-switchoo-label" for="ga_dash_network">
1131
+ <div class="gadwp-settings-switchoo-inner"></div>
1132
+ <div class="gadwp-settings-switchoo-switch"></div>
1133
+ </label>
1134
+ </div>
1135
+ <div class="switch-desc"><?php echo " ".__("use a single Google Analytics account for the entire network", 'google-analytics-dashboard-for-wp' );?></div>
1136
+ </td>
1137
+ </tr>
1138
+ <?php if ($options['ga_dash_network']){ //Network Mode check?>
1139
+ <tr>
1140
+ <td colspan="2"><hr></td>
1141
+ </tr>
1142
+ <tr>
1143
+ <td colspan="2"><?php echo "<h2>" . __( "Plugin Authorization", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1144
+ </tr>
1145
+ <tr>
1146
+ <td colspan="2" class="gadwp-settings-info">
1147
+ <?php printf(__('You should watch the %1$s and read this %2$s before proceeding to authorization. This plugin requires a properly configured Google Analytics account!', 'google-analytics-dashboard-for-wp'), sprintf('<a href="%1$s" target="_blank">%2$s</a>', 'https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=top_video&utm_campaign=gadwp', __("video", 'google-analytics-dashboard-for-wp')), sprintf('<a href="%1$s" target="_blank">%2$s</a>', 'https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=top_tutorial&utm_campaign=gadwp', __("tutorial", 'google-analytics-dashboard-for-wp')));?>
1148
+ </td>
1149
+ </tr>
1150
+ <?php
1151
+ if ( ! $options['ga_dash_token'] || $options['ga_dash_userapi'] ) {
1152
+ ?>
1153
+ <tr>
1154
+ <td colspan="2" class="gadwp-settings-info"><input name="options[ga_dash_userapi]" type="checkbox" id="ga_dash_userapi" value="1" <?php checked( $options['ga_dash_userapi'], 1 ); ?> onchange="this.form.submit()" /><?php echo " ".__("use your own API Project credentials", 'google-analytics-dashboard-for-wp' );?>
1155
+ </td>
1156
+ </tr>
1157
+ <?php
1158
+ }
1159
+ if ( $options['ga_dash_userapi'] ) {
1160
+ ?>
1161
+ <tr>
1162
+ <td class="gadwp-settings-title"><label for="options[ga_dash_clientid]"><?php _e("Client ID:", 'google-analytics-dashboard-for-wp'); ?></label></td>
1163
+ <td><input type="text" name="options[ga_dash_clientid]" value="<?php echo esc_attr($options['ga_dash_clientid']); ?>" size="40" required="required"></td>
1164
+ </tr>
1165
+ <tr>
1166
+ <td class="gadwp-settings-title"><label for="options[ga_dash_clientsecret]"><?php _e("Client Secret:", 'google-analytics-dashboard-for-wp'); ?></label></td>
1167
+ <td><input type="text" name="options[ga_dash_clientsecret]" value="<?php echo esc_attr($options['ga_dash_clientsecret']); ?>" size="40" required="required"> <input type="hidden" name="options[ga_dash_hidden]" value="Y">
1168
+ <?php wp_nonce_field('gadash_form','gadash_security'); ?>
1169
+ </td>
1170
+ </tr>
1171
+ <?php
1172
+ }
1173
+ if ( $options['ga_dash_token'] ) {
1174
+ ?>
1175
+ <tr>
1176
+ <td colspan="2"><input type="submit" name="Reset" class="button button-secondary" value="<?php _e( "Clear Authorization", 'google-analytics-dashboard-for-wp' ); ?>" /> <input type="submit" name="Clear" class="button button-secondary" value="<?php _e( "Clear Cache", 'google-analytics-dashboard-for-wp' ); ?>" /> <input type="submit" name="Refresh" class="button button-secondary" value="<?php _e( "Refresh Properties", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
1177
+ </tr>
1178
+ <tr>
1179
+ <td colspan="2"><hr></td>
1180
+ </tr>
1181
+ <tr>
1182
+ <td colspan="2"><?php echo "<h2>" . __( "Properties/Views Settings", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1183
+ </tr>
1184
+ <?php
1185
+ if ( isset( $options['ga_dash_tableid_network'] ) ) {
1186
+ $options['ga_dash_tableid_network'] = json_decode( json_encode( $options['ga_dash_tableid_network'] ), false );
1187
+ }
1188
+ foreach ( GADWP_Tools::get_sites( array( 'limit' => apply_filters( 'gadwp_sites_limit', 100 ) ) ) as $blog ) {
1189
+ ?>
1190
+ <tr>
1191
+ <td class="gadwp-settings-title-s"><label for="ga_dash_tableid_network"><?php echo '<strong>'.$blog['domain'].$blog['path'].'</strong>: ';?></label></td>
1192
+ <td><select id="ga_dash_tableid_network" <?php disabled(!empty($options['ga_dash_profile_list']),false);?> name="options[ga_dash_tableid_network][<?php echo $blog['blog_id'];?>]">
1193
+ <?php
1194
+ if ( ! empty( $options['ga_dash_profile_list'] ) ) {
1195
+ foreach ( $options['ga_dash_profile_list'] as $items ) {
1196
+ if ( $items[3] ) {
1197
+ $temp_id = $blog['blog_id'];
1198
+ echo '<option value="' . esc_attr( $items[1] ) . '" ' . selected( $items[1], isset( $options['ga_dash_tableid_network']->$temp_id ) ? $options['ga_dash_tableid_network']->$temp_id : '', false );
1199
+ echo ' title="' . __( "View Name:", 'google-analytics-dashboard-for-wp' ) . ' ' . esc_attr( $items[0] ) . '">' . esc_html( GADWP_Tools::strip_protocol( $items[3] ) ) . ' &#8658; ' . esc_attr( $items[0] ) . '</option>';
1200
+ }
1201
+ }
1202
+ } else {
1203
+ echo '<option value="">' . __( "Property not found", 'google-analytics-dashboard-for-wp' ) . '</option>';
1204
+ }
1205
+ ?>
1206
+ </select> <br /></td>
1207
+ </tr>
1208
+ <?php
1209
+ }
1210
+ ?>
1211
+ <tr>
1212
+ <td colspan="2"><?php echo "<h2>" . __( "Automatic Updates", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1213
+ </tr>
1214
+ <tr>
1215
+ <td colspan="2" class="gadwp-settings-title">
1216
+ <div class="button-primary gadwp-settings-switchoo">
1217
+ <input type="checkbox" name="options[automatic_updates_minorversion]" value="1" class="gadwp-settings-switchoo-checkbox" id="automatic_updates_minorversion" <?php checked( $options['automatic_updates_minorversion'], 1 ); ?>> <label class="gadwp-settings-switchoo-label" for="automatic_updates_minorversion">
1218
+ <div class="gadwp-settings-switchoo-inner"></div>
1219
+ <div class="gadwp-settings-switchoo-switch"></div>
1220
+ </label>
1221
+ </div>
1222
+ <div class="switch-desc"><?php echo " ".__( "automatic updates for minor versions (security and maintenance releases only)", 'google-analytics-dashboard-for-wp' );?></div>
1223
+ </td>
1224
+ </tr>
1225
+ <tr>
1226
+ <td colspan="2"><hr><?php echo "<h2>" . __( "Exclude Tracking", 'google-analytics-dashboard-for-wp' ) . "</h2>"; ?></td>
1227
+ </tr>
1228
+ <tr>
1229
+ <td colspan="2" class="gadwp-settings-title">
1230
+ <div class="button-primary gadwp-settings-switchoo">
1231
+ <input type="checkbox" name="options[ga_dash_excludesa]" value="1" class="gadwp-settings-switchoo-checkbox" id="ga_dash_excludesa"<?php checked( $options['ga_dash_excludesa'], 1); ?>"> <label class="gadwp-settings-switchoo-label" for="ga_dash_excludesa">
1232
+ <div class="gadwp-settings-switchoo-inner"></div>
1233
+ <div class="gadwp-settings-switchoo-switch"></div>
1234
+ </label>
1235
+ </div>
1236
+ <div class="switch-desc"><?php echo " ".__("exclude Super Admin tracking for the entire network", 'google-analytics-dashboard-for-wp' );?></div>
1237
+ </td>
1238
+ </tr>
1239
+ <tr>
1240
+ <td colspan="2"><hr></td>
1241
+ </tr>
1242
+ <tr>
1243
+ <td colspan="2" class="submit"><input type="submit" name="Submit" class="button button-primary" value="<?php _e('Save Changes', 'google-analytics-dashboard-for-wp' ) ?>" /></td>
1244
+ </tr>
1245
+ <?php
1246
+ } else {
1247
+ ?>
1248
+ <tr>
1249
+ <td colspan="2"><hr></td>
1250
+ </tr>
1251
+ <tr>
1252
+ <td colspan="2"><input type="submit" name="Authorize" class="button button-secondary" id="authorize" value="<?php _e( "Authorize Plugin", 'google-analytics-dashboard-for-wp' ); ?>" /> <input type="submit" name="Clear" class="button button-secondary" value="<?php _e( "Clear Cache", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
1253
+ </tr>
1254
+ <?php } //Network Mode check?>
1255
+ <tr>
1256
+ <td colspan="2"><hr></td>
1257
+ </tr>
1258
+ </table>
1259
+ </form>
1260
+ <?php
1261
+ self::output_sidebar();
1262
+ return;
1263
+ }
1264
+ ?>
1265
+ </table>
1266
+ </form>
1267
+ <?php
1268
+ }
1269
+ self::output_sidebar();
1270
+ }
1271
+
1272
+ public static function output_sidebar() {
1273
+ global $wp_version;
1274
+
1275
+ $gadwp = GADWP();
1276
+ ?>
1277
+ </div>
1278
+ </div>
1279
+ </div>
1280
+ <div id="postbox-container-1" class="postbox-container">
1281
+ <div class="meta-box-sortables">
1282
+ <div class="postbox">
1283
+ <h3>
1284
+ <span><?php _e("Setup Tutorial & Demo",'google-analytics-dashboard-for-wp') ?></span>
1285
+ </h3>
1286
+ <div class="inside">
1287
+ <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=video&utm_campaign=gadwp" target="_blank"><img src="<?php echo plugins_url( 'images/google-analytics-dashboard.png' , __FILE__ );?>" width="100%" alt="" /></a>
1288
+ </div>
1289
+ </div>
1290
+ <div class="postbox">
1291
+ <h3>
1292
+ <span><?php _e("Follow & Review",'google-analytics-dashboard-for-wp')?></span>
1293
+ </h3>
1294
+ <div class="inside">
1295
+ <div class="gadash-desc">
1296
+ <div style="margin-left: -10px;">
1297
+ <div class="g-page" data-width="273" data-href="//plus.google.com/+Deconfcom" data-layout="landscape" data-showtagline="false" data-showcoverphoto="false" data-rel="publisher"></div>
1298
+ </div>
1299
+ <script type="text/javascript">
1300
+ (function() {
1301
+ var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
1302
+ po.src = 'https://apis.google.com/js/platform.js';
1303
+ var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
1304
+ })();
1305
+ </script>
1306
+ </div>
1307
+ <br />
1308
+ <div class="gadash-desc">
1309
+ <a href="https://twitter.com/deconfcom" class="twitter-follow-button" data-show-count="false" data-size="large">Follow @deconfcom</a>
1310
+ <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
1311
+ </div>
1312
+ <br />
1313
+ <div class="gadash-title">
1314
+ <a href="http://wordpress.org/support/view/plugin-reviews/google-analytics-dashboard-for-wp#plugin-info"><img src="<?php echo plugins_url( 'images/star.png' , __FILE__ ); ?>" /></a>
1315
+ </div>
1316
+ <div class="gadash-desc">
1317
+ <?php printf(__('Your feedback and review are both important, %s!', 'google-analytics-dashboard-for-wp'), sprintf('<a href="http://wordpress.org/support/view/plugin-reviews/google-analytics-dashboard-for-wp#plugin-info">%s</a>', __('rate this plugin', 'google-analytics-dashboard-for-wp')));?>
1318
+ </div>
1319
+ </div>
1320
+ </div>
1321
+ <div class="postbox">
1322
+ <h3>
1323
+ <span><?php _e("Further Reading",'google-analytics-dashboard-for-wp')?></span>
1324
+ </h3>
1325
+ <div class="inside">
1326
+ <div class="gadash-title">
1327
+ <a href="https://deconf.com/clicky-web-analytics-review/?utm_source=gadwp_config&utm_medium=link&utm_content=clicky&utm_campaign=gadwp"><img src="<?php echo plugins_url( 'images/clicky.png' , __FILE__ ); ?>" /></a>
1328
+ </div>
1329
+ <div class="gadash-desc">
1330
+ <?php printf(__('%s service with users tracking at IP level.', 'google-analytics-dashboard-for-wp'), sprintf('<a href="https://deconf.com/clicky-web-analytics-review/?utm_source=gadwp_config&utm_medium=link&utm_content=clicky&utm_campaign=gadwp">%s</a>', __('Web Analytics', 'google-analytics-dashboard-for-wp')));?>
1331
+ </div>
1332
+ <br />
1333
+ <div class="gadash-title">
1334
+ <a href="https://deconf.com/move-website-https-ssl/?utm_source=gadwp_config&utm_medium=link&utm_content=ssl&utm_campaign=gadwp"><img src="<?php echo plugins_url( 'images/ssl.png' , __FILE__ ); ?>" /></a>
1335
+ </div>
1336
+ <div class="gadash-desc">
1337
+ <?php printf(__('%s by moving your website to HTTPS/SSL.', 'google-analytics-dashboard-for-wp'), sprintf('<a href="https://deconf.com/move-website-https-ssl/?utm_source=gadwp_config&utm_medium=link&utm_content=ssl&utm_campaign=gadwp">%s</a>', __('Improve search rankings', 'google-analytics-dashboard-for-wp')));?>
1338
+ </div>
1339
+ <br />
1340
+ <div class="gadash-title">
1341
+ <a href="https://deconf.com/wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=plugins&utm_campaign=gadwp"><img src="<?php echo plugins_url( 'images/wp.png' , __FILE__ ); ?>" /></a>
1342
+ </div>
1343
+ <div class="gadash-desc">
1344
+ <?php printf(__('Other %s written by the same author', 'google-analytics-dashboard-for-wp'), sprintf('<a href="https://deconf.com/wordpress/?utm_source=gadwp_config&utm_medium=link&utm_content=plugins&utm_campaign=gadwp">%s</a>', __('WordPress Plugins', 'google-analytics-dashboard-for-wp')));?>
1345
+ </div>
1346
+ </div>
1347
+ </div>
1348
+ </div>
1349
+ </div>
1350
+ </div>
1351
+ </div>
1352
+ <?php
1353
+ //Dismiss the admin update notice
1354
+ if ( version_compare( $wp_version, '4.2', '<' ) && current_user_can('manage_options') ) {
1355
+ delete_option('gadwp_got_updated');
1356
+ }
1357
+ }
1358
+ }
admin/setup.php CHANGED
@@ -1,357 +1,357 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Backend_Setup' ) ) {
15
-
16
- final class GADWP_Backend_Setup {
17
-
18
- private $gadwp;
19
-
20
- public function __construct() {
21
- $this->gadwp = GADWP();
22
-
23
- // Styles & Scripts
24
- add_action( 'admin_enqueue_scripts', array( $this, 'load_styles_scripts' ) );
25
- // Site Menu
26
- add_action( 'admin_menu', array( $this, 'site_menu' ) );
27
- // Network Menu
28
- add_action( 'network_admin_menu', array( $this, 'network_menu' ) );
29
- // Settings link
30
- add_filter( "plugin_action_links_" . plugin_basename( GADWP_DIR . 'gadwp.php' ), array( $this, 'settings_link' ) );
31
- // Updated admin notice
32
- add_action( 'admin_notices', array( $this, 'admin_notice' ) );
33
- }
34
-
35
- /**
36
- * Add Site Menu
37
- */
38
- public function site_menu() {
39
- global $wp_version;
40
- if ( current_user_can( 'manage_options' ) ) {
41
- include ( GADWP_DIR . 'admin/settings.php' );
42
- add_menu_page( __( "Google Analytics", 'google-analytics-dashboard-for-wp' ), __( "Google Analytics", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_settings', array( 'GADWP_Settings', 'general_settings' ), version_compare( $wp_version, '3.8.0', '>=' ) ? 'dashicons-chart-area' : GADWP_URL . 'admin/images/gadash-icon.png' );
43
- add_submenu_page( 'gadash_settings', __( "General Settings", 'google-analytics-dashboard-for-wp' ), __( "General Settings", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_settings', array( 'GADWP_Settings', 'general_settings' ) );
44
- add_submenu_page( 'gadash_settings', __( "Backend Settings", 'google-analytics-dashboard-for-wp' ), __( "Backend Settings", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_backend_settings', array( 'GADWP_Settings', 'backend_settings' ) );
45
- add_submenu_page( 'gadash_settings', __( "Frontend Settings", 'google-analytics-dashboard-for-wp' ), __( "Frontend Settings", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_frontend_settings', array( 'GADWP_Settings', 'frontend_settings' ) );
46
- add_submenu_page( 'gadash_settings', __( "Tracking Code", 'google-analytics-dashboard-for-wp' ), __( "Tracking Code", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_tracking_settings', array( 'GADWP_Settings', 'tracking_settings' ) );
47
- add_submenu_page( 'gadash_settings', __( "Errors & Debug", 'google-analytics-dashboard-for-wp' ), __( "Errors & Debug", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_errors_debugging', array( 'GADWP_Settings', 'errors_debugging' ) );
48
- }
49
- }
50
-
51
- /**
52
- * Add Network Menu
53
- */
54
- public function network_menu() {
55
- global $wp_version;
56
- if ( current_user_can( 'manage_netwrok' ) ) {
57
- include ( GADWP_DIR . 'admin/settings.php' );
58
- add_menu_page( __( "Google Analytics", 'google-analytics-dashboard-for-wp' ), "Google Analytics", 'manage_netwrok', 'gadash_settings', array( 'GADWP_Settings', 'general_settings_network' ), version_compare( $wp_version, '3.8.0', '>=' ) ? 'dashicons-chart-area' : GADWP_URL . 'admin/images/gadash-icon.png' );
59
- add_submenu_page( 'gadash_settings', __( "General Settings", 'google-analytics-dashboard-for-wp' ), __( "General Settings", 'google-analytics-dashboard-for-wp' ), 'manage_netwrok', 'gadash_settings', array( 'GADWP_Settings', 'general_settings_network' ) );
60
- add_submenu_page( 'gadash_settings', __( "Errors & Debug", 'google-analytics-dashboard-for-wp' ), __( "Errors & Debug", 'google-analytics-dashboard-for-wp' ), 'manage_network', 'gadash_errors_debugging', array( 'GADWP_Settings', 'errors_debugging' ) );
61
- }
62
- }
63
-
64
- /**
65
- * Styles & Scripts conditional loading (based on current URI)
66
- *
67
- * @param
68
- * $hook
69
- */
70
- public function load_styles_scripts( $hook ) {
71
- $new_hook = explode( '_page_', $hook );
72
-
73
- if ( isset( $new_hook[1] ) ) {
74
- $new_hook = '_page_' . $new_hook[1];
75
- } else {
76
- $new_hook = $hook;
77
- }
78
-
79
- /*
80
- * GADWP main stylesheet
81
- */
82
- wp_enqueue_style( 'gadwp', GADWP_URL . 'admin/css/gadwp.css', null, GADWP_CURRENT_VERSION );
83
-
84
- /*
85
- * GADWP UI
86
- */
87
-
88
- if ( GADWP_Tools::get_cache( 'gapi_errors' ) ) {
89
- $ed_bubble = '!';
90
- } else {
91
- $ed_bubble = '';
92
- }
93
-
94
- wp_enqueue_script( 'gadwp-backend-ui', plugins_url( 'js/ui.js', __FILE__ ), array( 'jquery' ), GADWP_CURRENT_VERSION, true );
95
-
96
- /* @formatter:off */
97
- wp_localize_script( 'gadwp-backend-ui', 'gadwp_ui_data', array(
98
- 'ajaxurl' => admin_url( 'admin-ajax.php' ),
99
- 'security' => wp_create_nonce( 'gadwp_dismiss_notices' ),
100
- 'ed_bubble' => $ed_bubble,
101
- )
102
- );
103
- /* @formatter:on */
104
-
105
- if ( $this->gadwp->config->options['switch_profile'] && count( $this->gadwp->config->options['ga_dash_profile_list'] ) > 1 ) {
106
- $views = array();
107
- foreach ( $this->gadwp->config->options['ga_dash_profile_list'] as $items ) {
108
- if ( $items[3] ) {
109
- $views[$items[1]] = esc_js( GADWP_Tools::strip_protocol( $items[3] ) ); // . ' &#8658; ' . $items[0] );
110
- }
111
- }
112
- } else {
113
- $views = false;
114
- }
115
-
116
- /*
117
- * Main Dashboard Widgets Styles & Scripts
118
- */
119
- $widgets_hooks = array( 'index.php' );
120
-
121
- if ( in_array( $new_hook, $widgets_hooks ) ) {
122
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && $this->gadwp->config->options['dashboard_widget'] ) {
123
-
124
- if ( $this->gadwp->config->options['ga_target_geomap'] ) {
125
- $country_codes = GADWP_Tools::get_countrycodes();
126
- if ( isset( $country_codes[$this->gadwp->config->options['ga_target_geomap']] ) ) {
127
- $region = $this->gadwp->config->options['ga_target_geomap'];
128
- } else {
129
- $region = false;
130
- }
131
- } else {
132
- $region = false;
133
- }
134
-
135
- wp_enqueue_style( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.css', null, GADWP_CURRENT_VERSION );
136
-
137
- wp_enqueue_style( 'gadwp-backend-item-reports', GADWP_URL . 'admin/css/admin-widgets.css', null, GADWP_CURRENT_VERSION );
138
-
139
- wp_register_style( 'jquery-ui-tooltip-html', GADWP_URL . 'common/realtime/jquery.ui.tooltip.html.css' );
140
-
141
- wp_enqueue_style( 'jquery-ui-tooltip-html' );
142
-
143
- wp_register_script( 'jquery-ui-tooltip-html', GADWP_URL . 'common/realtime/jquery.ui.tooltip.html.js' );
144
-
145
- wp_register_script( 'googlecharts', 'https://www.gstatic.com/charts/loader.js', array(), null );
146
-
147
- wp_enqueue_script( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.js', array( 'jquery' ), GADWP_CURRENT_VERSION );
148
-
149
- wp_enqueue_script( 'gadwp-backend-dashboard-reports', GADWP_URL . 'common/js/reports.js', array( 'jquery', 'googlecharts', 'gadwp-nprogress', 'jquery-ui-tooltip', 'jquery-ui-core', 'jquery-ui-position', 'jquery-ui-tooltip-html' ), GADWP_CURRENT_VERSION, true );
150
-
151
- /* @formatter:off */
152
- wp_localize_script( 'gadwp-backend-dashboard-reports', 'gadwpItemData', array(
153
- 'ajaxurl' => admin_url( 'admin-ajax.php' ),
154
- 'security' => wp_create_nonce( 'gadwp_backend_item_reports' ),
155
- 'dateList' => array(
156
- 'realtime' => __( "Real-Time", 'google-analytics-dashboard-for-wp' ),
157
- 'today' => __( "Today", 'google-analytics-dashboard-for-wp' ),
158
- 'yesterday' => __( "Yesterday", 'google-analytics-dashboard-for-wp' ),
159
- '7daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 7 ),
160
- '14daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 14 ),
161
- '30daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 30 ),
162
- '90daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 90 ),
163
- '365daysAgo' => sprintf( _n( "%s Year", "%s Years", 1, 'google-analytics-dashboard-for-wp' ), __('One', 'google-analytics-dashboard-for-wp') ),
164
- '1095daysAgo' => sprintf( _n( "%s Year", "%s Years", 3, 'google-analytics-dashboard-for-wp' ), __('Three', 'google-analytics-dashboard-for-wp') ),
165
- ),
166
- 'reportList' => array(
167
- 'sessions' => __( "Sessions", 'google-analytics-dashboard-for-wp' ),
168
- 'users' => __( "Users", 'google-analytics-dashboard-for-wp' ),
169
- 'organicSearches' => __( "Organic", 'google-analytics-dashboard-for-wp' ),
170
- 'pageviews' => __( "Page Views", 'google-analytics-dashboard-for-wp' ),
171
- 'visitBounceRate' => __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
172
- 'locations' => __( "Location", 'google-analytics-dashboard-for-wp' ),
173
- 'contentpages' => __( "Pages", 'google-analytics-dashboard-for-wp' ),
174
- 'referrers' => __( "Referrers", 'google-analytics-dashboard-for-wp' ),
175
- 'searches' => __( "Searches", 'google-analytics-dashboard-for-wp' ),
176
- 'trafficdetails' => __( "Traffic", 'google-analytics-dashboard-for-wp' ),
177
- 'technologydetails' => __( "Technology", 'google-analytics-dashboard-for-wp' ),
178
- '404errors' => __( "404 Errors", 'google-analytics-dashboard-for-wp' ),
179
- ),
180
- 'i18n' => array(
181
- __( "A JavaScript Error is blocking plugin resources!", 'google-analytics-dashboard-for-wp' ), //0
182
- __( "Traffic Mediums", 'google-analytics-dashboard-for-wp' ),
183
- __( "Visitor Type", 'google-analytics-dashboard-for-wp' ),
184
- __( "Search Engines", 'google-analytics-dashboard-for-wp' ),
185
- __( "Social Networks", 'google-analytics-dashboard-for-wp' ),
186
- __( "Sessions", 'google-analytics-dashboard-for-wp' ),
187
- __( "Users", 'google-analytics-dashboard-for-wp' ),
188
- __( "Page Views", 'google-analytics-dashboard-for-wp' ),
189
- __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
190
- __( "Organic Search", 'google-analytics-dashboard-for-wp' ),
191
- __( "Pages/Session", 'google-analytics-dashboard-for-wp' ),
192
- __( "Invalid response", 'google-analytics-dashboard-for-wp' ),
193
- __( "Not enough data collected", 'google-analytics-dashboard-for-wp' ),
194
- __( "This report is unavailable", 'google-analytics-dashboard-for-wp' ),
195
- __( "report generated by", 'google-analytics-dashboard-for-wp' ), //14
196
- __( "This plugin needs an authorization:", 'google-analytics-dashboard-for-wp' ) . ' <a href="' . menu_page_url( 'gadash_settings', false ) . '">' . __( "authorize the plugin", 'google-analytics-dashboard-for-wp' ) . '</a>.',
197
- __( "Browser", 'google-analytics-dashboard-for-wp' ), //16
198
- __( "Operating System", 'google-analytics-dashboard-for-wp' ),
199
- __( "Screen Resolution", 'google-analytics-dashboard-for-wp' ),
200
- __( "Mobile Brand", 'google-analytics-dashboard-for-wp' ),
201
- __( "REFERRALS", 'google-analytics-dashboard-for-wp' ), //20
202
- __( "KEYWORDS", 'google-analytics-dashboard-for-wp' ),
203
- __( "SOCIAL", 'google-analytics-dashboard-for-wp' ),
204
- __( "CAMPAIGN", 'google-analytics-dashboard-for-wp' ),
205
- __( "DIRECT", 'google-analytics-dashboard-for-wp' ),
206
- __( "NEW", 'google-analytics-dashboard-for-wp' ), //25
207
- ),
208
- 'rtLimitPages' => $this->gadwp->config->options['ga_realtime_pages'],
209
- 'colorVariations' => GADWP_Tools::variations( $this->gadwp->config->options['ga_dash_style'] ),
210
- 'region' => $region,
211
- 'mapsApiKey' => $this->gadwp->config->options['maps_api_key'],
212
- 'language' => get_bloginfo( 'language' ),
213
- 'viewList' => $views,
214
- 'scope' => 'admin-widgets',
215
- )
216
- );
217
- /* @formatter:on */
218
- }
219
- }
220
-
221
- /*
222
- * Posts/Pages List Styles & Scripts
223
- */
224
- $contentstats_hooks = array( 'edit.php' );
225
- if ( in_array( $hook, $contentstats_hooks ) ) {
226
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && $this->gadwp->config->options['backend_item_reports'] ) {
227
-
228
- if ( $this->gadwp->config->options['ga_target_geomap'] ) {
229
- $country_codes = GADWP_Tools::get_countrycodes();
230
- if ( isset( $country_codes[$this->gadwp->config->options['ga_target_geomap']] ) ) {
231
- $region = $this->gadwp->config->options['ga_target_geomap'];
232
- } else {
233
- $region = false;
234
- }
235
- } else {
236
- $region = false;
237
- }
238
-
239
- wp_enqueue_style( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.css', null, GADWP_CURRENT_VERSION );
240
-
241
- wp_enqueue_style( 'gadwp-backend-item-reports', GADWP_URL . 'admin/css/item-reports.css', null, GADWP_CURRENT_VERSION );
242
-
243
- wp_enqueue_style( "wp-jquery-ui-dialog" );
244
-
245
- wp_register_script( 'googlecharts', 'https://www.gstatic.com/charts/loader.js', array(), null );
246
-
247
- wp_enqueue_script( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.js', array( 'jquery' ), GADWP_CURRENT_VERSION );
248
-
249
- wp_enqueue_script( 'gadwp-backend-item-reports', GADWP_URL . 'common/js/reports.js', array( 'gadwp-nprogress', 'googlecharts', 'jquery', 'jquery-ui-dialog' ), GADWP_CURRENT_VERSION, true );
250
-
251
- /* @formatter:off */
252
- wp_localize_script( 'gadwp-backend-item-reports', 'gadwpItemData', array(
253
- 'ajaxurl' => admin_url( 'admin-ajax.php' ),
254
- 'security' => wp_create_nonce( 'gadwp_backend_item_reports' ),
255
- 'dateList' => array(
256
- 'today' => __( "Today", 'google-analytics-dashboard-for-wp' ),
257
- 'yesterday' => __( "Yesterday", 'google-analytics-dashboard-for-wp' ),
258
- '7daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 7 ),
259
- '14daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 14 ),
260
- '30daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 30 ),
261
- '90daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 90 ),
262
- '365daysAgo' => sprintf( _n( "%s Year", "%s Years", 1, 'google-analytics-dashboard-for-wp' ), __('One', 'google-analytics-dashboard-for-wp') ),
263
- '1095daysAgo' => sprintf( _n( "%s Year", "%s Years", 3, 'google-analytics-dashboard-for-wp' ), __('Three', 'google-analytics-dashboard-for-wp') ),
264
- ),
265
- 'reportList' => array(
266
- 'sessions' => __( "Sessions", 'google-analytics-dashboard-for-wp' ),
267
- 'users' => __( "Users", 'google-analytics-dashboard-for-wp' ),
268
- 'organicSearches' => __( "Organic", 'google-analytics-dashboard-for-wp' ),
269
- 'pageviews' => __( "Page Views", 'google-analytics-dashboard-for-wp' ),
270
- 'visitBounceRate' => __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
271
- 'locations' => __( "Location", 'google-analytics-dashboard-for-wp' ),
272
- 'referrers' => __( "Referrers", 'google-analytics-dashboard-for-wp' ),
273
- 'searches' => __( "Searches", 'google-analytics-dashboard-for-wp' ),
274
- 'trafficdetails' => __( "Traffic", 'google-analytics-dashboard-for-wp' ),
275
- 'technologydetails' => __( "Technology", 'google-analytics-dashboard-for-wp' ),
276
- ),
277
- 'i18n' => array(
278
- __( "A JavaScript Error is blocking plugin resources!", 'google-analytics-dashboard-for-wp' ), //0
279
- __( "Traffic Mediums", 'google-analytics-dashboard-for-wp' ),
280
- __( "Visitor Type", 'google-analytics-dashboard-for-wp' ),
281
- __( "Social Networks", 'google-analytics-dashboard-for-wp' ),
282
- __( "Search Engines", 'google-analytics-dashboard-for-wp' ),
283
- __( "Sessions", 'google-analytics-dashboard-for-wp' ),
284
- __( "Users", 'google-analytics-dashboard-for-wp' ),
285
- __( "Page Views", 'google-analytics-dashboard-for-wp' ),
286
- __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
287
- __( "Organic Search", 'google-analytics-dashboard-for-wp' ),
288
- __( "Pages/Session", 'google-analytics-dashboard-for-wp' ),
289
- __( "Invalid response", 'google-analytics-dashboard-for-wp' ),
290
- __( "Not enough data collected", 'google-analytics-dashboard-for-wp' ),
291
- __( "This report is unavailable", 'google-analytics-dashboard-for-wp' ),
292
- __( "report generated by", 'google-analytics-dashboard-for-wp' ), //14
293
- __( "This plugin needs an authorization:", 'google-analytics-dashboard-for-wp' ) . ' <a href="' . menu_page_url( 'gadash_settings', false ) . '">' . __( "authorize the plugin", 'google-analytics-dashboard-for-wp' ) . '</a>.',
294
- __( "Browser", 'google-analytics-dashboard-for-wp' ), //16
295
- __( "Operating System", 'google-analytics-dashboard-for-wp' ),
296
- __( "Screen Resolution", 'google-analytics-dashboard-for-wp' ),
297
- __( "Mobile Brand", 'google-analytics-dashboard-for-wp' ),
298
- ),
299
- 'colorVariations' => GADWP_Tools::variations( $this->gadwp->config->options['ga_dash_style'] ),
300
- 'region' => $region,
301
- 'mapsApiKey' => $this->gadwp->config->options['maps_api_key'],
302
- 'language' => get_bloginfo( 'language' ),
303
- 'viewList' => false,
304
- 'scope' => 'admin-item',
305
- )
306
- );
307
- /* @formatter:on */
308
- }
309
- }
310
-
311
- /*
312
- * Settings Styles & Scripts
313
- */
314
- $settings_hooks = array( '_page_gadash_settings', '_page_gadash_backend_settings', '_page_gadash_frontend_settings', '_page_gadash_tracking_settings', '_page_gadash_errors_debugging' );
315
-
316
- if ( in_array( $new_hook, $settings_hooks ) ) {
317
- wp_enqueue_style( 'wp-color-picker' );
318
- wp_enqueue_script( 'wp-color-picker' );
319
- wp_enqueue_script( 'wp-color-picker-script-handle', plugins_url( 'js/wp-color-picker-script.js', __FILE__ ), array( 'wp-color-picker' ), false, true );
320
- wp_enqueue_script( 'gadwp-settings', plugins_url( 'js/settings.js', __FILE__ ), array( 'jquery' ), GADWP_CURRENT_VERSION, true );
321
- }
322
- }
323
-
324
- /**
325
- * Add "Settings" link in Plugins List
326
- *
327
- * @param
328
- * $links
329
- * @return array
330
- */
331
- public function settings_link( $links ) {
332
- $settings_link = '<a href="' . esc_url( get_admin_url( null, 'admin.php?page=gadash_settings' ) ) . '">' . __( "Settings", 'google-analytics-dashboard-for-wp' ) . '</a>';
333
- array_unshift( $links, $settings_link );
334
- return $links;
335
- }
336
-
337
- /**
338
- * Add an admin notice after a manual or atuomatic update
339
- */
340
- function admin_notice() {
341
- $currentScreen = get_current_screen();
342
-
343
- if ( ! current_user_can( 'manage_options' ) || $currentScreen->base != 'dashboard' ) {
344
- return;
345
- }
346
-
347
- if ( get_option( 'gadwp_got_updated' ) ) :
348
- ?>
349
- <div id="gadwp-notice" class="notice is-dismissible">
350
- <p><?php echo sprintf( __('Google Analytics Dashboard for WP has been updated to version %s.', 'google-analytics-dashboard-for-wp' ), GADWP_CURRENT_VERSION).' '.sprintf( __('For details, check out %1$s and %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf(' <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_notice&utm_medium=link&utm_content=release_notice&utm_campaign=gadwp">%s</a> ', __('the documentation page', 'google-analytics-dashboard-for-wp') ), sprintf(' <a href="%1$s">%2$s</a>', esc_url( get_admin_url( null, 'admin.php?page=gadash_settings' ) ), __('the plugin&#39;s settings page', 'google-analytics-dashboard-for-wp') ) ); ?></p>
351
- </div>
352
-
353
- <?php
354
- endif;
355
- }
356
- }
357
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Backend_Setup' ) ) {
15
+
16
+ final class GADWP_Backend_Setup {
17
+
18
+ private $gadwp;
19
+
20
+ public function __construct() {
21
+ $this->gadwp = GADWP();
22
+
23
+ // Styles & Scripts
24
+ add_action( 'admin_enqueue_scripts', array( $this, 'load_styles_scripts' ) );
25
+ // Site Menu
26
+ add_action( 'admin_menu', array( $this, 'site_menu' ) );
27
+ // Network Menu
28
+ add_action( 'network_admin_menu', array( $this, 'network_menu' ) );
29
+ // Settings link
30
+ add_filter( "plugin_action_links_" . plugin_basename( GADWP_DIR . 'gadwp.php' ), array( $this, 'settings_link' ) );
31
+ // Updated admin notice
32
+ add_action( 'admin_notices', array( $this, 'admin_notice' ) );
33
+ }
34
+
35
+ /**
36
+ * Add Site Menu
37
+ */
38
+ public function site_menu() {
39
+ global $wp_version;
40
+ if ( current_user_can( 'manage_options' ) ) {
41
+ include ( GADWP_DIR . 'admin/settings.php' );
42
+ add_menu_page( __( "Google Analytics", 'google-analytics-dashboard-for-wp' ), __( "Google Analytics", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_settings', array( 'GADWP_Settings', 'general_settings' ), version_compare( $wp_version, '3.8.0', '>=' ) ? 'dashicons-chart-area' : GADWP_URL . 'admin/images/gadash-icon.png' );
43
+ add_submenu_page( 'gadash_settings', __( "General Settings", 'google-analytics-dashboard-for-wp' ), __( "General Settings", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_settings', array( 'GADWP_Settings', 'general_settings' ) );
44
+ add_submenu_page( 'gadash_settings', __( "Backend Settings", 'google-analytics-dashboard-for-wp' ), __( "Backend Settings", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_backend_settings', array( 'GADWP_Settings', 'backend_settings' ) );
45
+ add_submenu_page( 'gadash_settings', __( "Frontend Settings", 'google-analytics-dashboard-for-wp' ), __( "Frontend Settings", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_frontend_settings', array( 'GADWP_Settings', 'frontend_settings' ) );
46
+ add_submenu_page( 'gadash_settings', __( "Tracking Code", 'google-analytics-dashboard-for-wp' ), __( "Tracking Code", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_tracking_settings', array( 'GADWP_Settings', 'tracking_settings' ) );
47
+ add_submenu_page( 'gadash_settings', __( "Errors & Debug", 'google-analytics-dashboard-for-wp' ), __( "Errors & Debug", 'google-analytics-dashboard-for-wp' ), 'manage_options', 'gadash_errors_debugging', array( 'GADWP_Settings', 'errors_debugging' ) );
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Add Network Menu
53
+ */
54
+ public function network_menu() {
55
+ global $wp_version;
56
+ if ( current_user_can( 'manage_netwrok' ) ) {
57
+ include ( GADWP_DIR . 'admin/settings.php' );
58
+ add_menu_page( __( "Google Analytics", 'google-analytics-dashboard-for-wp' ), "Google Analytics", 'manage_netwrok', 'gadash_settings', array( 'GADWP_Settings', 'general_settings_network' ), version_compare( $wp_version, '3.8.0', '>=' ) ? 'dashicons-chart-area' : GADWP_URL . 'admin/images/gadash-icon.png' );
59
+ add_submenu_page( 'gadash_settings', __( "General Settings", 'google-analytics-dashboard-for-wp' ), __( "General Settings", 'google-analytics-dashboard-for-wp' ), 'manage_netwrok', 'gadash_settings', array( 'GADWP_Settings', 'general_settings_network' ) );
60
+ add_submenu_page( 'gadash_settings', __( "Errors & Debug", 'google-analytics-dashboard-for-wp' ), __( "Errors & Debug", 'google-analytics-dashboard-for-wp' ), 'manage_network', 'gadash_errors_debugging', array( 'GADWP_Settings', 'errors_debugging' ) );
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Styles & Scripts conditional loading (based on current URI)
66
+ *
67
+ * @param
68
+ * $hook
69
+ */
70
+ public function load_styles_scripts( $hook ) {
71
+ $new_hook = explode( '_page_', $hook );
72
+
73
+ if ( isset( $new_hook[1] ) ) {
74
+ $new_hook = '_page_' . $new_hook[1];
75
+ } else {
76
+ $new_hook = $hook;
77
+ }
78
+
79
+ /*
80
+ * GADWP main stylesheet
81
+ */
82
+ wp_enqueue_style( 'gadwp', GADWP_URL . 'admin/css/gadwp.css', null, GADWP_CURRENT_VERSION );
83
+
84
+ /*
85
+ * GADWP UI
86
+ */
87
+
88
+ if ( GADWP_Tools::get_cache( 'gapi_errors' ) ) {
89
+ $ed_bubble = '!';
90
+ } else {
91
+ $ed_bubble = '';
92
+ }
93
+
94
+ wp_enqueue_script( 'gadwp-backend-ui', plugins_url( 'js/ui.js', __FILE__ ), array( 'jquery' ), GADWP_CURRENT_VERSION, true );
95
+
96
+ /* @formatter:off */
97
+ wp_localize_script( 'gadwp-backend-ui', 'gadwp_ui_data', array(
98
+ 'ajaxurl' => admin_url( 'admin-ajax.php' ),
99
+ 'security' => wp_create_nonce( 'gadwp_dismiss_notices' ),
100
+ 'ed_bubble' => $ed_bubble,
101
+ )
102
+ );
103
+ /* @formatter:on */
104
+
105
+ if ( $this->gadwp->config->options['switch_profile'] && count( $this->gadwp->config->options['ga_dash_profile_list'] ) > 1 ) {
106
+ $views = array();
107
+ foreach ( $this->gadwp->config->options['ga_dash_profile_list'] as $items ) {
108
+ if ( $items[3] ) {
109
+ $views[$items[1]] = esc_js( GADWP_Tools::strip_protocol( $items[3] ) ); // . ' &#8658; ' . $items[0] );
110
+ }
111
+ }
112
+ } else {
113
+ $views = false;
114
+ }
115
+
116
+ /*
117
+ * Main Dashboard Widgets Styles & Scripts
118
+ */
119
+ $widgets_hooks = array( 'index.php' );
120
+
121
+ if ( in_array( $new_hook, $widgets_hooks ) ) {
122
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && $this->gadwp->config->options['dashboard_widget'] ) {
123
+
124
+ if ( $this->gadwp->config->options['ga_target_geomap'] ) {
125
+ $country_codes = GADWP_Tools::get_countrycodes();
126
+ if ( isset( $country_codes[$this->gadwp->config->options['ga_target_geomap']] ) ) {
127
+ $region = $this->gadwp->config->options['ga_target_geomap'];
128
+ } else {
129
+ $region = false;
130
+ }
131
+ } else {
132
+ $region = false;
133
+ }
134
+
135
+ wp_enqueue_style( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.css', null, GADWP_CURRENT_VERSION );
136
+
137
+ wp_enqueue_style( 'gadwp-backend-item-reports', GADWP_URL . 'admin/css/admin-widgets.css', null, GADWP_CURRENT_VERSION );
138
+
139
+ wp_register_style( 'jquery-ui-tooltip-html', GADWP_URL . 'common/realtime/jquery.ui.tooltip.html.css' );
140
+
141
+ wp_enqueue_style( 'jquery-ui-tooltip-html' );
142
+
143
+ wp_register_script( 'jquery-ui-tooltip-html', GADWP_URL . 'common/realtime/jquery.ui.tooltip.html.js' );
144
+
145
+ wp_register_script( 'googlecharts', 'https://www.gstatic.com/charts/loader.js', array(), null );
146
+
147
+ wp_enqueue_script( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.js', array( 'jquery' ), GADWP_CURRENT_VERSION );
148
+
149
+ wp_enqueue_script( 'gadwp-backend-dashboard-reports', GADWP_URL . 'common/js/reports.js', array( 'jquery', 'googlecharts', 'gadwp-nprogress', 'jquery-ui-tooltip', 'jquery-ui-core', 'jquery-ui-position', 'jquery-ui-tooltip-html' ), GADWP_CURRENT_VERSION, true );
150
+
151
+ /* @formatter:off */
152
+ wp_localize_script( 'gadwp-backend-dashboard-reports', 'gadwpItemData', array(
153
+ 'ajaxurl' => admin_url( 'admin-ajax.php' ),
154
+ 'security' => wp_create_nonce( 'gadwp_backend_item_reports' ),
155
+ 'dateList' => array(
156
+ 'realtime' => __( "Real-Time", 'google-analytics-dashboard-for-wp' ),
157
+ 'today' => __( "Today", 'google-analytics-dashboard-for-wp' ),
158
+ 'yesterday' => __( "Yesterday", 'google-analytics-dashboard-for-wp' ),
159
+ '7daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 7 ),
160
+ '14daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 14 ),
161
+ '30daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 30 ),
162
+ '90daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 90 ),
163
+ '365daysAgo' => sprintf( _n( "%s Year", "%s Years", 1, 'google-analytics-dashboard-for-wp' ), __('One', 'google-analytics-dashboard-for-wp') ),
164
+ '1095daysAgo' => sprintf( _n( "%s Year", "%s Years", 3, 'google-analytics-dashboard-for-wp' ), __('Three', 'google-analytics-dashboard-for-wp') ),
165
+ ),
166
+ 'reportList' => array(
167
+ 'sessions' => __( "Sessions", 'google-analytics-dashboard-for-wp' ),
168
+ 'users' => __( "Users", 'google-analytics-dashboard-for-wp' ),
169
+ 'organicSearches' => __( "Organic", 'google-analytics-dashboard-for-wp' ),
170
+ 'pageviews' => __( "Page Views", 'google-analytics-dashboard-for-wp' ),
171
+ 'visitBounceRate' => __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
172
+ 'locations' => __( "Location", 'google-analytics-dashboard-for-wp' ),
173
+ 'contentpages' => __( "Pages", 'google-analytics-dashboard-for-wp' ),
174
+ 'referrers' => __( "Referrers", 'google-analytics-dashboard-for-wp' ),
175
+ 'searches' => __( "Searches", 'google-analytics-dashboard-for-wp' ),
176
+ 'trafficdetails' => __( "Traffic", 'google-analytics-dashboard-for-wp' ),
177
+ 'technologydetails' => __( "Technology", 'google-analytics-dashboard-for-wp' ),
178
+ '404errors' => __( "404 Errors", 'google-analytics-dashboard-for-wp' ),
179
+ ),
180
+ 'i18n' => array(
181
+ __( "A JavaScript Error is blocking plugin resources!", 'google-analytics-dashboard-for-wp' ), //0
182
+ __( "Traffic Mediums", 'google-analytics-dashboard-for-wp' ),
183
+ __( "Visitor Type", 'google-analytics-dashboard-for-wp' ),
184
+ __( "Search Engines", 'google-analytics-dashboard-for-wp' ),
185
+ __( "Social Networks", 'google-analytics-dashboard-for-wp' ),
186
+ __( "Sessions", 'google-analytics-dashboard-for-wp' ),
187
+ __( "Users", 'google-analytics-dashboard-for-wp' ),
188
+ __( "Page Views", 'google-analytics-dashboard-for-wp' ),
189
+ __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
190
+ __( "Organic Search", 'google-analytics-dashboard-for-wp' ),
191
+ __( "Pages/Session", 'google-analytics-dashboard-for-wp' ),
192
+ __( "Invalid response", 'google-analytics-dashboard-for-wp' ),
193
+ __( "Not enough data collected", 'google-analytics-dashboard-for-wp' ),
194
+ __( "This report is unavailable", 'google-analytics-dashboard-for-wp' ),
195
+ __( "report generated by", 'google-analytics-dashboard-for-wp' ), //14
196
+ __( "This plugin needs an authorization:", 'google-analytics-dashboard-for-wp' ) . ' <a href="' . menu_page_url( 'gadash_settings', false ) . '">' . __( "authorize the plugin", 'google-analytics-dashboard-for-wp' ) . '</a>.',
197
+ __( "Browser", 'google-analytics-dashboard-for-wp' ), //16
198
+ __( "Operating System", 'google-analytics-dashboard-for-wp' ),
199
+ __( "Screen Resolution", 'google-analytics-dashboard-for-wp' ),
200
+ __( "Mobile Brand", 'google-analytics-dashboard-for-wp' ),
201
+ __( "REFERRALS", 'google-analytics-dashboard-for-wp' ), //20
202
+ __( "KEYWORDS", 'google-analytics-dashboard-for-wp' ),
203
+ __( "SOCIAL", 'google-analytics-dashboard-for-wp' ),
204
+ __( "CAMPAIGN", 'google-analytics-dashboard-for-wp' ),
205
+ __( "DIRECT", 'google-analytics-dashboard-for-wp' ),
206
+ __( "NEW", 'google-analytics-dashboard-for-wp' ), //25
207
+ ),
208
+ 'rtLimitPages' => $this->gadwp->config->options['ga_realtime_pages'],
209
+ 'colorVariations' => GADWP_Tools::variations( $this->gadwp->config->options['ga_dash_style'] ),
210
+ 'region' => $region,
211
+ 'mapsApiKey' => $this->gadwp->config->options['maps_api_key'],
212
+ 'language' => get_bloginfo( 'language' ),
213
+ 'viewList' => $views,
214
+ 'scope' => 'admin-widgets',
215
+ )
216
+ );
217
+ /* @formatter:on */
218
+ }
219
+ }
220
+
221
+ /*
222
+ * Posts/Pages List Styles & Scripts
223
+ */
224
+ $contentstats_hooks = array( 'edit.php' );
225
+ if ( in_array( $hook, $contentstats_hooks ) ) {
226
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && $this->gadwp->config->options['backend_item_reports'] ) {
227
+
228
+ if ( $this->gadwp->config->options['ga_target_geomap'] ) {
229
+ $country_codes = GADWP_Tools::get_countrycodes();
230
+ if ( isset( $country_codes[$this->gadwp->config->options['ga_target_geomap']] ) ) {
231
+ $region = $this->gadwp->config->options['ga_target_geomap'];
232
+ } else {
233
+ $region = false;
234
+ }
235
+ } else {
236
+ $region = false;
237
+ }
238
+
239
+ wp_enqueue_style( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.css', null, GADWP_CURRENT_VERSION );
240
+
241
+ wp_enqueue_style( 'gadwp-backend-item-reports', GADWP_URL . 'admin/css/item-reports.css', null, GADWP_CURRENT_VERSION );
242
+
243
+ wp_enqueue_style( "wp-jquery-ui-dialog" );
244
+
245
+ wp_register_script( 'googlecharts', 'https://www.gstatic.com/charts/loader.js', array(), null );
246
+
247
+ wp_enqueue_script( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.js', array( 'jquery' ), GADWP_CURRENT_VERSION );
248
+
249
+ wp_enqueue_script( 'gadwp-backend-item-reports', GADWP_URL . 'common/js/reports.js', array( 'gadwp-nprogress', 'googlecharts', 'jquery', 'jquery-ui-dialog' ), GADWP_CURRENT_VERSION, true );
250
+
251
+ /* @formatter:off */
252
+ wp_localize_script( 'gadwp-backend-item-reports', 'gadwpItemData', array(
253
+ 'ajaxurl' => admin_url( 'admin-ajax.php' ),
254
+ 'security' => wp_create_nonce( 'gadwp_backend_item_reports' ),
255
+ 'dateList' => array(
256
+ 'today' => __( "Today", 'google-analytics-dashboard-for-wp' ),
257
+ 'yesterday' => __( "Yesterday", 'google-analytics-dashboard-for-wp' ),
258
+ '7daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 7 ),
259
+ '14daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 14 ),
260
+ '30daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 30 ),
261
+ '90daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 90 ),
262
+ '365daysAgo' => sprintf( _n( "%s Year", "%s Years", 1, 'google-analytics-dashboard-for-wp' ), __('One', 'google-analytics-dashboard-for-wp') ),
263
+ '1095daysAgo' => sprintf( _n( "%s Year", "%s Years", 3, 'google-analytics-dashboard-for-wp' ), __('Three', 'google-analytics-dashboard-for-wp') ),
264
+ ),
265
+ 'reportList' => array(
266
+ 'sessions' => __( "Sessions", 'google-analytics-dashboard-for-wp' ),
267
+ 'users' => __( "Users", 'google-analytics-dashboard-for-wp' ),
268
+ 'organicSearches' => __( "Organic", 'google-analytics-dashboard-for-wp' ),
269
+ 'pageviews' => __( "Page Views", 'google-analytics-dashboard-for-wp' ),
270
+ 'visitBounceRate' => __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
271
+ 'locations' => __( "Location", 'google-analytics-dashboard-for-wp' ),
272
+ 'referrers' => __( "Referrers", 'google-analytics-dashboard-for-wp' ),
273
+ 'searches' => __( "Searches", 'google-analytics-dashboard-for-wp' ),
274
+ 'trafficdetails' => __( "Traffic", 'google-analytics-dashboard-for-wp' ),
275
+ 'technologydetails' => __( "Technology", 'google-analytics-dashboard-for-wp' ),
276
+ ),
277
+ 'i18n' => array(
278
+ __( "A JavaScript Error is blocking plugin resources!", 'google-analytics-dashboard-for-wp' ), //0
279
+ __( "Traffic Mediums", 'google-analytics-dashboard-for-wp' ),
280
+ __( "Visitor Type", 'google-analytics-dashboard-for-wp' ),
281
+ __( "Social Networks", 'google-analytics-dashboard-for-wp' ),
282
+ __( "Search Engines", 'google-analytics-dashboard-for-wp' ),
283
+ __( "Sessions", 'google-analytics-dashboard-for-wp' ),
284
+ __( "Users", 'google-analytics-dashboard-for-wp' ),
285
+ __( "Page Views", 'google-analytics-dashboard-for-wp' ),
286
+ __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
287
+ __( "Organic Search", 'google-analytics-dashboard-for-wp' ),
288
+ __( "Pages/Session", 'google-analytics-dashboard-for-wp' ),
289
+ __( "Invalid response", 'google-analytics-dashboard-for-wp' ),
290
+ __( "Not enough data collected", 'google-analytics-dashboard-for-wp' ),
291
+ __( "This report is unavailable", 'google-analytics-dashboard-for-wp' ),
292
+ __( "report generated by", 'google-analytics-dashboard-for-wp' ), //14
293
+ __( "This plugin needs an authorization:", 'google-analytics-dashboard-for-wp' ) . ' <a href="' . menu_page_url( 'gadash_settings', false ) . '">' . __( "authorize the plugin", 'google-analytics-dashboard-for-wp' ) . '</a>.',
294
+ __( "Browser", 'google-analytics-dashboard-for-wp' ), //16
295
+ __( "Operating System", 'google-analytics-dashboard-for-wp' ),
296
+ __( "Screen Resolution", 'google-analytics-dashboard-for-wp' ),
297
+ __( "Mobile Brand", 'google-analytics-dashboard-for-wp' ),
298
+ ),
299
+ 'colorVariations' => GADWP_Tools::variations( $this->gadwp->config->options['ga_dash_style'] ),
300
+ 'region' => $region,
301
+ 'mapsApiKey' => $this->gadwp->config->options['maps_api_key'],
302
+ 'language' => get_bloginfo( 'language' ),
303
+ 'viewList' => false,
304
+ 'scope' => 'admin-item',
305
+ )
306
+ );
307
+ /* @formatter:on */
308
+ }
309
+ }
310
+
311
+ /*
312
+ * Settings Styles & Scripts
313
+ */
314
+ $settings_hooks = array( '_page_gadash_settings', '_page_gadash_backend_settings', '_page_gadash_frontend_settings', '_page_gadash_tracking_settings', '_page_gadash_errors_debugging' );
315
+
316
+ if ( in_array( $new_hook, $settings_hooks ) ) {
317
+ wp_enqueue_style( 'wp-color-picker' );
318
+ wp_enqueue_script( 'wp-color-picker' );
319
+ wp_enqueue_script( 'wp-color-picker-script-handle', plugins_url( 'js/wp-color-picker-script.js', __FILE__ ), array( 'wp-color-picker' ), false, true );
320
+ wp_enqueue_script( 'gadwp-settings', plugins_url( 'js/settings.js', __FILE__ ), array( 'jquery' ), GADWP_CURRENT_VERSION, true );
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Add "Settings" link in Plugins List
326
+ *
327
+ * @param
328
+ * $links
329
+ * @return array
330
+ */
331
+ public function settings_link( $links ) {
332
+ $settings_link = '<a href="' . esc_url( get_admin_url( null, 'admin.php?page=gadash_settings' ) ) . '">' . __( "Settings", 'google-analytics-dashboard-for-wp' ) . '</a>';
333
+ array_unshift( $links, $settings_link );
334
+ return $links;
335
+ }
336
+
337
+ /**
338
+ * Add an admin notice after a manual or atuomatic update
339
+ */
340
+ function admin_notice() {
341
+ $currentScreen = get_current_screen();
342
+
343
+ if ( ! current_user_can( 'manage_options' ) || $currentScreen->base != 'dashboard' ) {
344
+ return;
345
+ }
346
+
347
+ if ( get_option( 'gadwp_got_updated' ) ) :
348
+ ?>
349
+ <div id="gadwp-notice" class="notice is-dismissible">
350
+ <p><?php echo sprintf( __('Google Analytics Dashboard for WP has been updated to version %s.', 'google-analytics-dashboard-for-wp' ), GADWP_CURRENT_VERSION).' '.sprintf( __('For details, check out %1$s and %2$s.', 'google-analytics-dashboard-for-wp' ), sprintf(' <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_notice&utm_medium=link&utm_content=release_notice&utm_campaign=gadwp">%s</a> ', __('the documentation page', 'google-analytics-dashboard-for-wp') ), sprintf(' <a href="%1$s">%2$s</a>', esc_url( get_admin_url( null, 'admin.php?page=gadash_settings' ) ), __('the plugin&#39;s settings page', 'google-analytics-dashboard-for-wp') ) ); ?></p>
351
+ </div>
352
+
353
+ <?php
354
+ endif;
355
+ }
356
+ }
357
+ }
admin/widgets.php CHANGED
@@ -1,65 +1,65 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Backend_Widgets' ) ) {
15
-
16
- class GADWP_Backend_Widgets {
17
-
18
- private $gadwp;
19
-
20
- public function __construct() {
21
- $this->gadwp = GADWP();
22
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && ( 1 == $this->gadwp->config->options['dashboard_widget'] ) ) {
23
- add_action( 'wp_dashboard_setup', array( $this, 'add_widget' ) );
24
- }
25
- }
26
-
27
- public function add_widget() {
28
- wp_add_dashboard_widget( 'gadwp-widget', __( "Google Analytics Dashboard", 'google-analytics-dashboard-for-wp' ), array( $this, 'dashboard_widget' ), $control_callback = null );
29
- }
30
-
31
- public function dashboard_widget() {
32
- $projectId = 0;
33
-
34
- if ( empty( $this->gadwp->config->options['ga_dash_token'] ) ) {
35
- echo '<p>' . __( "This plugin needs an authorization:", 'google-analytics-dashboard-for-wp' ) . '</p><form action="' . menu_page_url( 'gadash_settings', false ) . '" method="POST">' . get_submit_button( __( "Authorize Plugin", 'google-analytics-dashboard-for-wp' ), 'secondary' ) . '</form>';
36
- return;
37
- }
38
-
39
- if ( current_user_can( 'manage_options' ) ) {
40
- if ( $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
41
- $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
42
- } else {
43
- echo '<p>' . __( "An admin should asign a default Google Analytics Profile.", 'google-analytics-dashboard-for-wp' ) . '</p><form action="' . menu_page_url( 'gadash_settings', false ) . '" method="POST">' . get_submit_button( __( "Select Domain", 'google-analytics-dashboard-for-wp' ), 'secondary' ) . '</form>';
44
- return;
45
- }
46
- } else {
47
- if ( $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
48
- $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
49
- } else {
50
- echo '<p>' . __( "An admin should asign a default Google Analytics Profile.", 'google-analytics-dashboard-for-wp' ) . '</p><form action="' . menu_page_url( 'gadash_settings', false ) . '" method="POST">' . get_submit_button( __( "Select Domain", 'google-analytics-dashboard-for-wp' ), 'secondary' ) . '</form>';
51
- return;
52
- }
53
- }
54
-
55
- if ( ! ( $projectId ) ) {
56
- echo '<p>' . __( "Something went wrong while retrieving property data. You need to create and properly configure a Google Analytics account:", 'google-analytics-dashboard-for-wp' ) . '</p> <form action="https://deconf.com/how-to-set-up-google-analytics-on-your-website/" method="POST">' . get_submit_button( __( "Find out more!", 'google-analytics-dashboard-for-wp' ), 'secondary' ) . '</form>';
57
- return;
58
- }
59
-
60
- ?>
61
- <div id="gadwp-window-1"></div>
62
- <?php
63
- }
64
- }
65
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Backend_Widgets' ) ) {
15
+
16
+ class GADWP_Backend_Widgets {
17
+
18
+ private $gadwp;
19
+
20
+ public function __construct() {
21
+ $this->gadwp = GADWP();
22
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) && ( 1 == $this->gadwp->config->options['dashboard_widget'] ) ) {
23
+ add_action( 'wp_dashboard_setup', array( $this, 'add_widget' ) );
24
+ }
25
+ }
26
+
27
+ public function add_widget() {
28
+ wp_add_dashboard_widget( 'gadwp-widget', __( "Google Analytics Dashboard", 'google-analytics-dashboard-for-wp' ), array( $this, 'dashboard_widget' ), $control_callback = null );
29
+ }
30
+
31
+ public function dashboard_widget() {
32
+ $projectId = 0;
33
+
34
+ if ( empty( $this->gadwp->config->options['ga_dash_token'] ) ) {
35
+ echo '<p>' . __( "This plugin needs an authorization:", 'google-analytics-dashboard-for-wp' ) . '</p><form action="' . menu_page_url( 'gadash_settings', false ) . '" method="POST">' . get_submit_button( __( "Authorize Plugin", 'google-analytics-dashboard-for-wp' ), 'secondary' ) . '</form>';
36
+ return;
37
+ }
38
+
39
+ if ( current_user_can( 'manage_options' ) ) {
40
+ if ( $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
41
+ $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
42
+ } else {
43
+ echo '<p>' . __( "An admin should asign a default Google Analytics Profile.", 'google-analytics-dashboard-for-wp' ) . '</p><form action="' . menu_page_url( 'gadash_settings', false ) . '" method="POST">' . get_submit_button( __( "Select Domain", 'google-analytics-dashboard-for-wp' ), 'secondary' ) . '</form>';
44
+ return;
45
+ }
46
+ } else {
47
+ if ( $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
48
+ $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
49
+ } else {
50
+ echo '<p>' . __( "An admin should asign a default Google Analytics Profile.", 'google-analytics-dashboard-for-wp' ) . '</p><form action="' . menu_page_url( 'gadash_settings', false ) . '" method="POST">' . get_submit_button( __( "Select Domain", 'google-analytics-dashboard-for-wp' ), 'secondary' ) . '</form>';
51
+ return;
52
+ }
53
+ }
54
+
55
+ if ( ! ( $projectId ) ) {
56
+ echo '<p>' . __( "Something went wrong while retrieving property data. You need to create and properly configure a Google Analytics account:", 'google-analytics-dashboard-for-wp' ) . '</p> <form action="https://deconf.com/how-to-set-up-google-analytics-on-your-website/" method="POST">' . get_submit_button( __( "Find out more!", 'google-analytics-dashboard-for-wp' ), 'secondary' ) . '</form>';
57
+ return;
58
+ }
59
+
60
+ ?>
61
+ <div id="gadwp-window-1"></div>
62
+ <?php
63
+ }
64
+ }
65
+ }
common/ajax-actions.php CHANGED
@@ -1,43 +1,43 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Common_Ajax' ) ) {
15
-
16
- final class GADWP_Common_Ajax {
17
-
18
- private $gadwp;
19
-
20
- public function __construct() {
21
- $this->gadwp = GADWP();
22
-
23
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) || GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) ) {
24
- add_action( 'wp_ajax_gadwp_set_error', array( $this, 'ajax_set_error' ) );
25
- }
26
- }
27
-
28
- /**
29
- * Ajax handler for storing JavaScript Errors
30
- *
31
- * @return json|int
32
- */
33
- public function ajax_set_error() {
34
- if ( ! isset( $_POST['gadwp_security_set_error'] ) || ! ( wp_verify_nonce( $_POST['gadwp_security_set_error'], 'gadwp_backend_item_reports' ) || wp_verify_nonce( $_POST['gadwp_security_set_error'], 'gadwp_frontend_item_reports' ) ) ) {
35
- wp_die( - 40 );
36
- }
37
-
38
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $_POST['response'] ), 24 * 60 * 60 );
39
-
40
- wp_die();
41
- }
42
- }
43
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Common_Ajax' ) ) {
15
+
16
+ final class GADWP_Common_Ajax {
17
+
18
+ private $gadwp;
19
+
20
+ public function __construct() {
21
+ $this->gadwp = GADWP();
22
+
23
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_back'] ) || GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) ) {
24
+ add_action( 'wp_ajax_gadwp_set_error', array( $this, 'ajax_set_error' ) );
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Ajax handler for storing JavaScript Errors
30
+ *
31
+ * @return json|int
32
+ */
33
+ public function ajax_set_error() {
34
+ if ( ! isset( $_POST['gadwp_security_set_error'] ) || ! ( wp_verify_nonce( $_POST['gadwp_security_set_error'], 'gadwp_backend_item_reports' ) || wp_verify_nonce( $_POST['gadwp_security_set_error'], 'gadwp_frontend_item_reports' ) ) ) {
35
+ wp_die( - 40 );
36
+ }
37
+
38
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $_POST['response'] ), 24 * 60 * 60 );
39
+
40
+ wp_die();
41
+ }
42
+ }
43
+ }
common/js/reports.js CHANGED
@@ -1,1107 +1,1107 @@
1
- /*-
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
-
9
- "use strict";
10
-
11
- google.charts.load('current', {mapsApiKey: gadwpItemData.mapsApiKey, 'packages':['corechart', 'table', 'orgchart', 'geochart']});
12
- google.charts.setOnLoadCallback( GADWPReportLoad );
13
-
14
- // Get the numeric ID
15
- gadwpItemData.getID = function ( item ) {
16
- if ( gadwpItemData.scope == 'admin-item' ) {
17
- if ( typeof item.id == "undefined" ) {
18
- return 0
19
- }
20
- if ( item.id.split( '-' )[ 1 ] == "undefined" ) {
21
- return 0;
22
- } else {
23
- return item.id.split( '-' )[ 1 ];
24
- }
25
- } else {
26
- if ( typeof item.id == "undefined" ) {
27
- return 1;
28
- }
29
- if ( item.id.split( '-' )[ 4 ] == "undefined" ) {
30
- return 1;
31
- } else {
32
- return item.id.split( '-' )[ 4 ];
33
- }
34
- }
35
- }
36
-
37
- // Get the selector
38
- gadwpItemData.getSelector = function ( scope ) {
39
- if ( scope == 'admin-item' ) {
40
- return 'a[id^="gadwp-"]';
41
- } else {
42
- return 'li[id^="wp-admin-bar-gadwp"]';
43
- }
44
- }
45
-
46
- gadwpItemData.responsiveDialog = function () {
47
- var dialog, wWidth, visible;
48
-
49
- visible = jQuery( ".ui-dialog:visible" );
50
-
51
- // on each visible dialog
52
- visible.each( function () {
53
- dialog = jQuery( this ).find( ".ui-dialog-content" ).data( "ui-dialog" );
54
- // on each fluid dialog
55
- if ( dialog.options.fluid ) {
56
- wWidth = jQuery( window ).width();
57
- // window width vs dialog width
58
- if ( wWidth < ( parseInt( dialog.options.maxWidth ) + 50 ) ) {
59
- // don't fill the entire screen
60
- jQuery( this ).css( "max-width", "90%" );
61
- } else {
62
- // maxWidth bug fix
63
- jQuery( this ).css( "max-width", dialog.options.maxWidth + "px" );
64
- }
65
- // change dialog position
66
- dialog.option( "position", dialog.options.position );
67
- }
68
- } );
69
- }
70
-
71
- jQuery.fn.extend( {
72
- gadwpItemReport : function ( itemId ) {
73
- var postData, tools, template, reports, refresh, init, slug = "-" + itemId;
74
-
75
- tools = {
76
- setCookie : function ( name, value ) {
77
- var expires, dateItem = new Date();
78
-
79
- if ( gadwpItemData.scope == 'admin-widgets' ) {
80
- name = "gadwp_wg_" + name;
81
- } else {
82
- name = "gadwp_ir_" + name;
83
- }
84
- dateItem.setTime( dateItem.getTime() + ( 24 * 60 * 60 * 1000 * 7 ) );
85
- expires = "expires=" + dateItem.toUTCString();
86
- document.cookie = name + "=" + value + "; " + expires + "; path=/";
87
- },
88
- getCookie : function ( name ) {
89
- var cookie, cookiesArray, div, i = 0;
90
-
91
- if ( gadwpItemData.scope == 'admin-widgets' ) {
92
- name = "gadwp_wg_" + name + "=";
93
- } else {
94
- name = "gadwp_ir_" + name + "=";
95
- }
96
- cookiesArray = document.cookie.split( ';' );
97
- for ( i = 0; i < cookiesArray.length; i++ ) {
98
- cookie = cookiesArray[ i ];
99
- while ( cookie.charAt( 0 ) == ' ' )
100
- cookie = cookie.substring( 1 );
101
- if ( cookie.indexOf( name ) == 0 )
102
- return cookie.substring( name.length, cookie.length );
103
- }
104
- return false;
105
- },
106
- escape : function ( str ) {
107
- div = document.createElement( 'div' );
108
- div.appendChild( document.createTextNode( str ) );
109
- return div.innerHTML;
110
- }
111
- }
112
-
113
- template = {
114
-
115
- addOptions : function ( id, list ) {
116
- var defaultMetric, defaultDimension, defaultView, output = [];
117
-
118
- if ( list == false ) {
119
- return;
120
- }
121
-
122
- if ( !tools.getCookie( 'default_metric' ) || !tools.getCookie( 'default_dimension' ) ) {
123
- defaultMetric = 'sessions';
124
- defaultDimension = '30daysAgo';
125
- } else {
126
- defaultMetric = tools.getCookie( 'default_metric' );
127
- defaultDimension = tools.getCookie( 'default_dimension' );
128
- defaultView = tools.getCookie( 'default_view' );
129
- }
130
-
131
- jQuery.each( list, function ( key, value ) {
132
- if ( key == defaultMetric || key == defaultDimension || key == defaultView ) {
133
- output.push( '<option value="' + key + '" selected="selected">' + value + '</option>' );
134
- } else {
135
- output.push( '<option value="' + key + '">' + value + '</option>' );
136
- }
137
- } );
138
- jQuery( id ).html( output.join( '' ) );
139
- },
140
-
141
- init : function () {
142
- var tpl;
143
-
144
- if ( !jQuery( '#gadwp-window' + slug ).length ) {
145
- return;
146
- }
147
-
148
- if ( jQuery( '#gadwp-window' + slug ).html().length ) { // add main template once
149
- return;
150
- }
151
-
152
- tpl = '<div id="gadwp-container' + slug + '">';
153
- if ( gadwpItemData.viewList != false ) {
154
- tpl += '<select id="gadwp-sel-view' + slug + '"></select>';
155
- }
156
- tpl += '<select id="gadwp-sel-period' + slug + '"></select> ';
157
- tpl += '<select id="gadwp-sel-report' + slug + '"></select>';
158
- tpl += '<div id="gadwp-progressbar' + slug + '"></div>';
159
- tpl += '<div id="gadwp-status' + slug + '"></div>';
160
- tpl += '<div id="gadwp-reports' + slug + '"></div>';
161
- tpl += '<div style="text-align:right;width:100%;font-size:0.8em;clear:both;margin-right:5px;margin-top:10px;">';
162
- tpl += gadwpItemData.i18n[ 14 ];
163
- tpl += ' <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_report&utm_medium=link&utm_content=back_report&utm_campaign=gadwp" rel="nofollow" style="text-decoration:none;font-size:1em;">GADWP</a>&nbsp;';
164
- tpl += '</div>';
165
- tpl += '</div>',
166
-
167
- jQuery( '#gadwp-window' + slug ).append( tpl );
168
-
169
- template.addOptions( '#gadwp-sel-view' + slug, gadwpItemData.viewList );
170
- template.addOptions( '#gadwp-sel-period' + slug, gadwpItemData.dateList );
171
- template.addOptions( '#gadwp-sel-report' + slug, gadwpItemData.reportList );
172
-
173
- }
174
- }
175
-
176
- reports = {
177
- oldViewPort: 0,
178
- orgChartTableChartData : '',
179
- tableChartData : '',
180
- orgChartPieChartsData : '',
181
- geoChartTableChartData : '',
182
- areaChartBottomStatsData : '',
183
- realtime : '',
184
- rtRuns : null,
185
- i18n : null,
186
-
187
- getTitle : function ( scope ) {
188
- if ( scope == 'admin-item' ) {
189
- return jQuery( '#gadwp' + slug ).attr( "title" );
190
- } else {
191
- return document.getElementsByTagName( "title" )[ 0 ].innerHTML;
192
- }
193
- },
194
-
195
- alertMessage : function ( msg ) {
196
- jQuery( "#gadwp-status" + slug ).css( {
197
- "margin-top" : "3px",
198
- "padding-left" : "5px",
199
- "height" : "auto",
200
- "color" : "#000",
201
- "border-left" : "5px solid red"
202
- } );
203
- jQuery( "#gadwp-status" + slug ).html( msg );
204
- },
205
-
206
- areaChartBottomStats : function ( response ) {
207
- reports.areaChartBottomStatsData = response;
208
- if ( jQuery.isArray( response ) ) {
209
- if ( !jQuery.isNumeric( response[ 0 ] ) ) {
210
- if ( jQuery.isArray( response[ 0 ] ) ) {
211
- jQuery( '#gadwp-reports' + slug ).show();
212
- if ( postData.query == 'visitBounceRate,bottomstats' ) {
213
- reports.drawAreaChart( response[ 0 ], true );
214
- } else {
215
- reports.drawAreaChart( response[ 0 ], false );
216
- }
217
- } else {
218
- reports.throwDebug( response[ 0 ] );
219
- }
220
- } else {
221
- jQuery( '#gadwp-reports' + slug ).show();
222
- reports.throwError( '#gadwp-areachart' + slug, response[ 0 ], "125px" );
223
- }
224
- if ( !jQuery.isNumeric( response[ 1 ] ) ) {
225
- if ( jQuery.isArray( response[ 1 ] ) ) {
226
- jQuery( '#gadwp-reports' + slug ).show();
227
- reports.drawBottomStats( response[ 1 ] );
228
- } else {
229
- reports.throwDebug( response[ 1 ] );
230
- }
231
- } else {
232
- jQuery( '#gadwp-reports' + slug ).show();
233
- reports.throwError( '#gadwp-bottomstats' + slug, response[ 1 ], "40px" );
234
- }
235
- } else {
236
- reports.throwDebug( response );
237
- }
238
- NProgress.done();
239
-
240
- },
241
-
242
- orgChartPieCharts : function ( response ) {
243
- var i = 0;
244
- reports.orgChartPieChartsData = response;
245
- if ( jQuery.isArray( response ) ) {
246
- if ( !jQuery.isNumeric( response[ 0 ] ) ) {
247
- if ( jQuery.isArray( response[ 0 ] ) ) {
248
- jQuery( '#gadwp-reports' + slug ).show();
249
- reports.drawOrgChart( response[ 0 ] );
250
- } else {
251
- reports.throwDebug( response[ 0 ] );
252
- }
253
- } else {
254
- jQuery( '#gadwp-reports' + slug ).show();
255
- reports.throwError( '#gadwp-orgchart' + slug, response[ 0 ], "125px" );
256
- }
257
-
258
- for ( i = 1; i < response.length; i++ ) {
259
- if ( !jQuery.isNumeric( response[ i ] ) ) {
260
- if ( jQuery.isArray( response[ i ] ) ) {
261
- jQuery( '#gadwp-reports' + slug ).show();
262
- reports.drawPieChart( 'piechart-' + i, response[ i ], reports.i18n[ i ] );
263
- } else {
264
- reports.throwDebug( response[ i ] );
265
- }
266
- } else {
267
- jQuery( '#gadwp-reports' + slug ).show();
268
- reports.throwError( '#gadwp-piechart-' + i + slug, response[ i ], "80px" );
269
- }
270
- }
271
- } else {
272
- reports.throwDebug( response );
273
- }
274
- NProgress.done();
275
- },
276
-
277
- geoChartTableChart : function ( response ) {
278
- reports.geoChartTableChartData = response;
279
- if ( jQuery.isArray( response ) ) {
280
- if ( !jQuery.isNumeric( response[ 0 ] ) ) {
281
- if ( jQuery.isArray( response[ 0 ] ) ) {
282
- jQuery( '#gadwp-reports' + slug ).show();
283
- reports.drawGeoChart( response[ 0 ] );
284
- reports.drawTableChart( response[ 0 ] );
285
- } else {
286
- reports.throwDebug( response[ 0 ] );
287
- }
288
- } else {
289
- jQuery( '#gadwp-reports' + slug ).show();
290
- reports.throwError( '#gadwp-geochart' + slug, response[ 0 ], "125px" );
291
- reports.throwError( '#gadwp-tablechart' + slug, response[ 0 ], "125px" );
292
- }
293
- } else {
294
- reports.throwDebug( response );
295
- }
296
- NProgress.done();
297
- },
298
-
299
- orgChartTableChart : function ( response ) {
300
- reports.orgChartTableChartData = response
301
- if ( jQuery.isArray( response ) ) {
302
- if ( !jQuery.isNumeric( response[ 0 ] ) ) {
303
- if ( jQuery.isArray( response[ 0 ] ) ) {
304
- jQuery( '#gadwp-reports' + slug ).show();
305
- reports.drawOrgChart( response[ 0 ] );
306
- } else {
307
- reports.throwDebug( response[ 0 ] );
308
- }
309
- } else {
310
- jQuery( '#gadwp-reports' + slug ).show();
311
- reports.throwError( '#gadwp-orgchart' + slug, response[ 0 ], "125px" );
312
- }
313
-
314
- if ( !jQuery.isNumeric( response[ 1 ] ) ) {
315
- if ( jQuery.isArray( response[ 1 ] ) ) {
316
- reports.drawTableChart( response[ 1 ] );
317
- } else {
318
- reports.throwDebug( response[ 1 ] );
319
- }
320
- } else {
321
- reports.throwError( '#gadwp-tablechart' + slug, response[ 1 ], "125px" );
322
- }
323
- } else {
324
- reports.throwDebug( response );
325
- }
326
- NProgress.done();
327
- },
328
-
329
- tableChart : function ( response ) {
330
- reports.tableChartData = response
331
- if ( jQuery.isArray( response ) ) {
332
- if ( !jQuery.isNumeric( response[ 0 ] ) ) {
333
- if ( jQuery.isArray( response[ 0 ] ) ) {
334
- jQuery( '#gadwp-reports' + slug ).show();
335
- reports.drawTableChart( response[ 0 ] );
336
- } else {
337
- reports.throwDebug( response[ 0 ] );
338
- }
339
- } else {
340
- jQuery( '#gadwp-reports' + slug ).show();
341
- reports.throwError( '#gadwp-tablechart' + slug, response[ 0 ], "125px" );
342
- }
343
- } else {
344
- reports.throwDebug( response );
345
- }
346
- NProgress.done();
347
- },
348
-
349
- drawTableChart : function ( data ) {
350
- var chartData, options, chart;
351
-
352
- chartData = google.visualization.arrayToDataTable( data );
353
- options = {
354
- page : 'enable',
355
- pageSize : 10,
356
- width : '100%',
357
- allowHtml : true
358
- };
359
- chart = new google.visualization.Table( document.getElementById( 'gadwp-tablechart' + slug ) );
360
-
361
- chart.draw( chartData, options );
362
- },
363
-
364
- drawOrgChart : function ( data ) {
365
- var chartData, options, chart;
366
-
367
- chartData = google.visualization.arrayToDataTable( data );
368
- options = {
369
- allowCollapse : true,
370
- allowHtml : true,
371
- height : '100%'
372
- };
373
- chart = new google.visualization.OrgChart( document.getElementById( 'gadwp-orgchart' + slug ) );
374
-
375
- chart.draw( chartData, options );
376
- },
377
-
378
- drawPieChart : function ( id, data, title ) {
379
- var chartData, options, chart;
380
-
381
- chartData = google.visualization.arrayToDataTable( data );
382
- options = {
383
- is3D : false,
384
- tooltipText : 'percentage',
385
- legend : 'none',
386
- chartArea : {
387
- width : '99%',
388
- height : '80%'
389
- },
390
- title : title,
391
- pieSliceText : 'value',
392
- colors : gadwpItemData.colorVariations
393
- };
394
- chart = new google.visualization.PieChart( document.getElementById( 'gadwp-' + id + slug ) );
395
-
396
- chart.draw( chartData, options );
397
- },
398
-
399
- drawGeoChart : function ( data ) {
400
- var chartData, options, chart;
401
-
402
- chartData = google.visualization.arrayToDataTable( data );
403
- options = {
404
- chartArea : {
405
- width : '99%',
406
- height : '90%'
407
- },
408
- colors : [ gadwpItemData.colorVariations[ 5 ], gadwpItemData.colorVariations[ 4 ] ]
409
- }
410
- if ( gadwpItemData.region ) {
411
- options.region = gadwpItemData.region;
412
- options.displayMode = 'markers';
413
- options.datalessRegionColor = 'EFEFEF';
414
- }
415
- chart = new google.visualization.GeoChart( document.getElementById( 'gadwp-geochart' + slug ) );
416
-
417
- chart.draw( chartData, options );
418
- },
419
-
420
- drawAreaChart : function ( data, format ) {
421
- var chartData, options, chart, formatter;
422
-
423
- chartData = google.visualization.arrayToDataTable( data );
424
-
425
- if ( format ) {
426
- formatter = new google.visualization.NumberFormat( {
427
- suffix : '%',
428
- fractionDigits : 2
429
- } );
430
-
431
- formatter.format( chartData, 1 );
432
- }
433
-
434
- options = {
435
- legend : {
436
- position : 'none'
437
- },
438
- pointSize : 3,
439
- colors : [ gadwpItemData.colorVariations[ 0 ], gadwpItemData.colorVariations[ 4 ] ],
440
- chartArea : {
441
- width : '99%',
442
- height : '90%'
443
- },
444
- vAxis : {
445
- textPosition : "in",
446
- minValue : 0
447
- },
448
- hAxis : {
449
- textPosition : 'none'
450
- }
451
- };
452
- chart = new google.visualization.AreaChart( document.getElementById( 'gadwp-areachart' + slug ) );
453
-
454
- chart.draw( chartData, options );
455
- },
456
-
457
- drawBottomStats : function ( data ) {
458
- jQuery( "#gdsessions" + slug ).html( data[ 0 ] );
459
- jQuery( "#gdusers" + slug ).html( data[ 1 ] );
460
- jQuery( "#gdpageviews" + slug ).html( data[ 2 ] );
461
- jQuery( "#gdbouncerate" + slug ).html( data[ 3 ] + "%" );
462
- jQuery( "#gdorganicsearch" + slug ).html( data[ 4 ] );
463
- jQuery( "#gdpagespervisit" + slug ).html( data[ 5 ] );
464
- },
465
-
466
- rtOnlyUniqueValues : function ( value, index, self ) {
467
- return self.indexOf( value ) === index;
468
- },
469
-
470
- rtCountSessions : function ( rtData, searchValue ) {
471
- var count = 0, i = 0;
472
-
473
- for ( i = 0; i < rtData[ "rows" ].length; i++ ) {
474
- if ( jQuery.inArray( searchValue, rtData[ "rows" ][ i ] ) > -1 ) {
475
- count += parseInt( rtData[ "rows" ][ i ][ 6 ] );
476
- }
477
- }
478
- return count;
479
- },
480
-
481
- rtGenerateTooltip : function ( rtData ) {
482
- var count = 0, table = "", i = 0;
483
-
484
- for ( i = 0; i < rtData.length; i++ ) {
485
- count += parseInt( rtData[ i ].count );
486
- table += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ].value + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ].count + "</td></tr>";
487
- }
488
- ;
489
- if ( count ) {
490
- return ( "<table>" + table + "</table>" );
491
- } else {
492
- return ( "" );
493
- }
494
- },
495
-
496
- rtPageDetails : function ( rtData, searchValue ) {
497
- var sant, pageTitle, pgStatsTable, i = 0, j = 0, sum = 0, newsum = 0, countrfr = 0, countkwd = 0, countdrt = 0, countscl = 0, countcpg = 0, tablerfr = "", tablekwd = "", tablescl = "", tablecpg = "", tabledrt = "";
498
-
499
- rtData = rtData[ "rows" ];
500
-
501
- for ( i = 0; i < rtData.length; i++ ) {
502
-
503
- if ( rtData[ i ][ 0 ] == searchValue ) {
504
- pageTitle = rtData[ i ][ 5 ];
505
-
506
- switch ( rtData[ i ][ 3 ] ) {
507
-
508
- case "REFERRAL":
509
- countrfr += parseInt( rtData[ i ][ 6 ] );
510
- tablerfr += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ][ 1 ] + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ][ 6 ] + "</td></tr>";
511
- break;
512
- case "ORGANIC":
513
- countkwd += parseInt( rtData[ i ][ 6 ] );
514
- tablekwd += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ][ 2 ] + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ][ 6 ] + "</td></tr>";
515
- break;
516
- case "SOCIAL":
517
- countscl += parseInt( rtData[ i ][ 6 ] );
518
- tablescl += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ][ 1 ] + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ][ 6 ] + "</td></tr>";
519
- break;
520
- case "CUSTOM":
521
- countcpg += parseInt( rtData[ i ][ 6 ] );
522
- tablecpg += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ][ 1 ] + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ][ 6 ] + "</td></tr>";
523
- break;
524
- case "DIRECT":
525
- countdrt += parseInt( rtData[ i ][ 6 ] );
526
- break;
527
- }
528
- }
529
- }
530
-
531
- if ( countrfr ) {
532
- tablerfr = "<table><tr><td>" + reports.i18n[ 0 ] + "(" + countrfr + ")</td></tr>" + tablerfr + "</table><br />";
533
- }
534
- if ( countkwd ) {
535
- tablekwd = "<table><tr><td>" + reports.i18n[ 1 ] + "(" + countkwd + ")</td></tr>" + tablekwd + "</table><br />";
536
- }
537
- if ( countscl ) {
538
- tablescl = "<table><tr><td>" + reports.i18n[ 2 ] + "(" + countscl + ")</td></tr>" + tablescl + "</table><br />";
539
- }
540
- if ( countcpg ) {
541
- tablecpg = "<table><tr><td>" + reports.i18n[ 3 ] + "(" + countcpg + ")</td></tr>" + tablecpg + "</table><br />";
542
- }
543
- if ( countdrt ) {
544
- tabledrt = "<table><tr><td>" + reports.i18n[ 4 ] + "(" + countdrt + ")</td></tr></table><br />";
545
- }
546
- return ( "<p><center><strong>" + pageTitle + "</strong></center></p>" + tablerfr + tablekwd + tablescl + tablecpg + tabledrt );
547
- },
548
-
549
- rtRefresh : function () {
550
- if ( reports.render.focusFlag ) {
551
- postData.from = false;
552
- postData.to = false;
553
- postData.query = 'realtime';
554
- jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
555
- if ( jQuery.isArray( response ) ) {
556
- jQuery( '#gadwp-reports' + slug ).show();
557
- reports.realtime = response[ 0 ];
558
- reports.drawRealtime( reports.realtime );
559
- } else {
560
- reports.throwDebug( response );
561
- }
562
-
563
- NProgress.done();
564
-
565
- } );
566
- }
567
- },
568
-
569
- drawRealtime : function ( rtData ) {
570
- var rtInfoRight, uPagePath, uReferrals, uKeywords, uSocial, uCustom, i = 0, pagepath = [], referrals = [], keywords = [], social = [], visittype = [], custom = [], uPagePathStats = [], pgStatsTable = "", uReferrals = [], uKeywords = [], uSocial = [], uCustom = [], uVisitType = [ "REFERRAL", "ORGANIC", "SOCIAL", "CUSTOM" ], uVisitorType = [ "DIRECT", "NEW" ];
571
-
572
- jQuery( function () {
573
- jQuery( '#gadwp-widget *' ).tooltip( {
574
- tooltipClass : "gadwp"
575
- } );
576
- } );
577
-
578
- rtData = rtData[ 0 ];
579
-
580
- if ( jQuery.isNumeric( rtData ) || typeof rtData === "undefined" ) {
581
- rtData = [];
582
- rtData[ "totalsForAllResults" ] = []
583
- rtData[ "totalsForAllResults" ][ "rt:activeUsers" ] = "0";
584
- rtData[ "rows" ] = [];
585
- }
586
-
587
- if ( rtData[ "totalsForAllResults" ][ "rt:activeUsers" ] !== document.getElementById( "gadwp-online" ).innerHTML ) {
588
- jQuery( "#gadwp-online" ).fadeOut( "slow" );
589
- jQuery( "#gadwp-online" ).fadeOut( 500 );
590
- jQuery( "#gadwp-online" ).fadeOut( "slow", function () {
591
- if ( ( parseInt( rtData[ "totalsForAllResults" ][ "rt:activeUsers" ] ) ) < ( parseInt( document.getElementById( "gadwp-online" ).innerHTML ) ) ) {
592
- jQuery( "#gadwp-online" ).css( {
593
- 'background-color' : '#FFE8E8'
594
- } );
595
- } else {
596
- jQuery( "#gadwp-online" ).css( {
597
- 'background-color' : '#E0FFEC'
598
- } );
599
- }
600
- document.getElementById( "gadwp-online" ).innerHTML = rtData[ "totalsForAllResults" ][ "rt:activeUsers" ];
601
- } );
602
- jQuery( "#gadwp-online" ).fadeIn( "slow" );
603
- jQuery( "#gadwp-online" ).fadeIn( 500 );
604
- jQuery( "#gadwp-online" ).fadeIn( "slow", function () {
605
- jQuery( "#gadwp-online" ).css( {
606
- 'background-color' : '#FFFFFF'
607
- } );
608
- } );
609
- }
610
-
611
- if ( rtData[ "totalsForAllResults" ][ "rt:activeUsers" ] == 0 ) {
612
- rtData[ "rows" ] = [];
613
- }
614
-
615
- for ( i = 0; i < rtData[ "rows" ].length; i++ ) {
616
- pagepath.push( rtData[ "rows" ][ i ][ 0 ] );
617
- if ( rtData[ "rows" ][ i ][ 3 ] == "REFERRAL" ) {
618
- referrals.push( rtData[ "rows" ][ i ][ 1 ] );
619
- }
620
- if ( rtData[ "rows" ][ i ][ 3 ] == "ORGANIC" ) {
621
- keywords.push( rtData[ "rows" ][ i ][ 2 ] );
622
- }
623
- if ( rtData[ "rows" ][ i ][ 3 ] == "SOCIAL" ) {
624
- social.push( rtData[ "rows" ][ i ][ 1 ] );
625
- }
626
- if ( rtData[ "rows" ][ i ][ 3 ] == "CUSTOM" ) {
627
- custom.push( rtData[ "rows" ][ i ][ 1 ] );
628
- }
629
- visittype.push( rtData[ "rows" ][ i ][ 3 ] );
630
- }
631
-
632
- uPagePath = pagepath.filter( reports.rtOnlyUniqueValues );
633
- for ( i = 0; i < uPagePath.length; i++ ) {
634
- uPagePathStats[ i ] = {
635
- "pagepath" : uPagePath[ i ],
636
- "count" : reports.rtCountSessions( rtData, uPagePath[ i ] )
637
- }
638
- }
639
- uPagePathStats.sort( function ( a, b ) {
640
- return b.count - a.count
641
- } );
642
-
643
- pgStatsTable = "";
644
- for ( i = 0; i < uPagePathStats.length; i++ ) {
645
- if ( i < gadwpItemData.rtLimitPages ) {
646
- pgStatsTable += '<div class="gadwp-pline"><div class="gadwp-pleft"><a href="#" data-gadwp="' + reports.rtPageDetails( rtData, uPagePathStats[ i ].pagepath ) + '">' + uPagePathStats[ i ].pagepath.substring( 0, 70 ) + '</a></div><div class="gadwp-pright">' + uPagePathStats[ i ].count + '</div></div>';
647
- }
648
- }
649
- document.getElementById( "gadwp-pages" ).innerHTML = '<br /><div class="gadwp-pg">' + pgStatsTable + '</div>';
650
-
651
- uReferrals = referrals.filter( reports.rtOnlyUniqueValues );
652
- for ( i = 0; i < uReferrals.length; i++ ) {
653
- uReferrals[ i ] = {
654
- "value" : uReferrals[ i ],
655
- "count" : reports.rtCountSessions( rtData, uReferrals[ i ] )
656
- };
657
- }
658
- uReferrals.sort( function ( a, b ) {
659
- return b.count - a.count
660
- } );
661
-
662
- uKeywords = keywords.filter( reports.rtOnlyUniqueValues );
663
- for ( i = 0; i < uKeywords.length; i++ ) {
664
- uKeywords[ i ] = {
665
- "value" : uKeywords[ i ],
666
- "count" : reports.rtCountSessions( rtData, uKeywords[ i ] )
667
- };
668
- }
669
- uKeywords.sort( function ( a, b ) {
670
- return b.count - a.count
671
- } );
672
-
673
- uSocial = social.filter( reports.rtOnlyUniqueValues );
674
- for ( i = 0; i < uSocial.length; i++ ) {
675
- uSocial[ i ] = {
676
- "value" : uSocial[ i ],
677
- "count" : reports.rtCountSessions( rtData, uSocial[ i ] )
678
- };
679
- }
680
- uSocial.sort( function ( a, b ) {
681
- return b.count - a.count
682
- } );
683
-
684
- uCustom = custom.filter( reports.rtOnlyUniqueValues );
685
- for ( i = 0; i < uCustom.length; i++ ) {
686
- uCustom[ i ] = {
687
- "value" : uCustom[ i ],
688
- "count" : reports.rtCountSessions( rtData, uCustom[ i ] )
689
- };
690
- }
691
- uCustom.sort( function ( a, b ) {
692
- return b.count - a.count
693
- } );
694
-
695
- rtInfoRight = '<div class="gadwp-bigtext"><a href="#" data-gadwp="' + reports.rtGenerateTooltip( uReferrals ) + '"><div class="gadwp-bleft">' + reports.i18n[ 0 ] + '</a></div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitType[ 0 ] ) + '</div></div>';
696
- rtInfoRight += '<div class="gadwp-bigtext"><a href="#" data-gadwp="' + reports.rtGenerateTooltip( uKeywords ) + '"><div class="gadwp-bleft">' + reports.i18n[ 1 ] + '</a></div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitType[ 1 ] ) + '</div></div>';
697
- rtInfoRight += '<div class="gadwp-bigtext"><a href="#" data-gadwp="' + reports.rtGenerateTooltip( uSocial ) + '"><div class="gadwp-bleft">' + reports.i18n[ 2 ] + '</a></div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitType[ 2 ] ) + '</div></div>';
698
- rtInfoRight += '<div class="gadwp-bigtext"><a href="#" data-gadwp="' + reports.rtGenerateTooltip( uCustom ) + '"><div class="gadwp-bleft">' + reports.i18n[ 3 ] + '</a></div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitType[ 3 ] ) + '</div></div>';
699
-
700
- rtInfoRight += '<div class="gadwp-bigtext"><div class="gadwp-bleft">' + reports.i18n[ 4 ] + '</div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitorType[ 0 ] ) + '</div></div>';
701
- rtInfoRight += '<div class="gadwp-bigtext"><div class="gadwp-bleft">' + reports.i18n[ 5 ] + '</div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitorType[ 1 ] ) + '</div></div>';
702
-
703
- document.getElementById( "gadwp-tdo-right" ).innerHTML = rtInfoRight;
704
- },
705
-
706
- throwDebug : function ( response ) {
707
- jQuery( "#gadwp-status" + slug ).css( {
708
- "margin-top" : "3px",
709
- "padding-left" : "5px",
710
- "height" : "auto",
711
- "color" : "#000",
712
- "border-left" : "5px solid red"
713
- } );
714
- if ( response == '-24' ) {
715
- jQuery( "#gadwp-status" + slug ).html( gadwpItemData.i18n[ 15 ] );
716
- } else {
717
- jQuery( "#gadwp-reports" + slug ).css( {
718
- "background-color" : "#F7F7F7",
719
- "height" : "auto",
720
- "margin-top" : "10px",
721
- "padding-top" : "50px",
722
- "padding-bottom" : "50px",
723
- "color" : "#000",
724
- "text-align" : "center"
725
- } );
726
- jQuery( "#gadwp-reports" + slug ).html ( response );
727
- jQuery( "#gadwp-reports" + slug ).show();
728
- jQuery( "#gadwp-status" + slug ).html( gadwpItemData.i18n[ 11 ] );
729
- console.log( "\n********************* GADWP Log ********************* \n\n" + response );
730
- postData = {
731
- action : 'gadwp_set_error',
732
- response : response,
733
- gadwp_security_set_error : gadwpItemData.security,
734
- }
735
- jQuery.post( gadwpItemData.ajaxurl, postData );
736
- }
737
- },
738
-
739
- throwError : function ( target, response, p ) {
740
- jQuery( target ).css( {
741
- "background-color" : "#F7F7F7",
742
- "height" : "auto",
743
- "padding-top" : p,
744
- "padding-bottom" : p,
745
- "color" : "#000",
746
- "text-align" : "center"
747
- } );
748
- if ( response == -21 ) {
749
- jQuery( target ).html( gadwpItemData.i18n[ 12 ] + ' (' + response + ')' );
750
- } else {
751
- jQuery( target ).html( gadwpItemData.i18n[ 13 ] + ' (' + response + ')' );
752
- }
753
- },
754
-
755
- render : function ( view, period, query ) {
756
- var projectId, from, to, tpl, focusFlag;
757
-
758
- if ( period == 'realtime' ) {
759
- jQuery( '#gadwp-sel-report' + slug ).hide();
760
- } else {
761
- jQuery( '#gadwp-sel-report' + slug ).show();
762
- clearInterval( reports.rtRuns );
763
- }
764
-
765
- jQuery( '#gadwp-status' + slug ).html( '' );
766
- switch ( period ) {
767
- case 'today':
768
- from = 'today';
769
- to = 'today';
770
- break;
771
- case 'yesterday':
772
- from = 'yesterday';
773
- to = 'yesterday';
774
- break;
775
- case '7daysAgo':
776
- from = '7daysAgo';
777
- to = 'yesterday';
778
- break;
779
- case '14daysAgo':
780
- from = '14daysAgo';
781
- to = 'yesterday';
782
- break;
783
- case '90daysAgo':
784
- from = '90daysAgo';
785
- to = 'yesterday';
786
- break;
787
- case '365daysAgo':
788
- from = '365daysAgo';
789
- to = 'yesterday';
790
- break;
791
- case '1095daysAgo':
792
- from = '1095daysAgo';
793
- to = 'yesterday';
794
- break;
795
- default:
796
- from = '30daysAgo';
797
- to = 'yesterday';
798
- break;
799
- }
800
-
801
- tools.setCookie( 'default_metric', query );
802
- tools.setCookie( 'default_dimension', period );
803
-
804
- if ( typeof view !== 'undefined' ) {
805
- tools.setCookie( 'default_view', view );
806
- projectId = view;
807
- } else {
808
- projectId = false;
809
- }
810
-
811
- if ( gadwpItemData.scope == 'admin-item' ) {
812
- postData = {
813
- action : 'gadwp_backend_item_reports',
814
- gadwp_security_backend_item_reports : gadwpItemData.security,
815
- from : from,
816
- to : to,
817
- filter : itemId
818
- }
819
- } else if ( gadwpItemData.scope == 'front-item' ) {
820
- postData = {
821
- action : 'gadwp_frontend_item_reports',
822
- gadwp_security_frontend_item_reports : gadwpItemData.security,
823
- from : from,
824
- to : to,
825
- filter : gadwpItemData.filter
826
- }
827
- } else {
828
- postData = {
829
- action : 'gadwp_backend_item_reports',
830
- gadwp_security_backend_item_reports : gadwpItemData.security,
831
- projectId : projectId,
832
- from : from,
833
- to : to
834
- }
835
- }
836
- if ( period == 'realtime' ) {
837
-
838
- reports.i18n = gadwpItemData.i18n.slice( 20, 26 );
839
-
840
- reports.render.focusFlag = 1;
841
-
842
- jQuery( window ).bind( "focus", function ( event ) {
843
- reports.render.focusFlag = 1;
844
- } ).bind( "blur", function ( event ) {
845
- reports.render.focusFlag = 0;
846
- } );
847
-
848
- tpl = '<div id="gadwp-realtime' + slug + '">';
849
- tpl += '<div class="gadwp-rt-box">';
850
- tpl += '<div class="gadwp-tdo-left">';
851
- tpl += '<div class="gadwp-online" id="gadwp-online">0</div>';
852
- tpl += '</div>';
853
- tpl += '<div class="gadwp-tdo-right" id="gadwp-tdo-right">';
854
- tpl += '<div class="gadwp-bigtext">';
855
- tpl += '<div class="gadwp-bleft">' + reports.i18n[ 0 ] + '</div>';
856
- tpl += '<div class="gadwp-bright">0</div>';
857
- tpl += '</div>';
858
- tpl += '<div class="gadwp-bigtext">';
859
- tpl += '<div class="gadwp-bleft">' + reports.i18n[ 1 ] + '</div>';
860
- tpl += '<div class="gadwp-bright">0</div>';
861
- tpl += '</div>';
862
- tpl += '<div class="gadwp-bigtext">';
863
- tpl += '<div class="gadwp-bleft">' + reports.i18n[ 2 ] + '</div>';
864
- tpl += '<div class="gadwp-bright">0</div>';
865
- tpl += '</div>';
866
- tpl += '<div class="gadwp-bigtext">';
867
- tpl += '<div class="gadwp-bleft">' + reports.i18n[ 3 ] + '</div>';
868
- tpl += '<div class="gadwp-bright">0</div>';
869
- tpl += '</div>';
870
- tpl += '<div class="gadwp-bigtext">';
871
- tpl += '<div class="gadwp-bleft">' + reports.i18n[ 4 ] + '</div>';
872
- tpl += '<div class="gadwp-bright">0</div>';
873
- tpl += '</div>';
874
- tpl += '<div class="gadwp-bigtext">';
875
- tpl += '<div class="gadwp-bleft">' + reports.i18n[ 5 ] + '</div>';
876
- tpl += '<div class="gadwp-bright">0</div>';
877
- tpl += '</div>';
878
- tpl += '</div>';
879
- tpl += '</div>';
880
- tpl += '<div>';
881
- tpl += '<div id="gadwp-pages" class="gadwp-pages">&nbsp;</div>';
882
- tpl += '</div>';
883
- tpl += '</div>';
884
-
885
- jQuery( '#gadwp-reports' + slug ).html( tpl );
886
-
887
- reports.rtRefresh( reports.render.focusFlag );
888
-
889
- reports.rtRuns = setInterval( reports.rtRefresh, 55000 );
890
-
891
- } else {
892
- if ( jQuery.inArray( query, [ 'referrers', 'contentpages', 'searches' ] ) > -1 ) {
893
-
894
- tpl = '<div id="gadwp-orgcharttablechart' + slug + '">';
895
- tpl += '<div id="gadwp-orgchart' + slug + '"></div>';
896
- tpl += '<div id="gadwp-tablechart' + slug + '"></div>';
897
- tpl += '</div>';
898
-
899
- jQuery( '#gadwp-reports' + slug ).html( tpl );
900
- jQuery( '#gadwp-reports' + slug ).hide();
901
-
902
- postData.query = 'channelGrouping,' + query;
903
-
904
- jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
905
- reports.orgChartTableChart( response );
906
- } );
907
- } else if ( query == '404errors' ) {
908
- tpl = '<div id="gadwp-404tablechart' + slug + '">';
909
- tpl += '<div id="gadwp-tablechart' + slug + '"></div>';
910
- tpl += '</div>';
911
-
912
- jQuery( '#gadwp-reports' + slug ).html( tpl );
913
- jQuery( '#gadwp-reports' + slug ).hide();
914
-
915
- postData.query = query;
916
-
917
- jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
918
- reports.tableChart( response );
919
- } );
920
- } else if ( query == 'trafficdetails' || query == 'technologydetails' ) {
921
-
922
- tpl = '<div id="gadwp-orgchartpiecharts' + slug + '">';
923
- tpl += '<div id="gadwp-orgchart' + slug + '"></div>';
924
- tpl += '<div class="gadwp-floatwraper">';
925
- tpl += '<div id="gadwp-piechart-1' + slug + '" class="halfsize floatleft"></div>';
926
- tpl += '<div id="gadwp-piechart-2' + slug + '" class="halfsize floatright"></div>';
927
- tpl += '</div>';
928
- tpl += '<div class="gadwp-floatwraper">';
929
- tpl += '<div id="gadwp-piechart-3' + slug + '" class="halfsize floatleft"></div>';
930
- tpl += '<div id="gadwp-piechart-4' + slug + '" class="halfsize floatright"></div>';
931
- tpl += '</div>';
932
- tpl += '</div>';
933
-
934
- jQuery( '#gadwp-reports' + slug ).html( tpl );
935
- jQuery( '#gadwp-reports' + slug ).hide();
936
- if ( query == 'trafficdetails' ) {
937
- postData.query = 'channelGrouping,medium,visitorType,source,socialNetwork';
938
- reports.i18n = gadwpItemData.i18n.slice( 0, 5 );
939
- } else {
940
- reports.i18n = gadwpItemData.i18n.slice( 15, 20 );
941
- postData.query = 'deviceCategory,browser,operatingSystem,screenResolution,mobileDeviceBranding';
942
- }
943
-
944
- jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
945
- reports.orgChartPieCharts( response )
946
- } );
947
-
948
- } else if ( query == 'locations' ) {
949
-
950
- tpl = '<div id="gadwp-geocharttablechart' + slug + '">';
951
- tpl += '<div id="gadwp-geochart' + slug + '"></div>';
952
- tpl += '<div id="gadwp-tablechart' + slug + '"></div>';
953
- tpl += '</div>';
954
-
955
- jQuery( '#gadwp-reports' + slug ).html( tpl );
956
- jQuery( '#gadwp-reports' + slug ).hide();
957
-
958
- postData.query = query;
959
-
960
- jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
961
- reports.geoChartTableChart( response );
962
- } );
963
-
964
- } else {
965
-
966
- tpl = '<div id="gadwp-areachartbottomstats' + slug + '">';
967
- tpl += '<div id="gadwp-areachart' + slug + '"></div>';
968
- tpl += '<div id="gadwp-bottomstats' + slug + '">';
969
- tpl += '<div class="inside">';
970
- tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 5 ] + '</h3><p id="gdsessions' + slug + '">&nbsp;</p></div>';
971
- tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 6 ] + '</h3><p id="gdusers' + slug + '">&nbsp;</p></div>';
972
- tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 7 ] + '</h3><p id="gdpageviews' + slug + '">&nbsp;</p></div>';
973
- tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 8 ] + '</h3><p id="gdbouncerate' + slug + '">&nbsp;</p></div>';
974
- tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 9 ] + '</h3><p id="gdorganicsearch' + slug + '">&nbsp;</p></div>';
975
- tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 10 ] + '</h3><p id="gdpagespervisit' + slug + '">&nbsp;</p></div>';
976
- tpl += '</div>';
977
- tpl += '</div>';
978
- tpl += '</div>';
979
-
980
- jQuery( '#gadwp-reports' + slug ).html( tpl );
981
- jQuery( '#gadwp-reports' + slug ).hide();
982
-
983
- postData.query = query + ',bottomstats';
984
-
985
- jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
986
- reports.areaChartBottomStats( response );
987
- } );
988
-
989
- }
990
-
991
- }
992
-
993
- },
994
-
995
- refresh : function () {
996
- if ( jQuery( '#gadwp-areachartbottomstats' + slug ).length > 0 && jQuery.isArray( reports.areaChartBottomStatsData ) ) {
997
- reports.areaChartBottomStats( reports.areaChartBottomStatsData );
998
- }
999
- if ( jQuery( '#gadwp-orgchartpiecharts' + slug ).length > 0 && jQuery.isArray( reports.orgChartPieChartsData ) ) {
1000
- reports.orgChartPieCharts( reports.orgChartPieChartsData );
1001
- }
1002
- if ( jQuery( '#gadwp-geocharttablechart' + slug ).length > 0 && jQuery.isArray( reports.geoChartTableChartData ) ) {
1003
- reports.geoChartTableChart( reports.geoChartTableChartData );
1004
- }
1005
- if ( jQuery( '#gadwp-orgcharttablechart' + slug ).length > 0 && jQuery.isArray( reports.orgChartTableChartData ) ) {
1006
- reports.orgChartTableChart( reports.orgChartTableChartData );
1007
- }
1008
- if ( jQuery( '#gadwp-404tablechart' + slug ).length > 0 && jQuery.isArray( reports.tableChartData ) ) {
1009
- reports.tableChart( reports.tableChartData );
1010
- }
1011
- },
1012
-
1013
- init : function () {
1014
-
1015
- if ( !jQuery( "#gadwp-reports" + slug ).length ) {
1016
- return;
1017
- }
1018
-
1019
- if ( jQuery( "#gadwp-reports" + slug ).html().length ) { // only when report is empty
1020
- return;
1021
- }
1022
-
1023
- try {
1024
- NProgress.configure( {
1025
- parent : "#gadwp-progressbar" + slug,
1026
- showSpinner : false
1027
- } );
1028
- NProgress.start();
1029
- } catch ( e ) {
1030
- reports.alertMessage( gadwpItemData.i18n[ 0 ] );
1031
- }
1032
-
1033
- reports.render( jQuery( '#gadwp-sel-view' + slug ).val(), jQuery( '#gadwp-sel-period' + slug ).val(), jQuery( '#gadwp-sel-report' + slug ).val() );
1034
-
1035
- jQuery( window ).resize( function () {
1036
- var diff = jQuery(window).width() - reports.oldViewPort;
1037
- if ( ( diff < -5 ) || ( diff > 5 ) ) {
1038
- reports.oldViewPort = jQuery(window).width();
1039
- reports.refresh(); //refresh only on over 5px viewport width changes
1040
- }
1041
- } );
1042
- }
1043
- }
1044
-
1045
- template.init();
1046
-
1047
- reports.init();
1048
-
1049
- jQuery( '#gadwp-sel-view' + slug ).change( function () {
1050
- jQuery( '#gadwp-reports' + slug ).html( '' );
1051
- reports.init();
1052
- } );
1053
-
1054
- jQuery( '#gadwp-sel-period' + slug ).change( function () {
1055
- jQuery( '#gadwp-reports' + slug ).html( '' );
1056
- reports.init();
1057
- } );
1058
-
1059
- jQuery( '#gadwp-sel-report' + slug ).change( function () {
1060
- jQuery( '#gadwp-reports' + slug ).html( '' );
1061
- reports.init();
1062
- } );
1063
-
1064
- if ( gadwpItemData.scope == 'admin-widgets' ) {
1065
- return;
1066
- } else {
1067
- return this.dialog( {
1068
- width : 'auto',
1069
- maxWidth : 510,
1070
- height : 'auto',
1071
- modal : true,
1072
- fluid : true,
1073
- dialogClass : 'gadwp wp-dialog',
1074
- resizable : false,
1075
- title : reports.getTitle( gadwpItemData.scope ),
1076
- position : {
1077
- my : "top",
1078
- at : "top+100",
1079
- of : window
1080
- }
1081
- } );
1082
- }
1083
- }
1084
- } );
1085
-
1086
- function GADWPReportLoad () {
1087
- if ( gadwpItemData.scope == 'admin-widgets' ) {
1088
- jQuery( '#gadwp-window-1' ).gadwpItemReport( 1 );
1089
- } else {
1090
- jQuery( gadwpItemData.getSelector( gadwpItemData.scope ) ).click( function () {
1091
- if ( !jQuery( "#gadwp-window-" + gadwpItemData.getID( this ) ).length > 0 ) {
1092
- jQuery( "body" ).append( '<div id="gadwp-window-' + gadwpItemData.getID( this ) + '"></div>' );
1093
- }
1094
- jQuery( '#gadwp-window-' + gadwpItemData.getID( this ) ).gadwpItemReport( gadwpItemData.getID( this ) );
1095
- } );
1096
- }
1097
-
1098
- // on window resize
1099
- jQuery( window ).resize( function () {
1100
- gadwpItemData.responsiveDialog();
1101
- } );
1102
-
1103
- // dialog width larger than viewport
1104
- jQuery( document ).on( "dialogopen", ".ui-dialog", function ( event, ui ) {
1105
- gadwpItemData.responsiveDialog();
1106
- } );
1107
- }
1
+ /*-
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+
9
+ "use strict";
10
+
11
+ google.charts.load('current', {mapsApiKey: gadwpItemData.mapsApiKey, 'packages':['corechart', 'table', 'orgchart', 'geochart']});
12
+ google.charts.setOnLoadCallback( GADWPReportLoad );
13
+
14
+ // Get the numeric ID
15
+ gadwpItemData.getID = function ( item ) {
16
+ if ( gadwpItemData.scope == 'admin-item' ) {
17
+ if ( typeof item.id == "undefined" ) {
18
+ return 0
19
+ }
20
+ if ( item.id.split( '-' )[ 1 ] == "undefined" ) {
21
+ return 0;
22
+ } else {
23
+ return item.id.split( '-' )[ 1 ];
24
+ }
25
+ } else {
26
+ if ( typeof item.id == "undefined" ) {
27
+ return 1;
28
+ }
29
+ if ( item.id.split( '-' )[ 4 ] == "undefined" ) {
30
+ return 1;
31
+ } else {
32
+ return item.id.split( '-' )[ 4 ];
33
+ }
34
+ }
35
+ }
36
+
37
+ // Get the selector
38
+ gadwpItemData.getSelector = function ( scope ) {
39
+ if ( scope == 'admin-item' ) {
40
+ return 'a[id^="gadwp-"]';
41
+ } else {
42
+ return 'li[id^="wp-admin-bar-gadwp"]';
43
+ }
44
+ }
45
+
46
+ gadwpItemData.responsiveDialog = function () {
47
+ var dialog, wWidth, visible;
48
+
49
+ visible = jQuery( ".ui-dialog:visible" );
50
+
51
+ // on each visible dialog
52
+ visible.each( function () {
53
+ dialog = jQuery( this ).find( ".ui-dialog-content" ).data( "ui-dialog" );
54
+ // on each fluid dialog
55
+ if ( dialog.options.fluid ) {
56
+ wWidth = jQuery( window ).width();
57
+ // window width vs dialog width
58
+ if ( wWidth < ( parseInt( dialog.options.maxWidth ) + 50 ) ) {
59
+ // don't fill the entire screen
60
+ jQuery( this ).css( "max-width", "90%" );
61
+ } else {
62
+ // maxWidth bug fix
63
+ jQuery( this ).css( "max-width", dialog.options.maxWidth + "px" );
64
+ }
65
+ // change dialog position
66
+ dialog.option( "position", dialog.options.position );
67
+ }
68
+ } );
69
+ }
70
+
71
+ jQuery.fn.extend( {
72
+ gadwpItemReport : function ( itemId ) {
73
+ var postData, tools, template, reports, refresh, init, slug = "-" + itemId;
74
+
75
+ tools = {
76
+ setCookie : function ( name, value ) {
77
+ var expires, dateItem = new Date();
78
+
79
+ if ( gadwpItemData.scope == 'admin-widgets' ) {
80
+ name = "gadwp_wg_" + name;
81
+ } else {
82
+ name = "gadwp_ir_" + name;
83
+ }
84
+ dateItem.setTime( dateItem.getTime() + ( 24 * 60 * 60 * 1000 * 7 ) );
85
+ expires = "expires=" + dateItem.toUTCString();
86
+ document.cookie = name + "=" + value + "; " + expires + "; path=/";
87
+ },
88
+ getCookie : function ( name ) {
89
+ var cookie, cookiesArray, div, i = 0;
90
+
91
+ if ( gadwpItemData.scope == 'admin-widgets' ) {
92
+ name = "gadwp_wg_" + name + "=";
93
+ } else {
94
+ name = "gadwp_ir_" + name + "=";
95
+ }
96
+ cookiesArray = document.cookie.split( ';' );
97
+ for ( i = 0; i < cookiesArray.length; i++ ) {
98
+ cookie = cookiesArray[ i ];
99
+ while ( cookie.charAt( 0 ) == ' ' )
100
+ cookie = cookie.substring( 1 );
101
+ if ( cookie.indexOf( name ) == 0 )
102
+ return cookie.substring( name.length, cookie.length );
103
+ }
104
+ return false;
105
+ },
106
+ escape : function ( str ) {
107
+ div = document.createElement( 'div' );
108
+ div.appendChild( document.createTextNode( str ) );
109
+ return div.innerHTML;
110
+ }
111
+ }
112
+
113
+ template = {
114
+
115
+ addOptions : function ( id, list ) {
116
+ var defaultMetric, defaultDimension, defaultView, output = [];
117
+
118
+ if ( list == false ) {
119
+ return;
120
+ }
121
+
122
+ if ( !tools.getCookie( 'default_metric' ) || !tools.getCookie( 'default_dimension' ) ) {
123
+ defaultMetric = 'sessions';
124
+ defaultDimension = '30daysAgo';
125
+ } else {
126
+ defaultMetric = tools.getCookie( 'default_metric' );
127
+ defaultDimension = tools.getCookie( 'default_dimension' );
128
+ defaultView = tools.getCookie( 'default_view' );
129
+ }
130
+
131
+ jQuery.each( list, function ( key, value ) {
132
+ if ( key == defaultMetric || key == defaultDimension || key == defaultView ) {
133
+ output.push( '<option value="' + key + '" selected="selected">' + value + '</option>' );
134
+ } else {
135
+ output.push( '<option value="' + key + '">' + value + '</option>' );
136
+ }
137
+ } );
138
+ jQuery( id ).html( output.join( '' ) );
139
+ },
140
+
141
+ init : function () {
142
+ var tpl;
143
+
144
+ if ( !jQuery( '#gadwp-window' + slug ).length ) {
145
+ return;
146
+ }
147
+
148
+ if ( jQuery( '#gadwp-window' + slug ).html().length ) { // add main template once
149
+ return;
150
+ }
151
+
152
+ tpl = '<div id="gadwp-container' + slug + '">';
153
+ if ( gadwpItemData.viewList != false ) {
154
+ tpl += '<select id="gadwp-sel-view' + slug + '"></select>';
155
+ }
156
+ tpl += '<select id="gadwp-sel-period' + slug + '"></select> ';
157
+ tpl += '<select id="gadwp-sel-report' + slug + '"></select>';
158
+ tpl += '<div id="gadwp-progressbar' + slug + '"></div>';
159
+ tpl += '<div id="gadwp-status' + slug + '"></div>';
160
+ tpl += '<div id="gadwp-reports' + slug + '"></div>';
161
+ tpl += '<div style="text-align:right;width:100%;font-size:0.8em;clear:both;margin-right:5px;margin-top:10px;">';
162
+ tpl += gadwpItemData.i18n[ 14 ];
163
+ tpl += ' <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_report&utm_medium=link&utm_content=back_report&utm_campaign=gadwp" rel="nofollow" style="text-decoration:none;font-size:1em;">GADWP</a>&nbsp;';
164
+ tpl += '</div>';
165
+ tpl += '</div>',
166
+
167
+ jQuery( '#gadwp-window' + slug ).append( tpl );
168
+
169
+ template.addOptions( '#gadwp-sel-view' + slug, gadwpItemData.viewList );
170
+ template.addOptions( '#gadwp-sel-period' + slug, gadwpItemData.dateList );
171
+ template.addOptions( '#gadwp-sel-report' + slug, gadwpItemData.reportList );
172
+
173
+ }
174
+ }
175
+
176
+ reports = {
177
+ oldViewPort: 0,
178
+ orgChartTableChartData : '',
179
+ tableChartData : '',
180
+ orgChartPieChartsData : '',
181
+ geoChartTableChartData : '',
182
+ areaChartBottomStatsData : '',
183
+ realtime : '',
184
+ rtRuns : null,
185
+ i18n : null,
186
+
187
+ getTitle : function ( scope ) {
188
+ if ( scope == 'admin-item' ) {
189
+ return jQuery( '#gadwp' + slug ).attr( "title" );
190
+ } else {
191
+ return document.getElementsByTagName( "title" )[ 0 ].innerHTML;
192
+ }
193
+ },
194
+
195
+ alertMessage : function ( msg ) {
196
+ jQuery( "#gadwp-status" + slug ).css( {
197
+ "margin-top" : "3px",
198
+ "padding-left" : "5px",
199
+ "height" : "auto",
200
+ "color" : "#000",
201
+ "border-left" : "5px solid red"
202
+ } );
203
+ jQuery( "#gadwp-status" + slug ).html( msg );
204
+ },
205
+
206
+ areaChartBottomStats : function ( response ) {
207
+ reports.areaChartBottomStatsData = response;
208
+ if ( jQuery.isArray( response ) ) {
209
+ if ( !jQuery.isNumeric( response[ 0 ] ) ) {
210
+ if ( jQuery.isArray( response[ 0 ] ) ) {
211
+ jQuery( '#gadwp-reports' + slug ).show();
212
+ if ( postData.query == 'visitBounceRate,bottomstats' ) {
213
+ reports.drawAreaChart( response[ 0 ], true );
214
+ } else {
215
+ reports.drawAreaChart( response[ 0 ], false );
216
+ }
217
+ } else {
218
+ reports.throwDebug( response[ 0 ] );
219
+ }
220
+ } else {
221
+ jQuery( '#gadwp-reports' + slug ).show();
222
+ reports.throwError( '#gadwp-areachart' + slug, response[ 0 ], "125px" );
223
+ }
224
+ if ( !jQuery.isNumeric( response[ 1 ] ) ) {
225
+ if ( jQuery.isArray( response[ 1 ] ) ) {
226
+ jQuery( '#gadwp-reports' + slug ).show();
227
+ reports.drawBottomStats( response[ 1 ] );
228
+ } else {
229
+ reports.throwDebug( response[ 1 ] );
230
+ }
231
+ } else {
232
+ jQuery( '#gadwp-reports' + slug ).show();
233
+ reports.throwError( '#gadwp-bottomstats' + slug, response[ 1 ], "40px" );
234
+ }
235
+ } else {
236
+ reports.throwDebug( response );
237
+ }
238
+ NProgress.done();
239
+
240
+ },
241
+
242
+ orgChartPieCharts : function ( response ) {
243
+ var i = 0;
244
+ reports.orgChartPieChartsData = response;
245
+ if ( jQuery.isArray( response ) ) {
246
+ if ( !jQuery.isNumeric( response[ 0 ] ) ) {
247
+ if ( jQuery.isArray( response[ 0 ] ) ) {
248
+ jQuery( '#gadwp-reports' + slug ).show();
249
+ reports.drawOrgChart( response[ 0 ] );
250
+ } else {
251
+ reports.throwDebug( response[ 0 ] );
252
+ }
253
+ } else {
254
+ jQuery( '#gadwp-reports' + slug ).show();
255
+ reports.throwError( '#gadwp-orgchart' + slug, response[ 0 ], "125px" );
256
+ }
257
+
258
+ for ( i = 1; i < response.length; i++ ) {
259
+ if ( !jQuery.isNumeric( response[ i ] ) ) {
260
+ if ( jQuery.isArray( response[ i ] ) ) {
261
+ jQuery( '#gadwp-reports' + slug ).show();
262
+ reports.drawPieChart( 'piechart-' + i, response[ i ], reports.i18n[ i ] );
263
+ } else {
264
+ reports.throwDebug( response[ i ] );
265
+ }
266
+ } else {
267
+ jQuery( '#gadwp-reports' + slug ).show();
268
+ reports.throwError( '#gadwp-piechart-' + i + slug, response[ i ], "80px" );
269
+ }
270
+ }
271
+ } else {
272
+ reports.throwDebug( response );
273
+ }
274
+ NProgress.done();
275
+ },
276
+
277
+ geoChartTableChart : function ( response ) {
278
+ reports.geoChartTableChartData = response;
279
+ if ( jQuery.isArray( response ) ) {
280
+ if ( !jQuery.isNumeric( response[ 0 ] ) ) {
281
+ if ( jQuery.isArray( response[ 0 ] ) ) {
282
+ jQuery( '#gadwp-reports' + slug ).show();
283
+ reports.drawGeoChart( response[ 0 ] );
284
+ reports.drawTableChart( response[ 0 ] );
285
+ } else {
286
+ reports.throwDebug( response[ 0 ] );
287
+ }
288
+ } else {
289
+ jQuery( '#gadwp-reports' + slug ).show();
290
+ reports.throwError( '#gadwp-geochart' + slug, response[ 0 ], "125px" );
291
+ reports.throwError( '#gadwp-tablechart' + slug, response[ 0 ], "125px" );
292
+ }
293
+ } else {
294
+ reports.throwDebug( response );
295
+ }
296
+ NProgress.done();
297
+ },
298
+
299
+ orgChartTableChart : function ( response ) {
300
+ reports.orgChartTableChartData = response
301
+ if ( jQuery.isArray( response ) ) {
302
+ if ( !jQuery.isNumeric( response[ 0 ] ) ) {
303
+ if ( jQuery.isArray( response[ 0 ] ) ) {
304
+ jQuery( '#gadwp-reports' + slug ).show();
305
+ reports.drawOrgChart( response[ 0 ] );
306
+ } else {
307
+ reports.throwDebug( response[ 0 ] );
308
+ }
309
+ } else {
310
+ jQuery( '#gadwp-reports' + slug ).show();
311
+ reports.throwError( '#gadwp-orgchart' + slug, response[ 0 ], "125px" );
312
+ }
313
+
314
+ if ( !jQuery.isNumeric( response[ 1 ] ) ) {
315
+ if ( jQuery.isArray( response[ 1 ] ) ) {
316
+ reports.drawTableChart( response[ 1 ] );
317
+ } else {
318
+ reports.throwDebug( response[ 1 ] );
319
+ }
320
+ } else {
321
+ reports.throwError( '#gadwp-tablechart' + slug, response[ 1 ], "125px" );
322
+ }
323
+ } else {
324
+ reports.throwDebug( response );
325
+ }
326
+ NProgress.done();
327
+ },
328
+
329
+ tableChart : function ( response ) {
330
+ reports.tableChartData = response
331
+ if ( jQuery.isArray( response ) ) {
332
+ if ( !jQuery.isNumeric( response[ 0 ] ) ) {
333
+ if ( jQuery.isArray( response[ 0 ] ) ) {
334
+ jQuery( '#gadwp-reports' + slug ).show();
335
+ reports.drawTableChart( response[ 0 ] );
336
+ } else {
337
+ reports.throwDebug( response[ 0 ] );
338
+ }
339
+ } else {
340
+ jQuery( '#gadwp-reports' + slug ).show();
341
+ reports.throwError( '#gadwp-tablechart' + slug, response[ 0 ], "125px" );
342
+ }
343
+ } else {
344
+ reports.throwDebug( response );
345
+ }
346
+ NProgress.done();
347
+ },
348
+
349
+ drawTableChart : function ( data ) {
350
+ var chartData, options, chart;
351
+
352
+ chartData = google.visualization.arrayToDataTable( data );
353
+ options = {
354
+ page : 'enable',
355
+ pageSize : 10,
356
+ width : '100%',
357
+ allowHtml : true
358
+ };
359
+ chart = new google.visualization.Table( document.getElementById( 'gadwp-tablechart' + slug ) );
360
+
361
+ chart.draw( chartData, options );
362
+ },
363
+
364
+ drawOrgChart : function ( data ) {
365
+ var chartData, options, chart;
366
+
367
+ chartData = google.visualization.arrayToDataTable( data );
368
+ options = {
369
+ allowCollapse : true,
370
+ allowHtml : true,
371
+ height : '100%'
372
+ };
373
+ chart = new google.visualization.OrgChart( document.getElementById( 'gadwp-orgchart' + slug ) );
374
+
375
+ chart.draw( chartData, options );
376
+ },
377
+
378
+ drawPieChart : function ( id, data, title ) {
379
+ var chartData, options, chart;
380
+
381
+ chartData = google.visualization.arrayToDataTable( data );
382
+ options = {
383
+ is3D : false,
384
+ tooltipText : 'percentage',
385
+ legend : 'none',
386
+ chartArea : {
387
+ width : '99%',
388
+ height : '80%'
389
+ },
390
+ title : title,
391
+ pieSliceText : 'value',
392
+ colors : gadwpItemData.colorVariations
393
+ };
394
+ chart = new google.visualization.PieChart( document.getElementById( 'gadwp-' + id + slug ) );
395
+
396
+ chart.draw( chartData, options );
397
+ },
398
+
399
+ drawGeoChart : function ( data ) {
400
+ var chartData, options, chart;
401
+
402
+ chartData = google.visualization.arrayToDataTable( data );
403
+ options = {
404
+ chartArea : {
405
+ width : '99%',
406
+ height : '90%'
407
+ },
408
+ colors : [ gadwpItemData.colorVariations[ 5 ], gadwpItemData.colorVariations[ 4 ] ]
409
+ }
410
+ if ( gadwpItemData.region ) {
411
+ options.region = gadwpItemData.region;
412
+ options.displayMode = 'markers';
413
+ options.datalessRegionColor = 'EFEFEF';
414
+ }
415
+ chart = new google.visualization.GeoChart( document.getElementById( 'gadwp-geochart' + slug ) );
416
+
417
+ chart.draw( chartData, options );
418
+ },
419
+
420
+ drawAreaChart : function ( data, format ) {
421
+ var chartData, options, chart, formatter;
422
+
423
+ chartData = google.visualization.arrayToDataTable( data );
424
+
425
+ if ( format ) {
426
+ formatter = new google.visualization.NumberFormat( {
427
+ suffix : '%',
428
+ fractionDigits : 2
429
+ } );
430
+
431
+ formatter.format( chartData, 1 );
432
+ }
433
+
434
+ options = {
435
+ legend : {
436
+ position : 'none'
437
+ },
438
+ pointSize : 3,
439
+ colors : [ gadwpItemData.colorVariations[ 0 ], gadwpItemData.colorVariations[ 4 ] ],
440
+ chartArea : {
441
+ width : '99%',
442
+ height : '90%'
443
+ },
444
+ vAxis : {
445
+ textPosition : "in",
446
+ minValue : 0
447
+ },
448
+ hAxis : {
449
+ textPosition : 'none'
450
+ }
451
+ };
452
+ chart = new google.visualization.AreaChart( document.getElementById( 'gadwp-areachart' + slug ) );
453
+
454
+ chart.draw( chartData, options );
455
+ },
456
+
457
+ drawBottomStats : function ( data ) {
458
+ jQuery( "#gdsessions" + slug ).html( data[ 0 ] );
459
+ jQuery( "#gdusers" + slug ).html( data[ 1 ] );
460
+ jQuery( "#gdpageviews" + slug ).html( data[ 2 ] );
461
+ jQuery( "#gdbouncerate" + slug ).html( data[ 3 ] + "%" );
462
+ jQuery( "#gdorganicsearch" + slug ).html( data[ 4 ] );
463
+ jQuery( "#gdpagespervisit" + slug ).html( data[ 5 ] );
464
+ },
465
+
466
+ rtOnlyUniqueValues : function ( value, index, self ) {
467
+ return self.indexOf( value ) === index;
468
+ },
469
+
470
+ rtCountSessions : function ( rtData, searchValue ) {
471
+ var count = 0, i = 0;
472
+
473
+ for ( i = 0; i < rtData[ "rows" ].length; i++ ) {
474
+ if ( jQuery.inArray( searchValue, rtData[ "rows" ][ i ] ) > -1 ) {
475
+ count += parseInt( rtData[ "rows" ][ i ][ 6 ] );
476
+ }
477
+ }
478
+ return count;
479
+ },
480
+
481
+ rtGenerateTooltip : function ( rtData ) {
482
+ var count = 0, table = "", i = 0;
483
+
484
+ for ( i = 0; i < rtData.length; i++ ) {
485
+ count += parseInt( rtData[ i ].count );
486
+ table += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ].value + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ].count + "</td></tr>";
487
+ }
488
+ ;
489
+ if ( count ) {
490
+ return ( "<table>" + table + "</table>" );
491
+ } else {
492
+ return ( "" );
493
+ }
494
+ },
495
+
496
+ rtPageDetails : function ( rtData, searchValue ) {
497
+ var sant, pageTitle, pgStatsTable, i = 0, j = 0, sum = 0, newsum = 0, countrfr = 0, countkwd = 0, countdrt = 0, countscl = 0, countcpg = 0, tablerfr = "", tablekwd = "", tablescl = "", tablecpg = "", tabledrt = "";
498
+
499
+ rtData = rtData[ "rows" ];
500
+
501
+ for ( i = 0; i < rtData.length; i++ ) {
502
+
503
+ if ( rtData[ i ][ 0 ] == searchValue ) {
504
+ pageTitle = rtData[ i ][ 5 ];
505
+
506
+ switch ( rtData[ i ][ 3 ] ) {
507
+
508
+ case "REFERRAL":
509
+ countrfr += parseInt( rtData[ i ][ 6 ] );
510
+ tablerfr += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ][ 1 ] + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ][ 6 ] + "</td></tr>";
511
+ break;
512
+ case "ORGANIC":
513
+ countkwd += parseInt( rtData[ i ][ 6 ] );
514
+ tablekwd += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ][ 2 ] + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ][ 6 ] + "</td></tr>";
515
+ break;
516
+ case "SOCIAL":
517
+ countscl += parseInt( rtData[ i ][ 6 ] );
518
+ tablescl += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ][ 1 ] + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ][ 6 ] + "</td></tr>";
519
+ break;
520
+ case "CUSTOM":
521
+ countcpg += parseInt( rtData[ i ][ 6 ] );
522
+ tablecpg += "<tr><td class='gadwp-pgdetailsl'>" + rtData[ i ][ 1 ] + "</td><td class='gadwp-pgdetailsr'>" + rtData[ i ][ 6 ] + "</td></tr>";
523
+ break;
524
+ case "DIRECT":
525
+ countdrt += parseInt( rtData[ i ][ 6 ] );
526
+ break;
527
+ }
528
+ }
529
+ }
530
+
531
+ if ( countrfr ) {
532
+ tablerfr = "<table><tr><td>" + reports.i18n[ 0 ] + "(" + countrfr + ")</td></tr>" + tablerfr + "</table><br />";
533
+ }
534
+ if ( countkwd ) {
535
+ tablekwd = "<table><tr><td>" + reports.i18n[ 1 ] + "(" + countkwd + ")</td></tr>" + tablekwd + "</table><br />";
536
+ }
537
+ if ( countscl ) {
538
+ tablescl = "<table><tr><td>" + reports.i18n[ 2 ] + "(" + countscl + ")</td></tr>" + tablescl + "</table><br />";
539
+ }
540
+ if ( countcpg ) {
541
+ tablecpg = "<table><tr><td>" + reports.i18n[ 3 ] + "(" + countcpg + ")</td></tr>" + tablecpg + "</table><br />";
542
+ }
543
+ if ( countdrt ) {
544
+ tabledrt = "<table><tr><td>" + reports.i18n[ 4 ] + "(" + countdrt + ")</td></tr></table><br />";
545
+ }
546
+ return ( "<p><center><strong>" + pageTitle + "</strong></center></p>" + tablerfr + tablekwd + tablescl + tablecpg + tabledrt );
547
+ },
548
+
549
+ rtRefresh : function () {
550
+ if ( reports.render.focusFlag ) {
551
+ postData.from = false;
552
+ postData.to = false;
553
+ postData.query = 'realtime';
554
+ jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
555
+ if ( jQuery.isArray( response ) ) {
556
+ jQuery( '#gadwp-reports' + slug ).show();
557
+ reports.realtime = response[ 0 ];
558
+ reports.drawRealtime( reports.realtime );
559
+ } else {
560
+ reports.throwDebug( response );
561
+ }
562
+
563
+ NProgress.done();
564
+
565
+ } );
566
+ }
567
+ },
568
+
569
+ drawRealtime : function ( rtData ) {
570
+ var rtInfoRight, uPagePath, uReferrals, uKeywords, uSocial, uCustom, i = 0, pagepath = [], referrals = [], keywords = [], social = [], visittype = [], custom = [], uPagePathStats = [], pgStatsTable = "", uReferrals = [], uKeywords = [], uSocial = [], uCustom = [], uVisitType = [ "REFERRAL", "ORGANIC", "SOCIAL", "CUSTOM" ], uVisitorType = [ "DIRECT", "NEW" ];
571
+
572
+ jQuery( function () {
573
+ jQuery( '#gadwp-widget *' ).tooltip( {
574
+ tooltipClass : "gadwp"
575
+ } );
576
+ } );
577
+
578
+ rtData = rtData[ 0 ];
579
+
580
+ if ( jQuery.isNumeric( rtData ) || typeof rtData === "undefined" ) {
581
+ rtData = [];
582
+ rtData[ "totalsForAllResults" ] = []
583
+ rtData[ "totalsForAllResults" ][ "rt:activeUsers" ] = "0";
584
+ rtData[ "rows" ] = [];
585
+ }
586
+
587
+ if ( rtData[ "totalsForAllResults" ][ "rt:activeUsers" ] !== document.getElementById( "gadwp-online" ).innerHTML ) {
588
+ jQuery( "#gadwp-online" ).fadeOut( "slow" );
589
+ jQuery( "#gadwp-online" ).fadeOut( 500 );
590
+ jQuery( "#gadwp-online" ).fadeOut( "slow", function () {
591
+ if ( ( parseInt( rtData[ "totalsForAllResults" ][ "rt:activeUsers" ] ) ) < ( parseInt( document.getElementById( "gadwp-online" ).innerHTML ) ) ) {
592
+ jQuery( "#gadwp-online" ).css( {
593
+ 'background-color' : '#FFE8E8'
594
+ } );
595
+ } else {
596
+ jQuery( "#gadwp-online" ).css( {
597
+ 'background-color' : '#E0FFEC'
598
+ } );
599
+ }
600
+ document.getElementById( "gadwp-online" ).innerHTML = rtData[ "totalsForAllResults" ][ "rt:activeUsers" ];
601
+ } );
602
+ jQuery( "#gadwp-online" ).fadeIn( "slow" );
603
+ jQuery( "#gadwp-online" ).fadeIn( 500 );
604
+ jQuery( "#gadwp-online" ).fadeIn( "slow", function () {
605
+ jQuery( "#gadwp-online" ).css( {
606
+ 'background-color' : '#FFFFFF'
607
+ } );
608
+ } );
609
+ }
610
+
611
+ if ( rtData[ "totalsForAllResults" ][ "rt:activeUsers" ] == 0 ) {
612
+ rtData[ "rows" ] = [];
613
+ }
614
+
615
+ for ( i = 0; i < rtData[ "rows" ].length; i++ ) {
616
+ pagepath.push( rtData[ "rows" ][ i ][ 0 ] );
617
+ if ( rtData[ "rows" ][ i ][ 3 ] == "REFERRAL" ) {
618
+ referrals.push( rtData[ "rows" ][ i ][ 1 ] );
619
+ }
620
+ if ( rtData[ "rows" ][ i ][ 3 ] == "ORGANIC" ) {
621
+ keywords.push( rtData[ "rows" ][ i ][ 2 ] );
622
+ }
623
+ if ( rtData[ "rows" ][ i ][ 3 ] == "SOCIAL" ) {
624
+ social.push( rtData[ "rows" ][ i ][ 1 ] );
625
+ }
626
+ if ( rtData[ "rows" ][ i ][ 3 ] == "CUSTOM" ) {
627
+ custom.push( rtData[ "rows" ][ i ][ 1 ] );
628
+ }
629
+ visittype.push( rtData[ "rows" ][ i ][ 3 ] );
630
+ }
631
+
632
+ uPagePath = pagepath.filter( reports.rtOnlyUniqueValues );
633
+ for ( i = 0; i < uPagePath.length; i++ ) {
634
+ uPagePathStats[ i ] = {
635
+ "pagepath" : uPagePath[ i ],
636
+ "count" : reports.rtCountSessions( rtData, uPagePath[ i ] )
637
+ }
638
+ }
639
+ uPagePathStats.sort( function ( a, b ) {
640
+ return b.count - a.count
641
+ } );
642
+
643
+ pgStatsTable = "";
644
+ for ( i = 0; i < uPagePathStats.length; i++ ) {
645
+ if ( i < gadwpItemData.rtLimitPages ) {
646
+ pgStatsTable += '<div class="gadwp-pline"><div class="gadwp-pleft"><a href="#" data-gadwp="' + reports.rtPageDetails( rtData, uPagePathStats[ i ].pagepath ) + '">' + uPagePathStats[ i ].pagepath.substring( 0, 70 ) + '</a></div><div class="gadwp-pright">' + uPagePathStats[ i ].count + '</div></div>';
647
+ }
648
+ }
649
+ document.getElementById( "gadwp-pages" ).innerHTML = '<br /><div class="gadwp-pg">' + pgStatsTable + '</div>';
650
+
651
+ uReferrals = referrals.filter( reports.rtOnlyUniqueValues );
652
+ for ( i = 0; i < uReferrals.length; i++ ) {
653
+ uReferrals[ i ] = {
654
+ "value" : uReferrals[ i ],
655
+ "count" : reports.rtCountSessions( rtData, uReferrals[ i ] )
656
+ };
657
+ }
658
+ uReferrals.sort( function ( a, b ) {
659
+ return b.count - a.count
660
+ } );
661
+
662
+ uKeywords = keywords.filter( reports.rtOnlyUniqueValues );
663
+ for ( i = 0; i < uKeywords.length; i++ ) {
664
+ uKeywords[ i ] = {
665
+ "value" : uKeywords[ i ],
666
+ "count" : reports.rtCountSessions( rtData, uKeywords[ i ] )
667
+ };
668
+ }
669
+ uKeywords.sort( function ( a, b ) {
670
+ return b.count - a.count
671
+ } );
672
+
673
+ uSocial = social.filter( reports.rtOnlyUniqueValues );
674
+ for ( i = 0; i < uSocial.length; i++ ) {
675
+ uSocial[ i ] = {
676
+ "value" : uSocial[ i ],
677
+ "count" : reports.rtCountSessions( rtData, uSocial[ i ] )
678
+ };
679
+ }
680
+ uSocial.sort( function ( a, b ) {
681
+ return b.count - a.count
682
+ } );
683
+
684
+ uCustom = custom.filter( reports.rtOnlyUniqueValues );
685
+ for ( i = 0; i < uCustom.length; i++ ) {
686
+ uCustom[ i ] = {
687
+ "value" : uCustom[ i ],
688
+ "count" : reports.rtCountSessions( rtData, uCustom[ i ] )
689
+ };
690
+ }
691
+ uCustom.sort( function ( a, b ) {
692
+ return b.count - a.count
693
+ } );
694
+
695
+ rtInfoRight = '<div class="gadwp-bigtext"><a href="#" data-gadwp="' + reports.rtGenerateTooltip( uReferrals ) + '"><div class="gadwp-bleft">' + reports.i18n[ 0 ] + '</a></div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitType[ 0 ] ) + '</div></div>';
696
+ rtInfoRight += '<div class="gadwp-bigtext"><a href="#" data-gadwp="' + reports.rtGenerateTooltip( uKeywords ) + '"><div class="gadwp-bleft">' + reports.i18n[ 1 ] + '</a></div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitType[ 1 ] ) + '</div></div>';
697
+ rtInfoRight += '<div class="gadwp-bigtext"><a href="#" data-gadwp="' + reports.rtGenerateTooltip( uSocial ) + '"><div class="gadwp-bleft">' + reports.i18n[ 2 ] + '</a></div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitType[ 2 ] ) + '</div></div>';
698
+ rtInfoRight += '<div class="gadwp-bigtext"><a href="#" data-gadwp="' + reports.rtGenerateTooltip( uCustom ) + '"><div class="gadwp-bleft">' + reports.i18n[ 3 ] + '</a></div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitType[ 3 ] ) + '</div></div>';
699
+
700
+ rtInfoRight += '<div class="gadwp-bigtext"><div class="gadwp-bleft">' + reports.i18n[ 4 ] + '</div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitorType[ 0 ] ) + '</div></div>';
701
+ rtInfoRight += '<div class="gadwp-bigtext"><div class="gadwp-bleft">' + reports.i18n[ 5 ] + '</div><div class="gadwp-bright">' + reports.rtCountSessions( rtData, uVisitorType[ 1 ] ) + '</div></div>';
702
+
703
+ document.getElementById( "gadwp-tdo-right" ).innerHTML = rtInfoRight;
704
+ },
705
+
706
+ throwDebug : function ( response ) {
707
+ jQuery( "#gadwp-status" + slug ).css( {
708
+ "margin-top" : "3px",
709
+ "padding-left" : "5px",
710
+ "height" : "auto",
711
+ "color" : "#000",
712
+ "border-left" : "5px solid red"
713
+ } );
714
+ if ( response == '-24' ) {
715
+ jQuery( "#gadwp-status" + slug ).html( gadwpItemData.i18n[ 15 ] );
716
+ } else {
717
+ jQuery( "#gadwp-reports" + slug ).css( {
718
+ "background-color" : "#F7F7F7",
719
+ "height" : "auto",
720
+ "margin-top" : "10px",
721
+ "padding-top" : "50px",
722
+ "padding-bottom" : "50px",
723
+ "color" : "#000",
724
+ "text-align" : "center"
725
+ } );
726
+ jQuery( "#gadwp-reports" + slug ).html ( response );
727
+ jQuery( "#gadwp-reports" + slug ).show();
728
+ jQuery( "#gadwp-status" + slug ).html( gadwpItemData.i18n[ 11 ] );
729
+ console.log( "\n********************* GADWP Log ********************* \n\n" + response );
730
+ postData = {
731
+ action : 'gadwp_set_error',
732
+ response : response,
733
+ gadwp_security_set_error : gadwpItemData.security,
734
+ }
735
+ jQuery.post( gadwpItemData.ajaxurl, postData );
736
+ }
737
+ },
738
+
739
+ throwError : function ( target, response, p ) {
740
+ jQuery( target ).css( {
741
+ "background-color" : "#F7F7F7",
742
+ "height" : "auto",
743
+ "padding-top" : p,
744
+ "padding-bottom" : p,
745
+ "color" : "#000",
746
+ "text-align" : "center"
747
+ } );
748
+ if ( response == -21 ) {
749
+ jQuery( target ).html( gadwpItemData.i18n[ 12 ] + ' (' + response + ')' );
750
+ } else {
751
+ jQuery( target ).html( gadwpItemData.i18n[ 13 ] + ' (' + response + ')' );
752
+ }
753
+ },
754
+
755
+ render : function ( view, period, query ) {
756
+ var projectId, from, to, tpl, focusFlag;
757
+
758
+ if ( period == 'realtime' ) {
759
+ jQuery( '#gadwp-sel-report' + slug ).hide();
760
+ } else {
761
+ jQuery( '#gadwp-sel-report' + slug ).show();
762
+ clearInterval( reports.rtRuns );
763
+ }
764
+
765
+ jQuery( '#gadwp-status' + slug ).html( '' );
766
+ switch ( period ) {
767
+ case 'today':
768
+ from = 'today';
769
+ to = 'today';
770
+ break;
771
+ case 'yesterday':
772
+ from = 'yesterday';
773
+ to = 'yesterday';
774
+ break;
775
+ case '7daysAgo':
776
+ from = '7daysAgo';
777
+ to = 'yesterday';
778
+ break;
779
+ case '14daysAgo':
780
+ from = '14daysAgo';
781
+ to = 'yesterday';
782
+ break;
783
+ case '90daysAgo':
784
+ from = '90daysAgo';
785
+ to = 'yesterday';
786
+ break;
787
+ case '365daysAgo':
788
+ from = '365daysAgo';
789
+ to = 'yesterday';
790
+ break;
791
+ case '1095daysAgo':
792
+ from = '1095daysAgo';
793
+ to = 'yesterday';
794
+ break;
795
+ default:
796
+ from = '30daysAgo';
797
+ to = 'yesterday';
798
+ break;
799
+ }
800
+
801
+ tools.setCookie( 'default_metric', query );
802
+ tools.setCookie( 'default_dimension', period );
803
+
804
+ if ( typeof view !== 'undefined' ) {
805
+ tools.setCookie( 'default_view', view );
806
+ projectId = view;
807
+ } else {
808
+ projectId = false;
809
+ }
810
+
811
+ if ( gadwpItemData.scope == 'admin-item' ) {
812
+ postData = {
813
+ action : 'gadwp_backend_item_reports',
814
+ gadwp_security_backend_item_reports : gadwpItemData.security,
815
+ from : from,
816
+ to : to,
817
+ filter : itemId
818
+ }
819
+ } else if ( gadwpItemData.scope == 'front-item' ) {
820
+ postData = {
821
+ action : 'gadwp_frontend_item_reports',
822
+ gadwp_security_frontend_item_reports : gadwpItemData.security,
823
+ from : from,
824
+ to : to,
825
+ filter : gadwpItemData.filter
826
+ }
827
+ } else {
828
+ postData = {
829
+ action : 'gadwp_backend_item_reports',
830
+ gadwp_security_backend_item_reports : gadwpItemData.security,
831
+ projectId : projectId,
832
+ from : from,
833
+ to : to
834
+ }
835
+ }
836
+ if ( period == 'realtime' ) {
837
+
838
+ reports.i18n = gadwpItemData.i18n.slice( 20, 26 );
839
+
840
+ reports.render.focusFlag = 1;
841
+
842
+ jQuery( window ).bind( "focus", function ( event ) {
843
+ reports.render.focusFlag = 1;
844
+ } ).bind( "blur", function ( event ) {
845
+ reports.render.focusFlag = 0;
846
+ } );
847
+
848
+ tpl = '<div id="gadwp-realtime' + slug + '">';
849
+ tpl += '<div class="gadwp-rt-box">';
850
+ tpl += '<div class="gadwp-tdo-left">';
851
+ tpl += '<div class="gadwp-online" id="gadwp-online">0</div>';
852
+ tpl += '</div>';
853
+ tpl += '<div class="gadwp-tdo-right" id="gadwp-tdo-right">';
854
+ tpl += '<div class="gadwp-bigtext">';
855
+ tpl += '<div class="gadwp-bleft">' + reports.i18n[ 0 ] + '</div>';
856
+ tpl += '<div class="gadwp-bright">0</div>';
857
+ tpl += '</div>';
858
+ tpl += '<div class="gadwp-bigtext">';
859
+ tpl += '<div class="gadwp-bleft">' + reports.i18n[ 1 ] + '</div>';
860
+ tpl += '<div class="gadwp-bright">0</div>';
861
+ tpl += '</div>';
862
+ tpl += '<div class="gadwp-bigtext">';
863
+ tpl += '<div class="gadwp-bleft">' + reports.i18n[ 2 ] + '</div>';
864
+ tpl += '<div class="gadwp-bright">0</div>';
865
+ tpl += '</div>';
866
+ tpl += '<div class="gadwp-bigtext">';
867
+ tpl += '<div class="gadwp-bleft">' + reports.i18n[ 3 ] + '</div>';
868
+ tpl += '<div class="gadwp-bright">0</div>';
869
+ tpl += '</div>';
870
+ tpl += '<div class="gadwp-bigtext">';
871
+ tpl += '<div class="gadwp-bleft">' + reports.i18n[ 4 ] + '</div>';
872
+ tpl += '<div class="gadwp-bright">0</div>';
873
+ tpl += '</div>';
874
+ tpl += '<div class="gadwp-bigtext">';
875
+ tpl += '<div class="gadwp-bleft">' + reports.i18n[ 5 ] + '</div>';
876
+ tpl += '<div class="gadwp-bright">0</div>';
877
+ tpl += '</div>';
878
+ tpl += '</div>';
879
+ tpl += '</div>';
880
+ tpl += '<div>';
881
+ tpl += '<div id="gadwp-pages" class="gadwp-pages">&nbsp;</div>';
882
+ tpl += '</div>';
883
+ tpl += '</div>';
884
+
885
+ jQuery( '#gadwp-reports' + slug ).html( tpl );
886
+
887
+ reports.rtRefresh( reports.render.focusFlag );
888
+
889
+ reports.rtRuns = setInterval( reports.rtRefresh, 55000 );
890
+
891
+ } else {
892
+ if ( jQuery.inArray( query, [ 'referrers', 'contentpages', 'searches' ] ) > -1 ) {
893
+
894
+ tpl = '<div id="gadwp-orgcharttablechart' + slug + '">';
895
+ tpl += '<div id="gadwp-orgchart' + slug + '"></div>';
896
+ tpl += '<div id="gadwp-tablechart' + slug + '"></div>';
897
+ tpl += '</div>';
898
+
899
+ jQuery( '#gadwp-reports' + slug ).html( tpl );
900
+ jQuery( '#gadwp-reports' + slug ).hide();
901
+
902
+ postData.query = 'channelGrouping,' + query;
903
+
904
+ jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
905
+ reports.orgChartTableChart( response );
906
+ } );
907
+ } else if ( query == '404errors' ) {
908
+ tpl = '<div id="gadwp-404tablechart' + slug + '">';
909
+ tpl += '<div id="gadwp-tablechart' + slug + '"></div>';
910
+ tpl += '</div>';
911
+
912
+ jQuery( '#gadwp-reports' + slug ).html( tpl );
913
+ jQuery( '#gadwp-reports' + slug ).hide();
914
+
915
+ postData.query = query;
916
+
917
+ jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
918
+ reports.tableChart( response );
919
+ } );
920
+ } else if ( query == 'trafficdetails' || query == 'technologydetails' ) {
921
+
922
+ tpl = '<div id="gadwp-orgchartpiecharts' + slug + '">';
923
+ tpl += '<div id="gadwp-orgchart' + slug + '"></div>';
924
+ tpl += '<div class="gadwp-floatwraper">';
925
+ tpl += '<div id="gadwp-piechart-1' + slug + '" class="halfsize floatleft"></div>';
926
+ tpl += '<div id="gadwp-piechart-2' + slug + '" class="halfsize floatright"></div>';
927
+ tpl += '</div>';
928
+ tpl += '<div class="gadwp-floatwraper">';
929
+ tpl += '<div id="gadwp-piechart-3' + slug + '" class="halfsize floatleft"></div>';
930
+ tpl += '<div id="gadwp-piechart-4' + slug + '" class="halfsize floatright"></div>';
931
+ tpl += '</div>';
932
+ tpl += '</div>';
933
+
934
+ jQuery( '#gadwp-reports' + slug ).html( tpl );
935
+ jQuery( '#gadwp-reports' + slug ).hide();
936
+ if ( query == 'trafficdetails' ) {
937
+ postData.query = 'channelGrouping,medium,visitorType,source,socialNetwork';
938
+ reports.i18n = gadwpItemData.i18n.slice( 0, 5 );
939
+ } else {
940
+ reports.i18n = gadwpItemData.i18n.slice( 15, 20 );
941
+ postData.query = 'deviceCategory,browser,operatingSystem,screenResolution,mobileDeviceBranding';
942
+ }
943
+
944
+ jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
945
+ reports.orgChartPieCharts( response )
946
+ } );
947
+
948
+ } else if ( query == 'locations' ) {
949
+
950
+ tpl = '<div id="gadwp-geocharttablechart' + slug + '">';
951
+ tpl += '<div id="gadwp-geochart' + slug + '"></div>';
952
+ tpl += '<div id="gadwp-tablechart' + slug + '"></div>';
953
+ tpl += '</div>';
954
+
955
+ jQuery( '#gadwp-reports' + slug ).html( tpl );
956
+ jQuery( '#gadwp-reports' + slug ).hide();
957
+
958
+ postData.query = query;
959
+
960
+ jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
961
+ reports.geoChartTableChart( response );
962
+ } );
963
+
964
+ } else {
965
+
966
+ tpl = '<div id="gadwp-areachartbottomstats' + slug + '">';
967
+ tpl += '<div id="gadwp-areachart' + slug + '"></div>';
968
+ tpl += '<div id="gadwp-bottomstats' + slug + '">';
969
+ tpl += '<div class="inside">';
970
+ tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 5 ] + '</h3><p id="gdsessions' + slug + '">&nbsp;</p></div>';
971
+ tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 6 ] + '</h3><p id="gdusers' + slug + '">&nbsp;</p></div>';
972
+ tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 7 ] + '</h3><p id="gdpageviews' + slug + '">&nbsp;</p></div>';
973
+ tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 8 ] + '</h3><p id="gdbouncerate' + slug + '">&nbsp;</p></div>';
974
+ tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 9 ] + '</h3><p id="gdorganicsearch' + slug + '">&nbsp;</p></div>';
975
+ tpl += '<div class="small-box"><h3>' + gadwpItemData.i18n[ 10 ] + '</h3><p id="gdpagespervisit' + slug + '">&nbsp;</p></div>';
976
+ tpl += '</div>';
977
+ tpl += '</div>';
978
+ tpl += '</div>';
979
+
980
+ jQuery( '#gadwp-reports' + slug ).html( tpl );
981
+ jQuery( '#gadwp-reports' + slug ).hide();
982
+
983
+ postData.query = query + ',bottomstats';
984
+
985
+ jQuery.post( gadwpItemData.ajaxurl, postData, function ( response ) {
986
+ reports.areaChartBottomStats( response );
987
+ } );
988
+
989
+ }
990
+
991
+ }
992
+
993
+ },
994
+
995
+ refresh : function () {
996
+ if ( jQuery( '#gadwp-areachartbottomstats' + slug ).length > 0 && jQuery.isArray( reports.areaChartBottomStatsData ) ) {
997
+ reports.areaChartBottomStats( reports.areaChartBottomStatsData );
998
+ }
999
+ if ( jQuery( '#gadwp-orgchartpiecharts' + slug ).length > 0 && jQuery.isArray( reports.orgChartPieChartsData ) ) {
1000
+ reports.orgChartPieCharts( reports.orgChartPieChartsData );
1001
+ }
1002
+ if ( jQuery( '#gadwp-geocharttablechart' + slug ).length > 0 && jQuery.isArray( reports.geoChartTableChartData ) ) {
1003
+ reports.geoChartTableChart( reports.geoChartTableChartData );
1004
+ }
1005
+ if ( jQuery( '#gadwp-orgcharttablechart' + slug ).length > 0 && jQuery.isArray( reports.orgChartTableChartData ) ) {
1006
+ reports.orgChartTableChart( reports.orgChartTableChartData );
1007
+ }
1008
+ if ( jQuery( '#gadwp-404tablechart' + slug ).length > 0 && jQuery.isArray( reports.tableChartData ) ) {
1009
+ reports.tableChart( reports.tableChartData );
1010
+ }
1011
+ },
1012
+
1013
+ init : function () {
1014
+
1015
+ if ( !jQuery( "#gadwp-reports" + slug ).length ) {
1016
+ return;
1017
+ }
1018
+
1019
+ if ( jQuery( "#gadwp-reports" + slug ).html().length ) { // only when report is empty
1020
+ return;
1021
+ }
1022
+
1023
+ try {
1024
+ NProgress.configure( {
1025
+ parent : "#gadwp-progressbar" + slug,
1026
+ showSpinner : false
1027
+ } );
1028
+ NProgress.start();
1029
+ } catch ( e ) {
1030
+ reports.alertMessage( gadwpItemData.i18n[ 0 ] );
1031
+ }
1032
+
1033
+ reports.render( jQuery( '#gadwp-sel-view' + slug ).val(), jQuery( '#gadwp-sel-period' + slug ).val(), jQuery( '#gadwp-sel-report' + slug ).val() );
1034
+
1035
+ jQuery( window ).resize( function () {
1036
+ var diff = jQuery(window).width() - reports.oldViewPort;
1037
+ if ( ( diff < -5 ) || ( diff > 5 ) ) {
1038
+ reports.oldViewPort = jQuery(window).width();
1039
+ reports.refresh(); //refresh only on over 5px viewport width changes
1040
+ }
1041
+ } );
1042
+ }
1043
+ }
1044
+
1045
+ template.init();
1046
+
1047
+ reports.init();
1048
+
1049
+ jQuery( '#gadwp-sel-view' + slug ).change( function () {
1050
+ jQuery( '#gadwp-reports' + slug ).html( '' );
1051
+ reports.init();
1052
+ } );
1053
+
1054
+ jQuery( '#gadwp-sel-period' + slug ).change( function () {
1055
+ jQuery( '#gadwp-reports' + slug ).html( '' );
1056
+ reports.init();
1057
+ } );
1058
+
1059
+ jQuery( '#gadwp-sel-report' + slug ).change( function () {
1060
+ jQuery( '#gadwp-reports' + slug ).html( '' );
1061
+ reports.init();
1062
+ } );
1063
+
1064
+ if ( gadwpItemData.scope == 'admin-widgets' ) {
1065
+ return;
1066
+ } else {
1067
+ return this.dialog( {
1068
+ width : 'auto',
1069
+ maxWidth : 510,
1070
+ height : 'auto',
1071
+ modal : true,
1072
+ fluid : true,
1073
+ dialogClass : 'gadwp wp-dialog',
1074
+ resizable : false,
1075
+ title : reports.getTitle( gadwpItemData.scope ),
1076
+ position : {
1077
+ my : "top",
1078
+ at : "top+100",
1079
+ of : window
1080
+ }
1081
+ } );
1082
+ }
1083
+ }
1084
+ } );
1085
+
1086
+ function GADWPReportLoad () {
1087
+ if ( gadwpItemData.scope == 'admin-widgets' ) {
1088
+ jQuery( '#gadwp-window-1' ).gadwpItemReport( 1 );
1089
+ } else {
1090
+ jQuery( gadwpItemData.getSelector( gadwpItemData.scope ) ).click( function () {
1091
+ if ( !jQuery( "#gadwp-window-" + gadwpItemData.getID( this ) ).length > 0 ) {
1092
+ jQuery( "body" ).append( '<div id="gadwp-window-' + gadwpItemData.getID( this ) + '"></div>' );
1093
+ }
1094
+ jQuery( '#gadwp-window-' + gadwpItemData.getID( this ) ).gadwpItemReport( gadwpItemData.getID( this ) );
1095
+ } );
1096
+ }
1097
+
1098
+ // on window resize
1099
+ jQuery( window ).resize( function () {
1100
+ gadwpItemData.responsiveDialog();
1101
+ } );
1102
+
1103
+ // dialog width larger than viewport
1104
+ jQuery( document ).on( "dialogopen", ".ui-dialog", function ( event, ui ) {
1105
+ gadwpItemData.responsiveDialog();
1106
+ } );
1107
+ }
config.php CHANGED
@@ -1,422 +1,422 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Config' ) ) {
15
-
16
- final class GADWP_Config {
17
-
18
- public $options;
19
-
20
- public function __construct() {
21
- // Get plugin options
22
- $this->get_plugin_options();
23
- // Automatic updates
24
- add_filter( 'auto_update_plugin', array( $this, 'automatic_update' ), 10, 2 );
25
- // Provide language packs for all available Network languages
26
- if ( is_multisite() ) {
27
- add_filter( 'plugins_update_check_locales', array( $this, 'translation_updates' ), 10, 1 );
28
- }
29
- }
30
-
31
- public function get_major_version( $version ) {
32
- $exploded_version = explode( '.', $version );
33
- if ( isset( $exploded_version[2] ) ) {
34
- return $exploded_version[0] . '.' . $exploded_version[1] . '.' . $exploded_version[2];
35
- } else {
36
- return $exploded_version[0] . '.' . $exploded_version[1] . '.0';
37
- }
38
- }
39
-
40
- public function automatic_update( $update, $item ) {
41
- $item = (array) $item;
42
- if ( is_multisite() && ! is_main_site() ) {
43
- return;
44
- }
45
- if ( ! isset( $item['new_version'] ) || ! isset( $item['plugin'] ) || ! $this->options['automatic_updates_minorversion'] ) {
46
- return $update;
47
- }
48
- if ( isset( $item['slug'] ) && $item['slug'] == 'google-analytics-dashboard-for-wp' ) {
49
- // Only when a minor update is available
50
- return ( $this->get_major_version( GADWP_CURRENT_VERSION ) == $this->get_major_version( $item['new_version'] ) );
51
- }
52
- return $update;
53
- }
54
-
55
- public function translation_updates( $locales ) {
56
- $languages = get_available_languages();
57
- return array_values( $languages );
58
- }
59
-
60
- // Validates data before storing
61
- private static function validate_data( $options ) {
62
- if ( isset( $options['ga_realtime_pages'] ) ) {
63
- $options['ga_realtime_pages'] = (int) $options['ga_realtime_pages'];
64
- }
65
- if ( isset( $options['ga_crossdomain_tracking'] ) ) {
66
- $options['ga_crossdomain_tracking'] = (int) $options['ga_crossdomain_tracking'];
67
- }
68
- if ( isset( $options['ga_crossdomain_list'] ) ) {
69
- $options['ga_crossdomain_list'] = sanitize_text_field( $options['ga_crossdomain_list'] );
70
- }
71
- if ( isset( $options['ga_dash_clientid'] ) ) {
72
- $options['ga_dash_clientid'] = sanitize_text_field( $options['ga_dash_clientid'] );
73
- }
74
- if ( isset( $options['ga_dash_clientsecret'] ) ) {
75
- $options['ga_dash_clientsecret'] = sanitize_text_field( $options['ga_dash_clientsecret'] );
76
- }
77
- if ( isset( $options['ga_dash_style'] ) ) {
78
- $options['ga_dash_style'] = sanitize_text_field( $options['ga_dash_style'] );
79
- }
80
- if ( isset( $options['ga_event_downloads'] ) ) {
81
- if ( empty( $options['ga_event_downloads'] ) ) {
82
- $options['ga_event_downloads'] = 'zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*';
83
- }
84
- $options['ga_event_downloads'] = sanitize_text_field( $options['ga_event_downloads'] );
85
- }
86
- if ( isset( $options['ga_speed_samplerate'] ) && ( $options['ga_speed_samplerate'] < 1 || $options['ga_speed_samplerate'] > 100 ) ) {
87
- $options['ga_speed_samplerate'] = 1;
88
- }
89
- if ( isset( $options['ga_target_geomap'] ) ) {
90
- $options['ga_target_geomap'] = sanitize_text_field( $options['ga_target_geomap'] );
91
- }
92
- if ( isset( $options['ga_author_dimindex'] ) ) {
93
- $options['ga_author_dimindex'] = (int) $options['ga_author_dimindex'];
94
- }
95
- if ( isset( $options['ga_category_dimindex'] ) ) {
96
- $options['ga_category_dimindex'] = (int) $options['ga_category_dimindex'];
97
- }
98
- if ( isset( $options['ga_tag_dimindex'] ) ) {
99
- $options['ga_tag_dimindex'] = (int) $options['ga_tag_dimindex'];
100
- }
101
- if ( isset( $options['ga_user_dimindex'] ) ) {
102
- $options['ga_user_dimindex'] = (int) $options['ga_user_dimindex'];
103
- }
104
- if ( isset( $options['ga_pubyear_dimindex'] ) ) {
105
- $options['ga_pubyear_dimindex'] = (int) $options['ga_pubyear_dimindex'];
106
- }
107
- if ( isset( $options['ga_pubyearmonth_dimindex'] ) ) {
108
- $options['ga_pubyearmonth_dimindex'] = (int) $options['ga_pubyearmonth_dimindex'];
109
- }
110
- if ( isset( $options['ga_aff_tracking'] ) ) {
111
- $options['ga_aff_tracking'] = (int) $options['ga_aff_tracking'];
112
- }
113
- if ( isset( $options['ga_cookiedomain'] ) ) { // v4.9
114
- $options['ga_cookiedomain'] = sanitize_text_field( $options['ga_cookiedomain'] );
115
- }
116
- if ( isset( $options['ga_cookiename'] ) ) { // v4.9
117
- $options['ga_cookiename'] = sanitize_text_field( $options['ga_cookiename'] );
118
- }
119
- if ( isset( $options['pagetitle_404'] ) ) { // v4.9.4
120
- $options['pagetitle_404'] = sanitize_text_field( $options['pagetitle_404'] );
121
- }
122
- if ( isset( $options['maps_api_key'] ) ) { // v4.9.4
123
- $options['maps_api_key'] = sanitize_text_field( $options['maps_api_key'] );
124
- }
125
- if ( isset( $options['ga_cookieexpires'] ) && $options['ga_cookieexpires'] ) { // v4.9
126
- $options['ga_cookieexpires'] = (int) $options['ga_cookieexpires'];
127
- }
128
- if ( isset( $options['ga_event_affiliates'] ) ) {
129
- if ( empty( $options['ga_event_affiliates'] ) ) {
130
- $options['ga_event_affiliates'] = '/out/';
131
- }
132
- $options['ga_event_affiliates'] = sanitize_text_field( $options['ga_event_affiliates'] );
133
- }
134
-
135
- $token = json_decode( $options['ga_dash_token'] ); // v4.8.2
136
- if ( isset( $token->token_type ) ) {
137
- unset( $options['ga_dash_refresh_token'] );
138
- }
139
-
140
- return $options;
141
- }
142
-
143
- public function set_plugin_options( $network_settings = false ) {
144
- // Handle Network Mode
145
- $options = $this->options;
146
- $get_network_options = get_site_option( 'gadash_network_options' );
147
- $old_network_options = (array) json_decode( $get_network_options );
148
- if ( is_multisite() ) {
149
- if ( $network_settings ) { // Retrieve network options, clear blog options, store both to db
150
- $network_options['ga_dash_token'] = $this->options['ga_dash_token'];
151
- $options['ga_dash_token'] = '';
152
- if ( is_network_admin() ) {
153
- $network_options['ga_dash_profile_list'] = $this->options['ga_dash_profile_list'];
154
- $options['ga_dash_profile_list'] = array();
155
- $network_options['ga_dash_clientid'] = $this->options['ga_dash_clientid'];
156
- $options['ga_dash_clientid'] = '';
157
- $network_options['ga_dash_clientsecret'] = $this->options['ga_dash_clientsecret'];
158
- $options['ga_dash_clientsecret'] = '';
159
- $network_options['ga_dash_userapi'] = $this->options['ga_dash_userapi'];
160
- $options['ga_dash_userapi'] = 0;
161
- $network_options['ga_dash_network'] = $this->options['ga_dash_network'];
162
- $network_options['ga_dash_excludesa'] = $this->options['ga_dash_excludesa'];
163
- $network_options['automatic_updates_minorversion'] = $this->options['automatic_updates_minorversion'];
164
- unset( $options['ga_dash_network'] );
165
- if ( isset( $this->options['ga_dash_tableid_network'] ) ) {
166
- $network_options['ga_dash_tableid_network'] = $this->options['ga_dash_tableid_network'];
167
- unset( $options['ga_dash_tableid_network'] );
168
- }
169
- }
170
- update_site_option( 'gadash_network_options', json_encode( $this->validate_data( array_merge( $old_network_options, $network_options ) ) ) );
171
- }
172
- }
173
- update_option( 'gadash_options', json_encode( $this->validate_data( $options ) ) );
174
- }
175
-
176
- private function get_plugin_options() {
177
- /*
178
- * Get plugin options
179
- */
180
- global $blog_id;
181
-
182
- if ( ! get_option( 'gadash_options' ) ) {
183
- GADWP_Install::install();
184
- }
185
- $this->options = (array) json_decode( get_option( 'gadash_options' ) );
186
- // Maintain Compatibility
187
- $this->maintain_compatibility();
188
- // Handle Network Mode
189
- if ( is_multisite() ) {
190
- $get_network_options = get_site_option( 'gadash_network_options' );
191
- $network_options = (array) json_decode( $get_network_options );
192
- if ( isset( $network_options['ga_dash_network'] ) && ( $network_options['ga_dash_network'] ) ) {
193
- if ( ! is_network_admin() && ! empty( $network_options['ga_dash_profile_list'] ) && isset( $network_options['ga_dash_tableid_network']->$blog_id ) ) {
194
- $network_options['ga_dash_profile_list'] = array( 0 => GADWP_Tools::get_selected_profile( $network_options['ga_dash_profile_list'], $network_options['ga_dash_tableid_network']->$blog_id ) );
195
- $network_options['ga_dash_tableid_jail'] = $network_options['ga_dash_profile_list'][0][1];
196
- }
197
- $this->options = array_merge( $this->options, $network_options );
198
- } else {
199
- $this->options['ga_dash_network'] = 0;
200
- }
201
- }
202
- }
203
-
204
- private function maintain_compatibility() {
205
- $flag = false;
206
-
207
- if ( GADWP_CURRENT_VERSION != get_option( 'gadwp_version' ) ) {
208
- $flag = true;
209
- update_option( 'gadwp_version', GADWP_CURRENT_VERSION );
210
- update_option( 'gadwp_got_updated', true );
211
- $rebuild_token = json_decode( $this->options['ga_dash_token'] ); // v4.8.2
212
- if ( is_object( $rebuild_token ) && ! isset( $rebuild_token->token_type ) ) {
213
- if ( isset( $this->options['ga_dash_refresh_token'] ) ) {
214
- $rebuild_token->refresh_token = $this->options['ga_dash_refresh_token'];
215
- }
216
- $rebuild_token->token_type = "Bearer";
217
- $this->options['ga_dash_token'] = json_encode( $rebuild_token );
218
- unset( $this->options['ga_dash_refresh_token'] );
219
- $this->set_plugin_options( true );
220
- } else {
221
- unset( $this->options['ga_dash_refresh_token'] );
222
- }
223
- GADWP_Tools::clear_cache();
224
- GADWP_Tools::delete_cache( 'last_error' );
225
- if ( is_multisite() ) { // Cleanup errors and cookies on the entire network
226
- foreach ( GADWP_Tools::get_sites( array( 'limit' => apply_filters( 'gadwp_sites_limit', 100 ) ) ) as $blog ) {
227
- switch_to_blog( $blog['blog_id'] );
228
- GADWP_Tools::delete_cache( 'gapi_errors' );
229
- restore_current_blog();
230
- }
231
- } else {
232
- GADWP_Tools::delete_cache( 'gapi_errors' );
233
- }
234
- GADWP_Tools::unset_cookie( 'default_metric' );
235
- GADWP_Tools::unset_cookie( 'default_dimension' );
236
- GADWP_Tools::unset_cookie( 'default_view' );
237
- }
238
- if ( ! isset( $this->options['ga_enhanced_links'] ) ) {
239
- $this->options['ga_enhanced_links'] = 0;
240
- $flag = true;
241
- }
242
- if ( ! isset( $this->options['ga_dash_network'] ) ) {
243
- $this->options['ga_dash_network'] = 0;
244
- $flag = true;
245
- }
246
- if ( ! isset( $this->options['ga_enhanced_excludesa'] ) ) {
247
- $this->options['ga_dash_excludesa'] = 0;
248
- $flag = true;
249
- }
250
- if ( ! isset( $this->options['ga_dash_remarketing'] ) ) {
251
- $this->options['ga_dash_remarketing'] = 0;
252
- $flag = true;
253
- }
254
- if ( ! isset( $this->options['ga_dash_adsense'] ) ) {
255
- $this->options['ga_dash_adsense'] = 0;
256
- $flag = true;
257
- }
258
- if ( ! isset( $this->options['ga_speed_samplerate'] ) ) {
259
- $this->options['ga_speed_samplerate'] = 1;
260
- $flag = true;
261
- }
262
- if ( ! isset( $this->options['automatic_updates_minorversion'] ) ) {
263
- $this->options['automatic_updates_minorversion'] = 1;
264
- $flag = true;
265
- }
266
- if ( ! isset( $this->options['ga_event_bouncerate'] ) ) {
267
- $this->options['ga_event_bouncerate'] = 0;
268
- $flag = true;
269
- }
270
- if ( ! is_array( $this->options['ga_dash_access_front'] ) || empty( $this->options['ga_dash_access_front'] ) ) {
271
- $this->options['ga_dash_access_front'] = array();
272
- $this->options['ga_dash_access_front'][] = 'administrator';
273
- $flag = true;
274
- }
275
-
276
- if ( ! is_array( $this->options['ga_dash_profile_list'] ) ) {
277
- $this->options['ga_dash_profile_list'] = array();
278
- $flag = true;
279
- }
280
-
281
- if ( ! is_array( $this->options['ga_dash_access_back'] ) || empty( $this->options['ga_dash_access_back'] ) ) {
282
- $this->options['ga_dash_access_back'] = array();
283
- $this->options['ga_dash_access_back'][] = 'administrator';
284
- $flag = true;
285
- }
286
- if ( ! is_array( $this->options['ga_track_exclude'] ) ) {
287
- $this->options['ga_track_exclude'] = array();
288
- $flag = true;
289
- }
290
- if ( ! isset( $this->options['ga_crossdomain_tracking'] ) ) {
291
- $this->options['ga_crossdomain_tracking'] = 0;
292
- $flag = true;
293
- }
294
- if ( ! isset( $this->options['ga_crossdomain_list'] ) ) {
295
- $this->options['ga_crossdomain_list'] = '';
296
- $flag = true;
297
- }
298
- if ( ! isset( $this->options['ga_author_dimindex'] ) ) {
299
- $this->options['ga_author_dimindex'] = 0;
300
- $flag = true;
301
- }
302
- if ( ! isset( $this->options['ga_tag_dimindex'] ) ) {
303
- $this->options['ga_tag_dimindex'] = 0;
304
- $flag = true;
305
- }
306
- if ( ! isset( $this->options['ga_category_dimindex'] ) ) {
307
- $this->options['ga_category_dimindex'] = 0;
308
- $flag = true;
309
- }
310
- $options['ga_tag_dimindex'] = 0;
311
- if ( ! isset( $this->options['ga_user_dimindex'] ) ) {
312
- $this->options['ga_user_dimindex'] = 0;
313
- $flag = true;
314
- }
315
- if ( ! isset( $this->options['ga_pubyear_dimindex'] ) ) {
316
- $this->options['ga_pubyear_dimindex'] = 0;
317
- $flag = true;
318
- }
319
- if ( ! isset( $this->options['ga_pubyearmonth_dimindex'] ) ) {
320
- $this->options['ga_pubyearmonth_dimindex'] = 0;
321
- $flag = true;
322
- }
323
- if ( ! isset( $this->options['ga_event_affiliates'] ) ) {
324
- $this->options['ga_event_affiliates'] = '/out/';
325
- $flag = true;
326
- }
327
- if ( ! isset( $this->options['ga_aff_tracking'] ) ) {
328
- $this->options['ga_aff_tracking'] = 0;
329
- $flag = true;
330
- }
331
- if ( ! isset( $this->options['ga_hash_tracking'] ) ) {
332
- $this->options['ga_hash_tracking'] = 0;
333
- $flag = true;
334
- }
335
- if ( ! isset( $this->options['backend_item_reports'] ) ) { // v4.8
336
- $this->options['backend_item_reports'] = 1;
337
- $flag = true;
338
- }
339
- if ( isset( $this->options['ga_dash_default_metric'] ) ) { // v4.8.1
340
- unset( $this->options['ga_dash_default_metric'] );
341
- $flag = true;
342
- }
343
- if ( isset( $this->options['ga_dash_default_dimension'] ) ) { // v4.8.1
344
- unset( $this->options['ga_dash_default_dimension'] );
345
- $flag = true;
346
- }
347
- if ( isset( $this->options['item_reports'] ) ) { // v4.8
348
- $this->options['backend_item_reports'] = $this->options['item_reports'];
349
- unset( $this->options['item_reports'] );
350
- $flag = true;
351
- }
352
- if ( isset( $this->options['ga_dash_frontend_stats'] ) ) { // v4.8
353
- $this->options['frontend_item_reports'] = $this->options['ga_dash_frontend_stats'];
354
- unset( $this->options['ga_dash_frontend_stats'] );
355
- $flag = true;
356
- }
357
- if ( ! isset( $this->options['dashboard_widget'] ) ) { // v4.7
358
- $this->options['dashboard_widget'] = 1;
359
- $flag = true;
360
- }
361
- if ( ! isset( $this->options['api_backoff'] ) ) { // v4.8.1.3
362
- $this->options['api_backoff'] = 0;
363
- $flag = true;
364
- }
365
- if ( ! isset( $this->options['pagetitle_404'] ) ) { // v4.9.4
366
- $this->options['pagetitle_404'] = 'Page Not Found';
367
- $flag = true;
368
- }
369
- if ( ! isset( $this->options['maps_api_key'] ) ) { // v4.9.4
370
- $this->options['maps_api_key'] = '';
371
- $flag = true;
372
- }
373
- if ( isset( $this->options['ga_tracking_code'] ) ) {
374
- unset( $this->options['ga_tracking_code'] );
375
- $flag = true;
376
- }
377
- if ( isset( $this->options['ga_dash_tableid'] ) ) { // v4.9
378
- unset( $this->options['ga_dash_tableid'] );
379
- $flag = true;
380
- }
381
- if ( isset( $this->options['ga_dash_frontend_keywords'] ) ) { // v4.8
382
- unset( $this->options['ga_dash_frontend_keywords'] );
383
- $flag = true;
384
- }
385
- if ( isset( $this->options['ga_dash_apikey'] ) ) { // v4.9.1.3
386
- unset( $this->options['ga_dash_apikey'] );
387
- $flag = true;
388
- }
389
- if ( isset( $this->options['ga_dash_jailadmins'] ) ) { // v4.7
390
- if ( isset( $this->options['ga_dash_jailadmins'] ) ) {
391
- $this->options['switch_profile'] = 0;
392
- unset( $this->options['ga_dash_jailadmins'] );
393
- $flag = true;
394
- } else {
395
- $this->options['switch_profile'] = 1;
396
- unset( $this->options['ga_dash_jailadmins'] );
397
- $flag = true;
398
- }
399
- }
400
- if ( ! isset( $this->options['ga_cookiedomain'] ) ) {
401
- $this->options['ga_cookiedomain'] = '';
402
- $flag = true;
403
- }
404
- if ( ! isset( $this->options['ga_cookiedomain'] ) ) { // v4.9
405
- $this->options['ga_cookiedomain'] = '';
406
- $flag = true;
407
- }
408
- if ( ! isset( $this->options['ga_cookiename'] ) ) { // v4.9
409
- $this->options['ga_cookiename'] = '';
410
- $flag = true;
411
- }
412
- if ( ! isset( $this->options['ga_cookieexpires'] ) ) { // v4.9
413
- $this->options['ga_cookieexpires'] = '';
414
- $flag = true;
415
- }
416
-
417
- if ( $flag ) {
418
- $this->set_plugin_options( false );
419
- }
420
- }
421
- }
422
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Config' ) ) {
15
+
16
+ final class GADWP_Config {
17
+
18
+ public $options;
19
+
20
+ public function __construct() {
21
+ // Get plugin options
22
+ $this->get_plugin_options();
23
+ // Automatic updates
24
+ add_filter( 'auto_update_plugin', array( $this, 'automatic_update' ), 10, 2 );
25
+ // Provide language packs for all available Network languages
26
+ if ( is_multisite() ) {
27
+ add_filter( 'plugins_update_check_locales', array( $this, 'translation_updates' ), 10, 1 );
28
+ }
29
+ }
30
+
31
+ public function get_major_version( $version ) {
32
+ $exploded_version = explode( '.', $version );
33
+ if ( isset( $exploded_version[2] ) ) {
34
+ return $exploded_version[0] . '.' . $exploded_version[1] . '.' . $exploded_version[2];
35
+ } else {
36
+ return $exploded_version[0] . '.' . $exploded_version[1] . '.0';
37
+ }
38
+ }
39
+
40
+ public function automatic_update( $update, $item ) {
41
+ $item = (array) $item;
42
+ if ( is_multisite() && ! is_main_site() ) {
43
+ return;
44
+ }
45
+ if ( ! isset( $item['new_version'] ) || ! isset( $item['plugin'] ) || ! $this->options['automatic_updates_minorversion'] ) {
46
+ return $update;
47
+ }
48
+ if ( isset( $item['slug'] ) && $item['slug'] == 'google-analytics-dashboard-for-wp' ) {
49
+ // Only when a minor update is available
50
+ return ( $this->get_major_version( GADWP_CURRENT_VERSION ) == $this->get_major_version( $item['new_version'] ) );
51
+ }
52
+ return $update;
53
+ }
54
+
55
+ public function translation_updates( $locales ) {
56
+ $languages = get_available_languages();
57
+ return array_values( $languages );
58
+ }
59
+
60
+ // Validates data before storing
61
+ private static function validate_data( $options ) {
62
+ if ( isset( $options['ga_realtime_pages'] ) ) {
63
+ $options['ga_realtime_pages'] = (int) $options['ga_realtime_pages'];
64
+ }
65
+ if ( isset( $options['ga_crossdomain_tracking'] ) ) {
66
+ $options['ga_crossdomain_tracking'] = (int) $options['ga_crossdomain_tracking'];
67
+ }
68
+ if ( isset( $options['ga_crossdomain_list'] ) ) {
69
+ $options['ga_crossdomain_list'] = sanitize_text_field( $options['ga_crossdomain_list'] );
70
+ }
71
+ if ( isset( $options['ga_dash_clientid'] ) ) {
72
+ $options['ga_dash_clientid'] = sanitize_text_field( $options['ga_dash_clientid'] );
73
+ }
74
+ if ( isset( $options['ga_dash_clientsecret'] ) ) {
75
+ $options['ga_dash_clientsecret'] = sanitize_text_field( $options['ga_dash_clientsecret'] );
76
+ }
77
+ if ( isset( $options['ga_dash_style'] ) ) {
78
+ $options['ga_dash_style'] = sanitize_text_field( $options['ga_dash_style'] );
79
+ }
80
+ if ( isset( $options['ga_event_downloads'] ) ) {
81
+ if ( empty( $options['ga_event_downloads'] ) ) {
82
+ $options['ga_event_downloads'] = 'zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*';
83
+ }
84
+ $options['ga_event_downloads'] = sanitize_text_field( $options['ga_event_downloads'] );
85
+ }
86
+ if ( isset( $options['ga_speed_samplerate'] ) && ( $options['ga_speed_samplerate'] < 1 || $options['ga_speed_samplerate'] > 100 ) ) {
87
+ $options['ga_speed_samplerate'] = 1;
88
+ }
89
+ if ( isset( $options['ga_target_geomap'] ) ) {
90
+ $options['ga_target_geomap'] = sanitize_text_field( $options['ga_target_geomap'] );
91
+ }
92
+ if ( isset( $options['ga_author_dimindex'] ) ) {
93
+ $options['ga_author_dimindex'] = (int) $options['ga_author_dimindex'];
94
+ }
95
+ if ( isset( $options['ga_category_dimindex'] ) ) {
96
+ $options['ga_category_dimindex'] = (int) $options['ga_category_dimindex'];
97
+ }
98
+ if ( isset( $options['ga_tag_dimindex'] ) ) {
99
+ $options['ga_tag_dimindex'] = (int) $options['ga_tag_dimindex'];
100
+ }
101
+ if ( isset( $options['ga_user_dimindex'] ) ) {
102
+ $options['ga_user_dimindex'] = (int) $options['ga_user_dimindex'];
103
+ }
104
+ if ( isset( $options['ga_pubyear_dimindex'] ) ) {
105
+ $options['ga_pubyear_dimindex'] = (int) $options['ga_pubyear_dimindex'];
106
+ }
107
+ if ( isset( $options['ga_pubyearmonth_dimindex'] ) ) {
108
+ $options['ga_pubyearmonth_dimindex'] = (int) $options['ga_pubyearmonth_dimindex'];
109
+ }
110
+ if ( isset( $options['ga_aff_tracking'] ) ) {
111
+ $options['ga_aff_tracking'] = (int) $options['ga_aff_tracking'];
112
+ }
113
+ if ( isset( $options['ga_cookiedomain'] ) ) { // v4.9
114
+ $options['ga_cookiedomain'] = sanitize_text_field( $options['ga_cookiedomain'] );
115
+ }
116
+ if ( isset( $options['ga_cookiename'] ) ) { // v4.9
117
+ $options['ga_cookiename'] = sanitize_text_field( $options['ga_cookiename'] );
118
+ }
119
+ if ( isset( $options['pagetitle_404'] ) ) { // v4.9.4
120
+ $options['pagetitle_404'] = sanitize_text_field( $options['pagetitle_404'] );
121
+ }
122
+ if ( isset( $options['maps_api_key'] ) ) { // v4.9.4
123
+ $options['maps_api_key'] = sanitize_text_field( $options['maps_api_key'] );
124
+ }
125
+ if ( isset( $options['ga_cookieexpires'] ) && $options['ga_cookieexpires'] ) { // v4.9
126
+ $options['ga_cookieexpires'] = (int) $options['ga_cookieexpires'];
127
+ }
128
+ if ( isset( $options['ga_event_affiliates'] ) ) {
129
+ if ( empty( $options['ga_event_affiliates'] ) ) {
130
+ $options['ga_event_affiliates'] = '/out/';
131
+ }
132
+ $options['ga_event_affiliates'] = sanitize_text_field( $options['ga_event_affiliates'] );
133
+ }
134
+
135
+ $token = json_decode( $options['ga_dash_token'] ); // v4.8.2
136
+ if ( isset( $token->token_type ) ) {
137
+ unset( $options['ga_dash_refresh_token'] );
138
+ }
139
+
140
+ return $options;
141
+ }
142
+
143
+ public function set_plugin_options( $network_settings = false ) {
144
+ // Handle Network Mode
145
+ $options = $this->options;
146
+ $get_network_options = get_site_option( 'gadash_network_options' );
147
+ $old_network_options = (array) json_decode( $get_network_options );
148
+ if ( is_multisite() ) {
149
+ if ( $network_settings ) { // Retrieve network options, clear blog options, store both to db
150
+ $network_options['ga_dash_token'] = $this->options['ga_dash_token'];
151
+ $options['ga_dash_token'] = '';
152
+ if ( is_network_admin() ) {
153
+ $network_options['ga_dash_profile_list'] = $this->options['ga_dash_profile_list'];
154
+ $options['ga_dash_profile_list'] = array();
155
+ $network_options['ga_dash_clientid'] = $this->options['ga_dash_clientid'];
156
+ $options['ga_dash_clientid'] = '';
157
+ $network_options['ga_dash_clientsecret'] = $this->options['ga_dash_clientsecret'];
158
+ $options['ga_dash_clientsecret'] = '';
159
+ $network_options['ga_dash_userapi'] = $this->options['ga_dash_userapi'];
160
+ $options['ga_dash_userapi'] = 0;
161
+ $network_options['ga_dash_network'] = $this->options['ga_dash_network'];
162
+ $network_options['ga_dash_excludesa'] = $this->options['ga_dash_excludesa'];
163
+ $network_options['automatic_updates_minorversion'] = $this->options['automatic_updates_minorversion'];
164
+ unset( $options['ga_dash_network'] );
165
+ if ( isset( $this->options['ga_dash_tableid_network'] ) ) {
166
+ $network_options['ga_dash_tableid_network'] = $this->options['ga_dash_tableid_network'];
167
+ unset( $options['ga_dash_tableid_network'] );
168
+ }
169
+ }
170
+ update_site_option( 'gadash_network_options', json_encode( $this->validate_data( array_merge( $old_network_options, $network_options ) ) ) );
171
+ }
172
+ }
173
+ update_option( 'gadash_options', json_encode( $this->validate_data( $options ) ) );
174
+ }
175
+
176
+ private function get_plugin_options() {
177
+ /*
178
+ * Get plugin options
179
+ */
180
+ global $blog_id;
181
+
182
+ if ( ! get_option( 'gadash_options' ) ) {
183
+ GADWP_Install::install();
184
+ }
185
+ $this->options = (array) json_decode( get_option( 'gadash_options' ) );
186
+ // Maintain Compatibility
187
+ $this->maintain_compatibility();
188
+ // Handle Network Mode
189
+ if ( is_multisite() ) {
190
+ $get_network_options = get_site_option( 'gadash_network_options' );
191
+ $network_options = (array) json_decode( $get_network_options );
192
+ if ( isset( $network_options['ga_dash_network'] ) && ( $network_options['ga_dash_network'] ) ) {
193
+ if ( ! is_network_admin() && ! empty( $network_options['ga_dash_profile_list'] ) && isset( $network_options['ga_dash_tableid_network']->$blog_id ) ) {
194
+ $network_options['ga_dash_profile_list'] = array( 0 => GADWP_Tools::get_selected_profile( $network_options['ga_dash_profile_list'], $network_options['ga_dash_tableid_network']->$blog_id ) );
195
+ $network_options['ga_dash_tableid_jail'] = $network_options['ga_dash_profile_list'][0][1];
196
+ }
197
+ $this->options = array_merge( $this->options, $network_options );
198
+ } else {
199
+ $this->options['ga_dash_network'] = 0;
200
+ }
201
+ }
202
+ }
203
+
204
+ private function maintain_compatibility() {
205
+ $flag = false;
206
+
207
+ if ( GADWP_CURRENT_VERSION != get_option( 'gadwp_version' ) ) {
208
+ $flag = true;
209
+ update_option( 'gadwp_version', GADWP_CURRENT_VERSION );
210
+ update_option( 'gadwp_got_updated', true );
211
+ $rebuild_token = json_decode( $this->options['ga_dash_token'] ); // v4.8.2
212
+ if ( is_object( $rebuild_token ) && ! isset( $rebuild_token->token_type ) ) {
213
+ if ( isset( $this->options['ga_dash_refresh_token'] ) ) {
214
+ $rebuild_token->refresh_token = $this->options['ga_dash_refresh_token'];
215
+ }
216
+ $rebuild_token->token_type = "Bearer";
217
+ $this->options['ga_dash_token'] = json_encode( $rebuild_token );
218
+ unset( $this->options['ga_dash_refresh_token'] );
219
+ $this->set_plugin_options( true );
220
+ } else {
221
+ unset( $this->options['ga_dash_refresh_token'] );
222
+ }
223
+ GADWP_Tools::clear_cache();
224
+ GADWP_Tools::delete_cache( 'last_error' );
225
+ if ( is_multisite() ) { // Cleanup errors and cookies on the entire network
226
+ foreach ( GADWP_Tools::get_sites( array( 'limit' => apply_filters( 'gadwp_sites_limit', 100 ) ) ) as $blog ) {
227
+ switch_to_blog( $blog['blog_id'] );
228
+ GADWP_Tools::delete_cache( 'gapi_errors' );
229
+ restore_current_blog();
230
+ }
231
+ } else {
232
+ GADWP_Tools::delete_cache( 'gapi_errors' );
233
+ }
234
+ GADWP_Tools::unset_cookie( 'default_metric' );
235
+ GADWP_Tools::unset_cookie( 'default_dimension' );
236
+ GADWP_Tools::unset_cookie( 'default_view' );
237
+ }
238
+ if ( ! isset( $this->options['ga_enhanced_links'] ) ) {
239
+ $this->options['ga_enhanced_links'] = 0;
240
+ $flag = true;
241
+ }
242
+ if ( ! isset( $this->options['ga_dash_network'] ) ) {
243
+ $this->options['ga_dash_network'] = 0;
244
+ $flag = true;
245
+ }
246
+ if ( ! isset( $this->options['ga_enhanced_excludesa'] ) ) {
247
+ $this->options['ga_dash_excludesa'] = 0;
248
+ $flag = true;
249
+ }
250
+ if ( ! isset( $this->options['ga_dash_remarketing'] ) ) {
251
+ $this->options['ga_dash_remarketing'] = 0;
252
+ $flag = true;
253
+ }
254
+ if ( ! isset( $this->options['ga_dash_adsense'] ) ) {
255
+ $this->options['ga_dash_adsense'] = 0;
256
+ $flag = true;
257
+ }
258
+ if ( ! isset( $this->options['ga_speed_samplerate'] ) ) {
259
+ $this->options['ga_speed_samplerate'] = 1;
260
+ $flag = true;
261
+ }
262
+ if ( ! isset( $this->options['automatic_updates_minorversion'] ) ) {
263
+ $this->options['automatic_updates_minorversion'] = 1;
264
+ $flag = true;
265
+ }
266
+ if ( ! isset( $this->options['ga_event_bouncerate'] ) ) {
267
+ $this->options['ga_event_bouncerate'] = 0;
268
+ $flag = true;
269
+ }
270
+ if ( ! is_array( $this->options['ga_dash_access_front'] ) || empty( $this->options['ga_dash_access_front'] ) ) {
271
+ $this->options['ga_dash_access_front'] = array();
272
+ $this->options['ga_dash_access_front'][] = 'administrator';
273
+ $flag = true;
274
+ }
275
+
276
+ if ( ! is_array( $this->options['ga_dash_profile_list'] ) ) {
277
+ $this->options['ga_dash_profile_list'] = array();
278
+ $flag = true;
279
+ }
280
+
281
+ if ( ! is_array( $this->options['ga_dash_access_back'] ) || empty( $this->options['ga_dash_access_back'] ) ) {
282
+ $this->options['ga_dash_access_back'] = array();
283
+ $this->options['ga_dash_access_back'][] = 'administrator';
284
+ $flag = true;
285
+ }
286
+ if ( ! is_array( $this->options['ga_track_exclude'] ) ) {
287
+ $this->options['ga_track_exclude'] = array();
288
+ $flag = true;
289
+ }
290
+ if ( ! isset( $this->options['ga_crossdomain_tracking'] ) ) {
291
+ $this->options['ga_crossdomain_tracking'] = 0;
292
+ $flag = true;
293
+ }
294
+ if ( ! isset( $this->options['ga_crossdomain_list'] ) ) {
295
+ $this->options['ga_crossdomain_list'] = '';
296
+ $flag = true;
297
+ }
298
+ if ( ! isset( $this->options['ga_author_dimindex'] ) ) {
299
+ $this->options['ga_author_dimindex'] = 0;
300
+ $flag = true;
301
+ }
302
+ if ( ! isset( $this->options['ga_tag_dimindex'] ) ) {
303
+ $this->options['ga_tag_dimindex'] = 0;
304
+ $flag = true;
305
+ }
306
+ if ( ! isset( $this->options['ga_category_dimindex'] ) ) {
307
+ $this->options['ga_category_dimindex'] = 0;
308
+ $flag = true;
309
+ }
310
+ $options['ga_tag_dimindex'] = 0;
311
+ if ( ! isset( $this->options['ga_user_dimindex'] ) ) {
312
+ $this->options['ga_user_dimindex'] = 0;
313
+ $flag = true;
314
+ }
315
+ if ( ! isset( $this->options['ga_pubyear_dimindex'] ) ) {
316
+ $this->options['ga_pubyear_dimindex'] = 0;
317
+ $flag = true;
318
+ }
319
+ if ( ! isset( $this->options['ga_pubyearmonth_dimindex'] ) ) {
320
+ $this->options['ga_pubyearmonth_dimindex'] = 0;
321
+ $flag = true;
322
+ }
323
+ if ( ! isset( $this->options['ga_event_affiliates'] ) ) {
324
+ $this->options['ga_event_affiliates'] = '/out/';
325
+ $flag = true;
326
+ }
327
+ if ( ! isset( $this->options['ga_aff_tracking'] ) ) {
328
+ $this->options['ga_aff_tracking'] = 0;
329
+ $flag = true;
330
+ }
331
+ if ( ! isset( $this->options['ga_hash_tracking'] ) ) {
332
+ $this->options['ga_hash_tracking'] = 0;
333
+ $flag = true;
334
+ }
335
+ if ( ! isset( $this->options['backend_item_reports'] ) ) { // v4.8
336
+ $this->options['backend_item_reports'] = 1;
337
+ $flag = true;
338
+ }
339
+ if ( isset( $this->options['ga_dash_default_metric'] ) ) { // v4.8.1
340
+ unset( $this->options['ga_dash_default_metric'] );
341
+ $flag = true;
342
+ }
343
+ if ( isset( $this->options['ga_dash_default_dimension'] ) ) { // v4.8.1
344
+ unset( $this->options['ga_dash_default_dimension'] );
345
+ $flag = true;
346
+ }
347
+ if ( isset( $this->options['item_reports'] ) ) { // v4.8
348
+ $this->options['backend_item_reports'] = $this->options['item_reports'];
349
+ unset( $this->options['item_reports'] );
350
+ $flag = true;
351
+ }
352
+ if ( isset( $this->options['ga_dash_frontend_stats'] ) ) { // v4.8
353
+ $this->options['frontend_item_reports'] = $this->options['ga_dash_frontend_stats'];
354
+ unset( $this->options['ga_dash_frontend_stats'] );
355
+ $flag = true;
356
+ }
357
+ if ( ! isset( $this->options['dashboard_widget'] ) ) { // v4.7
358
+ $this->options['dashboard_widget'] = 1;
359
+ $flag = true;
360
+ }
361
+ if ( ! isset( $this->options['api_backoff'] ) ) { // v4.8.1.3
362
+ $this->options['api_backoff'] = 0;
363
+ $flag = true;
364
+ }
365
+ if ( ! isset( $this->options['pagetitle_404'] ) ) { // v4.9.4
366
+ $this->options['pagetitle_404'] = 'Page Not Found';
367
+ $flag = true;
368
+ }
369
+ if ( ! isset( $this->options['maps_api_key'] ) ) { // v4.9.4
370
+ $this->options['maps_api_key'] = '';
371
+ $flag = true;
372
+ }
373
+ if ( isset( $this->options['ga_tracking_code'] ) ) {
374
+ unset( $this->options['ga_tracking_code'] );
375
+ $flag = true;
376
+ }
377
+ if ( isset( $this->options['ga_dash_tableid'] ) ) { // v4.9
378
+ unset( $this->options['ga_dash_tableid'] );
379
+ $flag = true;
380
+ }
381
+ if ( isset( $this->options['ga_dash_frontend_keywords'] ) ) { // v4.8
382
+ unset( $this->options['ga_dash_frontend_keywords'] );
383
+ $flag = true;
384
+ }
385
+ if ( isset( $this->options['ga_dash_apikey'] ) ) { // v4.9.1.3
386
+ unset( $this->options['ga_dash_apikey'] );
387
+ $flag = true;
388
+ }
389
+ if ( isset( $this->options['ga_dash_jailadmins'] ) ) { // v4.7
390
+ if ( isset( $this->options['ga_dash_jailadmins'] ) ) {
391
+ $this->options['switch_profile'] = 0;
392
+ unset( $this->options['ga_dash_jailadmins'] );
393
+ $flag = true;
394
+ } else {
395
+ $this->options['switch_profile'] = 1;
396
+ unset( $this->options['ga_dash_jailadmins'] );
397
+ $flag = true;
398
+ }
399
+ }
400
+ if ( ! isset( $this->options['ga_cookiedomain'] ) ) {
401
+ $this->options['ga_cookiedomain'] = '';
402
+ $flag = true;
403
+ }
404
+ if ( ! isset( $this->options['ga_cookiedomain'] ) ) { // v4.9
405
+ $this->options['ga_cookiedomain'] = '';
406
+ $flag = true;
407
+ }
408
+ if ( ! isset( $this->options['ga_cookiename'] ) ) { // v4.9
409
+ $this->options['ga_cookiename'] = '';
410
+ $flag = true;
411
+ }
412
+ if ( ! isset( $this->options['ga_cookieexpires'] ) ) { // v4.9
413
+ $this->options['ga_cookieexpires'] = '';
414
+ $flag = true;
415
+ }
416
+
417
+ if ( $flag ) {
418
+ $this->set_plugin_options( false );
419
+ }
420
+ }
421
+ }
422
+ }
front/ajax-actions.php CHANGED
@@ -1,152 +1,152 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Frontend_Ajax' ) ) {
15
-
16
- final class GADWP_Frontend_Ajax {
17
-
18
- private $gadwp;
19
-
20
- public function __construct() {
21
- $this->gadwp = GADWP();
22
-
23
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) && $this->gadwp->config->options['frontend_item_reports'] ) {
24
- // Item Reports action
25
- add_action( 'wp_ajax_gadwp_frontend_item_reports', array( $this, 'ajax_item_reports' ) );
26
- }
27
-
28
- // Frontend Widget actions
29
- add_action( 'wp_ajax_ajax_frontwidget_report', array( $this, 'ajax_frontend_widget' ) );
30
- add_action( 'wp_ajax_nopriv_ajax_frontwidget_report', array( $this, 'ajax_frontend_widget' ) );
31
- }
32
-
33
- /**
34
- * Ajax handler for Item Reports
35
- *
36
- * @return string|int
37
- */
38
- public function ajax_item_reports() {
39
- if ( ! isset( $_POST['gadwp_security_frontend_item_reports'] ) || ! wp_verify_nonce( $_POST['gadwp_security_frontend_item_reports'], 'gadwp_frontend_item_reports' ) ) {
40
- wp_die( - 30 );
41
- }
42
-
43
- $from = $_POST['from'];
44
- $to = $_POST['to'];
45
- $query = $_POST['query'];
46
- $uri = $_POST['filter'];
47
-
48
- $query = $_POST['query'];
49
- if ( ob_get_length() ) {
50
- ob_clean();
51
- }
52
-
53
- if ( ! GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) || 0 == $this->gadwp->config->options['frontend_item_reports'] ) {
54
- wp_die( - 31 );
55
- }
56
-
57
- if ( $this->gadwp->config->options['ga_dash_token'] && $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
58
- if ( null === $this->gadwp->gapi_controller ) {
59
- $this->gadwp->gapi_controller = new GADWP_GAPI_Controller();
60
- }
61
- } else {
62
- wp_die( - 24 );
63
- }
64
-
65
- if ( $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
66
- $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
67
- } else {
68
- wp_die( - 26 );
69
- }
70
-
71
- $profile_info = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $projectId );
72
-
73
- if ( isset( $profile_info[4] ) ) {
74
- $this->gadwp->gapi_controller->timeshift = $profile_info[4];
75
- } else {
76
- $this->gadwp->gapi_controller->timeshift = (int) current_time( 'timestamp' ) - time();
77
- }
78
-
79
- $uri = '/' . ltrim( $uri, '/' );
80
-
81
- // allow URL correction before sending an API request
82
- $filter = apply_filters( 'gadwp_frontenditem_uri', $uri );
83
-
84
- $lastchar = substr( $filter, - 1 );
85
-
86
- if ( isset( $profile_info[6] ) && $profile_info[6] && $lastchar == '/' ) {
87
- $filter = $filter . $profile_info[6];
88
- }
89
-
90
- // Encode URL
91
- $filter = rawurlencode( rawurldecode( $filter ) );
92
-
93
- $queries = explode( ',', $query );
94
-
95
- $results = array();
96
-
97
- foreach ( $queries as $value ) {
98
- $results[] = $this->gadwp->gapi_controller->get( $projectId, $value, $from, $to, $filter );
99
- }
100
-
101
- wp_send_json( $results );
102
- }
103
-
104
- /**
105
- * Ajax handler for getting analytics data for frontend Widget
106
- *
107
- * @return string|int
108
- */
109
- public function ajax_frontend_widget() {
110
- if ( ! isset( $_POST['gadwp_number'] ) || ! isset( $_POST['gadwp_optionname'] ) || ! is_active_widget( false, false, 'gadwp-frontwidget-report' ) ) {
111
- wp_die( - 30 );
112
- }
113
- $widget_index = $_POST['gadwp_number'];
114
- $option_name = $_POST['gadwp_optionname'];
115
- $options = get_option( $option_name );
116
- if ( isset( $options[$widget_index] ) ) {
117
- $instance = $options[$widget_index];
118
- } else {
119
- wp_die( - 32 );
120
- }
121
- switch ( $instance['period'] ) { // make sure we have a valid request
122
- case '7daysAgo' :
123
- $period = '7daysAgo';
124
- break;
125
- case '14daysAgo' :
126
- $period = '14daysAgo';
127
- break;
128
- default :
129
- $period = '30daysAgo';
130
- break;
131
- }
132
- if ( ob_get_length() ) {
133
- ob_clean();
134
- }
135
- if ( $this->gadwp->config->options['ga_dash_token'] && $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
136
- if ( null === $this->gadwp->gapi_controller ) {
137
- $this->gadwp->gapi_controller = new GADWP_GAPI_Controller();
138
- }
139
- } else {
140
- wp_die( - 24 );
141
- }
142
- $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
143
- $profile_info = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $projectId );
144
- if ( isset( $profile_info[4] ) ) {
145
- $this->gadwp->gapi_controller->timeshift = $profile_info[4];
146
- } else {
147
- $this->gadwp->gapi_controller->timeshift = (int) current_time( 'timestamp' ) - time();
148
- }
149
- wp_send_json( $this->gadwp->gapi_controller->frontend_widget_stats( $projectId, $period, (int) $instance['anonim'] ) );
150
- }
151
- }
152
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Frontend_Ajax' ) ) {
15
+
16
+ final class GADWP_Frontend_Ajax {
17
+
18
+ private $gadwp;
19
+
20
+ public function __construct() {
21
+ $this->gadwp = GADWP();
22
+
23
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) && $this->gadwp->config->options['frontend_item_reports'] ) {
24
+ // Item Reports action
25
+ add_action( 'wp_ajax_gadwp_frontend_item_reports', array( $this, 'ajax_item_reports' ) );
26
+ }
27
+
28
+ // Frontend Widget actions
29
+ add_action( 'wp_ajax_ajax_frontwidget_report', array( $this, 'ajax_frontend_widget' ) );
30
+ add_action( 'wp_ajax_nopriv_ajax_frontwidget_report', array( $this, 'ajax_frontend_widget' ) );
31
+ }
32
+
33
+ /**
34
+ * Ajax handler for Item Reports
35
+ *
36
+ * @return string|int
37
+ */
38
+ public function ajax_item_reports() {
39
+ if ( ! isset( $_POST['gadwp_security_frontend_item_reports'] ) || ! wp_verify_nonce( $_POST['gadwp_security_frontend_item_reports'], 'gadwp_frontend_item_reports' ) ) {
40
+ wp_die( - 30 );
41
+ }
42
+
43
+ $from = $_POST['from'];
44
+ $to = $_POST['to'];
45
+ $query = $_POST['query'];
46
+ $uri = $_POST['filter'];
47
+
48
+ $query = $_POST['query'];
49
+ if ( ob_get_length() ) {
50
+ ob_clean();
51
+ }
52
+
53
+ if ( ! GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) || 0 == $this->gadwp->config->options['frontend_item_reports'] ) {
54
+ wp_die( - 31 );
55
+ }
56
+
57
+ if ( $this->gadwp->config->options['ga_dash_token'] && $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
58
+ if ( null === $this->gadwp->gapi_controller ) {
59
+ $this->gadwp->gapi_controller = new GADWP_GAPI_Controller();
60
+ }
61
+ } else {
62
+ wp_die( - 24 );
63
+ }
64
+
65
+ if ( $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
66
+ $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
67
+ } else {
68
+ wp_die( - 26 );
69
+ }
70
+
71
+ $profile_info = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $projectId );
72
+
73
+ if ( isset( $profile_info[4] ) ) {
74
+ $this->gadwp->gapi_controller->timeshift = $profile_info[4];
75
+ } else {
76
+ $this->gadwp->gapi_controller->timeshift = (int) current_time( 'timestamp' ) - time();
77
+ }
78
+
79
+ $uri = '/' . ltrim( $uri, '/' );
80
+
81
+ // allow URL correction before sending an API request
82
+ $filter = apply_filters( 'gadwp_frontenditem_uri', $uri );
83
+
84
+ $lastchar = substr( $filter, - 1 );
85
+
86
+ if ( isset( $profile_info[6] ) && $profile_info[6] && $lastchar == '/' ) {
87
+ $filter = $filter . $profile_info[6];
88
+ }
89
+
90
+ // Encode URL
91
+ $filter = rawurlencode( rawurldecode( $filter ) );
92
+
93
+ $queries = explode( ',', $query );
94
+
95
+ $results = array();
96
+
97
+ foreach ( $queries as $value ) {
98
+ $results[] = $this->gadwp->gapi_controller->get( $projectId, $value, $from, $to, $filter );
99
+ }
100
+
101
+ wp_send_json( $results );
102
+ }
103
+
104
+ /**
105
+ * Ajax handler for getting analytics data for frontend Widget
106
+ *
107
+ * @return string|int
108
+ */
109
+ public function ajax_frontend_widget() {
110
+ if ( ! isset( $_POST['gadwp_number'] ) || ! isset( $_POST['gadwp_optionname'] ) || ! is_active_widget( false, false, 'gadwp-frontwidget-report' ) ) {
111
+ wp_die( - 30 );
112
+ }
113
+ $widget_index = $_POST['gadwp_number'];
114
+ $option_name = $_POST['gadwp_optionname'];
115
+ $options = get_option( $option_name );
116
+ if ( isset( $options[$widget_index] ) ) {
117
+ $instance = $options[$widget_index];
118
+ } else {
119
+ wp_die( - 32 );
120
+ }
121
+ switch ( $instance['period'] ) { // make sure we have a valid request
122
+ case '7daysAgo' :
123
+ $period = '7daysAgo';
124
+ break;
125
+ case '14daysAgo' :
126
+ $period = '14daysAgo';
127
+ break;
128
+ default :
129
+ $period = '30daysAgo';
130
+ break;
131
+ }
132
+ if ( ob_get_length() ) {
133
+ ob_clean();
134
+ }
135
+ if ( $this->gadwp->config->options['ga_dash_token'] && $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
136
+ if ( null === $this->gadwp->gapi_controller ) {
137
+ $this->gadwp->gapi_controller = new GADWP_GAPI_Controller();
138
+ }
139
+ } else {
140
+ wp_die( - 24 );
141
+ }
142
+ $projectId = $this->gadwp->config->options['ga_dash_tableid_jail'];
143
+ $profile_info = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $projectId );
144
+ if ( isset( $profile_info[4] ) ) {
145
+ $this->gadwp->gapi_controller->timeshift = $profile_info[4];
146
+ } else {
147
+ $this->gadwp->gapi_controller->timeshift = (int) current_time( 'timestamp' ) - time();
148
+ }
149
+ wp_send_json( $this->gadwp->gapi_controller->frontend_widget_stats( $projectId, $period, (int) $instance['anonim'] ) );
150
+ }
151
+ }
152
+ }
front/css/item-reports.css CHANGED
@@ -1,185 +1,185 @@
1
- /**
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
-
9
- /* Frontend Item Reports */
10
- .column-gadwp_stats {
11
- width: 70px;
12
- }
13
-
14
- .gadwp-icon {
15
- color: #555;
16
- }
17
-
18
- .gadwp-icon:hover {
19
- color: #2ea2cc;
20
- }
21
-
22
- .gadwp-icon-oldwp {
23
- padding-top: 5px;
24
- }
25
-
26
- [id^=gadwp-container-] {
27
- width: 480px;
28
- }
29
-
30
- [id^=gadwp-areachart-] {
31
- height: 280px;
32
- }
33
-
34
- [id^=gadwp-progressbar-] {
35
- width: 100%;
36
- height: 3px;
37
- margin: 5px 0 0px 0;
38
- }
39
-
40
- [id^=gadwp-bottomstats-] {
41
- width: 100%;
42
- }
43
-
44
- [id^=gadwp-bottomstats-] .inside {
45
- display: table;
46
- margin: 0 auto;
47
- padding: 0px;
48
- }
49
-
50
- [id^=gadwp-bottomstats-] .inside .small-box {
51
- width: 31.2%;
52
- float: left;
53
- margin: 10px 5px 10px 5px;
54
- background: #fff;
55
- text-align: center;
56
- -moz-box-shadow: 0px 0px 7px 0px #BBB;
57
- -webkit-box-shadow: 0px 0px 7px 0px #BBB;
58
- box-shadow: 0px 0px 7px 0px #BBB;
59
- }
60
-
61
- [id^=gadwp-bottomstats-] .inside .small-box h3 {
62
- font-family: 'Open Sans', sans-serif;
63
- font-size: 1em;
64
- color: #777;
65
- padding: 0px 5px 0px 5px;
66
- margin: 0px 0px 0px 0px;
67
- text-overflow: ellipsis;
68
- overflow: hidden;
69
- white-space: nowrap;
70
- }
71
-
72
- [id^=gadwp-bottomstats-] .inside .small-box p {
73
- font-size: 1.2em;
74
- margin: 0px 0px 2px 0px;
75
- }
76
-
77
- .gadwp-floatwraper {
78
- display: table;
79
- width: 100%;
80
- height: 100%;
81
- }
82
-
83
- [id^=gadwp-piechart-].halfsize {
84
- width: 47%;
85
- margin: 10px 0 0 0;
86
- height: 200px;
87
- float: left;
88
- }
89
-
90
- [id^=gadwp-piechart-].floatleft {
91
- float: left;
92
- }
93
-
94
- [id^=gadwp-piechart-].floatright {
95
- float: right;
96
- }
97
-
98
- [id^=gadwp-tablechart-], [id^=gadwp-tablechart-] {
99
- margin: 10px 0 0 0;
100
- }
101
-
102
- .ui-dialog.gadwp {
103
- font-family: 'Open Sans', sans-serif;
104
- font-size: 13px;
105
- -webkit-box-sizing: initial;
106
- -moz-box-sizing: initial;
107
- }
108
-
109
- .ui-dialog.gadwp select {
110
- font-family: 'Open Sans', sans-serif;
111
- border: 1px solid #ddd;
112
- font-size: 14px;
113
- background: #fff;
114
- padding: 2px;
115
- color: #333;
116
- width: auto;
117
- }
118
-
119
- .ui-dialog.gadwp table {
120
- margin: auto;
121
- width: auto;
122
- }
123
-
124
- .gadwp .ui-dialog-titlebar {
125
- font-size: 1.1em;
126
- text-overflow: ellipsis;
127
- overflow: hidden;
128
- }
129
-
130
- @media screen and (max-width: 500px) {
131
- [id^=gadwp-container-] {
132
- width: 410px;
133
- }
134
- [id^=gadwp-bottomstats-] .inside .small-box {
135
- width: 30.8%;
136
- }
137
- }
138
-
139
- @media screen and (max-width: 410px) {
140
- [id^=gadwp-container-] {
141
- width: 260px;
142
- }
143
- [id^=gadwp-bottomstats-] .inside .small-box {
144
- width: 46%;
145
- }
146
- }
147
-
148
- /* Toolbar Node (Analytics menu item) */
149
- #wpadminbar #wp-admin-bar-gadwp-1>.ab-item:before {
150
- content: '\f239';
151
- top: 2px;
152
- }
153
-
154
- .no-font-face #wpadminbar #wp-admin-bar-gadwp-1>.ab-item {
155
- text-indent: 0;
156
- }
157
-
158
- @media screen and ( max-width: 782px ) {
159
- #wpadminbar #wp-admin-bar-gadwp-1>.ab-item {
160
- text-indent: 100%;
161
- white-space: nowrap;
162
- overflow: hidden;
163
- width: 52px;
164
- padding: 0;
165
- color: #999;
166
- position: relative;
167
- }
168
- #wpadminbar #wp-admin-bar-gadwp-1>.ab-item:before {
169
- display: block;
170
- text-indent: 0;
171
- font: normal 32px/1 'dashicons';
172
- speak: none;
173
- top: 7px;
174
- width: 52px;
175
- text-align: center;
176
- -webkit-font-smoothing: antialiased;
177
- -moz-osx-font-smoothing: grayscale;
178
- }
179
- #wpadminbar li#wp-admin-bar-gadwp-1 {
180
- display: block;
181
- }
182
- #wpadminbar #wp-admin-bar-gadwp-1 {
183
- position: static;
184
- }
185
  }
1
+ /**
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+
9
+ /* Frontend Item Reports */
10
+ .column-gadwp_stats {
11
+ width: 70px;
12
+ }
13
+
14
+ .gadwp-icon {
15
+ color: #555;
16
+ }
17
+
18
+ .gadwp-icon:hover {
19
+ color: #2ea2cc;
20
+ }
21
+
22
+ .gadwp-icon-oldwp {
23
+ padding-top: 5px;
24
+ }
25
+
26
+ [id^=gadwp-container-] {
27
+ width: 480px;
28
+ }
29
+
30
+ [id^=gadwp-areachart-] {
31
+ height: 280px;
32
+ }
33
+
34
+ [id^=gadwp-progressbar-] {
35
+ width: 100%;
36
+ height: 3px;
37
+ margin: 5px 0 0px 0;
38
+ }
39
+
40
+ [id^=gadwp-bottomstats-] {
41
+ width: 100%;
42
+ }
43
+
44
+ [id^=gadwp-bottomstats-] .inside {
45
+ display: table;
46
+ margin: 0 auto;
47
+ padding: 0px;
48
+ }
49
+
50
+ [id^=gadwp-bottomstats-] .inside .small-box {
51
+ width: 31.2%;
52
+ float: left;
53
+ margin: 10px 5px 10px 5px;
54
+ background: #fff;
55
+ text-align: center;
56
+ -moz-box-shadow: 0px 0px 7px 0px #BBB;
57
+ -webkit-box-shadow: 0px 0px 7px 0px #BBB;
58
+ box-shadow: 0px 0px 7px 0px #BBB;
59
+ }
60
+
61
+ [id^=gadwp-bottomstats-] .inside .small-box h3 {
62
+ font-family: 'Open Sans', sans-serif;
63
+ font-size: 1em;
64
+ color: #777;
65
+ padding: 0px 5px 0px 5px;
66
+ margin: 0px 0px 0px 0px;
67
+ text-overflow: ellipsis;
68
+ overflow: hidden;
69
+ white-space: nowrap;
70
+ }
71
+
72
+ [id^=gadwp-bottomstats-] .inside .small-box p {
73
+ font-size: 1.2em;
74
+ margin: 0px 0px 2px 0px;
75
+ }
76
+
77
+ .gadwp-floatwraper {
78
+ display: table;
79
+ width: 100%;
80
+ height: 100%;
81
+ }
82
+
83
+ [id^=gadwp-piechart-].halfsize {
84
+ width: 47%;
85
+ margin: 10px 0 0 0;
86
+ height: 200px;
87
+ float: left;
88
+ }
89
+
90
+ [id^=gadwp-piechart-].floatleft {
91
+ float: left;
92
+ }
93
+
94
+ [id^=gadwp-piechart-].floatright {
95
+ float: right;
96
+ }
97
+
98
+ [id^=gadwp-tablechart-], [id^=gadwp-tablechart-] {
99
+ margin: 10px 0 0 0;
100
+ }
101
+
102
+ .ui-dialog.gadwp {
103
+ font-family: 'Open Sans', sans-serif;
104
+ font-size: 13px;
105
+ -webkit-box-sizing: initial;
106
+ -moz-box-sizing: initial;
107
+ }
108
+
109
+ .ui-dialog.gadwp select {
110
+ font-family: 'Open Sans', sans-serif;
111
+ border: 1px solid #ddd;
112
+ font-size: 14px;
113
+ background: #fff;
114
+ padding: 2px;
115
+ color: #333;
116
+ width: auto;
117
+ }
118
+
119
+ .ui-dialog.gadwp table {
120
+ margin: auto;
121
+ width: auto;
122
+ }
123
+
124
+ .gadwp .ui-dialog-titlebar {
125
+ font-size: 1.1em;
126
+ text-overflow: ellipsis;
127
+ overflow: hidden;
128
+ }
129
+
130
+ @media screen and (max-width: 500px) {
131
+ [id^=gadwp-container-] {
132
+ width: 410px;
133
+ }
134
+ [id^=gadwp-bottomstats-] .inside .small-box {
135
+ width: 30.8%;
136
+ }
137
+ }
138
+
139
+ @media screen and (max-width: 410px) {
140
+ [id^=gadwp-container-] {
141
+ width: 260px;
142
+ }
143
+ [id^=gadwp-bottomstats-] .inside .small-box {
144
+ width: 46%;
145
+ }
146
+ }
147
+
148
+ /* Toolbar Node (Analytics menu item) */
149
+ #wpadminbar #wp-admin-bar-gadwp-1>.ab-item:before {
150
+ content: '\f239';
151
+ top: 2px;
152
+ }
153
+
154
+ .no-font-face #wpadminbar #wp-admin-bar-gadwp-1>.ab-item {
155
+ text-indent: 0;
156
+ }
157
+
158
+ @media screen and ( max-width: 782px ) {
159
+ #wpadminbar #wp-admin-bar-gadwp-1>.ab-item {
160
+ text-indent: 100%;
161
+ white-space: nowrap;
162
+ overflow: hidden;
163
+ width: 52px;
164
+ padding: 0;
165
+ color: #999;
166
+ position: relative;
167
+ }
168
+ #wpadminbar #wp-admin-bar-gadwp-1>.ab-item:before {
169
+ display: block;
170
+ text-indent: 0;
171
+ font: normal 32px/1 'dashicons';
172
+ speak: none;
173
+ top: 7px;
174
+ width: 52px;
175
+ text-align: center;
176
+ -webkit-font-smoothing: antialiased;
177
+ -moz-osx-font-smoothing: grayscale;
178
+ }
179
+ #wpadminbar li#wp-admin-bar-gadwp-1 {
180
+ display: block;
181
+ }
182
+ #wpadminbar #wp-admin-bar-gadwp-1 {
183
+ position: static;
184
+ }
185
  }
front/css/widgets.css CHANGED
@@ -1,75 +1,75 @@
1
- /**
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
- #gadwp {
9
- font-family: 'Open Sans', sans-serif;
10
- }
11
-
12
- #gadwp-searches td {
13
- line-height: 1.5em;
14
- padding: 2px;
15
- font-size: 1em;
16
- }
17
-
18
- #gadwp-searches {
19
- line-height: 10px;
20
- margin-top: 15px;
21
- }
22
-
23
- #gadwp-visits {
24
- height: 200px;
25
- margin-top: 15px;
26
- }
27
-
28
- #gadwp-content {
29
- width: 100%;
30
- }
31
-
32
- #gadwp-title {
33
- text-transform: uppercase;
34
- font-weight: 600;
35
- font-size: 14px;
36
- padding-bottom: 2px;
37
- }
38
-
39
- #gadwp-widget {
40
- padding: 0 5px;
41
- }
42
-
43
- #gadwp-widgetchart {
44
- width: 100%;
45
- }
46
-
47
- #gadwp-widgettotals {
48
- margin: 0 0 10px 0;
49
- width: 100%;
50
- display: table;
51
- clear: both;
52
- }
53
-
54
- #gadwp-widgettotals .gadwp-left {
55
- padding: 10px 0 0 0;
56
- width: 45%;
57
- float: left;
58
- font-weight: 600;
59
- }
60
-
61
- #gadwp-progressbar {
62
- width: 100%;
63
- height: 3px;
64
- margin: 3px 0;
65
- }
66
-
67
- #gadwp-widgettotals .gadwp-right {
68
- padding: 10px 0 0 0;
69
- float: left;
70
- font-style: italic;
71
- }
72
-
73
- .widget_gadwp-frontwidget-report h2.widget-title {
74
- margin-bottom: 0px;
75
  }
1
+ /**
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+ #gadwp {
9
+ font-family: 'Open Sans', sans-serif;
10
+ }
11
+
12
+ #gadwp-searches td {
13
+ line-height: 1.5em;
14
+ padding: 2px;
15
+ font-size: 1em;
16
+ }
17
+
18
+ #gadwp-searches {
19
+ line-height: 10px;
20
+ margin-top: 15px;
21
+ }
22
+
23
+ #gadwp-visits {
24
+ height: 200px;
25
+ margin-top: 15px;
26
+ }
27
+
28
+ #gadwp-content {
29
+ width: 100%;
30
+ }
31
+
32
+ #gadwp-title {
33
+ text-transform: uppercase;
34
+ font-weight: 600;
35
+ font-size: 14px;
36
+ padding-bottom: 2px;
37
+ }
38
+
39
+ #gadwp-widget {
40
+ padding: 0 5px;
41
+ }
42
+
43
+ #gadwp-widgetchart {
44
+ width: 100%;
45
+ }
46
+
47
+ #gadwp-widgettotals {
48
+ margin: 0 0 10px 0;
49
+ width: 100%;
50
+ display: table;
51
+ clear: both;
52
+ }
53
+
54
+ #gadwp-widgettotals .gadwp-left {
55
+ padding: 10px 0 0 0;
56
+ width: 45%;
57
+ float: left;
58
+ font-weight: 600;
59
+ }
60
+
61
+ #gadwp-progressbar {
62
+ width: 100%;
63
+ height: 3px;
64
+ margin: 3px 0;
65
+ }
66
+
67
+ #gadwp-widgettotals .gadwp-right {
68
+ padding: 10px 0 0 0;
69
+ float: left;
70
+ font-style: italic;
71
+ }
72
+
73
+ .widget_gadwp-frontwidget-report h2.widget-title {
74
+ margin-bottom: 0px;
75
  }
front/item-reports.php CHANGED
@@ -1,38 +1,38 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Frontend_Item_Reports' ) ) {
15
-
16
- final class GADWP_Frontend_Item_Reports {
17
-
18
- private $gadwp;
19
-
20
- public function __construct() {
21
- $this->gadwp = GADWP();
22
-
23
- add_action( 'admin_bar_menu', array( $this, 'custom_adminbar_node' ), 999 );
24
- }
25
-
26
- function custom_adminbar_node( $wp_admin_bar ) {
27
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) && $this->gadwp->config->options['frontend_item_reports'] ) {
28
- /* @formatter:off */
29
- $args = array( 'id' => 'gadwp-1',
30
- 'title' => '<span class="ab-icon"></span><span class="">' . __( "Analytics", 'google-analytics-dashboard-for-wp' ) . '</span>',
31
- 'href' => '#1',
32
- );
33
- /* @formatter:on */
34
- $wp_admin_bar->add_node( $args );
35
- }
36
- }
37
- }
38
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Frontend_Item_Reports' ) ) {
15
+
16
+ final class GADWP_Frontend_Item_Reports {
17
+
18
+ private $gadwp;
19
+
20
+ public function __construct() {
21
+ $this->gadwp = GADWP();
22
+
23
+ add_action( 'admin_bar_menu', array( $this, 'custom_adminbar_node' ), 999 );
24
+ }
25
+
26
+ function custom_adminbar_node( $wp_admin_bar ) {
27
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) && $this->gadwp->config->options['frontend_item_reports'] ) {
28
+ /* @formatter:off */
29
+ $args = array( 'id' => 'gadwp-1',
30
+ 'title' => '<span class="ab-icon"></span><span class="">' . __( "Analytics", 'google-analytics-dashboard-for-wp' ) . '</span>',
31
+ 'href' => '#1',
32
+ );
33
+ /* @formatter:on */
34
+ $wp_admin_bar->add_node( $args );
35
+ }
36
+ }
37
+ }
38
+ }
front/js/widgets.js CHANGED
@@ -1,13 +1,13 @@
1
- /*-
2
- * Author: Alin Marcu
3
- * Author URI: https://deconf.com
4
- * Copyright 2013 Alin Marcu
5
- * License: GPLv2 or later
6
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
- */
8
-
9
- jQuery( window ).resize( function () {
10
- if ( typeof gadwp_drawFrontWidgetChart == "function" && typeof gadwpFrontWidgetData !== 'undefined' && !jQuery.isNumeric( gadwpFrontWidgetData ) ) {
11
- gadwp_drawFrontWidgetChart( gadwpFrontWidgetData );
12
- }
13
  } );
1
+ /*-
2
+ * Author: Alin Marcu
3
+ * Author URI: https://deconf.com
4
+ * Copyright 2013 Alin Marcu
5
+ * License: GPLv2 or later
6
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
7
+ */
8
+
9
+ jQuery( window ).resize( function () {
10
+ if ( typeof gadwp_drawFrontWidgetChart == "function" && typeof gadwpFrontWidgetData !== 'undefined' && !jQuery.isNumeric( gadwpFrontWidgetData ) ) {
11
+ gadwp_drawFrontWidgetChart( gadwpFrontWidgetData );
12
+ }
13
  } );
front/setup.php CHANGED
@@ -1,123 +1,123 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Frontend_Setup' ) ) {
15
-
16
- final class GADWP_Frontend_Setup {
17
-
18
- private $gadwp;
19
-
20
- public function __construct() {
21
- $this->gadwp = GADWP();
22
-
23
- // Styles & Scripts
24
- add_action( 'wp_enqueue_scripts', array( $this, 'load_styles_scripts' ) );
25
- }
26
-
27
- /**
28
- * Styles & Scripts conditional loading
29
- *
30
- * @param
31
- * $hook
32
- */
33
- public function load_styles_scripts() {
34
- $lang = get_bloginfo( 'language' );
35
- $lang = explode( '-', $lang );
36
- $lang = $lang[0];
37
-
38
- /*
39
- * Item reports Styles & Scripts
40
- */
41
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) && $this->gadwp->config->options['frontend_item_reports'] ) {
42
-
43
- wp_enqueue_style( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.css', null, GADWP_CURRENT_VERSION );
44
-
45
- wp_enqueue_style( 'gadwp-frontend-item-reports', GADWP_URL . 'front/css/item-reports.css', null, GADWP_CURRENT_VERSION );
46
-
47
- $country_codes = GADWP_Tools::get_countrycodes();
48
- if ( $this->gadwp->config->options['ga_target_geomap'] && isset( $country_codes[$this->gadwp->config->options['ga_target_geomap']] ) ) {
49
- $region = $this->gadwp->config->options['ga_target_geomap'];
50
- } else {
51
- $region = false;
52
- }
53
-
54
- wp_enqueue_style( "wp-jquery-ui-dialog" );
55
-
56
- wp_register_script( 'googlecharts', 'https://www.gstatic.com/charts/loader.js', array(), null );
57
-
58
- wp_enqueue_script( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.js', array( 'jquery' ), GADWP_CURRENT_VERSION );
59
-
60
- wp_enqueue_script( 'gadwp-frontend-item-reports', GADWP_URL . 'common/js/reports.js', array( 'gadwp-nprogress', 'googlecharts', 'jquery', 'jquery-ui-dialog' ), GADWP_CURRENT_VERSION, true );
61
-
62
- /* @formatter:off */
63
- wp_localize_script( 'gadwp-frontend-item-reports', 'gadwpItemData', array(
64
- 'ajaxurl' => admin_url( 'admin-ajax.php' ),
65
- 'security' => wp_create_nonce( 'gadwp_frontend_item_reports' ),
66
- 'dateList' => array(
67
- 'today' => __( "Today", 'google-analytics-dashboard-for-wp' ),
68
- 'yesterday' => __( "Yesterday", 'google-analytics-dashboard-for-wp' ),
69
- '7daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 7 ),
70
- '14daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 14 ),
71
- '30daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 30 ),
72
- '90daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 90 ),
73
- '365daysAgo' => sprintf( _n( "%s Year", "%s Years", 1, 'google-analytics-dashboard-for-wp' ), __('One', 'google-analytics-dashboard-for-wp') ),
74
- '1095daysAgo' => sprintf( _n( "%s Year", "%s Years", 3, 'google-analytics-dashboard-for-wp' ), __('Three', 'google-analytics-dashboard-for-wp') ),
75
- ),
76
- 'reportList' => array(
77
- 'sessions' => __( "Sessions", 'google-analytics-dashboard-for-wp' ),
78
- 'users' => __( "Users", 'google-analytics-dashboard-for-wp' ),
79
- 'organicSearches' => __( "Organic", 'google-analytics-dashboard-for-wp' ),
80
- 'pageviews' => __( "Page Views", 'google-analytics-dashboard-for-wp' ),
81
- 'visitBounceRate' => __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
82
- 'locations' => __( "Location", 'google-analytics-dashboard-for-wp' ),
83
- 'referrers' => __( "Referrers", 'google-analytics-dashboard-for-wp' ),
84
- 'searches' => __( "Searches", 'google-analytics-dashboard-for-wp' ),
85
- 'trafficdetails' => __( "Traffic", 'google-analytics-dashboard-for-wp' ),
86
- 'technologydetails' => __( "Technology", 'google-analytics-dashboard-for-wp' ),
87
- ),
88
- 'i18n' => array(
89
- __( "A JavaScript Error is blocking plugin resources!", 'google-analytics-dashboard-for-wp' ), //0
90
- __( "Traffic Mediums", 'google-analytics-dashboard-for-wp' ),
91
- __( "Visitor Type", 'google-analytics-dashboard-for-wp' ),
92
- __( "Search Engines", 'google-analytics-dashboard-for-wp' ),
93
- __( "Social Networks", 'google-analytics-dashboard-for-wp' ),
94
- __( "Sessions", 'google-analytics-dashboard-for-wp' ),
95
- __( "Users", 'google-analytics-dashboard-for-wp' ),
96
- __( "Page Views", 'google-analytics-dashboard-for-wp' ),
97
- __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
98
- __( "Organic Search", 'google-analytics-dashboard-for-wp' ),
99
- __( "Pages/Session", 'google-analytics-dashboard-for-wp' ),
100
- __( "Invalid response", 'google-analytics-dashboard-for-wp' ),
101
- __( "Not enough data collected", 'google-analytics-dashboard-for-wp' ),
102
- __( "This report is unavailable", 'google-analytics-dashboard-for-wp' ),
103
- __( "report generated by", 'google-analytics-dashboard-for-wp' ), //14
104
- __( "This plugin needs an authorization:", 'google-analytics-dashboard-for-wp' ) . ' <strong>' . __( "authorize the plugin", 'google-analytics-dashboard-for-wp' ) . '</strong>!',
105
- __( "Browser", 'google-analytics-dashboard-for-wp' ), //16
106
- __( "Operating System", 'google-analytics-dashboard-for-wp' ),
107
- __( "Screen Resolution", 'google-analytics-dashboard-for-wp' ),
108
- __( "Mobile Brand", 'google-analytics-dashboard-for-wp' ),
109
- ),
110
- 'colorVariations' => GADWP_Tools::variations( $this->gadwp->config->options['ga_dash_style'] ),
111
- 'region' => $region,
112
- 'mapsApiKey' => $this->gadwp->config->options['maps_api_key'],
113
- 'language' => get_bloginfo( 'language' ),
114
- 'filter' => $_SERVER["REQUEST_URI"],
115
- 'viewList' => false,
116
- 'scope' => 'front-item',
117
- )
118
- );
119
- /* @formatter:on */
120
- }
121
- }
122
- }
123
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Frontend_Setup' ) ) {
15
+
16
+ final class GADWP_Frontend_Setup {
17
+
18
+ private $gadwp;
19
+
20
+ public function __construct() {
21
+ $this->gadwp = GADWP();
22
+
23
+ // Styles & Scripts
24
+ add_action( 'wp_enqueue_scripts', array( $this, 'load_styles_scripts' ) );
25
+ }
26
+
27
+ /**
28
+ * Styles & Scripts conditional loading
29
+ *
30
+ * @param
31
+ * $hook
32
+ */
33
+ public function load_styles_scripts() {
34
+ $lang = get_bloginfo( 'language' );
35
+ $lang = explode( '-', $lang );
36
+ $lang = $lang[0];
37
+
38
+ /*
39
+ * Item reports Styles & Scripts
40
+ */
41
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_dash_access_front'] ) && $this->gadwp->config->options['frontend_item_reports'] ) {
42
+
43
+ wp_enqueue_style( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.css', null, GADWP_CURRENT_VERSION );
44
+
45
+ wp_enqueue_style( 'gadwp-frontend-item-reports', GADWP_URL . 'front/css/item-reports.css', null, GADWP_CURRENT_VERSION );
46
+
47
+ $country_codes = GADWP_Tools::get_countrycodes();
48
+ if ( $this->gadwp->config->options['ga_target_geomap'] && isset( $country_codes[$this->gadwp->config->options['ga_target_geomap']] ) ) {
49
+ $region = $this->gadwp->config->options['ga_target_geomap'];
50
+ } else {
51
+ $region = false;
52
+ }
53
+
54
+ wp_enqueue_style( "wp-jquery-ui-dialog" );
55
+
56
+ wp_register_script( 'googlecharts', 'https://www.gstatic.com/charts/loader.js', array(), null );
57
+
58
+ wp_enqueue_script( 'gadwp-nprogress', GADWP_URL . 'common/nprogress/nprogress.js', array( 'jquery' ), GADWP_CURRENT_VERSION );
59
+
60
+ wp_enqueue_script( 'gadwp-frontend-item-reports', GADWP_URL . 'common/js/reports.js', array( 'gadwp-nprogress', 'googlecharts', 'jquery', 'jquery-ui-dialog' ), GADWP_CURRENT_VERSION, true );
61
+
62
+ /* @formatter:off */
63
+ wp_localize_script( 'gadwp-frontend-item-reports', 'gadwpItemData', array(
64
+ 'ajaxurl' => admin_url( 'admin-ajax.php' ),
65
+ 'security' => wp_create_nonce( 'gadwp_frontend_item_reports' ),
66
+ 'dateList' => array(
67
+ 'today' => __( "Today", 'google-analytics-dashboard-for-wp' ),
68
+ 'yesterday' => __( "Yesterday", 'google-analytics-dashboard-for-wp' ),
69
+ '7daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 7 ),
70
+ '14daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 14 ),
71
+ '30daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 30 ),
72
+ '90daysAgo' => sprintf( __( "Last %d Days", 'google-analytics-dashboard-for-wp' ), 90 ),
73
+ '365daysAgo' => sprintf( _n( "%s Year", "%s Years", 1, 'google-analytics-dashboard-for-wp' ), __('One', 'google-analytics-dashboard-for-wp') ),
74
+ '1095daysAgo' => sprintf( _n( "%s Year", "%s Years", 3, 'google-analytics-dashboard-for-wp' ), __('Three', 'google-analytics-dashboard-for-wp') ),
75
+ ),
76
+ 'reportList' => array(
77
+ 'sessions' => __( "Sessions", 'google-analytics-dashboard-for-wp' ),
78
+ 'users' => __( "Users", 'google-analytics-dashboard-for-wp' ),
79
+ 'organicSearches' => __( "Organic", 'google-analytics-dashboard-for-wp' ),
80
+ 'pageviews' => __( "Page Views", 'google-analytics-dashboard-for-wp' ),
81
+ 'visitBounceRate' => __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
82
+ 'locations' => __( "Location", 'google-analytics-dashboard-for-wp' ),
83
+ 'referrers' => __( "Referrers", 'google-analytics-dashboard-for-wp' ),
84
+ 'searches' => __( "Searches", 'google-analytics-dashboard-for-wp' ),
85
+ 'trafficdetails' => __( "Traffic", 'google-analytics-dashboard-for-wp' ),
86
+ 'technologydetails' => __( "Technology", 'google-analytics-dashboard-for-wp' ),
87
+ ),
88
+ 'i18n' => array(
89
+ __( "A JavaScript Error is blocking plugin resources!", 'google-analytics-dashboard-for-wp' ), //0
90
+ __( "Traffic Mediums", 'google-analytics-dashboard-for-wp' ),
91
+ __( "Visitor Type", 'google-analytics-dashboard-for-wp' ),
92
+ __( "Search Engines", 'google-analytics-dashboard-for-wp' ),
93
+ __( "Social Networks", 'google-analytics-dashboard-for-wp' ),
94
+ __( "Sessions", 'google-analytics-dashboard-for-wp' ),
95
+ __( "Users", 'google-analytics-dashboard-for-wp' ),
96
+ __( "Page Views", 'google-analytics-dashboard-for-wp' ),
97
+ __( "Bounce Rate", 'google-analytics-dashboard-for-wp' ),
98
+ __( "Organic Search", 'google-analytics-dashboard-for-wp' ),
99
+ __( "Pages/Session", 'google-analytics-dashboard-for-wp' ),
100
+ __( "Invalid response", 'google-analytics-dashboard-for-wp' ),
101
+ __( "Not enough data collected", 'google-analytics-dashboard-for-wp' ),
102
+ __( "This report is unavailable", 'google-analytics-dashboard-for-wp' ),
103
+ __( "report generated by", 'google-analytics-dashboard-for-wp' ), //14
104
+ __( "This plugin needs an authorization:", 'google-analytics-dashboard-for-wp' ) . ' <strong>' . __( "authorize the plugin", 'google-analytics-dashboard-for-wp' ) . '</strong>!',
105
+ __( "Browser", 'google-analytics-dashboard-for-wp' ), //16
106
+ __( "Operating System", 'google-analytics-dashboard-for-wp' ),
107
+ __( "Screen Resolution", 'google-analytics-dashboard-for-wp' ),
108
+ __( "Mobile Brand", 'google-analytics-dashboard-for-wp' ),
109
+ ),
110
+ 'colorVariations' => GADWP_Tools::variations( $this->gadwp->config->options['ga_dash_style'] ),
111
+ 'region' => $region,
112
+ 'mapsApiKey' => $this->gadwp->config->options['maps_api_key'],
113
+ 'language' => get_bloginfo( 'language' ),
114
+ 'filter' => $_SERVER["REQUEST_URI"],
115
+ 'viewList' => false,
116
+ 'scope' => 'front-item',
117
+ )
118
+ );
119
+ /* @formatter:on */
120
+ }
121
+ }
122
+ }
123
+ }
front/tracking.php CHANGED
@@ -1,64 +1,64 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_Tracking' ) ) {
15
-
16
- class GADWP_Tracking {
17
-
18
- private $gadwp;
19
-
20
- public function __construct() {
21
- $this->gadwp = GADWP();
22
-
23
- add_action( 'wp_head', array( $this, 'tracking_code' ), 99 );
24
- add_action( 'wp_enqueue_scripts', array( $this, 'load_scripts' ) );
25
- }
26
-
27
- public function load_scripts() {
28
- if ( $this->gadwp->config->options['ga_event_tracking'] ) {
29
- if ( wp_script_is( 'jquery' ) ) {
30
- wp_dequeue_script( 'jquery' );
31
- }
32
- wp_enqueue_script( 'jquery' );
33
- }
34
- }
35
-
36
- public function tracking_code() {
37
- if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_track_exclude'], true ) || ( $this->gadwp->config->options['ga_dash_excludesa'] && current_user_can( 'manage_network' ) ) ) {
38
- return;
39
- }
40
- $traking_mode = $this->gadwp->config->options['ga_dash_tracking'];
41
- $traking_type = $this->gadwp->config->options['ga_dash_tracking_type'];
42
- if ( $traking_mode > 0 ) {
43
- if ( ! $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
44
- return;
45
- }
46
- if ( $traking_type == "classic" ) {
47
- echo "\n<!-- BEGIN GADWP v" . GADWP_CURRENT_VERSION . " Classic Tracking - https://deconf.com/google-analytics-dashboard-wordpress/ -->\n";
48
- if ( $this->gadwp->config->options['ga_event_tracking'] ) {
49
- require_once 'tracking/events-classic.php';
50
- }
51
- require_once 'tracking/code-classic.php';
52
- echo "\n<!-- END GADWP Classic Tracking -->\n\n";
53
- } else {
54
- echo "\n<!-- BEGIN GADWP v" . GADWP_CURRENT_VERSION . " Universal Tracking - https://deconf.com/google-analytics-dashboard-wordpress/ -->\n";
55
- if ( $this->gadwp->config->options['ga_event_tracking'] || $this->gadwp->config->options['ga_aff_tracking'] || $this->gadwp->config->options['ga_hash_tracking'] ) {
56
- require_once 'tracking/events-universal.php';
57
- }
58
- require_once 'tracking/code-universal.php';
59
- echo "\n<!-- END GADWP Universal Tracking -->\n\n";
60
- }
61
- }
62
- }
63
- }
64
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_Tracking' ) ) {
15
+
16
+ class GADWP_Tracking {
17
+
18
+ private $gadwp;
19
+
20
+ public function __construct() {
21
+ $this->gadwp = GADWP();
22
+
23
+ add_action( 'wp_head', array( $this, 'tracking_code' ), 99 );
24
+ add_action( 'wp_enqueue_scripts', array( $this, 'load_scripts' ) );
25
+ }
26
+
27
+ public function load_scripts() {
28
+ if ( $this->gadwp->config->options['ga_event_tracking'] ) {
29
+ if ( wp_script_is( 'jquery' ) ) {
30
+ wp_dequeue_script( 'jquery' );
31
+ }
32
+ wp_enqueue_script( 'jquery' );
33
+ }
34
+ }
35
+
36
+ public function tracking_code() {
37
+ if ( GADWP_Tools::check_roles( $this->gadwp->config->options['ga_track_exclude'], true ) || ( $this->gadwp->config->options['ga_dash_excludesa'] && current_user_can( 'manage_network' ) ) ) {
38
+ return;
39
+ }
40
+ $traking_mode = $this->gadwp->config->options['ga_dash_tracking'];
41
+ $traking_type = $this->gadwp->config->options['ga_dash_tracking_type'];
42
+ if ( $traking_mode > 0 ) {
43
+ if ( ! $this->gadwp->config->options['ga_dash_tableid_jail'] ) {
44
+ return;
45
+ }
46
+ if ( $traking_type == "classic" ) {
47
+ echo "\n<!-- BEGIN GADWP v" . GADWP_CURRENT_VERSION . " Classic Tracking - https://deconf.com/google-analytics-dashboard-wordpress/ -->\n";
48
+ if ( $this->gadwp->config->options['ga_event_tracking'] ) {
49
+ require_once 'tracking/events-classic.php';
50
+ }
51
+ require_once 'tracking/code-classic.php';
52
+ echo "\n<!-- END GADWP Classic Tracking -->\n\n";
53
+ } else {
54
+ echo "\n<!-- BEGIN GADWP v" . GADWP_CURRENT_VERSION . " Universal Tracking - https://deconf.com/google-analytics-dashboard-wordpress/ -->\n";
55
+ if ( $this->gadwp->config->options['ga_event_tracking'] || $this->gadwp->config->options['ga_aff_tracking'] || $this->gadwp->config->options['ga_hash_tracking'] ) {
56
+ require_once 'tracking/events-universal.php';
57
+ }
58
+ require_once 'tracking/code-universal.php';
59
+ echo "\n<!-- END GADWP Universal Tracking -->\n\n";
60
+ }
61
+ }
62
+ }
63
+ }
64
+ }
front/tracking/code-classic.php CHANGED
@@ -1,34 +1,34 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- $profile = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $this->gadwp->config->options['ga_dash_tableid_jail'] );
15
- ?>
16
- <script type="text/javascript">
17
- var _gaq = _gaq || [];
18
- <?php if ($this->gadwp->config->options ['ga_enhanced_links']) {?>
19
- var pluginUrl = '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
20
- _gaq.push(['_require', 'inpage_linkid', pluginUrl]);
21
- <?php }?>
22
- _gaq.push(['_setAccount', '<?php echo esc_html($profile[2]); ?>']);
23
- _gaq.push(['_trackPageview']<?php if ($this->gadwp->config->options ['ga_dash_anonim']) {?>, ['_gat._anonymizeIp']<?php }?>);
24
-
25
- (function() {
26
- var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
27
- <?php if ($this->gadwp->config->options ['ga_dash_remarketing']) { ?>
28
- ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
29
- <?php }else{?>
30
- ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
31
- <?php }?>
32
- var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
33
- })();
34
  </script>
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ $profile = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $this->gadwp->config->options['ga_dash_tableid_jail'] );
15
+ ?>
16
+ <script type="text/javascript">
17
+ var _gaq = _gaq || [];
18
+ <?php if ($this->gadwp->config->options ['ga_enhanced_links']) {?>
19
+ var pluginUrl = '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
20
+ _gaq.push(['_require', 'inpage_linkid', pluginUrl]);
21
+ <?php }?>
22
+ _gaq.push(['_setAccount', '<?php echo esc_html($profile[2]); ?>']);
23
+ _gaq.push(['_trackPageview']<?php if ($this->gadwp->config->options ['ga_dash_anonim']) {?>, ['_gat._anonymizeIp']<?php }?>);
24
+
25
+ (function() {
26
+ var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
27
+ <?php if ($this->gadwp->config->options ['ga_dash_remarketing']) { ?>
28
+ ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
29
+ <?php }else{?>
30
+ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
31
+ <?php }?>
32
+ var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
33
+ })();
34
  </script>
front/tracking/code-universal.php CHANGED
@@ -1,138 +1,138 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- $profile = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $this->gadwp->config->options['ga_dash_tableid_jail'] );
15
- ?>
16
- <script>
17
- (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
18
- (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
19
- m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
20
- })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
21
- <?php
22
- $create_options = '{';
23
- if ( $this->gadwp->config->options['ga_speed_samplerate'] != 1 ) {
24
- $create_options .= "'siteSpeedSampleRate' : " . (int) $this->gadwp->config->options['ga_speed_samplerate'];
25
- }
26
- if ( $this->gadwp->config->options['ga_crossdomain_tracking'] && $this->gadwp->config->options['ga_crossdomain_list'] != '' ) {
27
- if ( $create_options != '{' ) {
28
- $create_options .= ', ';
29
- }
30
- $create_options .= "'allowLinker' : true";
31
- }
32
- $create_options .= '}';
33
-
34
- $options = "'auto'";
35
- $optionsArray = array();
36
- if ( ! empty( $this->gadwp->config->options['ga_cookiedomain'] ) ) {
37
- $optionsArray['cookieDomain'] = $this->gadwp->config->options['ga_cookiedomain'];
38
- }
39
- if ( ! empty( $this->gadwp->config->options['ga_cookiename'] ) ) {
40
- $optionsArray['cookieName'] = $this->gadwp->config->options['ga_cookiename'];
41
- }
42
- if ( ! empty( $this->gadwp->config->options['ga_cookieexpires'] ) ) {
43
- $optionsArray['cookieExpires'] = (int) $this->gadwp->config->options['ga_cookieexpires'];
44
- }
45
- if ( ! empty( $optionsArray ) ) {
46
- $options = json_encode( $optionsArray );
47
- }
48
- ?>
49
- ga('create', '<?php echo esc_html($profile[2]); ?>', <?php echo $options; ?><?php if ($create_options != '{}') {?>, <?php echo $create_options; }?>);
50
- <?php if ($this->gadwp->config->options ['ga_crossdomain_tracking'] && $this->gadwp->config->options ['ga_crossdomain_list']!='') {?>
51
- ga('require', 'linker');
52
- <?php
53
- $crossdomain_list = explode( ',', $this->gadwp->config->options['ga_crossdomain_list'] );
54
- $crossdomain_list = array_map( 'trim', $crossdomain_list );
55
- $crossdomain_list = strip_tags( implode( "','", $crossdomain_list ) );
56
- ?>
57
- ga('linker:autoLink', ['<?php echo ($crossdomain_list)?>'] );
58
- <?php
59
- }
60
- if ( $this->gadwp->config->options['ga_dash_remarketing'] ) {
61
- ?>
62
- ga('require', 'displayfeatures');
63
- <?php
64
- }
65
- if ( $this->gadwp->config->options['ga_enhanced_links'] ) {
66
- ?>
67
- ga('require', 'linkid', 'linkid.js');
68
- <?php
69
- }
70
- if ( $this->gadwp->config->options['ga_author_dimindex'] && ( is_single() || is_page() ) ) {
71
- global $post;
72
- $author_id = $post->post_author;
73
- $author_name = get_the_author_meta( 'display_name', $author_id );
74
- ?>
75
- ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_author_dimindex']; ?>', '<?php echo esc_attr($author_name); ?>');
76
- <?php
77
- }
78
- if ( $this->gadwp->config->options['ga_pubyear_dimindex'] && is_single() ) {
79
- global $post;
80
- $date = get_the_date( 'Y', $post->ID );
81
- ?>
82
- ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_pubyear_dimindex']; ?>', '<?php echo (int)$date; ?>');
83
- <?php
84
- }
85
- if ( $this->gadwp->config->options['ga_pubyearmonth_dimindex'] && is_single() ) {
86
- global $post;
87
- $date = get_the_date( 'Y-m', $post->ID );
88
- ?>
89
- ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_pubyearmonth_dimindex']; ?>', '<?php echo $date; ?>');
90
- <?php
91
- }
92
- if ( $this->gadwp->config->options['ga_category_dimindex'] && is_category() ) {
93
- ?>
94
- ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_category_dimindex']; ?>', '<?php echo esc_attr(single_tag_title()); ?>');
95
- <?php
96
- }
97
- if ( $this->gadwp->config->options['ga_tag_dimindex'] && is_single() ) {
98
- global $post;
99
- $post_tags_list = '';
100
- $post_tags_array = get_the_tags( $post->ID );
101
- if ( $post_tags_array ) {
102
- foreach ( $post_tags_array as $tag ) {
103
- $post_tags_list .= $tag->name . ', ';
104
- }
105
- }
106
- $post_tags_list = rtrim( $post_tags_list, ', ' );
107
- if ( $post_tags_list ) {
108
- ?>
109
- ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_tag_dimindex']; ?>', '<?php echo esc_attr($post_tags_list); ?>');
110
- <?php
111
- }
112
- }
113
- if ( $this->gadwp->config->options['ga_category_dimindex'] && is_single() ) {
114
- global $post;
115
- $categories = get_the_category( $post->ID );
116
- foreach ( $categories as $category ) {
117
- ?>
118
- ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_category_dimindex']; ?>', '<?php echo esc_attr($category->name); ?>');
119
- <?php
120
- break;
121
- }
122
- }
123
- if ( $this->gadwp->config->options['ga_user_dimindex'] ) {
124
- ?>
125
- ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_user_dimindex']; ?>', '<?php echo is_user_logged_in()?'registered':'guest'; ?>');
126
- <?php
127
- }
128
- do_action( 'ga_dash_addtrackingcode' );
129
- if ( $this->gadwp->config->options['ga_dash_anonim'] ) {
130
- ?> ga('send', 'pageview', {'anonymizeIp': true});<?php } else {?> ga('send', 'pageview');
131
- <?php
132
- }
133
- if ( $this->gadwp->config->options['ga_dash_adsense'] ) {
134
- ?>
135
-
136
- window.google_analytics_uacct = "<?php echo esc_html($profile[2]); ?>";
137
- <?php }?>
138
- </script>
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ $profile = GADWP_Tools::get_selected_profile( $this->gadwp->config->options['ga_dash_profile_list'], $this->gadwp->config->options['ga_dash_tableid_jail'] );
15
+ ?>
16
+ <script>
17
+ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
18
+ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
19
+ m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
20
+ })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
21
+ <?php
22
+ $create_options = '{';
23
+ if ( $this->gadwp->config->options['ga_speed_samplerate'] != 1 ) {
24
+ $create_options .= "'siteSpeedSampleRate' : " . (int) $this->gadwp->config->options['ga_speed_samplerate'];
25
+ }
26
+ if ( $this->gadwp->config->options['ga_crossdomain_tracking'] && $this->gadwp->config->options['ga_crossdomain_list'] != '' ) {
27
+ if ( $create_options != '{' ) {
28
+ $create_options .= ', ';
29
+ }
30
+ $create_options .= "'allowLinker' : true";
31
+ }
32
+ $create_options .= '}';
33
+
34
+ $options = "'auto'";
35
+ $optionsArray = array();
36
+ if ( ! empty( $this->gadwp->config->options['ga_cookiedomain'] ) ) {
37
+ $optionsArray['cookieDomain'] = $this->gadwp->config->options['ga_cookiedomain'];
38
+ }
39
+ if ( ! empty( $this->gadwp->config->options['ga_cookiename'] ) ) {
40
+ $optionsArray['cookieName'] = $this->gadwp->config->options['ga_cookiename'];
41
+ }
42
+ if ( ! empty( $this->gadwp->config->options['ga_cookieexpires'] ) ) {
43
+ $optionsArray['cookieExpires'] = (int) $this->gadwp->config->options['ga_cookieexpires'];
44
+ }
45
+ if ( ! empty( $optionsArray ) ) {
46
+ $options = json_encode( $optionsArray );
47
+ }
48
+ ?>
49
+ ga('create', '<?php echo esc_html($profile[2]); ?>', <?php echo $options; ?><?php if ($create_options != '{}') {?>, <?php echo $create_options; }?>);
50
+ <?php if ($this->gadwp->config->options ['ga_crossdomain_tracking'] && $this->gadwp->config->options ['ga_crossdomain_list']!='') {?>
51
+ ga('require', 'linker');
52
+ <?php
53
+ $crossdomain_list = explode( ',', $this->gadwp->config->options['ga_crossdomain_list'] );
54
+ $crossdomain_list = array_map( 'trim', $crossdomain_list );
55
+ $crossdomain_list = strip_tags( implode( "','", $crossdomain_list ) );
56
+ ?>
57
+ ga('linker:autoLink', ['<?php echo ($crossdomain_list)?>'] );
58
+ <?php
59
+ }
60
+ if ( $this->gadwp->config->options['ga_dash_remarketing'] ) {
61
+ ?>
62
+ ga('require', 'displayfeatures');
63
+ <?php
64
+ }
65
+ if ( $this->gadwp->config->options['ga_enhanced_links'] ) {
66
+ ?>
67
+ ga('require', 'linkid', 'linkid.js');
68
+ <?php
69
+ }
70
+ if ( $this->gadwp->config->options['ga_author_dimindex'] && ( is_single() || is_page() ) ) {
71
+ global $post;
72
+ $author_id = $post->post_author;
73
+ $author_name = get_the_author_meta( 'display_name', $author_id );
74
+ ?>
75
+ ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_author_dimindex']; ?>', '<?php echo esc_attr($author_name); ?>');
76
+ <?php
77
+ }
78
+ if ( $this->gadwp->config->options['ga_pubyear_dimindex'] && is_single() ) {
79
+ global $post;
80
+ $date = get_the_date( 'Y', $post->ID );
81
+ ?>
82
+ ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_pubyear_dimindex']; ?>', '<?php echo (int)$date; ?>');
83
+ <?php
84
+ }
85
+ if ( $this->gadwp->config->options['ga_pubyearmonth_dimindex'] && is_single() ) {
86
+ global $post;
87
+ $date = get_the_date( 'Y-m', $post->ID );
88
+ ?>
89
+ ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_pubyearmonth_dimindex']; ?>', '<?php echo $date; ?>');
90
+ <?php
91
+ }
92
+ if ( $this->gadwp->config->options['ga_category_dimindex'] && is_category() ) {
93
+ ?>
94
+ ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_category_dimindex']; ?>', '<?php echo esc_attr(single_tag_title()); ?>');
95
+ <?php
96
+ }
97
+ if ( $this->gadwp->config->options['ga_tag_dimindex'] && is_single() ) {
98
+ global $post;
99
+ $post_tags_list = '';
100
+ $post_tags_array = get_the_tags( $post->ID );
101
+ if ( $post_tags_array ) {
102
+ foreach ( $post_tags_array as $tag ) {
103
+ $post_tags_list .= $tag->name . ', ';
104
+ }
105
+ }
106
+ $post_tags_list = rtrim( $post_tags_list, ', ' );
107
+ if ( $post_tags_list ) {
108
+ ?>
109
+ ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_tag_dimindex']; ?>', '<?php echo esc_attr($post_tags_list); ?>');
110
+ <?php
111
+ }
112
+ }
113
+ if ( $this->gadwp->config->options['ga_category_dimindex'] && is_single() ) {
114
+ global $post;
115
+ $categories = get_the_category( $post->ID );
116
+ foreach ( $categories as $category ) {
117
+ ?>
118
+ ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_category_dimindex']; ?>', '<?php echo esc_attr($category->name); ?>');
119
+ <?php
120
+ break;
121
+ }
122
+ }
123
+ if ( $this->gadwp->config->options['ga_user_dimindex'] ) {
124
+ ?>
125
+ ga('set', 'dimension<?php echo (int)$this->gadwp->config->options ['ga_user_dimindex']; ?>', '<?php echo is_user_logged_in()?'registered':'guest'; ?>');
126
+ <?php
127
+ }
128
+ do_action( 'ga_dash_addtrackingcode' );
129
+ if ( $this->gadwp->config->options['ga_dash_anonim'] ) {
130
+ ?> ga('send', 'pageview', {'anonymizeIp': true});<?php } else {?> ga('send', 'pageview');
131
+ <?php
132
+ }
133
+ if ( $this->gadwp->config->options['ga_dash_adsense'] ) {
134
+ ?>
135
+
136
+ window.google_analytics_uacct = "<?php echo esc_html($profile[2]); ?>";
137
+ <?php }?>
138
+ </script>
front/tracking/events-classic.php CHANGED
@@ -1,55 +1,55 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
- ?>
14
- <script type="text/javascript">
15
- (function($){
16
- $(window).load(function() {
17
- if (this._gat) {
18
- tks = this._gat._getTrackers();
19
- ga_track = function(p) {
20
- for (i=0; i < tks.length; i++) {
21
- var n = tks[i]._getName() !== "" ? tks[i]._getName()+"." : "";
22
- a = [];
23
- for (i2=0; i2 < p.length; i2++) {
24
- var b = i2===0 ? n+p[i2] : p[i2];
25
- a.push(b);
26
- }
27
- _gaq.push(a);
28
- }
29
- };
30
- $('a').filter(function() {
31
- return this.href.match(/.*\.(<?php echo esc_js($this->gadwp->config->options['ga_event_downloads']);?>)(\?.*)?$/);
32
- }).click(function(e) {
33
- ga_track(['_trackEvent', 'download', 'click', this.href]);
34
- });
35
- $('a[href^="mailto"]').click(function(e) {
36
- ga_track(['_trackSocial', 'email', 'send', this.href]);
37
- });
38
- var loc = location.host.split('.');
39
- while (loc.length > 2) { loc.shift(); }
40
- loc = loc.join('.');
41
- var localURLs = [
42
- loc,
43
- '<?php echo esc_html(get_option('siteurl'));?>'
44
- ];
45
- $('a[href^="http"]').filter(function() {
46
- for (var i = 0; i < localURLs.length; i++) {
47
- if (this.href.indexOf(localURLs[i]) == -1) return this.href;
48
- }
49
- }).click(function(e) {
50
- ga_track(['_trackEvent', 'outbound', 'click', this.href]);
51
- });
52
- }
53
- });
54
- })(jQuery);
55
- </script>
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+ ?>
14
+ <script type="text/javascript">
15
+ (function($){
16
+ $(window).load(function() {
17
+ if (this._gat) {
18
+ tks = this._gat._getTrackers();
19
+ ga_track = function(p) {
20
+ for (i=0; i < tks.length; i++) {
21
+ var n = tks[i]._getName() !== "" ? tks[i]._getName()+"." : "";
22
+ a = [];
23
+ for (i2=0; i2 < p.length; i2++) {
24
+ var b = i2===0 ? n+p[i2] : p[i2];
25
+ a.push(b);
26
+ }
27
+ _gaq.push(a);
28
+ }
29
+ };
30
+ $('a').filter(function() {
31
+ return this.href.match(/.*\.(<?php echo esc_js($this->gadwp->config->options['ga_event_downloads']);?>)(\?.*)?$/);
32
+ }).click(function(e) {
33
+ ga_track(['_trackEvent', 'download', 'click', this.href]);
34
+ });
35
+ $('a[href^="mailto"]').click(function(e) {
36
+ ga_track(['_trackSocial', 'email', 'send', this.href]);
37
+ });
38
+ var loc = location.host.split('.');
39
+ while (loc.length > 2) { loc.shift(); }
40
+ loc = loc.join('.');
41
+ var localURLs = [
42
+ loc,
43
+ '<?php echo esc_html(get_option('siteurl'));?>'
44
+ ];
45
+ $('a[href^="http"]').filter(function() {
46
+ for (var i = 0; i < localURLs.length; i++) {
47
+ if (this.href.indexOf(localURLs[i]) == -1) return this.href;
48
+ }
49
+ }).click(function(e) {
50
+ ga_track(['_trackEvent', 'outbound', 'click', this.href]);
51
+ });
52
+ }
53
+ });
54
+ })(jQuery);
55
+ </script>
front/tracking/events-universal.php CHANGED
@@ -1,67 +1,67 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- $domaindata = GADWP_Tools::get_root_domain( esc_html( get_option( 'siteurl' ) ) );
15
- ?>
16
- <script type="text/javascript">
17
- (function($){
18
- $(window).load(function() {
19
- <?php if ($this->gadwp->config->options['ga_event_tracking']){ ?>
20
-
21
- //Track Downloads
22
- $('a').filter(function() {
23
- return this.href.match(/.*\.(<?php echo esc_js($this->gadwp->config->options['ga_event_downloads']);?>)(\?.*)?$/);
24
- }).click(function(e) {
25
- ga('send','event', 'download', 'click', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
26
- });
27
-
28
- //Track Mailto
29
- $('a[href^="mailto"]').click(function(e) {
30
- ga('send','event', 'email', 'send', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
31
- });
32
- <?php if (isset ( $domaindata ['domain'] ) && $domaindata ['domain']) { ?>
33
-
34
- //Track Outbound Links
35
- $('a[href^="http"]').filter(function() {
36
- if (!this.href.match(/.*\.(<?php echo esc_js($this->gadwp->config->options['ga_event_downloads']);?>)(\?.*)?$/)){
37
- if (this.href.indexOf('<?php echo $domaindata['domain']; ?>') == -1) return this.href;
38
- }
39
- }).click(function(e) {
40
- ga('send','event', 'outbound', 'click', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
41
- });
42
- <?php } ?>
43
- <?php } ?>
44
- <?php if ($this->gadwp->config->options['ga_event_affiliates'] && $this->gadwp->config->options['ga_aff_tracking']){ ?>
45
-
46
- //Track Affiliates
47
- $('a').filter(function() {
48
- if ('<?php echo esc_js($this->gadwp->config->options['ga_event_affiliates']);?>'!=''){
49
- return this.href.match(/(<?php echo str_replace('/','\/',(esc_js($this->gadwp->config->options['ga_event_affiliates'])));?>)/);
50
- }
51
- }).click(function(event) {
52
- ga('send','event', 'affiliates', 'click', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
53
- });
54
- <?php } ?>
55
- <?php if (isset ( $domaindata ['domain'] ) && $domaindata ['domain'] && $this->gadwp->config->options ['ga_hash_tracking']) { ?>
56
-
57
- //Track Hashmarks
58
- $('a').filter(function() {
59
- if (this.href.indexOf('<?php echo $domaindata['domain']; ?>') != -1 || this.href.indexOf('://') == -1) return this.hash;
60
- }).click(function(e) {
61
- ga('send','event', 'hashmark', 'click', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
62
- });
63
-
64
- <?php } ?>
65
- });
66
- })(jQuery);
67
- </script>
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ $domaindata = GADWP_Tools::get_root_domain( esc_html( get_option( 'siteurl' ) ) );
15
+ ?>
16
+ <script type="text/javascript">
17
+ (function($){
18
+ $(window).load(function() {
19
+ <?php if ($this->gadwp->config->options['ga_event_tracking']){ ?>
20
+
21
+ //Track Downloads
22
+ $('a').filter(function() {
23
+ return this.href.match(/.*\.(<?php echo esc_js($this->gadwp->config->options['ga_event_downloads']);?>)(\?.*)?$/);
24
+ }).click(function(e) {
25
+ ga('send','event', 'download', 'click', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
26
+ });
27
+
28
+ //Track Mailto
29
+ $('a[href^="mailto"]').click(function(e) {
30
+ ga('send','event', 'email', 'send', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
31
+ });
32
+ <?php if (isset ( $domaindata ['domain'] ) && $domaindata ['domain']) { ?>
33
+
34
+ //Track Outbound Links
35
+ $('a[href^="http"]').filter(function() {
36
+ if (!this.href.match(/.*\.(<?php echo esc_js($this->gadwp->config->options['ga_event_downloads']);?>)(\?.*)?$/)){
37
+ if (this.href.indexOf('<?php echo $domaindata['domain']; ?>') == -1) return this.href;
38
+ }
39
+ }).click(function(e) {
40
+ ga('send','event', 'outbound', 'click', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
41
+ });
42
+ <?php } ?>
43
+ <?php } ?>
44
+ <?php if ($this->gadwp->config->options['ga_event_affiliates'] && $this->gadwp->config->options['ga_aff_tracking']){ ?>
45
+
46
+ //Track Affiliates
47
+ $('a').filter(function() {
48
+ if ('<?php echo esc_js($this->gadwp->config->options['ga_event_affiliates']);?>'!=''){
49
+ return this.href.match(/(<?php echo str_replace('/','\/',(esc_js($this->gadwp->config->options['ga_event_affiliates'])));?>)/);
50
+ }
51
+ }).click(function(event) {
52
+ ga('send','event', 'affiliates', 'click', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
53
+ });
54
+ <?php } ?>
55
+ <?php if (isset ( $domaindata ['domain'] ) && $domaindata ['domain'] && $this->gadwp->config->options ['ga_hash_tracking']) { ?>
56
+
57
+ //Track Hashmarks
58
+ $('a').filter(function() {
59
+ if (this.href.indexOf('<?php echo $domaindata['domain']; ?>') != -1 || this.href.indexOf('://') == -1) return this.hash;
60
+ }).click(function(e) {
61
+ ga('send','event', 'hashmark', 'click', this.href<?php if(isset($this->gadwp->config->options['ga_event_bouncerate']) && $this->gadwp->config->options['ga_event_bouncerate']){echo ", {'nonInteraction': 1}";}?>);
62
+ });
63
+
64
+ <?php } ?>
65
+ });
66
+ })(jQuery);
67
+ </script>
front/widgets.php CHANGED
@@ -1,194 +1,194 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- final class GADWP_Frontend_Widget extends WP_Widget {
15
-
16
- private $gadwp;
17
-
18
- public function __construct() {
19
- $this->gadwp = GADWP();
20
-
21
- parent::__construct( 'gadwp-frontwidget-report', __( 'Google Analytics Dashboard', 'google-analytics-dashboard-for-wp' ), array( 'description' => __( "Will display your google analytics stats in a widget", 'google-analytics-dashboard-for-wp' ) ) );
22
- // Frontend Styles
23
- if ( is_active_widget( false, false, $this->id_base, true ) ) {
24
- add_action( 'wp_enqueue_scripts', array( $this, 'load_styles_scripts' ) );
25
- }
26
- }
27
-
28
- public function load_styles_scripts() {
29
- $lang = get_bloginfo( 'language' );
30
- $lang = explode( '-', $lang );
31
- $lang = $lang[0];
32
-
33
- wp_enqueue_style( 'gadwp-front-widget', GADWP_URL . 'front/css/widgets.css', null, GADWP_CURRENT_VERSION );
34
- wp_enqueue_script( 'gadwp-front-widget', GADWP_URL . 'front/js/widgets.js', array( 'jquery' ), GADWP_CURRENT_VERSION );
35
- wp_enqueue_script( 'googlecharts', 'https://www.gstatic.com/charts/loader.js', array(), null );
36
- }
37
-
38
- public function widget( $args, $instance ) {
39
- $widget_title = apply_filters( 'widget_title', $instance['title'] );
40
- $title = __( "Sessions", 'google-analytics-dashboard-for-wp' );
41
- echo "\n<!-- BEGIN GADWP v" . GADWP_CURRENT_VERSION . " Widget - https://deconf.com/google-analytics-dashboard-wordpress/ -->\n";
42
- echo $args['before_widget'];
43
- if ( ! empty( $widget_title ) ) {
44
- echo $args['before_title'] . $widget_title . $args['after_title'];
45
- }
46
-
47
- if ( isset( $this->gadwp->config->options['ga_dash_style'] ) ) {
48
- $css = "colors:['" . $this->gadwp->config->options['ga_dash_style'] . "','" . GADWP_Tools::colourVariator( $this->gadwp->config->options['ga_dash_style'], - 20 ) . "'],";
49
- $color = $this->gadwp->config->options['ga_dash_style'];
50
- } else {
51
- $css = "";
52
- $color = "#3366CC";
53
- }
54
- ob_start();
55
- if ( $instance['anonim'] ) {
56
- $formater = "var formatter = new google.visualization.NumberFormat({
57
- suffix: '%',
58
- fractionDigits: 2
59
- });
60
-
61
- formatter.format(data, 1);";
62
- } else {
63
- $formater = '';
64
- }
65
- $periodtext = "";
66
- switch ( $instance['period'] ) {
67
- case '7daysAgo' :
68
- $periodtext = sprintf( __( 'Last %d Days', 'google-analytics-dashboard-for-wp' ), 7 );
69
- break;
70
- case '14daysAgo' :
71
- $periodtext = sprintf( __( 'Last %d Days', 'google-analytics-dashboard-for-wp' ), 14 );
72
- break;
73
- case '30daysAgo' :
74
- $periodtext = sprintf( __( 'Last %d Days', 'google-analytics-dashboard-for-wp' ), 30 );
75
- break;
76
- default :
77
- $periodtext = "";
78
- break;
79
- }
80
- switch ( $instance['display'] ) {
81
- case '1' :
82
- echo '<div id="gadwp-widget"><div id="gadwp-widgetchart"></div><div id="gadwp-widgettotals"></div></div>';
83
- break;
84
- case '2' :
85
- echo '<div id="gadwp-widget"><div id="gadwp-widgetchart"></div></div>';
86
- break;
87
- case '3' :
88
- echo '<div id="gadwp-widget"><div id="gadwp-widgettotals"></div></div>';
89
- break;
90
- }
91
- ?>
92
- <script type="text/javascript">
93
- google.charts.load('current', {mapsApiKey: '<?php echo $this->gadwp->config->options['maps_api_key']; ?>', 'packages':['corechart']});
94
- google.charts.setOnLoadCallback( GADWPWidgetLoad );
95
- function GADWPWidgetLoad (){
96
- jQuery.post("<?php echo admin_url( 'admin-ajax.php' ); ?>", {action: "ajax_frontwidget_report", gadwp_number: "<?php echo $this->number; ?>", gadwp_optionname: "<?php echo $this->option_name; ?>" }, function(response){
97
- if (!jQuery.isNumeric(response) && jQuery.isArray(response)){
98
- if (jQuery("#gadwp-widgetchart")[0]){
99
- gadwpFrontWidgetData = response[0];
100
- gadwp_drawFrontWidgetChart(gadwpFrontWidgetData);
101
- }
102
- if (jQuery("#gadwp-widgettotals")[0]){
103
- gadwp_drawFrontWidgetTotals(response[1]);
104
- }
105
- }else{
106
- jQuery("#gadwp-widgetchart").css({"background-color":"#F7F7F7","height":"auto","padding-top":"50px","padding-bottom":"50px","color":"#000","text-align":"center"});
107
- jQuery("#gadwp-widgetchart").html("<?php __( "This report is unavailable", 'google-analytics-dashboard-for-wp' ); ?> ("+response+")");
108
- }
109
- });
110
- }
111
- function gadwp_drawFrontWidgetChart(response) {
112
- var data = google.visualization.arrayToDataTable(response);
113
- var options = {
114
- legend: { position: "none" },
115
- pointSize: "3, <?php echo $css; ?>",
116
- title: "<?php echo $title; ?>",
117
- titlePosition: "in",
118
- chartArea: { width: "95%", height: "75%" },
119
- hAxis: { textPosition: "none"},
120
- vAxis: { textPosition: "none", minValue: 0, gridlines: { color: "transparent" }, baselineColor: "transparent"}
121
- }
122
- var chart = new google.visualization.AreaChart(document.getElementById("gadwp-widgetchart"));
123
- <?php echo $formater; ?>
124
- chart.draw(data, options);
125
- }
126
- function gadwp_drawFrontWidgetTotals(response) {
127
- if (response == null){
128
- response = 0;
129
- }
130
- jQuery("#gadwp-widgettotals").html('<div class="gadwp-left"><?php _e( "Period:", 'google-analytics-dashboard-for-wp' ); ?></div> <div class="gadwp-right"><?php echo $periodtext; ?> </div><div class="gadwp-left"><?php _e( "Sessions:", 'google-analytics-dashboard-for-wp' ); ?></div> <div class="gadwp-right">'+response+'</div>');
131
- }
132
- </script>
133
- <?php
134
- if ( $instance['give_credits'] == 1 ) :
135
- ?>
136
- <div style="text-align: right; width: 100%; font-size: 0.8em; clear: both; margin-right: 5px;"><?php _e( 'generated by', 'google-analytics-dashboard-for-wp' ); ?> <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_report&utm_medium=link&utm_content=front_widget&utm_campaign=gadwp" rel="nofollow" style="text-decoration: none; font-size: 1em;">GADWP</a>&nbsp;
137
- </div>
138
-
139
- <?php
140
- endif;
141
- $widget_content = ob_get_contents();
142
- if ( ob_get_length() ) {
143
- ob_end_clean();
144
- }
145
- echo $widget_content;
146
- echo $args['after_widget'];
147
- echo "\n<!-- END GADWP Widget -->\n";
148
- }
149
-
150
- public function form( $instance ) {
151
- $widget_title = ( isset( $instance['title'] ) ? $instance['title'] : __( "Google Analytics Stats", 'google-analytics-dashboard-for-wp' ) );
152
- $period = ( isset( $instance['period'] ) ? $instance['period'] : '7daysAgo' );
153
- $display = ( isset( $instance['display'] ) ? $instance['display'] : 1 );
154
- $give_credits = ( isset( $instance['give_credits'] ) ? $instance['give_credits'] : 1 );
155
- $anonim = ( isset( $instance['anonim'] ) ? $instance['anonim'] : 0 );
156
- /* @formatter:off */
157
- ?>
158
- <p>
159
- <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( "Title:",'google-analytics-dashboard-for-wp' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $widget_title ); ?>">
160
- </p>
161
- <p>
162
- <label for="<?php echo $this->get_field_id( 'display' ); ?>"><?php _e( "Display:",'google-analytics-dashboard-for-wp' ); ?></label> <select id="<?php echo $this->get_field_id('display'); ?>" class="widefat" name="<?php echo $this->get_field_name( 'display' ); ?>">
163
- <option value="1" <?php selected( $display, 1 ); ?>><?php _e('Chart & Totals', 'google-analytics-dashboard-for-wp');?></option>
164
- <option value="2" <?php selected( $display, 2 ); ?>><?php _e('Chart', 'google-analytics-dashboard-for-wp');?></option>
165
- <option value="3" <?php selected( $display, 3 ); ?>><?php _e('Totals', 'google-analytics-dashboard-for-wp');?></option>
166
- </select>
167
- </p>
168
- <p>
169
- <label for="<?php echo $this->get_field_id( 'anonim' ); ?>"><?php _e( "Anonymize stats:",'google-analytics-dashboard-for-wp' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'anonim' ); ?>" name="<?php echo $this->get_field_name( 'anonim' ); ?>" type="checkbox" <?php checked( $anonim, 1 ); ?> value="1">
170
- </p>
171
- <p>
172
- <label for="<?php echo $this->get_field_id( 'period' ); ?>"><?php _e( "Stats for:",'google-analytics-dashboard-for-wp' ); ?></label> <select id="<?php echo $this->get_field_id('period'); ?>" class="widefat" name="<?php echo $this->get_field_name( 'period' ); ?>">
173
- <option value="7daysAgo" <?php selected( $period, '7daysAgo' ); ?>><?php printf( __('Last %d Days', 'google-analytics-dashboard-for-wp'), 7 );?></option>
174
- <option value="14daysAgo" <?php selected( $period, '14daysAgo' ); ?>><?php printf( __('Last %d Days', 'google-analytics-dashboard-for-wp'), 14 );?></option>
175
- <option value="30daysAgo" <?php selected( $period, '30daysAgo' ); ?>><?php printf( __('Last %d Days', 'google-analytics-dashboard-for-wp'), 30 );?></option>
176
- </select>
177
- </p>
178
- <p>
179
- <label for="<?php echo $this->get_field_id( 'give_credits' ); ?>"><?php _e( "Give credits:",'google-analytics-dashboard-for-wp' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'give_credits' ); ?>" name="<?php echo $this->get_field_name( 'give_credits' ); ?>" type="checkbox" <?php checked( $give_credits, 1 ); ?> value="1">
180
- </p>
181
- <?php
182
- /* @formatter:on */
183
- }
184
-
185
- public function update( $new_instance, $old_instance ) {
186
- $instance = array();
187
- $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : 'Analytics Stats';
188
- $instance['period'] = ( ! empty( $new_instance['period'] ) ) ? strip_tags( $new_instance['period'] ) : '7daysAgo';
189
- $instance['display'] = ( ! empty( $new_instance['display'] ) ) ? strip_tags( $new_instance['display'] ) : 1;
190
- $instance['give_credits'] = ( ! empty( $new_instance['give_credits'] ) ) ? strip_tags( $new_instance['give_credits'] ) : 0;
191
- $instance['anonim'] = ( ! empty( $new_instance['anonim'] ) ) ? strip_tags( $new_instance['anonim'] ) : 0;
192
- return $instance;
193
- }
194
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ final class GADWP_Frontend_Widget extends WP_Widget {
15
+
16
+ private $gadwp;
17
+
18
+ public function __construct() {
19
+ $this->gadwp = GADWP();
20
+
21
+ parent::__construct( 'gadwp-frontwidget-report', __( 'Google Analytics Dashboard', 'google-analytics-dashboard-for-wp' ), array( 'description' => __( "Will display your google analytics stats in a widget", 'google-analytics-dashboard-for-wp' ) ) );
22
+ // Frontend Styles
23
+ if ( is_active_widget( false, false, $this->id_base, true ) ) {
24
+ add_action( 'wp_enqueue_scripts', array( $this, 'load_styles_scripts' ) );
25
+ }
26
+ }
27
+
28
+ public function load_styles_scripts() {
29
+ $lang = get_bloginfo( 'language' );
30
+ $lang = explode( '-', $lang );
31
+ $lang = $lang[0];
32
+
33
+ wp_enqueue_style( 'gadwp-front-widget', GADWP_URL . 'front/css/widgets.css', null, GADWP_CURRENT_VERSION );
34
+ wp_enqueue_script( 'gadwp-front-widget', GADWP_URL . 'front/js/widgets.js', array( 'jquery' ), GADWP_CURRENT_VERSION );
35
+ wp_enqueue_script( 'googlecharts', 'https://www.gstatic.com/charts/loader.js', array(), null );
36
+ }
37
+
38
+ public function widget( $args, $instance ) {
39
+ $widget_title = apply_filters( 'widget_title', $instance['title'] );
40
+ $title = __( "Sessions", 'google-analytics-dashboard-for-wp' );
41
+ echo "\n<!-- BEGIN GADWP v" . GADWP_CURRENT_VERSION . " Widget - https://deconf.com/google-analytics-dashboard-wordpress/ -->\n";
42
+ echo $args['before_widget'];
43
+ if ( ! empty( $widget_title ) ) {
44
+ echo $args['before_title'] . $widget_title . $args['after_title'];
45
+ }
46
+
47
+ if ( isset( $this->gadwp->config->options['ga_dash_style'] ) ) {
48
+ $css = "colors:['" . $this->gadwp->config->options['ga_dash_style'] . "','" . GADWP_Tools::colourVariator( $this->gadwp->config->options['ga_dash_style'], - 20 ) . "'],";
49
+ $color = $this->gadwp->config->options['ga_dash_style'];
50
+ } else {
51
+ $css = "";
52
+ $color = "#3366CC";
53
+ }
54
+ ob_start();
55
+ if ( $instance['anonim'] ) {
56
+ $formater = "var formatter = new google.visualization.NumberFormat({
57
+ suffix: '%',
58
+ fractionDigits: 2
59
+ });
60
+
61
+ formatter.format(data, 1);";
62
+ } else {
63
+ $formater = '';
64
+ }
65
+ $periodtext = "";
66
+ switch ( $instance['period'] ) {
67
+ case '7daysAgo' :
68
+ $periodtext = sprintf( __( 'Last %d Days', 'google-analytics-dashboard-for-wp' ), 7 );
69
+ break;
70
+ case '14daysAgo' :
71
+ $periodtext = sprintf( __( 'Last %d Days', 'google-analytics-dashboard-for-wp' ), 14 );
72
+ break;
73
+ case '30daysAgo' :
74
+ $periodtext = sprintf( __( 'Last %d Days', 'google-analytics-dashboard-for-wp' ), 30 );
75
+ break;
76
+ default :
77
+ $periodtext = "";
78
+ break;
79
+ }
80
+ switch ( $instance['display'] ) {
81
+ case '1' :
82
+ echo '<div id="gadwp-widget"><div id="gadwp-widgetchart"></div><div id="gadwp-widgettotals"></div></div>';
83
+ break;
84
+ case '2' :
85
+ echo '<div id="gadwp-widget"><div id="gadwp-widgetchart"></div></div>';
86
+ break;
87
+ case '3' :
88
+ echo '<div id="gadwp-widget"><div id="gadwp-widgettotals"></div></div>';
89
+ break;
90
+ }
91
+ ?>
92
+ <script type="text/javascript">
93
+ google.charts.load('current', {'packages':['corechart']});
94
+ google.charts.setOnLoadCallback( GADWPWidgetLoad );
95
+ function GADWPWidgetLoad (){
96
+ jQuery.post("<?php echo admin_url( 'admin-ajax.php' ); ?>", {action: "ajax_frontwidget_report", gadwp_number: "<?php echo $this->number; ?>", gadwp_optionname: "<?php echo $this->option_name; ?>" }, function(response){
97
+ if (!jQuery.isNumeric(response) && jQuery.isArray(response)){
98
+ if (jQuery("#gadwp-widgetchart")[0]){
99
+ gadwpFrontWidgetData = response[0];
100
+ gadwp_drawFrontWidgetChart(gadwpFrontWidgetData);
101
+ }
102
+ if (jQuery("#gadwp-widgettotals")[0]){
103
+ gadwp_drawFrontWidgetTotals(response[1]);
104
+ }
105
+ }else{
106
+ jQuery("#gadwp-widgetchart").css({"background-color":"#F7F7F7","height":"auto","padding-top":"50px","padding-bottom":"50px","color":"#000","text-align":"center"});
107
+ jQuery("#gadwp-widgetchart").html("<?php __( "This report is unavailable", 'google-analytics-dashboard-for-wp' ); ?> ("+response+")");
108
+ }
109
+ });
110
+ }
111
+ function gadwp_drawFrontWidgetChart(response) {
112
+ var data = google.visualization.arrayToDataTable(response);
113
+ var options = {
114
+ legend: { position: "none" },
115
+ pointSize: "3, <?php echo $css; ?>",
116
+ title: "<?php echo $title; ?>",
117
+ titlePosition: "in",
118
+ chartArea: { width: "95%", height: "75%" },
119
+ hAxis: { textPosition: "none"},
120
+ vAxis: { textPosition: "none", minValue: 0, gridlines: { color: "transparent" }, baselineColor: "transparent"}
121
+ }
122
+ var chart = new google.visualization.AreaChart(document.getElementById("gadwp-widgetchart"));
123
+ <?php echo $formater; ?>
124
+ chart.draw(data, options);
125
+ }
126
+ function gadwp_drawFrontWidgetTotals(response) {
127
+ if (response == null){
128
+ response = 0;
129
+ }
130
+ jQuery("#gadwp-widgettotals").html('<div class="gadwp-left"><?php _e( "Period:", 'google-analytics-dashboard-for-wp' ); ?></div> <div class="gadwp-right"><?php echo $periodtext; ?> </div><div class="gadwp-left"><?php _e( "Sessions:", 'google-analytics-dashboard-for-wp' ); ?></div> <div class="gadwp-right">'+response+'</div>');
131
+ }
132
+ </script>
133
+ <?php
134
+ if ( $instance['give_credits'] == 1 ) :
135
+ ?>
136
+ <div style="text-align: right; width: 100%; font-size: 0.8em; clear: both; margin-right: 5px;"><?php _e( 'generated by', 'google-analytics-dashboard-for-wp' ); ?> <a href="https://deconf.com/google-analytics-dashboard-wordpress/?utm_source=gadwp_report&utm_medium=link&utm_content=front_widget&utm_campaign=gadwp" rel="nofollow" style="text-decoration: none; font-size: 1em;">GADWP</a>&nbsp;
137
+ </div>
138
+
139
+ <?php
140
+ endif;
141
+ $widget_content = ob_get_contents();
142
+ if ( ob_get_length() ) {
143
+ ob_end_clean();
144
+ }
145
+ echo $widget_content;
146
+ echo $args['after_widget'];
147
+ echo "\n<!-- END GADWP Widget -->\n";
148
+ }
149
+
150
+ public function form( $instance ) {
151
+ $widget_title = ( isset( $instance['title'] ) ? $instance['title'] : __( "Google Analytics Stats", 'google-analytics-dashboard-for-wp' ) );
152
+ $period = ( isset( $instance['period'] ) ? $instance['period'] : '7daysAgo' );
153
+ $display = ( isset( $instance['display'] ) ? $instance['display'] : 1 );
154
+ $give_credits = ( isset( $instance['give_credits'] ) ? $instance['give_credits'] : 1 );
155
+ $anonim = ( isset( $instance['anonim'] ) ? $instance['anonim'] : 0 );
156
+ /* @formatter:off */
157
+ ?>
158
+ <p>
159
+ <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( "Title:",'google-analytics-dashboard-for-wp' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $widget_title ); ?>">
160
+ </p>
161
+ <p>
162
+ <label for="<?php echo $this->get_field_id( 'display' ); ?>"><?php _e( "Display:",'google-analytics-dashboard-for-wp' ); ?></label> <select id="<?php echo $this->get_field_id('display'); ?>" class="widefat" name="<?php echo $this->get_field_name( 'display' ); ?>">
163
+ <option value="1" <?php selected( $display, 1 ); ?>><?php _e('Chart & Totals', 'google-analytics-dashboard-for-wp');?></option>
164
+ <option value="2" <?php selected( $display, 2 ); ?>><?php _e('Chart', 'google-analytics-dashboard-for-wp');?></option>
165
+ <option value="3" <?php selected( $display, 3 ); ?>><?php _e('Totals', 'google-analytics-dashboard-for-wp');?></option>
166
+ </select>
167
+ </p>
168
+ <p>
169
+ <label for="<?php echo $this->get_field_id( 'anonim' ); ?>"><?php _e( "Anonymize stats:",'google-analytics-dashboard-for-wp' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'anonim' ); ?>" name="<?php echo $this->get_field_name( 'anonim' ); ?>" type="checkbox" <?php checked( $anonim, 1 ); ?> value="1">
170
+ </p>
171
+ <p>
172
+ <label for="<?php echo $this->get_field_id( 'period' ); ?>"><?php _e( "Stats for:",'google-analytics-dashboard-for-wp' ); ?></label> <select id="<?php echo $this->get_field_id('period'); ?>" class="widefat" name="<?php echo $this->get_field_name( 'period' ); ?>">
173
+ <option value="7daysAgo" <?php selected( $period, '7daysAgo' ); ?>><?php printf( __('Last %d Days', 'google-analytics-dashboard-for-wp'), 7 );?></option>
174
+ <option value="14daysAgo" <?php selected( $period, '14daysAgo' ); ?>><?php printf( __('Last %d Days', 'google-analytics-dashboard-for-wp'), 14 );?></option>
175
+ <option value="30daysAgo" <?php selected( $period, '30daysAgo' ); ?>><?php printf( __('Last %d Days', 'google-analytics-dashboard-for-wp'), 30 );?></option>
176
+ </select>
177
+ </p>
178
+ <p>
179
+ <label for="<?php echo $this->get_field_id( 'give_credits' ); ?>"><?php _e( "Give credits:",'google-analytics-dashboard-for-wp' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'give_credits' ); ?>" name="<?php echo $this->get_field_name( 'give_credits' ); ?>" type="checkbox" <?php checked( $give_credits, 1 ); ?> value="1">
180
+ </p>
181
+ <?php
182
+ /* @formatter:on */
183
+ }
184
+
185
+ public function update( $new_instance, $old_instance ) {
186
+ $instance = array();
187
+ $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : 'Analytics Stats';
188
+ $instance['period'] = ( ! empty( $new_instance['period'] ) ) ? strip_tags( $new_instance['period'] ) : '7daysAgo';
189
+ $instance['display'] = ( ! empty( $new_instance['display'] ) ) ? strip_tags( $new_instance['display'] ) : 1;
190
+ $instance['give_credits'] = ( ! empty( $new_instance['give_credits'] ) ) ? strip_tags( $new_instance['give_credits'] ) : 0;
191
+ $instance['anonim'] = ( ! empty( $new_instance['anonim'] ) ) ? strip_tags( $new_instance['anonim'] ) : 0;
192
+ return $instance;
193
+ }
194
+ }
gadwp.php CHANGED
@@ -1,258 +1,258 @@
1
- <?php
2
- /**
3
- * Plugin Name: Google Analytics Dashboard for WP
4
- * Plugin URI: https://deconf.com
5
- * Description: Displays Google Analytics Reports and Real-Time Statistics in your Dashboard. Automatically inserts the tracking code in every page of your website.
6
- * Author: Alin Marcu
7
- * Version: 4.9.4
8
- * Author URI: https://deconf.com
9
- * Text Domain: google-analytics-dashboard-for-wp
10
- * Domain Path: /languages
11
- */
12
-
13
- // Exit if accessed directly
14
- if ( ! defined( 'ABSPATH' ) )
15
- exit();
16
-
17
- // Plugin Version
18
- if ( ! defined( 'GADWP_CURRENT_VERSION' ) ) {
19
- define( 'GADWP_CURRENT_VERSION', '4.9.4' );
20
- }
21
-
22
- if ( ! class_exists( 'GADWP_Manager' ) ) {
23
-
24
- final class GADWP_Manager {
25
-
26
- private static $instance = null;
27
-
28
- public $config = null;
29
-
30
- public $frontend_actions = null;
31
-
32
- public $common_actions = null;
33
-
34
- public $backend_actions = null;
35
-
36
- public $tracking = null;
37
-
38
- public $frontend_item_reports = null;
39
-
40
- public $backend_setup = null;
41
-
42
- public $frontend_setup = null;
43
-
44
- public $backend_widgets = null;
45
-
46
- public $backend_item_reports = null;
47
-
48
- public $gapi_controller = null;
49
-
50
- /**
51
- * Construct forbidden
52
- */
53
- private function __construct() {
54
- if ( null !== self::$instance ) {
55
- _doing_it_wrong( __FUNCTION__, __( "This is not allowed, read the documentation!", 'google-analytics-dashboard-for-wp' ), '4.6' );
56
- }
57
- }
58
-
59
- /**
60
- * Clone warning
61
- */
62
- private function __clone() {
63
- _doing_it_wrong( __FUNCTION__, __( "This is not allowed, read the documentation!", 'google-analytics-dashboard-for-wp' ), '4.6' );
64
- }
65
-
66
- /**
67
- * Wakeup warning
68
- */
69
- private function __wakeup() {
70
- _doing_it_wrong( __FUNCTION__, __( "This is not allowed, read the documentation!", 'google-analytics-dashboard-for-wp' ), '4.6' );
71
- }
72
-
73
- /**
74
- * Creates a single instance for GADWP and makes sure only one instance is present in memory.
75
- *
76
- * @return GADWP_Manager
77
- */
78
- public static function instance() {
79
- if ( null === self::$instance ) {
80
- self::$instance = new self();
81
- self::$instance->setup();
82
- self::$instance->config = new GADWP_Config();
83
- }
84
- return self::$instance;
85
- }
86
-
87
- /**
88
- * Defines constants and loads required resources
89
- */
90
- private function setup() {
91
-
92
- // Plugin Path
93
- if ( ! defined( 'GADWP_DIR' ) ) {
94
- define( 'GADWP_DIR', plugin_dir_path( __FILE__ ) );
95
- }
96
-
97
- // Plugin URL
98
- if ( ! defined( 'GADWP_URL' ) ) {
99
- define( 'GADWP_URL', plugin_dir_url( __FILE__ ) );
100
- }
101
-
102
- // Plugin main File
103
- if ( ! defined( 'GADWP_FILE' ) ) {
104
- define( 'GADWP_FILE', __FILE__ );
105
- }
106
-
107
- /*
108
- * Load Tools class
109
- */
110
- include_once ( GADWP_DIR . 'tools/tools.php' );
111
-
112
- /*
113
- * Load Config class
114
- */
115
- include_once ( GADWP_DIR . 'config.php' );
116
-
117
- /*
118
- * Load GAPI Controller class
119
- */
120
- include_once ( GADWP_DIR . 'tools/gapi.php' );
121
-
122
- /*
123
- * Plugin i18n
124
- */
125
- add_action( 'init', array( self::$instance, 'load_i18n' ) );
126
-
127
- /*
128
- * Plugin Init
129
- */
130
- add_action( 'init', array( self::$instance, 'load' ) );
131
-
132
- /*
133
- * Include Install
134
- */
135
- include_once ( GADWP_DIR . 'install/install.php' );
136
- register_activation_hook( GADWP_FILE, array( 'GADWP_Install', 'install' ) );
137
-
138
- /*
139
- * Include Uninstall
140
- */
141
- include_once ( GADWP_DIR . 'install/uninstall.php' );
142
- register_uninstall_hook( GADWP_FILE, array( 'GADWP_Uninstall', 'uninstall' ) );
143
-
144
- /*
145
- * Load Frontend Widgets
146
- * (needed during ajax)
147
- */
148
- include_once ( GADWP_DIR . 'front/widgets.php' );
149
-
150
- /*
151
- * Add Frontend Widgets
152
- * (needed during ajax)
153
- */
154
- add_action( 'widgets_init', array( self::$instance, 'add_frontend_widget' ) );
155
- }
156
-
157
- /**
158
- * Load i18n
159
- */
160
- public function load_i18n() {
161
- load_plugin_textdomain( 'google-analytics-dashboard-for-wp', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
162
- }
163
-
164
- /**
165
- * Register Frontend Widgets
166
- */
167
- public function add_frontend_widget() {
168
- register_widget( 'GADWP_Frontend_Widget' );
169
- }
170
-
171
- /**
172
- * Conditional load
173
- */
174
- public function load() {
175
- if ( is_admin() ) {
176
- if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
177
- if ( GADWP_Tools::check_roles( self::$instance->config->options['ga_dash_access_back'] ) ) {
178
- /*
179
- * Load Backend ajax actions
180
- */
181
- include_once ( GADWP_DIR . 'admin/ajax-actions.php' );
182
- self::$instance->backend_actions = new GADWP_Backend_Ajax();
183
- }
184
-
185
- /*
186
- * Load Frontend ajax actions
187
- */
188
- include_once ( GADWP_DIR . 'front/ajax-actions.php' );
189
- self::$instance->frontend_actions = new GADWP_Frontend_Ajax();
190
-
191
- /*
192
- * Load Common ajax actions
193
- */
194
- include_once ( GADWP_DIR . 'common/ajax-actions.php' );
195
- self::$instance->common_actions = new GADWP_Common_Ajax();
196
- } else if ( GADWP_Tools::check_roles( self::$instance->config->options['ga_dash_access_back'] ) ) {
197
- /*
198
- * Load Backend Setup
199
- */
200
- include_once ( GADWP_DIR . 'admin/setup.php' );
201
- self::$instance->backend_setup = new GADWP_Backend_Setup();
202
-
203
- if ( self::$instance->config->options['dashboard_widget'] ) {
204
- /*
205
- * Load Backend Widget
206
- */
207
- include_once ( GADWP_DIR . 'admin/widgets.php' );
208
- self::$instance->backend_widgets = new GADWP_Backend_Widgets();
209
- }
210
-
211
- if ( self::$instance->config->options['backend_item_reports'] ) {
212
- /*
213
- * Load Backend Item Reports
214
- */
215
- include_once ( GADWP_DIR . 'admin/item-reports.php' );
216
- self::$instance->backend_item_reports = new GADWP_Backend_Item_Reports();
217
- }
218
- }
219
- } else {
220
- if ( GADWP_Tools::check_roles( self::$instance->config->options['ga_dash_access_front'] ) ) {
221
- /*
222
- * Load Frontend Setup
223
- */
224
- include_once ( GADWP_DIR . 'front/setup.php' );
225
- self::$instance->frontend_setup = new GADWP_Frontend_Setup();
226
-
227
- if ( self::$instance->config->options['frontend_item_reports'] ) {
228
- /*
229
- * Load Frontend Item Reports
230
- */
231
- include_once ( GADWP_DIR . 'front/item-reports.php' );
232
- self::$instance->frontend_item_reports = new GADWP_Frontend_Item_Reports();
233
- }
234
- }
235
-
236
- if ( ! GADWP_Tools::check_roles( self::$instance->config->options['ga_track_exclude'], true ) && self::$instance->config->options['ga_dash_tracking'] ) {
237
- /*
238
- * Load tracking class
239
- */
240
- include_once ( GADWP_DIR . 'front/tracking.php' );
241
- self::$instance->tracking = new GADWP_Tracking();
242
- }
243
- }
244
- }
245
- }
246
- }
247
-
248
- /**
249
- * Returns a unique instance of GADWP
250
- */
251
- function GADWP() {
252
- return GADWP_Manager::instance();
253
- }
254
-
255
- /*
256
- * Start GADWP
257
- */
258
- GADWP();
1
+ <?php
2
+ /**
3
+ * Plugin Name: Google Analytics Dashboard for WP
4
+ * Plugin URI: https://deconf.com
5
+ * Description: Displays Google Analytics Reports and Real-Time Statistics in your Dashboard. Automatically inserts the tracking code in every page of your website.
6
+ * Author: Alin Marcu
7
+ * Version: 4.9.5
8
+ * Author URI: https://deconf.com
9
+ * Text Domain: google-analytics-dashboard-for-wp
10
+ * Domain Path: /languages
11
+ */
12
+
13
+ // Exit if accessed directly
14
+ if ( ! defined( 'ABSPATH' ) )
15
+ exit();
16
+
17
+ // Plugin Version
18
+ if ( ! defined( 'GADWP_CURRENT_VERSION' ) ) {
19
+ define( 'GADWP_CURRENT_VERSION', '4.9.5' );
20
+ }
21
+
22
+ if ( ! class_exists( 'GADWP_Manager' ) ) {
23
+
24
+ final class GADWP_Manager {
25
+
26
+ private static $instance = null;
27
+
28
+ public $config = null;
29
+
30
+ public $frontend_actions = null;
31
+
32
+ public $common_actions = null;
33
+
34
+ public $backend_actions = null;
35
+
36
+ public $tracking = null;
37
+
38
+ public $frontend_item_reports = null;
39
+
40
+ public $backend_setup = null;
41
+
42
+ public $frontend_setup = null;
43
+
44
+ public $backend_widgets = null;
45
+
46
+ public $backend_item_reports = null;
47
+
48
+ public $gapi_controller = null;
49
+
50
+ /**
51
+ * Construct forbidden
52
+ */
53
+ private function __construct() {
54
+ if ( null !== self::$instance ) {
55
+ _doing_it_wrong( __FUNCTION__, __( "This is not allowed, read the documentation!", 'google-analytics-dashboard-for-wp' ), '4.6' );
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Clone warning
61
+ */
62
+ private function __clone() {
63
+ _doing_it_wrong( __FUNCTION__, __( "This is not allowed, read the documentation!", 'google-analytics-dashboard-for-wp' ), '4.6' );
64
+ }
65
+
66
+ /**
67
+ * Wakeup warning
68
+ */
69
+ private function __wakeup() {
70
+ _doing_it_wrong( __FUNCTION__, __( "This is not allowed, read the documentation!", 'google-analytics-dashboard-for-wp' ), '4.6' );
71
+ }
72
+
73
+ /**
74
+ * Creates a single instance for GADWP and makes sure only one instance is present in memory.
75
+ *
76
+ * @return GADWP_Manager
77
+ */
78
+ public static function instance() {
79
+ if ( null === self::$instance ) {
80
+ self::$instance = new self();
81
+ self::$instance->setup();
82
+ self::$instance->config = new GADWP_Config();
83
+ }
84
+ return self::$instance;
85
+ }
86
+
87
+ /**
88
+ * Defines constants and loads required resources
89
+ */
90
+ private function setup() {
91
+
92
+ // Plugin Path
93
+ if ( ! defined( 'GADWP_DIR' ) ) {
94
+ define( 'GADWP_DIR', plugin_dir_path( __FILE__ ) );
95
+ }
96
+
97
+ // Plugin URL
98
+ if ( ! defined( 'GADWP_URL' ) ) {
99
+ define( 'GADWP_URL', plugin_dir_url( __FILE__ ) );
100
+ }
101
+
102
+ // Plugin main File
103
+ if ( ! defined( 'GADWP_FILE' ) ) {
104
+ define( 'GADWP_FILE', __FILE__ );
105
+ }
106
+
107
+ /*
108
+ * Load Tools class
109
+ */
110
+ include_once ( GADWP_DIR . 'tools/tools.php' );
111
+
112
+ /*
113
+ * Load Config class
114
+ */
115
+ include_once ( GADWP_DIR . 'config.php' );
116
+
117
+ /*
118
+ * Load GAPI Controller class
119
+ */
120
+ include_once ( GADWP_DIR . 'tools/gapi.php' );
121
+
122
+ /*
123
+ * Plugin i18n
124
+ */
125
+ add_action( 'init', array( self::$instance, 'load_i18n' ) );
126
+
127
+ /*
128
+ * Plugin Init
129
+ */
130
+ add_action( 'init', array( self::$instance, 'load' ) );
131
+
132
+ /*
133
+ * Include Install
134
+ */
135
+ include_once ( GADWP_DIR . 'install/install.php' );
136
+ register_activation_hook( GADWP_FILE, array( 'GADWP_Install', 'install' ) );
137
+
138
+ /*
139
+ * Include Uninstall
140
+ */
141
+ include_once ( GADWP_DIR . 'install/uninstall.php' );
142
+ register_uninstall_hook( GADWP_FILE, array( 'GADWP_Uninstall', 'uninstall' ) );
143
+
144
+ /*
145
+ * Load Frontend Widgets
146
+ * (needed during ajax)
147
+ */
148
+ include_once ( GADWP_DIR . 'front/widgets.php' );
149
+
150
+ /*
151
+ * Add Frontend Widgets
152
+ * (needed during ajax)
153
+ */
154
+ add_action( 'widgets_init', array( self::$instance, 'add_frontend_widget' ) );
155
+ }
156
+
157
+ /**
158
+ * Load i18n
159
+ */
160
+ public function load_i18n() {
161
+ load_plugin_textdomain( 'google-analytics-dashboard-for-wp', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
162
+ }
163
+
164
+ /**
165
+ * Register Frontend Widgets
166
+ */
167
+ public function add_frontend_widget() {
168
+ register_widget( 'GADWP_Frontend_Widget' );
169
+ }
170
+
171
+ /**
172
+ * Conditional load
173
+ */
174
+ public function load() {
175
+ if ( is_admin() ) {
176
+ if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
177
+ if ( GADWP_Tools::check_roles( self::$instance->config->options['ga_dash_access_back'] ) ) {
178
+ /*
179
+ * Load Backend ajax actions
180
+ */
181
+ include_once ( GADWP_DIR . 'admin/ajax-actions.php' );
182
+ self::$instance->backend_actions = new GADWP_Backend_Ajax();
183
+ }
184
+
185
+ /*
186
+ * Load Frontend ajax actions
187
+ */
188
+ include_once ( GADWP_DIR . 'front/ajax-actions.php' );
189
+ self::$instance->frontend_actions = new GADWP_Frontend_Ajax();
190
+
191
+ /*
192
+ * Load Common ajax actions
193
+ */
194
+ include_once ( GADWP_DIR . 'common/ajax-actions.php' );
195
+ self::$instance->common_actions = new GADWP_Common_Ajax();
196
+ } else if ( GADWP_Tools::check_roles( self::$instance->config->options['ga_dash_access_back'] ) ) {
197
+ /*
198
+ * Load Backend Setup
199
+ */
200
+ include_once ( GADWP_DIR . 'admin/setup.php' );
201
+ self::$instance->backend_setup = new GADWP_Backend_Setup();
202
+
203
+ if ( self::$instance->config->options['dashboard_widget'] ) {
204
+ /*
205
+ * Load Backend Widget
206
+ */
207
+ include_once ( GADWP_DIR . 'admin/widgets.php' );
208
+ self::$instance->backend_widgets = new GADWP_Backend_Widgets();
209
+ }
210
+
211
+ if ( self::$instance->config->options['backend_item_reports'] ) {
212
+ /*
213
+ * Load Backend Item Reports
214
+ */
215
+ include_once ( GADWP_DIR . 'admin/item-reports.php' );
216
+ self::$instance->backend_item_reports = new GADWP_Backend_Item_Reports();
217
+ }
218
+ }
219
+ } else {
220
+ if ( GADWP_Tools::check_roles( self::$instance->config->options['ga_dash_access_front'] ) ) {
221
+ /*
222
+ * Load Frontend Setup
223
+ */
224
+ include_once ( GADWP_DIR . 'front/setup.php' );
225
+ self::$instance->frontend_setup = new GADWP_Frontend_Setup();
226
+
227
+ if ( self::$instance->config->options['frontend_item_reports'] ) {
228
+ /*
229
+ * Load Frontend Item Reports
230
+ */
231
+ include_once ( GADWP_DIR . 'front/item-reports.php' );
232
+ self::$instance->frontend_item_reports = new GADWP_Frontend_Item_Reports();
233
+ }
234
+ }
235
+
236
+ if ( ! GADWP_Tools::check_roles( self::$instance->config->options['ga_track_exclude'], true ) && self::$instance->config->options['ga_dash_tracking'] ) {
237
+ /*
238
+ * Load tracking class
239
+ */
240
+ include_once ( GADWP_DIR . 'front/tracking.php' );
241
+ self::$instance->tracking = new GADWP_Tracking();
242
+ }
243
+ }
244
+ }
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Returns a unique instance of GADWP
250
+ */
251
+ function GADWP() {
252
+ return GADWP_Manager::instance();
253
+ }
254
+
255
+ /*
256
+ * Start GADWP
257
+ */
258
+ GADWP();
install/install.php CHANGED
@@ -1,149 +1,149 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- class GADWP_Install {
15
-
16
- public static function install() {
17
- if ( ! get_option( 'ga_dash_token' ) ) {
18
- $options = array();
19
- $options['ga_dash_clientid'] = '';
20
- $options['ga_dash_clientsecret'] = '';
21
- $options['ga_dash_access_front'][] = 'administrator';
22
- $options['ga_dash_access_back'][] = 'administrator';
23
- $options['ga_dash_tableid_jail'] = '';
24
- $options['ga_dash_style'] = '#1e73be';
25
- $options['switch_profile'] = 0;
26
- $options['ga_dash_cachetime'] = 3600;
27
- $options['ga_dash_tracking'] = 1;
28
- $options['ga_dash_tracking_type'] = 'universal';
29
- $options['ga_dash_default_ua'] = '';
30
- $options['ga_dash_anonim'] = 0;
31
- $options['ga_dash_userapi'] = 0;
32
- $options['ga_event_tracking'] = 0;
33
- $options['ga_event_downloads'] = 'zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*';
34
- $options['ga_track_exclude'] = array();
35
- $options['ga_target_geomap'] = '';
36
- $options['ga_realtime_pages'] = 10;
37
- $options['ga_dash_token'] = '';
38
- $options['ga_dash_profile_list'] = array();
39
- $options['ga_dash_frontend_keywords'] = 0;
40
- $options['ga_tracking_code'] = '';
41
- $options['ga_enhanced_links'] = 0;
42
- $options['ga_dash_remarketing'] = 0;
43
- $options['ga_dash_frontend_stats'] = 0;
44
- $options['ga_dash_network'] = 0;
45
- $options['ga_dash_adsense'] = 0;
46
- $options['ga_speed_samplerate'] = 1;
47
- $options['ga_event_bouncerate'] = 0;
48
- $options['ga_crossdomain_tracking'] = 0;
49
- $options['ga_crossdomain_list'] = '';
50
- $options['ga_author_dimindex'] = 0;
51
- $options['ga_category_dimindex'] = 0;
52
- $options['ga_tag_dimindex'] = 0;
53
- $options['ga_user_dimindex'] = 0;
54
- $options['ga_pubyear_dimindex'] = 0;
55
- $options['ga_pubyearmonth_dimindex'] = 0;
56
- $options['ga_aff_tracking'] = 0;
57
- $options['ga_event_affiliates'] = '/out/';
58
- $options['automatic_updates_minorversion'] = 1;
59
- $options['backend_item_reports'] = 1;
60
- $options['frontend_item_reports'] = 0;
61
- $options['dashboard_widget'] = 1;
62
- $options['api_backoff'] = 0;
63
- $options['ga_cookiedomain'] = '';
64
- $options['ga_cookiename'] = '';
65
- $options['ga_cookieexpires'] = '';
66
- $option['pagetitle_404'] = 'Page Not Found';
67
- $option['maps_api_key'] = '';
68
-
69
- } else {
70
- $options = array();
71
- $options['ga_dash_clientid'] = get_option( 'ga_dash_clientid' );
72
- $options['ga_dash_clientsecret'] = get_option( 'ga_dash_clientsecret' );
73
- $options['ga_dash_access'] = get_option( 'ga_dash_access' );
74
- $options['ga_dash_access_front'][] = 'administrator';
75
- $options['ga_dash_access_back'][] = 'administrator';
76
- $options['ga_dash_tableid_jail'] = get_option( 'ga_dash_tableid_jail' );
77
- $options['ga_dash_frontend_stats'] = get_option( 'ga_dash_frontend' );
78
- $options['ga_dash_style'] = '#1e73be';
79
- $options['switch_profile'] = get_option( 'ga_dash_jailadmins' );
80
- $options['ga_dash_cachetime'] = get_option( 'ga_dash_cachetime' );
81
- if ( get_option( 'ga_dash_tracking' ) == 4 ) {
82
- $options['ga_dash_tracking'] = 0;
83
- } else {
84
- $options['ga_dash_tracking'] = 1;
85
- }
86
- $options['ga_dash_tracking_type'] = get_option( 'ga_dash_tracking_type' );
87
- $options['ga_dash_default_ua'] = get_option( 'ga_dash_default_ua' );
88
- $options['ga_dash_anonim'] = get_option( 'ga_dash_anonim' );
89
- $options['ga_dash_userapi'] = get_option( 'ga_dash_userapi' );
90
- $options['ga_event_tracking'] = get_option( 'ga_event_tracking' );
91
- $options['ga_event_downloads'] = get_option( 'ga_event_downloads' );
92
- $options['ga_track_exclude'] = array();
93
- $options['ga_target_geomap'] = get_option( 'ga_target_geomap' );
94
- $options['ga_realtime_pages'] = get_option( 'ga_realtime_pages' );
95
- $options['ga_dash_token'] = get_option( 'ga_dash_token' );
96
- $options['ga_dash_profile_list'] = get_option( 'ga_dash_profile_list' );
97
- $options['ga_dash_frontend_keywords'] = 0;
98
- $options['ga_enhanced_links'] = 0;
99
- $options['ga_dash_remarketing'] = 0;
100
- $options['ga_dash_network'] = 0;
101
- $options['ga_event_bouncerate'] = 0;
102
- $options['ga_crossdomain_tracking'] = 0;
103
- $options['ga_crossdomain_list'] = '';
104
- $options['ga_author_dimindex'] = 0;
105
- $options['ga_category_dimindex'] = 0;
106
- $options['ga_tag_dimindex'] = 0;
107
- $options['ga_user_dimindex'] = 0;
108
- $options['ga_pubyear_dimindex'] = 0;
109
- $options['ga_pubyearmonth_dimindex'] = 0;
110
- $options['ga_event_affiliates'] = '/out/';
111
- $options['ga_aff_tracking'] = 0;
112
- $options['automatic_updates_minorversion'] = 1;
113
- $options['backend_item_reports'] = 1;
114
- $options['frontend_item_reports'] = 0;
115
- $options['dashboard_widget'] = 1;
116
- $options['api_backoff'] = 0;
117
- $options['ga_cookiedomain'] = '';
118
- $options['ga_cookiename'] = '';
119
- $options['ga_cookieexpires'] = '';
120
- $option['pagetitle_404'] = 'Page Not Found';
121
- $option['maps_api_key'] = '';
122
-
123
- delete_option( 'ga_dash_clientid' );
124
- delete_option( 'ga_dash_clientsecret' );
125
- delete_option( 'ga_dash_access' );
126
- delete_option( 'ga_dash_access_front' );
127
- delete_option( 'ga_dash_access_back' );
128
- delete_option( 'ga_dash_tableid_jail' );
129
- delete_option( 'ga_dash_frontend' );
130
- delete_option( 'ga_dash_style' );
131
- delete_option( 'ga_dash_jailadmins' );
132
- delete_option( 'ga_dash_cachetime' );
133
- delete_option( 'ga_dash_tracking' );
134
- delete_option( 'ga_dash_tracking_type' );
135
- delete_option( 'ga_dash_default_ua' );
136
- delete_option( 'ga_dash_anonim' );
137
- delete_option( 'ga_dash_userapi' );
138
- delete_option( 'ga_event_tracking' );
139
- delete_option( 'ga_event_downloads' );
140
- delete_option( 'ga_track_exclude' );
141
- delete_option( 'ga_target_geomap' );
142
- delete_option( 'ga_realtime_pages' );
143
- delete_option( 'ga_dash_token' );
144
- delete_option( 'ga_dash_refresh_token' );
145
- delete_option( 'ga_dash_profile_list' );
146
- }
147
- add_option( 'gadash_options', json_encode( $options ) );
148
- }
149
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ class GADWP_Install {
15
+
16
+ public static function install() {
17
+ if ( ! get_option( 'ga_dash_token' ) ) {
18
+ $options = array();
19
+ $options['ga_dash_clientid'] = '';
20
+ $options['ga_dash_clientsecret'] = '';
21
+ $options['ga_dash_access_front'][] = 'administrator';
22
+ $options['ga_dash_access_back'][] = 'administrator';
23
+ $options['ga_dash_tableid_jail'] = '';
24
+ $options['ga_dash_style'] = '#1e73be';
25
+ $options['switch_profile'] = 0;
26
+ $options['ga_dash_cachetime'] = 3600;
27
+ $options['ga_dash_tracking'] = 1;
28
+ $options['ga_dash_tracking_type'] = 'universal';
29
+ $options['ga_dash_default_ua'] = '';
30
+ $options['ga_dash_anonim'] = 0;
31
+ $options['ga_dash_userapi'] = 0;
32
+ $options['ga_event_tracking'] = 0;
33
+ $options['ga_event_downloads'] = 'zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*';
34
+ $options['ga_track_exclude'] = array();
35
+ $options['ga_target_geomap'] = '';
36
+ $options['ga_realtime_pages'] = 10;
37
+ $options['ga_dash_token'] = '';
38
+ $options['ga_dash_profile_list'] = array();
39
+ $options['ga_dash_frontend_keywords'] = 0;
40
+ $options['ga_tracking_code'] = '';
41
+ $options['ga_enhanced_links'] = 0;
42
+ $options['ga_dash_remarketing'] = 0;
43
+ $options['ga_dash_frontend_stats'] = 0;
44
+ $options['ga_dash_network'] = 0;
45
+ $options['ga_dash_adsense'] = 0;
46
+ $options['ga_speed_samplerate'] = 1;
47
+ $options['ga_event_bouncerate'] = 0;
48
+ $options['ga_crossdomain_tracking'] = 0;
49
+ $options['ga_crossdomain_list'] = '';
50
+ $options['ga_author_dimindex'] = 0;
51
+ $options['ga_category_dimindex'] = 0;
52
+ $options['ga_tag_dimindex'] = 0;
53
+ $options['ga_user_dimindex'] = 0;
54
+ $options['ga_pubyear_dimindex'] = 0;
55
+ $options['ga_pubyearmonth_dimindex'] = 0;
56
+ $options['ga_aff_tracking'] = 0;
57
+ $options['ga_event_affiliates'] = '/out/';
58
+ $options['automatic_updates_minorversion'] = 1;
59
+ $options['backend_item_reports'] = 1;
60
+ $options['frontend_item_reports'] = 0;
61
+ $options['dashboard_widget'] = 1;
62
+ $options['api_backoff'] = 0;
63
+ $options['ga_cookiedomain'] = '';
64
+ $options['ga_cookiename'] = '';
65
+ $options['ga_cookieexpires'] = '';
66
+ $option['pagetitle_404'] = 'Page Not Found';
67
+ $option['maps_api_key'] = '';
68
+
69
+ } else {
70
+ $options = array();
71
+ $options['ga_dash_clientid'] = get_option( 'ga_dash_clientid' );
72
+ $options['ga_dash_clientsecret'] = get_option( 'ga_dash_clientsecret' );
73
+ $options['ga_dash_access'] = get_option( 'ga_dash_access' );
74
+ $options['ga_dash_access_front'][] = 'administrator';
75
+ $options['ga_dash_access_back'][] = 'administrator';
76
+ $options['ga_dash_tableid_jail'] = get_option( 'ga_dash_tableid_jail' );
77
+ $options['ga_dash_frontend_stats'] = get_option( 'ga_dash_frontend' );
78
+ $options['ga_dash_style'] = '#1e73be';
79
+ $options['switch_profile'] = get_option( 'ga_dash_jailadmins' );
80
+ $options['ga_dash_cachetime'] = get_option( 'ga_dash_cachetime' );
81
+ if ( get_option( 'ga_dash_tracking' ) == 4 ) {
82
+ $options['ga_dash_tracking'] = 0;
83
+ } else {
84
+ $options['ga_dash_tracking'] = 1;
85
+ }
86
+ $options['ga_dash_tracking_type'] = get_option( 'ga_dash_tracking_type' );
87
+ $options['ga_dash_default_ua'] = get_option( 'ga_dash_default_ua' );
88
+ $options['ga_dash_anonim'] = get_option( 'ga_dash_anonim' );
89
+ $options['ga_dash_userapi'] = get_option( 'ga_dash_userapi' );
90
+ $options['ga_event_tracking'] = get_option( 'ga_event_tracking' );
91
+ $options['ga_event_downloads'] = get_option( 'ga_event_downloads' );
92
+ $options['ga_track_exclude'] = array();
93
+ $options['ga_target_geomap'] = get_option( 'ga_target_geomap' );
94
+ $options['ga_realtime_pages'] = get_option( 'ga_realtime_pages' );
95
+ $options['ga_dash_token'] = get_option( 'ga_dash_token' );
96
+ $options['ga_dash_profile_list'] = get_option( 'ga_dash_profile_list' );
97
+ $options['ga_dash_frontend_keywords'] = 0;
98
+ $options['ga_enhanced_links'] = 0;
99
+ $options['ga_dash_remarketing'] = 0;
100
+ $options['ga_dash_network'] = 0;
101
+ $options['ga_event_bouncerate'] = 0;
102
+ $options['ga_crossdomain_tracking'] = 0;
103
+ $options['ga_crossdomain_list'] = '';
104
+ $options['ga_author_dimindex'] = 0;
105
+ $options['ga_category_dimindex'] = 0;
106
+ $options['ga_tag_dimindex'] = 0;
107
+ $options['ga_user_dimindex'] = 0;
108
+ $options['ga_pubyear_dimindex'] = 0;
109
+ $options['ga_pubyearmonth_dimindex'] = 0;
110
+ $options['ga_event_affiliates'] = '/out/';
111
+ $options['ga_aff_tracking'] = 0;
112
+ $options['automatic_updates_minorversion'] = 1;
113
+ $options['backend_item_reports'] = 1;
114
+ $options['frontend_item_reports'] = 0;
115
+ $options['dashboard_widget'] = 1;
116
+ $options['api_backoff'] = 0;
117
+ $options['ga_cookiedomain'] = '';
118
+ $options['ga_cookiename'] = '';
119
+ $options['ga_cookieexpires'] = '';
120
+ $option['pagetitle_404'] = 'Page Not Found';
121
+ $option['maps_api_key'] = '';
122
+
123
+ delete_option( 'ga_dash_clientid' );
124
+ delete_option( 'ga_dash_clientsecret' );
125
+ delete_option( 'ga_dash_access' );
126
+ delete_option( 'ga_dash_access_front' );
127
+ delete_option( 'ga_dash_access_back' );
128
+ delete_option( 'ga_dash_tableid_jail' );
129
+ delete_option( 'ga_dash_frontend' );
130
+ delete_option( 'ga_dash_style' );
131
+ delete_option( 'ga_dash_jailadmins' );
132
+ delete_option( 'ga_dash_cachetime' );
133
+ delete_option( 'ga_dash_tracking' );
134
+ delete_option( 'ga_dash_tracking_type' );
135
+ delete_option( 'ga_dash_default_ua' );
136
+ delete_option( 'ga_dash_anonim' );
137
+ delete_option( 'ga_dash_userapi' );
138
+ delete_option( 'ga_event_tracking' );
139
+ delete_option( 'ga_event_downloads' );
140
+ delete_option( 'ga_track_exclude' );
141
+ delete_option( 'ga_target_geomap' );
142
+ delete_option( 'ga_realtime_pages' );
143
+ delete_option( 'ga_dash_token' );
144
+ delete_option( 'ga_dash_refresh_token' );
145
+ delete_option( 'ga_dash_profile_list' );
146
+ }
147
+ add_option( 'gadash_options', json_encode( $options ) );
148
+ }
149
+ }
install/uninstall.php CHANGED
@@ -1,34 +1,34 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- class GADWP_Uninstall {
15
-
16
- public static function uninstall() {
17
- global $wpdb;
18
- if ( is_multisite() ) { // Cleanup Network install
19
- foreach ( GADWP_Tools::get_sites( array( 'limit' => apply_filters( 'gadwp_sites_limit', 100 ) ) ) as $blog ) {
20
- switch_to_blog( $blog['blog_id'] );
21
- $sqlquery = $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'gadwp_cache_%%'" );
22
- delete_option( 'gadash_options' );
23
- restore_current_blog();
24
- }
25
- delete_site_option( 'gadash_network_options' );
26
- } else { // Cleanup Single install
27
- $sqlquery = $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'gadwp_cache_%%'" );
28
- delete_option( 'gadash_options' );
29
- }
30
- GADWP_Tools::unset_cookie( 'default_metric' );
31
- GADWP_Tools::unset_cookie( 'default_dimension' );
32
- GADWP_Tools::unset_cookie( 'default_view' );
33
- }
34
- }
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ class GADWP_Uninstall {
15
+
16
+ public static function uninstall() {
17
+ global $wpdb;
18
+ if ( is_multisite() ) { // Cleanup Network install
19
+ foreach ( GADWP_Tools::get_sites( array( 'limit' => apply_filters( 'gadwp_sites_limit', 100 ) ) ) as $blog ) {
20
+ switch_to_blog( $blog['blog_id'] );
21
+ $sqlquery = $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'gadwp_cache_%%'" );
22
+ delete_option( 'gadash_options' );
23
+ restore_current_blog();
24
+ }
25
+ delete_site_option( 'gadash_network_options' );
26
+ } else { // Cleanup Single install
27
+ $sqlquery = $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'gadwp_cache_%%'" );
28
+ delete_option( 'gadash_options' );
29
+ }
30
+ GADWP_Tools::unset_cookie( 'default_metric' );
31
+ GADWP_Tools::unset_cookie( 'default_dimension' );
32
+ GADWP_Tools::unset_cookie( 'default_view' );
33
+ }
34
+ }
readme.txt CHANGED
@@ -4,7 +4,7 @@ Donate link: https://deconf.com/donate/
4
  Tags: google,analytics,google analytics,dashboard,analytics dashboard,google analytics dashboard,google analytics plugin,google analytics widget,tracking,universal google analytics,realtime,multisite,gadwp
5
  Requires at least: 3.5
6
  Tested up to: 4.7
7
- Stable tag: 4.9.4
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
@@ -137,6 +137,14 @@ Google Analytics Dashboard for WP it's released under the GPLv2, you can use it
137
 
138
  == Changelog ==
139
 
 
 
 
 
 
 
 
 
140
  = 4.9.4 =
141
  * Enhancements:
142
  * always load analytics.js over SSL
4
  Tags: google,analytics,google analytics,dashboard,analytics dashboard,google analytics dashboard,google analytics plugin,google analytics widget,tracking,universal google analytics,realtime,multisite,gadwp
5
  Requires at least: 3.5
6
  Tested up to: 4.7
7
+ Stable tag: 4.9.5
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
137
 
138
  == Changelog ==
139
 
140
+ = 4.9.5 =
141
+ * Bug Fixes:
142
+ * correction of some files with mixed endings, props by [Edward Dekker](http://www.github.com/edwarddekker)
143
+ * only load the necessary resources for frontend widget
144
+ * corrected a JavaScript error on frontend sidebar widget
145
+ * Enhancements:
146
+ * introducing the <strong>gadwp_curl_options</strong> filter to allow changes on CURL options for the Google_IO_Curl class, props by [Alexandre Simard](https://github.com/brocheafoin)
147
+
148
  = 4.9.4 =
149
  * Enhancements:
150
  * always load analytics.js over SSL
tools/autoload.php CHANGED
@@ -1,38 +1,38 @@
1
- <?php
2
-
3
- /*
4
- * Copyright 2014 Google Inc.
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */
18
-
19
- // Exit if accessed directly
20
- if (! defined('ABSPATH'))
21
- exit();
22
-
23
- function google_api_php_client_autoload_gadwp($className)
24
- {
25
- $classPath = explode('_', $className);
26
- if ($classPath[0] != 'Google') {
27
- return;
28
- }
29
- if (count($classPath) > 3) {
30
- // Maximum class file path depth in this project is 3.
31
- $classPath = array_slice($classPath, 0, 3);
32
- }
33
- $filePath = dirname(__FILE__) . '/src/' . implode('/', $classPath) . '.php';
34
- if (file_exists($filePath)) {
35
- require_once ($filePath);
36
- }
37
- }
38
  spl_autoload_register('google_api_php_client_autoload_gadwp');
1
+ <?php
2
+
3
+ /*
4
+ * Copyright 2014 Google Inc.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ // Exit if accessed directly
20
+ if (! defined('ABSPATH'))
21
+ exit();
22
+
23
+ function google_api_php_client_autoload_gadwp($className)
24
+ {
25
+ $classPath = explode('_', $className);
26
+ if ($classPath[0] != 'Google') {
27
+ return;
28
+ }
29
+ if (count($classPath) > 3) {
30
+ // Maximum class file path depth in this project is 3.
31
+ $classPath = array_slice($classPath, 0, 3);
32
+ }
33
+ $filePath = dirname(__FILE__) . '/src/' . implode('/', $classPath) . '.php';
34
+ if (file_exists($filePath)) {
35
+ require_once ($filePath);
36
+ }
37
+ }
38
  spl_autoload_register('google_api_php_client_autoload_gadwp');
tools/gapi.php CHANGED
@@ -1,862 +1,867 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- if ( ! class_exists( 'GADWP_GAPI_Controller' ) ) {
15
-
16
- final class GADWP_GAPI_Controller {
17
-
18
- public $client;
19
-
20
- public $service;
21
-
22
- public $timeshift;
23
-
24
- public $error_timeout;
25
-
26
- private $managequota;
27
-
28
- private $gadwp;
29
-
30
- private $access = array( '65556128672.apps.googleusercontent.com', 'Kc7888wgbc_JbeCmApbFjnYpwE' );
31
-
32
- public function __construct() {
33
- $this->gadwp = GADWP();
34
-
35
- include_once ( GADWP_DIR . 'tools/autoload.php' );
36
- $config = new Google_Config();
37
- $config->setCacheClass( 'Google_Cache_Null' );
38
- if ( function_exists( 'curl_version' ) ) {
39
- $curlversion = curl_version();
40
- if ( isset( $curlversion['version'] ) && ( version_compare( PHP_VERSION, '5.3.0' ) >= 0 ) && version_compare( $curlversion['version'], '7.10.8' ) >= 0 && defined( 'GADWP_IP_VERSION' ) && GADWP_IP_VERSION ) {
41
- $config->setClassConfig( 'Google_IO_Curl', array( 'options' => array( CURLOPT_IPRESOLVE => GADWP_IP_VERSION ) ) ); // Force CURL_IPRESOLVE_V4 or CURL_IPRESOLVE_V6
42
- }
43
- }
44
- $this->client = new Google_Client( $config );
45
- $this->client->setScopes( 'https://www.googleapis.com/auth/analytics.readonly' );
46
- $this->client->setAccessType( 'offline' );
47
- $this->client->setApplicationName( 'Google Analytics Dashboard' );
48
- $this->client->setRedirectUri( 'urn:ietf:wg:oauth:2.0:oob' );
49
- $this->set_error_timeout();
50
- $this->managequota = 'u' . get_current_user_id() . 's' . get_current_blog_id();
51
- $this->access = array_map( array( $this, 'map' ), $this->access );
52
- if ( $this->gadwp->config->options['ga_dash_userapi'] ) {
53
- $this->client->setClientId( $this->gadwp->config->options['ga_dash_clientid'] );
54
- $this->client->setClientSecret( $this->gadwp->config->options['ga_dash_clientsecret'] );
55
- } else {
56
- $this->client->setClientId( $this->access[0] );
57
- $this->client->setClientSecret( $this->access[1] );
58
- }
59
- $this->service = new Google_Service_Analytics( $this->client );
60
- if ( $this->gadwp->config->options['ga_dash_token'] ) {
61
- $token = $this->gadwp->config->options['ga_dash_token'];
62
- if ( $token ) {
63
- try {
64
- $this->client->setAccessToken( $token );
65
- $gadwp->config->options['ga_dash_token'] = $this->client->getAccessToken();
66
- } catch ( Google_IO_Exception $e ) {
67
- GADWP_Tools::set_cache( 'ga_dash_lasterror', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
68
- } catch ( Google_Service_Exception $e ) {
69
- GADWP_Tools::set_cache( 'ga_dash_lasterror', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $this->error_timeout );
70
- GADWP_Tools::set_cache( 'ga_dash_gapi_errors', array( $e->getCode(), (array) $e->getErrors() ), $this->error_timeout );
71
- $this->reset_token();
72
- } catch ( Exception $e ) {
73
- GADWP_Tools::set_cache( 'ga_dash_lasterror', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
74
- $this->reset_token();
75
- }
76
- if ( is_multisite() && $this->gadwp->config->options['ga_dash_network'] ) {
77
- $this->gadwp->config->set_plugin_options( true );
78
- } else {
79
- $this->gadwp->config->set_plugin_options();
80
- }
81
- }
82
- }
83
- }
84
-
85
- private function set_error_timeout() {
86
- $midnight = strtotime( "tomorrow 00:00:00" ); // UTC midnight
87
- $midnight = $midnight + 8 * 3600; // UTC 8 AM
88
- $this->error_timeout = $midnight - time();
89
- return;
90
- }
91
-
92
- /**
93
- * Handles errors returned by GAPI Library
94
- *
95
- * @return boolean
96
- */
97
- public function gapi_errors_handler() {
98
- $errors = GADWP_Tools::get_cache( 'gapi_errors' );
99
- if ( $errors === false || ! isset( $errors[0] ) ) { // invalid error
100
- return false;
101
- }
102
- if ( isset( $errors[1][0]['reason'] ) && ( $errors[1][0]['reason'] == 'invalidCredentials' || $errors[1][0]['reason'] == 'authError' || $errors[1][0]['reason'] == 'insufficientPermissions' || $errors[1][0]['reason'] == 'required' || $errors[1][0]['reason'] == 'keyExpired' ) ) {
103
- $this->reset_token( false );
104
- return true;
105
- }
106
- if ( isset( $errors[1][0]['reason'] ) && ( $errors[1][0]['reason'] == 'userRateLimitExceeded' || $errors[1][0]['reason'] == 'quotaExceeded' ) ) {
107
- if ( $this->gadwp->config->options['api_backoff'] <= 5 ) {
108
- usleep( rand( 100000, 1500000 ) );
109
- $this->gadwp->config->options['api_backoff'] = $this->gadwp->config->options['api_backoff'] + 1;
110
- $this->gadwp->config->set_plugin_options();
111
- return false;
112
- } else {
113
- return true;
114
- }
115
- }
116
- if ( $errors[0] == 400 || $errors[0] == 401 || $errors[0] == 403 ) {
117
- return true;
118
- }
119
- return false;
120
- }
121
-
122
- /**
123
- * Calculates proper timeouts for each GAPI query
124
- *
125
- * @param
126
- * $daily
127
- * @return number
128
- */
129
- public function get_timeouts( $daily ) {
130
- $local_time = time() + $this->timeshift;
131
- if ( $daily ) {
132
- $nextday = explode( '-', date( 'n-j-Y', strtotime( ' +1 day', $local_time ) ) );
133
- $midnight = mktime( 0, 0, 0, $nextday[0], $nextday[1], $nextday[2] );
134
- return $midnight - $local_time;
135
- } else {
136
- $nexthour = explode( '-', date( 'H-n-j-Y', strtotime( ' +1 hour', $local_time ) ) );
137
- $newhour = mktime( $nexthour[0], 0, 0, $nexthour[1], $nexthour[2], $nexthour[3] );
138
- return $newhour - $local_time;
139
- }
140
- }
141
-
142
- /**
143
- * Generates and retrieves the Access Code
144
- */
145
- public function token_request() {
146
- $authUrl = $this->client->createAuthUrl();
147
- ?>
148
- <form name="input" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post">
149
- <table class="gadwp-settings-options">
150
- <tr>
151
- <td colspan="2" class="gadwp-settings-info">
152
- <?php echo __( "Use this link to get your access code:", 'google-analytics-dashboard-for-wp' ) . ' <a href="' . $authUrl . '" id="gapi-access-code" target="_blank">' . __ ( "Get Access Code", 'google-analytics-dashboard-for-wp' ) . '</a>.'; ?>
153
- </td>
154
- </tr>
155
- <tr>
156
- <td class="gadwp-settings-title"><label for="ga_dash_code" title="<?php _e("Use the red link to get your access code!",'google-analytics-dashboard-for-wp')?>"><?php echo _e( "Access Code:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
157
- <td><input type="text" id="ga_dash_code" name="ga_dash_code" value="" size="61" required="required" title="<?php _e("Use the red link to get your access code!",'google-analytics-dashboard-for-wp')?>"></td>
158
- </tr>
159
- <tr>
160
- <td colspan="2"><hr></td>
161
- </tr>
162
- <tr>
163
- <td colspan="2"><input type="submit" class="button button-secondary" name="ga_dash_authorize" value="<?php _e( "Save Access Code", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
164
- </tr>
165
- </table>
166
- </form>
167
- <?php
168
- }
169
-
170
- /**
171
- * Retrieves all Google Analytics Views with details
172
- *
173
- * @return array
174
- */
175
- public function refresh_profiles() {
176
- try {
177
-
178
- $ga_dash_profile_list = array();
179
- $startindex = 1;
180
- $totalresults = 65535; // use something big
181
-
182
- while ( $startindex < $totalresults ) {
183
-
184
- $profiles = $this->service->management_profiles->listManagementProfiles( '~all', '~all', array( 'start-index' => $startindex ) );
185
-
186
- $items = $profiles->getItems();
187
-
188
- $totalresults = $profiles->getTotalResults();
189
-
190
- if ( $totalresults > 0 ) {
191
-
192
- foreach ( $items as $profile ) {
193
- $timetz = new DateTimeZone( $profile->getTimezone() );
194
- $localtime = new DateTime( 'now', $timetz );
195
- $timeshift = strtotime( $localtime->format( 'Y-m-d H:i:s' ) ) - time();
196
- $ga_dash_profile_list[] = array( $profile->getName(), $profile->getId(), $profile->getwebPropertyId(), $profile->getwebsiteUrl(), $timeshift, $profile->getTimezone(), $profile->getDefaultPage() );
197
- $startindex++;
198
- }
199
- }
200
- }
201
-
202
- if ( empty( $ga_dash_profile_list ) ) {
203
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': No properties were found in this account!', $this->error_timeout );
204
- } else {
205
- GADWP_Tools::delete_cache( 'last_error' );
206
- }
207
- return $ga_dash_profile_list;
208
- } catch ( Google_IO_Exception $e ) {
209
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
210
- return $ga_dash_profile_list;
211
- } catch ( Google_Service_Exception $e ) {
212
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $this->error_timeout );
213
- GADWP_Tools::set_cache( 'gapi_errors', array( $e->getCode(), (array) $e->getErrors() ), $this->error_timeout );
214
- } catch ( Exception $e ) {
215
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
216
- return $ga_dash_profile_list;
217
- }
218
- }
219
-
220
- /**
221
- * Handles the token reset process
222
- *
223
- * @param
224
- * $all
225
- */
226
- public function reset_token( $all = true ) {
227
- $this->gadwp->config->options['ga_dash_token'] = "";
228
- if ( $all ) {
229
- $this->gadwp->config->options['ga_dash_tableid_jail'] = "";
230
- $this->gadwp->config->options['ga_dash_profile_list'] = array();
231
- try {
232
- $this->client->revokeToken();
233
- } catch ( Exception $e ) {
234
- if ( is_multisite() && $this->gadwp->config->options['ga_dash_network'] ) {
235
- $this->gadwp->config->set_plugin_options( true );
236
- } else {
237
- $this->gadwp->config->set_plugin_options();
238
- }
239
- }
240
- }
241
- if ( is_multisite() && $this->gadwp->config->options['ga_dash_network'] ) {
242
- $this->gadwp->config->set_plugin_options( true );
243
- } else {
244
- $this->gadwp->config->set_plugin_options();
245
- }
246
- }
247
-
248
- /**
249
- * Get and cache Core Reports
250
- *
251
- * @param
252
- * $projecId
253
- * @param
254
- * $from
255
- * @param
256
- * $to
257
- * @param
258
- * $metrics
259
- * @param
260
- * $options
261
- * @param
262
- * $serial
263
- * @return int|Google_Service_Analytics_GaData
264
- */
265
- private function handle_corereports( $projectId, $from, $to, $metrics, $options, $serial ) {
266
- try {
267
- if ( $from == "today" ) {
268
- $timeouts = 0;
269
- } else {
270
- $timeouts = 1;
271
- }
272
- $transient = GADWP_Tools::get_cache( $serial );
273
- if ( $transient === false ) {
274
- if ( $this->gapi_errors_handler() ) {
275
- return - 23;
276
- }
277
- $data = $this->service->data_ga->get( 'ga:' . $projectId, $from, $to, $metrics, $options );
278
- GADWP_Tools::set_cache( $serial, $data, $this->get_timeouts( $timeouts ) );
279
- $this->gadwp->config->options['api_backoff'] = 0;
280
- $this->gadwp->config->set_plugin_options();
281
- } else {
282
- $data = $transient;
283
- }
284
- } catch ( Google_Service_Exception $e ) {
285
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $this->error_timeout );
286
- GADWP_Tools::set_cache( 'gapi_errors', array( $e->getCode(), (array) $e->getErrors() ), $this->error_timeout );
287
- return $e->getCode();
288
- } catch ( Exception $e ) {
289
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
290
- return $e->getCode();
291
- }
292
- if ( $data->getRows() > 0 ) {
293
- return $data;
294
- } else {
295
- return - 21;
296
- }
297
- }
298
-
299
- /**
300
- * Generates serials for transients
301
- *
302
- * @param
303
- * $serial
304
- * @return string
305
- */
306
- public function get_serial( $serial ) {
307
- return sprintf( "%u", crc32( $serial ) );
308
- }
309
-
310
- /**
311
- * Analytics data for Area Charts (Admin Dashboard Widget report)
312
- *
313
- * @param
314
- * $projectId
315
- * @param
316
- * $from
317
- * @param
318
- * $to
319
- * @param
320
- * $query
321
- * @param
322
- * $filter
323
- * @return array|int
324
- */
325
- private function get_areachart_data( $projectId, $from, $to, $query, $filter = '' ) {
326
- switch ( $query ) {
327
- case 'users' :
328
- $title = __( "Users", 'google-analytics-dashboard-for-wp' );
329
- break;
330
- case 'pageviews' :
331
- $title = __( "Page Views", 'google-analytics-dashboard-for-wp' );
332
- break;
333
- case 'visitBounceRate' :
334
- $title = __( "Bounce Rate", 'google-analytics-dashboard-for-wp' );
335
- break;
336
- case 'organicSearches' :
337
- $title = __( "Organic Searches", 'google-analytics-dashboard-for-wp' );
338
- break;
339
- default :
340
- $title = __( "Sessions", 'google-analytics-dashboard-for-wp' );
341
- }
342
- $metrics = 'ga:' . $query;
343
- if ( $from == "today" || $from == "yesterday" ) {
344
- $dimensions = 'ga:hour';
345
- $dayorhour = __( "Hour", 'google-analytics-dashboard-for-wp' );
346
- } else if ( $from == "365daysAgo" || $from == "1095daysAgo" ) {
347
- $dimensions = 'ga:yearMonth, ga:month';
348
- $dayorhour = __( "Date", 'google-analytics-dashboard-for-wp' );
349
- } else {
350
- $dimensions = 'ga:date,ga:dayOfWeekName';
351
- $dayorhour = __( "Date", 'google-analytics-dashboard-for-wp' );
352
- }
353
- $options = array( 'dimensions' => $dimensions, 'quotaUser' => $this->managequota . 'p' . $projectId );
354
- if ( $filter ) {
355
- $options['filters'] = 'ga:pagePath==' . $filter;
356
- }
357
- $serial = 'qr2_' . $this->get_serial( $projectId . $from . $metrics . $filter );
358
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
359
- if ( is_numeric( $data ) ) {
360
- return $data;
361
- }
362
- $gadwp_data = array( array( $dayorhour, $title ) );
363
- if ( $from == "today" || $from == "yesterday" ) {
364
- foreach ( $data->getRows() as $row ) {
365
- $gadwp_data[] = array( (int) $row[0] . ':00', round( $row[1], 2 ) );
366
- }
367
- } else if ( $from == "365daysAgo" || $from == "1095daysAgo" ) {
368
- foreach ( $data->getRows() as $row ) {
369
- /*
370
- * translators:
371
- * Example: 'F, Y' will become 'November, 2015'
372
- * For details see: http://php.net/manual/en/function.date.php#refsect1-function.date-parameters
373
- */
374
- $gadwp_data[] = array( date_i18n( __( 'F, Y', 'google-analytics-dashboard-for-wp' ), strtotime( $row[0] . '01' ) ), round( $row[2], 2 ) );
375
- }
376
- } else {
377
- foreach ( $data->getRows() as $row ) {
378
- /*
379
- * translators:
380
- * Example: 'l, F j, Y' will become 'Thusday, November 17, 2015'
381
- * For details see: http://php.net/manual/en/function.date.php#refsect1-function.date-parameters
382
- */
383
- $gadwp_data[] = array( date_i18n( __( 'l, F j, Y', 'google-analytics-dashboard-for-wp' ), strtotime( $row[0] ) ), round( $row[2], 2 ) );
384
- }
385
- }
386
-
387
- return $gadwp_data;
388
- }
389
-
390
- /**
391
- * Analytics data for Bottom Stats (bottom stats on main report)
392
- *
393
- * @param
394
- * $projectId
395
- * @param
396
- * $from
397
- * @param
398
- * $to
399
- * @param
400
- * $filter
401
- * @return array|int
402
- */
403
- private function get_bottomstats( $projectId, $from, $to, $filter = '' ) {
404
- $options = array( 'dimensions' => null, 'quotaUser' => $this->managequota . 'p' . $projectId );
405
- if ( $filter ) {
406
- $options['filters'] = 'ga:pagePath==' . $filter;
407
- $metrics = 'ga:sessions,ga:users,ga:pageviews,ga:BounceRate,ga:organicSearches,ga:pageviewsPerSession';
408
- } else {
409
- $metrics = 'ga:sessions,ga:users,ga:pageviews,ga:BounceRate,ga:organicSearches,ga:pageviewsPerSession';
410
- }
411
- $serial = 'qr3_' . $this->get_serial( $projectId . $from . $filter );
412
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
413
- if ( is_numeric( $data ) ) {
414
- if ( $data == - 21 ) {
415
- return array_fill( 0, 6, 0 );
416
- } else {
417
- return $data;
418
- }
419
- }
420
- $gadwp_data = array();
421
- foreach ( $data->getRows() as $row ) {
422
- $gadwp_data = array_map( 'floatval', $row );
423
- }
424
-
425
- // i18n support
426
- $gadwp_data[0] = number_format_i18n( $gadwp_data[0] );
427
- $gadwp_data[1] = number_format_i18n( $gadwp_data[1] );
428
- $gadwp_data[2] = number_format_i18n( $gadwp_data[2] );
429
- $gadwp_data[3] = number_format_i18n( $gadwp_data[3], 2 );
430
- $gadwp_data[4] = number_format_i18n( $gadwp_data[4] );
431
- $gadwp_data[5] = number_format_i18n( $gadwp_data[5], 2 );
432
-
433
- return $gadwp_data;
434
- }
435
-
436
- /**
437
- * Analytics data for Org Charts & Table Charts (content pages)
438
- *
439
- * @param
440
- * $projectId
441
- * @param
442
- * $from
443
- * @param
444
- * $to
445
- * @param
446
- * $filter
447
- * @return array|int
448
- */
449
- private function get_contentpages( $projectId, $from, $to, $filter = '' ) {
450
- $metrics = 'ga:sessions';
451
- $dimensions = 'ga:pageTitle';
452
- $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
453
- if ( $filter ) {
454
- $options['filters'] = 'ga:pagePath==' . $filter;
455
- }
456
- $serial = 'qr4_' . $this->get_serial( $projectId . $from . $filter );
457
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
458
- if ( is_numeric( $data ) ) {
459
- return $data;
460
- }
461
- $gadwp_data = array( array( __( "Pages", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
462
- foreach ( $data->getRows() as $row ) {
463
- $gadwp_data[] = array( esc_html( $row[0] ), (int) $row[1] );
464
- }
465
- return $gadwp_data;
466
- }
467
-
468
- /**
469
- * Analytics data for 404 Errors
470
- *
471
- * @param
472
- * $projectId
473
- * @param
474
- * $from
475
- * @param
476
- * $to
477
- * @return array|int
478
- */
479
- private function get_404errors( $projectId, $from, $to, $filter = "Page Not Found" ) {
480
- $metrics = 'ga:sessions';
481
- $dimensions = 'ga:pagePath,ga:fullReferrer';
482
- $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
483
- $options['filters'] = 'ga:pageTitle=@' . $filter;
484
- $serial = 'qr4_' . $this->get_serial( $projectId . $from . $filter );
485
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
486
- if ( is_numeric( $data ) ) {
487
- return $data;
488
- }
489
- $gadwp_data = array( array( __( "404 Errors", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
490
- foreach ( $data->getRows() as $row ) {
491
- $path = esc_html( $row[0] );
492
- $source = esc_html( $row[1] );
493
- $gadwp_data[] = array( "<strong>" . __( "URI:", 'google-analytics-dashboard-for-wp' ) . "</strong> " . $path . "<br><strong>" . __( "Source:", 'google-analytics-dashboard-for-wp' ) . "</strong> " . $source, (int) $row[2] );
494
- }
495
- return $gadwp_data;
496
- }
497
-
498
- /**
499
- * Analytics data for Org Charts & Table Charts (referrers)
500
- *
501
- * @param
502
- * $projectId
503
- * @param
504
- * $from
505
- * @param
506
- * $to
507
- * @param
508
- * $filter
509
- * @return array|int
510
- */
511
- private function get_referrers( $projectId, $from, $to, $filter = '' ) {
512
- $metrics = 'ga:sessions';
513
- $dimensions = 'ga:source';
514
- $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
515
- if ( $filter ) {
516
- $options['filters'] = 'ga:medium==referral;ga:pagePath==' . $filter;
517
- } else {
518
- $options['filters'] = 'ga:medium==referral';
519
- }
520
- $serial = 'qr5_' . $this->get_serial( $projectId . $from . $filter );
521
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
522
- if ( is_numeric( $data ) ) {
523
- return $data;
524
- }
525
- $gadwp_data = array( array( __( "Referrers", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
526
- foreach ( $data->getRows() as $row ) {
527
- $gadwp_data[] = array( esc_html( $row[0] ), (int) $row[1] );
528
- }
529
- return $gadwp_data;
530
- }
531
-
532
- /**
533
- * Analytics data for Org Charts & Table Charts (searches)
534
- *
535
- * @param
536
- * $projectId
537
- * @param
538
- * $from
539
- * @param
540
- * $to
541
- * @param
542
- * $filter
543
- * @return array|int
544
- */
545
- private function get_searches( $projectId, $from, $to, $filter = '' ) {
546
- $metrics = 'ga:sessions';
547
- $dimensions = 'ga:keyword';
548
- $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
549
- if ( $filter ) {
550
- $options['filters'] = 'ga:keyword!=(not set);ga:pagePath==' . $filter;
551
- } else {
552
- $options['filters'] = 'ga:keyword!=(not set)';
553
- }
554
- $serial = 'qr6_' . $this->get_serial( $projectId . $from . $filter );
555
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
556
- if ( is_numeric( $data ) ) {
557
- return $data;
558
- }
559
-
560
- $gadwp_data = array( array( __( "Searches", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
561
- foreach ( $data->getRows() as $row ) {
562
- $gadwp_data[] = array( esc_html( $row[0] ), (int) $row[1] );
563
- }
564
- return $gadwp_data;
565
- }
566
-
567
- /**
568
- * Analytics data for Org Charts & Table Charts (location reports)
569
- *
570
- * @param
571
- * $projectId
572
- * @param
573
- * $from
574
- * @param
575
- * $to
576
- * @param
577
- * $filter
578
- * @return array|int
579
- */
580
- private function get_locations( $projectId, $from, $to, $filter = '' ) {
581
- $metrics = 'ga:sessions';
582
- $options = "";
583
- $title = __( "Countries", 'google-analytics-dashboard-for-wp' );
584
- $serial = 'qr7_' . $this->get_serial( $projectId . $from . $filter );
585
- $dimensions = 'ga:country';
586
- $local_filter = '';
587
- if ( $this->gadwp->config->options['ga_target_geomap'] ) {
588
- $dimensions = 'ga:city, ga:region';
589
-
590
- $country_codes = GADWP_Tools::get_countrycodes();
591
- if ( isset( $country_codes[$this->gadwp->config->options['ga_target_geomap']] ) ) {
592
- $local_filter = 'ga:country==' . ( $country_codes[$this->gadwp->config->options['ga_target_geomap']] );
593
- $title = __( "Cities from", 'google-analytics-dashboard-for-wp' ) . ' ' . __( $country_codes[$this->gadwp->config->options['ga_target_geomap']] );
594
- $serial = 'qr7_' . $this->get_serial( $projectId . $from . $this->gadwp->config->options['ga_target_geomap'] . $filter );
595
- }
596
- }
597
- $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
598
- if ( $filter ) {
599
- $options['filters'] = 'ga:pagePath==' . $filter;
600
- if ( $local_filter ) {
601
- $options['filters'] .= ';' . $local_filter;
602
- }
603
- } else {
604
- if ( $local_filter ) {
605
- $options['filters'] = $local_filter;
606
- }
607
- }
608
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
609
- if ( is_numeric( $data ) ) {
610
- return $data;
611
- }
612
- $gadwp_data = array( array( $title, __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
613
- foreach ( $data->getRows() as $row ) {
614
- if ( isset( $row[2] ) ) {
615
- $gadwp_data[] = array( esc_html( $row[0] ) . ', ' . esc_html( $row[1] ), (int) $row[2] );
616
- } else {
617
- $gadwp_data[] = array( esc_html( $row[0] ), (int) $row[1] );
618
- }
619
- }
620
- return $gadwp_data;
621
- }
622
-
623
- /**
624
- * Analytics data for Org Charts (traffic channels, device categories)
625
- *
626
- * @param
627
- * $projectId
628
- * @param
629
- * $from
630
- * @param
631
- * $to
632
- * @param
633
- * $query
634
- * @param
635
- * $filter
636
- * @return array|int
637
- */
638
- private function get_orgchart_data( $projectId, $from, $to, $query, $filter = '' ) {
639
- $metrics = 'ga:sessions';
640
- $dimensions = 'ga:' . $query;
641
- $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
642
- if ( $filter ) {
643
- $options['filters'] = 'ga:pagePath==' . $filter;
644
- }
645
- $serial = 'qr8_' . $this->get_serial( $projectId . $from . $query . $filter );
646
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
647
- if ( is_numeric( $data ) ) {
648
- return $data;
649
- }
650
- $block = ( $query == 'channelGrouping' ) ? __( "Channels", 'google-analytics-dashboard-for-wp' ) : __( "Devices", 'google-analytics-dashboard-for-wp' );
651
- $gadwp_data = array( array( '<div style="color:black; font-size:1.1em">' . $block . '</div><div style="color:darkblue; font-size:1.2em">' . (int) $data['totalsForAllResults']["ga:sessions"] . '</div>', "" ) );
652
- foreach ( $data->getRows() as $row ) {
653
- $shrink = explode( " ", $row[0] );
654
- $gadwp_data[] = array( '<div style="color:black; font-size:1.1em">' . esc_html( $shrink[0] ) . '</div><div style="color:darkblue; font-size:1.2em">' . (int) $row[1] . '</div>', '<div style="color:black; font-size:1.1em">' . $block . '</div><div style="color:darkblue; font-size:1.2em">' . (int) $data['totalsForAllResults']["ga:sessions"] . '</div>' );
655
- }
656
- return $gadwp_data;
657
- }
658
-
659
- /**
660
- * Analytics data for Pie Charts (traffic mediums, serach engines, social networks, browsers, screen rsolutions, etc.)
661
- *
662
- * @param
663
- * $projectId
664
- * @param
665
- * $from
666
- * @param
667
- * $to
668
- * @param
669
- * $query
670
- * @param
671
- * $filter
672
- * @return array|int
673
- */
674
- private function get_piechart_data( $projectId, $from, $to, $query, $filter = '' ) {
675
- $metrics = 'ga:sessions';
676
- $dimensions = 'ga:' . $query;
677
-
678
- if ( $query == 'source' ) {
679
- $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
680
- if ( $filter ) {
681
- $options['filters'] = 'ga:medium==organic;ga:keyword!=(not set);ga:pagePath==' . $filter;
682
- } else {
683
- $options['filters'] = 'ga:medium==organic;ga:keyword!=(not set)';
684
- }
685
- } else {
686
- $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
687
- if ( $filter ) {
688
- $options['filters'] = 'ga:' . $query . '!=(not set);ga:pagePath==' . $filter;
689
- } else {
690
- $options['filters'] = 'ga:' . $query . '!=(not set)';
691
- }
692
- }
693
- $serial = 'qr10_' . $this->get_serial( $projectId . $from . $query . $filter );
694
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
695
- if ( is_numeric( $data ) ) {
696
- return $data;
697
- }
698
- $gadwp_data = array( array( __( "Type", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
699
- $i = 0;
700
- $included = 0;
701
- foreach ( $data->getRows() as $row ) {
702
- if ( $i < 20 ) {
703
- $gadwp_data[] = array( str_replace( "(none)", "direct", esc_html( $row[0] ) ), (int) $row[1] );
704
- $included += $row[1];
705
- $i++;
706
- } else {
707
- break;
708
- }
709
- }
710
- $totals = $data->getTotalsForAllResults();
711
- $others = $totals['ga:sessions'] - $included;
712
- if ( $others > 0 ) {
713
- $gadwp_data[] = array( __( 'Other', 'google-analytics-dashboard-for-wp' ), $others );
714
- }
715
-
716
- return $gadwp_data;
717
- }
718
-
719
- /**
720
- * Analytics data for Frontend Widget (chart data and totals)
721
- *
722
- * @param
723
- * $projectId
724
- * @param
725
- * $period
726
- * @param
727
- * $anonim
728
- * @return array|int
729
- */
730
- public function frontend_widget_stats( $projectId, $from, $anonim ) {
731
- $content = '';
732
- $to = 'yesterday';
733
- $metrics = 'ga:sessions';
734
- $dimensions = 'ga:date,ga:dayOfWeekName';
735
- $options = array( 'dimensions' => $dimensions, 'quotaUser' => $this->managequota . 'p' . $projectId );
736
- $serial = 'qr2_' . $this->get_serial( $projectId . $from . $metrics );
737
- $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
738
- if ( is_numeric( $data ) ) {
739
- return $data;
740
- }
741
- $gadwp_data = array( array( __( "Date", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
742
- if ( $anonim ) {
743
- $max_array = array();
744
- foreach ( $data->getRows() as $item ) {
745
- $max_array[] = $item[2];
746
- }
747
- $max = max( $max_array ) ? max( $max_array ) : 1;
748
- }
749
- foreach ( $data->getRows() as $row ) {
750
- $gadwp_data[] = array( date_i18n( __( 'l, F j, Y', 'google-analytics-dashboard-for-wp' ), strtotime( $row[0] ) ), ( $anonim ? round( $row[2] * 100 / $max, 2 ) : (int) $row[2] ) );
751
- }
752
- $totals = $data->getTotalsForAllResults();
753
- return array( $gadwp_data, $anonim ? 0 : number_format_i18n( $totals['ga:sessions'] ) );
754
- }
755
-
756
- /**
757
- * Analytics data for Realtime component (the real-time report)
758
- *
759
- * @param
760
- * $projectId
761
- * @return array|int
762
- */
763
- private function get_realtime( $projectId ) {
764
- $metrics = 'rt:activeUsers';
765
- $dimensions = 'rt:pagePath,rt:source,rt:keyword,rt:trafficType,rt:visitorType,rt:pageTitle';
766
- try {
767
- $serial = 'qr_realtimecache_' . $this->get_serial( $projectId );
768
- $transient = GADWP_Tools::get_cache( $serial );
769
- if ( $transient === false ) {
770
- if ( $this->gapi_errors_handler() ) {
771
- return - 23;
772
- }
773
- $data = $this->service->data_realtime->get( 'ga:' . $projectId, $metrics, array( 'dimensions' => $dimensions, 'quotaUser' => $this->managequota . 'p' . $projectId ) );
774
- GADWP_Tools::set_cache( $serial, $data, 55 );
775
- $this->gadwp->config->options['api_backoff'] = 0;
776
- $this->gadwp->config->set_plugin_options();
777
- } else {
778
- $data = $transient;
779
- }
780
- } catch ( Google_Service_Exception $e ) {
781
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $this->error_timeout );
782
- GADWP_Tools::set_cache( 'gapi_errors', array( $e->getCode(), (array) $e->getErrors() ), $this->error_timeout );
783
- return $e->getCode();
784
- } catch ( Exception $e ) {
785
- GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
786
- return $e->getCode();
787
- }
788
- if ( $data->getRows() < 1 ) {
789
- return - 21;
790
- }
791
- $i = 0;
792
- $gadwp_data = $data;
793
- foreach ( $data->getRows() as $row ) {
794
- $gadwp_data->rows[$i] = array_map( 'esc_html', $row );
795
- $i++;
796
- }
797
- return array( $gadwp_data );
798
- }
799
-
800
- private function map( $map ) {
801
- $map = explode( '.', $map );
802
- if ( isset( $map[1] ) ) {
803
- $map[0] += ord( 'map' );
804
- return implode( '.', $map );
805
- } else {
806
- return str_ireplace( 'map', chr( 112 ), $map[0] );
807
- }
808
- }
809
-
810
- /**
811
- * Handles ajax requests and calls the needed methods
812
- * @param
813
- * $projectId
814
- * @param
815
- * $query
816
- * @param
817
- * $from
818
- * @param
819
- * $to
820
- * @param
821
- * $filter
822
- * @return number|Google_Service_Analytics_GaData
823
- */
824
- public function get( $projectId, $query, $from = false, $to = false, $filter = '' ) {
825
- if ( empty( $projectId ) || ! is_numeric( $projectId ) ) {
826
- wp_die( - 26 );
827
- }
828
- if ( in_array( $query, array( 'sessions', 'users', 'organicSearches', 'visitBounceRate', 'pageviews') ) ) {
829
- return $this->get_areachart_data( $projectId, $from, $to, $query, $filter );
830
- }
831
- if ( $query == 'bottomstats' ) {
832
- return $this->get_bottomstats( $projectId, $from, $to, $filter );
833
- }
834
- if ( $query == 'locations' ) {
835
- return $this->get_locations( $projectId, $from, $to, $filter );
836
- }
837
- if ( $query == 'referrers' ) {
838
- return $this->get_referrers( $projectId, $from, $to, $filter );
839
- }
840
- if ( $query == 'contentpages' ) {
841
- return $this->get_contentpages( $projectId, $from, $to, $filter );
842
- }
843
- if ( $query == '404errors' ) {
844
- $filter = $this->gadwp->config->options['pagetitle_404'];
845
- return $this->get_404errors( $projectId, $from, $to, $filter );
846
- }
847
- if ( $query == 'searches' ) {
848
- return $this->get_searches( $projectId, $from, $to, $filter );
849
- }
850
- if ( $query == 'realtime' ) {
851
- return $this->get_realtime( $projectId );
852
- }
853
- if ( $query == 'channelGrouping' || $query == 'deviceCategory' ) {
854
- return $this->get_orgchart_data( $projectId, $from, $to, $query, $filter );
855
- }
856
- if ( in_array( $query, array( 'medium', 'visitorType', 'socialNetwork', 'source', 'browser', 'operatingSystem', 'screenResolution', 'mobileDeviceBranding' ) ) ) {
857
- return $this->get_piechart_data( $projectId, $from, $to, $query, $filter );
858
- }
859
- wp_die( - 27 );
860
- }
861
- }
862
- }
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ if ( ! class_exists( 'GADWP_GAPI_Controller' ) ) {
15
+
16
+ final class GADWP_GAPI_Controller {
17
+
18
+ public $client;
19
+
20
+ public $service;
21
+
22
+ public $timeshift;
23
+
24
+ public $error_timeout;
25
+
26
+ private $managequota;
27
+
28
+ private $gadwp;
29
+
30
+ private $access = array( '65556128672.apps.googleusercontent.com', 'Kc7888wgbc_JbeCmApbFjnYpwE' );
31
+
32
+ public function __construct() {
33
+ $this->gadwp = GADWP();
34
+
35
+ include_once ( GADWP_DIR . 'tools/autoload.php' );
36
+ $config = new Google_Config();
37
+ $config->setCacheClass( 'Google_Cache_Null' );
38
+ if ( function_exists( 'curl_version' ) ) {
39
+ $curlversion = curl_version();
40
+ $curl_options = array();
41
+ if ( isset( $curlversion['version'] ) && ( version_compare( PHP_VERSION, '5.3.0' ) >= 0 ) && version_compare( $curlversion['version'], '7.10.8' ) >= 0 && defined( 'GADWP_IP_VERSION' ) && GADWP_IP_VERSION ) {
42
+ $curl_options[CURLOPT_IPRESOLVE] = GADWP_IP_VERSION; // Force CURL_IPRESOLVE_V4 or CURL_IPRESOLVE_V6
43
+ }
44
+ $curl_options = apply_filters( 'gadwp_curl_options', $curl_options );
45
+ if ( !empty( $curl_options ) ) {
46
+ $config->setClassConfig( 'Google_IO_Curl', array( 'options' => $curl_options ) );
47
+ }
48
+ }
49
+ $this->client = new Google_Client( $config );
50
+ $this->client->setScopes( 'https://www.googleapis.com/auth/analytics.readonly' );
51
+ $this->client->setAccessType( 'offline' );
52
+ $this->client->setApplicationName( 'Google Analytics Dashboard' );
53
+ $this->client->setRedirectUri( 'urn:ietf:wg:oauth:2.0:oob' );
54
+ $this->set_error_timeout();
55
+ $this->managequota = 'u' . get_current_user_id() . 's' . get_current_blog_id();
56
+ $this->access = array_map( array( $this, 'map' ), $this->access );
57
+ if ( $this->gadwp->config->options['ga_dash_userapi'] ) {
58
+ $this->client->setClientId( $this->gadwp->config->options['ga_dash_clientid'] );
59
+ $this->client->setClientSecret( $this->gadwp->config->options['ga_dash_clientsecret'] );
60
+ } else {
61
+ $this->client->setClientId( $this->access[0] );
62
+ $this->client->setClientSecret( $this->access[1] );
63
+ }
64
+ $this->service = new Google_Service_Analytics( $this->client );
65
+ if ( $this->gadwp->config->options['ga_dash_token'] ) {
66
+ $token = $this->gadwp->config->options['ga_dash_token'];
67
+ if ( $token ) {
68
+ try {
69
+ $this->client->setAccessToken( $token );
70
+ $gadwp->config->options['ga_dash_token'] = $this->client->getAccessToken();
71
+ } catch ( Google_IO_Exception $e ) {
72
+ GADWP_Tools::set_cache( 'ga_dash_lasterror', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
73
+ } catch ( Google_Service_Exception $e ) {
74
+ GADWP_Tools::set_cache( 'ga_dash_lasterror', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $this->error_timeout );
75
+ GADWP_Tools::set_cache( 'ga_dash_gapi_errors', array( $e->getCode(), (array) $e->getErrors() ), $this->error_timeout );
76
+ $this->reset_token();
77
+ } catch ( Exception $e ) {
78
+ GADWP_Tools::set_cache( 'ga_dash_lasterror', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
79
+ $this->reset_token();
80
+ }
81
+ if ( is_multisite() && $this->gadwp->config->options['ga_dash_network'] ) {
82
+ $this->gadwp->config->set_plugin_options( true );
83
+ } else {
84
+ $this->gadwp->config->set_plugin_options();
85
+ }
86
+ }
87
+ }
88
+ }
89
+
90
+ private function set_error_timeout() {
91
+ $midnight = strtotime( "tomorrow 00:00:00" ); // UTC midnight
92
+ $midnight = $midnight + 8 * 3600; // UTC 8 AM
93
+ $this->error_timeout = $midnight - time();
94
+ return;
95
+ }
96
+
97
+ /**
98
+ * Handles errors returned by GAPI Library
99
+ *
100
+ * @return boolean
101
+ */
102
+ public function gapi_errors_handler() {
103
+ $errors = GADWP_Tools::get_cache( 'gapi_errors' );
104
+ if ( $errors === false || ! isset( $errors[0] ) ) { // invalid error
105
+ return false;
106
+ }
107
+ if ( isset( $errors[1][0]['reason'] ) && ( $errors[1][0]['reason'] == 'invalidCredentials' || $errors[1][0]['reason'] == 'authError' || $errors[1][0]['reason'] == 'insufficientPermissions' || $errors[1][0]['reason'] == 'required' || $errors[1][0]['reason'] == 'keyExpired' ) ) {
108
+ $this->reset_token( false );
109
+ return true;
110
+ }
111
+ if ( isset( $errors[1][0]['reason'] ) && ( $errors[1][0]['reason'] == 'userRateLimitExceeded' || $errors[1][0]['reason'] == 'quotaExceeded' ) ) {
112
+ if ( $this->gadwp->config->options['api_backoff'] <= 5 ) {
113
+ usleep( rand( 100000, 1500000 ) );
114
+ $this->gadwp->config->options['api_backoff'] = $this->gadwp->config->options['api_backoff'] + 1;
115
+ $this->gadwp->config->set_plugin_options();
116
+ return false;
117
+ } else {
118
+ return true;
119
+ }
120
+ }
121
+ if ( $errors[0] == 400 || $errors[0] == 401 || $errors[0] == 403 ) {
122
+ return true;
123
+ }
124
+ return false;
125
+ }
126
+
127
+ /**
128
+ * Calculates proper timeouts for each GAPI query
129
+ *
130
+ * @param
131
+ * $daily
132
+ * @return number
133
+ */
134
+ public function get_timeouts( $daily ) {
135
+ $local_time = time() + $this->timeshift;
136
+ if ( $daily ) {
137
+ $nextday = explode( '-', date( 'n-j-Y', strtotime( ' +1 day', $local_time ) ) );
138
+ $midnight = mktime( 0, 0, 0, $nextday[0], $nextday[1], $nextday[2] );
139
+ return $midnight - $local_time;
140
+ } else {
141
+ $nexthour = explode( '-', date( 'H-n-j-Y', strtotime( ' +1 hour', $local_time ) ) );
142
+ $newhour = mktime( $nexthour[0], 0, 0, $nexthour[1], $nexthour[2], $nexthour[3] );
143
+ return $newhour - $local_time;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Generates and retrieves the Access Code
149
+ */
150
+ public function token_request() {
151
+ $authUrl = $this->client->createAuthUrl();
152
+ ?>
153
+ <form name="input" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="post">
154
+ <table class="gadwp-settings-options">
155
+ <tr>
156
+ <td colspan="2" class="gadwp-settings-info">
157
+ <?php echo __( "Use this link to get your access code:", 'google-analytics-dashboard-for-wp' ) . ' <a href="' . $authUrl . '" id="gapi-access-code" target="_blank">' . __ ( "Get Access Code", 'google-analytics-dashboard-for-wp' ) . '</a>.'; ?>
158
+ </td>
159
+ </tr>
160
+ <tr>
161
+ <td class="gadwp-settings-title"><label for="ga_dash_code" title="<?php _e("Use the red link to get your access code!",'google-analytics-dashboard-for-wp')?>"><?php echo _e( "Access Code:", 'google-analytics-dashboard-for-wp' ); ?></label></td>
162
+ <td><input type="text" id="ga_dash_code" name="ga_dash_code" value="" size="61" required="required" title="<?php _e("Use the red link to get your access code!",'google-analytics-dashboard-for-wp')?>"></td>
163
+ </tr>
164
+ <tr>
165
+ <td colspan="2"><hr></td>
166
+ </tr>
167
+ <tr>
168
+ <td colspan="2"><input type="submit" class="button button-secondary" name="ga_dash_authorize" value="<?php _e( "Save Access Code", 'google-analytics-dashboard-for-wp' ); ?>" /></td>
169
+ </tr>
170
+ </table>
171
+ </form>
172
+ <?php
173
+ }
174
+
175
+ /**
176
+ * Retrieves all Google Analytics Views with details
177
+ *
178
+ * @return array
179
+ */
180
+ public function refresh_profiles() {
181
+ try {
182
+
183
+ $ga_dash_profile_list = array();
184
+ $startindex = 1;
185
+ $totalresults = 65535; // use something big
186
+
187
+ while ( $startindex < $totalresults ) {
188
+
189
+ $profiles = $this->service->management_profiles->listManagementProfiles( '~all', '~all', array( 'start-index' => $startindex ) );
190
+
191
+ $items = $profiles->getItems();
192
+
193
+ $totalresults = $profiles->getTotalResults();
194
+
195
+ if ( $totalresults > 0 ) {
196
+
197
+ foreach ( $items as $profile ) {
198
+ $timetz = new DateTimeZone( $profile->getTimezone() );
199
+ $localtime = new DateTime( 'now', $timetz );
200
+ $timeshift = strtotime( $localtime->format( 'Y-m-d H:i:s' ) ) - time();
201
+ $ga_dash_profile_list[] = array( $profile->getName(), $profile->getId(), $profile->getwebPropertyId(), $profile->getwebsiteUrl(), $timeshift, $profile->getTimezone(), $profile->getDefaultPage() );
202
+ $startindex++;
203
+ }
204
+ }
205
+ }
206
+
207
+ if ( empty( $ga_dash_profile_list ) ) {
208
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': No properties were found in this account!', $this->error_timeout );
209
+ } else {
210
+ GADWP_Tools::delete_cache( 'last_error' );
211
+ }
212
+ return $ga_dash_profile_list;
213
+ } catch ( Google_IO_Exception $e ) {
214
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
215
+ return $ga_dash_profile_list;
216
+ } catch ( Google_Service_Exception $e ) {
217
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $this->error_timeout );
218
+ GADWP_Tools::set_cache( 'gapi_errors', array( $e->getCode(), (array) $e->getErrors() ), $this->error_timeout );
219
+ } catch ( Exception $e ) {
220
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
221
+ return $ga_dash_profile_list;
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Handles the token reset process
227
+ *
228
+ * @param
229
+ * $all
230
+ */
231
+ public function reset_token( $all = true ) {
232
+ $this->gadwp->config->options['ga_dash_token'] = "";
233
+ if ( $all ) {
234
+ $this->gadwp->config->options['ga_dash_tableid_jail'] = "";
235
+ $this->gadwp->config->options['ga_dash_profile_list'] = array();
236
+ try {
237
+ $this->client->revokeToken();
238
+ } catch ( Exception $e ) {
239
+ if ( is_multisite() && $this->gadwp->config->options['ga_dash_network'] ) {
240
+ $this->gadwp->config->set_plugin_options( true );
241
+ } else {
242
+ $this->gadwp->config->set_plugin_options();
243
+ }
244
+ }
245
+ }
246
+ if ( is_multisite() && $this->gadwp->config->options['ga_dash_network'] ) {
247
+ $this->gadwp->config->set_plugin_options( true );
248
+ } else {
249
+ $this->gadwp->config->set_plugin_options();
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Get and cache Core Reports
255
+ *
256
+ * @param
257
+ * $projecId
258
+ * @param
259
+ * $from
260
+ * @param
261
+ * $to
262
+ * @param
263
+ * $metrics
264
+ * @param
265
+ * $options
266
+ * @param
267
+ * $serial
268
+ * @return int|Google_Service_Analytics_GaData
269
+ */
270
+ private function handle_corereports( $projectId, $from, $to, $metrics, $options, $serial ) {
271
+ try {
272
+ if ( $from == "today" ) {
273
+ $timeouts = 0;
274
+ } else {
275
+ $timeouts = 1;
276
+ }
277
+ $transient = GADWP_Tools::get_cache( $serial );
278
+ if ( $transient === false ) {
279
+ if ( $this->gapi_errors_handler() ) {
280
+ return - 23;
281
+ }
282
+ $data = $this->service->data_ga->get( 'ga:' . $projectId, $from, $to, $metrics, $options );
283
+ GADWP_Tools::set_cache( $serial, $data, $this->get_timeouts( $timeouts ) );
284
+ $this->gadwp->config->options['api_backoff'] = 0;
285
+ $this->gadwp->config->set_plugin_options();
286
+ } else {
287
+ $data = $transient;
288
+ }
289
+ } catch ( Google_Service_Exception $e ) {
290
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $this->error_timeout );
291
+ GADWP_Tools::set_cache( 'gapi_errors', array( $e->getCode(), (array) $e->getErrors() ), $this->error_timeout );
292
+ return $e->getCode();
293
+ } catch ( Exception $e ) {
294
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
295
+ return $e->getCode();
296
+ }
297
+ if ( $data->getRows() > 0 ) {
298
+ return $data;
299
+ } else {
300
+ return - 21;
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Generates serials for transients
306
+ *
307
+ * @param
308
+ * $serial
309
+ * @return string
310
+ */
311
+ public function get_serial( $serial ) {
312
+ return sprintf( "%u", crc32( $serial ) );
313
+ }
314
+
315
+ /**
316
+ * Analytics data for Area Charts (Admin Dashboard Widget report)
317
+ *
318
+ * @param
319
+ * $projectId
320
+ * @param
321
+ * $from
322
+ * @param
323
+ * $to
324
+ * @param
325
+ * $query
326
+ * @param
327
+ * $filter
328
+ * @return array|int
329
+ */
330
+ private function get_areachart_data( $projectId, $from, $to, $query, $filter = '' ) {
331
+ switch ( $query ) {
332
+ case 'users' :
333
+ $title = __( "Users", 'google-analytics-dashboard-for-wp' );
334
+ break;
335
+ case 'pageviews' :
336
+ $title = __( "Page Views", 'google-analytics-dashboard-for-wp' );
337
+ break;
338
+ case 'visitBounceRate' :
339
+ $title = __( "Bounce Rate", 'google-analytics-dashboard-for-wp' );
340
+ break;
341
+ case 'organicSearches' :
342
+ $title = __( "Organic Searches", 'google-analytics-dashboard-for-wp' );
343
+ break;
344
+ default :
345
+ $title = __( "Sessions", 'google-analytics-dashboard-for-wp' );
346
+ }
347
+ $metrics = 'ga:' . $query;
348
+ if ( $from == "today" || $from == "yesterday" ) {
349
+ $dimensions = 'ga:hour';
350
+ $dayorhour = __( "Hour", 'google-analytics-dashboard-for-wp' );
351
+ } else if ( $from == "365daysAgo" || $from == "1095daysAgo" ) {
352
+ $dimensions = 'ga:yearMonth, ga:month';
353
+ $dayorhour = __( "Date", 'google-analytics-dashboard-for-wp' );
354
+ } else {
355
+ $dimensions = 'ga:date,ga:dayOfWeekName';
356
+ $dayorhour = __( "Date", 'google-analytics-dashboard-for-wp' );
357
+ }
358
+ $options = array( 'dimensions' => $dimensions, 'quotaUser' => $this->managequota . 'p' . $projectId );
359
+ if ( $filter ) {
360
+ $options['filters'] = 'ga:pagePath==' . $filter;
361
+ }
362
+ $serial = 'qr2_' . $this->get_serial( $projectId . $from . $metrics . $filter );
363
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
364
+ if ( is_numeric( $data ) ) {
365
+ return $data;
366
+ }
367
+ $gadwp_data = array( array( $dayorhour, $title ) );
368
+ if ( $from == "today" || $from == "yesterday" ) {
369
+ foreach ( $data->getRows() as $row ) {
370
+ $gadwp_data[] = array( (int) $row[0] . ':00', round( $row[1], 2 ) );
371
+ }
372
+ } else if ( $from == "365daysAgo" || $from == "1095daysAgo" ) {
373
+ foreach ( $data->getRows() as $row ) {
374
+ /*
375
+ * translators:
376
+ * Example: 'F, Y' will become 'November, 2015'
377
+ * For details see: http://php.net/manual/en/function.date.php#refsect1-function.date-parameters
378
+ */
379
+ $gadwp_data[] = array( date_i18n( __( 'F, Y', 'google-analytics-dashboard-for-wp' ), strtotime( $row[0] . '01' ) ), round( $row[2], 2 ) );
380
+ }
381
+ } else {
382
+ foreach ( $data->getRows() as $row ) {
383
+ /*
384
+ * translators:
385
+ * Example: 'l, F j, Y' will become 'Thusday, November 17, 2015'
386
+ * For details see: http://php.net/manual/en/function.date.php#refsect1-function.date-parameters
387
+ */
388
+ $gadwp_data[] = array( date_i18n( __( 'l, F j, Y', 'google-analytics-dashboard-for-wp' ), strtotime( $row[0] ) ), round( $row[2], 2 ) );
389
+ }
390
+ }
391
+
392
+ return $gadwp_data;
393
+ }
394
+
395
+ /**
396
+ * Analytics data for Bottom Stats (bottom stats on main report)
397
+ *
398
+ * @param
399
+ * $projectId
400
+ * @param
401
+ * $from
402
+ * @param
403
+ * $to
404
+ * @param
405
+ * $filter
406
+ * @return array|int
407
+ */
408
+ private function get_bottomstats( $projectId, $from, $to, $filter = '' ) {
409
+ $options = array( 'dimensions' => null, 'quotaUser' => $this->managequota . 'p' . $projectId );
410
+ if ( $filter ) {
411
+ $options['filters'] = 'ga:pagePath==' . $filter;
412
+ $metrics = 'ga:sessions,ga:users,ga:pageviews,ga:BounceRate,ga:organicSearches,ga:pageviewsPerSession';
413
+ } else {
414
+ $metrics = 'ga:sessions,ga:users,ga:pageviews,ga:BounceRate,ga:organicSearches,ga:pageviewsPerSession';
415
+ }
416
+ $serial = 'qr3_' . $this->get_serial( $projectId . $from . $filter );
417
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
418
+ if ( is_numeric( $data ) ) {
419
+ if ( $data == - 21 ) {
420
+ return array_fill( 0, 6, 0 );
421
+ } else {
422
+ return $data;
423
+ }
424
+ }
425
+ $gadwp_data = array();
426
+ foreach ( $data->getRows() as $row ) {
427
+ $gadwp_data = array_map( 'floatval', $row );
428
+ }
429
+
430
+ // i18n support
431
+ $gadwp_data[0] = number_format_i18n( $gadwp_data[0] );
432
+ $gadwp_data[1] = number_format_i18n( $gadwp_data[1] );
433
+ $gadwp_data[2] = number_format_i18n( $gadwp_data[2] );
434
+ $gadwp_data[3] = number_format_i18n( $gadwp_data[3], 2 );
435
+ $gadwp_data[4] = number_format_i18n( $gadwp_data[4] );
436
+ $gadwp_data[5] = number_format_i18n( $gadwp_data[5], 2 );
437
+
438
+ return $gadwp_data;
439
+ }
440
+
441
+ /**
442
+ * Analytics data for Org Charts & Table Charts (content pages)
443
+ *
444
+ * @param
445
+ * $projectId
446
+ * @param
447
+ * $from
448
+ * @param
449
+ * $to
450
+ * @param
451
+ * $filter
452
+ * @return array|int
453
+ */
454
+ private function get_contentpages( $projectId, $from, $to, $filter = '' ) {
455
+ $metrics = 'ga:sessions';
456
+ $dimensions = 'ga:pageTitle';
457
+ $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
458
+ if ( $filter ) {
459
+ $options['filters'] = 'ga:pagePath==' . $filter;
460
+ }
461
+ $serial = 'qr4_' . $this->get_serial( $projectId . $from . $filter );
462
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
463
+ if ( is_numeric( $data ) ) {
464
+ return $data;
465
+ }
466
+ $gadwp_data = array( array( __( "Pages", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
467
+ foreach ( $data->getRows() as $row ) {
468
+ $gadwp_data[] = array( esc_html( $row[0] ), (int) $row[1] );
469
+ }
470
+ return $gadwp_data;
471
+ }
472
+
473
+ /**
474
+ * Analytics data for 404 Errors
475
+ *
476
+ * @param
477
+ * $projectId
478
+ * @param
479
+ * $from
480
+ * @param
481
+ * $to
482
+ * @return array|int
483
+ */
484
+ private function get_404errors( $projectId, $from, $to, $filter = "Page Not Found" ) {
485
+ $metrics = 'ga:sessions';
486
+ $dimensions = 'ga:pagePath,ga:fullReferrer';
487
+ $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
488
+ $options['filters'] = 'ga:pageTitle=@' . $filter;
489
+ $serial = 'qr4_' . $this->get_serial( $projectId . $from . $filter );
490
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
491
+ if ( is_numeric( $data ) ) {
492
+ return $data;
493
+ }
494
+ $gadwp_data = array( array( __( "404 Errors", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
495
+ foreach ( $data->getRows() as $row ) {
496
+ $path = esc_html( $row[0] );
497
+ $source = esc_html( $row[1] );
498
+ $gadwp_data[] = array( "<strong>" . __( "URI:", 'google-analytics-dashboard-for-wp' ) . "</strong> " . $path . "<br><strong>" . __( "Source:", 'google-analytics-dashboard-for-wp' ) . "</strong> " . $source, (int) $row[2] );
499
+ }
500
+ return $gadwp_data;
501
+ }
502
+
503
+ /**
504
+ * Analytics data for Org Charts & Table Charts (referrers)
505
+ *
506
+ * @param
507
+ * $projectId
508
+ * @param
509
+ * $from
510
+ * @param
511
+ * $to
512
+ * @param
513
+ * $filter
514
+ * @return array|int
515
+ */
516
+ private function get_referrers( $projectId, $from, $to, $filter = '' ) {
517
+ $metrics = 'ga:sessions';
518
+ $dimensions = 'ga:source';
519
+ $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
520
+ if ( $filter ) {
521
+ $options['filters'] = 'ga:medium==referral;ga:pagePath==' . $filter;
522
+ } else {
523
+ $options['filters'] = 'ga:medium==referral';
524
+ }
525
+ $serial = 'qr5_' . $this->get_serial( $projectId . $from . $filter );
526
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
527
+ if ( is_numeric( $data ) ) {
528
+ return $data;
529
+ }
530
+ $gadwp_data = array( array( __( "Referrers", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
531
+ foreach ( $data->getRows() as $row ) {
532
+ $gadwp_data[] = array( esc_html( $row[0] ), (int) $row[1] );
533
+ }
534
+ return $gadwp_data;
535
+ }
536
+
537
+ /**
538
+ * Analytics data for Org Charts & Table Charts (searches)
539
+ *
540
+ * @param
541
+ * $projectId
542
+ * @param
543
+ * $from
544
+ * @param
545
+ * $to
546
+ * @param
547
+ * $filter
548
+ * @return array|int
549
+ */
550
+ private function get_searches( $projectId, $from, $to, $filter = '' ) {
551
+ $metrics = 'ga:sessions';
552
+ $dimensions = 'ga:keyword';
553
+ $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
554
+ if ( $filter ) {
555
+ $options['filters'] = 'ga:keyword!=(not set);ga:pagePath==' . $filter;
556
+ } else {
557
+ $options['filters'] = 'ga:keyword!=(not set)';
558
+ }
559
+ $serial = 'qr6_' . $this->get_serial( $projectId . $from . $filter );
560
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
561
+ if ( is_numeric( $data ) ) {
562
+ return $data;
563
+ }
564
+
565
+ $gadwp_data = array( array( __( "Searches", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
566
+ foreach ( $data->getRows() as $row ) {
567
+ $gadwp_data[] = array( esc_html( $row[0] ), (int) $row[1] );
568
+ }
569
+ return $gadwp_data;
570
+ }
571
+
572
+ /**
573
+ * Analytics data for Org Charts & Table Charts (location reports)
574
+ *
575
+ * @param
576
+ * $projectId
577
+ * @param
578
+ * $from
579
+ * @param
580
+ * $to
581
+ * @param
582
+ * $filter
583
+ * @return array|int
584
+ */
585
+ private function get_locations( $projectId, $from, $to, $filter = '' ) {
586
+ $metrics = 'ga:sessions';
587
+ $options = "";
588
+ $title = __( "Countries", 'google-analytics-dashboard-for-wp' );
589
+ $serial = 'qr7_' . $this->get_serial( $projectId . $from . $filter );
590
+ $dimensions = 'ga:country';
591
+ $local_filter = '';
592
+ if ( $this->gadwp->config->options['ga_target_geomap'] ) {
593
+ $dimensions = 'ga:city, ga:region';
594
+
595
+ $country_codes = GADWP_Tools::get_countrycodes();
596
+ if ( isset( $country_codes[$this->gadwp->config->options['ga_target_geomap']] ) ) {
597
+ $local_filter = 'ga:country==' . ( $country_codes[$this->gadwp->config->options['ga_target_geomap']] );
598
+ $title = __( "Cities from", 'google-analytics-dashboard-for-wp' ) . ' ' . __( $country_codes[$this->gadwp->config->options['ga_target_geomap']] );
599
+ $serial = 'qr7_' . $this->get_serial( $projectId . $from . $this->gadwp->config->options['ga_target_geomap'] . $filter );
600
+ }
601
+ }
602
+ $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
603
+ if ( $filter ) {
604
+ $options['filters'] = 'ga:pagePath==' . $filter;
605
+ if ( $local_filter ) {
606
+ $options['filters'] .= ';' . $local_filter;
607
+ }
608
+ } else {
609
+ if ( $local_filter ) {
610
+ $options['filters'] = $local_filter;
611
+ }
612
+ }
613
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
614
+ if ( is_numeric( $data ) ) {
615
+ return $data;
616
+ }
617
+ $gadwp_data = array( array( $title, __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
618
+ foreach ( $data->getRows() as $row ) {
619
+ if ( isset( $row[2] ) ) {
620
+ $gadwp_data[] = array( esc_html( $row[0] ) . ', ' . esc_html( $row[1] ), (int) $row[2] );
621
+ } else {
622
+ $gadwp_data[] = array( esc_html( $row[0] ), (int) $row[1] );
623
+ }
624
+ }
625
+ return $gadwp_data;
626
+ }
627
+
628
+ /**
629
+ * Analytics data for Org Charts (traffic channels, device categories)
630
+ *
631
+ * @param
632
+ * $projectId
633
+ * @param
634
+ * $from
635
+ * @param
636
+ * $to
637
+ * @param
638
+ * $query
639
+ * @param
640
+ * $filter
641
+ * @return array|int
642
+ */
643
+ private function get_orgchart_data( $projectId, $from, $to, $query, $filter = '' ) {
644
+ $metrics = 'ga:sessions';
645
+ $dimensions = 'ga:' . $query;
646
+ $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
647
+ if ( $filter ) {
648
+ $options['filters'] = 'ga:pagePath==' . $filter;
649
+ }
650
+ $serial = 'qr8_' . $this->get_serial( $projectId . $from . $query . $filter );
651
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
652
+ if ( is_numeric( $data ) ) {
653
+ return $data;
654
+ }
655
+ $block = ( $query == 'channelGrouping' ) ? __( "Channels", 'google-analytics-dashboard-for-wp' ) : __( "Devices", 'google-analytics-dashboard-for-wp' );
656
+ $gadwp_data = array( array( '<div style="color:black; font-size:1.1em">' . $block . '</div><div style="color:darkblue; font-size:1.2em">' . (int) $data['totalsForAllResults']["ga:sessions"] . '</div>', "" ) );
657
+ foreach ( $data->getRows() as $row ) {
658
+ $shrink = explode( " ", $row[0] );
659
+ $gadwp_data[] = array( '<div style="color:black; font-size:1.1em">' . esc_html( $shrink[0] ) . '</div><div style="color:darkblue; font-size:1.2em">' . (int) $row[1] . '</div>', '<div style="color:black; font-size:1.1em">' . $block . '</div><div style="color:darkblue; font-size:1.2em">' . (int) $data['totalsForAllResults']["ga:sessions"] . '</div>' );
660
+ }
661
+ return $gadwp_data;
662
+ }
663
+
664
+ /**
665
+ * Analytics data for Pie Charts (traffic mediums, serach engines, social networks, browsers, screen rsolutions, etc.)
666
+ *
667
+ * @param
668
+ * $projectId
669
+ * @param
670
+ * $from
671
+ * @param
672
+ * $to
673
+ * @param
674
+ * $query
675
+ * @param
676
+ * $filter
677
+ * @return array|int
678
+ */
679
+ private function get_piechart_data( $projectId, $from, $to, $query, $filter = '' ) {
680
+ $metrics = 'ga:sessions';
681
+ $dimensions = 'ga:' . $query;
682
+
683
+ if ( $query == 'source' ) {
684
+ $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
685
+ if ( $filter ) {
686
+ $options['filters'] = 'ga:medium==organic;ga:keyword!=(not set);ga:pagePath==' . $filter;
687
+ } else {
688
+ $options['filters'] = 'ga:medium==organic;ga:keyword!=(not set)';
689
+ }
690
+ } else {
691
+ $options = array( 'dimensions' => $dimensions, 'sort' => '-ga:sessions', 'quotaUser' => $this->managequota . 'p' . $projectId );
692
+ if ( $filter ) {
693
+ $options['filters'] = 'ga:' . $query . '!=(not set);ga:pagePath==' . $filter;
694
+ } else {
695
+ $options['filters'] = 'ga:' . $query . '!=(not set)';
696
+ }
697
+ }
698
+ $serial = 'qr10_' . $this->get_serial( $projectId . $from . $query . $filter );
699
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
700
+ if ( is_numeric( $data ) ) {
701
+ return $data;
702
+ }
703
+ $gadwp_data = array( array( __( "Type", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
704
+ $i = 0;
705
+ $included = 0;
706
+ foreach ( $data->getRows() as $row ) {
707
+ if ( $i < 20 ) {
708
+ $gadwp_data[] = array( str_replace( "(none)", "direct", esc_html( $row[0] ) ), (int) $row[1] );
709
+ $included += $row[1];
710
+ $i++;
711
+ } else {
712
+ break;
713
+ }
714
+ }
715
+ $totals = $data->getTotalsForAllResults();
716
+ $others = $totals['ga:sessions'] - $included;
717
+ if ( $others > 0 ) {
718
+ $gadwp_data[] = array( __( 'Other', 'google-analytics-dashboard-for-wp' ), $others );
719
+ }
720
+
721
+ return $gadwp_data;
722
+ }
723
+
724
+ /**
725
+ * Analytics data for Frontend Widget (chart data and totals)
726
+ *
727
+ * @param
728
+ * $projectId
729
+ * @param
730
+ * $period
731
+ * @param
732
+ * $anonim
733
+ * @return array|int
734
+ */
735
+ public function frontend_widget_stats( $projectId, $from, $anonim ) {
736
+ $content = '';
737
+ $to = 'yesterday';
738
+ $metrics = 'ga:sessions';
739
+ $dimensions = 'ga:date,ga:dayOfWeekName';
740
+ $options = array( 'dimensions' => $dimensions, 'quotaUser' => $this->managequota . 'p' . $projectId );
741
+ $serial = 'qr2_' . $this->get_serial( $projectId . $from . $metrics );
742
+ $data = $this->handle_corereports( $projectId, $from, $to, $metrics, $options, $serial );
743
+ if ( is_numeric( $data ) ) {
744
+ return $data;
745
+ }
746
+ $gadwp_data = array( array( __( "Date", 'google-analytics-dashboard-for-wp' ), __( "Sessions", 'google-analytics-dashboard-for-wp' ) ) );
747
+ if ( $anonim ) {
748
+ $max_array = array();
749
+ foreach ( $data->getRows() as $item ) {
750
+ $max_array[] = $item[2];
751
+ }
752
+ $max = max( $max_array ) ? max( $max_array ) : 1;
753
+ }
754
+ foreach ( $data->getRows() as $row ) {
755
+ $gadwp_data[] = array( date_i18n( __( 'l, F j, Y', 'google-analytics-dashboard-for-wp' ), strtotime( $row[0] ) ), ( $anonim ? round( $row[2] * 100 / $max, 2 ) : (int) $row[2] ) );
756
+ }
757
+ $totals = $data->getTotalsForAllResults();
758
+ return array( $gadwp_data, $anonim ? 0 : number_format_i18n( $totals['ga:sessions'] ) );
759
+ }
760
+
761
+ /**
762
+ * Analytics data for Realtime component (the real-time report)
763
+ *
764
+ * @param
765
+ * $projectId
766
+ * @return array|int
767
+ */
768
+ private function get_realtime( $projectId ) {
769
+ $metrics = 'rt:activeUsers';
770
+ $dimensions = 'rt:pagePath,rt:source,rt:keyword,rt:trafficType,rt:visitorType,rt:pageTitle';
771
+ try {
772
+ $serial = 'qr_realtimecache_' . $this->get_serial( $projectId );
773
+ $transient = GADWP_Tools::get_cache( $serial );
774
+ if ( $transient === false ) {
775
+ if ( $this->gapi_errors_handler() ) {
776
+ return - 23;
777
+ }
778
+ $data = $this->service->data_realtime->get( 'ga:' . $projectId, $metrics, array( 'dimensions' => $dimensions, 'quotaUser' => $this->managequota . 'p' . $projectId ) );
779
+ GADWP_Tools::set_cache( $serial, $data, 55 );
780
+ $this->gadwp->config->options['api_backoff'] = 0;
781
+ $this->gadwp->config->set_plugin_options();
782
+ } else {
783
+ $data = $transient;
784
+ }
785
+ } catch ( Google_Service_Exception $e ) {
786
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( "(" . $e->getCode() . ") " . $e->getMessage() ), $this->error_timeout );
787
+ GADWP_Tools::set_cache( 'gapi_errors', array( $e->getCode(), (array) $e->getErrors() ), $this->error_timeout );
788
+ return $e->getCode();
789
+ } catch ( Exception $e ) {
790
+ GADWP_Tools::set_cache( 'last_error', date( 'Y-m-d H:i:s' ) . ': ' . esc_html( $e ), $this->error_timeout );
791
+ return $e->getCode();
792
+ }
793
+ if ( $data->getRows() < 1 ) {
794
+ return - 21;
795
+ }
796
+ $i = 0;
797
+ $gadwp_data = $data;
798
+ foreach ( $data->getRows() as $row ) {
799
+ $gadwp_data->rows[$i] = array_map( 'esc_html', $row );
800
+ $i++;
801
+ }
802
+ return array( $gadwp_data );
803
+ }
804
+
805
+ private function map( $map ) {
806
+ $map = explode( '.', $map );
807
+ if ( isset( $map[1] ) ) {
808
+ $map[0] += ord( 'map' );
809
+ return implode( '.', $map );
810
+ } else {
811
+ return str_ireplace( 'map', chr( 112 ), $map[0] );
812
+ }
813
+ }
814
+
815
+ /**
816
+ * Handles ajax requests and calls the needed methods
817
+ * @param
818
+ * $projectId
819
+ * @param
820
+ * $query
821
+ * @param
822
+ * $from
823
+ * @param
824
+ * $to
825
+ * @param
826
+ * $filter
827
+ * @return number|Google_Service_Analytics_GaData
828
+ */
829
+ public function get( $projectId, $query, $from = false, $to = false, $filter = '' ) {
830
+ if ( empty( $projectId ) || ! is_numeric( $projectId ) ) {
831
+ wp_die( - 26 );
832
+ }
833
+ if ( in_array( $query, array( 'sessions', 'users', 'organicSearches', 'visitBounceRate', 'pageviews') ) ) {
834
+ return $this->get_areachart_data( $projectId, $from, $to, $query, $filter );
835
+ }
836
+ if ( $query == 'bottomstats' ) {
837
+ return $this->get_bottomstats( $projectId, $from, $to, $filter );
838
+ }
839
+ if ( $query == 'locations' ) {
840
+ return $this->get_locations( $projectId, $from, $to, $filter );
841
+ }
842
+ if ( $query == 'referrers' ) {
843
+ return $this->get_referrers( $projectId, $from, $to, $filter );
844
+ }
845
+ if ( $query == 'contentpages' ) {
846
+ return $this->get_contentpages( $projectId, $from, $to, $filter );
847
+ }
848
+ if ( $query == '404errors' ) {
849
+ $filter = $this->gadwp->config->options['pagetitle_404'];
850
+ return $this->get_404errors( $projectId, $from, $to, $filter );
851
+ }
852
+ if ( $query == 'searches' ) {
853
+ return $this->get_searches( $projectId, $from, $to, $filter );
854
+ }
855
+ if ( $query == 'realtime' ) {
856
+ return $this->get_realtime( $projectId );
857
+ }
858
+ if ( $query == 'channelGrouping' || $query == 'deviceCategory' ) {
859
+ return $this->get_orgchart_data( $projectId, $from, $to, $query, $filter );
860
+ }
861
+ if ( in_array( $query, array( 'medium', 'visitorType', 'socialNetwork', 'source', 'browser', 'operatingSystem', 'screenResolution', 'mobileDeviceBranding' ) ) ) {
862
+ return $this->get_piechart_data( $projectId, $from, $to, $query, $filter );
863
+ }
864
+ wp_die( - 27 );
865
+ }
866
+ }
867
+ }
tools/iso3166.php CHANGED
@@ -1,255 +1,255 @@
1
- <?php
2
- /**
3
- * Author: Alin Marcu
4
- * Author URI: https://deconf.com
5
- * Copyright 2013 Alin Marcu
6
- * License: GPLv2 or later
7
- * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
- */
9
-
10
- // Exit if accessed directly
11
- if ( ! defined( 'ABSPATH' ) )
12
- exit();
13
-
14
- /* @formatter:off */
15
- $country_codes = array(
16
- 'AD' => 'Andorra',
17
- 'AE' => 'United Arab Emirates',
18
- 'AF' => 'Afghanistan',
19
- 'AG' => 'Antigua and Barbuda',
20
- 'AI' => 'Anguilla',
21
- 'AL' => 'Albania',
22
- 'AM' => 'Armenia',
23
- 'AN' => 'Netherlands Antilles',
24
- 'AO' => 'Angola',
25
- 'AQ' => 'Antarctica',
26
- 'AR' => 'Argentina',
27
- 'AS' => 'American Samoa',
28
- 'AT' => 'Austria',
29
- 'AU' => 'Australia',
30
- 'AW' => 'Aruba',
31
- 'AZ' => 'Azerbaijan',
32
- 'BA' => 'Bosnia and Herzegovina',
33
- 'BB' => 'Barbados',
34
- 'BD' => 'Bangladesh',
35
- 'BE' => 'Belgium',
36
- 'BF' => 'Burkina Faso',
37
- 'BG' => 'Bulgaria',
38
- 'BH' => 'Bahrain',
39
- 'BI' => 'Burundi',
40
- 'BJ' => 'Benin',
41
- 'BM' => 'Bermuda',
42
- 'BN' => 'Brunei',
43
- 'BO' => 'Bolivia',
44
- 'BR' => 'Brazil',
45
- 'BS' => 'Bahamas',
46
- 'BT' => 'Bhutan',
47
- 'BV' => 'Bouvet Island',
48
- 'BW' => 'Botswana',
49
- 'BY' => 'Belarus',
50
- 'BZ' => 'Belize',
51
- 'CA' => 'Canada',
52
- 'CC' => 'Cocos (Keeling) Islands',
53
- 'CD' => 'Congo, The Democratic Republic of the',
54
- 'CF' => 'Central African Republic',
55
- 'CG' => 'Congo',
56
- 'CH' => 'Switzerland',
57
- 'CI' => 'C�te d?Ivoire',
58
- 'CK' => 'Cook Islands',
59
- 'CL' => 'Chile',
60
- 'CM' => 'Cameroon',
61
- 'CN' => 'China',
62
- 'CO' => 'Colombia',
63
- 'CR' => 'Costa Rica',
64
- 'CU' => 'Cuba',
65
- 'CV' => 'Cape Verde',
66
- 'CX' => 'Christmas Island',
67
- 'CY' => 'Cyprus',
68
- 'CZ' => 'Czech Republic',
69
- 'DE' => 'Germany',
70
- 'DJ' => 'Djibouti',
71
- 'DK' => 'Denmark',
72
- 'DM' => 'Dominica',
73
- 'DO' => 'Dominican Republic',
74
- 'DZ' => 'Algeria',
75
- 'EC' => 'Ecuador',
76
- 'EE' => 'Estonia',
77
- 'EG' => 'Egypt',
78
- 'EH' => 'Western Sahara',
79
- 'ER' => 'Eritrea',
80
- 'ES' => 'Spain',
81
- 'ET' => 'Ethiopia',
82
- 'FI' => 'Finland',
83
- 'FJ' => 'Fiji Islands',
84
- 'FK' => 'Falkland Islands',
85
- 'FM' => 'Micronesia, Federated States of',
86
- 'FO' => 'Faroe Islands',
87
- 'FR' => 'France',
88
- 'GA' => 'Gabon',
89
- 'GB' => 'United Kingdom',
90
- 'GD' => 'Grenada',
91
- 'GE' => 'Georgia',
92
- 'GF' => 'French Guiana',
93
- 'GH' => 'Ghana',
94
- 'GI' => 'Gibraltar',
95
- 'GL' => 'Greenland',
96
- 'GM' => 'Gambia',
97
- 'GN' => 'Guinea',
98
- 'GP' => 'Guadeloupe',
99
- 'GQ' => 'Equatorial Guinea',
100
- 'GR' => 'Greece',
101
- 'GS' => 'South Georgia and the South Sandwich Islands',
102
- 'GT' => 'Guatemala',
103
- 'GU' => 'Guam',
104
- 'GW' => 'Guinea-Bissau',
105
- 'GY' => 'Guyana',
106
- 'HK' => 'Hong Kong',
107
- 'HM' => 'Heard Island and McDonald Islands',
108
- 'HN' => 'Honduras',
109
- 'HR' => 'Croatia',
110
- 'HT' => 'Haiti',
111
- 'HU' => 'Hungary',
112
- 'ID' => 'Indonesia',
113
- 'IE' => 'Ireland',
114
- 'IL' => 'Israel',
115
- 'IN' => 'India',
116
- 'IO' => 'British Indian Ocean Territory',
117
- 'IQ' => 'Iraq',
118
- 'IR' => 'Iran',
119
- 'IS' => 'Iceland',
120
- 'IT' => 'Italy',
121
- 'JM' => 'Jamaica',
122
- 'JO' => 'Jordan',
123
- 'JP' => 'Japan',
124
- 'KE' => 'Kenya',
125
- 'KG' => 'Kyrgyzstan',
126
- 'KH' => 'Cambodia',
127
- 'KI' => 'Kiribati',
128
- 'KM' => 'Comoros',
129
- 'KN' => 'Saint Kitts and Nevis',
130
- 'KP' => 'North Korea',
131
- 'KR' => 'South Korea',
132
- 'KW' => 'Kuwait',
133
- 'KY' => 'Cayman Islands',
134
- 'KZ' => 'Kazakstan',
135
- 'LA' => 'Laos',
136
- 'LB' => 'Lebanon',
137
- 'LC' => 'Saint Lucia',
138
- 'LI' => 'Liechtenstein',
139
- 'LK' => 'Sri Lanka',
140
- 'LR' => 'Liberia',
141
- 'LS' => 'Lesotho',
142
- 'LT' => 'Lithuania',
143
- 'LU' => 'Luxembourg',
144
- 'LV' => 'Latvia',
145
- 'LY' => 'Libyan Arab Jamahiriya',
146
- 'MA' => 'Morocco',
147
- 'MC' => 'Monaco',
148
- 'MD' => 'Moldova',
149
- 'MG' => 'Madagascar',
150
- 'MH' => 'Marshall Islands',
151
- 'MK' => 'Macedonia',
152
- 'ML' => 'Mali',
153
- 'MM' => 'Myanmar',
154
- 'MN' => 'Mongolia',
155
- 'MO' => 'Macao',
156
- 'MP' => 'Northern Mariana Islands',
157
- 'MQ' => 'Martinique',
158
- 'MR' => 'Mauritania',
159
- 'MS' => 'Montserrat',
160
- 'MT' => 'Malta',
161
- 'MU' => 'Mauritius',
162
- 'MV' => 'Maldives',
163
- 'MW' => 'Malawi',
164
- 'MX' => 'Mexico',
165
- 'MY' => 'Malaysia',
166
- 'MZ' => 'Mozambique',
167
- 'NA' => 'Namibia',
168
- 'NC' => 'New Caledonia',
169
- 'NE' => 'Niger',
170
- 'NF' => 'Norfolk Island',
171
- 'NG' => 'Nigeria',
172
- 'NI' => 'Nicaragua',
173
- 'NL' => 'Netherlands',
174
- 'NO' => 'Norway',
175
- 'NP' => 'Nepal',
176
- 'NR' => 'Nauru',
177
- 'NU' => 'Niue',
178
- 'NZ' => 'New Zealand',
179
- 'OM' => 'Oman',
180
- 'PA' => 'Panama',
181
- 'PE' => 'Peru',
182
- 'PF' => 'French Polynesia',
183
- 'PG' => 'Papua New Guinea',
184
- 'PH' => 'Philippines',
185
- 'PK' => 'Pakistan',
186
- 'PL' => 'Poland',
187
- 'PM' => 'Saint Pierre and Miquelon',
188
- 'PN' => 'Pitcairn',
189
- 'PR' => 'Puerto Rico',
190
- 'PS' => 'Palestine',
191
- 'PT' => 'Portugal',
192
- 'PW' => 'Palau',
193
- 'PY' => 'Paraguay',
194
- 'QA' => 'Qatar',
195
- 'RE' => 'Reunion',
196
- 'RO' => 'Romania',
197
- 'RU' => 'Russia',
198
- 'RW' => 'Rwanda',
199
- 'SA' => 'Saudi Arabia',
200
- 'SB' => 'Solomon Islands',
201
- 'SC' => 'Seychelles',
202
- 'SD' => 'Sudan',
203
- 'SE' => 'Sweden',
204
- 'SG' => 'Singapore',
205
- 'SH' => 'Saint Helena',
206
- 'SI' => 'Slovenia',
207
- 'SJ' => 'Svalbard and Jan Mayen',
208
- 'SK' => 'Slovakia',
209
- 'SL' => 'Sierra Leone',
210
- 'SM' => 'San Marino',
211
- 'SN' => 'Senegal',
212
- 'SO' => 'Somalia',
213
- 'SR' => 'Suriname',
214
- 'ST' => 'Sao Tome and Principe',
215
- 'SV' => 'El Salvador',
216
- 'SY' => 'Syria',
217
- 'SZ' => 'Swaziland',
218
- 'TC' => 'Turks and Caicos Islands',
219
- 'TD' => 'Chad',
220
- 'TF' => 'French Southern territories',
221
- 'TG' => 'Togo',
222
- 'TH' => 'Thailand',
223
- 'TJ' => 'Tajikistan',
224
- 'TK' => 'Tokelau',
225
- 'TM' => 'Turkmenistan',
226
- 'TN' => 'Tunisia',
227
- 'TO' => 'Tonga',
228
- 'TP' => 'East Timor',
229
- 'TR' => 'Turkey',
230
- 'TT' => 'Trinidad and Tobago',
231
- 'TV' => 'Tuvalu',
232
- 'TW' => 'Taiwan',
233
- 'TZ' => 'Tanzania',
234
- 'UA' => 'Ukraine',
235
- 'UG' => 'Uganda',
236
- 'UM' => 'United States Minor Outlying Islands',
237
- 'US' => 'United States',
238
- 'UY' => 'Uruguay',
239
- 'UZ' => 'Uzbekistan',
240
- 'VA' => 'Holy See (Vatican City State)',
241
- 'VC' => 'Saint Vincent and the Grenadines',
242
- 'VE' => 'Venezuela',
243
- 'VG' => 'Virgin Islands, British',
244
- 'VI' => 'Virgin Islands, U.S.',
245
- 'VN' => 'Vietnam',
246
- 'VU' => 'Vanuatu',
247
- 'WF' => 'Wallis and Futuna',
248
- 'WS' => 'Samoa',
249
- 'YE' => 'Yemen',
250
- 'YT' => 'Mayotte',
251
- 'YU' => 'Yugoslavia',
252
- 'ZA' => 'South Africa',
253
- 'ZM' => 'Zambia',
254
- 'ZW' => 'Zimbabwe' );
255
  /* @formatter:on */
1
+ <?php
2
+ /**
3
+ * Author: Alin Marcu
4
+ * Author URI: https://deconf.com
5
+ * Copyright 2013 Alin Marcu
6
+ * License: GPLv2 or later
7
+ * License URI: http://www.gnu.org/licenses/gpl-2.0.html
8
+ */
9
+
10
+ // Exit if accessed directly
11
+ if ( ! defined( 'ABSPATH' ) )
12
+ exit();
13
+
14
+ /* @formatter:off */
15
+ $country_codes = array(
16
+ 'AD' => 'Andorra',
17
+ 'AE' => 'United Arab Emirates',
18
+ 'AF' => 'Afghanistan',
19
+ 'AG' => 'Antigua and Barbuda',
20
+ 'AI' => 'Anguilla',
21
+ 'AL' => 'Albania',
22
+ 'AM' => 'Armenia',
23
+ 'AN' => 'Netherlands Antilles',
24
+ 'AO' => 'Angola',
25
+ 'AQ' => 'Antarctica',
26
+ 'AR' => 'Argentina',
27
+ 'AS' => 'American Samoa',
28
+ 'AT' => 'Austria',
29
+ 'AU' => 'Australia',
30
+ 'AW' => 'Aruba',
31
+ 'AZ' => 'Azerbaijan',
32
+ 'BA' => 'Bosnia and Herzegovina',
33
+ 'BB' => 'Barbados',
34
+ 'BD' => 'Bangladesh',
35
+ 'BE' => 'Belgium',
36
+ 'BF' => 'Burkina Faso',
37
+ 'BG' => 'Bulgaria',
38
+ 'BH' => 'Bahrain',
39
+ 'BI' => 'Burundi',
40
+ 'BJ' => 'Benin',
41
+ 'BM' => 'Bermuda',
42
+ 'BN' => 'Brunei',
43
+ 'BO' => 'Bolivia',
44
+ 'BR' => 'Brazil',
45
+ 'BS' => 'Bahamas',
46
+ 'BT' => 'Bhutan',
47
+ 'BV' => 'Bouvet Island',
48
+ 'BW' => 'Botswana',
49
+ 'BY' => 'Belarus',
50
+ 'BZ' => 'Belize',
51
+ 'CA' => 'Canada',
52
+ 'CC' => 'Cocos (Keeling) Islands',
53
+ 'CD' => 'Congo, The Democratic Republic of the',
54
+ 'CF' => 'Central African Republic',
55
+ 'CG' => 'Congo',
56
+ 'CH' => 'Switzerland',
57
+ 'CI' => 'C�te d?Ivoire',
58
+ 'CK' => 'Cook Islands',
59
+ 'CL' => 'Chile',
60
+ 'CM' => 'Cameroon',
61
+ 'CN' => 'China',
62
+ 'CO' => 'Colombia',
63
+ 'CR' => 'Costa Rica',
64
+ 'CU' => 'Cuba',
65
+ 'CV' => 'Cape Verde',
66
+ 'CX' => 'Christmas Island',
67
+ 'CY' => 'Cyprus',
68
+ 'CZ' => 'Czech Republic',
69
+ 'DE' => 'Germany',
70
+ 'DJ' => 'Djibouti',
71
+ 'DK' => 'Denmark',
72
+ 'DM' => 'Dominica',
73
+ 'DO' => 'Dominican Republic',
74
+ 'DZ' => 'Algeria',
75
+ 'EC' => 'Ecuador',
76
+ 'EE' => 'Estonia',
77
+ 'EG' => 'Egypt',
78
+ 'EH' => 'Western Sahara',
79
+ 'ER' => 'Eritrea',
80
+ 'ES' => 'Spain',
81
+ 'ET' => 'Ethiopia',
82
+ 'FI' => 'Finland',
83
+ 'FJ' => 'Fiji Islands',
84
+ 'FK' => 'Falkland Islands',
85
+ 'FM' => 'Micronesia, Federated States of',
86
+ 'FO' => 'Faroe Islands',
87
+ 'FR' => 'France',
88
+ 'GA' => 'Gabon',
89
+ 'GB' => 'United Kingdom',
90
+ 'GD' => 'Grenada',
91
+ 'GE' => 'Georgia',
92
+ 'GF' => 'French Guiana',
93
+ 'GH' => 'Ghana',
94
+ 'GI' => 'Gibraltar',
95
+ 'GL' => 'Greenland',
96
+ 'GM' => 'Gambia',
97
+ 'GN' => 'Guinea',
98
+ 'GP' => 'Guadeloupe',
99
+ 'GQ' => 'Equatorial Guinea',
100
+ 'GR' => 'Greece',
101
+ 'GS' => 'South Georgia and the South Sandwich Islands',
102
+ 'GT' => 'Guatemala',
103
+ 'GU' => 'Guam',
104
+ 'GW' => 'Guinea-Bissau',
105
+ 'GY' => 'Guyana',
106
+ 'HK' => 'Hong Kong',
107
+ 'HM' => 'Heard Island and McDonald Islands',
108
+ 'HN' => 'Honduras',
109
+ 'HR' => 'Croatia',
110
+ 'HT' => 'Haiti',
111
+ 'HU' => 'Hungary',
112
+ 'ID' => 'Indonesia',
113
+ 'IE' => 'Ireland',
114
+ 'IL' => 'Israel',
115
+ 'IN' => 'India',
116
+ 'IO' => 'British Indian Ocean Territory',
117
+ 'IQ' => 'Iraq',
118
+ 'IR' => 'Iran',
119
+ 'IS' => 'Iceland',
120
+ 'IT' => 'Italy',
121
+ 'JM' => 'Jamaica',
122
+ 'JO' => 'Jordan',
123
+ 'JP' => 'Japan',
124
+ 'KE' => 'Kenya',
125
+ 'KG' => 'Kyrgyzstan',
126
+ 'KH' => 'Cambodia',
127
+ 'KI' => 'Kiribati',
128
+ 'KM' => 'Comoros',
129
+ 'KN' => 'Saint Kitts and Nevis',
130
+ 'KP' => 'North Korea',
131
+ 'KR' => 'South Korea',
132
+ 'KW' => 'Kuwait',
133
+ 'KY' => 'Cayman Islands',
134
+ 'KZ' => 'Kazakstan',
135
+ 'LA' => 'Laos',
136
+ 'LB' => 'Lebanon',
137
+ 'LC' => 'Saint Lucia',
138
+ 'LI' => 'Liechtenstein',
139
+ 'LK' => 'Sri Lanka',
140
+ 'LR' => 'Liberia',
141
+ 'LS' => 'Lesotho',
142
+ 'LT' => 'Lithuania',
143
+ 'LU' => 'Luxembourg',
144
+ 'LV' => 'Latvia',
145
+ 'LY' => 'Libyan Arab Jamahiriya',
146
+ 'MA' => 'Morocco',
147
+ 'MC' => 'Monaco',
148
+ 'MD' => 'Moldova',
149
+ 'MG' => 'Madagascar',
150
+ 'MH' => 'Marshall Islands',
151
+ 'MK' => 'Macedonia',
152
+ 'ML' => 'Mali',
153
+ 'MM' => 'Myanmar',
154
+ 'MN' => 'Mongolia',
155
+ 'MO' => 'Macao',
156
+ 'MP' => 'Northern Mariana Islands',
157
+ 'MQ' => 'Martinique',
158
+ 'MR' => 'Mauritania',
159
+ 'MS' => 'Montserrat',
160
+ 'MT' => 'Malta',
161
+ 'MU' => 'Mauritius',
162
+ 'MV' => 'Maldives',
163
+ 'MW' => 'Malawi',
164
+ 'MX' => 'Mexico',
165
+ 'MY' => 'Malaysia',
166
+ 'MZ' => 'Mozambique',
167
+ 'NA' => 'Namibia',
168
+ 'NC' => 'New Caledonia',
169
+ 'NE' => 'Niger',
170
+ 'NF' => 'Norfolk Island',
171
+ 'NG' => 'Nigeria',
172
+ 'NI' => 'Nicaragua',
173
+ 'NL' => 'Netherlands',
174
+ 'NO' => 'Norway',
175
+ 'NP' => 'Nepal',
176
+ 'NR' => 'Nauru',
177
+ 'NU' => 'Niue',
178
+ 'NZ' => 'New Zealand',
179
+ 'OM' => 'Oman',
180
+ 'PA' => 'Panama',
181
+ 'PE' => 'Peru',
182
+ 'PF' => 'French Polynesia',
183
+ 'PG' => 'Papua New Guinea',
184
+ 'PH' => 'Philippines',
185
+ 'PK' => 'Pakistan',
186
+ 'PL' => 'Poland',
187
+ 'PM' => 'Saint Pierre and Miquelon',
188
+ 'PN' => 'Pitcairn',
189
+ 'PR' => 'Puerto Rico',
190
+ 'PS' => 'Palestine',
191
+ 'PT' => 'Portugal',
192
+ 'PW' => 'Palau',
193
+ 'PY' => 'Paraguay',
194
+ 'QA' => 'Qatar',
195
+ 'RE' => 'Reunion',
196
+ 'RO' => 'Romania',
197
+ 'RU' => 'Russia',
198
+ 'RW' => 'Rwanda',
199
+ 'SA' => 'Saudi Arabia',
200
+ 'SB' => 'Solomon Islands',
201
+ 'SC' => 'Seychelles',
202
+ 'SD' => 'Sudan',
203
+ 'SE' => 'Sweden',
204
+ 'SG' => 'Singapore',
205
+ 'SH' => 'Saint Helena',
206
+ 'SI' => 'Slovenia',
207
+ 'SJ' => 'Svalbard and Jan Mayen',
208
+ 'SK' => 'Slovakia',
209
+ 'SL' => 'Sierra Leone',
210
+ 'SM' => 'San Marino',
211
+ 'SN' => 'Senegal',
212
+ 'SO' => 'Somalia',
213
+ 'SR' => 'Suriname',
214
+ 'ST' => 'Sao Tome and Principe',
215
+ 'SV' => 'El Salvador',
216
+ 'SY' => 'Syria',
217
+ 'SZ' => 'Swaziland',
218
+ 'TC' => 'Turks and Caicos Islands',
219
+ 'TD' => 'Chad',
220
+ 'TF' => 'French Southern territories',
221
+ 'TG' => 'Togo',
222
+ 'TH' => 'Thailand',
223
+ 'TJ' => 'Tajikistan',
224
+ 'TK' => 'Tokelau',
225
+ 'TM' => 'Turkmenistan',
226
+ 'TN' => 'Tunisia',
227
+ 'TO' => 'Tonga',
228
+ 'TP' => 'East Timor',
229
+ 'TR' => 'Turkey',
230
+ 'TT' => 'Trinidad and Tobago',
231
+ 'TV' => 'Tuvalu',
232
+ 'TW' => 'Taiwan',
233
+ 'TZ' => 'Tanzania',
234
+ 'UA' => 'Ukraine',
235
+ 'UG' => 'Uganda',
236
+ 'UM' => 'United States Minor Outlying Islands',
237
+ 'US' => 'United States',
238
+ 'UY' => 'Uruguay',
239
+ 'UZ' => 'Uzbekistan',
240
+ 'VA' => 'Holy See (Vatican City State)',
241
+ 'VC' => 'Saint Vincent and the Grenadines',
242
+ 'VE' => 'Venezuela',
243
+ 'VG' => 'Virgin Islands, British',
244
+ 'VI' => 'Virgin Islands, U.S.',
245
+ 'VN' => 'Vietnam',
246
+ 'VU' => 'Vanuatu',
247
+ 'WF' => 'Wallis and Futuna',
248
+ 'WS' => 'Samoa',
249
+ 'YE' => 'Yemen',
250
+ 'YT' => 'Mayotte',
251
+ 'YU' => 'Yugoslavia',
252
+ 'ZA' => 'South Africa',
253
+ 'ZM' => 'Zambia',
254
+ 'ZW' => 'Zimbabwe' );
255
  /* @formatter:on */
tools/src/Google/Auth/Abstract.php CHANGED
@@ -1,40 +1,40 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * Abstract class for the Authentication in the API client
21
- *
22
- * @author Chris Chabot <chabotc@google.com>
23
- *
24
- */
25
- abstract class Google_Auth_Abstract
26
- {
27
-
28
- /**
29
- * An utility function that first calls $this->auth->sign($request) and then
30
- * executes makeRequest() on that signed request.
31
- * Used for when a request
32
- * should be authenticated
33
- *
34
- * @param Google_Http_Request $request
35
- * @return Google_Http_Request $request
36
- */
37
- abstract public function authenticatedRequest(Google_Http_Request $request);
38
-
39
- abstract public function sign(Google_Http_Request $request);
40
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * Abstract class for the Authentication in the API client
21
+ *
22
+ * @author Chris Chabot <chabotc@google.com>
23
+ *
24
+ */
25
+ abstract class Google_Auth_Abstract
26
+ {
27
+
28
+ /**
29
+ * An utility function that first calls $this->auth->sign($request) and then
30
+ * executes makeRequest() on that signed request.
31
+ * Used for when a request
32
+ * should be authenticated
33
+ *
34
+ * @param Google_Http_Request $request
35
+ * @return Google_Http_Request $request
36
+ */
37
+ abstract public function authenticatedRequest(Google_Http_Request $request);
38
+
39
+ abstract public function sign(Google_Http_Request $request);
40
  }
tools/src/Google/Auth/AppIdentity.php CHANGED
@@ -1,101 +1,101 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- /*
18
- * WARNING - this class depends on the Google App Engine PHP library
19
- * which is 5.3 and above only, so if you include this in a PHP 5.2
20
- * setup or one without 5.3 things will blow up.
21
- */
22
- use google\appengine\api\app_identity\AppIdentityService;
23
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
24
-
25
- /**
26
- * Authentication via the Google App Engine App Identity service.
27
- */
28
- class Google_Auth_AppIdentity extends Google_Auth_Abstract
29
- {
30
-
31
- const CACHE_PREFIX = "Google_Auth_AppIdentity::";
32
-
33
- private $key = null;
34
-
35
- private $client;
36
-
37
- private $token = false;
38
-
39
- private $tokenScopes = false;
40
-
41
- public function __construct(Google_Client $client, $config = null)
42
- {
43
- $this->client = $client;
44
- }
45
-
46
- /**
47
- * Retrieve an access token for the scopes supplied.
48
- */
49
- public function authenticateForScope($scopes)
50
- {
51
- if ($this->token && $this->tokenScopes == $scopes) {
52
- return $this->token;
53
- }
54
- $cacheKey = self::CACHE_PREFIX;
55
- if (is_string($scopes)) {
56
- $cacheKey .= $scopes;
57
- } else
58
- if (is_array($scopes)) {
59
- $cacheKey .= implode(":", $scopes);
60
- }
61
- $this->token = $this->client->getCache()->get($cacheKey);
62
- if (! $this->token) {
63
- $this->token = AppIdentityService::getAccessToken($scopes);
64
- if ($this->token) {
65
- $this->client->getCache()->set($cacheKey, $this->token);
66
- }
67
- }
68
- $this->tokenScopes = $scopes;
69
- return $this->token;
70
- }
71
-
72
- /**
73
- * Perform an authenticated / signed apiHttpRequest.
74
- * This function takes the apiHttpRequest, calls apiAuth->sign on it
75
- * (which can modify the request in what ever way fits the auth mechanism)
76
- * and then calls apiCurlIO::makeRequest on the signed request
77
- *
78
- * @param Google_Http_Request $request
79
- * @return Google_Http_Request The resulting HTTP response including the
80
- * responseHttpCode, responseHeaders and responseBody.
81
- */
82
- public function authenticatedRequest(Google_Http_Request $request)
83
- {
84
- $request = $this->sign($request);
85
- return $this->client->getIo()->makeRequest($request);
86
- }
87
-
88
- public function sign(Google_Http_Request $request)
89
- {
90
- if (! $this->token) {
91
- // No token, so nothing to do.
92
- return $request;
93
- }
94
- $this->client->getLogger()->debug('App Identity authentication');
95
- // Add the OAuth2 header to the request
96
- $request->setRequestHeaders(array(
97
- 'Authorization' => 'Bearer ' . $this->token['access_token']
98
- ));
99
- return $request;
100
- }
101
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /*
18
+ * WARNING - this class depends on the Google App Engine PHP library
19
+ * which is 5.3 and above only, so if you include this in a PHP 5.2
20
+ * setup or one without 5.3 things will blow up.
21
+ */
22
+ use google\appengine\api\app_identity\AppIdentityService;
23
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
24
+
25
+ /**
26
+ * Authentication via the Google App Engine App Identity service.
27
+ */
28
+ class Google_Auth_AppIdentity extends Google_Auth_Abstract
29
+ {
30
+
31
+ const CACHE_PREFIX = "Google_Auth_AppIdentity::";
32
+
33
+ private $key = null;
34
+
35
+ private $client;
36
+
37
+ private $token = false;
38
+
39
+ private $tokenScopes = false;
40
+
41
+ public function __construct(Google_Client $client, $config = null)
42
+ {
43
+ $this->client = $client;
44
+ }
45
+
46
+ /**
47
+ * Retrieve an access token for the scopes supplied.
48
+ */
49
+ public function authenticateForScope($scopes)
50
+ {
51
+ if ($this->token && $this->tokenScopes == $scopes) {
52
+ return $this->token;
53
+ }
54
+ $cacheKey = self::CACHE_PREFIX;
55
+ if (is_string($scopes)) {
56
+ $cacheKey .= $scopes;
57
+ } else
58
+ if (is_array($scopes)) {
59
+ $cacheKey .= implode(":", $scopes);
60
+ }
61
+ $this->token = $this->client->getCache()->get($cacheKey);
62
+ if (! $this->token) {
63
+ $this->token = AppIdentityService::getAccessToken($scopes);
64
+ if ($this->token) {
65
+ $this->client->getCache()->set($cacheKey, $this->token);
66
+ }
67
+ }
68
+ $this->tokenScopes = $scopes;
69
+ return $this->token;
70
+ }
71
+
72
+ /**
73
+ * Perform an authenticated / signed apiHttpRequest.
74
+ * This function takes the apiHttpRequest, calls apiAuth->sign on it
75
+ * (which can modify the request in what ever way fits the auth mechanism)
76
+ * and then calls apiCurlIO::makeRequest on the signed request
77
+ *
78
+ * @param Google_Http_Request $request
79
+ * @return Google_Http_Request The resulting HTTP response including the
80
+ * responseHttpCode, responseHeaders and responseBody.
81
+ */
82
+ public function authenticatedRequest(Google_Http_Request $request)
83
+ {
84
+ $request = $this->sign($request);
85
+ return $this->client->getIo()->makeRequest($request);
86
+ }
87
+
88
+ public function sign(Google_Http_Request $request)
89
+ {
90
+ if (! $this->token) {
91
+ // No token, so nothing to do.
92
+ return $request;
93
+ }
94
+ $this->client->getLogger()->debug('App Identity authentication');
95
+ // Add the OAuth2 header to the request
96
+ $request->setRequestHeaders(array(
97
+ 'Authorization' => 'Bearer ' . $this->token['access_token']
98
+ ));
99
+ return $request;
100
+ }
101
  }
tools/src/Google/Auth/AssertionCredentials.php CHANGED
@@ -1,143 +1,143 @@
1
- <?php
2
- /*
3
- * Copyright 2012 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * Credentials object used for OAuth 2.0 Signed JWT assertion grants.
21
- *
22
- * @author Chirag Shah <chirags@google.com>
23
- */
24
- class Google_Auth_AssertionCredentials
25
- {
26
-
27
- const MAX_TOKEN_LIFETIME_SECS = 3600;
28
-
29
- public $serviceAccountName;
30
-
31
- public $scopes;
32
-
33
- public $privateKey;
34
-
35
- public $privateKeyPassword;
36
-
37
- public $assertionType;
38
-
39
- public $sub;
40
-
41
- /**
42
- *
43
- * @deprecated
44
- *
45
- * @link http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
46
- */
47
- public $prn;
48
-
49
- private $useCache;
50
-
51
- /**
52
- *
53
- * @param
54
- * $serviceAccountName
55
- * @param $scopes array
56
- * List of scopes
57
- * @param
58
- * $privateKey
59
- * @param string $privateKeyPassword
60
- * @param string $assertionType
61
- * @param bool|string $sub
62
- * The email address of the user for which the
63
- * application is requesting delegated access.
64
- * @param
65
- * bool useCache Whether to generate a cache key and allow
66
- * automatic caching of the generated token.
67
- */
68
- public function __construct($serviceAccountName, $scopes, $privateKey, $privateKeyPassword = 'notasecret', $assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer', $sub = false, $useCache = true)
69
- {
70
- $this->serviceAccountName = $serviceAccountName;
71
- $this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
72
- $this->privateKey = $privateKey;
73
- $this->privateKeyPassword = $privateKeyPassword;
74
- $this->assertionType = $assertionType;
75
- $this->sub = $sub;
76
- $this->prn = $sub;
77
- $this->useCache = $useCache;
78
- }
79
-
80
- /**
81
- * Generate a unique key to represent this credential.
82
- *
83
- * @return string
84
- */
85
- public function getCacheKey()
86
- {
87
- if (! $this->useCache) {
88
- return false;
89
- }
90
- $h = $this->sub;
91
- $h .= $this->assertionType;
92
- $h .= $this->privateKey;
93
- $h .= $this->scopes;
94
- $h .= $this->serviceAccountName;
95
- return md5($h);
96
- }
97
-
98
- public function generateAssertion()
99
- {
100
- $now = time();
101
- $jwtParams = array(
102
- 'aud' => Google_Auth_OAuth2::OAUTH2_TOKEN_URI,
103
- 'scope' => $this->scopes,
104
- 'iat' => $now,
105
- 'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
106
- 'iss' => $this->serviceAccountName
107
- );
108
- if ($this->sub !== false) {
109
- $jwtParams['sub'] = $this->sub;
110
- } else
111
- if ($this->prn !== false) {
112
- $jwtParams['prn'] = $this->prn;
113
- }
114
- return $this->makeSignedJwt($jwtParams);
115
- }
116
-
117
- /**
118
- * Creates a signed JWT.
119
- *
120
- * @param array $payload
121
- * @return string The signed JWT.
122
- */
123
- private function makeSignedJwt($payload)
124
- {
125
- $header = array(
126
- 'typ' => 'JWT',
127
- 'alg' => 'RS256'
128
- );
129
- $payload = json_encode($payload);
130
- // Handle some overzealous escaping in PHP json that seemed to cause some errors
131
- // with claimsets.
132
- $payload = str_replace('\/', '/', $payload);
133
- $segments = array(
134
- Google_Utils::urlSafeB64Encode(json_encode($header)),
135
- Google_Utils::urlSafeB64Encode($payload)
136
- );
137
- $signingInput = implode('.', $segments);
138
- $signer = new Google_Signer_P12($this->privateKey, $this->privateKeyPassword);
139
- $signature = $signer->sign($signingInput);
140
- $segments[] = Google_Utils::urlSafeB64Encode($signature);
141
- return implode(".", $segments);
142
- }
143
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2012 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * Credentials object used for OAuth 2.0 Signed JWT assertion grants.
21
+ *
22
+ * @author Chirag Shah <chirags@google.com>
23
+ */
24
+ class Google_Auth_AssertionCredentials
25
+ {
26
+
27
+ const MAX_TOKEN_LIFETIME_SECS = 3600;
28
+
29
+ public $serviceAccountName;
30
+
31
+ public $scopes;
32
+
33
+ public $privateKey;
34
+
35
+ public $privateKeyPassword;
36
+
37
+ public $assertionType;
38
+
39
+ public $sub;
40
+
41
+ /**
42
+ *
43
+ * @deprecated
44
+ *
45
+ * @link http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
46
+ */
47
+ public $prn;
48
+
49
+ private $useCache;
50
+
51
+ /**
52
+ *
53
+ * @param
54
+ * $serviceAccountName
55
+ * @param $scopes array
56
+ * List of scopes
57
+ * @param
58
+ * $privateKey
59
+ * @param string $privateKeyPassword
60
+ * @param string $assertionType
61
+ * @param bool|string $sub
62
+ * The email address of the user for which the
63
+ * application is requesting delegated access.
64
+ * @param
65
+ * bool useCache Whether to generate a cache key and allow
66
+ * automatic caching of the generated token.
67
+ */
68
+ public function __construct($serviceAccountName, $scopes, $privateKey, $privateKeyPassword = 'notasecret', $assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer', $sub = false, $useCache = true)
69
+ {
70
+ $this->serviceAccountName = $serviceAccountName;
71
+ $this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
72
+ $this->privateKey = $privateKey;
73
+ $this->privateKeyPassword = $privateKeyPassword;
74
+ $this->assertionType = $assertionType;
75
+ $this->sub = $sub;
76
+ $this->prn = $sub;
77
+ $this->useCache = $useCache;
78
+ }
79
+
80
+ /**
81
+ * Generate a unique key to represent this credential.
82
+ *
83
+ * @return string
84
+ */
85
+ public function getCacheKey()
86
+ {
87
+ if (! $this->useCache) {
88
+ return false;
89
+ }
90
+ $h = $this->sub;
91
+ $h .= $this->assertionType;
92
+ $h .= $this->privateKey;
93
+ $h .= $this->scopes;
94
+ $h .= $this->serviceAccountName;
95
+ return md5($h);
96
+ }
97
+
98
+ public function generateAssertion()
99
+ {
100
+ $now = time();
101
+ $jwtParams = array(
102
+ 'aud' => Google_Auth_OAuth2::OAUTH2_TOKEN_URI,
103
+ 'scope' => $this->scopes,
104
+ 'iat' => $now,
105
+ 'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
106
+ 'iss' => $this->serviceAccountName
107
+ );
108
+ if ($this->sub !== false) {
109
+ $jwtParams['sub'] = $this->sub;
110
+ } else
111
+ if ($this->prn !== false) {
112
+ $jwtParams['prn'] = $this->prn;
113
+ }
114
+ return $this->makeSignedJwt($jwtParams);
115
+ }
116
+
117
+ /**
118
+ * Creates a signed JWT.
119
+ *
120
+ * @param array $payload
121
+ * @return string The signed JWT.
122
+ */
123
+ private function makeSignedJwt($payload)
124
+ {
125
+ $header = array(
126
+ 'typ' => 'JWT',
127
+ 'alg' => 'RS256'
128
+ );
129
+ $payload = json_encode($payload);
130
+ // Handle some overzealous escaping in PHP json that seemed to cause some errors
131
+ // with claimsets.
132
+ $payload = str_replace('\/', '/', $payload);
133
+ $segments = array(
134
+ Google_Utils::urlSafeB64Encode(json_encode($header)),
135
+ Google_Utils::urlSafeB64Encode($payload)
136
+ );
137
+ $signingInput = implode('.', $segments);
138
+ $signer = new Google_Signer_P12($this->privateKey, $this->privateKeyPassword);
139
+ $signature = $signer->sign($signingInput);
140
+ $segments[] = Google_Utils::urlSafeB64Encode($signature);
141
+ return implode(".", $segments);
142
+ }
143
  }
tools/src/Google/Auth/Exception.php CHANGED
@@ -1,21 +1,21 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- class Google_Auth_Exception extends Google_Exception
20
- {
21
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ class Google_Auth_Exception extends Google_Exception
20
+ {
21
  }
tools/src/Google/Auth/LoginTicket.php CHANGED
@@ -1,76 +1,76 @@
1
- <?php
2
- /*
3
- * Copyright 2011 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * Class to hold information about an authenticated login.
21
- *
22
- * @author Brian Eaton <beaton@google.com>
23
- */
24
- class Google_Auth_LoginTicket
25
- {
26
-
27
- const USER_ATTR = "sub";
28
- // Information from id token envelope.
29
- private $envelope;
30
- // Information from id token payload.
31
- private $payload;
32
-
33
- /**
34
- * Creates a user based on the supplied token.
35
- *
36
- * @param string $envelope
37
- * Header from a verified authentication token.
38
- * @param string $payload
39
- * Information from a verified authentication token.
40
- */
41
- public function __construct($envelope, $payload)
42
- {
43
- $this->envelope = $envelope;
44
- $this->payload = $payload;
45
- }
46
-
47
- /**
48
- * Returns the numeric identifier for the user.
49
- *
50
- * @throws Google_Auth_Exception
51
- * @return
52
- *
53
- */
54
- public function getUserId()
55
- {
56
- if (array_key_exists(self::USER_ATTR, $this->payload)) {
57
- return $this->payload[self::USER_ATTR];
58
- }
59
- throw new Google_Auth_Exception("No user_id in token");
60
- }
61
-
62
- /**
63
- * Returns attributes from the login ticket.
64
- * This can contain
65
- * various information about the user session.
66
- *
67
- * @return array
68
- */
69
- public function getAttributes()
70
- {
71
- return array(
72
- "envelope" => $this->envelope,
73
- "payload" => $this->payload
74
- );
75
- }
76
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2011 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * Class to hold information about an authenticated login.
21
+ *
22
+ * @author Brian Eaton <beaton@google.com>
23
+ */
24
+ class Google_Auth_LoginTicket
25
+ {
26
+
27
+ const USER_ATTR = "sub";
28
+ // Information from id token envelope.
29
+ private $envelope;
30
+ // Information from id token payload.
31
+ private $payload;
32
+
33
+ /**
34
+ * Creates a user based on the supplied token.
35
+ *
36
+ * @param string $envelope
37
+ * Header from a verified authentication token.
38
+ * @param string $payload
39
+ * Information from a verified authentication token.
40
+ */
41
+ public function __construct($envelope, $payload)
42
+ {
43
+ $this->envelope = $envelope;
44
+ $this->payload = $payload;
45
+ }
46
+
47
+ /**
48
+ * Returns the numeric identifier for the user.
49
+ *
50
+ * @throws Google_Auth_Exception
51
+ * @return
52
+ *
53
+ */
54
+ public function getUserId()
55
+ {
56
+ if (array_key_exists(self::USER_ATTR, $this->payload)) {
57
+ return $this->payload[self::USER_ATTR];
58
+ }
59
+ throw new Google_Auth_Exception("No user_id in token");
60
+ }
61
+
62
+ /**
63
+ * Returns attributes from the login ticket.
64
+ * This can contain
65
+ * various information about the user session.
66
+ *
67
+ * @return array
68
+ */
69
+ public function getAttributes()
70
+ {
71
+ return array(
72
+ "envelope" => $this->envelope,
73
+ "payload" => $this->payload
74
+ );
75
+ }
76
  }
tools/src/Google/Auth/OAuth2.php CHANGED
@@ -1,547 +1,547 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * Authentication class that deals with the OAuth 2 web-server authentication flow
21
- *
22
- * @author Chris Chabot <chabotc@google.com>
23
- * @author Chirag Shah <chirags@google.com>
24
- *
25
- */
26
- class Google_Auth_OAuth2 extends Google_Auth_Abstract
27
- {
28
-
29
- const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
30
-
31
- const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
32
-
33
- const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
34
-
35
- const CLOCK_SKEW_SECS = 300;
36
- // five minutes in seconds
37
- const AUTH_TOKEN_LIFETIME_SECS = 300;
38
- // five minutes in seconds
39
- const MAX_TOKEN_LIFETIME_SECS = 86400;
40
- // one day in seconds
41
- const OAUTH2_ISSUER = 'accounts.google.com';
42
-
43
- /**
44
- *
45
- * @var Google_Auth_AssertionCredentials $assertionCredentials
46
- */
47
- private $assertionCredentials;
48
-
49
- /**
50
- *
51
- * @var string The state parameters for CSRF and other forgery protection.
52
- */
53
- private $state;
54
-
55
- /**
56
- *
57
- * @var array The token bundle.
58
- */
59
- private $token = array();
60
-
61
- /**
62
- *
63
- * @var Google_Client the base client
64
- */
65
- private $client;
66
-
67
- /**
68
- * Instantiates the class, but does not initiate the login flow, leaving it
69
- * to the discretion of the caller.
70
- */
71
- public function __construct(Google_Client $client)
72
- {
73
- $this->client = $client;
74
- }
75
-
76
- /**
77
- * Perform an authenticated / signed apiHttpRequest.
78
- * This function takes the apiHttpRequest, calls apiAuth->sign on it
79
- * (which can modify the request in what ever way fits the auth mechanism)
80
- * and then calls apiCurlIO::makeRequest on the signed request
81
- *
82
- * @param Google_Http_Request $request
83
- * @return Google_Http_Request The resulting HTTP response including the
84
- * responseHttpCode, responseHeaders and responseBody.
85
- */
86
- public function authenticatedRequest(Google_Http_Request $request)
87
- {
88
- $request = $this->sign($request);
89
- return $this->client->getIo()->makeRequest($request);
90
- }
91
-
92
- /**
93
- *
94
- * @param string $code
95
- * @throws Google_Auth_Exception
96
- * @return string
97
- */
98
- public function authenticate($code)
99
- {
100
- if (strlen($code) == 0) {
101
- throw new Google_Auth_Exception("Invalid code");
102
- }
103
- // We got here from the redirect from a successful authorization grant,
104
- // fetch the access token
105
- $request = new Google_Http_Request(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
106
- 'code' => $code,
107
- 'grant_type' => 'authorization_code',
108
- 'redirect_uri' => $this->client->getClassConfig($this, 'redirect_uri'),
109
- 'client_id' => $this->client->getClassConfig($this, 'client_id'),
110
- 'client_secret' => $this->client->getClassConfig($this, 'client_secret')
111
- ));
112
- $request->disableGzip();
113
- $response = $this->client->getIo()->makeRequest($request);
114
- if ($response->getResponseHttpCode() == 200) {
115
- $this->setAccessToken($response->getResponseBody());
116
- $this->token['created'] = time();
117
- return $this->getAccessToken();
118
- } else {
119
- $decodedResponse = json_decode($response->getResponseBody(), true);
120
- if ($decodedResponse != null && $decodedResponse['error']) {
121
- $errorText = $decodedResponse['error'];
122
- if (isset($decodedResponse['error_description'])) {
123
- $errorText .= ": " . $decodedResponse['error_description'];
124
- }
125
- }
126
- throw new Google_Auth_Exception(sprintf("Error fetching OAuth2 access token, message: '%s'", $errorText), $response->getResponseHttpCode());
127
- }
128
- }
129
-
130
- /**
131
- * Create a URL to obtain user authorization.
132
- * The authorization endpoint allows the user to first
133
- * authenticate, and then grant/deny the access request.
134
- *
135
- * @param string $scope
136
- * The scope is expressed as a list of space-delimited strings.
137
- * @return string
138
- */
139
- public function createAuthUrl($scope)
140
- {
141
- $params = array(
142
- 'response_type' => 'code',
143
- 'redirect_uri' => $this->client->getClassConfig($this, 'redirect_uri'),
144
- 'client_id' => $this->client->getClassConfig($this, 'client_id'),
145
- 'scope' => $scope,
146
- 'access_type' => $this->client->getClassConfig($this, 'access_type')
147
- );
148
- // Prefer prompt to approval prompt.
149
- if ($this->client->getClassConfig($this, 'prompt')) {
150
- $params = $this->maybeAddParam($params, 'prompt');
151
- } else {
152
- $params = $this->maybeAddParam($params, 'approval_prompt');
153
- }
154
- $params = $this->maybeAddParam($params, 'login_hint');
155
- $params = $this->maybeAddParam($params, 'hd');
156
- $params = $this->maybeAddParam($params, 'openid.realm');
157
- $params = $this->maybeAddParam($params, 'include_granted_scopes');
158
- // If the list of scopes contains plus.login, add request_visible_actions
159
- // to auth URL.
160
- $rva = $this->client->getClassConfig($this, 'request_visible_actions');
161
- if (strpos($scope, 'plus.login') && strlen($rva) > 0) {
162
- $params['request_visible_actions'] = $rva;
163
- }
164
- if (isset($this->state)) {
165
- $params['state'] = $this->state;
166
- }
167
- return self::OAUTH2_AUTH_URL . "?" . http_build_query($params, '', '&');
168
- }
169
-
170
- /**
171
- *
172
- * @param string $token
173
- * @throws Google_Auth_Exception
174
- */
175
- public function setAccessToken($token)
176
- {
177
- $token = json_decode($token, true);
178
- if ($token == null) {
179
- throw new Google_Auth_Exception('Could not json decode the token');
180
- }
181
- if (! isset($token['access_token'])) {
182
- throw new Google_Auth_Exception("Invalid token format");
183
- }
184
- $this->token = $token;
185
- }
186
-
187
- public function getAccessToken()
188
- {
189
- return json_encode($this->token);
190
- }
191
-
192
- public function getRefreshToken()
193
- {
194
- if (array_key_exists('refresh_token', $this->token)) {
195
- return $this->token['refresh_token'];
196
- } else {
197
- return null;
198
- }
199
- }
200
-
201
- public function setState($state)
202
- {
203
- $this->state = $state;
204
- }
205
-
206
- public function setAssertionCredentials(Google_Auth_AssertionCredentials $creds)
207
- {
208
- $this->assertionCredentials = $creds;
209
- }
210
-
211
- /**
212
- * Include an accessToken in a given apiHttpRequest.
213
- *
214
- * @param Google_Http_Request $request
215
- * @return Google_Http_Request
216
- * @throws Google_Auth_Exception
217
- */
218
- public function sign(Google_Http_Request $request)
219
- {
220
- // add the developer key to the request before signing it
221
- if ($this->client->getClassConfig($this, 'developer_key')) {
222
- $request->setQueryParam('key', $this->client->getClassConfig($this, 'developer_key'));
223
- }
224
- // Cannot sign the request without an OAuth access token.
225
- if (null == $this->token && null == $this->assertionCredentials) {
226
- return $request;
227
- }
228
- // Check if the token is set to expire in the next 30 seconds
229
- // (or has already expired).
230
- if ($this->isAccessTokenExpired()) {
231
- if ($this->assertionCredentials) {
232
- $this->refreshTokenWithAssertion();
233
- } else {
234
- $this->client->getLogger()->debug('OAuth2 access token expired');
235
- if (! array_key_exists('refresh_token', $this->token)) {
236
- $error = "The OAuth 2.0 access token has expired," . " and a refresh token is not available. Refresh tokens" . " are not returned for responses that were auto-approved.";
237
- $this->client->getLogger()->error($error);
238
- throw new Google_Auth_Exception($error);
239
- }
240
- $this->refreshToken($this->token['refresh_token']);
241
- }
242
- }
243
- $this->client->getLogger()->debug('OAuth2 authentication');
244
- // Add the OAuth2 header to the request
245
- $request->setRequestHeaders(array(
246
- 'Authorization' => 'Bearer ' . $this->token['access_token']
247
- ));
248
- return $request;
249
- }
250
-
251
- /**
252
- * Fetches a fresh access token with the given refresh token.
253
- *
254
- * @param string $refreshToken
255
- * @return void
256
- */
257
- public function refreshToken($refreshToken)
258
- {
259
- $this->refreshTokenRequest(array(
260
- 'client_id' => $this->client->getClassConfig($this, 'client_id'),
261
- 'client_secret' => $this->client->getClassConfig($this, 'client_secret'),
262
- 'refresh_token' => $refreshToken,
263
- 'grant_type' => 'refresh_token'
264
- ));
265
- }
266
-
267
- /**
268
- * Fetches a fresh access token with a given assertion token.
269
- *
270
- * @param Google_Auth_AssertionCredentials $assertionCredentials
271
- * optional.
272
- * @return void
273
- */
274
- public function refreshTokenWithAssertion($assertionCredentials = null)
275
- {
276
- if (! $assertionCredentials) {
277
- $assertionCredentials = $this->assertionCredentials;
278
- }
279
- $cacheKey = $assertionCredentials->getCacheKey();
280
- if ($cacheKey) {
281
- // We can check whether we have a token available in the
282
- // cache. If it is expired, we can retrieve a new one from
283
- // the assertion.
284
- $token = $this->client->getCache()->get($cacheKey);
285
- if ($token) {
286
- $this->setAccessToken($token);
287
- }
288
- if (! $this->isAccessTokenExpired()) {
289
- return;
290
- }
291
- }
292
- $this->client->getLogger()->debug('OAuth2 access token expired');
293
- $this->refreshTokenRequest(array(
294
- 'grant_type' => 'assertion',
295
- 'assertion_type' => $assertionCredentials->assertionType,
296
- 'assertion' => $assertionCredentials->generateAssertion()
297
- ));
298
- if ($cacheKey) {
299
- // Attempt to cache the token.
300
- $this->client->getCache()->set($cacheKey, $this->getAccessToken());
301
- }
302
- }
303
-
304
- private function refreshTokenRequest($params)
305
- {
306
- if (isset($params['assertion'])) {
307
- $this->client->getLogger()->info('OAuth2 access token refresh with Signed JWT assertion grants.');
308
- } else {
309
- $this->client->getLogger()->info('OAuth2 access token refresh');
310
- }
311
- $http = new Google_Http_Request(self::OAUTH2_TOKEN_URI, 'POST', array(), $params);
312
- $http->disableGzip();
313
- $request = $this->client->getIo()->makeRequest($http);
314
- $code = $request->getResponseHttpCode();
315
- $body = $request->getResponseBody();
316
- if (200 == $code) {
317
- $token = json_decode($body, true);
318
- if ($token == null) {
319
- throw new Google_Auth_Exception("Could not json decode the access token");
320
- }
321
- if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
322
- throw new Google_Auth_Exception("Invalid token format");
323
- }
324
- if (isset($token['id_token'])) {
325
- $this->token['id_token'] = $token['id_token'];
326
- }
327
- $this->token['access_token'] = $token['access_token'];
328
- $this->token['expires_in'] = $token['expires_in'];
329
- $this->token['created'] = time();
330
- } else {
331
- throw new Google_Auth_Exception("Error refreshing the OAuth2 token, message: '$body'", $code);
332
- }
333
- }
334
-
335
- /**
336
- * Revoke an OAuth2 access token or refresh token.
337
- * This method will revoke the current access
338
- * token, if a token isn't provided.
339
- *
340
- * @throws Google_Auth_Exception
341
- * @param string|null $token
342
- * The token (access token or a refresh token) that should be revoked.
343
- * @return boolean Returns True if the revocation was successful, otherwise False.
344
- */
345
- public function revokeToken($token = null)
346
- {
347
- if (! $token) {
348
- if (! $this->token) {
349
- // Not initialized, no token to actually revoke
350
- return false;
351
- } elseif (array_key_exists('refresh_token', $this->token)) {
352
- $token = $this->token['refresh_token'];
353
- } else {
354
- $token = $this->token['access_token'];
355
- }
356
- }
357
- $request = new Google_Http_Request(self::OAUTH2_REVOKE_URI, 'POST', array(), "token=$token");
358
- $request->disableGzip();
359
- $response = $this->client->getIo()->makeRequest($request);
360
- $code = $response->getResponseHttpCode();
361
- if ($code == 200) {
362
- $this->token = null;
363
- return true;
364
- }
365
- return false;
366
- }
367
-
368
- /**
369
- * Returns if the access_token is expired.
370
- *
371
- * @return bool Returns True if the access_token is expired.
372
- */
373
- public function isAccessTokenExpired()
374
- {
375
- if (! $this->token || ! isset($this->token['created'])) {
376
- return true;
377
- }
378
- // If the token is set to expire in the next 30 seconds.
379
- $expired = ($this->token['created'] + ($this->token['expires_in'] - 30)) < time();
380
- return $expired;
381
- }
382
- // Gets federated sign-on certificates to use for verifying identity tokens.
383
- // Returns certs as array structure, where keys are key ids, and values
384
- // are PEM encoded certificates.
385
- private function getFederatedSignOnCerts()
386
- {
387
- return $this->retrieveCertsFromLocation($this->client->getClassConfig($this, 'federated_signon_certs_url'));
388
- }
389
-
390
- /**
391
- * Retrieve and cache a certificates file.
392
- *
393
- * @param $url string
394
- * location
395
- * @throws Google_Auth_Exception
396
- * @return array certificates
397
- */
398
- public function retrieveCertsFromLocation($url)
399
- {
400
- // If we're retrieving a local file, just grab it.
401
- if ("http" != substr($url, 0, 4)) {
402
- $file = file_get_contents($url);
403
- if ($file) {
404
- return json_decode($file, true);
405
- } else {
406
- throw new Google_Auth_Exception("Failed to retrieve verification certificates: '" . $url . "'.");
407
- }
408
- }
409
- // This relies on makeRequest caching certificate responses.
410
- $request = $this->client->getIo()->makeRequest(new Google_Http_Request($url));
411
- if ($request->getResponseHttpCode() == 200) {
412
- $certs = json_decode($request->getResponseBody(), true);
413
- if ($certs) {
414
- return $certs;
415
- }
416
- }
417
- throw new Google_Auth_Exception("Failed to retrieve verification certificates: '" . $request->getResponseBody() . "'.", $request->getResponseHttpCode());
418
- }
419
-
420
- /**
421
- * Verifies an id token and returns the authenticated apiLoginTicket.
422
- * Throws an exception if the id token is not valid.
423
- * The audience parameter can be used to control which id tokens are
424
- * accepted. By default, the id token must have been issued to this OAuth2 client.
425
- *
426
- * @param
427
- * $id_token
428
- * @param
429
- * $audience
430
- * @return Google_Auth_LoginTicket
431
- */
432
- public function verifyIdToken($id_token = null, $audience = null)
433
- {
434
- if (! $id_token) {
435
- $id_token = $this->token['id_token'];
436
- }
437
- $certs = $this->getFederatedSignonCerts();
438
- if (! $audience) {
439
- $audience = $this->client->getClassConfig($this, 'client_id');
440
- }
441
- return $this->verifySignedJwtWithCerts($id_token, $certs, $audience, self::OAUTH2_ISSUER);
442
- }
443
-
444
- /**
445
- * Verifies the id token, returns the verified token contents.
446
- *
447
- * @param $jwt string
448
- * the token
449
- * @param $certs array
450
- * of certificates
451
- * @param $required_audience string
452
- * the expected consumer of the token
453
- * @param
454
- * [$issuer] the expected issues, defaults to Google
455
- * @param
456
- * [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS
457
- * @throws Google_Auth_Exception
458
- * @return mixed token information if valid, false if not
459
- */
460
- public function verifySignedJwtWithCerts($jwt, $certs, $required_audience, $issuer = null, $max_expiry = null)
461
- {
462
- if (! $max_expiry) {
463
- // Set the maximum time we will accept a token for.
464
- $max_expiry = self::MAX_TOKEN_LIFETIME_SECS;
465
- }
466
- $segments = explode(".", $jwt);
467
- if (count($segments) != 3) {
468
- throw new Google_Auth_Exception("Wrong number of segments in token: $jwt");
469
- }
470
- $signed = $segments[0] . "." . $segments[1];
471
- $signature = Google_Utils::urlSafeB64Decode($segments[2]);
472
- // Parse envelope.
473
- $envelope = json_decode(Google_Utils::urlSafeB64Decode($segments[0]), true);
474
- if (! $envelope) {
475
- throw new Google_Auth_Exception("Can't parse token envelope: " . $segments[0]);
476
- }
477
- // Parse token
478
- $json_body = Google_Utils::urlSafeB64Decode($segments[1]);
479
- $payload = json_decode($json_body, true);
480
- if (! $payload) {
481
- throw new Google_Auth_Exception("Can't parse token payload: " . $segments[1]);
482
- }
483
- // Check signature
484
- $verified = false;
485
- foreach ($certs as $keyName => $pem) {
486
- $public_key = new Google_Verifier_Pem($pem);
487
- if ($public_key->verify($signed, $signature)) {
488
- $verified = true;
489
- break;
490
- }
491
- }
492
- if (! $verified) {
493
- throw new Google_Auth_Exception("Invalid token signature: $jwt");
494
- }
495
- // Check issued-at timestamp
496
- $iat = 0;
497
- if (array_key_exists("iat", $payload)) {
498
- $iat = $payload["iat"];
499
- }
500
- if (! $iat) {
501
- throw new Google_Auth_Exception("No issue time in token: $json_body");
502
- }
503
- $earliest = $iat - self::CLOCK_SKEW_SECS;
504
- // Check expiration timestamp
505
- $now = time();
506
- $exp = 0;
507
- if (array_key_exists("exp", $payload)) {
508
- $exp = $payload["exp"];
509
- }
510
- if (! $exp) {
511
- throw new Google_Auth_Exception("No expiration time in token: $json_body");
512
- }
513
- if ($exp >= $now + $max_expiry) {
514
- throw new Google_Auth_Exception(sprintf("Expiration time too far in future: %s", $json_body));
515
- }
516
- $latest = $exp + self::CLOCK_SKEW_SECS;
517
- if ($now < $earliest) {
518
- throw new Google_Auth_Exception(sprintf("Token used too early, %s < %s: %s", $now, $earliest, $json_body));
519
- }
520
- if ($now > $latest) {
521
- throw new Google_Auth_Exception(sprintf("Token used too late, %s > %s: %s", $now, $latest, $json_body));
522
- }
523
- $iss = $payload['iss'];
524
- if ($issuer && $iss != $issuer) {
525
- throw new Google_Auth_Exception(sprintf("Invalid issuer, %s != %s: %s", $iss, $issuer, $json_body));
526
- }
527
- // Check audience
528
- $aud = $payload["aud"];
529
- if ($aud != $required_audience) {
530
- throw new Google_Auth_Exception(sprintf("Wrong recipient, %s != %s:", $aud, $required_audience, $json_body));
531
- }
532
- // All good.
533
- return new Google_Auth_LoginTicket($envelope, $payload);
534
- }
535
-
536
- /**
537
- * Add a parameter to the auth params if not empty string.
538
- */
539
- private function maybeAddParam($params, $name)
540
- {
541
- $param = $this->client->getClassConfig($this, $name);
542
- if ($param != '') {
543
- $params[$name] = $param;
544
- }
545
- return $params;
546
- }
547
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2008 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * Authentication class that deals with the OAuth 2 web-server authentication flow
21
+ *
22
+ * @author Chris Chabot <chabotc@google.com>
23
+ * @author Chirag Shah <chirags@google.com>
24
+ *
25
+ */
26
+ class Google_Auth_OAuth2 extends Google_Auth_Abstract
27
+ {
28
+
29
+ const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
30
+
31
+ const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
32
+
33
+ const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
34
+
35
+ const CLOCK_SKEW_SECS = 300;
36
+ // five minutes in seconds
37
+ const AUTH_TOKEN_LIFETIME_SECS = 300;
38
+ // five minutes in seconds
39
+ const MAX_TOKEN_LIFETIME_SECS = 86400;
40
+ // one day in seconds
41
+ const OAUTH2_ISSUER = 'accounts.google.com';
42
+
43
+ /**
44
+ *
45
+ * @var Google_Auth_AssertionCredentials $assertionCredentials
46
+ */
47
+ private $assertionCredentials;
48
+
49
+ /**
50
+ *
51
+ * @var string The state parameters for CSRF and other forgery protection.
52
+ */
53
+ private $state;
54
+
55
+ /**
56
+ *
57
+ * @var array The token bundle.
58
+ */
59
+ private $token = array();
60
+
61
+ /**
62
+ *
63
+ * @var Google_Client the base client
64
+ */
65
+ private $client;
66
+
67
+ /**
68
+ * Instantiates the class, but does not initiate the login flow, leaving it
69
+ * to the discretion of the caller.
70
+ */
71
+ public function __construct(Google_Client $client)
72
+ {
73
+ $this->client = $client;
74
+ }
75
+
76
+ /**
77
+ * Perform an authenticated / signed apiHttpRequest.
78
+ * This function takes the apiHttpRequest, calls apiAuth->sign on it
79
+ * (which can modify the request in what ever way fits the auth mechanism)
80
+ * and then calls apiCurlIO::makeRequest on the signed request
81
+ *
82
+ * @param Google_Http_Request $request
83
+ * @return Google_Http_Request The resulting HTTP response including the
84
+ * responseHttpCode, responseHeaders and responseBody.
85
+ */
86
+ public function authenticatedRequest(Google_Http_Request $request)
87
+ {
88
+ $request = $this->sign($request);
89
+ return $this->client->getIo()->makeRequest($request);
90
+ }
91
+
92
+ /**
93
+ *
94
+ * @param string $code
95
+ * @throws Google_Auth_Exception
96
+ * @return string
97
+ */
98
+ public function authenticate($code)
99
+ {
100
+ if (strlen($code) == 0) {
101
+ throw new Google_Auth_Exception("Invalid code");
102
+ }
103
+ // We got here from the redirect from a successful authorization grant,
104
+ // fetch the access token
105
+ $request = new Google_Http_Request(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
106
+ 'code' => $code,
107
+ 'grant_type' => 'authorization_code',
108
+ 'redirect_uri' => $this->client->getClassConfig($this, 'redirect_uri'),
109
+ 'client_id' => $this->client->getClassConfig($this, 'client_id'),
110
+ 'client_secret' => $this->client->getClassConfig($this, 'client_secret')
111
+ ));
112
+ $request->disableGzip();
113
+ $response = $this->client->getIo()->makeRequest($request);
114
+ if ($response->getResponseHttpCode() == 200) {
115
+ $this->setAccessToken($response->getResponseBody());
116
+ $this->token['created'] = time();
117
+ return $this->getAccessToken();
118
+ } else {
119
+ $decodedResponse = json_decode($response->getResponseBody(), true);
120
+ if ($decodedResponse != null && $decodedResponse['error']) {
121
+ $errorText = $decodedResponse['error'];
122
+ if (isset($decodedResponse['error_description'])) {
123
+ $errorText .= ": " . $decodedResponse['error_description'];
124
+ }
125
+ }
126
+ throw new Google_Auth_Exception(sprintf("Error fetching OAuth2 access token, message: '%s'", $errorText), $response->getResponseHttpCode());
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Create a URL to obtain user authorization.
132
+ * The authorization endpoint allows the user to first
133
+ * authenticate, and then grant/deny the access request.
134
+ *
135
+ * @param string $scope
136
+ * The scope is expressed as a list of space-delimited strings.
137
+ * @return string
138
+ */
139
+ public function createAuthUrl($scope)
140
+ {
141
+ $params = array(
142
+ 'response_type' => 'code',
143
+ 'redirect_uri' => $this->client->getClassConfig($this, 'redirect_uri'),
144
+ 'client_id' => $this->client->getClassConfig($this, 'client_id'),
145
+ 'scope' => $scope,
146
+ 'access_type' => $this->client->getClassConfig($this, 'access_type')
147
+ );
148
+ // Prefer prompt to approval prompt.
149
+ if ($this->client->getClassConfig($this, 'prompt')) {
150
+ $params = $this->maybeAddParam($params, 'prompt');
151
+ } else {
152
+ $params = $this->maybeAddParam($params, 'approval_prompt');
153
+ }
154
+ $params = $this->maybeAddParam($params, 'login_hint');
155
+ $params = $this->maybeAddParam($params, 'hd');
156
+ $params = $this->maybeAddParam($params, 'openid.realm');
157
+ $params = $this->maybeAddParam($params, 'include_granted_scopes');
158
+ // If the list of scopes contains plus.login, add request_visible_actions
159
+ // to auth URL.
160
+ $rva = $this->client->getClassConfig($this, 'request_visible_actions');
161
+ if (strpos($scope, 'plus.login') && strlen($rva) > 0) {
162
+ $params['request_visible_actions'] = $rva;
163
+ }
164
+ if (isset($this->state)) {
165
+ $params['state'] = $this->state;
166
+ }
167
+ return self::OAUTH2_AUTH_URL . "?" . http_build_query($params, '', '&');
168
+ }
169
+
170
+ /**
171
+ *
172
+ * @param string $token
173
+ * @throws Google_Auth_Exception
174
+ */
175
+ public function setAccessToken($token)
176
+ {
177
+ $token = json_decode($token, true);
178
+ if ($token == null) {
179
+ throw new Google_Auth_Exception('Could not json decode the token');
180
+ }
181
+ if (! isset($token['access_token'])) {
182
+ throw new Google_Auth_Exception("Invalid token format");
183
+ }
184
+ $this->token = $token;
185
+ }
186
+
187
+ public function getAccessToken()
188
+ {
189
+ return json_encode($this->token);
190
+ }
191
+
192
+ public function getRefreshToken()
193
+ {
194
+ if (array_key_exists('refresh_token', $this->token)) {
195
+ return $this->token['refresh_token'];
196
+ } else {
197
+ return null;
198
+ }
199
+ }
200
+
201
+ public function setState($state)
202
+ {
203
+ $this->state = $state;
204
+ }
205
+
206
+ public function setAssertionCredentials(Google_Auth_AssertionCredentials $creds)
207
+ {
208
+ $this->assertionCredentials = $creds;
209
+ }
210
+
211
+ /**
212
+ * Include an accessToken in a given apiHttpRequest.
213
+ *
214
+ * @param Google_Http_Request $request
215
+ * @return Google_Http_Request
216
+ * @throws Google_Auth_Exception
217
+ */
218
+ public function sign(Google_Http_Request $request)
219
+ {
220
+ // add the developer key to the request before signing it
221
+ if ($this->client->getClassConfig($this, 'developer_key')) {
222
+ $request->setQueryParam('key', $this->client->getClassConfig($this, 'developer_key'));
223
+ }
224
+ // Cannot sign the request without an OAuth access token.
225
+ if (null == $this->token && null == $this->assertionCredentials) {
226
+ return $request;
227
+ }
228
+ // Check if the token is set to expire in the next 30 seconds
229
+ // (or has already expired).
230
+ if ($this->isAccessTokenExpired()) {
231
+ if ($this->assertionCredentials) {
232
+ $this->refreshTokenWithAssertion();
233
+ } else {
234
+ $this->client->getLogger()->debug('OAuth2 access token expired');
235
+ if (! array_key_exists('refresh_token', $this->token)) {
236
+ $error = "The OAuth 2.0 access token has expired," . " and a refresh token is not available. Refresh tokens" . " are not returned for responses that were auto-approved.";
237
+ $this->client->getLogger()->error($error);
238
+ throw new Google_Auth_Exception($error);
239
+ }
240
+ $this->refreshToken($this->token['refresh_token']);
241
+ }
242
+ }
243
+ $this->client->getLogger()->debug('OAuth2 authentication');
244
+ // Add the OAuth2 header to the request
245
+ $request->setRequestHeaders(array(
246
+ 'Authorization' => 'Bearer ' . $this->token['access_token']
247
+ ));
248
+ return $request;
249
+ }
250
+
251
+ /**
252
+ * Fetches a fresh access token with the given refresh token.
253
+ *
254
+ * @param string $refreshToken
255
+ * @return void
256
+ */
257
+ public function refreshToken($refreshToken)
258
+ {
259
+ $this->refreshTokenRequest(array(
260
+ 'client_id' => $this->client->getClassConfig($this, 'client_id'),
261
+ 'client_secret' => $this->client->getClassConfig($this, 'client_secret'),
262
+ 'refresh_token' => $refreshToken,
263
+ 'grant_type' => 'refresh_token'
264
+ ));
265
+ }
266
+
267
+ /**
268
+ * Fetches a fresh access token with a given assertion token.
269
+ *
270
+ * @param Google_Auth_AssertionCredentials $assertionCredentials
271
+ * optional.
272
+ * @return void
273
+ */
274
+ public function refreshTokenWithAssertion($assertionCredentials = null)
275
+ {
276
+ if (! $assertionCredentials) {
277
+ $assertionCredentials = $this->assertionCredentials;
278
+ }
279
+ $cacheKey = $assertionCredentials->getCacheKey();
280
+ if ($cacheKey) {
281
+ // We can check whether we have a token available in the
282
+ // cache. If it is expired, we can retrieve a new one from
283
+ // the assertion.
284
+ $token = $this->client->getCache()->get($cacheKey);
285
+ if ($token) {
286
+ $this->setAccessToken($token);
287
+ }
288
+ if (! $this->isAccessTokenExpired()) {
289
+ return;
290
+ }
291
+ }
292
+ $this->client->getLogger()->debug('OAuth2 access token expired');
293
+ $this->refreshTokenRequest(array(
294
+ 'grant_type' => 'assertion',
295
+ 'assertion_type' => $assertionCredentials->assertionType,
296
+ 'assertion' => $assertionCredentials->generateAssertion()
297
+ ));
298
+ if ($cacheKey) {
299
+ // Attempt to cache the token.
300
+ $this->client->getCache()->set($cacheKey, $this->getAccessToken());
301
+ }
302
+ }
303
+
304
+ private function refreshTokenRequest($params)
305
+ {
306
+ if (isset($params['assertion'])) {
307
+ $this->client->getLogger()->info('OAuth2 access token refresh with Signed JWT assertion grants.');
308
+ } else {
309
+ $this->client->getLogger()->info('OAuth2 access token refresh');
310
+ }
311
+ $http = new Google_Http_Request(self::OAUTH2_TOKEN_URI, 'POST', array(), $params);
312
+ $http->disableGzip();
313
+ $request = $this->client->getIo()->makeRequest($http);
314
+ $code = $request->getResponseHttpCode();
315
+ $body = $request->getResponseBody();
316
+ if (200 == $code) {
317
+ $token = json_decode($body, true);
318
+ if ($token == null) {
319
+ throw new Google_Auth_Exception("Could not json decode the access token");
320
+ }
321
+ if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
322
+ throw new Google_Auth_Exception("Invalid token format");
323
+ }
324
+ if (isset($token['id_token'])) {
325
+ $this->token['id_token'] = $token['id_token'];
326
+ }
327
+ $this->token['access_token'] = $token['access_token'];
328
+ $this->token['expires_in'] = $token['expires_in'];
329
+ $this->token['created'] = time();
330
+ } else {
331
+ throw new Google_Auth_Exception("Error refreshing the OAuth2 token, message: '$body'", $code);
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Revoke an OAuth2 access token or refresh token.
337
+ * This method will revoke the current access
338
+ * token, if a token isn't provided.
339
+ *
340
+ * @throws Google_Auth_Exception
341
+ * @param string|null $token
342
+ * The token (access token or a refresh token) that should be revoked.
343
+ * @return boolean Returns True if the revocation was successful, otherwise False.
344
+ */
345
+ public function revokeToken($token = null)
346
+ {
347
+ if (! $token) {
348
+ if (! $this->token) {
349
+ // Not initialized, no token to actually revoke
350
+ return false;
351
+ } elseif (array_key_exists('refresh_token', $this->token)) {
352
+ $token = $this->token['refresh_token'];
353
+ } else {
354
+ $token = $this->token['access_token'];
355
+ }
356
+ }
357
+ $request = new Google_Http_Request(self::OAUTH2_REVOKE_URI, 'POST', array(), "token=$token");
358
+ $request->disableGzip();
359
+ $response = $this->client->getIo()->makeRequest($request);
360
+ $code = $response->getResponseHttpCode();
361
+ if ($code == 200) {
362
+ $this->token = null;
363
+ return true;
364
+ }
365
+ return false;
366
+ }
367
+
368
+ /**
369
+ * Returns if the access_token is expired.
370
+ *
371
+ * @return bool Returns True if the access_token is expired.
372
+ */
373
+ public function isAccessTokenExpired()
374
+ {
375
+ if (! $this->token || ! isset($this->token['created'])) {
376
+ return true;
377
+ }
378
+ // If the token is set to expire in the next 30 seconds.
379
+ $expired = ($this->token['created'] + ($this->token['expires_in'] - 30)) < time();
380
+ return $expired;
381
+ }
382
+ // Gets federated sign-on certificates to use for verifying identity tokens.
383
+ // Returns certs as array structure, where keys are key ids, and values
384
+ // are PEM encoded certificates.
385
+ private function getFederatedSignOnCerts()
386
+ {
387
+ return $this->retrieveCertsFromLocation($this->client->getClassConfig($this, 'federated_signon_certs_url'));
388
+ }
389
+
390
+ /**
391
+ * Retrieve and cache a certificates file.
392
+ *
393
+ * @param $url string
394
+ * location
395
+ * @throws Google_Auth_Exception
396
+ * @return array certificates
397
+ */
398
+ public function retrieveCertsFromLocation($url)
399
+ {
400
+ // If we're retrieving a local file, just grab it.
401
+ if ("http" != substr($url, 0, 4)) {
402
+ $file = file_get_contents($url);
403
+ if ($file) {
404
+ return json_decode($file, true);
405
+ } else {
406
+ throw new Google_Auth_Exception("Failed to retrieve verification certificates: '" . $url . "'.");
407
+ }
408
+ }
409
+ // This relies on makeRequest caching certificate responses.
410
+ $request = $this->client->getIo()->makeRequest(new Google_Http_Request($url));
411
+ if ($request->getResponseHttpCode() == 200) {
412
+ $certs = json_decode($request->getResponseBody(), true);
413
+ if ($certs) {
414
+ return $certs;
415
+ }
416
+ }
417
+ throw new Google_Auth_Exception("Failed to retrieve verification certificates: '" . $request->getResponseBody() . "'.", $request->getResponseHttpCode());
418
+ }
419
+
420
+ /**
421
+ * Verifies an id token and returns the authenticated apiLoginTicket.
422
+ * Throws an exception if the id token is not valid.
423
+ * The audience parameter can be used to control which id tokens are
424
+ * accepted. By default, the id token must have been issued to this OAuth2 client.
425
+ *
426
+ * @param
427
+ * $id_token
428
+ * @param
429
+ * $audience
430
+ * @return Google_Auth_LoginTicket
431
+ */
432
+ public function verifyIdToken($id_token = null, $audience = null)
433
+ {
434
+ if (! $id_token) {
435
+ $id_token = $this->token['id_token'];
436
+ }
437
+ $certs = $this->getFederatedSignonCerts();
438
+ if (! $audience) {
439
+ $audience = $this->client->getClassConfig($this, 'client_id');
440
+ }
441
+ return $this->verifySignedJwtWithCerts($id_token, $certs, $audience, self::OAUTH2_ISSUER);
442
+ }
443
+
444
+ /**
445
+ * Verifies the id token, returns the verified token contents.
446
+ *
447
+ * @param $jwt string
448
+ * the token
449
+ * @param $certs array
450
+ * of certificates
451
+ * @param $required_audience string
452
+ * the expected consumer of the token
453
+ * @param
454
+ * [$issuer] the expected issues, defaults to Google
455
+ * @param
456
+ * [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS
457
+ * @throws Google_Auth_Exception
458
+ * @return mixed token information if valid, false if not
459
+ */
460
+ public function verifySignedJwtWithCerts($jwt, $certs, $required_audience, $issuer = null, $max_expiry = null)
461
+ {
462
+ if (! $max_expiry) {
463
+ // Set the maximum time we will accept a token for.
464
+ $max_expiry = self::MAX_TOKEN_LIFETIME_SECS;
465
+ }
466
+ $segments = explode(".", $jwt);
467
+ if (count($segments) != 3) {
468
+ throw new Google_Auth_Exception("Wrong number of segments in token: $jwt");
469
+ }
470
+ $signed = $segments[0] . "." . $segments[1];
471
+ $signature = Google_Utils::urlSafeB64Decode($segments[2]);
472
+ // Parse envelope.
473
+ $envelope = json_decode(Google_Utils::urlSafeB64Decode($segments[0]), true);
474
+ if (! $envelope) {
475
+ throw new Google_Auth_Exception("Can't parse token envelope: " . $segments[0]);
476
+ }
477
+ // Parse token
478
+ $json_body = Google_Utils::urlSafeB64Decode($segments[1]);
479
+ $payload = json_decode($json_body, true);
480
+ if (! $payload) {
481
+ throw new Google_Auth_Exception("Can't parse token payload: " . $segments[1]);
482
+ }
483
+ // Check signature
484
+ $verified = false;
485
+ foreach ($certs as $keyName => $pem) {
486
+ $public_key = new Google_Verifier_Pem($pem);
487
+ if ($public_key->verify($signed, $signature)) {
488
+ $verified = true;
489
+ break;
490
+ }
491
+ }
492
+ if (! $verified) {
493
+ throw new Google_Auth_Exception("Invalid token signature: $jwt");
494
+ }
495
+ // Check issued-at timestamp
496
+ $iat = 0;
497
+ if (array_key_exists("iat", $payload)) {
498
+ $iat = $payload["iat"];
499
+ }
500
+ if (! $iat) {
501
+ throw new Google_Auth_Exception("No issue time in token: $json_body");
502
+ }
503
+ $earliest = $iat - self::CLOCK_SKEW_SECS;
504
+ // Check expiration timestamp
505
+ $now = time();
506
+ $exp = 0;
507
+ if (array_key_exists("exp", $payload)) {
508
+ $exp = $payload["exp"];
509
+ }
510
+ if (! $exp) {
511
+ throw new Google_Auth_Exception("No expiration time in token: $json_body");
512
+ }
513
+ if ($exp >= $now + $max_expiry) {
514
+ throw new Google_Auth_Exception(sprintf("Expiration time too far in future: %s", $json_body));
515
+ }
516
+ $latest = $exp + self::CLOCK_SKEW_SECS;
517
+ if ($now < $earliest) {
518
+ throw new Google_Auth_Exception(sprintf("Token used too early, %s < %s: %s", $now, $earliest, $json_body));
519
+ }
520
+ if ($now > $latest) {
521
+ throw new Google_Auth_Exception(sprintf("Token used too late, %s > %s: %s", $now, $latest, $json_body));
522
+ }
523
+ $iss = $payload['iss'];
524
+ if ($issuer && $iss != $issuer) {
525
+ throw new Google_Auth_Exception(sprintf("Invalid issuer, %s != %s: %s", $iss, $issuer, $json_body));
526
+ }
527
+ // Check audience
528
+ $aud = $payload["aud"];
529
+ if ($aud != $required_audience) {
530
+ throw new Google_Auth_Exception(sprintf("Wrong recipient, %s != %s:", $aud, $required_audience, $json_body));
531
+ }
532
+ // All good.
533
+ return new Google_Auth_LoginTicket($envelope, $payload);
534
+ }
535
+
536
+ /**
537
+ * Add a parameter to the auth params if not empty string.
538
+ */
539
+ private function maybeAddParam($params, $name)
540
+ {
541
+ $param = $this->client->getClassConfig($this, $name);
542
+ if ($param != '') {
543
+ $params[$name] = $param;
544
+ }
545
+ return $params;
546
+ }
547
  }
tools/src/Google/Auth/Simple.php CHANGED
@@ -1,65 +1,65 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * Simple API access implementation.
21
- * Can either be used to make requests
22
- * completely unauthenticated, or by using a Simple API Access developer
23
- * key.
24
- *
25
- * @author Chris Chabot <chabotc@google.com>
26
- * @author Chirag Shah <chirags@google.com>
27
- */
28
- class Google_Auth_Simple extends Google_Auth_Abstract
29
- {
30
-
31
- private $key = null;
32
-
33
- private $client;
34
-
35
- public function __construct(Google_Client $client, $config = null)
36
- {
37
- $this->client = $client;
38
- }
39
-
40
- /**
41
- * Perform an authenticated / signed apiHttpRequest.
42
- * This function takes the apiHttpRequest, calls apiAuth->sign on it
43
- * (which can modify the request in what ever way fits the auth mechanism)
44
- * and then calls apiCurlIO::makeRequest on the signed request
45
- *
46
- * @param Google_Http_Request $request
47
- * @return Google_Http_Request The resulting HTTP response including the
48
- * responseHttpCode, responseHeaders and responseBody.
49
- */
50
- public function authenticatedRequest(Google_Http_Request $request)
51
- {
52
- $request = $this->sign($request);
53
- return $this->io->makeRequest($request);
54
- }
55
-
56
- public function sign(Google_Http_Request $request)
57
- {
58
- $key = $this->client->getClassConfig($this, 'developer_key');
59
- if ($key) {
60
- $this->client->getLogger()->debug('Simple API Access developer key authentication');
61
- $request->setQueryParam('key', $key);
62
- }
63
- return $request;
64
- }
65
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * Simple API access implementation.
21
+ * Can either be used to make requests
22
+ * completely unauthenticated, or by using a Simple API Access developer
23
+ * key.
24
+ *
25
+ * @author Chris Chabot <chabotc@google.com>
26
+ * @author Chirag Shah <chirags@google.com>
27
+ */
28
+ class Google_Auth_Simple extends Google_Auth_Abstract
29
+ {
30
+
31
+ private $key = null;
32
+
33
+ private $client;
34
+
35
+ public function __construct(Google_Client $client, $config = null)
36
+ {
37
+ $this->client = $client;
38
+ }
39
+
40
+ /**
41
+ * Perform an authenticated / signed apiHttpRequest.
42
+ * This function takes the apiHttpRequest, calls apiAuth->sign on it
43
+ * (which can modify the request in what ever way fits the auth mechanism)
44
+ * and then calls apiCurlIO::makeRequest on the signed request
45
+ *
46
+ * @param Google_Http_Request $request
47
+ * @return Google_Http_Request The resulting HTTP response including the
48
+ * responseHttpCode, responseHeaders and responseBody.
49
+ */
50
+ public function authenticatedRequest(Google_Http_Request $request)
51
+ {
52
+ $request = $this->sign($request);
53
+ return $this->io->makeRequest($request);
54
+ }
55
+
56
+ public function sign(Google_Http_Request $request)
57
+ {
58
+ $key = $this->client->getClassConfig($this, 'developer_key');
59
+ if ($key) {
60
+ $this->client->getLogger()->debug('Simple API Access developer key authentication');
61
+ $request->setQueryParam('key', $key);
62
+ }
63
+ return $request;
64
+ }
65
  }
tools/src/Google/Cache/Abstract.php CHANGED
@@ -1,58 +1,58 @@
1
- <?php
2
-
3
- /*
4
- * Copyright 2008 Google Inc.
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */
18
- /**
19
- * Abstract storage class
20
- *
21
- * @author Chris Chabot <chabotc@google.com>
22
- */
23
- abstract class Google_Cache_Abstract
24
- {
25
-
26
- abstract public function __construct(Google_Client $client);
27
-
28
- /**
29
- * Retrieves the data for the given key, or false if they
30
- * key is unknown or expired
31
- *
32
- * @param String $key
33
- * The key who's data to retrieve
34
- * @param boolean|int $expiration
35
- * Expiration time in seconds
36
- *
37
- */
38
- abstract public function get($key, $expiration = false);
39
-
40
- /**
41
- * Store the key => $value set.
42
- * The $value is serialized
43
- * by this function so can be of any type
44
- *
45
- * @param string $key
46
- * Key of the data
47
- * @param string $value
48
- * data
49
- */
50
- abstract public function set($key, $value);
51
-
52
- /**
53
- * Removes the key/data pair for the given $key
54
- *
55
- * @param String $key
56
- */
57
- abstract public function delete($key);
58
  }
1
+ <?php
2
+
3
+ /*
4
+ * Copyright 2008 Google Inc.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ /**
19
+ * Abstract storage class
20
+ *
21
+ * @author Chris Chabot <chabotc@google.com>
22
+ */
23
+ abstract class Google_Cache_Abstract
24
+ {
25
+
26
+ abstract public function __construct(Google_Client $client);
27
+
28
+ /**
29
+ * Retrieves the data for the given key, or false if they
30
+ * key is unknown or expired
31
+ *
32
+ * @param String $key
33
+ * The key who's data to retrieve
34
+ * @param boolean|int $expiration
35
+ * Expiration time in seconds
36
+ *
37
+ */
38
+ abstract public function get($key, $expiration = false);
39
+
40
+ /**
41
+ * Store the key => $value set.
42
+ * The $value is serialized
43
+ * by this function so can be of any type
44
+ *
45
+ * @param string $key
46
+ * Key of the data
47
+ * @param string $value
48
+ * data
49
+ */
50
+ abstract public function set($key, $value);
51
+
52
+ /**
53
+ * Removes the key/data pair for the given $key
54
+ *
55
+ * @param String $key
56
+ */
57
+ abstract public function delete($key);
58
  }
tools/src/Google/Cache/Apc.php CHANGED
@@ -1,108 +1,108 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * A persistent storage class based on the APC cache, which is not
21
- * really very persistent, as soon as you restart your web server
22
- * the storage will be wiped, however for debugging and/or speed
23
- * it can be useful, and cache is a lot cheaper then storage.
24
- *
25
- * @author Chris Chabot <chabotc@google.com>
26
- */
27
- class Google_Cache_Apc extends Google_Cache_Abstract
28
- {
29
-
30
- /**
31
- *
32
- * @var Google_Client the current client
33
- */
34
- private $client;
35
-
36
- public function __construct(Google_Client $client)
37
- {
38
- if (! function_exists('apc_add')) {
39
- $error = "Apc functions not available";
40
- $client->getLogger()->error($error);
41
- throw new Google_Cache_Exception($error);
42
- }
43
- $this->client = $client;
44
- }
45
-
46
- /**
47
- * @inheritDoc
48
- */
49
- public function get($key, $expiration = false)
50
- {
51
- $ret = apc_fetch($key);
52
- if ($ret === false) {
53
- $this->client->getLogger()->debug('APC cache miss', array(
54
- 'key' => $key
55
- ));
56
- return false;
57
- }
58
- if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
59
- $this->client->getLogger()->debug('APC cache miss (expired)', array(
60
- 'key' => $key,
61
- 'var' => $ret
62
- ));
63
- $this->delete($key);
64
- return false;
65
- }
66
- $this->client->getLogger()->debug('APC cache hit', array(
67
- 'key' => $key,
68
- 'var' => $ret
69
- ));
70
- return $ret['data'];
71
- }
72
-
73
- /**
74
- * @inheritDoc
75
- */
76
- public function set($key, $value)
77
- {
78
- $var = array(
79
- 'time' => time(),
80
- 'data' => $value
81
- );
82
- $rc = apc_store($key, $var);
83
- if ($rc == false) {
84
- $this->client->getLogger()->error('APC cache set failed', array(
85
- 'key' => $key,
86
- 'var' => $var
87
- ));
88
- throw new Google_Cache_Exception("Couldn't store data");
89
- }
90
- $this->client->getLogger()->debug('APC cache set', array(
91
- 'key' => $key,
92
- 'var' => $var
93
- ));
94
- }
95
-
96
- /**
97
- * @inheritDoc
98
- *
99
- * @param String $key
100
- */
101
- public function delete($key)
102
- {
103
- $this->client->getLogger()->debug('APC cache delete', array(
104
- 'key' => $key
105
- ));
106
- apc_delete($key);
107
- }
108
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * A persistent storage class based on the APC cache, which is not
21
+ * really very persistent, as soon as you restart your web server
22
+ * the storage will be wiped, however for debugging and/or speed
23
+ * it can be useful, and cache is a lot cheaper then storage.
24
+ *
25
+ * @author Chris Chabot <chabotc@google.com>
26
+ */
27
+ class Google_Cache_Apc extends Google_Cache_Abstract
28
+ {
29
+
30
+ /**
31
+ *
32
+ * @var Google_Client the current client
33
+ */
34
+ private $client;
35
+
36
+ public function __construct(Google_Client $client)
37
+ {
38
+ if (! function_exists('apc_add')) {
39
+ $error = "Apc functions not available";
40
+ $client->getLogger()->error($error);
41
+ throw new Google_Cache_Exception($error);
42
+ }
43
+ $this->client = $client;
44
+ }
45
+
46
+ /**
47
+ * @inheritDoc
48
+ */
49
+ public function get($key, $expiration = false)
50
+ {
51
+ $ret = apc_fetch($key);
52
+ if ($ret === false) {
53
+ $this->client->getLogger()->debug('APC cache miss', array(
54
+ 'key' => $key
55
+ ));
56
+ return false;
57
+ }
58
+ if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
59
+ $this->client->getLogger()->debug('APC cache miss (expired)', array(
60
+ 'key' => $key,
61
+ 'var' => $ret
62
+ ));
63
+ $this->delete($key);
64
+ return false;
65
+ }
66
+ $this->client->getLogger()->debug('APC cache hit', array(
67
+ 'key' => $key,
68
+ 'var' => $ret
69
+ ));
70
+ return $ret['data'];
71
+ }
72
+
73
+ /**
74
+ * @inheritDoc
75
+ */
76
+ public function set($key, $value)
77
+ {
78
+ $var = array(
79
+ 'time' => time(),
80
+ 'data' => $value
81
+ );
82
+ $rc = apc_store($key, $var);
83
+ if ($rc == false) {
84
+ $this->client->getLogger()->error('APC cache set failed', array(
85
+ 'key' => $key,
86
+ 'var' => $var
87
+ ));
88
+ throw new Google_Cache_Exception("Couldn't store data");
89
+ }
90
+ $this->client->getLogger()->debug('APC cache set', array(
91
+ 'key' => $key,
92
+ 'var' => $var
93
+ ));
94
+ }
95
+
96
+ /**
97
+ * @inheritDoc
98
+ *
99
+ * @param String $key
100
+ */
101
+ public function delete($key)
102
+ {
103
+ $this->client->getLogger()->debug('APC cache delete', array(
104
+ 'key' => $key
105
+ ));
106
+ apc_delete($key);
107
+ }
108
  }
tools/src/Google/Cache/Exception.php CHANGED
@@ -1,21 +1,21 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- class Google_Cache_Exception extends Google_Exception
20
- {
21
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ class Google_Cache_Exception extends Google_Exception
20
+ {
21
  }
tools/src/Google/Cache/File.php CHANGED
@@ -1,186 +1,186 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /*
20
- * This class implements a basic on disk storage. While that does
21
- * work quite well it's not the most elegant and scalable solution.
22
- * It will also get you into a heap of trouble when you try to run
23
- * this in a clustered environment.
24
- *
25
- * @author Chris Chabot <chabotc@google.com>
26
- */
27
- class Google_Cache_File extends Google_Cache_Abstract
28
- {
29
-
30
- const MAX_LOCK_RETRIES = 10;
31
-
32
- private $path;
33
-
34
- private $fh;
35
-
36
- /**
37
- *
38
- * @var Google_Client the current client
39
- */
40
- private $client;
41
-
42
- public function __construct(Google_Client $client)
43
- {
44
- $this->client = $client;
45
- $this->path = $this->client->getClassConfig($this, 'directory');
46
- }
47
-
48
- public function get($key, $expiration = false)
49
- {
50
- $storageFile = $this->getCacheFile($key);
51
- $data = false;
52
- if (! file_exists($storageFile)) {
53
- $this->client->getLogger()->debug('File cache miss', array(
54
- 'key' => $key,
55
- 'file' => $storageFile
56
- ));
57
- return false;
58
- }
59
- if ($expiration) {
60
- $mtime = filemtime($storageFile);
61
- if ((time() - $mtime) >= $expiration) {
62
- $this->client->getLogger()->debug('File cache miss (expired)', array(
63
- 'key' => $key,
64
- 'file' => $storageFile
65
- ));
66
- $this->delete($key);
67
- return false;
68
- }
69
- }
70
- if ($this->acquireReadLock($storageFile)) {
71
- $data = fread($this->fh, filesize($storageFile));
72
- $data = unserialize($data);
73
- $this->unlock($storageFile);
74
- }
75
- $this->client->getLogger()->debug('File cache hit', array(
76
- 'key' => $key,
77
- 'file' => $storageFile,
78
- 'var' => $data
79
- ));
80
- return $data;
81
- }
82
-
83
- public function set($key, $value)
84
- {
85
- $storageFile = $this->getWriteableCacheFile($key);
86
- if ($this->acquireWriteLock($storageFile)) {
87
- // We serialize the whole request object, since we don't only want the
88
- // responseContent but also the postBody used, headers, size, etc.
89
- $data = serialize($value);
90
- $result = fwrite($this->fh, $data);
91
- $this->unlock($storageFile);
92
- $this->client->getLogger()->debug('File cache set', array(
93
- 'key' => $key,
94
- 'file' => $storageFile,
95
- 'var' => $value
96
- ));
97
- } else {
98
- $this->client->getLogger()->notice('File cache set failed', array(
99
- 'key' => $key,
100
- 'file' => $storageFile
101
- ));
102
- }
103
- }
104
-
105
- public function delete($key)
106
- {
107
- $file = $this->getCacheFile($key);
108
- if (file_exists($file) && ! unlink($file)) {
109
- $this->client->getLogger()->error('File cache delete failed', array(
110
- 'key' => $key,
111
- 'file' => $file
112
- ));
113
- throw new Google_Cache_Exception("Cache file could not be deleted");
114
- }
115
- $this->client->getLogger()->debug('File cache delete', array(
116
- 'key' => $key,
117
- 'file' => $file
118
- ));
119
- }
120
-
121
- private function getWriteableCacheFile($file)
122
- {
123
- return $this->getCacheFile($file, true);
124
- }
125
-
126
- private function getCacheFile($file, $forWrite = false)
127
- {
128
- return $this->getCacheDir($file, $forWrite) . '/' . md5($file);
129
- }
130
-
131
- private function getCacheDir($file, $forWrite)
132
- {
133
- // use the first 2 characters of the hash as a directory prefix
134
- // this should prevent slowdowns due to huge directory listings
135
- // and thus give some basic amount of scalability
136
- $storageDir = $this->path . '/' . substr(md5($file), 0, 2);
137
- if ($forWrite && ! is_dir($storageDir)) {
138
- if (! mkdir($storageDir, 0755, true)) {
139
- $this->client->getLogger()->error('File cache creation failed', array(
140
- 'dir' => $storageDir
141
- ));
142
- throw new Google_Cache_Exception("Could not create storage directory: $storageDir");
143
- }
144
- }
145
- return $storageDir;
146
- }
147
-
148
- private function acquireReadLock($storageFile)
149
- {
150
- return $this->acquireLock(LOCK_SH, $storageFile);
151
- }
152
-
153
- private function acquireWriteLock($storageFile)
154
- {
155
- $rc = $this->acquireLock(LOCK_EX, $storageFile);
156
- if (! $rc) {
157
- $this->client->getLogger()->notice('File cache write lock failed', array(
158
- 'file' => $storageFile
159
- ));
160
- $this->delete($storageFile);
161
- }
162
- return $rc;
163
- }
164
-
165
- private function acquireLock($type, $storageFile)
166
- {
167
- $mode = $type == LOCK_EX ? "w" : "r";
168
- $this->fh = fopen($storageFile, $mode);
169
- $count = 0;
170
- while (! flock($this->fh, $type | LOCK_NB)) {
171
- // Sleep for 10ms.
172
- usleep(10000);
173
- if (++ $count < self::MAX_LOCK_RETRIES) {
174
- return false;
175
- }
176
- }
177
- return true;
178
- }
179
-
180
- public function unlock($storageFile)
181
- {
182
- if ($this->fh) {
183
- flock($this->fh, LOCK_UN);
184
- }
185
- }
186
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2008 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /*
20
+ * This class implements a basic on disk storage. While that does
21
+ * work quite well it's not the most elegant and scalable solution.
22
+ * It will also get you into a heap of trouble when you try to run
23
+ * this in a clustered environment.
24
+ *
25
+ * @author Chris Chabot <chabotc@google.com>
26
+ */
27
+ class Google_Cache_File extends Google_Cache_Abstract
28
+ {
29
+
30
+ const MAX_LOCK_RETRIES = 10;
31
+
32
+ private $path;
33
+
34
+ private $fh;
35
+
36
+ /**
37
+ *
38
+ * @var Google_Client the current client
39
+ */
40
+ private $client;
41
+
42
+ public function __construct(Google_Client $client)
43
+ {
44
+ $this->client = $client;
45
+ $this->path = $this->client->getClassConfig($this, 'directory');
46
+ }
47
+
48
+ public function get($key, $expiration = false)
49
+ {
50
+ $storageFile = $this->getCacheFile($key);
51
+ $data = false;
52
+ if (! file_exists($storageFile)) {
53
+ $this->client->getLogger()->debug('File cache miss', array(
54
+ 'key' => $key,
55
+ 'file' => $storageFile
56
+ ));
57
+ return false;
58
+ }
59
+ if ($expiration) {
60
+ $mtime = filemtime($storageFile);
61
+ if ((time() - $mtime) >= $expiration) {
62
+ $this->client->getLogger()->debug('File cache miss (expired)', array(
63
+ 'key' => $key,
64
+ 'file' => $storageFile
65
+ ));
66
+ $this->delete($key);
67
+ return false;
68
+ }
69
+ }
70
+ if ($this->acquireReadLock($storageFile)) {
71
+ $data = fread($this->fh, filesize($storageFile));
72
+ $data = unserialize($data);
73
+ $this->unlock($storageFile);
74
+ }
75
+ $this->client->getLogger()->debug('File cache hit', array(
76
+ 'key' => $key,
77
+ 'file' => $storageFile,
78
+ 'var' => $data
79
+ ));
80
+ return $data;
81
+ }
82
+
83
+ public function set($key, $value)
84
+ {
85
+ $storageFile = $this->getWriteableCacheFile($key);
86
+ if ($this->acquireWriteLock($storageFile)) {
87
+ // We serialize the whole request object, since we don't only want the
88
+ // responseContent but also the postBody used, headers, size, etc.
89
+ $data = serialize($value);
90
+ $result = fwrite($this->fh, $data);
91
+ $this->unlock($storageFile);
92
+ $this->client->getLogger()->debug('File cache set', array(
93
+ 'key' => $key,
94
+ 'file' => $storageFile,
95
+ 'var' => $value
96
+ ));
97
+ } else {
98
+ $this->client->getLogger()->notice('File cache set failed', array(
99
+ 'key' => $key,
100
+ 'file' => $storageFile
101
+ ));
102
+ }
103
+ }
104
+
105
+ public function delete($key)
106
+ {
107
+ $file = $this->getCacheFile($key);
108
+ if (file_exists($file) && ! unlink($file)) {
109
+ $this->client->getLogger()->error('File cache delete failed', array(
110
+ 'key' => $key,
111
+ 'file' => $file
112
+ ));
113
+ throw new Google_Cache_Exception("Cache file could not be deleted");
114
+ }
115
+ $this->client->getLogger()->debug('File cache delete', array(
116
+ 'key' => $key,
117
+ 'file' => $file
118
+ ));
119
+ }
120
+
121
+ private function getWriteableCacheFile($file)
122
+ {
123
+ return $this->getCacheFile($file, true);
124
+ }
125
+
126
+ private function getCacheFile($file, $forWrite = false)
127
+ {
128
+ return $this->getCacheDir($file, $forWrite) . '/' . md5($file);
129
+ }
130
+
131
+ private function getCacheDir($file, $forWrite)
132
+ {
133
+ // use the first 2 characters of the hash as a directory prefix
134
+ // this should prevent slowdowns due to huge directory listings
135
+ // and thus give some basic amount of scalability
136
+ $storageDir = $this->path . '/' . substr(md5($file), 0, 2);
137
+ if ($forWrite && ! is_dir($storageDir)) {
138
+ if (! mkdir($storageDir, 0755, true)) {
139
+ $this->client->getLogger()->error('File cache creation failed', array(
140
+ 'dir' => $storageDir
141
+ ));
142
+ throw new Google_Cache_Exception("Could not create storage directory: $storageDir");
143
+ }
144
+ }
145
+ return $storageDir;
146
+ }
147
+
148
+ private function acquireReadLock($storageFile)
149
+ {
150
+ return $this->acquireLock(LOCK_SH, $storageFile);
151
+ }
152
+
153
+ private function acquireWriteLock($storageFile)
154
+ {
155
+ $rc = $this->acquireLock(LOCK_EX, $storageFile);
156
+ if (! $rc) {
157
+ $this->client->getLogger()->notice('File cache write lock failed', array(
158
+ 'file' => $storageFile
159
+ ));
160
+ $this->delete($storageFile);
161
+ }
162
+ return $rc;
163
+ }
164
+
165
+ private function acquireLock($type, $storageFile)
166
+ {
167
+ $mode = $type == LOCK_EX ? "w" : "r";
168
+ $this->fh = fopen($storageFile, $mode);
169
+ $count = 0;
170
+ while (! flock($this->fh, $type | LOCK_NB)) {
171
+ // Sleep for 10ms.
172
+ usleep(10000);
173
+ if (++ $count < self::MAX_LOCK_RETRIES) {
174
+ return false;
175
+ }
176
+ }
177
+ return true;
178
+ }
179
+
180
+ public function unlock($storageFile)
181
+ {
182
+ if ($this->fh) {
183
+ flock($this->fh, LOCK_UN);
184
+ }
185
+ }
186
  }
tools/src/Google/Cache/Memcache.php CHANGED
@@ -1,178 +1,178 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * A persistent storage class based on the memcache, which is not
21
- * really very persistent, as soon as you restart your memcache daemon
22
- * the storage will be wiped.
23
- *
24
- * Will use either the memcache or memcached extensions, preferring
25
- * memcached.
26
- *
27
- * @author Chris Chabot <chabotc@google.com>
28
- */
29
- class Google_Cache_Memcache extends Google_Cache_Abstract
30
- {
31
-
32
- private $connection = false;
33
-
34
- private $mc = false;
35
-
36
- private $host;
37
-
38
- private $port;
39
-
40
- /**
41
- *
42
- * @var Google_Client the current client
43
- */
44
- private $client;
45
-
46
- public function __construct(Google_Client $client)
47
- {
48
- if (! function_exists('memcache_connect') && ! class_exists("Memcached")) {
49
- $error = "Memcache functions not available";
50
- $client->getLogger()->error($error);
51
- throw new Google_Cache_Exception($error);
52
- }
53
- $this->client = $client;
54
- if ($client->isAppEngine()) {
55
- // No credentials needed for GAE.
56
- $this->mc = new Memcached();
57
- $this->connection = true;
58
- } else {
59
- $this->host = $client->getClassConfig($this, 'host');
60
- $this->port = $client->getClassConfig($this, 'port');
61
- if (empty($this->host) || (empty($this->port) && (string) $this->port != "0")) {
62
- $error = "You need to supply a valid memcache host and port";
63
- $client->getLogger()->error($error);
64
- throw new Google_Cache_Exception($error);
65
- }
66
- }
67
- }
68
-
69
- /**
70
- * @inheritDoc
71
- */
72
- public function get($key, $expiration = false)
73
- {
74
- $this->connect();
75
- $ret = false;
76
- if ($this->mc) {
77
- $ret = $this->mc->get($key);
78
- } else {
79
- $ret = memcache_get($this->connection, $key);
80
- }
81
- if ($ret === false) {
82
- $this->client->getLogger()->debug('Memcache cache miss', array(
83
- 'key' => $key
84
- ));
85
- return false;
86
- }
87
- if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
88
- $this->client->getLogger()->debug('Memcache cache miss (expired)', array(
89
- 'key' => $key,
90
- 'var' => $ret
91
- ));
92
- $this->delete($key);
93
- return false;
94
- }
95
- $this->client->getLogger()->debug('Memcache cache hit', array(
96
- 'key' => $key,
97
- 'var' => $ret
98
- ));
99
- return $ret['data'];
100
- }
101
-
102
- /**
103
- * @inheritDoc
104
- *
105
- * @param string $key
106
- * @param string $value
107
- * @throws Google_Cache_Exception
108
- */
109
- public function set($key, $value)
110
- {
111
- $this->connect();
112
- // we store it with the cache_time default expiration so objects will at
113
- // least get cleaned eventually.
114
- $data = array(
115
- 'time' => time(),
116
- 'data' => $value
117
- );
118
- $rc = false;
119
- if ($this->mc) {
120
- $rc = $this->mc->set($key, $data);
121
- } else {
122
- $rc = memcache_set($this->connection, $key, $data, false);
123
- }
124
- if ($rc == false) {
125
- $this->client->getLogger()->error('Memcache cache set failed', array(
126
- 'key' => $key,
127
- 'var' => $data
128
- ));
129
- throw new Google_Cache_Exception("Couldn't store data in cache");
130
- }
131
- $this->client->getLogger()->debug('Memcache cache set', array(
132
- 'key' => $key,
133
- 'var' => $data
134
- ));
135
- }
136
-
137
- /**
138
- * @inheritDoc
139
- *
140
- * @param String $key
141
- */
142
- public function delete($key)
143
- {
144
- $this->connect();
145
- if ($this->mc) {
146
- $this->mc->delete($key, 0);
147
- } else {
148
- memcache_delete($this->connection, $key, 0);
149
- }
150
- $this->client->getLogger()->debug('Memcache cache delete', array(
151
- 'key' => $key
152
- ));
153
- }
154
-
155
- /**
156
- * Lazy initialiser for memcache connection.
157
- * Uses pconnect for to take
158
- * advantage of the persistence pool where possible.
159
- */
160
- private function connect()
161
- {
162
- if ($this->connection) {
163
- return;
164
- }
165
- if (class_exists("Memcached")) {
166
- $this->mc = new Memcached();
167
- $this->mc->addServer($this->host, $this->port);
168
- $this->connection = true;
169
- } else {
170
- $this->connection = memcache_pconnect($this->host, $this->port);
171
- }
172
- if (! $this->connection) {
173
- $error = "Couldn't connect to memcache server";
174
- $this->client->getLogger()->error($error);
175
- throw new Google_Cache_Exception($error);
176
- }
177
- }
178
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2008 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * A persistent storage class based on the memcache, which is not
21
+ * really very persistent, as soon as you restart your memcache daemon
22
+ * the storage will be wiped.
23
+ *
24
+ * Will use either the memcache or memcached extensions, preferring
25
+ * memcached.
26
+ *
27
+ * @author Chris Chabot <chabotc@google.com>
28
+ */
29
+ class Google_Cache_Memcache extends Google_Cache_Abstract
30
+ {
31
+
32
+ private $connection = false;
33
+
34
+ private $mc = false;
35
+
36
+ private $host;
37
+
38
+ private $port;
39
+
40
+ /**
41
+ *
42
+ * @var Google_Client the current client
43
+ */
44
+ private $client;
45
+
46
+ public function __construct(Google_Client $client)
47
+ {
48
+ if (! function_exists('memcache_connect') && ! class_exists("Memcached")) {
49
+ $error = "Memcache functions not available";
50
+ $client->getLogger()->error($error);
51
+ throw new Google_Cache_Exception($error);
52
+ }
53
+ $this->client = $client;
54
+ if ($client->isAppEngine()) {
55
+ // No credentials needed for GAE.
56
+ $this->mc = new Memcached();
57
+ $this->connection = true;
58
+ } else {
59
+ $this->host = $client->getClassConfig($this, 'host');
60
+ $this->port = $client->getClassConfig($this, 'port');
61
+ if (empty($this->host) || (empty($this->port) && (string) $this->port != "0")) {
62
+ $error = "You need to supply a valid memcache host and port";
63
+ $client->getLogger()->error($error);
64
+ throw new Google_Cache_Exception($error);
65
+ }
66
+ }
67
+ }
68
+
69
+ /**
70
+ * @inheritDoc
71
+ */
72
+ public function get($key, $expiration = false)
73
+ {
74
+ $this->connect();
75
+ $ret = false;
76
+ if ($this->mc) {
77
+ $ret = $this->mc->get($key);
78
+ } else {
79
+ $ret = memcache_get($this->connection, $key);
80
+ }
81
+ if ($ret === false) {
82
+ $this->client->getLogger()->debug('Memcache cache miss', array(
83
+ 'key' => $key
84
+ ));
85
+ return false;
86
+ }
87
+ if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
88
+ $this->client->getLogger()->debug('Memcache cache miss (expired)', array(
89
+ 'key' => $key,
90
+ 'var' => $ret
91
+ ));
92
+ $this->delete($key);
93
+ return false;
94
+ }
95
+ $this->client->getLogger()->debug('Memcache cache hit', array(
96
+ 'key' => $key,
97
+ 'var' => $ret
98
+ ));
99
+ return $ret['data'];
100
+ }
101
+
102
+ /**
103
+ * @inheritDoc
104
+ *
105
+ * @param string $key
106
+ * @param string $value
107
+ * @throws Google_Cache_Exception
108
+ */
109
+ public function set($key, $value)
110
+ {
111
+ $this->connect();
112
+ // we store it with the cache_time default expiration so objects will at
113
+ // least get cleaned eventually.
114
+ $data = array(
115
+ 'time' => time(),
116
+ 'data' => $value
117
+ );
118
+ $rc = false;
119
+ if ($this->mc) {
120
+ $rc = $this->mc->set($key, $data);
121
+ } else {
122
+ $rc = memcache_set($this->connection, $key, $data, false);
123
+ }
124
+ if ($rc == false) {
125
+ $this->client->getLogger()->error('Memcache cache set failed', array(
126
+ 'key' => $key,
127
+ 'var' => $data
128
+ ));
129
+ throw new Google_Cache_Exception("Couldn't store data in cache");
130
+ }
131
+ $this->client->getLogger()->debug('Memcache cache set', array(
132
+ 'key' => $key,
133
+ 'var' => $data
134
+ ));
135
+ }
136
+
137
+ /**
138
+ * @inheritDoc
139
+ *
140
+ * @param String $key
141
+ */
142
+ public function delete($key)
143
+ {
144
+ $this->connect();
145
+ if ($this->mc) {
146
+ $this->mc->delete($key, 0);
147
+ } else {
148
+ memcache_delete($this->connection, $key, 0);
149
+ }
150
+ $this->client->getLogger()->debug('Memcache cache delete', array(
151
+ 'key' => $key
152
+ ));
153
+ }
154
+
155
+ /**
156
+ * Lazy initialiser for memcache connection.
157
+ * Uses pconnect for to take
158
+ * advantage of the persistence pool where possible.
159
+ */
160
+ private function connect()
161
+ {
162
+ if ($this->connection) {
163
+ return;
164
+ }
165
+ if (class_exists("Memcached")) {
166
+ $this->mc = new Memcached();
167
+ $this->mc->addServer($this->host, $this->port);
168
+ $this->connection = true;
169
+ } else {
170
+ $this->connection = memcache_pconnect($this->host, $this->port);
171
+ }
172
+ if (! $this->connection) {
173
+ $error = "Couldn't connect to memcache server";
174
+ $this->client->getLogger()->error($error);
175
+ throw new Google_Cache_Exception($error);
176
+ }
177
+ }
178
  }
tools/src/Google/Cache/Null.php CHANGED
@@ -1,54 +1,54 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * A blank storage class, for cases where caching is not
21
- * required.
22
- */
23
- class Google_Cache_Null extends Google_Cache_Abstract
24
- {
25
-
26
- public function __construct(Google_Client $client)
27
- {}
28
-
29
- /**
30
- * @inheritDoc
31
- */
32
- public function get($key, $expiration = false)
33
- {
34
- return false;
35
- }
36
-
37
- /**
38
- * @inheritDoc
39
- */
40
- public function set($key, $value)
41
- {
42
- // Nop.
43
- }
44
-
45
- /**
46
- * @inheritDoc
47
- *
48
- * @param String $key
49
- */
50
- public function delete($key)
51
- {
52
- // Nop.
53
- }
54
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * A blank storage class, for cases where caching is not
21
+ * required.
22
+ */
23
+ class Google_Cache_Null extends Google_Cache_Abstract
24
+ {
25
+
26
+ public function __construct(Google_Client $client)
27
+ {}
28
+
29
+ /**
30
+ * @inheritDoc
31
+ */
32
+ public function get($key, $expiration = false)
33
+ {
34
+ return false;
35
+ }
36
+
37
+ /**
38
+ * @inheritDoc
39
+ */
40
+ public function set($key, $value)
41
+ {
42
+ // Nop.
43
+ }
44
+
45
+ /**
46
+ * @inheritDoc
47
+ *
48
+ * @param String $key
49
+ */
50
+ public function delete($key)
51
+ {
52
+ // Nop.
53
+ }
54
  }
tools/src/Google/Client.php CHANGED
@@ -1,761 +1,761 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../autoload.php');
18
-
19
- /**
20
- * The Google API Client
21
- * http://code.google.com/p/google-api-php-client/
22
- *
23
- * @author Chris Chabot <chabotc@google.com>
24
- * @author Chirag Shah <chirags@google.com>
25
- */
26
- class Google_Client
27
- {
28
-
29
- const LIBVER = "1.1.2";
30
-
31
- const USER_AGENT_SUFFIX = "google-api-php-client/";
32
-
33
- /**
34
- *
35
- * @var Google_Auth_Abstract $auth
36
- */
37
- private $auth;
38
-
39
- /**
40
- *
41
- * @var Google_IO_Abstract $io
42
- */
43
- private $io;
44
-
45
- /**
46
- *
47
- * @var Google_Cache_Abstract $cache
48
- */
49
- private $cache;
50
-
51
- /**
52
- *
53
- * @var Google_Config $config
54
- */
55
- private $config;
56
-
57
- /**
58
- *
59
- * @var Google_Logger_Abstract $logger
60
- */
61
- private $logger;
62
-
63
- /**
64
- *
65
- * @var boolean $deferExecution
66
- */
67
- private $deferExecution = false;
68
-
69
- /**
70
- *
71
- * @var array $scopes
72
- */
73
- // Scopes requested by the client
74
- protected $requestedScopes = array();
75
- // definitions of services that are discovered.
76
- protected $services = array();
77
- // Used to track authenticated state, can't discover services after doing authenticate()
78
- private $authenticated = false;
79
-
80
- /**
81
- * Construct the Google Client.
82
- *
83
- * @param $config Google_Config
84
- * or string for the ini file to load
85
- */
86
- public function __construct($config = null)
87
- {
88
- if (is_string($config) && strlen($config)) {
89
- $config = new Google_Config($config);
90
- } else
91
- if (! ($config instanceof Google_Config)) {
92
- $config = new Google_Config();
93
- if ($this->isAppEngine()) {
94
- // Automatically use Memcache if we're in AppEngine.
95
- $config->setCacheClass('Google_Cache_Memcache');
96
- }
97
- if (version_compare(phpversion(), "5.3.4", "<=") || $this->isAppEngine()) {
98
- // Automatically disable compress.zlib, as currently unsupported.
99
- $config->setClassConfig('Google_Http_Request', 'disable_gzip', true);
100
- }
101
- }
102
- if ($config->getIoClass() == Google_Config::USE_AUTO_IO_SELECTION) {
103
- if (function_exists('curl_version') && function_exists('curl_exec') && ! $this->isAppEngine()) {
104
- $config->setIoClass("Google_IO_Curl");
105
- } else {
106
- $config->setIoClass("Google_IO_Stream");
107
- }
108
- }
109
- $this->config = $config;
110
- }
111
-
112
- /**
113
- * Get a string containing the version of the library.
114
- *
115
- * @return string
116
- */
117
- public function getLibraryVersion()
118
- {
119
- return self::LIBVER;
120
- }
121
-
122
- /**
123
- * Attempt to exchange a code for an valid authentication token.
124
- * Helper wrapped around the OAuth 2.0 implementation.
125
- *
126
- * @param $code string
127
- * code from accounts.google.com
128
- * @return string token
129
- */
130
- public function authenticate($code)
131
- {
132
- $this->authenticated = true;
133
- return $this->getAuth()->authenticate($code);
134
- }
135
-
136
- /**
137
- * Set the auth config from the JSON string provided.
138
- * This structure should match the file downloaded from
139
- * the "Download JSON" button on in the Google Developer
140
- * Console.
141
- *
142
- * @param string $json
143
- * the configuration json
144
- * @throws Google_Exception
145
- */
146
- public function setAuthConfig($json)
147
- {
148
- $data = json_decode($json);
149
- $key = isset($data->installed) ? 'installed' : 'web';
150
- if (! isset($data->$key)) {
151
- throw new Google_Exception("Invalid client secret JSON file.");
152
- }
153
- $this->setClientId($data->$key->client_id);
154
- $this->setClientSecret($data->$key->client_secret);
155
- if (isset($data->$key->redirect_uris)) {
156
- $this->setRedirectUri($data->$key->redirect_uris[0]);
157
- }
158
- }
159
-
160
- /**
161
- * Set the auth config from the JSON file in the path
162
- * provided.
163
- * This should match the file downloaded from
164
- * the "Download JSON" button on in the Google Developer
165
- * Console.
166
- *
167
- * @param string $file
168
- * the file location of the client json
169
- */
170
- public function setAuthConfigFile($file)
171
- {
172
- $this->setAuthConfig(file_get_contents($file));
173
- }
174
-
175
- /**
176
- *
177
- * @throws Google_Auth_Exception
178
- * @return array @visible For Testing
179
- */
180
- public function prepareScopes()
181
- {
182
- if (empty($this->requestedScopes)) {
183
- throw new Google_Auth_Exception("No scopes specified");
184
- }
185
- $scopes = implode(' ', $this->requestedScopes);
186
- return $scopes;
187
- }
188
-
189
- /**
190
- * Set the OAuth 2.0 access token using the string that resulted from calling createAuthUrl()
191
- * or Google_Client#getAccessToken().
192
- *
193
- * @param string $accessToken
194
- * JSON encoded string containing in the following format:
195
- * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
196
- * "expires_in":3600, "id_token":"TOKEN", "created":1320790426}
197
- */
198
- public function setAccessToken($accessToken)
199
- {
200
- if ($accessToken == 'null') {
201
- $accessToken = null;
202
- }
203
- $this->getAuth()->setAccessToken($accessToken);
204
- }
205
-
206
- /**
207
- * Set the authenticator object
208
- *
209
- * @param Google_Auth_Abstract $auth
210
- */
211
- public function setAuth(Google_Auth_Abstract $auth)
212
- {
213
- $this->config->setAuthClass(get_class($auth));
214
- $this->auth = $auth;
215
- }
216
-
217
- /**
218
- * Set the IO object
219
- *
220
- * @param Google_IO_Abstract $io
221
- */
222
- public function setIo(Google_IO_Abstract $io)
223
- {
224
- $this->config->setIoClass(get_class($io));
225
- $this->io = $io;
226
- }
227
-
228
- /**
229
- * Set the Cache object
230
- *
231
- * @param Google_Cache_Abstract $cache
232
- */
233
- public function setCache(Google_Cache_Abstract $cache)
234
- {
235
- $this->config->setCacheClass(get_class($cache));
236
- $this->cache = $cache;
237
- }
238
-
239
- /**
240
- * Set the Logger object
241
- *
242
- * @param Google_Logger_Abstract $logger
243
- */
244
- public function setLogger(Google_Logger_Abstract $logger)
245
- {
246
- $this->config->setLoggerClass(get_class($logger));
247
- $this->logger = $logger;
248
- }
249
-
250
- /**
251
- * Construct the OAuth 2.0 authorization request URI.
252
- *
253
- * @return string
254
- */
255
- public function createAuthUrl()
256
- {
257
- $scopes = $this->prepareScopes();
258
- return $this->getAuth()->createAuthUrl($scopes);
259
- }
260
-
261
- /**
262
- * Get the OAuth 2.0 access token.
263
- *
264
- * @return string $accessToken JSON encoded string in the following format:
265
- * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
266
- * "expires_in":3600,"id_token":"TOKEN", "created":1320790426}
267
- */
268
- public function getAccessToken()
269
- {
270
- $token = $this->getAuth()->getAccessToken();
271
- // The response is json encoded, so could be the string null.
272
- // It is arguable whether this check should be here or lower
273
- // in the library.
274
- return (null == $token || 'null' == $token || '[]' == $token) ? null : $token;
275
- }
276
-
277
- /**
278
- * Get the OAuth 2.0 refresh token.
279
- *
280
- * @return string $refreshToken refresh token or null if not available
281
- */
282
- public function getRefreshToken()
283
- {
284
- return $this->getAuth()->getRefreshToken();
285
- }
286
-
287
- /**
288
- * Returns if the access_token is expired.
289
- *
290
- * @return bool Returns True if the access_token is expired.
291
- */
292
- public function isAccessTokenExpired()
293
- {
294
- return $this->getAuth()->isAccessTokenExpired();
295
- }
296
-
297
- /**
298
- * Set OAuth 2.0 "state" parameter to achieve per-request customization.
299
- *
300
- * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
301
- * @param string $state
302
- */
303
- public function setState($state)
304
- {
305
- $this->getAuth()->setState($state);
306
- }
307
-
308
- /**
309
- *
310
- * @param string $accessType
311
- * Possible values for access_type include:
312
- * {@code "offline"} to request offline access from the user.
313
- * {@code "online"} to request online access from the user.
314
- */
315
- public function setAccessType($accessType)
316
- {
317
- $this->config->setAccessType($accessType);
318
- }
319
-
320
- /**
321
- *
322
- * @param string $approvalPrompt
323
- * Possible values for approval_prompt include:
324
- * {@code "force"} to force the approval UI to appear. (This is the default value)
325
- * {@code "auto"} to request auto-approval when possible.
326
- */
327
- public function setApprovalPrompt($approvalPrompt)
328
- {
329
- $this->config->setApprovalPrompt($approvalPrompt);
330
- }
331
-
332
- /**
333
- * Set the login hint, email address or sub id.
334
- *
335
- * @param string $loginHint
336
- */
337
- public function setLoginHint($loginHint)
338
- {
339
- $this->config->setLoginHint($loginHint);
340
- }
341
-
342
- /**
343
- * Set the application name, this is included in the User-Agent HTTP header.
344
- *
345
- * @param string $applicationName
346
- */
347
- public function setApplicationName($applicationName)
348
- {
349
- $this->config->setApplicationName($applicationName);
350
- }
351
-
352
- /**
353
- * Set the OAuth 2.0 Client ID.
354
- *
355
- * @param string $clientId
356
- */
357
- public function setClientId($clientId)
358
- {
359
- $this->config->setClientId($clientId);
360
- }
361
-
362
- /**
363
- * Set the OAuth 2.0 Client Secret.
364
- *
365
- * @param string $clientSecret
366
- */
367
- public function setClientSecret($clientSecret)
368
- {
369
- $this->config->setClientSecret($clientSecret);
370
- }
371
-
372
- /**
373
- * Set the OAuth 2.0 Redirect URI.
374
- *
375
- * @param string $redirectUri
376
- */
377
- public function setRedirectUri($redirectUri)
378
- {
379
- $this->config->setRedirectUri($redirectUri);
380
- }
381
-
382
- /**
383
- * If 'plus.login' is included in the list of requested scopes, you can use
384
- * this method to define types of app activities that your app will write.
385
- * You can find a list of available types here:
386
- *
387
- * @link https://developers.google.com/+/api/moment-types
388
- *
389
- * @param array $requestVisibleActions
390
- * Array of app activity types
391
- */
392
- public function setRequestVisibleActions($requestVisibleActions)
393
- {
394
- if (is_array($requestVisibleActions)) {
395
- $requestVisibleActions = join(" ", $requestVisibleActions);
396
- }
397
- $this->config->setRequestVisibleActions($requestVisibleActions);
398
- }
399
-
400
- /**
401
- * Set the developer key to use, these are obtained through the API Console.
402
- *
403
- * @see http://code.google.com/apis/console-help/#generatingdevkeys
404
- * @param string $developerKey
405
- */
406
- public function setDeveloperKey($developerKey)
407
- {
408
- $this->config->setDeveloperKey($developerKey);
409
- }
410
-
411
- /**
412
- * Set the hd (hosted domain) parameter streamlines the login process for
413
- * Google Apps hosted accounts.
414
- * By including the domain of the user, you
415
- * restrict sign-in to accounts at that domain.
416
- *
417
- * @param $hd string
418
- * - the domain to use.
419
- */
420
- public function setHostedDomain($hd)
421
- {
422
- $this->config->setHostedDomain($hd);
423
- }
424
-
425
- /**
426
- * Set the prompt hint.
427
- * Valid values are none, consent and select_account.
428
- * If no value is specified and the user has not previously authorized
429
- * access, then the user is shown a consent screen.
430
- *
431
- * @param $prompt string
432
- */
433
- public function setPrompt($prompt)
434
- {
435
- $this->config->setPrompt($prompt);
436
- }
437
-
438
- /**
439
- * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
440
- * 2.0.
441
- * It is used in OpenID 2.0 requests to signify the URL-space for which
442
- * an authentication request is valid.
443
- *
444
- * @param $realm string
445
- * - the URL-space to use.
446
- */
447
- public function setOpenidRealm($realm)
448
- {
449
- $this->config->setOpenidRealm($realm);
450
- }
451
-
452
- /**
453
- * If this is provided with the value true, and the authorization request is
454
- * granted, the authorization will include any previous authorizations
455
- * granted to this user/application combination for other scopes.
456
- *
457
- * @param $include boolean
458
- * - the URL-space to use.
459
- */
460
- public function setIncludeGrantedScopes($include)
461
- {
462
- $this->config->setIncludeGrantedScopes($include);
463
- }
464
-
465
- /**
466
- * Fetches a fresh OAuth 2.0 access token with the given refresh token.
467
- *
468
- * @param string $refreshToken
469
- */
470
- public function refreshToken($refreshToken)
471
- {
472
- $this->getAuth()->refreshToken($refreshToken);
473
- }
474
-
475
- /**
476
- * Revoke an OAuth2 access token or refresh token.
477
- * This method will revoke the current access
478
- * token, if a token isn't provided.
479
- *
480
- * @throws Google_Auth_Exception
481
- * @param string|null $token
482
- * The token (access token or a refresh token) that should be revoked.
483
- * @return boolean Returns True if the revocation was successful, otherwise False.
484
- */
485
- public function revokeToken($token = null)
486
- {
487
- return $this->getAuth()->revokeToken($token);
488
- }
489
-
490
- /**
491
- * Verify an id_token.
492
- * This method will verify the current id_token, if one
493
- * isn't provided.
494
- *
495
- * @throws Google_Auth_Exception
496
- * @param string|null $token
497
- * The token (id_token) that should be verified.
498
- * @return Google_Auth_LoginTicket Returns an apiLoginTicket if the verification was
499
- * successful.
500
- */
501
- public function verifyIdToken($token = null)
502
- {
503
- return $this->getAuth()->verifyIdToken($token);
504
- }
505
-
506
- /**
507
- * Verify a JWT that was signed with your own certificates.
508
- *
509
- * @param $id_token string
510
- * The JWT token
511
- * @param $cert_location array
512
- * of certificates
513
- * @param $audience string
514
- * the expected consumer of the token
515
- * @param $issuer string
516
- * the expected issuer, defaults to Google
517
- * @param
518
- * [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS
519
- * @return mixed token information if valid, false if not
520
- */
521
- public function verifySignedJwt($id_token, $cert_location, $audience, $issuer, $max_expiry = null)
522
- {
523
- $auth = new Google_Auth_OAuth2($this);
524
- $certs = $auth->retrieveCertsFromLocation($cert_location);
525
- return $auth->verifySignedJwtWithCerts($id_token, $certs, $audience, $issuer, $max_expiry);
526
- }
527
-
528
- /**
529
- *
530
- * @param $creds Google_Auth_AssertionCredentials
531
- */
532
- public function setAssertionCredentials(Google_Auth_AssertionCredentials $creds)
533
- {
534
- $this->getAuth()->setAssertionCredentials($creds);
535
- }
536
-
537
- /**
538
- * Set the scopes to be requested.
539
- * Must be called before createAuthUrl().
540
- * Will remove any previously configured scopes.
541
- *
542
- * @param array $scopes,
543
- * ie: array('https://www.googleapis.com/auth/plus.login',
544
- * 'https://www.googleapis.com/auth/moderator')
545
- */
546
- public function setScopes($scopes)
547
- {
548
- $this->requestedScopes = array();
549
- $this->addScope($scopes);
550
- }
551
-
552
- /**
553
- * This functions adds a scope to be requested as part of the OAuth2.0 flow.
554
- * Will append any scopes not previously requested to the scope parameter.
555
- * A single string will be treated as a scope to request. An array of strings
556
- * will each be appended.
557
- *
558
- * @param $scope_or_scopes string|array
559
- * e.g. "profile"
560
- */
561
- public function addScope($scope_or_scopes)
562
- {
563
- if (is_string($scope_or_scopes) && ! in_array($scope_or_scopes, $this->requestedScopes)) {
564
- $this->requestedScopes[] = $scope_or_scopes;
565
- } else
566
- if (is_array($scope_or_scopes)) {
567
- foreach ($scope_or_scopes as $scope) {
568
- $this->addScope($scope);
569
- }
570
- }
571
- }
572
-
573
- /**
574
- * Returns the list of scopes requested by the client
575
- *
576
- * @return array the list of scopes
577
- *
578
- */
579
- public function getScopes()
580
- {
581
- return $this->requestedScopes;
582
- }
583
-
584
- /**
585
- * Declare whether batch calls should be used.
586
- * This may increase throughput
587
- * by making multiple requests in one connection.
588
- *
589
- * @param boolean $useBatch
590
- * True if the batch support should
591
- * be enabled. Defaults to False.
592
- */
593
- public function setUseBatch($useBatch)
594
- {
595
- // This is actually an alias for setDefer.
596
- $this->setDefer($useBatch);
597
- }
598
-
599
- /**
600
- * Declare whether making API calls should make the call immediately, or
601
- * return a request which can be called with ->execute();
602
- *
603
- * @param boolean $defer
604
- * True if calls should not be executed right away.
605
- */
606
- public function setDefer($defer)
607
- {
608
- $this->deferExecution = $defer;
609
- }
610
-
611
- /**
612
- * Helper method to execute deferred HTTP requests.
613
- *
614
- * @param $request Google_Http_Request|Google_Http_Batch
615
- * @throws Google_Exception
616
- * @return object of the type of the expected class or array.
617
- */
618
- public function execute($request)
619
- {
620
- if ($request instanceof Google_Http_Request) {
621
- $request->setUserAgent($this->getApplicationName() . " " . self::USER_AGENT_SUFFIX . $this->getLibraryVersion());
622
- if (! $this->getClassConfig("Google_Http_Request", "disable_gzip")) {
623
- $request->enableGzip();
624
- }
625
- $request->maybeMoveParametersToBody();
626
- return Google_Http_REST::execute($this, $request);
627
- } else
628
- if ($request instanceof Google_Http_Batch) {
629
- return $request->execute();
630
- } else {
631
- throw new Google_Exception("Do not know how to execute this type of object.");
632
- }
633
- }
634
-
635
- /**
636
- * Whether or not to return raw requests
637
- *
638
- * @return boolean
639
- */
640
- public function shouldDefer()
641
- {
642
- return $this->deferExecution;
643
- }
644
-
645
- /**
646
- *
647
- * @return Google_Auth_Abstract Authentication implementation
648
- */
649
- public function getAuth()
650
- {
651
- if (! isset($this->auth)) {
652
- $class = $this->config->getAuthClass();
653
- $this->auth = new $class($this);
654
- }
655
- return $this->auth;
656
- }
657
-
658
- /**
659
- *
660
- * @return Google_IO_Abstract IO implementation
661
- */
662
- public function getIo()
663
- {
664
- if (! isset($this->io)) {
665
- $class = $this->config->getIoClass();
666
- $this->io = new $class($this);
667
- }
668
- return $this->io;
669
- }
670
-
671
- /**
672
- *
673
- * @return Google_Cache_Abstract Cache implementation
674
- */
675
- public function getCache()
676
- {
677
- if (! isset($this->cache)) {
678
- $class = $this->config->getCacheClass();
679
- $this->cache = new $class($this);
680
- }
681
- return $this->cache;
682
- }
683
-
684
- /**
685
- *
686
- * @return Google_Logger_Abstract Logger implementation
687
- */
688
- public function getLogger()
689
- {
690
- if (! isset($this->logger)) {
691
- $class = $this->config->getLoggerClass();
692
- $this->logger = new $class($this);
693
- }
694
- return $this->logger;
695
- }
696
-
697
- /**
698
- * Retrieve custom configuration for a specific class.
699
- *
700
- * @param $class string|object
701
- * - class or instance of class to retrieve
702
- * @param $key string
703
- * optional - key to retrieve
704
- * @return array
705
- */
706
- public function getClassConfig($class, $key = null)
707
- {
708
- if (! is_string($class)) {
709
- $class = get_class($class);
710
- }
711
- return $this->config->getClassConfig($class, $key);
712
- }
713
-
714
- /**
715
- * Set configuration specific to a given class.
716
- * $config->setClassConfig('Google_Cache_File',
717
- * array('directory' => '/tmp/cache'));
718
- *
719
- * @param $class string|object
720
- * - The class name for the configuration
721
- * @param $config string
722
- * key or an array of configuration values
723
- * @param $value string
724
- * optional - if $config is a key, the value
725
- *
726
- */
727
- public function setClassConfig($class, $config, $value = null)
728
- {
729
- if (! is_string($class)) {
730
- $class = get_class($class);
731
- }
732
- $this->config->setClassConfig($class, $config, $value);
733
- }
734
-
735
- /**
736
- *
737
- * @return string the base URL to use for calls to the APIs
738
- */
739
- public function getBasePath()
740
- {
741
- return $this->config->getBasePath();
742
- }
743
-
744
- /**
745
- *
746
- * @return string the name of the application
747
- */
748
- public function getApplicationName()
749
- {
750
- return $this->config->getApplicationName();
751
- }
752
-
753
- /**
754
- * Are we running in Google AppEngine?
755
- * return bool
756
- */
757
- public function isAppEngine()
758
- {
759
- return (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false);
760
- }
761
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../autoload.php');
18
+
19
+ /**
20
+ * The Google API Client
21
+ * http://code.google.com/p/google-api-php-client/
22
+ *
23
+ * @author Chris Chabot <chabotc@google.com>
24
+ * @author Chirag Shah <chirags@google.com>
25
+ */
26
+ class Google_Client
27
+ {
28
+
29
+ const LIBVER = "1.1.2";
30
+
31
+ const USER_AGENT_SUFFIX = "google-api-php-client/";
32
+
33
+ /**
34
+ *
35
+ * @var Google_Auth_Abstract $auth
36
+ */
37
+ private $auth;
38
+
39
+ /**
40
+ *
41
+ * @var Google_IO_Abstract $io
42
+ */
43
+ private $io;
44
+
45
+ /**
46
+ *
47
+ * @var Google_Cache_Abstract $cache
48
+ */
49
+ private $cache;
50
+
51
+ /**
52
+ *
53
+ * @var Google_Config $config
54
+ */
55
+ private $config;
56
+
57
+ /**
58
+ *
59
+ * @var Google_Logger_Abstract $logger
60
+ */
61
+ private $logger;
62
+
63
+ /**
64
+ *
65
+ * @var boolean $deferExecution
66
+ */
67
+ private $deferExecution = false;
68
+
69
+ /**
70
+ *
71
+ * @var array $scopes
72
+ */
73
+ // Scopes requested by the client
74
+ protected $requestedScopes = array();
75
+ // definitions of services that are discovered.
76
+ protected $services = array();
77
+ // Used to track authenticated state, can't discover services after doing authenticate()
78
+ private $authenticated = false;
79
+
80
+ /**
81
+ * Construct the Google Client.
82
+ *
83
+ * @param $config Google_Config
84
+ * or string for the ini file to load
85
+ */
86
+ public function __construct($config = null)
87
+ {
88
+ if (is_string($config) && strlen($config)) {
89
+ $config = new Google_Config($config);
90
+ } else
91
+ if (! ($config instanceof Google_Config)) {
92
+ $config = new Google_Config();
93
+ if ($this->isAppEngine()) {
94
+ // Automatically use Memcache if we're in AppEngine.
95
+ $config->setCacheClass('Google_Cache_Memcache');
96
+ }
97
+ if (version_compare(phpversion(), "5.3.4", "<=") || $this->isAppEngine()) {
98
+ // Automatically disable compress.zlib, as currently unsupported.
99
+ $config->setClassConfig('Google_Http_Request', 'disable_gzip', true);
100
+ }
101
+ }
102
+ if ($config->getIoClass() == Google_Config::USE_AUTO_IO_SELECTION) {
103
+ if (function_exists('curl_version') && function_exists('curl_exec') && ! $this->isAppEngine()) {
104
+ $config->setIoClass("Google_IO_Curl");
105
+ } else {
106
+ $config->setIoClass("Google_IO_Stream");
107
+ }
108
+ }
109
+ $this->config = $config;
110
+ }
111
+
112
+ /**
113
+ * Get a string containing the version of the library.
114
+ *
115
+ * @return string
116
+ */
117
+ public function getLibraryVersion()
118
+ {
119
+ return self::LIBVER;
120
+ }
121
+
122
+ /**
123
+ * Attempt to exchange a code for an valid authentication token.
124
+ * Helper wrapped around the OAuth 2.0 implementation.
125
+ *
126
+ * @param $code string
127
+ * code from accounts.google.com
128
+ * @return string token
129
+ */
130
+ public function authenticate($code)
131
+ {
132
+ $this->authenticated = true;
133
+ return $this->getAuth()->authenticate($code);
134
+ }
135
+
136
+ /**
137
+ * Set the auth config from the JSON string provided.
138
+ * This structure should match the file downloaded from
139
+ * the "Download JSON" button on in the Google Developer
140
+ * Console.
141
+ *
142
+ * @param string $json
143
+ * the configuration json
144
+ * @throws Google_Exception
145
+ */
146
+ public function setAuthConfig($json)
147
+ {
148
+ $data = json_decode($json);
149
+ $key = isset($data->installed) ? 'installed' : 'web';
150
+ if (! isset($data->$key)) {
151
+ throw new Google_Exception("Invalid client secret JSON file.");
152
+ }
153
+ $this->setClientId($data->$key->client_id);
154
+ $this->setClientSecret($data->$key->client_secret);
155
+ if (isset($data->$key->redirect_uris)) {
156
+ $this->setRedirectUri($data->$key->redirect_uris[0]);
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Set the auth config from the JSON file in the path
162
+ * provided.
163
+ * This should match the file downloaded from
164
+ * the "Download JSON" button on in the Google Developer
165
+ * Console.
166
+ *
167
+ * @param string $file
168
+ * the file location of the client json
169
+ */
170
+ public function setAuthConfigFile($file)
171
+ {
172
+ $this->setAuthConfig(file_get_contents($file));
173
+ }
174
+
175
+ /**
176
+ *
177
+ * @throws Google_Auth_Exception
178
+ * @return array @visible For Testing
179
+ */
180
+ public function prepareScopes()
181
+ {
182
+ if (empty($this->requestedScopes)) {
183
+ throw new Google_Auth_Exception("No scopes specified");
184
+ }
185
+ $scopes = implode(' ', $this->requestedScopes);
186
+ return $scopes;
187
+ }
188
+
189
+ /**
190
+ * Set the OAuth 2.0 access token using the string that resulted from calling createAuthUrl()
191
+ * or Google_Client#getAccessToken().
192
+ *
193
+ * @param string $accessToken
194
+ * JSON encoded string containing in the following format:
195
+ * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
196
+ * "expires_in":3600, "id_token":"TOKEN", "created":1320790426}
197
+ */
198
+ public function setAccessToken($accessToken)
199
+ {
200
+ if ($accessToken == 'null') {
201
+ $accessToken = null;
202
+ }
203
+ $this->getAuth()->setAccessToken($accessToken);
204
+ }
205
+
206
+ /**
207
+ * Set the authenticator object
208
+ *
209
+ * @param Google_Auth_Abstract $auth
210
+ */
211
+ public function setAuth(Google_Auth_Abstract $auth)
212
+ {
213
+ $this->config->setAuthClass(get_class($auth));
214
+ $this->auth = $auth;
215
+ }
216
+
217
+ /**
218
+ * Set the IO object
219
+ *
220
+ * @param Google_IO_Abstract $io
221
+ */
222
+ public function setIo(Google_IO_Abstract $io)
223
+ {
224
+ $this->config->setIoClass(get_class($io));
225
+ $this->io = $io;
226
+ }
227
+
228
+ /**
229
+ * Set the Cache object
230
+ *
231
+ * @param Google_Cache_Abstract $cache
232
+ */
233
+ public function setCache(Google_Cache_Abstract $cache)
234
+ {
235
+ $this->config->setCacheClass(get_class($cache));
236
+ $this->cache = $cache;
237
+ }
238
+
239
+ /**
240
+ * Set the Logger object
241
+ *
242
+ * @param Google_Logger_Abstract $logger
243
+ */
244
+ public function setLogger(Google_Logger_Abstract $logger)
245
+ {
246
+ $this->config->setLoggerClass(get_class($logger));
247
+ $this->logger = $logger;
248
+ }
249
+
250
+ /**
251
+ * Construct the OAuth 2.0 authorization request URI.
252
+ *
253
+ * @return string
254
+ */
255
+ public function createAuthUrl()
256
+ {
257
+ $scopes = $this->prepareScopes();
258
+ return $this->getAuth()->createAuthUrl($scopes);
259
+ }
260
+
261
+ /**
262
+ * Get the OAuth 2.0 access token.
263
+ *
264
+ * @return string $accessToken JSON encoded string in the following format:
265
+ * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
266
+ * "expires_in":3600,"id_token":"TOKEN", "created":1320790426}
267
+ */
268
+ public function getAccessToken()
269
+ {
270
+ $token = $this->getAuth()->getAccessToken();
271
+ // The response is json encoded, so could be the string null.
272
+ // It is arguable whether this check should be here or lower
273
+ // in the library.
274
+ return (null == $token || 'null' == $token || '[]' == $token) ? null : $token;
275
+ }
276
+
277
+ /**
278
+ * Get the OAuth 2.0 refresh token.
279
+ *
280
+ * @return string $refreshToken refresh token or null if not available
281
+ */
282
+ public function getRefreshToken()
283
+ {
284
+ return $this->getAuth()->getRefreshToken();
285
+ }
286
+
287
+ /**
288
+ * Returns if the access_token is expired.
289
+ *
290
+ * @return bool Returns True if the access_token is expired.
291
+ */
292
+ public function isAccessTokenExpired()
293
+ {
294
+ return $this->getAuth()->isAccessTokenExpired();
295
+ }
296
+
297
+ /**
298
+ * Set OAuth 2.0 "state" parameter to achieve per-request customization.
299
+ *
300
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
301
+ * @param string $state
302
+ */
303
+ public function setState($state)
304
+ {
305
+ $this->getAuth()->setState($state);
306
+ }
307
+
308
+ /**
309
+ *
310
+ * @param string $accessType
311
+ * Possible values for access_type include:
312
+ * {@code "offline"} to request offline access from the user.
313
+ * {@code "online"} to request online access from the user.
314
+ */
315
+ public function setAccessType($accessType)
316
+ {
317
+ $this->config->setAccessType($accessType);
318
+ }
319
+
320
+ /**
321
+ *
322
+ * @param string $approvalPrompt
323
+ * Possible values for approval_prompt include:
324
+ * {@code "force"} to force the approval UI to appear. (This is the default value)
325
+ * {@code "auto"} to request auto-approval when possible.
326
+ */
327
+ public function setApprovalPrompt($approvalPrompt)
328
+ {
329
+ $this->config->setApprovalPrompt($approvalPrompt);
330
+ }
331
+
332
+ /**
333
+ * Set the login hint, email address or sub id.
334
+ *
335
+ * @param string $loginHint
336
+ */
337
+ public function setLoginHint($loginHint)
338
+ {
339
+ $this->config->setLoginHint($loginHint);
340
+ }
341
+
342
+ /**
343
+ * Set the application name, this is included in the User-Agent HTTP header.
344
+ *
345
+ * @param string $applicationName
346
+ */
347
+ public function setApplicationName($applicationName)
348
+ {
349
+ $this->config->setApplicationName($applicationName);
350
+ }
351
+
352
+ /**
353
+ * Set the OAuth 2.0 Client ID.
354
+ *
355
+ * @param string $clientId
356
+ */
357
+ public function setClientId($clientId)
358
+ {
359
+ $this->config->setClientId($clientId);
360
+ }
361
+
362
+ /**
363
+ * Set the OAuth 2.0 Client Secret.
364
+ *
365
+ * @param string $clientSecret
366
+ */
367
+ public function setClientSecret($clientSecret)
368
+ {
369
+ $this->config->setClientSecret($clientSecret);
370
+ }
371
+
372
+ /**
373
+ * Set the OAuth 2.0 Redirect URI.
374
+ *
375
+ * @param string $redirectUri
376
+ */
377
+ public function setRedirectUri($redirectUri)
378
+ {
379
+ $this->config->setRedirectUri($redirectUri);
380
+ }
381
+
382
+ /**
383
+ * If 'plus.login' is included in the list of requested scopes, you can use
384
+ * this method to define types of app activities that your app will write.
385
+ * You can find a list of available types here:
386
+ *
387
+ * @link https://developers.google.com/+/api/moment-types
388
+ *
389
+ * @param array $requestVisibleActions
390
+ * Array of app activity types
391
+ */
392
+ public function setRequestVisibleActions($requestVisibleActions)
393
+ {
394
+ if (is_array($requestVisibleActions)) {
395
+ $requestVisibleActions = join(" ", $requestVisibleActions);
396
+ }
397
+ $this->config->setRequestVisibleActions($requestVisibleActions);
398
+ }
399
+
400
+ /**
401
+ * Set the developer key to use, these are obtained through the API Console.
402
+ *
403
+ * @see http://code.google.com/apis/console-help/#generatingdevkeys
404
+ * @param string $developerKey
405
+ */
406
+ public function setDeveloperKey($developerKey)
407
+ {
408
+ $this->config->setDeveloperKey($developerKey);
409
+ }
410
+
411
+ /**
412
+ * Set the hd (hosted domain) parameter streamlines the login process for
413
+ * Google Apps hosted accounts.
414
+ * By including the domain of the user, you
415
+ * restrict sign-in to accounts at that domain.
416
+ *
417
+ * @param $hd string
418
+ * - the domain to use.
419
+ */
420
+ public function setHostedDomain($hd)
421
+ {
422
+ $this->config->setHostedDomain($hd);
423
+ }
424
+
425
+ /**
426
+ * Set the prompt hint.
427
+ * Valid values are none, consent and select_account.
428
+ * If no value is specified and the user has not previously authorized
429
+ * access, then the user is shown a consent screen.
430
+ *
431
+ * @param $prompt string
432
+ */
433
+ public function setPrompt($prompt)
434
+ {
435
+ $this->config->setPrompt($prompt);
436
+ }
437
+
438
+ /**
439
+ * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
440
+ * 2.0.
441
+ * It is used in OpenID 2.0 requests to signify the URL-space for which
442
+ * an authentication request is valid.
443
+ *
444
+ * @param $realm string
445
+ * - the URL-space to use.
446
+ */
447
+ public function setOpenidRealm($realm)
448
+ {
449
+ $this->config->setOpenidRealm($realm);
450
+ }
451
+
452
+ /**
453
+ * If this is provided with the value true, and the authorization request is
454
+ * granted, the authorization will include any previous authorizations
455
+ * granted to this user/application combination for other scopes.
456
+ *
457
+ * @param $include boolean
458
+ * - the URL-space to use.
459
+ */
460
+ public function setIncludeGrantedScopes($include)
461
+ {
462
+ $this->config->setIncludeGrantedScopes($include);
463
+ }
464
+
465
+ /**
466
+ * Fetches a fresh OAuth 2.0 access token with the given refresh token.
467
+ *
468
+ * @param string $refreshToken
469
+ */
470
+ public function refreshToken($refreshToken)
471
+ {
472
+ $this->getAuth()->refreshToken($refreshToken);
473
+ }
474
+
475
+ /**
476
+ * Revoke an OAuth2 access token or refresh token.
477
+ * This method will revoke the current access
478
+ * token, if a token isn't provided.
479
+ *
480
+ * @throws Google_Auth_Exception
481
+ * @param string|null $token
482
+ * The token (access token or a refresh token) that should be revoked.
483
+ * @return boolean Returns True if the revocation was successful, otherwise False.
484
+ */
485
+ public function revokeToken($token = null)
486
+ {
487
+ return $this->getAuth()->revokeToken($token);
488
+ }
489
+
490
+ /**
491
+ * Verify an id_token.
492
+ * This method will verify the current id_token, if one
493
+ * isn't provided.
494
+ *
495
+ * @throws Google_Auth_Exception
496
+ * @param string|null $token
497
+ * The token (id_token) that should be verified.
498
+ * @return Google_Auth_LoginTicket Returns an apiLoginTicket if the verification was
499
+ * successful.
500
+ */
501
+ public function verifyIdToken($token = null)
502
+ {
503
+ return $this->getAuth()->verifyIdToken($token);
504
+ }
505
+
506
+ /**
507
+ * Verify a JWT that was signed with your own certificates.
508
+ *
509
+ * @param $id_token string
510
+ * The JWT token
511
+ * @param $cert_location array
512
+ * of certificates
513
+ * @param $audience string
514
+ * the expected consumer of the token
515
+ * @param $issuer string
516
+ * the expected issuer, defaults to Google
517
+ * @param
518
+ * [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS
519
+ * @return mixed token information if valid, false if not
520
+ */
521
+ public function verifySignedJwt($id_token, $cert_location, $audience, $issuer, $max_expiry = null)
522
+ {
523
+ $auth = new Google_Auth_OAuth2($this);
524
+ $certs = $auth->retrieveCertsFromLocation($cert_location);
525
+ return $auth->verifySignedJwtWithCerts($id_token, $certs, $audience, $issuer, $max_expiry);
526
+ }
527
+
528
+ /**
529
+ *
530
+ * @param $creds Google_Auth_AssertionCredentials
531
+ */
532
+ public function setAssertionCredentials(Google_Auth_AssertionCredentials $creds)
533
+ {
534
+ $this->getAuth()->setAssertionCredentials($creds);
535
+ }
536
+
537
+ /**
538
+ * Set the scopes to be requested.
539
+ * Must be called before createAuthUrl().
540
+ * Will remove any previously configured scopes.
541
+ *
542
+ * @param array $scopes,
543
+ * ie: array('https://www.googleapis.com/auth/plus.login',
544
+ * 'https://www.googleapis.com/auth/moderator')
545
+ */
546
+ public function setScopes($scopes)
547
+ {
548
+ $this->requestedScopes = array();
549
+ $this->addScope($scopes);
550
+ }
551
+
552
+ /**
553
+ * This functions adds a scope to be requested as part of the OAuth2.0 flow.
554
+ * Will append any scopes not previously requested to the scope parameter.
555
+ * A single string will be treated as a scope to request. An array of strings
556
+ * will each be appended.
557
+ *
558
+ * @param $scope_or_scopes string|array
559
+ * e.g. "profile"
560
+ */
561
+ public function addScope($scope_or_scopes)
562
+ {
563
+ if (is_string($scope_or_scopes) && ! in_array($scope_or_scopes, $this->requestedScopes)) {
564
+ $this->requestedScopes[] = $scope_or_scopes;
565
+ } else
566
+ if (is_array($scope_or_scopes)) {
567
+ foreach ($scope_or_scopes as $scope) {
568
+ $this->addScope($scope);
569
+ }
570
+ }
571
+ }
572
+
573
+ /**
574
+ * Returns the list of scopes requested by the client
575
+ *
576
+ * @return array the list of scopes
577
+ *
578
+ */
579
+ public function getScopes()
580
+ {
581
+ return $this->requestedScopes;
582
+ }
583
+
584
+ /**
585
+ * Declare whether batch calls should be used.
586
+ * This may increase throughput
587
+ * by making multiple requests in one connection.
588
+ *
589
+ * @param boolean $useBatch
590
+ * True if the batch support should
591
+ * be enabled. Defaults to False.
592
+ */
593
+ public function setUseBatch($useBatch)
594
+ {
595
+ // This is actually an alias for setDefer.
596
+ $this->setDefer($useBatch);
597
+ }
598
+
599
+ /**
600
+ * Declare whether making API calls should make the call immediately, or
601
+ * return a request which can be called with ->execute();
602
+ *
603
+ * @param boolean $defer
604
+ * True if calls should not be executed right away.
605
+ */
606
+ public function setDefer($defer)
607
+ {
608
+ $this->deferExecution = $defer;
609
+ }
610
+
611
+ /**
612
+ * Helper method to execute deferred HTTP requests.
613
+ *
614
+ * @param $request Google_Http_Request|Google_Http_Batch
615
+ * @throws Google_Exception
616
+ * @return object of the type of the expected class or array.
617
+ */
618
+ public function execute($request)
619
+ {
620
+ if ($request instanceof Google_Http_Request) {
621
+ $request->setUserAgent($this->getApplicationName() . " " . self::USER_AGENT_SUFFIX . $this->getLibraryVersion());
622
+ if (! $this->getClassConfig("Google_Http_Request", "disable_gzip")) {
623
+ $request->enableGzip();
624
+ }
625
+ $request->maybeMoveParametersToBody();
626
+ return Google_Http_REST::execute($this, $request);
627
+ } else
628
+ if ($request instanceof Google_Http_Batch) {
629
+ return $request->execute();
630
+ } else {
631
+ throw new Google_Exception("Do not know how to execute this type of object.");
632
+ }
633
+ }
634
+
635
+ /**
636
+ * Whether or not to return raw requests
637
+ *
638
+ * @return boolean
639
+ */
640
+ public function shouldDefer()
641
+ {
642
+ return $this->deferExecution;
643
+ }
644
+
645
+ /**
646
+ *
647
+ * @return Google_Auth_Abstract Authentication implementation
648
+ */
649
+ public function getAuth()
650
+ {
651
+ if (! isset($this->auth)) {
652
+ $class = $this->config->getAuthClass();
653
+ $this->auth = new $class($this);
654
+ }
655
+ return $this->auth;
656
+ }
657
+
658
+ /**
659
+ *
660
+ * @return Google_IO_Abstract IO implementation
661
+ */
662
+ public function getIo()
663
+ {
664
+ if (! isset($this->io)) {
665
+ $class = $this->config->getIoClass();
666
+ $this->io = new $class($this);
667
+ }
668
+ return $this->io;
669
+ }
670
+
671
+ /**
672
+ *
673
+ * @return Google_Cache_Abstract Cache implementation
674
+ */
675
+ public function getCache()
676
+ {
677
+ if (! isset($this->cache)) {
678
+ $class = $this->config->getCacheClass();
679
+ $this->cache = new $class($this);
680
+ }
681
+ return $this->cache;
682
+ }
683
+
684
+ /**
685
+ *
686
+ * @return Google_Logger_Abstract Logger implementation
687
+ */
688
+ public function getLogger()
689
+ {
690
+ if (! isset($this->logger)) {
691
+ $class = $this->config->getLoggerClass();
692
+ $this->logger = new $class($this);
693
+ }
694
+ return $this->logger;
695
+ }
696
+
697
+ /**
698
+ * Retrieve custom configuration for a specific class.
699
+ *
700
+ * @param $class string|object
701
+ * - class or instance of class to retrieve
702
+ * @param $key string
703
+ * optional - key to retrieve
704
+ * @return array
705
+ */
706
+ public function getClassConfig($class, $key = null)
707
+ {
708
+ if (! is_string($class)) {
709
+ $class = get_class($class);
710
+ }
711
+ return $this->config->getClassConfig($class, $key);
712
+ }
713
+
714
+ /**
715
+ * Set configuration specific to a given class.
716
+ * $config->setClassConfig('Google_Cache_File',
717
+ * array('directory' => '/tmp/cache'));
718
+ *
719
+ * @param $class string|object
720
+ * - The class name for the configuration
721
+ * @param $config string
722
+ * key or an array of configuration values
723
+ * @param $value string
724
+ * optional - if $config is a key, the value
725
+ *
726
+ */
727
+ public function setClassConfig($class, $config, $value = null)
728
+ {
729
+ if (! is_string($class)) {
730
+ $class = get_class($class);
731
+ }
732
+ $this->config->setClassConfig($class, $config, $value);
733
+ }
734
+
735
+ /**
736
+ *
737
+ * @return string the base URL to use for calls to the APIs
738
+ */
739
+ public function getBasePath()
740
+ {
741
+ return $this->config->getBasePath();
742
+ }
743
+
744
+ /**
745
+ *
746
+ * @return string the name of the application
747
+ */
748
+ public function getApplicationName()
749
+ {
750
+ return $this->config->getApplicationName();
751
+ }
752
+
753
+ /**
754
+ * Are we running in Google AppEngine?
755
+ * return bool
756
+ */
757
+ public function isAppEngine()
758
+ {
759
+ return (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false);
760
+ }
761
  }
tools/src/Google/Collection.php CHANGED
@@ -1,93 +1,93 @@
1
- <?php
2
- require_once realpath(dirname(__FILE__) . '/../../autoload.php');
3
-
4
- /**
5
- * Extension to the regular Google_Model that automatically
6
- * exposes the items array for iteration, so you can just
7
- * iterate over the object rather than a reference inside.
8
- */
9
- class Google_Collection extends Google_Model implements Iterator, Countable
10
- {
11
-
12
- protected $collection_key = 'items';
13
-
14
- public function rewind()
15
- {
16
- if (isset($this->modelData[$this->collection_key]) && is_array($this->modelData[$this->collection_key])) {
17
- reset($this->modelData[$this->collection_key]);
18
- }
19
- }
20
-
21
- public function current()
22
- {
23
- $this->coerceType($this->key());
24
- if (is_array($this->modelData[$this->collection_key])) {
25
- return current($this->modelData[$this->collection_key]);
26
- }
27
- }
28
-
29
- public function key()
30
- {
31
- if (isset($this->modelData[$this->collection_key]) && is_array($this->modelData[$this->collection_key])) {
32
- return key($this->modelData[$this->collection_key]);
33
- }
34
- }
35
-
36
- public function next()
37
- {
38
- return next($this->modelData[$this->collection_key]);
39
- }
40
-
41
- public function valid()
42
- {
43
- $key = $this->key();
44
- return $key !== null && $key !== false;
45
- }
46
-
47
- public function count()
48
- {
49
- return count($this->modelData[$this->collection_key]);
50
- }
51
-
52
- public function offsetExists($offset)
53
- {
54
- if (! is_numeric($offset)) {
55
- return parent::offsetExists($offset);
56
- }
57
- return isset($this->modelData[$this->collection_key][$offset]);
58
- }
59
-
60
- public function offsetGet($offset)
61
- {
62
- if (! is_numeric($offset)) {
63
- return parent::offsetGet($offset);
64
- }
65
- $this->coerceType($offset);
66
- return $this->modelData[$this->collection_key][$offset];
67
- }
68
-
69
- public function offsetSet($offset, $value)
70
- {
71
- if (! is_numeric($offset)) {
72
- return parent::offsetSet($offset, $value);
73
- }
74
- $this->modelData[$this->collection_key][$offset] = $value;
75
- }
76
-
77
- public function offsetUnset($offset)
78
- {
79
- if (! is_numeric($offset)) {
80
- return parent::offsetUnset($offset);
81
- }
82
- unset($this->modelData[$this->collection_key][$offset]);
83
- }
84
-
85
- private function coerceType($offset)
86
- {
87
- $typeKey = $this->keyType($this->collection_key);
88
- if (isset($this->$typeKey) && ! is_object($this->modelData[$this->collection_key][$offset])) {
89
- $type = $this->$typeKey;
90
- $this->modelData[$this->collection_key][$offset] = new $type($this->modelData[$this->collection_key][$offset]);
91
- }
92
- }
93
  }
1
+ <?php
2
+ require_once realpath(dirname(__FILE__) . '/../../autoload.php');
3
+
4
+ /**
5
+ * Extension to the regular Google_Model that automatically
6
+ * exposes the items array for iteration, so you can just
7
+ * iterate over the object rather than a reference inside.
8
+ */
9
+ class Google_Collection extends Google_Model implements Iterator, Countable
10
+ {
11
+
12
+ protected $collection_key = 'items';
13
+
14
+ public function rewind()
15
+ {
16
+ if (isset($this->modelData[$this->collection_key]) && is_array($this->modelData[$this->collection_key])) {
17
+ reset($this->modelData[$this->collection_key]);
18
+ }
19
+ }
20
+
21
+ public function current()
22
+ {
23
+ $this->coerceType($this->key());
24
+ if (is_array($this->modelData[$this->collection_key])) {
25
+ return current($this->modelData[$this->collection_key]);
26
+ }
27
+ }
28
+
29
+ public function key()
30
+ {
31
+ if (isset($this->modelData[$this->collection_key]) && is_array($this->modelData[$this->collection_key])) {
32
+ return key($this->modelData[$this->collection_key]);
33
+ }
34
+ }
35
+
36
+ public function next()
37
+ {
38
+ return next($this->modelData[$this->collection_key]);
39
+ }
40
+
41
+ public function valid()
42
+ {
43
+ $key = $this->key();
44
+ return $key !== null && $key !== false;
45
+ }
46
+
47
+ public function count()
48
+ {
49
+ return count($this->modelData[$this->collection_key]);
50
+ }
51
+
52
+ public function offsetExists($offset)
53
+ {
54
+ if (! is_numeric($offset)) {
55
+ return parent::offsetExists($offset);
56
+ }
57
+ return isset($this->modelData[$this->collection_key][$offset]);
58
+ }
59
+
60
+ public function offsetGet($offset)
61
+ {
62
+ if (! is_numeric($offset)) {
63
+ return parent::offsetGet($offset);
64
+ }
65
+ $this->coerceType($offset);
66
+ return $this->modelData[$this->collection_key][$offset];
67
+ }
68
+
69
+ public function offsetSet($offset, $value)
70
+ {
71
+ if (! is_numeric($offset)) {
72
+ return parent::offsetSet($offset, $value);
73
+ }
74
+ $this->modelData[$this->collection_key][$offset] = $value;
75
+ }
76
+
77
+ public function offsetUnset($offset)
78
+ {
79
+ if (! is_numeric($offset)) {
80
+ return parent::offsetUnset($offset);
81
+ }
82
+ unset($this->modelData[$this->collection_key][$offset]);
83
+ }
84
+
85
+ private function coerceType($offset)
86
+ {
87
+ $typeKey = $this->keyType($this->collection_key);
88
+ if (isset($this->$typeKey) && ! is_object($this->modelData[$this->collection_key][$offset])) {
89
+ $type = $this->$typeKey;
90
+ $this->modelData[$this->collection_key][$offset] = new $type($this->modelData[$this->collection_key][$offset]);
91
+ }
92
+ }
93
  }
tools/src/Google/Config.php CHANGED
@@ -1,447 +1,447 @@
1
- <?php
2
-
3
- /*
4
- * Copyright 2010 Google Inc.
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */
18
- /**
19
- * A class to contain the library configuration for the Google API client.
20
- */
21
- class Google_Config
22
- {
23
-
24
- const GZIP_DISABLED = true;
25
-
26
- const GZIP_ENABLED = false;
27
-
28
- const GZIP_UPLOADS_ENABLED = true;
29
-
30
- const GZIP_UPLOADS_DISABLED = false;
31
-
32
- const USE_AUTO_IO_SELECTION = "auto";
33
-
34
- protected $configuration;
35
-
36
- /**
37
- * Create a new Google_Config.
38
- * Can accept an ini file location with the
39
- * local configuration. For example:
40
- * application_name="My App"
41
- *
42
- * @param
43
- * [$ini_file_location] - optional - The location of the ini file to load
44
- */
45
- public function __construct($ini_file_location = null)
46
- {
47
- $this->configuration = array(
48
- // The application_name is included in the User-Agent HTTP header.
49
- 'application_name' => '',
50
- // Which Authentication, Storage and HTTP IO classes to use.
51
- 'auth_class' => 'Google_Auth_OAuth2',
52
- 'io_class' => self::USE_AUTO_IO_SELECTION,
53
- 'cache_class' => 'Google_Cache_File',
54
- 'logger_class' => 'Google_Logger_Null',
55
- // Don't change these unless you're working against a special development
56
- // or testing environment.
57
- 'base_path' => 'https://www.googleapis.com',
58
- // Definition of class specific values, like file paths and so on.
59
- 'classes' => array(
60
- 'Google_IO_Abstract' => array(
61
- 'request_timeout_seconds' => 100
62
- ),
63
- 'Google_Logger_Abstract' => array(
64
- 'level' => 'debug',
65
- 'log_format' => "[%datetime%] %level%: %message% %context%\n",
66
- 'date_format' => 'd/M/Y:H:i:s O',
67
- 'allow_newlines' => true
68
- ),
69
- 'Google_Logger_File' => array(
70
- 'file' => 'php://stdout',
71
- 'mode' => 0640,
72
- 'lock' => false
73
- ),
74
- 'Google_Http_Request' => array(
75
- // Disable the use of gzip on calls if set to true. Defaults to false.
76
- 'disable_gzip' => self::GZIP_ENABLED,
77
- // We default gzip to disabled on uploads even if gzip is otherwise
78
- // enabled, due to some issues seen with small packet sizes for uploads.
79
- // Please test with this option before enabling gzip for uploads in
80
- // a production environment.
81
- 'enable_gzip_for_uploads' => self::GZIP_UPLOADS_DISABLED
82
- ),
83
- // If you want to pass in OAuth 2.0 settings, they will need to be
84
- // structured like this.
85
- 'Google_Auth_OAuth2' => array(
86
- // Keys for OAuth 2.0 access, see the API console at
87
- // https://developers.google.com/console
88
- 'client_id' => '',
89
- 'client_secret' => '',
90
- 'redirect_uri' => '',
91
- // Simple API access key, also from the API console. Ensure you get
92
- // a Server key, and not a Browser key.
93
- 'developer_key' => '',
94
- // Other parameters.
95
- 'hd' => '',
96
- 'prompt' => '',
97
- 'openid.realm' => '',
98
- 'include_granted_scopes' => '',
99
- 'login_hint' => '',
100
- 'request_visible_actions' => '',
101
- 'access_type' => 'online',
102
- 'approval_prompt' => 'auto',
103
- 'federated_signon_certs_url' => 'https://www.googleapis.com/oauth2/v1/certs'
104
- ),
105
- // Set a default directory for the file cache.
106
- 'Google_Cache_File' => array(
107
- 'directory' => sys_get_temp_dir() . '/Google_Client'
108
- )
109
- )
110
- );
111
- if ($ini_file_location) {
112
- $ini = parse_ini_file($ini_file_location, true);
113
- if (is_array($ini) && count($ini)) {
114
- $merged_configuration = $ini + $this->configuration;
115
- if (isset($ini['classes']) && isset($this->configuration['classes'])) {
116
- $merged_configuration['classes'] = $ini['classes'] + $this->configuration['classes'];
117
- }
118
- $this->configuration = $merged_configuration;
119
- }
120
- }
121
- }
122
-
123
- /**
124
- * Set configuration specific to a given class.
125
- * $config->setClassConfig('Google_Cache_File',
126
- * array('directory' => '/tmp/cache'));
127
- *
128
- * @param $class string
129
- * The class name for the configuration
130
- * @param $config string
131
- * key or an array of configuration values
132
- * @param $value string
133
- * optional - if $config is a key, the value
134
- */
135
- public function setClassConfig($class, $config, $value = null)
136
- {
137
- if (! is_array($config)) {
138
- if (! isset($this->configuration['classes'][$class])) {
139
- $this->configuration['classes'][$class] = array();
140
- }
141
- $this->configuration['classes'][$class][$config] = $value;
142
- } else {
143
- $this->configuration['classes'][$class] = $config;
144
- }
145
- }
146
-
147
- public function getClassConfig($class, $key = null)
148
- {
149
- if (! isset($this->configuration['classes'][$class])) {
150
- return null;
151
- }
152
- if ($key === null) {
153
- return $this->configuration['classes'][$class];
154
- } else {
155
- return $this->configuration['classes'][$class][$key];
156
- }
157
- }
158
-
159
- /**
160
- * Return the configured cache class.
161
- *
162
- * @return string
163
- */
164
- public function getCacheClass()
165
- {
166
- return $this->configuration['cache_class'];
167
- }
168
-
169
- /**
170
- * Return the configured logger class.
171
- *
172
- * @return string
173
- */
174
- public function getLoggerClass()
175
- {
176
- return $this->configuration['logger_class'];
177
- }
178
-
179
- /**
180
- * Return the configured Auth class.
181
- *
182
- * @return string
183
- */
184
- public function getAuthClass()
185
- {
186
- return $this->configuration['auth_class'];
187
- }
188
-
189
- /**
190
- * Set the auth class.
191
- *
192
- * @param $class string
193
- * the class name to set
194
- */
195
- public function setAuthClass($class)
196
- {
197
- $prev = $this->configuration['auth_class'];
198
- if (! isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
199
- $this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
200
- }
201
- $this->configuration['auth_class'] = $class;
202
- }
203
-
204
- /**
205
- * Set the IO class.
206
- *
207
- * @param $class string
208
- * the class name to set
209
- */
210
- public function setIoClass($class)
211
- {
212
- $prev = $this->configuration['io_class'];
213
- if (! isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
214
- $this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
215
- }
216
- $this->configuration['io_class'] = $class;
217
- }
218
-
219
- /**
220
- * Set the cache class.
221
- *
222
- * @param $class string
223
- * the class name to set
224
- */
225
- public function setCacheClass($class)
226
- {
227
- $prev = $this->configuration['cache_class'];
228
- if (! isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
229
- $this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
230
- }
231
- $this->configuration['cache_class'] = $class;
232
- }
233
-
234
- /**
235
- * Set the logger class.
236
- *
237
- * @param $class string
238
- * the class name to set
239
- */
240
- public function setLoggerClass($class)
241
- {
242
- $prev = $this->configuration['logger_class'];
243
- if (! isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
244
- $this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
245
- }
246
- $this->configuration['logger_class'] = $class;
247
- }
248
-
249
- /**
250
- * Return the configured IO class.
251
- *
252
- * @return string
253
- */
254
- public function getIoClass()
255
- {
256
- return $this->configuration['io_class'];
257
- }
258
-
259
- /**
260
- * Set the application name, this is included in the User-Agent HTTP header.
261
- *
262
- * @param string $name
263
- */
264
- public function setApplicationName($name)
265
- {
266
- $this->configuration['application_name'] = $name;
267
- }
268
-
269
- /**
270
- *
271
- * @return string the name of the application
272
- */
273
- public function getApplicationName()
274
- {
275
- return $this->configuration['application_name'];
276
- }
277
-
278
- /**
279
- * Set the client ID for the auth class.
280
- *
281
- * @param $clientId string
282
- * - the API console client ID
283
- */
284
- public function setClientId($clientId)
285
- {
286
- $this->setAuthConfig('client_id', $clientId);
287
- }
288
-
289
- /**
290
- * Set the client secret for the auth class.
291
- *
292
- * @param $secret string
293
- * - the API console client secret
294
- */
295
- public function setClientSecret($secret)
296
- {
297
- $this->setAuthConfig('client_secret', $secret);
298
- }
299
-
300
- /**
301
- * Set the redirect uri for the auth class.
302
- * Note that if using the
303
- * Javascript based sign in flow, this should be the string 'postmessage'.
304
- *
305
- * @param $uri string
306
- * - the URI that users should be redirected to
307
- */
308
- public function setRedirectUri($uri)
309
- {
310
- $this->setAuthConfig('redirect_uri', $uri);
311
- }
312
-
313
- /**
314
- * Set the app activities for the auth class.
315
- *
316
- * @param $rva string
317
- * a space separated list of app activity types
318
- */
319
- public function setRequestVisibleActions($rva)
320
- {
321
- $this->setAuthConfig('request_visible_actions', $rva);
322
- }
323
-
324
- /**
325
- * Set the the access type requested (offline or online.)
326
- *
327
- * @param $access string
328
- * - the access type
329
- */
330
- public function setAccessType($access)
331
- {
332
- $this->setAuthConfig('access_type', $access);
333
- }
334
-
335
- /**
336
- * Set when to show the approval prompt (auto or force)
337
- *
338
- * @param $approval string
339
- * - the approval request
340
- */
341
- public function setApprovalPrompt($approval)
342
- {
343
- $this->setAuthConfig('approval_prompt', $approval);
344
- }
345
-
346
- /**
347
- * Set the login hint (email address or sub identifier)
348
- *
349
- * @param $hint string
350
- */
351
- public function setLoginHint($hint)
352
- {
353
- $this->setAuthConfig('login_hint', $hint);
354
- }
355
-
356
- /**
357
- * Set the developer key for the auth class.
358
- * Note that this is separate value
359
- * from the client ID - if it looks like a URL, its a client ID!
360
- *
361
- * @param $key string
362
- * - the API console developer key
363
- */
364
- public function setDeveloperKey($key)
365
- {
366
- $this->setAuthConfig('developer_key', $key);
367
- }
368
-
369
- /**
370
- * Set the hd (hosted domain) parameter streamlines the login process for
371
- * Google Apps hosted accounts.
372
- * By including the domain of the user, you
373
- * restrict sign-in to accounts at that domain.
374
- *
375
- * @param $hd string
376
- * - the domain to use.
377
- */
378
- public function setHostedDomain($hd)
379
- {
380
- $this->setAuthConfig('hd', $hd);
381
- }
382
-
383
- /**
384
- * Set the prompt hint.
385
- * Valid values are none, consent and select_account.
386
- * If no value is specified and the user has not previously authorized
387
- * access, then the user is shown a consent screen.
388
- *
389
- * @param $prompt string
390
- */
391
- public function setPrompt($prompt)
392
- {
393
- $this->setAuthConfig('prompt', $prompt);
394
- }
395
-
396
- /**
397
- * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
398
- * 2.0.
399
- * It is used in OpenID 2.0 requests to signify the URL-space for which
400
- * an authentication request is valid.
401
- *
402
- * @param $realm string
403
- * - the URL-space to use.
404
- */
405
- public function setOpenidRealm($realm)
406
- {
407
- $this->setAuthConfig('openid.realm', $realm);
408
- }
409
-
410
- /**
411
- * If this is provided with the value true, and the authorization request is
412
- * granted, the authorization will include any previous authorizations
413
- * granted to this user/application combination for other scopes.
414
- *
415
- * @param $include boolean
416
- * - the URL-space to use.
417
- */
418
- public function setIncludeGrantedScopes($include)
419
- {
420
- $this->setAuthConfig('include_granted_scopes', $include ? "true" : "false");
421
- }
422
-
423
- /**
424
- *
425
- * @return string the base URL to use for API calls
426
- */
427
- public function getBasePath()
428
- {
429
- return $this->configuration['base_path'];
430
- }
431
-
432
- /**
433
- * Set the auth configuration for the current auth class.
434
- *
435
- * @param $key -
436
- * the key to set
437
- * @param $value -
438
- * the parameter value
439
- */
440
- private function setAuthConfig($key, $value)
441
- {
442
- if (! isset($this->configuration['classes'][$this->getAuthClass()])) {
443
- $this->configuration['classes'][$this->getAuthClass()] = array();
444
- }
445
- $this->configuration['classes'][$this->getAuthClass()][$key] = $value;
446
- }
447
  }
1
+ <?php
2
+
3
+ /*
4
+ * Copyright 2010 Google Inc.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ /**
19
+ * A class to contain the library configuration for the Google API client.
20
+ */
21
+ class Google_Config
22
+ {
23
+
24
+ const GZIP_DISABLED = true;
25
+
26
+ const GZIP_ENABLED = false;
27
+
28
+ const GZIP_UPLOADS_ENABLED = true;
29
+
30
+ const GZIP_UPLOADS_DISABLED = false;
31
+
32
+ const USE_AUTO_IO_SELECTION = "auto";
33
+
34
+ protected $configuration;
35
+
36
+ /**
37
+ * Create a new Google_Config.
38
+ * Can accept an ini file location with the
39
+ * local configuration. For example:
40
+ * application_name="My App"
41
+ *
42
+ * @param
43
+ * [$ini_file_location] - optional - The location of the ini file to load
44
+ */
45
+ public function __construct($ini_file_location = null)
46
+ {
47
+ $this->configuration = array(
48
+ // The application_name is included in the User-Agent HTTP header.
49
+ 'application_name' => '',
50
+ // Which Authentication, Storage and HTTP IO classes to use.
51
+ 'auth_class' => 'Google_Auth_OAuth2',
52
+ 'io_class' => self::USE_AUTO_IO_SELECTION,
53
+ 'cache_class' => 'Google_Cache_File',
54
+ 'logger_class' => 'Google_Logger_Null',
55
+ // Don't change these unless you're working against a special development
56
+ // or testing environment.
57
+ 'base_path' => 'https://www.googleapis.com',
58
+ // Definition of class specific values, like file paths and so on.
59
+ 'classes' => array(
60
+ 'Google_IO_Abstract' => array(
61
+ 'request_timeout_seconds' => 100
62
+ ),
63
+ 'Google_Logger_Abstract' => array(
64
+ 'level' => 'debug',
65
+ 'log_format' => "[%datetime%] %level%: %message% %context%\n",
66
+ 'date_format' => 'd/M/Y:H:i:s O',
67
+ 'allow_newlines' => true
68
+ ),
69
+ 'Google_Logger_File' => array(
70
+ 'file' => 'php://stdout',
71
+ 'mode' => 0640,
72
+ 'lock' => false
73
+ ),
74
+ 'Google_Http_Request' => array(
75
+ // Disable the use of gzip on calls if set to true. Defaults to false.
76
+ 'disable_gzip' => self::GZIP_ENABLED,
77
+ // We default gzip to disabled on uploads even if gzip is otherwise
78
+ // enabled, due to some issues seen with small packet sizes for uploads.
79
+ // Please test with this option before enabling gzip for uploads in
80
+ // a production environment.
81
+ 'enable_gzip_for_uploads' => self::GZIP_UPLOADS_DISABLED
82
+ ),
83
+ // If you want to pass in OAuth 2.0 settings, they will need to be
84
+ // structured like this.
85
+ 'Google_Auth_OAuth2' => array(
86
+ // Keys for OAuth 2.0 access, see the API console at
87
+ // https://developers.google.com/console
88
+ 'client_id' => '',
89
+ 'client_secret' => '',
90
+ 'redirect_uri' => '',
91
+ // Simple API access key, also from the API console. Ensure you get
92
+ // a Server key, and not a Browser key.
93
+ 'developer_key' => '',
94
+ // Other parameters.
95
+ 'hd' => '',
96
+ 'prompt' => '',
97
+ 'openid.realm' => '',
98
+ 'include_granted_scopes' => '',
99
+ 'login_hint' => '',
100
+ 'request_visible_actions' => '',
101
+ 'access_type' => 'online',
102
+ 'approval_prompt' => 'auto',
103
+ 'federated_signon_certs_url' => 'https://www.googleapis.com/oauth2/v1/certs'
104
+ ),
105
+ // Set a default directory for the file cache.
106
+ 'Google_Cache_File' => array(
107
+ 'directory' => sys_get_temp_dir() . '/Google_Client'
108
+ )
109
+ )
110
+ );
111
+ if ($ini_file_location) {
112
+ $ini = parse_ini_file($ini_file_location, true);
113
+ if (is_array($ini) && count($ini)) {
114
+ $merged_configuration = $ini + $this->configuration;
115
+ if (isset($ini['classes']) && isset($this->configuration['classes'])) {
116
+ $merged_configuration['classes'] = $ini['classes'] + $this->configuration['classes'];
117
+ }
118
+ $this->configuration = $merged_configuration;
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Set configuration specific to a given class.
125
+ * $config->setClassConfig('Google_Cache_File',
126
+ * array('directory' => '/tmp/cache'));
127
+ *
128
+ * @param $class string
129
+ * The class name for the configuration
130
+ * @param $config string
131
+ * key or an array of configuration values
132
+ * @param $value string
133
+ * optional - if $config is a key, the value
134
+ */
135
+ public function setClassConfig($class, $config, $value = null)
136
+ {
137
+ if (! is_array($config)) {
138
+ if (! isset($this->configuration['classes'][$class])) {
139
+ $this->configuration['classes'][$class] = array();
140
+ }
141
+ $this->configuration['classes'][$class][$config] = $value;
142
+ } else {
143
+ $this->configuration['classes'][$class] = $config;
144
+ }
145
+ }
146
+
147
+ public function getClassConfig($class, $key = null)
148
+ {
149
+ if (! isset($this->configuration['classes'][$class])) {
150
+ return null;
151
+ }
152
+ if ($key === null) {
153
+ return $this->configuration['classes'][$class];
154
+ } else {
155
+ return $this->configuration['classes'][$class][$key];
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Return the configured cache class.
161
+ *
162
+ * @return string
163
+ */
164
+ public function getCacheClass()
165
+ {
166
+ return $this->configuration['cache_class'];
167
+ }
168
+
169
+ /**
170
+ * Return the configured logger class.
171
+ *
172
+ * @return string
173
+ */
174
+ public function getLoggerClass()
175
+ {
176
+ return $this->configuration['logger_class'];
177
+ }
178
+
179
+ /**
180
+ * Return the configured Auth class.
181
+ *
182
+ * @return string
183
+ */
184
+ public function getAuthClass()
185
+ {
186
+ return $this->configuration['auth_class'];
187
+ }
188
+
189
+ /**
190
+ * Set the auth class.
191
+ *
192
+ * @param $class string
193
+ * the class name to set
194
+ */
195
+ public function setAuthClass($class)
196
+ {
197
+ $prev = $this->configuration['auth_class'];
198
+ if (! isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
199
+ $this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
200
+ }
201
+ $this->configuration['auth_class'] = $class;
202
+ }
203
+
204
+ /**
205
+ * Set the IO class.
206
+ *
207
+ * @param $class string
208
+ * the class name to set
209
+ */
210
+ public function setIoClass($class)
211
+ {
212
+ $prev = $this->configuration['io_class'];
213
+ if (! isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
214
+ $this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
215
+ }
216
+ $this->configuration['io_class'] = $class;
217
+ }
218
+
219
+ /**
220
+ * Set the cache class.
221
+ *
222
+ * @param $class string
223
+ * the class name to set
224
+ */
225
+ public function setCacheClass($class)
226
+ {
227
+ $prev = $this->configuration['cache_class'];
228
+ if (! isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
229
+ $this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
230
+ }
231
+ $this->configuration['cache_class'] = $class;
232
+ }
233
+
234
+ /**
235
+ * Set the logger class.
236
+ *
237
+ * @param $class string
238
+ * the class name to set
239
+ */
240
+ public function setLoggerClass($class)
241
+ {
242
+ $prev = $this->configuration['logger_class'];
243
+ if (! isset($this->configuration['classes'][$class]) && isset($this->configuration['classes'][$prev])) {
244
+ $this->configuration['classes'][$class] = $this->configuration['classes'][$prev];
245
+ }
246
+ $this->configuration['logger_class'] = $class;
247
+ }
248
+
249
+ /**
250
+ * Return the configured IO class.
251
+ *
252
+ * @return string
253
+ */
254
+ public function getIoClass()
255
+ {
256
+ return $this->configuration['io_class'];
257
+ }
258
+
259
+ /**
260
+ * Set the application name, this is included in the User-Agent HTTP header.
261
+ *
262
+ * @param string $name
263
+ */
264
+ public function setApplicationName($name)
265
+ {
266
+ $this->configuration['application_name'] = $name;
267
+ }
268
+
269
+ /**
270
+ *
271
+ * @return string the name of the application
272
+ */
273
+ public function getApplicationName()
274
+ {
275
+ return $this->configuration['application_name'];
276
+ }
277
+
278
+ /**
279
+ * Set the client ID for the auth class.
280
+ *
281
+ * @param $clientId string
282
+ * - the API console client ID
283
+ */
284
+ public function setClientId($clientId)
285
+ {
286
+ $this->setAuthConfig('client_id', $clientId);
287
+ }
288
+
289
+ /**
290
+ * Set the client secret for the auth class.
291
+ *
292
+ * @param $secret string
293
+ * - the API console client secret
294
+ */
295
+ public function setClientSecret($secret)
296
+ {
297
+ $this->setAuthConfig('client_secret', $secret);
298
+ }
299
+
300
+ /**
301
+ * Set the redirect uri for the auth class.
302
+ * Note that if using the
303
+ * Javascript based sign in flow, this should be the string 'postmessage'.
304
+ *
305
+ * @param $uri string
306
+ * - the URI that users should be redirected to
307
+ */
308
+ public function setRedirectUri($uri)
309
+ {
310
+ $this->setAuthConfig('redirect_uri', $uri);
311
+ }
312
+
313
+ /**
314
+ * Set the app activities for the auth class.
315
+ *
316
+ * @param $rva string
317
+ * a space separated list of app activity types
318
+ */
319
+ public function setRequestVisibleActions($rva)
320
+ {
321
+ $this->setAuthConfig('request_visible_actions', $rva);
322
+ }
323
+
324
+ /**
325
+ * Set the the access type requested (offline or online.)
326
+ *
327
+ * @param $access string
328
+ * - the access type
329
+ */
330
+ public function setAccessType($access)
331
+ {
332
+ $this->setAuthConfig('access_type', $access);
333
+ }
334
+
335
+ /**
336
+ * Set when to show the approval prompt (auto or force)
337
+ *
338
+ * @param $approval string
339
+ * - the approval request
340
+ */
341
+ public function setApprovalPrompt($approval)
342
+ {
343
+ $this->setAuthConfig('approval_prompt', $approval);
344
+ }
345
+
346
+ /**
347
+ * Set the login hint (email address or sub identifier)
348
+ *
349
+ * @param $hint string
350
+ */
351
+ public function setLoginHint($hint)
352
+ {
353
+ $this->setAuthConfig('login_hint', $hint);
354
+ }
355
+
356
+ /**
357
+ * Set the developer key for the auth class.
358
+ * Note that this is separate value
359
+ * from the client ID - if it looks like a URL, its a client ID!
360
+ *
361
+ * @param $key string
362
+ * - the API console developer key
363
+ */
364
+ public function setDeveloperKey($key)
365
+ {
366
+ $this->setAuthConfig('developer_key', $key);
367
+ }
368
+
369
+ /**
370
+ * Set the hd (hosted domain) parameter streamlines the login process for
371
+ * Google Apps hosted accounts.
372
+ * By including the domain of the user, you
373
+ * restrict sign-in to accounts at that domain.
374
+ *
375
+ * @param $hd string
376
+ * - the domain to use.
377
+ */
378
+ public function setHostedDomain($hd)
379
+ {
380
+ $this->setAuthConfig('hd', $hd);
381
+ }
382
+
383
+ /**
384
+ * Set the prompt hint.
385
+ * Valid values are none, consent and select_account.
386
+ * If no value is specified and the user has not previously authorized
387
+ * access, then the user is shown a consent screen.
388
+ *
389
+ * @param $prompt string
390
+ */
391
+ public function setPrompt($prompt)
392
+ {
393
+ $this->setAuthConfig('prompt', $prompt);
394
+ }
395
+
396
+ /**
397
+ * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
398
+ * 2.0.
399
+ * It is used in OpenID 2.0 requests to signify the URL-space for which
400
+ * an authentication request is valid.
401
+ *
402
+ * @param $realm string
403
+ * - the URL-space to use.
404
+ */
405
+ public function setOpenidRealm($realm)
406
+ {
407
+ $this->setAuthConfig('openid.realm', $realm);
408
+ }
409
+
410
+ /**
411
+ * If this is provided with the value true, and the authorization request is
412
+ * granted, the authorization will include any previous authorizations
413
+ * granted to this user/application combination for other scopes.
414
+ *
415
+ * @param $include boolean
416
+ * - the URL-space to use.
417
+ */
418
+ public function setIncludeGrantedScopes($include)
419
+ {
420
+ $this->setAuthConfig('include_granted_scopes', $include ? "true" : "false");
421
+ }
422
+
423
+ /**
424
+ *
425
+ * @return string the base URL to use for API calls
426
+ */
427
+ public function getBasePath()
428
+ {
429
+ return $this->configuration['base_path'];
430
+ }
431
+
432
+ /**
433
+ * Set the auth configuration for the current auth class.
434
+ *
435
+ * @param $key -
436
+ * the key to set
437
+ * @param $value -
438
+ * the parameter value
439
+ */
440
+ private function setAuthConfig($key, $value)
441
+ {
442
+ if (! isset($this->configuration['classes'][$this->getAuthClass()])) {
443
+ $this->configuration['classes'][$this->getAuthClass()] = array();
444
+ }
445
+ $this->configuration['classes'][$this->getAuthClass()][$key] = $value;
446
+ }
447
  }
tools/src/Google/Exception.php CHANGED
@@ -1,20 +1,20 @@
1
- <?php
2
-
3
- /*
4
- * Copyright 2013 Google Inc.
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */
18
- class Google_Exception extends Exception
19
- {
20
  }
1
+ <?php
2
+
3
+ /*
4
+ * Copyright 2013 Google Inc.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ class Google_Exception extends Exception
19
+ {
20
  }
tools/src/Google/Http/Batch.php CHANGED
@@ -1,138 +1,138 @@
1
- <?php
2
- /*
3
- * Copyright 2012 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- *
21
- * @author Chirag Shah <chirags@google.com>
22
- */
23
- class Google_Http_Batch
24
- {
25
-
26
- /**
27
- *
28
- * @var string Multipart Boundary.
29
- */
30
- private $boundary;
31
-
32
- /**
33
- *
34
- * @var array service requests to be executed.
35
- */
36
- private $requests = array();
37
-
38
- /**
39
- *
40
- * @var Google_Client
41
- */
42
- private $client;
43
-
44
- private $expected_classes = array();
45
-
46
- private $base_path;
47
-
48
- public function __construct(Google_Client $client, $boundary = false)
49
- {
50
- $this->client = $client;
51
- $this->base_path = $this->client->getBasePath();
52
- $this->expected_classes = array();
53
- $boundary = (false == $boundary) ? mt_rand() : $boundary;
54
- $this->boundary = str_replace('"', '', $boundary);
55
- }
56
-
57
- public function add(Google_Http_Request $request, $key = false)
58
- {
59
- if (false == $key) {
60
- $key = mt_rand();
61
- }
62
- $this->requests[$key] = $request;
63
- }
64
-
65
- public function execute()
66
- {
67
- $body = '';
68
- /**
69
- *
70
- * @var Google_Http_Request $req
71
- */
72
- foreach ($this->requests as $key => $req) {
73
- $body .= "--{$this->boundary}\n";
74
- $body .= $req->toBatchString($key) . "\n";
75
- $this->expected_classes["response-" . $key] = $req->getExpectedClass();
76
- }
77
- $body = rtrim($body);
78
- $body .= "\n--{$this->boundary}--";
79
- $url = $this->base_path . '/batch';
80
- $httpRequest = new Google_Http_Request($url, 'POST');
81
- $httpRequest->setRequestHeaders(array(
82
- 'Content-Type' => 'multipart/mixed; boundary=' . $this->boundary
83
- ));
84
- $httpRequest->setPostBody($body);
85
- $response = $this->client->getIo()->makeRequest($httpRequest);
86
- return $this->parseResponse($response);
87
- }
88
-
89
- public function parseResponse(Google_Http_Request $response)
90
- {
91
- $contentType = $response->getResponseHeader('content-type');
92
- $contentType = explode(';', $contentType);
93
- $boundary = false;
94
- foreach ($contentType as $part) {
95
- $part = (explode('=', $part, 2));
96
- if (isset($part[0]) && 'boundary' == trim($part[0])) {
97
- $boundary = $part[1];
98
- }
99
- }
100
- $body = $response->getResponseBody();
101
- if ($body) {
102
- $body = str_replace("--$boundary--", "--$boundary", $body);
103
- $parts = explode("--$boundary", $body);
104
- $responses = array();
105
- foreach ($parts as $part) {
106
- $part = trim($part);
107
- if (! empty($part)) {
108
- list ($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
109
- $metaHeaders = $this->client->getIo()->getHttpResponseHeaders($metaHeaders);
110
- $status = substr($part, 0, strpos($part, "\n"));
111
- $status = explode(" ", $status);
112
- $status = $status[1];
113
- list ($partHeaders, $partBody) = $this->client->getIo()->ParseHttpResponse($part, false);
114
- $response = new Google_Http_Request("");
115
- $response->setResponseHttpCode($status);
116
- $response->setResponseHeaders($partHeaders);
117
- $response->setResponseBody($partBody);
118
- // Need content id.
119
- $key = $metaHeaders['content-id'];
120
- if (isset($this->expected_classes[$key]) && strlen($this->expected_classes[$key]) > 0) {
121
- $class = $this->expected_classes[$key];
122
- $response->setExpectedClass($class);
123
- }
124
- try {
125
- $response = Google_Http_REST::decodeHttpResponse($response, $this->client);
126
- $responses[$key] = $response;
127
- } catch (Google_Service_Exception $e) {
128
- // Store the exception as the response, so successful responses
129
- // can be processed.
130
- $responses[$key] = $e;
131
- }
132
- }
133
- }
134
- return $responses;
135
- }
136
- return null;
137
- }
138
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2012 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ *
21
+ * @author Chirag Shah <chirags@google.com>
22
+ */
23
+ class Google_Http_Batch
24
+ {
25
+
26
+ /**
27
+ *
28
+ * @var string Multipart Boundary.
29
+ */
30
+ private $boundary;
31
+
32
+ /**
33
+ *
34
+ * @var array service requests to be executed.
35
+ */
36
+ private $requests = array();
37
+
38
+ /**
39
+ *
40
+ * @var Google_Client
41
+ */
42
+ private $client;
43
+
44
+ private $expected_classes = array();
45
+
46
+ private $base_path;
47
+
48
+ public function __construct(Google_Client $client, $boundary = false)
49
+ {
50
+ $this->client = $client;
51
+ $this->base_path = $this->client->getBasePath();
52
+ $this->expected_classes = array();
53
+ $boundary = (false == $boundary) ? mt_rand() : $boundary;
54
+ $this->boundary = str_replace('"', '', $boundary);
55
+ }
56
+
57
+ public function add(Google_Http_Request $request, $key = false)
58
+ {
59
+ if (false == $key) {
60
+ $key = mt_rand();
61
+ }
62
+ $this->requests[$key] = $request;
63
+ }
64
+
65
+ public function execute()
66
+ {
67
+ $body = '';
68
+ /**
69
+ *
70
+ * @var Google_Http_Request $req
71
+ */
72
+ foreach ($this->requests as $key => $req) {
73
+ $body .= "--{$this->boundary}\n";
74
+ $body .= $req->toBatchString($key) . "\n";
75
+ $this->expected_classes["response-" . $key] = $req->getExpectedClass();
76
+ }
77
+ $body = rtrim($body);
78
+ $body .= "\n--{$this->boundary}--";
79
+ $url = $this->base_path . '/batch';
80
+ $httpRequest = new Google_Http_Request($url, 'POST');
81
+ $httpRequest->setRequestHeaders(array(
82
+ 'Content-Type' => 'multipart/mixed; boundary=' . $this->boundary
83
+ ));
84
+ $httpRequest->setPostBody($body);
85
+ $response = $this->client->getIo()->makeRequest($httpRequest);
86
+ return $this->parseResponse($response);
87
+ }
88
+
89
+ public function parseResponse(Google_Http_Request $response)
90
+ {
91
+ $contentType = $response->getResponseHeader('content-type');
92
+ $contentType = explode(';', $contentType);
93
+ $boundary = false;
94
+ foreach ($contentType as $part) {
95
+ $part = (explode('=', $part, 2));
96
+ if (isset($part[0]) && 'boundary' == trim($part[0])) {
97
+ $boundary = $part[1];
98
+ }
99
+ }
100
+ $body = $response->getResponseBody();
101
+ if ($body) {
102
+ $body = str_replace("--$boundary--", "--$boundary", $body);
103
+ $parts = explode("--$boundary", $body);
104
+ $responses = array();
105
+ foreach ($parts as $part) {
106
+ $part = trim($part);
107
+ if (! empty($part)) {
108
+ list ($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
109
+ $metaHeaders = $this->client->getIo()->getHttpResponseHeaders($metaHeaders);
110
+ $status = substr($part, 0, strpos($part, "\n"));
111
+ $status = explode(" ", $status);
112
+ $status = $status[1];
113
+ list ($partHeaders, $partBody) = $this->client->getIo()->ParseHttpResponse($part, false);
114
+ $response = new Google_Http_Request("");
115
+ $response->setResponseHttpCode($status);
116
+ $response->setResponseHeaders($partHeaders);
117
+ $response->setResponseBody($partBody);
118
+ // Need content id.
119
+ $key = $metaHeaders['content-id'];
120
+ if (isset($this->expected_classes[$key]) && strlen($this->expected_classes[$key]) > 0) {
121
+ $class = $this->expected_classes[$key];
122
+ $response->setExpectedClass($class);
123
+ }
124
+ try {
125
+ $response = Google_Http_REST::decodeHttpResponse($response, $this->client);
126
+ $responses[$key] = $response;
127
+ } catch (Google_Service_Exception $e) {
128
+ // Store the exception as the response, so successful responses
129
+ // can be processed.
130
+ $responses[$key] = $e;
131
+ }
132
+ }
133
+ }
134
+ return $responses;
135
+ }
136
+ return null;
137
+ }
138
  }
tools/src/Google/Http/CacheParser.php CHANGED
@@ -1,182 +1,182 @@
1
- <?php
2
- /*
3
- * Copyright 2012 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * Implement the caching directives specified in rfc2616.
21
- * This
22
- * implementation is guided by the guidance offered in rfc2616-sec13.
23
- *
24
- * @author Chirag Shah <chirags@google.com>
25
- */
26
- class Google_Http_CacheParser
27
- {
28
-
29
- public static $CACHEABLE_HTTP_METHODS = array(
30
- 'GET',
31
- 'HEAD'
32
- );
33
-
34
- public static $CACHEABLE_STATUS_CODES = array(
35
- '200',
36
- '203',
37
- '300',
38
- '301'
39
- );
40
-
41
- /**
42
- * Check if an HTTP request can be cached by a private local cache.
43
- *
44
- * @static
45
- *
46
- * @param Google_Http_Request $resp
47
- * @return bool True if the request is cacheable.
48
- * False if the request is uncacheable.
49
- */
50
- public static function isRequestCacheable(Google_Http_Request $resp)
51
- {
52
- $method = $resp->getRequestMethod();
53
- if (! in_array($method, self::$CACHEABLE_HTTP_METHODS)) {
54
- return false;
55
- }
56
- // Don't cache authorized requests/responses.
57
- // [rfc2616-14.8] When a shared cache receives a request containing an
58
- // Authorization field, it MUST NOT return the corresponding response
59
- // as a reply to any other request...
60
- if ($resp->getRequestHeader("authorization")) {
61
- return false;
62
- }
63
- return true;
64
- }
65
-
66
- /**
67
- * Check if an HTTP response can be cached by a private local cache.
68
- *
69
- * @static
70
- *
71
- * @param Google_Http_Request $resp
72
- * @return bool True if the response is cacheable.
73
- * False if the response is un-cacheable.
74
- */
75
- public static function isResponseCacheable(Google_Http_Request $resp)
76
- {
77
- // First, check if the HTTP request was cacheable before inspecting the
78
- // HTTP response.
79
- if (false == self::isRequestCacheable($resp)) {
80
- return false;
81
- }
82
- $code = $resp->getResponseHttpCode();
83
- if (! in_array($code, self::$CACHEABLE_STATUS_CODES)) {
84
- return false;
85
- }
86
- // The resource is uncacheable if the resource is already expired and
87
- // the resource doesn't have an ETag for revalidation.
88
- $etag = $resp->getResponseHeader("etag");
89
- if (self::isExpired($resp) && $etag == false) {
90
- return false;
91
- }
92
- // [rfc2616-14.9.2] If [no-store is] sent in a response, a cache MUST NOT
93
- // store any part of either this response or the request that elicited it.
94
- $cacheControl = $resp->getParsedCacheControl();
95
- if (isset($cacheControl['no-store'])) {
96
- return false;
97
- }
98
- // Pragma: no-cache is an http request directive, but is occasionally
99
- // used as a response header incorrectly.
100
- $pragma = $resp->getResponseHeader('pragma');
101
- if ($pragma == 'no-cache' || strpos($pragma, 'no-cache') !== false) {
102
- return false;
103
- }
104
- // [rfc2616-14.44] Vary: * is extremely difficult to cache. "It implies that
105
- // a cache cannot determine from the request headers of a subsequent request
106
- // whether this response is the appropriate representation."
107
- // Given this, we deem responses with the Vary header as uncacheable.
108
- $vary = $resp->getResponseHeader('vary');
109
- if ($vary) {
110
- return false;
111
- }
112
- return true;
113
- }
114
-
115
- /**
116
- *
117
- * @static
118
- *
119
- * @param Google_Http_Request $resp
120
- * @return bool True if the HTTP response is considered to be expired.
121
- * False if it is considered to be fresh.
122
- */
123
- public static function isExpired(Google_Http_Request $resp)
124
- {
125
- // HTTP/1.1 clients and caches MUST treat other invalid date formats,
126
- // especially including the value “0”, as in the past.
127
- $parsedExpires = false;
128
- $responseHeaders = $resp->getResponseHeaders();
129
- if (isset($responseHeaders['expires'])) {
130
- $rawExpires = $responseHeaders['expires'];
131
- // Check for a malformed expires header first.
132
- if (empty($rawExpires) || (is_numeric($rawExpires) && $rawExpires <= 0)) {
133
- return true;
134
- }
135
- // See if we can parse the expires header.
136
- $parsedExpires = strtotime($rawExpires);
137
- if (false == $parsedExpires || $parsedExpires <= 0) {
138
- return true;
139
- }
140
- }
141
- // Calculate the freshness of an http response.
142
- $freshnessLifetime = false;
143
- $cacheControl = $resp->getParsedCacheControl();
144
- if (isset($cacheControl['max-age'])) {
145
- $freshnessLifetime = $cacheControl['max-age'];
146
- }
147
- $rawDate = $resp->getResponseHeader('date');
148
- $parsedDate = strtotime($rawDate);
149
- if (empty($rawDate) || false == $parsedDate) {
150
- // We can't default this to now, as that means future cache reads
151
- // will always pass with the logic below, so we will require a
152
- // date be injected if not supplied.
153
- throw new Google_Exception("All cacheable requests must have creation dates.");
154
- }
155
- if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
156
- $freshnessLifetime = $parsedExpires - $parsedDate;
157
- }
158
- if (false == $freshnessLifetime) {
159
- return true;
160
- }
161
- // Calculate the age of an http response.
162
- $age = max(0, time() - $parsedDate);
163
- if (isset($responseHeaders['age'])) {
164
- $age = max($age, strtotime($responseHeaders['age']));
165
- }
166
- return $freshnessLifetime <= $age;
167
- }
168
-
169
- /**
170
- * Determine if a cache entry should be revalidated with by the origin.
171
- *
172
- * @param Google_Http_Request $response
173
- * @return bool True if the entry is expired, else return false.
174
- */
175
- public static function mustRevalidate(Google_Http_Request $response)
176
- {
177
- // [13.3] When a cache has a stale entry that it would like to use as a
178
- // response to a client's request, it first has to check with the origin
179
- // server to see if its cached entry is still usable.
180
- return self::isExpired($response);
181
- }
182
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2012 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * Implement the caching directives specified in rfc2616.
21
+ * This
22
+ * implementation is guided by the guidance offered in rfc2616-sec13.
23
+ *
24
+ * @author Chirag Shah <chirags@google.com>
25
+ */
26
+ class Google_Http_CacheParser
27
+ {
28
+
29
+ public static $CACHEABLE_HTTP_METHODS = array(
30
+ 'GET',
31
+ 'HEAD'
32
+ );
33
+
34
+ public static $CACHEABLE_STATUS_CODES = array(
35
+ '200',
36
+ '203',
37
+ '300',
38
+ '301'
39
+ );
40
+
41
+ /**
42
+ * Check if an HTTP request can be cached by a private local cache.
43
+ *
44
+ * @static
45
+ *
46
+ * @param Google_Http_Request $resp
47
+ * @return bool True if the request is cacheable.
48
+ * False if the request is uncacheable.
49
+ */
50
+ public static function isRequestCacheable(Google_Http_Request $resp)
51
+ {
52
+ $method = $resp->getRequestMethod();
53
+ if (! in_array($method, self::$CACHEABLE_HTTP_METHODS)) {
54
+ return false;
55
+ }
56
+ // Don't cache authorized requests/responses.
57
+ // [rfc2616-14.8] When a shared cache receives a request containing an
58
+ // Authorization field, it MUST NOT return the corresponding response
59
+ // as a reply to any other request...
60
+ if ($resp->getRequestHeader("authorization")) {
61
+ return false;
62
+ }
63
+ return true;
64
+ }
65
+
66
+ /**
67
+ * Check if an HTTP response can be cached by a private local cache.
68
+ *
69
+ * @static
70
+ *
71
+ * @param Google_Http_Request $resp
72
+ * @return bool True if the response is cacheable.
73
+ * False if the response is un-cacheable.
74
+ */
75
+ public static function isResponseCacheable(Google_Http_Request $resp)
76
+ {
77
+ // First, check if the HTTP request was cacheable before inspecting the
78
+ // HTTP response.
79
+ if (false == self::isRequestCacheable($resp)) {
80
+ return false;
81
+ }
82
+ $code = $resp->getResponseHttpCode();
83
+ if (! in_array($code, self::$CACHEABLE_STATUS_CODES)) {
84
+ return false;
85
+ }
86
+ // The resource is uncacheable if the resource is already expired and
87
+ // the resource doesn't have an ETag for revalidation.
88
+ $etag = $resp->getResponseHeader("etag");
89
+ if (self::isExpired($resp) && $etag == false) {
90
+ return false;
91
+ }
92
+ // [rfc2616-14.9.2] If [no-store is] sent in a response, a cache MUST NOT
93
+ // store any part of either this response or the request that elicited it.
94
+ $cacheControl = $resp->getParsedCacheControl();
95
+ if (isset($cacheControl['no-store'])) {
96
+ return false;
97
+ }
98
+ // Pragma: no-cache is an http request directive, but is occasionally
99
+ // used as a response header incorrectly.
100
+ $pragma = $resp->getResponseHeader('pragma');
101
+ if ($pragma == 'no-cache' || strpos($pragma, 'no-cache') !== false) {
102
+ return false;
103
+ }
104
+ // [rfc2616-14.44] Vary: * is extremely difficult to cache. "It implies that
105
+ // a cache cannot determine from the request headers of a subsequent request
106
+ // whether this response is the appropriate representation."
107
+ // Given this, we deem responses with the Vary header as uncacheable.
108
+ $vary = $resp->getResponseHeader('vary');
109
+ if ($vary) {
110
+ return false;
111
+ }
112
+ return true;
113
+ }
114
+
115
+ /**
116
+ *
117
+ * @static
118
+ *
119
+ * @param Google_Http_Request $resp
120
+ * @return bool True if the HTTP response is considered to be expired.
121
+ * False if it is considered to be fresh.
122
+ */
123
+ public static function isExpired(Google_Http_Request $resp)
124
+ {
125
+ // HTTP/1.1 clients and caches MUST treat other invalid date formats,
126
+ // especially including the value “0”, as in the past.
127
+ $parsedExpires = false;
128
+ $responseHeaders = $resp->getResponseHeaders();
129
+ if (isset($responseHeaders['expires'])) {
130
+ $rawExpires = $responseHeaders['expires'];
131
+ // Check for a malformed expires header first.
132
+ if (empty($rawExpires) || (is_numeric($rawExpires) && $rawExpires <= 0)) {
133
+ return true;
134
+ }
135
+ // See if we can parse the expires header.
136
+ $parsedExpires = strtotime($rawExpires);
137
+ if (false == $parsedExpires || $parsedExpires <= 0) {
138
+ return true;
139
+ }
140
+ }
141
+ // Calculate the freshness of an http response.
142
+ $freshnessLifetime = false;
143
+ $cacheControl = $resp->getParsedCacheControl();
144
+ if (isset($cacheControl['max-age'])) {
145
+ $freshnessLifetime = $cacheControl['max-age'];
146
+ }
147
+ $rawDate = $resp->getResponseHeader('date');
148
+ $parsedDate = strtotime($rawDate);
149
+ if (empty($rawDate) || false == $parsedDate) {
150
+ // We can't default this to now, as that means future cache reads
151
+ // will always pass with the logic below, so we will require a
152
+ // date be injected if not supplied.
153
+ throw new Google_Exception("All cacheable requests must have creation dates.");
154
+ }
155
+ if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
156
+ $freshnessLifetime = $parsedExpires - $parsedDate;
157
+ }
158
+ if (false == $freshnessLifetime) {
159
+ return true;
160
+ }
161
+ // Calculate the age of an http response.
162
+ $age = max(0, time() - $parsedDate);
163
+ if (isset($responseHeaders['age'])) {
164
+ $age = max($age, strtotime($responseHeaders['age']));
165
+ }
166
+ return $freshnessLifetime <= $age;
167
+ }
168
+
169
+ /**
170
+ * Determine if a cache entry should be revalidated with by the origin.
171
+ *
172
+ * @param Google_Http_Request $response
173
+ * @return bool True if the entry is expired, else return false.
174
+ */
175
+ public static function mustRevalidate(Google_Http_Request $response)
176
+ {
177
+ // [13.3] When a cache has a stale entry that it would like to use as a
178
+ // response to a client's request, it first has to check with the origin
179
+ // server to see if its cached entry is still usable.
180
+ return self::isExpired($response);
181
+ }
182
  }
tools/src/Google/Http/MediaFileUpload.php CHANGED
@@ -1,315 +1,315 @@
1
- <?php
2
- /**
3
- * Copyright 2012 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- *
21
- * @author Chirag Shah <chirags@google.com>
22
- *
23
- */
24
- class Google_Http_MediaFileUpload
25
- {
26
-
27
- const UPLOAD_MEDIA_TYPE = 'media';
28
-
29
- const UPLOAD_MULTIPART_TYPE = 'multipart';
30
-
31
- const UPLOAD_RESUMABLE_TYPE = 'resumable';
32
-
33
- /**
34
- *
35
- * @var string $mimeType
36
- */
37
- private $mimeType;
38
-
39
- /**
40
- *
41
- * @var string $data
42
- */
43
- private $data;
44
-
45
- /**
46
- *
47
- * @var bool $resumable
48
- */
49
- private $resumable;
50
-
51
- /**
52
- *
53
- * @var int $chunkSize
54
- */
55
- private $chunkSize;
56
-
57
- /**
58
- *
59
- * @var int $size
60
- */
61
- private $size;
62
-
63
- /**
64
- *
65
- * @var string $resumeUri
66
- */
67
- private $resumeUri;
68
-
69
- /**
70
- *
71
- * @var int $progress
72
- */
73
- private $progress;
74
-
75
- /**
76
- *
77
- * @var Google_Client
78
- */
79
- private $client;
80
-
81
- /**
82
- *
83
- * @var Google_Http_Request
84
- */
85
- private $request;
86
-
87
- /**
88
- *
89
- * @var string
90
- */
91
- private $boundary;
92
-
93
- /**
94
- * Result code from last HTTP call
95
- *
96
- * @var int
97
- */
98
- private $httpResultCode;
99
-
100
- /**
101
- *
102
- * @param $mimeType string
103
- * @param $data string
104
- * The bytes you want to upload.
105
- * @param $resumable bool
106
- * @param bool $chunkSize
107
- * File will be uploaded in chunks of this many bytes.
108
- * only used if resumable=True
109
- */
110
- public function __construct(Google_Client $client, Google_Http_Request $request, $mimeType, $data, $resumable = false, $chunkSize = false, $boundary = false)
111
- {
112
- $this->client = $client;
113
- $this->request = $request;
114
- $this->mimeType = $mimeType;
115
- $this->data = $data;
116
- $this->size = strlen($this->data);
117
- $this->resumable = $resumable;
118
- if (! $chunkSize) {
119
- $chunkSize = 256 * 1024;
120
- }
121
- $this->chunkSize = $chunkSize;
122
- $this->progress = 0;
123
- $this->boundary = $boundary;
124
- // Process Media Request
125
- $this->process();
126
- }
127
-
128
- /**
129
- * Set the size of the file that is being uploaded.
130
- *
131
- * @param $size -
132
- * int file size in bytes
133
- */
134
- public function setFileSize($size)
135
- {
136
- $this->size = $size;
137
- }
138
-
139
- /**
140
- * Return the progress on the upload
141
- *
142
- * @return int progress in bytes uploaded.
143
- */
144
- public function getProgress()
145
- {
146
- return $this->progress;
147
- }
148
-
149
- /**
150
- * Return the HTTP result code from the last call made.
151
- *
152
- * @return int code
153
- */
154
- public function getHttpResultCode()
155
- {
156
- return $this->httpResultCode;
157
- }
158
-
159
- /**
160
- * Send the next part of the file to upload.
161
- *
162
- * @param
163
- * [$chunk] the next set of bytes to send. If false will used $data passed
164
- * at construct time.
165
- */
166
- public function nextChunk($chunk = false)
167
- {
168
- if (false == $this->resumeUri) {
169
- $this->resumeUri = $this->getResumeUri();
170
- }
171
- if (false == $chunk) {
172
- $chunk = substr($this->data, $this->progress, $this->chunkSize);
173
- }
174
- $lastBytePos = $this->progress + strlen($chunk) - 1;
175
- $headers = array(
176
- 'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
177
- 'content-type' => $this->request->getRequestHeader('content-type'),
178
- 'content-length' => $this->chunkSize,
179
- 'expect' => ''
180
- );
181
- $httpRequest = new Google_Http_Request($this->resumeUri, 'PUT', $headers, $chunk);
182
- if ($this->client->getClassConfig("Google_Http_Request", "enable_gzip_for_uploads")) {
183
- $httpRequest->enableGzip();
184
- } else {
185
- $httpRequest->disableGzip();
186
- }
187
- $response = $this->client->getIo()->makeRequest($httpRequest);
188
- $response->setExpectedClass($this->request->getExpectedClass());
189
- $code = $response->getResponseHttpCode();
190
- $this->httpResultCode = $code;
191
- if (308 == $code) {
192
- // Track the amount uploaded.
193
- $range = explode('-', $response->getResponseHeader('range'));
194
- $this->progress = $range[1] + 1;
195
- // Allow for changing upload URLs.
196
- $location = $response->getResponseHeader('location');
197
- if ($location) {
198
- $this->resumeUri = $location;
199
- }
200
- // No problems, but upload not complete.
201
- return false;
202
- } else {
203
- return Google_Http_REST::decodeHttpResponse($response, $this->client);
204
- }
205
- }
206
-
207
- /**
208
- *
209
- * @param
210
- * $meta
211
- * @param
212
- * $params
213
- * @return array|bool @visible for testing
214
- */
215
- private function process()
216
- {
217
- $postBody = false;
218
- $contentType = false;
219
- $meta = $this->request->getPostBody();
220
- $meta = is_string($meta) ? json_decode($meta, true) : $meta;
221
- $uploadType = $this->getUploadType($meta);
222
- $this->request->setQueryParam('uploadType', $uploadType);
223
- $this->transformToUploadUrl();
224
- $mimeType = $this->mimeType ? $this->mimeType : $this->request->getRequestHeader('content-type');
225
- if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
226
- $contentType = $mimeType;
227
- $postBody = is_string($meta) ? $meta : json_encode($meta);
228
- } else
229
- if (self::UPLOAD_MEDIA_TYPE == $uploadType) {
230
- $contentType = $mimeType;
231
- $postBody = $this->data;
232
- } else
233
- if (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
234
- // This is a multipart/related upload.
235
- $boundary = $this->boundary ? $this->boundary : mt_rand();
236
- $boundary = str_replace('"', '', $boundary);
237
- $contentType = 'multipart/related; boundary=' . $boundary;
238
- $related = "--$boundary\r\n";
239
- $related .= "Content-Type: application/json; charset=UTF-8\r\n";
240
- $related .= "\r\n" . json_encode($meta) . "\r\n";
241
- $related .= "--$boundary\r\n";
242
- $related .= "Content-Type: $mimeType\r\n";
243
- $related .= "Content-Transfer-Encoding: base64\r\n";
244
- $related .= "\r\n" . base64_encode($this->data) . "\r\n";
245
- $related .= "--$boundary--";
246
- $postBody = $related;
247
- }
248
- $this->request->setPostBody($postBody);
249
- if (isset($contentType) && $contentType) {
250
- $contentTypeHeader['content-type'] = $contentType;
251
- $this->request->setRequestHeaders($contentTypeHeader);
252
- }
253
- }
254
-
255
- private function transformToUploadUrl()
256
- {
257
- $base = $this->request->getBaseComponent();
258
- $this->request->setBaseComponent($base . '/upload');
259
- }
260
-
261
- /**
262
- * Valid upload types:
263
- * - resumable (UPLOAD_RESUMABLE_TYPE)
264
- * - media (UPLOAD_MEDIA_TYPE)
265
- * - multipart (UPLOAD_MULTIPART_TYPE)
266
- *
267
- * @param
268
- * $meta
269
- * @return string @visible for testing
270
- */
271
- public function getUploadType($meta)
272
- {
273
- if ($this->resumable) {
274
- return self::UPLOAD_RESUMABLE_TYPE;
275
- }
276
- if (false == $meta && $this->data) {
277
- return self::UPLOAD_MEDIA_TYPE;
278
- }
279
- return self::UPLOAD_MULTIPART_TYPE;
280
- }
281
-
282
- private function getResumeUri()
283
- {
284
- $result = null;
285
- $body = $this->request->getPostBody();
286
- if ($body) {
287
- $headers = array(
288
- 'content-type' => 'application/json; charset=UTF-8',
289
- 'content-length' => Google_Utils::getStrLen($body),
290
- 'x-upload-content-type' => $this->mimeType,
291
- 'x-upload-content-length' => $this->size,
292
- 'expect' => ''
293
- );
294
- $this->request->setRequestHeaders($headers);
295
- }
296
- $response = $this->client->getIo()->makeRequest($this->request);
297
- $location = $response->getResponseHeader('location');
298
- $code = $response->getResponseHttpCode();
299
- if (200 == $code && true == $location) {
300
- return $location;
301
- }
302
- $message = $code;
303
- $body = @json_decode($response->getResponseBody());
304
- if (! empty($body->error->errors)) {
305
- $message .= ': ';
306
- foreach ($body->error->errors as $error) {
307
- $message .= "{$error->domain}, {$error->message};";
308
- }
309
- $message = rtrim($message, ';');
310
- }
311
- $error = "Failed to start the resumable upload (HTTP {$message})";
312
- $this->client->getLogger()->error($error);
313
- throw new Google_Exception($error);
314
- }
315
  }
1
+ <?php
2
+ /**
3
+ * Copyright 2012 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ *
21
+ * @author Chirag Shah <chirags@google.com>
22
+ *
23
+ */
24
+ class Google_Http_MediaFileUpload
25
+ {
26
+
27
+ const UPLOAD_MEDIA_TYPE = 'media';
28
+
29
+ const UPLOAD_MULTIPART_TYPE = 'multipart';
30
+
31
+ const UPLOAD_RESUMABLE_TYPE = 'resumable';
32
+
33
+ /**
34
+ *
35
+ * @var string $mimeType
36
+ */
37
+ private $mimeType;
38
+
39
+ /**
40
+ *
41
+ * @var string $data
42
+ */
43
+ private $data;
44
+
45
+ /**
46
+ *
47
+ * @var bool $resumable
48
+ */
49
+ private $resumable;
50
+
51
+ /**
52
+ *
53
+ * @var int $chunkSize
54
+ */
55
+ private $chunkSize;
56
+
57
+ /**
58
+ *
59
+ * @var int $size
60
+ */
61
+ private $size;
62
+
63
+ /**
64
+ *
65
+ * @var string $resumeUri
66
+ */
67
+ private $resumeUri;
68
+
69
+ /**
70
+ *
71
+ * @var int $progress
72
+ */
73
+ private $progress;
74
+
75
+ /**
76
+ *
77
+ * @var Google_Client
78
+ */
79
+ private $client;
80
+
81
+ /**
82
+ *
83
+ * @var Google_Http_Request
84
+ */
85
+ private $request;
86
+
87
+ /**
88
+ *
89
+ * @var string
90
+ */
91
+ private $boundary;
92
+
93
+ /**
94
+ * Result code from last HTTP call
95
+ *
96
+ * @var int
97
+ */
98
+ private $httpResultCode;
99
+
100
+ /**
101
+ *
102
+ * @param $mimeType string
103
+ * @param $data string
104
+ * The bytes you want to upload.
105
+ * @param $resumable bool
106
+ * @param bool $chunkSize
107
+ * File will be uploaded in chunks of this many bytes.
108
+ * only used if resumable=True
109
+ */
110
+ public function __construct(Google_Client $client, Google_Http_Request $request, $mimeType, $data, $resumable = false, $chunkSize = false, $boundary = false)
111
+ {
112
+ $this->client = $client;
113
+ $this->request = $request;
114
+ $this->mimeType = $mimeType;
115
+ $this->data = $data;
116
+ $this->size = strlen($this->data);
117
+ $this->resumable = $resumable;
118
+ if (! $chunkSize) {
119
+ $chunkSize = 256 * 1024;
120
+ }
121
+ $this->chunkSize = $chunkSize;
122
+ $this->progress = 0;
123
+ $this->boundary = $boundary;
124
+ // Process Media Request
125
+ $this->process();
126
+ }
127
+
128
+ /**
129
+ * Set the size of the file that is being uploaded.
130
+ *
131
+ * @param $size -
132
+ * int file size in bytes
133
+ */
134
+ public function setFileSize($size)
135
+ {
136
+ $this->size = $size;
137
+ }
138
+
139
+ /**
140
+ * Return the progress on the upload
141
+ *
142
+ * @return int progress in bytes uploaded.
143
+ */
144
+ public function getProgress()
145
+ {
146
+ return $this->progress;
147
+ }
148
+
149
+ /**
150
+ * Return the HTTP result code from the last call made.
151
+ *
152
+ * @return int code
153
+ */
154
+ public function getHttpResultCode()
155
+ {
156
+ return $this->httpResultCode;
157
+ }
158
+
159
+ /**
160
+ * Send the next part of the file to upload.
161
+ *
162
+ * @param
163
+ * [$chunk] the next set of bytes to send. If false will used $data passed
164
+ * at construct time.
165
+ */
166
+ public function nextChunk($chunk = false)
167
+ {
168
+ if (false == $this->resumeUri) {
169
+ $this->resumeUri = $this->getResumeUri();
170
+ }
171
+ if (false == $chunk) {
172
+ $chunk = substr($this->data, $this->progress, $this->chunkSize);
173
+ }
174
+ $lastBytePos = $this->progress + strlen($chunk) - 1;
175
+ $headers = array(
176
+ 'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
177
+ 'content-type' => $this->request->getRequestHeader('content-type'),
178
+ 'content-length' => $this->chunkSize,
179
+ 'expect' => ''
180
+ );
181
+ $httpRequest = new Google_Http_Request($this->resumeUri, 'PUT', $headers, $chunk);
182
+ if ($this->client->getClassConfig("Google_Http_Request", "enable_gzip_for_uploads")) {
183
+ $httpRequest->enableGzip();
184
+ } else {
185
+ $httpRequest->disableGzip();
186
+ }
187
+ $response = $this->client->getIo()->makeRequest($httpRequest);
188
+ $response->setExpectedClass($this->request->getExpectedClass());
189
+ $code = $response->getResponseHttpCode();
190
+ $this->httpResultCode = $code;
191
+ if (308 == $code) {
192
+ // Track the amount uploaded.
193
+ $range = explode('-', $response->getResponseHeader('range'));
194
+ $this->progress = $range[1] + 1;
195
+ // Allow for changing upload URLs.
196
+ $location = $response->getResponseHeader('location');
197
+ if ($location) {
198
+ $this->resumeUri = $location;
199
+ }
200
+ // No problems, but upload not complete.
201
+ return false;
202
+ } else {
203
+ return Google_Http_REST::decodeHttpResponse($response, $this->client);
204
+ }
205
+ }
206
+
207
+ /**
208
+ *
209
+ * @param
210
+ * $meta
211
+ * @param
212
+ * $params
213
+ * @return array|bool @visible for testing
214
+ */
215
+ private function process()
216
+ {
217
+ $postBody = false;
218
+ $contentType = false;
219
+ $meta = $this->request->getPostBody();
220
+ $meta = is_string($meta) ? json_decode($meta, true) : $meta;
221
+ $uploadType = $this->getUploadType($meta);
222
+ $this->request->setQueryParam('uploadType', $uploadType);
223
+ $this->transformToUploadUrl();
224
+ $mimeType = $this->mimeType ? $this->mimeType : $this->request->getRequestHeader('content-type');
225
+ if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
226
+ $contentType = $mimeType;
227
+ $postBody = is_string($meta) ? $meta : json_encode($meta);
228
+ } else
229
+ if (self::UPLOAD_MEDIA_TYPE == $uploadType) {
230
+ $contentType = $mimeType;
231
+ $postBody = $this->data;
232
+ } else
233
+ if (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
234
+ // This is a multipart/related upload.
235
+ $boundary = $this->boundary ? $this->boundary : mt_rand();
236
+ $boundary = str_replace('"', '', $boundary);
237
+ $contentType = 'multipart/related; boundary=' . $boundary;
238
+ $related = "--$boundary\r\n";
239
+ $related .= "Content-Type: application/json; charset=UTF-8\r\n";
240
+ $related .= "\r\n" . json_encode($meta) . "\r\n";
241
+ $related .= "--$boundary\r\n";
242
+ $related .= "Content-Type: $mimeType\r\n";
243
+ $related .= "Content-Transfer-Encoding: base64\r\n";
244
+ $related .= "\r\n" . base64_encode($this->data) . "\r\n";
245
+ $related .= "--$boundary--";
246
+ $postBody = $related;
247
+ }
248
+ $this->request->setPostBody($postBody);
249
+ if (isset($contentType) && $contentType) {
250
+ $contentTypeHeader['content-type'] = $contentType;
251
+ $this->request->setRequestHeaders($contentTypeHeader);
252
+ }
253
+ }
254
+
255
+ private function transformToUploadUrl()
256
+ {
257
+ $base = $this->request->getBaseComponent();
258
+ $this->request->setBaseComponent($base . '/upload');
259
+ }
260
+
261
+ /**
262
+ * Valid upload types:
263
+ * - resumable (UPLOAD_RESUMABLE_TYPE)
264
+ * - media (UPLOAD_MEDIA_TYPE)
265
+ * - multipart (UPLOAD_MULTIPART_TYPE)
266
+ *
267
+ * @param
268
+ * $meta
269
+ * @return string @visible for testing
270
+ */
271
+ public function getUploadType($meta)
272
+ {
273
+ if ($this->resumable) {
274
+ return self::UPLOAD_RESUMABLE_TYPE;
275
+ }
276
+ if (false == $meta && $this->data) {
277
+ return self::UPLOAD_MEDIA_TYPE;
278
+ }
279
+ return self::UPLOAD_MULTIPART_TYPE;
280
+ }
281
+
282
+ private function getResumeUri()
283
+ {
284
+ $result = null;
285
+ $body = $this->request->getPostBody();
286
+ if ($body) {
287
+ $headers = array(
288
+ 'content-type' => 'application/json; charset=UTF-8',
289
+ 'content-length' => Google_Utils::getStrLen($body),
290
+ 'x-upload-content-type' => $this->mimeType,
291
+ 'x-upload-content-length' => $this->size,
292
+ 'expect' => ''
293
+ );
294
+ $this->request->setRequestHeaders($headers);
295
+ }
296
+ $response = $this->client->getIo()->makeRequest($this->request);
297
+ $location = $response->getResponseHeader('location');
298
+ $code = $response->getResponseHttpCode();
299
+ if (200 == $code && true == $location) {
300
+ return $location;
301
+ }
302
+ $message = $code;
303
+ $body = @json_decode($response->getResponseBody());
304
+ if (! empty($body->error->errors)) {
305
+ $message .= ': ';
306
+ foreach ($body->error->errors as $error) {
307
+ $message .= "{$error->domain}, {$error->message};";
308
+ }
309
+ $message = rtrim($message, ';');
310
+ }
311
+ $error = "Failed to start the resumable upload (HTTP {$message})";
312
+ $this->client->getLogger()->error($error);
313
+ throw new Google_Exception($error);
314
+ }
315
  }
tools/src/Google/Http/REST.php CHANGED
@@ -1,143 +1,143 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * This class implements the RESTful transport of apiServiceRequest()'s
21
- *
22
- * @author Chris Chabot <chabotc@google.com>
23
- * @author Chirag Shah <chirags@google.com>
24
- */
25
- class Google_Http_REST
26
- {
27
-
28
- /**
29
- * Executes a Google_Http_Request
30
- *
31
- * @param Google_Client $client
32
- * @param Google_Http_Request $req
33
- * @return array decoded result
34
- * @throws Google_Service_Exception on server side error (ie: not authenticated,
35
- * invalid or malformed post body, invalid url)
36
- */
37
- public static function execute(Google_Client $client, Google_Http_Request $req)
38
- {
39
- $httpRequest = $client->getIo()->makeRequest($req);
40
- $httpRequest->setExpectedClass($req->getExpectedClass());
41
- return self::decodeHttpResponse($httpRequest, $client);
42
- }
43
-
44
- /**
45
- * Decode an HTTP Response.
46
- *
47
- * @static
48
- *
49
- * @throws Google_Service_Exception
50
- * @param Google_Http_Request $response
51
- * The http response to be decoded.
52
- * @param Google_Client $client
53
- * @return mixed|null
54
- */
55
- public static function decodeHttpResponse($response, Google_Client $client = null)
56
- {
57
- $code = $response->getResponseHttpCode();
58
- $body = $response->getResponseBody();
59
- $decoded = null;
60
- if ((intVal($code)) >= 300) {
61
- $decoded = json_decode($body, true);
62
- $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
63
- if (isset($decoded['error']) && isset($decoded['error']['message']) && isset($decoded['error']['code'])) {
64
- // if we're getting a json encoded error definition, use that instead of the raw response
65
- // body for improved readability
66
- $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
67
- } else {
68
- $err .= ": ($code) $body";
69
- }
70
- $errors = null;
71
- // Specific check for APIs which don't return error details, such as Blogger.
72
- if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
73
- $errors = $decoded['error']['errors'];
74
- }
75
- if ($client) {
76
- $client->getLogger()->error($err, array(
77
- 'code' => $code,
78
- 'errors' => $errors
79
- ));
80
- }
81
- throw new Google_Service_Exception($err, $code, null, $errors);
82
- }
83
- // Only attempt to decode the response, if the response code wasn't (204) 'no content'
84
- if ($code != '204') {
85
- $decoded = json_decode($body, true);
86
- if ($decoded === null || $decoded === "") {
87
- $error = "Invalid json in service response: $body";
88
- if ($client) {
89
- $client->getLogger()->error($error);
90
- }
91
- throw new Google_Service_Exception($error);
92
- }
93
- if ($response->getExpectedClass()) {
94
- $class = $response->getExpectedClass();
95
- $decoded = new $class($decoded);
96
- }
97
- }
98
- return $decoded;
99
- }
100
-
101
- /**
102
- * Parse/expand request parameters and create a fully qualified
103
- * request uri.
104
- *
105
- * @static
106
- *
107
- * @param string $servicePath
108
- * @param string $restPath
109
- * @param array $params
110
- * @return string $requestUrl
111
- */
112
- public static function createRequestUri($servicePath, $restPath, $params)
113
- {
114
- $requestUrl = $servicePath . $restPath;
115
- $uriTemplateVars = array();
116
- $queryVars = array();
117
- foreach ($params as $paramName => $paramSpec) {
118
- if ($paramSpec['type'] == 'boolean') {
119
- $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
120
- }
121
- if ($paramSpec['location'] == 'path') {
122
- $uriTemplateVars[$paramName] = $paramSpec['value'];
123
- } else
124
- if ($paramSpec['location'] == 'query') {
125
- if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
126
- foreach ($paramSpec['value'] as $value) {
127
- $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($value));
128
- }
129
- } else {
130
- $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($paramSpec['value']));
131
- }
132
- }
133
- }
134
- if (count($uriTemplateVars)) {
135
- $uriTemplateParser = new Google_Utils_URITemplate();
136
- $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
137
- }
138
- if (count($queryVars)) {
139
- $requestUrl .= '?' . implode($queryVars, '&');
140
- }
141
- return $requestUrl;
142
- }
143
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * This class implements the RESTful transport of apiServiceRequest()'s
21
+ *
22
+ * @author Chris Chabot <chabotc@google.com>
23
+ * @author Chirag Shah <chirags@google.com>
24
+ */
25
+ class Google_Http_REST
26
+ {
27
+
28
+ /**
29
+ * Executes a Google_Http_Request
30
+ *
31
+ * @param Google_Client $client
32
+ * @param Google_Http_Request $req
33
+ * @return array decoded result
34
+ * @throws Google_Service_Exception on server side error (ie: not authenticated,
35
+ * invalid or malformed post body, invalid url)
36
+ */
37
+ public static function execute(Google_Client $client, Google_Http_Request $req)
38
+ {
39
+ $httpRequest = $client->getIo()->makeRequest($req);
40
+ $httpRequest->setExpectedClass($req->getExpectedClass());
41
+ return self::decodeHttpResponse($httpRequest, $client);
42
+ }
43
+
44
+ /**
45
+ * Decode an HTTP Response.
46
+ *
47
+ * @static
48
+ *
49
+ * @throws Google_Service_Exception
50
+ * @param Google_Http_Request $response
51
+ * The http response to be decoded.
52
+ * @param Google_Client $client
53
+ * @return mixed|null
54
+ */
55
+ public static function decodeHttpResponse($response, Google_Client $client = null)
56
+ {
57
+ $code = $response->getResponseHttpCode();
58
+ $body = $response->getResponseBody();
59
+ $decoded = null;
60
+ if ((intVal($code)) >= 300) {
61
+ $decoded = json_decode($body, true);
62
+ $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
63
+ if (isset($decoded['error']) && isset($decoded['error']['message']) && isset($decoded['error']['code'])) {
64
+ // if we're getting a json encoded error definition, use that instead of the raw response
65
+ // body for improved readability
66
+ $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
67
+ } else {
68
+ $err .= ": ($code) $body";
69
+ }
70
+ $errors = null;
71
+ // Specific check for APIs which don't return error details, such as Blogger.
72
+ if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
73
+ $errors = $decoded['error']['errors'];
74
+ }
75
+ if ($client) {
76
+ $client->getLogger()->error($err, array(
77
+ 'code' => $code,
78
+ 'errors' => $errors
79
+ ));
80
+ }
81
+ throw new Google_Service_Exception($err, $code, null, $errors);
82
+ }
83
+ // Only attempt to decode the response, if the response code wasn't (204) 'no content'
84
+ if ($code != '204') {
85
+ $decoded = json_decode($body, true);
86
+ if ($decoded === null || $decoded === "") {
87
+ $error = "Invalid json in service response: $body";
88
+ if ($client) {
89
+ $client->getLogger()->error($error);
90
+ }
91
+ throw new Google_Service_Exception($error);
92
+ }
93
+ if ($response->getExpectedClass()) {
94
+ $class = $response->getExpectedClass();
95
+ $decoded = new $class($decoded);
96
+ }
97
+ }
98
+ return $decoded;
99
+ }
100
+
101
+ /**
102
+ * Parse/expand request parameters and create a fully qualified
103
+ * request uri.
104
+ *
105
+ * @static
106
+ *
107
+ * @param string $servicePath
108
+ * @param string $restPath
109
+ * @param array $params
110
+ * @return string $requestUrl
111
+ */
112
+ public static function createRequestUri($servicePath, $restPath, $params)
113
+ {
114
+ $requestUrl = $servicePath . $restPath;
115
+ $uriTemplateVars = array();
116
+ $queryVars = array();
117
+ foreach ($params as $paramName => $paramSpec) {
118
+ if ($paramSpec['type'] == 'boolean') {
119
+ $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
120
+ }
121
+ if ($paramSpec['location'] == 'path') {
122
+ $uriTemplateVars[$paramName] = $paramSpec['value'];
123
+ } else
124
+ if ($paramSpec['location'] == 'query') {
125
+ if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
126
+ foreach ($paramSpec['value'] as $value) {
127
+ $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($value));
128
+ }
129
+ } else {
130
+ $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($paramSpec['value']));
131
+ }
132
+ }
133
+ }
134
+ if (count($uriTemplateVars)) {
135
+ $uriTemplateParser = new Google_Utils_URITemplate();
136
+ $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
137
+ }
138
+ if (count($queryVars)) {
139
+ $requestUrl .= '?' . implode($queryVars, '&');
140
+ }
141
+ return $requestUrl;
142
+ }
143
  }
tools/src/Google/Http/Request.php CHANGED
@@ -1,498 +1,498 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * HTTP Request to be executed by IO classes.
21
- * Upon execution, the
22
- * responseHttpCode, responseHeaders and responseBody will be filled in.
23
- *
24
- * @author Chris Chabot <chabotc@google.com>
25
- * @author Chirag Shah <chirags@google.com>
26
- *
27
- */
28
- class Google_Http_Request
29
- {
30
-
31
- const GZIP_UA = " (gzip)";
32
-
33
- private $batchHeaders = array(
34
- 'Content-Type' => 'application/http',
35
- 'Content-Transfer-Encoding' => 'binary',
36
- 'MIME-Version' => '1.0'
37
- );
38
-
39
- protected $queryParams;
40
-
41
- protected $requestMethod;
42
-
43
- protected $requestHeaders;
44
-
45
- protected $baseComponent = null;
46
-
47
- protected $path;
48
-
49
- protected $postBody;
50
-
51
- protected $userAgent;
52
-
53
- protected $canGzip = null;
54
-
55
- protected $responseHttpCode;
56
-
57
- protected $responseHeaders;
58
-
59
- protected $responseBody;
60
-
61
- protected $expectedClass;
62
-
63
- public $accessKey;
64
-
65
- public function __construct($url, $method = 'GET', $headers = array(), $postBody = null)
66
- {
67
- $this->setUrl($url);
68
- $this->setRequestMethod($method);
69
- $this->setRequestHeaders($headers);
70
- $this->setPostBody($postBody);
71
- }
72
-
73
- /**
74
- * Misc function that returns the base url component of the $url
75
- * used by the OAuth signing class to calculate the base string
76
- *
77
- * @return string The base url component of the $url.
78
- */
79
- public function getBaseComponent()
80
- {
81
- return $this->baseComponent;
82
- }
83
-
84
- /**
85
- * Set the base URL that path and query parameters will be added to.
86
- *
87
- * @param $baseComponent string
88
- */
89
- public function setBaseComponent($baseComponent)
90
- {
91
- $this->baseComponent = $baseComponent;
92
- }
93
-
94
- /**
95
- * Enable support for gzipped responses with this request.
96
- */
97
- public function enableGzip()
98
- {
99
- $this->setRequestHeaders(array(
100
- "Accept-Encoding" => "gzip"
101
- ));
102
- $this->canGzip = true;
103
- $this->setUserAgent($this->userAgent);
104
- }
105
-
106
- /**
107
- * Disable support for gzip responses with this request.
108
- */
109
- public function disableGzip()
110
- {
111
- if (isset($this->requestHeaders['accept-encoding']) && $this->requestHeaders['accept-encoding'] == "gzip") {
112
- unset($this->requestHeaders['accept-encoding']);
113
- }
114
- $this->canGzip = false;
115
- $this->userAgent = str_replace(self::GZIP_UA, "", $this->userAgent);
116
- }
117
-
118
- /**
119
- * Can this request accept a gzip response?
120
- *
121
- * @return bool
122
- */
123
- public function canGzip()
124
- {
125
- return $this->canGzip;
126
- }
127
-
128
- /**
129
- * Misc function that returns an array of the query parameters of the current
130
- * url used by the OAuth signing class to calculate the signature
131
- *
132
- * @return array Query parameters in the query string.
133
- */
134
- public function getQueryParams()
135
- {
136
- return $this->queryParams;
137
- }
138
-
139
- /**
140
- * Set a new query parameter.
141
- *
142
- * @param $key -
143
- * string to set, does not need to be URL encoded
144
- * @param $value -
145
- * string to set, does not need to be URL encoded
146
- */
147
- public function setQueryParam($key, $value)
148
- {
149
- $this->queryParams[$key] = $value;
150
- }
151
-
152
- /**
153
- *
154
- * @return string HTTP Response Code.
155
- */
156
- public function getResponseHttpCode()
157
- {
158
- return (int) $this->responseHttpCode;
159
- }
160
-
161
- /**
162
- *
163
- * @param int $responseHttpCode
164
- * HTTP Response Code.
165
- */
166
- public function setResponseHttpCode($responseHttpCode)
167
- {
168
- $this->responseHttpCode = $responseHttpCode;
169
- }
170
-
171
- /**
172
- *
173
- * @return $responseHeaders (array) HTTP Response Headers.
174
- */
175
- public function getResponseHeaders()
176
- {
177
- return $this->responseHeaders;
178
- }
179
-
180
- /**
181
- *
182
- * @return string HTTP Response Body
183
- */
184
- public function getResponseBody()
185
- {
186
- return $this->responseBody;
187
- }
188
-
189
- /**
190
- * Set the class the response to this request should expect.
191
- *
192
- * @param $class string
193
- * the class name
194
- */
195
- public function setExpectedClass($class)
196
- {
197
- $this->expectedClass = $class;
198
- }
199
-
200
- /**
201
- * Retrieve the expected class the response should expect.
202
- *
203
- * @return string class name
204
- */
205
- public function getExpectedClass()
206
- {
207
- return $this->expectedClass;
208
- }
209
-
210
- /**
211
- *
212
- * @param array $headers
213
- * The HTTP response headers
214
- * to be normalized.
215
- */
216
- public function setResponseHeaders($headers)
217
- {
218
- $headers = Google_Utils::normalize($headers);
219
- if ($this->responseHeaders) {
220
- $headers = array_merge($this->responseHeaders, $headers);
221
- }
222
- $this->responseHeaders = $headers;
223
- }
224
-
225
- /**
226
- *
227
- * @param string $key
228
- * @return array|boolean Returns the requested HTTP header or
229
- * false if unavailable.
230
- */
231
- public function getResponseHeader($key)
232
- {
233
- return isset($this->responseHeaders[$key]) ? $this->responseHeaders[$key] : false;
234
- }
235
-
236
- /**
237
- *
238
- * @param string $responseBody
239
- * The HTTP response body.
240
- */
241
- public function setResponseBody($responseBody)
242
- {
243
- $this->responseBody = $responseBody;
244
- }
245
-
246
- /**
247
- *
248
- * @return string $url The request URL.
249
- */
250
- public function getUrl()
251
- {
252
- return $this->baseComponent . $this->path . (count($this->queryParams) ? "?" . $this->buildQuery($this->queryParams) : '');
253
- }
254
-
255
- /**
256
- *
257
- * @return string $method HTTP Request Method.
258
- */
259
- public function getRequestMethod()
260
- {
261
- return $this->requestMethod;
262
- }
263
-
264
- /**
265
- *
266
- * @return array $headers HTTP Request Headers.
267
- */
268
- public function getRequestHeaders()
269
- {
270
- return $this->requestHeaders;
271
- }
272
-
273
- /**
274
- *
275
- * @param string $key
276
- * @return array|boolean Returns the requested HTTP header or
277
- * false if unavailable.
278
- */
279
- public function getRequestHeader($key)
280
- {
281
- return isset($this->requestHeaders[$key]) ? $this->requestHeaders[$key] : false;
282
- }
283
-
284
- /**
285
- *
286
- * @return string $postBody HTTP Request Body.
287
- */
288
- public function getPostBody()
289
- {
290
- return $this->postBody;
291
- }
292
-
293
- /**
294
- *
295
- * @param string $url
296
- * the url to set
297
- */
298
- public function setUrl($url)
299
- {
300
- if (substr($url, 0, 4) != 'http') {
301
- // Force the path become relative.
302
- if (substr($url, 0, 1) !== '/') {
303
- $url = '/' . $url;
304
- }
305
- }
306
- $parts = parse_url($url);
307
- if (isset($parts['host'])) {
308
- $this->baseComponent = sprintf("%s%s%s", isset($parts['scheme']) ? $parts['scheme'] . "://" : '', isset($parts['host']) ? $parts['host'] : '', isset($parts['port']) ? ":" . $parts['port'] : '');
309
- }
310
- $this->path = isset($parts['path']) ? $parts['path'] : '';
311
- $this->queryParams = array();
312
- if (isset($parts['query'])) {
313
- $this->queryParams = $this->parseQuery($parts['query']);
314
- }
315
- }
316
-
317
- /**
318
- *
319
- * @param string $method
320
- * Set he HTTP Method and normalize
321
- * it to upper-case, as required by HTTP.
322
- *
323
- */
324
- public function setRequestMethod($method)
325
- {
326
- $this->requestMethod = strtoupper($method);
327
- }
328
-
329
- /**
330
- *
331
- * @param array $headers
332
- * The HTTP request headers
333
- * to be set and normalized.
334
- */
335
- public function setRequestHeaders($headers)
336
- {
337
- $headers = Google_Utils::normalize($headers);
338
- if ($this->requestHeaders) {
339
- $headers = array_merge($this->requestHeaders, $headers);
340
- }
341
- $this->requestHeaders = $headers;
342
- }
343
-
344
- /**
345
- *
346
- * @param string $postBody
347
- * the postBody to set
348
- */
349
- public function setPostBody($postBody)
350
- {
351
- $this->postBody = $postBody;
352
- }
353
-
354
- /**
355
- * Set the User-Agent Header.
356
- *
357
- * @param string $userAgent
358
- * The User-Agent.
359
- */
360
- public function setUserAgent($userAgent)
361
- {
362
- $this->userAgent = $userAgent;
363
- if ($this->canGzip) {
364
- $this->userAgent = $userAgent . self::GZIP_UA;
365
- }
366
- }
367
-
368
- /**
369
- *
370
- * @return string The User-Agent.
371
- */
372
- public function getUserAgent()
373
- {
374
- return $this->userAgent;
375
- }
376
-
377
- /**
378
- * Returns a cache key depending on if this was an OAuth signed request
379
- * in which case it will use the non-signed url and access key to make this
380
- * cache key unique per authenticated user, else use the plain request url
381
- *
382
- * @return string The md5 hash of the request cache key.
383
- */
384
- public function getCacheKey()
385
- {
386
- $key = $this->getUrl();
387
- if (isset($this->accessKey)) {
388
- $key .= $this->accessKey;
389
- }
390
- if (isset($this->requestHeaders['authorization'])) {
391
- $key .= $this->requestHeaders['authorization'];
392
- }
393
- return md5($key);
394
- }
395
-
396
- public function getParsedCacheControl()
397
- {
398
- $parsed = array();
399
- $rawCacheControl = $this->getResponseHeader('cache-control');
400
- if ($rawCacheControl) {
401
- $rawCacheControl = str_replace(', ', '&', $rawCacheControl);
402
- parse_str($rawCacheControl, $parsed);
403
- }
404
- return $parsed;
405
- }
406
-
407
- /**
408
- *
409
- * @param string $id
410
- * @return string A string representation of the HTTP Request.
411
- */
412
- public function toBatchString($id)
413
- {
414
- $str = '';
415
- $path = parse_url($this->getUrl(), PHP_URL_PATH) . "?" . http_build_query($this->queryParams);
416
- $str .= $this->getRequestMethod() . ' ' . $path . " HTTP/1.1\n";
417
- foreach ($this->getRequestHeaders() as $key => $val) {
418
- $str .= $key . ': ' . $val . "\n";
419
- }
420
- if ($this->getPostBody()) {
421
- $str .= "\n";
422
- $str .= $this->getPostBody();
423
- }
424
- $headers = '';
425
- foreach ($this->batchHeaders as $key => $val) {
426
- $headers .= $key . ': ' . $val . "\n";
427
- }
428
- $headers .= "Content-ID: $id\n";
429
- $str = $headers . "\n" . $str;
430
- return $str;
431
- }
432
-
433
- /**
434
- * Our own version of parse_str that allows for multiple variables
435
- * with the same name.
436
- *
437
- * @param $string -
438
- * the query string to parse
439
- */
440
- private function parseQuery($string)
441
- {
442
- $return = array();
443
- $parts = explode("&", $string);
444
- foreach ($parts as $part) {
445
- list ($key, $value) = explode('=', $part, 2);
446
- $value = urldecode($value);
447
- if (isset($return[$key])) {
448
- if (! is_array($return[$key])) {
449
- $return[$key] = array(
450
- $return[$key]
451
- );
452
- }
453
- $return[$key][] = $value;
454
- } else {
455
- $return[$key] = $value;
456
- }
457
- }
458
- return $return;
459
- }
460
-
461
- /**
462
- * A version of build query that allows for multiple
463
- * duplicate keys.
464
- *
465
- * @param $parts array
466
- * of key value pairs
467
- */
468
- private function buildQuery($parts)
469
- {
470
- $return = array();
471
- foreach ($parts as $key => $value) {
472
- if (is_array($value)) {
473
- foreach ($value as $v) {
474
- $return[] = urlencode($key) . "=" . urlencode($v);
475
- }
476
- } else {
477
- $return[] = urlencode($key) . "=" . urlencode($value);
478
- }
479
- }
480
- return implode('&', $return);
481
- }
482
-
483
- /**
484
- * If we're POSTing and have no body to send, we can send the query
485
- * parameters in there, which avoids length issues with longer query
486
- * params.
487
- */
488
- public function maybeMoveParametersToBody()
489
- {
490
- if ($this->getRequestMethod() == "POST" && empty($this->postBody)) {
491
- $this->setRequestHeaders(array(
492
- "content-type" => "application/x-www-form-urlencoded; charset=UTF-8"
493
- ));
494
- $this->setPostBody($this->buildQuery($this->queryParams));
495
- $this->queryParams = array();
496
- }
497
- }
498
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * HTTP Request to be executed by IO classes.
21
+ * Upon execution, the
22
+ * responseHttpCode, responseHeaders and responseBody will be filled in.
23
+ *
24
+ * @author Chris Chabot <chabotc@google.com>
25
+ * @author Chirag Shah <chirags@google.com>
26
+ *
27
+ */
28
+ class Google_Http_Request
29
+ {
30
+
31
+ const GZIP_UA = " (gzip)";
32
+
33
+ private $batchHeaders = array(
34
+ 'Content-Type' => 'application/http',
35
+ 'Content-Transfer-Encoding' => 'binary',
36
+ 'MIME-Version' => '1.0'
37
+ );
38
+
39
+ protected $queryParams;
40
+
41
+ protected $requestMethod;
42
+
43
+ protected $requestHeaders;
44
+
45
+ protected $baseComponent = null;
46
+
47
+ protected $path;
48
+
49
+ protected $postBody;
50
+
51
+ protected $userAgent;
52
+
53
+ protected $canGzip = null;
54
+
55
+ protected $responseHttpCode;
56
+
57
+ protected $responseHeaders;
58
+
59
+ protected $responseBody;
60
+
61
+ protected $expectedClass;
62
+
63
+ public $accessKey;
64
+
65
+ public function __construct($url, $method = 'GET', $headers = array(), $postBody = null)
66
+ {
67
+ $this->setUrl($url);
68
+ $this->setRequestMethod($method);
69
+ $this->setRequestHeaders($headers);
70
+ $this->setPostBody($postBody);
71
+ }
72
+
73
+ /**
74
+ * Misc function that returns the base url component of the $url
75
+ * used by the OAuth signing class to calculate the base string
76
+ *
77
+ * @return string The base url component of the $url.
78
+ */
79
+ public function getBaseComponent()
80
+ {
81
+ return $this->baseComponent;
82
+ }
83
+
84
+ /**
85
+ * Set the base URL that path and query parameters will be added to.
86
+ *
87
+ * @param $baseComponent string
88
+ */
89
+ public function setBaseComponent($baseComponent)
90
+ {
91
+ $this->baseComponent = $baseComponent;
92
+ }
93
+
94
+ /**
95
+ * Enable support for gzipped responses with this request.
96
+ */
97
+ public function enableGzip()
98
+ {
99
+ $this->setRequestHeaders(array(
100
+ "Accept-Encoding" => "gzip"
101
+ ));
102
+ $this->canGzip = true;
103
+ $this->setUserAgent($this->userAgent);
104
+ }
105
+
106
+ /**
107
+ * Disable support for gzip responses with this request.
108
+ */
109
+ public function disableGzip()
110
+ {
111
+ if (isset($this->requestHeaders['accept-encoding']) && $this->requestHeaders['accept-encoding'] == "gzip") {
112
+ unset($this->requestHeaders['accept-encoding']);
113
+ }
114
+ $this->canGzip = false;
115
+ $this->userAgent = str_replace(self::GZIP_UA, "", $this->userAgent);
116
+ }
117
+
118
+ /**
119
+ * Can this request accept a gzip response?
120
+ *
121
+ * @return bool
122
+ */
123
+ public function canGzip()
124
+ {
125
+ return $this->canGzip;
126
+ }
127
+
128
+ /**
129
+ * Misc function that returns an array of the query parameters of the current
130
+ * url used by the OAuth signing class to calculate the signature
131
+ *
132
+ * @return array Query parameters in the query string.
133
+ */
134
+ public function getQueryParams()
135
+ {
136
+ return $this->queryParams;
137
+ }
138
+
139
+ /**
140
+ * Set a new query parameter.
141
+ *
142
+ * @param $key -
143
+ * string to set, does not need to be URL encoded
144
+ * @param $value -
145
+ * string to set, does not need to be URL encoded
146
+ */
147
+ public function setQueryParam($key, $value)
148
+ {
149
+ $this->queryParams[$key] = $value;
150
+ }
151
+
152
+ /**
153
+ *
154
+ * @return string HTTP Response Code.
155
+ */
156
+ public function getResponseHttpCode()
157
+ {
158
+ return (int) $this->responseHttpCode;
159
+ }
160
+
161
+ /**
162
+ *
163
+ * @param int $responseHttpCode
164
+ * HTTP Response Code.
165
+ */
166
+ public function setResponseHttpCode($responseHttpCode)
167
+ {
168
+ $this->responseHttpCode = $responseHttpCode;
169
+ }
170
+
171
+ /**
172
+ *
173
+ * @return $responseHeaders (array) HTTP Response Headers.
174
+ */
175
+ public function getResponseHeaders()
176
+ {
177
+ return $this->responseHeaders;
178
+ }
179
+
180
+ /**
181
+ *
182
+ * @return string HTTP Response Body
183
+ */
184
+ public function getResponseBody()
185
+ {
186
+ return $this->responseBody;
187
+ }
188
+
189
+ /**
190
+ * Set the class the response to this request should expect.
191
+ *
192
+ * @param $class string
193
+ * the class name
194
+ */
195
+ public function setExpectedClass($class)
196
+ {
197
+ $this->expectedClass = $class;
198
+ }
199
+
200
+ /**
201
+ * Retrieve the expected class the response should expect.
202
+ *
203
+ * @return string class name
204
+ */
205
+ public function getExpectedClass()
206
+ {
207
+ return $this->expectedClass;
208
+ }
209
+
210
+ /**
211
+ *
212
+ * @param array $headers
213
+ * The HTTP response headers
214
+ * to be normalized.
215
+ */
216
+ public function setResponseHeaders($headers)
217
+ {
218
+ $headers = Google_Utils::normalize($headers);
219
+ if ($this->responseHeaders) {
220
+ $headers = array_merge($this->responseHeaders, $headers);
221
+ }
222
+ $this->responseHeaders = $headers;
223
+ }
224
+
225
+ /**
226
+ *
227
+ * @param string $key
228
+ * @return array|boolean Returns the requested HTTP header or
229
+ * false if unavailable.
230
+ */
231
+ public function getResponseHeader($key)
232
+ {
233
+ return isset($this->responseHeaders[$key]) ? $this->responseHeaders[$key] : false;
234
+ }
235
+
236
+ /**
237
+ *
238
+ * @param string $responseBody
239
+ * The HTTP response body.
240
+ */
241
+ public function setResponseBody($responseBody)
242
+ {
243
+ $this->responseBody = $responseBody;
244
+ }
245
+
246
+ /**
247
+ *
248
+ * @return string $url The request URL.
249
+ */
250
+ public function getUrl()
251
+ {
252
+ return $this->baseComponent . $this->path . (count($this->queryParams) ? "?" . $this->buildQuery($this->queryParams) : '');
253
+ }
254
+
255
+ /**
256
+ *
257
+ * @return string $method HTTP Request Method.
258
+ */
259
+ public function getRequestMethod()
260
+ {
261
+ return $this->requestMethod;
262
+ }
263
+
264
+ /**
265
+ *
266
+ * @return array $headers HTTP Request Headers.
267
+ */
268
+ public function getRequestHeaders()
269
+ {
270
+ return $this->requestHeaders;
271
+ }
272
+
273
+ /**
274
+ *
275
+ * @param string $key
276
+ * @return array|boolean Returns the requested HTTP header or
277
+ * false if unavailable.
278
+ */
279
+ public function getRequestHeader($key)
280
+ {
281
+ return isset($this->requestHeaders[$key]) ? $this->requestHeaders[$key] : false;
282
+ }
283
+
284
+ /**
285
+ *
286
+ * @return string $postBody HTTP Request Body.
287
+ */
288
+ public function getPostBody()
289
+ {
290
+ return $this->postBody;
291
+ }
292
+
293
+ /**
294
+ *
295
+ * @param string $url
296
+ * the url to set
297
+ */
298
+ public function setUrl($url)
299
+ {
300
+ if (substr($url, 0, 4) != 'http') {
301
+ // Force the path become relative.
302
+ if (substr($url, 0, 1) !== '/') {
303
+ $url = '/' . $url;
304
+ }
305
+ }
306
+ $parts = parse_url($url);
307
+ if (isset($parts['host'])) {
308
+ $this->baseComponent = sprintf("%s%s%s", isset($parts['scheme']) ? $parts['scheme'] . "://" : '', isset($parts['host']) ? $parts['host'] : '', isset($parts['port']) ? ":" . $parts['port'] : '');
309
+ }
310
+ $this->path = isset($parts['path']) ? $parts['path'] : '';
311
+ $this->queryParams = array();
312
+ if (isset($parts['query'])) {
313
+ $this->queryParams = $this->parseQuery($parts['query']);
314
+ }
315
+ }
316
+
317
+ /**
318
+ *
319
+ * @param string $method
320
+ * Set he HTTP Method and normalize
321
+ * it to upper-case, as required by HTTP.
322
+ *
323
+ */
324
+ public function setRequestMethod($method)
325
+ {
326
+ $this->requestMethod = strtoupper($method);
327
+ }
328
+
329
+ /**
330
+ *
331
+ * @param array $headers
332
+ * The HTTP request headers
333
+ * to be set and normalized.
334
+ */
335
+ public function setRequestHeaders($headers)
336
+ {
337
+ $headers = Google_Utils::normalize($headers);
338
+ if ($this->requestHeaders) {
339
+ $headers = array_merge($this->requestHeaders, $headers);
340
+ }
341
+ $this->requestHeaders = $headers;
342
+ }
343
+
344
+ /**
345
+ *
346
+ * @param string $postBody
347
+ * the postBody to set
348
+ */
349
+ public function setPostBody($postBody)
350
+ {
351
+ $this->postBody = $postBody;
352
+ }
353
+
354
+ /**
355
+ * Set the User-Agent Header.
356
+ *
357
+ * @param string $userAgent
358
+ * The User-Agent.
359
+ */
360
+ public function setUserAgent($userAgent)
361
+ {
362
+ $this->userAgent = $userAgent;
363
+ if ($this->canGzip) {
364
+ $this->userAgent = $userAgent . self::GZIP_UA;
365
+ }
366
+ }
367
+
368
+ /**
369
+ *
370
+ * @return string The User-Agent.
371
+ */
372
+ public function getUserAgent()
373
+ {
374
+ return $this->userAgent;
375
+ }
376
+
377
+ /**
378
+ * Returns a cache key depending on if this was an OAuth signed request
379
+ * in which case it will use the non-signed url and access key to make this
380
+ * cache key unique per authenticated user, else use the plain request url
381
+ *
382
+ * @return string The md5 hash of the request cache key.
383
+ */
384
+ public function getCacheKey()
385
+ {
386
+ $key = $this->getUrl();
387
+ if (isset($this->accessKey)) {
388
+ $key .= $this->accessKey;
389
+ }
390
+ if (isset($this->requestHeaders['authorization'])) {
391
+ $key .= $this->requestHeaders['authorization'];
392
+ }
393
+ return md5($key);
394
+ }
395
+
396
+ public function getParsedCacheControl()
397
+ {
398
+ $parsed = array();
399
+ $rawCacheControl = $this->getResponseHeader('cache-control');
400
+ if ($rawCacheControl) {
401
+ $rawCacheControl = str_replace(', ', '&', $rawCacheControl);
402
+ parse_str($rawCacheControl, $parsed);
403
+ }
404
+ return $parsed;
405
+ }
406
+
407
+ /**
408
+ *
409
+ * @param string $id
410
+ * @return string A string representation of the HTTP Request.
411
+ */
412
+ public function toBatchString($id)
413
+ {
414
+ $str = '';
415
+ $path = parse_url($this->getUrl(), PHP_URL_PATH) . "?" . http_build_query($this->queryParams);
416
+ $str .= $this->getRequestMethod() . ' ' . $path . " HTTP/1.1\n";
417
+ foreach ($this->getRequestHeaders() as $key => $val) {
418
+ $str .= $key . ': ' . $val . "\n";
419
+ }
420
+ if ($this->getPostBody()) {
421
+ $str .= "\n";
422
+ $str .= $this->getPostBody();
423
+ }
424
+ $headers = '';
425
+ foreach ($this->batchHeaders as $key => $val) {
426
+ $headers .= $key . ': ' . $val . "\n";
427
+ }
428
+ $headers .= "Content-ID: $id\n";
429
+ $str = $headers . "\n" . $str;
430
+ return $str;
431
+ }
432
+
433
+ /**
434
+ * Our own version of parse_str that allows for multiple variables
435
+ * with the same name.
436
+ *
437
+ * @param $string -
438
+ * the query string to parse
439
+ */
440
+ private function parseQuery($string)
441
+ {
442
+ $return = array();
443
+ $parts = explode("&", $string);
444
+ foreach ($parts as $part) {
445
+ list ($key, $value) = explode('=', $part, 2);
446
+ $value = urldecode($value);
447
+ if (isset($return[$key])) {
448
+ if (! is_array($return[$key])) {
449
+ $return[$key] = array(
450
+ $return[$key]
451
+ );
452
+ }
453
+ $return[$key][] = $value;
454
+ } else {
455
+ $return[$key] = $value;
456
+ }
457
+ }
458
+ return $return;
459
+ }
460
+
461
+ /**
462
+ * A version of build query that allows for multiple
463
+ * duplicate keys.
464
+ *
465
+ * @param $parts array
466
+ * of key value pairs
467
+ */
468
+ private function buildQuery($parts)
469
+ {
470
+ $return = array();
471
+ foreach ($parts as $key => $value) {
472
+ if (is_array($value)) {
473
+ foreach ($value as $v) {
474
+ $return[] = urlencode($key) . "=" . urlencode($v);
475
+ }
476
+ } else {
477
+ $return[] = urlencode($key) . "=" . urlencode($value);
478
+ }
479
+ }
480
+ return implode('&', $return);
481
+ }
482
+
483
+ /**
484
+ * If we're POSTing and have no body to send, we can send the query
485
+ * parameters in there, which avoids length issues with longer query
486
+ * params.
487
+ */
488
+ public function maybeMoveParametersToBody()
489
+ {
490
+ if ($this->getRequestMethod() == "POST" && empty($this->postBody)) {
491
+ $this->setRequestHeaders(array(
492
+ "content-type" => "application/x-www-form-urlencoded; charset=UTF-8"
493
+ ));
494
+ $this->setPostBody($this->buildQuery($this->queryParams));
495
+ $this->queryParams = array();
496
+ }
497
+ }
498
  }
tools/src/Google/IO/Abstract.php CHANGED
@@ -1,340 +1,340 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- /**
18
- * Abstract IO base class
19
- */
20
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
21
-
22
- abstract class Google_IO_Abstract
23
- {
24
-
25
- const UNKNOWN_CODE = 0;
26
-
27
- const FORM_URLENCODED = 'application/x-www-form-urlencoded';
28
-
29
- private static $CONNECTION_ESTABLISHED_HEADERS = array(
30
- "HTTP/1.0 200 Connection established\r\n\r\n",
31
- "HTTP/1.1 200 Connection established\r\n\r\n"
32
- );
33
-
34
- private static $ENTITY_HTTP_METHODS = array(
35
- "POST" => null,
36
- "PUT" => null
37
- );
38
-
39
- /**
40
- *
41
- * @var Google_Client
42
- */
43
- protected $client;
44
-
45
- public function __construct(Google_Client $client)
46
- {
47
- $this->client = $client;
48
- $timeout = $client->getClassConfig('Google_IO_Abstract', 'request_timeout_seconds');
49
- if ($timeout > 0) {
50
- $this->setTimeout($timeout);
51
- }
52
- }
53
-
54
- /**
55
- * Executes a Google_Http_Request and returns the resulting populated Google_Http_Request
56
- *
57
- * @param Google_Http_Request $request
58
- * @return Google_Http_Request $request
59
- */
60
- abstract public function executeRequest(Google_Http_Request $request);
61
-
62
- /**
63
- * Set options that update the transport implementation's behavior.
64
- *
65
- * @param
66
- * $options
67
- */
68
- abstract public function setOptions($options);
69
-
70
- /**
71
- * Set the maximum request time in seconds.
72
- *
73
- * @param $timeout in
74
- * seconds
75
- */
76
- abstract public function setTimeout($timeout);
77
-
78
- /**
79
- * Get the maximum request time in seconds.
80
- *
81
- * @return timeout in seconds
82
- */
83
- abstract public function getTimeout();
84
-
85
- /**
86
- * Test for the presence of a cURL header processing bug
87
- *
88
- * The cURL bug was present in versions prior to 7.30.0 and caused the header
89
- * length to be miscalculated when a "Connection established" header added by
90
- * some proxies was present.
91
- *
92
- * @return boolean
93
- */
94
- abstract protected function needsQuirk();
95
-
96
- /**
97
- * @visible for testing.
98
- * Cache the response to an HTTP request if it is cacheable.
99
- *
100
- * @param Google_Http_Request $request
101
- * @return bool Returns true if the insertion was successful.
102
- * Otherwise, return false.
103
- */
104
- public function setCachedRequest(Google_Http_Request $request)
105
- {
106
- // Determine if the request is cacheable.
107
- if (Google_Http_CacheParser::isResponseCacheable($request)) {
108
- $this->client->getCache()->set($request->getCacheKey(), $request);
109
- return true;
110
- }
111
- return false;
112
- }
113
-
114
- /**
115
- * Execute an HTTP Request
116
- *
117
- * @param Google_HttpRequest $request
118
- * the http request to be executed
119
- * @return Google_HttpRequest http request with the response http code,
120
- * response headers and response body filled in
121
- * @throws Google_IO_Exception on curl or IO error
122
- */
123
- public function makeRequest(Google_Http_Request $request)
124
- {
125
- // First, check to see if we have a valid cached version.
126
- $cached = $this->getCachedRequest($request);
127
- if ($cached !== false && $cached instanceof Google_Http_Request) {
128
- if (! $this->checkMustRevalidateCachedRequest($cached, $request)) {
129
- return $cached;
130
- }
131
- }
132
- if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
133
- $request = $this->processEntityRequest($request);
134
- }
135
- list ($responseData, $responseHeaders, $respHttpCode) = $this->executeRequest($request);
136
- if ($respHttpCode == 304 && $cached) {
137
- // If the server responded NOT_MODIFIED, return the cached request.
138
- $this->updateCachedRequest($cached, $responseHeaders);
139
- return $cached;
140
- }
141
- if (! isset($responseHeaders['Date']) && ! isset($responseHeaders['date'])) {
142
- $responseHeaders['Date'] = date("r");
143
- }
144
- $request->setResponseHttpCode($respHttpCode);
145
- $request->setResponseHeaders($responseHeaders);
146
- $request->setResponseBody($responseData);
147
- // Store the request in cache (the function checks to see if the request
148
- // can actually be cached)
149
- $this->setCachedRequest($request);
150
- return $request;
151
- }
152
-
153
- /**
154
- * @visible for testing.
155
- *
156
- * @param Google_Http_Request $request
157
- * @return Google_Http_Request|bool Returns the cached object or
158
- * false if the operation was unsuccessful.
159
- */
160
- public function getCachedRequest(Google_Http_Request $request)
161
- {
162
- if (false === Google_Http_CacheParser::isRequestCacheable($request)) {
163
- return false;
164
- }
165
- return $this->client->getCache()->get($request->getCacheKey());
166
- }
167
-
168
- /**
169
- * @visible for testing
170
- * Process an http request that contains an enclosed entity.
171
- *
172
- * @param Google_Http_Request $request
173
- * @return Google_Http_Request Processed request with the enclosed entity.
174
- */
175
- public function processEntityRequest(Google_Http_Request $request)
176
- {
177
- $postBody = $request->getPostBody();
178
- $contentType = $request->getRequestHeader("content-type");
179
- // Set the default content-type as application/x-www-form-urlencoded.
180
- if (false == $contentType) {
181
- $contentType = self::FORM_URLENCODED;
182
- $request->setRequestHeaders(array(
183
- 'content-type' => $contentType
184
- ));
185
- }
186
- // Force the payload to match the content-type asserted in the header.
187
- if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
188
- $postBody = http_build_query($postBody, '', '&');
189
- $request->setPostBody($postBody);
190
- }
191
- // Make sure the content-length header is set.
192
- if (! $postBody || is_string($postBody)) {
193
- $postsLength = strlen($postBody);
194
- $request->setRequestHeaders(array(
195
- 'content-length' => $postsLength
196
- ));
197
- }
198
- return $request;
199
- }
200
-
201
- /**
202
- * Check if an already cached request must be revalidated, and if so update
203
- * the request with the correct ETag headers.
204
- *
205
- * @param Google_Http_Request $cached
206
- * A previously cached response.
207
- * @param Google_Http_Request $request
208
- * The outbound request.
209
- * return bool If the cached object needs to be revalidated, false if it is
210
- * still current and can be re-used.
211
- */
212
- protected function checkMustRevalidateCachedRequest($cached, $request)
213
- {
214
- if (Google_Http_CacheParser::mustRevalidate($cached)) {
215
- $addHeaders = array();
216
- if ($cached->getResponseHeader('etag')) {
217
- // [13.3.4] If an entity tag has been provided by the origin server,
218
- // we must use that entity tag in any cache-conditional request.
219
- $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
220
- } elseif ($cached->getResponseHeader('date')) {
221
- $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
222
- }
223
- $request->setRequestHeaders($addHeaders);
224
- return true;
225
- } else {
226
- return false;
227
- }
228
- }
229
-
230
- /**
231
- * Update a cached request, using the headers from the last response.
232
- *
233
- * @param Google_HttpRequest $cached
234
- * A previously cached response.
235
- * @param
236
- * mixed Associative array of response headers from the last request.
237
- */
238
- protected function updateCachedRequest($cached, $responseHeaders)
239
- {
240
- if (isset($responseHeaders['connection'])) {
241
- $hopByHop = array_merge(self::$HOP_BY_HOP, explode(',', $responseHeaders['connection']));
242
- $endToEnd = array();
243
- foreach ($hopByHop as $key) {
244
- if (isset($responseHeaders[$key])) {
245
- $endToEnd[$key] = $responseHeaders[$key];
246
- }
247
- }
248
- $cached->setResponseHeaders($endToEnd);
249
- }
250
- }
251
-
252
- /**
253
- * Used by the IO lib and also the batch processing.
254
- *
255
- * @param
256
- * $respData
257
- * @param
258
- * $headerSize
259
- * @return array
260
- */
261
- public function parseHttpResponse($respData, $headerSize)
262
- {
263
- // check proxy header
264
- foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) {
265
- if (stripos($respData, $established_header) !== false) {
266
- // existed, remove it
267
- $respData = str_ireplace($established_header, '', $respData);
268
- // Subtract the proxy header size unless the cURL bug prior to 7.30.0
269
- // is present which prevented the proxy header size from being taken into
270
- // account.
271
- if (! $this->needsQuirk()) {
272
- $headerSize -= strlen($established_header);
273
- }
274
- break;
275
- }
276
- }
277
- if ($headerSize) {
278
- $responseBody = substr($respData, $headerSize);
279
- $responseHeaders = substr($respData, 0, $headerSize);
280
- } else {
281
- $responseSegments = explode("\r\n\r\n", $respData, 2);
282
- $responseHeaders = $responseSegments[0];
283
- $responseBody = isset($responseSegments[1]) ? $responseSegments[1] : null;
284
- }
285
- $responseHeaders = $this->getHttpResponseHeaders($responseHeaders);
286
- return array(
287
- $responseHeaders,
288
- $responseBody
289
- );
290
- }
291
-
292
- /**
293
- * Parse out headers from raw headers
294
- *
295
- * @param
296
- * rawHeaders array or string
297
- * @return array
298
- */
299
- public function getHttpResponseHeaders($rawHeaders)
300
- {
301
- if (is_array($rawHeaders)) {
302
- return $this->parseArrayHeaders($rawHeaders);
303
- } else {
304
- return $this->parseStringHeaders($rawHeaders);
305
- }
306
- }
307
-
308
- private function parseStringHeaders($rawHeaders)
309
- {
310
- $headers = array();
311
- $responseHeaderLines = explode("\r\n", $rawHeaders);
312
- foreach ($responseHeaderLines as $headerLine) {
313
- if ($headerLine && strpos($headerLine, ':') !== false) {
314
- list ($header, $value) = explode(': ', $headerLine, 2);
315
- $header = strtolower($header);
316
- if (isset($headers[$header])) {
317
- $headers[$header] .= "\n" . $value;
318
- } else {
319
- $headers[$header] = $value;
320
- }
321
- }
322
- }
323
- return $headers;
324
- }
325
-
326
- private function parseArrayHeaders($rawHeaders)
327
- {
328
- $header_count = count($rawHeaders);
329
- $headers = array();
330
- for ($i = 0; $i < $header_count; $i ++) {
331
- $header = $rawHeaders[$i];
332
- // Times will have colons in - so we just want the first match.
333
- $header_parts = explode(': ', $header, 2);
334
- if (count($header_parts) == 2) {
335
- $headers[$header_parts[0]] = $header_parts[1];
336
- }
337
- }
338
- return $headers;
339
- }
340
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Abstract IO base class
19
+ */
20
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
21
+
22
+ abstract class Google_IO_Abstract
23
+ {
24
+
25
+ const UNKNOWN_CODE = 0;
26
+
27
+ const FORM_URLENCODED = 'application/x-www-form-urlencoded';
28
+
29
+ private static $CONNECTION_ESTABLISHED_HEADERS = array(
30
+ "HTTP/1.0 200 Connection established\r\n\r\n",
31
+ "HTTP/1.1 200 Connection established\r\n\r\n"
32
+ );
33
+
34
+ private static $ENTITY_HTTP_METHODS = array(
35
+ "POST" => null,
36
+ "PUT" => null
37
+ );
38
+
39
+ /**
40
+ *
41
+ * @var Google_Client
42
+ */
43
+ protected $client;
44
+
45
+ public function __construct(Google_Client $client)
46
+ {
47
+ $this->client = $client;
48
+ $timeout = $client->getClassConfig('Google_IO_Abstract', 'request_timeout_seconds');
49
+ if ($timeout > 0) {
50
+ $this->setTimeout($timeout);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Executes a Google_Http_Request and returns the resulting populated Google_Http_Request
56
+ *
57
+ * @param Google_Http_Request $request
58
+ * @return Google_Http_Request $request
59
+ */
60
+ abstract public function executeRequest(Google_Http_Request $request);
61
+
62
+ /**
63
+ * Set options that update the transport implementation's behavior.
64
+ *
65
+ * @param
66
+ * $options
67
+ */
68
+ abstract public function setOptions($options);
69
+
70
+ /**
71
+ * Set the maximum request time in seconds.
72
+ *
73
+ * @param $timeout in
74
+ * seconds
75
+ */
76
+ abstract public function setTimeout($timeout);
77
+
78
+ /**
79
+ * Get the maximum request time in seconds.
80
+ *
81
+ * @return timeout in seconds
82
+ */
83
+ abstract public function getTimeout();
84
+
85
+ /**
86
+ * Test for the presence of a cURL header processing bug
87
+ *
88
+ * The cURL bug was present in versions prior to 7.30.0 and caused the header
89
+ * length to be miscalculated when a "Connection established" header added by
90
+ * some proxies was present.
91
+ *
92
+ * @return boolean
93
+ */
94
+ abstract protected function needsQuirk();
95
+
96
+ /**
97
+ * @visible for testing.
98
+ * Cache the response to an HTTP request if it is cacheable.
99
+ *
100
+ * @param Google_Http_Request $request
101
+ * @return bool Returns true if the insertion was successful.
102
+ * Otherwise, return false.
103
+ */
104
+ public function setCachedRequest(Google_Http_Request $request)
105
+ {
106
+ // Determine if the request is cacheable.
107
+ if (Google_Http_CacheParser::isResponseCacheable($request)) {
108
+ $this->client->getCache()->set($request->getCacheKey(), $request);
109
+ return true;
110
+ }
111
+ return false;
112
+ }
113
+
114
+ /**
115
+ * Execute an HTTP Request
116
+ *
117
+ * @param Google_HttpRequest $request
118
+ * the http request to be executed
119
+ * @return Google_HttpRequest http request with the response http code,
120
+ * response headers and response body filled in
121
+ * @throws Google_IO_Exception on curl or IO error
122
+ */
123
+ public function makeRequest(Google_Http_Request $request)
124
+ {
125
+ // First, check to see if we have a valid cached version.
126
+ $cached = $this->getCachedRequest($request);
127
+ if ($cached !== false && $cached instanceof Google_Http_Request) {
128
+ if (! $this->checkMustRevalidateCachedRequest($cached, $request)) {
129
+ return $cached;
130
+ }
131
+ }
132
+ if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
133
+ $request = $this->processEntityRequest($request);
134
+ }
135
+ list ($responseData, $responseHeaders, $respHttpCode) = $this->executeRequest($request);
136
+ if ($respHttpCode == 304 && $cached) {
137
+ // If the server responded NOT_MODIFIED, return the cached request.
138
+ $this->updateCachedRequest($cached, $responseHeaders);
139
+ return $cached;
140
+ }
141
+ if (! isset($responseHeaders['Date']) && ! isset($responseHeaders['date'])) {
142
+ $responseHeaders['Date'] = date("r");
143
+ }
144
+ $request->setResponseHttpCode($respHttpCode);
145
+ $request->setResponseHeaders($responseHeaders);
146
+ $request->setResponseBody($responseData);
147
+ // Store the request in cache (the function checks to see if the request
148
+ // can actually be cached)
149
+ $this->setCachedRequest($request);
150
+ return $request;
151
+ }
152
+
153
+ /**
154
+ * @visible for testing.
155
+ *
156
+ * @param Google_Http_Request $request
157
+ * @return Google_Http_Request|bool Returns the cached object or
158
+ * false if the operation was unsuccessful.
159
+ */
160
+ public function getCachedRequest(Google_Http_Request $request)
161
+ {
162
+ if (false === Google_Http_CacheParser::isRequestCacheable($request)) {
163
+ return false;
164
+ }
165
+ return $this->client->getCache()->get($request->getCacheKey());
166
+ }
167
+
168
+ /**
169
+ * @visible for testing
170
+ * Process an http request that contains an enclosed entity.
171
+ *
172
+ * @param Google_Http_Request $request
173
+ * @return Google_Http_Request Processed request with the enclosed entity.
174
+ */
175
+ public function processEntityRequest(Google_Http_Request $request)
176
+ {
177
+ $postBody = $request->getPostBody();
178
+ $contentType = $request->getRequestHeader("content-type");
179
+ // Set the default content-type as application/x-www-form-urlencoded.
180
+ if (false == $contentType) {
181
+ $contentType = self::FORM_URLENCODED;
182
+ $request->setRequestHeaders(array(
183
+ 'content-type' => $contentType
184
+ ));
185
+ }
186
+ // Force the payload to match the content-type asserted in the header.
187
+ if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
188
+ $postBody = http_build_query($postBody, '', '&');
189
+ $request->setPostBody($postBody);
190
+ }
191
+ // Make sure the content-length header is set.
192
+ if (! $postBody || is_string($postBody)) {
193
+ $postsLength = strlen($postBody);
194
+ $request->setRequestHeaders(array(
195
+ 'content-length' => $postsLength
196
+ ));
197
+ }
198
+ return $request;
199
+ }
200
+
201
+ /**
202
+ * Check if an already cached request must be revalidated, and if so update
203
+ * the request with the correct ETag headers.
204
+ *
205
+ * @param Google_Http_Request $cached
206
+ * A previously cached response.
207
+ * @param Google_Http_Request $request
208
+ * The outbound request.
209
+ * return bool If the cached object needs to be revalidated, false if it is
210
+ * still current and can be re-used.
211
+ */
212
+ protected function checkMustRevalidateCachedRequest($cached, $request)
213
+ {
214
+ if (Google_Http_CacheParser::mustRevalidate($cached)) {
215
+ $addHeaders = array();
216
+ if ($cached->getResponseHeader('etag')) {
217
+ // [13.3.4] If an entity tag has been provided by the origin server,
218
+ // we must use that entity tag in any cache-conditional request.
219
+ $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
220
+ } elseif ($cached->getResponseHeader('date')) {
221
+ $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
222
+ }
223
+ $request->setRequestHeaders($addHeaders);
224
+ return true;
225
+ } else {
226
+ return false;
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Update a cached request, using the headers from the last response.
232
+ *
233
+ * @param Google_HttpRequest $cached
234
+ * A previously cached response.
235
+ * @param
236
+ * mixed Associative array of response headers from the last request.
237
+ */
238
+ protected function updateCachedRequest($cached, $responseHeaders)
239
+ {
240
+ if (isset($responseHeaders['connection'])) {
241
+ $hopByHop = array_merge(self::$HOP_BY_HOP, explode(',', $responseHeaders['connection']));
242
+ $endToEnd = array();
243
+ foreach ($hopByHop as $key) {
244
+ if (isset($responseHeaders[$key])) {
245
+ $endToEnd[$key] = $responseHeaders[$key];
246
+ }
247
+ }
248
+ $cached->setResponseHeaders($endToEnd);
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Used by the IO lib and also the batch processing.
254
+ *
255
+ * @param
256
+ * $respData
257
+ * @param
258
+ * $headerSize
259
+ * @return array
260
+ */
261
+ public function parseHttpResponse($respData, $headerSize)
262
+ {
263
+ // check proxy header
264
+ foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) {
265
+ if (stripos($respData, $established_header) !== false) {
266
+ // existed, remove it
267
+ $respData = str_ireplace($established_header, '', $respData);
268
+ // Subtract the proxy header size unless the cURL bug prior to 7.30.0
269
+ // is present which prevented the proxy header size from being taken into
270
+ // account.
271
+ if (! $this->needsQuirk()) {
272
+ $headerSize -= strlen($established_header);
273
+ }
274
+ break;
275
+ }
276
+ }
277
+ if ($headerSize) {
278
+ $responseBody = substr($respData, $headerSize);
279
+ $responseHeaders = substr($respData, 0, $headerSize);
280
+ } else {
281
+ $responseSegments = explode("\r\n\r\n", $respData, 2);
282
+ $responseHeaders = $responseSegments[0];
283
+ $responseBody = isset($responseSegments[1]) ? $responseSegments[1] : null;
284
+ }
285
+ $responseHeaders = $this->getHttpResponseHeaders($responseHeaders);
286
+ return array(
287
+ $responseHeaders,
288
+ $responseBody
289
+ );
290
+ }
291
+
292
+ /**
293
+ * Parse out headers from raw headers
294
+ *
295
+ * @param
296
+ * rawHeaders array or string
297
+ * @return array
298
+ */
299
+ public function getHttpResponseHeaders($rawHeaders)
300
+ {
301
+ if (is_array($rawHeaders)) {
302
+ return $this->parseArrayHeaders($rawHeaders);
303
+ } else {
304
+ return $this->parseStringHeaders($rawHeaders);
305
+ }
306
+ }
307
+
308
+ private function parseStringHeaders($rawHeaders)
309
+ {
310
+ $headers = array();
311
+ $responseHeaderLines = explode("\r\n", $rawHeaders);
312
+ foreach ($responseHeaderLines as $headerLine) {
313
+ if ($headerLine && strpos($headerLine, ':') !== false) {
314
+ list ($header, $value) = explode(': ', $headerLine, 2);
315
+ $header = strtolower($header);
316
+ if (isset($headers[$header])) {
317
+ $headers[$header] .= "\n" . $value;
318
+ } else {
319
+ $headers[$header] = $value;
320
+ }
321
+ }
322
+ }
323
+ return $headers;
324
+ }
325
+
326
+ private function parseArrayHeaders($rawHeaders)
327
+ {
328
+ $header_count = count($rawHeaders);
329
+ $headers = array();
330
+ for ($i = 0; $i < $header_count; $i ++) {
331
+ $header = $rawHeaders[$i];
332
+ // Times will have colons in - so we just want the first match.
333
+ $header_parts = explode(': ', $header, 2);
334
+ if (count($header_parts) == 2) {
335
+ $headers[$header_parts[0]] = $header_parts[1];
336
+ }
337
+ }
338
+ return $headers;
339
+ }
340
  }
tools/src/Google/IO/Curl.php CHANGED
@@ -1,153 +1,153 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- /**
18
- * Curl based implementation of Google_IO.
19
- *
20
- * @author Stuart Langley <slangley@google.com>
21
- */
22
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
23
-
24
- class Google_IO_Curl extends Google_IO_Abstract
25
- {
26
- // cURL hex representation of version 7.30.0
27
- const NO_QUIRK_VERSION = 0x071E00;
28
-
29
- private $options = array();
30
-
31
- /**
32
- * Execute an HTTP Request
33
- *
34
- * @param Google_HttpRequest $request
35
- * the http request to be executed
36
- * @return Google_HttpRequest http request with the response http code,
37
- * response headers and response body filled in
38
- * @throws Google_IO_Exception on curl or IO error
39
- */
40
- public function executeRequest(Google_Http_Request $request)
41
- {
42
- $curl = curl_init();
43
- if ($request->getPostBody()) {
44
- curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getPostBody());
45
- }
46
- $requestHeaders = $request->getRequestHeaders();
47
- if ($requestHeaders && is_array($requestHeaders)) {
48
- $curlHeaders = array();
49
- foreach ($requestHeaders as $k => $v) {
50
- $curlHeaders[] = "$k: $v";
51
- }
52
- curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
53
- }
54
- curl_setopt($curl, CURLOPT_URL, $request->getUrl());
55
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
56
- curl_setopt($curl, CURLOPT_USERAGENT, $request->getUserAgent());
57
- curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
58
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
59
- // 1 is CURL_SSLVERSION_TLSv1, which is not always defined in PHP.
60
- curl_setopt($curl, CURLOPT_SSLVERSION, 1);
61
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
62
- curl_setopt($curl, CURLOPT_HEADER, true);
63
- if ($request->canGzip()) {
64
- curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
65
- }
66
- $options = $this->client->getClassConfig('Google_IO_Curl', 'options');
67
- if (is_array($options)) {
68
- $this->setOptions($options);
69
- }
70
- foreach ($this->options as $key => $var) {
71
- curl_setopt($curl, $key, $var);
72
- }
73
- if (! isset($this->options[CURLOPT_CAINFO])) {
74
- curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
75
- }
76
- $this->client->getLogger()->debug('cURL request', array(
77
- 'url' => $request->getUrl(),
78
- 'method' => $request->getRequestMethod(),
79
- 'headers' => $requestHeaders,
80
- 'body' => $request->getPostBody()
81
- ));
82
- $response = curl_exec($curl);
83
- if ($response === false) {
84
- $error = curl_error($curl);
85
- $this->client->getLogger()->error('cURL ' . $error);
86
- throw new Google_IO_Exception($error);
87
- }
88
- $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
89
- list ($responseHeaders, $responseBody) = $this->parseHttpResponse($response, $headerSize);
90
- $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
91
- $this->client->getLogger()->debug('cURL response', array(
92
- 'code' => $responseCode,
93
- 'headers' => $responseHeaders,
94
- 'body' => $responseBody
95
- ));
96
- return array(
97
- $responseBody,
98
- $responseHeaders,
99
- $responseCode
100
- );
101
- }
102
-
103
- /**
104
- * Set options that update the transport implementation's behavior.
105
- *
106
- * @param
107
- * $options
108
- */
109
- public function setOptions($options)
110
- {
111
- $this->options = $options + $this->options;
112
- }
113
-
114
- /**
115
- * Set the maximum request time in seconds.
116
- *
117
- * @param $timeout in
118
- * seconds
119
- */
120
- public function setTimeout($timeout)
121
- {
122
- // Since this timeout is really for putting a bound on the time
123
- // we'll set them both to the same. If you need to specify a longer
124
- // CURLOPT_TIMEOUT, or a tigher CONNECTTIMEOUT, the best thing to
125
- // do is use the setOptions method for the values individually.
126
- $this->options[CURLOPT_CONNECTTIMEOUT] = $timeout;
127
- $this->options[CURLOPT_TIMEOUT] = $timeout;
128
- }
129
-
130
- /**
131
- * Get the maximum request time in seconds.
132
- *
133
- * @return timeout in seconds
134
- */
135
- public function getTimeout()
136
- {
137
- return $this->options[CURLOPT_TIMEOUT];
138
- }
139
-
140
- /**
141
- * Test for the presence of a cURL header processing bug
142
- *
143
- * {@inheritDoc}
144
- *
145
- * @return boolean
146
- */
147
- protected function needsQuirk()
148
- {
149
- $ver = curl_version();
150
- $versionNum = $ver['version_number'];
151
- return $versionNum < Google_IO_Curl::NO_QUIRK_VERSION;
152
- }
153
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Curl based implementation of Google_IO.
19
+ *
20
+ * @author Stuart Langley <slangley@google.com>
21
+ */
22
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
23
+
24
+ class Google_IO_Curl extends Google_IO_Abstract
25
+ {
26
+ // cURL hex representation of version 7.30.0
27
+ const NO_QUIRK_VERSION = 0x071E00;
28
+
29
+ private $options = array();
30
+
31
+ /**
32
+ * Execute an HTTP Request
33
+ *
34
+ * @param Google_HttpRequest $request
35
+ * the http request to be executed
36
+ * @return Google_HttpRequest http request with the response http code,
37
+ * response headers and response body filled in
38
+ * @throws Google_IO_Exception on curl or IO error
39
+ */
40
+ public function executeRequest(Google_Http_Request $request)
41
+ {
42
+ $curl = curl_init();
43
+ if ($request->getPostBody()) {
44
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getPostBody());
45
+ }
46
+ $requestHeaders = $request->getRequestHeaders();
47
+ if ($requestHeaders && is_array($requestHeaders)) {
48
+ $curlHeaders = array();
49
+ foreach ($requestHeaders as $k => $v) {
50
+ $curlHeaders[] = "$k: $v";
51
+ }
52
+ curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
53
+ }
54
+ curl_setopt($curl, CURLOPT_URL, $request->getUrl());
55
+ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
56
+ curl_setopt($curl, CURLOPT_USERAGENT, $request->getUserAgent());
57
+ curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
58
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
59
+ // 1 is CURL_SSLVERSION_TLSv1, which is not always defined in PHP.
60
+ curl_setopt($curl, CURLOPT_SSLVERSION, 1);
61
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
62
+ curl_setopt($curl, CURLOPT_HEADER, true);
63
+ if ($request->canGzip()) {
64
+ curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
65
+ }
66
+ $options = $this->client->getClassConfig('Google_IO_Curl', 'options');
67
+ if (is_array($options)) {
68
+ $this->setOptions($options);
69
+ }
70
+ foreach ($this->options as $key => $var) {
71
+ curl_setopt($curl, $key, $var);
72
+ }
73
+ if (! isset($this->options[CURLOPT_CAINFO])) {
74
+ curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
75
+ }
76
+ $this->client->getLogger()->debug('cURL request', array(
77
+ 'url' => $request->getUrl(),
78
+ 'method' => $request->getRequestMethod(),
79
+ 'headers' => $requestHeaders,
80
+ 'body' => $request->getPostBody()
81
+ ));
82
+ $response = curl_exec($curl);
83
+ if ($response === false) {
84
+ $error = curl_error($curl);
85
+ $this->client->getLogger()->error('cURL ' . $error);
86
+ throw new Google_IO_Exception($error);
87
+ }
88
+ $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
89
+ list ($responseHeaders, $responseBody) = $this->parseHttpResponse($response, $headerSize);
90
+ $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
91
+ $this->client->getLogger()->debug('cURL response', array(
92
+ 'code' => $responseCode,
93
+ 'headers' => $responseHeaders,
94
+ 'body' => $responseBody
95
+ ));
96
+ return array(
97
+ $responseBody,
98
+ $responseHeaders,
99
+ $responseCode
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Set options that update the transport implementation's behavior.
105
+ *
106
+ * @param
107
+ * $options
108
+ */
109
+ public function setOptions($options)
110
+ {
111
+ $this->options = $options + $this->options;
112
+ }
113
+
114
+ /**
115
+ * Set the maximum request time in seconds.
116
+ *
117
+ * @param $timeout in
118
+ * seconds
119
+ */
120
+ public function setTimeout($timeout)
121
+ {
122
+ // Since this timeout is really for putting a bound on the time
123
+ // we'll set them both to the same. If you need to specify a longer
124
+ // CURLOPT_TIMEOUT, or a tigher CONNECTTIMEOUT, the best thing to
125
+ // do is use the setOptions method for the values individually.
126
+ $this->options[CURLOPT_CONNECTTIMEOUT] = $timeout;
127
+ $this->options[CURLOPT_TIMEOUT] = $timeout;
128
+ }
129
+
130
+ /**
131
+ * Get the maximum request time in seconds.
132
+ *
133
+ * @return timeout in seconds
134
+ */
135
+ public function getTimeout()
136
+ {
137
+ return $this->options[CURLOPT_TIMEOUT];
138
+ }
139
+
140
+ /**
141
+ * Test for the presence of a cURL header processing bug
142
+ *
143
+ * {@inheritDoc}
144
+ *
145
+ * @return boolean
146
+ */
147
+ protected function needsQuirk()
148
+ {
149
+ $ver = curl_version();
150
+ $versionNum = $ver['version_number'];
151
+ return $versionNum < Google_IO_Curl::NO_QUIRK_VERSION;
152
+ }
153
  }
tools/src/Google/IO/Exception.php CHANGED
@@ -1,21 +1,21 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- class Google_IO_Exception extends Google_Exception
20
- {
21
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ class Google_IO_Exception extends Google_Exception
20
+ {
21
  }
tools/src/Google/IO/Stream.php CHANGED
@@ -1,202 +1,202 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- /**
18
- * Http Streams based implementation of Google_IO.
19
- *
20
- * @author Stuart Langley <slangley@google.com>
21
- */
22
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
23
-
24
- class Google_IO_Stream extends Google_IO_Abstract
25
- {
26
-
27
- const TIMEOUT = "timeout";
28
-
29
- const ZLIB = "compress.zlib://";
30
-
31
- private $options = array();
32
-
33
- private $trappedErrorNumber;
34
-
35
- private $trappedErrorString;
36
-
37
- private static $DEFAULT_HTTP_CONTEXT = array(
38
- "follow_location" => 0,
39
- "ignore_errors" => 1
40
- );
41
-
42
- private static $DEFAULT_SSL_CONTEXT = array(
43
- "verify_peer" => true
44
- );
45
-
46
- /**
47
- * Execute an HTTP Request
48
- *
49
- * @param Google_HttpRequest $request
50
- * the http request to be executed
51
- * @return Google_HttpRequest http request with the response http code,
52
- * response headers and response body filled in
53
- * @throws Google_IO_Exception on curl or IO error
54
- */
55
- public function executeRequest(Google_Http_Request $request)
56
- {
57
- $default_options = stream_context_get_options(stream_context_get_default());
58
- $requestHttpContext = array_key_exists('http', $default_options) ? $default_options['http'] : array();
59
- if ($request->getPostBody()) {
60
- $requestHttpContext["content"] = $request->getPostBody();
61
- }
62
- $requestHeaders = $request->getRequestHeaders();
63
- if ($requestHeaders && is_array($requestHeaders)) {
64
- $headers = "";
65
- foreach ($requestHeaders as $k => $v) {
66
- $headers .= "$k: $v\r\n";
67
- }
68
- $requestHttpContext["header"] = $headers;
69
- }
70
- $requestHttpContext["method"] = $request->getRequestMethod();
71
- $requestHttpContext["user_agent"] = $request->getUserAgent();
72
- $requestSslContext = array_key_exists('ssl', $default_options) ? $default_options['ssl'] : array();
73
- if (! array_key_exists("cafile", $requestSslContext)) {
74
- $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
75
- }
76
- $options = array(
77
- "http" => array_merge(self::$DEFAULT_HTTP_CONTEXT, $requestHttpContext),
78
- "ssl" => array_merge(self::$DEFAULT_SSL_CONTEXT, $requestSslContext)
79
- );
80
- $context = stream_context_create($options);
81
- $url = $request->getUrl();
82
- if ($request->canGzip()) {
83
- $url = self::ZLIB . $url;
84
- }
85
- $this->client->getLogger()->debug('Stream request', array(
86
- 'url' => $url,
87
- 'method' => $request->getRequestMethod(),
88
- 'headers' => $requestHeaders,
89
- 'body' => $request->getPostBody()
90
- ));
91
- // We are trapping any thrown errors in this method only and
92
- // throwing an exception.
93
- $this->trappedErrorNumber = null;
94
- $this->trappedErrorString = null;
95
- // START - error trap.
96
- set_error_handler(array(
97
- $this,
98
- 'trapError'
99
- ));
100
- $fh = fopen($url, 'r', false, $context);
101
- restore_error_handler();
102
- // END - error trap.
103
- if ($this->trappedErrorNumber) {
104
- $error = sprintf("HTTP Error: Unable to connect: '%s'", $this->trappedErrorString);
105
- $this->client->getLogger()->error('Stream ' . $error);
106
- throw new Google_IO_Exception($error, $this->trappedErrorNumber);
107
- }
108
- $response_data = false;
109
- $respHttpCode = self::UNKNOWN_CODE;
110
- if ($fh) {
111
- if (isset($this->options[self::TIMEOUT])) {
112
- stream_set_timeout($fh, $this->options[self::TIMEOUT]);
113
- }
114
- $response_data = stream_get_contents($fh);
115
- fclose($fh);
116
- $respHttpCode = $this->getHttpResponseCode($http_response_header);
117
- }
118
- if (false === $response_data) {
119
- $error = sprintf("HTTP Error: Unable to connect: '%s'", $respHttpCode);
120
- $this->client->getLogger()->error('Stream ' . $error);
121
- throw new Google_IO_Exception($error, $respHttpCode);
122
- }
123
- $responseHeaders = $this->getHttpResponseHeaders($http_response_header);
124
- $this->client->getLogger()->debug('Stream response', array(
125
- 'code' => $respHttpCode,
126
- 'headers' => $responseHeaders,
127
- 'body' => $response_data
128
- ));
129
- return array(
130
- $response_data,
131
- $responseHeaders,
132
- $respHttpCode
133
- );
134
- }
135
-
136
- /**
137
- * Set options that update the transport implementation's behavior.
138
- *
139
- * @param
140
- * $options
141
- */
142
- public function setOptions($options)
143
- {
144
- $this->options = $options + $this->options;
145
- }
146
-
147
- /**
148
- * Method to handle errors, used for error handling around
149
- * stream connection methods.
150
- */
151
- public function trapError($errno, $errstr)
152
- {
153
- $this->trappedErrorNumber = $errno;
154
- $this->trappedErrorString = $errstr;
155
- }
156
-
157
- /**
158
- * Set the maximum request time in seconds.
159
- *
160
- * @param $timeout in
161
- * seconds
162
- */
163
- public function setTimeout($timeout)
164
- {
165
- $this->options[self::TIMEOUT] = $timeout;
166
- }
167
-
168
- /**
169
- * Get the maximum request time in seconds.
170
- *
171
- * @return timeout in seconds
172
- */
173
- public function getTimeout()
174
- {
175
- return $this->options[self::TIMEOUT];
176
- }
177
-
178
- /**
179
- * Test for the presence of a cURL header processing bug
180
- *
181
- * {@inheritDoc}
182
- *
183
- * @return boolean
184
- */
185
- protected function needsQuirk()
186
- {
187
- return false;
188
- }
189
-
190
- protected function getHttpResponseCode($response_headers)
191
- {
192
- $header_count = count($response_headers);
193
- for ($i = 0; $i < $header_count; $i ++) {
194
- $header = $response_headers[$i];
195
- if (strncasecmp("HTTP", $header, strlen("HTTP")) == 0) {
196
- $response = explode(' ', $header);
197
- return $response[1];
198
- }
199
- }
200
- return self::UNKNOWN_CODE;
201
- }
202
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Http Streams based implementation of Google_IO.
19
+ *
20
+ * @author Stuart Langley <slangley@google.com>
21
+ */
22
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
23
+
24
+ class Google_IO_Stream extends Google_IO_Abstract
25
+ {
26
+
27
+ const TIMEOUT = "timeout";
28
+
29
+ const ZLIB = "compress.zlib://";
30
+
31
+ private $options = array();
32
+
33
+ private $trappedErrorNumber;
34
+
35
+ private $trappedErrorString;
36
+
37
+ private static $DEFAULT_HTTP_CONTEXT = array(
38
+ "follow_location" => 0,
39
+ "ignore_errors" => 1
40
+ );
41
+
42
+ private static $DEFAULT_SSL_CONTEXT = array(
43
+ "verify_peer" => true
44
+ );
45
+
46
+ /**
47
+ * Execute an HTTP Request
48
+ *
49
+ * @param Google_HttpRequest $request
50
+ * the http request to be executed
51
+ * @return Google_HttpRequest http request with the response http code,
52
+ * response headers and response body filled in
53
+ * @throws Google_IO_Exception on curl or IO error
54
+ */
55
+ public function executeRequest(Google_Http_Request $request)
56
+ {
57
+ $default_options = stream_context_get_options(stream_context_get_default());
58
+ $requestHttpContext = array_key_exists('http', $default_options) ? $default_options['http'] : array();
59
+ if ($request->getPostBody()) {
60
+ $requestHttpContext["content"] = $request->getPostBody();
61
+ }
62
+ $requestHeaders = $request->getRequestHeaders();
63
+ if ($requestHeaders && is_array($requestHeaders)) {
64
+ $headers = "";
65
+ foreach ($requestHeaders as $k => $v) {
66
+ $headers .= "$k: $v\r\n";
67
+ }
68
+ $requestHttpContext["header"] = $headers;
69
+ }
70
+ $requestHttpContext["method"] = $request->getRequestMethod();
71
+ $requestHttpContext["user_agent"] = $request->getUserAgent();
72
+ $requestSslContext = array_key_exists('ssl', $default_options) ? $default_options['ssl'] : array();
73
+ if (! array_key_exists("cafile", $requestSslContext)) {
74
+ $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
75
+ }
76
+ $options = array(
77
+ "http" => array_merge(self::$DEFAULT_HTTP_CONTEXT, $requestHttpContext),
78
+ "ssl" => array_merge(self::$DEFAULT_SSL_CONTEXT, $requestSslContext)
79
+ );
80
+ $context = stream_context_create($options);
81
+ $url = $request->getUrl();
82
+ if ($request->canGzip()) {
83
+ $url = self::ZLIB . $url;
84
+ }
85
+ $this->client->getLogger()->debug('Stream request', array(
86
+ 'url' => $url,
87
+ 'method' => $request->getRequestMethod(),
88
+ 'headers' => $requestHeaders,
89
+ 'body' => $request->getPostBody()
90
+ ));
91
+ // We are trapping any thrown errors in this method only and
92
+ // throwing an exception.
93
+ $this->trappedErrorNumber = null;
94
+ $this->trappedErrorString = null;
95
+ // START - error trap.
96
+ set_error_handler(array(
97
+ $this,
98
+ 'trapError'
99
+ ));
100
+ $fh = fopen($url, 'r', false, $context);
101
+ restore_error_handler();
102
+ // END - error trap.
103
+ if ($this->trappedErrorNumber) {
104
+ $error = sprintf("HTTP Error: Unable to connect: '%s'", $this->trappedErrorString);
105
+ $this->client->getLogger()->error('Stream ' . $error);
106
+ throw new Google_IO_Exception($error, $this->trappedErrorNumber);
107
+ }
108
+ $response_data = false;
109
+ $respHttpCode = self::UNKNOWN_CODE;
110
+ if ($fh) {
111
+ if (isset($this->options[self::TIMEOUT])) {
112
+ stream_set_timeout($fh, $this->options[self::TIMEOUT]);
113
+ }
114
+ $response_data = stream_get_contents($fh);
115
+ fclose($fh);
116
+ $respHttpCode = $this->getHttpResponseCode($http_response_header);
117
+ }
118
+ if (false === $response_data) {
119
+ $error = sprintf("HTTP Error: Unable to connect: '%s'", $respHttpCode);
120
+ $this->client->getLogger()->error('Stream ' . $error);
121
+ throw new Google_IO_Exception($error, $respHttpCode);
122
+ }
123
+ $responseHeaders = $this->getHttpResponseHeaders($http_response_header);
124
+ $this->client->getLogger()->debug('Stream response', array(
125
+ 'code' => $respHttpCode,
126
+ 'headers' => $responseHeaders,
127
+ 'body' => $response_data
128
+ ));
129
+ return array(
130
+ $response_data,
131
+ $responseHeaders,
132
+ $respHttpCode
133
+ );
134
+ }
135
+
136
+ /**
137
+ * Set options that update the transport implementation's behavior.
138
+ *
139
+ * @param
140
+ * $options
141
+ */
142
+ public function setOptions($options)
143
+ {
144
+ $this->options = $options + $this->options;
145
+ }
146
+
147
+ /**
148
+ * Method to handle errors, used for error handling around
149
+ * stream connection methods.
150
+ */
151
+ public function trapError($errno, $errstr)
152
+ {
153
+ $this->trappedErrorNumber = $errno;
154
+ $this->trappedErrorString = $errstr;
155
+ }
156
+
157
+ /**
158
+ * Set the maximum request time in seconds.
159
+ *
160
+ * @param $timeout in
161
+ * seconds
162
+ */
163
+ public function setTimeout($timeout)
164
+ {
165
+ $this->options[self::TIMEOUT] = $timeout;
166
+ }
167
+
168
+ /**
169
+ * Get the maximum request time in seconds.
170
+ *
171
+ * @return timeout in seconds
172
+ */
173
+ public function getTimeout()
174
+ {
175
+ return $this->options[self::TIMEOUT];
176
+ }
177
+
178
+ /**
179
+ * Test for the presence of a cURL header processing bug
180
+ *
181
+ * {@inheritDoc}
182
+ *
183
+ * @return boolean
184
+ */
185
+ protected function needsQuirk()
186
+ {
187
+ return false;
188
+ }
189
+
190
+ protected function getHttpResponseCode($response_headers)
191
+ {
192
+ $header_count = count($response_headers);
193
+ for ($i = 0; $i < $header_count; $i ++) {
194
+ $header = $response_headers[$i];
195
+ if (strncasecmp("HTTP", $header, strlen("HTTP")) == 0) {
196
+ $response = explode(' ', $header);
197
+ return $response[1];
198
+ }
199
+ }
200
+ return self::UNKNOWN_CODE;
201
+ }
202
  }
tools/src/Google/Logger/Abstract.php CHANGED
@@ -1,410 +1,410 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * Abstract logging class based on the PSR-3 standard.
21
- *
22
- * NOTE: We don't implement `Psr\Log\LoggerInterface` because we need to
23
- * maintain PHP 5.2 support.
24
- *
25
- * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
26
- */
27
- abstract class Google_Logger_Abstract
28
- {
29
-
30
- /**
31
- * Default log format
32
- */
33
- const DEFAULT_LOG_FORMAT = "[%datetime%] %level%: %message% %context%\n";
34
-
35
- /**
36
- * Default date format
37
- *
38
- * Example: 16/Nov/2014:03:26:16 -0500
39
- */
40
- const DEFAULT_DATE_FORMAT = 'd/M/Y:H:i:s O';
41
-
42
- /**
43
- * System is unusable
44
- */
45
- const EMERGENCY = 'emergency';
46
-
47
- /**
48
- * Action must be taken immediately
49
- *
50
- * Example: Entire website down, database unavailable, etc. This should
51
- * trigger the SMS alerts and wake you up.
52
- */
53
- const ALERT = 'alert';
54
-
55
- /**
56
- * Critical conditions
57
- *
58
- * Example: Application component unavailable, unexpected exception.
59
- */
60
- const CRITICAL = 'critical';
61
-
62
- /**
63
- * Runtime errors that do not require immediate action but should typically
64
- * be logged and monitored.
65
- */
66
- const ERROR = 'error';
67
-
68
- /**
69
- * Exceptional occurrences that are not errors.
70
- *
71
- * Example: Use of deprecated APIs, poor use of an API, undesirable things
72
- * that are not necessarily wrong.
73
- */
74
- const WARNING = 'warning';
75
-
76
- /**
77
- * Normal but significant events.
78
- */
79
- const NOTICE = 'notice';
80
-
81
- /**
82
- * Interesting events.
83
- *
84
- * Example: User logs in, SQL logs.
85
- */
86
- const INFO = 'info';
87
-
88
- /**
89
- * Detailed debug information.
90
- */
91
- const DEBUG = 'debug';
92
-
93
- /**
94
- *
95
- * @var array $levels Logging levels
96
- */
97
- protected static $levels = array(
98
- self::EMERGENCY => 600,
99
- self::ALERT => 550,
100
- self::CRITICAL => 500,
101
- self::ERROR => 400,
102
- self::WARNING => 300,
103
- self::NOTICE => 250,
104
- self::INFO => 200,
105
- self::DEBUG => 100
106
- );
107
-
108
- /**
109
- *
110
- * @var integer $level The minimum logging level
111
- */
112
- protected $level = self::DEBUG;
113
-
114
- /**
115
- *
116
- * @var string $logFormat The current log format
117
- */
118
- protected $logFormat = self::DEFAULT_LOG_FORMAT;
119
-
120
- /**
121
- *
122
- * @var string $dateFormat The current date format
123
- */
124
- protected $dateFormat = self::DEFAULT_DATE_FORMAT;
125
-
126
- /**
127
- *
128
- * @var boolean $allowNewLines If newlines are allowed
129
- */
130
- protected $allowNewLines = false;
131
-
132
- /**
133
- *
134
- * @param Google_Client $client
135
- * The current Google client
136
- */
137
- public function __construct(Google_Client $client)
138
- {
139
- $this->setLevel($client->getClassConfig('Google_Logger_Abstract', 'level'));
140
- $format = $client->getClassConfig('Google_Logger_Abstract', 'log_format');
141
- $this->logFormat = $format ? $format : self::DEFAULT_LOG_FORMAT;
142
- $format = $client->getClassConfig('Google_Logger_Abstract', 'date_format');
143
- $this->dateFormat = $format ? $format : self::DEFAULT_DATE_FORMAT;
144
- $this->allowNewLines = (bool) $client->getClassConfig('Google_Logger_Abstract', 'allow_newlines');
145
- }
146
-
147
- /**
148
- * Sets the minimum logging level that this logger handles.
149
- *
150
- * @param integer $level
151
- */
152
- public function setLevel($level)
153
- {
154
- $this->level = $this->normalizeLevel($level);
155
- }
156
-
157
- /**
158
- * Checks if the logger should handle messages at the provided level.
159
- *
160
- * @param integer $level
161
- * @return boolean
162
- */
163
- public function shouldHandle($level)
164
- {
165
- return $this->normalizeLevel($level) >= $this->level;
166
- }
167
-
168
- /**
169
- * System is unusable.
170
- *
171
- * @param string $message
172
- * The log message
173
- * @param array $context
174
- * The log context
175
- */
176
- public function emergency($message, array $context = array())
177
- {
178
- $this->log(self::EMERGENCY, $message, $context);
179
- }
180
-
181
- /**
182
- * Action must be taken immediately.
183
- *
184
- * Example: Entire website down, database unavailable, etc. This should
185
- * trigger the SMS alerts and wake you up.
186
- *
187
- * @param string $message
188
- * The log message
189
- * @param array $context
190
- * The log context
191
- */
192
- public function alert($message, array $context = array())
193
- {
194
- $this->log(self::ALERT, $message, $context);
195
- }
196
-
197
- /**
198
- * Critical conditions.
199
- *
200
- * Example: Application component unavailable, unexpected exception.
201
- *
202
- * @param string $message
203
- * The log message
204
- * @param array $context
205
- * The log context
206
- */
207
- public function critical($message, array $context = array())
208
- {
209
- $this->log(self::CRITICAL, $message, $context);
210
- }
211
-
212
- /**
213
- * Runtime errors that do not require immediate action but should typically
214
- * be logged and monitored.
215
- *
216
- * @param string $message
217
- * The log message
218
- * @param array $context
219
- * The log context
220
- */
221
- public function error($message, array $context = array())
222
- {
223
- $this->log(self::ERROR, $message, $context);
224
- }
225
-
226
- /**
227
- * Exceptional occurrences that are not errors.
228
- *
229
- * Example: Use of deprecated APIs, poor use of an API, undesirable things
230
- * that are not necessarily wrong.
231
- *
232
- * @param string $message
233
- * The log message
234
- * @param array $context
235
- * The log context
236
- */
237
- public function warning($message, array $context = array())
238
- {
239
- $this->log(self::WARNING, $message, $context);
240
- }
241
-
242
- /**
243
- * Normal but significant events.
244
- *
245
- * @param string $message
246
- * The log message
247
- * @param array $context
248
- * The log context
249
- */
250
- public function notice($message, array $context = array())
251
- {
252
- $this->log(self::NOTICE, $message, $context);
253
- }
254
-
255
- /**
256
- * Interesting events.
257
- *
258
- * Example: User logs in, SQL logs.
259
- *
260
- * @param string $message
261
- * The log message
262
- * @param array $context
263
- * The log context
264
- */
265
- public function info($message, array $context = array())
266
- {
267
- $this->log(self::INFO, $message, $context);
268
- }
269
-
270
- /**
271
- * Detailed debug information.
272
- *
273
- * @param string $message
274
- * The log message
275
- * @param array $context
276
- * The log context
277
- */
278
- public function debug($message, array $context = array())
279
- {
280
- $this->log(self::DEBUG, $message, $context);
281
- }
282
-
283
- /**
284
- * Logs with an arbitrary level.
285
- *
286
- * @param mixed $level
287
- * The log level
288
- * @param string $message
289
- * The log message
290
- * @param array $context
291
- * The log context
292
- */
293
- public function log($level, $message, array $context = array())
294
- {
295
- if (! $this->shouldHandle($level)) {
296
- return false;
297
- }
298
- $levelName = is_int($level) ? array_search($level, self::$levels) : $level;
299
- $message = $this->interpolate(array(
300
- 'message' => $message,
301
- 'context' => $context,
302
- 'level' => strtoupper($levelName),
303
- 'datetime' => new DateTime()
304
- ));
305
- $this->write($message);
306
- }
307
-
308
- /**
309
- * Interpolates log variables into the defined log format.
310
- *
311
- * @param array $variables
312
- * The log variables.
313
- * @return string
314
- */
315
- protected function interpolate(array $variables = array())
316
- {
317
- $template = $this->logFormat;
318
- if (! $variables['context']) {
319
- $template = str_replace('%context%', '', $template);
320
- unset($variables['context']);
321
- } else {
322
- $this->reverseJsonInContext($variables['context']);
323
- }
324
- foreach ($variables as $key => $value) {
325
- if (strpos($template, '%' . $key . '%') !== false) {
326
- $template = str_replace('%' . $key . '%', $this->export($value), $template);
327
- }
328
- }
329
- return $template;
330
- }
331
-
332
- /**
333
- * Reverses JSON encoded PHP arrays and objects so that they log better.
334
- *
335
- * @param array $context
336
- * The log context
337
- */
338
- protected function reverseJsonInContext(array &$context)
339
- {
340
- if (! $context) {
341
- return;
342
- }
343
- foreach ($context as $key => $val) {
344
- if (! $val || ! is_string($val) || ! ($val[0] == '{' || $val[0] == '[')) {
345
- continue;
346
- }
347
- $json = @json_decode($val);
348
- if (is_object($json) || is_array($json)) {
349
- $context[$key] = $json;
350
- }
351
- }
352
- }
353
-
354
- /**
355
- * Exports a PHP value for logging to a string.
356
- *
357
- * @param mixed $value
358
- * The value to
359
- */
360
- protected function export($value)
361
- {
362
- if (is_string($value)) {
363
- if ($this->allowNewLines) {
364
- return $value;
365
- }
366
- return preg_replace('/[\r\n]+/', ' ', $value);
367
- }
368
- if (is_resource($value)) {
369
- return sprintf('resource(%d) of type (%s)', $value, get_resource_type($value));
370
- }
371
- if ($value instanceof DateTime) {
372
- return $value->format($this->dateFormat);
373
- }
374
- if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
375
- $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
376
- if ($this->allowNewLines) {
377
- $options |= JSON_PRETTY_PRINT;
378
- }
379
- return @json_encode($value, $options);
380
- }
381
- return str_replace('\\/', '/', @json_encode($value));
382
- }
383
-
384
- /**
385
- * Converts a given log level to the integer form.
386
- *
387
- * @param mixed $level
388
- * The logging level
389
- * @return integer $level The normalized level
390
- * @throws Google_Logger_Exception If $level is invalid
391
- */
392
- protected function normalizeLevel($level)
393
- {
394
- if (is_int($level) && array_search($level, self::$levels) !== false) {
395
- return $level;
396
- }
397
- if (is_string($level) && isset(self::$levels[$level])) {
398
- return self::$levels[$level];
399
- }
400
- throw new Google_Logger_Exception(sprintf("Unknown LogLevel: '%s'", $level));
401
- }
402
-
403
- /**
404
- * Writes a message to the current log implementation.
405
- *
406
- * @param string $message
407
- * The message
408
- */
409
- abstract protected function write($message);
410
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * Abstract logging class based on the PSR-3 standard.
21
+ *
22
+ * NOTE: We don't implement `Psr\Log\LoggerInterface` because we need to
23
+ * maintain PHP 5.2 support.
24
+ *
25
+ * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
26
+ */
27
+ abstract class Google_Logger_Abstract
28
+ {
29
+
30
+ /**
31
+ * Default log format
32
+ */
33
+ const DEFAULT_LOG_FORMAT = "[%datetime%] %level%: %message% %context%\n";
34
+
35
+ /**
36
+ * Default date format
37
+ *
38
+ * Example: 16/Nov/2014:03:26:16 -0500
39
+ */
40
+ const DEFAULT_DATE_FORMAT = 'd/M/Y:H:i:s O';
41
+
42
+ /**
43
+ * System is unusable
44
+ */
45
+ const EMERGENCY = 'emergency';
46
+
47
+ /**
48
+ * Action must be taken immediately
49
+ *
50
+ * Example: Entire website down, database unavailable, etc. This should
51
+ * trigger the SMS alerts and wake you up.
52
+ */
53
+ const ALERT = 'alert';
54
+
55
+ /**
56
+ * Critical conditions
57
+ *
58
+ * Example: Application component unavailable, unexpected exception.
59
+ */
60
+ const CRITICAL = 'critical';
61
+
62
+ /**
63
+ * Runtime errors that do not require immediate action but should typically
64
+ * be logged and monitored.
65
+ */
66
+ const ERROR = 'error';
67
+
68
+ /**
69
+ * Exceptional occurrences that are not errors.
70
+ *
71
+ * Example: Use of deprecated APIs, poor use of an API, undesirable things
72
+ * that are not necessarily wrong.
73
+ */
74
+ const WARNING = 'warning';
75
+
76
+ /**
77
+ * Normal but significant events.
78
+ */
79
+ const NOTICE = 'notice';
80
+
81
+ /**
82
+ * Interesting events.
83
+ *
84
+ * Example: User logs in, SQL logs.
85
+ */
86
+ const INFO = 'info';
87
+
88
+ /**
89
+ * Detailed debug information.
90
+ */
91
+ const DEBUG = 'debug';
92
+
93
+ /**
94
+ *
95
+ * @var array $levels Logging levels
96
+ */
97
+ protected static $levels = array(
98
+ self::EMERGENCY => 600,
99
+ self::ALERT => 550,
100
+ self::CRITICAL => 500,
101
+ self::ERROR => 400,
102
+ self::WARNING => 300,
103
+ self::NOTICE => 250,
104
+ self::INFO => 200,
105
+ self::DEBUG => 100
106
+ );
107
+
108
+ /**
109
+ *
110
+ * @var integer $level The minimum logging level
111
+ */
112
+ protected $level = self::DEBUG;
113
+
114
+ /**
115
+ *
116
+ * @var string $logFormat The current log format
117
+ */
118
+ protected $logFormat = self::DEFAULT_LOG_FORMAT;
119
+
120
+ /**
121
+ *
122
+ * @var string $dateFormat The current date format
123
+ */
124
+ protected $dateFormat = self::DEFAULT_DATE_FORMAT;
125
+
126
+ /**
127
+ *
128
+ * @var boolean $allowNewLines If newlines are allowed
129
+ */
130
+ protected $allowNewLines = false;
131
+
132
+ /**
133
+ *
134
+ * @param Google_Client $client
135
+ * The current Google client
136
+ */
137
+ public function __construct(Google_Client $client)
138
+ {
139
+ $this->setLevel($client->getClassConfig('Google_Logger_Abstract', 'level'));
140
+ $format = $client->getClassConfig('Google_Logger_Abstract', 'log_format');
141
+ $this->logFormat = $format ? $format : self::DEFAULT_LOG_FORMAT;
142
+ $format = $client->getClassConfig('Google_Logger_Abstract', 'date_format');
143
+ $this->dateFormat = $format ? $format : self::DEFAULT_DATE_FORMAT;
144
+ $this->allowNewLines = (bool) $client->getClassConfig('Google_Logger_Abstract', 'allow_newlines');
145
+ }
146
+
147
+ /**
148
+ * Sets the minimum logging level that this logger handles.
149
+ *
150
+ * @param integer $level
151
+ */
152
+ public function setLevel($level)
153
+ {
154
+ $this->level = $this->normalizeLevel($level);
155
+ }
156
+
157
+ /**
158
+ * Checks if the logger should handle messages at the provided level.
159
+ *
160
+ * @param integer $level
161
+ * @return boolean
162
+ */
163
+ public function shouldHandle($level)
164
+ {
165
+ return $this->normalizeLevel($level) >= $this->level;
166
+ }
167
+
168
+ /**
169
+ * System is unusable.
170
+ *
171
+ * @param string $message
172
+ * The log message
173
+ * @param array $context
174
+ * The log context
175
+ */
176
+ public function emergency($message, array $context = array())
177
+ {
178
+ $this->log(self::EMERGENCY, $message, $context);
179
+ }
180
+
181
+ /**
182
+ * Action must be taken immediately.
183
+ *
184
+ * Example: Entire website down, database unavailable, etc. This should
185
+ * trigger the SMS alerts and wake you up.
186
+ *
187
+ * @param string $message
188
+ * The log message
189
+ * @param array $context
190
+ * The log context
191
+ */
192
+ public function alert($message, array $context = array())
193
+ {
194
+ $this->log(self::ALERT, $message, $context);
195
+ }
196
+
197
+ /**
198
+ * Critical conditions.
199
+ *
200
+ * Example: Application component unavailable, unexpected exception.
201
+ *
202
+ * @param string $message
203
+ * The log message
204
+ * @param array $context
205
+ * The log context
206
+ */
207
+ public function critical($message, array $context = array())
208
+ {
209
+ $this->log(self::CRITICAL, $message, $context);
210
+ }
211
+
212
+ /**
213
+ * Runtime errors that do not require immediate action but should typically
214
+ * be logged and monitored.
215
+ *
216
+ * @param string $message
217
+ * The log message
218
+ * @param array $context
219
+ * The log context
220
+ */
221
+ public function error($message, array $context = array())
222
+ {
223
+ $this->log(self::ERROR, $message, $context);
224
+ }
225
+
226
+ /**
227
+ * Exceptional occurrences that are not errors.
228
+ *
229
+ * Example: Use of deprecated APIs, poor use of an API, undesirable things
230
+ * that are not necessarily wrong.
231
+ *
232
+ * @param string $message
233
+ * The log message
234
+ * @param array $context
235
+ * The log context
236
+ */
237
+ public function warning($message, array $context = array())
238
+ {
239
+ $this->log(self::WARNING, $message, $context);
240
+ }
241
+
242
+ /**
243
+ * Normal but significant events.
244
+ *
245
+ * @param string $message
246
+ * The log message
247
+ * @param array $context
248
+ * The log context
249
+ */
250
+ public function notice($message, array $context = array())
251
+ {
252
+ $this->log(self::NOTICE, $message, $context);
253
+ }
254
+
255
+ /**
256
+ * Interesting events.
257
+ *
258
+ * Example: User logs in, SQL logs.
259
+ *
260
+ * @param string $message
261
+ * The log message
262
+ * @param array $context
263
+ * The log context
264
+ */
265
+ public function info($message, array $context = array())
266
+ {
267
+ $this->log(self::INFO, $message, $context);
268
+ }
269
+
270
+ /**
271
+ * Detailed debug information.
272
+ *
273
+ * @param string $message
274
+ * The log message
275
+ * @param array $context
276
+ * The log context
277
+ */
278
+ public function debug($message, array $context = array())
279
+ {
280
+ $this->log(self::DEBUG, $message, $context);
281
+ }
282
+
283
+ /**
284
+ * Logs with an arbitrary level.
285
+ *
286
+ * @param mixed $level
287
+ * The log level
288
+ * @param string $message
289
+ * The log message
290
+ * @param array $context
291
+ * The log context
292
+ */
293
+ public function log($level, $message, array $context = array())
294
+ {
295
+ if (! $this->shouldHandle($level)) {
296
+ return false;
297
+ }
298
+ $levelName = is_int($level) ? array_search($level, self::$levels) : $level;
299
+ $message = $this->interpolate(array(
300
+ 'message' => $message,
301
+ 'context' => $context,
302
+ 'level' => strtoupper($levelName),
303
+ 'datetime' => new DateTime()
304
+ ));
305
+ $this->write($message);
306
+ }
307
+
308
+ /**
309
+ * Interpolates log variables into the defined log format.
310
+ *
311
+ * @param array $variables
312
+ * The log variables.
313
+ * @return string
314
+ */
315
+ protected function interpolate(array $variables = array())
316
+ {
317
+ $template = $this->logFormat;
318
+ if (! $variables['context']) {
319
+ $template = str_replace('%context%', '', $template);
320
+ unset($variables['context']);
321
+ } else {
322
+ $this->reverseJsonInContext($variables['context']);
323
+ }
324
+ foreach ($variables as $key => $value) {
325
+ if (strpos($template, '%' . $key . '%') !== false) {
326
+ $template = str_replace('%' . $key . '%', $this->export($value), $template);
327
+ }
328
+ }
329
+ return $template;
330
+ }
331
+
332
+ /**
333
+ * Reverses JSON encoded PHP arrays and objects so that they log better.
334
+ *
335
+ * @param array $context
336
+ * The log context
337
+ */
338
+ protected function reverseJsonInContext(array &$context)
339
+ {
340
+ if (! $context) {
341
+ return;
342
+ }
343
+ foreach ($context as $key => $val) {
344
+ if (! $val || ! is_string($val) || ! ($val[0] == '{' || $val[0] == '[')) {
345
+ continue;
346
+ }
347
+ $json = @json_decode($val);
348
+ if (is_object($json) || is_array($json)) {
349
+ $context[$key] = $json;
350
+ }
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Exports a PHP value for logging to a string.
356
+ *
357
+ * @param mixed $value
358
+ * The value to
359
+ */
360
+ protected function export($value)
361
+ {
362
+ if (is_string($value)) {
363
+ if ($this->allowNewLines) {
364
+ return $value;
365
+ }
366
+ return preg_replace('/[\r\n]+/', ' ', $value);
367
+ }
368
+ if (is_resource($value)) {
369
+ return sprintf('resource(%d) of type (%s)', $value, get_resource_type($value));
370
+ }
371
+ if ($value instanceof DateTime) {
372
+ return $value->format($this->dateFormat);
373
+ }
374
+ if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
375
+ $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
376
+ if ($this->allowNewLines) {
377
+ $options |= JSON_PRETTY_PRINT;
378
+ }
379
+ return @json_encode($value, $options);
380
+ }
381
+ return str_replace('\\/', '/', @json_encode($value));
382
+ }
383
+
384
+ /**
385
+ * Converts a given log level to the integer form.
386
+ *
387
+ * @param mixed $level
388
+ * The logging level
389
+ * @return integer $level The normalized level
390
+ * @throws Google_Logger_Exception If $level is invalid
391
+ */
392
+ protected function normalizeLevel($level)
393
+ {
394
+ if (is_int($level) && array_search($level, self::$levels) !== false) {
395
+ return $level;
396
+ }
397
+ if (is_string($level) && isset(self::$levels[$level])) {
398
+ return self::$levels[$level];
399
+ }
400
+ throw new Google_Logger_Exception(sprintf("Unknown LogLevel: '%s'", $level));
401
+ }
402
+
403
+ /**
404
+ * Writes a message to the current log implementation.
405
+ *
406
+ * @param string $message
407
+ * The message
408
+ */
409
+ abstract protected function write($message);
410
  }
tools/src/Google/Logger/Exception.php CHANGED
@@ -1,21 +1,21 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- class Google_Logger_Exception extends Google_Exception
20
- {
21
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ class Google_Logger_Exception extends Google_Exception
20
+ {
21
  }
tools/src/Google/Logger/File.php CHANGED
@@ -1,149 +1,149 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * File logging class based on the PSR-3 standard.
21
- *
22
- * This logger writes to a PHP stream resource.
23
- */
24
- class Google_Logger_File extends Google_Logger_Abstract
25
- {
26
-
27
- /**
28
- *
29
- * @var string|resource $file Where logs are written
30
- */
31
- private $file;
32
-
33
- /**
34
- *
35
- * @var integer $mode The mode to use if the log file needs to be created
36
- */
37
- private $mode = 0640;
38
-
39
- /**
40
- *
41
- * @var boolean $lock If a lock should be attempted before writing to the log
42
- */
43
- private $lock = false;
44
-
45
- /**
46
- *
47
- * @var integer $trappedErrorNumber Trapped error number
48
- */
49
- private $trappedErrorNumber;
50
-
51
- /**
52
- *
53
- * @var string $trappedErrorString Trapped error string
54
- */
55
- private $trappedErrorString;
56
-
57
- /**
58
- * @ERROR!!!
59
- */
60
- public function __construct(Google_Client $client)
61
- {
62
- parent::__construct($client);
63
- $file = $client->getClassConfig('Google_Logger_File', 'file');
64
- if (! is_string($file) && ! is_resource($file)) {
65
- throw new Google_Logger_Exception('File logger requires a filename or a valid file pointer');
66
- }
67
- $mode = $client->getClassConfig('Google_Logger_File', 'mode');
68
- if (! $mode) {
69
- $this->mode = $mode;
70
- }
71
- $this->lock = (bool) $client->getClassConfig('Google_Logger_File', 'lock');
72
- $this->file = $file;
73
- }
74
-
75
- /**
76
- * @ERROR!!!
77
- */
78
- protected function write($message)
79
- {
80
- if (is_string($this->file)) {
81
- $this->open();
82
- } elseif (! is_resource($this->file)) {
83
- throw new Google_Logger_Exception('File pointer is no longer available');
84
- }
85
- if ($this->lock) {
86
- flock($this->file, LOCK_EX);
87
- }
88
- fwrite($this->file, (string) $message);
89
- if ($this->lock) {
90
- flock($this->file, LOCK_UN);
91
- }
92
- }
93
-
94
- /**
95
- * Opens the log for writing.
96
- *
97
- * @return resource
98
- */
99
- private function open()
100
- {
101
- // Used for trapping `fopen()` errors.
102
- $this->trappedErrorNumber = null;
103
- $this->trappedErrorString = null;
104
- $old = set_error_handler(array(
105
- $this,
106
- 'trapError'
107
- ));
108
- $needsChmod = ! file_exists($this->file);
109
- $fh = fopen($this->file, 'a');
110
- restore_error_handler();
111
- // Handles trapped `fopen()` errors.
112
- if ($this->trappedErrorNumber) {
113
- throw new Google_Logger_Exception(sprintf("Logger Error: '%s'", $this->trappedErrorString), $this->trappedErrorNumber);
114
- }
115
- if ($needsChmod) {
116
- @chmod($this->file, $this->mode & ~ umask());
117
- }
118
- return $this->file = $fh;
119
- }
120
-
121
- /**
122
- * Closes the log stream resource.
123
- */
124
- private function close()
125
- {
126
- if (is_resource($this->file)) {
127
- fclose($this->file);
128
- }
129
- }
130
-
131
- /**
132
- * Traps `fopen()` errors.
133
- *
134
- * @param integer $errno
135
- * The error number
136
- * @param string $errstr
137
- * The error string
138
- */
139
- private function trapError($errno, $errstr)
140
- {
141
- $this->trappedErrorNumber = $errno;
142
- $this->trappedErrorString = $errstr;
143
- }
144
-
145
- public function __destruct()
146
- {
147
- $this->close();
148
- }
149
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * File logging class based on the PSR-3 standard.
21
+ *
22
+ * This logger writes to a PHP stream resource.
23
+ */
24
+ class Google_Logger_File extends Google_Logger_Abstract
25
+ {
26
+
27
+ /**
28
+ *
29
+ * @var string|resource $file Where logs are written
30
+ */
31
+ private $file;
32
+
33
+ /**
34
+ *
35
+ * @var integer $mode The mode to use if the log file needs to be created
36
+ */
37
+ private $mode = 0640;
38
+
39
+ /**
40
+ *
41
+ * @var boolean $lock If a lock should be attempted before writing to the log
42
+ */
43
+ private $lock = false;
44
+
45
+ /**
46
+ *
47
+ * @var integer $trappedErrorNumber Trapped error number
48
+ */
49
+ private $trappedErrorNumber;
50
+
51
+ /**
52
+ *
53
+ * @var string $trappedErrorString Trapped error string
54
+ */
55
+ private $trappedErrorString;
56
+
57
+ /**
58
+ * @ERROR!!!
59
+ */
60
+ public function __construct(Google_Client $client)
61
+ {
62
+ parent::__construct($client);
63
+ $file = $client->getClassConfig('Google_Logger_File', 'file');
64
+ if (! is_string($file) && ! is_resource($file)) {
65
+ throw new Google_Logger_Exception('File logger requires a filename or a valid file pointer');
66
+ }
67
+ $mode = $client->getClassConfig('Google_Logger_File', 'mode');
68
+ if (! $mode) {
69
+ $this->mode = $mode;
70
+ }
71
+ $this->lock = (bool) $client->getClassConfig('Google_Logger_File', 'lock');
72
+ $this->file = $file;
73
+ }
74
+
75
+ /**
76
+ * @ERROR!!!
77
+ */
78
+ protected function write($message)
79
+ {
80
+ if (is_string($this->file)) {
81
+ $this->open();
82
+ } elseif (! is_resource($this->file)) {
83
+ throw new Google_Logger_Exception('File pointer is no longer available');
84
+ }
85
+ if ($this->lock) {
86
+ flock($this->file, LOCK_EX);
87
+ }
88
+ fwrite($this->file, (string) $message);
89
+ if ($this->lock) {
90
+ flock($this->file, LOCK_UN);
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Opens the log for writing.
96
+ *
97
+ * @return resource
98
+ */
99
+ private function open()
100
+ {
101
+ // Used for trapping `fopen()` errors.
102
+ $this->trappedErrorNumber = null;
103
+ $this->trappedErrorString = null;
104
+ $old = set_error_handler(array(
105
+ $this,
106
+ 'trapError'
107
+ ));
108
+ $needsChmod = ! file_exists($this->file);
109
+ $fh = fopen($this->file, 'a');
110
+ restore_error_handler();
111
+ // Handles trapped `fopen()` errors.
112
+ if ($this->trappedErrorNumber) {
113
+ throw new Google_Logger_Exception(sprintf("Logger Error: '%s'", $this->trappedErrorString), $this->trappedErrorNumber);
114
+ }
115
+ if ($needsChmod) {
116
+ @chmod($this->file, $this->mode & ~ umask());
117
+ }
118
+ return $this->file = $fh;
119
+ }
120
+
121
+ /**
122
+ * Closes the log stream resource.
123
+ */
124
+ private function close()
125
+ {
126
+ if (is_resource($this->file)) {
127
+ fclose($this->file);
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Traps `fopen()` errors.
133
+ *
134
+ * @param integer $errno
135
+ * The error number
136
+ * @param string $errstr
137
+ * The error string
138
+ */
139
+ private function trapError($errno, $errstr)
140
+ {
141
+ $this->trappedErrorNumber = $errno;
142
+ $this->trappedErrorString = $errstr;
143
+ }
144
+
145
+ public function __destruct()
146
+ {
147
+ $this->close();
148
+ }
149
  }
tools/src/Google/Logger/Null.php CHANGED
@@ -1,40 +1,40 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * Null logger based on the PSR-3 standard.
21
- *
22
- * This logger simply discards all messages.
23
- */
24
- class Google_Logger_Null extends Google_Logger_Abstract
25
- {
26
-
27
- /**
28
- * @ERROR!!!
29
- */
30
- public function shouldHandle($level)
31
- {
32
- return false;
33
- }
34
-
35
- /**
36
- * @ERROR!!!
37
- */
38
- protected function write($message, array $context = array())
39
- {}
40
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * Null logger based on the PSR-3 standard.
21
+ *
22
+ * This logger simply discards all messages.
23
+ */
24
+ class Google_Logger_Null extends Google_Logger_Abstract
25
+ {
26
+
27
+ /**
28
+ * @ERROR!!!
29
+ */
30
+ public function shouldHandle($level)
31
+ {
32
+ return false;
33
+ }
34
+
35
+ /**
36
+ * @ERROR!!!
37
+ */
38
+ protected function write($message, array $context = array())
39
+ {}
40
  }
tools/src/Google/Logger/Psr.php CHANGED
@@ -1,93 +1,93 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
-
19
- /**
20
- * Psr logging class based on the PSR-3 standard.
21
- *
22
- * This logger will delegate all logging to a PSR-3 compatible logger specified
23
- * with the `Google_Logger_Psr::setLogger()` method.
24
- */
25
- class Google_Logger_Psr extends Google_Logger_Abstract
26
- {
27
-
28
- /**
29
- *
30
- * @param Psr\Log\LoggerInterface $logger
31
- * The PSR-3 logger
32
- */
33
- private $logger;
34
-
35
- /**
36
- *
37
- * @param Google_Client $client
38
- * The current Google client
39
- * @param Psr\Log\LoggerInterface $logger
40
- * PSR-3 logger where logging will be delegated.
41
- */
42
- public function __construct(Google_Client $client, /*Psr\Log\LoggerInterface*/ $logger = null)
43
- {
44
- parent::__construct($client);
45
- if ($logger) {
46
- $this->setLogger($logger);
47
- }
48
- }
49
-
50
- /**
51
- * Sets the PSR-3 logger where logging will be delegated.
52
- *
53
- * NOTE: The `$logger` should technically implement
54
- * `Psr\Log\LoggerInterface`, but we don't explicitly require this so that
55
- * we can be compatible with PHP 5.2.
56
- *
57
- * @param Psr\Log\LoggerInterface $logger
58
- * The PSR-3 logger
59
- */
60
- public function setLogger(/*Psr\Log\LoggerInterface*/ $logger)
61
- {
62
- $this->logger = $logger;
63
- }
64
-
65
- /**
66
- * @ERROR!!!
67
- */
68
- public function shouldHandle($level)
69
- {
70
- return isset($this->logger) && parent::shouldHandle($level);
71
- }
72
-
73
- /**
74
- * @ERROR!!!
75
- */
76
- public function log($level, $message, array $context = array())
77
- {
78
- if (! $this->shouldHandle($level)) {
79
- return false;
80
- }
81
- if ($context) {
82
- $this->reverseJsonInContext($context);
83
- }
84
- $levelName = is_int($level) ? array_search($level, self::$levels) : $level;
85
- $this->logger->log($levelName, $message, $context);
86
- }
87
-
88
- /**
89
- * @ERROR!!!
90
- */
91
- protected function write($message, array $context = array())
92
- {}
93
  }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
18
+
19
+ /**
20
+ * Psr logging class based on the PSR-3 standard.
21
+ *
22
+ * This logger will delegate all logging to a PSR-3 compatible logger specified
23
+ * with the `Google_Logger_Psr::setLogger()` method.
24
+ */
25
+ class Google_Logger_Psr extends Google_Logger_Abstract
26
+ {
27
+
28
+ /**
29
+ *
30
+ * @param Psr\Log\LoggerInterface $logger
31
+ * The PSR-3 logger
32
+ */
33
+ private $logger;
34
+
35
+ /**
36
+ *
37
+ * @param Google_Client $client
38
+ * The current Google client
39
+ * @param Psr\Log\LoggerInterface $logger
40
+ * PSR-3 logger where logging will be delegated.
41
+ */
42
+ public function __construct(Google_Client $client, /*Psr\Log\LoggerInterface*/ $logger = null)
43
+ {
44
+ parent::__construct($client);
45
+ if ($logger) {
46
+ $this->setLogger($logger);
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Sets the PSR-3 logger where logging will be delegated.
52
+ *
53
+ * NOTE: The `$logger` should technically implement
54
+ * `Psr\Log\LoggerInterface`, but we don't explicitly require this so that
55
+ * we can be compatible with PHP 5.2.
56
+ *
57
+ * @param Psr\Log\LoggerInterface $logger
58
+ * The PSR-3 logger
59
+ */
60
+ public function setLogger(/*Psr\Log\LoggerInterface*/ $logger)
61
+ {
62
+ $this->logger = $logger;
63
+ }
64
+
65
+ /**
66
+ * @ERROR!!!
67
+ */
68
+ public function shouldHandle($level)
69
+ {
70
+ return isset($this->logger) && parent::shouldHandle($level);
71
+ }
72
+
73
+ /**
74
+ * @ERROR!!!
75
+ */
76
+ public function log($level, $message, array $context = array())
77
+ {
78
+ if (! $this->shouldHandle($level)) {
79
+ return false;
80
+ }
81
+ if ($context) {
82
+ $this->reverseJsonInContext($context);
83
+ }
84
+ $levelName = is_int($level) ? array_search($level, self::$levels) : $level;
85
+ $this->logger->log($levelName, $message, $context);
86
+ }
87
+
88
+ /**
89
+ * @ERROR!!!
90
+ */
91
+ protected function write($message, array $context = array())
92
+ {}
93
  }
tools/src/Google/Model.php CHANGED
@@ -1,283 +1,283 @@
1
- <?php
2
-
3
- /*
4
- * Copyright 2011 Google Inc.
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */
18
- /**
19
- * This class defines attributes, valid values, and usage which is generated
20
- * from a given json schema.
21
- * http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
22
- *
23
- * @author Chirag Shah <chirags@google.com>
24
- *
25
- */
26
- class Google_Model implements ArrayAccess
27
- {
28
-
29
- protected $internal_gapi_mappings = array();
30
-
31
- protected $modelData = array();
32
-
33
- protected $processed = array();
34
-
35
- /**
36
- * Polymorphic - accepts a variable number of arguments dependent
37
- * on the type of the model subclass.
38
- */
39
- final public function __construct()
40
- {
41
- if (func_num_args() == 1 && is_array(func_get_arg(0))) {
42
- // Initialize the model with the array's contents.
43
- $array = func_get_arg(0);
44
- $this->mapTypes($array);
45
- }
46
- $this->gapiInit();
47
- }
48
-
49
- /**
50
- * Getter that handles passthrough access to the data array, and lazy object creation.
51
- *
52
- * @param string $key
53
- * Property name.
54
- * @return mixed The value if any, or null.
55
- */
56
- public function __get($key)
57
- {
58
- $keyTypeName = $this->keyType($key);
59
- $keyDataType = $this->dataType($key);
60
- if (isset($this->$keyTypeName) && ! isset($this->processed[$key])) {
61
- if (isset($this->modelData[$key])) {
62
- $val = $this->modelData[$key];
63
- } else
64
- if (isset($this->$keyDataType) && ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
65
- $val = array();
66
- } else {
67
- $val = null;
68
- }
69
- if ($this->isAssociativeArray($val)) {
70
- if (isset($this->$keyDataType) && 'map' == $this->$keyDataType) {
71
- foreach ($val as $arrayKey => $arrayItem) {
72
- $this->modelData[$key][$arrayKey] = $this->createObjectFromName($keyTypeName, $arrayItem);
73
- }
74
- } else {
75
- $this->modelData[$key] = $this->createObjectFromName($keyTypeName, $val);
76
- }
77
- } else
78
- if (is_array($val)) {
79
- $arrayObject = array();
80
- foreach ($val as $arrayIndex => $arrayItem) {
81
- $arrayObject[$arrayIndex] = $this->createObjectFromName($keyTypeName, $arrayItem);
82
- }
83
- $this->modelData[$key] = $arrayObject;
84
- }
85
- $this->processed[$key] = true;
86
- }
87
- return isset($this->modelData[$key]) ? $this->modelData[$key] : null;
88
- }
89
-
90
- /**
91
- * Initialize this object's properties from an array.
92
- *
93
- * @param array $array
94
- * Used to seed this object's properties.
95
- * @return void
96
- */
97
- protected function mapTypes($array)
98
- {
99
- // Hard initilise simple types, lazy load more complex ones.
100
- foreach ($array as $key => $val) {
101
- if (! property_exists($this, $this->keyType($key)) && property_exists($this, $key)) {
102
- $this->$key = $val;
103
- unset($array[$key]);
104
- } elseif (property_exists($this, $camelKey = Google_Utils::camelCase($key))) {
105
- // This checks if property exists as camelCase, leaving it in array as snake_case
106
- // in case of backwards compatibility issues.
107
- $this->$camelKey = $val;
108
- }
109
- }
110
- $this->modelData = $array;
111
- }
112
-
113
- /**
114
- * Blank initialiser to be used in subclasses to do post-construction initialisation - this
115
- * avoids the need for subclasses to have to implement the variadics handling in their
116
- * constructors.
117
- */
118
- protected function gapiInit()
119
- {
120
- return;
121
- }
122
-
123
- /**
124
- * Create a simplified object suitable for straightforward
125
- * conversion to JSON.
126
- * This is relatively expensive
127
- * due to the usage of reflection, but shouldn't be called
128
- * a whole lot, and is the most straightforward way to filter.
129
- */
130
- public function toSimpleObject()
131
- {
132
- $object = new stdClass();
133
- // Process all other data.
134
- foreach ($this->modelData as $key => $val) {
135
- $result = $this->getSimpleValue($val);
136
- if ($result !== null) {
137
- $object->$key = $result;
138
- }
139
- }
140
- // Process all public properties.
141
- $reflect = new ReflectionObject($this);
142
- $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
143
- foreach ($props as $member) {
144
- $name = $member->getName();
145
- $result = $this->getSimpleValue($this->$name);
146
- if ($result !== null) {
147
- $name = $this->getMappedName($name);
148
- $object->$name = $result;
149
- }
150
- }
151
- return $object;
152
- }
153
-
154
- /**
155
- * Handle different types of values, primarily
156
- * other objects and map and array data types.
157
- */
158
- private function getSimpleValue($value)
159
- {
160
- if ($value instanceof Google_Model) {
161
- return $value->toSimpleObject();
162
- } else
163
- if (is_array($value)) {
164
- $return = array();
165
- foreach ($value as $key => $a_value) {
166
- $a_value = $this->getSimpleValue($a_value);
167
- if ($a_value !== null) {
168
- $key = $this->getMappedName($key);
169
- $return[$key] = $a_value;
170
- }
171
- }
172
- return $return;
173
- }
174
- return $value;
175
- }
176
-
177
- /**
178
- * If there is an internal name mapping, use that.
179
- */
180
- private function getMappedName($key)
181
- {
182
- if (isset($this->internal_gapi_mappings) && isset($this->internal_gapi_mappings[$key])) {
183
- $key = $this->internal_gapi_mappings[$key];
184
- }
185
- return $key;
186
- }
187
-
188
- /**
189
- * Returns true only if the array is associative.
190
- *
191
- * @param array $array
192
- * @return bool True if the array is associative.
193
- */
194
- protected function isAssociativeArray($array)
195
- {
196
- if (! is_array($array)) {
197
- return false;
198
- }
199
- $keys = array_keys($array);
200
- foreach ($keys as $key) {
201
- if (is_string($key)) {
202
- return true;
203
- }
204
- }
205
- return false;
206
- }
207
-
208
- /**
209
- * Given a variable name, discover its type.
210
- *
211
- * @param
212
- * $name
213
- * @param
214
- * $item
215
- * @return object The object from the item.
216
- */
217
- private function createObjectFromName($name, $item)
218
- {
219
- $type = $this->$name;
220
- return new $type($item);
221
- }
222
-
223
- /**
224
- * Verify if $obj is an array.
225
- *
226
- * @throws Google_Exception Thrown if $obj isn't an array.
227
- * @param array $obj
228
- * Items that should be validated.
229
- * @param string $method
230
- * Method expecting an array as an argument.
231
- */
232
- public function assertIsArray($obj, $method)
233
- {
234
- if ($obj && ! is_array($obj)) {
235
- throw new Google_Exception("Incorrect parameter type passed to $method(). Expected an array.");
236
- }
237
- }
238
-
239
- public function offsetExists($offset)
240
- {
241
- return isset($this->$offset) || isset($this->modelData[$offset]);
242
- }
243
-
244
- public function offsetGet($offset)
245
- {
246
- return isset($this->$offset) ? $this->$offset : $this->__get($offset);
247
- }
248
-
249
- public function offsetSet($offset, $value)
250
- {
251
- if (property_exists($this, $offset)) {
252
- $this->$offset = $value;
253
- } else {
254
- $this->modelData[$offset] = $value;
255
- $this->processed[$offset] = true;
256
- }
257
- }
258
-
259
- public function offsetUnset($offset)
260
- {
261
- unset($this->modelData[$offset]);
262
- }
263
-
264
- protected function keyType($key)
265
- {
266
- return $key . "Type";
267
- }
268
-
269
- protected function dataType($key)
270
- {
271
- return $key . "DataType";
272
- }
273
-
274
- public function __isset($key)
275
- {
276
- return isset($this->modelData[$key]);
277
- }
278
-
279
- public function __unset($key)
280
- {
281
- unset($this->modelData[$key]);
282
- }
283
  }
1
+ <?php
2
+
3
+ /*
4
+ * Copyright 2011 Google Inc.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ /**
19
+ * This class defines attributes, valid values, and usage which is generated
20
+ * from a given json schema.
21
+ * http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
22
+ *
23
+ * @author Chirag Shah <chirags@google.com>
24
+ *
25
+ */
26
+ class Google_Model implements ArrayAccess
27
+ {
28
+
29
+ protected $internal_gapi_mappings = array();
30
+
31
+ protected $modelData = array();
32
+
33
+ protected $processed = array();
34
+
35
+ /**
36
+ * Polymorphic - accepts a variable number of arguments dependent
37
+ * on the type of the model subclass.
38
+ */
39
+ final public function __construct()
40
+ {
41
+ if (func_num_args() == 1 && is_array(func_get_arg(0))) {
42
+ // Initialize the model with the array's contents.
43
+ $array = func_get_arg(0);
44
+ $this->mapTypes($array);
45
+ }
46
+ $this->gapiInit();
47
+ }
48
+
49
+ /**
50
+ * Getter that handles passthrough access to the data array, and lazy object creation.
51
+ *
52
+ * @param string $key
53
+ * Property name.
54
+ * @return mixed The value if any, or null.
55
+ */
56
+ public function __get($key)
57
+ {
58
+ $keyTypeName = $this->keyType($key);
59
+ $keyDataType = $this->dataType($key);
60
+ if (isset($this->$keyTypeName) && ! isset($this->processed[$key])) {
61
+ if (isset($this->modelData[$key])) {
62
+ $val = $this->modelData[$key];
63
+ } else
64
+ if (isset($this->$keyDataType) && ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
65
+ $val = array();
66
+ } else {
67
+ $val = null;
68
+ }
69
+ if ($this->isAssociativeArray($val)) {
70
+ if (isset($this->$keyDataType) && 'map' == $this->$keyDataType) {
71
+ foreach ($val as $arrayKey => $arrayItem) {
72
+ $this->modelData[$key][$arrayKey] = $this->createObjectFromName($keyTypeName, $arrayItem);
73
+ }
74
+ } else {
75
+ $this->modelData[$key] = $this->createObjectFromName($keyTypeName, $val);
76
+ }
77
+ } else
78
+ if (is_array($val)) {
79
+ $arrayObject = array();
80
+ foreach ($val as $arrayIndex => $arrayItem) {
81
+ $arrayObject[$arrayIndex] = $this->createObjectFromName($keyTypeName, $arrayItem);
82
+ }
83
+ $this->modelData[$key] = $arrayObject;
84
+ }
85
+ $this->processed[$key] = true;
86
+ }
87
+ return isset($this->modelData[$key]) ? $this->modelData[$key] : null;
88
+ }
89
+
90
+ /**
91
+ * Initialize this object's properties from an array.
92
+ *
93
+ * @param array $array
94
+ * Used to seed this object's properties.
95
+ * @return void
96
+ */
97
+ protected function mapTypes($array)
98
+ {
99
+ // Hard initilise simple types, lazy load more complex ones.
100
+ foreach ($array as $key => $val) {
101
+ if (! property_exists($this, $this->keyType($key)) && property_exists($this, $key)) {
102
+ $this->$key = $val;
103
+ unset($array[$key]);
104
+ } elseif (property_exists($this, $camelKey = Google_Utils::camelCase($key))) {
105
+ // This checks if property exists as camelCase, leaving it in array as snake_case
106
+ // in case of backwards compatibility issues.
107
+ $this->$camelKey = $val;
108
+ }
109
+ }
110
+ $this->modelData = $array;
111
+ }
112
+
113
+ /**
114
+ * Blank initialiser to be used in subclasses to do post-construction initialisation - this
115
+ * avoids the need for subclasses to have to implement the variadics handling in their
116
+ * constructors.
117
+ */
118
+ protected function gapiInit()
119
+ {
120
+ return;
121
+ }
122
+
123
+ /**
124
+ * Create a simplified object suitable for straightforward
125
+ * conversion to JSON.
126
+ * This is relatively expensive
127
+ * due to the usage of reflection, but shouldn't be called
128
+ * a whole lot, and is the most straightforward way to filter.
129
+ */
130
+ public function toSimpleObject()
131
+ {
132
+ $object = new stdClass();
133
+ // Process all other data.
134
+ foreach ($this->modelData as $key => $val) {
135
+ $result = $this->getSimpleValue($val);
136
+ if ($result !== null) {
137
+ $object->$key = $result;
138
+ }
139
+ }
140
+ // Process all public properties.
141
+ $reflect = new ReflectionObject($this);
142
+ $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
143
+ foreach ($props as $member) {
144
+ $name = $member->getName();
145
+ $result = $this->getSimpleValue($this->$name);
146
+ if ($result !== null) {
147
+ $name = $this->getMappedName($name);
148
+ $object->$name = $result;
149
+ }
150
+ }
151
+ return $object;
152
+ }
153
+
154
+ /**
155
+ * Handle different types of values, primarily
156
+ * other objects and map and array data types.
157
+ */
158
+ private function getSimpleValue($value)
159
+ {
160
+ if ($value instanceof Google_Model) {
161
+ return $value->toSimpleObject();
162
+ } else
163
+ if (is_array($value)) {
164
+ $return = array();
165
+ foreach ($value as $key => $a_value) {
166
+ $a_value = $this->getSimpleValue($a_value);
167
+ if ($a_value !== null) {
168
+ $key = $this->getMappedName($key);
169
+ $return[$key] = $a_value;
170
+ }
171
+ }
172
+ return $return;
173
+ }
174
+ return $value;
175
+ }
176
+
177
+ /**
178
+ * If there is an internal name mapping, use that.
179
+ */
180
+ private function getMappedName($key)
181
+ {
182
+ if (isset($this->internal_gapi_mappings) && isset($this->internal_gapi_mappings[$key])) {
183
+ $key = $this->internal_gapi_mappings[$key];
184
+ }
185
+ return $key;
186
+ }
187
+
188
+ /**
189
+ * Returns true only if the array is associative.
190
+ *
191
+ * @param array $array
192
+ * @return bool True if the array is associative.
193
+ */
194
+ protected function isAssociativeArray($array)
195
+ {
196
+ if (! is_array($array)) {
197
+ return false;
198
+ }
199
+ $keys = array_keys($array);
200
+ foreach ($keys as $key) {
201
+ if (is_string($key)) {
202
+ return true;
203
+ }
204
+ }
205
+ return false;
206
+ }
207
+
208
+ /**
209
+ * Given a variable name, discover its type.
210
+ *
211
+ * @param
212
+ * $name
213
+ * @param
214
+ * $item
215
+ * @return object The object from the item.
216
+ */
217
+ private function createObjectFromName($name, $item)
218
+ {
219
+ $type = $this->$name;
220
+ return new $type($item);
221
+ }
222
+
223
+ /**
224
+ * Verify if $obj is an array.
225
+ *
226
+ * @throws Google_Exception Thrown if $obj isn't an array.
227
+ * @param array $obj
228
+ * Items that should be validated.
229
+ * @param string $method
230
+ * Method expecting an array as an argument.
231
+ */
232
+ public function assertIsArray($obj, $method)
233
+ {
234
+ if ($obj && ! is_array($obj)) {
235
+ throw new Google_Exception("Incorrect parameter type passed to $method(). Expected an array.");
236
+ }
237
+ }
238
+
239
+ public function offsetExists($offset)
240
+ {
241
+ return isset($this->$offset) || isset($this->modelData[$offset]);
242
+ }
243
+
244
+ public function offsetGet($offset)
245
+ {
246
+ return isset($this->$offset) ? $this->$offset : $this->__get($offset);
247
+ }
248
+
249
+ public function offsetSet($offset, $value)
250
+ {
251
+ if (property_exists($this, $offset)) {
252
+ $this->$offset = $value;
253
+ } else {
254
+ $this->modelData[$offset] = $value;
255
+ $this->processed[$offset] = true;
256
+ }
257
+ }
258
+
259
+ public function offsetUnset($offset)
260
+ {
261
+ unset($this->modelData[$offset]);
262
+ }
263
+
264
+ protected function keyType($key)
265
+ {
266
+ return $key . "Type";
267
+ }
268
+
269
+ protected function dataType($key)
270
+ {
271
+ return $key . "DataType";
272
+ }
273
+
274
+ public function __isset($key)
275
+ {
276
+ return isset($this->modelData[$key]);
277
+ }
278
+
279
+ public function __unset($key)
280
+ {
281
+ unset($this->modelData[$key]);
282
+ }
283
  }
tools/src/Google/Service.php CHANGED
@@ -1,45 +1,45 @@
1
- <?php
2
-
3
- /*
4
- * Copyright 2010 Google Inc.
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */
18
- class Google_Service
19
- {
20
-
21
- public $version;
22
-
23
- public $servicePath;
24
-
25
- public $availableScopes;
26
-
27
- public $resource;
28
-
29
- private $client;
30
-
31
- public function __construct(Google_Client $client)
32
- {
33
- $this->client = $client;
34
- }
35
-
36
- /**
37
- * Return the associated Google_Client class.
38
- *
39
- * @return Google_Client
40
- */
41
- public function getClient()
42
- {
43
- return $this->client;
44
- }
45
  }
1
+ <?php
2
+
3
+ /*
4
+ * Copyright 2010 Google Inc.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ class Google_Service
19
+ {
20
+
21
+ public $version;
22
+
23
+ public $servicePath;
24
+
25
+ public $availableScopes;
26
+
27
+ public $resource;
28
+
29
+ private $client;
30
+
31
+ public function __construct(Google_Client $client)
32
+ {
33
+ $this->client = $client;
34
+ }
35
+
36
+ /**
37
+ * Return the associated Google_Client class.
38
+ *
39
+ * @return Google_Client
40
+ */
41
+ public function getClient()
42
+ {
43
+ return $this->client;
44
+ }
45
  }
tools/src/Google/Service/Analytics.php CHANGED
@@ -1,11796 +1,11796 @@
1
- <?php
2
-
3
- /*
4
- * Copyright 2010 Google Inc.
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
7
- * use this file except in compliance with the License. You may obtain a copy of
8
- * the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
- * License for the specific language governing permissions and limitations under
16
- * the License.
17
- */
18
- /**
19
- * Service definition for Analytics (v3).
20
- *
21
- * <p>
22
- * View and manage your Google Analytics data</p>
23
- *
24
- * <p>
25
- * For more information about this service, see the API
26
- * <a href="https://developers.google.com/analytics/" target="_blank">Documentation</a>
27
- * </p>
28
- *
29
- * @author Google, Inc.
30
- */
31
- class Google_Service_Analytics extends Google_Service
32
- {
33
-
34
- /**
35
- * View and manage your Google Analytics data.
36
- */
37
- const ANALYTICS = "https://www.googleapis.com/auth/analytics";
38
-
39
- /**
40
- * Edit Google Analytics management entities.
41
- */
42
- const ANALYTICS_EDIT = "https://www.googleapis.com/auth/analytics.edit";
43
-
44
- /**
45
- * Manage Google Analytics Account users by email address.
46
- */
47
- const ANALYTICS_MANAGE_USERS = "https://www.googleapis.com/auth/analytics.manage.users";
48
-
49
- /**
50
- * View Google Analytics user permissions.
51
- */
52
- const ANALYTICS_MANAGE_USERS_READONLY = "https://www.googleapis.com/auth/analytics.manage.users.readonly";
53
-
54
- /**
55
- * Create a new Google Analytics account along with its default property and view.
56
- */
57
- const ANALYTICS_PROVISION = "https://www.googleapis.com/auth/analytics.provision";
58
-
59
- /**
60
- * View your Google Analytics data.
61
- */
62
- const ANALYTICS_READONLY = "https://www.googleapis.com/auth/analytics.readonly";
63
-
64
- public $data_ga;
65
-
66
- public $data_mcf;
67
-
68
- public $data_realtime;
69
-
70
- public $management_accountSummaries;
71
-
72
- public $management_accountUserLinks;
73
-
74
- public $management_accounts;
75
-
76
- public $management_customDataSources;
77
-
78
- public $management_dailyUploads;
79
-
80
- public $management_experiments;
81
-
82
- public $management_filters;
83
-
84
- public $management_goals;
85
-
86
- public $management_profileFilterLinks;
87
-
88
- public $management_profileUserLinks;
89
-
90
- public $management_profiles;
91
-
92
- public $management_segments;
93
-
94
- public $management_unsampledReports;
95
-
96
- public $management_uploads;
97
-
98
- public $management_webPropertyAdWordsLinks;
99
-
100
- public $management_webproperties;
101
-
102
- public $management_webpropertyUserLinks;
103
-
104
- public $metadata_columns;
105
-
106
- public $provisioning;
107
-
108
- /**
109
- * Constructs the internal representation of the Analytics service.
110
- *
111
- * @param Google_Client $client
112
- */
113
- public function __construct(Google_Client $client)
114
- {
115
- parent::__construct($client);
116
- $this->servicePath = 'analytics/v3/';
117
- $this->version = 'v3';
118
- $this->serviceName = 'analytics';
119
- $this->data_ga = new Google_Service_Analytics_DataGa_Resource($this, $this->serviceName, 'ga', array(
120
- 'methods' => array(
121
- 'get' => array(
122
- 'path' => 'data/ga',
123
- 'httpMethod' => 'GET',
124
- 'parameters' => array(
125
- 'ids' => array(
126
- 'location' => 'query',
127
- 'type' => 'string',
128
- 'required' => true
129
- ),
130
- 'start-date' => array(
131
- 'location' => 'query',
132
- 'type' => 'string',
133
- 'required' => true
134
- ),
135
- 'end-date' => array(
136
- 'location' => 'query',
137
- 'type' => 'string',
138
- 'required' => true
139
- ),
140
- 'metrics' => array(
141
- 'location' => 'query',
142
- 'type' => 'string',
143
- 'required' => true
144
- ),
145
- 'max-results' => array(
146
- 'location' => 'query',
147
- 'type' => 'integer'
148
- ),
149
- 'sort' => array(
150
- 'location' => 'query',
151
- 'type' => 'string'
152
- ),
153
- 'dimensions' => array(
154
- 'location' => 'query',
155
- 'type' => 'string'
156
- ),
157
- 'start-index' => array(
158
- 'location' => 'query',
159
- 'type' => 'integer'
160
- ),
161
- 'segment' => array(
162
- 'location' => 'query',
163
- 'type' => 'string'
164
- ),
165
- 'samplingLevel' => array(
166
- 'location' => 'query',
167
- 'type' => 'string'
168
- ),
169
- 'filters' => array(
170
- 'location' => 'query',
171
- 'type' => 'string'
172
- ),
173
- 'output' => array(
174
- 'location' => 'query',
175
- 'type' => 'string'
176
- )
177
- )
178
- )
179
- )
180
- ));
181
- $this->data_mcf = new Google_Service_Analytics_DataMcf_Resource($this, $this->serviceName, 'mcf', array(
182
- 'methods' => array(
183
- 'get' => array(
184
- 'path' => 'data/mcf',
185
- 'httpMethod' => 'GET',
186
- 'parameters' => array(
187
- 'ids' => array(
188
- 'location' => 'query',
189
- 'type' => 'string',
190
- 'required' => true
191
- ),
192
- 'start-date' => array(
193
- 'location' => 'query',
194
- 'type' => 'string',
195
- 'required' => true
196
- ),
197
- 'end-date' => array(
198
- 'location' => 'query',
199
- 'type' => 'string',
200
- 'required' => true
201
- ),
202
- 'metrics' => array(
203
- 'location' => 'query',
204
- 'type' => 'string',
205
- 'required' => true
206
- ),
207
- 'max-results' => array(
208
- 'location' => 'query',
209
- 'type' => 'integer'
210
- ),
211
- 'sort' => array(
212
- 'location' => 'query',
213
- 'type' => 'string'
214
- ),
215
- 'dimensions' => array(
216
- 'location' => 'query',
217
- 'type' => 'string'
218
- ),
219
- 'start-index' => array(
220
- 'location' => 'query',
221
- 'type' => 'integer'
222
- ),
223
- 'samplingLevel' => array(
224
- 'location' => 'query',
225
- 'type' => 'string'
226
- ),
227
- 'filters' => array(
228
- 'location' => 'query',
229
- 'type' => 'string'
230
- )
231
- )
232
- )
233
- )
234
- ));
235
- $this->data_realtime = new Google_Service_Analytics_DataRealtime_Resource($this, $this->serviceName, 'realtime', array(
236
- 'methods' => array(
237
- 'get' => array(
238
- 'path' => 'data/realtime',
239
- 'httpMethod' => 'GET',
240
- 'parameters' => array(
241
- 'ids' => array(
242
- 'location' => 'query',
243
- 'type' => 'string',
244
- 'required' => true
245
- ),
246
- 'metrics' => array(
247
- 'location' => 'query',
248
- 'type' => 'string',
249
- 'required' => true
250
- ),
251
- 'max-results' => array(
252
- 'location' => 'query',
253
- 'type' => 'integer'
254
- ),
255
- 'sort' => array(
256
- 'location' => 'query',
257
- 'type' => 'string'
258
- ),
259
- 'dimensions' => array(
260
- 'location' => 'query',
261
- 'type' => 'string'
262
- ),
263
- 'filters' => array(
264
- 'location' => 'query',
265
- 'type' => 'string'
266
- )
267
- )
268
- )
269
- )
270
- ));
271
- $this->management_accountSummaries = new Google_Service_Analytics_ManagementAccountSummaries_Resource($this, $this->serviceName, 'accountSummaries', array(
272
- 'methods' => array(
273
- 'list' => array(
274
- 'path' => 'management/accountSummaries',
275
- 'httpMethod' => 'GET',
276
- 'parameters' => array(
277
- 'max-results' => array(
278
- 'location' => 'query',
279
- 'type' => 'integer'
280
- ),
281
- 'start-index' => array(
282
- 'location' => 'query',
283
- 'type' => 'integer'
284
- )
285
- )
286
- )
287
- )
288
- ));
289
- $this->management_accountUserLinks = new Google_Service_Analytics_ManagementAccountUserLinks_Resource($this, $this->serviceName, 'accountUserLinks', array(
290
- 'methods' => array(
291
- 'delete' => array(
292
- 'path' => 'management/accounts/{accountId}/entityUserLinks/{linkId}',
293
- 'httpMethod' => 'DELETE',
294
- 'parameters' => array(
295
- 'accountId' => array(
296
- 'location' => 'path',
297
- 'type' => 'string',
298
- 'required' => true
299
- ),
300
- 'linkId' => array(
301
- 'location' => 'path',
302
- 'type' => 'string',
303
- 'required' => true
304
- )
305
- )
306
- ),
307
- 'insert' => array(
308
- 'path' => 'management/accounts/{accountId}/entityUserLinks',
309
- 'httpMethod' => 'POST',
310
- 'parameters' => array(
311
- 'accountId' => array(
312
- 'location' => 'path',
313
- 'type' => 'string',
314
- 'required' => true
315
- )
316
- )
317
- ),
318
- 'list' => array(
319
- 'path' => 'management/accounts/{accountId}/entityUserLinks',
320
- 'httpMethod' => 'GET',
321
- 'parameters' => array(
322
- 'accountId' => array(
323
- 'location' => 'path',
324
- 'type' => 'string',
325
- 'required' => true
326
- ),
327
- 'max-results' => array(
328
- 'location' => 'query',
329
- 'type' => 'integer'
330
- ),
331
- 'start-index' => array(
332
- 'location' => 'query',
333
- 'type' => 'integer'
334
- )
335
- )
336
- ),
337
- 'update' => array(
338
- 'path' => 'management/accounts/{accountId}/entityUserLinks/{linkId}',
339
- 'httpMethod' => 'PUT',
340
- 'parameters' => array(
341
- 'accountId' => array(
342
- 'location' => 'path',
343
- 'type' => 'string',
344
- 'required' => true
345
- ),
346
- 'linkId' => array(
347
- 'location' => 'path',
348
- 'type' => 'string',
349
- 'required' => true
350
- )
351
- )
352
- )
353
- )
354
- ));
355
- $this->management_accounts = new Google_Service_Analytics_ManagementAccounts_Resource($this, $this->serviceName, 'accounts', array(
356
- 'methods' => array(
357
- 'list' => array(
358
- 'path' => 'management/accounts',
359
- 'httpMethod' => 'GET',
360
- 'parameters' => array(
361
- 'max-results' => array(
362
- 'location' => 'query',
363
- 'type' => 'integer'
364
- ),
365
- 'start-index' => array(
366
- 'location' => 'query',
367
- 'type' => 'integer'
368
- )
369
- )
370
- )
371
- )
372
- ));
373
- $this->management_customDataSources = new Google_Service_Analytics_ManagementCustomDataSources_Resource($this, $this->serviceName, 'customDataSources', array(
374
- 'methods' => array(
375
- 'list' => array(
376
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources',
377
- 'httpMethod' => 'GET',
378
- 'parameters' => array(
379
- 'accountId' => array(
380
- 'location' => 'path',
381
- 'type' => 'string',
382
- 'required' => true
383
- ),
384
- 'webPropertyId' => array(
385
- 'location' => 'path',
386
- 'type' => 'string',
387
- 'required' => true
388
- ),
389
- 'max-results' => array(
390
- 'location' => 'query',
391
- 'type' => 'integer'
392
- ),
393
- 'start-index' => array(
394
- 'location' => 'query',
395
- 'type' => 'integer'
396
- )
397
- )
398
- )
399
- )
400
- ));
401
- $this->management_dailyUploads = new Google_Service_Analytics_ManagementDailyUploads_Resource($this, $this->serviceName, 'dailyUploads', array(
402
- 'methods' => array(
403
- 'delete' => array(
404
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/dailyUploads/{date}',
405
- 'httpMethod' => 'DELETE',
406
- 'parameters' => array(
407
- 'accountId' => array(
408
- 'location' => 'path',
409
- 'type' => 'string',
410
- 'required' => true
411
- ),
412
- 'webPropertyId' => array(
413
- 'location' => 'path',
414
- 'type' => 'string',
415
- 'required' => true
416
- ),
417
- 'customDataSourceId' => array(
418
- 'location' => 'path',
419
- 'type' => 'string',
420
- 'required' => true
421
- ),
422
- 'date' => array(
423
- 'location' => 'path',
424
- 'type' => 'string',
425
- 'required' => true
426
- ),
427
- 'type' => array(
428
- 'location' => 'query',
429
- 'type' => 'string',
430
- 'required' => true
431
- )
432
- )
433
- ),
434
- 'list' => array(
435
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/dailyUploads',
436
- 'httpMethod' => 'GET',
437
- 'parameters' => array(
438
- 'accountId' => array(
439
- 'location' => 'path',
440
- 'type' => 'string',
441
- 'required' => true
442
- ),
443
- 'webPropertyId' => array(
444
- 'location' => 'path',
445
- 'type' => 'string',
446
- 'required' => true
447
- ),
448
- 'customDataSourceId' => array(
449
- 'location' => 'path',
450
- 'type' => 'string',
451
- 'required' => true
452
- ),
453
- 'start-date' => array(
454
- 'location' => 'query',
455
- 'type' => 'string',
456
- 'required' => true
457
- ),
458
- 'end-date' => array(
459
- 'location' => 'query',
460
- 'type' => 'string',
461
- 'required' => true
462
- ),
463
- 'max-results' => array(
464
- 'location' => 'query',
465
- 'type' => 'integer'
466
- ),
467
- 'start-index' => array(
468
- 'location' => 'query',
469
- 'type' => 'integer'
470
- )
471
- )
472
- ),
473
- 'upload' => array(
474
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/dailyUploads/{date}/uploads',
475
- 'httpMethod' => 'POST',
476
- 'parameters' => array(
477
- 'accountId' => array(
478
- 'location' => 'path',
479
- 'type' => 'string',
480
- 'required' => true
481
- ),
482
- 'webPropertyId' => array(
483
- 'location' => 'path',
484
- 'type' => 'string',
485
- 'required' => true
486
- ),
487
- 'customDataSourceId' => array(
488
- 'location' => 'path',
489
- 'type' => 'string',
490
- 'required' => true
491
- ),
492
- 'date' => array(
493
- 'location' => 'path',
494
- 'type' => 'string',
495
- 'required' => true
496
- ),
497
- 'appendNumber' => array(
498
- 'location' => 'query',
499
- 'type' => 'integer',
500
- 'required' => true
501
- ),
502
- 'type' => array(
503
- 'location' => 'query',
504
- 'type' => 'string',
505
- 'required' => true
506
- ),
507
- 'reset' => array(
508
- 'location' => 'query',
509
- 'type' => 'boolean'
510
- )
511
- )
512
- )
513
- )
514
- ));
515
- $this->management_experiments = new Google_Service_Analytics_ManagementExperiments_Resource($this, $this->serviceName, 'experiments', array(
516
- 'methods' => array(
517
- 'delete' => array(
518
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments/{experimentId}',
519
- 'httpMethod' => 'DELETE',
520
- 'parameters' => array(
521
- 'accountId' => array(
522
- 'location' => 'path',
523
- 'type' => 'string',
524
- 'required' => true
525
- ),
526
- 'webPropertyId' => array(
527
- 'location' => 'path',
528
- 'type' => 'string',
529
- 'required' => true
530
- ),
531
- 'profileId' => array(
532
- 'location' => 'path',
533
- 'type' => 'string',
534
- 'required' => true
535
- ),
536
- 'experimentId' => array(
537
- 'location' => 'path',
538
- 'type' => 'string',
539
- 'required' => true
540
- )
541
- )
542
- ),
543
- 'get' => array(
544
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments/{experimentId}',
545
- 'httpMethod' => 'GET',
546
- 'parameters' => array(
547
- 'accountId' => array(
548
- 'location' => 'path',
549
- 'type' => 'string',
550
- 'required' => true
551
- ),
552
- 'webPropertyId' => array(
553
- 'location' => 'path',
554
- 'type' => 'string',
555
- 'required' => true
556
- ),
557
- 'profileId' => array(
558
- 'location' => 'path',
559
- 'type' => 'string',
560
- 'required' => true
561
- ),
562
- 'experimentId' => array(
563
- 'location' => 'path',
564
- 'type' => 'string',
565
- 'required' => true
566
- )
567
- )
568
- ),
569
- 'insert' => array(
570
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments',
571
- 'httpMethod' => 'POST',
572
- 'parameters' => array(
573
- 'accountId' => array(
574
- 'location' => 'path',
575
- 'type' => 'string',
576
- 'required' => true
577
- ),
578
- 'webPropertyId' => array(
579
- 'location' => 'path',
580
- 'type' => 'string',
581
- 'required' => true
582
- ),
583
- 'profileId' => array(
584
- 'location' => 'path',
585
- 'type' => 'string',
586
- 'required' => true
587
- )
588
- )
589
- ),
590
- 'list' => array(
591
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments',
592
- 'httpMethod' => 'GET',
593
- 'parameters' => array(
594
- 'accountId' => array(
595
- 'location' => 'path',
596
- 'type' => 'string',
597
- 'required' => true
598
- ),
599
- 'webPropertyId' => array(
600
- 'location' => 'path',
601
- 'type' => 'string',
602
- 'required' => true
603
- ),
604
- 'profileId' => array(
605
- 'location' => 'path',
606
- 'type' => 'string',
607
- 'required' => true
608
- ),
609
- 'max-results' => array(
610
- 'location' => 'query',
611
- 'type' => 'integer'
612
- ),
613
- 'start-index' => array(
614
- 'location' => 'query',
615
- 'type' => 'integer'
616
- )
617
- )
618
- ),
619
- 'patch' => array(
620
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments/{experimentId}',
621
- 'httpMethod' => 'PATCH',
622
- 'parameters' => array(
623
- 'accountId' => array(
624
- 'location' => 'path',
625
- 'type' => 'string',
626
- 'required' => true
627
- ),
628
- 'webPropertyId' => array(
629
- 'location' => 'path',
630
- 'type' => 'string',
631
- 'required' => true
632
- ),
633
- 'profileId' => array(
634
- 'location' => 'path',
635
- 'type' => 'string',
636
- 'required' => true
637
- ),
638
- 'experimentId' => array(
639
- 'location' => 'path',
640
- 'type' => 'string',
641
- 'required' => true
642
- )
643
- )
644
- ),
645
- 'update' => array(
646
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments/{experimentId}',
647
- 'httpMethod' => 'PUT',
648
- 'parameters' => array(
649
- 'accountId' => array(
650
- 'location' => 'path',
651
- 'type' => 'string',
652
- 'required' => true
653
- ),
654
- 'webPropertyId' => array(
655
- 'location' => 'path',
656
- 'type' => 'string',
657
- 'required' => true
658
- ),
659
- 'profileId' => array(
660
- 'location' => 'path',
661
- 'type' => 'string',
662
- 'required' => true
663
- ),
664
- 'experimentId' => array(
665
- 'location' => 'path',
666
- 'type' => 'string',
667
- 'required' => true
668
- )
669
- )
670
- )
671
- )
672
- ));
673
- $this->management_filters = new Google_Service_Analytics_ManagementFilters_Resource($this, $this->serviceName, 'filters', array(
674
- 'methods' => array(
675
- 'delete' => array(
676
- 'path' => 'management/accounts/{accountId}/filters/{filterId}',
677
- 'httpMethod' => 'DELETE',
678
- 'parameters' => array(
679
- 'accountId' => array(
680
- 'location' => 'path',
681
- 'type' => 'string',
682
- 'required' => true
683
- ),
684
- 'filterId' => array(
685
- 'location' => 'path',
686
- 'type' => 'string',
687
- 'required' => true
688
- )
689
- )
690
- ),
691
- 'get' => array(
692
- 'path' => 'management/accounts/{accountId}/filters/{filterId}',
693
- 'httpMethod' => 'GET',
694
- 'parameters' => array(
695
- 'accountId' => array(
696
- 'location' => 'path',
697
- 'type' => 'string',
698
- 'required' => true
699
- ),
700
- 'filterId' => array(
701
- 'location' => 'path',
702
- 'type' => 'string',
703
- 'required' => true
704
- )
705
- )
706
- ),
707
- 'insert' => array(
708
- 'path' => 'management/accounts/{accountId}/filters',
709
- 'httpMethod' => 'POST',
710
- 'parameters' => array(
711
- 'accountId' => array(
712
- 'location' => 'path',
713
- 'type' => 'string',
714
- 'required' => true
715
- )
716
- )
717
- ),
718
- 'list' => array(
719
- 'path' => 'management/accounts/{accountId}/filters',
720
- 'httpMethod' => 'GET',
721
- 'parameters' => array(
722
- 'accountId' => array(
723
- 'location' => 'path',
724
- 'type' => 'string',
725
- 'required' => true
726
- ),
727
- 'max-results' => array(
728
- 'location' => 'query',
729
- 'type' => 'integer'
730
- ),
731
- 'start-index' => array(
732
- 'location' => 'query',
733
- 'type' => 'integer'
734
- )
735
- )
736
- ),
737
- 'patch' => array(
738
- 'path' => 'management/accounts/{accountId}/filters/{filterId}',
739
- 'httpMethod' => 'PATCH',
740
- 'parameters' => array(
741
- 'accountId' => array(
742
- 'location' => 'path',
743
- 'type' => 'string',
744
- 'required' => true
745
- ),
746
- 'filterId' => array(
747
- 'location' => 'path',
748
- 'type' => 'string',
749
- 'required' => true
750
- )
751
- )
752
- ),
753
- 'update' => array(
754
- 'path' => 'management/accounts/{accountId}/filters/{filterId}',
755
- 'httpMethod' => 'PUT',
756
- 'parameters' => array(
757
- 'accountId' => array(
758
- 'location' => 'path',
759
- 'type' => 'string',
760
- 'required' => true
761
- ),
762
- 'filterId' => array(
763
- 'location' => 'path',
764
- 'type' => 'string',
765
- 'required' => true
766
- )
767
- )
768
- )
769
- )
770
- ));
771
- $this->management_goals = new Google_Service_Analytics_ManagementGoals_Resource($this, $this->serviceName, 'goals', array(
772
- 'methods' => array(
773
- 'get' => array(
774
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals/{goalId}',
775
- 'httpMethod' => 'GET',
776
- 'parameters' => array(
777
- 'accountId' => array(
778
- 'location' => 'path',
779
- 'type' => 'string',
780
- 'required' => true
781
- ),
782
- 'webPropertyId' => array(
783
- 'location' => 'path',
784
- 'type' => 'string',
785
- 'required' => true
786
- ),
787
- 'profileId' => array(
788
- 'location' => 'path',
789
- 'type' => 'string',
790
- 'required' => true
791
- ),
792
- 'goalId' => array(
793
- 'location' => 'path',
794
- 'type' => 'string',
795
- 'required' => true
796
- )
797
- )
798
- ),
799
- 'insert' => array(
800
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals',
801
- 'httpMethod' => 'POST',
802
- 'parameters' => array(
803
- 'accountId' => array(
804
- 'location' => 'path',
805
- 'type' => 'string',
806
- 'required' => true
807
- ),
808
- 'webPropertyId' => array(
809
- 'location' => 'path',
810
- 'type' => 'string',
811
- 'required' => true
812
- ),
813
- 'profileId' => array(
814
- 'location' => 'path',
815
- 'type' => 'string',
816
- 'required' => true
817
- )
818
- )
819
- ),
820
- 'list' => array(
821
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals',
822
- 'httpMethod' => 'GET',
823
- 'parameters' => array(
824
- 'accountId' => array(
825
- 'location' => 'path',
826
- 'type' => 'string',
827
- 'required' => true
828
- ),
829
- 'webPropertyId' => array(
830
- 'location' => 'path',
831
- 'type' => 'string',
832
- 'required' => true
833
- ),
834
- 'profileId' => array(
835
- 'location' => 'path',
836
- 'type' => 'string',
837
- 'required' => true
838
- ),
839
- 'max-results' => array(
840
- 'location' => 'query',
841
- 'type' => 'integer'
842
- ),
843
- 'start-index' => array(
844
- 'location' => 'query',
845
- 'type' => 'integer'
846
- )
847
- )
848
- ),
849
- 'patch' => array(
850
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals/{goalId}',
851
- 'httpMethod' => 'PATCH',
852
- 'parameters' => array(
853
- 'accountId' => array(
854
- 'location' => 'path',
855
- 'type' => 'string',
856
- 'required' => true
857
- ),
858
- 'webPropertyId' => array(
859
- 'location' => 'path',
860
- 'type' => 'string',
861
- 'required' => true
862
- ),
863
- 'profileId' => array(
864
- 'location' => 'path',
865
- 'type' => 'string',
866
- 'required' => true
867
- ),
868
- 'goalId' => array(
869
- 'location' => 'path',
870
- 'type' => 'string',
871
- 'required' => true
872
- )
873
- )
874
- ),
875
- 'update' => array(
876
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals/{goalId}',
877
- 'httpMethod' => 'PUT',
878
- 'parameters' => array(
879
- 'accountId' => array(
880
- 'location' => 'path',
881
- 'type' => 'string',
882
- 'required' => true
883
- ),
884
- 'webPropertyId' => array(
885
- 'location' => 'path',
886
- 'type' => 'string',
887
- 'required' => true
888
- ),
889
- 'profileId' => array(
890
- 'location' => 'path',
891
- 'type' => 'string',
892
- 'required' => true
893
- ),
894
- 'goalId' => array(
895
- 'location' => 'path',
896
- 'type' => 'string',
897
- 'required' => true
898
- )
899
- )
900
- )
901
- )
902
- ));
903
- $this->management_profileFilterLinks = new Google_Service_Analytics_ManagementProfileFilterLinks_Resource($this, $this->serviceName, 'profileFilterLinks', array(
904
- 'methods' => array(
905
- 'delete' => array(
906
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks/{linkId}',
907
- 'httpMethod' => 'DELETE',
908
- 'parameters' => array(
909
- 'accountId' => array(
910
- 'location' => 'path',
911
- 'type' => 'string',
912
- 'required' => true
913
- ),
914
- 'webPropertyId' => array(
915
- 'location' => 'path',
916
- 'type' => 'string',
917
- 'required' => true
918
- ),
919
- 'profileId' => array(
920
- 'location' => 'path',
921
- 'type' => 'string',
922
- 'required' => true
923
- ),
924
- 'linkId' => array(
925
- 'location' => 'path',
926
- 'type' => 'string',
927
- 'required' => true
928
- )
929
- )
930
- ),
931
- 'get' => array(
932
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks/{linkId}',
933
- 'httpMethod' => 'GET',
934
- 'parameters' => array(
935
- 'accountId' => array(
936
- 'location' => 'path',
937
- 'type' => 'string',
938
- 'required' => true
939
- ),
940
- 'webPropertyId' => array(
941
- 'location' => 'path',
942
- 'type' => 'string',
943
- 'required' => true
944
- ),
945
- 'profileId' => array(
946
- 'location' => 'path',
947
- 'type' => 'string',
948
- 'required' => true
949
- ),
950
- 'linkId' => array(
951
- 'location' => 'path',
952
- 'type' => 'string',
953
- 'required' => true
954
- )
955
- )
956
- ),
957
- 'insert' => array(
958
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks',
959
- 'httpMethod' => 'POST',
960
- 'parameters' => array(
961
- 'accountId' => array(
962
- 'location' => 'path',
963
- 'type' => 'string',
964
- 'required' => true
965
- ),
966
- 'webPropertyId' => array(
967
- 'location' => 'path',
968
- 'type' => 'string',
969
- 'required' => true
970
- ),
971
- 'profileId' => array(
972
- 'location' => 'path',
973
- 'type' => 'string',
974
- 'required' => true
975
- )
976
- )
977
- ),
978
- 'list' => array(
979
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks',
980
- 'httpMethod' => 'GET',
981
- 'parameters' => array(
982
- 'accountId' => array(
983
- 'location' => 'path',
984
- 'type' => 'string',
985
- 'required' => true
986
- ),
987
- 'webPropertyId' => array(
988
- 'location' => 'path',
989
- 'type' => 'string',
990
- 'required' => true
991
- ),
992
- 'profileId' => array(
993
- 'location' => 'path',
994
- 'type' => 'string',
995
- 'required' => true
996
- ),
997
- 'max-results' => array(
998
- 'location' => 'query',
999
- 'type' => 'integer'
1000
- ),
1001
- 'start-index' => array(
1002
- 'location' => 'query',
1003
- 'type' => 'integer'
1004
- )
1005
- )
1006
- ),
1007
- 'patch' => array(
1008
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks/{linkId}',
1009
- 'httpMethod' => 'PATCH',
1010
- 'parameters' => array(
1011
- 'accountId' => array(
1012
- 'location' => 'path',
1013
- 'type' => 'string',
1014
- 'required' => true
1015
- ),
1016
- 'webPropertyId' => array(
1017
- 'location' => 'path',
1018
- 'type' => 'string',
1019
- 'required' => true
1020
- ),
1021
- 'profileId' => array(
1022
- 'location' => 'path',
1023
- 'type' => 'string',
1024
- 'required' => true
1025
- ),
1026
- 'linkId' => array(
1027
- 'location' => 'path',
1028
- 'type' => 'string',
1029
- 'required' => true
1030
- )
1031
- )
1032
- ),
1033
- 'update' => array(
1034
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks/{linkId}',
1035
- 'httpMethod' => 'PUT',
1036
- 'parameters' => array(
1037
- 'accountId' => array(
1038
- 'location' => 'path',
1039
- 'type' => 'string',
1040
- 'required' => true
1041
- ),
1042
- 'webPropertyId' => array(
1043
- 'location' => 'path',
1044
- 'type' => 'string',
1045
- 'required' => true
1046
- ),
1047
- 'profileId' => array(
1048
- 'location' => 'path',
1049
- 'type' => 'string',
1050
- 'required' => true
1051
- ),
1052
- 'linkId' => array(
1053
- 'location' => 'path',
1054
- 'type' => 'string',
1055
- 'required' => true
1056
- )
1057
- )
1058
- )
1059
- )
1060
- ));
1061
- $this->management_profileUserLinks = new Google_Service_Analytics_ManagementProfileUserLinks_Resource($this, $this->serviceName, 'profileUserLinks', array(
1062
- 'methods' => array(
1063
- 'delete' => array(
1064
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/entityUserLinks/{linkId}',
1065
- 'httpMethod' => 'DELETE',
1066
- 'parameters' => array(
1067
- 'accountId' => array(
1068
- 'location' => 'path',
1069
- 'type' => 'string',
1070
- 'required' => true
1071
- ),
1072
- 'webPropertyId' => array(
1073
- 'location' => 'path',
1074
- 'type' => 'string',
1075
- 'required' => true
1076
- ),
1077
- 'profileId' => array(
1078
- 'location' => 'path',
1079
- 'type' => 'string',
1080
- 'required' => true
1081
- ),
1082
- 'linkId' => array(
1083
- 'location' => 'path',
1084
- 'type' => 'string',
1085
- 'required' => true
1086
- )
1087
- )
1088
- ),
1089
- 'insert' => array(
1090
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/entityUserLinks',
1091
- 'httpMethod' => 'POST',
1092
- 'parameters' => array(
1093
- 'accountId' => array(
1094
- 'location' => 'path',
1095
- 'type' => 'string',
1096
- 'required' => true
1097
- ),
1098
- 'webPropertyId' => array(
1099
- 'location' => 'path',
1100
- 'type' => 'string',
1101
- 'required' => true
1102
- ),
1103
- 'profileId' => array(
1104
- 'location' => 'path',
1105
- 'type' => 'string',
1106
- 'required' => true
1107
- )
1108
- )
1109
- ),
1110
- 'list' => array(
1111
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/entityUserLinks',
1112
- 'httpMethod' => 'GET',
1113
- 'parameters' => array(
1114
- 'accountId' => array(
1115
- 'location' => 'path',
1116
- 'type' => 'string',
1117
- 'required' => true
1118
- ),
1119
- 'webPropertyId' => array(
1120
- 'location' => 'path',
1121
- 'type' => 'string',
1122
- 'required' => true
1123
- ),
1124
- 'profileId' => array(
1125
- 'location' => 'path',
1126
- 'type' => 'string',
1127
- 'required' => true
1128
- ),
1129
- 'max-results' => array(
1130
- 'location' => 'query',
1131
- 'type' => 'integer'
1132
- ),
1133
- 'start-index' => array(
1134
- 'location' => 'query',
1135
- 'type' => 'integer'
1136
- )
1137
- )
1138
- ),
1139
- 'update' => array(
1140
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/entityUserLinks/{linkId}',
1141
- 'httpMethod' => 'PUT',
1142
- 'parameters' => array(
1143
- 'accountId' => array(
1144
- 'location' => 'path',
1145
- 'type' => 'string',
1146
- 'required' => true
1147
- ),
1148
- 'webPropertyId' => array(
1149
- 'location' => 'path',
1150
- 'type' => 'string',
1151
- 'required' => true
1152
- ),
1153
- 'profileId' => array(
1154
- 'location' => 'path',
1155
- 'type' => 'string',
1156
- 'required' => true
1157
- ),
1158
- 'linkId' => array(
1159
- 'location' => 'path',
1160
- 'type' => 'string',
1161
- 'required' => true
1162
- )
1163
- )
1164
- )
1165
- )
1166
- ));
1167
- $this->management_profiles = new Google_Service_Analytics_ManagementProfiles_Resource($this, $this->serviceName, 'profiles', array(
1168
- 'methods' => array(
1169
- 'delete' => array(
1170
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}',
1171
- 'httpMethod' => 'DELETE',
1172
- 'parameters' => array(
1173
- 'accountId' => array(
1174
- 'location' => 'path',
1175
- 'type' => 'string',
1176
- 'required' => true
1177
- ),
1178
- 'webPropertyId' => array(
1179
- 'location' => 'path',
1180
- 'type' => 'string',
1181
- 'required' => true
1182
- ),
1183
- 'profileId' => array(
1184
- 'location' => 'path',
1185
- 'type' => 'string',
1186
- 'required' => true
1187
- )
1188
- )
1189
- ),
1190
- 'get' => array(
1191
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}',
1192
- 'httpMethod' => 'GET',
1193
- 'parameters' => array(
1194
- 'accountId' => array(
1195
- 'location' => 'path',
1196
- 'type' => 'string',
1197
- 'required' => true
1198
- ),
1199
- 'webPropertyId' => array(
1200
- 'location' => 'path',
1201
- 'type' => 'string',
1202
- 'required' => true
1203
- ),
1204
- 'profileId' => array(
1205
- 'location' => 'path',
1206
- 'type' => 'string',
1207
- 'required' => true
1208
- )
1209
- )
1210
- ),
1211
- 'insert' => array(
1212
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles',
1213
- 'httpMethod' => 'POST',
1214
- 'parameters' => array(
1215
- 'accountId' => array(
1216
- 'location' => 'path',
1217
- 'type' => 'string',
1218
- 'required' => true
1219
- ),
1220
- 'webPropertyId' => array(
1221
- 'location' => 'path',
1222
- 'type' => 'string',
1223
- 'required' => true
1224
- )
1225
- )
1226
- ),
1227
- 'list' => array(
1228
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles',
1229
- 'httpMethod' => 'GET',
1230
- 'parameters' => array(
1231
- 'accountId' => array(
1232
- 'location' => 'path',
1233
- 'type' => 'string',
1234
- 'required' => true
1235
- ),
1236
- 'webPropertyId' => array(
1237
- 'location' => 'path',
1238
- 'type' => 'string',
1239
- 'required' => true
1240
- ),
1241
- 'max-results' => array(
1242
- 'location' => 'query',
1243
- 'type' => 'integer'
1244
- ),
1245
- 'start-index' => array(
1246
- 'location' => 'query',
1247
- 'type' => 'integer'
1248
- )
1249
- )
1250
- ),
1251
- 'patch' => array(
1252
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}',
1253
- 'httpMethod' => 'PATCH',
1254
- 'parameters' => array(
1255
- 'accountId' => array(
1256
- 'location' => 'path',
1257
- 'type' => 'string',
1258
- 'required' => true
1259
- ),
1260
- 'webPropertyId' => array(
1261
- 'location' => 'path',
1262
- 'type' => 'string',
1263
- 'required' => true
1264
- ),
1265
- 'profileId' => array(
1266
- 'location' => 'path',
1267
- 'type' => 'string',
1268
- 'required' => true
1269
- )
1270
- )
1271
- ),
1272
- 'update' => array(
1273
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}',
1274
- 'httpMethod' => 'PUT',
1275
- 'parameters' => array(
1276
- 'accountId' => array(
1277
- 'location' => 'path',
1278
- 'type' => 'string',
1279
- 'required' => true
1280
- ),
1281
- 'webPropertyId' => array(
1282
- 'location' => 'path',
1283
- 'type' => 'string',
1284
- 'required' => true
1285
- ),
1286
- 'profileId' => array(
1287
- 'location' => 'path',
1288
- 'type' => 'string',
1289
- 'required' => true
1290
- )
1291
- )
1292
- )
1293
- )
1294
- ));
1295
- $this->management_segments = new Google_Service_Analytics_ManagementSegments_Resource($this, $this->serviceName, 'segments', array(
1296
- 'methods' => array(
1297
- 'list' => array(
1298
- 'path' => 'management/segments',
1299
- 'httpMethod' => 'GET',
1300
- 'parameters' => array(
1301
- 'max-results' => array(
1302
- 'location' => 'query',
1303
- 'type' => 'integer'
1304
- ),
1305
- 'start-index' => array(
1306
- 'location' => 'query',
1307
- 'type' => 'integer'
1308
- )
1309
- )
1310
- )
1311
- )
1312
- ));
1313
- $this->management_unsampledReports = new Google_Service_Analytics_ManagementUnsampledReports_Resource($this, $this->serviceName, 'unsampledReports', array(
1314
- 'methods' => array(
1315
- 'get' => array(
1316
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/unsampledReports/{unsampledReportId}',
1317
- 'httpMethod' => 'GET',
1318
- 'parameters' => array(
1319
- 'accountId' => array(
1320
- 'location' => 'path',
1321
- 'type' => 'string',
1322
- 'required' => true
1323
- ),
1324
- 'webPropertyId' => array(
1325
- 'location' => 'path',
1326
- 'type' => 'string',
1327
- 'required' => true
1328
- ),
1329
- 'profileId' => array(
1330
- 'location' => 'path',
1331
- 'type' => 'string',
1332
- 'required' => true
1333
- ),
1334
- 'unsampledReportId' => array(
1335
- 'location' => 'path',
1336
- 'type' => 'string',
1337
- 'required' => true
1338
- )
1339
- )
1340
- ),
1341
- 'insert' => array(
1342
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/unsampledReports',
1343
- 'httpMethod' => 'POST',
1344
- 'parameters' => array(
1345
- 'accountId' => array(
1346
- 'location' => 'path',
1347
- 'type' => 'string',
1348
- 'required' => true
1349
- ),
1350
- 'webPropertyId' => array(
1351
- 'location' => 'path',
1352
- 'type' => 'string',
1353
- 'required' => true
1354
- ),
1355
- 'profileId' => array(
1356
- 'location' => 'path',
1357
- 'type' => 'string',
1358
- 'required' => true
1359
- )
1360
- )
1361
- ),
1362
- 'list' => array(
1363
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/unsampledReports',
1364
- 'httpMethod' => 'GET',
1365
- 'parameters' => array(
1366
- 'accountId' => array(
1367
- 'location' => 'path',
1368
- 'type' => 'string',
1369
- 'required' => true
1370
- ),
1371
- 'webPropertyId' => array(
1372
- 'location' => 'path',
1373
- 'type' => 'string',
1374
- 'required' => true
1375
- ),
1376
- 'profileId' => array(
1377
- 'location' => 'path',
1378
- 'type' => 'string',
1379
- 'required' => true
1380
- ),
1381
- 'max-results' => array(
1382
- 'location' => 'query',
1383
- 'type' => 'integer'
1384
- ),
1385
- 'start-index' => array(
1386
- 'location' => 'query',
1387
- 'type' => 'integer'
1388
- )
1389
- )
1390
- )
1391
- )
1392
- ));
1393
- $this->management_uploads = new Google_Service_Analytics_ManagementUploads_Resource($this, $this->serviceName, 'uploads', array(
1394
- 'methods' => array(
1395
- 'deleteUploadData' => array(
1396
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/deleteUploadData',
1397
- 'httpMethod' => 'POST',
1398
- 'parameters' => array(
1399
- 'accountId' => array(
1400
- 'location' => 'path',
1401
- 'type' => 'string',
1402
- 'required' => true
1403
- ),
1404
- 'webPropertyId' => array(
1405
- 'location' => 'path',
1406
- 'type' => 'string',
1407
- 'required' => true
1408
- ),
1409
- 'customDataSourceId' => array(
1410
- 'location' => 'path',
1411
- 'type' => 'string',
1412
- 'required' => true
1413
- )
1414
- )
1415
- ),
1416
- 'get' => array(
1417
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/uploads/{uploadId}',
1418
- 'httpMethod' => 'GET',
1419
- 'parameters' => array(
1420
- 'accountId' => array(
1421
- 'location' => 'path',
1422
- 'type' => 'string',
1423
- 'required' => true
1424
- ),
1425
- 'webPropertyId' => array(
1426
- 'location' => 'path',
1427
- 'type' => 'string',
1428
- 'required' => true
1429
- ),
1430
- 'customDataSourceId' => array(
1431
- 'location' => 'path',
1432
- 'type' => 'string',
1433
- 'required' => true
1434
- ),
1435
- 'uploadId' => array(
1436
- 'location' => 'path',
1437
- 'type' => 'string',
1438
- 'required' => true
1439
- )
1440
- )
1441
- ),
1442
- 'list' => array(
1443
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/uploads',
1444
- 'httpMethod' => 'GET',
1445
- 'parameters' => array(
1446
- 'accountId' => array(
1447
- 'location' => 'path',
1448
- 'type' => 'string',
1449
- 'required' => true
1450
- ),
1451
- 'webPropertyId' => array(
1452
- 'location' => 'path',
1453
- 'type' => 'string',
1454
- 'required' => true
1455
- ),
1456
- 'customDataSourceId' => array(
1457
- 'location' => 'path',
1458
- 'type' => 'string',
1459
- 'required' => true
1460
- ),
1461
- 'max-results' => array(
1462
- 'location' => 'query',
1463
- 'type' => 'integer'
1464
- ),
1465
- 'start-index' => array(
1466
- 'location' => 'query',
1467
- 'type' => 'integer'
1468
- )
1469
- )
1470
- ),
1471
- 'migrateDataImport' => array(
1472
- 'path' => 'management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/migrateDataImport',
1473
- 'httpMethod' => 'POST',
1474
- 'parameters' => array(
1475
- 'accountId' => array(
1476
- 'location' => 'path',
1477
- 'type' => 'string',
1478
- 'required' => true
1479
- ),
1480
- 'webPropertyId' => array(
1481
- 'location' => 'path',
1482
- 'type' => 'string',
1483
-