Google Analytics - Version 2.0.3

Version Description

  • Reliability improvements for Google Analytics access
  • Better connection to Google Analytics API
  • Fixed the save settings issue, thanks @biologix @tanshaydar
  • Minor bug fixes
Download this release

Release Info

Developer ShareThis
Plugin Icon wp plugin Google Analytics
Version 2.0.3
Comparing to
See all releases

Code changes from version 2.0.2 to 2.0.3

class/Ga_Admin.php CHANGED
@@ -1,649 +1,641 @@
1
  <?php
2
 
3
- class Ga_Admin
4
- {
5
-
6
- const GA_WEB_PROPERTY_ID_OPTION_NAME = 'googleanalytics_web_property_id';
7
-
8
- const GA_EXCLUDE_ROLES_OPTION_NAME = 'googleanalytics_exclude_roles';
9
-
10
- const GA_SHARETHIS_TERMS_OPTION_NAME = 'googleanalytics_sharethis_terms';
11
-
12
- const GA_HIDE_TERMS_OPTION_NAME = 'googleanalytics_hide_terms';
13
-
14
- const GA_VERSION_OPTION_NAME = 'googleanalytics_version';
15
-
16
- const GA_SELECTED_ACCOUNT = 'googleanalytics_selected_account';
17
-
18
- const GA_OAUTH_AUTH_CODE_OPTION_NAME = 'googleanalytics_oauth_auth_code';
19
-
20
- const GA_OAUTH_AUTH_TOKEN_OPTION_NAME = 'googleanalytics_oauth_auth_token';
21
-
22
- const GA_ACCOUNT_DATA_OPTION_NAME = 'googleanalytics_account_data';
23
-
24
- const GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME = 'googleanalytics_web_property_id_manually';
25
-
26
- const GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME = 'googleanalytics_web_property_id_manually_value';
27
-
28
- const MIN_WP_VERSION = '3.8';
29
-
30
- const NOTICE_SUCCESS = 'success';
31
-
32
- const NOTICE_WARNING = 'warning';
33
-
34
- const NOTICE_ERROR = 'error';
35
-
36
- /**
37
- * Instantiate API client.
38
- *
39
- * @return Ga_Lib_Api_Client|null
40
- */
41
- public static function api_client()
42
- {
43
- $instance = Ga_Lib_Api_Client::get_instance();
44
- $token = Ga_Helper::get_option(self::GA_OAUTH_AUTH_TOKEN_OPTION_NAME);
45
- try {
46
- if ( ! empty($token)) {
47
- $token = json_decode($token, true);
48
- $instance->set_access_token($token);
49
- }
50
- } catch (Exception $e) {
51
- Ga_Helper::ga_oauth_notice($e->getMessage());
52
- }
53
-
54
- return $instance;
55
- }
56
-
57
- /*
58
- * Initializes plugin's options during plugin activation process.
59
- */
60
- public static function activate_googleanalytics()
61
- {
62
- add_option(self::GA_WEB_PROPERTY_ID_OPTION_NAME, Ga_Helper::GA_DEFAULT_WEB_ID);
63
- add_option(self::GA_EXCLUDE_ROLES_OPTION_NAME, wp_json_encode(array()));
64
- add_option(self::GA_SHARETHIS_TERMS_OPTION_NAME, false);
65
- add_option(self::GA_HIDE_TERMS_OPTION_NAME, false);
66
- add_option(self::GA_VERSION_OPTION_NAME);
67
- add_option(self::GA_OAUTH_AUTH_CODE_OPTION_NAME);
68
- add_option(self::GA_OAUTH_AUTH_TOKEN_OPTION_NAME);
69
- add_option(self::GA_ACCOUNT_DATA_OPTION_NAME);
70
- add_option(self::GA_SELECTED_ACCOUNT);
71
- add_option(self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME);
72
- add_option(self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME);
73
- }
74
-
75
- /*
76
- * Deletes plugin's options during plugin activation process.
77
- */
78
- public static function deactivate_googleanalytics()
79
- {
80
- delete_option(self::GA_WEB_PROPERTY_ID_OPTION_NAME);
81
- delete_option(self::GA_EXCLUDE_ROLES_OPTION_NAME);
82
- delete_option(self::GA_OAUTH_AUTH_CODE_OPTION_NAME);
83
- delete_option(self::GA_OAUTH_AUTH_TOKEN_OPTION_NAME);
84
- delete_option(self::GA_ACCOUNT_DATA_OPTION_NAME);
85
- delete_option(self::GA_SELECTED_ACCOUNT);
86
- delete_option(self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME);
87
- delete_option(self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME);
88
- }
89
-
90
- /**
91
- * Deletes plugin's options during plugin uninstallation process.
92
- */
93
- public static function uninstall_googleanalytics()
94
- {
95
- delete_option(self::GA_SHARETHIS_TERMS_OPTION_NAME);
96
- delete_option(self::GA_HIDE_TERMS_OPTION_NAME);
97
- delete_option(self::GA_VERSION_OPTION_NAME);
98
- }
99
-
100
- /**
101
- * Do actions during plugin load.
102
- */
103
- public static function loaded_googleanalytics()
104
- {
105
- self::update_googleanalytics();
106
- }
107
-
108
- /**
109
- * Update hook fires when plugin is being loaded.
110
- */
111
- public static function update_googleanalytics()
112
- {
113
-
114
- $version = get_option(self::GA_VERSION_OPTION_NAME);
115
- $installed_version = get_option(self::GA_VERSION_OPTION_NAME, '1.0.7');
116
- $old_property_value = Ga_Helper::get_option('web_property_id');
117
- if (version_compare($installed_version, GOOGLEANALYTICS_VERSION, 'eq')) {
118
- return;
119
- }
120
- if (empty($old_property_value) && empty($version)) {
121
- update_option(self::GA_SHARETHIS_TERMS_OPTION_NAME, true);
122
- }
123
-
124
- if (version_compare($installed_version, GOOGLEANALYTICS_VERSION, 'lt')) {
125
-
126
- if ( ! empty($old_property_value)) {
127
- Ga_Helper::update_option(self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME, $old_property_value);
128
- Ga_Helper::update_option(self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME, 1);
129
- delete_option('web_property_id');
130
- }
131
- }
132
-
133
- update_option(self::GA_VERSION_OPTION_NAME, GOOGLEANALYTICS_VERSION);
134
- }
135
-
136
-
137
- public static function preupdate_exclude_roles($new_value, $old_value)
138
- {
139
- if ( ! Ga_Helper::are_terms_accepted()) {
140
- return '';
141
- }
142
-
143
- return wp_json_encode($new_value);
144
- }
145
-
146
- /**
147
- * Pre-update hook for preparing JSON structure.
148
- *
149
- * @param $new_value
150
- * @param $old_value
151
- *
152
- * @return mixed
153
- */
154
- public static function preupdate_selected_account($new_value, $old_value)
155
- {
156
- if ( ! empty($new_value)) {
157
- $data = explode("_", $new_value);
158
-
159
- if ( ! empty($data[1])) {
160
- Ga_Helper::update_option(self::GA_WEB_PROPERTY_ID_OPTION_NAME, $data[1]);
161
- }
162
- }
163
-
164
- return wp_json_encode($data);
165
- }
166
-
167
- /**
168
- * Registers plugin's settings.
169
- */
170
- public static function admin_init_googleanalytics()
171
- {
172
- register_setting(GA_NAME, self::GA_WEB_PROPERTY_ID_OPTION_NAME);
173
- register_setting(GA_NAME, self::GA_EXCLUDE_ROLES_OPTION_NAME);
174
- register_setting(GA_NAME, self::GA_SELECTED_ACCOUNT);
175
- register_setting(GA_NAME, self::GA_OAUTH_AUTH_CODE_OPTION_NAME);
176
- register_setting(GA_NAME, self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME);
177
- register_setting(GA_NAME, self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME);
178
- add_filter('pre_update_option_' . Ga_Admin::GA_EXCLUDE_ROLES_OPTION_NAME, 'Ga_Admin::preupdate_exclude_roles',
179
- 1, 2);
180
- add_filter('pre_update_option_' . Ga_Admin::GA_SELECTED_ACCOUNT, 'Ga_Admin::preupdate_selected_account', 1, 2);
181
- }
182
-
183
- /**
184
- * Builds plugin's menu structure.
185
- */
186
- public static function admin_menu_googleanalytics()
187
- {
188
- if (current_user_can('manage_options')) {
189
- add_menu_page('Google Analytics', 'Google Analytics', 'manage_options', 'googleanalytics',
190
- 'Ga_Admin::statistics_page_googleanalytics', 'dashicons-chart-line', 1000);
191
- add_submenu_page('googleanalytics', 'Google Analytics', __('Dashboard'), 'manage_options',
192
- 'googleanalytics', 'Ga_Admin::statistics_page_googleanalytics');
193
- add_submenu_page('googleanalytics', 'Google Analytics', __('Settings'), 'manage_options',
194
- 'googleanalytics/settings', 'Ga_Admin::options_page_googleanalytics');
195
- }
196
- }
197
-
198
- /**
199
- * Sets accept terms option to TRUE.
200
- */
201
- public static function update_terms()
202
- {
203
- update_option(self::GA_SHARETHIS_TERMS_OPTION_NAME, true);
204
- wp_redirect(admin_url(Ga_Helper::GA_SETTINGS_PAGE_URL));
205
- }
206
-
207
- /**
208
- * Prepares and displays plugin's stats page.
209
- */
210
- public static function statistics_page_googleanalytics()
211
- {
212
-
213
- if ( ! Ga_Helper::is_wp_version_valid() || ! Ga_Helper::is_php_version_valid()) {
214
- return false;
215
- }
216
-
217
- $data = self::get_stats_page();
218
- Ga_View::load('statistics', array(
219
- 'data' => $data
220
- ));
221
- }
222
-
223
- /**
224
- * Prepares and displays plugin's settings page.
225
- */
226
- public static function options_page_googleanalytics()
227
- {
228
-
229
- if ( ! Ga_Helper::is_wp_version_valid() || ! Ga_Helper::is_php_version_valid()) {
230
- return false;
231
- }
232
-
233
- /**
234
- * Keeps data to be extracted as variables in the view.
235
- *
236
- * @var array $data
237
- */
238
- $data = array();
239
-
240
- $data[self::GA_WEB_PROPERTY_ID_OPTION_NAME] = get_option(self::GA_WEB_PROPERTY_ID_OPTION_NAME);
241
- $data[self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME] = get_option(self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME);
242
- $data[self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME] = get_option(self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME);
243
-
244
- $roles = Ga_Helper::get_user_roles();
245
- $saved = json_decode(get_option(self::GA_EXCLUDE_ROLES_OPTION_NAME), true);
246
-
247
- $tmp = array();
248
- if ( ! empty($roles)) {
249
- foreach ($roles as $role) {
250
- $role_id = Ga_Helper::prepare_role_id($role);
251
- $tmp[] = array(
252
- 'name' => $role,
253
- 'id' => $role_id,
254
- 'checked' => ( ! empty($saved[$role_id]) && $saved[$role_id] === 'on')
255
- );
256
- }
257
- }
258
- $data['roles'] = $tmp;
259
-
260
- if (Ga_Helper::is_authorized()) {
261
- $data['ga_accounts_selector'] = self::get_accounts_selector();
262
- } else {
263
- $data['popup_url'] = self::get_auth_popup_url();
264
- }
265
- if ( ! empty($_GET['err'])) {
266
- switch ($_GET['err']) {
267
- case 1:
268
- $data['error_message'] = Ga_Helper::ga_oauth_notice('There was a problem with Google Oauth2 authentication process.');
269
- break;
270
- }
271
- }
272
- Ga_View::load('page', array(
273
- 'data' => $data
274
- ));
275
- }
276
-
277
- /**
278
- * Prepares and returns a plugin's URL to be opened in a popup window
279
- * during Google authentication process.
280
- *
281
- * @return mixed
282
- */
283
- public static function get_auth_popup_url()
284
- {
285
- return admin_url(Ga_Helper::GA_SETTINGS_PAGE_URL . '&ga_action=ga_auth');
286
- }
287
-
288
- /**
289
- * Prepares and returns Google Account's dropdown code.
290
- *
291
- * @return string
292
- */
293
- public static function get_accounts_selector()
294
- {
295
- $selected = Ga_Helper::get_selected_account_data();
296
-
297
- return Ga_View::load('ga_accounts_selector', array(
298
- 'selector' => json_decode(get_option(self::GA_ACCOUNT_DATA_OPTION_NAME), true),
299
- 'selected' => $selected ? implode("_", $selected) : null,
300
- 'add_manually_enabled' => Ga_Helper::is_code_manually_enabled()
301
- ), true);
302
- }
303
-
304
- /**
305
- * Adds Bootstrap scripts.
306
- */
307
- public static function enqueue_bootstrap()
308
- {
309
- wp_register_script(GA_NAME . '-bootstrap-js', GA_PLUGIN_URL . '/js/bootstrap.min.js', array(
310
- 'jquery'
311
- ));
312
- wp_register_style(GA_NAME . '-bootstrap-css', GA_PLUGIN_URL . '/css/bootstrap.min.css', false, null, 'all');
313
- wp_enqueue_script(GA_NAME . '-bootstrap-js');
314
- wp_enqueue_style(GA_NAME . '-bootstrap-css');
315
- }
316
-
317
- /**
318
- * Adds JS scripts for the settings page.
319
- */
320
- public static function enqueue_ga_scripts()
321
- {
322
- wp_register_script(GA_NAME . '-page-js', GA_PLUGIN_URL . '/js/' . GA_NAME . '_page.js', array(
323
- 'jquery'
324
- ));
325
- wp_enqueue_script(GA_NAME . '-page-js');
326
- }
327
-
328
- /**
329
- * Adds CSS plugin's scripts.
330
- */
331
- public static function enqueue_ga_css()
332
- {
333
- wp_register_style(GA_NAME . '-css', GA_PLUGIN_URL . '/css/' . GA_NAME . '.css', false, null, 'all');
334
- wp_enqueue_style(GA_NAME . '-css');
335
- }
336
-
337
- /**
338
- * Enqueues dashboard JS scripts.
339
- */
340
- private static function enqueue_dashboard_scripts()
341
- {
342
- wp_register_script(GA_NAME . '-dashboard-js', GA_PLUGIN_URL . '/js/' . GA_NAME . '_dashboard.js', array(
343
- 'jquery'
344
- ));
345
- wp_enqueue_script(GA_NAME . '-dashboard-js');
346
- }
347
-
348
- /**
349
- * Enqueues plugin's JS and CSS scripts.
350
- */
351
- public static function enqueue_scripts()
352
- {
353
- if (Ga_Helper::is_dashboard_page() || Ga_Helper::is_plugin_page()) {
354
- wp_register_script(GA_NAME . '-js', GA_PLUGIN_URL . '/js/' . GA_NAME . '.js', array(
355
- 'jquery'
356
- ));
357
- wp_enqueue_script(GA_NAME . '-js');
358
-
359
- wp_register_script('googlecharts', 'https://www.gstatic.com/charts/loader.js', null, null, false);
360
- wp_enqueue_script('googlecharts');
361
-
362
- self::enqueue_ga_css();
363
- }
364
-
365
- if (Ga_Helper::is_dashboard_page()) {
366
- self::enqueue_dashboard_scripts();
367
- }
368
-
369
- if (Ga_Helper::is_plugin_page()) {
370
- self::enqueue_bootstrap();
371
- self::enqueue_ga_scripts();
372
- }
373
- }
374
-
375
- /**
376
- * Prepares plugin's statistics page and return HTML code.
377
- *
378
- * @return string HTML code
379
- */
380
- public static function get_stats_page()
381
- {
382
- $chart = null;
383
- $boxes = null;
384
- $labels = null;
385
- $sources = null;
386
- if (Ga_Helper::is_authorized() && Ga_Helper::is_account_selected()) {
387
- $selected = Ga_Helper::get_selected_account_data(true);
388
-
389
- $query_params = Ga_Stats::get_query('main_chart', $selected['view_id']);
390
- $stats_data = self::api_client()->call('ga_api_data', array(
391
-
392
- $query_params
393
- ));
394
-
395
- $boxes_data = self::api_client()->call('ga_api_data', array(
396
-
397
- Ga_Stats::get_query('boxes', $selected['view_id'])
398
- ));
399
- $sources_data = self::api_client()->call('ga_api_data', array(
400
-
401
- Ga_Stats::get_query('sources', $selected['view_id'])
402
- ));
403
- $chart = ! empty($stats_data) ? Ga_Stats::get_chart($stats_data->getData()) : array();
404
- $boxes = ! empty($boxes_data) ? Ga_Stats::get_boxes($boxes_data->getData()) : array();
405
- $last_chart_date = ! empty($chart) ? $chart['date'] : strtotime('now');
406
- unset($chart['date']);
407
- $labels = array(
408
- 'thisWeek' => date('M d, Y', strtotime('-6 day', $last_chart_date)) . ' - ' . date('M d, Y',
409
- $last_chart_date),
410
- 'lastWeek' => date('M d, Y', strtotime('-13 day', $last_chart_date)) . ' - ' . date('M d, Y',
411
- strtotime('-7 day', $last_chart_date))
412
- );
413
- $sources = ! empty($sources_data) ? Ga_Stats::get_sources($sources_data->getData()) : array();
414
- }
415
-
416
- return Ga_Helper::get_chart_page('stats', array(
417
-
418
- 'chart' => $chart,
419
- 'boxes' => $boxes,
420
- 'labels' => $labels,
421
- 'sources' => $sources
422
- ));
423
- }
424
-
425
- /**
426
- * Shows plugin's notice on the admin area.
427
- */
428
- public static function admin_notice_googleanalytics()
429
- {
430
- if (( ! get_option(self::GA_SHARETHIS_TERMS_OPTION_NAME) && Ga_Helper::is_plugin_page()) || ( ! get_option(self::GA_SHARETHIS_TERMS_OPTION_NAME) && ! get_option(self::GA_HIDE_TERMS_OPTION_NAME))) {
431
- $current_url = Ga_Helper::get_current_url();
432
- $url = (strstr($current_url,
433
- '?') ? $current_url . '&' : $current_url . '?') . http_build_query(array('ga_action' => 'update_terms'));
434
- Ga_View::load('ga_notice', array(
435
- 'url' => $url
436
- ));
437
- }
438
-
439
- if ( ! empty($_GET['settings-updated'])) {
440
- echo Ga_Helper::ga_wp_notice(_('Settings saved'), self::NOTICE_SUCCESS);
441
- }
442
- }
443
-
444
- /**
445
- * Prepare required PHP version warning.
446
- * @return string
447
- */
448
- public static function admin_notice_googleanalytics_php_version()
449
- {
450
- echo Ga_Helper::ga_wp_notice(_('Cannot use Google Analytics plugin. PHP version ' . phpversion() . ' is to low. Required PHP version: ' . Ga_Helper::PHP_VERSION_REQUIRED),
451
- self::NOTICE_ERROR);
452
- }
453
-
454
- /**
455
- * Prepare required WP version warning
456
- * @return string
457
- */
458
- public static function admin_notice_googleanalytics_wp_version()
459
- {
460
- echo Ga_Helper::ga_wp_notice(_('Google Analytics plugin requires at least WordPress version ' . self::MIN_WP_VERSION),
461
- self::NOTICE_ERROR);
462
- }
463
-
464
- /**
465
- * Hides plugin's notice
466
- */
467
- public static function admin_notice_hide_googleanalytics()
468
- {
469
- update_option(self::GA_HIDE_TERMS_OPTION_NAME, true);
470
- }
471
-
472
- /**
473
- * Adds GA dashboard widget only for administrators.
474
- */
475
- public static function add_dashboard_device_widget()
476
- {
477
- if (Ga_Helper::is_administrator()) {
478
- wp_add_dashboard_widget('ga_dashboard_widget', __('Google Analytics Dashboard'),
479
- 'Ga_Helper::add_ga_dashboard_widget');
480
- }
481
- }
482
-
483
- /**
484
- * Adds plugin's actions
485
- */
486
- public static function add_actions()
487
- {
488
- add_action('admin_init', 'Ga_Admin::admin_init_googleanalytics');
489
- add_action('admin_menu', 'Ga_Admin::admin_menu_googleanalytics');
490
- add_action('admin_enqueue_scripts', 'Ga_Admin::enqueue_scripts');
491
- add_action('wp_dashboard_setup', 'Ga_Admin::add_dashboard_device_widget');
492
- add_action('wp_ajax_ga_ajax_data_change', 'Ga_Admin::ga_ajax_data_change');
493
- add_action('admin_notices', 'Ga_Admin::admin_notice_googleanalytics');
494
-
495
- if ( ! get_option(self::GA_SHARETHIS_TERMS_OPTION_NAME) && ! get_option(self::GA_HIDE_TERMS_OPTION_NAME)) {
496
- add_action('wp_ajax_googleanalytics_hide_terms', 'Ga_Admin::admin_notice_hide_googleanalytics');
497
- }
498
- }
499
-
500
- /**
501
- * Adds plugin's filters
502
- */
503
- public static function add_filters()
504
- {
505
- add_filter('plugin_action_links', 'Ga_Admin::ga_action_links', 10, 5);
506
- }
507
-
508
- /**
509
- * Adds new action links on the plugin list.
510
- *
511
- * @param $actions
512
- * @param $plugin_file
513
- *
514
- * @return mixed
515
- */
516
- public static function ga_action_links($actions, $plugin_file)
517
- {
518
-
519
- if (basename($plugin_file) == GA_NAME . '.php') {
520
- array_unshift($actions, '<a href="' . esc_url(get_admin_url(null,
521
- Ga_Helper::GA_SETTINGS_PAGE_URL)) . '">' . _('Settings') . '</a>');
522
- }
523
-
524
- return $actions;
525
- }
526
-
527
- public static function init_oauth()
528
- {
529
- // $code = ! empty( $_GET['code'] ) ? $_GET['code'] : null;
530
- $code = Ga_Helper::get_option(self::GA_OAUTH_AUTH_CODE_OPTION_NAME);
531
-
532
- if ( ! Ga_Helper::is_authorized() && $code) {
533
- Ga_Helper::update_option(self::GA_OAUTH_AUTH_CODE_OPTION_NAME, "");
534
-
535
- // Get access token
536
- $response = self::api_client()->call('ga_auth_get_access_token', $code);
537
- $param = '';
538
- if ( ! self::save_access_token($response)) {
539
- $param = '&err=1';
540
- }
541
- self::api_client()->set_access_token($response->getData());
542
-
543
- // Get accounts data
544
- $account_summaries = self::api_client()->call('ga_api_account_summaries');
545
- self::save_ga_account_summaries($account_summaries->getData());
546
-
547
- wp_redirect(admin_url(Ga_Helper::GA_SETTINGS_PAGE_URL . $param));
548
- }
549
- }
550
-
551
- public static function handle_actions()
552
- {
553
- $action = ! empty($_GET['ga_action']) ? $_GET['ga_action'] : null;
554
-
555
- if ($action) {
556
- $class = __CLASS__;
557
- if (is_callable(array(
558
-
559
- $class,
560
- $action
561
- ))) {
562
- call_user_func($class . '::' . $action);
563
- }
564
- }
565
- }
566
-
567
- public static function ga_auth()
568
- {
569
- if (Ga_Helper::are_terms_accepted()) {
570
- header('Location:' . self::api_client()->create_auth_url());
571
- } else {
572
- wp_die(Ga_Helper::ga_oauth_notice(__('Please accept the terms to use this feature')));
573
- }
574
- }
575
-
576
- /**
577
- * Save access token.
578
- *
579
- * @param Ga_Lib_Api_Response $response
580
- *
581
- * @return boolean
582
- */
583
- public static function save_access_token($response)
584
- {
585
- $access_token = $response->getData();
586
- if ( ! empty($access_token)) {
587
- $access_token['created'] = time();
588
- } else {
589
- return false;
590
- }
591
-
592
- return update_option(self::GA_OAUTH_AUTH_TOKEN_OPTION_NAME, wp_json_encode($access_token));
593
- }
594
-
595
- /**
596
- * Saves Google Analytics account data.
597
- *
598
- * @param $data
599
- *
600
- * @return array
601
- */
602
- public static function save_ga_account_summaries($data)
603
- {
604
- $return = array();
605
- if ( ! empty($data['items'])) {
606
- foreach ($data['items'] as $item) {
607
- $tmp = array();
608
- $tmp['id'] = $item['id'];
609
- $tmp['name'] = $item['name'];
610
- if (is_array($item['webProperties'])) {
611
- foreach ($item['webProperties'] as $property) {
612
- $profiles = array();
613
- if (is_array($property['profiles'])) {
614
- foreach ($property['profiles'] as $profile) {
615
- $profiles[] = array(
616
-
617
- 'id' => $profile['id'],
618
- 'name' => $profile['name']
619
- );
620
- }
621
- }
622
-
623
- $tmp['webProperties'][] = array(
624
-
625
- 'webPropertyId' => $property['id'],
626
- 'name' => $property['name'],
627
- 'profiles' => $profiles
628
- );
629
- }
630
- }
631
-
632
- $return[] = $tmp;
633
- }
634
-
635
- update_option(self::GA_ACCOUNT_DATA_OPTION_NAME, wp_json_encode($return));
636
- update_option(self::GA_WEB_PROPERTY_ID_OPTION_NAME, "");
637
- }
638
-
639
- return $return;
640
- }
641
-
642
- public static function ga_ajax_data_change()
643
- {
644
- $date_range = ! empty($_POST['date_range']) ? $_POST['date_range'] : null;
645
- $metric = ! empty($_POST['metric']) ? $_POST['metric'] : null;
646
- echo Ga_Helper::get_ga_dashboard_widget_data_json($date_range, $metric, false, true);
647
- wp_die();
648
- }
649
  }
1
  <?php
2
 
3
+ class Ga_Admin {
4
+
5
+ const GA_WEB_PROPERTY_ID_OPTION_NAME = 'googleanalytics_web_property_id';
6
+
7
+ const GA_EXCLUDE_ROLES_OPTION_NAME = 'googleanalytics_exclude_roles';
8
+
9
+ const GA_SHARETHIS_TERMS_OPTION_NAME = 'googleanalytics_sharethis_terms';
10
+
11
+ const GA_HIDE_TERMS_OPTION_NAME = 'googleanalytics_hide_terms';
12
+
13
+ const GA_VERSION_OPTION_NAME = 'googleanalytics_version';
14
+
15
+ const GA_SELECTED_ACCOUNT = 'googleanalytics_selected_account';
16
+
17
+ const GA_OAUTH_AUTH_CODE_OPTION_NAME = 'googleanalytics_oauth_auth_code';
18
+
19
+ const GA_OAUTH_AUTH_TOKEN_OPTION_NAME = 'googleanalytics_oauth_auth_token';
20
+
21
+ const GA_ACCOUNT_DATA_OPTION_NAME = 'googleanalytics_account_data';
22
+
23
+ const GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME = 'googleanalytics_web_property_id_manually';
24
+
25
+ const GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME = 'googleanalytics_web_property_id_manually_value';
26
+
27
+ const MIN_WP_VERSION = '3.8';
28
+
29
+ const NOTICE_SUCCESS = 'success';
30
+
31
+ const NOTICE_WARNING = 'warning';
32
+
33
+ const NOTICE_ERROR = 'error';
34
+
35
+ /**
36
+ * Instantiate API client.
37
+ *
38
+ * @return Ga_Lib_Api_Client|null
39
+ */
40
+ public static function api_client() {
41
+ $instance = Ga_Lib_Api_Client::get_instance();
42
+ $token = Ga_Helper::get_option( self::GA_OAUTH_AUTH_TOKEN_OPTION_NAME );
43
+ try {
44
+ if ( ! empty( $token ) ) {
45
+ $token = json_decode( $token, true );
46
+ $instance->set_access_token( $token );
47
+ }
48
+ } catch ( Exception $e ) {
49
+ Ga_Helper::ga_oauth_notice( $e->getMessage() );
50
+ }
51
+
52
+ return $instance;
53
+ }
54
+
55
+ /*
56
+ * Initializes plugin's options during plugin activation process.
57
+ */
58
+ public static function activate_googleanalytics() {
59
+ add_option( self::GA_WEB_PROPERTY_ID_OPTION_NAME, Ga_Helper::GA_DEFAULT_WEB_ID );
60
+ add_option( self::GA_EXCLUDE_ROLES_OPTION_NAME, wp_json_encode( array() ) );
61
+ add_option( self::GA_SHARETHIS_TERMS_OPTION_NAME, false );
62
+ add_option( self::GA_HIDE_TERMS_OPTION_NAME, false );
63
+ add_option( self::GA_VERSION_OPTION_NAME );
64
+ add_option( self::GA_OAUTH_AUTH_CODE_OPTION_NAME );
65
+ add_option( self::GA_OAUTH_AUTH_TOKEN_OPTION_NAME );
66
+ add_option( self::GA_ACCOUNT_DATA_OPTION_NAME );
67
+ add_option( self::GA_SELECTED_ACCOUNT );
68
+ add_option( self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME );
69
+ add_option( self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME );
70
+ }
71
+
72
+ /*
73
+ * Deletes plugin's options during plugin activation process.
74
+ */
75
+ public static function deactivate_googleanalytics() {
76
+ delete_option( self::GA_WEB_PROPERTY_ID_OPTION_NAME );
77
+ delete_option( self::GA_EXCLUDE_ROLES_OPTION_NAME );
78
+ delete_option( self::GA_OAUTH_AUTH_CODE_OPTION_NAME );
79
+ delete_option( self::GA_OAUTH_AUTH_TOKEN_OPTION_NAME );
80
+ delete_option( self::GA_ACCOUNT_DATA_OPTION_NAME );
81
+ delete_option( self::GA_SELECTED_ACCOUNT );
82
+ delete_option( self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME );
83
+ delete_option( self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME );
84
+ }
85
+
86
+ /**
87
+ * Deletes plugin's options during plugin uninstallation process.
88
+ */
89
+ public static function uninstall_googleanalytics() {
90
+ delete_option( self::GA_SHARETHIS_TERMS_OPTION_NAME );
91
+ delete_option( self::GA_HIDE_TERMS_OPTION_NAME );
92
+ delete_option( self::GA_VERSION_OPTION_NAME );
93
+ }
94
+
95
+ /**
96
+ * Do actions during plugin load.
97
+ */
98
+ public static function loaded_googleanalytics() {
99
+ self::update_googleanalytics();
100
+ }
101
+
102
+ /**
103
+ * Update hook fires when plugin is being loaded.
104
+ */
105
+ public static function update_googleanalytics() {
106
+
107
+ $version = get_option( self::GA_VERSION_OPTION_NAME );
108
+ $installed_version = get_option( self::GA_VERSION_OPTION_NAME, '1.0.7' );
109
+ $old_property_value = Ga_Helper::get_option( 'web_property_id' );
110
+ if ( version_compare( $installed_version, GOOGLEANALYTICS_VERSION, 'eq' ) ) {
111
+ return;
112
+ }
113
+ if ( empty( $old_property_value ) && empty( $version ) ) {
114
+ update_option( self::GA_SHARETHIS_TERMS_OPTION_NAME, true );
115
+ }
116
+
117
+ if ( version_compare( $installed_version, GOOGLEANALYTICS_VERSION, 'lt' ) ) {
118
+
119
+ if ( ! empty( $old_property_value ) ) {
120
+ Ga_Helper::update_option( self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME, $old_property_value );
121
+ Ga_Helper::update_option( self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME, 1 );
122
+ delete_option( 'web_property_id' );
123
+ }
124
+ }
125
+
126
+ update_option( self::GA_VERSION_OPTION_NAME, GOOGLEANALYTICS_VERSION );
127
+ }
128
+
129
+
130
+ public static function preupdate_exclude_roles( $new_value, $old_value ) {
131
+ if ( ! Ga_Helper::are_terms_accepted() ) {
132
+ return '';
133
+ }
134
+
135
+ return wp_json_encode( $new_value );
136
+ }
137
+
138
+ /**
139
+ * Pre-update hook for preparing JSON structure.
140
+ *
141
+ * @param $new_value
142
+ * @param $old_value
143
+ *
144
+ * @return mixed
145
+ */
146
+ public static function preupdate_selected_account( $new_value, $old_value ) {
147
+ if ( ! empty( $new_value ) ) {
148
+ $data = explode( "_", $new_value );
149
+
150
+ if ( ! empty( $data[1] ) ) {
151
+ Ga_Helper::update_option( self::GA_WEB_PROPERTY_ID_OPTION_NAME, $data[1] );
152
+ }
153
+ }
154
+
155
+ return wp_json_encode( $data );
156
+ }
157
+
158
+ /**
159
+ * Registers plugin's settings.
160
+ */
161
+ public static function admin_init_googleanalytics() {
162
+ register_setting( GA_NAME, self::GA_WEB_PROPERTY_ID_OPTION_NAME );
163
+ register_setting( GA_NAME, self::GA_EXCLUDE_ROLES_OPTION_NAME );
164
+ register_setting( GA_NAME, self::GA_SELECTED_ACCOUNT );
165
+ register_setting( GA_NAME, self::GA_OAUTH_AUTH_CODE_OPTION_NAME );
166
+ register_setting( GA_NAME, self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME );
167
+ register_setting( GA_NAME, self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME );
168
+ add_filter( 'pre_update_option_' . Ga_Admin::GA_EXCLUDE_ROLES_OPTION_NAME, 'Ga_Admin::preupdate_exclude_roles',
169
+ 1, 2 );
170
+ add_filter( 'pre_update_option_' . Ga_Admin::GA_SELECTED_ACCOUNT, 'Ga_Admin::preupdate_selected_account', 1,
171
+ 2 );
172
+ }
173
+
174
+ /**
175
+ * Builds plugin's menu structure.
176
+ */
177
+ public static function admin_menu_googleanalytics() {
178
+ if ( current_user_can( 'manage_options' ) ) {
179
+ add_menu_page( 'Google Analytics', 'Google Analytics', 'manage_options', 'googleanalytics',
180
+ 'Ga_Admin::statistics_page_googleanalytics', 'dashicons-chart-line', 1000 );
181
+ add_submenu_page( 'googleanalytics', 'Google Analytics', __( 'Dashboard' ), 'manage_options',
182
+ 'googleanalytics', 'Ga_Admin::statistics_page_googleanalytics' );
183
+ add_submenu_page( 'googleanalytics', 'Google Analytics', __( 'Settings' ), 'manage_options',
184
+ 'googleanalytics/settings', 'Ga_Admin::options_page_googleanalytics' );
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Sets accept terms option to TRUE.
190
+ */
191
+ public static function update_terms() {
192
+ update_option( self::GA_SHARETHIS_TERMS_OPTION_NAME, true );
193
+ wp_redirect( admin_url( Ga_Helper::GA_SETTINGS_PAGE_URL ) );
194
+ }
195
+
196
+ /**
197
+ * Prepares and displays plugin's stats page.
198
+ */
199
+ public static function statistics_page_googleanalytics() {
200
+
201
+ if ( ! Ga_Helper::is_wp_version_valid() || ! Ga_Helper::is_php_version_valid() ) {
202
+ return false;
203
+ }
204
+
205
+ $data = self::get_stats_page();
206
+ Ga_View::load( 'statistics', array(
207
+ 'data' => $data
208
+ ) );
209
+
210
+ self::display_api_errors();
211
+ }
212
+
213
+ /**
214
+ * Prepares and displays plugin's settings page.
215
+ */
216
+ public static function options_page_googleanalytics() {
217
+
218
+ if ( ! Ga_Helper::is_wp_version_valid() || ! Ga_Helper::is_php_version_valid() ) {
219
+ return false;
220
+ }
221
+
222
+ /**
223
+ * Keeps data to be extracted as variables in the view.
224
+ *
225
+ * @var array $data
226
+ */
227
+ $data = array();
228
+
229
+ $data[ self::GA_WEB_PROPERTY_ID_OPTION_NAME ] = get_option( self::GA_WEB_PROPERTY_ID_OPTION_NAME );
230
+ $data[ self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME ] = get_option( self::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME );
231
+ $data[ self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME ] = get_option( self::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME );
232
+
233
+ $roles = Ga_Helper::get_user_roles();
234
+ $saved = json_decode( get_option( self::GA_EXCLUDE_ROLES_OPTION_NAME ), true );
235
+
236
+ $tmp = array();
237
+ if ( ! empty( $roles ) ) {
238
+ foreach ( $roles as $role ) {
239
+ $role_id = Ga_Helper::prepare_role_id( $role );
240
+ $tmp[] = array(
241
+ 'name' => $role,
242
+ 'id' => $role_id,
243
+ 'checked' => ( ! empty( $saved[ $role_id ] ) && $saved[ $role_id ] === 'on' )
244
+ );
245
+ }
246
+ }
247
+ $data['roles'] = $tmp;
248
+
249
+ if ( Ga_Helper::is_authorized() ) {
250
+ $data['ga_accounts_selector'] = self::get_accounts_selector();
251
+ } else {
252
+ $data['popup_url'] = self::get_auth_popup_url();
253
+ }
254
+ if ( ! empty( $_GET['err'] ) ) {
255
+ switch ( $_GET['err'] ) {
256
+ case 1:
257
+ $data['error_message'] = Ga_Helper::ga_oauth_notice( 'There was a problem with Google Oauth2 authentication process.' );
258
+ break;
259
+ }
260
+ }
261
+ Ga_View::load( 'page', array(
262
+ 'data' => $data
263
+ ) );
264
+
265
+ self::display_api_errors();
266
+ }
267
+
268
+ /**
269
+ * Prepares and returns a plugin's URL to be opened in a popup window
270
+ * during Google authentication process.
271
+ *
272
+ * @return mixed
273
+ */
274
+ public static function get_auth_popup_url() {
275
+ return admin_url( Ga_Helper::GA_SETTINGS_PAGE_URL . '&ga_action=ga_auth' );
276
+ }
277
+
278
+ /**
279
+ * Prepares and returns Google Account's dropdown code.
280
+ *
281
+ * @return string
282
+ */
283
+ public static function get_accounts_selector() {
284
+ $selected = Ga_Helper::get_selected_account_data();
285
+
286
+ return Ga_View::load( 'ga_accounts_selector', array(
287
+ 'selector' => json_decode( get_option( self::GA_ACCOUNT_DATA_OPTION_NAME ), true ),
288
+ 'selected' => $selected ? implode( "_", $selected ) : null,
289
+ 'add_manually_enabled' => Ga_Helper::is_code_manually_enabled()
290
+ ), true );
291
+ }
292
+
293
+ /**
294
+ * Adds Bootstrap scripts.
295
+ */
296
+ public static function enqueue_bootstrap() {
297
+ wp_register_script( GA_NAME . '-bootstrap-js', GA_PLUGIN_URL . '/js/bootstrap.min.js', array(
298
+ 'jquery'
299
+ ) );
300
+ wp_register_style( GA_NAME . '-bootstrap-css', GA_PLUGIN_URL . '/css/bootstrap.min.css', false, null, 'all' );
301
+ wp_enqueue_script( GA_NAME . '-bootstrap-js' );
302
+ wp_enqueue_style( GA_NAME . '-bootstrap-css' );
303
+ }
304
+
305
+ /**
306
+ * Adds JS scripts for the settings page.
307
+ */
308
+ public static function enqueue_ga_scripts() {
309
+ wp_register_script( GA_NAME . '-page-js', GA_PLUGIN_URL . '/js/' . GA_NAME . '_page.js', array(
310
+ 'jquery'
311
+ ) );
312
+ wp_enqueue_script( GA_NAME . '-page-js' );
313
+ }
314
+
315
+ /**
316
+ * Adds CSS plugin's scripts.
317
+ */
318
+ public static function enqueue_ga_css() {
319
+ wp_register_style( GA_NAME . '-css', GA_PLUGIN_URL . '/css/' . GA_NAME . '.css', false, null, 'all' );
320
+ wp_enqueue_style( GA_NAME . '-css' );
321
+ }
322
+
323
+ /**
324
+ * Enqueues dashboard JS scripts.
325
+ */
326
+ private static function enqueue_dashboard_scripts() {
327
+ wp_register_script( GA_NAME . '-dashboard-js', GA_PLUGIN_URL . '/js/' . GA_NAME . '_dashboard.js', array(
328
+ 'jquery'
329
+ ) );
330
+ wp_enqueue_script( GA_NAME . '-dashboard-js' );
331
+ }
332
+
333
+ /**
334
+ * Enqueues plugin's JS and CSS scripts.
335
+ */
336
+ public static function enqueue_scripts() {
337
+ if ( Ga_Helper::is_dashboard_page() || Ga_Helper::is_plugin_page() ) {
338
+ wp_register_script( GA_NAME . '-js', GA_PLUGIN_URL . '/js/' . GA_NAME . '.js', array(
339
+ 'jquery'
340
+ ) );
341
+ wp_enqueue_script( GA_NAME . '-js' );
342
+
343
+ wp_register_script( 'googlecharts', 'https://www.gstatic.com/charts/loader.js', null, null, false );
344
+ wp_enqueue_script( 'googlecharts' );
345
+
346
+ self::enqueue_ga_css();
347
+ }
348
+
349
+ if ( Ga_Helper::is_dashboard_page() ) {
350
+ self::enqueue_dashboard_scripts();
351
+ }
352
+
353
+ if ( Ga_Helper::is_plugin_page() ) {
354
+ self::enqueue_bootstrap();
355
+ self::enqueue_ga_scripts();
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Prepares plugin's statistics page and return HTML code.
361
+ *
362
+ * @return string HTML code
363
+ */
364
+ public static function get_stats_page() {
365
+ $chart = null;
366
+ $boxes = null;
367
+ $labels = null;
368
+ $sources = null;
369
+ if ( Ga_Helper::is_authorized() && Ga_Helper::is_account_selected() ) {
370
+ $selected = Ga_Helper::get_selected_account_data( true );
371
+
372
+ $query_params = Ga_Stats::get_query( 'main_chart', $selected['view_id'] );
373
+ $stats_data = self::api_client()->call( 'ga_api_data', array(
374
+
375
+ $query_params
376
+ ) );
377
+
378
+ $boxes_data = self::api_client()->call( 'ga_api_data', array(
379
+
380
+ Ga_Stats::get_query( 'boxes', $selected['view_id'] )
381
+ ) );
382
+ $sources_data = self::api_client()->call( 'ga_api_data', array(
383
+
384
+ Ga_Stats::get_query( 'sources', $selected['view_id'] )
385
+ ) );
386
+ $chart = ! empty( $stats_data ) ? Ga_Stats::get_chart( $stats_data->getData() ) : array();
387
+ $boxes = ! empty( $boxes_data ) ? Ga_Stats::get_boxes( $boxes_data->getData() ) : array();
388
+ $last_chart_date = ! empty( $chart ) ? $chart['date'] : strtotime( 'now' );
389
+ unset( $chart['date'] );
390
+ $labels = array(
391
+ 'thisWeek' => date( 'M d, Y', strtotime( '-6 day', $last_chart_date ) ) . ' - ' . date( 'M d, Y',
392
+ $last_chart_date ),
393
+ 'lastWeek' => date( 'M d, Y', strtotime( '-13 day', $last_chart_date ) ) . ' - ' . date( 'M d, Y',
394
+ strtotime( '-7 day', $last_chart_date ) )
395
+ );
396
+ $sources = ! empty( $sources_data ) ? Ga_Stats::get_sources( $sources_data->getData() ) : array();
397
+ }
398
+
399
+ return Ga_Helper::get_chart_page( 'stats', array(
400
+
401
+ 'chart' => $chart,
402
+ 'boxes' => $boxes,
403
+ 'labels' => $labels,
404
+ 'sources' => $sources
405
+ ) );
406
+ }
407
+
408
+ /**
409
+ * Shows plugin's notice on the admin area.
410
+ */
411
+ public static function admin_notice_googleanalytics() {
412
+ if ( ( ! get_option( self::GA_SHARETHIS_TERMS_OPTION_NAME ) && Ga_Helper::is_plugin_page() ) || ( ! get_option( self::GA_SHARETHIS_TERMS_OPTION_NAME ) && ! get_option( self::GA_HIDE_TERMS_OPTION_NAME ) ) ) {
413
+ $current_url = Ga_Helper::get_current_url();
414
+ $url = ( strstr( $current_url,
415
+ '?' ) ? $current_url . '&' : $current_url . '?' ) . http_build_query( array( 'ga_action' => 'update_terms' ) );
416
+ Ga_View::load( 'ga_notice', array(
417
+ 'url' => $url
418
+ ) );
419
+ }
420
+
421
+ if ( ! empty( $_GET['settings-updated'] ) ) {
422
+ echo Ga_Helper::ga_wp_notice( _( 'Settings saved' ), self::NOTICE_SUCCESS );
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Prepare required PHP version warning.
428
+ * @return string
429
+ */
430
+ public static function admin_notice_googleanalytics_php_version() {
431
+ echo Ga_Helper::ga_wp_notice( _( 'Cannot use Google Analytics plugin. PHP version ' . phpversion() . ' is to low. Required PHP version: ' . Ga_Helper::PHP_VERSION_REQUIRED ),
432
+ self::NOTICE_ERROR );
433
+ }
434
+
435
+ /**
436
+ * Prepare required WP version warning
437
+ * @return string
438
+ */
439
+ public static function admin_notice_googleanalytics_wp_version() {
440
+ echo Ga_Helper::ga_wp_notice( _( 'Google Analytics plugin requires at least WordPress version ' . self::MIN_WP_VERSION ),
441
+ self::NOTICE_ERROR );
442
+ }
443
+
444
+ /**
445
+ * Hides plugin's notice
446
+ */
447
+ public static function admin_notice_hide_googleanalytics() {
448
+ update_option( self::GA_HIDE_TERMS_OPTION_NAME, true );
449
+ }
450
+
451
+ /**
452
+ * Adds GA dashboard widget only for administrators.
453
+ */
454
+ public static function add_dashboard_device_widget() {
455
+ if ( Ga_Helper::is_administrator() ) {
456
+ wp_add_dashboard_widget( 'ga_dashboard_widget', __( 'Google Analytics Dashboard' ),
457
+ 'Ga_Helper::add_ga_dashboard_widget' );
458
+ }
459
+ }
460
+
461
+ /**
462
+ * Adds plugin's actions
463
+ */
464
+ public static function add_actions() {
465
+ add_action( 'admin_init', 'Ga_Admin::admin_init_googleanalytics' );
466
+ add_action( 'admin_menu', 'Ga_Admin::admin_menu_googleanalytics' );
467
+ add_action( 'admin_enqueue_scripts', 'Ga_Admin::enqueue_scripts' );
468
+ add_action( 'wp_dashboard_setup', 'Ga_Admin::add_dashboard_device_widget' );
469
+ add_action( 'wp_ajax_ga_ajax_data_change', 'Ga_Admin::ga_ajax_data_change' );
470
+ add_action( 'admin_notices', 'Ga_Admin::admin_notice_googleanalytics' );
471
+
472
+ if ( ! get_option( self::GA_SHARETHIS_TERMS_OPTION_NAME ) && ! get_option( self::GA_HIDE_TERMS_OPTION_NAME ) ) {
473
+ add_action( 'wp_ajax_googleanalytics_hide_terms', 'Ga_Admin::admin_notice_hide_googleanalytics' );
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Adds plugin's filters
479
+ */
480
+ public static function add_filters() {
481
+ add_filter( 'plugin_action_links', 'Ga_Admin::ga_action_links', 10, 5 );
482
+ }
483
+
484
+ /**
485
+ * Adds new action links on the plugin list.
486
+ *
487
+ * @param $actions
488
+ * @param $plugin_file
489
+ *
490
+ * @return mixed
491
+ */
492
+ public static function ga_action_links( $actions, $plugin_file ) {
493
+
494
+ if ( basename( $plugin_file ) == GA_NAME . '.php' ) {
495
+ array_unshift( $actions, '<a href="' . esc_url( get_admin_url( null,
496
+ Ga_Helper::GA_SETTINGS_PAGE_URL ) ) . '">' . _( 'Settings' ) . '</a>' );
497
+ }
498
+
499
+ return $actions;
500
+ }
501
+
502
+ public static function init_oauth() {
503
+ // $code = ! empty( $_GET['code'] ) ? $_GET['code'] : null;
504
+ $code = Ga_Helper::get_option( self::GA_OAUTH_AUTH_CODE_OPTION_NAME );
505
+
506
+ if ( ! Ga_Helper::is_authorized() && $code ) {
507
+ Ga_Helper::update_option( self::GA_OAUTH_AUTH_CODE_OPTION_NAME, "" );
508
+
509
+ // Get access token
510
+ $response = self::api_client()->call( 'ga_auth_get_access_token', $code );
511
+ if ( empty( $response ) ) {
512
+ return false;
513
+ }
514
+ $param = '';
515
+ if ( ! self::save_access_token( $response ) ) {
516
+ $param = '&err=1';
517
+ }
518
+ self::api_client()->set_access_token( $response->getData() );
519
+
520
+ // Get accounts data
521
+ $account_summaries = self::api_client()->call( 'ga_api_account_summaries' );
522
+ self::save_ga_account_summaries( $account_summaries->getData() );
523
+
524
+ wp_redirect( admin_url( Ga_Helper::GA_SETTINGS_PAGE_URL . $param ) );
525
+ }
526
+ }
527
+
528
+ public static function handle_actions() {
529
+ $action = ! empty( $_GET['ga_action'] ) ? $_GET['ga_action'] : null;
530
+
531
+ if ( $action ) {
532
+ $class = __CLASS__;
533
+ if ( is_callable( array(
534
+
535
+ $class,
536
+ $action
537
+ ) ) ) {
538
+ call_user_func( $class . '::' . $action );
539
+ }
540
+ }
541
+ }
542
+
543
+ public static function ga_auth() {
544
+ if ( Ga_Helper::are_terms_accepted() ) {
545
+ header( 'Location:' . self::api_client()->create_auth_url() );
546
+ } else {
547
+ wp_die( Ga_Helper::ga_oauth_notice( __( 'Please accept the terms to use this feature' ) ) );
548
+ }
549
+ }
550
+
551
+ /**
552
+ * Save access token.
553
+ *
554
+ * @param Ga_Lib_Api_Response $response
555
+ *
556
+ * @return boolean
557
+ */
558
+ public static function save_access_token( $response, $refresh_token = '' ) {
559
+ $access_token = $response->getData();
560
+ if ( ! empty( $access_token ) ) {
561
+ $access_token['created'] = time();
562
+ } else {
563
+ return false;
564
+ }
565
+
566
+ if ( ! empty( $refresh_token ) ) {
567
+ $access_token['refresh_token'] = $refresh_token;
568
+ }
569
+
570
+ return update_option( self::GA_OAUTH_AUTH_TOKEN_OPTION_NAME, wp_json_encode( $access_token ) );
571
+ }
572
+
573
+ /**
574
+ * Saves Google Analytics account data.
575
+ *
576
+ * @param $data
577
+ *
578
+ * @return array
579
+ */
580
+ public static function save_ga_account_summaries( $data ) {
581
+ $return = array();
582
+ if ( ! empty( $data['items'] ) ) {
583
+ foreach ( $data['items'] as $item ) {
584
+ $tmp = array();
585
+ $tmp['id'] = $item['id'];
586
+ $tmp['name'] = $item['name'];
587
+ if ( is_array( $item['webProperties'] ) ) {
588
+ foreach ( $item['webProperties'] as $property ) {
589
+ $profiles = array();
590
+ if ( is_array( $property['profiles'] ) ) {
591
+ foreach ( $property['profiles'] as $profile ) {
592
+ $profiles[] = array(
593
+
594
+ 'id' => $profile['id'],
595
+ 'name' => $profile['name']
596
+ );
597
+ }
598
+ }
599
+
600
+ $tmp['webProperties'][] = array(
601
+
602
+ 'webPropertyId' => $property['id'],
603
+ 'name' => $property['name'],
604
+ 'profiles' => $profiles
605
+ );
606
+ }
607
+ }
608
+
609
+ $return[] = $tmp;
610
+ }
611
+
612
+ update_option( self::GA_ACCOUNT_DATA_OPTION_NAME, wp_json_encode( $return ) );
613
+ update_option( self::GA_WEB_PROPERTY_ID_OPTION_NAME, "" );
614
+ }
615
+
616
+ return $return;
617
+ }
618
+
619
+ /**
620
+ * Handle AJAX data for the GA dashboard widget.
621
+ */
622
+ public static function ga_ajax_data_change() {
623
+ $date_range = ! empty( $_POST['date_range'] ) ? $_POST['date_range'] : null;
624
+ $metric = ! empty( $_POST['metric'] ) ? $_POST['metric'] : null;
625
+ echo Ga_Helper::get_ga_dashboard_widget_data_json( $date_range, $metric, false, true );
626
+ wp_die();
627
+ }
628
+
629
+ /**
630
+ * Displays API error messages.
631
+ */
632
+ public static function display_api_errors() {
633
+ $errors = self::api_client()->get_errors();
634
+ if ( ! empty( $errors ) ) {
635
+ foreach ( $errors as $error ) {
636
+ echo Ga_Helper::ga_wp_notice( _( '[' . $error['class'] . ']' ) . ' ' . $error['message'],
637
+ self::NOTICE_ERROR );
638
+ }
639
+ }
640
+ }
 
 
 
 
 
 
 
 
641
  }
class/Ga_Helper.php CHANGED
@@ -1,488 +1,461 @@
1
  <?php
2
 
3
- class Ga_Helper
4
- {
5
-
6
- const ROLE_ID_PREFIX = "role-id-";
7
-
8
- const GA_DEFAULT_WEB_ID = "UA-0000000-0";
9
-
10
- const GA_STATISTICS_PAGE_URL = "admin.php?page=googleanalytics";
11
-
12
- const GA_SETTINGS_PAGE_URL = "admin.php?page=googleanalytics/settings";
13
-
14
- const DASHBOARD_PAGE_NAME = "dashboard";
15
-
16
- const PHP_VERSION_REQUIRED = "5.2.17";
17
-
18
- /**
19
- * Init plugin actions.
20
- *
21
- */
22
- public static function init()
23
- {
24
-
25
- // Displays errors related to required PHP version
26
- if ( ! self::is_php_version_valid()) {
27
- add_action('admin_notices', 'Ga_Admin::admin_notice_googleanalytics_php_version');
28
-
29
- return false;
30
- }
31
-
32
- // Displays errors related to required WP version
33
- if ( ! self::is_wp_version_valid()) {
34
- add_action('admin_notices', 'Ga_Admin::admin_notice_googleanalytics_wp_version');
35
-
36
- return false;
37
- }
38
-
39
- if ( ! is_admin()) {
40
- Ga_Frontend::add_actions();
41
- }
42
-
43
- if (is_admin()) {
44
- Ga_Admin::add_filters();
45
- Ga_Admin::add_actions();
46
- Ga_Admin::init_oauth();
47
- Ga_Admin::handle_actions();
48
- }
49
- }
50
-
51
- /**
52
- * Checks if current page is a WordPress dashboard.
53
- * @return int
54
- */
55
- public static function is_plugin_page()
56
- {
57
- $site = get_current_screen();
58
-
59
- return preg_match('/' . GA_NAME . '/', $site->base);
60
- }
61
-
62
- /**
63
- * Checks if current page is a WordPress dashboard.
64
- * @return number
65
- */
66
- public static function is_dashboard_page()
67
- {
68
- $site = get_current_screen();
69
-
70
- return preg_match('/' . self::DASHBOARD_PAGE_NAME . '/', $site->base);
71
- }
72
-
73
- /**
74
- * Check whether the plugin is configured.
75
- *
76
- * @param String $web_id
77
- *
78
- * @return boolean
79
- */
80
- public static function is_configured($web_id)
81
- {
82
- return $web_id !== self::GA_DEFAULT_WEB_ID;
83
- }
84
-
85
- /**
86
- * Prepare an array of current site's user roles
87
- *
88
- * return array
89
- */
90
- public static function get_user_roles()
91
- {
92
- global $wp_roles;
93
- if ( ! isset($wp_roles)) {
94
- $wp_roles = new WP_Roles();
95
- }
96
-
97
- return $wp_roles->get_names();
98
- }
99
-
100
- /**
101
- * Prepare a role ID.
102
- *
103
- * The role ID is derived from the role's name and will be used
104
- * in its setting name in the additional settings.
105
- *
106
- * @param string $role_name Role name
107
- *
108
- * @return string
109
- */
110
- public static function prepare_role_id($role_name)
111
- {
112
- return self::ROLE_ID_PREFIX . strtolower(preg_replace('/[\W]/', '-', before_last_bar($role_name)));
113
- }
114
-
115
- /**
116
- * Prepares role id.
117
- *
118
- * @param $v
119
- * @param $k
120
- */
121
- public static function prepare_role(&$v, $k)
122
- {
123
- $v = self::prepare_role_id($v);
124
- }
125
-
126
- /**
127
- * Checks whether user role is excluded from adding UA code.
128
- *
129
- * @return boolean
130
- */
131
- public static function can_add_ga_code()
132
- {
133
- $current_user = wp_get_current_user();
134
- $user_roles = ! empty($current_user->roles) ? $current_user->roles : array();
135
- $exclude_roles = json_decode(get_option(Ga_Admin::GA_EXCLUDE_ROLES_OPTION_NAME), true);
136
-
137
- array_walk($user_roles, 'Ga_Helper::prepare_role');
138
-
139
- $return = true;
140
- foreach ($user_roles as $role) {
141
- if ( ! empty($exclude_roles[$role])) {
142
- $return = false;
143
- break;
144
- }
145
- }
146
-
147
- return $return;
148
- }
149
-
150
- /**
151
- * Adds ga dashboard widget HTML code for a WordPress
152
- * Dashboard widget hook.
153
- */
154
- public static function add_ga_dashboard_widget()
155
- {
156
- echo self::get_ga_dashboard_widget();
157
- }
158
-
159
- /**
160
- * Generates dashboard widget HTML code.
161
- *
162
- * @param string $date_range Google Analytics specific date range string.
163
- * @param boolean $text_mode
164
- * @param boolean $ajax
165
- *
166
- * @return null | string HTML dashboard widget code.
167
- */
168
- public static function get_ga_dashboard_widget($date_range = null, $text_mode = false, $ajax = false)
169
- {
170
- if (empty($date_range)) {
171
- $date_range = '30daysAgo';
172
- }
173
-
174
- // Get chart and boxes data
175
- $data = self::get_dashboard_widget_data($date_range);
176
-
177
- if ($text_mode) {
178
- return self::get_chart_page('ga_dashboard_widget' . ($ajax ? "_ajax" : ""), array(
179
- 'chart' => $data['chart'],
180
- 'boxes' => $data['boxes']
181
- ));
182
- } else {
183
- echo self::get_chart_page('ga_dashboard_widget' . ($ajax ? "_ajax" : ""), array(
184
- 'chart' => $data['chart'],
185
- 'boxes' => $data['boxes'],
186
- 'more_details_url' => admin_url(self::GA_STATISTICS_PAGE_URL)
187
- ));
188
- }
189
-
190
- return null;
191
- }
192
-
193
- /**
194
- * Generates JSON data string for AJAX calls.
195
- *
196
- * @param string $date_range
197
- * @param string $metric
198
- * @param boolean $text_mode
199
- * @param boolean $ajax
200
- *
201
- * @return string|false Returns JSON data string
202
- */
203
- public static function get_ga_dashboard_widget_data_json(
204
- $date_range = null,
205
- $metric = null,
206
- $text_mode = false,
207
- $ajax = false
208
- ) {
209
- if (empty($date_range)) {
210
- $date_range = '30daysAgo';
211
- }
212
-
213
- if (empty($metric)) {
214
- $metric = 'pageviews';
215
- }
216
-
217
- $data = self::get_dashboard_widget_data($date_range, $metric);
218
-
219
- return wp_json_encode($data);
220
- }
221
-
222
- /**
223
- * Gets dashboard widget data.
224
- *
225
- * @param date_range
226
- * @param metric
227
- *
228
- * @return array Return chart and boxes data
229
- */
230
- private static function get_dashboard_widget_data($date_range, $metric = null)
231
- {
232
- $selected = self::get_selected_account_data(true);
233
-
234
- $query_params = Ga_Stats::get_query('main_chart', $selected['view_id'], $date_range, $metric);
235
- $stats_data = Ga_Admin::api_client()->call('ga_api_data', array(
236
-
237
- $query_params
238
- ));
239
-
240
- $boxes_query = Ga_Stats::get_query('dashboard_boxes', $selected['view_id'], $date_range);
241
- $boxes_data = Ga_Admin::api_client()->call('ga_api_data', array(
242
-
243
- $boxes_query
244
- ));
245
-
246
- $chart = ! empty($stats_data) ? Ga_Stats::get_dashboard_chart($stats_data->getData()) : array();
247
- $boxes = ! empty($boxes_data) ? Ga_Stats::get_dashboard_boxes_data($boxes_data->getData()) : array();
248
-
249
- return array(
250
-
251
- 'chart' => $chart,
252
- 'boxes' => $boxes
253
- );
254
- }
255
-
256
- public static function is_account_selected()
257
- {
258
- return self::get_selected_account_data();
259
- }
260
-
261
- /**
262
- * Returns HTML code of the chart page or a notice.
263
- *
264
- * @param chart
265
- *
266
- * @return string Returns HTML code
267
- */
268
- public static function get_chart_page($view, $params)
269
- {
270
-
271
- $message = sprintf(__('Statistics can only be seen after you authenticate with your Google account on the <a href="%s">Settings page</a>.'),
272
- admin_url(self::GA_SETTINGS_PAGE_URL));
273
-
274
- if (self::is_authorized() && ! self::is_code_manually_enabled()) {
275
- if (self::is_account_selected()) {
276
- if ($params) {
277
- return Ga_View::load($view, $params, true);
278
- } else {
279
- return self::ga_oauth_notice(sprintf('Please configure your <a href="%s">Google Analytics settings</a>.',
280
- admin_url(self::GA_SETTINGS_PAGE_URL)));
281
- }
282
- } else {
283
- return self::ga_oauth_notice($message);
284
- }
285
- } else {
286
- return self::ga_oauth_notice($message);
287
- }
288
- }
289
-
290
- /**
291
- * Checks whether users is authorized with Google.
292
- *
293
- * @return boolean
294
- */
295
- public static function is_authorized()
296
- {
297
- return Ga_Admin::api_client()->get_instance()->is_authorized();
298
- }
299
-
300
- /**
301
- * Wrapper for WordPress method get_option
302
- *
303
- * @param string $name Option name
304
- *
305
- * @return NULL|mixed|boolean
306
- */
307
- public static function get_option($name)
308
- {
309
- $opt = get_option($name);
310
-
311
- return ! empty($opt) ? $opt : null;
312
- }
313
-
314
- /**
315
- * Wrapper for WordPress method update_option
316
- *
317
- * @param string $name
318
- * @param mixed $value
319
- *
320
- * @return NULL|boolean
321
- */
322
- public static function update_option($name, $value)
323
- {
324
- $opt = update_option($name, $value);
325
-
326
- return ! empty($opt) ? $opt : null;
327
- }
328
-
329
- /**
330
- * Loads ga notice HTML code with given message included.
331
- *
332
- * @param string $message
333
- * $param bool $cannot_activate Whether the plugin cannot be activated
334
- *
335
- * @return string
336
- */
337
- public static function ga_oauth_notice($message)
338
- {
339
- return Ga_View::load('ga_oauth_notice', array(
340
- 'msg' => $message
341
- ), true);
342
- }
343
-
344
- /**
345
- * Displays notice following the WP style.
346
- *
347
- * @param $message
348
- * @param string $type
349
- *
350
- * @return string
351
- */
352
- public static function ga_wp_notice($message, $type = '')
353
- {
354
- return Ga_View::load('ga_wp_notice', array(
355
- 'type' => empty($type) ? Ga_Admin::NOTICE_WARNING : $type,
356
- 'msg' => $message
357
- ), true);
358
- }
359
-
360
- /**
361
- * Gets data according to selected GA account.
362
- *
363
- * @param boolean $assoc
364
- *
365
- * @return mixed
366
- */
367
- public static function get_selected_account_data($assoc = false)
368
- {
369
- $data = json_decode(self::get_option(Ga_Admin::GA_SELECTED_ACCOUNT));
370
- $data = ( ! empty($data) && count($data) == 3) ? $data : false;
371
-
372
- if ($data) {
373
- if ($assoc) {
374
- return array(
375
-
376
- 'account_id' => $data[0],
377
- 'web_property_id' => $data[1],
378
- 'view_id' => $data[2]
379
- );
380
- } else {
381
- return $data;
382
- }
383
- }
384
-
385
- return false;
386
- }
387
-
388
- /**
389
- * Chekcs whether option for manually UA-code
390
- * @return NULL|mixed|boolean
391
- */
392
- public static function is_code_manually_enabled()
393
- {
394
- return Ga_Helper::get_option(Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME);
395
- }
396
-
397
- /**
398
- * Adds percent sign to the given text.
399
- *
400
- * @param $text
401
- *
402
- * @return string
403
- */
404
- public static function format_percent($text)
405
- {
406
- $text = self::add_plus($text);
407
-
408
- return $text . '%';
409
- }
410
-
411
- /**
412
- * Adds plus sign before number.
413
- *
414
- * @param $number
415
- *
416
- * @return string
417
- */
418
- public static function add_plus($number)
419
- {
420
- if ($number > 0) {
421
- return '+' . $number;
422
- }
423
-
424
- return $number;
425
- }
426
-
427
- /**
428
- * Check whether current user has administrator privileges.
429
- *
430
- * @return bool
431
- */
432
- public static function is_administrator()
433
- {
434
- if (current_user_can('administrator')) {
435
- return true;
436
- }
437
-
438
- return false;
439
- }
440
-
441
- public static function is_wp_version_valid()
442
- {
443
- $wp_version = get_bloginfo('version');
444
-
445
- return version_compare($wp_version, Ga_Admin::MIN_WP_VERSION, 'ge');
446
- }
447
-
448
- /**
449
- * Check if terms are accepted
450
- *
451
- * @return bool
452
- */
453
- public static function are_terms_accepted()
454
- {
455
- return self::get_option(Ga_Admin::GA_SHARETHIS_TERMS_OPTION_NAME);
456
- }
457
-
458
- /**
459
- * Check if sharethis scripts enabled
460
- *
461
- * @return bool
462
- */
463
- public static function is_sharethis_included()
464
- {
465
- return GA_SHARETHIS_SCRIPTS_INCLUDED;
466
- }
467
-
468
- /**
469
- * @return mixed
470
- */
471
- public static function is_php_version_valid()
472
- {
473
- $p = '#(\.0+)+($|-)#';
474
- $ver1 = preg_replace($p, '', phpversion());
475
- $ver2 = preg_replace($p, '', self::PHP_VERSION_REQUIRED);
476
- $operator = 'ge';
477
- $compare = isset($operator) ?
478
- version_compare($ver1, $ver2, $operator) :
479
- version_compare($ver1, $ver2);
480
-
481
- return $compare;
482
- }
483
-
484
- public static function get_current_url()
485
- {
486
- return $_SERVER['REQUEST_URI'];
487
- }
488
  }
1
  <?php
2
 
3
+ class Ga_Helper {
4
+
5
+ const ROLE_ID_PREFIX = "role-id-";
6
+
7
+ const GA_DEFAULT_WEB_ID = "UA-0000000-0";
8
+
9
+ const GA_STATISTICS_PAGE_URL = "admin.php?page=googleanalytics";
10
+
11
+ const GA_SETTINGS_PAGE_URL = "admin.php?page=googleanalytics/settings";
12
+
13
+ const DASHBOARD_PAGE_NAME = "dashboard";
14
+
15
+ const PHP_VERSION_REQUIRED = "5.2.17";
16
+
17
+ /**
18
+ * Init plugin actions.
19
+ *
20
+ */
21
+ public static function init() {
22
+
23
+ // Displays errors related to required PHP version
24
+ if ( ! self::is_php_version_valid() ) {
25
+ add_action( 'admin_notices', 'Ga_Admin::admin_notice_googleanalytics_php_version' );
26
+
27
+ return false;
28
+ }
29
+
30
+ // Displays errors related to required WP version
31
+ if ( ! self::is_wp_version_valid() ) {
32
+ add_action( 'admin_notices', 'Ga_Admin::admin_notice_googleanalytics_wp_version' );
33
+
34
+ return false;
35
+ }
36
+
37
+ if ( ! is_admin() ) {
38
+ Ga_Frontend::add_actions();
39
+ }
40
+
41
+ if ( is_admin() ) {
42
+ Ga_Admin::add_filters();
43
+ Ga_Admin::add_actions();
44
+ Ga_Admin::init_oauth();
45
+ Ga_Admin::handle_actions();
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Checks if current page is a WordPress dashboard.
51
+ * @return int
52
+ */
53
+ public static function is_plugin_page() {
54
+ $site = get_current_screen();
55
+
56
+ return preg_match( '/' . GA_NAME . '/', $site->base );
57
+ }
58
+
59
+ /**
60
+ * Checks if current page is a WordPress dashboard.
61
+ * @return number
62
+ */
63
+ public static function is_dashboard_page() {
64
+ $site = get_current_screen();
65
+
66
+ return preg_match( '/' . self::DASHBOARD_PAGE_NAME . '/', $site->base );
67
+ }
68
+
69
+ /**
70
+ * Check whether the plugin is configured.
71
+ *
72
+ * @param String $web_id
73
+ *
74
+ * @return boolean
75
+ */
76
+ public static function is_configured( $web_id ) {
77
+ return $web_id !== self::GA_DEFAULT_WEB_ID;
78
+ }
79
+
80
+ /**
81
+ * Prepare an array of current site's user roles
82
+ *
83
+ * return array
84
+ */
85
+ public static function get_user_roles() {
86
+ global $wp_roles;
87
+ if ( ! isset( $wp_roles ) ) {
88
+ $wp_roles = new WP_Roles();
89
+ }
90
+
91
+ return $wp_roles->get_names();
92
+ }
93
+
94
+ /**
95
+ * Prepare a role ID.
96
+ *
97
+ * The role ID is derived from the role's name and will be used
98
+ * in its setting name in the additional settings.
99
+ *
100
+ * @param string $role_name Role name
101
+ *
102
+ * @return string
103
+ */
104
+ public static function prepare_role_id( $role_name ) {
105
+ return self::ROLE_ID_PREFIX . strtolower( preg_replace( '/[\W]/', '-', before_last_bar( $role_name ) ) );
106
+ }
107
+
108
+ /**
109
+ * Prepares role id.
110
+ *
111
+ * @param $v
112
+ * @param $k
113
+ */
114
+ public static function prepare_role( &$v, $k ) {
115
+ $v = self::prepare_role_id( $v );
116
+ }
117
+
118
+ /**
119
+ * Checks whether user role is excluded from adding UA code.
120
+ *
121
+ * @return boolean
122
+ */
123
+ public static function can_add_ga_code() {
124
+ $current_user = wp_get_current_user();
125
+ $user_roles = ! empty( $current_user->roles ) ? $current_user->roles : array();
126
+ $exclude_roles = json_decode( get_option( Ga_Admin::GA_EXCLUDE_ROLES_OPTION_NAME ), true );
127
+
128
+ array_walk( $user_roles, 'Ga_Helper::prepare_role' );
129
+
130
+ $return = true;
131
+ foreach ( $user_roles as $role ) {
132
+ if ( ! empty( $exclude_roles[ $role ] ) ) {
133
+ $return = false;
134
+ break;
135
+ }
136
+ }
137
+
138
+ return $return;
139
+ }
140
+
141
+ /**
142
+ * Adds ga dashboard widget HTML code for a WordPress
143
+ * Dashboard widget hook.
144
+ */
145
+ public static function add_ga_dashboard_widget() {
146
+ echo self::get_ga_dashboard_widget();
147
+
148
+ Ga_Admin::display_api_errors();
149
+ }
150
+
151
+ /**
152
+ * Generates dashboard widget HTML code.
153
+ *
154
+ * @param string $date_range Google Analytics specific date range string.
155
+ * @param boolean $text_mode
156
+ * @param boolean $ajax
157
+ *
158
+ * @return null | string HTML dashboard widget code.
159
+ */
160
+ public static function get_ga_dashboard_widget( $date_range = null, $text_mode = false, $ajax = false ) {
161
+ if ( empty( $date_range ) ) {
162
+ $date_range = '30daysAgo';
163
+ }
164
+
165
+ // Get chart and boxes data
166
+ $data = self::get_dashboard_widget_data( $date_range );
167
+
168
+ if ( $text_mode ) {
169
+ return self::get_chart_page( 'ga_dashboard_widget' . ( $ajax ? "_ajax" : "" ), array(
170
+ 'chart' => $data['chart'],
171
+ 'boxes' => $data['boxes']
172
+ ) );
173
+ } else {
174
+ echo self::get_chart_page( 'ga_dashboard_widget' . ( $ajax ? "_ajax" : "" ), array(
175
+ 'chart' => $data['chart'],
176
+ 'boxes' => $data['boxes'],
177
+ 'more_details_url' => admin_url( self::GA_STATISTICS_PAGE_URL )
178
+ ) );
179
+ }
180
+
181
+ return null;
182
+ }
183
+
184
+ /**
185
+ * Generates JSON data string for AJAX calls.
186
+ *
187
+ * @param string $date_range
188
+ * @param string $metric
189
+ * @param boolean $text_mode
190
+ * @param boolean $ajax
191
+ *
192
+ * @return string|false Returns JSON data string
193
+ */
194
+ public static function get_ga_dashboard_widget_data_json(
195
+ $date_range = null,
196
+ $metric = null,
197
+ $text_mode = false,
198
+ $ajax = false
199
+ ) {
200
+ if ( empty( $date_range ) ) {
201
+ $date_range = '30daysAgo';
202
+ }
203
+
204
+ if ( empty( $metric ) ) {
205
+ $metric = 'pageviews';
206
+ }
207
+
208
+ $data = self::get_dashboard_widget_data( $date_range, $metric );
209
+
210
+ return wp_json_encode( $data );
211
+ }
212
+
213
+ /**
214
+ * Gets dashboard widget data.
215
+ *
216
+ * @param date_range
217
+ * @param metric
218
+ *
219
+ * @return array Return chart and boxes data
220
+ */
221
+ private static function get_dashboard_widget_data( $date_range, $metric = null ) {
222
+ $selected = self::get_selected_account_data( true );
223
+ if ( self::is_authorized() && self::is_account_selected() ) {
224
+ $query_params = Ga_Stats::get_query( 'main_chart', $selected['view_id'], $date_range, $metric );
225
+ $stats_data = Ga_Admin::api_client()->call( 'ga_api_data', array(
226
+
227
+ $query_params
228
+ ) );
229
+
230
+ $boxes_query = Ga_Stats::get_query( 'dashboard_boxes', $selected['view_id'], $date_range );
231
+ $boxes_data = Ga_Admin::api_client()->call( 'ga_api_data', array(
232
+
233
+ $boxes_query
234
+ ) );
235
+ }
236
+ $chart = ! empty( $stats_data ) ? Ga_Stats::get_dashboard_chart( $stats_data->getData() ) : array();
237
+ $boxes = ! empty( $boxes_data ) ? Ga_Stats::get_dashboard_boxes_data( $boxes_data->getData() ) : array();
238
+
239
+ return array(
240
+
241
+ 'chart' => $chart,
242
+ 'boxes' => $boxes
243
+ );
244
+ }
245
+
246
+ public static function is_account_selected() {
247
+ return self::get_selected_account_data();
248
+ }
249
+
250
+ /**
251
+ * Returns HTML code of the chart page or a notice.
252
+ *
253
+ * @param chart
254
+ *
255
+ * @return string Returns HTML code
256
+ */
257
+ public static function get_chart_page( $view, $params ) {
258
+
259
+ $message = sprintf( __( 'Statistics can only be seen after you authenticate with your Google account on the <a href="%s">Settings page</a>.' ),
260
+ admin_url( self::GA_SETTINGS_PAGE_URL ) );
261
+
262
+ if ( self::is_authorized() && ! self::is_code_manually_enabled() ) {
263
+ if ( self::is_account_selected() ) {
264
+ if ( $params ) {
265
+ return Ga_View::load( $view, $params, true );
266
+ } else {
267
+ return self::ga_oauth_notice( sprintf( 'Please configure your <a href="%s">Google Analytics settings</a>.',
268
+ admin_url( self::GA_SETTINGS_PAGE_URL ) ) );
269
+ }
270
+ } else {
271
+ return self::ga_oauth_notice( $message );
272
+ }
273
+ } else {
274
+ return self::ga_oauth_notice( $message );
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Checks whether users is authorized with Google.
280
+ *
281
+ * @return boolean
282
+ */
283
+ public static function is_authorized() {
284
+ return Ga_Admin::api_client()->get_instance()->is_authorized();
285
+ }
286
+
287
+ /**
288
+ * Wrapper for WordPress method get_option
289
+ *
290
+ * @param string $name Option name
291
+ *
292
+ * @return NULL|mixed|boolean
293
+ */
294
+ public static function get_option( $name ) {
295
+ $opt = get_option( $name );
296
+
297
+ return ! empty( $opt ) ? $opt : null;
298
+ }
299
+
300
+ /**
301
+ * Wrapper for WordPress method update_option
302
+ *
303
+ * @param string $name
304
+ * @param mixed $value
305
+ *
306
+ * @return NULL|boolean
307
+ */
308
+ public static function update_option( $name, $value ) {
309
+ $opt = update_option( $name, $value );
310
+
311
+ return ! empty( $opt ) ? $opt : null;
312
+ }
313
+
314
+ /**
315
+ * Loads ga notice HTML code with given message included.
316
+ *
317
+ * @param string $message
318
+ * $param bool $cannot_activate Whether the plugin cannot be activated
319
+ *
320
+ * @return string
321
+ */
322
+ public static function ga_oauth_notice( $message ) {
323
+ return Ga_View::load( 'ga_oauth_notice', array(
324
+ 'msg' => $message
325
+ ), true );
326
+ }
327
+
328
+ /**
329
+ * Displays notice following the WP style.
330
+ *
331
+ * @param $message
332
+ * @param string $type
333
+ *
334
+ * @return string
335
+ */
336
+ public static function ga_wp_notice( $message, $type = '' ) {
337
+ return Ga_View::load( 'ga_wp_notice', array(
338
+ 'type' => empty( $type ) ? Ga_Admin::NOTICE_WARNING : $type,
339
+ 'msg' => $message
340
+ ), true );
341
+ }
342
+
343
+ /**
344
+ * Gets data according to selected GA account.
345
+ *
346
+ * @param boolean $assoc
347
+ *
348
+ * @return mixed
349
+ */
350
+ public static function get_selected_account_data( $assoc = false ) {
351
+ $data = json_decode( self::get_option( Ga_Admin::GA_SELECTED_ACCOUNT ) );
352
+ $data = ( ! empty( $data ) && count( $data ) == 3 ) ? $data : false;
353
+
354
+ if ( $data ) {
355
+ if ( $assoc ) {
356
+ return array(
357
+
358
+ 'account_id' => $data[0],
359
+ 'web_property_id' => $data[1],
360
+ 'view_id' => $data[2]
361
+ );
362
+ } else {
363
+ return $data;
364
+ }
365
+ }
366
+
367
+ return false;
368
+ }
369
+
370
+ /**
371
+ * Chekcs whether option for manually UA-code
372
+ * @return NULL|mixed|boolean
373
+ */
374
+ public static function is_code_manually_enabled() {
375
+ return Ga_Helper::get_option( Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME );
376
+ }
377
+
378
+ /**
379
+ * Adds percent sign to the given text.
380
+ *
381
+ * @param $text
382
+ *
383
+ * @return string
384
+ */
385
+ public static function format_percent( $text ) {
386
+ $text = self::add_plus( $text );
387
+
388
+ return $text . '%';
389
+ }
390
+
391
+ /**
392
+ * Adds plus sign before number.
393
+ *
394
+ * @param $number
395
+ *
396
+ * @return string
397
+ */
398
+ public static function add_plus( $number ) {
399
+ if ( $number > 0 ) {
400
+ return '+' . $number;
401
+ }
402
+
403
+ return $number;
404
+ }
405
+
406
+ /**
407
+ * Check whether current user has administrator privileges.
408
+ *
409
+ * @return bool
410
+ */
411
+ public static function is_administrator() {
412
+ if ( current_user_can( 'administrator' ) ) {
413
+ return true;
414
+ }
415
+
416
+ return false;
417
+ }
418
+
419
+ public static function is_wp_version_valid() {
420
+ $wp_version = get_bloginfo( 'version' );
421
+
422
+ return version_compare( $wp_version, Ga_Admin::MIN_WP_VERSION, 'ge' );
423
+ }
424
+
425
+ /**
426
+ * Check if terms are accepted
427
+ *
428
+ * @return bool
429
+ */
430
+ public static function are_terms_accepted() {
431
+ return self::get_option( Ga_Admin::GA_SHARETHIS_TERMS_OPTION_NAME );
432
+ }
433
+
434
+ /**
435
+ * Check if sharethis scripts enabled
436
+ *
437
+ * @return bool
438
+ */
439
+ public static function is_sharethis_included() {
440
+ return GA_SHARETHIS_SCRIPTS_INCLUDED;
441
+ }
442
+
443
+ /**
444
+ * @return mixed
445
+ */
446
+ public static function is_php_version_valid() {
447
+ $p = '#(\.0+)+($|-)#';
448
+ $ver1 = preg_replace( $p, '', phpversion() );
449
+ $ver2 = preg_replace( $p, '', self::PHP_VERSION_REQUIRED );
450
+ $operator = 'ge';
451
+ $compare = isset( $operator ) ?
452
+ version_compare( $ver1, $ver2, $operator ) :
453
+ version_compare( $ver1, $ver2 );
454
+
455
+ return $compare;
456
+ }
457
+
458
+ public static function get_current_url() {
459
+ return $_SERVER['REQUEST_URI'];
460
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  }
class/Ga_Stats.php CHANGED
@@ -451,8 +451,8 @@ class Ga_Stats {
451
  public static function get_chart( $response_data ) {
452
  $chart_data = array();
453
  if ( ! empty( $response_data ) ) {
454
- $data = ( !empty( $response_data['reports'] ) && !empty( $response_data['reports'][0] ) && !empty( $response_data['reports'][0]['data'] ) ) ? $response_data['reports'][0]['data'] : array();
455
- $rows = ( !empty( $data['rows'] ) ) ? $data['rows'] : array();
456
  if ( ! empty( $rows ) ) {
457
  foreach ( $rows as $key => $row ) {
458
  if ( $key < 7 ) {
@@ -461,7 +461,7 @@ class Ga_Stats {
461
  } else {
462
  $chart_data[ $key - 7 ]['day'] = date( 'M j', strtotime( $row['dimensions'][0] ) );
463
  $chart_data[ $key - 7 ]['current'] = ! empty( $row['metrics'][0]['values'][0] ) ? $row['metrics'][0]['values'][0] : 0;
464
- $chart_data[ 'date'] = strtotime( $row['dimensions'][0] );
465
  }
466
  }
467
  }
@@ -480,8 +480,8 @@ class Ga_Stats {
480
  public static function get_dashboard_chart( $response_data ) {
481
  $chart_data = array();
482
  if ( ! empty( $response_data ) ) {
483
- $data = ( !empty( $response_data['reports'] ) && !empty( $response_data['reports'][0] ) && !empty( $response_data['reports'][0]['data'] ) ) ? $response_data['reports'][0]['data'] : array();
484
- $rows = ( !empty( $data['rows'] ) ) ? $data['rows'] : array();
485
  if ( ! empty( $rows ) ) {
486
  foreach ( $rows as $row ) {
487
  $chart_data[] = array(
@@ -553,22 +553,30 @@ class Ga_Stats {
553
  * @return array boxes data
554
  */
555
  public static function prepare_boxes( $boxes_data ) {
556
- $boxes_data['Users']['diff'] = ( $boxes_data['Users']['previous'] > 0 ) ? round( ( $boxes_data['Users']['current'] - $boxes_data['Users']['previous'] ) / $boxes_data['Users']['previous'] * 100, 2 ) : 100;
557
- $boxes_data['Pageviews']['diff'] = ( $boxes_data['Pageviews']['previous'] > 0 ) ? round( ( $boxes_data['Pageviews']['current'] - $boxes_data['Pageviews']['previous'] ) / $boxes_data['Pageviews']['previous'] * 100, 2 ) : 100;
558
- $boxes_data['PageviewsPerSession']['diff'] = ( $boxes_data['PageviewsPerSession']['previous'] > 0 ) ? round( ( $boxes_data['PageviewsPerSession']['current'] - $boxes_data['PageviewsPerSession']['previous'] ) / $boxes_data['PageviewsPerSession']['previous'] * 100, 2 ) : 100;
559
- $boxes_data['BounceRate']['diff'] = ( $boxes_data['BounceRate']['previous'] > 0 ) ? round( ( $boxes_data['BounceRate']['current'] - $boxes_data['BounceRate']['previous'] ) / $boxes_data['BounceRate']['previous'] * 100, 2 ) : 100;
560
- $boxes_data['Users']['diff'] = ( $boxes_data['Users']['previous'] == 0 && $boxes_data['Users']['current'] == 0) ? 0 : $boxes_data['Users']['diff'];
561
- $boxes_data['Pageviews']['diff'] = ( $boxes_data['Pageviews']['previous'] == 0 && $boxes_data['Pageviews']['current'] == 0) ? 0 : $boxes_data['Pageviews']['diff'];
562
- $boxes_data['PageviewsPerSession']['diff'] = ( $boxes_data['PageviewsPerSession']['previous'] == 0 && $boxes_data['PageviewsPerSession']['current'] == 0) ? 0 : $boxes_data['PageviewsPerSession']['diff'];
563
- $boxes_data['BounceRate']['diff'] = ( $boxes_data['BounceRate']['previous'] == 0 && $boxes_data['BounceRate']['current'] == 0) ? 0 : $boxes_data['BounceRate']['diff'];
 
 
 
 
564
  $boxes_data['Users']['label'] = 'Users';
565
  $boxes_data['Pageviews']['label'] = 'Pageviews';
566
  $boxes_data['PageviewsPerSession']['label'] = 'Pages / Session';
567
  $boxes_data['BounceRate']['label'] = 'Bounce Rate';
568
  $boxes_data['Users']['comparison'] = $boxes_data['Users']['current'] . ' vs ' . $boxes_data['Users']['previous'];
569
  $boxes_data['Pageviews']['comparison'] = $boxes_data['Pageviews']['current'] . ' vs ' . $boxes_data['Pageviews']['previous'];
570
- $boxes_data['PageviewsPerSession']['comparison'] = self::number_format_clean( $boxes_data['PageviewsPerSession']['current'], 2, '.', ',' ) . ' vs ' . self::number_format_clean( $boxes_data['PageviewsPerSession']['previous'], 2, '.', ',' );
571
- $boxes_data['BounceRate']['comparison'] = self::number_format_clean( $boxes_data['BounceRate']['current'], 2, '.', ',' ) . '% vs ' . self::number_format_clean( $boxes_data['BounceRate']['previous'], 2, '.', ',' ) . '%';
 
 
 
 
572
  $boxes_data['Users']['color'] = ( $boxes_data['Users']['diff'] > 0 ) ? 'green' : 'red';
573
  $boxes_data['Pageviews']['color'] = ( $boxes_data['Pageviews']['diff'] > 0 ) ? 'green' : 'red';
574
  $boxes_data['PageviewsPerSession']['color'] = ( $boxes_data['PageviewsPerSession']['diff'] > 0 ) ? 'green' : 'red';
@@ -576,7 +584,7 @@ class Ga_Stats {
576
  $boxes_data['Users']['color'] = ( $boxes_data['Users']['diff'] != 0 ) ? $boxes_data['Users']['color'] : 'black';
577
  $boxes_data['Pageviews']['color'] = ( $boxes_data['Pageviews']['diff'] != 0 ) ? $boxes_data['Pageviews']['color'] : 'black';
578
  $boxes_data['PageviewsPerSession']['color'] = ( $boxes_data['PageviewsPerSession']['diff'] != 0 ) ? $boxes_data['PageviewsPerSession']['color'] : 'black';
579
- $boxes_data['BounceRate']['color'] = ( $boxes_data['BounceRate']['diff'] != 0 ) ? $boxes_data['BounceRate']['color'] : 'black';
580
 
581
  return $boxes_data;
582
  }
@@ -638,10 +646,12 @@ class Ga_Stats {
638
  foreach ( $row as $key => $value ) {
639
  if ( $key == 'dimensions' ) {
640
  $sources['rows'][ $i ]['name'] = $value[0];
641
- $sources['rows'][ $i ]['url'] = 'http://' . substr( $value[0], 0, strpos( $value[0], '/' ) - 1 );
 
642
  } elseif ( $key == 'metrics' ) {
643
  $sources['rows'][ $i ]['number'] = $value[0]['values'][0];
644
- $sources['rows'][ $i ]['percent'] = ( ! empty( $totalCount ) ) ? round( $value[0]['values'][0] / $totalCount * 100, 2 ) : 0;
 
645
  $sources['sum'] += $value[0]['values'][0];
646
  }
647
  }
@@ -672,15 +682,15 @@ class Ga_Stats {
672
  $report_data = self::get_report_data( $report );
673
  $totals = self::get_totals( $report_data );
674
  $boxes_data = array();
675
- $boxes_data['Sessions'] = array(
676
  'label' => 'Visits',
677
  'value' => $totals[0]['values'][0],
678
  );
679
- $boxes_data['Pageviews'] = array(
680
  'label' => 'Pageviews',
681
  'value' => $totals[0]['values'][1],
682
  );
683
- $boxes_data['pageviewsPerSession'] = array(
684
  'label' => 'Pages / Visit',
685
  'value' => self::number_format_clean( $totals[0]['values'][2], 2, '.', ',' ),
686
  );
@@ -688,9 +698,9 @@ class Ga_Stats {
688
  'label' => 'Bounce Rate',
689
  'value' => self::number_format_clean( $totals[0]['values'][3], 2, '.', ',' ) . '%',
690
  );
691
- $boxes_data['avgTimeOnPage'] = array(
692
  'label' => 'Avg. Time on Site',
693
- 'value' => gmdate("H:i:s", $totals[0]['values'][4]),
694
  );
695
  $boxes_data['percentNewSessions'] = array(
696
  'label' => '% of New Visits',
451
  public static function get_chart( $response_data ) {
452
  $chart_data = array();
453
  if ( ! empty( $response_data ) ) {
454
+ $data = ( ! empty( $response_data['reports'] ) && ! empty( $response_data['reports'][0] ) && ! empty( $response_data['reports'][0]['data'] ) ) ? $response_data['reports'][0]['data'] : array();
455
+ $rows = ( ! empty( $data['rows'] ) ) ? $data['rows'] : array();
456
  if ( ! empty( $rows ) ) {
457
  foreach ( $rows as $key => $row ) {
458
  if ( $key < 7 ) {
461
  } else {
462
  $chart_data[ $key - 7 ]['day'] = date( 'M j', strtotime( $row['dimensions'][0] ) );
463
  $chart_data[ $key - 7 ]['current'] = ! empty( $row['metrics'][0]['values'][0] ) ? $row['metrics'][0]['values'][0] : 0;
464
+ $chart_data['date'] = strtotime( $row['dimensions'][0] );
465
  }
466
  }
467
  }
480
  public static function get_dashboard_chart( $response_data ) {
481
  $chart_data = array();
482
  if ( ! empty( $response_data ) ) {
483
+ $data = ( ! empty( $response_data['reports'] ) && ! empty( $response_data['reports'][0] ) && ! empty( $response_data['reports'][0]['data'] ) ) ? $response_data['reports'][0]['data'] : array();
484
+ $rows = ( ! empty( $data['rows'] ) ) ? $data['rows'] : array();
485
  if ( ! empty( $rows ) ) {
486
  foreach ( $rows as $row ) {
487
  $chart_data[] = array(
553
  * @return array boxes data
554
  */
555
  public static function prepare_boxes( $boxes_data ) {
556
+ $boxes_data['Users']['diff'] = ( $boxes_data['Users']['previous'] > 0 ) ? round( ( $boxes_data['Users']['current'] - $boxes_data['Users']['previous'] ) / $boxes_data['Users']['previous'] * 100,
557
+ 2 ) : 100;
558
+ $boxes_data['Pageviews']['diff'] = ( $boxes_data['Pageviews']['previous'] > 0 ) ? round( ( $boxes_data['Pageviews']['current'] - $boxes_data['Pageviews']['previous'] ) / $boxes_data['Pageviews']['previous'] * 100,
559
+ 2 ) : 100;
560
+ $boxes_data['PageviewsPerSession']['diff'] = ( $boxes_data['PageviewsPerSession']['previous'] > 0 ) ? round( ( $boxes_data['PageviewsPerSession']['current'] - $boxes_data['PageviewsPerSession']['previous'] ) / $boxes_data['PageviewsPerSession']['previous'] * 100,
561
+ 2 ) : 100;
562
+ $boxes_data['BounceRate']['diff'] = ( $boxes_data['BounceRate']['previous'] > 0 ) ? round( ( $boxes_data['BounceRate']['current'] - $boxes_data['BounceRate']['previous'] ) / $boxes_data['BounceRate']['previous'] * 100,
563
+ 2 ) : 100;
564
+ $boxes_data['Users']['diff'] = ( $boxes_data['Users']['previous'] == 0 && $boxes_data['Users']['current'] == 0 ) ? 0 : $boxes_data['Users']['diff'];
565
+ $boxes_data['Pageviews']['diff'] = ( $boxes_data['Pageviews']['previous'] == 0 && $boxes_data['Pageviews']['current'] == 0 ) ? 0 : $boxes_data['Pageviews']['diff'];
566
+ $boxes_data['PageviewsPerSession']['diff'] = ( $boxes_data['PageviewsPerSession']['previous'] == 0 && $boxes_data['PageviewsPerSession']['current'] == 0 ) ? 0 : $boxes_data['PageviewsPerSession']['diff'];
567
+ $boxes_data['BounceRate']['diff'] = ( $boxes_data['BounceRate']['previous'] == 0 && $boxes_data['BounceRate']['current'] == 0 ) ? 0 : $boxes_data['BounceRate']['diff'];
568
  $boxes_data['Users']['label'] = 'Users';
569
  $boxes_data['Pageviews']['label'] = 'Pageviews';
570
  $boxes_data['PageviewsPerSession']['label'] = 'Pages / Session';
571
  $boxes_data['BounceRate']['label'] = 'Bounce Rate';
572
  $boxes_data['Users']['comparison'] = $boxes_data['Users']['current'] . ' vs ' . $boxes_data['Users']['previous'];
573
  $boxes_data['Pageviews']['comparison'] = $boxes_data['Pageviews']['current'] . ' vs ' . $boxes_data['Pageviews']['previous'];
574
+ $boxes_data['PageviewsPerSession']['comparison'] = self::number_format_clean( $boxes_data['PageviewsPerSession']['current'],
575
+ 2, '.', ',' ) . ' vs ' . self::number_format_clean( $boxes_data['PageviewsPerSession']['previous'], 2,
576
+ '.', ',' );
577
+ $boxes_data['BounceRate']['comparison'] = self::number_format_clean( $boxes_data['BounceRate']['current'],
578
+ 2, '.', ',' ) . '% vs ' . self::number_format_clean( $boxes_data['BounceRate']['previous'], 2, '.',
579
+ ',' ) . '%';
580
  $boxes_data['Users']['color'] = ( $boxes_data['Users']['diff'] > 0 ) ? 'green' : 'red';
581
  $boxes_data['Pageviews']['color'] = ( $boxes_data['Pageviews']['diff'] > 0 ) ? 'green' : 'red';
582
  $boxes_data['PageviewsPerSession']['color'] = ( $boxes_data['PageviewsPerSession']['diff'] > 0 ) ? 'green' : 'red';
584
  $boxes_data['Users']['color'] = ( $boxes_data['Users']['diff'] != 0 ) ? $boxes_data['Users']['color'] : 'black';
585
  $boxes_data['Pageviews']['color'] = ( $boxes_data['Pageviews']['diff'] != 0 ) ? $boxes_data['Pageviews']['color'] : 'black';
586
  $boxes_data['PageviewsPerSession']['color'] = ( $boxes_data['PageviewsPerSession']['diff'] != 0 ) ? $boxes_data['PageviewsPerSession']['color'] : 'black';
587
+ $boxes_data['BounceRate']['color'] = ( $boxes_data['BounceRate']['diff'] != 0 ) ? $boxes_data['BounceRate']['color'] : 'black';
588
 
589
  return $boxes_data;
590
  }
646
  foreach ( $row as $key => $value ) {
647
  if ( $key == 'dimensions' ) {
648
  $sources['rows'][ $i ]['name'] = $value[0];
649
+ $sources['rows'][ $i ]['url'] = 'http://' . substr( $value[0], 0,
650
+ strpos( $value[0], '/' ) - 1 );
651
  } elseif ( $key == 'metrics' ) {
652
  $sources['rows'][ $i ]['number'] = $value[0]['values'][0];
653
+ $sources['rows'][ $i ]['percent'] = ( ! empty( $totalCount ) ) ? round( $value[0]['values'][0] / $totalCount * 100,
654
+ 2 ) : 0;
655
  $sources['sum'] += $value[0]['values'][0];
656
  }
657
  }
682
  $report_data = self::get_report_data( $report );
683
  $totals = self::get_totals( $report_data );
684
  $boxes_data = array();
685
+ $boxes_data['Sessions'] = array(
686
  'label' => 'Visits',
687
  'value' => $totals[0]['values'][0],
688
  );
689
+ $boxes_data['Pageviews'] = array(
690
  'label' => 'Pageviews',
691
  'value' => $totals[0]['values'][1],
692
  );
693
+ $boxes_data['pageviewsPerSession'] = array(
694
  'label' => 'Pages / Visit',
695
  'value' => self::number_format_clean( $totals[0]['values'][2], 2, '.', ',' ),
696
  );
698
  'label' => 'Bounce Rate',
699
  'value' => self::number_format_clean( $totals[0]['values'][3], 2, '.', ',' ) . '%',
700
  );
701
+ $boxes_data['avgTimeOnPage'] = array(
702
  'label' => 'Avg. Time on Site',
703
+ 'value' => gmdate( "H:i:s", $totals[0]['values'][4] ),
704
  );
705
  $boxes_data['percentNewSessions'] = array(
706
  'label' => '% of New Visits',
css/googleanalytics.css CHANGED
@@ -132,8 +132,8 @@ label.ga_checkbox_label {
132
  .ga-chart {
133
  }
134
 
135
- .label-grey{
136
- color:#ccc;
137
  }
138
 
139
  .ga-tooltip {
@@ -162,11 +162,13 @@ label.ga_checkbox_label {
162
  width: auto;
163
  z-index: 1;
164
  }
165
- .ga-tt-abs{
 
166
  display: inline-block;
167
  position: absolute;
168
  margin-top: 0px;
169
  }
 
170
  .ga-tooltip:hover .ga-tooltiptext {
171
  visibility: visible;
172
  }
132
  .ga-chart {
133
  }
134
 
135
+ .label-grey {
136
+ color: #ccc;
137
  }
138
 
139
  .ga-tooltip {
162
  width: auto;
163
  z-index: 1;
164
  }
165
+
166
+ .ga-tt-abs {
167
  display: inline-block;
168
  position: absolute;
169
  margin-top: 0px;
170
  }
171
+
172
  .ga-tooltip:hover .ga-tooltiptext {
173
  visibility: visible;
174
  }
googleanalytics.php CHANGED
@@ -4,7 +4,7 @@
4
  * Plugin Name: Google Analytics
5
  * Plugin URI: http://wordpress.org/extend/plugins/googleanalytics/
6
  * Description: Use Google Analytics on your Wordpress site without touching any code, and view visitor reports right in your Wordpress admin dashboard!
7
- * Version: 2.0.2
8
  * Author: ShareThis
9
  * Author URI: http://sharethis.com
10
  */
@@ -35,7 +35,7 @@ if ( ! defined( 'GA_MAIN_FILE_PATH' ) ) {
35
  if ( ! defined( 'GA_SHARETHIS_SCRIPTS_INCLUDED' ) ) {
36
  define( 'GA_SHARETHIS_SCRIPTS_INCLUDED', 0 );
37
  }
38
- define( 'GOOGLEANALYTICS_VERSION', '2.0.2' );
39
  include_once GA_PLUGIN_DIR . '/overwrite/ga_overwrite.php';
40
  include_once GA_PLUGIN_DIR . '/class/Ga_Autoloader.php';
41
  Ga_Autoloader::register();
4
  * Plugin Name: Google Analytics
5
  * Plugin URI: http://wordpress.org/extend/plugins/googleanalytics/
6
  * Description: Use Google Analytics on your Wordpress site without touching any code, and view visitor reports right in your Wordpress admin dashboard!
7
+ * Version: 2.0.3
8
  * Author: ShareThis
9
  * Author URI: http://sharethis.com
10
  */
35
  if ( ! defined( 'GA_SHARETHIS_SCRIPTS_INCLUDED' ) ) {
36
  define( 'GA_SHARETHIS_SCRIPTS_INCLUDED', 0 );
37
  }
38
+ define( 'GOOGLEANALYTICS_VERSION', '2.0.3' );
39
  include_once GA_PLUGIN_DIR . '/overwrite/ga_overwrite.php';
40
  include_once GA_PLUGIN_DIR . '/class/Ga_Autoloader.php';
41
  Ga_Autoloader::register();
js/googleanalytics_page.js CHANGED
@@ -37,10 +37,10 @@ const GA_FORM_ID = "ga_form";
37
  click: function (selector, callback) {
38
  $(selector).live('click', callback);
39
  },
40
- codeManuallyCallback: function ( terms_accepted ) {
41
  const button_disabled = $('#ga_authorize_with_google_button').attr('disabled');
42
  const selector_disabled = $('#ga_account_selector').attr('disabled');
43
- if ( terms_accepted ) {
44
  if (button_disabled) {
45
  $('#ga_authorize_with_google_button').removeAttr('disabled').next().hide();
46
  } else {
37
  click: function (selector, callback) {
38
  $(selector).live('click', callback);
39
  },
40
+ codeManuallyCallback: function (terms_accepted) {
41
  const button_disabled = $('#ga_authorize_with_google_button').attr('disabled');
42
  const selector_disabled = $('#ga_account_selector').attr('disabled');
43
+ if (terms_accepted) {
44
  if (button_disabled) {
45
  $('#ga_authorize_with_google_button').removeAttr('disabled').next().hide();
46
  } else {
lib/Ga_Lib_Api_Client.php CHANGED
@@ -37,6 +37,12 @@ class Ga_Lib_Api_Client {
37
  */
38
  private $token;
39
 
 
 
 
 
 
 
40
  /**
41
  * Returns API client instance.
42
  *
@@ -51,6 +57,14 @@ class Ga_Lib_Api_Client {
51
  return $instance;
52
  }
53
 
 
 
 
 
 
 
 
 
54
  /**
55
  * Calls api methods.
56
  *
@@ -73,14 +87,25 @@ class Ga_Lib_Api_Client {
73
  return call_user_func( $callback );
74
  }
75
  } else {
76
- throw new Exception( 'Unknown method: ' . $callback );
77
  }
78
- } catch ( Exception $e ) {
79
- // @todo: need to add exception
80
- echo $e->getMessage();
 
81
  }
82
  }
83
 
 
 
 
 
 
 
 
 
 
 
84
  /**
85
  * Sets access token.
86
  *
@@ -138,6 +163,19 @@ class Ga_Lib_Api_Client {
138
  return new Ga_Lib_Api_Response( $response );
139
  }
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  /**
142
  * Get list of the analytics accounts.
143
  *
@@ -173,26 +211,53 @@ class Ga_Lib_Api_Client {
173
  * @param Ga_Lib_Api_Request $request
174
  *
175
  * @return Ga_Lib_Api_Request Returns response object
 
176
  */
177
  private function sign( Ga_Lib_Api_Request $request ) {
 
 
 
 
 
 
 
 
178
  // Add the OAuth2 header to the request
179
  $request->set_request_headers( array( 'Authorization: Bearer ' . $this->token['access_token'] ) );
180
 
181
  return $request;
182
  }
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  /**
185
  * Checks if Access Token is valid.
186
  *
187
  * @return bool
188
  */
189
  public function is_authorized() {
190
- $authorized = true;
191
- if ( $this->is_access_token_expired() ) {
192
- $authorized = false;
 
 
 
193
  }
194
 
195
- return $authorized;
196
  }
197
 
198
  /**
@@ -203,10 +268,25 @@ class Ga_Lib_Api_Client {
203
  if ( null == $this->token ) {
204
  return true;
205
  }
206
-
 
 
207
  // Check if the token is expired in the next 30 seconds.
208
  $expired = ( $this->token['created'] + ( $this->token['expires_in'] - 30 ) ) < time();
209
 
210
  return $expired;
211
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  }
37
  */
38
  private $token;
39
 
40
+ /**
41
+ * Keeps error messages.
42
+ * @var array
43
+ */
44
+ private $errors = array();
45
+
46
  /**
47
  * Returns API client instance.
48
  *
57
  return $instance;
58
  }
59
 
60
+ /**
61
+ * Returns errors array.
62
+ * @return array
63
+ */
64
+ public function get_errors() {
65
+ return $this->errors;
66
+ }
67
+
68
  /**
69
  * Calls api methods.
70
  *
87
  return call_user_func( $callback );
88
  }
89
  } else {
90
+ throw new Ga_Lib_Api_Client_Exception( 'Unknown method: ' . $callback );
91
  }
92
+ } catch ( Ga_Lib_Api_Client_Exception $e ) {
93
+ $this->add_error( $e );
94
+ } catch ( Ga_Lib_Api_Request_Exception $e ) {
95
+ $this->add_error( $e );
96
  }
97
  }
98
 
99
+ /**
100
+ * Prepares error data.
101
+ *
102
+ * @param Exception $e
103
+ *
104
+ */
105
+ private function add_error( Exception $e ) {
106
+ $this->errors[ $e->getCode() ] = array( 'class' => get_class( $e ), 'message' => $e->getMessage() );
107
+ }
108
+
109
  /**
110
  * Sets access token.
111
  *
163
  return new Ga_Lib_Api_Response( $response );
164
  }
165
 
166
+ private function ga_auth_refresh_access_token( $refresh_token ) {
167
+ $request = array(
168
+ 'refresh_token' => $refresh_token,
169
+ 'grant_type' => 'refresh_token',
170
+ 'client_id' => $this->config['client_id'],
171
+ 'client_secret' => $this->config['client_secret']
172
+ );
173
+
174
+ $response = Ga_Lib_Api_Request::get_instance()->make_request( self::OAUTH2_TOKEN_ENDPOINT, $request );
175
+
176
+ return new Ga_Lib_Api_Response( $response );
177
+ }
178
+
179
  /**
180
  * Get list of the analytics accounts.
181
  *
211
  * @param Ga_Lib_Api_Request $request
212
  *
213
  * @return Ga_Lib_Api_Request Returns response object
214
+ * @throws Ga_Lib_Api_Client_Exception
215
  */
216
  private function sign( Ga_Lib_Api_Request $request ) {
217
+ if ( empty( $this->token ) ) {
218
+ throw new Ga_Lib_Api_Client_Exception( 'Access Token is not available. Please reauthenticate' );
219
+ }
220
+
221
+ // Check if the token is set to expire in the next 30 seconds
222
+ // (or has already expired).
223
+ $this->check_access_token();
224
+
225
  // Add the OAuth2 header to the request
226
  $request->set_request_headers( array( 'Authorization: Bearer ' . $this->token['access_token'] ) );
227
 
228
  return $request;
229
  }
230
 
231
+ /**
232
+ * Refresh and save refreshed Access Token.
233
+ *
234
+ * @param $refresh_token
235
+ */
236
+ public function refresh_access_token( $refresh_token ) {
237
+ // Request for a new Access Token
238
+ $response = $this->ga_auth_refresh_access_token( $refresh_token );
239
+ Ga_Admin::save_access_token( $response, $refresh_token );
240
+
241
+ // Set new access token
242
+ $token = Ga_Helper::get_option( Ga_Admin::GA_OAUTH_AUTH_TOKEN_OPTION_NAME );
243
+ $this->set_access_token( json_decode( $token, true ) );
244
+ }
245
+
246
  /**
247
  * Checks if Access Token is valid.
248
  *
249
  * @return bool
250
  */
251
  public function is_authorized() {
252
+ if ( ! empty( $this->token ) ) {
253
+ try {
254
+ $this->check_access_token();
255
+ } catch ( Ga_Lib_Api_Client_Exception $e ) {
256
+ $this->add_error( $e );
257
+ }
258
  }
259
 
260
+ return ! empty( $this->token ) && ! $this->is_access_token_expired();
261
  }
262
 
263
  /**
268
  if ( null == $this->token ) {
269
  return true;
270
  }
271
+ if ( ! empty( $this->token['error'] ) ) {
272
+ return true;
273
+ }
274
  // Check if the token is expired in the next 30 seconds.
275
  $expired = ( $this->token['created'] + ( $this->token['expires_in'] - 30 ) ) < time();
276
 
277
  return $expired;
278
  }
279
+
280
+ private function check_access_token() {
281
+ if ( $this->is_access_token_expired() ) {
282
+ if ( empty( $this->token['refresh_token'] ) ) {
283
+ throw new Ga_Lib_Api_Client_Exception( 'Refresh token is not available. Please re-authenticate.' );
284
+ } else {
285
+ $this->refresh_access_token( $this->token['refresh_token'] );
286
+ }
287
+ }
288
+ }
289
+ }
290
+
291
+ class Ga_Lib_Api_Client_Exception extends Exception {
292
  }
lib/Ga_Lib_Api_Request.php CHANGED
@@ -1,131 +1,137 @@
1
  <?php
2
 
3
- class Ga_Lib_Api_Request
4
- {
5
-
6
- const HEADER_CONTENT_TYPE = "application/x-www-form-urlencoded";
7
-
8
- const HEADER_CONTENT_TYPE_JSON = "Content-type: application/json";
9
-
10
- const HEADER_ACCEPT = "Accept: application/json, text/javascript, */*; q=0.01";
11
-
12
- const TIMEOUT = 30;
13
-
14
- const USER_AGENT = 'googleanalytics-wordpress-plugin';
15
-
16
- private $headers = array();
17
-
18
- function __construct()
19
- {
20
- }
21
-
22
- /**
23
- * Returns API client instance.
24
- *
25
- * @return Ga_Lib_Api_Request|null
26
- */
27
- public static function get_instance()
28
- {
29
- static $instance = null;
30
- if ($instance === null) {
31
- $instance = new Ga_Lib_Api_Request();
32
- }
33
-
34
- return $instance;
35
- }
36
-
37
- /**
38
- * Sets request headers.
39
- *
40
- * @param $headers
41
- */
42
- public function set_request_headers($headers)
43
- {
44
- if (is_array($headers)) {
45
- $this->headers = array_merge($this->headers, $headers);
46
- } else {
47
- $this->headers[] = $headers;
48
- }
49
- }
50
-
51
- /**
52
- * Perform HTTP request.
53
- *
54
- * @param string $url URL address
55
- * @param string $rawPostBody
56
- *
57
- * @return string Response
58
- * @throws Exception
59
- */
60
- public function make_request($url, $rawPostBody = null, $json = false)
61
- {
62
- if ( ! function_exists('curl_init')) {
63
- throw new Exception('cURL functions are not available');
64
- }
65
-
66
- // Set default headers
67
- $this->set_request_headers(array(
68
- ($json ? self::HEADER_CONTENT_TYPE_JSON : self::HEADER_CONTENT_TYPE),
69
- self::HEADER_ACCEPT
70
- ));
71
-
72
- $ch = curl_init($url);
73
- $headers = $this->headers;
74
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
75
-
76
- $curl_timeout = self::TIMEOUT;
77
- $php_execution_time = ini_get('max_execution_time');
78
- if ( ! empty($php_execution_time) && is_numeric($php_execution_time)) {
79
- if ($php_execution_time < 36 && $php_execution_time > 9) {
80
- $curl_timeout = $php_execution_time - 5;
81
- } elseif ($php_execution_time < 10) {
82
- $curl_timeout = 5;
83
- }
84
- }
85
-
86
- // Set the proxy configuration. The user can provide this in wp-config.php
87
- if (defined('WP_PROXY_HOST')) {
88
- curl_setopt($ch, CURLOPT_PROXY, WP_PROXY_HOST);
89
- }
90
- if (defined('WP_PROXY_PORT')) {
91
- curl_setopt($ch, CURLOPT_PROXYPORT, WP_PROXY_PORT);
92
- }
93
- if (defined('WP_PROXY_USERNAME')) {
94
- $auth = WP_PROXY_USERNAME;
95
- if (defined('WP_PROXY_PASSWORD')) {
96
- $auth .= ':' . WP_PROXY_PASSWORD;
97
- }
98
- curl_setopt($ch, CURLOPT_PROXYUSERPWD, $auth);
99
- }
100
-
101
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_timeout);
102
- curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
103
- curl_setopt($ch, CURLOPT_HEADER, true);
104
- curl_setopt($ch, CURLINFO_HEADER_OUT, true);
105
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
106
- curl_setopt($ch, CURLOPT_USERAGENT, self::USER_AGENT);
107
-
108
-
109
- // POST body
110
- if ( ! empty($rawPostBody)) {
111
- curl_setopt($ch, CURLOPT_POST, true);
112
- curl_setopt($ch, CURLOPT_POSTFIELDS, ($json ? $rawPostBody : http_build_query($rawPostBody)));
113
- }
114
-
115
- // Execute request
116
- $response = curl_exec($ch);
117
-
118
- if ($error = curl_error($ch)) {
119
- $errno = curl_errno($ch);
120
- curl_close($ch);
121
- throw new Exception($error . ' (' . $errno . ')');
122
- } else {
123
- $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
124
- $header = substr($response, 0, $headerSize);
125
- $body = substr($response, $headerSize, strlen($response));
126
- curl_close($ch);
127
-
128
- return array($header, $body);
129
- }
130
- }
 
 
 
 
 
 
131
  }
1
  <?php
2
 
3
+ class Ga_Lib_Api_Request {
4
+
5
+ const HEADER_CONTENT_TYPE = "application/x-www-form-urlencoded";
6
+
7
+ const HEADER_CONTENT_TYPE_JSON = "Content-type: application/json";
8
+
9
+ const HEADER_ACCEPT = "Accept: application/json, text/javascript, */*; q=0.01";
10
+
11
+ const TIMEOUT = 30;
12
+
13
+ const USER_AGENT = 'googleanalytics-wordpress-plugin';
14
+
15
+ private $headers = array();
16
+
17
+ function __construct() {
18
+ }
19
+
20
+ /**
21
+ * Returns API client instance.
22
+ *
23
+ * @return Ga_Lib_Api_Request|null
24
+ */
25
+ public static function get_instance() {
26
+ static $instance = null;
27
+ if ( $instance === null ) {
28
+ $instance = new Ga_Lib_Api_Request();
29
+ }
30
+
31
+ return $instance;
32
+ }
33
+
34
+ /**
35
+ * Sets request headers.
36
+ *
37
+ * @param $headers
38
+ */
39
+ public function set_request_headers( $headers ) {
40
+ if ( is_array( $headers ) ) {
41
+ $this->headers = array_merge( $this->headers, $headers );
42
+ } else {
43
+ $this->headers[] = $headers;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Perform HTTP request.
49
+ *
50
+ * @param string $url URL address
51
+ * @param string $rawPostBody
52
+ *
53
+ * @return string Response
54
+ * @throws Exception
55
+ */
56
+ public function make_request( $url, $rawPostBody = null, $json = false ) {
57
+ if ( ! function_exists( 'curl_init' ) ) {
58
+ throw new Ga_Lib_Api_Request_Exception( _( 'cURL functions are not available' ) );
59
+ }
60
+
61
+ // Set default headers
62
+ $this->set_request_headers( array(
63
+ ( $json ? self::HEADER_CONTENT_TYPE_JSON : self::HEADER_CONTENT_TYPE ),
64
+ self::HEADER_ACCEPT
65
+ ) );
66
+
67
+ $ch = curl_init( $url );
68
+ $headers = $this->headers;
69
+ curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
70
+
71
+ $curl_timeout = self::TIMEOUT;
72
+ $php_execution_time = ini_get( 'max_execution_time' );
73
+ if ( ! empty( $php_execution_time ) && is_numeric( $php_execution_time ) ) {
74
+ if ( $php_execution_time < 36 && $php_execution_time > 9 ) {
75
+ $curl_timeout = $php_execution_time - 5;
76
+ } elseif ( $php_execution_time < 10 ) {
77
+ $curl_timeout = 5;
78
+ }
79
+ }
80
+
81
+ // Set the proxy configuration. The user can provide this in wp-config.php
82
+ if ( defined( 'WP_PROXY_HOST' ) ) {
83
+ curl_setopt( $ch, CURLOPT_PROXY, WP_PROXY_HOST );
84
+ }
85
+ if ( defined( 'WP_PROXY_PORT' ) ) {
86
+ curl_setopt( $ch, CURLOPT_PROXYPORT, WP_PROXY_PORT );
87
+ }
88
+ if ( defined( 'WP_PROXY_USERNAME' ) ) {
89
+ $auth = WP_PROXY_USERNAME;
90
+ if ( defined( 'WP_PROXY_PASSWORD' ) ) {
91
+ $auth .= ':' . WP_PROXY_PASSWORD;
92
+ }
93
+ curl_setopt( $ch, CURLOPT_PROXYUSERPWD, $auth );
94
+ }
95
+
96
+ curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $curl_timeout );
97
+ curl_setopt( $ch, CURLOPT_TIMEOUT, $curl_timeout );
98
+ curl_setopt( $ch, CURLOPT_HEADER, true );
99
+ curl_setopt( $ch, CURLINFO_HEADER_OUT, true );
100
+ curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
101
+ curl_setopt( $ch, CURLOPT_USERAGENT, self::USER_AGENT );
102
+ if ( defined( 'CURLOPT_IPRESOLVE' ) && defined( 'CURL_IPRESOLVE_V4' ) ) {
103
+ curl_setopt( $ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
104
+ }
105
+
106
+ // POST body
107
+ if ( ! empty( $rawPostBody ) ) {
108
+ curl_setopt( $ch, CURLOPT_POST, true );
109
+ curl_setopt( $ch, CURLOPT_POSTFIELDS, ( $json ? $rawPostBody : http_build_query( $rawPostBody ) ) );
110
+ }
111
+
112
+ // Execute request
113
+ $response = curl_exec( $ch );
114
+
115
+ if ( $error = curl_error( $ch ) ) {
116
+ $errno = curl_errno( $ch );
117
+ curl_close( $ch );
118
+ throw new Ga_Lib_Api_Client_Exception( $error . ' (' . $errno . ')' );
119
+ } else {
120
+ $httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
121
+ $headerSize = curl_getinfo( $ch, CURLINFO_HEADER_SIZE );
122
+ $header = substr( $response, 0, $headerSize );
123
+ $body = substr( $response, $headerSize, strlen( $response ) );
124
+
125
+ if ( preg_match( '/^(4|5)[0-9]{2}/', $httpCode ) ) {
126
+ throw new Ga_Lib_Api_Request_Exception( _( 'There was an error while contacting Google API:' ) . ' ' . ( $httpCode == 404 ? _( 'Requested URL doesn\'t exists: ' . $url ) : $body ) );
127
+ }
128
+
129
+ curl_close( $ch );
130
+
131
+ return array( $header, $body );
132
+ }
133
+ }
134
+ }
135
+
136
+ class Ga_Lib_Api_Request_Exception extends Exception {
137
  }
readme.txt CHANGED
@@ -3,7 +3,7 @@ Contributors: ShareThis
3
  Tags: analytics, dashboard, google, google analytics, google analytics plugin, javascript, marketing, pageviews, statistics, stats, tracking, visits, web stats, widget, analytics dashboard, google analytics dashboard, google analytics widget, google analytics dashboard
4
  Requires at least: 3.8
5
  Tested up to: 4.7
6
- Stable tag: 2.0.2
7
 
8
  Use Google Analytics on your Wordpress site without touching any code, and view visitor reports right in your Wordpress admin dashboard!
9
 
@@ -47,6 +47,12 @@ By downloading and installing this plugin you are agreeing to the <a href="http:
47
 
48
  == Changelog ==
49
 
 
 
 
 
 
 
50
  = 2.0.2 =
51
  * Fixed issues related to older versions of PHP
52
  * Fixed terms of service notice
3
  Tags: analytics, dashboard, google, google analytics, google analytics plugin, javascript, marketing, pageviews, statistics, stats, tracking, visits, web stats, widget, analytics dashboard, google analytics dashboard, google analytics widget, google analytics dashboard
4
  Requires at least: 3.8
5
  Tested up to: 4.7
6
+ Stable tag: 2.0.3
7
 
8
  Use Google Analytics on your Wordpress site without touching any code, and view visitor reports right in your Wordpress admin dashboard!
9
 
47
 
48
  == Changelog ==
49
 
50
+ = 2.0.3 =
51
+ * Reliability improvements for Google Analytics access
52
+ * Better connection to Google Analytics API
53
+ * Fixed the save settings issue, thanks @biologix @tanshaydar
54
+ * Minor bug fixes
55
+
56
  = 2.0.2 =
57
  * Fixed issues related to older versions of PHP
58
  * Fixed terms of service notice
view/ga_dashboard_widget.php CHANGED
@@ -45,25 +45,25 @@
45
  </div>
46
  </div>
47
 
48
- <div style="margin-top: 5px;"><?php echo sprintf( '<a href="%s">' . __( 'Show more details' ) . '</a>', $more_details_url ); ?></div>
 
49
  </div>
50
 
51
  <script type="text/javascript">
52
-
53
  dataArr = [['Day', 'Pageviews'],<?php
54
- if ( $chart ) {
55
- $arr = "";
56
- foreach ( $chart as $row ) {
57
- if ( $arr ) {
58
- $arr .= ",";
59
- }
60
- $arr .= "['" . $row['day'] . "'," . $row['current'] . "]";
61
- }
62
  }
 
63
  echo $arr;
64
  ?>];
65
 
66
  ga_dashboard.init(dataArr);
67
  ga_dashboard.events(dataArr);
68
-
69
  </script>
45
  </div>
46
  </div>
47
 
48
+ <div style="margin-top: 5px;"><?php echo sprintf( '<a href="%s">' . __( 'Show more details' ) . '</a>',
49
+ $more_details_url ); ?></div>
50
  </div>
51
 
52
  <script type="text/javascript">
53
+ <?php if ( ! empty( $chart ) ) : ?>
54
  dataArr = [['Day', 'Pageviews'],<?php
55
+ $arr = "";
56
+ foreach ( $chart as $row ) {
57
+ if ( $arr ) {
58
+ $arr .= ",";
59
+ }
60
+ $arr .= "['" . $row['day'] . "'," . $row['current'] . "]";
 
 
61
  }
62
+
63
  echo $arr;
64
  ?>];
65
 
66
  ga_dashboard.init(dataArr);
67
  ga_dashboard.events(dataArr);
68
+ <?php endif; ?>
69
  </script>
view/ga_notice.php CHANGED
@@ -1,13 +1,20 @@
1
- <div id="googleanalytics_terms_notice" class="notice notice-warning <?php echo ( Ga_Helper::is_plugin_page() ) ? : 'is-dismissible' ?>">
 
2
  <p>
3
- Google Analytics <?php echo esc_html( GOOGLEANALYTICS_VERSION ); ?> plugin <a href="http://www.sharethis.com/news/2016/12/sharethis-adds-analytics-plugin-to-suite-of-tools/" target="_blank">has joined the ShareThis family.</a> <strong>A host of new features</strong> has been added in this version, including Google Analytics dashboards and roles management, and the update requires agreeing to the <a href="http://www.sharethis.com/privacy/" target="_blank">privacy policy</a> and <a href="http://www.sharethis.com/publisher-terms-of-use/" target="_blank">terms of use</a> to enable them. <a href="<?php echo esc_url( $url ); ?>"><span class="button button-primary">I accept</span></a>
 
 
 
 
 
 
4
  </p>
5
  </div>
6
  <script type="text/javascript">
7
- jQuery( document ).ready( function () {
8
- jQuery( '#googleanalytics_terms_notice .notice-dismiss' ).live( 'click', function ( event ) {
9
  event.preventDefault();
10
- jQuery.post( ajaxurl, { action: 'googleanalytics_hide_terms' } );
11
- } );
12
- } );
13
  </script>
1
+ <div id="googleanalytics_terms_notice"
2
+ class="notice notice-warning <?php echo ( Ga_Helper::is_plugin_page() ) ? '' : 'is-dismissible' ?>">
3
  <p>
4
+ Google Analytics <?php echo esc_html( GOOGLEANALYTICS_VERSION ); ?> plugin <a
5
+ href="http://www.sharethis.com/news/2016/12/sharethis-adds-analytics-plugin-to-suite-of-tools/"
6
+ target="_blank">has joined the ShareThis family.</a> <strong>A host of new features</strong> has been
7
+ added in this version, including Google Analytics dashboards and roles management, and the update requires
8
+ agreeing to the <a href="http://www.sharethis.com/privacy/" target="_blank">privacy policy</a> and <a
9
+ href="http://www.sharethis.com/publisher-terms-of-use/" target="_blank">terms of use</a> to enable them.
10
+ <a href="<?php echo esc_url( $url ); ?>"><span class="button button-primary">I accept</span></a>
11
  </p>
12
  </div>
13
  <script type="text/javascript">
14
+ jQuery(document).ready(function () {
15
+ jQuery('#googleanalytics_terms_notice .notice-dismiss').live('click', function (event) {
16
  event.preventDefault();
17
+ jQuery.post(ajaxurl, {action: 'googleanalytics_hide_terms'});
18
+ });
19
+ });
20
  </script>
view/ga_oauth_notice.php CHANGED
@@ -1,3 +1,3 @@
1
  <div class="alert alert-warning">
2
- <?php echo $msg; ?>
3
- </div>
1
  <div class="alert alert-warning">
2
+ <?php echo $msg; ?>
3
+ </div>
view/ga_wp_notice.php CHANGED
@@ -1,3 +1,3 @@
1
  <div class="notice notice-<?php echo $type; ?>">
2
- <?php echo $msg; ?>
3
  </div>
1
  <div class="notice notice-<?php echo $type; ?>">
2
+ <?php echo $msg; ?>
3
  </div>
view/page.php CHANGED
@@ -4,12 +4,12 @@
4
  <div class="modal-header">
5
  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
6
  aria-hidden="true">&times;</span></button>
7
- <h4 class="modal-title"><?php _e('Please paste the access code obtained from Google below:') ?></h4>
8
  </div>
9
  <div class="modal-body">
10
- <label for="ga_access_code"><strong><?php _e('Access Code'); ?></strong>:</label>
11
  &nbsp;<input id="ga_access_code_tmp" type="text" style="width: 350px"
12
- placeholder="<?php _e('Paste your access code here') ?>"/>
13
  <div class="ga-loader-wrapper">
14
  <div class="ga-loader"></div>
15
  </div>
@@ -18,53 +18,53 @@
18
  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
19
  <button type="button" class="btn btn-primary"
20
  id="ga_save_access_code"
21
- onclick="ga_popup.saveAccessCode( event )"><?php _e('Save Changes'); ?></button>
22
  </div>
23
  </div><!-- /.modal-content -->
24
  </div><!-- /.modal-dialog -->
25
  </div><!-- /.modal -->
26
 
27
  <div class="wrap ga-wrap">
28
- <h2>Google Analytics - <?php _e('Settings'); ?></h2>
29
  <div class="ga_container">
30
- <?php if ( ! empty($data['error_message'])) : ?>
31
- <?php echo $data['error_message']; ?>
32
- <?php endif; ?>
33
  <form id="ga_form" method="post" action="options.php">
34
- <?php settings_fields('googleanalytics'); ?>
35
  <input id="ga_access_code" type="hidden"
36
- name="<?php echo esc_attr(Ga_Admin::GA_OAUTH_AUTH_CODE_OPTION_NAME); ?>" value=""/>
37
  <table class="form-table">
38
  <tr valign="top">
39
- <?php if ( ! empty($data['popup_url'])): ?>
40
  <th scope="row">
41
- <label <?php echo ( ! Ga_Helper::are_terms_accepted()) ? 'class="label-grey ga-tooltip"' : '' ?>><?php echo _e('Google Profile') ?>
42
  :
43
- <span class="ga-tooltiptext ga-tt-abs"><?php _e('Please accept the terms to use this feature'); ?></span>
44
  </label>
45
  </th>
46
- <td <?php echo ( ! Ga_Helper::are_terms_accepted()) ? 'class="ga-tooltip"' : ''; ?>>
47
  <button id="ga_authorize_with_google_button" class="btn btn-primary"
48
- <?php if (Ga_Helper::are_terms_accepted()) : ?>
49
- onclick="ga_popup.authorize( event, '<?php echo esc_attr($data['popup_url']); ?>' )"
50
- <?php endif; ?>
51
- <?php echo((esc_attr($data[Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME]) || ! Ga_Helper::are_terms_accepted()) ? 'disabled="disabled"' : ''); ?>
52
- ><?php _e('Authenticate
53
- with Google') ?>
54
  </button>
55
- <span class="ga-tooltiptext"><?php _e('Please accept the terms to use this feature'); ?></span>
56
- <?php if ( ! empty($data[Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME])): ?>
57
  <div class="ga_warning">
58
- <strong><?php _e('Notice') ?></strong>:&nbsp;<?php _e('Please uncheck the "Manually enter Tracking ID" option to authenticate and view statistics.'); ?>
59
  </div>
60
- <?php endif; ?>
61
  </td>
62
- <?php endif; ?>
63
 
64
- <?php if ( ! empty($data['ga_accounts_selector'])): ?>
65
- <th scope="row"><?php echo _e('Google Analytics Account') ?>:</th>
66
  <td><?php echo $data['ga_accounts_selector']; ?></td>
67
- <?php endif; ?>
68
 
69
  </tr>
70
 
@@ -72,42 +72,42 @@
72
 
73
  <th scope="row">
74
  <div class="checkbox">
75
- <label class="ga_checkbox_label <?php echo ( ! Ga_Helper::are_terms_accepted()) ? 'label-grey ga-tooltip' : '' ?>"
76
  for="ga_enter_code_manually"> <input
77
- <?php if (Ga_Helper::are_terms_accepted()) : ?>
78
  onclick="ga_events.click( this, ga_events.codeManuallyCallback( <?php echo Ga_Helper::are_terms_accepted() ? 1 : 0; ?> ) )"
79
- <?php endif; ?>
80
  type="checkbox"
81
- <?php echo ( ! Ga_Helper::are_terms_accepted()) ? 'disabled="disabled"' : ''; ?>
82
- name="<?php echo esc_attr(Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME); ?>"
83
  id="ga_enter_code_manually"
84
  value="1"
85
- <?php echo(($data[Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME] || ! Ga_Helper::are_terms_accepted()) ? 'checked="checked"' : ''); ?>/>&nbsp;
86
- <?php _e('Manually enter Tracking ID') ?>
87
- <span class="ga-tooltiptext ga-tt-abs"><?php _e('Please accept the terms to use this feature'); ?></span>
88
  </label>
89
- <?php if ( ! Ga_Helper::are_terms_accepted()) : ?>
90
  <input id="ga_access_code" type="hidden"
91
- name="<?php echo esc_attr(Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME); ?>"
92
  value="1"/>
93
- <?php endif; ?>
94
  </div>
95
  </th>
96
  <td></td>
97
  </tr>
98
  <tr valign="top"
99
- id="ga_manually_wrapper" <?php echo(($data[Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME] || ! Ga_Helper::are_terms_accepted()) ? '' : 'style="display: none"'); ?> >
100
 
101
- <th scope="row"><?php _e('Tracking ID') ?>:</th>
102
  <td>
103
  <input type="text"
104
- name="<?php echo esc_attr(Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME); ?>"
105
- value="<?php echo esc_attr($data[Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME]); ?>"
106
  id="ga_manually_input"/>&nbsp;
107
  <div class="ga_warning">
108
- <strong><?php _e('Warning'); ?></strong>:&nbsp;<?php _e('If you enter your Tracking ID manually, Analytics statistics will not be shown.'); ?>
109
  <br>
110
- <?php _e('We strongly recommend to authenticate with Google using the button above.'); ?>
111
  </div>
112
  </td>
113
 
@@ -115,35 +115,35 @@
115
 
116
  <tr valign="top">
117
  <th scope="row">
118
- <label <?php echo ( ! Ga_Helper::are_terms_accepted()) ? 'class="label-grey ga-tooltip"' : '' ?>><?php _e('Exclude Tracking for Roles') ?>
119
  :
120
- <span class="ga-tooltiptext ga-tt-abs"><?php _e('Please accept the terms to use this feature'); ?></span>
121
  </label>
122
  </th>
123
  <td>
124
 
125
 
126
- <?php
127
- if ( ! empty($data['roles'])) {
128
- $roles = $data['roles'];
129
- foreach ($roles as $role) {
130
- ?>
131
  <div class="checkbox">
132
- <label class="ga_checkbox_label <?php echo ( ! Ga_Helper::are_terms_accepted()) ? 'label-grey ga-tooltip' : ''; ?>"
133
  for="checkbox_<?php echo $role['id']; ?>">
134
  <input id="checkbox_<?php echo $role['id']; ?>" type="checkbox"
135
- <?php echo ( ! Ga_Helper::are_terms_accepted()) ? 'disabled="disabled"' : ''; ?>
136
- name="<?php echo esc_attr(Ga_Admin::GA_EXCLUDE_ROLES_OPTION_NAME . "[" . $role['id'] . "]"); ?>"
137
- id="<?php echo esc_attr($role['id']); ?>"
138
- <?php echo esc_attr(($role['checked'] ? 'checked="checked"' : '')); ?> />&nbsp;
139
- <?php echo esc_html($role['name']); ?>
140
- <span class="ga-tooltiptext"><?php _e('Please accept the terms to use this feature'); ?></span>
141
  </label>
142
  </div>
143
- <?php
144
- }
145
- }
146
- ?>
147
 
148
  </td>
149
  </tr>
@@ -152,7 +152,7 @@
152
 
153
  <p class="submit">
154
  <input type="submit" class="button-primary"
155
- value="<?php _e('Save Changes') ?>"/>
156
  </p>
157
  </form>
158
  </div>
4
  <div class="modal-header">
5
  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
6
  aria-hidden="true">&times;</span></button>
7
+ <h4 class="modal-title"><?php _e( 'Please paste the access code obtained from Google below:' ) ?></h4>
8
  </div>
9
  <div class="modal-body">
10
+ <label for="ga_access_code"><strong><?php _e( 'Access Code' ); ?></strong>:</label>
11
  &nbsp;<input id="ga_access_code_tmp" type="text" style="width: 350px"
12
+ placeholder="<?php _e( 'Paste your access code here' ) ?>"/>
13
  <div class="ga-loader-wrapper">
14
  <div class="ga-loader"></div>
15
  </div>
18
  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
19
  <button type="button" class="btn btn-primary"
20
  id="ga_save_access_code"
21
+ onclick="ga_popup.saveAccessCode( event )"><?php _e( 'Save Changes' ); ?></button>
22
  </div>
23
  </div><!-- /.modal-content -->
24
  </div><!-- /.modal-dialog -->
25
  </div><!-- /.modal -->
26
 
27
  <div class="wrap ga-wrap">
28
+ <h2>Google Analytics - <?php _e( 'Settings' ); ?></h2>
29
  <div class="ga_container">
30
+ <?php if ( ! empty( $data['error_message'] ) ) : ?>
31
+ <?php echo $data['error_message']; ?>
32
+ <?php endif; ?>
33
  <form id="ga_form" method="post" action="options.php">
34
+ <?php settings_fields( 'googleanalytics' ); ?>
35
  <input id="ga_access_code" type="hidden"
36
+ name="<?php echo esc_attr( Ga_Admin::GA_OAUTH_AUTH_CODE_OPTION_NAME ); ?>" value=""/>
37
  <table class="form-table">
38
  <tr valign="top">
39
+ <?php if ( ! empty( $data['popup_url'] ) ): ?>
40
  <th scope="row">
41
+ <label <?php echo ( ! Ga_Helper::are_terms_accepted() ) ? 'class="label-grey ga-tooltip"' : '' ?>><?php echo _e( 'Google Profile' ) ?>
42
  :
43
+ <span class="ga-tooltiptext ga-tt-abs"><?php _e( 'Please accept the terms to use this feature' ); ?></span>
44
  </label>
45
  </th>
46
+ <td <?php echo ( ! Ga_Helper::are_terms_accepted() ) ? 'class="ga-tooltip"' : ''; ?>>
47
  <button id="ga_authorize_with_google_button" class="btn btn-primary"
48
+ <?php if ( Ga_Helper::are_terms_accepted() ) : ?>
49
+ onclick="ga_popup.authorize( event, '<?php echo esc_attr( $data['popup_url'] ); ?>' )"
50
+ <?php endif; ?>
51
+ <?php echo( ( esc_attr( $data[ Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME ] ) || ! Ga_Helper::are_terms_accepted() ) ? 'disabled="disabled"' : '' ); ?>
52
+ ><?php _e( 'Authenticate
53
+ with Google' ) ?>
54
  </button>
55
+ <span class="ga-tooltiptext"><?php _e( 'Please accept the terms to use this feature' ); ?></span>
56
+ <?php if ( ! empty( $data[ Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME ] ) ): ?>
57
  <div class="ga_warning">
58
+ <strong><?php _e( 'Notice' ) ?></strong>:&nbsp;<?php _e( 'Please uncheck the "Manually enter Tracking ID" option to authenticate and view statistics.' ); ?>
59
  </div>
60
+ <?php endif; ?>
61
  </td>
62
+ <?php endif; ?>
63
 
64
+ <?php if ( ! empty( $data['ga_accounts_selector'] ) ): ?>
65
+ <th scope="row"><?php echo _e( 'Google Analytics Account' ) ?>:</th>
66
  <td><?php echo $data['ga_accounts_selector']; ?></td>
67
+ <?php endif; ?>
68
 
69
  </tr>
70
 
72
 
73
  <th scope="row">
74
  <div class="checkbox">
75
+ <label class="ga_checkbox_label <?php echo ( ! Ga_Helper::are_terms_accepted() ) ? 'label-grey ga-tooltip' : '' ?>"
76
  for="ga_enter_code_manually"> <input
77
+ <?php if ( Ga_Helper::are_terms_accepted() ) : ?>
78
  onclick="ga_events.click( this, ga_events.codeManuallyCallback( <?php echo Ga_Helper::are_terms_accepted() ? 1 : 0; ?> ) )"
79
+ <?php endif; ?>
80
  type="checkbox"
81
+ <?php echo ( ! Ga_Helper::are_terms_accepted() ) ? 'disabled="disabled"' : ''; ?>
82
+ name="<?php echo esc_attr( Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME ); ?>"
83
  id="ga_enter_code_manually"
84
  value="1"
85
+ <?php echo( ( $data[ Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME ] || ! Ga_Helper::are_terms_accepted() ) ? 'checked="checked"' : '' ); ?>/>&nbsp;
86
+ <?php _e( 'Manually enter Tracking ID' ) ?>
87
+ <span class="ga-tooltiptext ga-tt-abs"><?php _e( 'Please accept the terms to use this feature' ); ?></span>
88
  </label>
89
+ <?php if ( ! Ga_Helper::are_terms_accepted() ) : ?>
90
  <input id="ga_access_code" type="hidden"
91
+ name="<?php echo esc_attr( Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME ); ?>"
92
  value="1"/>
93
+ <?php endif; ?>
94
  </div>
95
  </th>
96
  <td></td>
97
  </tr>
98
  <tr valign="top"
99
+ id="ga_manually_wrapper" <?php echo( ( $data[ Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_OPTION_NAME ] || ! Ga_Helper::are_terms_accepted() ) ? '' : 'style="display: none"' ); ?> >
100
 
101
+ <th scope="row"><?php _e( 'Tracking ID' ) ?>:</th>
102
  <td>
103
  <input type="text"
104
+ name="<?php echo esc_attr( Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME ); ?>"
105
+ value="<?php echo esc_attr( $data[ Ga_Admin::GA_WEB_PROPERTY_ID_MANUALLY_VALUE_OPTION_NAME ] ); ?>"
106
  id="ga_manually_input"/>&nbsp;
107
  <div class="ga_warning">
108
+ <strong><?php _e( 'Warning' ); ?></strong>:&nbsp;<?php _e( 'If you enter your Tracking ID manually, Analytics statistics will not be shown.' ); ?>
109
  <br>
110
+ <?php _e( 'We strongly recommend to authenticate with Google using the button above.' ); ?>
111
  </div>
112
  </td>
113
 
115
 
116
  <tr valign="top">
117
  <th scope="row">
118
+ <label <?php echo ( ! Ga_Helper::are_terms_accepted() ) ? 'class="label-grey ga-tooltip"' : '' ?>><?php _e( 'Exclude Tracking for Roles' ) ?>
119
  :
120
+ <span class="ga-tooltiptext ga-tt-abs"><?php _e( 'Please accept the terms to use this feature' ); ?></span>
121
  </label>
122
  </th>
123
  <td>
124
 
125
 
126
+ <?php
127
+ if ( ! empty( $data['roles'] ) ) {
128
+ $roles = $data['roles'];
129
+ foreach ( $roles as $role ) {
130
+ ?>
131
  <div class="checkbox">
132
+ <label class="ga_checkbox_label <?php echo ( ! Ga_Helper::are_terms_accepted() ) ? 'label-grey ga-tooltip' : ''; ?>"
133
  for="checkbox_<?php echo $role['id']; ?>">
134
  <input id="checkbox_<?php echo $role['id']; ?>" type="checkbox"
135
+ <?php echo ( ! Ga_Helper::are_terms_accepted() ) ? 'disabled="disabled"' : ''; ?>
136
+ name="<?php echo esc_attr( Ga_Admin::GA_EXCLUDE_ROLES_OPTION_NAME . "[" . $role['id'] . "]" ); ?>"
137
+ id="<?php echo esc_attr( $role['id'] ); ?>"
138
+ <?php echo esc_attr( ( $role['checked'] ? 'checked="checked"' : '' ) ); ?> />&nbsp;
139
+ <?php echo esc_html( $role['name'] ); ?>
140
+ <span class="ga-tooltiptext"><?php _e( 'Please accept the terms to use this feature' ); ?></span>
141
  </label>
142
  </div>
143
+ <?php
144
+ }
145
+ }
146
+ ?>
147
 
148
  </td>
149
  </tr>
152
 
153
  <p class="submit">
154
  <input type="submit" class="button-primary"
155
+ value="<?php _e( 'Save Changes' ) ?>"/>
156
  </p>
157
  </form>
158
  </div>
view/statistics.php CHANGED
@@ -2,5 +2,5 @@
2
  <h2>Google Analytics - <?php _e( 'Dashboard' ); ?></h2>
3
  <div class="ga_container" id="exTab2">
4
  <?php echo $data ?>
5
- </div>
6
  </div>
2
  <h2>Google Analytics - <?php _e( 'Dashboard' ); ?></h2>
3
  <div class="ga_container" id="exTab2">
4
  <?php echo $data ?>
5
+ </div>
6
  </div>
view/stats.php CHANGED
@@ -1,119 +1,121 @@
1
  <div class="wrap ga-wrap" id="ga-stats-container">
2
- <div class="panel panel-default">
3
- <div class="panel-heading"><strong><?php _e( "Pageviews - Last 7 days vs previous 7 days" ) ?></strong></div>
4
- <div class="panel-body ga-chart">
5
- <div id="chart_div" style="width: 100%;"></div>
6
- <div class="ga-loader-wrapper stats-page">
7
- <div class="ga-loader stats-page-loader"></div>
8
- </div>
9
- </div>
10
- </div>
11
 
12
- <div class="panel panel-default">
13
- <div class="panel-heading"><strong><?php _e( "Comparison - Last 7 days vs previous 7 days" ) ?></strong></div>
14
- <div class="panel-body">
15
- <div id="boxes-container">
16
- <div class="row">
17
  <?php if ( ! empty( $boxes ) ) : ?>
18
  <?php foreach ( $boxes as $box ) : ?>
19
- <div class="col-md-3">
20
- <div class="panel panel-default">
21
- <div class="panel-body ga-box-centered">
22
- <div style="font-size: 16px;"><?php echo $box['label'] ?></div>
23
- <div style="color: <?php echo $box['color'] ?>; font-size: 24px;"><?php echo Ga_Helper::format_percent( $box['diff'] ); ?></div>
24
- <div style="color: grey; font-size: 16px;"><?php echo $box['comparison'] ?></div>
25
- </div>
26
- </div>
27
- </div>
28
  <?php endforeach; ?>
29
  <?php endif; ?>
30
- </div>
31
- </div>
32
- </div>
33
- </div>
34
  <?php if ( ! empty( $sources ) ) : ?>
35
- <div class="panel panel-default">
36
- <div class="panel-heading"><strong><?php _e( "Top 5 Traffic Sources for the past 7 days" ) ?></strong></div>
37
- <div class="panel-body">
38
 
39
- <div id="table-container">
40
- <table class="table table-bordered">
41
- <tr>
42
- <td colspan="2">
43
- </td>
44
- <th style="text-align: right;">
45
  <?php _e( 'Pageviews' ); ?>
46
- </th>
47
- <th style="text-align: right;">
48
  <?php echo '%'; ?>
49
- </th>
50
- </tr>
51
- <tr>
52
- <td style="width: 20%; font-size: 20px;text-align:center" colspan="2"></td>
53
- <td class="col-md-2" style="text-align: right">
54
- <div style="font-size: 16px;"><?php echo $sources['total'] ?></div>
55
- <div style="color: grey; font-size: 10px;">% of
56
- Total: <?php echo Ga_Helper::format_percent( ( ! empty( $sources['total'] ) ) ? number_format( $sources['sum'] / $sources['total'] * 100, 2, '.', ' ' ) : 100 ); ?>
57
- (<?php echo $sources['sum'] ?>)
58
- </div>
59
- </td>
60
- <td class="col-md-5" style="text-align: right">
61
- <div style="font-size: 16px;"><?php echo $sources['total'] ?></div>
62
- <div style="color: grey; font-size: 10px;">% of
63
- Total: <?php echo Ga_Helper::format_percent( ( ! empty( $sources['total'] ) ) ? number_format( $sources['sum'] / $sources['total'] * 100, 2, '.', ' ' ) : 100 ); ?>
64
- (<?php echo $sources['sum'] ?>)
65
- </div>
66
- </td>
67
- </tr>
 
 
68
  <?php foreach ( $sources['rows'] as $key => $source ): ?>
69
- <tr>
70
- <td style="width: 5%;text-align: right"><?php echo $key ?>.</td>
71
- <td style="width: 10%;">
72
  <?php if ( $source['name'] != '(direct) / (none)' ) : ?>
73
- <a href="<?php echo $source['url'] ?>"
74
- target="_blank"><?php echo $source['name'] ?></a>
75
  <?php else: ?>
76
  <?php echo $source['name'] ?>
77
  <?php endif; ?>
78
- </td>
79
- <td style="text-align: right"><?php echo $source['number'] ?></td>
80
- <td>
81
- <div class="progress">
82
- <div class="progress-bar" role="progressbar"
83
- aria-valuenow="<?php echo $source['percent'] ?>" aria-valuemin="0"
84
- aria-valuemax="100"
85
- style="width: <?php echo $source['percent'] ?>%;"></div>
86
- <span style="margin-left: 10px;"><?php echo Ga_Helper::format_percent( $source['percent'] ); ?></span>
87
- </div>
88
- </td>
89
- </tr>
90
  <?php endforeach; ?>
91
- </table>
92
- </div>
93
- </div>
94
- </div>
95
  <?php endif; ?>
96
 
97
  <?php if ( ! empty( $chart ) ) : ?>
98
- <script type="text/javascript">
99
 
100
- ga_charts.init(function () {
101
 
102
- var data = new google.visualization.DataTable();
103
- data.addColumn('string', 'Day');
104
- data.addColumn('number', '<?php echo $labels['thisWeek'] ?>');
105
- data.addColumn({type: 'string', role: 'tooltip', 'p': {'html': true}});
106
- data.addColumn('number', '<?php echo $labels['lastWeek'] ?>');
107
- data.addColumn({type: 'string', role: 'tooltip', 'p': {'html': true}});
108
 
109
  <?php foreach ( $chart as $row ) : ?>
110
- data.addRow(['<?php echo $row['day'] ?>', <?php echo $row['current'] ?>, ga_charts.createTooltip('<?php echo $row['day'] ?>', '<?php echo $row['current'] ?>'), <?php echo $row['previous'] ?>, ga_charts.createTooltip('<?php echo $row['previous-day'] ?>', '<?php echo $row['previous'] ?>')]);
111
  <?php endforeach; ?>
112
- ga_charts.events(data);
113
- ga_charts.drawChart(data);
114
- ga_loader.hide();
115
- }
116
- );
117
- </script>
118
  <?php endif; ?>
119
  </div>
1
  <div class="wrap ga-wrap" id="ga-stats-container">
2
+ <div class="panel panel-default">
3
+ <div class="panel-heading"><strong><?php _e( "Pageviews - Last 7 days vs previous 7 days" ) ?></strong></div>
4
+ <div class="panel-body ga-chart">
5
+ <div id="chart_div" style="width: 100%;"></div>
6
+ <div class="ga-loader-wrapper stats-page">
7
+ <div class="ga-loader stats-page-loader"></div>
8
+ </div>
9
+ </div>
10
+ </div>
11
 
12
+ <div class="panel panel-default">
13
+ <div class="panel-heading"><strong><?php _e( "Comparison - Last 7 days vs previous 7 days" ) ?></strong></div>
14
+ <div class="panel-body">
15
+ <div id="boxes-container">
16
+ <div class="row">
17
  <?php if ( ! empty( $boxes ) ) : ?>
18
  <?php foreach ( $boxes as $box ) : ?>
19
+ <div class="col-md-3">
20
+ <div class="panel panel-default">
21
+ <div class="panel-body ga-box-centered">
22
+ <div style="font-size: 16px;"><?php echo $box['label'] ?></div>
23
+ <div style="color: <?php echo $box['color'] ?>; font-size: 24px;"><?php echo Ga_Helper::format_percent( $box['diff'] ); ?></div>
24
+ <div style="color: grey; font-size: 16px;"><?php echo $box['comparison'] ?></div>
25
+ </div>
26
+ </div>
27
+ </div>
28
  <?php endforeach; ?>
29
  <?php endif; ?>
30
+ </div>
31
+ </div>
32
+ </div>
33
+ </div>
34
  <?php if ( ! empty( $sources ) ) : ?>
35
+ <div class="panel panel-default">
36
+ <div class="panel-heading"><strong><?php _e( "Top 5 Traffic Sources for the past 7 days" ) ?></strong></div>
37
+ <div class="panel-body">
38
 
39
+ <div id="table-container">
40
+ <table class="table table-bordered">
41
+ <tr>
42
+ <td colspan="2">
43
+ </td>
44
+ <th style="text-align: right;">
45
  <?php _e( 'Pageviews' ); ?>
46
+ </th>
47
+ <th style="text-align: right;">
48
  <?php echo '%'; ?>
49
+ </th>
50
+ </tr>
51
+ <tr>
52
+ <td style="width: 20%; font-size: 20px;text-align:center" colspan="2"></td>
53
+ <td class="col-md-2" style="text-align: right">
54
+ <div style="font-size: 16px;"><?php echo $sources['total'] ?></div>
55
+ <div style="color: grey; font-size: 10px;">% of
56
+ Total: <?php echo Ga_Helper::format_percent( ( ! empty( $sources['total'] ) ) ? number_format( $sources['sum'] / $sources['total'] * 100,
57
+ 2, '.', ' ' ) : 100 ); ?>
58
+ (<?php echo $sources['sum'] ?>)
59
+ </div>
60
+ </td>
61
+ <td class="col-md-5" style="text-align: right">
62
+ <div style="font-size: 16px;"><?php echo $sources['total'] ?></div>
63
+ <div style="color: grey; font-size: 10px;">% of
64
+ Total: <?php echo Ga_Helper::format_percent( ( ! empty( $sources['total'] ) ) ? number_format( $sources['sum'] / $sources['total'] * 100,
65
+ 2, '.', ' ' ) : 100 ); ?>
66
+ (<?php echo $sources['sum'] ?>)
67
+ </div>
68
+ </td>
69
+ </tr>
70
  <?php foreach ( $sources['rows'] as $key => $source ): ?>
71
+ <tr>
72
+ <td style="width: 5%;text-align: right"><?php echo $key ?>.</td>
73
+ <td style="width: 10%;">
74
  <?php if ( $source['name'] != '(direct) / (none)' ) : ?>
75
+ <a href="<?php echo $source['url'] ?>"
76
+ target="_blank"><?php echo $source['name'] ?></a>
77
  <?php else: ?>
78
  <?php echo $source['name'] ?>
79
  <?php endif; ?>
80
+ </td>
81
+ <td style="text-align: right"><?php echo $source['number'] ?></td>
82
+ <td>
83
+ <div class="progress">
84
+ <div class="progress-bar" role="progressbar"
85
+ aria-valuenow="<?php echo $source['percent'] ?>" aria-valuemin="0"
86
+ aria-valuemax="100"
87
+ style="width: <?php echo $source['percent'] ?>%;"></div>
88
+ <span style="margin-left: 10px;"><?php echo Ga_Helper::format_percent( $source['percent'] ); ?></span>
89
+ </div>
90
+ </td>
91
+ </tr>
92
  <?php endforeach; ?>
93
+ </table>
94
+ </div>
95
+ </div>
96
+ </div>
97
  <?php endif; ?>
98
 
99
  <?php if ( ! empty( $chart ) ) : ?>
100
+ <script type="text/javascript">
101
 
102
+ ga_charts.init(function () {
103
 
104
+ var data = new google.visualization.DataTable();
105
+ data.addColumn('string', 'Day');
106
+ data.addColumn('number', '<?php echo $labels['thisWeek'] ?>');
107
+ data.addColumn({type: 'string', role: 'tooltip', 'p': {'html': true}});
108
+ data.addColumn('number', '<?php echo $labels['lastWeek'] ?>');
109
+ data.addColumn({type: 'string', role: 'tooltip', 'p': {'html': true}});
110
 
111
  <?php foreach ( $chart as $row ) : ?>
112
+ data.addRow(['<?php echo $row['day'] ?>', <?php echo $row['current'] ?>, ga_charts.createTooltip('<?php echo $row['day'] ?>', '<?php echo $row['current'] ?>'), <?php echo $row['previous'] ?>, ga_charts.createTooltip('<?php echo $row['previous-day'] ?>', '<?php echo $row['previous'] ?>')]);
113
  <?php endforeach; ?>
114
+ ga_charts.events(data);
115
+ ga_charts.drawChart(data);
116
+ ga_loader.hide();
117
+ }
118
+ );
119
+ </script>
120
  <?php endif; ?>
121
  </div>