WD Google Analytics - Version 1.0.2

Version Description

Changed: Site speed and Sales performance reports sorting

Download this release

Release Info

Developer webdorado
Plugin Icon 128x128 WD Google Analytics
Version 1.0.2
Comparing to
See all releases

Code changes from version 1.0.1 to 1.0.2

Files changed (51) hide show
  1. admin/gawd_google_class.php +1587 -1578
  2. admin/licensing.php +88 -88
  3. admin/pages/browser.php +10 -10
  4. admin/pages/custom_dimensions.php +82 -82
  5. admin/pages/custom_reports.php +6 -6
  6. admin/pages/dashboard.php +670 -670
  7. admin/pages/dashboard_menu.php +119 -119
  8. admin/pages/dashboard_widget.php +42 -42
  9. admin/pages/date.php +59 -59
  10. admin/pages/goals.php +261 -261
  11. admin/pages/location.php +11 -11
  12. admin/pages/overview.php +75 -75
  13. admin/pages/real_time.php +16 -16
  14. admin/pages/settings.php +546 -546
  15. admin/pages/tracking.php +253 -253
  16. admin/pages/uninstall.php +80 -80
  17. admin/pages/visitors.php +10 -10
  18. admin/post_page_view.php +61 -61
  19. admin/tracking.php +147 -147
  20. featured/featured.php +170 -170
  21. featured/featured_themes.php +301 -301
  22. featured/style.css +204 -204
  23. gawd_class.php +2133 -2133
  24. google-analytics-wd.php +37 -37
  25. google/Auth/Abstract.php +38 -38
  26. google/Auth/AppIdentity.php +120 -120
  27. google/Auth/AssertionCredentials.php +136 -136
  28. google/Auth/ComputeEngine.php +146 -146
  29. google/Auth/Exception.php +24 -24
  30. google/Auth/LoginTicket.php +71 -71
  31. google/Auth/OAuth2.php +646 -646
  32. google/Auth/Simple.php +63 -63
  33. google/Cache/Abstract.php +53 -53
  34. google/Cache/Apc.php +113 -113
  35. google/Cache/Exception.php +24 -24
  36. google/Cache/File.php +209 -209
  37. google/Cache/Memcache.php +184 -184
  38. google/Cache/Null.php +57 -57
  39. google/Client.php +715 -715
  40. google/Collection.php +101 -101
  41. google/Config.php +452 -452
  42. google/Exception.php +20 -20
  43. google/Http/Batch.php +145 -145
  44. google/Http/CacheParser.php +185 -185
  45. google/Http/MediaFileUpload.php +341 -341
  46. google/Http/REST.php +178 -178
  47. google/Http/Request.php +504 -504
  48. google/IO/Abstract.php +339 -339
  49. google/IO/Curl.php +182 -182
  50. google/IO/Exception.php +69 -69
  51. google/IO/Stream.php +243 -243
admin/gawd_google_class.php CHANGED
@@ -1,1578 +1,1587 @@
1
- <?php
2
-
3
- require_once(GAWD_DIR . '/google/autoload.php');
4
-
5
- class GAWD_google_client {
6
-
7
- private static $instance;
8
- private $google_client;
9
- public $analytics_member;
10
- private $gawd_user_data;
11
-
12
- protected function __construct() {
13
- $this->gawd_user_data = get_option('gawd_user_data');
14
- try{
15
- $this->google_client = new Google_Client();
16
- $this->set_google_client();
17
- $this->analytics_member = new Google_Service_Analytics($this->google_client);
18
-
19
- }catch(Google_Service_Exception $e){
20
-
21
- return $e->getErrors()[0]["message"];
22
- }catch(Exception $e){
23
- return $e->getMessage();
24
- }
25
- }
26
-
27
- /**
28
- * Sets the google class member.
29
- */
30
- private function set_google_client() {
31
-
32
- $access_token = $this->gawd_user_data['access_token'];
33
- $this->google_client->setAccessToken($access_token);
34
-
35
- if ($this->google_client->isAccessTokenExpired()) {
36
- $refresh_token = $this->gawd_user_data['refresh_token'];
37
-
38
- $this->google_client->setClientId(GAWD::get_instance()->get_project_client_id());
39
- $this->google_client->setClientSecret(GAWD::get_instance()->get_project_client_secret());
40
- $this->google_client->setRedirectUri(GAWD::get_instance()->redirect_uri);
41
- // $this->google_client->setAuthConfigFile(GAWD_DIR . '/client_secrets.json');
42
- $this->google_client->refreshToken($refresh_token);
43
- }
44
- }
45
-
46
- public static function create_authentication_url() {
47
- $client = new Google_Client();
48
- // $client->setAuthConfigFile(GAWD_DIR . '/client_secrets.json');
49
- $client->setClientId(GAWD::get_instance()->get_project_client_id());
50
- $client->setClientSecret(GAWD::get_instance()->get_project_client_secret());
51
- $client->setRedirectUri(GAWD::get_instance()->redirect_uri);
52
- $client->addScope(array(Google_Service_Analytics::ANALYTICS_EDIT, Google_Service_Analytics::ANALYTICS_READONLY));
53
- $client->setApprovalPrompt('force');
54
- $client->setAccessType('offline');
55
- return "'" . $client->createAuthUrl() . "'";
56
- }
57
-
58
- public static function authenticate($code) {
59
-
60
- $client = new Google_Client();
61
- // $client->setAuthConfigFile(GAWD_DIR . '/client_secrets.json');
62
- $client->setClientId(GAWD::get_instance()->get_project_client_id());
63
- $client->setClientSecret(GAWD::get_instance()->get_project_client_secret());
64
- $client->setRedirectUri(GAWD::get_instance()->redirect_uri);
65
- try {
66
- $client->authenticate($code);
67
-
68
- if ($client->isAccessTokenExpired()) {
69
- return false;
70
- }
71
- else {
72
- $access_token = $client->getAccessToken();
73
- $refresh_token = $client->getRefreshToken();
74
- update_option('gawd_user_data', array(
75
- 'access_token' => $access_token,
76
- 'refresh_token' => $refresh_token
77
- )
78
- );
79
-
80
- $gawd_client = self::get_instance();
81
- delete_transient('gawd_user_profiles');
82
- $profiles = $gawd_client->get_profiles();
83
-
84
- if ($profiles instanceof Google_Service_Exception) {
85
-
86
- delete_option('gawd_user_data');
87
-
88
- return $profiles->getErrors()[0]["message"];
89
- }
90
-
91
-
92
- update_option('gawd_user_data', array(
93
- 'access_token' => $access_token,
94
- 'refresh_token' => $refresh_token,
95
- 'gawd_profiles' => $profiles,
96
- )
97
- );
98
- return true;
99
- }
100
- } catch (Google_Service_Exception $e) {
101
- delete_option('gawd_user_data');
102
- return $e->getErrors()[0]["message"];
103
- } catch (Exception $e) {
104
- return $e->getMessage();
105
- }
106
- }
107
-
108
- public function get_management_accounts() {
109
- $accounts_light = array();
110
- try{
111
- $accounts = $this->analytics_member->management_accounts->listManagementAccounts()->getItems();
112
-
113
- foreach ($accounts as $account) {
114
- $edit_flag = FALSE;
115
- $permissions = $account['modelData']['permissions']['effective'];
116
- foreach ($permissions as $permission) {
117
- if ($permission == 'EDIT') {
118
- $edit_flag = TRUE;
119
- }
120
- }
121
- $accounts_light[] = array(
122
- 'name' => $account['name'],
123
- 'id' => $account['id'],
124
- 'edit_permissions' => $edit_flag
125
- );
126
- /*if ($edit_flag == TRUE) {
127
- $accounts_light[] = array(
128
- 'name' => $account['name'],
129
- 'id' => $account['id']
130
- );
131
- }*/
132
- }
133
- }catch (Google_Service_Exception $e) {
134
- //return $e->getErrors()[0]["message"];
135
- } catch (Exception $e) {
136
- //return $e->getMessage();
137
- }
138
- return $accounts_light;
139
- }
140
-
141
- public function property_exists() {
142
- try{
143
- $web_properties = $this->analytics_member->management_webproperties->listManagementWebproperties('~all')->getItems();
144
- }catch(Google_Service_Exception $e){
145
- return 'no_matches';
146
-
147
- }catch(Exception $e){
148
- return 'no_matches';
149
- }
150
- $exact_properties = array();
151
- $site_url = get_site_url() . '/';
152
-
153
- foreach ($web_properties as $web_property) {
154
- $current_url = $web_property['websiteUrl'];
155
- if (($current_url == $site_url) || (($current_url . '/') == $site_url)) {
156
- $exact_properties[] = $web_property;
157
- }
158
- }
159
- if (!empty($exact_properties)) {
160
- return $exact_properties;
161
- } else {
162
- return 'no_matches';
163
- }
164
- }
165
-
166
- public function get_default_profiles() {
167
- $gawd_user_data = get_option('gawd_user_data');
168
- $accountId = $this->get_default_accountId();
169
- $webPropertyId = $this->get_default_webPropertyId();
170
- $webProperty = $this->analytics_member->management_webproperties->get($accountId, $webPropertyId);
171
- $webPropertyName = $webProperty['name'];
172
- $profiles = $this->analytics_member->management_profiles->listManagementProfiles($accountId, $webPropertyId)->getItems();
173
- $profiles_light = array();
174
- foreach ($profiles as $profile) {
175
- $profiles_light[] = array(
176
- 'id' => $profile['id'],
177
- 'name' => $profile['name'],
178
- 'webPropertyName' => $webPropertyName
179
- );
180
- }
181
- return $profiles_light;
182
- }
183
-
184
- public function add_webproperty($accountId, $name) {
185
-
186
- $analytics = $this->analytics_member;
187
- $websiteUrl = get_site_url();
188
- try {
189
- $property = new Google_Service_Analytics_Webproperty();
190
- $property->setName($name);
191
- $property->setWebsiteUrl($websiteUrl);
192
- $analytics->management_webproperties->insert($accountId, $property);
193
- } catch (apiServiceException $e) {
194
- print 'There was an Analytics API service error '
195
- . $e->getCode() . ':' . $e->getMessage();
196
- } catch (apiException $e) {
197
- print 'There was a general API error '
198
- . $e->getCode() . ':' . $e->getMessage();
199
- }
200
- catch (Google_Service_Exception $e) {
201
- return 'There was a general API error '
202
- . $e->getCode() . ':' . $e->getMessage();
203
- }catch (Exception $e) {
204
- echo $e->getCode() . ':' . $e->getMessage();
205
- }
206
-
207
- $web_properties = $this->analytics_member->management_webproperties->listManagementWebproperties($accountId)->getItems();
208
-
209
- foreach ($web_properties as $web_property) {
210
- if ($web_property['name'] == $name) {
211
- $profile = new Google_Service_Analytics_Profile();
212
- $profile->setName('All Web Site Data');
213
- try {
214
- $analytics->management_profiles->insert($accountId, $web_property['id'], $profile);
215
- } catch (apiServiceException $e) {
216
- print 'There was an Analytics API service error '
217
- . $e->getCode() . ':' . $e->getMessage();
218
- } catch (apiException $e) {
219
- print 'There was a general API error '
220
- . $e->getCode() . ':' . $e->getMessage();
221
- }
222
- }
223
- }
224
- }
225
-
226
- /**
227
- * Get all the managment profiles of the authenticated user.
228
- *
229
- * @return array
230
- */
231
- public function get_profiles() {
232
- $profiles_light = get_transient('gawd_user_profiles') ? get_transient('gawd_user_profiles') : '';
233
- if ($profiles_light && $profiles_light != ''){
234
- return $profiles_light;
235
- }
236
- $profiles_light = array();
237
- $gawd_user_data = get_option('gawd_user_data');
238
- try{
239
-
240
- $web_properties = $this->analytics_member->management_webproperties->listManagementWebproperties('~all')->getItems();
241
- $profiles = $this->analytics_member->management_profiles->listManagementProfiles('~all', '~all')->getItems();
242
- $profiles_count = count($profiles);
243
- $web_properties_count = count($web_properties);
244
- for ($i = 0; $i < $web_properties_count; $i++) {
245
- for ($j = 0; $j < $profiles_count; $j++) {
246
- if ($web_properties[$i]['id'] == $profiles[$j]['webPropertyId']) {
247
- $profiles_light[$web_properties[$i]['name']][] = array(
248
- 'id' => $profiles[$j]['id'],
249
- 'name' => $profiles[$j]['name'],
250
- 'webPropertyId' => $profiles[$j]['webPropertyId'],
251
- 'websiteUrl' => $profiles[$j]['websiteUrl'],
252
- 'accountId' => $profiles[$j]['accountId']
253
- );
254
- }
255
- }
256
- }
257
- if (!isset($gawd_user_data['gawd_id']) || $gawd_user_data['gawd_id'] == '' || $gawd_user_data['gawd_id'] == NULL) {
258
- if (!empty($profiles_light)) {
259
- $first_profile = reset($profiles_light)[0];
260
- $gawd_user_data['gawd_id'] = $first_profile['id'];
261
- $gawd_user_data['webPropertyId'] = $first_profile['webPropertyId'];
262
- $gawd_user_data['accountId'] = $first_profile['accountId'];
263
- $gawd_user_data['web_property_name'] = $web_properties[0]['name'];
264
- }
265
- }
266
-
267
- $gawd_user_data['gawd_profiles'] = $profiles_light;
268
- update_option('gawd_user_data', $gawd_user_data);
269
- set_transient('gawd_user_profiles',$profiles_light, 60);
270
- return $profiles_light;
271
- }catch(Google_Service_Exception $e){
272
- return $e;
273
- }catch(Exception $e){
274
- return $e;
275
- }
276
- }
277
-
278
- public function get_custom_dimensions($default = '') {
279
- $this->gawd_user_data = get_option('gawd_user_data');
280
- if ($default == 'default') {
281
- $webPropertyId = $this->get_default_webPropertyId();
282
- $accountId = $this->get_default_accountId();
283
- }
284
- else {
285
- $webPropertyId = $this->get_profile_webPropertyId();
286
- $accountId = $this->get_profile_accountId();
287
- $transient = get_transient('gawd-custom-dimensions-' . $webPropertyId);
288
- if ($transient) {
289
- if ($transient != 'no_custom_dimensions_exist') {
290
- return json_decode($transient, true);
291
- } else {
292
- return $transient;
293
- }
294
- }
295
- }
296
-
297
- $all_dimensions = $this->analytics_member->management_customDimensions->listManagementCustomDimensions($accountId, $webPropertyId)->getItems();
298
- if (0 == sizeof($all_dimensions)) {
299
- if ($default == 'default') {
300
- update_option('gawd_custom_dimensions', "no_custom_dimensions_exist");
301
- }
302
- set_transient('gawd-custom-dimensions-' . $webPropertyId, "no_custom_dimensions_exist", 12 * HOUR_IN_SECONDS);
303
- return "no_custom_dimensions_exist";
304
- }
305
- else {
306
- foreach ($all_dimensions as $dimension) {
307
- $dimensions_light[] = array(
308
- 'name' => $dimension['name'],
309
- 'id' => $dimension['id']
310
- );
311
- }
312
- $supported_dimensions = array("Logged in", "Post type", "Author", "Category", "Tags", "Published Month", "Published Year");
313
- $dimensions = array();
314
- foreach ($dimensions_light as $dimension) {
315
- foreach ($supported_dimensions as $supported_dimension) {
316
- if (trim(strtolower($dimension['name'])) == strtolower($supported_dimension)) {
317
- $dimension['name'] = $supported_dimension;
318
- $dimension['id'] = substr($dimension['id'], -1);
319
- $dimensions[] = $dimension;
320
- }
321
- }
322
- }
323
- if ($default == 'default') {
324
- update_option('gawd_custom_dimensions', $dimensions);
325
- }
326
- set_transient('gawd-custom-dimensions-' . $webPropertyId, json_encode($dimensions_light), 12 * HOUR_IN_SECONDS);
327
- return $dimensions_light;
328
- }
329
- }
330
-
331
- public function get_custom_dimensions_tracking() {
332
- $all_dimensions = get_option('gawd_custom_dimensions');
333
- if ($all_dimensions) {
334
- return $all_dimensions;
335
- }
336
- $all_dimensions = $this->get_custom_dimensions('default');
337
- if ($all_dimensions == 'no_custom_dimensions_exist') {
338
- return 'no_custom_dimensions_exist';
339
- }
340
- $supported_dimensions = array("Logged in", "Post type", "Author", "Category", "Tags", "Published Month", "Published Year");
341
- $dimensions = array();
342
- foreach ($all_dimensions as $dimension) {
343
- foreach ($supported_dimensions as $supported_dimension) {
344
- if (trim(strtolower($dimension['name'])) == strtolower($supported_dimension)) {
345
- $dimension['id'] = substr($dimension['id'], -1);
346
- $dimension['name'] = $supported_dimension;
347
- $dimensions[] = $dimension;
348
- }
349
- }
350
- }
351
- update_option('gawd_custom_dimensions', $dimensions);
352
- if ($dimensions) {
353
- return $dimensions;
354
- } else {
355
- return "no_custom_dimensions_exist";
356
- }
357
- }
358
-
359
- public static function gawd_cd_logged_in() {
360
- $value = var_export(is_user_logged_in(), true);
361
- $value = $value == 'true' ? 'yes' : 'no';
362
- return $value;
363
- }
364
-
365
- public static function gawd_cd_post_type() {
366
- if (is_singular()) {
367
- $post_type = get_post_type(get_the_ID());
368
-
369
- if ($post_type) {
370
- return $post_type;
371
- }
372
- }
373
- }
374
-
375
- public static function gawd_cd_author() {
376
- if (is_singular()) {
377
- if (have_posts()) {
378
- while (have_posts()) {
379
- the_post();
380
- }
381
- }
382
- $name = get_the_author_meta('user_nicename');
383
- $value = trim($name);
384
- return $value;
385
- }
386
- }
387
-
388
- public static function gawd_cd_category() {
389
- if (is_single()) {
390
- $categories = get_the_category(get_the_ID());
391
-
392
- if ($categories) {
393
- foreach ($categories as $category) {
394
- $category_names[] = $category->slug;
395
- }
396
-
397
- return implode(',', $category_names);
398
- }
399
- }
400
- }
401
-
402
- public static function gawd_cd_tags() {
403
- if (is_single()) {
404
- $tag_names = 'untagged';
405
-
406
- $tags = get_the_tags(get_the_ID());
407
-
408
- if ($tags) {
409
- $tag_names = implode(',', wp_list_pluck($tags, 'name'));
410
- }
411
-
412
- return $tag_names;
413
- }
414
- }
415
-
416
-
417
- public static function gawd_cd_published_month() {
418
- if (is_singular()) {
419
- return get_the_date('M-Y');
420
- }
421
- }
422
- public static function gawd_cd_published_year() {
423
- if (is_singular()) {
424
- return get_the_date('Y');
425
- }
426
- }
427
-
428
- public function get_management_filters() {
429
- $analytics = $this->analytics_member;
430
- $this->gawd_user_data = get_option('gawd_user_data');
431
- $accountId = $this->get_profile_accountId();
432
- $profileId = $this->get_profile_id();
433
- $webPropertyId = $this->get_profile_webPropertyId();
434
-
435
- try {
436
- $view_filters = $analytics->management_profileFilterLinks->listManagementProfileFilterLinks($accountId, $webPropertyId, $profileId);
437
- $filters = $view_filters->getItems();
438
- foreach ($filters as $filter) {
439
- $filter_info = $analytics->management_filters->get($accountId,$filter['modelData']['filterRef']['id']);
440
- $all_filters[] = array(
441
- 'name' => $filter['modelData']['filterRef']['name'],
442
- 'id' => $filter['modelData']['filterRef']['id'],
443
- 'type' => $filter_info['excludeDetails']['field'],
444
- 'value' => $filter_info['excludeDetails']['expressionValue'],
445
- 'view' => $filter['modelData']['profileRef']['name']
446
- );
447
- }
448
- if (isset($all_filters)) {
449
- return $all_filters;
450
- }
451
- } catch (Exception $e) {
452
- $error = array('error_message' => 'Error');
453
- if (strpos($e->getMessage(), 'User does not have sufficient permissions for this ')) {
454
- $error['error_message'] = 'User does not have sufficient permissions for this profile';
455
- }
456
- return json_encode($error);
457
- }
458
- }
459
-
460
- public function get_management_goals() {
461
- $this->gawd_user_data = get_option('gawd_user_data');
462
- $profileId = $this->get_profile_id();
463
- $accountId = $this->get_profile_accountId();
464
- $webPropertyId = $this->get_profile_webPropertyId();
465
- $goals = array();
466
- try {
467
- $goals = $this->analytics_member->management_goals->listManagementGoals($accountId, $webPropertyId, $profileId)->getItems();
468
- } catch (Exception $e) {
469
-
470
- }
471
- if (0 == sizeof($goals)) {
472
- return "no_goals_exist";
473
- } else {
474
- foreach ($goals as $goal) {
475
- $goals_light[] = array(
476
- 'name' => $goal['name'],
477
- 'id' => $goal['id']
478
- );
479
- }
480
- return $goals_light;
481
- }
482
- }
483
-
484
- public function get_default_goals() {
485
- $this->gawd_user_data = get_option('gawd_user_data');
486
- $accountId = $this->get_default_accountId();
487
- $webPropertyId = $this->get_default_webPropertyId();
488
- $goals = array();
489
- try {
490
- $goals = $this->analytics_member->management_goals->listManagementGoals($accountId, $webPropertyId, '~all')->getItems();
491
- } catch (Exception $e) {
492
-
493
- }
494
- if (0 == sizeof($goals)) {
495
- return "no_goals_exist";
496
- } else {
497
- $profiles = array();
498
- foreach ($goals as $goal) {
499
- $flag = false;
500
- foreach ($profiles as $profile) {
501
- if ($profile == $goal['profileId']) {
502
- $flag = true;
503
- }
504
- }
505
- if ($flag == false) {
506
- $profiles[] = $goal['profileId'];
507
- }
508
- }
509
- $goals_light = array();
510
- $caseSensitive = '';
511
- foreach ($profiles as $profile) {
512
- foreach ($goals as $goal) {
513
- if ($goal['profileId'] == $profile) {
514
- if($goal['type'] == 'URL_DESTINATION'){
515
- $type = 'Destination';
516
- if($goal["modelData"]['urlDestinationDetails']['matchType'] == 'EXACT'){
517
- $match_type = 'Equals';
518
- }
519
- elseif($goal["modelData"]['urlDestinationDetails']['matchType'] == 'HEAD'){
520
- $match_type = 'Begin with';
521
- }
522
- else{
523
- $match_type = 'Regular expresion';
524
- }
525
- $value = $goal["modelData"]['urlDestinationDetails']['url'];
526
- $caseSensitive = $goal["modelData"]['urlDestinationDetails']['caseSensitive'];
527
- }
528
- elseif($goal['type'] == 'VISIT_TIME_ON_SITE'){
529
- $type = 'Duration';
530
- if($goal["modelData"]['visitTimeOnSiteDetails']['comparisonType'] == 'GREATER_THAN'){
531
- $match_type = 'Greater than';
532
- }
533
- $value = $goal["modelData"]['visitTimeOnSiteDetails']['comparisonValue'];
534
- $hours = strlen(floor($value / 3600)) < 2 ? '0' . floor($value / 3600) : floor($value / 3600);
535
- $mins = strlen(floor($value / 60 % 60)) < 2 ? '0' . floor($value / 60 % 60) : floor($value / 60 % 60);
536
- $secs = strlen(floor($value % 60)) < 2 ? '0' . floor($value % 60) : floor($value % 60);
537
- $value = $hours.':'.$mins.':'.$secs;
538
- }
539
- else{
540
- $type = 'Pages/Screens per session';
541
- if($goal["modelData"]['visitNumPagesDetails']['comparisonType'] == 'GREATER_THAN'){
542
- $match_type = 'Greater than';
543
- }
544
- $value = $goal["modelData"]['visitNumPagesDetails']['comparisonValue'];
545
- }
546
-
547
- $goals_light[$profile][] = array(
548
- 'name' => $goal['name'],
549
- 'id' => $goal['id'],
550
- 'type' => $type,
551
- 'match_type' => $match_type,
552
- 'profileID' => $goal['profileId'],
553
- 'caseSensitive' => $caseSensitive,
554
- 'value' => $value,
555
- );
556
- }
557
- }
558
- }
559
- return $goals_light;
560
- }
561
- }
562
-
563
- public function add_custom_dimension($name, $id) {
564
-
565
- $custom_dimension = new Google_Service_Analytics_CustomDimension();
566
- $custom_dimension->setId($id);
567
- $custom_dimension->setActive(TRUE);
568
- $custom_dimension->setScope('Hit');
569
- $custom_dimension->setName($name);
570
-
571
- $accountId = $this->get_default_accountId();
572
- $webPropertyId = $this->get_default_webPropertyId();
573
- $analytics = $this->analytics_member;
574
- delete_transient('gawd-custom-dimensions-' . $webPropertyId);
575
- try {
576
- $analytics->management_customDimensions->insert($accountId, $webPropertyId, $custom_dimension);
577
- } catch (apiServiceException $e) {
578
- print 'There was an Analytics API service error '
579
- . $e->getCode() . ':' . $e->getMessage();
580
- } catch (apiException $e) {
581
- print 'There was a general API error '
582
- . $e->getCode() . ':' . $e->getMessage();
583
- }
584
- }
585
-
586
- public function add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_comparison = "GREATER_THAN", $gawd_goal_value, $url_case_sensitve = 'false') {
587
- $this->gawd_user_data = get_option('gawd_user_data');
588
- /* This request creates a new Goal. */
589
- // Construct the body of the request.
590
- $goal = new Google_Service_Analytics_Goal();
591
- $goal->setId($goal_max_id); //ID
592
- $goal->setActive(True); //ACTIVE/INACTIVE
593
- $goal->setType($gawd_goal_type); //URL_DESTINATION, VISIT_TIME_ON_SITE, VISIT_NUM_PAGES, AND EVENT
594
- $goal->setName($gawd_goal_name); //NAME
595
- // Construct the time on site details.
596
- if ($gawd_goal_type == 'VISIT_TIME_ON_SITE') {
597
- $details = new Google_Service_Analytics_GoalVisitTimeOnSiteDetails();
598
- $details->setComparisonType($gawd_goal_comparison); //VISIT_TIME_ON_SITE -------- LESS_THAN/ GREATER_THAN------
599
- $details->setComparisonValue($gawd_goal_value);
600
- $goal->setVisitTimeOnSiteDetails($details);
601
- } elseif ($gawd_goal_type == 'URL_DESTINATION') {
602
- if($url_case_sensitve != ''){
603
- $url_case_sensitve = true;
604
- }
605
- $details = new Google_Service_Analytics_GoalUrlDestinationDetails();
606
- $details->setCaseSensitive($url_case_sensitve);
607
- $details->setFirstStepRequired('false');
608
- $details->setMatchType($gawd_goal_comparison);
609
- $details->setUrl($gawd_goal_value);
610
- $goal->setUrlDestinationDetails($details);
611
- } elseif ($gawd_goal_type == 'VISIT_NUM_PAGES') {
612
- $details = new Google_Service_Analytics_GoalVisitNumPagesDetails();
613
- $details->setComparisonType($gawd_goal_comparison); //VISIT_TIME_ON_SITE -------- LESS_THAN/ GREATER_THAN------
614
- $details->setComparisonValue($gawd_goal_value);
615
- $goal->setVisitNumPagesDetails($details);
616
- } elseif ($gawd_goal_type == 'EVENT') {
617
- /* $details = new Google_Service_Analytics_GoalEventDetails();
618
- $details = new Google_Service_Analytics_GoalEventDetailsEventConditions();
619
- $detailssetComparisonType
620
- //$details->setEventConditions($gawd_goal_comparison);//VISIT_TIME_ON_SITE -------- LESS_THAN/ GREATER_THAN------
621
- //$details->setUseEventValue($gawd_goal_value); */
622
- $goal->setEventDetails($details);
623
- }
624
-
625
- //Set the time on site details.
626
- $this->analytics_member;
627
- $this->gawd_user_data = get_option('gawd_user_data');
628
- $accountId = $this->get_default_accountId();
629
- $webPropertyId = $this->get_default_webPropertyId();
630
- $profileId = $gawd_goal_profile;
631
- $analytics = $this->analytics_member;
632
- try {
633
- $analytics->management_goals->insert($accountId, $webPropertyId, $profileId, $goal);
634
- } catch (apiServiceException $e) {
635
- print 'There was an Analytics API service error '
636
- . $e->getCode() . ':' . $e->getMessage();
637
- } catch (apiException $e) {
638
- print 'There was a general API error '
639
- . $e->getCode() . ':' . $e->getMessage();
640
- }
641
- catch (Exception $e) {
642
- $error = array('error_message' => $e->getMessage());
643
- if (strpos($e->getMessage(), 'User does not have permission to perform this operation')) {
644
- $error['error_message'] = 'User does not have permission to perform this operation';
645
- }
646
- return json_encode($error);
647
- }
648
- }
649
-
650
- public function add_filter($name, $type, $value) {
651
- $this->gawd_user_data = get_option('gawd_user_data');
652
- $accountId = $this->get_profile_accountId();
653
- $profileId = $this->get_profile_id();
654
- $webPropertyId = $this->get_profile_webPropertyId();
655
- $analytics = $this->analytics_member;
656
- $condition = $type == 'GEO_IP_ADDRESS' ? 'EQUAL' : 'MATCHES';
657
- /**
658
- * Note: This code assumes you have an authorized Analytics service object.
659
- * See the Filters Developer Guide for details.
660
- */
661
- /**
662
- * This request creates a new filter.
663
- */
664
- try {
665
- // Construct the filter expression object.
666
- $details = new Google_Service_Analytics_FilterExpression();
667
- $details->setField($type);
668
- $details->setMatchType($type);
669
- $details->setExpressionValue($value);
670
- $details->setCaseSensitive(false);
671
- // Construct the filter and set the details.
672
- $filter = new Google_Service_Analytics_Filter();
673
- $filter->setName($name);
674
- $filter->setType("EXCLUDE");
675
- $filter->setExcludeDetails($details);
676
-
677
- $insertedFilter = $analytics->management_filters->insert($accountId, $filter);
678
- $analyticsFilterRef = new Google_Service_Analytics_FilterRef();
679
- $analyticsFilterRef->setId($insertedFilter->id);
680
- $filterData = new Google_Service_Analytics_ProfileFilterLink();
681
- $filterData->setFilterRef($analyticsFilterRef );
682
- // Add view to inserted filter
683
- $res = $analytics->management_profileFilterLinks->insert($accountId, $webPropertyId, $profileId, $filterData);
684
-
685
- } catch (apiServiceException $e) {
686
- print 'There was an Analytics API service error '
687
- . $e->getCode() . ':' . $e->getMessage();
688
- } catch (apiException $e) {
689
- print 'There was a general API error '
690
- . $e->getCode() . ':' . $e->getMessage();
691
- } catch (Exception $e) {
692
- echo '<script>window.location.href="' . admin_url() . 'admin.php?page=gawd_settings&errorMsg=1#gawd_filters_tab";</script>';
693
- }
694
- }
695
-
696
- public function get_country_data($metric, $dimension, $start_date, $end_date, $country_filter, $geo_type, $timezone) {
697
- $profileId = $this->get_profile_id();
698
- $analytics = $this->analytics_member;
699
- $metric = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration';
700
-
701
- try {
702
- $results = $analytics->data_ga->get(
703
- 'ga:' . $profileId, $start_date, $end_date, $metric, array(
704
- 'dimensions' => 'ga:' . $dimension,
705
- 'sort' => 'ga:' . $dimension,
706
- 'filters' => 'ga:' . $geo_type . '==' . $country_filter
707
- )
708
- );
709
- } catch (Exception $e) {
710
- $error = array('error_message' => 'Error');
711
- if (strpos($e->getMessage(), 'User does not have sufficient permissions for this profile')) {
712
- $error['error_message'] = 'User does not have sufficient permissions for this profile';
713
- }
714
- return json_encode($error);
715
- }
716
- $rows = $results->getRows();
717
- $metric = explode(',', $metric);
718
- if ($rows) {
719
- $data_sum = array();
720
- foreach($results->getTotalsForAllResults() as $key => $value){
721
- $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($key,3))))] = $value;
722
- }
723
- $j = 0;
724
- foreach ($rows as $row) {
725
- $data[$j] = array(
726
- ucfirst($dimension) => $row[0]
727
- );
728
- $data[$j]['No'] = floatval($j + 1);
729
- for ($i = 0; $i < count($metric); $i++) {
730
- $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = floatval($row[$i + 1]);
731
- }
732
- $j++;
733
- }
734
- } else {
735
- $empty[0] = array(
736
- trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => 0
737
- );
738
- $empty[0]['No'] = 1;
739
- for ($i = 0; $i < count($metric); $i++) {
740
- $empty[0][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
741
- }
742
-
743
- return json_encode($empty);
744
- }
745
- $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
746
- $result = $data;
747
- if ($data_sum != '') {
748
- $result = array('data_sum' => $data_sum, 'chart_data' => $data);
749
- }
750
- set_transient( 'gawd-country-'.$profileId.'-'.$country_filter.'-'.$start_date.'-'.$end_date, json_encode($result), $expiration );
751
- return json_encode($result);
752
- }
753
-
754
- public function get_post_page_data($metric, $dimension, $start_date, $end_date, $filter, $timezone, $chart) {
755
- $profileId = $this->get_profile_id();
756
- $analytics = $this->analytics_member;
757
- $metric = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration,ga:pageviewsPerSession';
758
- if($chart == 'pie'){
759
- $diff = date_diff(date_create($start_date),date_create($end_date));
760
- if(intval($diff->format("%a")) > 7){
761
- $dimension = 'week';
762
- }
763
- if(intval($diff->format("%a")) > 60){
764
- $dimension = 'month';
765
- }
766
- }
767
- // Get the results from the Core Reporting API and print the results.
768
- // Calls the Core Reporting API and queries for the number of sessions
769
- // for the last seven days.
770
-
771
- $filter_type = 'pagePath';
772
- $results = $analytics->data_ga->get(
773
- 'ga:' . $profileId, $start_date, $end_date, $metric, array(
774
- 'dimensions' => 'ga:' . $dimension,
775
- 'sort' => 'ga:' . $dimension,
776
- 'filters' => 'ga:' . $filter_type . '=~' . $filter
777
- )
778
- );
779
- $rows = $results->getRows();
780
- $metric = explode(',', $metric);
781
- if ($rows) {
782
- $j = 0;
783
- $data_sum = array();
784
- /*if ($dimension == 'week') {
785
- $date = $start_date;
786
- $_end_date = date("M d,Y", strtotime('next Saturday ' . $date));
787
- if (strtotime($end_date) > strtotime(date('Y-m-d'))) {
788
- $end_date = date("M d,Y");
789
- }
790
- foreach ($rows as $row) {
791
- if (strtotime($_end_date) <= strtotime(date('Y-m-d'))) {
792
-
793
- $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
794
- // echo $date;
795
- }
796
- else {
797
-
798
- if (strtotime($date) != strtotime($end_date)) {
799
- $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
800
- } else {
801
- break;
802
- }
803
- }
804
- $data[] = array(trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => $dimension_value);
805
- $data[$j]['No'] = floatval($j + 1);
806
- for ($i = 0; $i < count($metric); $i++) {
807
- $val = $i + 1;
808
- $metric_val = floatval($row[$val]);
809
- if(substr($metric[$i], 3) == 'bounceRate'){
810
- $metric_val = $metric_val;
811
- }
812
- $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
813
- }
814
- $j++;
815
- $date = date("M d,Y", strtotime('next Sunday ' . $_end_date));
816
- $_end_date = date("M d,Y", strtotime('next Saturday ' . $date));
817
- if (isset($_end_date) && (strtotime($_end_date) > strtotime($end_date))) {
818
- $_end_date = $end_date;
819
- }
820
- }
821
- }*/
822
- if ($dimension == 'week' || $dimension == 'month') {
823
- $date = $start_date;
824
- if ($dimension == 'week') {
825
- $_end_date = date("l", strtotime($date)) == 'Saturday' ? date("M d,Y", strtotime($date)) : date("M d,Y", strtotime('next Saturday ' . $date));
826
- }
827
- elseif ($dimension == 'month') {
828
- $_end_date = date("M t,Y", strtotime($date));
829
- if(strtotime($_end_date) > strtotime(date('Y-m-d'))){
830
- $_end_date = date("M d,Y",strtotime('-1 day ' . date('Y-m-d')));
831
- }
832
- }
833
- if (strtotime($end_date) > strtotime(date('Y-m-d'))) {
834
- $end_date = date("M d,Y");
835
- }
836
- foreach ($rows as $row) {
837
- if ($dimension == 'hour') {
838
- $dimension_value = date("M d,Y", strtotime($row[0])) . ' ' . $row[1] . ':00';
839
- }
840
- else {
841
- if (strtotime($_end_date) <= strtotime(date('Y-m-d'))) {
842
-
843
- $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
844
- // echo $date;
845
- } else {
846
- if ($dimension == 'month') {
847
- //continue;
848
- }
849
- if (strtotime($date) != strtotime($end_date) ) {
850
- $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
851
- } else {
852
- break;
853
- }
854
- }
855
- }
856
- $data[] = array(trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => $dimension_value);
857
- $data[$j]['No'] = floatval($j + 1);
858
- for ($i = 0; $i < count($metric); $i++) {
859
- $val = $i + 1;
860
- if ($dimension == 'hour') {
861
- $val = $i + 2;
862
- }
863
- $metric_val = floatval($row[$val]);
864
- if(substr($metric[$i], 3) == 'bounceRate'){
865
- $metric_val = $metric_val;
866
- }
867
- $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
868
- }
869
-
870
- $j++;
871
-
872
- if(isset($break) && $break){
873
- break;
874
- }
875
-
876
- if ($dimension == 'week') {
877
- $date = date("M d,Y", strtotime('next Sunday ' . $_end_date));
878
- $_end_date = date("M d,Y", strtotime('next Saturday ' . $date));
879
- } elseif ($dimension == 'month') {
880
- $date = date("M d,Y", strtotime('+1 day ' . $_end_date));
881
- $_end_date = date("M t,Y", strtotime($date));
882
- }
883
- if (isset($_end_date) && (strtotime($_end_date) > strtotime($end_date))) {
884
- $_end_date = date("M d,Y", strtotime($end_date));
885
- $break = true;
886
- }
887
- }
888
- }
889
- else{
890
- foreach ($rows as $row) {
891
-
892
- if ($dimension == 'date') {
893
- $row[0] = date('Y-m-d', strtotime($row[0]));
894
- }
895
- $data[$j] = array(
896
- $dimension => $row[0]
897
- );
898
- for ($i = 0; $i < count($metric); $i++) {
899
- $data[$j][substr($metric[$i], 3)] = floatval($row[$i + 1]);
900
- if (isset($data_sum[substr($metric[$i], 3)])) {
901
- $data_sum[substr($metric[$i], 3)] += floatval($row[$i + 1]);
902
- } else {
903
- if (substr($metric[$i], 3) != 'percentNewSessions' && substr($metric[$i], 3) != 'bounceRate') {
904
- $data_sum[substr($metric[$i], 3)] = floatval($row[$i + 1]);
905
- }
906
- }
907
- }
908
- $j++;
909
- }
910
- }
911
- $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
912
- if (isset($same_dimension) && $same_dimension != null) {
913
- $dimension = $same_dimension;
914
- }
915
- $result = array('data_sum' => $data_sum, 'chart_data' => $data);
916
- set_transient('gawd-page-post-' . $profileId . '-' . $filter . '-' . '-' . $dimension . '-' . $start_date . '-' . $end_date . '-' . $chart, json_encode($result), $expiration);
917
- return json_encode($result);
918
- } else {
919
- $empty[] = array(
920
- $dimension => 0,
921
- substr($metric[0], 3) => 0);
922
- return json_encode($empty);
923
- }
924
- }
925
-
926
- public function get_data($metric, $dimension, $start_date, $end_date, $filter_type, $timezone, $same_dimension = null) {
927
- $dimension = lcfirst($dimension);
928
-
929
- $metric = lcfirst($metric);
930
- $profileId = $this->get_profile_id();
931
- $analytics = $this->analytics_member;
932
- $selected_metric = $metric;
933
- if (strpos($selected_metric, 'ga:') > -1) {
934
- $selected_metric = substr($selected_metric,3);
935
- }
936
- if (strpos($metric, 'ga:') === false) {
937
- $metric = 'ga:' . $metric;
938
- }
939
- if ($dimension == 'interestInMarketCategory' || $dimension == 'interestAffinityCategory' || $dimension == 'interestOtherCategory' || $dimension == 'country' || $dimension == 'language' || $dimension == 'userType' || $dimension == 'sessionDurationBucket' || $dimension == 'userAgeBracket' || $dimension == 'userGender' || $dimension == 'mobileDeviceInfo' || $dimension == 'deviceCategory' || $dimension == 'operatingSystem' || $dimension == 'browser' || $dimension == 'date' || $dimension == "source") {
940
- $metrics = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration,ga:pageviewsPerSession';
941
-
942
- if (strpos($metrics, $metric) !== false) {
943
- $metric = $metrics;
944
- }
945
- }
946
- elseif ($dimension == 'siteSpeed') {
947
- $dimension = 'date';
948
- $metrics = 'ga:avgPageLoadTime,ga:avgRedirectionTime,ga:avgServerResponseTime,ga:avgPageDownloadTime';
949
- if (strpos($metrics, $metric) !== false) {
950
- $metric = $metrics;
951
- }
952
- }
953
- elseif ($dimension == 'eventLabel' || $dimension == 'eventAction' || $dimension == 'eventCategory') {
954
- $metrics = 'ga:eventsPerSessionWithEvent,ga:sessionsWithEvent,ga:avgEventValue,ga:eventValue,ga:uniqueEvents,ga:totalEvents';
955
- if (strpos($metrics, $metric) !== false) {
956
- $metric = $metrics;
957
- }
958
- }
959
-
960
- $dimension = $dimension == 'date' ? $filter_type != '' ? $filter_type : 'date' : $dimension;
961
- if ($same_dimension == 'sales_performance' && ($dimension == 'week' || $dimension == 'month' || $dimension == 'hour')) {
962
- $metrics = 'ga:transactionRevenue, ga:transactionsPerSession';
963
- if (strpos($metrics, $metric) !== false) {
964
- $metric = $metrics;
965
- }
966
- } elseif ($same_dimension == 'adsense' && ($dimension == 'week' || $dimension == 'month' || $dimension == 'hour')) {
967
- $metrics = 'ga:adsenseRevenue,ga:adsenseAdsClicks';
968
- if (strpos($metrics, $metric) !== false) {
969
- $metric = $metrics;
970
- }
971
- } elseif ($same_dimension == 'siteSpeed' && ($dimension == 'week' || $dimension == 'month' || $dimension == 'hour')) {
972
- $metrics = 'ga:avgPageLoadTime,ga:avgRedirectionTime,ga:avgServerResponseTime,ga:avgPageDownloadTime';
973
- if (strpos($metrics, $metric) !== false) {
974
- $metric = $metrics;
975
- }
976
- }
977
-
978
- if ($same_dimension == 'week' || $same_dimension == 'month' || $same_dimension == 'hour') {
979
- $metrics = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration';
980
- if (strpos($metrics, $metric) !== false) {
981
- $metric = $metrics;
982
- }
983
- }
984
-
985
- /* if(!is_array($metric)){
986
- if (strpos($metric, 'ga') === false) {
987
- $metric = 'ga:' . $metric;
988
- }
989
- } */
990
- // Get the results from the Core Reporting API and print the results.
991
- // Calls the Core Reporting API and queries for the number of sessions
992
- // for the last seven days.
993
- if ($dimension == 'hour') {
994
-
995
- $gawd_dimension = array(
996
- 'dimensions' => 'ga:date, ga:hour',
997
- 'sort' => 'ga:date',
998
- );
999
- }
1000
- else {
1001
- $gawd_dimension = array(
1002
- 'dimensions' => 'ga:' . $dimension,
1003
- 'sort' => '-ga:' . $selected_metric,
1004
- );
1005
- }
1006
-
1007
- try {
1008
- $results = $analytics->data_ga->get(
1009
- 'ga:' . $profileId, $start_date, $end_date, $metric, $gawd_dimension
1010
- );
1011
-
1012
- } catch (Exception $e) {
1013
- $error = array('error_message' => 'Error');
1014
- if (strpos($e->getMessage(), 'Selected dimensions and metrics cannot be queried together')) {
1015
- $error['error_message'] = 'Selected dimensions and metrics cannot be queried together';
1016
- } else if (strpos($e->getMessage(), 'User does not have sufficient permissions for this profile')) {
1017
- $error['error_message'] = 'User does not have sufficient permissions for this profile';
1018
- }
1019
- return json_encode($error);
1020
- }
1021
-
1022
- $metric = explode(',', $metric);
1023
- $rows = $results->getRows();
1024
- if ($rows) {
1025
-
1026
- $j = 0;
1027
- $data_sum = array();
1028
- foreach($results->getTotalsForAllResults() as $key => $value){
1029
- $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($key,3))))] = $value;
1030
- }
1031
-
1032
- if ($dimension == 'week' || $dimension == 'month' || $dimension == 'hour') {
1033
-
1034
- $date = $start_date;
1035
- if ($dimension == 'week') {
1036
- $_end_date = date("l", strtotime($date)) == 'Saturday' ? date("M d,Y", strtotime($date)) : date("M d,Y", strtotime('next Saturday ' . $date));
1037
- }
1038
- elseif ($dimension == 'month') {
1039
- $_end_date = date("M t,Y", strtotime($date));
1040
- if(strtotime($_end_date) > strtotime(date('Y-m-d'))){
1041
- $_end_date = date("M d,Y",strtotime('-1 day ' . date('Y-m-d')));
1042
- }
1043
- }
1044
- if (strtotime($end_date) > strtotime(date('Y-m-d'))) {
1045
- $end_date = date("M d,Y");
1046
- }
1047
- foreach ($rows as $row) {
1048
- if ($dimension == 'hour') {
1049
- $dimension_value = date("M d,Y", strtotime($row[0])) . ' ' . $row[1] . ':00';
1050
- }
1051
- else {
1052
- if (strtotime($_end_date) <= strtotime(date('Y-m-d'))) {
1053
-
1054
- $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
1055
- // echo $date;
1056
- } else {
1057
- if ($dimension == 'month') {
1058
- //continue;
1059
- }
1060
- if (strtotime($date) != strtotime($end_date) ) {
1061
- $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
1062
- } else {
1063
- break;
1064
- }
1065
- }
1066
- }
1067
- $data[] = array(trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => $dimension_value);
1068
- $data[$j]['No'] = floatval($j + 1);
1069
- for ($i = 0; $i < count($metric); $i++) {
1070
- $val = $i + 1;
1071
- if ($dimension == 'hour') {
1072
- $val = $i + 2;
1073
- }
1074
- $metric_val = floatval($row[$val]);
1075
- if(substr($metric[$i], 3) == 'bounceRate'){
1076
- $metric_val = $metric_val;
1077
- }
1078
- $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
1079
- }
1080
-
1081
- $j++;
1082
-
1083
- if(isset($break) && $break){
1084
- break;
1085
- }
1086
-
1087
- if ($dimension == 'week') {
1088
- $date = date("M d,Y", strtotime('next Sunday ' . $_end_date));
1089
- $_end_date = date("M d,Y", strtotime('next Saturday ' . $date));
1090
- } elseif ($dimension == 'month') {
1091
- $date = date("M d,Y", strtotime('+1 day ' . $_end_date));
1092
- $_end_date = date("M t,Y", strtotime($date));
1093
- }
1094
- if (isset($_end_date) && (strtotime($_end_date) > strtotime($end_date))) {
1095
- $_end_date = date("M d,Y", strtotime($end_date));
1096
- $break = true;
1097
- }
1098
- }
1099
- }
1100
- else {
1101
- foreach ($rows as $row) {
1102
- if (strtolower($dimension) == 'date') {
1103
- $row[0] = date('Y-m-d', strtotime($row[0]));
1104
- }
1105
- elseif(strtolower($dimension) == 'sessiondurationbucket'){
1106
- if($row[0] >= 0 && $row[0] <= 10){
1107
- $row[0] = '0-10';
1108
- }
1109
- elseif($row[0] >= 11 && $row[0] <= 30){
1110
- $row[0] = '11-30';
1111
- }
1112
- elseif($row[0] >= 31 && $row[0] <= 40){
1113
- $row[0] = '31-40';
1114
- }
1115
- elseif($row[0] >= 41 && $row[0] <= 60){
1116
- $row[0] = '41-60';
1117
- }
1118
- elseif($row[0] >= 61 && $row[0] <= 180){
1119
- $row[0] = '61-180';
1120
- }
1121
- elseif($row[0] >= 181 && $row[0] <= 600){
1122
- $row[0] = '181-600';
1123
- }
1124
- elseif($row[0] >= 601 && $row[0] <= 1800){
1125
- $row[0] = '601-1800';
1126
- }
1127
- elseif($row[0] >= 1801){
1128
- $row[0] = '1801';
1129
- }
1130
- }
1131
- elseif(strpos($dimension,'dimension') >-1){
1132
- $dimension_data = $this->get_custom_dimensions();
1133
- foreach($dimension_data as $key => $value){
1134
- if($dimension == substr($value['id'],3)){
1135
- $dimension = $value['name'];
1136
- }
1137
- }
1138
- }
1139
- $data[$j]['No'] = floatval($j + 1);
1140
- $dimension_data = ctype_digit($row[0]) ? intval($row[0]) : $row[0];
1141
- $dimension_data = strpos($dimension_data,'T') ? substr($dimension_data ,0,strpos($dimension_data,'T')) : $dimension_data;
1142
- $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension)))] = $dimension_data;
1143
-
1144
- for ($i = 0; $i < count($metric); $i++) {
1145
- $metric_val = floatval($row[$i + 1]);
1146
- if(substr($metric[$i], 3) == 'avgSessionDuration'){
1147
- $metric_val = ceil($row[$i + 1]);
1148
- }
1149
- $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
1150
- }
1151
- $j++;
1152
- }
1153
- }
1154
- $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
1155
- if (isset($same_dimension) && $same_dimension != null) {
1156
- $dimension = $filter_type == 'date' || $filter_type == '' ? $same_dimension : $same_dimension . '_' . $filter_type;
1157
- }
1158
- if($dimension == "daysToTransaction"){
1159
- foreach ($data as $key => $row) {
1160
- $daysToTransaction[$key] = $row['Days To Transaction'];
1161
- }
1162
- array_multisort($daysToTransaction, SORT_ASC, $data);
1163
- foreach($data as $j=>$val){
1164
- $val["No"] = ($j+1);
1165
- $data[$j] = $val;
1166
- }
1167
- }
1168
- elseif($dimension == "sessionDurationBucket"){
1169
- $_data = array();
1170
- //$j = 1;
1171
- foreach($data as $val){
1172
- if(isset($_data[$val["Session Duration Bucket"]])){
1173
- $_data[$val["Session Duration Bucket"]]["Users"] += floatval($val["Users"]);
1174
- $_data[$val["Session Duration Bucket"]]["Sessions"] += floatval($val["Sessions"]);
1175
- $_data[$val["Session Duration Bucket"]]["Percent New Sessions"] += floatval($val["Percent New Sessions"]);
1176
- $_data[$val["Session Duration Bucket"]]["Bounce Rate"] += floatval($val["Bounce Rate"]);
1177
- $_data[$val["Session Duration Bucket"]]["Pageviews"] += floatval($val["Pageviews"]);
1178
- $_data[$val["Session Duration Bucket"]]["Avg Session Duration"] += $val["Avg Session Duration"];
1179
- }
1180
- else{
1181
- // $val["No"] = $j;
1182
- // $j++;
1183
- $_data[$val["Session Duration Bucket"]] = $val;
1184
- $_data[$val["Session Duration Bucket"]]["order"] = intval($val["Session Duration Bucket"]);
1185
- }
1186
-
1187
-
1188
- }
1189
- $data = array_values($_data);
1190
- foreach ($data as $key => $row) {
1191
- $yyy[$key] = $row['order'];
1192
- }
1193
- array_multisort($yyy, SORT_ASC, $data);
1194
- foreach($data as $j=>$val){
1195
- $val["No"] = ($j+1);
1196
- $data[$j] = $val;
1197
- }
1198
- }
1199
- else{
1200
- if(strpos($dimension,'dimension') === false){
1201
- foreach ($data as $key => $row) {
1202
- $new_data[$key] = $row[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension)))];
1203
- }
1204
- array_multisort($new_data, SORT_ASC, $data);
1205
- foreach($data as $j=>$val){
1206
- $val["No"] = ($j+1);
1207
- $data[$j] = $val;
1208
- }
1209
- }
1210
- }
1211
- $result = $data;
1212
- if ($data_sum != '') {
1213
- $result = array('data_sum' => $data_sum, 'chart_data' => $data);
1214
- }
1215
- set_transient( 'gawd-'.$profileId.'-'.$dimension.'-'.$start_date.'-'.$end_date, json_encode($result), $expiration );
1216
- return json_encode($result);
1217
- }
1218
- else {
1219
- if(strpos($dimension,'dimension') >-1){
1220
- $dimension_data = $this->get_custom_dimensions();
1221
- foreach($dimension_data as $key => $value){
1222
- if($dimension == substr($value['id'],3)){
1223
- $dimension = $value['name'];
1224
- }
1225
- }
1226
- }
1227
- $empty[0] = array(
1228
- trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => 0
1229
- );
1230
- $empty[0]['No'] = 1;
1231
- for ($i = 0; $i < count($metric); $i++) {
1232
- $empty[0][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
1233
- }
1234
-
1235
- return json_encode(array('chart_data' => $empty));
1236
- }
1237
- }
1238
-
1239
- public function get_data_compact($metric, $dimension, $start_date, $end_date, $timezone) {
1240
- $profileId = $this->get_profile_id();
1241
- $metric_sort = $metric;
1242
- //var_dump($profileId);exit;
1243
- $analytics = $this->analytics_member;
1244
- // Get the results from the Core Reporting API and print the results.
1245
- // Calls the Core Reporting API and queries for the number of sessions
1246
- // for the last seven days.
1247
- if ($dimension == 'date') {
1248
- $metric = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration,ga:pageviewsPerSession';
1249
- }
1250
- $results = $analytics->data_ga->get(
1251
- 'ga:' . $profileId, $start_date, $end_date, $metric, array(
1252
- 'dimensions' => 'ga:' . $dimension,
1253
- 'sort' => 'ga:' . $dimension,
1254
- )
1255
- );
1256
- $rows = $results->getRows();
1257
- $metric = explode(',', $metric);
1258
- if ($rows) {
1259
- $j = 0;
1260
- $data_sum = array();
1261
- foreach($results->getTotalsForAllResults() as $key => $value){
1262
- $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($key,3))))] = $value;
1263
- }
1264
-
1265
- foreach ($rows as $row) {
1266
- if ($dimension == 'date') {
1267
- $row[0] = date('Y-m-d', strtotime($row[0]));
1268
- }
1269
- $data[$j] = array(
1270
- trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => $row[0]
1271
- );
1272
- for ($i = 0; $i < count($metric); $i++) {
1273
- $metric_val = floatval($row[$i + 1]);
1274
-
1275
- $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
1276
- }
1277
- $j++;
1278
- }
1279
- if($dimension == "country"){
1280
- foreach ($data as $key => $row) {
1281
- $country[$key] = $row[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric_sort, 3))))];
1282
- }
1283
- array_multisort($country, SORT_DESC, $data);
1284
- foreach($data as $j=>$val){
1285
- $val["No"] = ($j+1);
1286
- $data[$j] = $val;
1287
- }
1288
- }
1289
- }
1290
- else {
1291
- $data_sum = array();
1292
- $empty[0] = array(
1293
- trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => 0
1294
- );
1295
- $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension)))] = 0;
1296
- $empty[0]['No'] = 1;
1297
- for ($i = 0; $i < count($metric); $i++) {
1298
- $empty[0][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
1299
- $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
1300
- }
1301
- $result = array('data_sum' => $data_sum, 'chart_data' => $empty);
1302
- return json_encode($result);
1303
- }
1304
- if ($data_sum != '') {
1305
- $result = array('data_sum' => $data_sum, 'chart_data' => $data);
1306
- }
1307
- $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
1308
- set_transient('gawd-compact-' . $profileId . '-' . $dimension . '-' . $start_date . '-' . $end_date, json_encode($result), $expiration);
1309
- return json_encode($result);
1310
- }
1311
-
1312
- public function get_data_alert($metric, $dimension, $start_date, $end_date, $gawd_alert_view) {
1313
- $profileId = $gawd_alert_view == '' ? $this->get_profile_id() : $gawd_alert_view;
1314
- $analytics = $this->analytics_member;
1315
- // Get the results from the Core Reporting API and print the results.
1316
- // Calls the Core Reporting API and queries for the number of sessions
1317
- // for the last seven days.
1318
- $results = $analytics->data_ga->get(
1319
- 'ga:' . $profileId, $start_date, $end_date, $metric, array(
1320
- 'dimensions' => 'ga:' . $dimension,
1321
- 'sort' => 'ga:' . $dimension,
1322
- )
1323
- );
1324
- $rows = $results->getRows();
1325
-
1326
- $data = '';
1327
- foreach ($rows as $row) {
1328
- $data += floatval($row[1]);
1329
- }
1330
- return ($data);
1331
- }
1332
-
1333
- public function get_profile_id() {
1334
- $this->gawd_user_data = get_option('gawd_user_data');
1335
- $profiles_light = get_transient('gawd_user_profiles') ? get_transient('gawd_user_profiles') : $this->gawd_user_data['gawd_profiles'];
1336
- if (!isset($this->gawd_user_data['gawd_id']) || $this->gawd_user_data['gawd_id'] == '') {
1337
- if (!empty($profiles_light)) {
1338
- $first_profile = reset($profiles_light)[0];
1339
- $this->gawd_user_data['gawd_id'] = $first_profile['id'];
1340
- }
1341
- }
1342
- return $this->gawd_user_data['gawd_id'];
1343
- }
1344
-
1345
- public function get_profile_webPropertyId() {
1346
- $this->gawd_user_data = get_option('gawd_user_data');
1347
- return $this->gawd_user_data['webPropertyId'];
1348
- }
1349
-
1350
- public function get_profile_accountId() {
1351
- $this->gawd_user_data = get_option('gawd_user_data');
1352
- return isset($this->gawd_user_data['accountId']) ? $this->gawd_user_data['accountId'] : '';
1353
- }
1354
-
1355
- public function get_default_webPropertyId() {
1356
- $this->gawd_user_data = get_option('gawd_user_data');
1357
- return $this->gawd_user_data['default_webPropertyId'];
1358
- }
1359
-
1360
- public function get_default_accountId() {
1361
- $this->gawd_user_data = get_option('gawd_user_data');
1362
- return $this->gawd_user_data['default_accountId'];
1363
- }
1364
-
1365
- public function get_page_data($dimension, $start_date, $end_date, $timezone) {
1366
- $analytics = $this->analytics_member;
1367
- $profileId = $this->get_profile_id();
1368
- $metric = $dimension == 'pagePath' || $dimension == 'PagePath' ? 'ga:pageviews,ga:uniquePageviews,ga:avgTimeOnPage,ga:entrances,ga:bounceRate,ga:exitRate,ga:pageValue,ga:avgPageLoadTime' : 'ga:sessions,ga:percentNewSessions,ga:newUsers,ga:bounceRate,ga:pageviewsPerSession,ga:avgSessionDuration,ga:transactions,ga:transactionRevenue,ga:transactionsPerSession';
1369
- $sort = '-'.explode(',', $metric)[0];
1370
-
1371
- try {
1372
- $results = $analytics->data_ga->get(
1373
- 'ga:' . $profileId, $start_date, $end_date, $metric, array(
1374
- 'dimensions' => 'ga:'.$dimension,
1375
- 'sort' => $sort,
1376
- )
1377
- );
1378
- } catch (Exception $e) {
1379
-
1380
- $error = array('error_message' => 'Error');
1381
- if (strpos($e->getMessage(), 'User does not have sufficient permissions for this profile')) {
1382
- $error['error_message'] = 'User does not have sufficient permissions for this profile';
1383
- }
1384
- return json_encode($error);
1385
- }
1386
- $rows = $results->getRows();
1387
- $metric = explode(',', $metric);
1388
- if ($rows) {
1389
- $data_sum = array();
1390
- foreach($results->getTotalsForAllResults() as $key => $value){
1391
- $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($key,3))))] = $value;
1392
- }
1393
- foreach ($rows as $key => $row) {
1394
- $hours = strlen(floor($row[3] / 3600)) < 2 ? '0' . floor($row[3] / 3600) : floor($row[3] / 3600);
1395
- $mins = strlen(floor($row[3] / 60 % 60)) < 2 ? '0' . floor($row[3] / 60 % 60) : floor($row[3] / 60 % 60);
1396
- $secs = strlen(floor($row[3] % 60)) < 2 ? '0' . floor($row[3] % 60) : floor($row[3] % 60);
1397
- $time_on_page = $hours.':'.$mins.':'.$secs;
1398
- if($dimension == 'pagePath' || $dimension == 'PagePath'){
1399
- $data[] = array(
1400
- 'No' => floatval($key + 1),
1401
- 'Page Path' => $row[0],
1402
- 'Pageviews' => intval($row[1]),
1403
- 'Unique Pageviews' => intval($row[2]),
1404
- 'Avg Time On Page' => $time_on_page,
1405
- 'Entrances' => intval($row[4]),
1406
- 'Bounce Rate' => floatval($row[5]),
1407
- 'Exit Rate' => intval($row[6]),
1408
- 'Page Value' => intval($row[7]),
1409
- 'Avg Page Load Time' => intval($row[8])
1410
- );
1411
- }
1412
- else{
1413
- $data[] = array(
1414
- 'No' => floatval($key + 1),
1415
- 'Landing Page' => $row[0],
1416
- 'Sessions' => intval($row[1]),
1417
- 'Percent New Sessions' => intval($row[2]),
1418
- 'New Users' => intval($row[3]),
1419
- 'Bounce Rate' => intval($row[4]),
1420
- 'Pageviews Per Session' => floatval($row[5]),
1421
- 'Avg Session Duration' => intval($row[6]),
1422
- 'Transactions' => intval($row[7]),
1423
- 'Transaction Revenue' => intval($row[8]),
1424
- 'Transactions Per Session' => intval($row[9])
1425
- );
1426
- }
1427
- }
1428
-
1429
- }
1430
- else {
1431
- $empty[0] = array(
1432
- trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => 0
1433
- );
1434
- $empty[0]['No'] = 1;
1435
- for ($i = 0; $i < count($metric); $i++) {
1436
- $empty[0][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
1437
- $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i],3))))] = 0;
1438
- }
1439
-
1440
- return json_encode(array('data_sum' => $data_sum, 'chart_data' => $empty));
1441
- }
1442
- if ($data_sum != '') {
1443
- $result = array('data_sum' => $data_sum, 'chart_data' => $data);
1444
- }
1445
- $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
1446
- set_transient('gawd-' . $profileId . '-' . $dimension . '-' . $start_date . '-' . $end_date, json_encode($result), $expiration);
1447
- return json_encode($result);
1448
- }
1449
-
1450
- public function get_goal_data($dimension, $start_date, $end_date, $timezone, $same_dimension) {
1451
- $goals = $this->get_management_goals();
1452
- if ('no_goals_exist' != $goals) {
1453
- $analytics = $this->analytics_member;
1454
- $profileId = $this->get_profile_id();
1455
- $metric = array();
1456
- $all_metric = '';
1457
- $counter = 1;
1458
- foreach ($goals as $goal) {
1459
- $all_metric .= 'ga:goal' . $goal['id'] . 'Completions,';
1460
- if($counter <= 10){
1461
- $metrics[0][] = 'ga:goal' . $goal['id'] . 'Completions';
1462
- }
1463
- else{
1464
- $metrics[1][] = 'ga:goal' . $goal['id'] . 'Completions';
1465
- }
1466
- $counter++;
1467
- }
1468
- $rows = array();
1469
- foreach($metrics as $metric){
1470
- $metric = implode(',',$metric);
1471
- $results = $analytics->data_ga->get(
1472
- 'ga:' . $profileId, $start_date, $end_date, $metric, array(
1473
- 'dimensions' => 'ga:' . $dimension,
1474
- 'sort' => 'ga:' . $dimension,
1475
- )
1476
- );
1477
-
1478
- $temp_rows = $results->getRows();
1479
- if(empty($temp_rows)){
1480
- continue;
1481
- }
1482
-
1483
- foreach($temp_rows as $key=>$value){
1484
- if(!isset($rows[$key])){
1485
- $rows[$key] = $value;
1486
- }
1487
- else{
1488
- unset($value[0]);
1489
- $rows[$key] = array_merge($rows[$key],$value);
1490
- }
1491
- }
1492
-
1493
- }
1494
- $all_metric = explode(',', $all_metric);
1495
- if ($rows) {
1496
- $j = 0;
1497
- $data_sum = array();
1498
- foreach ($rows as $row) {
1499
- if ($dimension == 'date') {
1500
- $row[0] = date('Y-m-d', strtotime($row[0]));
1501
- }
1502
- $data[$j] = array(
1503
- preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))))=> $row[0]
1504
- );
1505
- $data[$j]['No'] = floatval($j + 1);
1506
- for ($i = 0; $i < count($goals); $i++) {
1507
- $data[$j][preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $goals[$i]['name']))))] = floatval($row[$i + 1]);
1508
- if (isset($data_sum[preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $goals[$i]['name']))))])) {
1509
- $data_sum[preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $goals[$i]['name']))))] += floatval($row[$i + 1]);
1510
- } else {
1511
- if (substr($all_metric[$i], 3) != 'percentNewSessions' && substr($all_metric[$i], 3) != 'bounceRate') {
1512
- $data_sum[preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $goals[$i]['name']))))] = floatval($row[$i + 1]);
1513
- }
1514
- }
1515
- }
1516
- $j++;
1517
- }
1518
- $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
1519
- if (isset($same_dimension) && $same_dimension != null) {
1520
- $dimension = $same_dimension;
1521
- }
1522
- $result = $data;
1523
- if ($data_sum != '') {
1524
- $result = array('data_sum' => $data_sum, 'chart_data' => $data);
1525
- }
1526
- set_transient('gawd-' . $profileId . '-' . $dimension . '-' . $start_date . '-' . $end_date, json_encode($result), $expiration);
1527
- return json_encode($result);
1528
- } else {
1529
- return $goals;
1530
- }
1531
- } else {
1532
- return json_encode(array('error_message' => 'No goals exist'));
1533
- }
1534
- }
1535
-
1536
- public function gawd_realtime_data() {
1537
- $analytics = $this->analytics_member;
1538
- $profileId = $this->get_profile_id();
1539
- $metrics = 'rt:activeUsers';
1540
- $dimensions = 'rt:pagePath,rt:source,rt:keyword,rt:trafficType,rt:country,rt:pageTitle,rt:deviceCategory';
1541
- $managequota = 'u' . get_current_user_id() . 's' . get_current_blog_id();
1542
-
1543
- try {
1544
- $data = $analytics->data_realtime->get('ga:' . $profileId, $metrics, array('dimensions' => $dimensions, 'quotaUser' => $managequota . 'p' . $profileId));
1545
- } catch (Exception $e) {
1546
- $error = array('error_message' => 'Error');
1547
- if (strpos($e->getMessage(), 'User does not have sufficient permissions for this profile')) {
1548
- $error['error_message'] = 'User does not have sufficient permissions for this profile';
1549
- }
1550
- return json_encode($error);
1551
- }
1552
- $expiration = 5 ;
1553
- if ($data->getRows() != '') {
1554
- $i = 0;
1555
- $gawd_data = $data;
1556
- foreach ($data->getRows() as $row) {
1557
- $gawd_data[$i] = $row;
1558
- $i++;
1559
- }
1560
- set_transient('gawd-real-' . $profileId, json_encode($gawd_data), $expiration);
1561
- echo json_encode($gawd_data);
1562
- wp_die();
1563
- }
1564
- else {
1565
- return 0;
1566
- }
1567
- }
1568
-
1569
- public static function get_instance() {
1570
- if (null === static::$instance) {
1571
- static::$instance = new static();
1572
- }
1573
- return static::$instance;
1574
- }
1575
-
1576
- }
1577
-
1578
- ?>
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ require_once(GAWD_DIR . '/google/autoload.php');
4
+
5
+ class GAWD_google_client {
6
+
7
+ private static $instance;
8
+ private $google_client;
9
+ public $analytics_member;
10
+ private $gawd_user_data;
11
+
12
+ protected function __construct() {
13
+ $this->gawd_user_data = get_option('gawd_user_data');
14
+ try{
15
+ $this->google_client = new Google_Client();
16
+ $this->set_google_client();
17
+ $this->analytics_member = new Google_Service_Analytics($this->google_client);
18
+
19
+ }catch(Google_Service_Exception $e){
20
+
21
+ return $e->getErrors()[0]["message"];
22
+ }catch(Exception $e){
23
+ return $e->getMessage();
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Sets the google class member.
29
+ */
30
+ private function set_google_client() {
31
+
32
+ $access_token = $this->gawd_user_data['access_token'];
33
+ $this->google_client->setAccessToken($access_token);
34
+
35
+ if ($this->google_client->isAccessTokenExpired()) {
36
+ $refresh_token = $this->gawd_user_data['refresh_token'];
37
+
38
+ $this->google_client->setClientId(GAWD::get_instance()->get_project_client_id());
39
+ $this->google_client->setClientSecret(GAWD::get_instance()->get_project_client_secret());
40
+ $this->google_client->setRedirectUri(GAWD::get_instance()->redirect_uri);
41
+ // $this->google_client->setAuthConfigFile(GAWD_DIR . '/client_secrets.json');
42
+ $this->google_client->refreshToken($refresh_token);
43
+ }
44
+ }
45
+
46
+ public static function create_authentication_url() {
47
+ $client = new Google_Client();
48
+ // $client->setAuthConfigFile(GAWD_DIR . '/client_secrets.json');
49
+ $client->setClientId(GAWD::get_instance()->get_project_client_id());
50
+ $client->setClientSecret(GAWD::get_instance()->get_project_client_secret());
51
+ $client->setRedirectUri(GAWD::get_instance()->redirect_uri);
52
+ $client->addScope(array(Google_Service_Analytics::ANALYTICS_EDIT, Google_Service_Analytics::ANALYTICS_READONLY));
53
+ $client->setApprovalPrompt('force');
54
+ $client->setAccessType('offline');
55
+ return "'" . $client->createAuthUrl() . "'";
56
+ }
57
+
58
+ public static function authenticate($code) {
59
+
60
+ $client = new Google_Client();
61
+ // $client->setAuthConfigFile(GAWD_DIR . '/client_secrets.json');
62
+ $client->setClientId(GAWD::get_instance()->get_project_client_id());
63
+ $client->setClientSecret(GAWD::get_instance()->get_project_client_secret());
64
+ $client->setRedirectUri(GAWD::get_instance()->redirect_uri);
65
+ try {
66
+ $client->authenticate($code);
67
+
68
+ if ($client->isAccessTokenExpired()) {
69
+ return false;
70
+ }
71
+ else {
72
+ $access_token = $client->getAccessToken();
73
+ $refresh_token = $client->getRefreshToken();
74
+ update_option('gawd_user_data', array(
75
+ 'access_token' => $access_token,
76
+ 'refresh_token' => $refresh_token
77
+ )
78
+ );
79
+
80
+ $gawd_client = self::get_instance();
81
+ delete_transient('gawd_user_profiles');
82
+ $profiles = $gawd_client->get_profiles();
83
+
84
+ if ($profiles instanceof Google_Service_Exception) {
85
+
86
+ delete_option('gawd_user_data');
87
+
88
+ return $profiles->getErrors()[0]["message"];
89
+ }
90
+
91
+
92
+ update_option('gawd_user_data', array(
93
+ 'access_token' => $access_token,
94
+ 'refresh_token' => $refresh_token,
95
+ 'gawd_profiles' => $profiles,
96
+ )
97
+ );
98
+ return true;
99
+ }
100
+ } catch (Google_Service_Exception $e) {
101
+ delete_option('gawd_user_data');
102
+ return $e->getErrors()[0]["message"];
103
+ } catch (Exception $e) {
104
+ return $e->getMessage();
105
+ }
106
+ }
107
+
108
+ public function get_management_accounts() {
109
+ $accounts_light = array();
110
+ try{
111
+ $accounts = $this->analytics_member->management_accounts->listManagementAccounts()->getItems();
112
+
113
+ foreach ($accounts as $account) {
114
+ $edit_flag = FALSE;
115
+ $permissions = $account['modelData']['permissions']['effective'];
116
+ foreach ($permissions as $permission) {
117
+ if ($permission == 'EDIT') {
118
+ $edit_flag = TRUE;
119
+ }
120
+ }
121
+ $accounts_light[] = array(
122
+ 'name' => $account['name'],
123
+ 'id' => $account['id'],
124
+ 'edit_permissions' => $edit_flag
125
+ );
126
+ /*if ($edit_flag == TRUE) {
127
+ $accounts_light[] = array(
128
+ 'name' => $account['name'],
129
+ 'id' => $account['id']
130
+ );
131
+ }*/
132
+ }
133
+ }catch (Google_Service_Exception $e) {
134
+ //return $e->getErrors()[0]["message"];
135
+ } catch (Exception $e) {
136
+ //return $e->getMessage();
137
+ }
138
+ return $accounts_light;
139
+ }
140
+
141
+ public function property_exists() {
142
+ try{
143
+ $web_properties = $this->analytics_member->management_webproperties->listManagementWebproperties('~all')->getItems();
144
+ }catch(Google_Service_Exception $e){
145
+ return 'no_matches';
146
+
147
+ }catch(Exception $e){
148
+ return 'no_matches';
149
+ }
150
+ $exact_properties = array();
151
+ $site_url = get_site_url() . '/';
152
+
153
+ foreach ($web_properties as $web_property) {
154
+ $current_url = $web_property['websiteUrl'];
155
+ if (($current_url == $site_url) || (($current_url . '/') == $site_url)) {
156
+ $exact_properties[] = $web_property;
157
+ }
158
+ }
159
+ if (!empty($exact_properties)) {
160
+ return $exact_properties;
161
+ } else {
162
+ return 'no_matches';
163
+ }
164
+ }
165
+
166
+ public function get_default_profiles() {
167
+ $gawd_user_data = get_option('gawd_user_data');
168
+ $accountId = $this->get_default_accountId();
169
+ $webPropertyId = $this->get_default_webPropertyId();
170
+ $webProperty = $this->analytics_member->management_webproperties->get($accountId, $webPropertyId);
171
+ $webPropertyName = $webProperty['name'];
172
+ $profiles = $this->analytics_member->management_profiles->listManagementProfiles($accountId, $webPropertyId)->getItems();
173
+ $profiles_light = array();
174
+ foreach ($profiles as $profile) {
175
+ $profiles_light[] = array(
176
+ 'id' => $profile['id'],
177
+ 'name' => $profile['name'],
178
+ 'webPropertyName' => $webPropertyName
179
+ );
180
+ }
181
+ return $profiles_light;
182
+ }
183
+
184
+ public function add_webproperty($accountId, $name) {
185
+
186
+ $analytics = $this->analytics_member;
187
+ $websiteUrl = get_site_url();
188
+ try {
189
+ $property = new Google_Service_Analytics_Webproperty();
190
+ $property->setName($name);
191
+ $property->setWebsiteUrl($websiteUrl);
192
+ $analytics->management_webproperties->insert($accountId, $property);
193
+ } catch (apiServiceException $e) {
194
+ print 'There was an Analytics API service error '
195
+ . $e->getCode() . ':' . $e->getMessage();
196
+ } catch (apiException $e) {
197
+ print 'There was a general API error '
198
+ . $e->getCode() . ':' . $e->getMessage();
199
+ }
200
+ catch (Google_Service_Exception $e) {
201
+ return 'There was a general API error '
202
+ . $e->getCode() . ':' . $e->getMessage();
203
+ }catch (Exception $e) {
204
+ echo $e->getCode() . ':' . $e->getMessage();
205
+ }
206
+
207
+ $web_properties = $this->analytics_member->management_webproperties->listManagementWebproperties($accountId)->getItems();
208
+
209
+ foreach ($web_properties as $web_property) {
210
+ if ($web_property['name'] == $name) {
211
+ $profile = new Google_Service_Analytics_Profile();
212
+ $profile->setName('All Web Site Data');
213
+ try {
214
+ $analytics->management_profiles->insert($accountId, $web_property['id'], $profile);
215
+ } catch (apiServiceException $e) {
216
+ print 'There was an Analytics API service error '
217
+ . $e->getCode() . ':' . $e->getMessage();
218
+ } catch (apiException $e) {
219
+ print 'There was a general API error '
220
+ . $e->getCode() . ':' . $e->getMessage();
221
+ }
222
+ }
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Get all the managment profiles of the authenticated user.
228
+ *
229
+ * @return array
230
+ */
231
+ public function get_profiles() {
232
+ $profiles_light = get_transient('gawd_user_profiles') ? get_transient('gawd_user_profiles') : '';
233
+ if ($profiles_light && $profiles_light != ''){
234
+ return $profiles_light;
235
+ }
236
+ $profiles_light = array();
237
+ $gawd_user_data = get_option('gawd_user_data');
238
+ try{
239
+
240
+ $web_properties = $this->analytics_member->management_webproperties->listManagementWebproperties('~all')->getItems();
241
+ $profiles = $this->analytics_member->management_profiles->listManagementProfiles('~all', '~all')->getItems();
242
+ $profiles_count = count($profiles);
243
+ $web_properties_count = count($web_properties);
244
+ for ($i = 0; $i < $web_properties_count; $i++) {
245
+ for ($j = 0; $j < $profiles_count; $j++) {
246
+ if ($web_properties[$i]['id'] == $profiles[$j]['webPropertyId']) {
247
+ $profiles_light[$web_properties[$i]['name']][] = array(
248
+ 'id' => $profiles[$j]['id'],
249
+ 'name' => $profiles[$j]['name'],
250
+ 'webPropertyId' => $profiles[$j]['webPropertyId'],
251
+ 'websiteUrl' => $profiles[$j]['websiteUrl'],
252
+ 'accountId' => $profiles[$j]['accountId']
253
+ );
254
+ }
255
+ }
256
+ }
257
+ if (!isset($gawd_user_data['gawd_id']) || $gawd_user_data['gawd_id'] == '' || $gawd_user_data['gawd_id'] == NULL) {
258
+ if (!empty($profiles_light)) {
259
+ $first_profile = reset($profiles_light)[0];
260
+ $gawd_user_data['gawd_id'] = $first_profile['id'];
261
+ $gawd_user_data['webPropertyId'] = $first_profile['webPropertyId'];
262
+ $gawd_user_data['accountId'] = $first_profile['accountId'];
263
+ $gawd_user_data['web_property_name'] = $web_properties[0]['name'];
264
+ }
265
+ }
266
+
267
+ $gawd_user_data['gawd_profiles'] = $profiles_light;
268
+ update_option('gawd_user_data', $gawd_user_data);
269
+ set_transient('gawd_user_profiles',$profiles_light, 60);
270
+ return $profiles_light;
271
+ }catch(Google_Service_Exception $e){
272
+ return $e;
273
+ }catch(Exception $e){
274
+ return $e;
275
+ }
276
+ }
277
+
278
+ public function get_custom_dimensions($default = '') {
279
+ $this->gawd_user_data = get_option('gawd_user_data');
280
+ if ($default == 'default') {
281
+ $webPropertyId = $this->get_default_webPropertyId();
282
+ $accountId = $this->get_default_accountId();
283
+ }
284
+ else {
285
+ $webPropertyId = $this->get_profile_webPropertyId();
286
+ $accountId = $this->get_profile_accountId();
287
+ $transient = get_transient('gawd-custom-dimensions-' . $webPropertyId);
288
+ if ($transient) {
289
+ if ($transient != 'no_custom_dimensions_exist') {
290
+ return json_decode($transient, true);
291
+ } else {
292
+ return $transient;
293
+ }
294
+ }
295
+ }
296
+
297
+ $all_dimensions = $this->analytics_member->management_customDimensions->listManagementCustomDimensions($accountId, $webPropertyId)->getItems();
298
+ if (0 == sizeof($all_dimensions)) {
299
+ if ($default == 'default') {
300
+ update_option('gawd_custom_dimensions', "no_custom_dimensions_exist");
301
+ }
302
+ set_transient('gawd-custom-dimensions-' . $webPropertyId, "no_custom_dimensions_exist", 12 * HOUR_IN_SECONDS);
303
+ return "no_custom_dimensions_exist";
304
+ }
305
+ else {
306
+ foreach ($all_dimensions as $dimension) {
307
+ $dimensions_light[] = array(
308
+ 'name' => $dimension['name'],
309
+ 'id' => $dimension['id']
310
+ );
311
+ }
312
+ $supported_dimensions = array("Logged in", "Post type", "Author", "Category", "Tags", "Published Month", "Published Year");
313
+ $dimensions = array();
314
+ foreach ($dimensions_light as $dimension) {
315
+ foreach ($supported_dimensions as $supported_dimension) {
316
+ if (trim(strtolower($dimension['name'])) == strtolower($supported_dimension)) {
317
+ $dimension['name'] = $supported_dimension;
318
+ $dimension['id'] = substr($dimension['id'], -1);
319
+ $dimensions[] = $dimension;
320
+ }
321
+ }
322
+ }
323
+ if ($default == 'default') {
324
+ update_option('gawd_custom_dimensions', $dimensions);
325
+ }
326
+ set_transient('gawd-custom-dimensions-' . $webPropertyId, json_encode($dimensions_light), 12 * HOUR_IN_SECONDS);
327
+ return $dimensions_light;
328
+ }
329
+ }
330
+
331
+ public function get_custom_dimensions_tracking() {
332
+ $all_dimensions = get_option('gawd_custom_dimensions');
333
+ if ($all_dimensions) {
334
+ return $all_dimensions;
335
+ }
336
+ $all_dimensions = $this->get_custom_dimensions('default');
337
+ if ($all_dimensions == 'no_custom_dimensions_exist') {
338
+ return 'no_custom_dimensions_exist';
339
+ }
340
+ $supported_dimensions = array("Logged in", "Post type", "Author", "Category", "Tags", "Published Month", "Published Year");
341
+ $dimensions = array();
342
+ foreach ($all_dimensions as $dimension) {
343
+ foreach ($supported_dimensions as $supported_dimension) {
344
+ if (trim(strtolower($dimension['name'])) == strtolower($supported_dimension)) {
345
+ $dimension['id'] = substr($dimension['id'], -1);
346
+ $dimension['name'] = $supported_dimension;
347
+ $dimensions[] = $dimension;
348
+ }
349
+ }
350
+ }
351
+ update_option('gawd_custom_dimensions', $dimensions);
352
+ if ($dimensions) {
353
+ return $dimensions;
354
+ } else {
355
+ return "no_custom_dimensions_exist";
356
+ }
357
+ }
358
+
359
+ public static function gawd_cd_logged_in() {
360
+ $value = var_export(is_user_logged_in(), true);
361
+ $value = $value == 'true' ? 'yes' : 'no';
362
+ return $value;
363
+ }
364
+
365
+ public static function gawd_cd_post_type() {
366
+ if (is_singular()) {
367
+ $post_type = get_post_type(get_the_ID());
368
+
369
+ if ($post_type) {
370
+ return $post_type;
371
+ }
372
+ }
373
+ }
374
+
375
+ public static function gawd_cd_author() {
376
+ if (is_singular()) {
377
+ if (have_posts()) {
378
+ while (have_posts()) {
379
+ the_post();
380
+ }
381
+ }
382
+ $name = get_the_author_meta('user_nicename');
383
+ $value = trim($name);
384
+ return $value;
385
+ }
386
+ }
387
+
388
+ public static function gawd_cd_category() {
389
+ if (is_single()) {
390
+ $categories = get_the_category(get_the_ID());
391
+
392
+ if ($categories) {
393
+ foreach ($categories as $category) {
394
+ $category_names[] = $category->slug;
395
+ }
396
+
397
+ return implode(',', $category_names);
398
+ }
399
+ }
400
+ }
401
+
402
+ public static function gawd_cd_tags() {
403
+ if (is_single()) {
404
+ $tag_names = 'untagged';
405
+
406
+ $tags = get_the_tags(get_the_ID());
407
+
408
+ if ($tags) {
409
+ $tag_names = implode(',', wp_list_pluck($tags, 'name'));
410
+ }
411
+
412
+ return $tag_names;
413
+ }
414
+ }
415
+
416
+
417
+ public static function gawd_cd_published_month() {
418
+ if (is_singular()) {
419
+ return get_the_date('M-Y');
420
+ }
421
+ }
422
+ public static function gawd_cd_published_year() {
423
+ if (is_singular()) {
424
+ return get_the_date('Y');
425
+ }
426
+ }
427
+
428
+ public function get_management_filters() {
429
+ $analytics = $this->analytics_member;
430
+ $this->gawd_user_data = get_option('gawd_user_data');
431
+ $accountId = $this->get_profile_accountId();
432
+ $profileId = $this->get_profile_id();
433
+ $webPropertyId = $this->get_profile_webPropertyId();
434
+
435
+ try {
436
+ $view_filters = $analytics->management_profileFilterLinks->listManagementProfileFilterLinks($accountId, $webPropertyId, $profileId);
437
+ $filters = $view_filters->getItems();
438
+ foreach ($filters as $filter) {
439
+ $filter_info = $analytics->management_filters->get($accountId,$filter['modelData']['filterRef']['id']);
440
+ $all_filters[] = array(
441
+ 'name' => $filter['modelData']['filterRef']['name'],
442
+ 'id' => $filter['modelData']['filterRef']['id'],
443
+ 'type' => $filter_info['excludeDetails']['field'],
444
+ 'value' => $filter_info['excludeDetails']['expressionValue'],
445
+ 'view' => $filter['modelData']['profileRef']['name']
446
+ );
447
+ }
448
+ if (isset($all_filters)) {
449
+ return $all_filters;
450
+ }
451
+ } catch (Exception $e) {
452
+ $error = array('error_message' => 'Error');
453
+ if (strpos($e->getMessage(), 'User does not have sufficient permissions for this ')) {
454
+ $error['error_message'] = 'User does not have sufficient permissions for this profile';
455
+ }
456
+ return json_encode($error);
457
+ }
458
+ }
459
+
460
+ public function get_management_goals() {
461
+ $this->gawd_user_data = get_option('gawd_user_data');
462
+ $profileId = $this->get_profile_id();
463
+ $accountId = $this->get_profile_accountId();
464
+ $webPropertyId = $this->get_profile_webPropertyId();
465
+ $goals = array();
466
+ try {
467
+ $goals = $this->analytics_member->management_goals->listManagementGoals($accountId, $webPropertyId, $profileId)->getItems();
468
+ } catch (Exception $e) {
469
+
470
+ }
471
+ if (0 == sizeof($goals)) {
472
+ return "no_goals_exist";
473
+ } else {
474
+ foreach ($goals as $goal) {
475
+ $goals_light[] = array(
476
+ 'name' => $goal['name'],
477
+ 'id' => $goal['id']
478
+ );
479
+ }
480
+ return $goals_light;
481
+ }
482
+ }
483
+
484
+ public function get_default_goals() {
485
+ $this->gawd_user_data = get_option('gawd_user_data');
486
+ $accountId = $this->get_default_accountId();
487
+ $webPropertyId = $this->get_default_webPropertyId();
488
+ $goals = array();
489
+ try {
490
+ $goals = $this->analytics_member->management_goals->listManagementGoals($accountId, $webPropertyId, '~all')->getItems();
491
+ } catch (Exception $e) {
492
+
493
+ }
494
+ if (0 == sizeof($goals)) {
495
+ return "no_goals_exist";
496
+ } else {
497
+ $profiles = array();
498
+ foreach ($goals as $goal) {
499
+ $flag = false;
500
+ foreach ($profiles as $profile) {
501
+ if ($profile == $goal['profileId']) {
502
+ $flag = true;
503
+ }
504
+ }
505
+ if ($flag == false) {
506
+ $profiles[] = $goal['profileId'];
507
+ }
508
+ }
509
+ $goals_light = array();
510
+ $caseSensitive = '';
511
+ foreach ($profiles as $profile) {
512
+ foreach ($goals as $goal) {
513
+ if ($goal['profileId'] == $profile) {
514
+ if($goal['type'] == 'URL_DESTINATION'){
515
+ $type = 'Destination';
516
+ if($goal["modelData"]['urlDestinationDetails']['matchType'] == 'EXACT'){
517
+ $match_type = 'Equals';
518
+ }
519
+ elseif($goal["modelData"]['urlDestinationDetails']['matchType'] == 'HEAD'){
520
+ $match_type = 'Begin with';
521
+ }
522
+ else{
523
+ $match_type = 'Regular expresion';
524
+ }
525
+ $value = $goal["modelData"]['urlDestinationDetails']['url'];
526
+ $caseSensitive = $goal["modelData"]['urlDestinationDetails']['caseSensitive'];
527
+ }
528
+ elseif($goal['type'] == 'VISIT_TIME_ON_SITE'){
529
+ $type = 'Duration';
530
+ if($goal["modelData"]['visitTimeOnSiteDetails']['comparisonType'] == 'GREATER_THAN'){
531
+ $match_type = 'Greater than';
532
+ }
533
+ $value = $goal["modelData"]['visitTimeOnSiteDetails']['comparisonValue'];
534
+ $hours = strlen(floor($value / 3600)) < 2 ? '0' . floor($value / 3600) : floor($value / 3600);
535
+ $mins = strlen(floor($value / 60 % 60)) < 2 ? '0' . floor($value / 60 % 60) : floor($value / 60 % 60);
536
+ $secs = strlen(floor($value % 60)) < 2 ? '0' . floor($value % 60) : floor($value % 60);
537
+ $value = $hours.':'.$mins.':'.$secs;
538
+ }
539
+ else{
540
+ $type = 'Pages/Screens per session';
541
+ if($goal["modelData"]['visitNumPagesDetails']['comparisonType'] == 'GREATER_THAN'){
542
+ $match_type = 'Greater than';
543
+ }
544
+ $value = $goal["modelData"]['visitNumPagesDetails']['comparisonValue'];
545
+ }
546
+
547
+ $goals_light[$profile][] = array(
548
+ 'name' => $goal['name'],
549
+ 'id' => $goal['id'],
550
+ 'type' => $type,
551
+ 'match_type' => $match_type,
552
+ 'profileID' => $goal['profileId'],
553
+ 'caseSensitive' => $caseSensitive,
554
+ 'value' => $value,
555
+ );
556
+ }
557
+ }
558
+ }
559
+ return $goals_light;
560
+ }
561
+ }
562
+
563
+ public function add_custom_dimension($name, $id) {
564
+
565
+ $custom_dimension = new Google_Service_Analytics_CustomDimension();
566
+ $custom_dimension->setId($id);
567
+ $custom_dimension->setActive(TRUE);
568
+ $custom_dimension->setScope('Hit');
569
+ $custom_dimension->setName($name);
570
+
571
+ $accountId = $this->get_default_accountId();
572
+ $webPropertyId = $this->get_default_webPropertyId();
573
+ $analytics = $this->analytics_member;
574
+ delete_transient('gawd-custom-dimensions-' . $webPropertyId);
575
+ try {
576
+ $analytics->management_customDimensions->insert($accountId, $webPropertyId, $custom_dimension);
577
+ } catch (apiServiceException $e) {
578
+ print 'There was an Analytics API service error '
579
+ . $e->getCode() . ':' . $e->getMessage();
580
+ } catch (apiException $e) {
581
+ print 'There was a general API error '
582
+ . $e->getCode() . ':' . $e->getMessage();
583
+ }
584
+ }
585
+
586
+ public function add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_comparison = "GREATER_THAN", $gawd_goal_value, $url_case_sensitve = 'false') {
587
+ $this->gawd_user_data = get_option('gawd_user_data');
588
+ /* This request creates a new Goal. */
589
+ // Construct the body of the request.
590
+ $goal = new Google_Service_Analytics_Goal();
591
+ $goal->setId($goal_max_id); //ID
592
+ $goal->setActive(True); //ACTIVE/INACTIVE
593
+ $goal->setType($gawd_goal_type); //URL_DESTINATION, VISIT_TIME_ON_SITE, VISIT_NUM_PAGES, AND EVENT
594
+ $goal->setName($gawd_goal_name); //NAME
595
+ // Construct the time on site details.
596
+ if ($gawd_goal_type == 'VISIT_TIME_ON_SITE') {
597
+ $details = new Google_Service_Analytics_GoalVisitTimeOnSiteDetails();
598
+ $details->setComparisonType($gawd_goal_comparison); //VISIT_TIME_ON_SITE -------- LESS_THAN/ GREATER_THAN------
599
+ $details->setComparisonValue($gawd_goal_value);
600
+ $goal->setVisitTimeOnSiteDetails($details);
601
+ } elseif ($gawd_goal_type == 'URL_DESTINATION') {
602
+ if($url_case_sensitve != ''){
603
+ $url_case_sensitve = true;
604
+ }
605
+ $details = new Google_Service_Analytics_GoalUrlDestinationDetails();
606
+ $details->setCaseSensitive($url_case_sensitve);
607
+ $details->setFirstStepRequired('false');
608
+ $details->setMatchType($gawd_goal_comparison);
609
+ $details->setUrl($gawd_goal_value);
610
+ $goal->setUrlDestinationDetails($details);
611
+ } elseif ($gawd_goal_type == 'VISIT_NUM_PAGES') {
612
+ $details = new Google_Service_Analytics_GoalVisitNumPagesDetails();
613
+ $details->setComparisonType($gawd_goal_comparison); //VISIT_TIME_ON_SITE -------- LESS_THAN/ GREATER_THAN------
614
+ $details->setComparisonValue($gawd_goal_value);
615
+ $goal->setVisitNumPagesDetails($details);
616
+ } elseif ($gawd_goal_type == 'EVENT') {
617
+ /* $details = new Google_Service_Analytics_GoalEventDetails();
618
+ $details = new Google_Service_Analytics_GoalEventDetailsEventConditions();
619
+ $detailssetComparisonType
620
+ //$details->setEventConditions($gawd_goal_comparison);//VISIT_TIME_ON_SITE -------- LESS_THAN/ GREATER_THAN------
621
+ //$details->setUseEventValue($gawd_goal_value); */
622
+ $goal->setEventDetails($details);
623
+ }
624
+
625
+ //Set the time on site details.
626
+ $this->analytics_member;
627
+ $this->gawd_user_data = get_option('gawd_user_data');
628
+ $accountId = $this->get_default_accountId();
629
+ $webPropertyId = $this->get_default_webPropertyId();
630
+ $profileId = $gawd_goal_profile;
631
+ $analytics = $this->analytics_member;
632
+ try {
633
+ $analytics->management_goals->insert($accountId, $webPropertyId, $profileId, $goal);
634
+ } catch (apiServiceException $e) {
635
+ print 'There was an Analytics API service error '
636
+ . $e->getCode() . ':' . $e->getMessage();
637
+ } catch (apiException $e) {
638
+ print 'There was a general API error '
639
+ . $e->getCode() . ':' . $e->getMessage();
640
+ }
641
+ catch (Exception $e) {
642
+ $error = array('error_message' => $e->getMessage());
643
+ if (strpos($e->getMessage(), 'User does not have permission to perform this operation')) {
644
+ $error['error_message'] = 'User does not have permission to perform this operation';
645
+ }
646
+ return json_encode($error);
647
+ }
648
+ }
649
+
650
+ public function add_filter($name, $type, $value) {
651
+ $this->gawd_user_data = get_option('gawd_user_data');
652
+ $accountId = $this->get_profile_accountId();
653
+ $profileId = $this->get_profile_id();
654
+ $webPropertyId = $this->get_profile_webPropertyId();
655
+ $analytics = $this->analytics_member;
656
+ $condition = $type == 'GEO_IP_ADDRESS' ? 'EQUAL' : 'MATCHES';
657
+ /**
658
+ * Note: This code assumes you have an authorized Analytics service object.
659
+ * See the Filters Developer Guide for details.
660
+ */
661
+ /**
662
+ * This request creates a new filter.
663
+ */
664
+ try {
665
+ // Construct the filter expression object.
666
+ $details = new Google_Service_Analytics_FilterExpression();
667
+ $details->setField($type);
668
+ $details->setMatchType($type);
669
+ $details->setExpressionValue($value);
670
+ $details->setCaseSensitive(false);
671
+ // Construct the filter and set the details.
672
+ $filter = new Google_Service_Analytics_Filter();
673
+ $filter->setName($name);
674
+ $filter->setType("EXCLUDE");
675
+ $filter->setExcludeDetails($details);
676
+
677
+ $insertedFilter = $analytics->management_filters->insert($accountId, $filter);
678
+ $analyticsFilterRef = new Google_Service_Analytics_FilterRef();
679
+ $analyticsFilterRef->setId($insertedFilter->id);
680
+ $filterData = new Google_Service_Analytics_ProfileFilterLink();
681
+ $filterData->setFilterRef($analyticsFilterRef );
682
+ // Add view to inserted filter
683
+ $res = $analytics->management_profileFilterLinks->insert($accountId, $webPropertyId, $profileId, $filterData);
684
+
685
+ } catch (apiServiceException $e) {
686
+ print 'There was an Analytics API service error '
687
+ . $e->getCode() . ':' . $e->getMessage();
688
+ } catch (apiException $e) {
689
+ print 'There was a general API error '
690
+ . $e->getCode() . ':' . $e->getMessage();
691
+ } catch (Exception $e) {
692
+ echo '<script>window.location.href="' . admin_url() . 'admin.php?page=gawd_settings&errorMsg=1#gawd_filters_tab";</script>';
693
+ }
694
+ }
695
+
696
+ public function get_country_data($metric, $dimension, $start_date, $end_date, $country_filter, $geo_type, $timezone) {
697
+ $profileId = $this->get_profile_id();
698
+ $analytics = $this->analytics_member;
699
+ $metric = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration';
700
+
701
+ try {
702
+ $results = $analytics->data_ga->get(
703
+ 'ga:' . $profileId, $start_date, $end_date, $metric, array(
704
+ 'dimensions' => 'ga:' . $dimension,
705
+ 'sort' => 'ga:' . $dimension,
706
+ 'filters' => 'ga:' . $geo_type . '==' . $country_filter
707
+ )
708
+ );
709
+ } catch (Exception $e) {
710
+ $error = array('error_message' => 'Error');
711
+ if (strpos($e->getMessage(), 'User does not have sufficient permissions for this profile')) {
712
+ $error['error_message'] = 'User does not have sufficient permissions for this profile';
713
+ }
714
+ return json_encode($error);
715
+ }
716
+ $rows = $results->getRows();
717
+ $metric = explode(',', $metric);
718
+ if ($rows) {
719
+ $data_sum = array();
720
+ foreach($results->getTotalsForAllResults() as $key => $value){
721
+ $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($key,3))))] = $value;
722
+ }
723
+ $j = 0;
724
+ foreach ($rows as $row) {
725
+ $data[$j] = array(
726
+ ucfirst($dimension) => $row[0]
727
+ );
728
+ $data[$j]['No'] = floatval($j + 1);
729
+ for ($i = 0; $i < count($metric); $i++) {
730
+ $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = floatval($row[$i + 1]);
731
+ }
732
+ $j++;
733
+ }
734
+ } else {
735
+ $empty[0] = array(
736
+ trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => 0
737
+ );
738
+ $empty[0]['No'] = 1;
739
+ for ($i = 0; $i < count($metric); $i++) {
740
+ $empty[0][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
741
+ }
742
+
743
+ return json_encode($empty);
744
+ }
745
+ $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
746
+ $result = $data;
747
+ if ($data_sum != '') {
748
+ $result = array('data_sum' => $data_sum, 'chart_data' => $data);
749
+ }
750
+ set_transient( 'gawd-country-'.$profileId.'-'.$country_filter.'-'.$start_date.'-'.$end_date, json_encode($result), $expiration );
751
+ return json_encode($result);
752
+ }
753
+
754
+ public function get_post_page_data($metric, $dimension, $start_date, $end_date, $filter, $timezone, $chart) {
755
+ $profileId = $this->get_profile_id();
756
+ $analytics = $this->analytics_member;
757
+ $metric = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration,ga:pageviewsPerSession';
758
+ if($chart == 'pie'){
759
+ $diff = date_diff(date_create($start_date),date_create($end_date));
760
+ if(intval($diff->format("%a")) > 7){
761
+ $dimension = 'week';
762
+ }
763
+ if(intval($diff->format("%a")) > 60){
764
+ $dimension = 'month';
765
+ }
766
+ }
767
+ // Get the results from the Core Reporting API and print the results.
768
+ // Calls the Core Reporting API and queries for the number of sessions
769
+ // for the last seven days.
770
+
771
+ $filter_type = 'pagePath';
772
+ $results = $analytics->data_ga->get(
773
+ 'ga:' . $profileId, $start_date, $end_date, $metric, array(
774
+ 'dimensions' => 'ga:' . $dimension,
775
+ 'sort' => 'ga:' . $dimension,
776
+ 'filters' => 'ga:' . $filter_type . '=~' . $filter
777
+ )
778
+ );
779
+ $rows = $results->getRows();
780
+ $metric = explode(',', $metric);
781
+ if ($rows) {
782
+ $j = 0;
783
+ $data_sum = array();
784
+ /*if ($dimension == 'week') {
785
+ $date = $start_date;
786
+ $_end_date = date("M d,Y", strtotime('next Saturday ' . $date));
787
+ if (strtotime($end_date) > strtotime(date('Y-m-d'))) {
788
+ $end_date = date("M d,Y");
789
+ }
790
+ foreach ($rows as $row) {
791
+ if (strtotime($_end_date) <= strtotime(date('Y-m-d'))) {
792
+
793
+ $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
794
+ // echo $date;
795
+ }
796
+ else {
797
+
798
+ if (strtotime($date) != strtotime($end_date)) {
799
+ $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
800
+ } else {
801
+ break;
802
+ }
803
+ }
804
+ $data[] = array(trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => $dimension_value);
805
+ $data[$j]['No'] = floatval($j + 1);
806
+ for ($i = 0; $i < count($metric); $i++) {
807
+ $val = $i + 1;
808
+ $metric_val = floatval($row[$val]);
809
+ if(substr($metric[$i], 3) == 'bounceRate'){
810
+ $metric_val = $metric_val;
811
+ }
812
+ $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
813
+ }
814
+ $j++;
815
+ $date = date("M d,Y", strtotime('next Sunday ' . $_end_date));
816
+ $_end_date = date("M d,Y", strtotime('next Saturday ' . $date));
817
+ if (isset($_end_date) && (strtotime($_end_date) > strtotime($end_date))) {
818
+ $_end_date = $end_date;
819
+ }
820
+ }
821
+ }*/
822
+ if ($dimension == 'week' || $dimension == 'month') {
823
+ $date = $start_date;
824
+ if ($dimension == 'week') {
825
+ $_end_date = date("l", strtotime($date)) == 'Saturday' ? date("M d,Y", strtotime($date)) : date("M d,Y", strtotime('next Saturday ' . $date));
826
+ }
827
+ elseif ($dimension == 'month') {
828
+ $_end_date = date("M t,Y", strtotime($date));
829
+ if(strtotime($_end_date) > strtotime(date('Y-m-d'))){
830
+ $_end_date = date("M d,Y",strtotime('-1 day ' . date('Y-m-d')));
831
+ }
832
+ }
833
+ if (strtotime($end_date) > strtotime(date('Y-m-d'))) {
834
+ $end_date = date("M d,Y");
835
+ }
836
+ foreach ($rows as $row) {
837
+ if ($dimension == 'hour') {
838
+ $dimension_value = date("M d,Y", strtotime($row[0])) . ' ' . $row[1] . ':00';
839
+ }
840
+ else {
841
+ if (strtotime($_end_date) <= strtotime(date('Y-m-d'))) {
842
+
843
+ $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
844
+ // echo $date;
845
+ } else {
846
+ if ($dimension == 'month') {
847
+ //continue;
848
+ }
849
+ if (strtotime($date) != strtotime($end_date) ) {
850
+ $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
851
+ } else {
852
+ break;
853
+ }
854
+ }
855
+ }
856
+ $data[] = array(trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => $dimension_value);
857
+ $data[$j]['No'] = floatval($j + 1);
858
+ for ($i = 0; $i < count($metric); $i++) {
859
+ $val = $i + 1;
860
+ if ($dimension == 'hour') {
861
+ $val = $i + 2;
862
+ }
863
+ $metric_val = floatval($row[$val]);
864
+ if(substr($metric[$i], 3) == 'bounceRate'){
865
+ $metric_val = $metric_val;
866
+ }
867
+ $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
868
+ }
869
+
870
+ $j++;
871
+
872
+ if(isset($break) && $break){
873
+ break;
874
+ }
875
+
876
+ if ($dimension == 'week') {
877
+ $date = date("M d,Y", strtotime('next Sunday ' . $_end_date));
878
+ $_end_date = date("M d,Y", strtotime('next Saturday ' . $date));
879
+ } elseif ($dimension == 'month') {
880
+ $date = date("M d,Y", strtotime('+1 day ' . $_end_date));
881
+ $_end_date = date("M t,Y", strtotime($date));
882
+ }
883
+ if (isset($_end_date) && (strtotime($_end_date) > strtotime($end_date))) {
884
+ $_end_date = date("M d,Y", strtotime($end_date));
885
+ $break = true;
886
+ }
887
+ }
888
+ }
889
+ else{
890
+ foreach ($rows as $row) {
891
+
892
+ if ($dimension == 'date') {
893
+ $row[0] = date('Y-m-d', strtotime($row[0]));
894
+ }
895
+ $data[$j] = array(
896
+ $dimension => $row[0]
897
+ );
898
+ for ($i = 0; $i < count($metric); $i++) {
899
+ $data[$j][substr($metric[$i], 3)] = floatval($row[$i + 1]);
900
+ if (isset($data_sum[substr($metric[$i], 3)])) {
901
+ $data_sum[substr($metric[$i], 3)] += floatval($row[$i + 1]);
902
+ } else {
903
+ if (substr($metric[$i], 3) != 'percentNewSessions' && substr($metric[$i], 3) != 'bounceRate') {
904
+ $data_sum[substr($metric[$i], 3)] = floatval($row[$i + 1]);
905
+ }
906
+ }
907
+ }
908
+ $j++;
909
+ }
910
+ }
911
+ $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
912
+ if (isset($same_dimension) && $same_dimension != null) {
913
+ $dimension = $same_dimension;
914
+ }
915
+ $result = array('data_sum' => $data_sum, 'chart_data' => $data);
916
+ set_transient('gawd-page-post-' . $profileId . '-' . $filter . '-' . '-' . $dimension . '-' . $start_date . '-' . $end_date . '-' . $chart, json_encode($result), $expiration);
917
+ return json_encode($result);
918
+ } else {
919
+ $empty[] = array(
920
+ $dimension => 0,
921
+ substr($metric[0], 3) => 0);
922
+ return json_encode($empty);
923
+ }
924
+ }
925
+
926
+ public function get_data($metric, $dimension, $start_date, $end_date, $filter_type, $timezone, $same_dimension = null) {
927
+ $dimension = lcfirst($dimension);
928
+
929
+ $metric = lcfirst($metric);
930
+ $profileId = $this->get_profile_id();
931
+ $analytics = $this->analytics_member;
932
+ $selected_metric = $metric;
933
+ if (strpos($selected_metric, 'ga:') > -1) {
934
+ $selected_metric = substr($selected_metric,3);
935
+ }
936
+ if (strpos($metric, 'ga:') === false) {
937
+ $metric = 'ga:' . $metric;
938
+ }
939
+ if ($dimension == 'interestInMarketCategory' || $dimension == 'interestAffinityCategory' || $dimension == 'interestOtherCategory' || $dimension == 'country' || $dimension == 'language' || $dimension == 'userType' || $dimension == 'sessionDurationBucket' || $dimension == 'userAgeBracket' || $dimension == 'userGender' || $dimension == 'mobileDeviceInfo' || $dimension == 'deviceCategory' || $dimension == 'operatingSystem' || $dimension == 'browser' || $dimension == 'date' || $dimension == "source") {
940
+ $metrics = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration,ga:pageviewsPerSession';
941
+
942
+ if (strpos($metrics, $metric) !== false) {
943
+ $metric = $metrics;
944
+ }
945
+ }
946
+ elseif ($dimension == 'siteSpeed') {
947
+ $dimension = 'date';
948
+ $metrics = 'ga:avgPageLoadTime,ga:avgRedirectionTime,ga:avgServerResponseTime,ga:avgPageDownloadTime';
949
+ if (strpos($metrics, $metric) !== false) {
950
+ $metric = $metrics;
951
+ }
952
+ }
953
+ elseif ($dimension == 'eventLabel' || $dimension == 'eventAction' || $dimension == 'eventCategory') {
954
+ $metrics = 'ga:eventsPerSessionWithEvent,ga:sessionsWithEvent,ga:avgEventValue,ga:eventValue,ga:uniqueEvents,ga:totalEvents';
955
+ if (strpos($metrics, $metric) !== false) {
956
+ $metric = $metrics;
957
+ }
958
+ }
959
+
960
+ $dimension = $dimension == 'date' ? $filter_type != '' ? $filter_type : 'date' : $dimension;
961
+ if ($same_dimension == 'sales_performance' && ($dimension == 'week' || $dimension == 'month' || $dimension == 'hour')) {
962
+ $metrics = 'ga:transactionRevenue, ga:transactionsPerSession';
963
+ if (strpos($metrics, $metric) !== false) {
964
+ $metric = $metrics;
965
+ }
966
+ } elseif ($same_dimension == 'adsense' && ($dimension == 'week' || $dimension == 'month' || $dimension == 'hour')) {
967
+ $metrics = 'ga:adsenseRevenue,ga:adsenseAdsClicks';
968
+ if (strpos($metrics, $metric) !== false) {
969
+ $metric = $metrics;
970
+ }
971
+ } elseif ($same_dimension == 'siteSpeed' && ($dimension == 'week' || $dimension == 'month' || $dimension == 'hour')) {
972
+ $metrics = 'ga:avgPageLoadTime,ga:avgRedirectionTime,ga:avgServerResponseTime,ga:avgPageDownloadTime';
973
+ if (strpos($metrics, $metric) !== false) {
974
+ $metric = $metrics;
975
+ }
976
+ }
977
+
978
+ if ($same_dimension == 'week' || $same_dimension == 'month' || $same_dimension == 'hour') {
979
+ $metrics = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration';
980
+ if (strpos($metrics, $metric) !== false) {
981
+ $metric = $metrics;
982
+ }
983
+ }
984
+
985
+ /* if(!is_array($metric)){
986
+ if (strpos($metric, 'ga') === false) {
987
+ $metric = 'ga:' . $metric;
988
+ }
989
+ } */
990
+ // Get the results from the Core Reporting API and print the results.
991
+ // Calls the Core Reporting API and queries for the number of sessions
992
+ // for the last seven days.
993
+ if ($dimension == 'hour') {
994
+
995
+ $gawd_dimension = array(
996
+ 'dimensions' => 'ga:date, ga:hour',
997
+ 'sort' => 'ga:date',
998
+ );
999
+ }
1000
+ else {
1001
+ if($dimension != 'sessionDurationBucket'){
1002
+ $gawd_dimension = array(
1003
+ 'dimensions' => 'ga:' . $dimension,
1004
+ 'sort' => '-ga:' . $selected_metric,
1005
+ );
1006
+ }
1007
+ else{
1008
+ $gawd_dimension = array(
1009
+ 'dimensions' => 'ga:' . $dimension,
1010
+ 'sort' => 'ga:' . $dimension,
1011
+ );
1012
+ }
1013
+ }
1014
+
1015
+ try {
1016
+ $results = $analytics->data_ga->get(
1017
+ 'ga:' . $profileId, $start_date, $end_date, $metric, $gawd_dimension
1018
+ );
1019
+
1020
+ } catch (Exception $e) {
1021
+ $error = array('error_message' => 'Error');
1022
+ if (strpos($e->getMessage(), 'Selected dimensions and metrics cannot be queried together')) {
1023
+ $error['error_message'] = 'Selected dimensions and metrics cannot be queried together';
1024
+ } else if (strpos($e->getMessage(), 'User does not have sufficient permissions for this profile')) {
1025
+ $error['error_message'] = 'User does not have sufficient permissions for this profile';
1026
+ }
1027
+ return json_encode($error);
1028
+ }
1029
+
1030
+ $metric = explode(',', $metric);
1031
+ $rows = $results->getRows();
1032
+ if ($rows) {
1033
+
1034
+ $j = 0;
1035
+ $data_sum = array();
1036
+ foreach($results->getTotalsForAllResults() as $key => $value){
1037
+ $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($key,3))))] = $value;
1038
+ }
1039
+
1040
+ if ($dimension == 'week' || $dimension == 'month' || $dimension == 'hour') {
1041
+
1042
+ $date = $start_date;
1043
+ if ($dimension == 'week') {
1044
+ $_end_date = date("l", strtotime($date)) == 'Saturday' ? date("M d,Y", strtotime($date)) : date("M d,Y", strtotime('next Saturday ' . $date));
1045
+ }
1046
+ elseif ($dimension == 'month') {
1047
+ $_end_date = date("M t,Y", strtotime($date));
1048
+ if(strtotime($_end_date) > strtotime(date('Y-m-d'))){
1049
+ $_end_date = date("M d,Y",strtotime('-1 day ' . date('Y-m-d')));
1050
+ }
1051
+ }
1052
+ if (strtotime($end_date) > strtotime(date('Y-m-d'))) {
1053
+ $end_date = date("M d,Y");
1054
+ }
1055
+ foreach ($rows as $row) {
1056
+ if ($dimension == 'hour') {
1057
+ $dimension_value = date("M d,Y", strtotime($row[0])) . ' ' . $row[1] . ':00';
1058
+ }
1059
+ else {
1060
+ if (strtotime($_end_date) <= strtotime(date('Y-m-d'))) {
1061
+
1062
+ $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
1063
+ // echo $date;
1064
+ } else {
1065
+ if ($dimension == 'month') {
1066
+ //continue;
1067
+ }
1068
+ if (strtotime($date) != strtotime($end_date) ) {
1069
+ $dimension_value = date("M d,Y", strtotime($date)) . '-' . $_end_date;
1070
+ } else {
1071
+ break;
1072
+ }
1073
+ }
1074
+ }
1075
+ $data[] = array(trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => $dimension_value);
1076
+ $data[$j]['No'] = floatval($j + 1);
1077
+ for ($i = 0; $i < count($metric); $i++) {
1078
+ $val = $i + 1;
1079
+ if ($dimension == 'hour') {
1080
+ $val = $i + 2;
1081
+ }
1082
+ $metric_val = floatval($row[$val]);
1083
+ if(substr($metric[$i], 3) == 'bounceRate'){
1084
+ $metric_val = $metric_val;
1085
+ }
1086
+ $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
1087
+ }
1088
+
1089
+ $j++;
1090
+
1091
+ if(isset($break) && $break){
1092
+ break;
1093
+ }
1094
+
1095
+ if ($dimension == 'week') {
1096
+ $date = date("M d,Y", strtotime('next Sunday ' . $_end_date));
1097
+ $_end_date = date("M d,Y", strtotime('next Saturday ' . $date));
1098
+ } elseif ($dimension == 'month') {
1099
+ $date = date("M d,Y", strtotime('+1 day ' . $_end_date));
1100
+ $_end_date = date("M t,Y", strtotime($date));
1101
+ }
1102
+ if (isset($_end_date) && (strtotime($_end_date) > strtotime($end_date))) {
1103
+ $_end_date = date("M d,Y", strtotime($end_date));
1104
+ $break = true;
1105
+ }
1106
+ }
1107
+ }
1108
+ else {
1109
+ foreach ($rows as $row) {
1110
+ if (strtolower($dimension) == 'date') {
1111
+ $row[0] = date('Y-m-d', strtotime($row[0]));
1112
+ }
1113
+ elseif(strtolower($dimension) == 'sessiondurationbucket'){
1114
+ if($row[0] >= 0 && $row[0] <= 10){
1115
+ $row[0] = '0-10';
1116
+ }
1117
+ elseif($row[0] >= 11 && $row[0] <= 30){
1118
+ $row[0] = '11-30';
1119
+ }
1120
+ elseif($row[0] >= 31 && $row[0] <= 40){
1121
+ $row[0] = '31-40';
1122
+ }
1123
+ elseif($row[0] >= 41 && $row[0] <= 60){
1124
+ $row[0] = '41-60';
1125
+ }
1126
+ elseif($row[0] >= 61 && $row[0] <= 180){
1127
+ $row[0] = '61-180';
1128
+ }
1129
+ elseif($row[0] >= 181 && $row[0] <= 600){
1130
+ $row[0] = '181-600';
1131
+ }
1132
+ elseif($row[0] >= 601 && $row[0] <= 1800){
1133
+ $row[0] = '601-1800';
1134
+ }
1135
+ elseif($row[0] >= 1801){
1136
+ $row[0] = '1801';
1137
+ }
1138
+ }
1139
+ elseif(strpos($dimension,'dimension') >-1){
1140
+ $dimension_data = $this->get_custom_dimensions();
1141
+ foreach($dimension_data as $key => $value){
1142
+ if($dimension == substr($value['id'],3)){
1143
+ $dimension = $value['name'];
1144
+ }
1145
+ }
1146
+ }
1147
+ $data[$j]['No'] = floatval($j + 1);
1148
+ $dimension_data = ctype_digit($row[0]) ? intval($row[0]) : $row[0];
1149
+ $dimension_data = strpos($dimension_data,'T') ? substr($dimension_data ,0,strpos($dimension_data,'T')) : $dimension_data;
1150
+ $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension)))] = $dimension_data;
1151
+
1152
+ for ($i = 0; $i < count($metric); $i++) {
1153
+ $metric_val = floatval($row[$i + 1]);
1154
+ if(substr($metric[$i], 3) == 'avgSessionDuration'){
1155
+ $metric_val = ceil($row[$i + 1]);
1156
+ }
1157
+ $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
1158
+ }
1159
+ $j++;
1160
+ }
1161
+ }
1162
+ $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
1163
+ if (isset($same_dimension) && $same_dimension != null) {
1164
+ $dimension = $filter_type == 'date' || $filter_type == '' ? $same_dimension : $same_dimension . '_' . $filter_type;
1165
+ }
1166
+ if($dimension == "daysToTransaction"){
1167
+ foreach ($data as $key => $row) {
1168
+ $daysToTransaction[$key] = $row['Days To Transaction'];
1169
+ }
1170
+ array_multisort($daysToTransaction, SORT_ASC, $data);
1171
+ foreach($data as $j=>$val){
1172
+ $val["No"] = ($j+1);
1173
+ $data[$j] = $val;
1174
+ }
1175
+ }
1176
+ elseif($dimension == "sessionDurationBucket"){
1177
+ $_data = array();
1178
+ //$j = 1;
1179
+ foreach($data as $val){
1180
+ if(isset($_data[$val["Session Duration Bucket"]])){
1181
+ $_data[$val["Session Duration Bucket"]]["Users"] += floatval($val["Users"]);
1182
+ $_data[$val["Session Duration Bucket"]]["Sessions"] += floatval($val["Sessions"]);
1183
+ $_data[$val["Session Duration Bucket"]]["Percent New Sessions"] += floatval($val["Percent New Sessions"]);
1184
+ $_data[$val["Session Duration Bucket"]]["Bounce Rate"] += floatval($val["Bounce Rate"]);
1185
+ $_data[$val["Session Duration Bucket"]]["Pageviews"] += floatval($val["Pageviews"]);
1186
+ $_data[$val["Session Duration Bucket"]]["Avg Session Duration"] += $val["Avg Session Duration"];
1187
+ }
1188
+ else{
1189
+ // $val["No"] = $j;
1190
+ // $j++;
1191
+ $_data[$val["Session Duration Bucket"]] = $val;
1192
+ $_data[$val["Session Duration Bucket"]]["order"] = intval($val["Session Duration Bucket"]);
1193
+ }
1194
+
1195
+
1196
+ }
1197
+ $data = array_values($_data);
1198
+ foreach ($data as $key => $row) {
1199
+ $yyy[$key] = $row['order'];
1200
+ }
1201
+ array_multisort($yyy, SORT_ASC, $data);
1202
+ foreach($data as $j=>$val){
1203
+ $val["No"] = ($j+1);
1204
+ $data[$j] = $val;
1205
+ }
1206
+ }
1207
+ else{
1208
+ if(strpos($dimension,'dimension') === false){
1209
+ $dimension = $dimension == 'siteSpeed' || $dimension == 'sales_performance' ? 'Date' : $dimension;
1210
+ foreach ($data as $key => $row) {
1211
+ $new_data[$key] = $row[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension)))];
1212
+ }
1213
+ array_multisort($new_data, SORT_ASC, $data);
1214
+ foreach($data as $j=>$val){
1215
+ $val["No"] = ($j+1);
1216
+ $data[$j] = $val;
1217
+ }
1218
+ }
1219
+ }
1220
+ $result = $data;
1221
+ if ($data_sum != '') {
1222
+ $result = array('data_sum' => $data_sum, 'chart_data' => $data);
1223
+ }
1224
+ set_transient( 'gawd-'.$profileId.'-'.$dimension.'-'.$start_date.'-'.$end_date, json_encode($result), $expiration );
1225
+ return json_encode($result);
1226
+ }
1227
+ else {
1228
+ if(strpos($dimension,'dimension') >-1){
1229
+ $dimension_data = $this->get_custom_dimensions();
1230
+ foreach($dimension_data as $key => $value){
1231
+ if($dimension == substr($value['id'],3)){
1232
+ $dimension = $value['name'];
1233
+ }
1234
+ }
1235
+ }
1236
+ $empty[0] = array(
1237
+ trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => 0
1238
+ );
1239
+ $empty[0]['No'] = 1;
1240
+ for ($i = 0; $i < count($metric); $i++) {
1241
+ $empty[0][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
1242
+ }
1243
+
1244
+ return json_encode(array('chart_data' => $empty));
1245
+ }
1246
+ }
1247
+
1248
+ public function get_data_compact($metric, $dimension, $start_date, $end_date, $timezone) {
1249
+ $profileId = $this->get_profile_id();
1250
+ $metric_sort = $metric;
1251
+ //var_dump($profileId);exit;
1252
+ $analytics = $this->analytics_member;
1253
+ // Get the results from the Core Reporting API and print the results.
1254
+ // Calls the Core Reporting API and queries for the number of sessions
1255
+ // for the last seven days.
1256
+ if ($dimension == 'date') {
1257
+ $metric = 'ga:users,ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviews,ga:avgSessionDuration,ga:pageviewsPerSession';
1258
+ }
1259
+ $results = $analytics->data_ga->get(
1260
+ 'ga:' . $profileId, $start_date, $end_date, $metric, array(
1261
+ 'dimensions' => 'ga:' . $dimension,
1262
+ 'sort' => 'ga:' . $dimension,
1263
+ )
1264
+ );
1265
+ $rows = $results->getRows();
1266
+ $metric = explode(',', $metric);
1267
+ if ($rows) {
1268
+ $j = 0;
1269
+ $data_sum = array();
1270
+ foreach($results->getTotalsForAllResults() as $key => $value){
1271
+ $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($key,3))))] = $value;
1272
+ }
1273
+
1274
+ foreach ($rows as $row) {
1275
+ if ($dimension == 'date') {
1276
+ $row[0] = date('Y-m-d', strtotime($row[0]));
1277
+ }
1278
+ $data[$j] = array(
1279
+ trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => $row[0]
1280
+ );
1281
+ for ($i = 0; $i < count($metric); $i++) {
1282
+ $metric_val = floatval($row[$i + 1]);
1283
+
1284
+ $data[$j][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = $metric_val;
1285
+ }
1286
+ $j++;
1287
+ }
1288
+ if($dimension == "country"){
1289
+ foreach ($data as $key => $row) {
1290
+ $country[$key] = $row[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric_sort, 3))))];
1291
+ }
1292
+ array_multisort($country, SORT_DESC, $data);
1293
+ foreach($data as $j=>$val){
1294
+ $val["No"] = ($j+1);
1295
+ $data[$j] = $val;
1296
+ }
1297
+ }
1298
+ }
1299
+ else {
1300
+ $data_sum = array();
1301
+ $empty[0] = array(
1302
+ trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => 0
1303
+ );
1304
+ $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension)))] = 0;
1305
+ $empty[0]['No'] = 1;
1306
+ for ($i = 0; $i < count($metric); $i++) {
1307
+ $empty[0][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
1308
+ $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
1309
+ }
1310
+ $result = array('data_sum' => $data_sum, 'chart_data' => $empty);
1311
+ return json_encode($result);
1312
+ }
1313
+ if ($data_sum != '') {
1314
+ $result = array('data_sum' => $data_sum, 'chart_data' => $data);
1315
+ }
1316
+ $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
1317
+ set_transient('gawd-compact-' . $profileId . '-' . $dimension . '-' . $start_date . '-' . $end_date, json_encode($result), $expiration);
1318
+ return json_encode($result);
1319
+ }
1320
+
1321
+ public function get_data_alert($metric, $dimension, $start_date, $end_date, $gawd_alert_view) {
1322
+ $profileId = $gawd_alert_view == '' ? $this->get_profile_id() : $gawd_alert_view;
1323
+ $analytics = $this->analytics_member;
1324
+ // Get the results from the Core Reporting API and print the results.
1325
+ // Calls the Core Reporting API and queries for the number of sessions
1326
+ // for the last seven days.
1327
+ $results = $analytics->data_ga->get(
1328
+ 'ga:' . $profileId, $start_date, $end_date, $metric, array(
1329
+ 'dimensions' => 'ga:' . $dimension,
1330
+ 'sort' => 'ga:' . $dimension,
1331
+ )
1332
+ );
1333
+ $rows = $results->getRows();
1334
+
1335
+ $data = '';
1336
+ foreach ($rows as $row) {
1337
+ $data += floatval($row[1]);
1338
+ }
1339
+ return ($data);
1340
+ }
1341
+
1342
+ public function get_profile_id() {
1343
+ $this->gawd_user_data = get_option('gawd_user_data');
1344
+ $profiles_light = get_transient('gawd_user_profiles') ? get_transient('gawd_user_profiles') : $this->gawd_user_data['gawd_profiles'];
1345
+ if (!isset($this->gawd_user_data['gawd_id']) || $this->gawd_user_data['gawd_id'] == '') {
1346
+ if (!empty($profiles_light)) {
1347
+ $first_profile = reset($profiles_light)[0];
1348
+ $this->gawd_user_data['gawd_id'] = $first_profile['id'];
1349
+ }
1350
+ }
1351
+ return $this->gawd_user_data['gawd_id'];
1352
+ }
1353
+
1354
+ public function get_profile_webPropertyId() {
1355
+ $this->gawd_user_data = get_option('gawd_user_data');
1356
+ return $this->gawd_user_data['webPropertyId'];
1357
+ }
1358
+
1359
+ public function get_profile_accountId() {
1360
+ $this->gawd_user_data = get_option('gawd_user_data');
1361
+ return isset($this->gawd_user_data['accountId']) ? $this->gawd_user_data['accountId'] : '';
1362
+ }
1363
+
1364
+ public function get_default_webPropertyId() {
1365
+ $this->gawd_user_data = get_option('gawd_user_data');
1366
+ return $this->gawd_user_data['default_webPropertyId'];
1367
+ }
1368
+
1369
+ public function get_default_accountId() {
1370
+ $this->gawd_user_data = get_option('gawd_user_data');
1371
+ return $this->gawd_user_data['default_accountId'];
1372
+ }
1373
+
1374
+ public function get_page_data($dimension, $start_date, $end_date, $timezone) {
1375
+ $analytics = $this->analytics_member;
1376
+ $profileId = $this->get_profile_id();
1377
+ $metric = $dimension == 'pagePath' || $dimension == 'PagePath' ? 'ga:pageviews,ga:uniquePageviews,ga:avgTimeOnPage,ga:entrances,ga:bounceRate,ga:exitRate,ga:pageValue,ga:avgPageLoadTime' : 'ga:sessions,ga:percentNewSessions,ga:newUsers,ga:bounceRate,ga:pageviewsPerSession,ga:avgSessionDuration,ga:transactions,ga:transactionRevenue,ga:transactionsPerSession';
1378
+ $sort = '-'.explode(',', $metric)[0];
1379
+
1380
+ try {
1381
+ $results = $analytics->data_ga->get(
1382
+ 'ga:' . $profileId, $start_date, $end_date, $metric, array(
1383
+ 'dimensions' => 'ga:'.$dimension,
1384
+ 'sort' => $sort,
1385
+ )
1386
+ );
1387
+ } catch (Exception $e) {
1388
+
1389
+ $error = array('error_message' => 'Error');
1390
+ if (strpos($e->getMessage(), 'User does not have sufficient permissions for this profile')) {
1391
+ $error['error_message'] = 'User does not have sufficient permissions for this profile';
1392
+ }
1393
+ return json_encode($error);
1394
+ }
1395
+ $rows = $results->getRows();
1396
+ $metric = explode(',', $metric);
1397
+ if ($rows) {
1398
+ $data_sum = array();
1399
+ foreach($results->getTotalsForAllResults() as $key => $value){
1400
+ $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($key,3))))] = $value;
1401
+ }
1402
+ foreach ($rows as $key => $row) {
1403
+ $hours = strlen(floor($row[3] / 3600)) < 2 ? '0' . floor($row[3] / 3600) : floor($row[3] / 3600);
1404
+ $mins = strlen(floor($row[3] / 60 % 60)) < 2 ? '0' . floor($row[3] / 60 % 60) : floor($row[3] / 60 % 60);
1405
+ $secs = strlen(floor($row[3] % 60)) < 2 ? '0' . floor($row[3] % 60) : floor($row[3] % 60);
1406
+ $time_on_page = $hours.':'.$mins.':'.$secs;
1407
+ if($dimension == 'pagePath' || $dimension == 'PagePath'){
1408
+ $data[] = array(
1409
+ 'No' => floatval($key + 1),
1410
+ 'Page Path' => $row[0],
1411
+ 'Pageviews' => intval($row[1]),
1412
+ 'Unique Pageviews' => intval($row[2]),
1413
+ 'Avg Time On Page' => $time_on_page,
1414
+ 'Entrances' => intval($row[4]),
1415
+ 'Bounce Rate' => floatval($row[5]),
1416
+ 'Exit Rate' => intval($row[6]),
1417
+ 'Page Value' => intval($row[7]),
1418
+ 'Avg Page Load Time' => intval($row[8])
1419
+ );
1420
+ }
1421
+ else{
1422
+ $data[] = array(
1423
+ 'No' => floatval($key + 1),
1424
+ 'Landing Page' => $row[0],
1425
+ 'Sessions' => intval($row[1]),
1426
+ 'Percent New Sessions' => intval($row[2]),
1427
+ 'New Users' => intval($row[3]),
1428
+ 'Bounce Rate' => intval($row[4]),
1429
+ 'Pageviews Per Session' => floatval($row[5]),
1430
+ 'Avg Session Duration' => intval($row[6]),
1431
+ 'Transactions' => intval($row[7]),
1432
+ 'Transaction Revenue' => intval($row[8]),
1433
+ 'Transactions Per Session' => intval($row[9])
1434
+ );
1435
+ }
1436
+ }
1437
+
1438
+ }
1439
+ else {
1440
+ $empty[0] = array(
1441
+ trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))) => 0
1442
+ );
1443
+ $empty[0]['No'] = 1;
1444
+ for ($i = 0; $i < count($metric); $i++) {
1445
+ $empty[0][trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i], 3))))] = 0;
1446
+ $data_sum[trim(ucfirst(preg_replace('/([A-Z])/', ' $1', substr($metric[$i],3))))] = 0;
1447
+ }
1448
+
1449
+ return json_encode(array('data_sum' => $data_sum, 'chart_data' => $empty));
1450
+ }
1451
+ if ($data_sum != '') {
1452
+ $result = array('data_sum' => $data_sum, 'chart_data' => $data);
1453
+ }
1454
+ $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
1455
+ set_transient('gawd-' . $profileId . '-' . $dimension . '-' . $start_date . '-' . $end_date, json_encode($result), $expiration);
1456
+ return json_encode($result);
1457
+ }
1458
+
1459
+ public function get_goal_data($dimension, $start_date, $end_date, $timezone, $same_dimension) {
1460
+ $goals = $this->get_management_goals();
1461
+ if ('no_goals_exist' != $goals) {
1462
+ $analytics = $this->analytics_member;
1463
+ $profileId = $this->get_profile_id();
1464
+ $metric = array();
1465
+ $all_metric = '';
1466
+ $counter = 1;
1467
+ foreach ($goals as $goal) {
1468
+ $all_metric .= 'ga:goal' . $goal['id'] . 'Completions,';
1469
+ if($counter <= 10){
1470
+ $metrics[0][] = 'ga:goal' . $goal['id'] . 'Completions';
1471
+ }
1472
+ else{
1473
+ $metrics[1][] = 'ga:goal' . $goal['id'] . 'Completions';
1474
+ }
1475
+ $counter++;
1476
+ }
1477
+ $rows = array();
1478
+ foreach($metrics as $metric){
1479
+ $metric = implode(',',$metric);
1480
+ $results = $analytics->data_ga->get(
1481
+ 'ga:' . $profileId, $start_date, $end_date, $metric, array(
1482
+ 'dimensions' => 'ga:' . $dimension,
1483
+ 'sort' => 'ga:' . $dimension,
1484
+ )
1485
+ );
1486
+
1487
+ $temp_rows = $results->getRows();
1488
+ if(empty($temp_rows)){
1489
+ continue;
1490
+ }
1491
+
1492
+ foreach($temp_rows as $key=>$value){
1493
+ if(!isset($rows[$key])){
1494
+ $rows[$key] = $value;
1495
+ }
1496
+ else{
1497
+ unset($value[0]);
1498
+ $rows[$key] = array_merge($rows[$key],$value);
1499
+ }
1500
+ }
1501
+
1502
+ }
1503
+ $all_metric = explode(',', $all_metric);
1504
+ if ($rows) {
1505
+ $j = 0;
1506
+ $data_sum = array();
1507
+ foreach ($rows as $row) {
1508
+ if ($dimension == 'date') {
1509
+ $row[0] = date('Y-m-d', strtotime($row[0]));
1510
+ }
1511
+ $data[$j] = array(
1512
+ preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $dimension))))=> $row[0]
1513
+ );
1514
+ $data[$j]['No'] = floatval($j + 1);
1515
+ for ($i = 0; $i < count($goals); $i++) {
1516
+ $data[$j][preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $goals[$i]['name']))))] = floatval($row[$i + 1]);
1517
+ if (isset($data_sum[preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $goals[$i]['name']))))])) {
1518
+ $data_sum[preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $goals[$i]['name']))))] += floatval($row[$i + 1]);
1519
+ } else {
1520
+ if (substr($all_metric[$i], 3) != 'percentNewSessions' && substr($all_metric[$i], 3) != 'bounceRate') {
1521
+ $data_sum[preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $goals[$i]['name']))))] = floatval($row[$i + 1]);
1522
+ }
1523
+ }
1524
+ }
1525
+ $j++;
1526
+ }
1527
+ $expiration = strtotime(date("Y-m-d 23:59:59")) - strtotime(gmdate("Y-m-d H:i:s") . '+' . $timezone . ' hours');
1528
+ if (isset($same_dimension) && $same_dimension != null) {
1529
+ $dimension = $same_dimension;
1530
+ }
1531
+ $result = $data;
1532
+ if ($data_sum != '') {
1533
+ $result = array('data_sum' => $data_sum, 'chart_data' => $data);
1534
+ }
1535
+ set_transient('gawd-' . $profileId . '-' . $dimension . '-' . $start_date . '-' . $end_date, json_encode($result), $expiration);
1536
+ return json_encode($result);
1537
+ } else {
1538
+ return $goals;
1539
+ }
1540
+ } else {
1541
+ return json_encode(array('error_message' => 'No goals exist'));
1542
+ }
1543
+ }
1544
+
1545
+ public function gawd_realtime_data() {
1546
+ $analytics = $this->analytics_member;
1547
+ $profileId = $this->get_profile_id();
1548
+ $metrics = 'rt:activeUsers';
1549
+ $dimensions = 'rt:pagePath,rt:source,rt:keyword,rt:trafficType,rt:country,rt:pageTitle,rt:deviceCategory';
1550
+ $managequota = 'u' . get_current_user_id() . 's' . get_current_blog_id();
1551
+
1552
+ try {
1553
+ $data = $analytics->data_realtime->get('ga:' . $profileId, $metrics, array('dimensions' => $dimensions, 'quotaUser' => $managequota . 'p' . $profileId));
1554
+ } catch (Exception $e) {
1555
+ $error = array('error_message' => 'Error');
1556
+ if (strpos($e->getMessage(), 'User does not have sufficient permissions for this profile')) {
1557
+ $error['error_message'] = 'User does not have sufficient permissions for this profile';
1558
+ }
1559
+ return json_encode($error);
1560
+ }
1561
+ $expiration = 5 ;
1562
+ if ($data->getRows() != '') {
1563
+ $i = 0;
1564
+ $gawd_data = $data;
1565
+ foreach ($data->getRows() as $row) {
1566
+ $gawd_data[$i] = $row;
1567
+ $i++;
1568
+ }
1569
+ set_transient('gawd-real-' . $profileId, json_encode($gawd_data), $expiration);
1570
+ echo json_encode($gawd_data);
1571
+ wp_die();
1572
+ }
1573
+ else {
1574
+ return 0;
1575
+ }
1576
+ }
1577
+
1578
+ public static function get_instance() {
1579
+ if (null === static::$instance) {
1580
+ static::$instance = new static();
1581
+ }
1582
+ return static::$instance;
1583
+ }
1584
+
1585
+ }
1586
+
1587
+ ?>
admin/licensing.php CHANGED
@@ -1,88 +1,88 @@
1
-
2
- <div id="featurs_tables">
3
- <div id="featurs_table1">
4
- <span>WordPress 3.5+ <?php _e("ready", 'gawd'); ?></span>
5
- <span><?php _e("Overview reports", 'gawd'); ?></span>
6
- <span><?php _e("Analytics on WordPress dashboard", 'gawd'); ?></span>
7
- <span><?php _e("All Analytics reports", 'gawd'); ?></span>
8
- <span><?php _e("Metrics report comparison", 'gawd'); ?></span>
9
- <span><?php _e("Date range report comparison", 'gawd'); ?></span>
10
- <span><?php _e("Line, Pie and Column chart reports", 'gawd'); ?></span>
11
- <span><?php _e("CSV and PDF export", 'gawd'); ?></span>
12
- <span><?php _e("Scheduled email notifications", 'gawd'); ?></span>
13
- <span><?php _e("Page and post reports", 'gawd'); ?></span>
14
- <span><?php _e("Frontend reports", 'gawd'); ?></span>
15
- <span><?php _e("Google Analytics tracking code and options", 'gawd'); ?></span>
16
- <span><?php _e("Goal management", 'gawd'); ?></span>
17
- <span><?php _e("Google Analytics Filters management", 'gawd'); ?></span>
18
- <span><?php _e("User and Role permissions to access reports", 'gawd'); ?></span>
19
- <span><?php _e("Custom Dimensions", 'gawd'); ?></span>
20
- <span><?php _e("Custom Reports", 'gawd'); ?></span>
21
- <span><?php _e("Ecommerce reports", 'gawd'); ?></span>
22
- <span><?php _e("Google AdSense report", 'gawd'); ?></span>
23
- <span><?php _e("Google AdWords report", 'gawd'); ?></span>
24
- <span><?php _e("Tracking exclusions by roles and users", 'gawd'); ?></span>
25
- <span><?php _e("Google Analytics alerts", 'gawd'); ?></span>
26
- <span><?php _e("Pushover notifications", 'gawd'); ?></span>
27
- </div>
28
- <div id="featurs_table2">
29
- <span style="padding-top: 18px;height: 39px;"><?php _e("Free", 'gawd'); ?></span>
30
- <span class="yes"></span>
31
- <span class="yes"></span>
32
- <span class="yes"></span>
33
- <span class="yes"></span>
34
- <span class="yes"></span>
35
- <span class="yes"></span>
36
- <span class="yes"></span>
37
- <span class="yes"></span>
38
- <span class="yes"></span>
39
- <span class="yes"></span>
40
- <span class="yes"></span>
41
- <span class="yes"></span>
42
- <span class="yes"></span>
43
- <span class="yes"></span>
44
- <span class="yes"></span>
45
- <span class="no"></span>
46
- <span class="no"></span>
47
- <span class="no"></span>
48
- <span class="no"></span>
49
- <span class="no"></span>
50
- <span class="no"></span>
51
- <span class="no"></span>
52
- <span class="no"></span>
53
- </div>
54
- <div id="featurs_table3">
55
- <span><?php _e("Pro Version", 'gawd'); ?></span>
56
- <span class="yes"></span>
57
- <span class="yes"></span>
58
- <span class="yes"></span>
59
- <span class="yes"></span>
60
- <span class="yes"></span>
61
- <span class="yes"></span>
62
- <span class="yes"></span>
63
- <span class="yes"></span>
64
- <span class="yes"></span>
65
- <span class="yes"></span>
66
- <span class="yes"></span>
67
- <span class="yes"></span>
68
- <span class="yes"></span>
69
- <span class="yes"></span>
70
- <span class="yes"></span>
71
- <span class="yes"></span>
72
- <span class="yes"></span>
73
- <span class="yes"></span>
74
- <span class="yes"></span>
75
- <span class="yes"></span>
76
- <span class="yes"></span>
77
- <span class="yes"></span>
78
- <span class="yes"></span>
79
- </div>
80
- </div>
81
- <div style="float: left; clear: both;">
82
- <p><?php _e("After purchasing the commercial version follow these steps:", 'gawd'); ?></p>
83
- <ol>
84
- <li><?php _e("Deactivate WD Google Analytics plugin.", 'gawd'); ?></li>
85
- <li><?php _e("Delete WD Google Analytics plugin.", 'gawd'); ?></li>
86
- <li><?php _e("Install the downloaded commercial version of the plugin.", 'gawd'); ?></li>
87
- </ol>
88
- </div>
1
+
2
+ <div id="featurs_tables">
3
+ <div id="featurs_table1">
4
+ <span>WordPress 3.5+ <?php _e("ready", 'gawd'); ?></span>
5
+ <span><?php _e("Overview reports", 'gawd'); ?></span>
6
+ <span><?php _e("Analytics on WordPress dashboard", 'gawd'); ?></span>
7
+ <span><?php _e("All Analytics reports", 'gawd'); ?></span>
8
+ <span><?php _e("Metrics report comparison", 'gawd'); ?></span>
9
+ <span><?php _e("Date range report comparison", 'gawd'); ?></span>
10
+ <span><?php _e("Line, Pie and Column chart reports", 'gawd'); ?></span>
11
+ <span><?php _e("CSV and PDF export", 'gawd'); ?></span>
12
+ <span><?php _e("Scheduled email notifications", 'gawd'); ?></span>
13
+ <span><?php _e("Page and post reports", 'gawd'); ?></span>
14
+ <span><?php _e("Frontend reports", 'gawd'); ?></span>
15
+ <span><?php _e("Google Analytics tracking code and options", 'gawd'); ?></span>
16
+ <span><?php _e("Goal management", 'gawd'); ?></span>
17
+ <span><?php _e("Google Analytics Filters management", 'gawd'); ?></span>
18
+ <span><?php _e("User and Role permissions to access reports", 'gawd'); ?></span>
19
+ <span><?php _e("Custom Dimensions", 'gawd'); ?></span>
20
+ <span><?php _e("Custom Reports", 'gawd'); ?></span>
21
+ <span><?php _e("Ecommerce reports", 'gawd'); ?></span>
22
+ <span><?php _e("Google AdSense report", 'gawd'); ?></span>
23
+ <span><?php _e("Google AdWords report", 'gawd'); ?></span>
24
+ <span><?php _e("Tracking exclusions by roles and users", 'gawd'); ?></span>
25
+ <span><?php _e("Google Analytics alerts", 'gawd'); ?></span>
26
+ <span><?php _e("Pushover notifications", 'gawd'); ?></span>
27
+ </div>
28
+ <div id="featurs_table2">
29
+ <span style="padding-top: 18px;height: 39px;"><?php _e("Free", 'gawd'); ?></span>
30
+ <span class="yes"></span>
31
+ <span class="yes"></span>
32
+ <span class="yes"></span>
33
+ <span class="yes"></span>
34
+ <span class="yes"></span>
35
+ <span class="yes"></span>
36
+ <span class="yes"></span>
37
+ <span class="yes"></span>
38
+ <span class="yes"></span>
39
+ <span class="yes"></span>
40
+ <span class="yes"></span>
41
+ <span class="yes"></span>
42
+ <span class="yes"></span>
43
+ <span class="yes"></span>
44
+ <span class="yes"></span>
45
+ <span class="no"></span>
46
+ <span class="no"></span>
47
+ <span class="no"></span>
48
+ <span class="no"></span>
49
+ <span class="no"></span>
50
+ <span class="no"></span>
51
+ <span class="no"></span>
52
+ <span class="no"></span>
53
+ </div>
54
+ <div id="featurs_table3">
55
+ <span><?php _e("Pro Version", 'gawd'); ?></span>
56
+ <span class="yes"></span>
57
+ <span class="yes"></span>
58
+ <span class="yes"></span>
59
+ <span class="yes"></span>
60
+ <span class="yes"></span>
61
+ <span class="yes"></span>
62
+ <span class="yes"></span>
63
+ <span class="yes"></span>
64
+ <span class="yes"></span>
65
+ <span class="yes"></span>
66
+ <span class="yes"></span>
67
+ <span class="yes"></span>
68
+ <span class="yes"></span>
69
+ <span class="yes"></span>
70
+ <span class="yes"></span>
71
+ <span class="yes"></span>
72
+ <span class="yes"></span>
73
+ <span class="yes"></span>
74
+ <span class="yes"></span>
75
+ <span class="yes"></span>
76
+ <span class="yes"></span>
77
+ <span class="yes"></span>
78
+ <span class="yes"></span>
79
+ </div>
80
+ </div>
81
+ <div style="float: left; clear: both;">
82
+ <p><?php _e("After purchasing the commercial version follow these steps:", 'gawd'); ?></p>
83
+ <ol>
84
+ <li><?php _e("Deactivate WD Google Analytics plugin.", 'gawd'); ?></li>
85
+ <li><?php _e("Delete WD Google Analytics plugin.", 'gawd'); ?></li>
86
+ <li><?php _e("Install the downloaded commercial version of the plugin.", 'gawd'); ?></li>
87
+ </ol>
88
+ </div>
admin/pages/browser.php CHANGED
@@ -1,10 +1,10 @@
1
-
2
-
3
- <div class="">
4
- <div class="opacity_div_compact">
5
- <div class="loading_div_compact">
6
- <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
7
- </div>
8
- </div>
9
- <div id="gawd_browser_meta"></div>
10
- </div>
1
+
2
+
3
+ <div class="">
4
+ <div class="opacity_div_compact">
5
+ <div class="loading_div_compact">
6
+ <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
7
+ </div>
8
+ </div>
9
+ <div id="gawd_browser_meta"></div>
10
+ </div>
admin/pages/custom_dimensions.php CHANGED
@@ -1,82 +1,82 @@
1
- <?php
2
- $existing_custom_dimensions = $gawd_client->get_custom_dimensions('default');
3
- if (!is_array($existing_custom_dimensions)) {
4
- $existing_custom_dimensions = array();
5
- }
6
- $tracking_dimensions = $gawd_client->get_custom_dimensions_tracking();
7
- $supported_dimensions = array("Logged in","Post type","Author","Category","Tags", "Published Month", "Published Year");
8
- ?>
9
- <div class="dimension_wrapper">
10
- <form action="" method="post" id="gawd_dimensions_form">
11
- <div class="gawd_dimension_row">
12
- <span class="gawd_dimension_label">Name</span>
13
- <span class="gawd_dimension_input">
14
- <select name="gawd_custom_dimension_name" id="gawd_custom_dimension_name">
15
- <?php
16
- foreach ($supported_dimensions as $supported_dimension) {
17
- $disabled = '';
18
- if (is_array($tracking_dimensions) && !empty($tracking_dimensions)) {
19
- foreach ($tracking_dimensions as $tracking_dimension) {
20
- if ($supported_dimension == $tracking_dimension['name']) {
21
- $disabled = 'disabled="disabled"';
22
- break;
23
- }
24
- }
25
- }
26
- ?>
27
- <option value="<?php echo $supported_dimension; ?>" <?php echo $disabled; ?>><?php echo $supported_dimension; ?></option>
28
- <?php } ?>
29
- </select>
30
- </span>
31
- <div class="gawd_info" title="Pick a name for your custom dimension."></div>
32
- <div class="clear"></div>
33
- </div>
34
- <div class="gawd_dimension_row">
35
- <span class="gawd_dimension_label">Scope</span>
36
- <span class="gawd_dimension_input">
37
- <select name="gawd_custom_dimension_scope" id="gawd_custom_dimension_scope">
38
- <option value="Hit">Hit</option>
39
- <option value="Session">Session</option>
40
- <option value="User">User</option>
41
- <option value="Product">Product</option>
42
- </select>
43
- </span>
44
- <div class="gawd_info" title="Select a scope, hit, session, user or product."></div>
45
- <div class="clear"></div>
46
- </div>
47
- <div class="gawd_dimension_row">
48
- <div class="onoffswitch">
49
- <input type="checkbox" name="gawd_custom_dimension_tracking" class="onoffswitch-checkbox" id="gawd_custom_dimension_tracking" checked>
50
- <label class="onoffswitch-label" for="gawd_custom_dimension_tracking">
51
- <span class="onoffswitch-inner"></span>
52
- <span class="onoffswitch-switch"></span>
53
- </label>
54
- </div>
55
- <div class="gawd_info" title="Enable this option to track relevant activity and view statistics based on this custom dimension on Reports page."></div>
56
- <div class="onoffswitch_text">
57
- Tracking for this custom dimension
58
- </div>
59
- <div class="clear"></div>
60
- </div>
61
- <div class="gawd_buttons" id="goal_submit">
62
- <input class="button_gawd" type="submit" value="Save"/>
63
- <input name="gawd_custom_dimension_id" type="hidden" value="<?php echo count($existing_custom_dimensions);?>"/>
64
- <div class="clear"></div>
65
- </div>
66
- <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
67
- </form>
68
- <?php if (!empty($existing_custom_dimensions)) { ?>
69
- <table border="1" class="gawd_table">
70
- <tr>
71
- <th>Name</th>
72
- <th>Id</th>
73
- </tr>
74
- <?php foreach($existing_custom_dimensions as $existing_custom_dimension) { ?>
75
- <tr>
76
- <td><?php echo $existing_custom_dimension['name']; ?></td>
77
- <td><?php echo substr($existing_custom_dimension['id'],-1); ?></td>
78
- </tr>
79
- <?php } ?>
80
- </table>
81
- <?php } ?>
82
- </div>
1
+ <?php
2
+ $existing_custom_dimensions = $gawd_client->get_custom_dimensions('default');
3
+ if (!is_array($existing_custom_dimensions)) {
4
+ $existing_custom_dimensions = array();
5
+ }
6
+ $tracking_dimensions = $gawd_client->get_custom_dimensions_tracking();
7
+ $supported_dimensions = array("Logged in","Post type","Author","Category","Tags", "Published Month", "Published Year");
8
+ ?>
9
+ <div class="dimension_wrapper">
10
+ <form action="" method="post" id="gawd_dimensions_form">
11
+ <div class="gawd_dimension_row">
12
+ <span class="gawd_dimension_label">Name</span>
13
+ <span class="gawd_dimension_input">
14
+ <select name="gawd_custom_dimension_name" id="gawd_custom_dimension_name">
15
+ <?php
16
+ foreach ($supported_dimensions as $supported_dimension) {
17
+ $disabled = '';
18
+ if (is_array($tracking_dimensions) && !empty($tracking_dimensions)) {
19
+ foreach ($tracking_dimensions as $tracking_dimension) {
20
+ if ($supported_dimension == $tracking_dimension['name']) {
21
+ $disabled = 'disabled="disabled"';
22
+ break;
23
+ }
24
+ }
25
+ }
26
+ ?>
27
+ <option value="<?php echo $supported_dimension; ?>" <?php echo $disabled; ?>><?php echo $supported_dimension; ?></option>
28
+ <?php } ?>
29
+ </select>
30
+ </span>
31
+ <div class="gawd_info" title="Pick a name for your custom dimension."></div>
32
+ <div class="clear"></div>
33
+ </div>
34
+ <div class="gawd_dimension_row">
35
+ <span class="gawd_dimension_label">Scope</span>
36
+ <span class="gawd_dimension_input">
37
+ <select name="gawd_custom_dimension_scope" id="gawd_custom_dimension_scope">
38
+ <option value="Hit">Hit</option>
39
+ <option value="Session">Session</option>
40
+ <option value="User">User</option>
41
+ <option value="Product">Product</option>
42
+ </select>
43
+ </span>
44
+ <div class="gawd_info" title="Select a scope, hit, session, user or product."></div>
45
+ <div class="clear"></div>
46
+ </div>
47
+ <div class="gawd_dimension_row">
48
+ <div class="onoffswitch">
49
+ <input type="checkbox" name="gawd_custom_dimension_tracking" class="onoffswitch-checkbox" id="gawd_custom_dimension_tracking" checked>
50
+ <label class="onoffswitch-label" for="gawd_custom_dimension_tracking">
51
+ <span class="onoffswitch-inner"></span>
52
+ <span class="onoffswitch-switch"></span>
53
+ </label>
54
+ </div>
55
+ <div class="gawd_info" title="Enable this option to track relevant activity and view statistics based on this custom dimension on Reports page."></div>
56
+ <div class="onoffswitch_text">
57
+ Tracking for this custom dimension
58
+ </div>
59
+ <div class="clear"></div>
60
+ </div>
61
+ <div class="gawd_buttons" id="goal_submit">
62
+ <input class="button_gawd" type="submit" value="Save"/>
63
+ <input name="gawd_custom_dimension_id" type="hidden" value="<?php echo count($existing_custom_dimensions);?>"/>
64
+ <div class="clear"></div>
65
+ </div>
66
+ <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
67
+ </form>
68
+ <?php if (!empty($existing_custom_dimensions)) { ?>
69
+ <table border="1" class="gawd_table">
70
+ <tr>
71
+ <th>Name</th>
72
+ <th>Id</th>
73
+ </tr>
74
+ <?php foreach($existing_custom_dimensions as $existing_custom_dimension) { ?>
75
+ <tr>
76
+ <td><?php echo $existing_custom_dimension['name']; ?></td>
77
+ <td><?php echo substr($existing_custom_dimension['id'],-1); ?></td>
78
+ </tr>
79
+ <?php } ?>
80
+ </table>
81
+ <?php } ?>
82
+ </div>
admin/pages/custom_reports.php CHANGED
@@ -1,6 +1,6 @@
1
-
2
- <img style="margin-top:10px" src="<?php echo GAWD_URL . '/assets/freePages/custom_reports.png';?>"/>
3
-
4
-
5
-
6
-
1
+
2
+ <img style="margin-top:10px" src="<?php echo GAWD_URL . '/assets/freePages/custom_reports.png';?>"/>
3
+
4
+
5
+
6
+
admin/pages/dashboard.php CHANGED
@@ -1,671 +1,671 @@
1
- <?php
2
- $goals = $gawd_client->get_management_goals();
3
- if (!is_array($goals)) {
4
- $goals = array();
5
- }
6
- $get_custom_reports = get_option('gawd_custom_reports');
7
- if(!isset($_GET['tab'])){
8
- $_GET['tab'] = 'general';
9
- }
10
- $tabs = get_option('gawd_menu_items');
11
- $gawd_zoom_message = get_option('gawd_zoom_message');
12
- $current_user = get_current_user_id();
13
- $saved_user_menues = get_option('gawd_menu_for_user');
14
- if($current_user != 1 && isset($saved_user_menues[$current_user])){
15
- $tabs = array_intersect_key($tabs, $saved_user_menues[$current_user]);
16
- }
17
- ?>
18
- <form method="post" id="gawd_view">
19
-
20
- <div class="gawd_profiles" id="gawd_profile_wrapper">
21
- <?php if($gawd_zoom_message === false){
22
- ?>
23
- <div class="gawd_zoom_message">
24
- <span>You can zoom chart by dragging the mouse over it</span><input class="button_gawd" type="button" id="gawd_got_it" value="GOT IT"/>
25
- </div>
26
- <?php
27
- }
28
- ?>
29
- <select class="gawd_profile_select" id="gawd_id" name="gawd_id" onchange="change_account(this)">
30
- <?php foreach ($profiles as $property_name => $property): ?>
31
- <optgroup label="<?php echo $property_name; ?>">
32
- <?php foreach ($property as $profile):
33
- $webPropertyId = $profile['webPropertyId'];
34
- $id = $profile['id'];
35
- $name = $profile['name'];
36
- $selected = '';
37
- if($id == $gawd_user_data['gawd_id']){
38
- $selected = 'selected="selected"';
39
- }
40
- ?>
41
- <option value="<?php echo $id; ?>" <?php echo $selected; ?>><?php echo $property_name.' - '.$name ; ?></option>
42
- <?php endforeach ?>
43
- </optgroup>
44
- <?php endforeach ?>
45
- </select>
46
- <div class="clear"></div>
47
- <input type="hidden" name='web_property_name' id='web_property_name'/>
48
- </div>
49
- <div id="gawd_body">
50
- <?php
51
- include_once('dashboard_menu.php');
52
- $page = isset($_GET['tab']) ? $_GET['tab'] : 'overview';
53
- if(strpos($page,'custom_report')!==false){
54
- $tab = $page;
55
- }
56
- else{
57
- switch ($page) {
58
- case 'general':
59
- $tab = 'date';
60
- break;
61
- case 'location':
62
- $tab = 'country';
63
- break;
64
- case 'behaviour':
65
- $tab = 'userType';
66
- break;
67
- case 'engagement':
68
- $tab = 'sessionDurationBucket';
69
- break;
70
- case 'pagePath':
71
- $tab = 'pagePath';
72
- break;
73
- case 'landingPagePath':
74
- $tab = 'landingPagePath';
75
- break;
76
- case 'language':
77
- $tab = 'language';
78
- break;
79
- case 'browser':
80
- $tab = 'browser';
81
- break;
82
- case 'os':
83
- $tab = 'operatingSystem';
84
- break;
85
- case 'device_overview':
86
- $tab = 'deviceCategory';
87
- break;
88
- case 'devices':
89
- $tab = 'mobileDeviceInfo';
90
- break;
91
- case 'realtime':
92
- $tab = 'realTime';
93
- break;
94
- case 'custom':
95
- $tab = 'custom';
96
- break;
97
- case 'eventsCategory':
98
- $tab = 'eventCategory';
99
- break;
100
- case 'eventsAction':
101
- $tab = 'eventAction';
102
- break;
103
- case 'eventsLabel':
104
- $tab = 'eventLabel';
105
- break;
106
- case 'goals':
107
- $tab = 'goals';
108
- break;
109
- case 'userGender':
110
- $tab = 'userGender';
111
- break;
112
- case 'userAge':
113
- $tab = 'userAgeBracket';
114
- break;
115
- case 'adWords':
116
- $tab = 'adGroup';
117
- break;
118
- case 'otherCategory':
119
- $tab = 'interestOtherCategory';
120
- break;
121
- case 'affinityCategory':
122
- $tab = 'interestAffinityCategory';
123
- break;
124
- case 'inMarket':
125
- $tab = 'interestInMarketCategory';
126
- break;
127
- case 'trafficSource':
128
- $tab = 'source';
129
- break;
130
- case 'siteSpeed':
131
- $tab = 'siteSpeed';
132
- break;
133
- case 'adsense':
134
- $tab = 'adsense';
135
- break;
136
- case 'productName':
137
- $tab = 'productName';
138
- break;
139
- case 'productCategory':
140
- $tab = 'productCategory';
141
- break;
142
- case 'productSku':
143
- $tab = 'productSku';
144
- break;
145
- case 'transactionId':
146
- $tab = 'transactionId';
147
- break;
148
- case 'daysToTransaction':
149
- $tab = 'daysToTransaction';
150
- break;
151
- case 'sales_performance':
152
- $tab = 'sales_performance';
153
- break;
154
- default:
155
- if($tabs != ''){
156
- $tab = key($tabs);
157
- }
158
- else{
159
- $tab = 'date';
160
- }
161
- break;
162
- }
163
- }
164
- ?>
165
- <input id="gawd_filter_val" type="hidden" value="">
166
- <div class="resp_metrics_menu"><div class="menu_metrics_img"></div><div class="button_label">FILTERS</div><div class="clear"></div></div>
167
- <div id="gawd_right_conteiner">
168
- <h3 id="gawd_page_title">Audience</h3>
169
- <div class="filter_conteiner">
170
- <div id="metric_conteiner" class="float_conteiner">
171
- <div class="gawd_metrics">
172
- <?php
173
- if($tab == 'date'){
174
- ?>
175
- <div id="first_metric" >
176
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
177
- <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
178
- <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
179
- <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
180
- <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
181
- <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
182
- <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
183
- <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
184
- </select>
185
- </div>
186
- <div id="metric_compare">
187
- <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
188
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
189
- <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
190
- <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
191
- <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
192
- <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
193
- <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
194
- <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
195
- <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
196
- </select>
197
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
198
- </div>
199
- <?php
200
- }
201
- elseif($tab == 'inMarket' || $tab == 'affinityCategory' || $tab == 'otherCategory' || $tab == 'country' || $tab == 'language' || $tab == 'userType' || $tab == 'sessionDurationBucket' || $tab == 'userAgeBracket' || $tab == 'userGender' || $tab == 'mobileDeviceInfo' || $tab == 'deviceCategory' || $tab == 'operatingSystem' || $tab == 'browser' || $tab =='interestInMarketCategory' || $tab == 'interestAffinityCategory' || $tab == 'interestOtherCategory' || $tab == 'source'){
202
- ?>
203
- <div id="first_metric" >
204
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
205
- <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
206
- <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
207
- <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
208
- <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
209
- <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
210
- <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
211
- <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
212
- </select>
213
- </div>
214
- <div id="metric_compare">
215
- <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
216
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
217
- <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
218
- <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
219
- <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
220
- <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
221
- <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
222
- <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
223
- <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
224
- </select>
225
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
226
- </div>
227
- <?php
228
- }
229
- elseif($tab == 'eventLabel' || $tab == 'eventAction' || $tab == 'eventCategory'){
230
- ?>
231
- <div id="first_metric" >
232
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
233
- <option value="totalEvents" ><?php echo __('Total Events', 'gawd'); ?></option>
234
- <option value="uniqueEvents" ><?php echo __('Unique Events', 'gawd'); ?></option>
235
- <option value="eventValue" ><?php echo __('Event Value', 'gawd'); ?></option>
236
- <option value="avgEventValue" ><?php echo __('Average Event Value', 'gawd'); ?></option>
237
- <option value="sessionsWithEvent" ><?php echo __('Session with Event', 'gawd'); ?></option>
238
- <option value="eventsPerSessionWithEvent" ><?php echo __('Events per Session with Event ', 'gawd'); ?></option>
239
- </select>
240
- </div>
241
- <div id="metric_compare">
242
- <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
243
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
244
- <option value="totalEvents" ><?php echo __('Total Events', 'gawd'); ?></option>
245
- <option value="uniqueEvents" ><?php echo __('Unique Events', 'gawd'); ?></option>
246
- <option value="eventValue" ><?php echo __('Event Value', 'gawd'); ?></option>
247
- <option value="avgEventValue" ><?php echo __('Average Event Value', 'gawd'); ?></option>
248
- <option value="sessionsWithEvent" ><?php echo __('Session with Event', 'gawd'); ?></option>
249
- <option value="eventsPerSessionWithEvent" ><?php echo __('Events per Session with Event ', 'gawd'); ?></option>
250
- </select>
251
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
252
- </div>
253
- <?php
254
- }
255
- elseif($tab == 'goals'){
256
- ?>
257
- <div id="first_metric" >
258
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
259
- <?php
260
- if (!empty($goals)) {
261
- foreach ($goals as $goal) {
262
- echo '<option value="'. $goal['name'] . '">' . $goal['name'] . ' (Goal' . $goal['id'] . ' Completions)' . '</option>';
263
- }
264
- }
265
- ?>
266
- </select>
267
- </div>
268
- <div id="metric_compare">
269
- <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
270
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
271
- <?php
272
- if (!empty($goals)) {
273
- foreach ($goals as $goal) {
274
- echo '<option value="' . $goal['name'] . '">' . $goal['name'] . ' (Goal' . $goal['id'] . ' Completions)' . '</option>';
275
- }
276
- }
277
- ?>
278
- </select>
279
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
280
- </div>
281
- <?php
282
- }
283
- elseif($tab == 'siteSpeed'){
284
- ?>
285
- <div id="first_metric" >
286
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
287
- <option value="avgPageLoadTime" ><?php echo __('Avg. Page Load Time', 'gawd'); ?></option>
288
- <option value="avgRedirectionTime" ><?php echo __('Avg. Redirection Time', 'gawd'); ?></option>
289
- <option value="avgServerResponseTime" ><?php echo __('Avg. Server Response Time', 'gawd'); ?></option>
290
- <option value="avgPageDownloadTime" ><?php echo __('Avg. Page Download Time', 'gawd'); ?></option>
291
- </select>
292
- </div>
293
- <div id="metric_compare">
294
- <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
295
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
296
- <option value="avgPageLoadTime" ><?php echo __('Avg. Page Load Time', 'gawd'); ?></option>
297
- <option value="avgRedirectionTime" ><?php echo __('Avg. Redirection Time', 'gawd'); ?></option>
298
- <option value="avgServerResponseTime" ><?php echo __('Avg. Server Response Time', 'gawd'); ?></option>
299
- <option value="avgPageDownloadTime" ><?php echo __('Avg. Page Download Time', 'gawd'); ?></option>
300
- </select>
301
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
302
- </div>
303
- <?php
304
- }
305
- elseif($tab == 'adsense'){
306
- ?>
307
- <div id="first_metric" >
308
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
309
- <option value="adsenseRevenue" ><?php echo __('AdSense Revenue', 'gawd'); ?></option>
310
- <option value="adsenseAdsClicks" ><?php echo __('AdSense Ads Clicked', 'gawd'); ?></option>
311
- </select>
312
- </div>
313
- <div id="metric_compare">
314
- <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
315
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
316
- <option value="adsenseRevenue" ><?php echo __('AdSense Revenue', 'gawd'); ?></option>
317
- <option value="adsenseAdsClicks" ><?php echo __('AdSense Ads Clicked', 'gawd'); ?></option>
318
- </select>
319
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
320
- </div>
321
- <?php
322
- }
323
- elseif($tab == 'socialActivityNetworkAction' || $tab == 'socialActivityAction' || $tab == 'socialActivityTagsSummary' || $tab == 'socialActivityPost' || $tab == 'socialActivityTimestamp' || $tab == 'socialActivityUserProfileUrl' || $tab == 'socialActivityContentUrl' || $tab == 'socialActivityUserPhotoUrl' || $tab == 'socialActivityUserHandle' || $tab == 'socialActivityEndorsingUrl' || $tab == 'socialEndorsingUrl' || $tab == 'socialActivityDisplayName'){
324
- ?>
325
- <div id="first_metric" >
326
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
327
- <option value="socialActivities" ><?php echo __('Social Activity', 'gawd'); ?></option>
328
- </select>
329
- </div>
330
- <?php
331
- }
332
- elseif($tab == 'adGroup'){
333
- ?>
334
- <div id="first_metric" >
335
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
336
- <option value="adClicks" ><?php echo __('Clicks', 'gawd'); ?></option>
337
- <option value="adCost" ><?php echo __('Cost', 'gawd'); ?></option>
338
- </select>
339
- </div>
340
- <div id="metric_compare">
341
- <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
342
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
343
- <option value="adClicks" ><?php echo __('Clicks', 'gawd'); ?></option>
344
- <option value="adCost" ><?php echo __('Cost', 'gawd'); ?></option>
345
- </select>
346
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
347
- </div>
348
- <?php
349
- }
350
- elseif($tab == 'productCategory' || $tab == 'productName' || $tab == 'productSku'){
351
- ?>
352
- <div id="first_metric" >
353
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
354
- <option value="itemRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
355
- <option value="uniquePurchases" ><?php echo __('Unique Purchases', 'gawd'); ?></option>
356
- <option value="itemQuantity" ><?php echo __('Quantity', 'gawd'); ?></option>
357
- <option value="itemsPerPurchase" ><?php echo __('Average QTY', 'gawd'); ?></option>
358
- </select>
359
- </div>
360
- <div id="metric_compare">
361
- <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
362
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
363
- <option value="itemRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
364
- <option value="uniquePurchases" ><?php echo __('Unique Purchases', 'gawd'); ?></option>
365
- <option value="itemQuantity" ><?php echo __('Quantity', 'gawd'); ?></option>
366
- <option value="itemsPerPurchase" ><?php echo __('Average QTY', 'gawd'); ?></option>
367
- </select>
368
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
369
- </div>
370
- <?php
371
- }
372
- elseif($tab == 'transactionId'){
373
- ?>
374
- <div id="first_metric" >
375
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
376
- <option value="transactionRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
377
- <option value="transactionTax" ><?php echo __('Tax', 'gawd'); ?></option>
378
- <option value="transactionShipping" ><?php echo __('Shipping', 'gawd'); ?></option>
379
- <option value="itemQuantity" ><?php echo __('Quantity', 'gawd'); ?></option>
380
- </select>
381
- </div>
382
- <div id="metric_compare">
383
- <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
384
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
385
- <option value="transactionRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
386
- <option value="transactionTax" ><?php echo __('Tax', 'gawd'); ?></option>
387
- <option value="transactionShipping" ><?php echo __('Shipping', 'gawd'); ?></option>
388
- <option value="itemQuantity" ><?php echo __('Quantity', 'gawd'); ?></option>
389
- </select>
390
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
391
- </div>
392
- <?php
393
- }
394
- elseif($tab == 'sales_performance'){
395
- ?>
396
- <div id="first_metric" >
397
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
398
- <option value="transactionRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
399
- <option value="transactionsPerSession" ><?php echo __('Ecommerce Conversion Rate', 'gawd'); ?></option>
400
- </select>
401
- </div>
402
-
403
- <?php
404
- }
405
- elseif($tab == 'daysToTransaction'){
406
- ?>
407
- <div id="first_metric" >
408
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
409
- <option value="transactions" ><?php echo __('Transactions', 'gawd'); ?></option>
410
- </select>
411
- </div>
412
-
413
- <?php
414
- }
415
- elseif(strpos($tab,'custom_report')!==false){
416
- $tab = substr($page,14);
417
- ?>
418
- <div id="first_metric" >
419
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
420
- <option value="<?php echo $get_custom_reports[$tab]['metric'];?>" ><?php echo __(preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $get_custom_reports[$tab]['metric'])))), 'gawd'); ?></option>
421
-
422
- </select>
423
- </div>
424
- <?php
425
- $tab = $get_custom_reports[$tab]['dimension'];
426
- }
427
- elseif($tab == 'custom') { ?>
428
- <div id="first_metric" >
429
- <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
430
- <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
431
- <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
432
- <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
433
- <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
434
- <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
435
- <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
436
- <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
437
- </select>
438
- </div>
439
- <div id="metric_compare">
440
- <?php
441
- $dimensions = $gawd_client->get_custom_dimensions();
442
- if('no_custom_dimensions_exist' == $dimensions) { ?>
443
- <select class="load_tooltip" data-hint="Select the second metric to compare reports.">
444
- <option value="0">There are no custom dimensions set for current profile.</option>
445
- </select>
446
- <?php } else { ?>
447
- <select name="gawd_custom_option" id="gawd_custom_option" class="gawd_draw_analytics">
448
- <?php foreach ($dimensions as $dimension) : ?>
449
- <option value="<?php echo $dimension['id'] ?>"><?php echo $dimension['name'] ?></option>
450
- <?php endforeach; ?>
451
- </select>
452
- <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
453
- <?php }
454
- ?>
455
- </div>
456
- <?php } ?>
457
- </div>
458
-
459
- <input id="gawd_tab" type="hidden" value="<?php echo $tab; ?>">
460
-
461
- <?php if($tab != 'custom' && $tab != 'pagePath' && $tab != 'landingPagePath' && $tab != 'realTime' && $tab != 'daysToTransaction' && $tab != 'sales_performance' && strpos($_GET['tab'],'custom_report') === false) { ?>
462
- <div class="vs_image" class="gawd_metrics">
463
- <img width="30px" src="<?php echo GAWD_URL;?>/assets/vs.png">
464
- </div>
465
- <?php } ?>
466
- <div class='clear'></div>
467
- </div>
468
- <?php if($tab != 'realTime') { ?>
469
- <div id="date_chart_conteiner" class="float_conteiner">
470
- <div class="gawd_row load_tooltip" data-hint="Choose Line, Pie or Column chart type to view your Google Analytics report with.">
471
- <div id="gawd_text" class="gawd_text">
472
- CHART
473
- </div>
474
- <div class="gawd_content" id="gawd_content_chart" >
475
- <select name="gawd_chart_type" id="gawd_chart_type" class="gawd_draw_analytics">
476
- <?php if($tab == 'userGender' || $tab == 'userAgeBracket' || $tab == 'userType' || $tab == 'country' || $tab == 'language' || $tab == 'mobileDeviceInfo' || $tab == 'deviceCategory' || $tab == 'operatingSystem' || $tab == 'browser'){
477
- ?>
478
- <option value="pie" ><?php echo __('Pie Chart', 'gawd'); ?></option>
479
- <option value="column" ><?php echo __('Columns', 'gawd'); ?></option>
480
- <option value="line" ><?php echo __('Line Chart', 'gawd'); ?></option>
481
- <?php
482
- }
483
- else{
484
- ?>
485
- <option value="line" ><?php echo __('Line Chart', 'gawd'); ?></option>
486
- <option value="pie" ><?php echo __('Pie Chart', 'gawd'); ?></option>
487
- <option value="column" ><?php echo __('Columns', 'gawd'); ?></option>
488
- <?php };?>
489
- </select>
490
- </div>
491
- <div class='clear'></div>
492
- </div >
493
- <div class="gawd_row load_tooltip" data-hint="Select one of predefined date ranges or specify a custom period for your report.">
494
- <div class="gawd_text" >
495
- DATE
496
- </div>
497
- <div class="gawd_content" id="gawd_content_range" >
498
- <div id="reportrange" class="pull-right" style="float:none !important">
499
- <span></span> <b class="caret"></b>
500
- </div>
501
- <input type="hidden" id="gawd_start_end_date"/>
502
- </div>
503
- <div class='clear'></div>
504
- </div>
505
- <div class='clear'></div>
506
- </div>
507
- <?php } ?>
508
- <div id="compare_time_conteiner" class="float_conteiner">
509
- <?php if(($tab == 'date') || ($tab == 'adsense') || ($tab == 'siteSpeed') || $tab == 'sales_performance' || $tab == 'pagePath' || $tab == 'landingPagePath'){ ?>
510
- <div class="gawd_date_filter_container load_tooltip" data-hint="Set the scale of your statistics graph. It will separate graph results hourly, daily, weekly and monthly.">
511
- <ul class="gawd_list">
512
- <li class="gawd_list_item" id="gawd_hour"><a href='#' class="gawd_filter_item" data-type="hour">Hour</a></li>
513
- <li class="gawd_list_item" id="gawd_day"><a href='#' class="gawd_filter_item" data-type="date">Day</a></li>
514
- <li class="gawd_list_item" id="gawd_week"><a href='#' class="gawd_filter_item" data-type="week">Week</a></li>
515
- <li class="gawd_list_item" id="gawd_month"><a href='#' class="gawd_filter_item" data-type="month">Month</a></li>
516
- </ul>
517
- </div>
518
- <div id="compare_datepicker_wraper" class="load_tooltip" data-hint="Measure the results of Google Analytics tracking of two periods. Select Previous Period, Previous Year, or define a custom period using the datepicker.">COMPARE DATE</div>
519
- <div id="" class="pull-right" style="float:none !important">
520
- </div>
521
- <input type="hidden" id="gawd_start_end_date_compare"/>
522
- <div class='clear'></div>
523
- <?php } ?>
524
- </div>
525
- <div class='clear'></div>
526
- </div>
527
- <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
528
- </form>
529
-
530
- <div class="gawd_chart_conteiner">
531
- <div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div>
532
- <div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;">
533
- <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
534
- </div>
535
- <div id="chartdiv"></div>
536
- <?php if($tab != 'realTime'){
537
- ?>
538
- <div id="gawd_buttons">
539
- <span id="country_filter_reset" class="button_gawd">Back</span>
540
- <span class='clear'></span>
541
- <input class="button_gawd" type="button" id="gawd_export_buttons" value="EXPORT"/>
542
- <input class="button_gawd load_tooltip" type="button" id="gawd_email_button" data-hint="Click to forward this report to selected email recipients, or schedule emails to be sent out periodically." value="EMAIL"/>
543
- <div class="gawd_exports">
544
- <a class='button gawd_export_button_csv' href="">CSV</a>
545
- <a class='button gawd_export_button_pdf' href="#">PDF</a>
546
- </div>
547
- </div>
548
- <?php };?>
549
- <table id="griddiv"></table>
550
- <div id="pager"></div>
551
- </div>
552
- </div>
553
- <div class='clear'></div>
554
-
555
- </div>
556
- <?php //get parameters for export?>
557
-
558
- <div class="gawd_email_popup_overlay">
559
- </div>
560
- <div class="gawd_email_popup">
561
- <a href="#" class="gawd_btn">X</a>
562
- <div class="gawd_email_body">
563
- <form method="post" action="" id="gawd_email_form">
564
- <div class="gawd_email_row load_tooltip" data-hint="E-mail to send reports from. You can change it from WordPress Settings > General > Email Address.">
565
- <div class="gawd_email_label">From</div>
566
- <div class="gawd_email_input gawd_email_input_from">
567
- <?php echo get_option('admin_email'); ?>
568
- </div>
569
- <div class='clear'></div>
570
- </div>
571
- <div class="gawd_email_row load_tooltip" data-hint="Define one or more email report recipients separated by commas.">
572
- <div class="gawd_email_label">To</div>
573
- <div class="gawd_email_input">
574
- <input id="gawd_email_to" name="gawd_email_to" class="" type="text" value="">
575
- </div>
576
- <div class='clear'></div>
577
- </div>
578
- <div class="gawd_email_row load_tooltip" data-hint="Set the subject for email reports.">
579
- <div class="gawd_email_label">Subject</div>
580
- <div class="gawd_email_input">
581
- <input class="gawd_email_subject" name="gawd_email_subject" class="" type="text" value="">
582
- </div>
583
- <div class='clear'></div>
584
- </div>
585
- <div class="gawd_email_row">
586
- <div class="gawd_email_attachemnt load_tooltip" data-hint="Select type for report attachments, CSV or PDF.">Attachment</div>
587
- <div class="gawd_email_input_attachment" >
588
- <select id="gawd_attachment_type" name="export_type">
589
- <option value='csv'>CSV</option>
590
- <option value='pdf'>PDF</option>
591
- </select>
592
- </div>
593
- <div class="gawd_email_input gawd_email_month_day_div" id="gawd_email_month_day" data-hint="Select the day of month to send report on.">
594
- <div class="gawd_email_day_of_week">Day of Month</div>
595
- </div>
596
- <div class="gawd_email_input gawd_email_week_day_div" data-hint="Click on weekday to choose email report sending day." id="gawd_email_week_day">
597
- <div class="gawd_email_day_of_week">Day of Week</div>
598
- <input type="hidden" name="gawd_email_week_day" id="gawd_email_week_day_hidden" >
599
- </div>
600
- <div class='clear'></div>
601
- </div>
602
- <div class="gawd_email_row">
603
- <div class="gawd_email_frequency" data-hint="Send email report Once or set its frequency to Daily, Weekly or Monthly.">Frequency</div>
604
- <div class="gawd_email_input_frequency" id="gawd_email_period">
605
- <select name="gawd_email_period">
606
- <option value="once">Once</option>
607
- <option value="daily">Daily</option>
608
- <option value="gawd_weekly">Weekly</option>
609
- <option value="gawd_monthly">Monthly</option>
610
- </select>
611
- </div>
612
- <div class="gawd_email_input gawd_email_month_day_div" id="gawd_email_month_day">
613
- <div class="gawd_email_month_day">
614
- <select id="gawd_email_month_day_select" name="gawd_email_month_day">
615
- <?php
616
- for($i=1; $i<29; $i++){
617
-
618
- echo '<option value="'.$i.'">'.$i.'</option>';
619
- }
620
- ?>
621
- <option value="last">Last Day</option>
622
- </select>
623
- </div>
624
- <div class='clear'></div>
625
- </div>
626
- <div class="gawd_email_input gawd_email_week_day_div" id="gawd_email_week_day">
627
- <div class="gawd_email_week_days">
628
- <ul class="gawd_email_week_day_ul">
629
- <li class="gawd_email_week_day" data-atribute="sunday">Sun</li>
630
- <li class="gawd_email_week_day" data-atribute="monday">Mon</li>
631
- <li class="gawd_email_week_day" data-atribute="tuesday">Tue</li>
632
- <li class="gawd_email_week_day" data-atribute="wednsday">Wed</li>
633
- <li class="gawd_email_week_day" data-atribute="thursday">Thu</li>
634
- <li class="gawd_email_week_day" data-atribute="friday">Fri</li>
635
- <li class="gawd_email_week_day" data-atribute="saturday">Sat</li>
636
- </ul>
637
- </div>
638
- <input type="hidden" name="gawd_email_week_day" id="gawd_email_week_day_hidden" >
639
- </div>
640
- <div class='clear'></div>
641
- </div>
642
- <div class="gawd_email_row gawd_email_message_label" data-hint="Compose email content to be sent with your report.">
643
- Additional Message
644
- </div>
645
- <div class="gawd_email_row gawd_email_message">
646
- <textarea name="gawd_email_body" id="gawd_email_body"></textarea>
647
- </div>
648
- <input name="gawd_email_from" id="gawd_email_from" class="" type="hidden" value="<?php echo get_option('admin_email'); ?>">
649
- <input name="gawd_metric" id="gawd_email_metric" class="" type="hidden" value="">
650
- <input name="gawd_metric_compare" id="gawd_metric_compare" class="" type="hidden" value="">
651
- <input name="gawd_dimension" id="gawd_dimension" class="" type="hidden" value="<?php echo $tab; ?>">
652
- <input name="gawd_start_date" id="gawd_start_date" class="" type="hidden" value="">
653
- <input name="gawd_end_date" id="gawd_end_date" class="" type="hidden" value="">
654
- <input name="action" id="" class="" type="hidden" value="gawd_export">
655
- <input name="report_type" id="report_type" class="" type="hidden" value="email">
656
- <div class="gawd_email_send" id="email_submit">
657
- Send
658
- </div>
659
- <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
660
- </form>
661
- </div>
662
- <div class="email_message_cont"></div>
663
- </div>
664
- <canvas id='canvass' style="display:none"></canvas>
665
- <input id="first_data" class="" type="hidden" value="">
666
- <input id="second_data" class="" type="hidden" value="">
667
- <input id="dimension" class="" type="hidden" value="">
668
- <input id="first_data_sum" class="" type="hidden" value="">
669
- <input id="second_data_sum" class="" type="hidden" value="">
670
- <input id="second_start_date" class="" type="hidden" value="">
671
  <input id="second_end_date" class="" type="hidden" value="">
1
+ <?php
2
+ $goals = $gawd_client->get_management_goals();
3
+ if (!is_array($goals)) {
4
+ $goals = array();
5
+ }
6
+ $get_custom_reports = get_option('gawd_custom_reports');
7
+ if(!isset($_GET['tab'])){
8
+ $_GET['tab'] = 'general';
9
+ }
10
+ $tabs = get_option('gawd_menu_items');
11
+ $gawd_zoom_message = get_option('gawd_zoom_message');
12
+ $current_user = get_current_user_id();
13
+ $saved_user_menues = get_option('gawd_menu_for_user');
14
+ if($current_user != 1 && isset($saved_user_menues[$current_user])){
15
+ $tabs = array_intersect_key($tabs, $saved_user_menues[$current_user]);
16
+ }
17
+ ?>
18
+ <form method="post" id="gawd_view">
19
+
20
+ <div class="gawd_profiles" id="gawd_profile_wrapper">
21
+ <?php if($gawd_zoom_message === false){
22
+ ?>
23
+ <div class="gawd_zoom_message">
24
+ <span>You can zoom chart by dragging the mouse over it</span><input class="button_gawd" type="button" id="gawd_got_it" value="GOT IT"/>
25
+ </div>
26
+ <?php
27
+ }
28
+ ?>
29
+ <select class="gawd_profile_select" id="gawd_id" name="gawd_id" onchange="change_account(this)">
30
+ <?php foreach ($profiles as $property_name => $property): ?>
31
+ <optgroup label="<?php echo $property_name; ?>">
32
+ <?php foreach ($property as $profile):
33
+ $webPropertyId = $profile['webPropertyId'];
34
+ $id = $profile['id'];
35
+ $name = $profile['name'];
36
+ $selected = '';
37
+ if($id == $gawd_user_data['gawd_id']){
38
+ $selected = 'selected="selected"';
39
+ }
40
+ ?>
41
+ <option value="<?php echo $id; ?>" <?php echo $selected; ?>><?php echo $property_name.' - '.$name ; ?></option>
42
+ <?php endforeach ?>
43
+ </optgroup>
44
+ <?php endforeach ?>
45
+ </select>
46
+ <div class="clear"></div>
47
+ <input type="hidden" name='web_property_name' id='web_property_name'/>
48
+ </div>
49
+ <div id="gawd_body">
50
+ <?php
51
+ include_once('dashboard_menu.php');
52
+ $page = isset($_GET['tab']) ? $_GET['tab'] : 'overview';
53
+ if(strpos($page,'custom_report')!==false){
54
+ $tab = $page;
55
+ }
56
+ else{
57
+ switch ($page) {
58
+ case 'general':
59
+ $tab = 'date';
60
+ break;
61
+ case 'location':
62
+ $tab = 'country';
63
+ break;
64
+ case 'behaviour':
65
+ $tab = 'userType';
66
+ break;
67
+ case 'engagement':
68
+ $tab = 'sessionDurationBucket';
69
+ break;
70
+ case 'pagePath':
71
+ $tab = 'pagePath';
72
+ break;
73
+ case 'landingPagePath':
74
+ $tab = 'landingPagePath';
75
+ break;
76
+ case 'language':
77
+ $tab = 'language';
78
+ break;
79
+ case 'browser':
80
+ $tab = 'browser';
81
+ break;
82
+ case 'os':
83
+ $tab = 'operatingSystem';
84
+ break;
85
+ case 'device_overview':
86
+ $tab = 'deviceCategory';
87
+ break;
88
+ case 'devices':
89
+ $tab = 'mobileDeviceInfo';
90
+ break;
91
+ case 'realtime':
92
+ $tab = 'realTime';
93
+ break;
94
+ case 'custom':
95
+ $tab = 'custom';
96
+ break;
97
+ case 'eventsCategory':
98
+ $tab = 'eventCategory';
99
+ break;
100
+ case 'eventsAction':
101
+ $tab = 'eventAction';
102
+ break;
103
+ case 'eventsLabel':
104
+ $tab = 'eventLabel';
105
+ break;
106
+ case 'goals':
107
+ $tab = 'goals';
108
+ break;
109
+ case 'userGender':
110
+ $tab = 'userGender';
111
+ break;
112
+ case 'userAge':
113
+ $tab = 'userAgeBracket';
114
+ break;
115
+ case 'adWords':
116
+ $tab = 'adGroup';
117
+ break;
118
+ case 'otherCategory':
119
+ $tab = 'interestOtherCategory';
120
+ break;
121
+ case 'affinityCategory':
122
+ $tab = 'interestAffinityCategory';
123
+ break;
124
+ case 'inMarket':
125
+ $tab = 'interestInMarketCategory';
126
+ break;
127
+ case 'trafficSource':
128
+ $tab = 'source';
129
+ break;
130
+ case 'siteSpeed':
131
+ $tab = 'siteSpeed';
132
+ break;
133
+ case 'adsense':
134
+ $tab = 'adsense';
135
+ break;
136
+ case 'productName':
137
+ $tab = 'productName';
138
+ break;
139
+ case 'productCategory':
140
+ $tab = 'productCategory';
141
+ break;
142
+ case 'productSku':
143
+ $tab = 'productSku';
144
+ break;
145
+ case 'transactionId':
146
+ $tab = 'transactionId';
147
+ break;
148
+ case 'daysToTransaction':
149
+ $tab = 'daysToTransaction';
150
+ break;
151
+ case 'sales_performance':
152
+ $tab = 'sales_performance';
153
+ break;
154
+ default:
155
+ if($tabs != ''){
156
+ $tab = key($tabs);
157
+ }
158
+ else{
159
+ $tab = 'date';
160
+ }
161
+ break;
162
+ }
163
+ }
164
+ ?>
165
+ <input id="gawd_filter_val" type="hidden" value="">
166
+ <div class="resp_metrics_menu"><div class="menu_metrics_img"></div><div class="button_label">FILTERS</div><div class="clear"></div></div>
167
+ <div id="gawd_right_conteiner">
168
+ <h3 id="gawd_page_title">Audience</h3>
169
+ <div class="filter_conteiner">
170
+ <div id="metric_conteiner" class="float_conteiner">
171
+ <div class="gawd_metrics">
172
+ <?php
173
+ if($tab == 'date'){
174
+ ?>
175
+ <div id="first_metric" >
176
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
177
+ <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
178
+ <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
179
+ <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
180
+ <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
181
+ <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
182
+ <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
183
+ <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
184
+ </select>
185
+ </div>
186
+ <div id="metric_compare">
187
+ <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
188
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
189
+ <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
190
+ <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
191
+ <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
192
+ <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
193
+ <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
194
+ <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
195
+ <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
196
+ </select>
197
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
198
+ </div>
199
+ <?php
200
+ }
201
+ elseif($tab == 'inMarket' || $tab == 'affinityCategory' || $tab == 'otherCategory' || $tab == 'country' || $tab == 'language' || $tab == 'userType' || $tab == 'sessionDurationBucket' || $tab == 'userAgeBracket' || $tab == 'userGender' || $tab == 'mobileDeviceInfo' || $tab == 'deviceCategory' || $tab == 'operatingSystem' || $tab == 'browser' || $tab =='interestInMarketCategory' || $tab == 'interestAffinityCategory' || $tab == 'interestOtherCategory' || $tab == 'source'){
202
+ ?>
203
+ <div id="first_metric" >
204
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
205
+ <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
206
+ <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
207
+ <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
208
+ <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
209
+ <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
210
+ <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
211
+ <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
212
+ </select>
213
+ </div>
214
+ <div id="metric_compare">
215
+ <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
216
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
217
+ <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
218
+ <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
219
+ <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
220
+ <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
221
+ <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
222
+ <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
223
+ <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
224
+ </select>
225
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
226
+ </div>
227
+ <?php
228
+ }
229
+ elseif($tab == 'eventLabel' || $tab == 'eventAction' || $tab == 'eventCategory'){
230
+ ?>
231
+ <div id="first_metric" >
232
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
233
+ <option value="totalEvents" ><?php echo __('Total Events', 'gawd'); ?></option>
234
+ <option value="uniqueEvents" ><?php echo __('Unique Events', 'gawd'); ?></option>
235
+ <option value="eventValue" ><?php echo __('Event Value', 'gawd'); ?></option>
236
+ <option value="avgEventValue" ><?php echo __('Average Event Value', 'gawd'); ?></option>
237
+ <option value="sessionsWithEvent" ><?php echo __('Session with Event', 'gawd'); ?></option>
238
+ <option value="eventsPerSessionWithEvent" ><?php echo __('Events per Session with Event ', 'gawd'); ?></option>
239
+ </select>
240
+ </div>
241
+ <div id="metric_compare">
242
+ <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
243
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
244
+ <option value="totalEvents" ><?php echo __('Total Events', 'gawd'); ?></option>
245
+ <option value="uniqueEvents" ><?php echo __('Unique Events', 'gawd'); ?></option>
246
+ <option value="eventValue" ><?php echo __('Event Value', 'gawd'); ?></option>
247
+ <option value="avgEventValue" ><?php echo __('Average Event Value', 'gawd'); ?></option>
248
+ <option value="sessionsWithEvent" ><?php echo __('Session with Event', 'gawd'); ?></option>
249
+ <option value="eventsPerSessionWithEvent" ><?php echo __('Events per Session with Event ', 'gawd'); ?></option>
250
+ </select>
251
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
252
+ </div>
253
+ <?php
254
+ }
255
+ elseif($tab == 'goals'){
256
+ ?>
257
+ <div id="first_metric" >
258
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
259
+ <?php
260
+ if (!empty($goals)) {
261
+ foreach ($goals as $goal) {
262
+ echo '<option value="'. $goal['name'] . '">' . $goal['name'] . ' (Goal' . $goal['id'] . ' Completions)' . '</option>';
263
+ }
264
+ }
265
+ ?>
266
+ </select>
267
+ </div>
268
+ <div id="metric_compare">
269
+ <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
270
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
271
+ <?php
272
+ if (!empty($goals)) {
273
+ foreach ($goals as $goal) {
274
+ echo '<option value="' . $goal['name'] . '">' . $goal['name'] . ' (Goal' . $goal['id'] . ' Completions)' . '</option>';
275
+ }
276
+ }
277
+ ?>
278
+ </select>
279
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
280
+ </div>
281
+ <?php
282
+ }
283
+ elseif($tab == 'siteSpeed'){
284
+ ?>
285
+ <div id="first_metric" >
286
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
287
+ <option value="avgPageLoadTime" ><?php echo __('Avg. Page Load Time', 'gawd'); ?></option>
288
+ <option value="avgRedirectionTime" ><?php echo __('Avg. Redirection Time', 'gawd'); ?></option>
289
+ <option value="avgServerResponseTime" ><?php echo __('Avg. Server Response Time', 'gawd'); ?></option>
290
+ <option value="avgPageDownloadTime" ><?php echo __('Avg. Page Download Time', 'gawd'); ?></option>
291
+ </select>
292
+ </div>
293
+ <div id="metric_compare">
294
+ <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
295
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
296
+ <option value="avgPageLoadTime" ><?php echo __('Avg. Page Load Time', 'gawd'); ?></option>
297
+ <option value="avgRedirectionTime" ><?php echo __('Avg. Redirection Time', 'gawd'); ?></option>
298
+ <option value="avgServerResponseTime" ><?php echo __('Avg. Server Response Time', 'gawd'); ?></option>
299
+ <option value="avgPageDownloadTime" ><?php echo __('Avg. Page Download Time', 'gawd'); ?></option>
300
+ </select>
301
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
302
+ </div>
303
+ <?php
304
+ }
305
+ elseif($tab == 'adsense'){
306
+ ?>
307
+ <div id="first_metric" >
308
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
309
+ <option value="adsenseRevenue" ><?php echo __('AdSense Revenue', 'gawd'); ?></option>
310
+ <option value="adsenseAdsClicks" ><?php echo __('AdSense Ads Clicked', 'gawd'); ?></option>
311
+ </select>
312
+ </div>
313
+ <div id="metric_compare">
314
+ <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
315
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
316
+ <option value="adsenseRevenue" ><?php echo __('AdSense Revenue', 'gawd'); ?></option>
317
+ <option value="adsenseAdsClicks" ><?php echo __('AdSense Ads Clicked', 'gawd'); ?></option>
318
+ </select>
319
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
320
+ </div>
321
+ <?php
322
+ }
323
+ elseif($tab == 'socialActivityNetworkAction' || $tab == 'socialActivityAction' || $tab == 'socialActivityTagsSummary' || $tab == 'socialActivityPost' || $tab == 'socialActivityTimestamp' || $tab == 'socialActivityUserProfileUrl' || $tab == 'socialActivityContentUrl' || $tab == 'socialActivityUserPhotoUrl' || $tab == 'socialActivityUserHandle' || $tab == 'socialActivityEndorsingUrl' || $tab == 'socialEndorsingUrl' || $tab == 'socialActivityDisplayName'){
324
+ ?>
325
+ <div id="first_metric" >
326
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
327
+ <option value="socialActivities" ><?php echo __('Social Activity', 'gawd'); ?></option>
328
+ </select>
329
+ </div>
330
+ <?php
331
+ }
332
+ elseif($tab == 'adGroup'){
333
+ ?>
334
+ <div id="first_metric" >
335
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
336
+ <option value="adClicks" ><?php echo __('Clicks', 'gawd'); ?></option>
337
+ <option value="adCost" ><?php echo __('Cost', 'gawd'); ?></option>
338
+ </select>
339
+ </div>
340
+ <div id="metric_compare">
341
+ <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
342
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
343
+ <option value="adClicks" ><?php echo __('Clicks', 'gawd'); ?></option>
344
+ <option value="adCost" ><?php echo __('Cost', 'gawd'); ?></option>
345
+ </select>
346
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
347
+ </div>
348
+ <?php
349
+ }
350
+ elseif($tab == 'productCategory' || $tab == 'productName' || $tab == 'productSku'){
351
+ ?>
352
+ <div id="first_metric" >
353
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
354
+ <option value="itemRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
355
+ <option value="uniquePurchases" ><?php echo __('Unique Purchases', 'gawd'); ?></option>
356
+ <option value="itemQuantity" ><?php echo __('Quantity', 'gawd'); ?></option>
357
+ <option value="itemsPerPurchase" ><?php echo __('Average QTY', 'gawd'); ?></option>
358
+ </select>
359
+ </div>
360
+ <div id="metric_compare">
361
+ <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
362
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
363
+ <option value="itemRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
364
+ <option value="uniquePurchases" ><?php echo __('Unique Purchases', 'gawd'); ?></option>
365
+ <option value="itemQuantity" ><?php echo __('Quantity', 'gawd'); ?></option>
366
+ <option value="itemsPerPurchase" ><?php echo __('Average QTY', 'gawd'); ?></option>
367
+ </select>
368
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
369
+ </div>
370
+ <?php
371
+ }
372
+ elseif($tab == 'transactionId'){
373
+ ?>
374
+ <div id="first_metric" >
375
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
376
+ <option value="transactionRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
377
+ <option value="transactionTax" ><?php echo __('Tax', 'gawd'); ?></option>
378
+ <option value="transactionShipping" ><?php echo __('Shipping', 'gawd'); ?></option>
379
+ <option value="itemQuantity" ><?php echo __('Quantity', 'gawd'); ?></option>
380
+ </select>
381
+ </div>
382
+ <div id="metric_compare">
383
+ <select name="gawd_metric_compare" id="gawd_metric_compare" class="gawd_draw_analytics load_tooltip" data-hint="Select the second metric to compare reports.">
384
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
385
+ <option value="transactionRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
386
+ <option value="transactionTax" ><?php echo __('Tax', 'gawd'); ?></option>
387
+ <option value="transactionShipping" ><?php echo __('Shipping', 'gawd'); ?></option>
388
+ <option value="itemQuantity" ><?php echo __('Quantity', 'gawd'); ?></option>
389
+ </select>
390
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
391
+ </div>
392
+ <?php
393
+ }
394
+ elseif($tab == 'sales_performance'){
395
+ ?>
396
+ <div id="first_metric" >
397
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
398
+ <option value="transactionRevenue" ><?php echo __('Revenue', 'gawd'); ?></option>
399
+ <option value="transactionsPerSession" ><?php echo __('Ecommerce Conversion Rate', 'gawd'); ?></option>
400
+ </select>
401
+ </div>
402
+
403
+ <?php
404
+ }
405
+ elseif($tab == 'daysToTransaction'){
406
+ ?>
407
+ <div id="first_metric" >
408
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
409
+ <option value="transactions" ><?php echo __('Transactions', 'gawd'); ?></option>
410
+ </select>
411
+ </div>
412
+
413
+ <?php
414
+ }
415
+ elseif(strpos($tab,'custom_report')!==false){
416
+ $tab = substr($page,14);
417
+ ?>
418
+ <div id="first_metric" >
419
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
420
+ <option value="<?php echo $get_custom_reports[$tab]['metric'];?>" ><?php echo __(preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $get_custom_reports[$tab]['metric'])))), 'gawd'); ?></option>
421
+
422
+ </select>
423
+ </div>
424
+ <?php
425
+ $tab = $get_custom_reports[$tab]['dimension'];
426
+ }
427
+ elseif($tab == 'custom') { ?>
428
+ <div id="first_metric" >
429
+ <select name="gawd_metric" id="gawd_metric" class="gawd_draw_analytics load_tooltip" data-hint="Choose a metric to view overview graph.">
430
+ <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
431
+ <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
432
+ <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
433
+ <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
434
+ <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
435
+ <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
436
+ <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
437
+ </select>
438
+ </div>
439
+ <div id="metric_compare">
440
+ <?php
441
+ $dimensions = $gawd_client->get_custom_dimensions();
442
+ if('no_custom_dimensions_exist' == $dimensions) { ?>
443
+ <select class="load_tooltip" data-hint="Select the second metric to compare reports.">
444
+ <option value="0">There are no custom dimensions set for current profile.</option>
445
+ </select>
446
+ <?php } else { ?>
447
+ <select name="gawd_custom_option" id="gawd_custom_option" class="gawd_draw_analytics">
448
+ <?php foreach ($dimensions as $dimension) : ?>
449
+ <option value="<?php echo $dimension['id'] ?>"><?php echo $dimension['name'] ?></option>
450
+ <?php endforeach; ?>
451
+ </select>
452
+ <img src="<?php echo GAWD_URL. '/assets/cleardot.gif';?>"/>
453
+ <?php }
454
+ ?>
455
+ </div>
456
+ <?php } ?>
457
+ </div>
458
+
459
+ <input id="gawd_tab" type="hidden" value="<?php echo $tab; ?>">
460
+
461
+ <?php if($tab != 'custom' && $tab != 'pagePath' && $tab != 'landingPagePath' && $tab != 'realTime' && $tab != 'daysToTransaction' && $tab != 'sales_performance' && strpos($_GET['tab'],'custom_report') === false) { ?>
462
+ <div class="vs_image" class="gawd_metrics">
463
+ <img width="30px" src="<?php echo GAWD_URL;?>/assets/vs.png">
464
+ </div>
465
+ <?php } ?>
466
+ <div class='clear'></div>
467
+ </div>
468
+ <?php if($tab != 'realTime') { ?>
469
+ <div id="date_chart_conteiner" class="float_conteiner">
470
+ <div class="gawd_row load_tooltip" data-hint="Choose Line, Pie or Column chart type to view your Google Analytics report with.">
471
+ <div id="gawd_text" class="gawd_text">
472
+ CHART
473
+ </div>
474
+ <div class="gawd_content" id="gawd_content_chart" >
475
+ <select name="gawd_chart_type" id="gawd_chart_type" class="gawd_draw_analytics">
476
+ <?php if($tab == 'userGender' || $tab == 'userAgeBracket' || $tab == 'userType' || $tab == 'country' || $tab == 'language' || $tab == 'mobileDeviceInfo' || $tab == 'deviceCategory' || $tab == 'operatingSystem' || $tab == 'browser'){
477
+ ?>
478
+ <option value="pie" ><?php echo __('Pie Chart', 'gawd'); ?></option>
479
+ <option value="column" ><?php echo __('Columns', 'gawd'); ?></option>
480
+ <option value="line" ><?php echo __('Line Chart', 'gawd'); ?></option>
481
+ <?php
482
+ }
483
+ else{
484
+ ?>
485
+ <option value="line" ><?php echo __('Line Chart', 'gawd'); ?></option>
486
+ <option value="pie" ><?php echo __('Pie Chart', 'gawd'); ?></option>
487
+ <option value="column" ><?php echo __('Columns', 'gawd'); ?></option>
488
+ <?php };?>
489
+ </select>
490
+ </div>
491
+ <div class='clear'></div>
492
+ </div >
493
+ <div class="gawd_row load_tooltip" data-hint="Select one of predefined date ranges or specify a custom period for your report.">
494
+ <div class="gawd_text" >
495
+ DATE
496
+ </div>
497
+ <div class="gawd_content" id="gawd_content_range" >
498
+ <div id="reportrange" class="pull-right" style="float:none !important">
499
+ <span></span> <b class="caret"></b>
500
+ </div>
501
+ <input type="hidden" id="gawd_start_end_date"/>
502
+ </div>
503
+ <div class='clear'></div>
504
+ </div>
505
+ <div class='clear'></div>
506
+ </div>
507
+ <?php } ?>
508
+ <div id="compare_time_conteiner" class="float_conteiner">
509
+ <?php if(($tab == 'date') || ($tab == 'adsense') || ($tab == 'siteSpeed') || $tab == 'sales_performance' || $tab == 'pagePath' || $tab == 'landingPagePath'){ ?>
510
+ <div class="gawd_date_filter_container load_tooltip" data-hint="Set the scale of your statistics graph. It will separate graph results hourly, daily, weekly and monthly.">
511
+ <ul class="gawd_list">
512
+ <li class="gawd_list_item" id="gawd_hour"><a href='#' class="gawd_filter_item" data-type="hour">Hour</a></li>
513
+ <li class="gawd_list_item" id="gawd_day"><a href='#' class="gawd_filter_item" data-type="date">Day</a></li>
514
+ <li class="gawd_list_item" id="gawd_week"><a href='#' class="gawd_filter_item" data-type="week">Week</a></li>
515
+ <li class="gawd_list_item" id="gawd_month"><a href='#' class="gawd_filter_item" data-type="month">Month</a></li>
516
+ </ul>
517
+ </div>
518
+ <div id="compare_datepicker_wraper" class="load_tooltip" data-hint="Measure the results of Google Analytics tracking of two periods. Select Previous Period, Previous Year, or define a custom period using the datepicker.">COMPARE DATE</div>
519
+ <div id="" class="pull-right" style="float:none !important">
520
+ </div>
521
+ <input type="hidden" id="gawd_start_end_date_compare"/>
522
+ <div class='clear'></div>
523
+ <?php } ?>
524
+ </div>
525
+ <div class='clear'></div>
526
+ </div>
527
+ <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
528
+ </form>
529
+
530
+ <div class="gawd_chart_conteiner">
531
+ <div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div>
532
+ <div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;">
533
+ <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
534
+ </div>
535
+ <div id="chartdiv"></div>
536
+ <?php if($tab != 'realTime'){
537
+ ?>
538
+ <div id="gawd_buttons">
539
+ <span id="country_filter_reset" class="button_gawd">Back</span>
540
+ <span class='clear'></span>
541
+ <input class="button_gawd" type="button" id="gawd_export_buttons" value="EXPORT"/>
542
+ <input class="button_gawd load_tooltip" type="button" id="gawd_email_button" data-hint="Click to forward this report to selected email recipients, or schedule emails to be sent out periodically." value="EMAIL"/>
543
+ <div class="gawd_exports">
544
+ <a class='button gawd_export_button_csv' href="">CSV</a>
545
+ <a class='button gawd_export_button_pdf' href="#">PDF</a>
546
+ </div>
547
+ </div>
548
+ <?php };?>
549
+ <table id="griddiv"></table>
550
+ <div id="pager"></div>
551
+ </div>
552
+ </div>
553
+ <div class='clear'></div>
554
+
555
+ </div>
556
+ <?php //get parameters for export?>
557
+
558
+ <div class="gawd_email_popup_overlay">
559
+ </div>
560
+ <div class="gawd_email_popup">
561
+ <a href="#" class="gawd_btn">X</a>
562
+ <div class="gawd_email_body">
563
+ <form method="post" action="" id="gawd_email_form">
564
+ <div class="gawd_email_row load_tooltip" data-hint="E-mail to send reports from. You can change it from WordPress Settings > General > Email Address.">
565
+ <div class="gawd_email_label">From</div>
566
+ <div class="gawd_email_input gawd_email_input_from">
567
+ <?php echo get_option('admin_email'); ?>
568
+ </div>
569
+ <div class='clear'></div>
570
+ </div>
571
+ <div class="gawd_email_row load_tooltip" data-hint="Define one or more email report recipients separated by commas.">
572
+ <div class="gawd_email_label">To</div>
573
+ <div class="gawd_email_input">
574
+ <input id="gawd_email_to" name="gawd_email_to" class="" type="text" value="">
575
+ </div>
576
+ <div class='clear'></div>
577
+ </div>
578
+ <div class="gawd_email_row load_tooltip" data-hint="Set the subject for email reports.">
579
+ <div class="gawd_email_label">Subject</div>
580
+ <div class="gawd_email_input">
581
+ <input class="gawd_email_subject" name="gawd_email_subject" class="" type="text" value="">
582
+ </div>
583
+ <div class='clear'></div>
584
+ </div>
585
+ <div class="gawd_email_row">
586
+ <div class="gawd_email_attachemnt load_tooltip" data-hint="Select type for report attachments, CSV or PDF.">Attachment</div>
587
+ <div class="gawd_email_input_attachment" >
588
+ <select id="gawd_attachment_type" name="export_type">
589
+ <option value='csv'>CSV</option>
590
+ <option value='pdf'>PDF</option>
591
+ </select>
592
+ </div>
593
+ <div class="gawd_email_input gawd_email_month_day_div" id="gawd_email_month_day" data-hint="Select the day of month to send report on.">
594
+ <div class="gawd_email_day_of_week">Day of Month</div>
595
+ </div>
596
+ <div class="gawd_email_input gawd_email_week_day_div" data-hint="Click on weekday to choose email report sending day." id="gawd_email_week_day">
597
+ <div class="gawd_email_day_of_week">Day of Week</div>
598
+ <input type="hidden" name="gawd_email_week_day" id="gawd_email_week_day_hidden" >
599
+ </div>
600
+ <div class='clear'></div>
601
+ </div>
602
+ <div class="gawd_email_row">
603
+ <div class="gawd_email_frequency" data-hint="Send email report Once or set its frequency to Daily, Weekly or Monthly.">Frequency</div>
604
+ <div class="gawd_email_input_frequency" id="gawd_email_period">
605
+ <select name="gawd_email_period">
606
+ <option value="once">Once</option>
607
+ <option value="daily">Daily</option>
608
+ <option value="gawd_weekly">Weekly</option>
609
+ <option value="gawd_monthly">Monthly</option>
610
+ </select>
611
+ </div>
612
+ <div class="gawd_email_input gawd_email_month_day_div" id="gawd_email_month_day">
613
+ <div class="gawd_email_month_day">
614
+ <select id="gawd_email_month_day_select" name="gawd_email_month_day">
615
+ <?php
616
+ for($i=1; $i<29; $i++){
617
+
618
+ echo '<option value="'.$i.'">'.$i.'</option>';
619
+ }
620
+ ?>
621
+ <option value="last">Last Day</option>
622
+ </select>
623
+ </div>
624
+ <div class='clear'></div>
625
+ </div>
626
+ <div class="gawd_email_input gawd_email_week_day_div" id="gawd_email_week_day">
627
+ <div class="gawd_email_week_days">
628
+ <ul class="gawd_email_week_day_ul">
629
+ <li class="gawd_email_week_day" data-atribute="sunday">Sun</li>
630
+ <li class="gawd_email_week_day" data-atribute="monday">Mon</li>
631
+ <li class="gawd_email_week_day" data-atribute="tuesday">Tue</li>
632
+ <li class="gawd_email_week_day" data-atribute="wednsday">Wed</li>
633
+ <li class="gawd_email_week_day" data-atribute="thursday">Thu</li>
634
+ <li class="gawd_email_week_day" data-atribute="friday">Fri</li>
635
+ <li class="gawd_email_week_day" data-atribute="saturday">Sat</li>
636
+ </ul>
637
+ </div>
638
+ <input type="hidden" name="gawd_email_week_day" id="gawd_email_week_day_hidden" >
639
+ </div>
640
+ <div class='clear'></div>
641
+ </div>
642
+ <div class="gawd_email_row gawd_email_message_label" data-hint="Compose email content to be sent with your report.">
643
+ Additional Message
644
+ </div>
645
+ <div class="gawd_email_row gawd_email_message">
646
+ <textarea name="gawd_email_body" id="gawd_email_body"></textarea>
647
+ </div>
648
+ <input name="gawd_email_from" id="gawd_email_from" class="" type="hidden" value="<?php echo get_option('admin_email'); ?>">
649
+ <input name="gawd_metric" id="gawd_email_metric" class="" type="hidden" value="">
650
+ <input name="gawd_metric_compare" id="gawd_metric_compare" class="" type="hidden" value="">
651
+ <input name="gawd_dimension" id="gawd_dimension" class="" type="hidden" value="<?php echo $tab; ?>">
652
+ <input name="gawd_start_date" id="gawd_start_date" class="" type="hidden" value="">
653
+ <input name="gawd_end_date" id="gawd_end_date" class="" type="hidden" value="">
654
+ <input name="action" id="" class="" type="hidden" value="gawd_export">
655
+ <input name="report_type" id="report_type" class="" type="hidden" value="email">
656
+ <div class="gawd_email_send" id="email_submit">
657
+ Send
658
+ </div>
659
+ <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
660
+ </form>
661
+ </div>
662
+ <div class="email_message_cont"></div>
663
+ </div>
664
+ <canvas id='canvass' style="display:none"></canvas>
665
+ <input id="first_data" class="" type="hidden" value="">
666
+ <input id="second_data" class="" type="hidden" value="">
667
+ <input id="dimension" class="" type="hidden" value="">
668
+ <input id="first_data_sum" class="" type="hidden" value="">
669
+ <input id="second_data_sum" class="" type="hidden" value="">
670
+ <input id="second_start_date" class="" type="hidden" value="">
671
  <input id="second_end_date" class="" type="hidden" value="">
admin/pages/dashboard_menu.php CHANGED
@@ -1,120 +1,120 @@
1
- <?php
2
- function gawd_write_menu($tabs, $title = true){
3
- $sub_arrow = '<span class="gawd_menu_li_sub_arrow"></span>';
4
- foreach ($tabs as $tab_key => $tab_data){
5
- if(!$title){
6
- $tab_data["title"] = "";
7
- $sub_arrow = '';
8
- }
9
- if($tab_data["childs"] == array()){
10
- $active_tab = $_GET['tab'] == $tab_key ? 'gawd_active_li' : '';
11
- if($tab_key == 'customReport'){
12
- echo ' <li class="gawd_menu_li load_tooltip '.$active_tab.'" id="gawd_'.$tab_key.'" data-hint="'.$tab_data["desc"].'">
13
- <a class="gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_custom_reports">'.$tab_data["title"].'</a>
14
- </li>';
15
- }
16
- elseif($tab_key == 'custom'){
17
- echo ' <li class="gawd_menu_li load_tooltip '.$active_tab.'" id="gawd_'.$tab_key.'" data-hint="'.$tab_data["desc"].'">
18
- <a class="gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_tracking">'.$tab_data["title"].'</a>
19
- </li>';
20
- }
21
- elseif($tab_key == 'adsense' || $tab_key == 'adWords'){
22
- echo ' <li class="gawd_menu_li load_tooltip '.$active_tab.'" id="gawd_'.$tab_key.'" data-hint="'.$tab_data["desc"].'">
23
- <a class="gawd_menu_item " href="#">'.$tab_data["title"].'</a>
24
- </li>';
25
- }
26
- else{
27
- echo ' <li class="gawd_menu_li load_tooltip '.$active_tab.'" id="gawd_'.$tab_key.'" data-hint="'.$tab_data["desc"].'">
28
- <a class="gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_reports&tab='.$tab_key.'">'.$tab_data["title"].'</a>
29
- </li>';
30
- }
31
- }
32
- else{
33
- if($tab_key == 'customReport'){
34
- echo ' <li class="gawd_menu_li " id="gawd_'.$tab_key.'_li">
35
- <span id="gawd_'.$tab_key.'s" class="gawd_menu_li_sub">'.$tab_data["title"].$sub_arrow.'
36
- </span>
37
- <ul id="gawd_'.$tab_key.'_ul">';
38
- }
39
- else{
40
- echo ' <li class="gawd_menu_li load_tooltip" id="gawd_'.$tab_key.'_li" data-hint="'.$tab_data["desc"].'">
41
- <span id="gawd_'.$tab_key.'" class="gawd_menu_li_sub">'.$tab_data["title"].$sub_arrow.'
42
- </span>
43
- <ul id="gawd_'.$tab_key.'_ul">';
44
- }
45
- foreach($tab_data["childs"] as $child_key => $child_title) {
46
- if(!$title){
47
- $child_title = "";
48
- }
49
- $active_tab = $_GET['tab'] == $child_key ? 'gawd_active_li' : '';
50
- if($child_key == 'productCategory' || $child_key == 'productName' || $child_key == 'productSku' || $child_key == 'transactionId' || $child_key == 'sales_performance' || $child_key == 'daysToTransaction'){
51
- echo ' <li class="gawd_menu_ul_li '.$active_tab.'">
52
- <a class="gawd_menu_item " href="#">'.$child_title.'</a>
53
- </li> ';
54
- }
55
- else{
56
- echo ' <li class="gawd_menu_ul_li '.$active_tab.'">
57
- <a class="gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_reports&tab='.$child_key.'">'.$child_title.'</a>
58
- </li> ';
59
- }
60
- }
61
- echo '</ul>
62
- </li>';
63
- }
64
- }
65
- }
66
- function gawd_write_menu_collapse($tabs, $title = true){
67
- $sub_arrow = '<span class="gawd_menu_li_sub_arrow"></span>';
68
- foreach ($tabs as $tab_key => $tab_data){
69
- if(!$title){
70
- $tab_data["title"] = "";
71
- $sub_arrow = '';
72
- }
73
- if($tab_data["childs"] == array()){
74
- $active_tab = $_GET['tab'] == $tab_key ? 'gawd_active_li' : '';
75
- if($tab_key == 'customReport'){
76
- echo '<a id="gawd_'.$tab_key.'" class="'.$active_tab.' gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_custom_reports">'.$tab_data["title"].'</a>';
77
- }
78
- else{
79
- echo '<a id="gawd_'.$tab_key.'" class="'.$active_tab.' gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_reports&tab='.$tab_key.'">'.$tab_data["title"].'</a>';
80
- }
81
- }
82
- else{
83
- if($tab_key == 'customReport'){
84
- echo '<span id="gawd_'.$tab_key.'_li" id="gawd_'.$tab_key.'s" class="gawd_menu_li_sub">'.$tab_data["title"].$sub_arrow.'
85
- <div class="collapse_ul" id="gawd_'.$tab_key.'_ul">';
86
- }
87
- else{
88
- echo '<span id="gawd_'.$tab_key.'_li" id="gawd_'.$tab_key.'" class="gawd_menu_li_sub">'.$tab_data["title"].$sub_arrow.'
89
- <div class="collapse_ul" id="gawd_'.$tab_key.'_ul">';
90
- }
91
- foreach($tab_data["childs"] as $child_key => $child_title) {
92
- $active_tab = $_GET['tab'] == $child_key ? 'gawd_active_li_text' : '';
93
- echo '<a class="'.$active_tab.' gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_reports&tab='.$child_key.'">'.$child_title.'</a>';
94
- }
95
- echo '</div></span>';
96
- }
97
- }
98
-
99
- }
100
- ?>
101
- <div class="resp_menu"><div class="menu_img"></div><div class="button_label">REPORTS</div><div class="clear"></div></div>
102
-
103
- <div class="gawd_menu_coteiner_collapse">
104
- <div class="gawd_menu_ul">
105
- <?php
106
- gawd_write_menu_collapse($tabs,false);
107
- ?>
108
- <span class='gawd_collapsed'></span>
109
- </div>
110
- </div>
111
- <div class="gawd_menu_coteiner">
112
- <input style="width: 100%; margin-bottom: 5px;" onkeyup="gawd_search()" type="text" class='gawd_search_input'/>
113
- <ul class="gawd_menu_ul">
114
- <?php
115
-
116
- gawd_write_menu($tabs);
117
- ?>
118
- <li class='gawd_collapse'>Collapse menu</li>
119
- </ul>
120
  </div>
1
+ <?php
2
+ function gawd_write_menu($tabs, $title = true){
3
+ $sub_arrow = '<span class="gawd_menu_li_sub_arrow"></span>';
4
+ foreach ($tabs as $tab_key => $tab_data){
5
+ if(!$title){
6
+ $tab_data["title"] = "";
7
+ $sub_arrow = '';
8
+ }
9
+ if($tab_data["childs"] == array()){
10
+ $active_tab = $_GET['tab'] == $tab_key ? 'gawd_active_li' : '';
11
+ if($tab_key == 'customReport'){
12
+ echo ' <li class="gawd_menu_li load_tooltip '.$active_tab.'" id="gawd_'.$tab_key.'" data-hint="'.$tab_data["desc"].'">
13
+ <a class="gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_custom_reports">'.$tab_data["title"].'</a>
14
+ </li>';
15
+ }
16
+ elseif($tab_key == 'custom'){
17
+ echo ' <li class="gawd_menu_li load_tooltip '.$active_tab.'" id="gawd_'.$tab_key.'" data-hint="'.$tab_data["desc"].'">
18
+ <a class="gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_tracking">'.$tab_data["title"].'</a>
19
+ </li>';
20
+ }
21
+ elseif($tab_key == 'adsense' || $tab_key == 'adWords'){
22
+ echo ' <li class="gawd_menu_li load_tooltip '.$active_tab.'" id="gawd_'.$tab_key.'" data-hint="'.$tab_data["desc"].'">
23
+ <a class="gawd_menu_item " href="#">'.$tab_data["title"].'</a>
24
+ </li>';
25
+ }
26
+ else{
27
+ echo ' <li class="gawd_menu_li load_tooltip '.$active_tab.'" id="gawd_'.$tab_key.'" data-hint="'.$tab_data["desc"].'">
28
+ <a class="gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_reports&tab='.$tab_key.'">'.$tab_data["title"].'</a>
29
+ </li>';
30
+ }
31
+ }
32
+ else{
33
+ if($tab_key == 'customReport'){
34
+ echo ' <li class="gawd_menu_li " id="gawd_'.$tab_key.'_li">
35
+ <span id="gawd_'.$tab_key.'s" class="gawd_menu_li_sub">'.$tab_data["title"].$sub_arrow.'
36
+ </span>
37
+ <ul id="gawd_'.$tab_key.'_ul">';
38
+ }
39
+ else{
40
+ echo ' <li class="gawd_menu_li load_tooltip" id="gawd_'.$tab_key.'_li" data-hint="'.$tab_data["desc"].'">
41
+ <span id="gawd_'.$tab_key.'" class="gawd_menu_li_sub">'.$tab_data["title"].$sub_arrow.'
42
+ </span>
43
+ <ul id="gawd_'.$tab_key.'_ul">';
44
+ }
45
+ foreach($tab_data["childs"] as $child_key => $child_title) {
46
+ if(!$title){
47
+ $child_title = "";
48
+ }
49
+ $active_tab = $_GET['tab'] == $child_key ? 'gawd_active_li' : '';
50
+ if($child_key == 'productCategory' || $child_key == 'productName' || $child_key == 'productSku' || $child_key == 'transactionId' || $child_key == 'sales_performance' || $child_key == 'daysToTransaction'){
51
+ echo ' <li class="gawd_menu_ul_li '.$active_tab.'">
52
+ <a class="gawd_menu_item " href="#">'.$child_title.'</a>
53
+ </li> ';
54
+ }
55
+ else{
56
+ echo ' <li class="gawd_menu_ul_li '.$active_tab.'">
57
+ <a class="gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_reports&tab='.$child_key.'">'.$child_title.'</a>
58
+ </li> ';
59
+ }
60
+ }
61
+ echo '</ul>
62
+ </li>';
63
+ }
64
+ }
65
+ }
66
+ function gawd_write_menu_collapse($tabs, $title = true){
67
+ $sub_arrow = '<span class="gawd_menu_li_sub_arrow"></span>';
68
+ foreach ($tabs as $tab_key => $tab_data){
69
+ if(!$title){
70
+ $tab_data["title"] = "";
71
+ $sub_arrow = '';
72
+ }
73
+ if($tab_data["childs"] == array()){
74
+ $active_tab = $_GET['tab'] == $tab_key ? 'gawd_active_li' : '';
75
+ if($tab_key == 'customReport'){
76
+ echo '<a id="gawd_'.$tab_key.'" class="'.$active_tab.' gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_custom_reports">'.$tab_data["title"].'</a>';
77
+ }
78
+ else{
79
+ echo '<a id="gawd_'.$tab_key.'" class="'.$active_tab.' gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_reports&tab='.$tab_key.'">'.$tab_data["title"].'</a>';
80
+ }
81
+ }
82
+ else{
83
+ if($tab_key == 'customReport'){
84
+ echo '<span id="gawd_'.$tab_key.'_li" id="gawd_'.$tab_key.'s" class="gawd_menu_li_sub">'.$tab_data["title"].$sub_arrow.'
85
+ <div class="collapse_ul" id="gawd_'.$tab_key.'_ul">';
86
+ }
87
+ else{
88
+ echo '<span id="gawd_'.$tab_key.'_li" id="gawd_'.$tab_key.'" class="gawd_menu_li_sub">'.$tab_data["title"].$sub_arrow.'
89
+ <div class="collapse_ul" id="gawd_'.$tab_key.'_ul">';
90
+ }
91
+ foreach($tab_data["childs"] as $child_key => $child_title) {
92
+ $active_tab = $_GET['tab'] == $child_key ? 'gawd_active_li_text' : '';
93
+ echo '<a class="'.$active_tab.' gawd_menu_item " href="'.admin_url().'admin.php?page=gawd_reports&tab='.$child_key.'">'.$child_title.'</a>';
94
+ }
95
+ echo '</div></span>';
96
+ }
97
+ }
98
+
99
+ }
100
+ ?>
101
+ <div class="resp_menu"><div class="menu_img"></div><div class="button_label">REPORTS</div><div class="clear"></div></div>
102
+
103
+ <div class="gawd_menu_coteiner_collapse">
104
+ <div class="gawd_menu_ul">
105
+ <?php
106
+ gawd_write_menu_collapse($tabs,false);
107
+ ?>
108
+ <span class='gawd_collapsed'></span>
109
+ </div>
110
+ </div>
111
+ <div class="gawd_menu_coteiner">
112
+ <input style="width: 100%; margin-bottom: 5px;" onkeyup="gawd_search()" type="text" class='gawd_search_input'/>
113
+ <ul class="gawd_menu_ul">
114
+ <?php
115
+
116
+ gawd_write_menu($tabs);
117
+ ?>
118
+ <li class='gawd_collapse'>Collapse menu</li>
119
+ </ul>
120
  </div>
admin/pages/dashboard_widget.php CHANGED
@@ -1,43 +1,43 @@
1
- <form method="post" id="gawd_dashboard_wp">
2
- <select title="Click to pick the website, audience report of which you’d like to display." style="width: 41%; margin-right: 20px;" class="gawd_profile_select" name="gawd_id" onchange="change_account(this)">
3
- <?php foreach ($profiles as $property_name => $property): ?>
4
- <optgroup label="<?php echo $property_name; ?>">
5
- <?php foreach ($property as $profile):
6
- $webPropertyId = $profile['webPropertyId'];
7
- $id = $profile['id'];
8
- $name = $profile['name'];
9
- $selected = '';
10
- if($id == $gawd_user_data['gawd_id']){
11
- $selected = 'selected="selected"';
12
- }
13
- ?>
14
- <option value="<?php echo $id; ?>" <?php echo $selected; ?>><?php echo $property_name.' - '.$name ; ?></option>
15
- <?php endforeach ?>
16
- </optgroup>
17
- <?php endforeach ?>
18
- </select>
19
- <input type="hidden" name='web_property_name' id='web_property_name'/>
20
- <select name="gawd_widget_date" id="gawd_widget_date" onchange="gawd_draw_analytics_widget()">
21
- <option value="<?php echo date('Y-m-d', strtotime('-7 days')); ?>"><?php echo __('Last 7 Days', 'gawd'); ?></option>
22
- <option value="<?php echo date('Y-m-d', strtotime('-30 days')); ?>"><?php echo __('Last 30 Days', 'gawd'); ?></option>
23
- <option value="realTime" ><?php echo __('Real Time', 'gawd'); ?></option>
24
- </select>
25
- <select name="gawd_metric_widget" id="gawd_metric_widget" onchange="gawd_draw_analytics_widget()">
26
- <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
27
- <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
28
- <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
29
- <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
30
- <option value="percentNewSessions">% New Sessions</option>
31
- <option value="avgSessionDuration">Avg Session Duration</option>
32
- <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
33
- </select>
34
- </form>
35
-
36
- <div id="chart_widget"></div>
37
-
38
- <script>
39
- function change_account(that){
40
- jQuery('#web_property_name').val(jQuery(that).find(':selected').closest('optgroup').attr('label'));
41
- jQuery('#gawd_dashboard_wp').submit();
42
- }
43
  </script>
1
+ <form method="post" id="gawd_dashboard_wp">
2
+ <select title="Click to pick the website, audience report of which you’d like to display." style="width: 41%; margin-right: 20px;" class="gawd_profile_select" name="gawd_id" onchange="change_account(this)">
3
+ <?php foreach ($profiles as $property_name => $property): ?>
4
+ <optgroup label="<?php echo $property_name; ?>">
5
+ <?php foreach ($property as $profile):
6
+ $webPropertyId = $profile['webPropertyId'];
7
+ $id = $profile['id'];
8
+ $name = $profile['name'];
9
+ $selected = '';
10
+ if($id == $gawd_user_data['gawd_id']){
11
+ $selected = 'selected="selected"';
12
+ }
13
+ ?>
14
+ <option value="<?php echo $id; ?>" <?php echo $selected; ?>><?php echo $property_name.' - '.$name ; ?></option>
15
+ <?php endforeach ?>
16
+ </optgroup>
17
+ <?php endforeach ?>
18
+ </select>
19
+ <input type="hidden" name='web_property_name' id='web_property_name'/>
20
+ <select name="gawd_widget_date" id="gawd_widget_date" onchange="gawd_draw_analytics_widget()">
21
+ <option value="<?php echo date('Y-m-d', strtotime('-7 days')); ?>"><?php echo __('Last 7 Days', 'gawd'); ?></option>
22
+ <option value="<?php echo date('Y-m-d', strtotime('-30 days')); ?>"><?php echo __('Last 30 Days', 'gawd'); ?></option>
23
+ <option value="realTime" ><?php echo __('Real Time', 'gawd'); ?></option>
24
+ </select>
25
+ <select name="gawd_metric_widget" id="gawd_metric_widget" onchange="gawd_draw_analytics_widget()">
26
+ <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
27
+ <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
28
+ <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
29
+ <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
30
+ <option value="percentNewSessions">% New Sessions</option>
31
+ <option value="avgSessionDuration">Avg Session Duration</option>
32
+ <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
33
+ </select>
34
+ </form>
35
+
36
+ <div id="chart_widget"></div>
37
+
38
+ <script>
39
+ function change_account(that){
40
+ jQuery('#web_property_name').val(jQuery(that).find(':selected').closest('optgroup').attr('label'));
41
+ jQuery('#gawd_dashboard_wp').submit();
42
+ }
43
  </script>
admin/pages/date.php CHANGED
@@ -1,60 +1,60 @@
1
- <div class="gawd_wrapper">
2
- <div class="opacity_div_compact"> </div>
3
- <div class="loading_div_compact">
4
- <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
5
- </div>
6
- <div style="float:left">
7
- <div id="first_metric" >
8
- <select class="gawd_compact_metric_change" name="gawd_metric_compact" id="gawd_metric_compact" >
9
- <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
10
- <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
11
- <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
12
- <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
13
- <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
14
- <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
15
- <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
16
- </select>
17
- </div>
18
- <div id="metric_compare">
19
- <select class="gawd_compact_metric_change" name="gawd_metric_compare" id="gawd_metric_compare_compact">
20
- <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
21
- <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
22
- <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
23
- <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
24
- <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
25
- <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
26
- <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
27
- <option value="0"><?php echo __('None', 'gawd'); ?></option>
28
- </select>
29
- </div>
30
- </div>
31
- <div style="float:left;margin:16px 0 0 0 " class="vs_image" class="gawd_metrics">
32
- <img width="30px" src="<?php echo GAWD_URL; ?>/assets/vs.png">
33
- </div>
34
- <div class="clear"></div>
35
-
36
- <div id="gawd_date_meta"></div>
37
- </div>
38
- <script>
39
- jQuery(document).ready(function(){
40
- hide_same_metric(jQuery('#gawd_metric_compare_compact'));
41
- hide_same_metric(jQuery('#gawd_metric_compact'));
42
- var _end_date = (Date.today().add(-1).days()).toString("yyyy-MM-dd");
43
- var start_date_7 = (Date.today().add(-1).days()).add(-7).days().toString("yyyy-MM-dd");
44
- var start_end_date = typeof jQuery('#gawd_start_end_date_compact').val() != 'undefined' ? jQuery('#gawd_start_end_date_compact').val() : start_date_7 + '/-/' + _end_date;
45
-
46
- var start_end_date = start_end_date.split('/-/');
47
- var start_date = start_end_date[0];
48
- var end_date = start_end_date[1];
49
- jQuery('#gawd_metric_compact').on('change', function () {
50
- hide_same_metric(this);
51
- gawd_draw_analytics_compact(jQuery('#gawd_metric_compact').val(), jQuery('#gawd_metric_compare_compact').val(), 'date', 'line', 'gawd_date_meta');
52
- })
53
- jQuery('#gawd_metric_compare_compact').on('change', function () {
54
- hide_same_metric(this);
55
- gawd_draw_analytics_compact(jQuery('#gawd_metric_compact').val(), jQuery('#gawd_metric_compare_compact').val(), 'date', 'line', 'gawd_date_meta');
56
- })
57
- //gawd_draw_analytics_compact('sessions', 'users', 'date', 'line', start_date, end_date, 'gawd_date_meta');
58
-
59
- });
60
  </script>
1
+ <div class="gawd_wrapper">
2
+ <div class="opacity_div_compact"> </div>
3
+ <div class="loading_div_compact">
4
+ <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
5
+ </div>
6
+ <div style="float:left">
7
+ <div id="first_metric" >
8
+ <select class="gawd_compact_metric_change" name="gawd_metric_compact" id="gawd_metric_compact" >
9
+ <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
10
+ <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
11
+ <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
12
+ <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
13
+ <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
14
+ <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
15
+ <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
16
+ </select>
17
+ </div>
18
+ <div id="metric_compare">
19
+ <select class="gawd_compact_metric_change" name="gawd_metric_compare" id="gawd_metric_compare_compact">
20
+ <option value="users" ><?php echo __('Users', 'gawd'); ?></option>
21
+ <option value="sessions"><?php echo __('Sessions', 'gawd'); ?></option>
22
+ <option value="percentNewSessions"><?php echo __('% New Sessions', 'gawd'); ?></option>
23
+ <option value="bounceRate" ><?php echo __('Bounce Rate', 'gawd'); ?></option>
24
+ <option value="avgSessionDuration" ><?php echo __('Avg Session Duration', 'gawd'); ?></option>
25
+ <option value="pageviews" ><?php echo __('Pageviews', 'gawd'); ?></option>
26
+ <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
27
+ <option value="0"><?php echo __('None', 'gawd'); ?></option>
28
+ </select>
29
+ </div>
30
+ </div>
31
+ <div style="float:left;margin:16px 0 0 0 " class="vs_image" class="gawd_metrics">
32
+ <img width="30px" src="<?php echo GAWD_URL; ?>/assets/vs.png">
33
+ </div>
34
+ <div class="clear"></div>
35
+
36
+ <div id="gawd_date_meta"></div>
37
+ </div>
38
+ <script>
39
+ jQuery(document).ready(function(){
40
+ hide_same_metric(jQuery('#gawd_metric_compare_compact'));
41
+ hide_same_metric(jQuery('#gawd_metric_compact'));
42
+ var _end_date = (Date.today().add(-1).days()).toString("yyyy-MM-dd");
43
+ var start_date_7 = (Date.today().add(-1).days()).add(-7).days().toString("yyyy-MM-dd");
44
+ var start_end_date = typeof jQuery('#gawd_start_end_date_compact').val() != 'undefined' ? jQuery('#gawd_start_end_date_compact').val() : start_date_7 + '/-/' + _end_date;
45
+
46
+ var start_end_date = start_end_date.split('/-/');
47
+ var start_date = start_end_date[0];
48
+ var end_date = start_end_date[1];
49
+ jQuery('#gawd_metric_compact').on('change', function () {
50
+ hide_same_metric(this);
51
+ gawd_draw_analytics_compact(jQuery('#gawd_metric_compact').val(), jQuery('#gawd_metric_compare_compact').val(), 'date', 'line', 'gawd_date_meta');
52
+ })
53
+ jQuery('#gawd_metric_compare_compact').on('change', function () {
54
+ hide_same_metric(this);
55
+ gawd_draw_analytics_compact(jQuery('#gawd_metric_compact').val(), jQuery('#gawd_metric_compare_compact').val(), 'date', 'line', 'gawd_date_meta');
56
+ })
57
+ //gawd_draw_analytics_compact('sessions', 'users', 'date', 'line', start_date, end_date, 'gawd_date_meta');
58
+
59
+ });
60
  </script>
admin/pages/goals.php CHANGED
@@ -1,261 +1,261 @@
1
- <?php
2
- $profiles = $gawd_client->get_default_profiles();
3
- $goals = $gawd_client->get_default_goals();
4
- if (!is_array($goals)) {
5
- $goals = array();
6
- }
7
- ?>
8
- <div class="goal_wrap">
9
- <h3 class="gawd_page_titles">Goal Management</h3>
10
-
11
- <p>You can set and manage goals for your website tracking. Select the View that you’re going to track and configure these options based on the type of goal you would like to set.</p>
12
- <form action='' method="post" id="gawd_goal_form">
13
- <div class="gawd_goal_row">
14
- <span class="gawd_goal_label">View</span>
15
- <span class="gawd_goal_input">
16
- <select name="gawd_goal_profile" class="gawd_goal_profile">
17
- <?php foreach ($profiles as $profile) {
18
- echo '<option value="' . $profile['id'] . '">' . $profile['webPropertyName'] . ' - ' . $profile['name'] . '</option>';
19
- } ?>
20
- </select>
21
- </span>
22
- <div class="gawd_info" title="Choose the website, to which you would like to set Google Analytics Goals. "></div>
23
- <div class='clear'></div>
24
- </div>
25
- <div class="gawd_goal_row">
26
- <span class="gawd_goal_label">Name</span>
27
- <span class="gawd_goal_input">
28
- <input id="gawd_goal_name" name="gawd_goal_name" class="" type="text" value="">
29
- </span>
30
- <div class="gawd_info" title="Provide a name for this goal"></div>
31
- <div class='clear'></div>
32
- </div>
33
- <div class="gawd_goal_row">
34
- <span class="gawd_goal_label">Type</span>
35
- <span class="gawd_goal_input">
36
- <select name="gawd_goal_type" class="gawd_goal_type">
37
- <option value="URL_DESTINATION">Destination</option>
38
- <option value="VISIT_TIME_ON_SITE">Duration</option>
39
- <option value="VISIT_NUM_PAGES">Pages/Screens per session</option>
40
- <!-- <option value="EVENT">Event</option> -->
41
- </select>
42
- </span>
43
- <div class="gawd_info" title="Select its type (Destination, Duration, Pages/Screens per session or Event)."></div>
44
- <div class='clear'></div>
45
- </div>
46
- <div class="gawd_goal_duration_wrap" id="gawd_goal_duration_wrap">
47
- <div class="gawd_duration_label">Duration</div>
48
- <div class="gawd_comparison_input">
49
- <select name="gawd_goal_duration_comparison" class="gawd_goal_duration_comparison">
50
- <option value="GREATER_THAN">Greater than</option>
51
- </select>
52
- </div>
53
- <div class="gawd_duration">
54
- <div class="time_wrap">
55
- <!--<div class="time_label">Hour</div> -->
56
- <div class="time_input"><input placeholder="hour" type="number" min='0' name="gawd_visit_hour"/></div>
57
- </div>
58
- <div class="time_wrap">
59
- <!--<div class="time_label">Minute</div> -->
60
- <div class="time_input"><input placeholder="min." type="number" min='0' name="gawd_visit_minute"/></div>
61
- </div>
62
- <div class="time_wrap" id="time_wrap">
63
- <!--<div class="time_label">Second</div> -->
64
- <div class="time_input"><input placeholder="sec." type="number" min='0' name="gawd_visit_second"/></div>
65
- </div>
66
- <div class='clear'></div>
67
- </div>
68
- <div class="gawd_info" style="margin-left: 15px" title="Set a duration for this goal. For example, if you select 20 minutes, each time users spend 20 minutes or more on your site, it will be counted as goal completion."></div>
69
- <div class='clear'></div>
70
- </div>
71
- <div class="gawd_page_sessions" id="gawd_page_sessions">
72
- <div class="gawd_duration_label">Pages per session</div>
73
- <div class="gawd_comparison_input">
74
- <select name="gawd_goal_page_comparison" class="gawd_goal_duration_comparison">
75
- <option value="GREATER_THAN">Greater than</option>
76
- </select>
77
- </div>
78
- <div class="gawd_duration">
79
- <div class="time_wrap">
80
- <!--<div class="time_label">Hour</div> -->
81
- <input type="number" min='0' name="gawd_page_sessions"/>
82
- </div>
83
- <div class='clear'></div>
84
- </div>
85
- <div class="gawd_info" style="margin-left: 15px" title="Choose the number of pages/screens users should view to complete this goal."></div>
86
- <div class='clear'></div>
87
- </div>
88
- <div class="gawd_page_destination" id="gawd_page_destination">
89
- <div class="gawd_duration_label">Destination</div>
90
- <div class="gawd_url_comparison_input" >
91
- <select name="gawd_goal_page_destination_match" class="gawd_goal_duration_comparison">
92
- <option value="EXACT">Equals to</option>
93
- <option value="HEAD">Begins with</option>
94
- <option value="REGEX">Regular expression</option>
95
- </select>
96
- </div>
97
- <div class="gawd_info" style="margin-left: 8px;" title="Set the destination of your goal. It can be equal to the specified value, as well as begin with it. You can also add a Regular Expression as destination value."></div>
98
- <div class="gawd_destination_url">
99
- <label for="gawd_case_sensitive" class="case_sensitive gawd_duration_label">URL</label>
100
- <div class="time_wrap">
101
- <div class="time_input"><input type="text" name="gawd_page_url"/></div>
102
- </div>
103
- <div class="gawd_info" title="Set destination URL."></div>
104
- <div class='clear'></div>
105
- </div>
106
- <div class="gawd_destination_url">
107
- <label for="gawd_case_sensitive" class="case_sensitive gawd_duration_label">URL Case sensitive</label>
108
- <div class="time_wrap">
109
- <div class="onoffswitch" style="margin: 3px 0 0 6px;">
110
- <input type="checkbox" name="url_case_sensitve" class="onoffswitch-checkbox" id="gawd_case_sensitive">
111
- <label class="onoffswitch-label" for="gawd_case_sensitive">
112
- <span class="onoffswitch-inner"></span>
113
- <span class="onoffswitch-switch"></span>
114
- </label>
115
- </div>
116
- </div>
117
- <div class="gawd_info" title="Enable this option to set destination URL case sensitive."></div>
118
- </div>
119
-
120
- <div class='clear'></div>
121
- </div>
122
- <!-- <div class="gawd_page_event" id="gawd_page_event">
123
- <div class="event_type_row">
124
- <div class="gawd_duration_label">Category</div>
125
- <div class="gawd_event_comparison_input" >
126
- <select name="gawd_goal_event_match" class="gawd_goal_duration_comparison">
127
- <option value="EXACT">Equals to</option>
128
- <option value="HEAD">Begins with</option>
129
- <option value="REGEX">Regular expresion</option>
130
- </select>
131
- </div>
132
- <div class="gawd_event_name">
133
- <input type="text" name="gawd_category_name"/>
134
- <div class='clear'></div>
135
- </div>
136
- <div class='clear'></div>
137
- </div>
138
- <div class="event_type_row">
139
- <div class="gawd_duration_label">Action</div>
140
- <div class="gawd_event_comparison_input" >
141
- <select name="gawd_goal_event_match" class="gawd_goal_duration_comparison">
142
- <option value="EXACT">Equals to</option>
143
- <option value="HEAD">Begins with</option>
144
- <option value="REGEX">Regular expresion</option>
145
- </select>
146
- </div>
147
- <div class="gawd_event_name">
148
- <input type="text" name="gawd_action_name"/>
149
- <div class='clear'></div>
150
- </div>
151
- <div class='clear'></div>
152
- </div>
153
- <div class="event_type_row">
154
- <div class="gawd_duration_label">Label</div>
155
- <div class="gawd_event_comparison_input" >
156
- <select name="gawd_goal_event_match" class="gawd_goal_duration_comparison">
157
- <option value="EXACT">Equals to</option>
158
- <option value="HEAD">Begins with</option>
159
- <option value="REGEX">Regular expresion</option>
160
- </select>
161
- </div>
162
- <div class="gawd_event_name">
163
- <input type="text" name="gawd_label_name"/>
164
- <div class='clear'></div>
165
- </div>
166
- <div class='clear'></div>
167
- </div>
168
- <div class="event_type_row">
169
- <div class="gawd_duration_label">Value</div>
170
- <div class="gawd_event_comparison_input" >
171
- <select name="gawd_goal_event_match" class="gawd_goal_duration_comparison">
172
- <option value="EXACT">Equals to</option>
173
- <option value="GREATER_THAN">Greater than</option>
174
- <option value="LESS_THAN">Less than</option>
175
- </select>
176
- </div>
177
- <div class="gawd_event_name">
178
- <input type="text" name="gawd_value_name"/>
179
- <div class='clear'></div>
180
- </div>
181
- <div class='clear'></div>
182
- </div>
183
-
184
- </div>-->
185
- <div class="gawd_buttons" id="goal_submit">
186
- <input class="button_gawd" type="button" name="add_goal" value="Save"/>
187
- </div>
188
- <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
189
- <input class="goal_max_id" id="goal_max_id" name="goal_max_id" type="hidden" value="<?php echo count($goals[$profile_id]);?>"/>
190
-
191
- </form>
192
- <?php if (!empty($goals)) {
193
- $counter = 0;
194
- foreach ($goals as $profile_id => $profile_goals) { ?>
195
- <table border="1" class="gawd_table" id="<?php echo $profile_id; ?>" style="<?php echo (($counter != 0) ? 'display:none;' : ''); ?>">
196
- <tr>
197
- <th>Id</th>
198
- <th>Name</th>
199
- <th>Type</th>
200
- <th>Match Type</th>
201
- <th>Value</th>
202
- </tr>
203
- <?php
204
- foreach ($profile_goals as $goal) {
205
- $case_sensitive = $goal['caseSensitive'] ? ' - case sensitive' : '';
206
- ?>
207
- <tr class="gawd_rows">
208
- <td><?php echo $goal['id']; ?></td>
209
- <td><?php echo $goal['name']; ?></td>
210
- <td><?php echo $goal['type']; ?></td>
211
- <td><?php echo $goal['match_type']; ?></td>
212
- <td><?php echo $goal['value'].$case_sensitive; ?></td>
213
- </tr>
214
- <?php
215
- }
216
- ?>
217
- </table>
218
- <?php $counter++; }
219
- } ?>
220
-
221
- </div>
222
- <script>
223
- jQuery('.gawd_goal_type').on('change', function () {
224
- if (jQuery('.gawd_goal_type :selected').val() == 'VISIT_TIME_ON_SITE') {
225
- jQuery('.gawd_goal_duration_wrap').show();
226
- jQuery('.gawd_page_sessions').hide();
227
- jQuery('.gawd_page_destination').hide();
228
- jQuery('.gawd_page_event').hide();
229
- } else if (jQuery('.gawd_goal_type :selected').val() == 'VISIT_NUM_PAGES') {
230
- jQuery('.gawd_goal_duration_wrap').hide();
231
- jQuery('.gawd_page_destination').hide();
232
- jQuery('.gawd_page_event').hide();
233
- jQuery('.gawd_page_sessions').show();
234
- } else if (jQuery('.gawd_goal_type :selected').val() == 'EVENT') {
235
- jQuery('.gawd_goal_duration_wrap').hide();
236
- jQuery('.gawd_page_sessions').hide();
237
- jQuery('.gawd_page_destination').hide();
238
- jQuery('.gawd_page_event').show();
239
- } else {
240
- jQuery('.gawd_goal_duration_wrap').hide();
241
- jQuery('.gawd_page_sessions').hide();
242
- jQuery('.gawd_page_event').hide();
243
- jQuery('.gawd_page_destination').show();
244
- }
245
- });
246
- jQuery('.button_gawd').on('click',function(){
247
- if(jQuery('.gawd_table tr').length -1 >= 20){
248
- alert('You have reached the maximum number of goals.')
249
- return;
250
- }
251
- jQuery('#goal_max_id').val(jQuery('.gawd_rows').length);
252
- jQuery('#gawd_goal_form').submit();
253
- });
254
- jQuery('.gawd_goal_profile').on('change', function(){
255
- jQuery('.gawd_table').each(function(){
256
- jQuery(this).hide();
257
- });
258
- var id = jQuery(this).val();
259
- jQuery('#' + id).show();
260
- });
261
- </script>
1
+ <?php
2
+ $profiles = $gawd_client->get_default_profiles();
3
+ $goals = $gawd_client->get_default_goals();
4
+ if (!is_array($goals)) {
5
+ $goals = array();
6
+ }
7
+ ?>
8
+ <div class="goal_wrap">
9
+ <h3 class="gawd_page_titles">Goal Management</h3>
10
+
11
+ <p>You can set and manage goals for your website tracking. Select the View that you’re going to track and configure these options based on the type of goal you would like to set.</p>
12
+ <form action='' method="post" id="gawd_goal_form">
13
+ <div class="gawd_goal_row">
14
+ <span class="gawd_goal_label">View</span>
15
+ <span class="gawd_goal_input">
16
+ <select name="gawd_goal_profile" class="gawd_goal_profile">
17
+ <?php foreach ($profiles as $profile) {
18
+ echo '<option value="' . $profile['id'] . '">' . $profile['webPropertyName'] . ' - ' . $profile['name'] . '</option>';
19
+ } ?>
20
+ </select>
21
+ </span>
22
+ <div class="gawd_info" title="Choose the website, to which you would like to set Google Analytics Goals. "></div>
23
+ <div class='clear'></div>
24
+ </div>
25
+ <div class="gawd_goal_row">
26
+ <span class="gawd_goal_label">Name</span>
27
+ <span class="gawd_goal_input">
28
+ <input id="gawd_goal_name" name="gawd_goal_name" class="" type="text" value="">
29
+ </span>
30
+ <div class="gawd_info" title="Provide a name for this goal"></div>
31
+ <div class='clear'></div>
32
+ </div>
33
+ <div class="gawd_goal_row">
34
+ <span class="gawd_goal_label">Type</span>
35
+ <span class="gawd_goal_input">
36
+ <select name="gawd_goal_type" class="gawd_goal_type">
37
+ <option value="URL_DESTINATION">Destination</option>
38
+ <option value="VISIT_TIME_ON_SITE">Duration</option>
39
+ <option value="VISIT_NUM_PAGES">Pages/Screens per session</option>
40
+ <!-- <option value="EVENT">Event</option> -->
41
+ </select>
42
+ </span>
43
+ <div class="gawd_info" title="Select its type (Destination, Duration, Pages/Screens per session or Event)."></div>
44
+ <div class='clear'></div>
45
+ </div>
46
+ <div class="gawd_goal_duration_wrap" id="gawd_goal_duration_wrap">
47
+ <div class="gawd_duration_label">Duration</div>
48
+ <div class="gawd_comparison_input">
49
+ <select name="gawd_goal_duration_comparison" class="gawd_goal_duration_comparison">
50
+ <option value="GREATER_THAN">Greater than</option>
51
+ </select>
52
+ </div>
53
+ <div class="gawd_duration">
54
+ <div class="time_wrap">
55
+ <!--<div class="time_label">Hour</div> -->
56
+ <div class="time_input"><input placeholder="hour" type="number" min='0' name="gawd_visit_hour"/></div>
57
+ </div>
58
+ <div class="time_wrap">
59
+ <!--<div class="time_label">Minute</div> -->
60
+ <div class="time_input"><input placeholder="min." type="number" min='0' name="gawd_visit_minute"/></div>
61
+ </div>
62
+ <div class="time_wrap" id="time_wrap">
63
+ <!--<div class="time_label">Second</div> -->
64
+ <div class="time_input"><input placeholder="sec." type="number" min='0' name="gawd_visit_second"/></div>
65
+ </div>
66
+ <div class='clear'></div>
67
+ </div>
68
+ <div class="gawd_info" style="margin-left: 15px" title="Set a duration for this goal. For example, if you select 20 minutes, each time users spend 20 minutes or more on your site, it will be counted as goal completion."></div>
69
+ <div class='clear'></div>
70
+ </div>
71
+ <div class="gawd_page_sessions" id="gawd_page_sessions">
72
+ <div class="gawd_duration_label">Pages per session</div>
73
+ <div class="gawd_comparison_input">
74
+ <select name="gawd_goal_page_comparison" class="gawd_goal_duration_comparison">
75
+ <option value="GREATER_THAN">Greater than</option>
76
+ </select>
77
+ </div>
78
+ <div class="gawd_duration">
79
+ <div class="time_wrap">
80
+ <!--<div class="time_label">Hour</div> -->
81
+ <input type="number" min='0' name="gawd_page_sessions"/>
82
+ </div>
83
+ <div class='clear'></div>
84
+ </div>
85
+ <div class="gawd_info" style="margin-left: 15px" title="Choose the number of pages/screens users should view to complete this goal."></div>
86
+ <div class='clear'></div>
87
+ </div>
88
+ <div class="gawd_page_destination" id="gawd_page_destination">
89
+ <div class="gawd_duration_label">Destination</div>
90
+ <div class="gawd_url_comparison_input" >
91
+ <select name="gawd_goal_page_destination_match" class="gawd_goal_duration_comparison">
92
+ <option value="EXACT">Equals to</option>
93
+ <option value="HEAD">Begins with</option>
94
+ <option value="REGEX">Regular expression</option>
95
+ </select>
96
+ </div>
97
+ <div class="gawd_info" style="margin-left: 8px;" title="Set the destination of your goal. It can be equal to the specified value, as well as begin with it. You can also add a Regular Expression as destination value."></div>
98
+ <div class="gawd_destination_url">
99
+ <label for="gawd_case_sensitive" class="case_sensitive gawd_duration_label">URL</label>
100
+ <div class="time_wrap">
101
+ <div class="time_input"><input type="text" name="gawd_page_url"/></div>
102
+ </div>
103
+ <div class="gawd_info" title="Set destination URL."></div>
104
+ <div class='clear'></div>
105
+ </div>
106
+ <div class="gawd_destination_url">
107
+ <label for="gawd_case_sensitive" class="case_sensitive gawd_duration_label">URL Case sensitive</label>
108
+ <div class="time_wrap">
109
+ <div class="onoffswitch" style="margin: 3px 0 0 6px;">
110
+ <input type="checkbox" name="url_case_sensitve" class="onoffswitch-checkbox" id="gawd_case_sensitive">
111
+ <label class="onoffswitch-label" for="gawd_case_sensitive">
112
+ <span class="onoffswitch-inner"></span>
113
+ <span class="onoffswitch-switch"></span>
114
+ </label>
115
+ </div>
116
+ </div>
117
+ <div class="gawd_info" title="Enable this option to set destination URL case sensitive."></div>
118
+ </div>
119
+
120
+ <div class='clear'></div>
121
+ </div>
122
+ <!-- <div class="gawd_page_event" id="gawd_page_event">
123
+ <div class="event_type_row">
124
+ <div class="gawd_duration_label">Category</div>
125
+ <div class="gawd_event_comparison_input" >
126
+ <select name="gawd_goal_event_match" class="gawd_goal_duration_comparison">
127
+ <option value="EXACT">Equals to</option>
128
+ <option value="HEAD">Begins with</option>
129
+ <option value="REGEX">Regular expresion</option>
130
+ </select>
131
+ </div>
132
+ <div class="gawd_event_name">
133
+ <input type="text" name="gawd_category_name"/>
134
+ <div class='clear'></div>
135
+ </div>
136
+ <div class='clear'></div>
137
+ </div>
138
+ <div class="event_type_row">
139
+ <div class="gawd_duration_label">Action</div>
140
+ <div class="gawd_event_comparison_input" >
141
+ <select name="gawd_goal_event_match" class="gawd_goal_duration_comparison">
142
+ <option value="EXACT">Equals to</option>
143
+ <option value="HEAD">Begins with</option>
144
+ <option value="REGEX">Regular expresion</option>
145
+ </select>
146
+ </div>
147
+ <div class="gawd_event_name">
148
+ <input type="text" name="gawd_action_name"/>
149
+ <div class='clear'></div>
150
+ </div>
151
+ <div class='clear'></div>
152
+ </div>
153
+ <div class="event_type_row">
154
+ <div class="gawd_duration_label">Label</div>
155
+ <div class="gawd_event_comparison_input" >
156
+ <select name="gawd_goal_event_match" class="gawd_goal_duration_comparison">
157
+ <option value="EXACT">Equals to</option>
158
+ <option value="HEAD">Begins with</option>
159
+ <option value="REGEX">Regular expresion</option>
160
+ </select>
161
+ </div>
162
+ <div class="gawd_event_name">
163
+ <input type="text" name="gawd_label_name"/>
164
+ <div class='clear'></div>
165
+ </div>
166
+ <div class='clear'></div>
167
+ </div>
168
+ <div class="event_type_row">
169
+ <div class="gawd_duration_label">Value</div>
170
+ <div class="gawd_event_comparison_input" >
171
+ <select name="gawd_goal_event_match" class="gawd_goal_duration_comparison">
172
+ <option value="EXACT">Equals to</option>
173
+ <option value="GREATER_THAN">Greater than</option>
174
+ <option value="LESS_THAN">Less than</option>
175
+ </select>
176
+ </div>
177
+ <div class="gawd_event_name">
178
+ <input type="text" name="gawd_value_name"/>
179
+ <div class='clear'></div>
180
+ </div>
181
+ <div class='clear'></div>
182
+ </div>
183
+
184
+ </div>-->
185
+ <div class="gawd_buttons" id="goal_submit">
186
+ <input class="button_gawd" type="button" name="add_goal" value="Save"/>
187
+ </div>
188
+ <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
189
+ <input class="goal_max_id" id="goal_max_id" name="goal_max_id" type="hidden" value="<?php echo count($goals[$profile_id]);?>"/>
190
+
191
+ </form>
192
+ <?php if (!empty($goals)) {
193
+ $counter = 0;
194
+ foreach ($goals as $profile_id => $profile_goals) { ?>
195
+ <table border="1" class="gawd_table" id="<?php echo $profile_id; ?>" style="<?php echo (($counter != 0) ? 'display:none;' : ''); ?>">
196
+ <tr>
197
+ <th>Id</th>
198
+ <th>Name</th>
199
+ <th>Type</th>
200
+ <th>Match Type</th>
201
+ <th>Value</th>
202
+ </tr>
203
+ <?php
204
+ foreach ($profile_goals as $goal) {
205
+ $case_sensitive = $goal['caseSensitive'] ? ' - case sensitive' : '';
206
+ ?>
207
+ <tr class="gawd_rows">
208
+ <td><?php echo $goal['id']; ?></td>
209
+ <td><?php echo $goal['name']; ?></td>
210
+ <td><?php echo $goal['type']; ?></td>
211
+ <td><?php echo $goal['match_type']; ?></td>
212
+ <td><?php echo $goal['value'].$case_sensitive; ?></td>
213
+ </tr>
214
+ <?php
215
+ }
216
+ ?>
217
+ </table>
218
+ <?php $counter++; }
219
+ } ?>
220
+
221
+ </div>
222
+ <script>
223
+ jQuery('.gawd_goal_type').on('change', function () {
224
+ if (jQuery('.gawd_goal_type :selected').val() == 'VISIT_TIME_ON_SITE') {
225
+ jQuery('.gawd_goal_duration_wrap').show();
226
+ jQuery('.gawd_page_sessions').hide();
227
+ jQuery('.gawd_page_destination').hide();
228
+ jQuery('.gawd_page_event').hide();
229
+ } else if (jQuery('.gawd_goal_type :selected').val() == 'VISIT_NUM_PAGES') {
230
+ jQuery('.gawd_goal_duration_wrap').hide();
231
+ jQuery('.gawd_page_destination').hide();
232
+ jQuery('.gawd_page_event').hide();
233
+ jQuery('.gawd_page_sessions').show();
234
+ } else if (jQuery('.gawd_goal_type :selected').val() == 'EVENT') {
235
+ jQuery('.gawd_goal_duration_wrap').hide();
236
+ jQuery('.gawd_page_sessions').hide();
237
+ jQuery('.gawd_page_destination').hide();
238
+ jQuery('.gawd_page_event').show();
239
+ } else {
240
+ jQuery('.gawd_goal_duration_wrap').hide();
241
+ jQuery('.gawd_page_sessions').hide();
242
+ jQuery('.gawd_page_event').hide();
243
+ jQuery('.gawd_page_destination').show();
244
+ }
245
+ });
246
+ jQuery('.button_gawd').on('click',function(){
247
+ if(jQuery('.gawd_table tr').length -1 >= 20){
248
+ alert('You have reached the maximum number of goals.')
249
+ return;
250
+ }
251
+ jQuery('#goal_max_id').val(jQuery('.gawd_rows').length);
252
+ jQuery('#gawd_goal_form').submit();
253
+ });
254
+ jQuery('.gawd_goal_profile').on('change', function(){
255
+ jQuery('.gawd_table').each(function(){
256
+ jQuery(this).hide();
257
+ });
258
+ var id = jQuery(this).val();
259
+ jQuery('#' + id).show();
260
+ });
261
+ </script>
admin/pages/location.php CHANGED
@@ -1,11 +1,11 @@
1
-
2
-
3
- <div class="gawd_wrapper">
4
- <div class="opacity_div_compact">
5
- <div class="loading_div_compact">
6
- <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
7
- </div>
8
- </div>
9
- <table id="griddiv"></table>
10
- <div id="pager"></div>
11
- </div>
1
+
2
+
3
+ <div class="gawd_wrapper">
4
+ <div class="opacity_div_compact">
5
+ <div class="loading_div_compact">
6
+ <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
7
+ </div>
8
+ </div>
9
+ <table id="griddiv"></table>
10
+ <div id="pager"></div>
11
+ </div>
admin/pages/overview.php CHANGED
@@ -1,76 +1,76 @@
1
-
2
- <?php
3
- wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false );
4
- wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false );
5
- $new_buttons_refresh = '<button data-hint="Click to refresh this report block." class="handlediv load_tooltip button-link gawd-refresh" type="button" id="{{refreshid}}">' . gawd_icons( 'dashicons-update' ) . '</button>';
6
- $new_buttons_full = '<button data-hint="Click to navigate to Real Time report on your Reports page." class="handlediv load_tooltip button-link gawd-more" type="button" id="{{moreid}}">' . gawd_icons( 'dashicons-migrate' ) . '</button>';
7
-
8
- function gawd_icons($dashicons) {
9
-
10
- return '<img src="' . GAWD_URL . '/assets/' . $dashicons . '.png"/>';
11
- }
12
- ?>
13
-
14
- <?php screen_icon('options-general'); ?>
15
- <h2 style="margin-top:10px" class="gawd_page_titles"><?php echo get_admin_page_title(); ?></h2>
16
- <div class="gawd_wrap">
17
- <div class="gawd_row" style="float:left;width:35%; margin-bottom:0">
18
- <div class="gawd_text" style="width: 20%;padding: 9px 12px 9px 14px;">
19
- DATE RANGE
20
- </div>
21
- <div class="gawd_content load_tooltip" style="width: 42%;height: 22px;line-height: 22px;" id="gawd_content_range" data-hint="Choose a date range to display Google Analytics report. Select a predefined or custom period and click Apply.">
22
- <div id="reportrange" class="pull-right" style="float:none !important">
23
- <span></span> <b class="caret"></b>
24
- </div>
25
- <input type="hidden" id="gawd_start_end_date_compact"/>
26
- </div>
27
- <div class='clear'></div>
28
- </div>
29
- <div class="gawd_profiles" id="gawd_profile_wrapper" style="float:right;width: 63%; margin:0">
30
- <form method="post" id="gawd_overview">
31
- <select data-hint="Click to pick the website, overview reports of which you’d like to display." style="width: 41%;" class="gawd_profile_select load_tooltip" name="gawd_id" onchange="change_account(this)">
32
- <?php foreach ($profiles as $property_name => $property): ?>
33
- <optgroup label="<?php echo $property_name; ?>">
34
- <?php foreach ($property as $profile):
35
- $webPropertyId = $profile['webPropertyId'];
36
- $id = $profile['id'];
37
- $name = $profile['name'];
38
- $selected = '';
39
- if($id == $gawd_user_data['gawd_id']){
40
- $selected = 'selected="selected"';
41
- }
42
- ?>
43
- <option value="<?php echo $id; ?>" <?php echo $selected; ?>><?php echo $property_name.' - '.$name ; ?></option>
44
- <?php endforeach ?>
45
- </optgroup>
46
- <?php endforeach ?>
47
- </select>
48
- <div class="clear"></div>
49
- <input type="hidden" name='web_property_name' id='web_property_name'/>
50
- </form>
51
- </div>
52
- <div class="clear"></div>
53
- <?php wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false ); ?>
54
- <?php wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false ); ?>
55
- <div class="metabox-holder" >
56
- <div class="postbox-container gawd_normal_metabox_conteiner" >
57
- <?php do_meta_boxes( 'gawd_analytics', 'normal', '' ); ?>
58
- </div>
59
- <div class="postbox-container gawd_side_metabox_conteiner" >
60
- <?php do_meta_boxes( 'gawd_analytics', 'side', '' ); ?>
61
- </div>
62
- </div>
63
- </div>
64
-
65
- <script>
66
- function change_account(that){
67
- jQuery('#web_property_name').val(jQuery(that).find(':selected').closest('optgroup').attr('label'));
68
- jQuery('#gawd_overview').submit();
69
- }
70
- var buttons_refresh = '<?php echo $new_buttons_refresh; ?>';
71
- var buttons_full = '<?php echo $new_buttons_full; ?>';
72
- datepicker_js_compact();
73
-
74
- </script>
75
-
76
 
1
+
2
+ <?php
3
+ wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false );
4
+ wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false );
5
+ $new_buttons_refresh = '<button data-hint="Click to refresh this report block." class="handlediv load_tooltip button-link gawd-refresh" type="button" id="{{refreshid}}">' . gawd_icons( 'dashicons-update' ) . '</button>';
6
+ $new_buttons_full = '<button data-hint="Click to navigate to Real Time report on your Reports page." class="handlediv load_tooltip button-link gawd-more" type="button" id="{{moreid}}">' . gawd_icons( 'dashicons-migrate' ) . '</button>';
7
+
8
+ function gawd_icons($dashicons) {
9
+
10
+ return '<img src="' . GAWD_URL . '/assets/' . $dashicons . '.png"/>';
11
+ }
12
+ ?>
13
+
14
+ <?php screen_icon('options-general'); ?>
15
+ <h2 style="margin-top:10px" class="gawd_page_titles"><?php echo get_admin_page_title(); ?></h2>
16
+ <div class="gawd_wrap">
17
+ <div class="gawd_row" style="float:left;width:35%; margin-bottom:0">
18
+ <div class="gawd_text" style="width: 20%;padding: 9px 12px 9px 14px;">
19
+ DATE RANGE
20
+ </div>
21
+ <div class="gawd_content load_tooltip" style="width: 42%;height: 22px;line-height: 22px;" id="gawd_content_range" data-hint="Choose a date range to display Google Analytics report. Select a predefined or custom period and click Apply.">
22
+ <div id="reportrange" class="pull-right" style="float:none !important">
23
+ <span></span> <b class="caret"></b>
24
+ </div>
25
+ <input type="hidden" id="gawd_start_end_date_compact"/>
26
+ </div>
27
+ <div class='clear'></div>
28
+ </div>
29
+ <div class="gawd_profiles" id="gawd_profile_wrapper" style="float:right;width: 63%; margin:0">
30
+ <form method="post" id="gawd_overview">
31
+ <select data-hint="Click to pick the website, overview reports of which you’d like to display." style="width: 41%;" class="gawd_profile_select load_tooltip" name="gawd_id" onchange="change_account(this)">
32
+ <?php foreach ($profiles as $property_name => $property): ?>
33
+ <optgroup label="<?php echo $property_name; ?>">
34
+ <?php foreach ($property as $profile):
35
+ $webPropertyId = $profile['webPropertyId'];
36
+ $id = $profile['id'];
37
+ $name = $profile['name'];
38
+ $selected = '';
39
+ if($id == $gawd_user_data['gawd_id']){
40
+ $selected = 'selected="selected"';
41
+ }
42
+ ?>
43
+ <option value="<?php echo $id; ?>" <?php echo $selected; ?>><?php echo $property_name.' - '.$name ; ?></option>
44
+ <?php endforeach ?>
45
+ </optgroup>
46
+ <?php endforeach ?>
47
+ </select>
48
+ <div class="clear"></div>
49
+ <input type="hidden" name='web_property_name' id='web_property_name'/>
50
+ </form>
51
+ </div>
52
+ <div class="clear"></div>
53
+ <?php wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false ); ?>
54
+ <?php wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false ); ?>
55
+ <div class="metabox-holder" >
56
+ <div class="postbox-container gawd_normal_metabox_conteiner" >
57
+ <?php do_meta_boxes( 'gawd_analytics', 'normal', '' ); ?>
58
+ </div>
59
+ <div class="postbox-container gawd_side_metabox_conteiner" >
60
+ <?php do_meta_boxes( 'gawd_analytics', 'side', '' ); ?>
61
+ </div>
62
+ </div>
63
+ </div>
64
+
65
+ <script>
66
+ function change_account(that){
67
+ jQuery('#web_property_name').val(jQuery(that).find(':selected').closest('optgroup').attr('label'));
68
+ jQuery('#gawd_overview').submit();
69
+ }
70
+ var buttons_refresh = '<?php echo $new_buttons_refresh; ?>';
71
+ var buttons_full = '<?php echo $new_buttons_full; ?>';
72
+ datepicker_js_compact();
73
+
74
+ </script>
75
+
76
 
admin/pages/real_time.php CHANGED
@@ -1,17 +1,17 @@
1
-
2
-
3
- <div class="">
4
- <div class="opacity_div_compact">
5
- <div class="loading_div_compact">
6
- <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 30px; width:50px;">
7
- </div>
8
- </div>
9
-
10
- <div id="gawd_real_time_meta"></div>
11
- </div>
12
- <script>
13
- jQuery(document).ready(function(){
14
- gawd_widget_real_time('#gawd_real_time_meta');
15
-
16
- })
17
  </script>
1
+
2
+
3
+ <div class="">
4
+ <div class="opacity_div_compact">
5
+ <div class="loading_div_compact">
6
+ <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 30px; width:50px;">
7
+ </div>
8
+ </div>
9
+
10
+ <div id="gawd_real_time_meta"></div>
11
+ </div>
12
+ <script>
13
+ jQuery(document).ready(function(){
14
+ gawd_widget_real_time('#gawd_real_time_meta');
15
+
16
+ })
17
  </script>
admin/pages/settings.php CHANGED
@@ -1,546 +1,546 @@
1
- <?php
2
- $gawd_settings = get_option('gawd_settings');
3
- $gawd_own_project = get_option('gawd_own_project');
4
- $gawd_client = GAWD_google_client::get_instance();
5
- $profiles = $gawd_client->get_profiles();
6
- $accounts = $gawd_client->get_management_accounts();
7
- $tabs = get_option('gawd_menu_items');
8
- $current_user = get_current_user_id();
9
- $saved_user_menues = get_option('gawd_menu_for_user');
10
-
11
- if(isset($gawd_own_project) && $gawd_own_project && intval($gawd_own_project)==1){
12
- $own_credentials = get_option("gawd_credentials");
13
- $own_cliend_secret = $own_credentials['project_secret'];
14
- $own_cliend_id = $own_credentials['project_id'];
15
- echo'<form method="post" style="width: 92.9%;">
16
- <div class="">
17
- <input type="hidden" name="reset_data" id="reset_data"/>
18
- <input type="button" class="button_gawd" id="gawd_reset_button" value="RESET"/>
19
- <div class="clear"></div>
20
- </div>
21
- </form>';
22
- }
23
- $filters = $gawd_client->get_management_filters();
24
- if (!is_array($filters)) {
25
- $filters = array();
26
- }
27
-
28
- $gawd_permissions = isset($gawd_settings['gawd_permissions']) ? $gawd_settings['gawd_permissions'] : array();
29
- $gawd_excluded_users = isset($gawd_settings['gawd_excluded_users']) ? $gawd_settings['gawd_excluded_users'] : array();
30
- $gawd_excluded_roles = isset($gawd_settings['gawd_excluded_roles']) ? $gawd_settings['gawd_excluded_roles'] : array();
31
- $gawd_backend_roles = isset($gawd_settings['gawd_backend_roles']) ? $gawd_settings['gawd_backend_roles'] : array();
32
- $gawd_frontend_roles = isset($gawd_settings['gawd_frontend_roles']) ? $gawd_settings['gawd_frontend_roles'] : array();
33
- $gawd_post_page_roles = isset($gawd_settings['gawd_post_page_roles']) ? $gawd_settings['gawd_post_page_roles'] : array();
34
- $gawd_file_formats = isset($gawd_settings['gawd_file_formats']) ? $gawd_settings['gawd_file_formats'] : '';
35
- $enable_hover_tooltip = isset($gawd_settings['enable_hover_tooltip']) ? $gawd_settings['enable_hover_tooltip'] : 'on';
36
- $exclude_events = isset($gawd_settings['exclude_events']) ? $gawd_settings['exclude_events'] : '';
37
- $enable_cross_domain = isset($gawd_settings['enable_cross_domain']) ? $gawd_settings['enable_cross_domain'] : '';
38
- $default_date = isset($gawd_settings['default_date']) ? $gawd_settings['default_date'] : '';
39
- $default_date_format = isset($gawd_settings['default_date_format']) ? $gawd_settings['default_date_format'] : '';
40
- $post_page_chart = isset($gawd_settings['post_page_chart']) ? $gawd_settings['post_page_chart'] : '';
41
-
42
- ?>
43
-
44
- <div id="gawd_body">
45
- <div class="resp_menu"><div class="menu_img"></div><div class="button_label">SETTINGS</div><div class="clear"></div></div>
46
- <div class="gawd_menu_coteiner gawd_settings_menu_coteiner">
47
- <ul class="gawd_menu_ul">
48
- <li class="gawd_menu_li" id="gawd_authenicate">
49
- Authenticate
50
- </li>
51
- <li class="gawd_menu_li" id="gawd_alerts">
52
- Alerts
53
- </li>
54
- <li class="gawd_menu_li" id="gawd_pushover">
55
- Pushover
56
- </li>
57
- <li class="gawd_menu_li" id="gawd_filters">
58
- Filters
59
- </li>
60
- <li class="gawd_menu_li" id="gawd_emails">
61
- Emails
62
- </li>
63
- <li class=" gawd_menu_li" id="gawd_advanced">
64
- Advanced
65
- </li>
66
- </ul>
67
- </div>
68
- <div id="gawd_right_conteiner">
69
- <h3 class="gawd_page_titles">Settings</h3>
70
-
71
- <form method="post" id="gawd_form">
72
- <div class="gawd_authenicate">
73
- <div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div>
74
- <div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;">
75
- <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
76
- </div>
77
- <div id="gawd_auth_url" onclick="gawd_auth_popup(<?php echo GAWD_google_client::create_authentication_url();?>, 800,400)" style="cursor: pointer;"> REAUTHENTICATE
78
- </div>
79
- <div id="gawd_auth_code">
80
- <input id="gawd_token" type="text">
81
- <div id="gawd_auth_code_submit">SUBMIT</div>
82
- </div>
83
-
84
- <div class="gawd_own_wrap">
85
- <label for="gawd_own_project">
86
- <input type="checkbox" <?php echo $gawd_own_project != '' ? 'checked disabled' : '';?> name="gawd_own_project" id="gawd_own_project"/>
87
- <span>Use your own project</span>
88
- <div class="gawd_info" title="Mark as checked to use your project, which you created on console.developers.google.com"></div>
89
- </label>
90
- <div class="own_inputs" <?php echo $gawd_own_project != '' ? 'checked' : 'style="display:none"';?>>
91
- <div class="gawd_goal_row">
92
- <div class="gawd_goal_label">Client ID</div>
93
- <div class="gawd_goal_input">
94
- <input type="text" value="<?php echo isset($own_cliend_id) ? $own_cliend_id : '';?>" name="gawd_own_client_id"/>
95
- </div>
96
- <div class="gawd_info" title="Paste Client ID key. For more information about getting project keys please check the plugin documentation."></div>
97
- <div class='clear'></div>
98
- </div>
99
- <div class="gawd_goal_row">
100
- <div class="gawd_goal_label">Client Secret</div>
101
- <div class="gawd_goal_input">
102
- <input type="text" value="<?php echo isset($own_cliend_secret) ? $own_cliend_secret : '';?>" name="gawd_own_client_secret"/>
103
- </div>
104
- <div class="gawd_info" title="Paste Client Secret key. For more information about getting project keys please check the plugin documentation."></div>
105
- <div class='clear'></div>
106
- </div>
107
- </div>
108
- </div>
109
- </div>
110
- <div class="gawd_alerts">
111
- <img style="margin-top:10px" src="<?php echo GAWD_URL . '/assets/freePages/alerts.png';?>"/>
112
- </div>
113
- <div class="gawd_pushover">
114
- <img style="margin-top:10px" src="<?php echo GAWD_URL . '/assets/freePages/pushovers.png';?>"/>
115
- </div>
116
- <div class="gawd_filters">
117
- <div class="gawd_goal_row">
118
- <span class="gawd_goal_label">View</span>
119
-
120
- <span class="gawd_goal_input">
121
- <!--<select title="Click to pick the website, filters of which you’d like to display." name="gawd_id" onchange="change_filter_account(this)">
122
- <?php
123
-
124
- /* foreach ($accounts as $account_name ){
125
- $selected = $account_name['id'] == $gawd_user_data['accountId'] ? 'selected="selected"' : "";
126
- */
127
- ?>
128
- <option value="<?php echo $account_name['id']; ?>" <?php echo $selected; ?>><?php echo $account_name['name'] ; ?></option>
129
- <?php //} ?>-->
130
- </select>
131
- <select title="Click to pick the website, filters of which you’d like to display." name="gawd_id" onchange="change_filter_account(this)">
132
- <?php
133
- foreach ($profiles as $property_name => $property): ?>
134
- <optgroup label="<?php echo $property_name; ?>">
135
- <?php foreach ($property as $profile):
136
- $webPropertyId = $profile['webPropertyId'];
137
- $id = $profile['id'];
138
- $name = $profile['name'];
139
- $selected = '';
140
- if($id == $gawd_user_data['gawd_id']){
141
- $selected = 'selected="selected"';
142
- $filter_account_name = $property_name;
143
- }
144
- ?>
145
- <option value="<?php echo $id; ?>" <?php echo $selected; ?>><?php echo $property_name.' - '.$name ; ?></option>
146
- <?php endforeach ?>
147
- </optgroup>
148
- <?php endforeach ?>
149
- </select>
150
- <input type="hidden" name='account_name' id='account_name'/>
151
- <input type="hidden" name='web_property_name' id='web_property_name'/>
152
- </span>
153
- <div class="gawd_info" title="Select the website, to which you would like to configure this filter."></div>
154
- <div class='clear'></div>
155
- </div>
156
- <div class="gawd_goal_row">
157
- <span class="gawd_goal_label">Name</span>
158
- <span class="gawd_goal_input">
159
- <input id="gawd_goal_name " class="gawd_filter_name_fild" name="gawd_filter_name" type="text">
160
- </span>
161
- <div class="gawd_info" title="Write a title for the filter."></div>
162
- <div class='clear'></div>
163
- </div>
164
- <div class="gawd_goal_row">
165
- <span class="gawd_goal_label">Type</span>
166
- <span class="gawd_goal_input">
167
- <select name="gawd_filter_type" id="gawd_filter_type">
168
- <option data-name="IP" value="GEO_IP_ADDRESS">Exclude Traffic From IP Address</option>
169
- <option data-name="Country" value="GEO_COUNTRY">Exclude Traffic From Country</option>
170
- <option data-name="Region" value="GEO_REGION">Exclude Traffic From Region</option>
171
- <option data-name="City" value="GEO_CITY">Exclude Traffic From City</option>
172
- </select>
173
- </span>
174
- <div class="gawd_info" title="Choose a type for tracking exclusions: IP address, Country, Region or City."></div>
175
- <div class='clear'></div>
176
- </div>
177
- <div class="gawd_goal_row" id="gawd_filter_value_cont">
178
- <span class="gawd_goal_label" id="gawd_filter_name">IP</span>
179
- <span class="gawd_goal_input">
180
- <div class="time_input"><input id="gawd_filter_value" type="text" name="gawd_filter_value"/></div>
181
- </span>
182
- <div class="gawd_info" title="Define IP address to filter from Google Analytics tracking."></div>
183
- <div class='clear'></div>
184
- </div>
185
- <?php
186
- if (!empty($filters)) {
187
- ?>
188
- <table border="1" class="gawd_table">
189
- <tr>
190
- <th>Name</th>
191
- <th>Type</th>
192
- <th>Value</th>
193
- <th>View</th>
194
- <th>Action</th>
195
-
196
- </tr>
197
- <?php
198
- foreach ($filters as $filter) {
199
- $filter_type = 'Not Supported';
200
- $filter_value = $filter['value'] != "" ? $filter['value'] : 'Not Suported';
201
- if($filter['type'] == "GEO_COUNTRY"){
202
- $filter_type = 'Exclude Traffic From Country';
203
- }
204
- elseif($filter['type'] == "GEO_REGION"){
205
- $filter_type = 'Exclude Traffic From Region';
206
- }
207
- elseif($filter['type'] == "GEO_CITY"){
208
- $filter_type = 'Exclude Traffic From City';
209
- }
210
- elseif($filter['type'] == "GEO_IP_ADDRESS"){
211
- $filter_type = 'Exclude Traffic From IP Address';
212
- }
213
- ?>
214
- <tr data-key="<?php echo $filter['id']; ?>" >
215
- <td><?php echo $filter['name']; ?></td>
216
- <td><?php echo $filter_type; ?></td>
217
- <td><?php echo $filter_value; ?></td>
218
- <td><?php echo $filter['view']; ?></td>
219
- <td><a href="" class="gawd_filter_remove" onclick="if (confirm('<?php echo addslashes(__("Do you want to delete selected item?", 'gawd')); ?>')) {gawd_remove_item('<?php echo $filter['id']; ?>','gawd_filter_remove');return false;} else {return false;}">remove</a></td>
220
- </tr>
221
- <?php
222
- }
223
- ?>
224
- </table>
225
- <?php
226
- }
227
- else{
228
- echo 'There is no data for this view.';
229
- }
230
- ?>
231
- </div>
232
- <div class="gawd_emails">
233
- <?php
234
- $gawd_emails = get_option('gawd_email');
235
-
236
- if($gawd_emails){
237
- ?>
238
- <table border="1" class="gawd_table">
239
- <tr>
240
- <th>Subject</th>
241
- <th>Frequency</th>
242
- <th>Start Date</th>
243
- <th>Recipients</th>
244
- <th>View</th>
245
- <th>Action</th>
246
- </tr>
247
- <?php
248
- foreach($gawd_emails as $key => $email){
249
- if($email['period'] == 'gawd_weekly'){
250
- $email['period'] = 'Weekly';
251
- }
252
- elseif($email['period'] == 'gawd_monthly'){
253
- $email['period'] = 'Monthly';
254
- }
255
- else{
256
- $email['period'] = 'Daily';
257
- }
258
- ?>
259
- <tr data-key="<?php echo $key +1; ?>" >
260
- <td><?php echo $email['name']; ?></td>
261
- <td><?php echo $email['period']; ?></td>
262
- <td><?php echo $email['creation_date']; ?></td>
263
- <td><span class="gawd_break"><?php echo implode(', ',$email['emails']); ?></span></td>
264
- <td><span class="gawd_break"><?php echo $email['view_id']; ?></span></td>
265
- <td><a href="" class="gawd_remove_emails" onclick="if (confirm('<?php echo addslashes(__("Do you want to delete selected item?", 'gawd')); ?>')) {gawd_remove_item('<?php echo $key +1; ?>','gawd_email_remove');return false;} else {return false;}">remove</a></td>
266
- </tr>
267
- <?php
268
- }
269
- ?>
270
- </table>
271
- <?php
272
- }
273
- else{
274
- echo '<a href="' . admin_url() . 'admin.php?page=gawd_reports">You can setup sending e-mail to recipients for any report.</a>';
275
- }
276
- ?>
277
- </div>
278
- <div class="gawd_advanced">
279
- <div class="settings_row">
280
- <div class="onoffswitch">
281
- <input type="checkbox" name="gawd_show_in_dashboard" class="onoffswitch-checkbox" id="gawd_show_in_dashboard" <?php echo isset($gawd_settings['gawd_show_in_dashboard']) && 'on' == $gawd_settings['gawd_show_in_dashboard'] ? 'checked' : '';?>>
282
- <label class="onoffswitch-label" for="gawd_show_in_dashboard">
283
- <span class="onoffswitch-inner"></span>
284
- <span class="onoffswitch-switch"></span>
285
- </label>
286
- </div>
287
- <div class="gawd_info" title="Enable this option to display Google Analytics overview report on WordPress Dashboard."></div>
288
- <div class="onoffswitch_text">
289
- Analytics on WordPress Dashboard
290
- </div>
291
- <div class="clear"></div>
292
- </div>
293
- <div class="settings_row">
294
- <div class="onoffswitch">
295
- <input type="checkbox" name="enable_hover_tooltip" class="onoffswitch-checkbox" id="enable_hover_tooltip" <?php echo $enable_hover_tooltip != '' ? 'checked' : '';?>>
296
- <label class="onoffswitch-label" for="enable_hover_tooltip">
297
- <span class="onoffswitch-inner"></span>
298
- <span class="onoffswitch-switch"></span>
299
- </label>
300
- </div>
301
- <div class="gawd_info" title="Click to enable/disable help text for WD Google Analytics reports."></div>
302
- <div class="onoffswitch_text">
303
- Enable reports tooltips
304
- </div>
305
- <div class="clear"></div>
306
- </div>
307
- <div class="settings_row">
308
- <div class="onoffswitch onoffswitch_disabled">
309
- <input disabled type="checkbox" name="adsense_acc_linking" class="onoffswitch-checkbox" id="adsense_acc_linking" >
310
- <label class="onoffswitch-label" for="adsense_acc_linking">
311
- <span class="onoffswitch-inner"></span>
312
- <span class="onoffswitch-switch"></span>
313
- </label>
314
- </div>
315
- <div class="gawd_info" title="Turn this option on to get AdSense tracking reports. Make sure to link your Google AdSense to Google Analytics first (find out more in plugin documentation)"></div>
316
- <div class="onoffswitch_text">
317
- Enable AdSense link tracking <a target="_blank" href="https://web-dorado.com/products/wordpress-google-analytics-plugin.html" class="gawd_pro"> ( This feature is available in Google Analytics WD Pro. )</a>
318
- </div>
319
- <div class="clear"></div>
320
- </div>
321
- <div class="settings_row">
322
- <div class="onoffswitch">
323
- <input type="checkbox" name="post_page_chart" class="onoffswitch-checkbox" id="post_page_chart" <?php echo $post_page_chart != '' ? 'checked' : '';?>>
324
- <label class="onoffswitch-label" for="post_page_chart">
325
- <span class="onoffswitch-inner"></span>
326
- <span class="onoffswitch-switch"></span>
327
- </label>
328
- </div>
329
- <div class="gawd_info" title="Enable this option to display individual page and post reports on frontend and backend."></div>
330
- <div class="onoffswitch_text">
331
- Enable reports on posts/pages (frontend and backend)
332
- </div>
333
- <div class="clear"></div>
334
- </div>
335
- <div class="settings_row">
336
- <div class="onoffswitch">
337
- <input type="checkbox" name="exclude_events" class="onoffswitch-checkbox" id="exclude_events" <?php echo $exclude_events != '' ? 'checked' : '';?>>
338
- <label class="onoffswitch-label" for="exclude_events">
339
- <span class="onoffswitch-inner"></span>
340
- <span class="onoffswitch-switch"></span>
341
- </label>
342
- </div>
343
- <div class="gawd_info" title="For example, watching a video is a non-interactive event, whereas submitting a form is interactive. Enable this option to filter non-interactive events while calculating bounce-rate."></div>
344
- <div class="onoffswitch_text">
345
- Exclude non-interactive events from bounce-rate calculation
346
- </div>
347
- <div class="clear"></div>
348
- </div>
349
- <div class="settings_row">
350
- <div class="onoffswitch">
351
- <input type="checkbox" name="enable_cross_domain" class="onoffswitch-checkbox" id="enable_cross_domain" <?php echo $enable_cross_domain != '' ? 'checked' : '';?>>
352
- <label class="onoffswitch-label" for="enable_cross_domain">
353
- <span class="onoffswitch-inner"></span>
354
- <span class="onoffswitch-switch"></span>
355
- </label>
356
- </div>
357
- <div class="gawd_info" title="Enable Cross domain tracking to let Google Analytics see similar activities on two related websites as single session."></div>
358
- <div class="onoffswitch_text">
359
- Enable Cross Domain Tracking
360
- </div>
361
- <div class="clear"></div>
362
- </div>
363
- <?php
364
- $cross_dom_show = $enable_cross_domain == '' ? 'style="display:none"' : '';
365
- ?>
366
- <div id="cross_domains" class="gawd_goal_row" <?php echo $cross_dom_show;?>>
367
- <span class="gawd_goal_label">Cross Domains</span>
368
- <span class="gawd_goal_input">
369
- <div class="time_input">
370
- <?php $gawd_settings_cross_domains = get_option("gawd_settings");
371
- if(isset($gawd_settings_cross_domains) && isset($gawd_settings_cross_domains["cross_domains"])){
372
- $gawd_settings_cross_domains = $gawd_settings_cross_domains["cross_domains"];
373
- }else{
374
- $gawd_settings_cross_domains = "";
375
- }
376
- ?>
377
- <input type="text" value="<?php echo $gawd_settings_cross_domains;?>" name="cross_domains">
378
- </div>
379
- </span>
380
- <div class="gawd_info" title="Provide cross domain links separated by commas. The links should have the following format: http://example.com"></div>
381
- <div class="clear"></div>
382
- </div>
383
-
384
- <div class="gawd_goal_row">
385
- <?php $gawd_settings_site_speed_rate = get_option("gawd_settings");
386
- if(isset($gawd_settings_site_speed_rate) && isset($gawd_settings_site_speed_rate["site_speed_rate"])){
387
- $gawd_settings_site_speed_rate = intval($gawd_settings_site_speed_rate["site_speed_rate"]);
388
- }else{
389
- $gawd_settings_site_speed_rate = 1;
390
- }
391
- ?>
392
- <span class="gawd_goal_label">Site Speed SR (%)</span>
393
- <span class="gawd_goal_input">
394
- <div class="time_input"><input value="<?php echo $gawd_settings_site_speed_rate;?>" type="number" min="1" name="site_speed_rate"></div>
395
- </span>
396
- <div class="gawd_info" title="Define the percentage of users, which activity should be evaluated for Site Speed report."></div>
397
- <div class="clear"></div>
398
- </div>
399
- <div class="gawd_goal_row">
400
- <div class="gawd_goal_label">Back end plugin permissions</div>
401
- <div class="checkbox_wrap">
402
- <?php
403
- $roles = new WP_Roles();
404
- $settings_label_count = 0;
405
- foreach($roles->role_names as $key => $name){
406
- $settings_label_count++;
407
- if($name == 'Administrator'){
408
- $key = 'manage_options';
409
- }
410
- elseif($name == 'Editor'){
411
- $key = 'moderate_comments';
412
- }
413
- elseif($name == 'Author'){
414
- $key = 'publish_posts';
415
- }
416
- elseif($name == 'Contributor'){
417
- $key = 'edit_posts';
418
- }
419
- else{
420
- $key = 'read';
421
- }
422
- ?>
423
- <div class="setting_time_wrap time_wrap">
424
- <input id="inp<?php echo $settings_label_count;?>"<?php echo $key == 'manage_options' ? 'disabled' : '';?> class="gawd_perm" type="checkbox" name="gawd_permissions[]" <?php echo in_array($key,$gawd_permissions) || $key == 'manage_options' ? 'checked' : '';?> value="<?php echo $key;?>"/>
425
- <label for="inp<?php echo $settings_label_count;?>"><?php echo $name;?></label>
426
- </div>
427
- <?php
428
- }
429
- ?>
430
- <div class='clear'></div>
431
- </div>
432
- <div class="gawd_info" title="Select user roles to permit access to WD Google Analytics plugin. Only Administrator users can view it by default."></div>
433
- <div class='clear'></div>
434
- </div>
435
- <div class="gawd_goal_row">
436
- <div class="gawd_goal_label">Dashboard overview permissions</div>
437
- <div class="checkbox_wrap">
438
- <?php $roles = new WP_Roles();
439
- $inp_id = 0;
440
- foreach($roles->role_names as $key => $name){
441
- $inp_id++;
442
- ?>
443
- <div class="time_wrap">
444
- <input id="dashboard_overview_permissions<?php echo $inp_id;?>" <?php echo $key == 'administrator' ? 'disabled' : '';?> class="gawd_perm" type="checkbox" name="gawd_backend_roles[]" <?php echo in_array($key,$gawd_backend_roles) || $key == 'administrator' ? 'checked' : '';?> value="<?php echo $key;?>"/>
445
- <label for="dashboard_overview_permissions<?php echo $inp_id;?>"><?php echo $name;?></label>
446
- </div>
447
- <?php
448
- }
449
- ?>
450
- <div class='clear'></div>
451
- </div>
452
- <div class="gawd_info" title="Select user roles, which will have access to view WordPress Dashboard report."></div>
453
- <div class='clear'></div>
454
- </div>
455
- <div class="gawd_goal_row">
456
- <div class="gawd_goal_label">Post/Page report permissions</div>
457
- <div class="checkbox_wrap">
458
- <?php $roles = new WP_Roles();
459
- $inp_id = 0;
460
- foreach($roles->role_names as $key => $name){
461
- $inp_id++;
462
- ?>
463
- <div class="time_wrap">
464
- <input id="gawd_post_page_roles<?php echo $inp_id?>" <?php echo $key == 'administrator' ? 'disabled' : '';?> class="gawd_perm" type="checkbox" name="gawd_post_page_roles[]" <?php echo in_array($key,$gawd_post_page_roles) || $key == 'administrator' ? 'checked' : '';?> value="<?php echo $key;?>"/>
465
- <label for="gawd_post_page_roles<?php echo $inp_id?>"><?php echo $name;?></label>
466
- </div>
467
- <?php
468
- }
469
- ?>
470
- <div class='clear'></div>
471
- </div>
472
- <div class="gawd_info" title="Select user roles, which will have access to view reports from frontend of your website."></div>
473
- <div class='clear'></div>
474
- </div>
475
- <div class="gawd_goal_row">
476
- <div class="gawd_goal_label">Frontend report permissions</div>
477
- <div class="checkbox_wrap">
478
- <?php $roles = new WP_Roles();
479
- $inp_id = 0;
480
- foreach($roles->role_names as $key => $name){
481
- $inp_id++;
482
- ?>
483
- <div class="time_wrap">
484
- <input id="frontend_report_permissions<?php echo $inp_id?>" <?php echo $key == 'administrator' ? 'disabled' : '';?> class="gawd_perm" type="checkbox" name="gawd_frontend_roles[]" <?php echo in_array($key,$gawd_frontend_roles) || $key == 'administrator' ? 'checked' : '';?> value="<?php echo $key;?>"/>
485
- <label for="frontend_report_permissions<?php echo $inp_id?>"><?php echo $name;?></label>
486
- </div>
487
- <?php
488
- }
489
- ?>
490
- <div class='clear'></div>
491
- </div>
492
- <div class="gawd_info" title="Select user roles, which will have access to view reports from frontend of your website."></div>
493
- <div class='clear'></div>
494
- </div>
495
- <div class="gawd_goal_row">
496
- <span class="gawd_goal_label">Date format</span>
497
- <span class="gawd_goal_input">
498
- <select name="default_date_format" id="default_date_format">
499
- <option <?php selected($default_date_format,'ymd_with_week');?> value="ymd_with_week">l, Y-m-d</option>
500
- <option <?php selected($default_date_format,'ymd_without_week');?> value="ymd_without_week">Y-m-d</option>
501
- <option <?php selected($default_date_format,'month_name_with_week');?> value="month_name_with_week">l, F d, Y</option>
502
- <option <?php selected($default_date_format,'month_name_without_week');?> value="month_name_without_week">F d, Y</option>
503
- </select>
504
- </span>
505
- <div class="gawd_info" title="Choose the date format"></div>
506
- <div class='clear'></div>
507
- </div>
508
- <div class="gawd_goal_row">
509
- <span class="gawd_goal_label">Default Date</span>
510
- <span class="gawd_goal_input">
511
- <select name="default_date" id="default_date">
512
- <option id='gawd_last_30days' <?php selected($default_date,'last_30days');?> value="last_30days">Last 30 Days</option>
513
- <option id='gawd_last_7days' <?php selected($default_date,'last_7days');?> value="last_7days">Last 7 Days</option>
514
- <option id='gawd_last_week' <?php selected($default_date,'last_week');?> value="last_week">Last Week</option>
515
- <option id='gawd_this_month' <?php selected($default_date,'this_month');?> value="this_month">This Month</option>
516
- <option id='gawd_last_month' <?php selected($default_date,'last_month');?> value="last_month">Last Month</option>
517
- <option id='gawd_today' <?php selected($default_date,'today');?> value="today">Today</option>
518
- <option id='gawd_yesterday' <?php selected($default_date,'yesterday');?> value="yesterday">Yesterday</option>
519
- </select>
520
- </span>
521
- <div class="gawd_info" title="Choose the initial time period, which will be applied to all reports as their date range."></div>
522
- <div class='clear'></div>
523
- </div>
524
- </div>
525
- <div class="gawd_submit">
526
- <input type="button" class="button_gawd" id="gawd_settings_button"value="SAVE"/>
527
- <input type="button" style="display:none;" class="button_gawd" id="gawd_settings_logout"value="Logout"/>
528
- </div>
529
- <input type='hidden' name="gawd_alert_remove" id="gawd_alert_remove"/>
530
- <input type='hidden' name="gawd_menu_remove" id="gawd_menu_remove"/>
531
- <input type='hidden' name="gawd_pushover_remove" id="gawd_pushover_remove"/>
532
- <input type='hidden' name="gawd_email_remove" id="gawd_email_remove"/>
533
- <input type='hidden' name="gawd_filter_remove" id="gawd_filter_remove"/>
534
- <input type='hidden' name="gawd_settings_tab" id="gawd_settings_tab"/>
535
- <input type='hidden' name="settings_submit" id="gawd_settings_submit"/>
536
- <input type='hidden' name="gawd_settings_logout" id="gawd_settings_logout_val"/>
537
- <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
538
- </form>
539
- </div>
540
-
541
- <div class="clear"></div>
542
- </div>
543
-
544
- <script>
545
-
546
- </script>
1
+ <?php
2
+ $gawd_settings = get_option('gawd_settings');
3
+ $gawd_own_project = get_option('gawd_own_project');
4
+ $gawd_client = GAWD_google_client::get_instance();
5
+ $profiles = $gawd_client->get_profiles();
6
+ $accounts = $gawd_client->get_management_accounts();
7
+ $tabs = get_option('gawd_menu_items');
8
+ $current_user = get_current_user_id();
9
+ $saved_user_menues = get_option('gawd_menu_for_user');
10
+
11
+ if(isset($gawd_own_project) && $gawd_own_project && intval($gawd_own_project)==1){
12
+ $own_credentials = get_option("gawd_credentials");
13
+ $own_cliend_secret = $own_credentials['project_secret'];
14
+ $own_cliend_id = $own_credentials['project_id'];
15
+ echo'<form method="post" style="width: 92.9%;">
16
+ <div class="">
17
+ <input type="hidden" name="reset_data" id="reset_data"/>
18
+ <input type="button" class="button_gawd" id="gawd_reset_button" value="RESET"/>
19
+ <div class="clear"></div>
20
+ </div>
21
+ </form>';
22
+ }
23
+ $filters = $gawd_client->get_management_filters();
24
+ if (!is_array($filters)) {
25
+ $filters = array();
26
+ }
27
+
28
+ $gawd_permissions = isset($gawd_settings['gawd_permissions']) ? $gawd_settings['gawd_permissions'] : array();
29
+ $gawd_excluded_users = isset($gawd_settings['gawd_excluded_users']) ? $gawd_settings['gawd_excluded_users'] : array();
30
+ $gawd_excluded_roles = isset($gawd_settings['gawd_excluded_roles']) ? $gawd_settings['gawd_excluded_roles'] : array();
31
+ $gawd_backend_roles = isset($gawd_settings['gawd_backend_roles']) ? $gawd_settings['gawd_backend_roles'] : array();
32
+ $gawd_frontend_roles = isset($gawd_settings['gawd_frontend_roles']) ? $gawd_settings['gawd_frontend_roles'] : array();
33
+ $gawd_post_page_roles = isset($gawd_settings['gawd_post_page_roles']) ? $gawd_settings['gawd_post_page_roles'] : array();
34
+ $gawd_file_formats = isset($gawd_settings['gawd_file_formats']) ? $gawd_settings['gawd_file_formats'] : '';
35
+ $enable_hover_tooltip = isset($gawd_settings['enable_hover_tooltip']) ? $gawd_settings['enable_hover_tooltip'] : 'on';
36
+ $exclude_events = isset($gawd_settings['exclude_events']) ? $gawd_settings['exclude_events'] : '';
37
+ $enable_cross_domain = isset($gawd_settings['enable_cross_domain']) ? $gawd_settings['enable_cross_domain'] : '';
38
+ $default_date = isset($gawd_settings['default_date']) ? $gawd_settings['default_date'] : '';
39
+ $default_date_format = isset($gawd_settings['default_date_format']) ? $gawd_settings['default_date_format'] : '';
40
+ $post_page_chart = isset($gawd_settings['post_page_chart']) ? $gawd_settings['post_page_chart'] : '';
41
+
42
+ ?>
43
+
44
+ <div id="gawd_body">
45
+ <div class="resp_menu"><div class="menu_img"></div><div class="button_label">SETTINGS</div><div class="clear"></div></div>
46
+ <div class="gawd_menu_coteiner gawd_settings_menu_coteiner">
47
+ <ul class="gawd_menu_ul">
48
+ <li class="gawd_menu_li" id="gawd_authenicate">
49
+ Authenticate
50
+ </li>
51
+ <li class="gawd_menu_li" id="gawd_alerts">
52
+ Alerts
53
+ </li>
54
+ <li class="gawd_menu_li" id="gawd_pushover">
55
+ Pushover
56
+ </li>
57
+ <li class="gawd_menu_li" id="gawd_filters">
58
+ Filters
59
+ </li>
60
+ <li class="gawd_menu_li" id="gawd_emails">
61
+ Emails
62
+ </li>
63
+ <li class=" gawd_menu_li" id="gawd_advanced">
64
+ Advanced
65
+ </li>
66
+ </ul>
67
+ </div>
68
+ <div id="gawd_right_conteiner">
69
+ <h3 class="gawd_page_titles">Settings</h3>
70
+
71
+ <form method="post" id="gawd_form">
72
+ <div class="gawd_authenicate">
73
+ <div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div>
74
+ <div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;">
75
+ <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
76
+ </div>
77
+ <div id="gawd_auth_url" onclick="gawd_auth_popup(<?php echo GAWD_google_client::create_authentication_url();?>, 800,400)" style="cursor: pointer;"> REAUTHENTICATE
78
+ </div>
79
+ <div id="gawd_auth_code">
80
+ <input id="gawd_token" type="text">
81
+ <div id="gawd_auth_code_submit">SUBMIT</div>
82
+ </div>
83
+
84
+ <div class="gawd_own_wrap">
85
+ <label for="gawd_own_project">
86
+ <input type="checkbox" <?php echo $gawd_own_project != '' ? 'checked disabled' : '';?> name="gawd_own_project" id="gawd_own_project"/>
87
+ <span>Use your own project</span>
88
+ <div class="gawd_info" title="Mark as checked to use your project, which you created on console.developers.google.com"></div>
89
+ </label>
90
+ <div class="own_inputs" <?php echo $gawd_own_project != '' ? 'checked' : 'style="display:none"';?>>
91
+ <div class="gawd_goal_row">
92
+ <div class="gawd_goal_label">Client ID</div>
93
+ <div class="gawd_goal_input">
94
+ <input type="text" value="<?php echo isset($own_cliend_id) ? $own_cliend_id : '';?>" name="gawd_own_client_id"/>
95
+ </div>
96
+ <div class="gawd_info" title="Paste Client ID key. For more information about getting project keys please check the plugin documentation."></div>
97
+ <div class='clear'></div>
98
+ </div>
99
+ <div class="gawd_goal_row">
100
+ <div class="gawd_goal_label">Client Secret</div>
101
+ <div class="gawd_goal_input">
102
+ <input type="text" value="<?php echo isset($own_cliend_secret) ? $own_cliend_secret : '';?>" name="gawd_own_client_secret"/>
103
+ </div>
104
+ <div class="gawd_info" title="Paste Client Secret key. For more information about getting project keys please check the plugin documentation."></div>
105
+ <div class='clear'></div>
106
+ </div>
107
+ </div>
108
+ </div>
109
+ </div>
110
+ <div class="gawd_alerts">
111
+ <img style="margin-top:10px" src="<?php echo GAWD_URL . '/assets/freePages/alerts.png';?>"/>
112
+ </div>
113
+ <div class="gawd_pushover">
114
+ <img style="margin-top:10px" src="<?php echo GAWD_URL . '/assets/freePages/pushovers.png';?>"/>
115
+ </div>
116
+ <div class="gawd_filters">
117
+ <div class="gawd_goal_row">
118
+ <span class="gawd_goal_label">View</span>
119
+
120
+ <span class="gawd_goal_input">
121
+ <!--<select title="Click to pick the website, filters of which you’d like to display." name="gawd_id" onchange="change_filter_account(this)">
122
+ <?php
123
+
124
+ /* foreach ($accounts as $account_name ){
125
+ $selected = $account_name['id'] == $gawd_user_data['accountId'] ? 'selected="selected"' : "";
126
+ */
127
+ ?>
128
+ <option value="<?php echo $account_name['id']; ?>" <?php echo $selected; ?>><?php echo $account_name['name'] ; ?></option>
129
+ <?php //} ?>-->
130
+ </select>
131
+ <select title="Click to pick the website, filters of which you’d like to display." name="gawd_id" onchange="change_filter_account(this)">
132
+ <?php
133
+ foreach ($profiles as $property_name => $property): ?>
134
+ <optgroup label="<?php echo $property_name; ?>">
135
+ <?php foreach ($property as $profile):
136
+ $webPropertyId = $profile['webPropertyId'];
137
+ $id = $profile['id'];
138
+ $name = $profile['name'];
139
+ $selected = '';
140
+ if($id == $gawd_user_data['gawd_id']){
141
+ $selected = 'selected="selected"';
142
+ $filter_account_name = $property_name;
143
+ }
144
+ ?>
145
+ <option value="<?php echo $id; ?>" <?php echo $selected; ?>><?php echo $property_name.' - '.$name ; ?></option>
146
+ <?php endforeach ?>
147
+ </optgroup>
148
+ <?php endforeach ?>
149
+ </select>
150
+ <input type="hidden" name='account_name' id='account_name'/>
151
+ <input type="hidden" name='web_property_name' id='web_property_name'/>
152
+ </span>
153
+ <div class="gawd_info" title="Select the website, to which you would like to configure this filter."></div>
154
+ <div class='clear'></div>
155
+ </div>
156
+ <div class="gawd_goal_row">
157
+ <span class="gawd_goal_label">Name</span>
158
+ <span class="gawd_goal_input">
159
+ <input id="gawd_goal_name " class="gawd_filter_name_fild" name="gawd_filter_name" type="text">
160
+ </span>
161
+ <div class="gawd_info" title="Write a title for the filter."></div>
162
+ <div class='clear'></div>
163
+ </div>
164
+ <div class="gawd_goal_row">
165
+ <span class="gawd_goal_label">Type</span>
166
+ <span class="gawd_goal_input">
167
+ <select name="gawd_filter_type" id="gawd_filter_type">
168
+ <option data-name="IP" value="GEO_IP_ADDRESS">Exclude Traffic From IP Address</option>
169
+ <option data-name="Country" value="GEO_COUNTRY">Exclude Traffic From Country</option>
170
+ <option data-name="Region" value="GEO_REGION">Exclude Traffic From Region</option>
171
+ <option data-name="City" value="GEO_CITY">Exclude Traffic From City</option>
172
+ </select>
173
+ </span>
174
+ <div class="gawd_info" title="Choose a type for tracking exclusions: IP address, Country, Region or City."></div>
175
+ <div class='clear'></div>
176
+ </div>
177
+ <div class="gawd_goal_row" id="gawd_filter_value_cont">
178
+ <span class="gawd_goal_label" id="gawd_filter_name">IP</span>
179
+ <span class="gawd_goal_input">
180
+ <div class="time_input"><input id="gawd_filter_value" type="text" name="gawd_filter_value"/></div>
181
+ </span>
182
+ <div class="gawd_info" title="Define IP address to filter from Google Analytics tracking."></div>
183
+ <div class='clear'></div>
184
+ </div>
185
+ <?php
186
+ if (!empty($filters)) {
187
+ ?>
188
+ <table border="1" class="gawd_table">
189
+ <tr>
190
+ <th>Name</th>
191
+ <th>Type</th>
192
+ <th>Value</th>
193
+ <th>View</th>
194
+ <th>Action</th>
195
+
196
+ </tr>
197
+ <?php
198
+ foreach ($filters as $filter) {
199
+ $filter_type = 'Not Supported';
200
+ $filter_value = $filter['value'] != "" ? $filter['value'] : 'Not Suported';
201
+ if($filter['type'] == "GEO_COUNTRY"){
202
+ $filter_type = 'Exclude Traffic From Country';
203
+ }
204
+ elseif($filter['type'] == "GEO_REGION"){
205
+ $filter_type = 'Exclude Traffic From Region';
206
+ }
207
+ elseif($filter['type'] == "GEO_CITY"){
208
+ $filter_type = 'Exclude Traffic From City';
209
+ }
210
+ elseif($filter['type'] == "GEO_IP_ADDRESS"){
211
+ $filter_type = 'Exclude Traffic From IP Address';
212
+ }
213
+ ?>
214
+ <tr data-key="<?php echo $filter['id']; ?>" >
215
+ <td><?php echo $filter['name']; ?></td>
216
+ <td><?php echo $filter_type; ?></td>
217
+ <td><?php echo $filter_value; ?></td>
218
+ <td><?php echo $filter['view']; ?></td>
219
+ <td><a href="" class="gawd_filter_remove" onclick="if (confirm('<?php echo addslashes(__("Do you want to delete selected item?", 'gawd')); ?>')) {gawd_remove_item('<?php echo $filter['id']; ?>','gawd_filter_remove');return false;} else {return false;}">remove</a></td>
220
+ </tr>
221
+ <?php
222
+ }
223
+ ?>
224
+ </table>
225
+ <?php
226
+ }
227
+ else{
228
+ echo 'There is no data for this view.';
229
+ }
230
+ ?>
231
+ </div>
232
+ <div class="gawd_emails">
233
+ <?php
234
+ $gawd_emails = get_option('gawd_email');
235
+
236
+ if($gawd_emails){
237
+ ?>
238
+ <table border="1" class="gawd_table">
239
+ <tr>
240
+ <th>Subject</th>
241
+ <th>Frequency</th>
242
+ <th>Start Date</th>
243
+ <th>Recipients</th>
244
+ <th>View</th>
245
+ <th>Action</th>
246
+ </tr>
247
+ <?php
248
+ foreach($gawd_emails as $key => $email){
249
+ if($email['period'] == 'gawd_weekly'){
250
+ $email['period'] = 'Weekly';
251
+ }
252
+ elseif($email['period'] == 'gawd_monthly'){
253
+ $email['period'] = 'Monthly';
254
+ }
255
+ else{
256
+ $email['period'] = 'Daily';
257
+ }
258
+ ?>
259
+ <tr data-key="<?php echo $key +1; ?>" >
260
+ <td><?php echo $email['name']; ?></td>
261
+ <td><?php echo $email['period']; ?></td>
262
+ <td><?php echo $email['creation_date']; ?></td>
263
+ <td><span class="gawd_break"><?php echo implode(', ',$email['emails']); ?></span></td>
264
+ <td><span class="gawd_break"><?php echo $email['view_id']; ?></span></td>
265
+ <td><a href="" class="gawd_remove_emails" onclick="if (confirm('<?php echo addslashes(__("Do you want to delete selected item?", 'gawd')); ?>')) {gawd_remove_item('<?php echo $key +1; ?>','gawd_email_remove');return false;} else {return false;}">remove</a></td>
266
+ </tr>
267
+ <?php
268
+ }
269
+ ?>
270
+ </table>
271
+ <?php
272
+ }
273
+ else{
274
+ echo '<a href="' . admin_url() . 'admin.php?page=gawd_reports">You can setup sending e-mail to recipients for any report.</a>';
275
+ }
276
+ ?>
277
+ </div>
278
+ <div class="gawd_advanced">
279
+ <div class="settings_row">
280
+ <div class="onoffswitch">
281
+ <input type="checkbox" name="gawd_show_in_dashboard" class="onoffswitch-checkbox" id="gawd_show_in_dashboard" <?php echo isset($gawd_settings['gawd_show_in_dashboard']) && 'on' == $gawd_settings['gawd_show_in_dashboard'] ? 'checked' : '';?>>
282
+ <label class="onoffswitch-label" for="gawd_show_in_dashboard">
283
+ <span class="onoffswitch-inner"></span>
284
+ <span class="onoffswitch-switch"></span>
285
+ </label>
286
+ </div>
287
+ <div class="gawd_info" title="Enable this option to display Google Analytics overview report on WordPress Dashboard."></div>
288
+ <div class="onoffswitch_text">
289
+ Analytics on WordPress Dashboard
290
+ </div>
291
+ <div class="clear"></div>
292
+ </div>
293
+ <div class="settings_row">
294
+ <div class="onoffswitch">
295
+ <input type="checkbox" name="enable_hover_tooltip" class="onoffswitch-checkbox" id="enable_hover_tooltip" <?php echo $enable_hover_tooltip != '' ? 'checked' : '';?>>
296
+ <label class="onoffswitch-label" for="enable_hover_tooltip">
297
+ <span class="onoffswitch-inner"></span>
298
+ <span class="onoffswitch-switch"></span>
299
+ </label>
300
+ </div>
301
+ <div class="gawd_info" title="Click to enable/disable help text for WD Google Analytics reports."></div>
302
+ <div class="onoffswitch_text">
303
+ Enable reports tooltips
304
+ </div>
305
+ <div class="clear"></div>
306
+ </div>
307
+ <div class="settings_row">
308
+ <div class="onoffswitch onoffswitch_disabled">
309
+ <input disabled type="checkbox" name="adsense_acc_linking" class="onoffswitch-checkbox" id="adsense_acc_linking" >
310
+ <label class="onoffswitch-label" for="adsense_acc_linking">
311
+ <span class="onoffswitch-inner"></span>
312
+ <span class="onoffswitch-switch"></span>
313
+ </label>
314
+ </div>
315
+ <div class="gawd_info" title="Turn this option on to get AdSense tracking reports. Make sure to link your Google AdSense to Google Analytics first (find out more in plugin documentation)"></div>
316
+ <div class="onoffswitch_text">
317
+ Enable AdSense link tracking <a target="_blank" href="https://web-dorado.com/products/wordpress-google-analytics-plugin.html" class="gawd_pro"> ( This feature is available in Google Analytics WD Pro. )</a>
318
+ </div>
319
+ <div class="clear"></div>
320
+ </div>
321
+ <div class="settings_row">
322
+ <div class="onoffswitch">
323
+ <input type="checkbox" name="post_page_chart" class="onoffswitch-checkbox" id="post_page_chart" <?php echo $post_page_chart != '' ? 'checked' : '';?>>
324
+ <label class="onoffswitch-label" for="post_page_chart">
325
+ <span class="onoffswitch-inner"></span>
326
+ <span class="onoffswitch-switch"></span>
327
+ </label>
328
+ </div>
329
+ <div class="gawd_info" title="Enable this option to display individual page and post reports on frontend and backend."></div>
330
+ <div class="onoffswitch_text">
331
+ Enable reports on posts/pages (frontend and backend)
332
+ </div>
333
+ <div class="clear"></div>
334
+ </div>
335
+ <div class="settings_row">
336
+ <div class="onoffswitch">
337
+ <input type="checkbox" name="exclude_events" class="onoffswitch-checkbox" id="exclude_events" <?php echo $exclude_events != '' ? 'checked' : '';?>>
338
+ <label class="onoffswitch-label" for="exclude_events">
339
+ <span class="onoffswitch-inner"></span>
340
+ <span class="onoffswitch-switch"></span>
341
+ </label>
342
+ </div>
343
+ <div class="gawd_info" title="For example, watching a video is a non-interactive event, whereas submitting a form is interactive. Enable this option to filter non-interactive events while calculating bounce-rate."></div>
344
+ <div class="onoffswitch_text">
345
+ Exclude non-interactive events from bounce-rate calculation
346
+ </div>
347
+ <div class="clear"></div>
348
+ </div>
349
+ <div class="settings_row">
350
+ <div class="onoffswitch">
351
+ <input type="checkbox" name="enable_cross_domain" class="onoffswitch-checkbox" id="enable_cross_domain" <?php echo $enable_cross_domain != '' ? 'checked' : '';?>>
352
+ <label class="onoffswitch-label" for="enable_cross_domain">
353
+ <span class="onoffswitch-inner"></span>
354
+ <span class="onoffswitch-switch"></span>
355
+ </label>
356
+ </div>
357
+ <div class="gawd_info" title="Enable Cross domain tracking to let Google Analytics see similar activities on two related websites as single session."></div>
358
+ <div class="onoffswitch_text">
359
+ Enable Cross Domain Tracking
360
+ </div>
361
+ <div class="clear"></div>
362
+ </div>
363
+ <?php
364
+ $cross_dom_show = $enable_cross_domain == '' ? 'style="display:none"' : '';
365
+ ?>
366
+ <div id="cross_domains" class="gawd_goal_row" <?php echo $cross_dom_show;?>>
367
+ <span class="gawd_goal_label">Cross Domains</span>
368
+ <span class="gawd_goal_input">
369
+ <div class="time_input">
370
+ <?php $gawd_settings_cross_domains = get_option("gawd_settings");
371
+ if(isset($gawd_settings_cross_domains) && isset($gawd_settings_cross_domains["cross_domains"])){
372
+ $gawd_settings_cross_domains = $gawd_settings_cross_domains["cross_domains"];
373
+ }else{
374
+ $gawd_settings_cross_domains = "";
375
+ }
376
+ ?>
377
+ <input type="text" value="<?php echo $gawd_settings_cross_domains;?>" name="cross_domains">
378
+ </div>
379
+ </span>
380
+ <div class="gawd_info" title="Provide cross domain links separated by commas. The links should have the following format: http://example.com"></div>
381
+ <div class="clear"></div>
382
+ </div>
383
+
384
+ <div class="gawd_goal_row">
385
+ <?php $gawd_settings_site_speed_rate = get_option("gawd_settings");
386
+ if(isset($gawd_settings_site_speed_rate) && isset($gawd_settings_site_speed_rate["site_speed_rate"])){
387
+ $gawd_settings_site_speed_rate = intval($gawd_settings_site_speed_rate["site_speed_rate"]);
388
+ }else{
389
+ $gawd_settings_site_speed_rate = 1;
390
+ }
391
+ ?>
392
+ <span class="gawd_goal_label">Site Speed SR (%)</span>
393
+ <span class="gawd_goal_input">
394
+ <div class="time_input"><input value="<?php echo $gawd_settings_site_speed_rate;?>" type="number" min="1" name="site_speed_rate"></div>
395
+ </span>
396
+ <div class="gawd_info" title="Define the percentage of users, which activity should be evaluated for Site Speed report."></div>
397
+ <div class="clear"></div>
398
+ </div>
399
+ <div class="gawd_goal_row">
400
+ <div class="gawd_goal_label">Back end plugin permissions</div>
401
+ <div class="checkbox_wrap">
402
+ <?php
403
+ $roles = new WP_Roles();
404
+ $settings_label_count = 0;
405
+ foreach($roles->role_names as $key => $name){
406
+ $settings_label_count++;
407
+ if($name == 'Administrator'){
408
+ $key = 'manage_options';
409
+ }
410
+ elseif($name == 'Editor'){
411
+ $key = 'moderate_comments';
412
+ }
413
+ elseif($name == 'Author'){
414
+ $key = 'publish_posts';
415
+ }
416
+ elseif($name == 'Contributor'){
417
+ $key = 'edit_posts';
418
+ }
419
+ else{
420
+ $key = 'read';
421
+ }
422
+ ?>
423
+ <div class="setting_time_wrap time_wrap">
424
+ <input id="inp<?php echo $settings_label_count;?>"<?php echo $key == 'manage_options' ? 'disabled' : '';?> class="gawd_perm" type="checkbox" name="gawd_permissions[]" <?php echo in_array($key,$gawd_permissions) || $key == 'manage_options' ? 'checked' : '';?> value="<?php echo $key;?>"/>
425
+ <label for="inp<?php echo $settings_label_count;?>"><?php echo $name;?></label>
426
+ </div>
427
+ <?php
428
+ }
429
+ ?>
430
+ <div class='clear'></div>
431
+ </div>
432
+ <div class="gawd_info" title="Select user roles to permit access to WD Google Analytics plugin. Only Administrator users can view it by default."></div>
433
+ <div class='clear'></div>
434
+ </div>
435
+ <div class="gawd_goal_row">
436
+ <div class="gawd_goal_label">Dashboard overview permissions</div>
437
+ <div class="checkbox_wrap">
438
+ <?php $roles = new WP_Roles();
439
+ $inp_id = 0;
440
+ foreach($roles->role_names as $key => $name){
441
+ $inp_id++;
442
+ ?>
443
+ <div class="time_wrap">
444
+ <input id="dashboard_overview_permissions<?php echo $inp_id;?>" <?php echo $key == 'administrator' ? 'disabled' : '';?> class="gawd_perm" type="checkbox" name="gawd_backend_roles[]" <?php echo in_array($key,$gawd_backend_roles) || $key == 'administrator' ? 'checked' : '';?> value="<?php echo $key;?>"/>
445
+ <label for="dashboard_overview_permissions<?php echo $inp_id;?>"><?php echo $name;?></label>
446
+ </div>
447
+ <?php
448
+ }
449
+ ?>
450
+ <div class='clear'></div>
451
+ </div>
452
+ <div class="gawd_info" title="Select user roles, which will have access to view WordPress Dashboard report."></div>
453
+ <div class='clear'></div>
454
+ </div>
455
+ <div class="gawd_goal_row">
456
+ <div class="gawd_goal_label">Post/Page report permissions</div>
457
+ <div class="checkbox_wrap">
458
+ <?php $roles = new WP_Roles();
459
+ $inp_id = 0;
460
+ foreach($roles->role_names as $key => $name){
461
+ $inp_id++;
462
+ ?>
463
+ <div class="time_wrap">
464
+ <input id="gawd_post_page_roles<?php echo $inp_id?>" <?php echo $key == 'administrator' ? 'disabled' : '';?> class="gawd_perm" type="checkbox" name="gawd_post_page_roles[]" <?php echo in_array($key,$gawd_post_page_roles) || $key == 'administrator' ? 'checked' : '';?> value="<?php echo $key;?>"/>
465
+ <label for="gawd_post_page_roles<?php echo $inp_id?>"><?php echo $name;?></label>
466
+ </div>
467
+ <?php
468
+ }
469
+ ?>
470
+ <div class='clear'></div>
471
+ </div>
472
+ <div class="gawd_info" title="Select user roles, which will have access to view reports from frontend of your website."></div>
473
+ <div class='clear'></div>
474
+ </div>
475
+ <div class="gawd_goal_row">
476
+ <div class="gawd_goal_label">Frontend report permissions</div>
477
+ <div class="checkbox_wrap">
478
+ <?php $roles = new WP_Roles();
479
+ $inp_id = 0;
480
+ foreach($roles->role_names as $key => $name){
481
+ $inp_id++;
482
+ ?>
483
+ <div class="time_wrap">
484
+ <input id="frontend_report_permissions<?php echo $inp_id?>" <?php echo $key == 'administrator' ? 'disabled' : '';?> class="gawd_perm" type="checkbox" name="gawd_frontend_roles[]" <?php echo in_array($key,$gawd_frontend_roles) || $key == 'administrator' ? 'checked' : '';?> value="<?php echo $key;?>"/>
485
+ <label for="frontend_report_permissions<?php echo $inp_id?>"><?php echo $name;?></label>
486
+ </div>
487
+ <?php
488
+ }
489
+ ?>
490
+ <div class='clear'></div>
491
+ </div>
492
+ <div class="gawd_info" title="Select user roles, which will have access to view reports from frontend of your website."></div>
493
+ <div class='clear'></div>
494
+ </div>
495
+ <div class="gawd_goal_row">
496
+ <span class="gawd_goal_label">Date format</span>
497
+ <span class="gawd_goal_input">
498
+ <select name="default_date_format" id="default_date_format">
499
+ <option <?php selected($default_date_format,'ymd_with_week');?> value="ymd_with_week">l, Y-m-d</option>
500
+ <option <?php selected($default_date_format,'ymd_without_week');?> value="ymd_without_week">Y-m-d</option>
501
+ <option <?php selected($default_date_format,'month_name_with_week');?> value="month_name_with_week">l, F d, Y</option>
502
+ <option <?php selected($default_date_format,'month_name_without_week');?> value="month_name_without_week">F d, Y</option>
503
+ </select>
504
+ </span>
505
+ <div class="gawd_info" title="Choose the date format"></div>
506
+ <div class='clear'></div>
507
+ </div>
508
+ <div class="gawd_goal_row">
509
+ <span class="gawd_goal_label">Default Date</span>
510
+ <span class="gawd_goal_input">
511
+ <select name="default_date" id="default_date">
512
+ <option id='gawd_last_30days' <?php selected($default_date,'last_30days');?> value="last_30days">Last 30 Days</option>
513
+ <option id='gawd_last_7days' <?php selected($default_date,'last_7days');?> value="last_7days">Last 7 Days</option>
514
+ <option id='gawd_last_week' <?php selected($default_date,'last_week');?> value="last_week">Last Week</option>
515
+ <option id='gawd_this_month' <?php selected($default_date,'this_month');?> value="this_month">This Month</option>
516
+ <option id='gawd_last_month' <?php selected($default_date,'last_month');?> value="last_month">Last Month</option>
517
+ <option id='gawd_today' <?php selected($default_date,'today');?> value="today">Today</option>
518
+ <option id='gawd_yesterday' <?php selected($default_date,'yesterday');?> value="yesterday">Yesterday</option>
519
+ </select>
520
+ </span>
521
+ <div class="gawd_info" title="Choose the initial time period, which will be applied to all reports as their date range."></div>
522
+ <div class='clear'></div>
523
+ </div>
524
+ </div>
525
+ <div class="gawd_submit">
526
+ <input type="button" class="button_gawd" id="gawd_settings_button"value="SAVE"/>
527
+ <input type="button" style="display:none;" class="button_gawd" id="gawd_settings_logout"value="Logout"/>
528
+ </div>
529
+ <input type='hidden' name="gawd_alert_remove" id="gawd_alert_remove"/>
530
+ <input type='hidden' name="gawd_menu_remove" id="gawd_menu_remove"/>
531
+ <input type='hidden' name="gawd_pushover_remove" id="gawd_pushover_remove"/>
532
+ <input type='hidden' name="gawd_email_remove" id="gawd_email_remove"/>
533
+ <input type='hidden' name="gawd_filter_remove" id="gawd_filter_remove"/>
534
+ <input type='hidden' name="gawd_settings_tab" id="gawd_settings_tab"/>
535
+ <input type='hidden' name="settings_submit" id="gawd_settings_submit"/>
536
+ <input type='hidden' name="gawd_settings_logout" id="gawd_settings_logout_val"/>
537
+ <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
538
+ </form>
539
+ </div>
540
+
541
+ <div class="clear"></div>
542
+ </div>
543
+
544
+ <script>
545
+
546
+ </script>
admin/pages/tracking.php CHANGED
@@ -1,253 +1,253 @@
1
- <?php
2
- $gawd_settings = get_option('gawd_settings');
3
- if (isset($gawd_user_data['default_webPropertyId'])) {
4
- $tracking_dimensions = $gawd_client->get_custom_dimensions_tracking();
5
- } else {
6
- $tracking_dimensions = 'no_custom_dimensions_exist';
7
- }
8
- $existing_custom_dimensions = $gawd_client->get_custom_dimensions('default');
9
- if (!is_array($existing_custom_dimensions)) {
10
- $existing_custom_dimensions = array();
11
- }
12
- $supported_dimensions = array("Logged in","Post type","Author","Category","Tags","Published Month","Published Year");
13
- $ua_code = isset($gawd_user_data['default_webPropertyId']) ? $gawd_user_data['default_webPropertyId'] : '';
14
- $gawd_permissions = isset($gawd_settings['gawd_permissions']) ? $gawd_settings['gawd_permissions'] : array();
15
- $gawd_anonymize = isset($gawd_settings['gawd_anonymize']) ? $gawd_settings['gawd_anonymize'] : '';
16
- $gawd_tracking_enable = isset($gawd_settings['gawd_tracking_enable']) ? $gawd_settings['gawd_tracking_enable'] : 'on';
17
- $gawd_outbound = isset($gawd_settings['gawd_outbound']) ? $gawd_settings['gawd_outbound'] : '';
18
-
19
- $gawd_enhanced = isset($gawd_settings['gawd_enhanced']) ? $gawd_settings['gawd_enhanced'] : '';
20
- $gawd_file_formats = isset($gawd_settings['gawd_file_formats']) ? $gawd_settings['gawd_file_formats'] : '';
21
- $gawd_tracking_enable = isset($_GET['enableTracking']) ? 'on' : $gawd_tracking_enable;
22
- $domain = GAWD::get_domain(esc_html(get_option('siteurl')));
23
- ?>
24
-
25
- <div id="gawd_body">
26
- <div class="resp_menu"><div class="menu_img"></div><div class="button_label">TRACKING</div><div class="clear"></div></div>
27
- <div class="gawd_menu_coteiner gawd_settings_menu_coteiner">
28
- <ul class="gawd_menu_ul">
29
- <li class=" gawd_menu_li_tracking" id="gawd_tracking">
30
- Tracking
31
- </li>
32
- <li class=" gawd_menu_li_tracking" id="gawd_exclude_tracking">
33
- Exclude
34
- </li>
35
- </ul>
36
- </div>
37
- <div id="gawd_right_conteiner">
38
- <h3 class="gawd_page_titles">Tracking</h3>
39
-
40
- <form method="post" id="gawd_form">
41
- <div class="gawd_tracking">
42
- <div class="gawd_settings_wrapper">
43
- <div class="settings_row">
44
- <div class="onoffswitch">
45
- <input type="checkbox" name="gawd_tracking_enable" class="onoffswitch-checkbox" id="gawd_tracking_enable" <?php echo $gawd_tracking_enable != '' ? 'checked' : '';?>>
46
- <label class="onoffswitch-label" for="gawd_tracking_enable">
47
- <span class="onoffswitch-inner"></span>
48
- <span class="onoffswitch-switch"></span>
49
- </label>
50
- </div>
51
- <div class="gawd_info" title="Enable to add Google Analytics tracking code to <head> tag of your website HTML."></div>
52
- <div class="onoffswitch_text">
53
- Enable Tracking
54
- </div>
55
- <div class="clear"></div>
56
- </div>
57
- <div class="settings_row independent_setting">
58
- <div class="onoffswitch <?php echo (($gawd_tracking_enable == '') ? 'onoffswitch_disabled' : ''); ?> independent_switch">
59
- <input type="checkbox" name="gawd_anonymize" class="onoffswitch-checkbox independent_input" id="gawd_anonymize" <?php echo $gawd_anonymize != '' ? 'checked' : '';?> <?php echo (($gawd_tracking_enable == '') ? 'disabled' : ''); ?>>
60
- <label class="onoffswitch-label" for="gawd_anonymize">
61
- <span class="onoffswitch-inner"></span>
62
- <span class="onoffswitch-switch"></span>
63
- </label>
64
- </div>
65
- <div class="gawd_info" title="Turn this option on, in case you’d like to hide the last block of users’ IP addresses."></div>
66
- <div class="onoffswitch_text">
67
- Anonymize IP address
68
- </div>
69
- <div class="clear"></div>
70
- </div>
71
- <div class="settings_row independent_setting">
72
- <div class="onoffswitch <?php echo (($gawd_tracking_enable == '') ? 'onoffswitch_disabled' : ''); ?> independent_switch">
73
- <input type="checkbox" name="gawd_enhanced" class="onoffswitch-checkbox independent_input" id="gawd_enhanced" <?php echo $gawd_enhanced != '' ? 'checked' : '';?> <?php echo (($gawd_tracking_enable == '') ? 'disabled' : ''); ?>>
74
- <label class="onoffswitch-label" for="gawd_enhanced">
75
- <span class="onoffswitch-inner"></span>
76
- <span class="onoffswitch-switch"></span>
77
- </label>
78
- </div>
79
- <div class="gawd_info" title="Enable this option to track multiple links with the same destination. Get information for buttons, menus, as well as elements with multiple destinations, e.g. search boxes. You can find out more about Enhanced Link Attribution in the plugin documentation."></div>
80
- <div class="onoffswitch_text">
81
- Enhanced Link Attribution
82
- </div>
83
- <div class="clear"></div>
84
- </div>
85
- <div class="settings_row independent_setting">
86
- <div class="onoffswitch <?php echo (($gawd_tracking_enable == '') ? 'onoffswitch_disabled' : ''); ?> independent_switch">
87
- <input type="checkbox" name="gawd_outbound" class="onoffswitch-checkbox independent_input" id="gawd_outbound" <?php echo $gawd_outbound != '' ? 'checked' : '';?> <?php echo (($gawd_tracking_enable == '') ? 'disabled' : ''); ?>>
88
- <label class="onoffswitch-label" for="gawd_outbound">
89
- <span class="onoffswitch-inner"></span>
90
- <span class="onoffswitch-switch"></span>
91
- </label>
92
- </div>
93
- <div class="gawd_info" title="Turn outbound clicks tracking on to track the links users click to leave your website."></div>
94
- <div class="onoffswitch_text">
95
- Outbound clicks tracking
96
- </div>
97
- <div class="clear"></div>
98
- </div>
99
- <div class="settings_row independent_setting">
100
- <div class="onoffswitch <?php echo (($gawd_tracking_enable == '') ? 'onoffswitch_disabled' : ''); ?> independent_switch">
101
- <input type="checkbox" name="gawd_file_formats" value="zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*" class="onoffswitch-checkbox independent_input" id="gawd_file_formats" <?php echo $gawd_file_formats != '' ? 'checked' : '';?> <?php echo (($gawd_tracking_enable == '') ? 'disabled' : ''); ?>>
102
- <label class="onoffswitch-label" for="gawd_file_formats">
103
- <span class="onoffswitch-inner"></span>
104
- <span class="onoffswitch-switch"></span>
105
- </label>
106
- </div>
107
- <div class="gawd_info" title="Enable to track file downloads and mailing links."></div>
108
- <div class="onoffswitch_text track_label">
109
- Mailto, Download tracking (ex.: .doc, .pdf, .jpg, etc.)
110
- </div>
111
- <div class="clear"></div>
112
- </div>
113
- <div style="margin-top:25px">
114
- <img src="<?php echo GAWD_URL.'/assets/freePages/custom_dimensions.png';?>"/>
115
- </div>
116
- </div>
117
- <input name="gawd_custom_dimension_id" type="hidden" value="<?php echo count($existing_custom_dimensions);?>"/>
118
- <div class="gawd_tracking_display">
119
- <p>CODE ADDED TO SITE:</p>
120
- <div id="gawd_tracking_enable_code" <?php if('on' != $gawd_tracking_enable): ?>style="display: none;"<?php endif; ?>>
121
- <code class="html">&#60;script&#62;</code>
122
- <code class="javascript">
123
- (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
124
- (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
125
- m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
126
- })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
127
- <br /><br />
128
- ga('create', '<?php echo $ua_code ?>', 'auto');
129
- </code>
130
- <code id="gawd_anonymize_code" class="javascript" <?php if('on' != $gawd_anonymize): ?>style="display: none;"<?php endif; ?>>
131
- ga('set', 'anonymizeIp', true);
132
- </code>
133
- <code id="gawd_enhanced_code" class="javascript" <?php if('on' != $gawd_enhanced): ?>style="display: none;"<?php endif; ?>>
134
- ga('require', 'linkid', 'linkid.js');
135
- </code>
136
- <code id="gawd_outbound_code" class="javascript" <?php echo $gawd_outbound != '' && isset($domain) && $domain != '' ? '' : 'style="display: none;"';?>>
137
- jQuery(a[href^="http"]).filter(function () {
138
- if (!this.href.match(/.*\.(zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*)(\?.*)?$/)) {
139
- if (this.href.indexOf('devops.web-dorado.info') == -1) {
140
- return this.href
141
- };
142
- }
143
- }).click(function (e) {
144
- ga('send', 'event', 'outbound', 'click', this.href, {'nonInteraction': 1});
145
- });
146
- </code>
147
- <code id="gawd_file_formats_code" class="javascript" <?php echo isset($gawd_file_formats) && $gawd_file_formats != '' ? '' : 'style="display: none"';?>>
148
- jQuery('a').filter(function () {
149
- return this.href.match(/.*\.(zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*)(\?.*)?$/);
150
- }).click(function (e) {
151
- ga('send', 'event', 'download', 'click', this.href, {'nonInteraction': 1});
152
- });
153
- jQuery('a[href^="mailto"]').click(function (e) {
154
- ga('send', 'event', 'email', 'send', this.href, {'nonInteraction': 1});
155
- });
156
- </code>
157
- <code class="javascript">
158
- ga('send', 'pageview');
159
- </code>
160
- <code class="html">&#60;/script&#62;</code>
161
- </div>
162
- </div>
163
- <div class="clear"></div>
164
- </div>
165
- <div class="gawd_exclude_tracking">
166
- <img src="<?php echo GAWD_URL.'/assets/freePages/exclude_tracking.png';?>"/>
167
- </div>
168
- <input type='hidden' name="settings_submit" id="settings_submit"/>
169
- <div class="gawd_submit"><input type="submit" name="settings_submit" class="button_gawd" value="SAVE"/></div>
170
- <input type='hidden' name="gawd_settings_tab" id="gawd_settings_tab"/>
171
- <input type='hidden' name="add_dimension_value" id="add_dimension_value"/>
172
- <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
173
- </form>
174
- </div>
175
-
176
- <div class="clear"></div>
177
- </div>
178
- <script>
179
- jQuery(function() {
180
- jQuery('.chosen-select').chosen();
181
- jQuery('.chosen-select-deselect').chosen({ allow_single_deselect: true });
182
- });
183
- jQuery(document).ready(function(){
184
- jQuery('.button_gawd_add').on('click',function(){
185
- jQuery('#add_dimension_value').val(jQuery(this).data('name'));
186
- jQuery('#settings_submit').val('1');
187
- jQuery('#gawd_form').submit();
188
- })
189
- jQuery("#gawd_right_conteiner").show();
190
- if(window.location.hash===''){
191
- jQuery('.gawd_submit').width('92.9%');
192
- jQuery('.gawd_tracking').show();
193
- jQuery('#gawd_tracking').addClass('gawd_active_li');
194
- if(jQuery(window).width() < 720){
195
- jQuery('#gawd_tracking').addClass('gawd_resp_active_li');
196
- }
197
- }
198
-
199
- else if(window.location.hash==='#gawd_exclude_tracking_tab'){
200
- jQuery('.gawd_submit').width('92.9%');
201
- jQuery('#gawd_exclude_tracking').addClass('gawd_active_li');
202
- jQuery('.gawd_submit').hide();
203
- jQuery('.gawd_exclude_tracking').show();
204
- if(jQuery(window).width() < 720){
205
- jQuery('#gawd_exclude_tracking').addClass('gawd_resp_active_li');
206
- }
207
- }
208
- else if(window.location.hash==='#gawd_tracking_tab'){
209
- jQuery('.gawd_submit').width('92.9%');
210
- jQuery('#gawd_tracking').addClass('gawd_active_li');
211
- jQuery('.gawd_submit').show();
212
- jQuery('.gawd_tracking').show();
213
- if(jQuery(window).width() < 720){
214
- jQuery('#gawd_tracking').addClass('gawd_resp_active_li');
215
- }
216
- }
217
-
218
- else{
219
- jQuery('.gawd_submit').hide();
220
- jQuery('.gawd_tracking').show();
221
- jQuery('#gawd_tracking').addClass('gawd_active_li');
222
- if(jQuery(window).width() < 720){
223
- jQuery('#gawd_tracking').addClass('gawd_resp_active_li');
224
- }
225
- }
226
- })
227
- jQuery('.gawd_menu_li_tracking').on('click',function(){
228
- var tab = jQuery(this).attr('id');
229
- jQuery('.gawd_menu_li_tracking').removeClass('gawd_active_li');
230
- jQuery('.gawd_menu_li_tracking').removeClass('gawd_resp_active_li');
231
- jQuery(this).addClass('gawd_active_li');
232
- if(jQuery(window).width() < 720){
233
- jQuery(this).addClass('gawd_resp_active_li');
234
- }
235
-
236
- jQuery('#gawd_settings_tab').val(tab);
237
- if(tab == 'gawd_tracking'){
238
- window.location.hash = "gawd_tracking_tab";
239
- jQuery(this).addClass('gawd_active_li');
240
- jQuery('.gawd_exclude_tracking').hide();
241
- jQuery('.gawd_submit').show();
242
- jQuery('.gawd_tracking').show();
243
- }
244
- else if(tab == 'gawd_exclude_tracking'){
245
- window.location.hash = "gawd_exclude_tracking_tab";
246
- jQuery(this).addClass('gawd_active_li');
247
- jQuery('.gawd_tracking').hide();
248
- jQuery('.gawd_submit').hide();
249
- jQuery('.gawd_exclude_tracking').show();
250
- }
251
- })
252
- </script>
253
-
1
+ <?php
2
+ $gawd_settings = get_option('gawd_settings');
3
+ if (isset($gawd_user_data['default_webPropertyId'])) {
4
+ $tracking_dimensions = $gawd_client->get_custom_dimensions_tracking();
5
+ } else {
6
+ $tracking_dimensions = 'no_custom_dimensions_exist';
7
+ }
8
+ $existing_custom_dimensions = $gawd_client->get_custom_dimensions('default');
9
+ if (!is_array($existing_custom_dimensions)) {
10
+ $existing_custom_dimensions = array();
11
+ }
12
+ $supported_dimensions = array("Logged in","Post type","Author","Category","Tags","Published Month","Published Year");
13
+ $ua_code = isset($gawd_user_data['default_webPropertyId']) ? $gawd_user_data['default_webPropertyId'] : '';
14
+ $gawd_permissions = isset($gawd_settings['gawd_permissions']) ? $gawd_settings['gawd_permissions'] : array();
15
+ $gawd_anonymize = isset($gawd_settings['gawd_anonymize']) ? $gawd_settings['gawd_anonymize'] : '';
16
+ $gawd_tracking_enable = isset($gawd_settings['gawd_tracking_enable']) ? $gawd_settings['gawd_tracking_enable'] : 'on';
17
+ $gawd_outbound = isset($gawd_settings['gawd_outbound']) ? $gawd_settings['gawd_outbound'] : '';
18
+
19
+ $gawd_enhanced = isset($gawd_settings['gawd_enhanced']) ? $gawd_settings['gawd_enhanced'] : '';
20
+ $gawd_file_formats = isset($gawd_settings['gawd_file_formats']) ? $gawd_settings['gawd_file_formats'] : '';
21
+ $gawd_tracking_enable = isset($_GET['enableTracking']) ? 'on' : $gawd_tracking_enable;
22
+ $domain = GAWD::get_domain(esc_html(get_option('siteurl')));
23
+ ?>
24
+
25
+ <div id="gawd_body">
26
+ <div class="resp_menu"><div class="menu_img"></div><div class="button_label">TRACKING</div><div class="clear"></div></div>
27
+ <div class="gawd_menu_coteiner gawd_settings_menu_coteiner">
28
+ <ul class="gawd_menu_ul">
29
+ <li class=" gawd_menu_li_tracking" id="gawd_tracking">
30
+ Tracking
31
+ </li>
32
+ <li class=" gawd_menu_li_tracking" id="gawd_exclude_tracking">
33
+ Exclude
34
+ </li>
35
+ </ul>
36
+ </div>
37
+ <div id="gawd_right_conteiner">
38
+ <h3 class="gawd_page_titles">Tracking</h3>
39
+
40
+ <form method="post" id="gawd_form">
41
+ <div class="gawd_tracking">
42
+ <div class="gawd_settings_wrapper">
43
+ <div class="settings_row">
44
+ <div class="onoffswitch">
45
+ <input type="checkbox" name="gawd_tracking_enable" class="onoffswitch-checkbox" id="gawd_tracking_enable" <?php echo $gawd_tracking_enable != '' ? 'checked' : '';?>>
46
+ <label class="onoffswitch-label" for="gawd_tracking_enable">
47
+ <span class="onoffswitch-inner"></span>
48
+ <span class="onoffswitch-switch"></span>
49
+ </label>
50
+ </div>
51
+ <div class="gawd_info" title="Enable to add Google Analytics tracking code to <head> tag of your website HTML."></div>
52
+ <div class="onoffswitch_text">
53
+ Enable Tracking
54
+ </div>
55
+ <div class="clear"></div>
56
+ </div>
57
+ <div class="settings_row independent_setting">
58
+ <div class="onoffswitch <?php echo (($gawd_tracking_enable == '') ? 'onoffswitch_disabled' : ''); ?> independent_switch">
59
+ <input type="checkbox" name="gawd_anonymize" class="onoffswitch-checkbox independent_input" id="gawd_anonymize" <?php echo $gawd_anonymize != '' ? 'checked' : '';?> <?php echo (($gawd_tracking_enable == '') ? 'disabled' : ''); ?>>
60
+ <label class="onoffswitch-label" for="gawd_anonymize">
61
+ <span class="onoffswitch-inner"></span>
62
+ <span class="onoffswitch-switch"></span>
63
+ </label>
64
+ </div>
65
+ <div class="gawd_info" title="Turn this option on, in case you’d like to hide the last block of users’ IP addresses."></div>
66
+ <div class="onoffswitch_text">
67
+ Anonymize IP address
68
+ </div>
69
+ <div class="clear"></div>
70
+ </div>
71
+ <div class="settings_row independent_setting">
72
+ <div class="onoffswitch <?php echo (($gawd_tracking_enable == '') ? 'onoffswitch_disabled' : ''); ?> independent_switch">
73
+ <input type="checkbox" name="gawd_enhanced" class="onoffswitch-checkbox independent_input" id="gawd_enhanced" <?php echo $gawd_enhanced != '' ? 'checked' : '';?> <?php echo (($gawd_tracking_enable == '') ? 'disabled' : ''); ?>>
74
+ <label class="onoffswitch-label" for="gawd_enhanced">
75
+ <span class="onoffswitch-inner"></span>
76
+ <span class="onoffswitch-switch"></span>
77
+ </label>
78
+ </div>
79
+ <div class="gawd_info" title="Enable this option to track multiple links with the same destination. Get information for buttons, menus, as well as elements with multiple destinations, e.g. search boxes. You can find out more about Enhanced Link Attribution in the plugin documentation."></div>
80
+ <div class="onoffswitch_text">
81
+ Enhanced Link Attribution
82
+ </div>
83
+ <div class="clear"></div>
84
+ </div>
85
+ <div class="settings_row independent_setting">
86
+ <div class="onoffswitch <?php echo (($gawd_tracking_enable == '') ? 'onoffswitch_disabled' : ''); ?> independent_switch">
87
+ <input type="checkbox" name="gawd_outbound" class="onoffswitch-checkbox independent_input" id="gawd_outbound" <?php echo $gawd_outbound != '' ? 'checked' : '';?> <?php echo (($gawd_tracking_enable == '') ? 'disabled' : ''); ?>>
88
+ <label class="onoffswitch-label" for="gawd_outbound">
89
+ <span class="onoffswitch-inner"></span>
90
+ <span class="onoffswitch-switch"></span>
91
+ </label>
92
+ </div>
93
+ <div class="gawd_info" title="Turn outbound clicks tracking on to track the links users click to leave your website."></div>
94
+ <div class="onoffswitch_text">
95
+ Outbound clicks tracking
96
+ </div>
97
+ <div class="clear"></div>
98
+ </div>
99
+ <div class="settings_row independent_setting">
100
+ <div class="onoffswitch <?php echo (($gawd_tracking_enable == '') ? 'onoffswitch_disabled' : ''); ?> independent_switch">
101
+ <input type="checkbox" name="gawd_file_formats" value="zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*" class="onoffswitch-checkbox independent_input" id="gawd_file_formats" <?php echo $gawd_file_formats != '' ? 'checked' : '';?> <?php echo (($gawd_tracking_enable == '') ? 'disabled' : ''); ?>>
102
+ <label class="onoffswitch-label" for="gawd_file_formats">
103
+ <span class="onoffswitch-inner"></span>
104
+ <span class="onoffswitch-switch"></span>
105
+ </label>
106
+ </div>
107
+ <div class="gawd_info" title="Enable to track file downloads and mailing links."></div>
108
+ <div class="onoffswitch_text track_label">
109
+ Mailto, Download tracking (ex.: .doc, .pdf, .jpg, etc.)
110
+ </div>
111
+ <div class="clear"></div>
112
+ </div>
113
+ <div style="margin-top:25px">
114
+ <img src="<?php echo GAWD_URL.'/assets/freePages/custom_dimensions.png';?>"/>
115
+ </div>
116
+ </div>
117
+ <input name="gawd_custom_dimension_id" type="hidden" value="<?php echo count($existing_custom_dimensions);?>"/>
118
+ <div class="gawd_tracking_display">
119
+ <p>CODE ADDED TO SITE:</p>
120
+ <div id="gawd_tracking_enable_code" <?php if('on' != $gawd_tracking_enable): ?>style="display: none;"<?php endif; ?>>
121
+ <code class="html">&#60;script&#62;</code>
122
+ <code class="javascript">
123
+ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
124
+ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
125
+ m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
126
+ })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
127
+ <br /><br />
128
+ ga('create', '<?php echo $ua_code ?>', 'auto');
129
+ </code>
130
+ <code id="gawd_anonymize_code" class="javascript" <?php if('on' != $gawd_anonymize): ?>style="display: none;"<?php endif; ?>>
131
+ ga('set', 'anonymizeIp', true);
132
+ </code>
133
+ <code id="gawd_enhanced_code" class="javascript" <?php if('on' != $gawd_enhanced): ?>style="display: none;"<?php endif; ?>>
134
+ ga('require', 'linkid', 'linkid.js');
135
+ </code>
136
+ <code id="gawd_outbound_code" class="javascript" <?php echo $gawd_outbound != '' && isset($domain) && $domain != '' ? '' : 'style="display: none;"';?>>
137
+ jQuery(a[href^="http"]).filter(function () {
138
+ if (!this.href.match(/.*\.(zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*)(\?.*)?$/)) {
139
+ if (this.href.indexOf('devops.web-dorado.info') == -1) {
140
+ return this.href
141
+ };
142
+ }
143
+ }).click(function (e) {
144
+ ga('send', 'event', 'outbound', 'click', this.href, {'nonInteraction': 1});
145
+ });
146
+ </code>
147
+ <code id="gawd_file_formats_code" class="javascript" <?php echo isset($gawd_file_formats) && $gawd_file_formats != '' ? '' : 'style="display: none"';?>>
148
+ jQuery('a').filter(function () {
149
+ return this.href.match(/.*\.(zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*)(\?.*)?$/);
150
+ }).click(function (e) {
151
+ ga('send', 'event', 'download', 'click', this.href, {'nonInteraction': 1});
152
+ });
153
+ jQuery('a[href^="mailto"]').click(function (e) {
154
+ ga('send', 'event', 'email', 'send', this.href, {'nonInteraction': 1});
155
+ });
156
+ </code>
157
+ <code class="javascript">
158
+ ga('send', 'pageview');
159
+ </code>
160
+ <code class="html">&#60;/script&#62;</code>
161
+ </div>
162
+ </div>
163
+ <div class="clear"></div>
164
+ </div>
165
+ <div class="gawd_exclude_tracking">
166
+ <img src="<?php echo GAWD_URL.'/assets/freePages/exclude_tracking.png';?>"/>
167
+ </div>
168
+ <input type='hidden' name="settings_submit" id="settings_submit"/>
169
+ <div class="gawd_submit"><input type="submit" name="settings_submit" class="button_gawd" value="SAVE"/></div>
170
+ <input type='hidden' name="gawd_settings_tab" id="gawd_settings_tab"/>
171
+ <input type='hidden' name="add_dimension_value" id="add_dimension_value"/>
172
+ <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
173
+ </form>
174
+ </div>
175
+
176
+ <div class="clear"></div>
177
+ </div>
178
+ <script>
179
+ jQuery(function() {
180
+ jQuery('.chosen-select').chosen();
181
+ jQuery('.chosen-select-deselect').chosen({ allow_single_deselect: true });
182
+ });
183
+ jQuery(document).ready(function(){
184
+ jQuery('.button_gawd_add').on('click',function(){
185
+ jQuery('#add_dimension_value').val(jQuery(this).data('name'));
186
+ jQuery('#settings_submit').val('1');
187
+ jQuery('#gawd_form').submit();
188
+ })
189
+ jQuery("#gawd_right_conteiner").show();
190
+ if(window.location.hash===''){
191
+ jQuery('.gawd_submit').width('92.9%');
192
+ jQuery('.gawd_tracking').show();
193
+ jQuery('#gawd_tracking').addClass('gawd_active_li');
194
+ if(jQuery(window).width() < 720){
195
+ jQuery('#gawd_tracking').addClass('gawd_resp_active_li');
196
+ }
197
+ }
198
+
199
+ else if(window.location.hash==='#gawd_exclude_tracking_tab'){
200
+ jQuery('.gawd_submit').width('92.9%');
201
+ jQuery('#gawd_exclude_tracking').addClass('gawd_active_li');
202
+ jQuery('.gawd_submit').hide();
203
+ jQuery('.gawd_exclude_tracking').show();
204
+ if(jQuery(window).width() < 720){
205
+ jQuery('#gawd_exclude_tracking').addClass('gawd_resp_active_li');
206
+ }
207
+ }
208
+ else if(window.location.hash==='#gawd_tracking_tab'){
209
+ jQuery('.gawd_submit').width('92.9%');
210
+ jQuery('#gawd_tracking').addClass('gawd_active_li');
211
+ jQuery('.gawd_submit').show();
212
+ jQuery('.gawd_tracking').show();
213
+ if(jQuery(window).width() < 720){
214
+ jQuery('#gawd_tracking').addClass('gawd_resp_active_li');
215
+ }
216
+ }
217
+
218
+ else{
219
+ jQuery('.gawd_submit').hide();
220
+ jQuery('.gawd_tracking').show();
221
+ jQuery('#gawd_tracking').addClass('gawd_active_li');
222
+ if(jQuery(window).width() < 720){
223
+ jQuery('#gawd_tracking').addClass('gawd_resp_active_li');
224
+ }
225
+ }
226
+ })
227
+ jQuery('.gawd_menu_li_tracking').on('click',function(){
228
+ var tab = jQuery(this).attr('id');
229
+ jQuery('.gawd_menu_li_tracking').removeClass('gawd_active_li');
230
+ jQuery('.gawd_menu_li_tracking').removeClass('gawd_resp_active_li');
231
+ jQuery(this).addClass('gawd_active_li');
232
+ if(jQuery(window).width() < 720){
233
+ jQuery(this).addClass('gawd_resp_active_li');
234
+ }
235
+
236
+ jQuery('#gawd_settings_tab').val(tab);
237
+ if(tab == 'gawd_tracking'){
238
+ window.location.hash = "gawd_tracking_tab";
239
+ jQuery(this).addClass('gawd_active_li');
240
+ jQuery('.gawd_exclude_tracking').hide();
241
+ jQuery('.gawd_submit').show();
242
+ jQuery('.gawd_tracking').show();
243
+ }
244
+ else if(tab == 'gawd_exclude_tracking'){
245
+ window.location.hash = "gawd_exclude_tracking_tab";
246
+ jQuery(this).addClass('gawd_active_li');
247
+ jQuery('.gawd_tracking').hide();
248
+ jQuery('.gawd_submit').hide();
249
+ jQuery('.gawd_exclude_tracking').show();
250
+ }
251
+ })
252
+ </script>
253
+
admin/pages/uninstall.php CHANGED
@@ -1,81 +1,81 @@
1
- <?php
2
-
3
- class GAWDUninstall{
4
-
5
- public function uninstall(){
6
- ?>
7
- <form method="post" action="" id="adminForm">
8
- <div class="gawd">
9
- <h2>
10
- <img src="<?php echo GAWD_URL . '/assets/uninstall-icon.png';?>" width="30" style="vertical-align:middle;">
11
- <span><?php _e("Uninstall WD Google Analytics","gawd"); ?></span>
12
- </h2>
13
- <div class="goodbye-text">
14
- <?php
15
- $support_team = '<a href="https://web-dorado.com/support/contact-us.html?source=google-analytics-wd" target="_blank">' . __('support team', 'gawd') . '</a>';
16
- $contact_us = '<a href="https://web-dorado.com/support/contact-us.html?source=google-analytics-wd" target="_blank">' . __('Contact us', 'gawd') . '</a>';
17
- echo sprintf(__("Before uninstalling the plugin, please Contact our %s. We'll do our best to help you out with your issue. We value each and every user and value what's right for our users in everything we do.<br />
18
- However, if anyway you have made a decision to uninstall the plugin, please take a minute to %s and tell what you didn't like for our plugins further improvement and development. Thank you !!!", "gawd"), $support_team, $contact_us); ?>
19
- </div>
20
- <p style="color: red;">
21
- <strong><?php _e("WARNING:","gawd"); ?></strong>
22
- <?php _e("Once uninstalled, this can't be undone. You should use a Database Backup plugin of WordPress to back up all the data first.","gawd"); ?>
23
- </p>
24
- <p style="color: red">
25
- <strong><?php _e("The following Database options will be deleted:","gawd"); ?></strong>
26
- </p>
27
- <table class="widefat">
28
- <thead>
29
- <tr>
30
- <th><?php _e("Database options","gawd"); ?></th>
31
- </tr>
32
- </thead>
33
- <tr>
34
- <td valign="top">
35
- <ol>
36
- <li>gawd_custom_reports</li>
37
- <li>gawd_menu_for_user</li>
38
- <li>gawd_all_metrics</li>
39
- <li>gawd_all_dimensions</li>
40
- <li>gawd_custom_dimensions</li>
41
- <li>gawd_settings</li>
42
- <li>gawd_user_data</li>
43
- <li>gawd_credentials</li>
44
- <li>gawd_menu_items</li>
45
- <li>gawd_export_chart_data</li>
46
- <li>gawd_email</li>
47
- <li>gawd_custom_reports</li>
48
- <li>gawd_alerts</li>
49
- <li>gawd_pushovers</li>
50
- <li>gawd_menu_for_users</li>
51
- <li>gawd_own_project</li>
52
- <li>gawd_zoom_message</li>
53
- </ol>
54
- </td>
55
- </tr>
56
-
57
- </table>
58
- <p style="text-align: center;"> <?php _e("Do you really want to uninstall WD Google Analytics?","gawd"); ?></p>
59
- <p style="text-align: center;">
60
- <input type="checkbox" name="unistall_gawd" id="check_yes" value="yes" />&nbsp;
61
- <label for="check_yes"><?php _e("Yes","gawd"); ?></label>
62
- </p>
63
- <p style="text-align: center;">
64
- <input type="button" id="gawd_uninstall" value="<?php _e("UNINSTALL","gawd"); ?>" onclick="if (check_yes.checked) {
65
- if (confirm('You are About to Uninstall WD Google Analytics from WordPress.\nThis Action Is Not Reversible.')) {
66
- jQuery('#adminForm').submit();;
67
- } else {
68
- return false;
69
- }
70
- }
71
- else {
72
- return false;
73
- }" class="wd-btn wd-btn-primary" />
74
- </p>
75
- </div>
76
- <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
77
- </form>
78
- <?php
79
- }
80
-
81
  }
1
+ <?php
2
+
3
+ class GAWDUninstall{
4
+
5
+ public function uninstall(){
6
+ ?>
7
+ <form method="post" action="" id="adminForm">
8
+ <div class="gawd">
9
+ <h2>
10
+ <img src="<?php echo GAWD_URL . '/assets/uninstall-icon.png';?>" width="30" style="vertical-align:middle;">
11
+ <span><?php _e("Uninstall WD Google Analytics","gawd"); ?></span>
12
+ </h2>
13
+ <div class="goodbye-text">
14
+ <?php
15
+ $support_team = '<a href="https://web-dorado.com/support/contact-us.html?source=google-analytics-wd" target="_blank">' . __('support team', 'gawd') . '</a>';
16
+ $contact_us = '<a href="https://web-dorado.com/support/contact-us.html?source=google-analytics-wd" target="_blank">' . __('Contact us', 'gawd') . '</a>';
17
+ echo sprintf(__("Before uninstalling the plugin, please Contact our %s. We'll do our best to help you out with your issue. We value each and every user and value what's right for our users in everything we do.<br />
18
+ However, if anyway you have made a decision to uninstall the plugin, please take a minute to %s and tell what you didn't like for our plugins further improvement and development. Thank you !!!", "gawd"), $support_team, $contact_us); ?>
19
+ </div>
20
+ <p style="color: red;">
21
+ <strong><?php _e("WARNING:","gawd"); ?></strong>
22
+ <?php _e("Once uninstalled, this can't be undone. You should use a Database Backup plugin of WordPress to back up all the data first.","gawd"); ?>
23
+ </p>
24
+ <p style="color: red">
25
+ <strong><?php _e("The following Database options will be deleted:","gawd"); ?></strong>
26
+ </p>
27
+ <table class="widefat">
28
+ <thead>
29
+ <tr>
30
+ <th><?php _e("Database options","gawd"); ?></th>
31
+ </tr>
32
+ </thead>
33
+ <tr>
34
+ <td valign="top">
35
+ <ol>
36
+ <li>gawd_custom_reports</li>
37
+ <li>gawd_menu_for_user</li>
38
+ <li>gawd_all_metrics</li>
39
+ <li>gawd_all_dimensions</li>
40
+ <li>gawd_custom_dimensions</li>
41
+ <li>gawd_settings</li>
42
+ <li>gawd_user_data</li>
43
+ <li>gawd_credentials</li>
44
+ <li>gawd_menu_items</li>
45
+ <li>gawd_export_chart_data</li>
46
+ <li>gawd_email</li>
47
+ <li>gawd_custom_reports</li>
48
+ <li>gawd_alerts</li>
49
+ <li>gawd_pushovers</li>
50
+ <li>gawd_menu_for_users</li>
51
+ <li>gawd_own_project</li>
52
+ <li>gawd_zoom_message</li>
53
+ </ol>
54
+ </td>
55
+ </tr>
56
+
57
+ </table>
58
+ <p style="text-align: center;"> <?php _e("Do you really want to uninstall WD Google Analytics?","gawd"); ?></p>
59
+ <p style="text-align: center;">
60
+ <input type="checkbox" name="unistall_gawd" id="check_yes" value="yes" />&nbsp;
61
+ <label for="check_yes"><?php _e("Yes","gawd"); ?></label>
62
+ </p>
63
+ <p style="text-align: center;">
64
+ <input type="button" id="gawd_uninstall" value="<?php _e("UNINSTALL","gawd"); ?>" onclick="if (check_yes.checked) {
65
+ if (confirm('You are About to Uninstall WD Google Analytics from WordPress.\nThis Action Is Not Reversible.')) {
66
+ jQuery('#adminForm').submit();;
67
+ } else {
68
+ return false;
69
+ }
70
+ }
71
+ else {
72
+ return false;
73
+ }" class="wd-btn wd-btn-primary" />
74
+ </p>
75
+ </div>
76
+ <?php wp_nonce_field('gawd_save_form', 'gawd_save_form_fild'); ?>
77
+ </form>
78
+ <?php
79
+ }
80
+
81
  }
admin/pages/visitors.php CHANGED
@@ -1,10 +1,10 @@
1
-
2
-
3
- <div class="">
4
- <div class="opacity_div_compact">
5
- <div class="loading_div_compact">
6
- <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
7
- </div>
8
- </div>
9
- <div id="gawd_visitors_meta"></div>
10
- </div>
1
+
2
+
3
+ <div class="">
4
+ <div class="opacity_div_compact">
5
+ <div class="loading_div_compact">
6
+ <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
7
+ </div>
8
+ </div>
9
+ <div id="gawd_visitors_meta"></div>
10
+ </div>
admin/post_page_view.php CHANGED
@@ -1,62 +1,62 @@
1
- <?php
2
- $id = isset($_GET['post']) ? $_GET['post'] : '';
3
- $uri_parts = explode( '/', get_permalink( $id ), 4 );
4
- if ( isset( $uri_parts[3] ) ) {
5
- $uri = '/' . $uri_parts[3];
6
- }
7
- $uri = explode( '/',$uri);
8
- end($uri);
9
- $key = key($uri);
10
- $uri = '/' . $uri[$key-1];
11
- $filter = rawurlencode( rawurldecode( $uri ) );
12
- $filter = rawurlencode( rawurldecode(get_the_title()));
13
- ?>
14
- <a href="#" class="gawd_btn">X</a>
15
- <!--<select name="gawd_post_page_date" id="gawd_post_page_date" >
16
- <option value="<?php echo date('Y-m-d', strtotime('-30 days')); ?>"><?php _e('Last 30 Days', 'gawd'); ?></option>
17
- <option value="<?php echo date('Y-m-d', strtotime('-7 days')); ?>"><?php _e('Last 7 Days', 'gawd'); ?></option>
18
- </select> -->
19
- <div class="gawd_content" id="gawd_content_range" >
20
- <div id="reportrange" class="pull-right" style="float:none !important">
21
- <span></span> <b class="caret"></b>
22
- </div>
23
- <input type="hidden" id="gawd_start_end_date"/>
24
- </div>
25
- <select name="gawd_metric_post_page" id="gawd_metric_post_page" >
26
- <option value="sessions"><?php _e('Sessions', 'gawd'); ?></option>
27
- <option value="users" ><?php _e('Users', 'gawd'); ?></option>
28
- <option value="bounceRate" ><?php _e('Bounce Rate', 'gawd'); ?></option>
29
- <option value="pageviews" ><?php _e('Pageviews', 'gawd'); ?></option>
30
- <option value="percentNewSessions"><?php _e('% New Sessions', 'gawd'); ?></option>
31
- <option value="avgSessionDuration"><?php _e('Avg Session Duration', 'gawd'); ?></option>
32
- <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
33
- </select>
34
- <select name="gawd_chart_type_post_page" id="gawd_chart_type_post_page" class="gawd_draw_analytics">
35
- <option value="line" ><?php _e('Line Chart', 'gawd'); ?></option>
36
- <option value="pie" ><?php _e('Pie Chart', 'gawd'); ?></option>
37
- <option value="column" ><?php _e('Columns', 'gawd'); ?></option>
38
- </select>
39
- <div class="clear"></div>
40
-
41
- <div class="">
42
- <div class="opacity_div_compact">
43
- <div class="loading_div_compact">
44
- <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
45
- </div>
46
- </div>
47
- <div class="gawd_post_page_meta" id="gawd_post_page_meta"></div>
48
- </div>
49
- <script>
50
- jQuery(document).ready(function(){
51
- datepicker_js('right','gawd_chart_type_post_page_callback');
52
- jQuery('#gawd_metric_post_page, #gawd_post_page_date, #gawd_chart_type_post_page').on('change',function(){
53
- gawd_chart_type_post_page('#<?php echo $filter;?>','gawd_post_page_meta');
54
- })
55
- })
56
- function gawd_chart_type_post_page_callback(start, end){
57
- jQuery('#reportrange span').html(start.format('Y-MM-DD') + ' - ' + end.format('Y-MM-DD'));
58
- jQuery('#gawd_start_end_date').val(start.format('Y-MM-DD') + '/-/' + end.format('Y-MM-DD'));
59
- gawd_chart_type_post_page('#<?php echo $filter;?>','gawd_post_page_meta');
60
- }
61
-
62
  </script>
1
+ <?php
2
+ $id = isset($_GET['post']) ? $_GET['post'] : '';
3
+ $uri_parts = explode( '/', get_permalink( $id ), 4 );
4
+ if ( isset( $uri_parts[3] ) ) {
5
+ $uri = '/' . $uri_parts[3];
6
+ }
7
+ $uri = explode( '/',$uri);
8
+ end($uri);
9
+ $key = key($uri);
10
+ $uri = '/' . $uri[$key-1];
11
+ $filter = rawurlencode( rawurldecode( $uri ) );
12
+ $filter = rawurlencode( rawurldecode(get_the_title()));
13
+ ?>
14
+ <a href="#" class="gawd_btn">X</a>
15
+ <!--<select name="gawd_post_page_date" id="gawd_post_page_date" >
16
+ <option value="<?php echo date('Y-m-d', strtotime('-30 days')); ?>"><?php _e('Last 30 Days', 'gawd'); ?></option>
17
+ <option value="<?php echo date('Y-m-d', strtotime('-7 days')); ?>"><?php _e('Last 7 Days', 'gawd'); ?></option>
18
+ </select> -->
19
+ <div class="gawd_content" id="gawd_content_range" >
20
+ <div id="reportrange" class="pull-right" style="float:none !important">
21
+ <span></span> <b class="caret"></b>
22
+ </div>
23
+ <input type="hidden" id="gawd_start_end_date"/>
24
+ </div>
25
+ <select name="gawd_metric_post_page" id="gawd_metric_post_page" >
26
+ <option value="sessions"><?php _e('Sessions', 'gawd'); ?></option>
27
+ <option value="users" ><?php _e('Users', 'gawd'); ?></option>
28
+ <option value="bounceRate" ><?php _e('Bounce Rate', 'gawd'); ?></option>
29
+ <option value="pageviews" ><?php _e('Pageviews', 'gawd'); ?></option>
30
+ <option value="percentNewSessions"><?php _e('% New Sessions', 'gawd'); ?></option>
31
+ <option value="avgSessionDuration"><?php _e('Avg Session Duration', 'gawd'); ?></option>
32
+ <option value="pageviewsPerSession" ><?php echo __('Pages/Session', 'gawd'); ?></option>
33
+ </select>
34
+ <select name="gawd_chart_type_post_page" id="gawd_chart_type_post_page" class="gawd_draw_analytics">
35
+ <option value="line" ><?php _e('Line Chart', 'gawd'); ?></option>
36
+ <option value="pie" ><?php _e('Pie Chart', 'gawd'); ?></option>
37
+ <option value="column" ><?php _e('Columns', 'gawd'); ?></option>
38
+ </select>
39
+ <div class="clear"></div>
40
+
41
+ <div class="">
42
+ <div class="opacity_div_compact">
43
+ <div class="loading_div_compact">
44
+ <img src="<?php echo GAWD_URL . '/assets/ajax_loader.gif'; ?>" style="margin-top: 200px; width:50px;">
45
+ </div>
46
+ </div>
47
+ <div class="gawd_post_page_meta" id="gawd_post_page_meta"></div>
48
+ </div>
49
+ <script>
50
+ jQuery(document).ready(function(){
51
+ datepicker_js('right','gawd_chart_type_post_page_callback');
52
+ jQuery('#gawd_metric_post_page, #gawd_post_page_date, #gawd_chart_type_post_page').on('change',function(){
53
+ gawd_chart_type_post_page('#<?php echo $filter;?>','gawd_post_page_meta');
54
+ })
55
+ })
56
+ function gawd_chart_type_post_page_callback(start, end){
57
+ jQuery('#reportrange span').html(start.format('Y-MM-DD') + ' - ' + end.format('Y-MM-DD'));
58
+ jQuery('#gawd_start_end_date').val(start.format('Y-MM-DD') + '/-/' + end.format('Y-MM-DD'));
59
+ gawd_chart_type_post_page('#<?php echo $filter;?>','gawd_post_page_meta');
60
+ }
61
+
62
  </script>
admin/tracking.php CHANGED
@@ -1,148 +1,148 @@
1
- <?php
2
- $custom_dimensions = $gawd_client->get_custom_dimensions_tracking();
3
- $gawd_settings = get_option('gawd_settings');
4
- require_once(GAWD_DIR . '/gawd_class.php');
5
- $domain = GAWD::get_domain(esc_html(get_option('siteurl')));
6
- $all_users = get_users();
7
- $compare_users = array();
8
- foreach ($all_users as $user) {
9
- $compare_users[] = $user->user_nicename;
10
- }
11
- $gawd_user_data = get_option('gawd_user_data');
12
- $ua_code = $gawd_user_data['default_webPropertyId'];
13
-
14
-
15
-
16
- $cross_domain_list = '';
17
- if (isset($gawd_settings['enable_cross_domain']) && isset($gawd_settings['cross_domains']) && $gawd_settings['cross_domains'] != '' && $gawd_settings['enable_cross_domain'] != '') {
18
- $cross_domain_list = $gawd_settings['cross_domains'];
19
- }
20
- $gawd_outbound = isset($gawd_settings['gawd_outbound']) ? $gawd_settings['gawd_outbound'] : '';
21
-
22
- ?>
23
-
24
-
25
- <script>
26
- <?php if ('on' == $gawd_settings['gawd_tracking_enable']) { ?>
27
- (function (i, s, o, g, r, a, m) {
28
- i['GoogleAnalyticsObject'] = r;
29
- i[r] = i[r] || function () {
30
- (i[r].q = i[r].q || []).push(arguments)
31
- }, i[r].l = 1 * new Date();
32
- a = s.createElement(o),
33
- m = s.getElementsByTagName(o)[0];
34
- a.async = 1;
35
- a.src = g;
36
- m.parentNode.insertBefore(a, m)
37
- })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
38
- ga('create', '<?php echo $ua_code ?>', 'auto', {'siteSpeedSampleRate': '<?php echo isset($gawd_settings['site_speed_rate']) ? $gawd_settings['site_speed_rate'] : 1; ?>' <?php echo $cross_domain_list != '' ? ",'allowLinker' : true" : ""; ?>});
39
- <?php if ($cross_domain_list != '') { ?>
40
- ga('require', 'linker');
41
- ga('linker:autoLink', [' <?php echo $cross_domain_list; ?>']);
42
- <?php }; ?>
43
-
44
- <?php if (isset($gawd_settings['gawd_anonymize']) && 'on' == $gawd_settings['gawd_anonymize']) : ?>
45
- ga('set', 'anonymizeIp', true);
46
- <?php
47
- endif;
48
- if ($custom_dimensions != "no_custom_dimensions_exist") {
49
- foreach ($custom_dimensions as $custom_dimension) {
50
- $optname = 'gawd_custom_dimension_' . str_replace(' ', '_', $custom_dimension['name']);
51
- if ($gawd_settings[$optname] == 'on') {
52
- switch ($custom_dimension['name']) {
53
- case 'Logged in': {
54
- if (GAWD_google_client::gawd_cd_logged_in()) {
55
- echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_logged_in() . "');\n";
56
- }
57
- break;
58
- }
59
- case 'Post type': {
60
- if (GAWD_google_client::gawd_cd_post_type()) {
61
- echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_post_type() . "');\n";
62
- }
63
- break;
64
- }
65
- case 'Author': {
66
- if (GAWD_google_client::gawd_cd_author()) {
67
- echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_author() . "');\n";
68
- }
69
- break;
70
- }
71
- case 'Category': {
72
- if (GAWD_google_client::gawd_cd_category()) {
73
- echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_category() . "');\n";
74
- }
75
- break;
76
- }
77
- case 'Published Month': {
78
- if (GAWD_google_client::gawd_cd_published_month()) {
79
- echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_published_month() . "');\n";
80
- }
81
- break;
82
- }
83
- case 'Published Year': {
84
- if (GAWD_google_client::gawd_cd_published_year()) {
85
- echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_published_year() . "');\n";
86
- }
87
- break;
88
- }
89
- case 'Tags': {
90
- if (GAWD_google_client::gawd_cd_tags()) {
91
- echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_tags() . "');\n";
92
- }
93
- break;
94
- }
95
- default: break;
96
- }
97
- }
98
- }
99
- }
100
- ?>
101
- ga('send', 'pageview');
102
- <?php } ?>
103
- jQuery(document).ready(function () {
104
- jQuery(window).load(function () {
105
- <?php if (isset($gawd_settings['gawd_file_formats']) && $gawd_settings['gawd_file_formats'] != '') { ?>
106
- //Track Downloads
107
- jQuery('a').filter(function () {
108
- return this.href.match(/.*\.(<?php echo esc_js($gawd_settings['gawd_file_formats']); ?>)(\?.*)?$/);
109
- }).click(function (e) {
110
- ga('send', 'event', 'download', 'click', this.href<?php
111
- if (isset($gawd_settings['exclude_events']) && $gawd_settings['exclude_events']) {
112
- echo ", {'nonInteraction': 1}";
113
- }
114
- ?>);
115
- });
116
-
117
- //Track Mailto
118
- jQuery('a[href^="mailto"]').click(function (e) {
119
- ga('send', 'event', 'email', 'send', this.href<?php
120
- if (isset($gawd_settings['exclude_events']) && $gawd_settings['exclude_events']) {
121
- echo ", {'nonInteraction': 1}";
122
- }
123
- ?>);
124
- });
125
- <?php }
126
- if($gawd_outbound != ''){
127
- if (isset($domain) && $domain ) { ?>
128
- //Track Outbound Links
129
- jQuery('a[href^="http"]').filter(function () {
130
- if (!this.href.match(/.*\.(<?php echo esc_js(isset($gawd_settings['gawd_file_formats']) && $gawd_settings['gawd_file_formats'] != ''); ?>)(\?.*)?$/)) {
131
- if (this.href.indexOf('<?php echo $domain; ?>') == -1) {
132
- return this.href
133
- }
134
- ;
135
- }
136
- }).click(function (e) {
137
- ga('send', 'event', 'outbound', 'click', this.href<?php
138
- if (isset($gawd_settings['exclude_events']) && $gawd_settings['exclude_events']) {
139
- echo ", {'nonInteraction': 1}";
140
- }
141
- ?>);
142
- });
143
- <?php } ?>
144
- <?php } ?>
145
- });
146
- });
147
-
148
  </script>
1
+ <?php
2
+ $custom_dimensions = $gawd_client->get_custom_dimensions_tracking();
3
+ $gawd_settings = get_option('gawd_settings');
4
+ require_once(GAWD_DIR . '/gawd_class.php');
5
+ $domain = GAWD::get_domain(esc_html(get_option('siteurl')));
6
+ $all_users = get_users();
7
+ $compare_users = array();
8
+ foreach ($all_users as $user) {
9
+ $compare_users[] = $user->user_nicename;
10
+ }
11
+ $gawd_user_data = get_option('gawd_user_data');
12
+ $ua_code = $gawd_user_data['default_webPropertyId'];
13
+
14
+
15
+
16
+ $cross_domain_list = '';
17
+ if (isset($gawd_settings['enable_cross_domain']) && isset($gawd_settings['cross_domains']) && $gawd_settings['cross_domains'] != '' && $gawd_settings['enable_cross_domain'] != '') {
18
+ $cross_domain_list = $gawd_settings['cross_domains'];
19
+ }
20
+ $gawd_outbound = isset($gawd_settings['gawd_outbound']) ? $gawd_settings['gawd_outbound'] : '';
21
+
22
+ ?>
23
+
24
+
25
+ <script>
26
+ <?php if ('on' == $gawd_settings['gawd_tracking_enable']) { ?>
27
+ (function (i, s, o, g, r, a, m) {
28
+ i['GoogleAnalyticsObject'] = r;
29
+ i[r] = i[r] || function () {
30
+ (i[r].q = i[r].q || []).push(arguments)
31
+ }, i[r].l = 1 * new Date();
32
+ a = s.createElement(o),
33
+ m = s.getElementsByTagName(o)[0];
34
+ a.async = 1;
35
+ a.src = g;
36
+ m.parentNode.insertBefore(a, m)
37
+ })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
38
+ ga('create', '<?php echo $ua_code ?>', 'auto', {'siteSpeedSampleRate': '<?php echo isset($gawd_settings['site_speed_rate']) ? $gawd_settings['site_speed_rate'] : 1; ?>' <?php echo $cross_domain_list != '' ? ",'allowLinker' : true" : ""; ?>});
39
+ <?php if ($cross_domain_list != '') { ?>
40
+ ga('require', 'linker');
41
+ ga('linker:autoLink', [' <?php echo $cross_domain_list; ?>']);
42
+ <?php }; ?>
43
+
44
+ <?php if (isset($gawd_settings['gawd_anonymize']) && 'on' == $gawd_settings['gawd_anonymize']) : ?>
45
+ ga('set', 'anonymizeIp', true);
46
+ <?php
47
+ endif;
48
+ if ($custom_dimensions != "no_custom_dimensions_exist") {
49
+ foreach ($custom_dimensions as $custom_dimension) {
50
+ $optname = 'gawd_custom_dimension_' . str_replace(' ', '_', $custom_dimension['name']);
51
+ if ($gawd_settings[$optname] == 'on') {
52
+ switch ($custom_dimension['name']) {
53
+ case 'Logged in': {
54
+ if (GAWD_google_client::gawd_cd_logged_in()) {
55
+ echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_logged_in() . "');\n";
56
+ }
57
+ break;
58
+ }
59
+ case 'Post type': {
60
+ if (GAWD_google_client::gawd_cd_post_type()) {
61
+ echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_post_type() . "');\n";
62
+ }
63
+ break;
64
+ }
65
+ case 'Author': {
66
+ if (GAWD_google_client::gawd_cd_author()) {
67
+ echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_author() . "');\n";
68
+ }
69
+ break;
70
+ }
71
+ case 'Category': {
72
+ if (GAWD_google_client::gawd_cd_category()) {
73
+ echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_category() . "');\n";
74
+ }
75
+ break;
76
+ }
77
+ case 'Published Month': {
78
+ if (GAWD_google_client::gawd_cd_published_month()) {
79
+ echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_published_month() . "');\n";
80
+ }
81
+ break;
82
+ }
83
+ case 'Published Year': {
84
+ if (GAWD_google_client::gawd_cd_published_year()) {
85
+ echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_published_year() . "');\n";
86
+ }
87
+ break;
88
+ }
89
+ case 'Tags': {
90
+ if (GAWD_google_client::gawd_cd_tags()) {
91
+ echo "ga('set', 'dimension" . $custom_dimension['id'] . "', '" . GAWD_google_client::gawd_cd_tags() . "');\n";
92
+ }
93
+ break;
94
+ }
95
+ default: break;
96
+ }
97
+ }
98
+ }
99
+ }
100
+ ?>
101
+ ga('send', 'pageview');
102
+ <?php } ?>
103
+ jQuery(document).ready(function () {
104
+ jQuery(window).load(function () {
105
+ <?php if (isset($gawd_settings['gawd_file_formats']) && $gawd_settings['gawd_file_formats'] != '') { ?>
106
+ //Track Downloads
107
+ jQuery('a').filter(function () {
108
+ return this.href.match(/.*\.(<?php echo esc_js($gawd_settings['gawd_file_formats']); ?>)(\?.*)?$/);
109
+ }).click(function (e) {
110
+ ga('send', 'event', 'download', 'click', this.href<?php
111
+ if (isset($gawd_settings['exclude_events']) && $gawd_settings['exclude_events']) {
112
+ echo ", {'nonInteraction': 1}";
113
+ }
114
+ ?>);
115
+ });
116
+
117
+ //Track Mailto
118
+ jQuery('a[href^="mailto"]').click(function (e) {
119
+ ga('send', 'event', 'email', 'send', this.href<?php
120
+ if (isset($gawd_settings['exclude_events']) && $gawd_settings['exclude_events']) {
121
+ echo ", {'nonInteraction': 1}";
122
+ }
123
+ ?>);
124
+ });
125
+ <?php }
126
+ if($gawd_outbound != ''){
127
+ if (isset($domain) && $domain ) { ?>
128
+ //Track Outbound Links
129
+ jQuery('a[href^="http"]').filter(function () {
130
+ if (!this.href.match(/.*\.(<?php echo esc_js(isset($gawd_settings['gawd_file_formats']) && $gawd_settings['gawd_file_formats'] != ''); ?>)(\?.*)?$/)) {
131
+ if (this.href.indexOf('<?php echo $domain; ?>') == -1) {
132
+ return this.href
133
+ }
134
+ ;
135
+ }
136
+ }).click(function (e) {
137
+ ga('send', 'event', 'outbound', 'click', this.href<?php
138
+ if (isset($gawd_settings['exclude_events']) && $gawd_settings['exclude_events']) {
139
+ echo ", {'nonInteraction': 1}";
140
+ }
141
+ ?>);
142
+ });
143
+ <?php } ?>
144
+ <?php } ?>
145
+ });
146
+ });
147
+
148
  </script>
featured/featured.php CHANGED
@@ -1,171 +1,171 @@
1
- <?php
2
- function gawd_featured_plugins($current_plugin = '') {
3
- $plugins = array(
4
- "form-maker" => array(
5
- 'title' => 'Form Maker',
6
- 'text' => 'Wordpress form builder plugin',
7
- 'content' => 'Form Maker is a modern and advanced tool for creating WordPress forms easily and fast.',
8
- 'href' => 'https://web-dorado.com/products/wordpress-form.html'
9
- ),
10
- "photo-gallery" => array(
11
- 'title' => 'Photo Gallery',
12
- 'text' => 'WordPress Photo Gallery plugin',
13
- 'content' => 'Photo Gallery is a fully responsive WordPress Gallery plugin with advanced functionality.',
14
- 'href' => 'https://web-dorado.com/products/wordpress-photo-gallery-plugin.html'
15
- ),
16
- "contact_form_bulder" => array(
17
- 'title' => 'Contact Form Builder',
18
- 'text' => 'WordPress contact form builder plugin',
19
- 'content' => 'Contact Form Builder is the best tool for quickly arranging a contact form for your clients and visitors.',
20
- 'href' => 'https://web-dorado.com/products/wordpress-contact-form-builder.html'
21
- ),
22
- "slider_wd" => array(
23
- 'title' => 'Slider WD',
24
- 'text' => 'WordPress slider plugin',
25
- 'content' => 'Create responsive, highly configurable sliders with various effects for your WordPress site.',
26
- 'href' => 'https://web-dorado.com/products/wordpress-slider-plugin.html'
27
- ),
28
- "events-wd" => array(
29
- 'title' => 'Event Calendar WD',
30
- 'text' => 'WordPress calendar plugin',
31
- 'content' => 'Organize and publish your events in an easy and elegant way using Event Calendar WD.',
32
- 'href' => 'https://web-dorado.com/products/wordpress-event-calendar-wd.html'
33
- ),
34
- "contact-maker" => array(
35
- 'title' => 'Contact Form Maker',
36
- 'text' => 'WordPress contact form maker plugin',
37
- 'content' => 'WordPress Contact Form Maker is an advanced and easy-to-use tool for creating forms.',
38
- 'href' => 'https://web-dorado.com/products/wordpress-contact-form-maker-plugin.html'
39
- ),
40
- "spider-calendar" => array(
41
- 'title' => 'Spider Calendar',
42
- 'text' => 'WordPress event calendar plugin',
43
- 'content' => 'Spider Event Calendar is a highly configurable product which allows you to have multiple organized events.',
44
- 'href' => 'https://web-dorado.com/products/wordpress-calendar.html'
45
- ),
46
- "catalog" => array(
47
- 'title' => 'Spider Catalog',
48
- 'text' => 'WordPress product catalog plugin',
49
- 'content' => 'Spider Catalog for WordPress is a convenient tool for organizing the products represented on your website into catalogs.',
50
- 'href' => 'https://web-dorado.com/products/wordpress-catalog.html'
51
- ),
52
- "player" => array(
53
- 'title' => 'Video Player',
54
- 'text' => 'WordPress Video player plugin',
55
- 'content' => 'Spider Video Player for WordPress is a Flash & HTML5 video player plugin that allows you to easily add videos to your website with the possibility.',
56
- 'href' => 'https://web-dorado.com/products/wordpress-player.html'
57
- ),
58
- "contacts" => array(
59
- 'title' => 'Spider Contacts',
60
- 'text' => 'Wordpress staff list plugin',
61
- 'content' => 'Spider Contacts helps you to display information about the group of people more intelligible, effective and convenient.',
62
- 'href' => 'https://web-dorado.com/products/wordpress-contacts-plugin.html'
63
- ),
64
- "facebook" => array(
65
- 'title' => 'Spider Facebook',
66
- 'text' => 'WordPress Facebook plugin',
67
- 'content' => 'Spider Facebook is a WordPress integration tool for Facebook.It includes all the available Facebook social plugins and widgets.',
68
- 'href' => 'https://web-dorado.com/products/wordpress-facebook.html'
69
- ),
70
- "twitter-widget" => array(
71
- 'title' => 'Widget Twitter',
72
- 'text' => 'WordPress Widget Twitter plugin',
73
- 'content' => 'The Widget Twitter plugin lets you to fully integrate your WordPress site with your Twitter account.',
74
- 'href' => 'https://web-dorado.com/products/wordpress-twitter-integration-plugin.html'
75
- ),
76
- "faq" => array(
77
- 'title' => 'Spider FAQ',
78
- 'text' => 'WordPress FAQ Plugin',
79
- 'content' => 'The Spider FAQ WordPress plugin is for creating an FAQ (Frequently Asked Questions) section for your website.',
80
- 'href' => 'https://web-dorado.com/products/wordpress-faq-plugin.html'
81
- ),
82
- "zoom" => array(
83
- 'title' => 'Zoom',
84
- 'text' => 'WordPress text zoom plugin',
85
- 'content' => 'Zoom enables site users to resize the predefined areas of the web site.',
86
- 'href' => 'https://web-dorado.com/products/wordpress-zoom.html'
87
- ),
88
- "flash-calendar" => array(
89
- 'title' => 'Flash Calendar',
90
- 'text' => 'WordPress flash calendar plugin',
91
- 'content' => 'Spider Flash Calendar is a highly configurable Flash calendar plugin which allows you to have multiple organized events.',
92
- 'href' => 'https://web-dorado.com/products/wordpress-events-calendar.html'
93
- ),
94
- "folder_menu" => array(
95
- 'title' => 'Folder Menu',
96
- 'text' => 'WordPress folder menu plugin',
97
- 'content' => 'Folder Menu Vertical is a WordPress Flash menu module for your website, designed to meet your needs and preferences.',
98
- 'href' => 'https://web-dorado.com/products/wordpress-menu-vertical.html'
99
- ),
100
- "random_post" => array(
101
- 'title' => 'Random post',
102
- 'text' => 'WordPress random post plugin',
103
- 'content' => 'Spider Random Post is a small but very smart solution for your WordPress web site.',
104
- 'href' => 'https://web-dorado.com/products/wordpress-random-post.html'
105
- ),
106
- "faq_wd" => array(
107
- 'title' => 'FAQ WD',
108
- 'text' => 'WordPress FAQ plugin',
109
- 'content' => 'Organize and publish your FAQs in an easy and elegant way using FAQ WD.',
110
- 'href' => 'https://web-dorado.com/products/wordpress-faq-wd.html'
111
- ),
112
- "instagram_feed" => array(
113
- 'title' => 'Instagram Feed WD',
114
- 'text' => 'WordPress Instagram Feed plugin',
115
- 'content' => 'WD Instagram Feed is a user-friendly tool for displaying user or hashtag-based feeds on your website.',
116
- 'href' => 'https://web-dorado.com/products/wordpress-instagram-feed-wd.html'
117
- ),
118
- "post-slider" => array(
119
- 'title' => 'Post Slider',
120
- 'text' => 'WordPress Post Slider plugin',
121
- 'content' => 'Post Slider WD is designed to show off the selected posts of your website in a slider.',
122
- 'href' => 'https://web-dorado.com/products/wordpress-post-slider-plugin.html'
123
- ),
124
- "google-maps" => array(
125
- 'title' => 'Google Map',
126
- 'text' => 'WordPress Google Maps Plugin',
127
- 'content' => 'Google Maps WD is an intuitive tool for creating Google maps with advanced markers, custom layers and overlays for your website.',
128
- 'href' => 'https://web-dorado.com/products/wordpress-google-maps-plugin.html'
129
- ),
130
- "wd-google-analytics" => array(
131
- 'title' => 'Wd Google Analytics',
132
- 'text' => 'WordPress Google Analytics Plugin',
133
- 'content' => 'WD Google Analytics is a user-friendly all in one plugin, which allows to manage and monitor your website analytics from WordPress dashboard.',
134
- 'href' => 'https://web-dorado.com/products/wordpress-google-analytics-plugin.html'
135
- )
136
- );
137
- ?>
138
- <div id="main_featured_plugins_page">
139
- <h3>Featured Plugins</h3>
140
- <div class="featured_header">
141
- <a target="_blank" href="https://web-dorado.com/wordpress-plugins.html?source=<?php echo $current_plugin; ?>">
142
- <h1>GET <?php echo $plugins[$current_plugin]["title"]; ?> +23 PLUGINS</h1>
143
- <h1 class="get_plugins">FOR $100 ONLY <span>- SAVE 70%</span></h1>
144
- <div class="try-now">
145
- <span>TRY NOW</span>
146
- </div>
147
- </a>
148
- </div>
149
- <ul id="featured-plugins-list">
150
- <?php
151
- foreach ($plugins as $key => $plugins) {
152
- if ($current_plugin != $key) {
153
- ?>
154
- <li class="<?php echo $key; ?>">
155
- <div class="product"></div>
156
- <div class="title">
157
- <strong class="heading"><?php echo $plugins['title']; ?></strong>
158
- </div>
159
- <div class="description">
160
- <p><?php echo $plugins['content']; ?></p>
161
- </div>
162
- <a target="_blank" href="<?php echo $plugins['href']; ?>?source=<?php echo $current_plugin; ?>" class="download">Download Plugin &#9658;</a>
163
- </li>
164
- <?php
165
- }
166
- }
167
- ?>
168
- </ul>
169
- </div>
170
- <?php
171
  }
1
+ <?php
2
+ function gawd_featured_plugins($current_plugin = '') {
3
+ $plugins = array(
4
+ "form-maker" => array(
5
+ 'title' => 'Form Maker',
6
+ 'text' => 'Wordpress form builder plugin',
7
+ 'content' => 'Form Maker is a modern and advanced tool for creating WordPress forms easily and fast.',
8
+ 'href' => 'https://web-dorado.com/products/wordpress-form.html'
9
+ ),
10
+ "photo-gallery" => array(
11
+ 'title' => 'Photo Gallery',
12
+ 'text' => 'WordPress Photo Gallery plugin',
13
+ 'content' => 'Photo Gallery is a fully responsive WordPress Gallery plugin with advanced functionality.',
14
+ 'href' => 'https://web-dorado.com/products/wordpress-photo-gallery-plugin.html'
15
+ ),
16
+ "contact_form_bulder" => array(
17
+ 'title' => 'Contact Form Builder',
18
+ 'text' => 'WordPress contact form builder plugin',
19
+ 'content' => 'Contact Form Builder is the best tool for quickly arranging a contact form for your clients and visitors.',
20
+ 'href' => 'https://web-dorado.com/products/wordpress-contact-form-builder.html'
21
+ ),
22
+ "slider_wd" => array(
23
+ 'title' => 'Slider WD',
24
+ 'text' => 'WordPress slider plugin',
25
+ 'content' => 'Create responsive, highly configurable sliders with various effects for your WordPress site.',
26
+ 'href' => 'https://web-dorado.com/products/wordpress-slider-plugin.html'
27
+ ),
28
+ "events-wd" => array(
29
+ 'title' => 'Event Calendar WD',
30
+ 'text' => 'WordPress calendar plugin',
31
+ 'content' => 'Organize and publish your events in an easy and elegant way using Event Calendar WD.',
32
+ 'href' => 'https://web-dorado.com/products/wordpress-event-calendar-wd.html'
33
+ ),
34
+ "contact-maker" => array(
35
+ 'title' => 'Contact Form Maker',
36
+ 'text' => 'WordPress contact form maker plugin',
37
+ 'content' => 'WordPress Contact Form Maker is an advanced and easy-to-use tool for creating forms.',
38
+ 'href' => 'https://web-dorado.com/products/wordpress-contact-form-maker-plugin.html'
39
+ ),
40
+ "spider-calendar" => array(
41
+ 'title' => 'Spider Calendar',
42
+ 'text' => 'WordPress event calendar plugin',
43
+ 'content' => 'Spider Event Calendar is a highly configurable product which allows you to have multiple organized events.',
44
+ 'href' => 'https://web-dorado.com/products/wordpress-calendar.html'
45
+ ),
46
+ "catalog" => array(
47
+ 'title' => 'Spider Catalog',
48
+ 'text' => 'WordPress product catalog plugin',
49
+ 'content' => 'Spider Catalog for WordPress is a convenient tool for organizing the products represented on your website into catalogs.',
50
+ 'href' => 'https://web-dorado.com/products/wordpress-catalog.html'
51
+ ),
52
+ "player" => array(
53
+ 'title' => 'Video Player',
54
+ 'text' => 'WordPress Video player plugin',
55
+ 'content' => 'Spider Video Player for WordPress is a Flash & HTML5 video player plugin that allows you to easily add videos to your website with the possibility.',
56
+ 'href' => 'https://web-dorado.com/products/wordpress-player.html'
57
+ ),
58
+ "contacts" => array(
59
+ 'title' => 'Spider Contacts',
60
+ 'text' => 'Wordpress staff list plugin',
61
+ 'content' => 'Spider Contacts helps you to display information about the group of people more intelligible, effective and convenient.',
62
+ 'href' => 'https://web-dorado.com/products/wordpress-contacts-plugin.html'
63
+ ),
64
+ "facebook" => array(
65
+ 'title' => 'Spider Facebook',
66
+ 'text' => 'WordPress Facebook plugin',
67
+ 'content' => 'Spider Facebook is a WordPress integration tool for Facebook.It includes all the available Facebook social plugins and widgets.',
68
+ 'href' => 'https://web-dorado.com/products/wordpress-facebook.html'
69
+ ),
70
+ "twitter-widget" => array(
71
+ 'title' => 'Widget Twitter',
72
+ 'text' => 'WordPress Widget Twitter plugin',
73
+ 'content' => 'The Widget Twitter plugin lets you to fully integrate your WordPress site with your Twitter account.',
74
+ 'href' => 'https://web-dorado.com/products/wordpress-twitter-integration-plugin.html'
75
+ ),
76
+ "faq" => array(
77
+ 'title' => 'Spider FAQ',
78
+ 'text' => 'WordPress FAQ Plugin',
79
+ 'content' => 'The Spider FAQ WordPress plugin is for creating an FAQ (Frequently Asked Questions) section for your website.',
80
+ 'href' => 'https://web-dorado.com/products/wordpress-faq-plugin.html'
81
+ ),
82
+ "zoom" => array(
83
+ 'title' => 'Zoom',
84
+ 'text' => 'WordPress text zoom plugin',
85
+ 'content' => 'Zoom enables site users to resize the predefined areas of the web site.',
86
+ 'href' => 'https://web-dorado.com/products/wordpress-zoom.html'
87
+ ),
88
+ "flash-calendar" => array(
89
+ 'title' => 'Flash Calendar',
90
+ 'text' => 'WordPress flash calendar plugin',
91
+ 'content' => 'Spider Flash Calendar is a highly configurable Flash calendar plugin which allows you to have multiple organized events.',
92
+ 'href' => 'https://web-dorado.com/products/wordpress-events-calendar.html'
93
+ ),
94
+ "folder_menu" => array(
95
+ 'title' => 'Folder Menu',
96
+ 'text' => 'WordPress folder menu plugin',
97
+ 'content' => 'Folder Menu Vertical is a WordPress Flash menu module for your website, designed to meet your needs and preferences.',
98
+ 'href' => 'https://web-dorado.com/products/wordpress-menu-vertical.html'
99
+ ),
100
+ "random_post" => array(
101
+ 'title' => 'Random post',
102
+ 'text' => 'WordPress random post plugin',
103
+ 'content' => 'Spider Random Post is a small but very smart solution for your WordPress web site.',
104
+ 'href' => 'https://web-dorado.com/products/wordpress-random-post.html'
105
+ ),
106
+ "faq_wd" => array(
107
+ 'title' => 'FAQ WD',
108
+ 'text' => 'WordPress FAQ plugin',
109
+ 'content' => 'Organize and publish your FAQs in an easy and elegant way using FAQ WD.',
110
+ 'href' => 'https://web-dorado.com/products/wordpress-faq-wd.html'
111
+ ),
112
+ "instagram_feed" => array(
113
+ 'title' => 'Instagram Feed WD',
114
+ 'text' => 'WordPress Instagram Feed plugin',
115
+ 'content' => 'WD Instagram Feed is a user-friendly tool for displaying user or hashtag-based feeds on your website.',
116
+ 'href' => 'https://web-dorado.com/products/wordpress-instagram-feed-wd.html'
117
+ ),
118
+ "post-slider" => array(
119
+ 'title' => 'Post Slider',
120
+ 'text' => 'WordPress Post Slider plugin',
121
+ 'content' => 'Post Slider WD is designed to show off the selected posts of your website in a slider.',
122
+ 'href' => 'https://web-dorado.com/products/wordpress-post-slider-plugin.html'
123
+ ),
124
+ "google-maps" => array(
125
+ 'title' => 'Google Map',
126
+ 'text' => 'WordPress Google Maps Plugin',
127
+ 'content' => 'Google Maps WD is an intuitive tool for creating Google maps with advanced markers, custom layers and overlays for your website.',
128
+ 'href' => 'https://web-dorado.com/products/wordpress-google-maps-plugin.html'
129
+ ),
130
+ "wd-google-analytics" => array(
131
+ 'title' => 'Wd Google Analytics',
132
+ 'text' => 'WordPress Google Analytics Plugin',
133
+ 'content' => 'WD Google Analytics is a user-friendly all in one plugin, which allows to manage and monitor your website analytics from WordPress dashboard.',
134
+ 'href' => 'https://web-dorado.com/products/wordpress-google-analytics-plugin.html'
135
+ )
136
+ );
137
+ ?>
138
+ <div id="main_featured_plugins_page">
139
+ <h3>Featured Plugins</h3>
140
+ <div class="featured_header">
141
+ <a target="_blank" href="https://web-dorado.com/wordpress-plugins.html?source=<?php echo $current_plugin; ?>">
142
+ <h1>GET <?php echo $plugins[$current_plugin]["title"]; ?> +23 PLUGINS</h1>
143
+ <h1 class="get_plugins">FOR $100 ONLY <span>- SAVE 70%</span></h1>
144
+ <div class="try-now">
145
+ <span>TRY NOW</span>
146
+ </div>
147
+ </a>
148
+ </div>
149
+ <ul id="featured-plugins-list">
150
+ <?php
151
+ foreach ($plugins as $key => $plugins) {
152
+ if ($current_plugin != $key) {
153
+ ?>
154
+ <li class="<?php echo $key; ?>">
155
+ <div class="product"></div>
156
+ <div class="title">
157
+ <strong class="heading"><?php echo $plugins['title']; ?></strong>
158
+ </div>
159
+ <div class="description">
160
+ <p><?php echo $plugins['content']; ?></p>
161
+ </div>
162
+ <a target="_blank" href="<?php echo $plugins['href']; ?>?source=<?php echo $current_plugin; ?>" class="download">Download Plugin &#9658;</a>
163
+ </li>
164
+ <?php
165
+ }
166
+ }
167
+ ?>
168
+ </ul>
169
+ </div>
170
+ <?php
171
  }
featured/featured_themes.php CHANGED
@@ -1,302 +1,302 @@
1
- <?php
2
-
3
- class gawd_featured_themes {
4
-
5
-
6
- private $slug = 'wd-google-analytics';
7
- private $lang_slug = 'gawd';
8
-
9
- private $image_url = '';
10
- private $demo_url = 'http://themedemo.web-dorado.com/';
11
- private $site_url = 'https://web-dorado.com/wordpress-themes/';
12
-
13
- public function __construct() {
14
- $this->image_url = GAWD_URL . "/featured/images/";
15
-
16
- }
17
-
18
- ////////////////////////////////////////////////////////////////////////////////////////
19
- // Public Methods //
20
- ////////////////////////////////////////////////////////////////////////////////////////
21
-
22
- public function display() {
23
- ?>
24
-
25
- <style>
26
- @import url(https://fonts.googleapis.com/css?family=Oswald);
27
-
28
- #main_featured_themes_page #featured-themes-list {
29
- position:relative;
30
- margin:0px auto;
31
- height:auto;
32
- display:table;
33
- list-style:none;
34
- text-align: center;
35
- width: 100%;
36
- }
37
- #main_featured_themes_page #featured-themes-list li {
38
- display: inline-table;
39
- width: 300px;
40
- margin: 20px 10px 0px 10px;
41
- background: #FFFFFF;
42
- border-right: 3px solid #E5E5E5;
43
- border-bottom: 3px solid #E5E5E5;
44
- position: relative;
45
- }
46
- @media screen and (min-width: 1600px) {
47
- #main_featured_themes_page #featured-themes-list li {
48
- width:400px;
49
- }
50
-
51
- }
52
- #main_featured_themes_page .theme_img img {
53
- max-width: 100%;
54
- }
55
- #main_featured_themes_page .theme_img {
56
- display: inline-block;
57
- overflow: hidden;
58
- outline: 1px solid #D6D1D1;
59
- position:relative;
60
- /*height: 168px; */
61
- }
62
- #main_featured_themes_page #featured-themes-list li .title {
63
- width: 91%;
64
- text-align: center;
65
- margin: 0 auto;
66
- }
67
- #main_featured_themes_page {
68
- font-family: Oswald;
69
- }
70
- #main_featured_themes_page #featured-themes-list li .title .heading {
71
- display: block;
72
- position: relative;
73
- font-size: 17px;
74
- color: #666666;
75
- margin: 13px 0px 13px 0px;
76
- text-transform: uppercase;
77
- }
78
- #main_featured_themes_page #featured-themes-list li .title p {
79
- font-size:14px;
80
- color:#444;
81
- margin-left:20px;
82
- }
83
- #main_featured_themes_page #featured-themes-list li .description {
84
- height:130px;
85
- width: 90%;
86
- margin: 0 auto;
87
- }
88
- #main_featured_themes_page #featured-themes-list li .description p {
89
- text-align: center;
90
- width: 100%;
91
- color: #666666;
92
- font-family: "Open Sans",sans-serif;
93
- font-size: 14px;
94
- }
95
- #main_featured_themes_page #featured-themes-list li .links {
96
- border-top: 1px solid #d8d8d8;
97
- width: 90%;
98
- margin: 0 auto;
99
- font-size: 14px;
100
- line-height: 40px;
101
- font-weight: bolder;
102
- text-align: center;
103
- padding-top: 9px;
104
- padding-bottom: 12px;
105
- }
106
- #main_featured_themes_page .page_header h1 {
107
- margin: 0px;
108
- font-family: Segoe UI;
109
- padding-bottom: 15px;
110
- color: rgb(111, 111, 111);
111
- font-size: 24px;
112
- text-align:center;
113
- }
114
- #main_featured_themes_page .page_header {
115
- height: 40px;
116
- padding: 22px 0px 0px 0px;
117
- margin-bottom: 15px;
118
- /*border-bottom: rgb(111, 111, 111) solid 1px;*/
119
- }
120
- #main_featured_themes_page #featured-themes-list li a {
121
- outline: none;
122
- line-height: 29px;
123
- text-decoration: none;
124
- color: #134d68;
125
- font-family: "Open Sans",sans-serif;
126
- text-shadow: 1px 0;
127
- display: inline-block;
128
- font-size: 15px;
129
- }
130
- #main_featured_themes_page #featured-themes-list li a.demo {
131
- color: #ffffff;
132
- background: #F47629;
133
- border-radius: 3px;
134
- width: 76px;
135
- text-align:center;
136
- margin-right: 12px;
137
- }
138
- #main_featured_themes_page #featured-themes-list li a.download {
139
- padding-right: 30px;
140
- background:url(<?php echo $this->image_url; ?>down.png) no-repeat right;
141
- }
142
- #main_featured_themes_page .featured_header{
143
- background: #11465F;
144
- border-right: 3px solid #E5E5E5;
145
- border-bottom: 3px solid #E5E5E5;
146
- position: relative;
147
- padding: 20px 0;
148
- }
149
- #main_featured_themes_page .featured_header .try-now {
150
- text-align: center;
151
- }
152
- #main_featured_themes_page .featured_header .try-now span {
153
- display: inline-block;
154
- padding: 7px 16px;
155
- background: #F47629;
156
- border-radius: 10px;
157
- color: #ffffff;
158
- font-size: 23px;
159
- }
160
- #main_featured_themes_page .featured_container {
161
- position: relative;
162
- width: 90%;
163
- margin: 15px auto 0px auto;
164
- }
165
- #main_featured_themes_page .featured_container .old_price{
166
- color: rgba(180, 180, 180, 0.3);
167
- text-decoration: line-through;
168
- font-family: Oswald;
169
- }
170
- #main_featured_themes_page .featured_container .get_themes{
171
- color: #FFFFFF;
172
- height: 85px;
173
- margin: 0;
174
- background-size: 95% 100%;
175
- background-position: center;
176
- line-height: 60px;
177
- font-size: 45px;
178
- text-align: center;
179
- letter-spacing: 3px;
180
- }
181
- #main_featured_themes_page .featured_header h1{
182
- font-size: 45px;
183
- text-align: center;
184
- color: #ffffff;
185
- letter-spacing: 3px;
186
- line-height: 10px;
187
- }
188
- #main_featured_themes_page .featured_header a{
189
- text-decoration: none;
190
- }
191
- @media screen and (max-width: 1035px) {
192
- #main_featured_themes_page .featured_header h1{
193
- font-size: 37px;
194
- line-height: 0;
195
- }
196
- }
197
- @media screen and (max-width: 835px) {
198
- #main_featured_themes_page .get_themes span{
199
- display: none;
200
- }
201
- }
202
- @media screen and (max-width: 435px) {
203
- #main_featured_themes_page .featured_header h1 {
204
- font-size: 20px;
205
- line-height: 17px;
206
- }
207
- }
208
- </style>
209
-
210
- <?php
211
- $WDWThemes = array(
212
- "business_elite" => array(
213
- "title" => "Business Elite",
214
- "description" => __("Business Elite is a robust parallax theme for business websites. The theme uses smooth transitions and many functional sections.",$this->lang_slug),
215
- "link" => "business-elite.html",
216
- "demo" => "theme-businesselite",
217
- "image" => "business_elite.jpg"
218
- ),
219
- "portfolio" => array(
220
- "title" => "Portfolio Gallery",
221
- "description" => __("Portfolio Gallery helps to display images using various color schemes and layouts combined with elegant fonts and content parts.",$this->lang_slug),
222
- "link" => "portfolio-gallery.html",
223
- "demo" => "theme-portfoliogallery",
224
- "image" => "portfolio_gallery.jpg"
225
- ),
226
- "sauron" => array(
227
- "title" => "Sauron",
228
- "description" => __("Sauron is a multipurpose parallax theme, which uses multiple interactive sections designed for the client-engagement.",$this->lang_slug),
229
- "link" => "sauron.html",
230
- "demo" => "theme-sauron",
231
- "image" => "sauron.jpg"
232
- ),
233
- "business_world" => array(
234
- "title" => "Business World",
235
- "description" => __("Business World is an innovative WordPress theme great for Business websites.",$this->lang_slug),
236
- "link" => "business-world.html",
237
- "demo" => "theme-businessworld",
238
- "image" => "business_world.jpg"
239
- ),
240
- "best_magazine" => array(
241
- "title" => "Best Magazine",
242
- "description" => __("Best Magazine is an ultimate selection when you are dealing with multi-category news websites.",$this->lang_slug),
243
- "link" => "best-magazine.html",
244
- "demo" => "theme-bestmagazine",
245
- "image" => "best_magazine.jpg"
246
- ),
247
- "magazine" => array(
248
- "title" => "News Magazine",
249
- "description" => __("Magazine theme is a perfect solution when creating news and informational websites. It comes with a wide range of layout options.",$this->lang_slug),
250
- "link" => "news-magazine.html",
251
- "demo" => "theme-newsmagazine",
252
- "image" => "news_magazine.jpg"
253
- )
254
- );
255
- ?>
256
- <div id="main_featured_themes_page">
257
- <div class="featured_container">
258
- <div class="page_header">
259
- <h1><?php echo __("Featured Themes",$this->lang_slug); ?></h1>
260
- </div>
261
- <div class="featured_header">
262
- <a target="_blank" href="https://web-dorado.com/wordpress-themes.html?source=<?php echo $this->slug; ?>">
263
- <h1><?php echo __("WORDPRESS THEMES",$this->lang_slug); ?></h1>
264
- <h2 class="get_themes"><?php echo __("ALL FOR $40 ONLY ",$this->lang_slug); ?><span>- <?php echo __("SAVE 80%",$this->lang_slug); ?></span></h2>
265
- <div class="try-now">
266
- <span><?php echo __("TRY NOW",$this->lang_slug); ?></span>
267
- </div>
268
- </a>
269
- </div>
270
- <ul id="featured-themes-list">
271
- <?php foreach($WDWThemes as $key=>$WDWTheme) : ?>
272
- <li class="<?php echo $key; ?>">
273
- <div class="theme_img">
274
- <img src="<?php echo $this->image_url . $WDWTheme["image"]; ?>">
275
- </div>
276
- <div class="title">
277
- <h3 class="heading"><?php echo $WDWTheme["title"]; ?></h3>
278
- </div>
279
- <div class="description">
280
- <p><?php echo $WDWTheme["description"]; ?></p>
281
- </div>
282
- <div class="links">
283
- <a target="_blank" href="<?php echo $this->demo_url . $WDWTheme["demo"]."?source=".$this->slug; ?>" class="demo"><?php echo __("Demo",$this->lang_slug); ?></a>
284
- <a target="_blank" href="<?php echo $this->site_url . $WDWTheme["link"]."?source=".$this->slug; ?>" class="download"><?php echo __("Free Download",$this->lang_slug); ?></a>
285
- </div>
286
- </li>
287
- <?php endforeach; ?>
288
- </ul>
289
- </div>
290
- </div>
291
- <?php }
292
-
293
- ////////////////////////////////////////////////////////////////////////////////////////
294
- // Getters & Setters //
295
- ////////////////////////////////////////////////////////////////////////////////////////
296
- ////////////////////////////////////////////////////////////////////////////////////////
297
- // Private Methods //
298
- ////////////////////////////////////////////////////////////////////////////////////////
299
- ////////////////////////////////////////////////////////////////////////////////////////
300
- // Listeners //
301
- ////////////////////////////////////////////////////////////////////////////////////////
302
  }
1
+ <?php
2
+
3
+ class gawd_featured_themes {
4
+
5
+
6
+ private $slug = 'wd-google-analytics';
7
+ private $lang_slug = 'gawd';
8
+
9
+ private $image_url = '';
10
+ private $demo_url = 'http://themedemo.web-dorado.com/';
11
+ private $site_url = 'https://web-dorado.com/wordpress-themes/';
12
+
13
+ public function __construct() {
14
+ $this->image_url = GAWD_URL . "/featured/images/";
15
+
16
+ }
17
+
18
+ ////////////////////////////////////////////////////////////////////////////////////////
19
+ // Public Methods //
20
+ ////////////////////////////////////////////////////////////////////////////////////////
21
+
22
+ public function display() {
23
+ ?>
24
+
25
+ <style>
26
+ @import url(https://fonts.googleapis.com/css?family=Oswald);
27
+
28
+ #main_featured_themes_page #featured-themes-list {
29
+ position:relative;
30
+ margin:0px auto;
31
+ height:auto;
32
+ display:table;
33
+ list-style:none;
34
+ text-align: center;
35
+ width: 100%;
36
+ }
37
+ #main_featured_themes_page #featured-themes-list li {
38
+ display: inline-table;
39
+ width: 300px;
40
+ margin: 20px 10px 0px 10px;
41
+ background: #FFFFFF;
42
+ border-right: 3px solid #E5E5E5;
43
+ border-bottom: 3px solid #E5E5E5;
44
+ position: relative;
45
+ }
46
+ @media screen and (min-width: 1600px) {
47
+ #main_featured_themes_page #featured-themes-list li {
48
+ width:400px;
49
+ }
50
+
51
+ }
52
+ #main_featured_themes_page .theme_img img {
53
+ max-width: 100%;
54
+ }
55
+ #main_featured_themes_page .theme_img {
56
+ display: inline-block;
57
+ overflow: hidden;
58
+ outline: 1px solid #D6D1D1;
59
+ position:relative;
60
+ /*height: 168px; */
61
+ }
62
+ #main_featured_themes_page #featured-themes-list li .title {
63
+ width: 91%;
64
+ text-align: center;
65
+ margin: 0 auto;
66
+ }
67
+ #main_featured_themes_page {
68
+ font-family: Oswald;
69
+ }
70
+ #main_featured_themes_page #featured-themes-list li .title .heading {
71
+ display: block;
72
+ position: relative;
73
+ font-size: 17px;
74
+ color: #666666;
75
+ margin: 13px 0px 13px 0px;
76
+ text-transform: uppercase;
77
+ }
78
+ #main_featured_themes_page #featured-themes-list li .title p {
79
+ font-size:14px;
80
+ color:#444;
81
+ margin-left:20px;
82
+ }
83
+ #main_featured_themes_page #featured-themes-list li .description {
84
+ height:130px;
85
+ width: 90%;
86
+ margin: 0 auto;
87
+ }
88
+ #main_featured_themes_page #featured-themes-list li .description p {
89
+ text-align: center;
90
+ width: 100%;
91
+ color: #666666;
92
+ font-family: "Open Sans",sans-serif;
93
+ font-size: 14px;
94
+ }
95
+ #main_featured_themes_page #featured-themes-list li .links {
96
+ border-top: 1px solid #d8d8d8;
97
+ width: 90%;
98
+ margin: 0 auto;
99
+ font-size: 14px;
100
+ line-height: 40px;
101
+ font-weight: bolder;
102
+ text-align: center;
103
+ padding-top: 9px;
104
+ padding-bottom: 12px;
105
+ }
106
+ #main_featured_themes_page .page_header h1 {
107
+ margin: 0px;
108
+ font-family: Segoe UI;
109
+ padding-bottom: 15px;
110
+ color: rgb(111, 111, 111);
111
+ font-size: 24px;
112
+ text-align:center;
113
+ }
114
+ #main_featured_themes_page .page_header {
115
+ height: 40px;
116
+ padding: 22px 0px 0px 0px;
117
+ margin-bottom: 15px;
118
+ /*border-bottom: rgb(111, 111, 111) solid 1px;*/
119
+ }
120
+ #main_featured_themes_page #featured-themes-list li a {
121
+ outline: none;
122
+ line-height: 29px;
123
+ text-decoration: none;
124
+ color: #134d68;
125
+ font-family: "Open Sans",sans-serif;
126
+ text-shadow: 1px 0;
127
+ display: inline-block;
128
+ font-size: 15px;
129
+ }
130
+ #main_featured_themes_page #featured-themes-list li a.demo {
131
+ color: #ffffff;
132
+ background: #F47629;
133
+ border-radius: 3px;
134
+ width: 76px;
135
+ text-align:center;
136
+ margin-right: 12px;
137
+ }
138
+ #main_featured_themes_page #featured-themes-list li a.download {
139
+ padding-right: 30px;
140
+ background:url(<?php echo $this->image_url; ?>down.png) no-repeat right;
141
+ }
142
+ #main_featured_themes_page .featured_header{
143
+ background: #11465F;
144
+ border-right: 3px solid #E5E5E5;
145
+ border-bottom: 3px solid #E5E5E5;
146
+ position: relative;
147
+ padding: 20px 0;
148
+ }
149
+ #main_featured_themes_page .featured_header .try-now {
150
+ text-align: center;
151
+ }
152
+ #main_featured_themes_page .featured_header .try-now span {
153
+ display: inline-block;
154
+ padding: 7px 16px;
155
+ background: #F47629;
156
+ border-radius: 10px;
157
+ color: #ffffff;
158
+ font-size: 23px;
159
+ }
160
+ #main_featured_themes_page .featured_container {
161
+ position: relative;
162
+ width: 90%;
163
+ margin: 15px auto 0px auto;
164
+ }
165
+ #main_featured_themes_page .featured_container .old_price{
166
+ color: rgba(180, 180, 180, 0.3);
167
+ text-decoration: line-through;
168
+ font-family: Oswald;
169
+ }
170
+ #main_featured_themes_page .featured_container .get_themes{
171
+ color: #FFFFFF;
172
+ height: 85px;
173
+ margin: 0;
174
+ background-size: 95% 100%;
175
+ background-position: center;
176
+ line-height: 60px;
177
+ font-size: 45px;
178
+ text-align: center;
179
+ letter-spacing: 3px;
180
+ }
181
+ #main_featured_themes_page .featured_header h1{
182
+ font-size: 45px;
183
+ text-align: center;
184
+ color: #ffffff;
185
+ letter-spacing: 3px;
186
+ line-height: 10px;
187
+ }
188
+ #main_featured_themes_page .featured_header a{
189
+ text-decoration: none;
190
+ }
191
+ @media screen and (max-width: 1035px) {
192
+ #main_featured_themes_page .featured_header h1{
193
+ font-size: 37px;
194
+ line-height: 0;
195
+ }
196
+ }
197
+ @media screen and (max-width: 835px) {
198
+ #main_featured_themes_page .get_themes span{
199
+ display: none;
200
+ }
201
+ }
202
+ @media screen and (max-width: 435px) {
203
+ #main_featured_themes_page .featured_header h1 {
204
+ font-size: 20px;
205
+ line-height: 17px;
206
+ }
207
+ }
208
+ </style>
209
+
210
+ <?php
211
+ $WDWThemes = array(
212
+ "business_elite" => array(
213
+ "title" => "Business Elite",
214
+ "description" => __("Business Elite is a robust parallax theme for business websites. The theme uses smooth transitions and many functional sections.",$this->lang_slug),
215
+ "link" => "business-elite.html",
216
+ "demo" => "theme-businesselite",
217
+ "image" => "business_elite.jpg"
218
+ ),
219
+ "portfolio" => array(
220
+ "title" => "Portfolio Gallery",
221
+ "description" => __("Portfolio Gallery helps to display images using various color schemes and layouts combined with elegant fonts and content parts.",$this->lang_slug),
222
+ "link" => "portfolio-gallery.html",
223
+ "demo" => "theme-portfoliogallery",
224
+ "image" => "portfolio_gallery.jpg"
225
+ ),
226
+ "sauron" => array(
227
+ "title" => "Sauron",
228
+ "description" => __("Sauron is a multipurpose parallax theme, which uses multiple interactive sections designed for the client-engagement.",$this->lang_slug),
229
+ "link" => "sauron.html",
230
+ "demo" => "theme-sauron",
231
+ "image" => "sauron.jpg"
232
+ ),
233
+ "business_world" => array(
234
+ "title" => "Business World",
235
+ "description" => __("Business World is an innovative WordPress theme great for Business websites.",$this->lang_slug),
236
+ "link" => "business-world.html",
237
+ "demo" => "theme-businessworld",
238
+ "image" => "business_world.jpg"
239
+ ),
240
+ "best_magazine" => array(
241
+ "title" => "Best Magazine",
242
+ "description" => __("Best Magazine is an ultimate selection when you are dealing with multi-category news websites.",$this->lang_slug),
243
+ "link" => "best-magazine.html",
244
+ "demo" => "theme-bestmagazine",
245
+ "image" => "best_magazine.jpg"
246
+ ),
247
+ "magazine" => array(
248
+ "title" => "News Magazine",
249
+ "description" => __("Magazine theme is a perfect solution when creating news and informational websites. It comes with a wide range of layout options.",$this->lang_slug),
250
+ "link" => "news-magazine.html",
251
+ "demo" => "theme-newsmagazine",
252
+ "image" => "news_magazine.jpg"
253
+ )
254
+ );
255
+ ?>
256
+ <div id="main_featured_themes_page">
257
+ <div class="featured_container">
258
+ <div class="page_header">
259
+ <h1><?php echo __("Featured Themes",$this->lang_slug); ?></h1>
260
+ </div>
261
+ <div class="featured_header">
262
+ <a target="_blank" href="https://web-dorado.com/wordpress-themes.html?source=<?php echo $this->slug; ?>">
263
+ <h1><?php echo __("WORDPRESS THEMES",$this->lang_slug); ?></h1>
264
+ <h2 class="get_themes"><?php echo __("ALL FOR $40 ONLY ",$this->lang_slug); ?><span>- <?php echo __("SAVE 80%",$this->lang_slug); ?></span></h2>
265
+ <div class="try-now">
266
+ <span><?php echo __("TRY NOW",$this->lang_slug); ?></span>
267
+ </div>
268
+ </a>
269
+ </div>
270
+ <ul id="featured-themes-list">
271
+ <?php foreach($WDWThemes as $key=>$WDWTheme) : ?>
272
+ <li class="<?php echo $key; ?>">
273
+ <div class="theme_img">
274
+ <img src="<?php echo $this->image_url . $WDWTheme["image"]; ?>">
275
+ </div>
276
+ <div class="title">
277
+ <h3 class="heading"><?php echo $WDWTheme["title"]; ?></h3>
278
+ </div>
279
+ <div class="description">
280
+ <p><?php echo $WDWTheme["description"]; ?></p>
281
+ </div>
282
+ <div class="links">
283
+ <a target="_blank" href="<?php echo $this->demo_url . $WDWTheme["demo"]."?source=".$this->slug; ?>" class="demo"><?php echo __("Demo",$this->lang_slug); ?></a>
284
+ <a target="_blank" href="<?php echo $this->site_url . $WDWTheme["link"]."?source=".$this->slug; ?>" class="download"><?php echo __("Free Download",$this->lang_slug); ?></a>
285
+ </div>
286
+ </li>
287
+ <?php endforeach; ?>
288
+ </ul>
289
+ </div>
290
+ </div>
291
+ <?php }
292
+
293
+ ////////////////////////////////////////////////////////////////////////////////////////
294
+ // Getters & Setters //
295
+ ////////////////////////////////////////////////////////////////////////////////////////
296
+ ////////////////////////////////////////////////////////////////////////////////////////
297
+ // Private Methods //
298
+ ////////////////////////////////////////////////////////////////////////////////////////
299
+ ////////////////////////////////////////////////////////////////////////////////////////
300
+ // Listeners //
301
+ ////////////////////////////////////////////////////////////////////////////////////////
302
  }
featured/style.css CHANGED
@@ -1,205 +1,205 @@
1
- @import url(http://fonts.googleapis.com/css?family=Oswald);
2
- #main_featured_plugins_page {
3
- font-family: Oswald;
4
- width: 90%;
5
- margin: 15px auto 0px auto;
6
- }
7
-
8
- #main_featured_plugins_page h3 {
9
- border-bottom: 2px solid #CECECE;
10
- color: rgb(111, 111, 111);
11
- font-family: Segoe UI;
12
- font-size: 18px;
13
- margin: 0px auto 15px auto;
14
- padding: 20px 0;
15
- }
16
-
17
- #main_featured_plugins_page #featured-plugins-list {
18
- position:relative;
19
- margin:0px auto;
20
- height:auto;
21
- display:table;
22
- list-style:none;
23
- text-align: center;
24
- width: 100%;
25
- }
26
-
27
- #main_featured_plugins_page #featured-plugins-list li {
28
- display: inline-table;
29
- width: 200px;
30
- margin: 20px 10px 0px 10px;
31
- background: #FFFFFF;
32
- border-right: 3px solid #E5E5E5;
33
- height: 335px;
34
- border-bottom: 3px solid #E5E5E5;
35
- position: relative;
36
- }
37
-
38
- #main_featured_plugins_page #featured-plugins-list li .product {
39
- position:relative;
40
- height:113px;
41
- background-color: transparent !important;
42
- background-position-x: 50% !important;
43
- margin: 7px;
44
- border-radius: 3px;
45
- background-size: 115px !important;
46
- }
47
-
48
- #main_featured_plugins_page #featured-plugins-list li .title {
49
- width: 90%;
50
- text-align: center;
51
- margin: 0 auto;
52
- }
53
-
54
- #main_featured_plugins_page #featured-plugins-list li.form-maker .product {background:url("images/form.png") center center no-repeat;}
55
- #main_featured_plugins_page #featured-plugins-list li.catalog .product {background:url("images/catalog.png") center center no-repeat;}
56
- #main_featured_plugins_page #featured-plugins-list li.contact-maker .product {background:url("images/contact.maker.png") center center no-repeat;}
57
- #main_featured_plugins_page #featured-plugins-list li.contacts .product {background:url("images/contacts.png") center center no-repeat;}
58
- #main_featured_plugins_page #featured-plugins-list li.facebook .product {background:url("images/facebook.png") center center no-repeat;}
59
- #main_featured_plugins_page #featured-plugins-list li.faq .product {background:url("images/faq.png") center center no-repeat;}
60
- #main_featured_plugins_page #featured-plugins-list li.flash-calendar .product {background:url("images/flash.calendar.png") center center no-repeat;}
61
- #main_featured_plugins_page #featured-plugins-list li.player .product {background:url("images/player.png") center center no-repeat; }
62
- #main_featured_plugins_page #featured-plugins-list li.spider-calendar .product {background:url("images/spider.calendar.png") center center no-repeat;}
63
- #main_featured_plugins_page #featured-plugins-list li.contact_form_bulder .product {background:url("images/contact.builder.png") center center no-repeat;}
64
- #main_featured_plugins_page #featured-plugins-list li.random_post .product {background:url("images/random.post.png") center center no-repeat;}
65
- #main_featured_plugins_page #featured-plugins-list li.slider_wd .product {background:url("images/slider.png") center center no-repeat;}
66
- #main_featured_plugins_page #featured-plugins-list li.folder_menu .product {background:url("images/folder.menu.png") center center no-repeat;}
67
- #main_featured_plugins_page #featured-plugins-list li.zoom .product {background:url("images/zoom.png") center center no-repeat;}
68
- #main_featured_plugins_page #featured-plugins-list li.fm-import .product {background:url("images/fm-import.png") center center no-repeat;}
69
- #main_featured_plugins_page #featured-plugins-list li.photo-gallery .product {background:url("images/photo-gallery.png") center center no-repeat;}
70
- #main_featured_plugins_page #featured-plugins-list li.twitter-widget .product {background:url("images/twittertools.png") center center no-repeat;}
71
- #main_featured_plugins_page #featured-plugins-list li.events-wd .product {background:url("images/events-wd.png") center center no-repeat;}
72
- #main_featured_plugins_page #featured-plugins-list li.faq_wd .product {background:url("images/faq_wd.png") center center no-repeat;}
73
- #main_featured_plugins_page #featured-plugins-list li.instagram_feed .product {background:url("images/instagram_feed.png") center center no-repeat;}
74
- #main_featured_plugins_page #featured-plugins-list li.post-slider .product {background:url("images/post-slider.png") center center no-repeat;}
75
- #main_featured_plugins_page #featured-plugins-list li.google-maps .product {background:url("images/google-maps.png") center center no-repeat;}
76
-
77
- #main_featured_plugins_page #featured-plugins-list li .title .heading {
78
- display: block;
79
- position: relative;
80
- font-size: 17px;
81
- color: #767676;
82
- margin: 13px 0px 13px 0px;
83
- text-transform: uppercase;
84
- }
85
-
86
- #main_featured_plugins_page #featured-plugins-list li .title p {
87
- font-size:14px;
88
- color:#444;
89
- margin-left:20px;
90
- }
91
-
92
- #main_featured_plugins_page #featured-plugins-list li .description {
93
- height: 127px;
94
- width: 90%;
95
- margin: 0 auto;
96
- }
97
-
98
- #main_featured_plugins_page #featured-plugins-list li .description p {
99
- text-align: center;
100
- width: 100%;
101
- color: #9A9A9A;
102
- font-family: Segoe UI Light;
103
- }
104
-
105
- #featured-plugins-list li a.download {
106
- display: block;
107
- border-top: 1px solid #CACACA;
108
- outline: none;
109
- width: 90%;
110
- margin: 0 auto;
111
- font-size: 14px;
112
- line-height: 40px;
113
- text-decoration: none;
114
- font-weight: bolder;
115
- text-align: center;
116
- color: #134D68;
117
- position: absolute;
118
- text-transform: uppercase;
119
- bottom: 0;
120
- left: 10px;
121
- font-family: Segoe UI Black;
122
- text-shadow: 1px 0;
123
- }
124
-
125
- #featured-plugins-list li a.download:hover {
126
- color: #F47629;
127
- }
128
-
129
- .featured_header {
130
- background: #11465F;
131
- border-right: 3px solid #E5E5E5;
132
- border-bottom: 3px solid #E5E5E5;
133
- position: relative;
134
- padding: 20px 0;
135
- }
136
-
137
- .featured_header .old_price {
138
- color: rgba(180, 180, 180, 0.3);
139
- text-decoration: line-through;
140
- font-family: Oswald;
141
- }
142
-
143
- .featured_header h1.get_plugins {
144
- color: #FFFFFF;
145
- height: 85px;
146
- margin: 0;
147
- background-size: 85% 100%;
148
- background-position: center;
149
- line-height: 60px;
150
- }
151
-
152
- .featured_header .try-now {
153
- text-align: center;
154
- }
155
-
156
- .featured_header .try-now span {
157
- display: inline-block;
158
- padding: 7px 16px;
159
- background: #F47629;
160
- border-radius: 10px;
161
- color: #ffffff;
162
- font-size: 23px;
163
- }
164
-
165
- .featured_header h1 {
166
- font-size: 50px;
167
- text-align: center;
168
- color: #FFFFFF;
169
- letter-spacing: 3px;
170
- text-transform: uppercase;
171
- }
172
-
173
- .featured_header a {
174
- text-decoration: none;
175
- }
176
-
177
- .featured_header a:hover {
178
- text-decoration: none;
179
- }
180
-
181
- @media screen and (max-width: 1105px) {
182
- .featured_header h1 {
183
- font-size: 37px;
184
- line-height: 0;
185
- }
186
- }
187
-
188
- @media screen and (max-width: 835px) {
189
- .get_plugins span {
190
- display: none;
191
- }
192
- }
193
-
194
- @media screen and (max-width: 700px) {
195
- .featured_header h1 {
196
- line-height: 40px;
197
- }
198
- }
199
-
200
- @media screen and (max-width: 435px) {
201
- .featured_header h1 {
202
- font-size: 20px;
203
- line-height: 25px;
204
- }
205
  }
1
+ @import url(http://fonts.googleapis.com/css?family=Oswald);
2
+ #main_featured_plugins_page {
3
+ font-family: Oswald;
4
+ width: 90%;
5
+ margin: 15px auto 0px auto;
6
+ }
7
+
8
+ #main_featured_plugins_page h3 {
9
+ border-bottom: 2px solid #CECECE;
10
+ color: rgb(111, 111, 111);
11
+ font-family: Segoe UI;
12
+ font-size: 18px;
13
+ margin: 0px auto 15px auto;
14
+ padding: 20px 0;
15
+ }
16
+
17
+ #main_featured_plugins_page #featured-plugins-list {
18
+ position:relative;
19
+ margin:0px auto;
20
+ height:auto;
21
+ display:table;
22
+ list-style:none;
23
+ text-align: center;
24
+ width: 100%;
25
+ }
26
+
27
+ #main_featured_plugins_page #featured-plugins-list li {
28
+ display: inline-table;
29
+ width: 200px;
30
+ margin: 20px 10px 0px 10px;
31
+ background: #FFFFFF;
32
+ border-right: 3px solid #E5E5E5;
33
+ height: 335px;
34
+ border-bottom: 3px solid #E5E5E5;
35
+ position: relative;
36
+ }
37
+
38
+ #main_featured_plugins_page #featured-plugins-list li .product {
39
+ position:relative;
40
+ height:113px;
41
+ background-color: transparent !important;
42
+ background-position-x: 50% !important;
43
+ margin: 7px;
44
+ border-radius: 3px;
45
+ background-size: 115px !important;
46
+ }
47
+
48
+ #main_featured_plugins_page #featured-plugins-list li .title {
49
+ width: 90%;
50
+ text-align: center;
51
+ margin: 0 auto;
52
+ }
53
+
54
+ #main_featured_plugins_page #featured-plugins-list li.form-maker .product {background:url("images/form.png") center center no-repeat;}
55
+ #main_featured_plugins_page #featured-plugins-list li.catalog .product {background:url("images/catalog.png") center center no-repeat;}
56
+ #main_featured_plugins_page #featured-plugins-list li.contact-maker .product {background:url("images/contact.maker.png") center center no-repeat;}
57
+ #main_featured_plugins_page #featured-plugins-list li.contacts .product {background:url("images/contacts.png") center center no-repeat;}
58
+ #main_featured_plugins_page #featured-plugins-list li.facebook .product {background:url("images/facebook.png") center center no-repeat;}
59
+ #main_featured_plugins_page #featured-plugins-list li.faq .product {background:url("images/faq.png") center center no-repeat;}
60
+ #main_featured_plugins_page #featured-plugins-list li.flash-calendar .product {background:url("images/flash.calendar.png") center center no-repeat;}
61
+ #main_featured_plugins_page #featured-plugins-list li.player .product {background:url("images/player.png") center center no-repeat; }
62
+ #main_featured_plugins_page #featured-plugins-list li.spider-calendar .product {background:url("images/spider.calendar.png") center center no-repeat;}
63
+ #main_featured_plugins_page #featured-plugins-list li.contact_form_bulder .product {background:url("images/contact.builder.png") center center no-repeat;}
64
+ #main_featured_plugins_page #featured-plugins-list li.random_post .product {background:url("images/random.post.png") center center no-repeat;}
65
+ #main_featured_plugins_page #featured-plugins-list li.slider_wd .product {background:url("images/slider.png") center center no-repeat;}
66
+ #main_featured_plugins_page #featured-plugins-list li.folder_menu .product {background:url("images/folder.menu.png") center center no-repeat;}
67
+ #main_featured_plugins_page #featured-plugins-list li.zoom .product {background:url("images/zoom.png") center center no-repeat;}
68
+ #main_featured_plugins_page #featured-plugins-list li.fm-import .product {background:url("images/fm-import.png") center center no-repeat;}
69
+ #main_featured_plugins_page #featured-plugins-list li.photo-gallery .product {background:url("images/photo-gallery.png") center center no-repeat;}
70
+ #main_featured_plugins_page #featured-plugins-list li.twitter-widget .product {background:url("images/twittertools.png") center center no-repeat;}
71
+ #main_featured_plugins_page #featured-plugins-list li.events-wd .product {background:url("images/events-wd.png") center center no-repeat;}
72
+ #main_featured_plugins_page #featured-plugins-list li.faq_wd .product {background:url("images/faq_wd.png") center center no-repeat;}
73
+ #main_featured_plugins_page #featured-plugins-list li.instagram_feed .product {background:url("images/instagram_feed.png") center center no-repeat;}
74
+ #main_featured_plugins_page #featured-plugins-list li.post-slider .product {background:url("images/post-slider.png") center center no-repeat;}
75
+ #main_featured_plugins_page #featured-plugins-list li.google-maps .product {background:url("images/google-maps.png") center center no-repeat;}
76
+
77
+ #main_featured_plugins_page #featured-plugins-list li .title .heading {
78
+ display: block;
79
+ position: relative;
80
+ font-size: 17px;
81
+ color: #767676;
82
+ margin: 13px 0px 13px 0px;
83
+ text-transform: uppercase;
84
+ }
85
+
86
+ #main_featured_plugins_page #featured-plugins-list li .title p {
87
+ font-size:14px;
88
+ color:#444;
89
+ margin-left:20px;
90
+ }
91
+
92
+ #main_featured_plugins_page #featured-plugins-list li .description {
93
+ height: 127px;
94
+ width: 90%;
95
+ margin: 0 auto;
96
+ }
97
+
98
+ #main_featured_plugins_page #featured-plugins-list li .description p {
99
+ text-align: center;
100
+ width: 100%;
101
+ color: #9A9A9A;
102
+ font-family: Segoe UI Light;
103
+ }
104
+
105
+ #featured-plugins-list li a.download {
106
+ display: block;
107
+ border-top: 1px solid #CACACA;
108
+ outline: none;
109
+ width: 90%;
110
+ margin: 0 auto;
111
+ font-size: 14px;
112
+ line-height: 40px;
113
+ text-decoration: none;
114
+ font-weight: bolder;
115
+ text-align: center;
116
+ color: #134D68;
117
+ position: absolute;
118
+ text-transform: uppercase;
119
+ bottom: 0;
120
+ left: 10px;
121
+ font-family: Segoe UI Black;
122
+ text-shadow: 1px 0;
123
+ }
124
+
125
+ #featured-plugins-list li a.download:hover {
126
+ color: #F47629;
127
+ }
128
+
129
+ .featured_header {
130
+ background: #11465F;
131
+ border-right: 3px solid #E5E5E5;
132
+ border-bottom: 3px solid #E5E5E5;
133
+ position: relative;
134
+ padding: 20px 0;
135
+ }
136
+
137
+ .featured_header .old_price {
138
+ color: rgba(180, 180, 180, 0.3);
139
+ text-decoration: line-through;
140
+ font-family: Oswald;
141
+ }
142
+
143
+ .featured_header h1.get_plugins {
144
+ color: #FFFFFF;
145
+ height: 85px;
146
+ margin: 0;
147
+ background-size: 85% 100%;
148
+ background-position: center;
149
+ line-height: 60px;
150
+ }
151
+
152
+ .featured_header .try-now {
153
+ text-align: center;
154
+ }
155
+
156
+ .featured_header .try-now span {
157
+ display: inline-block;
158
+ padding: 7px 16px;
159
+ background: #F47629;
160
+ border-radius: 10px;
161
+ color: #ffffff;
162
+ font-size: 23px;
163
+ }
164
+
165
+ .featured_header h1 {
166
+ font-size: 50px;
167
+ text-align: center;
168
+ color: #FFFFFF;
169
+ letter-spacing: 3px;
170
+ text-transform: uppercase;
171
+ }
172
+
173
+ .featured_header a {
174
+ text-decoration: none;
175
+ }
176
+
177
+ .featured_header a:hover {
178
+ text-decoration: none;
179
+ }
180
+
181
+ @media screen and (max-width: 1105px) {
182
+ .featured_header h1 {
183
+ font-size: 37px;
184
+ line-height: 0;
185
+ }
186
+ }
187
+
188
+ @media screen and (max-width: 835px) {
189
+ .get_plugins span {
190
+ display: none;
191
+ }
192
+ }
193
+
194
+ @media screen and (max-width: 700px) {
195
+ .featured_header h1 {
196
+ line-height: 40px;
197
+ }
198
+ }
199
+
200
+ @media screen and (max-width: 435px) {
201
+ .featured_header h1 {
202
+ font-size: 20px;
203
+ line-height: 25px;
204
+ }
205
  }
gawd_class.php CHANGED
@@ -1,2133 +1,2133 @@
1
- <?php
2
-
3
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
4
-
5
- class GAWD {
6
-
7
- /**
8
- * @var GAWD The reference to Singleton instance of this class
9
- */
10
- private static $instance;
11
- private $project_client_id = null;
12
- private $project_client_secret = null;
13
- public $redirect_uri = "urn:ietf:wg:oauth:2.0:oob";
14
-
15
- /**
16
- * Protected constructor to prevent creating a new instance of the
17
- * Singleton via the `new` operator from outside of this class.
18
- */
19
- protected function __construct() {
20
-
21
- if(isset($_POST["reset_data"]) && $_POST["reset_data"] != ''){
22
- $this->reset_user_data();
23
- }
24
- add_action('admin_enqueue_scripts', array($this, 'gawd_check_id'));
25
- add_action('admin_notices', array($this, 'upgrade_pro'));
26
-
27
- add_action('admin_menu', array($this, 'gawd_add_menu'));
28
- add_action('admin_enqueue_scripts', array($this, 'gawd_enqueue_scripts'));
29
- add_action('wp_enqueue_scripts', array($this, 'gawd_front_scripts'));
30
- add_action('wp_ajax_gawd_auth', array($this, 'gawd_auth'));
31
- add_action('wp_ajax_create_pdf_file', array($this, 'create_pdf_file'));
32
- add_action('wp_ajax_create_csv_file', array($this, 'create_csv_file'));
33
- add_action('wp_ajax_show_data', array($this, 'show_data'));
34
- add_action('wp_ajax_remove_zoom_message', array($this, 'remove_zoom_message'));
35
- add_action('wp_ajax_show_page_post_data', array($this, 'show_page_post_data'));
36
- add_action('wp_ajax_show_data_compact', array($this, 'show_data_compact'));
37
- add_action('wp_ajax_get_realtime', array($this, 'get_realtime'));
38
- add_action('wp_dashboard_setup', array($this, 'google_analytics_wd_dashboard_widget'));
39
- add_action('admin_menu', array($this, 'overview_date_meta'));
40
- add_filter('cron_schedules', array($this, 'gawd_my_schedule'));
41
- add_action('admin_init', array($this, 'gawd_export'));
42
- add_action('gawd_pushover_daily', array($this, 'gawd_pushover_daily'));
43
- add_action('gawd_pushover_gawd_weekly', array($this, 'gawd_pushover_weekly'));
44
- add_action('gawd_pushover_gawd_monthly', array($this, 'gawd_pushover_monthly'));
45
- add_action('gawd_alert_daily', array($this, 'gawd_alert_daily'));
46
- add_action('gawd_alert_gawd_monthly', array($this, 'gawd_alert_monthly'));
47
- add_action('gawd_alert_gawd_weekly', array($this, 'gawd_alert_weekly'));
48
- add_action('gawd_email_daily', array($this, 'gawd_daily_email'), 0);
49
- add_action('gawd_email_gawd_weekly', array($this, 'gawd_weekly_email'));
50
- add_action('gawd_email_gawd_monthly', array($this, 'gawd_monthly_email'));
51
- //add_action('init', array($this, 'gawd_daily_email'));
52
- add_action('wp_head', array($this, 'gawd_tracking_code'), 99);
53
- $gawd_settings = get_option('gawd_settings');
54
- $gawd_post_page_roles = isset($gawd_settings['gawd_post_page_roles']) ? $gawd_settings['gawd_post_page_roles'] : array();
55
- $roles = $this->get_current_user_role();
56
- if((isset($gawd_settings['gawd_tracking_enable']) && $gawd_settings['gawd_tracking_enable'] == 'on') && (isset($gawd_settings['post_page_chart']) && $gawd_settings['post_page_chart'] != '') && (in_array($roles, $gawd_post_page_roles) || current_user_can('manage_options'))){
57
- add_filter('manage_posts_columns', array($this, 'gawd_add_columns'));
58
- // Populate custom column in Posts List
59
- add_action('manage_posts_custom_column', array($this, 'gawd_add_icons'), 10, 2);
60
- // Add custom column in Pages List
61
- add_filter('manage_pages_columns', array($this, 'gawd_add_columns'));
62
- // Populate custom column in Pages List
63
- add_action('manage_pages_custom_column', array($this, 'gawd_add_icons'), 10, 2);
64
- add_action('add_meta_boxes', array($this, 'gawd_add_custom_box'));
65
- add_action('admin_bar_menu', array($this, 'report_adminbar'), 999);
66
- }
67
-
68
-
69
- $this->update_credentials();
70
- $credentials = get_option('gawd_credentials');
71
-
72
-
73
- if (is_array($credentials)) {
74
- $this->set_project_client_id($credentials['project_id']);
75
- $this->set_project_client_secret($credentials['project_secret']);
76
- } else {
77
- //send error
78
- return;
79
- }
80
-
81
- }
82
-
83
- function get_current_user_role() {
84
- global $wp_roles;
85
- $current_user = wp_get_current_user();
86
- $roles = $current_user->roles;
87
- $role = array_shift($roles);
88
- return $role;
89
- }
90
-
91
- function report_adminbar($wp_admin_bar) {
92
- /* @formatter:off */
93
- $gawd_settings = get_option('gawd_settings');
94
- $gawd_frontend_roles = isset($gawd_settings['gawd_frontend_roles']) ? $gawd_settings['gawd_frontend_roles'] : array();
95
- $roles = $this->get_current_user_role();
96
- if (((in_array($roles, $gawd_frontend_roles) || current_user_can('manage_options')) && !is_admin()) && $gawd_settings['post_page_chart'] != '') {
97
- $id = get_the_ID();
98
- $uri_parts = explode('/', get_permalink($id), 4);
99
- if ($uri_parts[0] != '') {
100
- if (isset($uri_parts[3])) {
101
- $uri = '/' . $uri_parts[3];
102
- }
103
- $uri = explode('/', $uri);
104
- end($uri);
105
- $key = key($uri);
106
- $uri = '/' . $uri[$key - 1];
107
- $filter = rawurlencode(rawurldecode($uri));
108
-
109
- $args = array('id' => 'gawd',
110
- 'title' => '<span data-url="' . $filter . '" class="ab-icon"></span><span class="">' . __("Analytics WD", 'gawd') . '</span>',
111
- 'href' => '#1',
112
- );
113
- /* @formatter:on */
114
- $wp_admin_bar->add_node($args);
115
- }
116
- }
117
- }
118
-
119
- public function update_credentials() {
120
- //check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
121
- if ($_POST) {
122
- $gawd_own_project = isset($_POST['gawd_own_project']) ? $_POST['gawd_own_project'] : '';
123
- $gawd_own_client_id = isset($_POST['gawd_own_client_id']) ? $_POST['gawd_own_client_id'] : '';
124
- $gawd_own_client_secret = isset($_POST['gawd_own_client_secret']) ? $_POST['gawd_own_client_secret'] : '';
125
- $gawd_credentials['project_id'] = $gawd_own_client_id;
126
- $gawd_credentials['project_secret'] = $gawd_own_client_secret;
127
- if ($gawd_own_project && $gawd_own_client_id != '' && $gawd_own_client_secret != '') {
128
- update_option('gawd_credentials', $gawd_credentials);
129
- delete_option('gawd_user_data');
130
- add_option('gawd_own_project' , 1);
131
- }
132
- }
133
- }
134
-
135
- public function set_project_client_id($id) {
136
- $this->project_client_id = $id;
137
- }
138
-
139
- public function get_project_client_id() {
140
- return $this->project_client_id;
141
- }
142
-
143
- public function set_project_client_secret($secret) {
144
- $this->project_client_secret = $secret;
145
- }
146
-
147
- public function get_project_client_secret() {
148
- return $this->project_client_secret;
149
- }
150
-
151
- function gawd_check_id() {
152
- global $gawd_user_data;
153
- $current_user = get_current_screen();
154
-
155
- if (strpos($current_user->base, 'gawd')) {
156
- $gawd_user_data = get_option('gawd_user_data');
157
- if (!isset($gawd_user_data['refresh_token']) || ($gawd_user_data['refresh_token'] == '')) {
158
- if (strpos($current_user->base, 'gawd_settings') === false && strpos($current_user->base, 'gawd_uninstall') === false) {
159
- wp_redirect(admin_url() . 'admin.php?page=gawd_settings');
160
- }
161
- }
162
- }
163
- }
164
-
165
- function gawd_add_custom_box() {
166
- $screens = array('post', 'page');
167
- foreach ($screens as $screen)
168
- add_meta_box('gawd_page_post_meta', 'Sessions in month', array($this, 'gawd_add_custom_box_callback'), $screen, 'normal');
169
- }
170
-
171
- function gawd_add_custom_box_callback() {
172
- require_once( 'admin/post_page_view.php' );
173
- }
174
-
175
- public function gawd_add_icons($column, $id) {
176
- if ($column != 'gawd_stats') {
177
- return;
178
- }
179
- $uri_parts = explode('/', get_permalink($id), 4);
180
- if (isset($uri_parts[3])) {
181
- $uri = '/' . $uri_parts[3];
182
- }
183
- $uri = explode('/', $uri);
184
- end($uri);
185
- $key = key($uri);
186
- $uri = '/' . $uri[$key - 1];
187
- $filter = rawurlencode(rawurldecode($uri));
188
- echo '<a id="gawd-' . $id . '" class="gawd_page_post_stats" title="' . get_the_title($id) . '" href="#' . $filter . '"><img src="' . GAWD_URL . '/assets/back_logo.png"</a>';
189
- }
190
-
191
- public function gawd_add_columns($columns) {
192
- return array_merge($columns, array('gawd_stats' => __('Analytics WD', 'gawd')));
193
- }
194
-
195
- public static function gawd_roles($access_level, $tracking = false) {
196
- if (is_user_logged_in() && isset($access_level)) {
197
- $current_user = wp_get_current_user();
198
- $roles = (array) $current_user->roles;
199
- if (( current_user_can('manage_options') ) && !$tracking) {
200
- return true;
201
- }
202
- if (count(array_intersect($roles, $access_level)) > 0) {
203
- return true;
204
- } else {
205
- return false;
206
- }
207
- }
208
- return false;
209
- }
210
-
211
- public function gawd_tracking_code() {
212
- $gawd_user_data = get_option('gawd_user_data');
213
- if (isset($gawd_user_data['default_webPropertyId']) && ($gawd_user_data['default_webPropertyId'])) {
214
- global $gawd_client;
215
- $gawd_client = GAWD_google_client::get_instance();
216
- require_once(GAWD_DIR . '/admin/tracking.php');
217
- }
218
- }
219
-
220
- public function create_pdf_file($ajax=true,$data = null,$dimension = null, $start_date = null, $end_date = null,$metric_compare_recc = null, $metric_recc = null) {
221
- $first_data = isset($_REQUEST["first_data"]) ? sanitize_text_field($_REQUEST["first_data"]) : '';
222
- $_data_compare = isset($_REQUEST["_data_compare"]) ? ($_REQUEST["_data_compare"]) : '';
223
- if($ajax == true){
224
- $export_type = isset($_REQUEST["export_type"]) ? sanitize_text_field($_REQUEST["export_type"]) : '';
225
- if ($export_type != 'pdf') {
226
- return;
227
- }
228
-
229
- $report_type = isset($_REQUEST["report_type"]) ? sanitize_text_field($_REQUEST["report_type"]) : '';
230
-
231
-
232
- if ($report_type !== 'alert') {
233
- return;
234
- }
235
-
236
- }
237
-
238
- include_once GAWD_DIR . '/include/gawd_pdf_file.php';
239
- $file = new GAWD_PDF_FILE();
240
-
241
- /*
242
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
243
- $this->gawd_google_client = GAWD_google_client::get_instance();
244
- */
245
- $file->get_request_data($this,$ajax,$data,$dimension, $start_date, $end_date,$metric_compare_recc, $metric_recc );
246
-
247
- $file->sort_data();
248
- if($first_data != ''){
249
- $file->create_file('pages');
250
- }
251
- elseif(($_data_compare) != ''){
252
- $file->create_file('compare');
253
- }
254
- else{
255
- $file->create_file(true);
256
- }
257
- if($ajax == true){
258
- die();
259
- }
260
- else{
261
- return $file->file_dir;
262
- }
263
- }
264
- public function create_csv_file($ajax=true,$data = null,$dimension = null, $start_date = null, $end_date = null, $metric_compare_recc = null, $metric_recc = null){
265
- if($ajax == true){
266
- $export_type = isset($_REQUEST["export_type"]) ? sanitize_text_field($_REQUEST["export_type"]) : '';
267
- if ($export_type != 'csv') {
268
- return;
269
- }
270
- $report_type = isset($_REQUEST["report_type"]) ? sanitize_text_field($_REQUEST["report_type"]) : '';
271
- if ($report_type !== 'alert') {
272
- return;
273
- }
274
- }
275
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
276
- $this->gawd_google_client = GAWD_google_client::get_instance();
277
-
278
- $first_data = isset($_REQUEST["first_data"]) ? sanitize_text_field($_REQUEST["first_data"]) : '';
279
-
280
-
281
-
282
- include_once GAWD_DIR . '/include/gawd_csv_file.php';
283
-
284
- $file = new GAWD_CSV_FILE();
285
- $file->get_request_data($this,$ajax,$data,$dimension, $start_date, $end_date,$metric_compare_recc, $metric_recc );
286
-
287
- $file->sort_data();
288
-
289
- //$file->get_request_data($this);
290
-
291
- $file->sort_data();
292
- if($first_data != ''){
293
- $file->create_file(false);
294
- }
295
- else{
296
- $file->create_file();
297
- }
298
- if($ajax == true){
299
- die();
300
- }
301
- else{
302
- return $file->file_dir;
303
- }
304
- }
305
-
306
- public static function get_domain($domain) {
307
- $root = explode('/', $domain);
308
- $ret_domain = str_ireplace('www', '', isset($root[2]) ? $root[2] : $domain );
309
- return $ret_domain;
310
- }
311
-
312
- public static function error_message($type,$message){
313
- echo '<div style="width:99%"><div class="' . $type . '"><p><strong>' . $message . '</strong></p></div></div>';
314
- }
315
- public function gawd_export() {
316
- if (!isset($_REQUEST['action']) || (isset($_REQUEST['action']) && $_REQUEST['action'] !== 'gawd_export')) {
317
- return;
318
- }
319
-
320
- $export_type = isset($_REQUEST["export_type"]) ? sanitize_text_field($_REQUEST["export_type"]) : '';
321
- if ($export_type != 'pdf' && $export_type != 'csv') {
322
- return;
323
- }
324
-
325
- $report_type = isset($_REQUEST["report_type"]) ? sanitize_text_field($_REQUEST["report_type"]) : '';
326
-
327
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
328
- $this->gawd_google_client = GAWD_google_client::get_instance();
329
-
330
- if ($export_type == 'pdf') {
331
- include_once GAWD_DIR . '/include/gawd_pdf_file.php';
332
- $file = new GAWD_PDF_FILE();
333
- } else {
334
- include_once GAWD_DIR . '/include/gawd_csv_file.php';
335
- $file = new GAWD_CSV_FILE();
336
- }
337
-
338
- if ($report_type == 'alert') {
339
- if ($export_type == 'pdf') {
340
- $file->export_file();
341
- } else {
342
- $file->export_file();
343
- }
344
- }
345
-
346
- else {
347
- $metric = isset($_REQUEST["gawd_metric"]) ? sanitize_text_field($_REQUEST["gawd_metric"]) : '';
348
- $_data_compare = isset($_REQUEST["_data_compare"]) ? ($_REQUEST["_data_compare"]) : '';
349
- $first_data = isset($_REQUEST["first_data"]) ? ($_REQUEST["first_data"]) : '';
350
- $view_id = isset($_REQUEST["view_id"]) ? sanitize_text_field($_REQUEST["view_id"]) : '';
351
- $metric_compare = isset($_REQUEST["gawd_metric_compare"]) ? sanitize_text_field($_REQUEST["gawd_metric_compare"]) : '';
352
- $dimension = isset($_REQUEST["gawd_dimension"]) ? sanitize_text_field($_REQUEST["gawd_dimension"]) : '';
353
- $tab_name = isset($_REQUEST["tab_name"]) ? sanitize_text_field($_REQUEST["tab_name"]) : '';
354
- $img = isset($_REQUEST["img"]) ? sanitize_text_field($_REQUEST["img"]) : '';
355
- $gawd_email_subject = isset($_REQUEST["gawd_email_subject"]) ? sanitize_text_field($_REQUEST["gawd_email_subject"]) : '';
356
- $gawd_email_body = isset($_REQUEST["gawd_email_body"]) && $_REQUEST["gawd_email_body"] != '' ? sanitize_text_field($_REQUEST["gawd_email_body"]) : ' ';
357
- $email_from = isset($_REQUEST["gawd_email_from"]) ? sanitize_email($_REQUEST["gawd_email_from"]) : '';
358
- $email_to = isset($_REQUEST["gawd_email_to"]) ? sanitize_email($_REQUEST["gawd_email_to"]) : '';
359
- $email_period = isset($_REQUEST["gawd_email_period"]) ? sanitize_text_field($_REQUEST["gawd_email_period"]) : '';
360
- $week_day = isset($_REQUEST["gawd_email_week_day"]) ? sanitize_text_field($_REQUEST["gawd_email_week_day"]) : '';
361
- $month_day = isset($_REQUEST["gawd_email_month_day"]) ? sanitize_text_field($_REQUEST["gawd_email_month_day"]) : '';
362
- $emails = array();
363
- $invalid_email = false;
364
- $email_to = explode(',', $email_to);
365
- foreach ($email_to as $email) {
366
- if (is_email($email) == false) {
367
- $emails = $email;
368
- }
369
- }
370
- if (count($emails) > 0) {
371
- $invalid_email = true;
372
- }
373
- if (($invalid_email != true) && is_email($email_from) && $gawd_email_subject != '') {
374
- if ($email_period == "once") {
375
- $file->get_request_data($this);
376
- $file->sort_data();
377
- if($export_type == 'csv'){
378
- if($first_data != ''){
379
- $file->create_file(false);
380
- }
381
- else{
382
- $file->create_file();
383
- }
384
- }
385
- else{
386
- if($first_data != ''){
387
- $file->create_file('pages');
388
- }
389
- elseif(($_data_compare) != ''){
390
- $file->create_file('compare');
391
- }
392
- else{
393
- $file->create_file(false);
394
- }
395
- }
396
- $attachment = $file->file_dir;
397
-
398
- if ($report_type == 'email') {
399
- $headers = 'From: <' . $email_from . '>';
400
- wp_mail($email_to, $gawd_email_subject, $gawd_email_body, $headers, $attachment);
401
- }
402
- echo json_encode( array('status'=>'success','msg'=>'Email successfuly sent'));
403
- }
404
- else {
405
- if ($email_period == 'gawd_weekly') {
406
- $period_day = $week_day;
407
- $timestamp = strtotime('this ' . $period_day);
408
- }
409
- elseif ($email_period == 'gawd_monthly') {
410
- $period_day = $month_day;
411
- $timestamp = strtotime(date('Y-m-' . $period_day));
412
- }
413
- else {
414
- $period_day = '';
415
- $timestamp = time();
416
- }
417
- $saved_email = get_option('gawd_email');
418
- if ($saved_email) {
419
- $gawd_email_options = array('name' => $gawd_email_subject, 'period' => $email_period, 'metric' => $metric, 'metric_compare' => $metric_compare, 'dimension' => $dimension, 'creation_date' => date('Y-m-d'), 'emails' => $email_to, 'email_from' => $email_from, 'email_subject' => $gawd_email_subject, 'email_body' => $gawd_email_body, 'period_day' => $period_day, 'img' => $img, 'tab_name' => $tab_name, 'view_id' => $view_id, 'export_type' => $export_type);
420
- $saved_email[] = $gawd_email_options;
421
- update_option('gawd_email', $saved_email);
422
- }
423
- else {
424
- $gawd_email_options = array(0 => array('name' => $gawd_email_subject, 'period' => $email_period, 'metric' => $metric, 'metric_compare' => $metric_compare, 'dimension' => $dimension, 'creation_date' => date('Y-m-d'), 'emails' => $email_to, 'email_from' => $email_from, 'email_subject' => $gawd_email_subject, 'email_body' => $gawd_email_body, 'period_day' => $period_day, 'img' => $img, 'tab_name' => $tab_name, 'view_id' => $view_id, 'export_type' => $export_type));
425
- update_option('gawd_email', $gawd_email_options);
426
- }
427
- $saved_email = get_option('gawd_email');
428
- if ($saved_email) {
429
- foreach ($saved_email as $email) {
430
- if (!wp_next_scheduled('gawd_email_' . $email['period'])) {
431
- wp_schedule_event($timestamp, $email['period'], 'gawd_email_' . $email['period']);
432
- }
433
- }
434
- }
435
- $success_message = 'Email successfuly Scheduled </br> Go to <a href="'.admin_url() . 'admin.php?page=gawd_settings#gawd_emails_tab">Settings page</a> to delete scheduled e-mails.';
436
- echo json_encode( array('status'=>'success','msg'=>$success_message));
437
- }
438
-
439
- die;
440
- }
441
- else {
442
- if ($invalid_email == true) {
443
- echo json_encode('Invalid email');
444
- die;
445
- }
446
- else if ($gawd_email_subject == '') {
447
- echo json_encode("Can't send email with empty subject");
448
- die;
449
- }
450
- }
451
- }
452
- }
453
-
454
- public function overview_date_meta($screen = null, $context = 'advanced') {
455
- //righ side wide meta..
456
- $orintation = wp_is_mobile() ? 'side' : 'normal';
457
- add_meta_box('gawd-real-time', __('Real Time', 'gawd'), array($this, 'gawd_real_time'), 'gawd_analytics', 'side', 'high');
458
- add_meta_box('gawd-date-meta', __('Audience', 'gawd'), array($this, 'gawd_date_box'), 'gawd_analytics', $orintation, null);
459
- add_meta_box('gawd-country-box', __('Location', 'gawd'), array($this, 'gawd_country_box'), 'gawd_analytics', $orintation, null);
460
- //left side thin meta.
461
- add_meta_box('gawd-visitors-meta', __('Visitors', 'gawd'), array($this, 'gawd_visitors'), 'gawd_analytics', 'side', null);
462
- add_meta_box('gawd-browser-meta', __('Browsers', 'gawd'), array($this, 'gawd_browser'), 'gawd_analytics', 'side', null);
463
- }
464
-
465
- public function gawd_date_box() {
466
- require_once( 'admin/pages/date.php' );
467
- }
468
-
469
- public function gawd_country_box() {
470
- require_once( 'admin/pages/location.php' );
471
- }
472
-
473
- public function gawd_real_time() {
474
- require_once( 'admin/pages/real_time.php' );
475
- }
476
-
477
- public function gawd_visitors() {
478
- require_once( 'admin/pages/visitors.php' );
479
- }
480
-
481
- public function gawd_browser() {
482
- require_once( 'admin/pages/browser.php' );
483
- }
484
-
485
- /**
486
- * Activation function needed for the activation hook.
487
- */
488
- public static function activate() {
489
- $credentials['project_id'] = '115052745574-5vbr7tci4hjkr9clkflmnpto5jisgstg.apps.googleusercontent.com';
490
- $credentials['project_secret'] = 'wtNiu3c_bA_g7res6chV0Trt';
491
- if (!get_option('gawd_credentials')) {
492
- update_option('gawd_credentials', $credentials);
493
- }
494
- self::gawd_settings_defaults();
495
- self::add_dashboard_menu();
496
- }
497
-
498
- /**
499
- * Deactivation function needed for the deactivation hook.
500
- */
501
- public static function deactivate() {
502
-
503
- }
504
-
505
- /**
506
- * Enqueues the required styles and scripts, localizes some js variables.
507
- */
508
- public function gawd_front_scripts() {
509
- wp_enqueue_style('admin_css', GAWD_URL . '/inc/css/gawd_admin.css', false, GAWD_VERSION);
510
- wp_enqueue_script('gawd_amcharts', GAWD_URL . '/inc/js/amcharts.js', false, GAWD_VERSION);
511
- wp_enqueue_script('gawd_pie', GAWD_URL . '/inc/js/pie.js', false, GAWD_VERSION);
512
- wp_enqueue_script('gawd_serial', GAWD_URL . '/inc/js/serial.js', false, GAWD_VERSION);
513
- wp_enqueue_script('gawd_light_theme', GAWD_URL . '/inc/js/light.js', array('jquery'), GAWD_VERSION);
514
- wp_enqueue_script('gawd_dataloader', GAWD_URL . '/inc/js/dataloader.min.js', array('jquery'), GAWD_VERSION);
515
- wp_enqueue_script('date-js', GAWD_URL . '/inc/js/date.js', array('jquery'), GAWD_VERSION);
516
- wp_enqueue_script('gawd_front_js', GAWD_URL . '/inc/js/gawd_front.js', array('jquery'), GAWD_VERSION);
517
- wp_localize_script('gawd_front_js', 'gawd_front', array(
518
- 'ajaxurl' => admin_url('admin-ajax.php'),
519
- 'ajaxnonce' => wp_create_nonce('gawd_admin_page_nonce'),
520
- 'gawd_plugin_url' => GAWD_URL,
521
- 'date_30' => date('Y-m-d',strtotime('-31 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
522
- 'date_7' => date('Y-m-d',strtotime('-8 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
523
- 'date_last_week' => date('Y-m-d',strtotime('last week -1day')).'/-/'.date('Y-m-d',strtotime('last week +5day')),
524
- 'date_last_month' => date('Y-m-01',strtotime('last month')).'/-/'.date('Y-m-t',strtotime('last month')),
525
- 'date_this_month' =>date('Y-m-01').'/-/'.date('Y-m-d'),
526
- 'date_today' => date('Y-m-d').'/-/'.date('Y-m-d'),
527
- 'date_yesterday' => date('Y-m-d',strtotime('-1 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
528
- 'wp_admin_url' => admin_url(),
529
- 'exportUrl' => add_query_arg(array('action' => 'gawd_export'), admin_url('admin-ajax.php'))
530
- ));
531
- }
532
-
533
- public function gawd_enqueue_scripts() {
534
- $options = get_option('gawd_settings');
535
- $default_date = (isset($options['default_date']) && $options['default_date'] != '') ? $options['default_date'] : 'last_30days';
536
- $default_date_format = (isset($options['default_date_format']) && $options['default_date_format'] != '') ? $options['default_date_format'] : 'ymd_with_week';
537
- $enable_hover_tooltip = (isset($options['enable_hover_tooltip']) && $options['enable_hover_tooltip'] != '') ? $options['enable_hover_tooltip'] : '';
538
- $screen = get_current_screen();
539
- if (strpos($screen->base, 'gawd') !== false || strpos($screen->post_type, 'page') !== false || strpos($screen->post_type, 'post') !== false || strpos($screen->base, 'dashboard') !== false) {
540
- wp_enqueue_script('common');
541
- wp_enqueue_script('wp-lists');
542
- wp_enqueue_script('postbox');
543
- wp_enqueue_script('jquery-ui-tooltip');
544
- wp_enqueue_script('gawd_paging', GAWD_URL . '/inc/js/paging.js',false,GAWD_VERSION);
545
- wp_enqueue_script('jquery.cookie', GAWD_URL . '/inc/js/jquery.cookie.js',false,GAWD_VERSION);
546
- wp_enqueue_style('admin_css', GAWD_URL . '/inc/css/gawd_admin.css', false, GAWD_VERSION);
547
- wp_enqueue_style('gawd_licensing', GAWD_URL . '/inc/css/gawd_licensing.css', false, GAWD_VERSION);
548
- wp_enqueue_style('gawd_featured', GAWD_URL . '/featured/style.css', array(), GAWD_VERSION);
549
- wp_enqueue_style('font_awesome', GAWD_URL . '/inc/css/font_awesome.css', false, GAWD_VERSION);
550
- wp_enqueue_style('jquery-ui.css', GAWD_URL . '/inc/css/jquery-ui.css', false, GAWD_VERSION);
551
- wp_enqueue_style('gawd_bootstrap', GAWD_URL . '/inc/css/bootstrap.css', false, GAWD_VERSION);
552
- wp_enqueue_style('gawd_bootstrap-chosen', GAWD_URL . '/inc/css/bootstrap-chosen.css', false, GAWD_VERSION);
553
- wp_enqueue_style('gawd_bootstrap-select', GAWD_URL . '/inc/css/bootstrap-select.css', false, GAWD_VERSION);
554
- wp_enqueue_style('gawd_datepicker', GAWD_URL . '/inc/css/daterangepicker.css', false, GAWD_VERSION);
555
- wp_enqueue_style('ui.jqgrid.css', GAWD_URL . '/inc/css/ui.jqgrid.css', false, GAWD_VERSION);
556
- wp_enqueue_script('gawd_moment', GAWD_URL . '/inc/js/moment.min.js', false, GAWD_VERSION);
557
- wp_enqueue_script('gawd_daterangepicker', GAWD_URL . '/inc/js/daterangepicker.js', false, GAWD_VERSION);
558
- wp_enqueue_script('gawd_amcharts', GAWD_URL . '/inc/js/amcharts.js', false, GAWD_VERSION);
559
- wp_enqueue_script('ddd', 'http://www.amcharts.com/lib/3/plugins/responsive/responsive.min.js?0.9.1a', false, GAWD_VERSION);
560
- wp_enqueue_script('gawd_pie', GAWD_URL . '/inc/js/pie.js', false, GAWD_VERSION);
561
- wp_enqueue_script('gawd_serial', GAWD_URL . '/inc/js/serial.js', false, GAWD_VERSION);
562
- /*Map*/
563
- wp_enqueue_script('gawd_ammap', GAWD_URL . '/inc/js/ammap.js', false, GAWD_VERSION);
564
- wp_enqueue_script('gawd_worldLow', GAWD_URL . '/inc/js/worldLow.js', false, GAWD_VERSION);
565
- wp_enqueue_script('gawd_map_chart', GAWD_URL . '/inc/js/gawd_map_chart.js', false, GAWD_VERSION);
566
- /*End Map*/
567
- wp_enqueue_script('gawd_light_theme', GAWD_URL . '/inc/js/light.js', array('jquery'), GAWD_VERSION);
568
- wp_enqueue_script('gawd_dataloader', GAWD_URL . '/inc/js/dataloader.min.js', array('jquery'), GAWD_VERSION);
569
- wp_enqueue_script('rgbcolor.js', GAWD_URL . '/inc/js/rgbcolor.js', array('jquery'), GAWD_VERSION);
570
- wp_enqueue_script('StackBlur.js', GAWD_URL . '/inc/js/StackBlur.js', array('jquery'), GAWD_VERSION);
571
- wp_enqueue_script('canvg.js', GAWD_URL . '/inc/js/canvg.js', array('jquery'), GAWD_VERSION);
572
- wp_enqueue_script('gawd_tables', GAWD_URL . '/inc/js/loader.js', array('jquery'), GAWD_VERSION);
573
- wp_enqueue_script('gawd_grid', GAWD_URL . '/inc/js/jquery.jqGrid.min.js', array('jquery'), GAWD_VERSION);
574
- wp_enqueue_script('gawd_grid_locale', GAWD_URL . '/inc/js/grid.locale-en.js', array('jquery'), GAWD_VERSION);
575
- wp_enqueue_script('date-js', GAWD_URL . '/inc/js/date.js', array('jquery'), GAWD_VERSION);
576
- wp_enqueue_script('admin_js', GAWD_URL . '/inc/js/gawd_admin.js', array('jquery'), GAWD_VERSION);
577
- wp_enqueue_script('chosen.jquery.js', GAWD_URL . '/inc/js/chosen.jquery.js', array('jquery'), GAWD_VERSION);
578
- wp_enqueue_script('bootstrap_js', GAWD_URL . '/inc/js/bootstrap_js.js', array('jquery'), GAWD_VERSION);
579
- wp_enqueue_script('bootstrap-select', GAWD_URL . '/inc/js/bootstrap-select.js', array('jquery'), GAWD_VERSION);
580
- wp_enqueue_script('highlight_js', GAWD_URL . '/inc/js/js_highlight.js', array('jquery'), GAWD_VERSION);
581
- wp_enqueue_script('settings_js', GAWD_URL . '/inc/js/gawd_settings.js', array('jquery'), GAWD_VERSION);
582
- wp_enqueue_script('overview', GAWD_URL . '/inc/js/gawd_overview.js', array('jquery'), GAWD_VERSION);
583
- wp_localize_script('overview', 'gawd_overview', array(
584
- 'ajaxurl' => admin_url('admin-ajax.php'),
585
- 'ajaxnonce' => wp_create_nonce('gawd_admin_page_nonce'),
586
- 'gawd_plugin_url' => GAWD_URL,
587
- 'default_date' => $default_date,
588
- 'enableHoverTooltip' => $enable_hover_tooltip,
589
- 'wp_admin_url' => admin_url()
590
- ));
591
- wp_localize_script('admin_js', 'gawd_admin', array(
592
- 'ajaxurl' => admin_url('admin-ajax.php'),
593
- 'ajaxnonce' => wp_create_nonce('gawd_admin_page_nonce'),
594
- 'gawd_plugin_url' => GAWD_URL,
595
- 'wp_admin_url' => admin_url(),
596
- 'enableHoverTooltip' => $enable_hover_tooltip,
597
- 'default_date' => $default_date,
598
- 'default_date_format' => $default_date_format,
599
- 'date_30' => date('Y-m-d',strtotime('-31 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
600
- 'date_7' => date('Y-m-d',strtotime('-8 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
601
- 'date_last_week' => date('Y-m-d',strtotime('last week -1day')).'/-/'.date('Y-m-d',strtotime('last week +5day')),
602
- 'date_last_month' => date('Y-m-01',strtotime('last month')).'/-/'.date('Y-m-t',strtotime('last month')),
603
- 'date_this_month' =>date('Y-m-01').'/-/'.date('Y-m-d'),
604
- 'date_today' => date('Y-m-d').'/-/'.date('Y-m-d'),
605
- 'date_yesterday' => date('Y-m-d',strtotime('-1 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
606
- 'exportUrl' => add_query_arg(array('action' => 'gawd_export'), admin_url('admin-ajax.php'))
607
- ));
608
- }
609
- }
610
-
611
- /**
612
- * Adds the menu page with its submenus.
613
- */
614
- public function gawd_add_menu() {
615
- $gawd_settings = get_option('gawd_settings');
616
- $gawd_permissions = isset($gawd_settings['gawd_permissions']) ? $gawd_settings['gawd_permissions'] : array();
617
- if (empty($gawd_permissions)) {
618
- $permission = 'manage_options';
619
- } else {
620
- if (in_array('manage_options', $gawd_permissions)) {
621
- $permission = 'manage_options';
622
- }
623
- if (in_array('moderate_comments', $gawd_permissions)) {
624
- $permission = 'moderate_comments';
625
- }
626
- if (in_array('publish_posts', $gawd_permissions)) {
627
- $permission = 'publish_posts';
628
- }
629
- if (in_array('edit_posts', $gawd_permissions)) {
630
- $permission = 'edit_posts';
631
- }
632
- }
633
- add_menu_page(
634
- __('Analytics', 'gawd'), //$page_title
635
- __('Analytics', 'gawd'), //$menu_title
636
- $permission, //$capability
637
- 'gawd_analytics', //$menu_slug
638
- array($this, 'gawd_display_overview_page'), //$function = '',
639
- GAWD_URL . '/assets/main_icon.png'
640
- //$position = null
641
- );
642
-
643
- add_submenu_page(
644
- 'gawd_analytics', //$parent_slug
645
- __('Overview', 'gawd'), //$page_title
646
- __('Overview', 'gawd'), //$menu_title
647
- $permission, //$capability
648
- 'gawd_analytics', //$menu_slug
649
- array($this, 'gawd_display_overview_page') //$function = '',
650
- );
651
- add_submenu_page(
652
- 'gawd_analytics', //$parent_slug
653
- __('Reports', 'gawd'), //$page_title
654
- __('Reports', 'gawd'), //$menu_title
655
- $permission, //$capability
656
- 'gawd_reports', //$menu_slug
657
- array($this, 'gawd_display_reports_page') //$function = '',
658
- );
659
-
660
- add_submenu_page(
661
- 'gawd_analytics', //$parent_slug
662
- __('Settings', 'gawd'), //$page_title
663
- __('Settings', 'gawd'), //$menu_title
664
- $permission, //$capability
665
- 'gawd_settings', //$menu_slug
666
- array($this, 'gawd_display_settings_page') //$function = '',
667
- );
668
- add_submenu_page(
669
- 'gawd_analytics', //$parent_slug
670
- __('Tracking', 'gawd'), //$page_title
671
- __('Tracking', 'gawd'), //$menu_title
672
- $permission, //$capability
673
- 'gawd_tracking', //$menu_slug
674
- array($this, 'gawd_display_tracking_page') //$function = '',
675
- );
676
- add_submenu_page(
677
- 'gawd_analytics', //$parent_slug
678
- __('Goal Management', 'gawd'), //$page_title
679
- __('Goal Management', 'gawd'), //$menu_title
680
- $permission, //$capability
681
- 'gawd_goals', //$menu_slug
682
- array($this, 'gawd_display_goals_page') //$function = '',
683
- );
684
-
685
- add_submenu_page(
686
- 'gawd_analytics', //$parent_slug
687
- __('Custom Reports', 'gawd'), //$page_title
688
- __('Custom Reports', 'gawd'), //$menu_title
689
- $permission, //$capability
690
- 'gawd_custom_reports', //$menu_slug
691
- array($this, 'gawd_display_custom_reports_page') //$function = '',
692
- );
693
- add_submenu_page(
694
- 'gawd_analytics', //$parent_slug
695
- __('Get Pro', 'gawd'), //$page_title
696
- __('Get Pro', 'gawd'), //$menu_title
697
- $permission, //$capability
698
- 'gawd_licensing', //$menu_slug
699
- array($this, 'gawd_display_licensing_page') //$function = '',
700
- );
701
- add_submenu_page(
702
- 'gawd_analytics', //$parent_slug
703
- __('Featured Plugins', 'gawd'), //$page_title
704
- __('Featured Plugins', 'gawd'), //$menu_title
705
- $permission, //$capability
706
- 'gawd_featured_plugins', //$menu_slug
707
- array($this, 'gawd_display_featured_plugins_page') //$function = '',
708
- );
709
- add_submenu_page(
710
- 'gawd_analytics', //$parent_slug
711
- __('Featured Themes', 'gawd'), //$page_title
712
- __('Featured Themes', 'gawd'), //$menu_title
713
- $permission, //$capability
714
- 'gawd_featured_themes', //$menu_slug
715
- array($this, 'gawd_display_featured_themes_page') //$function = '',
716
- );
717
- add_submenu_page(
718
- 'gawd_analytics', //$parent_slug
719
- __('Uninstall', 'gawd'), //$page_title
720
- __('Uninstall', 'gawd'), //$menu_title
721
- $permission, //$capability
722
- 'gawd_uninstall', //$menu_slug
723
- array($this, 'gawd_display_uninstall_page') //$function = '',
724
- );
725
-
726
- }
727
- public function gawd_display_licensing_page() {
728
- require_once(GAWD_DIR . '/admin/licensing.php');
729
- }
730
- function upgrade_pro(){
731
- $screen = get_current_screen();
732
- if (strpos($screen->base, 'gawd') !== false && strpos($screen->base, 'gawd_featured') === false) {
733
- ?>
734
- <div class="gawd_upgrade wd-clear" >
735
- <div class="wd-right">
736
- <a href="https://web-dorado.com/products/wordpress-google-analytics-plugin.html" target="_blank">
737
- <div class="wd-table">
738
- <div class="wd-cell wd-cell-valign-middle">
739
- <?php _e("Upgrade to paid version", "gawd"); ?>
740
- </div>
741
-
742
- <div class="wd-cell wd-cell-valign-middle">
743
- <img src="<?php echo GAWD_URL; ?>/assets/web-dorado.png" >
744
- </div>
745
- </div>
746
- </a>
747
- </div>
748
- </div>
749
- <?php
750
- }
751
- }
752
-
753
- public function gawd_display_featured_plugins_page() {
754
- require_once(GAWD_DIR . '/featured/featured.php');
755
- gawd_featured_plugins('wd-google-analytics');
756
-
757
- }
758
- public function gawd_display_featured_themes_page() {
759
- require_once(GAWD_DIR . '/featured/featured_themes.php');
760
- $controller = new gawd_featured_themes();
761
- $controller->display();
762
- }
763
-
764
- public function gawd_auth() {
765
- check_ajax_referer('gawd_admin_page_nonce', 'security');
766
- $code = $_POST['token'];
767
- $status = GAWD_google_client::authenticate($code);
768
- if ($status === true) {
769
- $res = array(
770
- 'message' => 'successfully saved',
771
- 'status' => $status,
772
- );
773
- } else {
774
- $res = array(
775
- 'message' => 'there is an error',
776
- 'status' => $status
777
- );
778
- }
779
- header('content-type: application/json');
780
- echo json_encode($res);
781
- wp_die();
782
- }
783
-
784
- /**
785
- * Displays the Dashboard page.
786
- */
787
- public function gawd_display_uninstall_page() {
788
- require_once( 'admin/pages/uninstall.php' );
789
- $gawd_uninstall = new GAWDUninstall();
790
- $deactivate_url = wp_nonce_url('plugins.php?action=deactivate&plugin='.GWD_NAME.'/google-analytics-wd.php', 'deactivate-plugin_'.GWD_NAME.'/google-analytics-wd.php');
791
- $deactivate_url = str_replace('&amp;','&',$deactivate_url);
792
- if (isset($_POST['unistall_gawd'])) {
793
- check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
794
- delete_option('gawd_custom_reports');
795
- delete_option('gawd_menu_for_user');
796
- delete_option('gawd_all_metrics');
797
- delete_option('gawd_all_dimensions');
798
- delete_option('gawd_custom_dimensions');
799
- delete_option('gawd_settings');
800
- delete_option('gawd_user_data');
801
- delete_option('gawd_credentials');
802
- delete_option('gawd_menu_items');
803
- delete_option('gawd_export_chart_data');
804
- delete_option('gawd_email');
805
- delete_option('gawd_custom_reports');
806
- delete_option('gawd_alerts');
807
- delete_option('gawd_pushovers');
808
- delete_option('gawd_menu_for_users');
809
- delete_option('gawd_own_project');
810
- delete_option('gawd_zoom_message');
811
- delete_transient('gawd_user_profiles');
812
- echo '<script>window.location.href="'.$deactivate_url.'";</script>';
813
- }
814
- if (get_option('gawd_credentials')) {
815
- $gawd_uninstall->uninstall();
816
- }
817
- }
818
-
819
- public function gawd_display_goals_page() {
820
- if($this->manage_ua_code_selection() != 'done') {
821
- return;
822
- }
823
- global $gawd_client;
824
- $gawd_client = GAWD_google_client::get_instance();
825
- if (!empty($_POST)) {
826
- check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
827
- }
828
- $gawd_goal_profile = isset($_POST['gawd_goal_profile']) ? sanitize_text_field($_POST['gawd_goal_profile']) : '';
829
- $gawd_goal_name = isset($_POST['gawd_goal_name']) ? sanitize_text_field($_POST['gawd_goal_name']) : '';
830
- $gawd_goal_type = isset($_POST['gawd_goal_type']) ? sanitize_text_field($_POST['gawd_goal_type']) : '';
831
- $gawd_visit_hour = isset($_POST['gawd_visit_hour']) ? sanitize_text_field($_POST['gawd_visit_hour']) : '';
832
- $gawd_visit_minute = isset($_POST['gawd_visit_minute']) ? sanitize_text_field($_POST['gawd_visit_minute']) : '';
833
- $gawd_visit_second = isset($_POST['gawd_visit_second']) ? sanitize_text_field($_POST['gawd_visit_second']) : '';
834
- $gawd_goal_duration_comparison = isset($_POST['gawd_goal_duration_comparison']) ? sanitize_text_field($_POST['gawd_goal_duration_comparison']) : '';
835
- $gawd_goal_page_comparison = isset($_POST['gawd_goal_page_comparison']) ? sanitize_text_field($_POST['gawd_goal_page_comparison']) : '';
836
- $gawd_page_sessions = isset($_POST['gawd_page_sessions']) ? sanitize_text_field($_POST['gawd_page_sessions']) : '';
837
- $goal_max_id = isset($_POST['goal_max_id']) ? $_POST['goal_max_id'] + 1 : 1;
838
- $gawd_goal_page_destination_match = isset($_POST['gawd_goal_page_destination_match']) ? sanitize_text_field($_POST['gawd_goal_page_destination_match']) : '';
839
- $gawd_page_url = isset($_POST['gawd_page_url']) ? sanitize_text_field($_POST['gawd_page_url']) : '';
840
- $url_case_sensitve = isset($_POST['url_case_sensitve']) ? $_POST['url_case_sensitve'] : '';
841
- if ($gawd_goal_type == 'VISIT_TIME_ON_SITE') {
842
- if ($gawd_visit_hour != '' || $gawd_visit_minute != '' || $gawd_visit_second != '') {
843
- $value = 0;
844
- if ($gawd_visit_hour != '') {
845
- $value += $gawd_visit_hour * 60 * 60;
846
- }
847
- if ($gawd_visit_minute != '') {
848
- $value += $gawd_visit_minute * 60;
849
- }
850
- if ($gawd_visit_second != '') {
851
- $value += $gawd_visit_second;
852
- }
853
- }
854
- $gawd_client->add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_duration_comparison, $value);
855
- } elseif ($gawd_goal_type == 'VISIT_NUM_PAGES') {
856
- if ($gawd_page_sessions != '') {
857
- $gawd_client->add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_page_comparison, $gawd_page_sessions);
858
- }
859
- } elseif ($gawd_goal_type == 'URL_DESTINATION') {
860
- if ($gawd_page_url != '') {
861
- $gawd_client->add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_page_destination_match, $gawd_page_url, $url_case_sensitve);
862
- }
863
- } elseif ($gawd_goal_type == 'EVENT') {
864
- if ($gawd_page_url != '') {
865
- $gawd_client->add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_page_comparison, $gawd_page_url, $url_case_sensitve);
866
- }
867
- }
868
- require_once( 'admin/pages/goals.php' );
869
-
870
- }
871
-
872
- public function gawd_display_custom_reports_page() {
873
- global $gawd_client;
874
- if (!empty($_POST)) {
875
- check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
876
- }
877
- $gawd_client = GAWD_google_client::get_instance();
878
- $gawd_remove_custom_report = isset($_POST['gawd_remove_custom_report']) ? sanitize_text_field($_POST['gawd_remove_custom_report']) : '';
879
- if ($gawd_remove_custom_report) {
880
- $all_reports = get_option("gawd_custom_reports");
881
- if ($all_reports) {
882
- unset($all_reports[$gawd_remove_custom_report]);
883
- update_option('gawd_custom_reports', $all_reports);
884
- self::add_dashboard_menu();
885
- }
886
- }
887
- if (isset($_POST['gawd_add_custom_report'])) {
888
- $gawd_custom_report_name = isset($_POST['gawd_custom_report_name']) ? sanitize_text_field($_POST['gawd_custom_report_name']) : '';
889
- $gawd_custom_report_metric = isset($_POST['gawd_custom_report_metric']) ? sanitize_text_field($_POST['gawd_custom_report_metric']) : '';
890
- $gawd_custom_report_dimension = isset($_POST['gawd_custom_report_dimension']) ? sanitize_text_field($_POST['gawd_custom_report_dimension']) : '';
891
-
892
- if ($gawd_custom_report_name != '' && $gawd_custom_report_metric != '' && $gawd_custom_report_dimension != '') {
893
- $saved_custom_reports = get_option("gawd_custom_reports");
894
- if(!isset($saved_custom_reports[$gawd_custom_report_name])){
895
- if ($saved_custom_reports) {
896
- $custom_reports = array('metric' => $gawd_custom_report_metric, 'dimension' => $gawd_custom_report_dimension, 'id' => count($saved_custom_reports) + 1);
897
- $saved_custom_reports[$gawd_custom_report_name] = $custom_reports;
898
-
899
- update_option('gawd_custom_reports', $saved_custom_reports);
900
- }
901
- else {
902
- $custom_reports = array($gawd_custom_report_name => array('metric' => $gawd_custom_report_metric, 'dimension' => $gawd_custom_report_dimension, 'id' => 1));
903
- update_option('gawd_custom_reports', $custom_reports);
904
- }
905
- }
906
- }
907
- self::add_dashboard_menu();
908
- }
909
- require_once( 'admin/pages/custom_reports.php' );
910
- }
911
-
912
- public function gawd_display_overview_page() {
913
- global $gawd_client, $gawd_user_data;
914
- $gawd_client = GAWD_google_client::get_instance();
915
- $profiles = $gawd_client->get_profiles();
916
- $gawd_user_data = get_option('gawd_user_data');
917
- if(isset($_POST['gawd_id'])){
918
- $gawd_user_data['gawd_id'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
919
- foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
920
- foreach ($web_property as $profile) {
921
- if ($profile['id'] == $gawd_user_data['gawd_id']) {
922
- $gawd_user_data['web_property_name'] = $web_property_name;
923
- $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
924
- $gawd_user_data['accountId'] = $profile['accountId'];
925
- }
926
- }
927
- }
928
- $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
929
- update_option('gawd_user_data', $gawd_user_data);
930
- }
931
- require_once( 'admin/pages/overview.php' );
932
- }
933
-
934
- public function gawd_display_reports_page() {
935
- global $gawd_client, $gawd_user_data;
936
- $gawd_client = GAWD_google_client::get_instance();
937
- $profiles = $gawd_client->get_profiles();
938
- $gawd_user_data = get_option('gawd_user_data');
939
- if(isset($_POST['gawd_id'])){
940
- $gawd_user_data['gawd_id'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
941
- foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
942
- foreach ($web_property as $profile) {
943
- if ($profile['id'] == $gawd_user_data['gawd_id']) {
944
- $gawd_user_data['web_property_name'] = $web_property_name;
945
- $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
946
- $gawd_user_data['accountId'] = $profile['accountId'];
947
- }
948
- }
949
- }
950
- $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
951
- update_option('gawd_user_data', $gawd_user_data);
952
- }
953
- require_once( 'admin/pages/dashboard.php' );
954
- }
955
-
956
- public function gawd_daily_email() {
957
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
958
- $gawd_client = GAWD_google_client::get_instance();
959
- $emails = get_option('gawd_email');
960
- $gawd_user_data = get_option('gawd_user_data');
961
- $data = '';
962
- foreach ($emails as $email) {
963
- if (isset($email['period']) && $email['period'] == 'daily') {
964
- //pls send email if ....
965
- $date = date('Y-m-d', strtotime('yesterday'));
966
- $email_subject = preg_match('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', $email['email_subject']) ? preg_replace('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', '(' . $date . ' - ' . $date . ')', $email['email_subject']) : $email['email_subject'] . ' (' . $date . ' - ' . $date . ')';
967
- $data = $this->show_data(array('metric'=>'ga:' . $email['metric'], 'dimension'=>$email['dimension'], 'start_date'=>$date,'end_date'=> $date));
968
- if($email['export_type'] == 'pdf'){
969
- $filedir = $this->create_pdf_file(false,$data, $email['dimension'], $date, $date,$email['metric_compare'],$email['metric']);
970
- }
971
- else{
972
- $filedir = $this->create_csv_file(false,$data, $email['dimension'], $date, $date,$email['metric_compare'],$email['metric']);
973
- }
974
- //$attachment = gawd_export_data($data, $export_type, 'email', $email['dimension'], $email['metric'], $email['metric_compare'], $email['img'], $email['tab_name'], $start_date, $end_date, $gawd_user_data['web_property_name'],$filter_type);
975
- $attachment = $filedir;
976
- $headers = 'From: <' . $email['email_from'] . '>';
977
- wp_mail($email['emails'], $email_subject, $email['email_body'], $headers, $attachment);
978
- }
979
- }
980
- }
981
-
982
- public function gawd_weekly_email() {
983
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
984
- $gawd_client = GAWD_google_client::get_instance();
985
- $emails = get_option('gawd_email');
986
- $gawd_user_data = get_option('gawd_user_data');
987
- $data = '';
988
- foreach ($emails as $email) {
989
- if (isset($email['period']) && $email['period'] == 'gawd_weekly') {
990
- //pls send email if ....
991
- /*$start_date = date('Y-m-d', strtotime('last' . $email['period_day']));
992
- $end_date = date('Y-m-d', strtotime('this' . $email['period_day']));*/
993
- $start_date = date('Y-m-d', strtotime('last week -1 day'));
994
- $end_date = date('l') != 'Sunday' ? date('Y-m-d',strtotime('last sunday -1 day')) : date('Y-m-d', strtotime('-1 day'));
995
- $email_subject = preg_match('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', $email['email_subject']) ? preg_replace('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', '(' . $start_date . ' - ' . $end_date . ')', $email['email_subject']) : $email['email_subject'] . ' (' . $start_date . ' - ' . $end_date . ')';
996
- $data = $this->show_data(array('metric'=>'ga:' . $email['metric'], 'dimension'=>$email['dimension'], 'start_date'=>$start_date,'end_date'=> $end_date));
997
- if($email['export_type'] == 'pdf'){
998
- $filedir = $this->create_pdf_file(false,$data, $email['dimension'], $start_date, $end_date,$email['metric_compare'],$email['metric']);
999
- }
1000
- else{
1001
- $filedir = $this->create_csv_file(false,$data, $email['dimension'], $start_date, $end_date, $email['metric_compare'],$email['metric']);
1002
- }
1003
- //$attachment = gawd_export_data($data, $export_type, 'email', $email['dimension'], $email['metric'], $email['metric_compare'], $email['img'], $email['tab_name'], $start_date, $end_date, $gawd_user_data['web_property_name'],$filter_type);
1004
- $attachment = $filedir;
1005
-
1006
- $headers = 'From: <' . $email['email_from'] . '>';
1007
- wp_mail($email['emails'], $email_subject, $email['email_body'], $headers, $attachment);
1008
- }
1009
- }
1010
- }
1011
-
1012
- public function gawd_monthly_email() {
1013
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1014
- $gawd_client = GAWD_google_client::get_instance();
1015
- $emails = get_option('gawd_email');
1016
- $gawd_user_data = get_option('gawd_user_data');
1017
- $data = '';
1018
- foreach ($emails as $email) {
1019
- if (isset($email['period']) && $email['period'] == 'gawd_monthly') {
1020
- //pls send email if ....
1021
- $end_date = date('Y-m-d', strtotime(date('Y-' . date('m') . '-1') . '-1 day'));
1022
- $start_date = date('Y-m-d', strtotime($end_date . '- 1 month'));
1023
- $data = $this->show_data(array('metric'=>'ga:' . $email['metric'], 'dimension'=>$email['dimension'], 'start_date'=>$start_date,'end_date'=> $end_date));
1024
- $email_subject = preg_match('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', $email['email_subject']) ? preg_replace('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', '(' . $start_date . ' - ' . $end_date . ')', $email['email_subject']) : $email['email_subject'] . ' (' . $start_date . ' - ' . $end_date . ')';
1025
- if($email['export_type'] == 'pdf'){
1026
- $filedir = $this->create_pdf_file(false,$data, $email['dimension'], $start_date, $end_date,$email['metric_compare'],$email['metric']);
1027
- }
1028
- else{
1029
- $filedir = $this->create_csv_file(false,$data, $email['dimension'], $start_date, $end_date,$email['metric_compare'],$email['metric']);
1030
- }
1031
- //$attachment = gawd_export_data($data, $export_type, 'email', $email['dimension'], $email['metric'], $email['metric_compare'], $email['img'], $email['tab_name'], $start_date, $end_date, $gawd_user_data['web_property_name'],$filter_type);
1032
- $attachment = $filedir;
1033
- $headers = 'From: <' . $email['email_from'] . '>';
1034
- wp_mail($email['emails'], $email_subject, $email['email_body'], $headers, $attachment);
1035
- }
1036
- }
1037
- }
1038
-
1039
- /**
1040
- * Prepares the settings to be displayed then displays the settings page.
1041
- */
1042
- public static function gawd_settings_defaults() {
1043
- $settings = get_option('gawd_settings');
1044
- $settings['gawd_tracking_enable'] = 'on';
1045
- $settings['gawd_custom_dimension_Logged_in'] = 'on';
1046
- $settings['gawd_custom_dimension_Post_type'] = 'on';
1047
- $settings['gawd_custom_dimension_Author'] = 'on';
1048
- $settings['gawd_custom_dimension_Category'] = 'on';
1049
- $settings['gawd_custom_dimension_Published_Month'] = 'on';
1050
- $settings['gawd_custom_dimension_Published_Year'] = 'on';
1051
- $settings['gawd_custom_dimension_Tags'] = 'on';
1052
- $settings['enable_hover_tooltip'] = 'on';
1053
- update_option('gawd_settings', $settings);
1054
- }
1055
-
1056
- public function manage_ua_code_selection() {
1057
- global $gawd_user_data;
1058
- if (isset($gawd_user_data['default_webPropertyId']) && $gawd_user_data['default_webPropertyId']) {
1059
- return 'done';
1060
- } else {
1061
- $gawd_client = GAWD_google_client::get_instance();
1062
- $property = $gawd_client->property_exists();
1063
- if ($property == 'no_matches') {
1064
- $this->gawd_admin_notice("<p class='gawd_notice'>You don't have any web-properties with current site url, go with <a href='" . admin_url('admin.php?page=gawd_tracking') . "'>this</a> link to add.</p>", 'error');
1065
- // show notice that you don't have property with current site url
1066
- // add account or property to an existing account
1067
- } elseif (count($property) == 1) {
1068
- $property = $property[0];
1069
- $gawd_user_data['webPropertyId'] = $property['id'];
1070
- $gawd_user_data['default_webPropertyId'] = $property['id'];
1071
- $gawd_user_data['accountId'] = $property['accountId'];
1072
- $gawd_user_data['default_accountId'] = $property['accountId'];
1073
- $gawd_user_data['gawd_id'] = $property['defaultProfileId'];
1074
- update_option('gawd_user_data', $gawd_user_data);
1075
- $this->gawd_admin_notice("In order to enable tracking for your website, you have to go with
1076
- <a href='" . admin_url('admin.php?page=gawd_tracking') . "'>this</a> link and turn the option on.", 'warning is-dismissible');
1077
- // show notice that you have to enable tracking code, link to tracking submenu
1078
- } else {
1079
- $this->gawd_admin_notice("You have two or more web-properties configured with current site url. Please go with
1080
- <a href='" . admin_url('admin.php?page=gawd_tracking') . "'>this</a> link to select the proper one.", 'error');
1081
- // show notice that you have >=2 properties with current site url
1082
- // select property from same url properties
1083
- }
1084
- }
1085
- }
1086
-
1087
- public function manage_ua_code_selection_tracking() {
1088
- global $gawd_user_data;
1089
- if (isset($gawd_user_data['default_webPropertyId']) && $gawd_user_data['default_webPropertyId']) {
1090
- return 'done';
1091
- } else {
1092
- $gawd_client = GAWD_google_client::get_instance();
1093
- $property = $gawd_client->property_exists();
1094
- if ($property == 'no_matches') {
1095
- $accounts = $gawd_client->get_management_accounts();
1096
- if (!empty($accounts)) {
1097
- echo "<h3 style='margin-top:10px' class='gawd_page_titles'>Tracking</h3>
1098
- <p class='gawd_notice notice'>Here you can add a <b>web property</b> on your Google Analytics account using current WordPress website.<br>
1099
- Provide a <b>Name</b> for the property and click <b>Add</b>. You can check and manage web properties from your Google Analytics account, <b>Admin</b> page.<br>
1100
- Alternatively, you can click <b>Later</b> and configure the web property any other time.</p>
1101
- <br/>
1102
- <form method='post' id='gawd_property_add'>
1103
- <div class='gawd_settings_wrapper'>
1104
- <div class='gawd_goal_row'>
1105
- <span class='gawd_goal_label'>Account</span>
1106
- <span class='gawd_goal_input'>
1107
- <select name='gawd_account_select' class='gawd_account_select' style='padding: 2px;width: 96%;line-height: 30px;height: 30px !important;'>";
1108
- foreach ($accounts as $account) {
1109
- echo "<option value='" . $account['id'] . "'>" . $account['name'] . "</option>";
1110
- }
1111
- echo "</select>
1112
- </span>
1113
- <div class='gawd_info' title='this_is_tooltip'></div>
1114
- <div class='clear'></div>
1115
- </div>
1116
- <div class='gawd_goal_row'>
1117
- <span class='gawd_goal_label'>Name</span>
1118
- <span class='gawd_goal_input'>
1119
- <input id='gawd_property_name' name='gawd_property_name' type='text'>
1120
- </span>
1121
- <div class='gawd_info' title='this_is_tooltip'></div>
1122
- <div class='clear'></div>
1123
- </div>
1124
- </div>
1125
- <div class='gawd_add_prop gawd_submit'>
1126
- <a href='".admin_url() . "admin.php?page=gawd_analytics' class='gawd_later button_gawd'>Later</a>
1127
- <input type='submit' name='add_property' class='button_gawd' value='ADD'/>
1128
- </div>
1129
- </form>";
1130
- // account select to add web property and web property parameters
1131
- // and add link to google analytics for manually creating an account
1132
- // wp_die();
1133
- } else {
1134
- $this->gawd_admin_notice("You do not have any google analytics accounts set. Please go with <a href='https://analytics.google.com/' target='_blank'>this</a> link to add one.", "error");
1135
- // link to google analytics to add account
1136
- // wp_die();
1137
- }
1138
- } elseif (count($property) == 1) {
1139
- $property = $property[0];
1140
- $gawd_user_data['webPropertyId'] = $property['id'];
1141
- $gawd_user_data['default_webPropertyId'] = $property['id'];
1142
- $gawd_user_data['accountId'] = $property['accountId'];
1143
- $gawd_user_data['default_accountId'] = $property['accountId'];
1144
- $gawd_user_data['gawd_id'] = $property['defaultProfileId'];
1145
- update_option('gawd_user_data', $gawd_user_data);
1146
- } else {
1147
- echo "<p class='notice'>You have multiple web-properties set with current site url. Please select the one which you want to use for tracking from the list below.</p>
1148
- <br/>
1149
- <form method='post' id='gawd_property_select'>
1150
- <div class='gawd_settings_wrapper'>
1151
- <div class='gawd_goal_row'>
1152
- <span class='gawd_goal_label'>Web-property</span>
1153
- <span class='gawd_goal_input'>
1154
- <select name='gawd_property_select' class='gawd_property_select' style='padding: 2px;width: 96%;line-height: 30px;height: 30px !important;'>";
1155
- foreach ($property as $select_property) {
1156
- echo "<option value='" . $select_property['id'] . "'>" . $select_property['name'] . " (" . $select_property['id'] . ")</option>";
1157
- }
1158
- echo "</select>
1159
- </span>
1160
- <div class='gawd_info' title='this_is_tooltip'></div>
1161
- <div class='clear'></div>
1162
- </div>
1163
- </div>
1164
- <div class='gawd_submit'><input type='submit' name='lock_property' class='button_gawd' value='SAVE'/></div>
1165
- </form>";
1166
- // web property select to select from properties with same site url
1167
- // wp_die();
1168
- }
1169
- }
1170
- }
1171
-
1172
- public function gawd_admin_notice($message, $type) {
1173
- $class = 'notice notice-' . $type;
1174
- echo '<div class="' . $class . '"><p>' . $message . '</p></div>';
1175
- }
1176
-
1177
- public function gawd_display_settings_page() {
1178
- global $gawd_user_data;
1179
- $gawd_user_data = get_option('gawd_user_data');
1180
- if(isset($_GET['defaultExist']) && $_GET['defaultExist'] ==1){
1181
- $redirect_url = admin_url() . 'admin.php?page=gawd_tracking';
1182
- echo '<script>window.location.href="'.$redirect_url.'";</script>';
1183
- }
1184
- if(isset($_POST['gawd_settings_logout'])&& $_POST['gawd_settings_logout'] == 1){
1185
- delete_option('gawd_user_data');
1186
- $redirect_url = admin_url() . 'admin.php?page=gawd_settings';
1187
- echo '<script>window.location.href="'.$redirect_url.'";</script>';
1188
- }
1189
- if(isset($_POST['web_property_name']) && $_POST['web_property_name'] != ''){
1190
- $gawd_user_data['gawd_id'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
1191
- foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
1192
- foreach ($web_property as $profile) {
1193
- if ($profile['id'] == $gawd_user_data['gawd_id']) {
1194
- $gawd_user_data['web_property_name'] = $web_property_name;
1195
- $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
1196
- $gawd_user_data['accountId'] = $profile['accountId'];
1197
- }
1198
- }
1199
- }
1200
- $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
1201
- update_option('gawd_user_data', $gawd_user_data);
1202
- $redirect_url = admin_url() . 'admin.php?page=gawd_settings';
1203
- //echo '<script>window.location.href="'.$redirect_url.'";</script>';
1204
- }
1205
- /* if(isset($_POST['account_name']) && $_POST['account_name'] != ''){
1206
- $gawd_user_data['accountId'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
1207
- foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
1208
- foreach ($web_property as $profile) {
1209
- if ($profile['accountId'] == $gawd_user_data['accountId']) {
1210
- $gawd_user_data['web_property_name'] = $web_property_name;
1211
- $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
1212
- $gawd_user_data['accountId'] = $profile['accountId'];
1213
- }
1214
- }
1215
- }
1216
- $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
1217
- update_option('gawd_user_data', $gawd_user_data);
1218
- $redirect_url = admin_url() . 'admin.php?page=gawd_settings';
1219
- //echo '<script>window.location.href="'.$redirect_url.'";</script>';
1220
- } */
1221
- if(isset($_GET['errorMsg'])){
1222
- self::error_message('error','User does not have sufficient permissions for this account to add filter');
1223
- }
1224
- if (!isset($gawd_user_data['refresh_token']) || ($gawd_user_data['refresh_token'] == '')) {
1225
- echo '<div class="gawd_auth_wrap"><p class="auth_description">Click <b>Authenticate</b> button and login to your Google account. A window asking for relevant permissions will appear. Click <b>Allow</b> and copy the authentication code from the text input.</p><div id="gawd_auth_url" onclick="gawd_auth_popup(' . GAWD_google_client::create_authentication_url() . ',800,400)" style="cursor: pointer;">AUTHENTICATE</div>';
1226
- echo '<div id="gawd_auth_code"><form id="gawd_auth_code_paste" action="" method="post"><input id="gawd_token" type="text">';
1227
- wp_nonce_field("gawd_save_form", "gawd_save_form_fild");
1228
- echo '</form>
1229
- <div id="gawd_auth_code_submit">SUBMIT</div></div>';
1230
- $gawd_own_project = get_option('gawd_own_project');
1231
- if(isset($gawd_own_project) && $gawd_own_project && intval($gawd_own_project)==1){
1232
- echo'<form method="post">
1233
- <div class="gawd_reset_button">
1234
- <input type="hidden" name="reset_data" id="reset_data"/>
1235
- <input type="button" class="button_gawd" id="gawd_reset_button" value="RESET"/>
1236
- </div>
1237
- </form>';
1238
- }
1239
- echo '</div><div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div>
1240
- <div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;">
1241
- <img src="' . GAWD_URL . '/assets/ajax_loader.gif" style="margin-top: 200px; width:50px;">
1242
- </div>';
1243
- }
1244
- else {
1245
- if($this->manage_ua_code_selection() != 'done') {
1246
- // return;
1247
- }
1248
- try{
1249
- $gawd_client = GAWD_google_client::get_instance();
1250
- $gawd_client->get_profiles();
1251
-
1252
- }catch(Google_Service_Exception $e){
1253
- return $e->getErrors()[0]["message"];
1254
- }catch(Exception $e){
1255
- return $e->getMessage();
1256
- }
1257
-
1258
- $gawd_alert_remove = isset($_POST['gawd_alert_remove']) ? intval($_POST['gawd_alert_remove']) : false;
1259
- $gawd_menu_remove = isset($_POST['gawd_menu_remove']) ? intval($_POST['gawd_menu_remove']) : false;
1260
- $gawd_pushover_remove = isset($_POST['gawd_pushover_remove']) ? intval($_POST['gawd_pushover_remove']) : false;
1261
- $gawd_email_remove = isset($_POST['gawd_email_remove']) ? intval($_POST['gawd_email_remove']) : false;
1262
- $gawd_filter_remove = isset($_POST['gawd_filter_remove']) ? intval($_POST['gawd_filter_remove']) : false;
1263
- if ($gawd_alert_remove) {
1264
- $all_alerts = get_option('gawd_alerts');
1265
- if ($all_alerts) {
1266
- foreach ($all_alerts as $alert) {
1267
- wp_unschedule_event(wp_next_scheduled('gawd_alert_' . $alert['period']), 'gawd_alert_' . $alert['period']);
1268
- }
1269
- unset($all_alerts[$gawd_alert_remove - 1]);
1270
- update_option('gawd_alerts', $all_alerts);
1271
- }
1272
- }
1273
- if ($gawd_menu_remove) {
1274
- $all_menues = get_option('gawd_menu_for_user');
1275
- if ($all_menues) {
1276
- unset($all_menues[$gawd_menu_remove]);
1277
- update_option('gawd_menu_for_user', $all_menues);
1278
- }
1279
- }
1280
- if ($gawd_email_remove) {
1281
- $all_emails = get_option('gawd_email');
1282
- if ($all_emails) {
1283
- foreach ($all_emails as $email) {
1284
- wp_unschedule_event(wp_next_scheduled('gawd_email_' . $email['period']), 'gawd_email_' . $email['period']);
1285
- }
1286
- unset($all_emails[$gawd_email_remove - 1]);
1287
- update_option('gawd_email', $all_emails);
1288
- }
1289
- }
1290
- if ($gawd_filter_remove) {
1291
- $analytics = $gawd_client->analytics_member;
1292
- $accountId = $gawd_client->get_profile_accountId();
1293
- try{
1294
- $analytics->management_filters->delete($accountId, $gawd_filter_remove);
1295
- } catch (apiServiceException $e) {
1296
- print 'There was an Analytics API service error '
1297
- . $e->getCode() . ':' . $e->getMessage();
1298
- } catch (apiException $e) {
1299
- print 'There was a general API error '
1300
- . $e->getCode() . ':' . $e->getMessage();
1301
- } catch (Exception $e) {
1302
- echo '<script>window.location.href="' . admin_url() . 'admin.php?page=gawd_settings&errorMsg=1#gawd_filters_tab";</script>';
1303
- }
1304
- }
1305
- $gawd_pushover_remove = isset($_POST['gawd_pushover_remove']) ? $_POST['gawd_pushover_remove'] : false;
1306
- if ($gawd_pushover_remove) {
1307
- $all_pushovers = get_option('gawd_pushovers');
1308
- if ($all_pushovers) {
1309
- foreach ($all_pushovers as $pushover) {
1310
- wp_unschedule_event(wp_next_scheduled('gawd_pushover_' . $pushover['period']), 'gawd_pushover_' . $pushover['period']);
1311
- }
1312
- unset($all_pushovers[$gawd_pushover_remove - 1]);
1313
- update_option('gawd_pushovers', $all_pushovers);
1314
- }
1315
- }
1316
- if (isset($_POST['settings_submit'])) {
1317
- check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
1318
- $gawd_user_data = get_option('gawd_user_data');
1319
- $gawd_alert_name = isset($_POST['gawd_alert_name']) ? sanitize_text_field($_POST['gawd_alert_name']) : '';
1320
- $gawd_alert_period = isset($_POST['gawd_alert_name']) ? sanitize_text_field($_POST['gawd_alert_period']) : '';
1321
- $gawd_alert_metric = isset($_POST['gawd_alert_metric']) ? sanitize_text_field($_POST['gawd_alert_metric']) : '';
1322
- $gawd_alert_condition = isset($_POST['gawd_alert_condition']) ? sanitize_text_field($_POST['gawd_alert_condition']) : '';
1323
- $gawd_alert_value = isset($_POST['gawd_alert_value']) ? sanitize_text_field($_POST['gawd_alert_value']) : '';
1324
- $gawd_alert_emails = isset($_POST['gawd_alert_emails']) ? sanitize_email($_POST['gawd_alert_emails']) : '';
1325
- $gawd_alert_view = isset($_POST['gawd_alert_view']) ? sanitize_text_field($_POST['gawd_alert_view']) : '';
1326
- $alert_view_name = isset($_POST['alert_view_name']) ? sanitize_text_field($_POST['alert_view_name']) : '';
1327
- if ($gawd_alert_name != '' && $gawd_alert_period != '' && $gawd_alert_metric != '' && $gawd_alert_condition != '' && $gawd_alert_value != '' && $gawd_alert_emails != '') {
1328
- $saved_alerts = get_option('gawd_alerts');
1329
- if ($saved_alerts) {
1330
- $gawd_alert_options = array('name' => $gawd_alert_name, 'period' => $gawd_alert_period, 'metric' => $gawd_alert_metric, 'condition' => $gawd_alert_condition, 'value' => $gawd_alert_value, 'creation_date' => date('Y-m-d'), 'emails' => $gawd_alert_emails, 'alert_view' => $gawd_alert_view, 'alert_view_name' => $alert_view_name);
1331
- $saved_alerts[] = $gawd_alert_options;
1332
- update_option('gawd_alerts', $saved_alerts);
1333
- } else {
1334
- $gawd_alert_options = array(0 => array('name' => $gawd_alert_name, 'period' => $gawd_alert_period, 'metric' => $gawd_alert_metric, 'condition' => $gawd_alert_condition, 'value' => $gawd_alert_value, 'creation_date' => date('Y-m-d'), 'emails' => $gawd_alert_emails, 'alert_view' => $gawd_alert_view, 'alert_view_name' => $alert_view_name));
1335
- update_option('gawd_alerts', $gawd_alert_options);
1336
- }
1337
- $saved_alerts = get_option('gawd_alerts');
1338
- if ($saved_alerts) {
1339
- foreach ($saved_alerts as $alert) {
1340
- if (!wp_next_scheduled('gawd_alert_' . $alert['period'])) {
1341
- wp_schedule_event(time(), $alert['period'], 'gawd_alert_' . $alert['period']);
1342
- }
1343
- }
1344
- }
1345
- }
1346
- $gawd_pushover_name = isset($_POST['gawd_pushover_name']) ? sanitize_text_field($_POST['gawd_pushover_name']) : '';
1347
- $gawd_pushover_period = isset($_POST['gawd_pushover_period']) ? sanitize_text_field($_POST['gawd_pushover_period']) : '';
1348
- $gawd_pushover_metric = isset($_POST['gawd_pushover_metric']) ? sanitize_text_field($_POST['gawd_pushover_metric']) : '';
1349
- $gawd_pushover_condition = isset($_POST['gawd_pushover_condition']) ? sanitize_text_field($_POST['gawd_pushover_condition']) : '';
1350
- $gawd_pushover_value = isset($_POST['gawd_pushover_value']) ? intval($_POST['gawd_pushover_value']) : '';
1351
-
1352
- $gawd_pushover_user_keys = isset($_POST['gawd_pushover_user_keys']) ? sanitize_text_field($_POST['gawd_pushover_user_keys']) : '';
1353
- $gawd_pushover_view = isset($_POST['gawd_pushover_view']) ? sanitize_text_field($_POST['gawd_pushover_view']) : '';
1354
- $pushover_view_name = isset($_POST['pushover_view_name']) ? sanitize_text_field($_POST['pushover_view_name']) : '';
1355
- if ($gawd_pushover_name != '' && $gawd_pushover_period != '' && $gawd_pushover_metric != '' && $gawd_pushover_condition != '' && $gawd_pushover_value !== '' && $gawd_pushover_user_keys != '') {
1356
- $saved_pushovers = get_option('gawd_pushovers');
1357
- if ($saved_pushovers) {
1358
- $gawd_pushover_options = array('name' => $gawd_pushover_name, 'period' => $gawd_pushover_period, 'metric' => $gawd_pushover_metric, 'condition' => $gawd_pushover_condition, 'value' => $gawd_pushover_value, 'creation_date' => date('Y-m-d'), 'user_key' => $gawd_pushover_user_keys,'pushover_view' => $gawd_pushover_view, 'pushover_view_name' => $pushover_view_name);
1359
- $saved_pushovers[] = $gawd_pushover_options;
1360
- update_option('gawd_pushovers', $saved_pushovers);
1361
- }
1362
- else {
1363
- $gawd_pushover_options = array(0 => array('name' => $gawd_pushover_name, 'period' => $gawd_pushover_period, 'metric' => $gawd_pushover_metric, 'condition' => $gawd_pushover_condition, 'value' => $gawd_pushover_value, 'creation_date' => date('Y-m-d'), 'user_key' => $gawd_pushover_user_keys,'pushover_view' => $gawd_pushover_view, 'pushover_view_name' => $pushover_view_name));
1364
- update_option('gawd_pushovers', $gawd_pushover_options);
1365
- }
1366
- $saved_pushovers = get_option('gawd_pushovers');
1367
- if ($saved_pushovers) {
1368
-
1369
- foreach ($saved_pushovers as $pushover) {
1370
- $this->gawd_pushover_api($pushover['user_key'], $pushover['metric'], $pushover['condition'], $pushover['value']);
1371
- if(!wp_next_scheduled('gawd_pushover_'.$pushover['period'])){
1372
- wp_schedule_event(time(),$pushover['period'], 'gawd_pushover_'.$pushover['period']) ;
1373
- }
1374
- }
1375
- }
1376
- }
1377
- $gawd_show_in_dashboard = isset($_POST['gawd_show_in_dashboard']) ? sanitize_text_field($_POST['gawd_show_in_dashboard']) : '';
1378
-
1379
- $gawd_permissions = isset($_POST['gawd_permissions']) ? $_POST['gawd_permissions'] : array();
1380
- $gawd_own_project = isset($_POST['gawd_own_project']) ? sanitize_text_field($_POST['gawd_own_project']) : '';
1381
- $site_speed_rate = isset($_POST['site_speed_rate']) ? intval($_POST['site_speed_rate']) : '1';
1382
- $post_page_chart = isset($_POST['post_page_chart']) ? sanitize_text_field($_POST['post_page_chart']) : '';
1383
- $enable_cross_domain = isset($_POST['enable_cross_domain']) ? sanitize_text_field($_POST['enable_cross_domain']) : '';
1384
- $cross_domains = isset($_POST['cross_domains']) ? sanitize_text_field($_POST['cross_domains']) : '';
1385
- $default_date = isset($_POST['default_date']) ? $_POST['default_date'] : 'last_7_days';
1386
- $default_date_format = isset($_POST['default_date_format']) ? $_POST['default_date_format'] : 'ymd_with_week';
1387
- $enable_hover_tooltip = isset($_POST['enable_hover_tooltip']) ? $_POST['enable_hover_tooltip'] : '';
1388
- $gawd_backend_roles = isset($_POST['gawd_backend_roles']) ? ($_POST['gawd_backend_roles']) : array();
1389
- $gawd_frontend_roles = isset($_POST['gawd_frontend_roles']) ? ($_POST['gawd_frontend_roles']) : array();
1390
- $gawd_post_page_roles = isset($_POST['gawd_post_page_roles']) ? ($_POST['gawd_post_page_roles']) : array();
1391
- $exclude_events = isset($_POST['exclude_events']) ? sanitize_text_field($_POST['exclude_events']) : array();
1392
- $gawd_settings_exist = get_option('gawd_settings');
1393
- $gawd_settings_exist['gawd_show_in_dashboard'] = $gawd_show_in_dashboard;
1394
- $gawd_settings_exist['site_speed_rate'] = $site_speed_rate;
1395
- $gawd_settings_exist['post_page_chart'] = $post_page_chart;
1396
- $gawd_settings_exist['enable_cross_domain'] = $enable_cross_domain;
1397
- $gawd_settings_exist['cross_domains'] = $cross_domains;
1398
- $gawd_settings_exist['gawd_backend_roles'] = $gawd_backend_roles;
1399
- $gawd_settings_exist['gawd_frontend_roles'] = $gawd_frontend_roles;
1400
- $gawd_settings_exist['gawd_post_page_roles'] = $gawd_post_page_roles;
1401
- $gawd_settings_exist['default_date'] = $default_date;
1402
- $gawd_settings_exist['default_date_format'] = $default_date_format;
1403
- $gawd_settings_exist['enable_hover_tooltip'] = $enable_hover_tooltip;
1404
- $gawd_settings_exist['exclude_events'] = $exclude_events;
1405
- $gawd_settings_exist['gawd_permissions'] = $gawd_permissions;
1406
- update_option('gawd_settings', $gawd_settings_exist);
1407
- $gawd_filter_name = isset($_POST['gawd_filter_name']) ? sanitize_text_field($_POST['gawd_filter_name']) : '';
1408
- $gawd_filter_type = isset($_POST['gawd_filter_type']) ? sanitize_text_field($_POST['gawd_filter_type']) : '';
1409
- $gawd_filter_value = isset($_POST['gawd_filter_value']) ? $gawd_filter_type == 'GEO_IP_ADDRESS' ? ($_POST['gawd_filter_value']) : sanitize_text_field($_POST['gawd_filter_value']) : '';
1410
- if ($gawd_filter_name != '' && $gawd_filter_type != '' && $gawd_filter_value != '') {
1411
- $gawd_client->add_filter($gawd_filter_name, $gawd_filter_type, $gawd_filter_value);
1412
- }
1413
- add_option("gawd_save_settings",1) ;
1414
- }
1415
- if(get_option('gawd_save_settings') == 1){
1416
- $this->gawd_admin_notice('Your changes have been saved successfully.','success is-dismissible');
1417
- }
1418
- delete_option('gawd_save_settings');
1419
- require_once( 'admin/pages/settings.php' );
1420
- }
1421
- }
1422
-
1423
- public function reset_user_data(){
1424
- delete_option("gawd_credentials");
1425
- $credentials['project_id'] = '115052745574-5vbr7tci4hjkr9clkflmnpto5jisgstg.apps.googleusercontent.com';
1426
- $credentials['project_secret'] = 'wtNiu3c_bA_g7res6chV0Trt';
1427
- update_option('gawd_credentials', $credentials);
1428
- delete_option('gawd_own_project');
1429
- delete_option('gawd_user_data');
1430
-
1431
- }
1432
- public function gawd_display_tracking_page() {
1433
- global $gawd_client, $gawd_user_data;
1434
- $gawd_client = GAWD_google_client::get_instance();
1435
- $gawd_user_data = get_option('gawd_user_data');
1436
- $add_dimension_value = isset($_POST['add_dimension_value']) ? $_POST['add_dimension_value'] : '';
1437
- if(isset($_GET['errorMsg'])){
1438
- self::error_message('error','User does not have sufficient permissions for this account');
1439
- }
1440
- if (isset($_POST['add_property'])) {
1441
- $gawd_account_select = isset($_POST['gawd_account_select']) ? $_POST['gawd_account_select'] : '';
1442
- $gawd_property_name = isset($_POST['gawd_property_name']) ? $_POST['gawd_property_name'] : '';
1443
- if ($gawd_account_select && $gawd_property_name) {
1444
- $err_msg = $gawd_client->add_webproperty($gawd_account_select, $gawd_property_name);
1445
- $redirect_url = admin_url() . 'admin.php?page=gawd_tracking&enableTracking=1';
1446
- if($err_msg){
1447
- $redirect_url .='&errorMsg=1';
1448
- }
1449
- echo '<script>window.location.href="'.$redirect_url.'";</script>';
1450
- }
1451
- }
1452
- if (isset($_POST['lock_property'])) {
1453
- $property = $gawd_client->property_exists();
1454
- $gawd_property_select = $_POST['gawd_property_select'];
1455
- foreach ($property as $property_select) {
1456
- if ($property_select['id'] == $gawd_property_select) {
1457
- $property = $property_select;
1458
- break;
1459
- }
1460
- }
1461
- $gawd_user_data['webPropertyId'] = $property['id'];
1462
- $gawd_user_data['default_webPropertyId'] = $property['id'];
1463
- $gawd_user_data['accountId'] = $property['accountId'];
1464
- $gawd_user_data['default_accountId'] = $property['accountId'];
1465
- $gawd_user_data['gawd_id'] = $property['defaultProfileId'];
1466
- update_option('gawd_user_data', $gawd_user_data);
1467
- }
1468
- if($this->manage_ua_code_selection_tracking() != 'done') {
1469
- $redirect_url = admin_url() . 'admin.php?page=gawd_tracking';
1470
- //echo '<script>window.location.href="'.$redirect_url.'";</script>';
1471
- return;
1472
- }
1473
- if ($add_dimension_value == 'add_dimension_Logged_in') {
1474
- $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1475
- $gawd_client->add_custom_dimension('Logged in', $id);
1476
- $settings = get_option('gawd_settings');
1477
- $optname = 'gawd_custom_dimension_Logged_in';
1478
- $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1479
- update_option('gawd_settings', $settings);
1480
-
1481
- }
1482
- if ($add_dimension_value == 'add_dimension_Post_type') {
1483
- $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1484
- $gawd_client->add_custom_dimension('Post type', $id);
1485
- $settings = get_option('gawd_settings');
1486
- $optname = 'gawd_custom_dimension_Post_type';
1487
- $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1488
- update_option('gawd_settings', $settings);
1489
-
1490
- }
1491
- if ($add_dimension_value == 'add_dimension_Author') {
1492
- $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1493
- $gawd_client->add_custom_dimension('Author', $id);
1494
- $settings = get_option('gawd_settings');
1495
- $optname = 'gawd_custom_dimension_Author';
1496
- $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1497
- update_option('gawd_settings', $settings);
1498
-
1499
- }
1500
- if ($add_dimension_value == 'add_dimension_Category') {
1501
- $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1502
- $gawd_client->add_custom_dimension('Category', $id);
1503
- $settings = get_option('gawd_settings');
1504
- $optname = 'gawd_custom_dimension_Category';
1505
-
1506
- $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1507
- update_option('gawd_settings', $settings);
1508
- }
1509
- if ($add_dimension_value == 'add_dimension_Published_Month') {
1510
- $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1511
- $gawd_client->add_custom_dimension('Published Month', $id);
1512
- $settings = get_option('gawd_settings');
1513
- $optname = 'gawd_custom_dimension_Published_Month';
1514
- $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1515
- update_option('gawd_settings', $settings);
1516
-
1517
- }
1518
- if ($add_dimension_value == 'add_dimension_Published_Year') {
1519
- $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1520
- $gawd_client->add_custom_dimension('Published Year', $id);
1521
- $settings = get_option('gawd_settings');
1522
- $optname = 'gawd_custom_dimension_Published_Year';
1523
- $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1524
- update_option('gawd_settings', $settings);
1525
-
1526
- }
1527
- if ($add_dimension_value == 'add_dimension_Tags') {
1528
- $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1529
- $gawd_client->add_custom_dimension('Tags', $id);
1530
- $settings = get_option('gawd_settings');
1531
- $optname = 'gawd_custom_dimension_Tags';
1532
- $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1533
- update_option('gawd_settings', $settings);
1534
- }
1535
- if (isset($_POST['settings_submit'])) {
1536
- check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
1537
- $gawd_user_data = get_option('gawd_user_data');
1538
- $gawd_file_formats = isset($_POST['gawd_file_formats']) ? sanitize_text_field($_POST['gawd_file_formats']) : '';
1539
- $gawd_anonymize = isset($_POST['gawd_anonymize']) ? sanitize_text_field($_POST['gawd_anonymize']) : '';
1540
- $gawd_tracking_enable = isset($_POST['gawd_tracking_enable']) ? sanitize_text_field($_POST['gawd_tracking_enable']) : '';
1541
- $gawd_outbound = isset($_POST['gawd_outbound']) ? sanitize_text_field($_POST['gawd_outbound']) : '';
1542
- $gawd_enhanced = isset($_POST['gawd_enhanced']) ? sanitize_text_field($_POST['gawd_enhanced']) : '';
1543
- if($add_dimension_value == ''){
1544
- $gawd_cd_Logged_in = isset($_POST['gawd_custom_dimension_Logged_in']) ? sanitize_text_field($_POST['gawd_custom_dimension_Logged_in']) : '';
1545
- $gawd_cd_Post_type = isset($_POST['gawd_custom_dimension_Post_type']) ? sanitize_text_field($_POST['gawd_custom_dimension_Post_type']) : '';
1546
- $gawd_cd_Author = isset($_POST['gawd_custom_dimension_Author']) ? sanitize_text_field($_POST['gawd_custom_dimension_Author']) : '';
1547
- $gawd_cd_Category = isset($_POST['gawd_custom_dimension_Category']) ? sanitize_text_field($_POST['gawd_custom_dimension_Category']) : '';
1548
- $gawd_cd_Published_Month = isset($_POST['gawd_custom_dimension_Published_Month']) ? sanitize_text_field($_POST['gawd_custom_dimension_Published_Month']) : '';
1549
- $gawd_cd_Published_Year = isset($_POST['gawd_custom_dimension_Published_Year']) ? sanitize_text_field($_POST['gawd_custom_dimension_Published_Year']) : '';
1550
- $gawd_cd_Tags = isset($_POST['gawd_custom_dimension_Tags']) ? sanitize_text_field($_POST['gawd_custom_dimension_Tags']) : '';
1551
- $gawd_settings['gawd_custom_dimension_Logged_in'] = $gawd_cd_Logged_in;
1552
- $gawd_settings['gawd_custom_dimension_Post_type'] = $gawd_cd_Post_type;
1553
- $gawd_settings['gawd_custom_dimension_Author'] = $gawd_cd_Author;
1554
- $gawd_settings['gawd_custom_dimension_Category'] = $gawd_cd_Category;
1555
- $gawd_settings['gawd_custom_dimension_Published_Month'] = $gawd_cd_Published_Month;
1556
- $gawd_settings['gawd_custom_dimension_Published_Year'] = $gawd_cd_Published_Year;
1557
- $gawd_settings['gawd_custom_dimension_Tags'] = $gawd_cd_Tags;
1558
- }
1559
- $gawd_excluded_roles = isset($_POST['gawd_excluded_roles']) ? $_POST['gawd_excluded_roles'] : array();
1560
- $gawd_excluded_users = isset($_POST['gawd_excluded_users']) ? $_POST['gawd_excluded_users'] : array();
1561
- $gawd_settings = get_option('gawd_settings');
1562
- $gawd_settings['gawd_file_formats'] = $gawd_file_formats;
1563
- $gawd_settings['gawd_anonymize'] = $gawd_anonymize;
1564
- $gawd_settings['gawd_file_formats'] = $gawd_file_formats;
1565
- $gawd_settings['gawd_tracking_enable'] = $gawd_tracking_enable;
1566
- $gawd_settings['gawd_outbound'] = $gawd_outbound;
1567
- $gawd_settings['gawd_enhanced'] = $gawd_enhanced;
1568
- $gawd_settings['gawd_excluded_roles'] = $gawd_excluded_roles;
1569
- $gawd_settings['gawd_excluded_users'] = $gawd_excluded_users;
1570
- update_option('gawd_settings', $gawd_settings);
1571
- add_option("gawd_save_tracking",1) ;
1572
- }
1573
- if(get_option('gawd_save_tracking') == 1){
1574
- $this->gawd_admin_notice('Your changes have been saved successfully.','success is-dismissible');
1575
- }
1576
- delete_option('gawd_save_tracking');
1577
- $gawd_settings = get_option('gawd_settings');
1578
- if($add_dimension_value != ''){
1579
- $redirect_url = admin_url() . 'admin.php?page=gawd_tracking';
1580
- echo '<script>window.location.href="'.$redirect_url.'";</script>';
1581
- }
1582
- require_once( 'admin/pages/tracking.php' );
1583
- }
1584
-
1585
- public function gawd_my_schedule() {
1586
- $schedules['gawd_weekly'] = array(
1587
- 'interval' => 604800,
1588
- 'display' => __('Every week')
1589
- );
1590
- $schedules['gawd_monthly'] = array(
1591
- 'interval' => 18748800,
1592
- 'display' => __('Every month')
1593
- );
1594
- return $schedules;
1595
- }
1596
-
1597
- public function gawd_pushover_api($user_key, $metric, $condition, $value) {
1598
- $ch = curl_init();
1599
- curl_setopt($ch, CURLOPT_URL, "https://api.pushover.net/1/messages.json");
1600
- curl_setopt($ch, CURLOPT_POSTFIELDS, array(
1601
- "token" => "aJBDhTfhR87EaTzs7wpx1MMKwboBjB",
1602
- "user" => $user_key,
1603
- "message" => 'The ' . $metric . ' less ' . $value));
1604
- // curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
1605
- curl_exec($ch);
1606
- curl_close($ch);
1607
- }
1608
-
1609
- public function gawd_pushover_daily() {
1610
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1611
- $gawd_client = GAWD_google_client::get_instance();
1612
- $pushovers = get_option('gawd_pushovers');
1613
- $data = '';
1614
- $condition = '';
1615
-
1616
- foreach ($pushovers as $pushover) {
1617
- if (isset($pushover['period']) && $pushover['period'] == 'daily') {
1618
- //pls send email if ....
1619
- $date = date('Y-m-d', strtotime('yesterday'));
1620
- $data = $gawd_client->get_data_alert('ga:' . $pushover['metric'], 'date', $date, $date, $pushover['pushover_view']);
1621
- $pushover_condition = $pushover['condition'] == 'greater' ? '>' : '<';
1622
- if (!eval($data . $pushover_condition . $pushover['value'] . ';')) {
1623
- $cond = ' '.$pushover['condition'] . ' than';
1624
- $this->gawd_pushover_api($pushover['user_key'], $pushover['metric'], $pushover['condition'], $pushover['value']);
1625
- }
1626
- }
1627
- }
1628
- }
1629
-
1630
- public function gawd_pushover_weekly() {
1631
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1632
- $gawd_client = GAWD_google_client::get_instance();
1633
- $pushovers = get_option('gawd_pushovers');
1634
- $data = '';
1635
- $condition = '';
1636
- foreach ($pushovers as $pushover) {
1637
- if (isset($pushover['period']) && $pushover['period'] == 'gawd_weekly') {
1638
- //pls send email if ....
1639
- $start_date = date('Y-m-d', strtotime('last week -1 day'));
1640
- $end_date = date('l') != 'Sunday' ? date('Y-m-d',strtotime('last sunday -1 day')) : date('Y-m-d', strtotime('-1 day'));
1641
- $data = $gawd_client->get_data_alert('ga:' . $pushover['metric'], 'date', $start_date, $end_date, $pushover['pushover_view']);
1642
- $pushover_condition = $pushover['condition'] == 'greater' ? '>' : '<';
1643
- if (!eval($data . $pushover_condition . $pushover['value'] . ';')) {
1644
- $cond = ' '.$pushover['condition'] . ' than';
1645
- $this->gawd_pushover_api($pushover['user_key'], $pushover['metric'], $pushover['condition'], $pushover['value']);
1646
- }
1647
- }
1648
- }
1649
- }
1650
-
1651
- public function gawd_pushover_monthly() {
1652
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1653
- $gawd_client = GAWD_google_client::get_instance();
1654
- $pushovers = get_option('gawd_pushovers');
1655
- $data = '';
1656
- $condition = '';
1657
- foreach ($pushovers as $pushover) {
1658
- if (isset($pushover['period']) && $pushover['period'] == 'gawd_monthly') {
1659
- //pls send email if ....
1660
- $end_date = date('Y-m-t', strtotime('last month'));
1661
- $start_date = date('Y-m-01', strtotime('last month'));
1662
- $data = $gawd_client->get_data_alert('ga:' . $pushover['metric'], 'date', $start_date, $end_date, $pushover['pushover_view']);
1663
- $pushover_condition = $pushover['condition'] == 'greater' ? '>' : '<';
1664
- if (!eval($data . $pushover_condition . $pushover['value'] . ';')) {
1665
- $cond = ' '.$pushover['condition'] . ' than';
1666
- $this->gawd_pushover_api($pushover['user_key'], $pushover['metric'], $pushover['condition'], $pushover['value']);
1667
- }
1668
- }
1669
- }
1670
- }
1671
-
1672
- public function gawd_alert_daily() {
1673
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1674
- $gawd_client = GAWD_google_client::get_instance();
1675
- $alerts = get_option('gawd_alerts');
1676
- $data = '';
1677
- $condition = '';
1678
- $email_from = get_option('admin_email');
1679
- foreach ($alerts as $alert) {
1680
- if (isset($alert['period']) && $alert['period'] == 'daily') {
1681
- //pls send email if ....
1682
- $date = date('Y-m-d', strtotime('yesterday'));
1683
- $data = $gawd_client->get_data_alert('ga:' . $alert['metric'], 'date', $date, $date, $alert['alert_view']);
1684
- $alert_condition = $alert['condition'] == 'greater' ? '>' : '<';
1685
- $color_condition = $alert['condition'] == 'greater' ? 'rgb(157, 207, 172)' : 'rgb(251, 133, 131)';
1686
- if (!eval($data . $alert_condition . $alert['value'] . ';')) {
1687
- $cond = ' '.$alert['condition'] . ' than';
1688
- $headers = array();
1689
- $headers[] = 'From: <' . $email_from . '>';
1690
- $headers[] = 'Content-Type: text/html';
1691
- $content = '<div style="font-family: sans-serif;width:100%;height:50px;background-color:#FB8583;font-size:20px;color:#fff;margin-bottom:20px;text-align:center;line-height:50px">Google Analytics WD Alert!</div><p style="color:#808080;text-align: center;font-size: 26px;font-family: sans-serif;">' . preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $alert['metric'])))). ' in <a style="text-decoration:none;color:rgba(124,181,216,1);font-family: sans-serif;" href="' . $alert["alert_view_name"] . '" target="_blank">' . $alert["alert_view_name"] . '</a> are <span style="color:'.$color_condition.'">' . $cond . '</span></p><p style="color:rgba(124,181,216,1);font-size: 26px;font-family: sans-serif; text-align: center;">' . $alert['value'] . '</p>';
1692
- wp_mail($alert['emails'], 'Analytics Alert',$content, $headers);
1693
- }
1694
- }
1695
- }
1696
- }
1697
- public function gawd_alert_weekly() {
1698
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1699
- $gawd_client = GAWD_google_client::get_instance();
1700
- $alerts = get_option('gawd_alerts');
1701
- $data = '';
1702
- $condition = '';
1703
- $email_from = get_option('admin_email');
1704
- foreach ($alerts as $alert) {
1705
- if (isset($alert['period']) && $alert['period'] == 'gawd_weekly') {
1706
- //pls send email if ....
1707
- $start_date = date('Y-m-d', strtotime('last week -1 day'));
1708
- $end_date = date('l') != 'Sunday' ? date('Y-m-d',strtotime('last sunday -1 day')) : date('Y-m-d', strtotime('-1 day'));
1709
- $data = $gawd_client->get_data_alert('ga:' . $alert['metric'], 'date', $start_date, $end_date, $alert['alert_view']);
1710
- $alert_condition = $alert['condition'] == 'greater' ? '>' : '<';
1711
- if (!eval($data . $alert_condition . $alert['value'] . ';')) {
1712
- $cond = ' '.$alert['condition'] . ' than';
1713
- $headers = array();
1714
- $headers[] = 'From: <' . $email_from . '>';
1715
- $headers[] = 'Content-Type: text/html';
1716
- $content = '<div style="font-family: sans-serif;width:100%;height:50px;background-color:#FB8583;font-size:20px;color:#fff;margin-bottom:20px;text-align:center;line-height:50px">Google Analytics WD Alert!</div><p style="color:#808080;text-align: center;font-size: 26px;font-family: sans-serif;">' . preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $alert['metric'])))). ' in <a style="text-decoration:none;color:rgba(124,181,216,1);font-family: sans-serif;" href="' . $alert["alert_view_name"] . '" target="_blank">' . $alert["alert_view_name"] . '</a> are <span style="color:'.$color_condition.'">' . $cond . '</span></p><p style="color:rgba(124,181,216,1);font-size: 26px;font-family: sans-serif; text-align: center;">' . $alert['value'] . '</p>';
1717
- wp_mail($alert['emails'], 'Analytics Alert',$content, $headers);
1718
- }
1719
- }
1720
- }
1721
- }
1722
-
1723
- public function gawd_alert_monthly() {
1724
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1725
- $gawd_client = GAWD_google_client::get_instance();
1726
- $alerts = get_option('gawd_alerts');
1727
- $data = '';
1728
- $email_from = get_option('admin_email');
1729
- foreach ($alerts as $alert) {
1730
- if (isset($alert['period']) && $alert['period'] == 'gawd_monthly') {
1731
- //pls send email if ....
1732
- $end_date = date('Y-m-t', strtotime('last month'));
1733
- $start_date = date('Y-m-01', strtotime('last month'));
1734
- $data = $gawd_client->get_data_alert('ga:' . $alert['metric'], 'date', $start_date, $end_date, $alert['alert_view']);
1735
- $alert_condition = $alert['condition'] == 'greater' ? '>' : '<';
1736
- if (!eval($data . $alert_condition . $alert['value'] . ';')) {
1737
- $cond = ' '.$alert['condition'] . ' than';
1738
- $headers = array();
1739
- $headers[] = 'From: <' . $email_from . '>';
1740
- $headers[] = 'Content-Type: text/html';
1741
- $content = '<div style="font-family: sans-serif;width:100%;height:50px;background-color:#FB8583;font-size:20px;color:#fff;margin-bottom:20px;text-align:center;line-height:50px">Google Analytics WD Alert!</div><p style="color:#808080;text-align: center;font-size: 26px;font-family: sans-serif;">' . preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $alert['metric'])))). ' in <a style="text-decoration:none;color:rgba(124,181,216,1);font-family: sans-serif;" href="' . $alert["alert_view_name"] . '" target="_blank">' . $alert["alert_view_name"] . '</a> are <span style="color:'.$color_condition.'">' . $cond . '</span></p><p style="color:rgba(124,181,216,1);font-size: 26px;font-family: sans-serif; text-align: center;">' . $alert['value'] . '</p>';
1742
- wp_mail($alert['emails'], 'Analytics Alert',$content, $headers);
1743
- }
1744
- }
1745
- }
1746
- }
1747
-
1748
- public function wd_dashboard_widget() {
1749
- global $gawd_client, $gawd_user_data;
1750
- $gawd_client = GAWD_google_client::get_instance();
1751
- $profiles = $gawd_client->get_profiles();
1752
- $gawd_user_data = get_option('gawd_user_data');
1753
- if(isset($_POST['gawd_id'])){
1754
- $gawd_user_data['gawd_id'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
1755
- foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
1756
- foreach ($web_property as $profile) {
1757
- if ($profile['id'] == $gawd_user_data['gawd_id']) {
1758
- $gawd_user_data['web_property_name'] = $web_property_name;
1759
- $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
1760
- $gawd_user_data['accountId'] = $profile['accountId'];
1761
- }
1762
- }
1763
- }
1764
- $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
1765
- update_option('gawd_user_data', $gawd_user_data);
1766
- }
1767
- require_once( 'admin/pages/dashboard_widget.php' );
1768
- }
1769
-
1770
- public function google_analytics_wd_dashboard_widget() {
1771
- $gawd_settings = get_option('gawd_settings');
1772
- $gawd_backend_roles = isset($gawd_settings['gawd_backend_roles']) ? $gawd_settings['gawd_backend_roles'] : array();
1773
- $roles = $this->get_current_user_role();
1774
-
1775
- if (isset($gawd_settings['gawd_show_in_dashboard']) && $gawd_settings['gawd_show_in_dashboard'] == 'on') {
1776
- if (in_array($roles, $gawd_backend_roles) || current_user_can('manage_options')) {
1777
- wp_add_dashboard_widget('wd_dashboard_widget', 'WD Google Analytics', array($this, 'wd_dashboard_widget'));
1778
- }
1779
- }
1780
- }
1781
-
1782
- public function show_data($params = array()) {
1783
- /* if (isset($_REQUEST['security'])) {
1784
- check_ajax_referer('gawd_admin_page_nonce', 'security');
1785
- } else {
1786
- check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
1787
- } */
1788
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1789
- $return = true;
1790
- if ($params == '') {
1791
- $params = $_POST;
1792
- $return = false;
1793
- }
1794
- $gawd_client = GAWD_google_client::get_instance();
1795
- $start_date = isset($params["start_date"]) && $params["start_date"] != '' ? $params["start_date"] : date('Y-m-d', strtotime('-7 days'));
1796
- $end_date = isset($params["end_date"]) && $params["end_date"] != '' ? $params["end_date"] : date('Y-m-d');
1797
- $metric = isset($params["metric"]) ? $params["metric"] : 'ga:sessions';
1798
- $metric = is_array($metric) ? count($metric) > 1 ? implode(",", $metric) : $metric[0] : $metric;
1799
- $dimension = isset($params["dimension"]) ? $params["dimension"] : 'date';
1800
-
1801
- $country_filter = isset($params["country_filter"]) ? $params["country_filter"] : '';
1802
- $geo_type = isset($params["geo_type"]) ? $params["geo_type"] : '';
1803
- $filter_type = isset($params["filter_type"]) && $params["filter_type"] != '' ? $params["filter_type"] : '';
1804
- $custom = isset($params["custom"]) && $params["custom"] != '' ? $params["custom"] : '';
1805
- $same_dimension = $dimension;
1806
-
1807
- $dimension = $filter_type != '' && $dimension == 'date' ? $filter_type : $dimension;
1808
- if ($dimension == 'week' || $dimension == 'month') {
1809
- $same_dimension = $dimension;
1810
- }
1811
-
1812
-
1813
- $timezone = isset($params["timezone"]) && $params["timezone"] != '' ? $params["timezone"] : 0;
1814
- if ($dimension == 'pagePath' || $dimension == 'PagePath' || $dimension == 'landingPagePath' || $dimension == 'LandingPagePath') {
1815
- if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date)) {
1816
- $grid_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1817
- } else {
1818
- $grid_data = $gawd_client->get_page_data($dimension, $start_date, $end_date, $timezone);
1819
- }
1820
- if ($return) {
1821
- return $grid_data;
1822
- }
1823
- echo $grid_data;
1824
- die();
1825
- }
1826
- elseif ($dimension == 'goals') {
1827
- if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date)) {
1828
- $goal_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1829
- } else {
1830
- $goal_data = $gawd_client->get_goal_data('date', $start_date, $end_date, $timezone,$same_dimension);
1831
- }
1832
- if ($return) {
1833
- return $goal_data;
1834
- }
1835
- echo $goal_data;
1836
- die();
1837
- }
1838
- elseif (($dimension == 'region' || $dimension == 'city') || ($dimension == 'Region' || $dimension == 'City')) {
1839
- if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $country_filter . '-' . $start_date . '-' . $end_date)) {
1840
- $chart_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $country_filter . '-' . $start_date . '-' . $end_date);
1841
- } else {
1842
-
1843
- $chart_data = $gawd_client->get_country_data($metric, $dimension, $start_date, $end_date, $country_filter, $geo_type, $timezone);
1844
- }
1845
- if ($return) {
1846
- return $chart_data;
1847
- }
1848
- echo $chart_data;
1849
- die();
1850
- }
1851
- else {
1852
- if($custom != ''){
1853
- $chart_data = $gawd_client->get_data($metric, $dimension, $start_date, $end_date, $filter_type, $timezone, $same_dimension);
1854
- }
1855
- else{
1856
- if($dimension == 'siteSpeed'){
1857
- if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $same_dimension . '_' . $filter_type . '-' . $start_date . '-' . $end_date)) {
1858
- $chart_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1859
- } else {
1860
- $chart_data = $gawd_client->get_data($metric, $dimension, $start_date, $end_date, $filter_type, $timezone, $same_dimension);
1861
- }
1862
- if ($return) {
1863
- return $chart_data;
1864
- }
1865
- }
1866
- else{
1867
-
1868
- /* if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date)) {
1869
- $chart_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1870
- } */
1871
- //else {
1872
-
1873
- $chart_data = $gawd_client->get_data($metric, $dimension, $start_date, $end_date, $filter_type, $timezone, $same_dimension);
1874
- //}
1875
- if ($return) {
1876
- return $chart_data;
1877
- }
1878
- }
1879
- }
1880
- echo $chart_data;
1881
- die();
1882
- }
1883
- }
1884
-
1885
- public function show_data_compact() {
1886
- check_ajax_referer('gawd_admin_page_nonce', 'security');
1887
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1888
- $gawd_client = GAWD_google_client::get_instance();
1889
- $start_date = isset($_POST["start_date"]) && $_POST["start_date"] != '' ? $_POST["start_date"] : date('Y-m-d', strtotime('-30 days'));
1890
- $end_date = isset($_POST["end_date"]) && $_POST["end_date"] != '' ? $_POST["end_date"] : date('Y-m-d');
1891
- $metric = isset($_POST["metric"]) ? $_POST["metric"] : 'sessions';
1892
- $metric = is_array($metric) ? count($metric) > 1 ? implode(",", $metric) : $metric[0] : 'ga:' . $metric;
1893
- $dimension = isset($_POST["dimension"]) ? $_POST["dimension"] : 'date';
1894
- $timezone = isset($_POST["timezone"]) ? $_POST["timezone"] : 0;
1895
- if (get_transient('gawd-compact-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date)) {
1896
- $chart_data = get_transient('gawd-compact-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1897
- } else {
1898
- $chart_data = $gawd_client->get_data_compact($metric, $dimension, $start_date, $end_date, $timezone);
1899
- }
1900
- echo $chart_data;
1901
- die();
1902
- }
1903
-
1904
- public function show_page_post_data() {
1905
- check_ajax_referer('gawd_admin_page_nonce', 'security');
1906
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1907
- $gawd_client = GAWD_google_client::get_instance();
1908
- $start_date = isset($_POST["start_date"]) && $_POST["start_date"] != '' ? $_POST["start_date"] : date('Y-m-d', strtotime('-30 days'));
1909
- $end_date = isset($_POST["end_date"]) && $_POST["end_date"] != '' ? $_POST["end_date"] : date('Y-m-d');
1910
- $metric = isset($_POST["metric"]) ? $_POST["metric"] : 'ga:sessions';
1911
- $metric = is_array($metric) ? count($metric) > 1 ? implode(",", $metric) : $metric[0] : $metric;
1912
- $dimension = isset($_POST["dimension"]) ? $_POST["dimension"] : 'date';
1913
- $timezone = isset($_POST["timezone"]) ? $_POST["timezone"] : 0;
1914
- $filter = isset($_POST["filter"]) ? substr($_POST["filter"], 1) : '';
1915
- $chart = isset($_POST["chart"]) ? $_POST["chart"] : '';
1916
- $chart_data = get_transient('gawd-page-post-' . $gawd_client->get_profile_id() . '-' . $filter . '-' . '-' . $dimension . '-' . $start_date . '-' . $end_date. '-' . $chart);
1917
- if (!$chart_data) {
1918
- $chart_data = $gawd_client->get_post_page_data($metric, $dimension, $start_date, $end_date, $filter, $timezone, $chart);
1919
- }
1920
- echo $chart_data;
1921
- die();
1922
- }
1923
-
1924
- public function get_realtime() {
1925
- check_ajax_referer('gawd_admin_page_nonce', 'security');
1926
- require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1927
- $gawd_client = GAWD_google_client::get_instance();
1928
- $chart_data = get_transient('gawd-real' . $gawd_client->get_profile_id());
1929
- if (!$chart_data) {
1930
- $chart_data = $gawd_client->gawd_realtime_data();
1931
- }
1932
- return $chart_data;
1933
- }
1934
-
1935
- /**
1936
- * Checks if the protocol is secure.
1937
- *
1938
- * @return boolean
1939
- */
1940
- public static function is_ssl() {
1941
- if (isset($_SERVER['HTTPS'])) {
1942
- if ('on' == strtolower($_SERVER['HTTPS']))
1943
- return true;
1944
- if ('1' == $_SERVER['HTTPS'])
1945
- return true;
1946
- } elseif (isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] )) {
1947
- return true;
1948
- }
1949
- return false;
1950
- }
1951
-
1952
- /**
1953
- * Returns the Singleton instance of this class.
1954
- *
1955
- * @return GAWD The Singleton instance.
1956
- */
1957
- public static function get_instance() {
1958
- if (null === static::$instance) {
1959
- static::$instance = new static();
1960
- }
1961
- return static::$instance;
1962
- }
1963
-
1964
- /**
1965
- * Private clone method to prevent cloning of the instance of the
1966
- * Singleton instance.
1967
- *
1968
- * @return void
1969
- */
1970
- private function __clone() {
1971
-
1972
- }
1973
-
1974
- /**
1975
- * Private unserialize method to prevent unserializing of the Singleton
1976
- * instance.
1977
- *
1978
- * @return void
1979
- */
1980
- private function __wakeup() {
1981
-
1982
- }
1983
-
1984
- public static function add_dashboard_menu() {
1985
- $get_custom_reports = get_option('gawd_custom_reports');
1986
- if (!$get_custom_reports) {
1987
- $custom_report = array();
1988
- } else {
1989
- foreach ($get_custom_reports as $name => $report) {
1990
- $custom_report['custom_report_' . $name] = __($name, "gawd");
1991
- }
1992
- }
1993
- $tabs = array(
1994
- "general" => array(
1995
- "title" => __("Audience", "gawd"),
1996
- "childs" => array(),
1997
- "desc" => "Report of your website audience. Provides details about new and returning users of your website, sessions, bounces, pageviews and session durations."
1998
- ),
1999
- "realtime" => array(
2000
- "title" => __("Real Time", "gawd"),
2001
- "childs" => array(),
2002
- "desc" => "Real Time statistics show the number of active users currently visiting your website pages."
2003
- ),
2004
- "demographics" => array(
2005
- "title" => __("Demographics", "gawd"),
2006
- "childs" => array(
2007
- "userGender" => __("User Gender", "gawd"),
2008
- "userAge" => __("User Age", "gawd")
2009
- ),
2010
- "desc" => "Demographics display tracking statistics of your website users based on their age and gender. "
2011
-
2012
- ),
2013
- "interests" => array(
2014
- "title" => __("Interests", "gawd"),
2015
- "childs" => array(
2016
- "inMarket" => __("In-Market Segment", "gawd"),
2017
- "affinityCategory" => __("Affinity Category", "gawd"),
2018
- "otherCategory" => __("Other Category", "gawd")
2019
- ),
2020
- "desc" => "Provides tracking information about site users depending on Affinity Categories (e.g. Music Lovers or Mobile Enthusiasts), In-Market Segments (based on online product purchase interests) and Other Categories (most specific identification, for example, tennis lovers among Sports Fans)."
2021
- ),
2022
- "geo" => array(
2023
- "title" => __("GEO", "gawd"),
2024
- "childs" => array(
2025
- "location" => __("Location", "gawd"),
2026
- "language" => __("Language", "gawd")
2027
- ),
2028
- "desc" => "Geo-identifier report is built from interactions of location (countries, cities) and language of your website users."
2029
- ),
2030
- "behavior" => array(
2031
- "title" => __("Behavior", "gawd"),
2032
- "childs" => array(
2033
- "behaviour" => __("New vs Returning", "gawd"),
2034
- "engagement" => __("Engagement", "gawd")
2035
- ),
2036
- "desc" => "Compares number of New visitors and Returning users of your website in percents. You can check the duration of sessions with Engagement report."
2037
- ),
2038
- "technology" => array(
2039
- "title" => __("Technology", "gawd"),
2040
- "childs" => array(
2041
- "os" => __("OS", "gawd"),
2042
- "browser" => __("Browser", "gawd")
2043
- ),
2044
- "desc" => "Identifies tracking of the site based on operating systems and browsers visitors use."
2045
- ),
2046
- "mobile" => array(
2047
- "title" => __("Mobile", "gawd"),
2048
- "childs" => array(
2049
- "device_overview" => __("Overview", "gawd"),
2050
- "devices" => __("Devices", "gawd")
2051
- ),
2052
- "desc" => "Shows statistics of mobile and desktop devices visitors have used while interacting with your website."
2053
- ),
2054
- "custom" => array(
2055
- "title" => __("Custom Dimensions", "gawd"),
2056
- "childs" => array(),
2057
- "desc" => "Set up Custom Dimensions based on Users, Post type, Author, Category, Publication date and Tags in Custom Dimensions page, and view their report in this tab."
2058
- ),
2059
- "trafficSource" => array(
2060
- "title" => __("Traffic Source", "gawd"),
2061
- "childs" => array(),
2062
- "desc" => "Displays overall graph of traffic sources directing to your website."
2063
- ),
2064
- "adWords" => array(
2065
- "title" => __("AdWords", "gawd"),
2066
- "childs" => array(),
2067
- "desc" => "If your website is registered on Google AdWords, you can link its Google Analytics to AdWords, and gather relevant tracking information with this report."
2068
- ),
2069
- /* "pagePath" => array(
2070
- "title" => __("Pages", "gawd"),
2071
- "childs" => array(),
2072
- "desc" => "Pages report table will provide you information about Bounces, Entrances, Pageviews, Unique Pageviews, time spent on pages, Exits and Average page loading time."
2073
- ), */
2074
- "siteContent" => array(
2075
- "title" => __("Site Content", "gawd"),
2076
- "childs" => array(
2077
- "pagePath" => __("All Pages", "gawd"),
2078
- "landingPagePath" => __("Landing Pages", "gawd"),
2079
- ),
2080
- "desc" => "Pages report table will provide you information about Bounces, Entrances, Pageviews, Unique Pageviews, time spent on pages, Exits and Average page loading time."
2081
- ),
2082
- "siteSpeed" => array(
2083
- "title" => __("Site Speed", "gawd"),
2084
- "childs" => array(),
2085
- "desc" => "Shows the average load time of your website users experienced during specified date range."
2086
- ),
2087
- "events" => array(
2088
- "title" => __("Events", "gawd"),
2089
- "childs" => array(
2090
- "eventsLabel" => __("Events by Label", "gawd"),
2091
- "eventsAction" => __("Events by Action", "gawd"),
2092
- "eventsCategory" => __("Events by Category", "gawd")
2093
- ),
2094
- "desc" => "Displays the report based on Events you set up on Google Analytics of your website. Graphs are built based on Event Labels, Categories and Actions."
2095
- ),
2096
- "goals" => array(
2097
- "title" => __("Goals", "gawd"),
2098
- "childs" => array(),
2099
- "desc" => "Set Goals from Goal Management and review their Google Analytics reports under this tab."
2100
- ),
2101
- "ecommerce" => array(
2102
- "title" => __("Ecommerce", "gawd"),
2103
- "childs" => array(
2104
- "daysToTransaction" => __("TIme to Purchase", "gawd"),
2105
- "transactionId" => __("Transaction ID", "gawd"),
2106
- "sales_performance" => __("Sales Performance", "gawd"),
2107
- "productSku" => __("Product Sku", "gawd"),
2108
- "productCategory" => __("Product Category ", "gawd"),
2109
- "productName" => __("Product Name", "gawd"),
2110
- ),
2111
- "desc" => "Check sales statistics of your website identified by revenues, transactions, products and performance."
2112
- ),
2113
- "adsense" => array(
2114
- "title" => __("AdSense", "gawd"),
2115
- "childs" => array(),
2116
- "desc" => "Link your Google Analytics and AdSense accounts from Google Analytics Admin setting and keep track of AdSense tracking under this report."
2117
- ),
2118
- "customReport" => array(
2119
- "title" => __("Custom Report", "gawd"),
2120
- "childs" => $custom_report,
2121
- "desc" => "Add Custom Reports from any metric and dimension in Custom Reports page, and view relevant Google Analytics tracking information in this tab."
2122
- ),
2123
- );
2124
- update_option('gawd_menu_items', $tabs);
2125
- }
2126
- public function remove_zoom_message(){
2127
- check_ajax_referer('gawd_admin_page_nonce', 'security');
2128
- $got_it = isset($_REQUEST["got_it"]) ? sanitize_text_field($_REQUEST["got_it"]) : '';
2129
- if($got_it != ''){
2130
- add_option('gawd_zoom_message',$got_it);
2131
- }
2132
- }
2133
- }
1
+ <?php
2
+
3
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
4
+
5
+ class GAWD {
6
+
7
+ /**
8
+ * @var GAWD The reference to Singleton instance of this class
9
+ */
10
+ private static $instance;
11
+ private $project_client_id = null;
12
+ private $project_client_secret = null;
13
+ public $redirect_uri = "urn:ietf:wg:oauth:2.0:oob";
14
+
15
+ /**
16
+ * Protected constructor to prevent creating a new instance of the
17
+ * Singleton via the `new` operator from outside of this class.
18
+ */
19
+ protected function __construct() {
20
+
21
+ if(isset($_POST["reset_data"]) && $_POST["reset_data"] != ''){
22
+ $this->reset_user_data();
23
+ }
24
+ add_action('admin_enqueue_scripts', array($this, 'gawd_check_id'));
25
+ add_action('admin_notices', array($this, 'upgrade_pro'));
26
+
27
+ add_action('admin_menu', array($this, 'gawd_add_menu'));
28
+ add_action('admin_enqueue_scripts', array($this, 'gawd_enqueue_scripts'));
29
+ add_action('wp_enqueue_scripts', array($this, 'gawd_front_scripts'));
30
+ add_action('wp_ajax_gawd_auth', array($this, 'gawd_auth'));
31
+ add_action('wp_ajax_create_pdf_file', array($this, 'create_pdf_file'));
32
+ add_action('wp_ajax_create_csv_file', array($this, 'create_csv_file'));
33
+ add_action('wp_ajax_show_data', array($this, 'show_data'));
34
+ add_action('wp_ajax_remove_zoom_message', array($this, 'remove_zoom_message'));
35
+ add_action('wp_ajax_show_page_post_data', array($this, 'show_page_post_data'));
36
+ add_action('wp_ajax_show_data_compact', array($this, 'show_data_compact'));
37
+ add_action('wp_ajax_get_realtime', array($this, 'get_realtime'));
38
+ add_action('wp_dashboard_setup', array($this, 'google_analytics_wd_dashboard_widget'));
39
+ add_action('admin_menu', array($this, 'overview_date_meta'));
40
+ add_filter('cron_schedules', array($this, 'gawd_my_schedule'));
41
+ add_action('admin_init', array($this, 'gawd_export'));
42
+ add_action('gawd_pushover_daily', array($this, 'gawd_pushover_daily'));
43
+ add_action('gawd_pushover_gawd_weekly', array($this, 'gawd_pushover_weekly'));
44
+ add_action('gawd_pushover_gawd_monthly', array($this, 'gawd_pushover_monthly'));
45
+ add_action('gawd_alert_daily', array($this, 'gawd_alert_daily'));
46
+ add_action('gawd_alert_gawd_monthly', array($this, 'gawd_alert_monthly'));
47
+ add_action('gawd_alert_gawd_weekly', array($this, 'gawd_alert_weekly'));
48
+ add_action('gawd_email_daily', array($this, 'gawd_daily_email'), 0);
49
+ add_action('gawd_email_gawd_weekly', array($this, 'gawd_weekly_email'));
50
+ add_action('gawd_email_gawd_monthly', array($this, 'gawd_monthly_email'));
51
+ //add_action('init', array($this, 'gawd_daily_email'));
52
+ add_action('wp_head', array($this, 'gawd_tracking_code'), 99);
53
+ $gawd_settings = get_option('gawd_settings');
54
+ $gawd_post_page_roles = isset($gawd_settings['gawd_post_page_roles']) ? $gawd_settings['gawd_post_page_roles'] : array();
55
+ $roles = $this->get_current_user_role();
56
+ if((isset($gawd_settings['gawd_tracking_enable']) && $gawd_settings['gawd_tracking_enable'] == 'on') && (isset($gawd_settings['post_page_chart']) && $gawd_settings['post_page_chart'] != '') && (in_array($roles, $gawd_post_page_roles) || current_user_can('manage_options'))){
57
+ add_filter('manage_posts_columns', array($this, 'gawd_add_columns'));
58
+ // Populate custom column in Posts List
59
+ add_action('manage_posts_custom_column', array($this, 'gawd_add_icons'), 10, 2);
60
+ // Add custom column in Pages List
61
+ add_filter('manage_pages_columns', array($this, 'gawd_add_columns'));
62
+ // Populate custom column in Pages List
63
+ add_action('manage_pages_custom_column', array($this, 'gawd_add_icons'), 10, 2);
64
+ add_action('add_meta_boxes', array($this, 'gawd_add_custom_box'));
65
+ add_action('admin_bar_menu', array($this, 'report_adminbar'), 999);
66
+ }
67
+
68
+
69
+ $this->update_credentials();
70
+ $credentials = get_option('gawd_credentials');
71
+
72
+
73
+ if (is_array($credentials)) {
74
+ $this->set_project_client_id($credentials['project_id']);
75
+ $this->set_project_client_secret($credentials['project_secret']);
76
+ } else {
77
+ //send error
78
+ return;
79
+ }
80
+
81
+ }
82
+
83
+ function get_current_user_role() {
84
+ global $wp_roles;
85
+ $current_user = wp_get_current_user();
86
+ $roles = $current_user->roles;
87
+ $role = array_shift($roles);
88
+ return $role;
89
+ }
90
+
91
+ function report_adminbar($wp_admin_bar) {
92
+ /* @formatter:off */
93
+ $gawd_settings = get_option('gawd_settings');
94
+ $gawd_frontend_roles = isset($gawd_settings['gawd_frontend_roles']) ? $gawd_settings['gawd_frontend_roles'] : array();
95
+ $roles = $this->get_current_user_role();
96
+ if (((in_array($roles, $gawd_frontend_roles) || current_user_can('manage_options')) && !is_admin()) && $gawd_settings['post_page_chart'] != '') {
97
+ $id = get_the_ID();
98
+ $uri_parts = explode('/', get_permalink($id), 4);
99
+ if ($uri_parts[0] != '') {
100
+ if (isset($uri_parts[3])) {
101
+ $uri = '/' . $uri_parts[3];
102
+ }
103
+ $uri = explode('/', $uri);
104
+ end($uri);
105
+ $key = key($uri);
106
+ $uri = '/' . $uri[$key - 1];
107
+ $filter = rawurlencode(rawurldecode($uri));
108
+
109
+ $args = array('id' => 'gawd',
110
+ 'title' => '<span data-url="' . $filter . '" class="ab-icon"></span><span class="">' . __("Analytics WD", 'gawd') . '</span>',
111
+ 'href' => '#1',
112
+ );
113
+ /* @formatter:on */
114
+ $wp_admin_bar->add_node($args);
115
+ }
116
+ }
117
+ }
118
+
119
+ public function update_credentials() {
120
+ //check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
121
+ if ($_POST) {
122
+ $gawd_own_project = isset($_POST['gawd_own_project']) ? $_POST['gawd_own_project'] : '';
123
+ $gawd_own_client_id = isset($_POST['gawd_own_client_id']) ? $_POST['gawd_own_client_id'] : '';
124
+ $gawd_own_client_secret = isset($_POST['gawd_own_client_secret']) ? $_POST['gawd_own_client_secret'] : '';
125
+ $gawd_credentials['project_id'] = $gawd_own_client_id;
126
+ $gawd_credentials['project_secret'] = $gawd_own_client_secret;
127
+ if ($gawd_own_project && $gawd_own_client_id != '' && $gawd_own_client_secret != '') {
128
+ update_option('gawd_credentials', $gawd_credentials);
129
+ delete_option('gawd_user_data');
130
+ add_option('gawd_own_project' , 1);
131
+ }
132
+ }
133
+ }
134
+
135
+ public function set_project_client_id($id) {
136
+ $this->project_client_id = $id;
137
+ }
138
+
139
+ public function get_project_client_id() {
140
+ return $this->project_client_id;
141
+ }
142
+
143
+ public function set_project_client_secret($secret) {
144
+ $this->project_client_secret = $secret;
145
+ }
146
+
147
+ public function get_project_client_secret() {
148
+ return $this->project_client_secret;
149
+ }
150
+
151
+ function gawd_check_id() {
152
+ global $gawd_user_data;
153
+ $current_user = get_current_screen();
154
+
155
+ if (strpos($current_user->base, 'gawd')) {
156
+ $gawd_user_data = get_option('gawd_user_data');
157
+ if (!isset($gawd_user_data['refresh_token']) || ($gawd_user_data['refresh_token'] == '')) {
158
+ if (strpos($current_user->base, 'gawd_settings') === false && strpos($current_user->base, 'gawd_uninstall') === false) {
159
+ wp_redirect(admin_url() . 'admin.php?page=gawd_settings');
160
+ }
161
+ }
162
+ }
163
+ }
164
+
165
+ function gawd_add_custom_box() {
166
+ $screens = array('post', 'page');
167
+ foreach ($screens as $screen)
168
+ add_meta_box('gawd_page_post_meta', 'Sessions in month', array($this, 'gawd_add_custom_box_callback'), $screen, 'normal');
169
+ }
170
+
171
+ function gawd_add_custom_box_callback() {
172
+ require_once( 'admin/post_page_view.php' );
173
+ }
174
+
175
+ public function gawd_add_icons($column, $id) {
176
+ if ($column != 'gawd_stats') {
177
+ return;
178
+ }
179
+ $uri_parts = explode('/', get_permalink($id), 4);
180
+ if (isset($uri_parts[3])) {
181
+ $uri = '/' . $uri_parts[3];
182
+ }
183
+ $uri = explode('/', $uri);
184
+ end($uri);
185
+ $key = key($uri);
186
+ $uri = '/' . $uri[$key - 1];
187
+ $filter = rawurlencode(rawurldecode($uri));
188
+ echo '<a id="gawd-' . $id . '" class="gawd_page_post_stats" title="' . get_the_title($id) . '" href="#' . $filter . '"><img src="' . GAWD_URL . '/assets/back_logo.png"</a>';
189
+ }
190
+
191
+ public function gawd_add_columns($columns) {
192
+ return array_merge($columns, array('gawd_stats' => __('Analytics WD', 'gawd')));
193
+ }
194
+
195
+ public static function gawd_roles($access_level, $tracking = false) {
196
+ if (is_user_logged_in() && isset($access_level)) {
197
+ $current_user = wp_get_current_user();
198
+ $roles = (array) $current_user->roles;
199
+ if (( current_user_can('manage_options') ) && !$tracking) {
200
+ return true;
201
+ }
202
+ if (count(array_intersect($roles, $access_level)) > 0) {
203
+ return true;
204
+ } else {
205
+ return false;
206
+ }
207
+ }
208
+ return false;
209
+ }
210
+
211
+ public function gawd_tracking_code() {
212
+ $gawd_user_data = get_option('gawd_user_data');
213
+ if (isset($gawd_user_data['default_webPropertyId']) && ($gawd_user_data['default_webPropertyId'])) {
214
+ global $gawd_client;
215
+ $gawd_client = GAWD_google_client::get_instance();
216
+ require_once(GAWD_DIR . '/admin/tracking.php');
217
+ }
218
+ }
219
+
220
+ public function create_pdf_file($ajax=true,$data = null,$dimension = null, $start_date = null, $end_date = null,$metric_compare_recc = null, $metric_recc = null) {
221
+ $first_data = isset($_REQUEST["first_data"]) ? sanitize_text_field($_REQUEST["first_data"]) : '';
222
+ $_data_compare = isset($_REQUEST["_data_compare"]) ? ($_REQUEST["_data_compare"]) : '';
223
+ if($ajax == true){
224
+ $export_type = isset($_REQUEST["export_type"]) ? sanitize_text_field($_REQUEST["export_type"]) : '';
225
+ if ($export_type != 'pdf') {
226
+ return;
227
+ }
228
+
229
+ $report_type = isset($_REQUEST["report_type"]) ? sanitize_text_field($_REQUEST["report_type"]) : '';
230
+
231
+
232
+ if ($report_type !== 'alert') {
233
+ return;
234
+ }
235
+
236
+ }
237
+
238
+ include_once GAWD_DIR . '/include/gawd_pdf_file.php';
239
+ $file = new GAWD_PDF_FILE();
240
+
241
+ /*
242
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
243
+ $this->gawd_google_client = GAWD_google_client::get_instance();
244
+ */
245
+ $file->get_request_data($this,$ajax,$data,$dimension, $start_date, $end_date,$metric_compare_recc, $metric_recc );
246
+
247
+ $file->sort_data();
248
+ if($first_data != ''){
249
+ $file->create_file('pages');
250
+ }
251
+ elseif(($_data_compare) != ''){
252
+ $file->create_file('compare');
253
+ }
254
+ else{
255
+ $file->create_file(true);
256
+ }
257
+ if($ajax == true){
258
+ die();
259
+ }
260
+ else{
261
+ return $file->file_dir;
262
+ }
263
+ }
264
+ public function create_csv_file($ajax=true,$data = null,$dimension = null, $start_date = null, $end_date = null, $metric_compare_recc = null, $metric_recc = null){
265
+ if($ajax == true){
266
+ $export_type = isset($_REQUEST["export_type"]) ? sanitize_text_field($_REQUEST["export_type"]) : '';
267
+ if ($export_type != 'csv') {
268
+ return;
269
+ }
270
+ $report_type = isset($_REQUEST["report_type"]) ? sanitize_text_field($_REQUEST["report_type"]) : '';
271
+ if ($report_type !== 'alert') {
272
+ return;
273
+ }
274
+ }
275
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
276
+ $this->gawd_google_client = GAWD_google_client::get_instance();
277
+
278
+ $first_data = isset($_REQUEST["first_data"]) ? sanitize_text_field($_REQUEST["first_data"]) : '';
279
+
280
+
281
+
282
+ include_once GAWD_DIR . '/include/gawd_csv_file.php';
283
+
284
+ $file = new GAWD_CSV_FILE();
285
+ $file->get_request_data($this,$ajax,$data,$dimension, $start_date, $end_date,$metric_compare_recc, $metric_recc );
286
+
287
+ $file->sort_data();
288
+
289
+ //$file->get_request_data($this);
290
+
291
+ $file->sort_data();
292
+ if($first_data != ''){
293
+ $file->create_file(false);
294
+ }
295
+ else{
296
+ $file->create_file();
297
+ }
298
+ if($ajax == true){
299
+ die();
300
+ }
301
+ else{
302
+ return $file->file_dir;
303
+ }
304
+ }
305
+
306
+ public static function get_domain($domain) {
307
+ $root = explode('/', $domain);
308
+ $ret_domain = str_ireplace('www', '', isset($root[2]) ? $root[2] : $domain );
309
+ return $ret_domain;
310
+ }
311
+
312
+ public static function error_message($type,$message){
313
+ echo '<div style="width:99%"><div class="' . $type . '"><p><strong>' . $message . '</strong></p></div></div>';
314
+ }
315
+ public function gawd_export() {
316
+ if (!isset($_REQUEST['action']) || (isset($_REQUEST['action']) && $_REQUEST['action'] !== 'gawd_export')) {
317
+ return;
318
+ }
319
+
320
+ $export_type = isset($_REQUEST["export_type"]) ? sanitize_text_field($_REQUEST["export_type"]) : '';
321
+ if ($export_type != 'pdf' && $export_type != 'csv') {
322
+ return;
323
+ }
324
+
325
+ $report_type = isset($_REQUEST["report_type"]) ? sanitize_text_field($_REQUEST["report_type"]) : '';
326
+
327
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
328
+ $this->gawd_google_client = GAWD_google_client::get_instance();
329
+
330
+ if ($export_type == 'pdf') {
331
+ include_once GAWD_DIR . '/include/gawd_pdf_file.php';
332
+ $file = new GAWD_PDF_FILE();
333
+ } else {
334
+ include_once GAWD_DIR . '/include/gawd_csv_file.php';
335
+ $file = new GAWD_CSV_FILE();
336
+ }
337
+
338
+ if ($report_type == 'alert') {
339
+ if ($export_type == 'pdf') {
340
+ $file->export_file();
341
+ } else {
342
+ $file->export_file();
343
+ }
344
+ }
345
+
346
+ else {
347
+ $metric = isset($_REQUEST["gawd_metric"]) ? sanitize_text_field($_REQUEST["gawd_metric"]) : '';
348
+ $_data_compare = isset($_REQUEST["_data_compare"]) ? ($_REQUEST["_data_compare"]) : '';
349
+ $first_data = isset($_REQUEST["first_data"]) ? ($_REQUEST["first_data"]) : '';
350
+ $view_id = isset($_REQUEST["view_id"]) ? sanitize_text_field($_REQUEST["view_id"]) : '';
351
+ $metric_compare = isset($_REQUEST["gawd_metric_compare"]) ? sanitize_text_field($_REQUEST["gawd_metric_compare"]) : '';
352
+ $dimension = isset($_REQUEST["gawd_dimension"]) ? sanitize_text_field($_REQUEST["gawd_dimension"]) : '';
353
+ $tab_name = isset($_REQUEST["tab_name"]) ? sanitize_text_field($_REQUEST["tab_name"]) : '';
354
+ $img = isset($_REQUEST["img"]) ? sanitize_text_field($_REQUEST["img"]) : '';
355
+ $gawd_email_subject = isset($_REQUEST["gawd_email_subject"]) ? sanitize_text_field($_REQUEST["gawd_email_subject"]) : '';
356
+ $gawd_email_body = isset($_REQUEST["gawd_email_body"]) && $_REQUEST["gawd_email_body"] != '' ? sanitize_text_field($_REQUEST["gawd_email_body"]) : ' ';
357
+ $email_from = isset($_REQUEST["gawd_email_from"]) ? sanitize_email($_REQUEST["gawd_email_from"]) : '';
358
+ $email_to = isset($_REQUEST["gawd_email_to"]) ? sanitize_email($_REQUEST["gawd_email_to"]) : '';
359
+ $email_period = isset($_REQUEST["gawd_email_period"]) ? sanitize_text_field($_REQUEST["gawd_email_period"]) : '';
360
+ $week_day = isset($_REQUEST["gawd_email_week_day"]) ? sanitize_text_field($_REQUEST["gawd_email_week_day"]) : '';
361
+ $month_day = isset($_REQUEST["gawd_email_month_day"]) ? sanitize_text_field($_REQUEST["gawd_email_month_day"]) : '';
362
+ $emails = array();
363
+ $invalid_email = false;
364
+ $email_to = explode(',', $email_to);
365
+ foreach ($email_to as $email) {
366
+ if (is_email($email) == false) {
367
+ $emails = $email;
368
+ }
369
+ }
370
+ if (count($emails) > 0) {
371
+ $invalid_email = true;
372
+ }
373
+ if (($invalid_email != true) && is_email($email_from) && $gawd_email_subject != '') {
374
+ if ($email_period == "once") {
375
+ $file->get_request_data($this);
376
+ $file->sort_data();
377
+ if($export_type == 'csv'){
378
+ if($first_data != ''){
379
+ $file->create_file(false);
380
+ }
381
+ else{
382
+ $file->create_file();
383
+ }
384
+ }
385
+ else{
386
+ if($first_data != ''){
387
+ $file->create_file('pages');
388
+ }
389
+ elseif(($_data_compare) != ''){
390
+ $file->create_file('compare');
391
+ }
392
+ else{
393
+ $file->create_file(false);
394
+ }
395
+ }
396
+ $attachment = $file->file_dir;
397
+
398
+ if ($report_type == 'email') {
399
+ $headers = 'From: <' . $email_from . '>';
400
+ wp_mail($email_to, $gawd_email_subject, $gawd_email_body, $headers, $attachment);
401
+ }
402
+ echo json_encode( array('status'=>'success','msg'=>'Email successfuly sent'));
403
+ }
404
+ else {
405
+ if ($email_period == 'gawd_weekly') {
406
+ $period_day = $week_day;
407
+ $timestamp = strtotime('this ' . $period_day);
408
+ }
409
+ elseif ($email_period == 'gawd_monthly') {
410
+ $period_day = $month_day;
411
+ $timestamp = strtotime(date('Y-m-' . $period_day));
412
+ }
413
+ else {
414
+ $period_day = '';
415
+ $timestamp = time();
416
+ }
417
+ $saved_email = get_option('gawd_email');
418
+ if ($saved_email) {
419
+ $gawd_email_options = array('name' => $gawd_email_subject, 'period' => $email_period, 'metric' => $metric, 'metric_compare' => $metric_compare, 'dimension' => $dimension, 'creation_date' => date('Y-m-d'), 'emails' => $email_to, 'email_from' => $email_from, 'email_subject' => $gawd_email_subject, 'email_body' => $gawd_email_body, 'period_day' => $period_day, 'img' => $img, 'tab_name' => $tab_name, 'view_id' => $view_id, 'export_type' => $export_type);
420
+ $saved_email[] = $gawd_email_options;
421
+ update_option('gawd_email', $saved_email);
422
+ }
423
+ else {
424
+ $gawd_email_options = array(0 => array('name' => $gawd_email_subject, 'period' => $email_period, 'metric' => $metric, 'metric_compare' => $metric_compare, 'dimension' => $dimension, 'creation_date' => date('Y-m-d'), 'emails' => $email_to, 'email_from' => $email_from, 'email_subject' => $gawd_email_subject, 'email_body' => $gawd_email_body, 'period_day' => $period_day, 'img' => $img, 'tab_name' => $tab_name, 'view_id' => $view_id, 'export_type' => $export_type));
425
+ update_option('gawd_email', $gawd_email_options);
426
+ }
427
+ $saved_email = get_option('gawd_email');
428
+ if ($saved_email) {
429
+ foreach ($saved_email as $email) {
430
+ if (!wp_next_scheduled('gawd_email_' . $email['period'])) {
431
+ wp_schedule_event($timestamp, $email['period'], 'gawd_email_' . $email['period']);
432
+ }
433
+ }
434
+ }
435
+ $success_message = 'Email successfuly Scheduled </br> Go to <a href="'.admin_url() . 'admin.php?page=gawd_settings#gawd_emails_tab">Settings page</a> to delete scheduled e-mails.';
436
+ echo json_encode( array('status'=>'success','msg'=>$success_message));
437
+ }
438
+
439
+ die;
440
+ }
441
+ else {
442
+ if ($invalid_email == true) {
443
+ echo json_encode('Invalid email');
444
+ die;
445
+ }
446
+ else if ($gawd_email_subject == '') {
447
+ echo json_encode("Can't send email with empty subject");
448
+ die;
449
+ }
450
+ }
451
+ }
452
+ }
453
+
454
+ public function overview_date_meta($screen = null, $context = 'advanced') {
455
+ //righ side wide meta..
456
+ $orintation = wp_is_mobile() ? 'side' : 'normal';
457
+ add_meta_box('gawd-real-time', __('Real Time', 'gawd'), array($this, 'gawd_real_time'), 'gawd_analytics', 'side', 'high');
458
+ add_meta_box('gawd-date-meta', __('Audience', 'gawd'), array($this, 'gawd_date_box'), 'gawd_analytics', $orintation, null);
459
+ add_meta_box('gawd-country-box', __('Location', 'gawd'), array($this, 'gawd_country_box'), 'gawd_analytics', $orintation, null);
460
+ //left side thin meta.
461
+ add_meta_box('gawd-visitors-meta', __('Visitors', 'gawd'), array($this, 'gawd_visitors'), 'gawd_analytics', 'side', null);
462
+ add_meta_box('gawd-browser-meta', __('Browsers', 'gawd'), array($this, 'gawd_browser'), 'gawd_analytics', 'side', null);
463
+ }
464
+
465
+ public function gawd_date_box() {
466
+ require_once( 'admin/pages/date.php' );
467
+ }
468
+
469
+ public function gawd_country_box() {
470
+ require_once( 'admin/pages/location.php' );
471
+ }
472
+
473
+ public function gawd_real_time() {
474
+ require_once( 'admin/pages/real_time.php' );
475
+ }
476
+
477
+ public function gawd_visitors() {
478
+ require_once( 'admin/pages/visitors.php' );
479
+ }
480
+
481
+ public function gawd_browser() {
482
+ require_once( 'admin/pages/browser.php' );
483
+ }
484
+
485
+ /**
486
+ * Activation function needed for the activation hook.
487
+ */
488
+ public static function activate() {
489
+ $credentials['project_id'] = '115052745574-5vbr7tci4hjkr9clkflmnpto5jisgstg.apps.googleusercontent.com';
490
+ $credentials['project_secret'] = 'wtNiu3c_bA_g7res6chV0Trt';
491
+ if (!get_option('gawd_credentials')) {
492
+ update_option('gawd_credentials', $credentials);
493
+ }
494
+ self::gawd_settings_defaults();
495
+ self::add_dashboard_menu();
496
+ }
497
+
498
+ /**
499
+ * Deactivation function needed for the deactivation hook.
500
+ */
501
+ public static function deactivate() {
502
+
503
+ }
504
+
505
+ /**
506
+ * Enqueues the required styles and scripts, localizes some js variables.
507
+ */
508
+ public function gawd_front_scripts() {
509
+ wp_enqueue_style('admin_css', GAWD_URL . '/inc/css/gawd_admin.css', false, GAWD_VERSION);
510
+ wp_enqueue_script('gawd_amcharts', GAWD_URL . '/inc/js/amcharts.js', false, GAWD_VERSION);
511
+ wp_enqueue_script('gawd_pie', GAWD_URL . '/inc/js/pie.js', false, GAWD_VERSION);
512
+ wp_enqueue_script('gawd_serial', GAWD_URL . '/inc/js/serial.js', false, GAWD_VERSION);
513
+ wp_enqueue_script('gawd_light_theme', GAWD_URL . '/inc/js/light.js', array('jquery'), GAWD_VERSION);
514
+ wp_enqueue_script('gawd_dataloader', GAWD_URL . '/inc/js/dataloader.min.js', array('jquery'), GAWD_VERSION);
515
+ wp_enqueue_script('date-js', GAWD_URL . '/inc/js/date.js', array('jquery'), GAWD_VERSION);
516
+ wp_enqueue_script('gawd_front_js', GAWD_URL . '/inc/js/gawd_front.js', array('jquery'), GAWD_VERSION);
517
+ wp_localize_script('gawd_front_js', 'gawd_front', array(
518
+ 'ajaxurl' => admin_url('admin-ajax.php'),
519
+ 'ajaxnonce' => wp_create_nonce('gawd_admin_page_nonce'),
520
+ 'gawd_plugin_url' => GAWD_URL,
521
+ 'date_30' => date('Y-m-d',strtotime('-31 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
522
+ 'date_7' => date('Y-m-d',strtotime('-8 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
523
+ 'date_last_week' => date('Y-m-d',strtotime('last week -1day')).'/-/'.date('Y-m-d',strtotime('last week +5day')),
524
+ 'date_last_month' => date('Y-m-01',strtotime('last month')).'/-/'.date('Y-m-t',strtotime('last month')),
525
+ 'date_this_month' =>date('Y-m-01').'/-/'.date('Y-m-d'),
526
+ 'date_today' => date('Y-m-d').'/-/'.date('Y-m-d'),
527
+ 'date_yesterday' => date('Y-m-d',strtotime('-1 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
528
+ 'wp_admin_url' => admin_url(),
529
+ 'exportUrl' => add_query_arg(array('action' => 'gawd_export'), admin_url('admin-ajax.php'))
530
+ ));
531
+ }
532
+
533
+ public function gawd_enqueue_scripts() {
534
+ $options = get_option('gawd_settings');
535
+ $default_date = (isset($options['default_date']) && $options['default_date'] != '') ? $options['default_date'] : 'last_30days';
536
+ $default_date_format = (isset($options['default_date_format']) && $options['default_date_format'] != '') ? $options['default_date_format'] : 'ymd_with_week';
537
+ $enable_hover_tooltip = (isset($options['enable_hover_tooltip']) && $options['enable_hover_tooltip'] != '') ? $options['enable_hover_tooltip'] : '';
538
+ $screen = get_current_screen();
539
+ if (strpos($screen->base, 'gawd') !== false || strpos($screen->post_type, 'page') !== false || strpos($screen->post_type, 'post') !== false || strpos($screen->base, 'dashboard') !== false) {
540
+ wp_enqueue_script('common');
541
+ wp_enqueue_script('wp-lists');
542
+ wp_enqueue_script('postbox');
543
+ wp_enqueue_script('jquery-ui-tooltip');
544
+ wp_enqueue_script('gawd_paging', GAWD_URL . '/inc/js/paging.js',false,GAWD_VERSION);
545
+ wp_enqueue_script('jquery.cookie', GAWD_URL . '/inc/js/jquery.cookie.js',false,GAWD_VERSION);
546
+ wp_enqueue_style('admin_css', GAWD_URL . '/inc/css/gawd_admin.css', false, GAWD_VERSION);
547
+ wp_enqueue_style('gawd_licensing', GAWD_URL . '/inc/css/gawd_licensing.css', false, GAWD_VERSION);
548
+ wp_enqueue_style('gawd_featured', GAWD_URL . '/featured/style.css', array(), GAWD_VERSION);
549
+ wp_enqueue_style('font_awesome', GAWD_URL . '/inc/css/font_awesome.css', false, GAWD_VERSION);
550
+ wp_enqueue_style('jquery-ui.css', GAWD_URL . '/inc/css/jquery-ui.css', false, GAWD_VERSION);
551
+ wp_enqueue_style('gawd_bootstrap', GAWD_URL . '/inc/css/bootstrap.css', false, GAWD_VERSION);
552
+ wp_enqueue_style('gawd_bootstrap-chosen', GAWD_URL . '/inc/css/bootstrap-chosen.css', false, GAWD_VERSION);
553
+ wp_enqueue_style('gawd_bootstrap-select', GAWD_URL . '/inc/css/bootstrap-select.css', false, GAWD_VERSION);
554
+ wp_enqueue_style('gawd_datepicker', GAWD_URL . '/inc/css/daterangepicker.css', false, GAWD_VERSION);
555
+ wp_enqueue_style('ui.jqgrid.css', GAWD_URL . '/inc/css/ui.jqgrid.css', false, GAWD_VERSION);
556
+ wp_enqueue_script('gawd_moment', GAWD_URL . '/inc/js/moment.min.js', false, GAWD_VERSION);
557
+ wp_enqueue_script('gawd_daterangepicker', GAWD_URL . '/inc/js/daterangepicker.js', false, GAWD_VERSION);
558
+ wp_enqueue_script('gawd_amcharts', GAWD_URL . '/inc/js/amcharts.js', false, GAWD_VERSION);
559
+ wp_enqueue_script('ddd', 'http://www.amcharts.com/lib/3/plugins/responsive/responsive.min.js?0.9.1a', false, GAWD_VERSION);
560
+ wp_enqueue_script('gawd_pie', GAWD_URL . '/inc/js/pie.js', false, GAWD_VERSION);
561
+ wp_enqueue_script('gawd_serial', GAWD_URL . '/inc/js/serial.js', false, GAWD_VERSION);
562
+ /*Map*/
563
+ wp_enqueue_script('gawd_ammap', GAWD_URL . '/inc/js/ammap.js', false, GAWD_VERSION);
564
+ wp_enqueue_script('gawd_worldLow', GAWD_URL . '/inc/js/worldLow.js', false, GAWD_VERSION);
565
+ wp_enqueue_script('gawd_map_chart', GAWD_URL . '/inc/js/gawd_map_chart.js', false, GAWD_VERSION);
566
+ /*End Map*/
567
+ wp_enqueue_script('gawd_light_theme', GAWD_URL . '/inc/js/light.js', array('jquery'), GAWD_VERSION);
568
+ wp_enqueue_script('gawd_dataloader', GAWD_URL . '/inc/js/dataloader.min.js', array('jquery'), GAWD_VERSION);
569
+ wp_enqueue_script('rgbcolor.js', GAWD_URL . '/inc/js/rgbcolor.js', array('jquery'), GAWD_VERSION);
570
+ wp_enqueue_script('StackBlur.js', GAWD_URL . '/inc/js/StackBlur.js', array('jquery'), GAWD_VERSION);
571
+ wp_enqueue_script('canvg.js', GAWD_URL . '/inc/js/canvg.js', array('jquery'), GAWD_VERSION);
572
+ wp_enqueue_script('gawd_tables', GAWD_URL . '/inc/js/loader.js', array('jquery'), GAWD_VERSION);
573
+ wp_enqueue_script('gawd_grid', GAWD_URL . '/inc/js/jquery.jqGrid.min.js', array('jquery'), GAWD_VERSION);
574
+ wp_enqueue_script('gawd_grid_locale', GAWD_URL . '/inc/js/grid.locale-en.js', array('jquery'), GAWD_VERSION);
575
+ wp_enqueue_script('date-js', GAWD_URL . '/inc/js/date.js', array('jquery'), GAWD_VERSION);
576
+ wp_enqueue_script('admin_js', GAWD_URL . '/inc/js/gawd_admin.js', array('jquery'), GAWD_VERSION);
577
+ wp_enqueue_script('chosen.jquery.js', GAWD_URL . '/inc/js/chosen.jquery.js', array('jquery'), GAWD_VERSION);
578
+ wp_enqueue_script('bootstrap_js', GAWD_URL . '/inc/js/bootstrap_js.js', array('jquery'), GAWD_VERSION);
579
+ wp_enqueue_script('bootstrap-select', GAWD_URL . '/inc/js/bootstrap-select.js', array('jquery'), GAWD_VERSION);
580
+ wp_enqueue_script('highlight_js', GAWD_URL . '/inc/js/js_highlight.js', array('jquery'), GAWD_VERSION);
581
+ wp_enqueue_script('settings_js', GAWD_URL . '/inc/js/gawd_settings.js', array('jquery'), GAWD_VERSION);
582
+ wp_enqueue_script('overview', GAWD_URL . '/inc/js/gawd_overview.js', array('jquery'), GAWD_VERSION);
583
+ wp_localize_script('overview', 'gawd_overview', array(
584
+ 'ajaxurl' => admin_url('admin-ajax.php'),
585
+ 'ajaxnonce' => wp_create_nonce('gawd_admin_page_nonce'),
586
+ 'gawd_plugin_url' => GAWD_URL,
587
+ 'default_date' => $default_date,
588
+ 'enableHoverTooltip' => $enable_hover_tooltip,
589
+ 'wp_admin_url' => admin_url()
590
+ ));
591
+ wp_localize_script('admin_js', 'gawd_admin', array(
592
+ 'ajaxurl' => admin_url('admin-ajax.php'),
593
+ 'ajaxnonce' => wp_create_nonce('gawd_admin_page_nonce'),
594
+ 'gawd_plugin_url' => GAWD_URL,
595
+ 'wp_admin_url' => admin_url(),
596
+ 'enableHoverTooltip' => $enable_hover_tooltip,
597
+ 'default_date' => $default_date,
598
+ 'default_date_format' => $default_date_format,
599
+ 'date_30' => date('Y-m-d',strtotime('-31 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
600
+ 'date_7' => date('Y-m-d',strtotime('-8 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
601
+ 'date_last_week' => date('Y-m-d',strtotime('last week -1day')).'/-/'.date('Y-m-d',strtotime('last week +5day')),
602
+ 'date_last_month' => date('Y-m-01',strtotime('last month')).'/-/'.date('Y-m-t',strtotime('last month')),
603
+ 'date_this_month' =>date('Y-m-01').'/-/'.date('Y-m-d'),
604
+ 'date_today' => date('Y-m-d').'/-/'.date('Y-m-d'),
605
+ 'date_yesterday' => date('Y-m-d',strtotime('-1 day')).'/-/'.date('Y-m-d',strtotime('-1 day')),
606
+ 'exportUrl' => add_query_arg(array('action' => 'gawd_export'), admin_url('admin-ajax.php'))
607
+ ));
608
+ }
609
+ }
610
+
611
+ /**
612
+ * Adds the menu page with its submenus.
613
+ */
614
+ public function gawd_add_menu() {
615
+ $gawd_settings = get_option('gawd_settings');
616
+ $gawd_permissions = isset($gawd_settings['gawd_permissions']) ? $gawd_settings['gawd_permissions'] : array();
617
+ if (empty($gawd_permissions)) {
618
+ $permission = 'manage_options';
619
+ } else {
620
+ if (in_array('manage_options', $gawd_permissions)) {
621
+ $permission = 'manage_options';
622
+ }
623
+ if (in_array('moderate_comments', $gawd_permissions)) {
624
+ $permission = 'moderate_comments';
625
+ }
626
+ if (in_array('publish_posts', $gawd_permissions)) {
627
+ $permission = 'publish_posts';
628
+ }
629
+ if (in_array('edit_posts', $gawd_permissions)) {
630
+ $permission = 'edit_posts';
631
+ }
632
+ }
633
+ add_menu_page(
634
+ __('Analytics', 'gawd'), //$page_title
635
+ __('Analytics', 'gawd'), //$menu_title
636
+ $permission, //$capability
637
+ 'gawd_analytics', //$menu_slug
638
+ array($this, 'gawd_display_overview_page'), //$function = '',
639
+ GAWD_URL . '/assets/main_icon.png'
640
+ //$position = null
641
+ );
642
+
643
+ add_submenu_page(
644
+ 'gawd_analytics', //$parent_slug
645
+ __('Overview', 'gawd'), //$page_title
646
+ __('Overview', 'gawd'), //$menu_title
647
+ $permission, //$capability
648
+ 'gawd_analytics', //$menu_slug
649
+ array($this, 'gawd_display_overview_page') //$function = '',
650
+ );
651
+ add_submenu_page(
652
+ 'gawd_analytics', //$parent_slug
653
+ __('Reports', 'gawd'), //$page_title
654
+ __('Reports', 'gawd'), //$menu_title
655
+ $permission, //$capability
656
+ 'gawd_reports', //$menu_slug
657
+ array($this, 'gawd_display_reports_page') //$function = '',
658
+ );
659
+
660
+ add_submenu_page(
661
+ 'gawd_analytics', //$parent_slug
662
+ __('Settings', 'gawd'), //$page_title
663
+ __('Settings', 'gawd'), //$menu_title
664
+ $permission, //$capability
665
+ 'gawd_settings', //$menu_slug
666
+ array($this, 'gawd_display_settings_page') //$function = '',
667
+ );
668
+ add_submenu_page(
669
+ 'gawd_analytics', //$parent_slug
670
+ __('Tracking', 'gawd'), //$page_title
671
+ __('Tracking', 'gawd'), //$menu_title
672
+ $permission, //$capability
673
+ 'gawd_tracking', //$menu_slug
674
+ array($this, 'gawd_display_tracking_page') //$function = '',
675
+ );
676
+ add_submenu_page(
677
+ 'gawd_analytics', //$parent_slug
678
+ __('Goal Management', 'gawd'), //$page_title
679
+ __('Goal Management', 'gawd'), //$menu_title
680
+ $permission, //$capability
681
+ 'gawd_goals', //$menu_slug
682
+ array($this, 'gawd_display_goals_page') //$function = '',
683
+ );
684
+
685
+ add_submenu_page(
686
+ 'gawd_analytics', //$parent_slug
687
+ __('Custom Reports', 'gawd'), //$page_title
688
+ __('Custom Reports', 'gawd'), //$menu_title
689
+ $permission, //$capability
690
+ 'gawd_custom_reports', //$menu_slug
691
+ array($this, 'gawd_display_custom_reports_page') //$function = '',
692
+ );
693
+ add_submenu_page(
694
+ 'gawd_analytics', //$parent_slug
695
+ __('Get Pro', 'gawd'), //$page_title
696
+ __('Get Pro', 'gawd'), //$menu_title
697
+ $permission, //$capability
698
+ 'gawd_licensing', //$menu_slug
699
+ array($this, 'gawd_display_licensing_page') //$function = '',
700
+ );
701
+ add_submenu_page(
702
+ 'gawd_analytics', //$parent_slug
703
+ __('Featured Plugins', 'gawd'), //$page_title
704
+ __('Featured Plugins', 'gawd'), //$menu_title
705
+ $permission, //$capability
706
+ 'gawd_featured_plugins', //$menu_slug
707
+ array($this, 'gawd_display_featured_plugins_page') //$function = '',
708
+ );
709
+ add_submenu_page(
710
+ 'gawd_analytics', //$parent_slug
711
+ __('Featured Themes', 'gawd'), //$page_title
712
+ __('Featured Themes', 'gawd'), //$menu_title
713
+ $permission, //$capability
714
+ 'gawd_featured_themes', //$menu_slug
715
+ array($this, 'gawd_display_featured_themes_page') //$function = '',
716
+ );
717
+ add_submenu_page(
718
+ 'gawd_analytics', //$parent_slug
719
+ __('Uninstall', 'gawd'), //$page_title
720
+ __('Uninstall', 'gawd'), //$menu_title
721
+ $permission, //$capability
722
+ 'gawd_uninstall', //$menu_slug
723
+ array($this, 'gawd_display_uninstall_page') //$function = '',
724
+ );
725
+
726
+ }
727
+ public function gawd_display_licensing_page() {
728
+ require_once(GAWD_DIR . '/admin/licensing.php');
729
+ }
730
+ function upgrade_pro(){
731
+ $screen = get_current_screen();
732
+ if (strpos($screen->base, 'gawd') !== false && strpos($screen->base, 'gawd_featured') === false) {
733
+ ?>
734
+ <div class="gawd_upgrade wd-clear" >
735
+ <div class="wd-right">
736
+ <a href="https://web-dorado.com/products/wordpress-google-analytics-plugin.html" target="_blank">
737
+ <div class="wd-table">
738
+ <div class="wd-cell wd-cell-valign-middle">
739
+ <?php _e("Upgrade to paid version", "gawd"); ?>
740
+ </div>
741
+
742
+ <div class="wd-cell wd-cell-valign-middle">
743
+ <img src="<?php echo GAWD_URL; ?>/assets/web-dorado.png" >
744
+ </div>
745
+ </div>
746
+ </a>
747
+ </div>
748
+ </div>
749
+ <?php
750
+ }
751
+ }
752
+
753
+ public function gawd_display_featured_plugins_page() {
754
+ require_once(GAWD_DIR . '/featured/featured.php');
755
+ gawd_featured_plugins('wd-google-analytics');
756
+
757
+ }
758
+ public function gawd_display_featured_themes_page() {
759
+ require_once(GAWD_DIR . '/featured/featured_themes.php');
760
+ $controller = new gawd_featured_themes();
761
+ $controller->display();
762
+ }
763
+
764
+ public function gawd_auth() {
765
+ check_ajax_referer('gawd_admin_page_nonce', 'security');
766
+ $code = $_POST['token'];
767
+ $status = GAWD_google_client::authenticate($code);
768
+ if ($status === true) {
769
+ $res = array(
770
+ 'message' => 'successfully saved',
771
+ 'status' => $status,
772
+ );
773
+ } else {
774
+ $res = array(
775
+ 'message' => 'there is an error',
776
+ 'status' => $status
777
+ );
778
+ }
779
+ header('content-type: application/json');
780
+ echo json_encode($res);
781
+ wp_die();
782
+ }
783
+
784
+ /**
785
+ * Displays the Dashboard page.
786
+ */
787
+ public function gawd_display_uninstall_page() {
788
+ require_once( 'admin/pages/uninstall.php' );
789
+ $gawd_uninstall = new GAWDUninstall();
790
+ $deactivate_url = wp_nonce_url('plugins.php?action=deactivate&plugin='.GWD_NAME.'/google-analytics-wd.php', 'deactivate-plugin_'.GWD_NAME.'/google-analytics-wd.php');
791
+ $deactivate_url = str_replace('&amp;','&',$deactivate_url);
792
+ if (isset($_POST['unistall_gawd'])) {
793
+ check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
794
+ delete_option('gawd_custom_reports');
795
+ delete_option('gawd_menu_for_user');
796
+ delete_option('gawd_all_metrics');
797
+ delete_option('gawd_all_dimensions');
798
+ delete_option('gawd_custom_dimensions');
799
+ delete_option('gawd_settings');
800
+ delete_option('gawd_user_data');
801
+ delete_option('gawd_credentials');
802
+ delete_option('gawd_menu_items');
803
+ delete_option('gawd_export_chart_data');
804
+ delete_option('gawd_email');
805
+ delete_option('gawd_custom_reports');
806
+ delete_option('gawd_alerts');
807
+ delete_option('gawd_pushovers');
808
+ delete_option('gawd_menu_for_users');
809
+ delete_option('gawd_own_project');
810
+ delete_option('gawd_zoom_message');
811
+ delete_transient('gawd_user_profiles');
812
+ echo '<script>window.location.href="'.$deactivate_url.'";</script>';
813
+ }
814
+ if (get_option('gawd_credentials')) {
815
+ $gawd_uninstall->uninstall();
816
+ }
817
+ }
818
+
819
+ public function gawd_display_goals_page() {
820
+ if($this->manage_ua_code_selection() != 'done') {
821
+ return;
822
+ }
823
+ global $gawd_client;
824
+ $gawd_client = GAWD_google_client::get_instance();
825
+ if (!empty($_POST)) {
826
+ check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
827
+ }
828
+ $gawd_goal_profile = isset($_POST['gawd_goal_profile']) ? sanitize_text_field($_POST['gawd_goal_profile']) : '';
829
+ $gawd_goal_name = isset($_POST['gawd_goal_name']) ? sanitize_text_field($_POST['gawd_goal_name']) : '';
830
+ $gawd_goal_type = isset($_POST['gawd_goal_type']) ? sanitize_text_field($_POST['gawd_goal_type']) : '';
831
+ $gawd_visit_hour = isset($_POST['gawd_visit_hour']) ? sanitize_text_field($_POST['gawd_visit_hour']) : '';
832
+ $gawd_visit_minute = isset($_POST['gawd_visit_minute']) ? sanitize_text_field($_POST['gawd_visit_minute']) : '';
833
+ $gawd_visit_second = isset($_POST['gawd_visit_second']) ? sanitize_text_field($_POST['gawd_visit_second']) : '';
834
+ $gawd_goal_duration_comparison = isset($_POST['gawd_goal_duration_comparison']) ? sanitize_text_field($_POST['gawd_goal_duration_comparison']) : '';
835
+ $gawd_goal_page_comparison = isset($_POST['gawd_goal_page_comparison']) ? sanitize_text_field($_POST['gawd_goal_page_comparison']) : '';
836
+ $gawd_page_sessions = isset($_POST['gawd_page_sessions']) ? sanitize_text_field($_POST['gawd_page_sessions']) : '';
837
+ $goal_max_id = isset($_POST['goal_max_id']) ? $_POST['goal_max_id'] + 1 : 1;
838
+ $gawd_goal_page_destination_match = isset($_POST['gawd_goal_page_destination_match']) ? sanitize_text_field($_POST['gawd_goal_page_destination_match']) : '';
839
+ $gawd_page_url = isset($_POST['gawd_page_url']) ? sanitize_text_field($_POST['gawd_page_url']) : '';
840
+ $url_case_sensitve = isset($_POST['url_case_sensitve']) ? $_POST['url_case_sensitve'] : '';
841
+ if ($gawd_goal_type == 'VISIT_TIME_ON_SITE') {
842
+ if ($gawd_visit_hour != '' || $gawd_visit_minute != '' || $gawd_visit_second != '') {
843
+ $value = 0;
844
+ if ($gawd_visit_hour != '') {
845
+ $value += $gawd_visit_hour * 60 * 60;
846
+ }
847
+ if ($gawd_visit_minute != '') {
848
+ $value += $gawd_visit_minute * 60;
849
+ }
850
+ if ($gawd_visit_second != '') {
851
+ $value += $gawd_visit_second;
852
+ }
853
+ }
854
+ $gawd_client->add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_duration_comparison, $value);
855
+ } elseif ($gawd_goal_type == 'VISIT_NUM_PAGES') {
856
+ if ($gawd_page_sessions != '') {
857
+ $gawd_client->add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_page_comparison, $gawd_page_sessions);
858
+ }
859
+ } elseif ($gawd_goal_type == 'URL_DESTINATION') {
860
+ if ($gawd_page_url != '') {
861
+ $gawd_client->add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_page_destination_match, $gawd_page_url, $url_case_sensitve);
862
+ }
863
+ } elseif ($gawd_goal_type == 'EVENT') {
864
+ if ($gawd_page_url != '') {
865
+ $gawd_client->add_goal($gawd_goal_profile, $goal_max_id, $gawd_goal_type, $gawd_goal_name, $gawd_goal_page_comparison, $gawd_page_url, $url_case_sensitve);
866
+ }
867
+ }
868
+ require_once( 'admin/pages/goals.php' );
869
+
870
+ }
871
+
872
+ public function gawd_display_custom_reports_page() {
873
+ global $gawd_client;
874
+ if (!empty($_POST)) {
875
+ check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
876
+ }
877
+ $gawd_client = GAWD_google_client::get_instance();
878
+ $gawd_remove_custom_report = isset($_POST['gawd_remove_custom_report']) ? sanitize_text_field($_POST['gawd_remove_custom_report']) : '';
879
+ if ($gawd_remove_custom_report) {
880
+ $all_reports = get_option("gawd_custom_reports");
881
+ if ($all_reports) {
882
+ unset($all_reports[$gawd_remove_custom_report]);
883
+ update_option('gawd_custom_reports', $all_reports);
884
+ self::add_dashboard_menu();
885
+ }
886
+ }
887
+ if (isset($_POST['gawd_add_custom_report'])) {
888
+ $gawd_custom_report_name = isset($_POST['gawd_custom_report_name']) ? sanitize_text_field($_POST['gawd_custom_report_name']) : '';
889
+ $gawd_custom_report_metric = isset($_POST['gawd_custom_report_metric']) ? sanitize_text_field($_POST['gawd_custom_report_metric']) : '';
890
+ $gawd_custom_report_dimension = isset($_POST['gawd_custom_report_dimension']) ? sanitize_text_field($_POST['gawd_custom_report_dimension']) : '';
891
+
892
+ if ($gawd_custom_report_name != '' && $gawd_custom_report_metric != '' && $gawd_custom_report_dimension != '') {
893
+ $saved_custom_reports = get_option("gawd_custom_reports");
894
+ if(!isset($saved_custom_reports[$gawd_custom_report_name])){
895
+ if ($saved_custom_reports) {
896
+ $custom_reports = array('metric' => $gawd_custom_report_metric, 'dimension' => $gawd_custom_report_dimension, 'id' => count($saved_custom_reports) + 1);
897
+ $saved_custom_reports[$gawd_custom_report_name] = $custom_reports;
898
+
899
+ update_option('gawd_custom_reports', $saved_custom_reports);
900
+ }
901
+ else {
902
+ $custom_reports = array($gawd_custom_report_name => array('metric' => $gawd_custom_report_metric, 'dimension' => $gawd_custom_report_dimension, 'id' => 1));
903
+ update_option('gawd_custom_reports', $custom_reports);
904
+ }
905
+ }
906
+ }
907
+ self::add_dashboard_menu();
908
+ }
909
+ require_once( 'admin/pages/custom_reports.php' );
910
+ }
911
+
912
+ public function gawd_display_overview_page() {
913
+ global $gawd_client, $gawd_user_data;
914
+ $gawd_client = GAWD_google_client::get_instance();
915
+ $profiles = $gawd_client->get_profiles();
916
+ $gawd_user_data = get_option('gawd_user_data');
917
+ if(isset($_POST['gawd_id'])){
918
+ $gawd_user_data['gawd_id'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
919
+ foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
920
+ foreach ($web_property as $profile) {
921
+ if ($profile['id'] == $gawd_user_data['gawd_id']) {
922
+ $gawd_user_data['web_property_name'] = $web_property_name;
923
+ $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
924
+ $gawd_user_data['accountId'] = $profile['accountId'];
925
+ }
926
+ }
927
+ }
928
+ $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
929
+ update_option('gawd_user_data', $gawd_user_data);
930
+ }
931
+ require_once( 'admin/pages/overview.php' );
932
+ }
933
+
934
+ public function gawd_display_reports_page() {
935
+ global $gawd_client, $gawd_user_data;
936
+ $gawd_client = GAWD_google_client::get_instance();
937
+ $profiles = $gawd_client->get_profiles();
938
+ $gawd_user_data = get_option('gawd_user_data');
939
+ if(isset($_POST['gawd_id'])){
940
+ $gawd_user_data['gawd_id'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
941
+ foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
942
+ foreach ($web_property as $profile) {
943
+ if ($profile['id'] == $gawd_user_data['gawd_id']) {
944
+ $gawd_user_data['web_property_name'] = $web_property_name;
945
+ $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
946
+ $gawd_user_data['accountId'] = $profile['accountId'];
947
+ }
948
+ }
949
+ }
950
+ $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
951
+ update_option('gawd_user_data', $gawd_user_data);
952
+ }
953
+ require_once( 'admin/pages/dashboard.php' );
954
+ }
955
+
956
+ public function gawd_daily_email() {
957
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
958
+ $gawd_client = GAWD_google_client::get_instance();
959
+ $emails = get_option('gawd_email');
960
+ $gawd_user_data = get_option('gawd_user_data');
961
+ $data = '';
962
+ foreach ($emails as $email) {
963
+ if (isset($email['period']) && $email['period'] == 'daily') {
964
+ //pls send email if ....
965
+ $date = date('Y-m-d', strtotime('yesterday'));
966
+ $email_subject = preg_match('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', $email['email_subject']) ? preg_replace('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', '(' . $date . ' - ' . $date . ')', $email['email_subject']) : $email['email_subject'] . ' (' . $date . ' - ' . $date . ')';
967
+ $data = $this->show_data(array('metric'=>'ga:' . $email['metric'], 'dimension'=>$email['dimension'], 'start_date'=>$date,'end_date'=> $date));
968
+ if($email['export_type'] == 'pdf'){
969
+ $filedir = $this->create_pdf_file(false,$data, $email['dimension'], $date, $date,$email['metric_compare'],$email['metric']);
970
+ }
971
+ else{
972
+ $filedir = $this->create_csv_file(false,$data, $email['dimension'], $date, $date,$email['metric_compare'],$email['metric']);
973
+ }
974
+ //$attachment = gawd_export_data($data, $export_type, 'email', $email['dimension'], $email['metric'], $email['metric_compare'], $email['img'], $email['tab_name'], $start_date, $end_date, $gawd_user_data['web_property_name'],$filter_type);
975
+ $attachment = $filedir;
976
+ $headers = 'From: <' . $email['email_from'] . '>';
977
+ wp_mail($email['emails'], $email_subject, $email['email_body'], $headers, $attachment);
978
+ }
979
+ }
980
+ }
981
+
982
+ public function gawd_weekly_email() {
983
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
984
+ $gawd_client = GAWD_google_client::get_instance();
985
+ $emails = get_option('gawd_email');
986
+ $gawd_user_data = get_option('gawd_user_data');
987
+ $data = '';
988
+ foreach ($emails as $email) {
989
+ if (isset($email['period']) && $email['period'] == 'gawd_weekly') {
990
+ //pls send email if ....
991
+ /*$start_date = date('Y-m-d', strtotime('last' . $email['period_day']));
992
+ $end_date = date('Y-m-d', strtotime('this' . $email['period_day']));*/
993
+ $start_date = date('Y-m-d', strtotime('last week -1 day'));
994
+ $end_date = date('l') != 'Sunday' ? date('Y-m-d',strtotime('last sunday -1 day')) : date('Y-m-d', strtotime('-1 day'));
995
+ $email_subject = preg_match('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', $email['email_subject']) ? preg_replace('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', '(' . $start_date . ' - ' . $end_date . ')', $email['email_subject']) : $email['email_subject'] . ' (' . $start_date . ' - ' . $end_date . ')';
996
+ $data = $this->show_data(array('metric'=>'ga:' . $email['metric'], 'dimension'=>$email['dimension'], 'start_date'=>$start_date,'end_date'=> $end_date));
997
+ if($email['export_type'] == 'pdf'){
998
+ $filedir = $this->create_pdf_file(false,$data, $email['dimension'], $start_date, $end_date,$email['metric_compare'],$email['metric']);
999
+ }
1000
+ else{
1001
+ $filedir = $this->create_csv_file(false,$data, $email['dimension'], $start_date, $end_date, $email['metric_compare'],$email['metric']);
1002
+ }
1003
+ //$attachment = gawd_export_data($data, $export_type, 'email', $email['dimension'], $email['metric'], $email['metric_compare'], $email['img'], $email['tab_name'], $start_date, $end_date, $gawd_user_data['web_property_name'],$filter_type);
1004
+ $attachment = $filedir;
1005
+
1006
+ $headers = 'From: <' . $email['email_from'] . '>';
1007
+ wp_mail($email['emails'], $email_subject, $email['email_body'], $headers, $attachment);
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ public function gawd_monthly_email() {
1013
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1014
+ $gawd_client = GAWD_google_client::get_instance();
1015
+ $emails = get_option('gawd_email');
1016
+ $gawd_user_data = get_option('gawd_user_data');
1017
+ $data = '';
1018
+ foreach ($emails as $email) {
1019
+ if (isset($email['period']) && $email['period'] == 'gawd_monthly') {
1020
+ //pls send email if ....
1021
+ $end_date = date('Y-m-d', strtotime(date('Y-' . date('m') . '-1') . '-1 day'));
1022
+ $start_date = date('Y-m-d', strtotime($end_date . '- 1 month'));
1023
+ $data = $this->show_data(array('metric'=>'ga:' . $email['metric'], 'dimension'=>$email['dimension'], 'start_date'=>$start_date,'end_date'=> $end_date));
1024
+ $email_subject = preg_match('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', $email['email_subject']) ? preg_replace('/\(([0-9]{4}-[0-1][0-9]-[0-3][0-9] \- [0-9]{4}-[0-1][0-9]-[0-3][0-9])\)/', '(' . $start_date . ' - ' . $end_date . ')', $email['email_subject']) : $email['email_subject'] . ' (' . $start_date . ' - ' . $end_date . ')';
1025
+ if($email['export_type'] == 'pdf'){
1026
+ $filedir = $this->create_pdf_file(false,$data, $email['dimension'], $start_date, $end_date,$email['metric_compare'],$email['metric']);
1027
+ }
1028
+ else{
1029
+ $filedir = $this->create_csv_file(false,$data, $email['dimension'], $start_date, $end_date,$email['metric_compare'],$email['metric']);
1030
+ }
1031
+ //$attachment = gawd_export_data($data, $export_type, 'email', $email['dimension'], $email['metric'], $email['metric_compare'], $email['img'], $email['tab_name'], $start_date, $end_date, $gawd_user_data['web_property_name'],$filter_type);
1032
+ $attachment = $filedir;
1033
+ $headers = 'From: <' . $email['email_from'] . '>';
1034
+ wp_mail($email['emails'], $email_subject, $email['email_body'], $headers, $attachment);
1035
+ }
1036
+ }
1037
+ }
1038
+
1039
+ /**
1040
+ * Prepares the settings to be displayed then displays the settings page.
1041
+ */
1042
+ public static function gawd_settings_defaults() {
1043
+ $settings = get_option('gawd_settings');
1044
+ $settings['gawd_tracking_enable'] = 'on';
1045
+ $settings['gawd_custom_dimension_Logged_in'] = 'on';
1046
+ $settings['gawd_custom_dimension_Post_type'] = 'on';
1047
+ $settings['gawd_custom_dimension_Author'] = 'on';
1048
+ $settings['gawd_custom_dimension_Category'] = 'on';
1049
+ $settings['gawd_custom_dimension_Published_Month'] = 'on';
1050
+ $settings['gawd_custom_dimension_Published_Year'] = 'on';
1051
+ $settings['gawd_custom_dimension_Tags'] = 'on';
1052
+ $settings['enable_hover_tooltip'] = 'on';
1053
+ update_option('gawd_settings', $settings);
1054
+ }
1055
+
1056
+ public function manage_ua_code_selection() {
1057
+ global $gawd_user_data;
1058
+ if (isset($gawd_user_data['default_webPropertyId']) && $gawd_user_data['default_webPropertyId']) {
1059
+ return 'done';
1060
+ } else {
1061
+ $gawd_client = GAWD_google_client::get_instance();
1062
+ $property = $gawd_client->property_exists();
1063
+ if ($property == 'no_matches') {
1064
+ $this->gawd_admin_notice("<p class='gawd_notice'>You don't have any web-properties with current site url, go with <a href='" . admin_url('admin.php?page=gawd_tracking') . "'>this</a> link to add.</p>", 'error');
1065
+ // show notice that you don't have property with current site url
1066
+ // add account or property to an existing account
1067
+ } elseif (count($property) == 1) {
1068
+ $property = $property[0];
1069
+ $gawd_user_data['webPropertyId'] = $property['id'];
1070
+ $gawd_user_data['default_webPropertyId'] = $property['id'];
1071
+ $gawd_user_data['accountId'] = $property['accountId'];
1072
+ $gawd_user_data['default_accountId'] = $property['accountId'];
1073
+ $gawd_user_data['gawd_id'] = $property['defaultProfileId'];
1074
+ update_option('gawd_user_data', $gawd_user_data);
1075
+ $this->gawd_admin_notice("In order to enable tracking for your website, you have to go with
1076
+ <a href='" . admin_url('admin.php?page=gawd_tracking') . "'>this</a> link and turn the option on.", 'warning is-dismissible');
1077
+ // show notice that you have to enable tracking code, link to tracking submenu
1078
+ } else {
1079
+ $this->gawd_admin_notice("You have two or more web-properties configured with current site url. Please go with
1080
+ <a href='" . admin_url('admin.php?page=gawd_tracking') . "'>this</a> link to select the proper one.", 'error');
1081
+ // show notice that you have >=2 properties with current site url
1082
+ // select property from same url properties
1083
+ }
1084
+ }
1085
+ }
1086
+
1087
+ public function manage_ua_code_selection_tracking() {
1088
+ global $gawd_user_data;
1089
+ if (isset($gawd_user_data['default_webPropertyId']) && $gawd_user_data['default_webPropertyId']) {
1090
+ return 'done';
1091
+ } else {
1092
+ $gawd_client = GAWD_google_client::get_instance();
1093
+ $property = $gawd_client->property_exists();
1094
+ if ($property == 'no_matches') {
1095
+ $accounts = $gawd_client->get_management_accounts();
1096
+ if (!empty($accounts)) {
1097
+ echo "<h3 style='margin-top:10px' class='gawd_page_titles'>Tracking</h3>
1098
+ <p class='gawd_notice notice'>Here you can add a <b>web property</b> on your Google Analytics account using current WordPress website.<br>
1099
+ Provide a <b>Name</b> for the property and click <b>Add</b>. You can check and manage web properties from your Google Analytics account, <b>Admin</b> page.<br>
1100
+ Alternatively, you can click <b>Later</b> and configure the web property any other time.</p>
1101
+ <br/>
1102
+ <form method='post' id='gawd_property_add'>
1103
+ <div class='gawd_settings_wrapper'>
1104
+ <div class='gawd_goal_row'>
1105
+ <span class='gawd_goal_label'>Account</span>
1106
+ <span class='gawd_goal_input'>
1107
+ <select name='gawd_account_select' class='gawd_account_select' style='padding: 2px;width: 96%;line-height: 30px;height: 30px !important;'>";
1108
+ foreach ($accounts as $account) {
1109
+ echo "<option value='" . $account['id'] . "'>" . $account['name'] . "</option>";
1110
+ }
1111
+ echo "</select>
1112
+ </span>
1113
+ <div class='gawd_info' title='this_is_tooltip'></div>
1114
+ <div class='clear'></div>
1115
+ </div>
1116
+ <div class='gawd_goal_row'>
1117
+ <span class='gawd_goal_label'>Name</span>
1118
+ <span class='gawd_goal_input'>
1119
+ <input id='gawd_property_name' name='gawd_property_name' type='text'>
1120
+ </span>
1121
+ <div class='gawd_info' title='this_is_tooltip'></div>
1122
+ <div class='clear'></div>
1123
+ </div>
1124
+ </div>
1125
+ <div class='gawd_add_prop gawd_submit'>
1126
+ <a href='".admin_url() . "admin.php?page=gawd_analytics' class='gawd_later button_gawd'>Later</a>
1127
+ <input type='submit' name='add_property' class='button_gawd' value='ADD'/>
1128
+ </div>
1129
+ </form>";
1130
+ // account select to add web property and web property parameters
1131
+ // and add link to google analytics for manually creating an account
1132
+ // wp_die();
1133
+ } else {
1134
+ $this->gawd_admin_notice("You do not have any google analytics accounts set. Please go with <a href='https://analytics.google.com/' target='_blank'>this</a> link to add one.", "error");
1135
+ // link to google analytics to add account
1136
+ // wp_die();
1137
+ }
1138
+ } elseif (count($property) == 1) {
1139
+ $property = $property[0];
1140
+ $gawd_user_data['webPropertyId'] = $property['id'];
1141
+ $gawd_user_data['default_webPropertyId'] = $property['id'];
1142
+ $gawd_user_data['accountId'] = $property['accountId'];
1143
+ $gawd_user_data['default_accountId'] = $property['accountId'];
1144
+ $gawd_user_data['gawd_id'] = $property['defaultProfileId'];
1145
+ update_option('gawd_user_data', $gawd_user_data);
1146
+ } else {
1147
+ echo "<p class='notice'>You have multiple web-properties set with current site url. Please select the one which you want to use for tracking from the list below.</p>
1148
+ <br/>
1149
+ <form method='post' id='gawd_property_select'>
1150
+ <div class='gawd_settings_wrapper'>
1151
+ <div class='gawd_goal_row'>
1152
+ <span class='gawd_goal_label'>Web-property</span>
1153
+ <span class='gawd_goal_input'>
1154
+ <select name='gawd_property_select' class='gawd_property_select' style='padding: 2px;width: 96%;line-height: 30px;height: 30px !important;'>";
1155
+ foreach ($property as $select_property) {
1156
+ echo "<option value='" . $select_property['id'] . "'>" . $select_property['name'] . " (" . $select_property['id'] . ")</option>";
1157
+ }
1158
+ echo "</select>
1159
+ </span>
1160
+ <div class='gawd_info' title='this_is_tooltip'></div>
1161
+ <div class='clear'></div>
1162
+ </div>
1163
+ </div>
1164
+ <div class='gawd_submit'><input type='submit' name='lock_property' class='button_gawd' value='SAVE'/></div>
1165
+ </form>";
1166
+ // web property select to select from properties with same site url
1167
+ // wp_die();
1168
+ }
1169
+ }
1170
+ }
1171
+
1172
+ public function gawd_admin_notice($message, $type) {
1173
+ $class = 'notice notice-' . $type;
1174
+ echo '<div class="' . $class . '"><p>' . $message . '</p></div>';
1175
+ }
1176
+
1177
+ public function gawd_display_settings_page() {
1178
+ global $gawd_user_data;
1179
+ $gawd_user_data = get_option('gawd_user_data');
1180
+ if(isset($_GET['defaultExist']) && $_GET['defaultExist'] ==1){
1181
+ $redirect_url = admin_url() . 'admin.php?page=gawd_tracking';
1182
+ echo '<script>window.location.href="'.$redirect_url.'";</script>';
1183
+ }
1184
+ if(isset($_POST['gawd_settings_logout'])&& $_POST['gawd_settings_logout'] == 1){
1185
+ delete_option('gawd_user_data');
1186
+ $redirect_url = admin_url() . 'admin.php?page=gawd_settings';
1187
+ echo '<script>window.location.href="'.$redirect_url.'";</script>';
1188
+ }
1189
+ if(isset($_POST['web_property_name']) && $_POST['web_property_name'] != ''){
1190
+ $gawd_user_data['gawd_id'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
1191
+ foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
1192
+ foreach ($web_property as $profile) {
1193
+ if ($profile['id'] == $gawd_user_data['gawd_id']) {
1194
+ $gawd_user_data['web_property_name'] = $web_property_name;
1195
+ $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
1196
+ $gawd_user_data['accountId'] = $profile['accountId'];
1197
+ }
1198
+ }
1199
+ }
1200
+ $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
1201
+ update_option('gawd_user_data', $gawd_user_data);
1202
+ $redirect_url = admin_url() . 'admin.php?page=gawd_settings';
1203
+ //echo '<script>window.location.href="'.$redirect_url.'";</script>';
1204
+ }
1205
+ /* if(isset($_POST['account_name']) && $_POST['account_name'] != ''){
1206
+ $gawd_user_data['accountId'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
1207
+ foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
1208
+ foreach ($web_property as $profile) {
1209
+ if ($profile['accountId'] == $gawd_user_data['accountId']) {
1210
+ $gawd_user_data['web_property_name'] = $web_property_name;
1211
+ $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
1212
+ $gawd_user_data['accountId'] = $profile['accountId'];
1213
+ }
1214
+ }
1215
+ }
1216
+ $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
1217
+ update_option('gawd_user_data', $gawd_user_data);
1218
+ $redirect_url = admin_url() . 'admin.php?page=gawd_settings';
1219
+ //echo '<script>window.location.href="'.$redirect_url.'";</script>';
1220
+ } */
1221
+ if(isset($_GET['errorMsg'])){
1222
+ self::error_message('error','User does not have sufficient permissions for this account to add filter');
1223
+ }
1224
+ if (!isset($gawd_user_data['refresh_token']) || ($gawd_user_data['refresh_token'] == '')) {
1225
+ echo '<div class="gawd_auth_wrap"><p class="auth_description">Click <b>Authenticate</b> button and login to your Google account. A window asking for relevant permissions will appear. Click <b>Allow</b> and copy the authentication code from the text input.</p><div id="gawd_auth_url" onclick="gawd_auth_popup(' . GAWD_google_client::create_authentication_url() . ',800,400)" style="cursor: pointer;">AUTHENTICATE</div>';
1226
+ echo '<div id="gawd_auth_code"><form id="gawd_auth_code_paste" action="" method="post"><input id="gawd_token" type="text">';
1227
+ wp_nonce_field("gawd_save_form", "gawd_save_form_fild");
1228
+ echo '</form>
1229
+ <div id="gawd_auth_code_submit">SUBMIT</div></div>';
1230
+ $gawd_own_project = get_option('gawd_own_project');
1231
+ if(isset($gawd_own_project) && $gawd_own_project && intval($gawd_own_project)==1){
1232
+ echo'<form method="post">
1233
+ <div class="gawd_reset_button">
1234
+ <input type="hidden" name="reset_data" id="reset_data"/>
1235
+ <input type="button" class="button_gawd" id="gawd_reset_button" value="RESET"/>
1236
+ </div>
1237
+ </form>';
1238
+ }
1239
+ echo '</div><div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div>
1240
+ <div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;">
1241
+ <img src="' . GAWD_URL . '/assets/ajax_loader.gif" style="margin-top: 200px; width:50px;">
1242
+ </div>';
1243
+ }
1244
+ else {
1245
+ if($this->manage_ua_code_selection() != 'done') {
1246
+ // return;
1247
+ }
1248
+ try{
1249
+ $gawd_client = GAWD_google_client::get_instance();
1250
+ $gawd_client->get_profiles();
1251
+
1252
+ }catch(Google_Service_Exception $e){
1253
+ return $e->getErrors()[0]["message"];
1254
+ }catch(Exception $e){
1255
+ return $e->getMessage();
1256
+ }
1257
+
1258
+ $gawd_alert_remove = isset($_POST['gawd_alert_remove']) ? intval($_POST['gawd_alert_remove']) : false;
1259
+ $gawd_menu_remove = isset($_POST['gawd_menu_remove']) ? intval($_POST['gawd_menu_remove']) : false;
1260
+ $gawd_pushover_remove = isset($_POST['gawd_pushover_remove']) ? intval($_POST['gawd_pushover_remove']) : false;
1261
+ $gawd_email_remove = isset($_POST['gawd_email_remove']) ? intval($_POST['gawd_email_remove']) : false;
1262
+ $gawd_filter_remove = isset($_POST['gawd_filter_remove']) ? intval($_POST['gawd_filter_remove']) : false;
1263
+ if ($gawd_alert_remove) {
1264
+ $all_alerts = get_option('gawd_alerts');
1265
+ if ($all_alerts) {
1266
+ foreach ($all_alerts as $alert) {
1267
+ wp_unschedule_event(wp_next_scheduled('gawd_alert_' . $alert['period']), 'gawd_alert_' . $alert['period']);
1268
+ }
1269
+ unset($all_alerts[$gawd_alert_remove - 1]);
1270
+ update_option('gawd_alerts', $all_alerts);
1271
+ }
1272
+ }
1273
+ if ($gawd_menu_remove) {
1274
+ $all_menues = get_option('gawd_menu_for_user');
1275
+ if ($all_menues) {
1276
+ unset($all_menues[$gawd_menu_remove]);
1277
+ update_option('gawd_menu_for_user', $all_menues);
1278
+ }
1279
+ }
1280
+ if ($gawd_email_remove) {
1281
+ $all_emails = get_option('gawd_email');
1282
+ if ($all_emails) {
1283
+ foreach ($all_emails as $email) {
1284
+ wp_unschedule_event(wp_next_scheduled('gawd_email_' . $email['period']), 'gawd_email_' . $email['period']);
1285
+ }
1286
+ unset($all_emails[$gawd_email_remove - 1]);
1287
+ update_option('gawd_email', $all_emails);
1288
+ }
1289
+ }
1290
+ if ($gawd_filter_remove) {
1291
+ $analytics = $gawd_client->analytics_member;
1292
+ $accountId = $gawd_client->get_profile_accountId();
1293
+ try{
1294
+ $analytics->management_filters->delete($accountId, $gawd_filter_remove);
1295
+ } catch (apiServiceException $e) {
1296
+ print 'There was an Analytics API service error '
1297
+ . $e->getCode() . ':' . $e->getMessage();
1298
+ } catch (apiException $e) {
1299
+ print 'There was a general API error '
1300
+ . $e->getCode() . ':' . $e->getMessage();
1301
+ } catch (Exception $e) {
1302
+ echo '<script>window.location.href="' . admin_url() . 'admin.php?page=gawd_settings&errorMsg=1#gawd_filters_tab";</script>';
1303
+ }
1304
+ }
1305
+ $gawd_pushover_remove = isset($_POST['gawd_pushover_remove']) ? $_POST['gawd_pushover_remove'] : false;
1306
+ if ($gawd_pushover_remove) {
1307
+ $all_pushovers = get_option('gawd_pushovers');
1308
+ if ($all_pushovers) {
1309
+ foreach ($all_pushovers as $pushover) {
1310
+ wp_unschedule_event(wp_next_scheduled('gawd_pushover_' . $pushover['period']), 'gawd_pushover_' . $pushover['period']);
1311
+ }
1312
+ unset($all_pushovers[$gawd_pushover_remove - 1]);
1313
+ update_option('gawd_pushovers', $all_pushovers);
1314
+ }
1315
+ }
1316
+ if (isset($_POST['settings_submit'])) {
1317
+ check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
1318
+ $gawd_user_data = get_option('gawd_user_data');
1319
+ $gawd_alert_name = isset($_POST['gawd_alert_name']) ? sanitize_text_field($_POST['gawd_alert_name']) : '';
1320
+ $gawd_alert_period = isset($_POST['gawd_alert_name']) ? sanitize_text_field($_POST['gawd_alert_period']) : '';
1321
+ $gawd_alert_metric = isset($_POST['gawd_alert_metric']) ? sanitize_text_field($_POST['gawd_alert_metric']) : '';
1322
+ $gawd_alert_condition = isset($_POST['gawd_alert_condition']) ? sanitize_text_field($_POST['gawd_alert_condition']) : '';
1323
+ $gawd_alert_value = isset($_POST['gawd_alert_value']) ? sanitize_text_field($_POST['gawd_alert_value']) : '';
1324
+ $gawd_alert_emails = isset($_POST['gawd_alert_emails']) ? sanitize_email($_POST['gawd_alert_emails']) : '';
1325
+ $gawd_alert_view = isset($_POST['gawd_alert_view']) ? sanitize_text_field($_POST['gawd_alert_view']) : '';
1326
+ $alert_view_name = isset($_POST['alert_view_name']) ? sanitize_text_field($_POST['alert_view_name']) : '';
1327
+ if ($gawd_alert_name != '' && $gawd_alert_period != '' && $gawd_alert_metric != '' && $gawd_alert_condition != '' && $gawd_alert_value != '' && $gawd_alert_emails != '') {
1328
+ $saved_alerts = get_option('gawd_alerts');
1329
+ if ($saved_alerts) {
1330
+ $gawd_alert_options = array('name' => $gawd_alert_name, 'period' => $gawd_alert_period, 'metric' => $gawd_alert_metric, 'condition' => $gawd_alert_condition, 'value' => $gawd_alert_value, 'creation_date' => date('Y-m-d'), 'emails' => $gawd_alert_emails, 'alert_view' => $gawd_alert_view, 'alert_view_name' => $alert_view_name);
1331
+ $saved_alerts[] = $gawd_alert_options;
1332
+ update_option('gawd_alerts', $saved_alerts);
1333
+ } else {
1334
+ $gawd_alert_options = array(0 => array('name' => $gawd_alert_name, 'period' => $gawd_alert_period, 'metric' => $gawd_alert_metric, 'condition' => $gawd_alert_condition, 'value' => $gawd_alert_value, 'creation_date' => date('Y-m-d'), 'emails' => $gawd_alert_emails, 'alert_view' => $gawd_alert_view, 'alert_view_name' => $alert_view_name));
1335
+ update_option('gawd_alerts', $gawd_alert_options);
1336
+ }
1337
+ $saved_alerts = get_option('gawd_alerts');
1338
+ if ($saved_alerts) {
1339
+ foreach ($saved_alerts as $alert) {
1340
+ if (!wp_next_scheduled('gawd_alert_' . $alert['period'])) {
1341
+ wp_schedule_event(time(), $alert['period'], 'gawd_alert_' . $alert['period']);
1342
+ }
1343
+ }
1344
+ }
1345
+ }
1346
+ $gawd_pushover_name = isset($_POST['gawd_pushover_name']) ? sanitize_text_field($_POST['gawd_pushover_name']) : '';
1347
+ $gawd_pushover_period = isset($_POST['gawd_pushover_period']) ? sanitize_text_field($_POST['gawd_pushover_period']) : '';
1348
+ $gawd_pushover_metric = isset($_POST['gawd_pushover_metric']) ? sanitize_text_field($_POST['gawd_pushover_metric']) : '';
1349
+ $gawd_pushover_condition = isset($_POST['gawd_pushover_condition']) ? sanitize_text_field($_POST['gawd_pushover_condition']) : '';
1350
+ $gawd_pushover_value = isset($_POST['gawd_pushover_value']) ? intval($_POST['gawd_pushover_value']) : '';
1351
+
1352
+ $gawd_pushover_user_keys = isset($_POST['gawd_pushover_user_keys']) ? sanitize_text_field($_POST['gawd_pushover_user_keys']) : '';
1353
+ $gawd_pushover_view = isset($_POST['gawd_pushover_view']) ? sanitize_text_field($_POST['gawd_pushover_view']) : '';
1354
+ $pushover_view_name = isset($_POST['pushover_view_name']) ? sanitize_text_field($_POST['pushover_view_name']) : '';
1355
+ if ($gawd_pushover_name != '' && $gawd_pushover_period != '' && $gawd_pushover_metric != '' && $gawd_pushover_condition != '' && $gawd_pushover_value !== '' && $gawd_pushover_user_keys != '') {
1356
+ $saved_pushovers = get_option('gawd_pushovers');
1357
+ if ($saved_pushovers) {
1358
+ $gawd_pushover_options = array('name' => $gawd_pushover_name, 'period' => $gawd_pushover_period, 'metric' => $gawd_pushover_metric, 'condition' => $gawd_pushover_condition, 'value' => $gawd_pushover_value, 'creation_date' => date('Y-m-d'), 'user_key' => $gawd_pushover_user_keys,'pushover_view' => $gawd_pushover_view, 'pushover_view_name' => $pushover_view_name);
1359
+ $saved_pushovers[] = $gawd_pushover_options;
1360
+ update_option('gawd_pushovers', $saved_pushovers);
1361
+ }
1362
+ else {
1363
+ $gawd_pushover_options = array(0 => array('name' => $gawd_pushover_name, 'period' => $gawd_pushover_period, 'metric' => $gawd_pushover_metric, 'condition' => $gawd_pushover_condition, 'value' => $gawd_pushover_value, 'creation_date' => date('Y-m-d'), 'user_key' => $gawd_pushover_user_keys,'pushover_view' => $gawd_pushover_view, 'pushover_view_name' => $pushover_view_name));
1364
+ update_option('gawd_pushovers', $gawd_pushover_options);
1365
+ }
1366
+ $saved_pushovers = get_option('gawd_pushovers');
1367
+ if ($saved_pushovers) {
1368
+
1369
+ foreach ($saved_pushovers as $pushover) {
1370
+ $this->gawd_pushover_api($pushover['user_key'], $pushover['metric'], $pushover['condition'], $pushover['value']);
1371
+ if(!wp_next_scheduled('gawd_pushover_'.$pushover['period'])){
1372
+ wp_schedule_event(time(),$pushover['period'], 'gawd_pushover_'.$pushover['period']) ;
1373
+ }
1374
+ }
1375
+ }
1376
+ }
1377
+ $gawd_show_in_dashboard = isset($_POST['gawd_show_in_dashboard']) ? sanitize_text_field($_POST['gawd_show_in_dashboard']) : '';
1378
+
1379
+ $gawd_permissions = isset($_POST['gawd_permissions']) ? $_POST['gawd_permissions'] : array();
1380
+ $gawd_own_project = isset($_POST['gawd_own_project']) ? sanitize_text_field($_POST['gawd_own_project']) : '';
1381
+ $site_speed_rate = isset($_POST['site_speed_rate']) ? intval($_POST['site_speed_rate']) : '1';
1382
+ $post_page_chart = isset($_POST['post_page_chart']) ? sanitize_text_field($_POST['post_page_chart']) : '';
1383
+ $enable_cross_domain = isset($_POST['enable_cross_domain']) ? sanitize_text_field($_POST['enable_cross_domain']) : '';
1384
+ $cross_domains = isset($_POST['cross_domains']) ? sanitize_text_field($_POST['cross_domains']) : '';
1385
+ $default_date = isset($_POST['default_date']) ? $_POST['default_date'] : 'last_7_days';
1386
+ $default_date_format = isset($_POST['default_date_format']) ? $_POST['default_date_format'] : 'ymd_with_week';
1387
+ $enable_hover_tooltip = isset($_POST['enable_hover_tooltip']) ? $_POST['enable_hover_tooltip'] : '';
1388
+ $gawd_backend_roles = isset($_POST['gawd_backend_roles']) ? ($_POST['gawd_backend_roles']) : array();
1389
+ $gawd_frontend_roles = isset($_POST['gawd_frontend_roles']) ? ($_POST['gawd_frontend_roles']) : array();
1390
+ $gawd_post_page_roles = isset($_POST['gawd_post_page_roles']) ? ($_POST['gawd_post_page_roles']) : array();
1391
+ $exclude_events = isset($_POST['exclude_events']) ? sanitize_text_field($_POST['exclude_events']) : array();
1392
+ $gawd_settings_exist = get_option('gawd_settings');
1393
+ $gawd_settings_exist['gawd_show_in_dashboard'] = $gawd_show_in_dashboard;
1394
+ $gawd_settings_exist['site_speed_rate'] = $site_speed_rate;
1395
+ $gawd_settings_exist['post_page_chart'] = $post_page_chart;
1396
+ $gawd_settings_exist['enable_cross_domain'] = $enable_cross_domain;
1397
+ $gawd_settings_exist['cross_domains'] = $cross_domains;
1398
+ $gawd_settings_exist['gawd_backend_roles'] = $gawd_backend_roles;
1399
+ $gawd_settings_exist['gawd_frontend_roles'] = $gawd_frontend_roles;
1400
+ $gawd_settings_exist['gawd_post_page_roles'] = $gawd_post_page_roles;
1401
+ $gawd_settings_exist['default_date'] = $default_date;
1402
+ $gawd_settings_exist['default_date_format'] = $default_date_format;
1403
+ $gawd_settings_exist['enable_hover_tooltip'] = $enable_hover_tooltip;
1404
+ $gawd_settings_exist['exclude_events'] = $exclude_events;
1405
+ $gawd_settings_exist['gawd_permissions'] = $gawd_permissions;
1406
+ update_option('gawd_settings', $gawd_settings_exist);
1407
+ $gawd_filter_name = isset($_POST['gawd_filter_name']) ? sanitize_text_field($_POST['gawd_filter_name']) : '';
1408
+ $gawd_filter_type = isset($_POST['gawd_filter_type']) ? sanitize_text_field($_POST['gawd_filter_type']) : '';
1409
+ $gawd_filter_value = isset($_POST['gawd_filter_value']) ? $gawd_filter_type == 'GEO_IP_ADDRESS' ? ($_POST['gawd_filter_value']) : sanitize_text_field($_POST['gawd_filter_value']) : '';
1410
+ if ($gawd_filter_name != '' && $gawd_filter_type != '' && $gawd_filter_value != '') {
1411
+ $gawd_client->add_filter($gawd_filter_name, $gawd_filter_type, $gawd_filter_value);
1412
+ }
1413
+ add_option("gawd_save_settings",1) ;
1414
+ }
1415
+ if(get_option('gawd_save_settings') == 1){
1416
+ $this->gawd_admin_notice('Your changes have been saved successfully.','success is-dismissible');
1417
+ }
1418
+ delete_option('gawd_save_settings');
1419
+ require_once( 'admin/pages/settings.php' );
1420
+ }
1421
+ }
1422
+
1423
+ public function reset_user_data(){
1424
+ delete_option("gawd_credentials");
1425
+ $credentials['project_id'] = '115052745574-5vbr7tci4hjkr9clkflmnpto5jisgstg.apps.googleusercontent.com';
1426
+ $credentials['project_secret'] = 'wtNiu3c_bA_g7res6chV0Trt';
1427
+ update_option('gawd_credentials', $credentials);
1428
+ delete_option('gawd_own_project');
1429
+ delete_option('gawd_user_data');
1430
+
1431
+ }
1432
+ public function gawd_display_tracking_page() {
1433
+ global $gawd_client, $gawd_user_data;
1434
+ $gawd_client = GAWD_google_client::get_instance();
1435
+ $gawd_user_data = get_option('gawd_user_data');
1436
+ $add_dimension_value = isset($_POST['add_dimension_value']) ? $_POST['add_dimension_value'] : '';
1437
+ if(isset($_GET['errorMsg'])){
1438
+ self::error_message('error','User does not have sufficient permissions for this account');
1439
+ }
1440
+ if (isset($_POST['add_property'])) {
1441
+ $gawd_account_select = isset($_POST['gawd_account_select']) ? $_POST['gawd_account_select'] : '';
1442
+ $gawd_property_name = isset($_POST['gawd_property_name']) ? $_POST['gawd_property_name'] : '';
1443
+ if ($gawd_account_select && $gawd_property_name) {
1444
+ $err_msg = $gawd_client->add_webproperty($gawd_account_select, $gawd_property_name);
1445
+ $redirect_url = admin_url() . 'admin.php?page=gawd_tracking&enableTracking=1';
1446
+ if($err_msg){
1447
+ $redirect_url .='&errorMsg=1';
1448
+ }
1449
+ echo '<script>window.location.href="'.$redirect_url.'";</script>';
1450
+ }
1451
+ }
1452
+ if (isset($_POST['lock_property'])) {
1453
+ $property = $gawd_client->property_exists();
1454
+ $gawd_property_select = $_POST['gawd_property_select'];
1455
+ foreach ($property as $property_select) {
1456
+ if ($property_select['id'] == $gawd_property_select) {
1457
+ $property = $property_select;
1458
+ break;
1459
+ }
1460
+ }
1461
+ $gawd_user_data['webPropertyId'] = $property['id'];
1462
+ $gawd_user_data['default_webPropertyId'] = $property['id'];
1463
+ $gawd_user_data['accountId'] = $property['accountId'];
1464
+ $gawd_user_data['default_accountId'] = $property['accountId'];
1465
+ $gawd_user_data['gawd_id'] = $property['defaultProfileId'];
1466
+ update_option('gawd_user_data', $gawd_user_data);
1467
+ }
1468
+ if($this->manage_ua_code_selection_tracking() != 'done') {
1469
+ $redirect_url = admin_url() . 'admin.php?page=gawd_tracking';
1470
+ //echo '<script>window.location.href="'.$redirect_url.'";</script>';
1471
+ return;
1472
+ }
1473
+ if ($add_dimension_value == 'add_dimension_Logged_in') {
1474
+ $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1475
+ $gawd_client->add_custom_dimension('Logged in', $id);
1476
+ $settings = get_option('gawd_settings');
1477
+ $optname = 'gawd_custom_dimension_Logged_in';
1478
+ $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1479
+ update_option('gawd_settings', $settings);
1480
+
1481
+ }
1482
+ if ($add_dimension_value == 'add_dimension_Post_type') {
1483
+ $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1484
+ $gawd_client->add_custom_dimension('Post type', $id);
1485
+ $settings = get_option('gawd_settings');
1486
+ $optname = 'gawd_custom_dimension_Post_type';
1487
+ $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1488
+ update_option('gawd_settings', $settings);
1489
+
1490
+ }
1491
+ if ($add_dimension_value == 'add_dimension_Author') {
1492
+ $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1493
+ $gawd_client->add_custom_dimension('Author', $id);
1494
+ $settings = get_option('gawd_settings');
1495
+ $optname = 'gawd_custom_dimension_Author';
1496
+ $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1497
+ update_option('gawd_settings', $settings);
1498
+
1499
+ }
1500
+ if ($add_dimension_value == 'add_dimension_Category') {
1501
+ $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1502
+ $gawd_client->add_custom_dimension('Category', $id);
1503
+ $settings = get_option('gawd_settings');
1504
+ $optname = 'gawd_custom_dimension_Category';
1505
+
1506
+ $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1507
+ update_option('gawd_settings', $settings);
1508
+ }
1509
+ if ($add_dimension_value == 'add_dimension_Published_Month') {
1510
+ $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1511
+ $gawd_client->add_custom_dimension('Published Month', $id);
1512
+ $settings = get_option('gawd_settings');
1513
+ $optname = 'gawd_custom_dimension_Published_Month';
1514
+ $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1515
+ update_option('gawd_settings', $settings);
1516
+
1517
+ }
1518
+ if ($add_dimension_value == 'add_dimension_Published_Year') {
1519
+ $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1520
+ $gawd_client->add_custom_dimension('Published Year', $id);
1521
+ $settings = get_option('gawd_settings');
1522
+ $optname = 'gawd_custom_dimension_Published_Year';
1523
+ $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1524
+ update_option('gawd_settings', $settings);
1525
+
1526
+ }
1527
+ if ($add_dimension_value == 'add_dimension_Tags') {
1528
+ $id = isset($_POST['gawd_custom_dimension_id']) ? ($_POST['gawd_custom_dimension_id'] + 1) : 1;
1529
+ $gawd_client->add_custom_dimension('Tags', $id);
1530
+ $settings = get_option('gawd_settings');
1531
+ $optname = 'gawd_custom_dimension_Tags';
1532
+ $settings[$optname] = isset($_POST['gawd_tracking_enable']) ? $_POST['gawd_tracking_enable'] : '';
1533
+ update_option('gawd_settings', $settings);
1534
+ }
1535
+ if (isset($_POST['settings_submit'])) {
1536
+ check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
1537
+ $gawd_user_data = get_option('gawd_user_data');
1538
+ $gawd_file_formats = isset($_POST['gawd_file_formats']) ? sanitize_text_field($_POST['gawd_file_formats']) : '';
1539
+ $gawd_anonymize = isset($_POST['gawd_anonymize']) ? sanitize_text_field($_POST['gawd_anonymize']) : '';
1540
+ $gawd_tracking_enable = isset($_POST['gawd_tracking_enable']) ? sanitize_text_field($_POST['gawd_tracking_enable']) : '';
1541
+ $gawd_outbound = isset($_POST['gawd_outbound']) ? sanitize_text_field($_POST['gawd_outbound']) : '';
1542
+ $gawd_enhanced = isset($_POST['gawd_enhanced']) ? sanitize_text_field($_POST['gawd_enhanced']) : '';
1543
+ if($add_dimension_value == ''){
1544
+ $gawd_cd_Logged_in = isset($_POST['gawd_custom_dimension_Logged_in']) ? sanitize_text_field($_POST['gawd_custom_dimension_Logged_in']) : '';
1545
+ $gawd_cd_Post_type = isset($_POST['gawd_custom_dimension_Post_type']) ? sanitize_text_field($_POST['gawd_custom_dimension_Post_type']) : '';
1546
+ $gawd_cd_Author = isset($_POST['gawd_custom_dimension_Author']) ? sanitize_text_field($_POST['gawd_custom_dimension_Author']) : '';
1547
+ $gawd_cd_Category = isset($_POST['gawd_custom_dimension_Category']) ? sanitize_text_field($_POST['gawd_custom_dimension_Category']) : '';
1548
+ $gawd_cd_Published_Month = isset($_POST['gawd_custom_dimension_Published_Month']) ? sanitize_text_field($_POST['gawd_custom_dimension_Published_Month']) : '';
1549
+ $gawd_cd_Published_Year = isset($_POST['gawd_custom_dimension_Published_Year']) ? sanitize_text_field($_POST['gawd_custom_dimension_Published_Year']) : '';
1550
+ $gawd_cd_Tags = isset($_POST['gawd_custom_dimension_Tags']) ? sanitize_text_field($_POST['gawd_custom_dimension_Tags']) : '';
1551
+ $gawd_settings['gawd_custom_dimension_Logged_in'] = $gawd_cd_Logged_in;
1552
+ $gawd_settings['gawd_custom_dimension_Post_type'] = $gawd_cd_Post_type;
1553
+ $gawd_settings['gawd_custom_dimension_Author'] = $gawd_cd_Author;
1554
+ $gawd_settings['gawd_custom_dimension_Category'] = $gawd_cd_Category;
1555
+ $gawd_settings['gawd_custom_dimension_Published_Month'] = $gawd_cd_Published_Month;
1556
+ $gawd_settings['gawd_custom_dimension_Published_Year'] = $gawd_cd_Published_Year;
1557
+ $gawd_settings['gawd_custom_dimension_Tags'] = $gawd_cd_Tags;
1558
+ }
1559
+ $gawd_excluded_roles = isset($_POST['gawd_excluded_roles']) ? $_POST['gawd_excluded_roles'] : array();
1560
+ $gawd_excluded_users = isset($_POST['gawd_excluded_users']) ? $_POST['gawd_excluded_users'] : array();
1561
+ $gawd_settings = get_option('gawd_settings');
1562
+ $gawd_settings['gawd_file_formats'] = $gawd_file_formats;
1563
+ $gawd_settings['gawd_anonymize'] = $gawd_anonymize;
1564
+ $gawd_settings['gawd_file_formats'] = $gawd_file_formats;
1565
+ $gawd_settings['gawd_tracking_enable'] = $gawd_tracking_enable;
1566
+ $gawd_settings['gawd_outbound'] = $gawd_outbound;
1567
+ $gawd_settings['gawd_enhanced'] = $gawd_enhanced;
1568
+ $gawd_settings['gawd_excluded_roles'] = $gawd_excluded_roles;
1569
+ $gawd_settings['gawd_excluded_users'] = $gawd_excluded_users;
1570
+ update_option('gawd_settings', $gawd_settings);
1571
+ add_option("gawd_save_tracking",1) ;
1572
+ }
1573
+ if(get_option('gawd_save_tracking') == 1){
1574
+ $this->gawd_admin_notice('Your changes have been saved successfully.','success is-dismissible');
1575
+ }
1576
+ delete_option('gawd_save_tracking');
1577
+ $gawd_settings = get_option('gawd_settings');
1578
+ if($add_dimension_value != ''){
1579
+ $redirect_url = admin_url() . 'admin.php?page=gawd_tracking';
1580
+ echo '<script>window.location.href="'.$redirect_url.'";</script>';
1581
+ }
1582
+ require_once( 'admin/pages/tracking.php' );
1583
+ }
1584
+
1585
+ public function gawd_my_schedule() {
1586
+ $schedules['gawd_weekly'] = array(
1587
+ 'interval' => 604800,
1588
+ 'display' => __('Every week')
1589
+ );
1590
+ $schedules['gawd_monthly'] = array(
1591
+ 'interval' => 18748800,
1592
+ 'display' => __('Every month')
1593
+ );
1594
+ return $schedules;
1595
+ }
1596
+
1597
+ public function gawd_pushover_api($user_key, $metric, $condition, $value) {
1598
+ $ch = curl_init();
1599
+ curl_setopt($ch, CURLOPT_URL, "https://api.pushover.net/1/messages.json");
1600
+ curl_setopt($ch, CURLOPT_POSTFIELDS, array(
1601
+ "token" => "aJBDhTfhR87EaTzs7wpx1MMKwboBjB",
1602
+ "user" => $user_key,
1603
+ "message" => 'The ' . $metric . ' less ' . $value));
1604
+ // curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
1605
+ curl_exec($ch);
1606
+ curl_close($ch);
1607
+ }
1608
+
1609
+ public function gawd_pushover_daily() {
1610
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1611
+ $gawd_client = GAWD_google_client::get_instance();
1612
+ $pushovers = get_option('gawd_pushovers');
1613
+ $data = '';
1614
+ $condition = '';
1615
+
1616
+ foreach ($pushovers as $pushover) {
1617
+ if (isset($pushover['period']) && $pushover['period'] == 'daily') {
1618
+ //pls send email if ....
1619
+ $date = date('Y-m-d', strtotime('yesterday'));
1620
+ $data = $gawd_client->get_data_alert('ga:' . $pushover['metric'], 'date', $date, $date, $pushover['pushover_view']);
1621
+ $pushover_condition = $pushover['condition'] == 'greater' ? '>' : '<';
1622
+ if (!eval($data . $pushover_condition . $pushover['value'] . ';')) {
1623
+ $cond = ' '.$pushover['condition'] . ' than';
1624
+ $this->gawd_pushover_api($pushover['user_key'], $pushover['metric'], $pushover['condition'], $pushover['value']);
1625
+ }
1626
+ }
1627
+ }
1628
+ }
1629
+
1630
+ public function gawd_pushover_weekly() {
1631
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1632
+ $gawd_client = GAWD_google_client::get_instance();
1633
+ $pushovers = get_option('gawd_pushovers');
1634
+ $data = '';
1635
+ $condition = '';
1636
+ foreach ($pushovers as $pushover) {
1637
+ if (isset($pushover['period']) && $pushover['period'] == 'gawd_weekly') {
1638
+ //pls send email if ....
1639
+ $start_date = date('Y-m-d', strtotime('last week -1 day'));
1640
+ $end_date = date('l') != 'Sunday' ? date('Y-m-d',strtotime('last sunday -1 day')) : date('Y-m-d', strtotime('-1 day'));
1641
+ $data = $gawd_client->get_data_alert('ga:' . $pushover['metric'], 'date', $start_date, $end_date, $pushover['pushover_view']);
1642
+ $pushover_condition = $pushover['condition'] == 'greater' ? '>' : '<';
1643
+ if (!eval($data . $pushover_condition . $pushover['value'] . ';')) {
1644
+ $cond = ' '.$pushover['condition'] . ' than';
1645
+ $this->gawd_pushover_api($pushover['user_key'], $pushover['metric'], $pushover['condition'], $pushover['value']);
1646
+ }
1647
+ }
1648
+ }
1649
+ }
1650
+
1651
+ public function gawd_pushover_monthly() {
1652
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1653
+ $gawd_client = GAWD_google_client::get_instance();
1654
+ $pushovers = get_option('gawd_pushovers');
1655
+ $data = '';
1656
+ $condition = '';
1657
+ foreach ($pushovers as $pushover) {
1658
+ if (isset($pushover['period']) && $pushover['period'] == 'gawd_monthly') {
1659
+ //pls send email if ....
1660
+ $end_date = date('Y-m-t', strtotime('last month'));
1661
+ $start_date = date('Y-m-01', strtotime('last month'));
1662
+ $data = $gawd_client->get_data_alert('ga:' . $pushover['metric'], 'date', $start_date, $end_date, $pushover['pushover_view']);
1663
+ $pushover_condition = $pushover['condition'] == 'greater' ? '>' : '<';
1664
+ if (!eval($data . $pushover_condition . $pushover['value'] . ';')) {
1665
+ $cond = ' '.$pushover['condition'] . ' than';
1666
+ $this->gawd_pushover_api($pushover['user_key'], $pushover['metric'], $pushover['condition'], $pushover['value']);
1667
+ }
1668
+ }
1669
+ }
1670
+ }
1671
+
1672
+ public function gawd_alert_daily() {
1673
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1674
+ $gawd_client = GAWD_google_client::get_instance();
1675
+ $alerts = get_option('gawd_alerts');
1676
+ $data = '';
1677
+ $condition = '';
1678
+ $email_from = get_option('admin_email');
1679
+ foreach ($alerts as $alert) {
1680
+ if (isset($alert['period']) && $alert['period'] == 'daily') {
1681
+ //pls send email if ....
1682
+ $date = date('Y-m-d', strtotime('yesterday'));
1683
+ $data = $gawd_client->get_data_alert('ga:' . $alert['metric'], 'date', $date, $date, $alert['alert_view']);
1684
+ $alert_condition = $alert['condition'] == 'greater' ? '>' : '<';
1685
+ $color_condition = $alert['condition'] == 'greater' ? 'rgb(157, 207, 172)' : 'rgb(251, 133, 131)';
1686
+ if (!eval($data . $alert_condition . $alert['value'] . ';')) {
1687
+ $cond = ' '.$alert['condition'] . ' than';
1688
+ $headers = array();
1689
+ $headers[] = 'From: <' . $email_from . '>';
1690
+ $headers[] = 'Content-Type: text/html';
1691
+ $content = '<div style="font-family: sans-serif;width:100%;height:50px;background-color:#FB8583;font-size:20px;color:#fff;margin-bottom:20px;text-align:center;line-height:50px">Google Analytics WD Alert!</div><p style="color:#808080;text-align: center;font-size: 26px;font-family: sans-serif;">' . preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $alert['metric'])))). ' in <a style="text-decoration:none;color:rgba(124,181,216,1);font-family: sans-serif;" href="' . $alert["alert_view_name"] . '" target="_blank">' . $alert["alert_view_name"] . '</a> are <span style="color:'.$color_condition.'">' . $cond . '</span></p><p style="color:rgba(124,181,216,1);font-size: 26px;font-family: sans-serif; text-align: center;">' . $alert['value'] . '</p>';
1692
+ wp_mail($alert['emails'], 'Analytics Alert',$content, $headers);
1693
+ }
1694
+ }
1695
+ }
1696
+ }
1697
+ public function gawd_alert_weekly() {
1698
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1699
+ $gawd_client = GAWD_google_client::get_instance();
1700
+ $alerts = get_option('gawd_alerts');
1701
+ $data = '';
1702
+ $condition = '';
1703
+ $email_from = get_option('admin_email');
1704
+ foreach ($alerts as $alert) {
1705
+ if (isset($alert['period']) && $alert['period'] == 'gawd_weekly') {
1706
+ //pls send email if ....
1707
+ $start_date = date('Y-m-d', strtotime('last week -1 day'));
1708
+ $end_date = date('l') != 'Sunday' ? date('Y-m-d',strtotime('last sunday -1 day')) : date('Y-m-d', strtotime('-1 day'));
1709
+ $data = $gawd_client->get_data_alert('ga:' . $alert['metric'], 'date', $start_date, $end_date, $alert['alert_view']);
1710
+ $alert_condition = $alert['condition'] == 'greater' ? '>' : '<';
1711
+ if (!eval($data . $alert_condition . $alert['value'] . ';')) {
1712
+ $cond = ' '.$alert['condition'] . ' than';
1713
+ $headers = array();
1714
+ $headers[] = 'From: <' . $email_from . '>';
1715
+ $headers[] = 'Content-Type: text/html';
1716
+ $content = '<div style="font-family: sans-serif;width:100%;height:50px;background-color:#FB8583;font-size:20px;color:#fff;margin-bottom:20px;text-align:center;line-height:50px">Google Analytics WD Alert!</div><p style="color:#808080;text-align: center;font-size: 26px;font-family: sans-serif;">' . preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $alert['metric'])))). ' in <a style="text-decoration:none;color:rgba(124,181,216,1);font-family: sans-serif;" href="' . $alert["alert_view_name"] . '" target="_blank">' . $alert["alert_view_name"] . '</a> are <span style="color:'.$color_condition.'">' . $cond . '</span></p><p style="color:rgba(124,181,216,1);font-size: 26px;font-family: sans-serif; text-align: center;">' . $alert['value'] . '</p>';
1717
+ wp_mail($alert['emails'], 'Analytics Alert',$content, $headers);
1718
+ }
1719
+ }
1720
+ }
1721
+ }
1722
+
1723
+ public function gawd_alert_monthly() {
1724
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1725
+ $gawd_client = GAWD_google_client::get_instance();
1726
+ $alerts = get_option('gawd_alerts');
1727
+ $data = '';
1728
+ $email_from = get_option('admin_email');
1729
+ foreach ($alerts as $alert) {
1730
+ if (isset($alert['period']) && $alert['period'] == 'gawd_monthly') {
1731
+ //pls send email if ....
1732
+ $end_date = date('Y-m-t', strtotime('last month'));
1733
+ $start_date = date('Y-m-01', strtotime('last month'));
1734
+ $data = $gawd_client->get_data_alert('ga:' . $alert['metric'], 'date', $start_date, $end_date, $alert['alert_view']);
1735
+ $alert_condition = $alert['condition'] == 'greater' ? '>' : '<';
1736
+ if (!eval($data . $alert_condition . $alert['value'] . ';')) {
1737
+ $cond = ' '.$alert['condition'] . ' than';
1738
+ $headers = array();
1739
+ $headers[] = 'From: <' . $email_from . '>';
1740
+ $headers[] = 'Content-Type: text/html';
1741
+ $content = '<div style="font-family: sans-serif;width:100%;height:50px;background-color:#FB8583;font-size:20px;color:#fff;margin-bottom:20px;text-align:center;line-height:50px">Google Analytics WD Alert!</div><p style="color:#808080;text-align: center;font-size: 26px;font-family: sans-serif;">' . preg_replace('!\s+!',' ',trim(ucfirst(preg_replace('/([A-Z])/', ' $1', $alert['metric'])))). ' in <a style="text-decoration:none;color:rgba(124,181,216,1);font-family: sans-serif;" href="' . $alert["alert_view_name"] . '" target="_blank">' . $alert["alert_view_name"] . '</a> are <span style="color:'.$color_condition.'">' . $cond . '</span></p><p style="color:rgba(124,181,216,1);font-size: 26px;font-family: sans-serif; text-align: center;">' . $alert['value'] . '</p>';
1742
+ wp_mail($alert['emails'], 'Analytics Alert',$content, $headers);
1743
+ }
1744
+ }
1745
+ }
1746
+ }
1747
+
1748
+ public function wd_dashboard_widget() {
1749
+ global $gawd_client, $gawd_user_data;
1750
+ $gawd_client = GAWD_google_client::get_instance();
1751
+ $profiles = $gawd_client->get_profiles();
1752
+ $gawd_user_data = get_option('gawd_user_data');
1753
+ if(isset($_POST['gawd_id'])){
1754
+ $gawd_user_data['gawd_id'] = isset($_POST['gawd_id']) ? $_POST['gawd_id'] : '';
1755
+ foreach ($gawd_user_data['gawd_profiles'] as $web_property_name => $web_property) {
1756
+ foreach ($web_property as $profile) {
1757
+ if ($profile['id'] == $gawd_user_data['gawd_id']) {
1758
+ $gawd_user_data['web_property_name'] = $web_property_name;
1759
+ $gawd_user_data['webPropertyId'] = $profile['webPropertyId'];
1760
+ $gawd_user_data['accountId'] = $profile['accountId'];
1761
+ }
1762
+ }
1763
+ }
1764
+ $gawd_user_data['web_property_name'] = isset($_POST['web_property_name']) ? $_POST['web_property_name'] : '';
1765
+ update_option('gawd_user_data', $gawd_user_data);
1766
+ }
1767
+ require_once( 'admin/pages/dashboard_widget.php' );
1768
+ }
1769
+
1770
+ public function google_analytics_wd_dashboard_widget() {
1771
+ $gawd_settings = get_option('gawd_settings');
1772
+ $gawd_backend_roles = isset($gawd_settings['gawd_backend_roles']) ? $gawd_settings['gawd_backend_roles'] : array();
1773
+ $roles = $this->get_current_user_role();
1774
+
1775
+ if (isset($gawd_settings['gawd_show_in_dashboard']) && $gawd_settings['gawd_show_in_dashboard'] == 'on') {
1776
+ if (in_array($roles, $gawd_backend_roles) || current_user_can('manage_options')) {
1777
+ wp_add_dashboard_widget('wd_dashboard_widget', 'WD Google Analytics', array($this, 'wd_dashboard_widget'));
1778
+ }
1779
+ }
1780
+ }
1781
+
1782
+ public function show_data($params = array()) {
1783
+ /* if (isset($_REQUEST['security'])) {
1784
+ check_ajax_referer('gawd_admin_page_nonce', 'security');
1785
+ } else {
1786
+ check_admin_referer('gawd_save_form', 'gawd_save_form_fild');
1787
+ } */
1788
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1789
+ $return = true;
1790
+ if ($params == '') {
1791
+ $params = $_POST;
1792
+ $return = false;
1793
+ }
1794
+ $gawd_client = GAWD_google_client::get_instance();
1795
+ $start_date = isset($params["start_date"]) && $params["start_date"] != '' ? $params["start_date"] : date('Y-m-d', strtotime('-7 days'));
1796
+ $end_date = isset($params["end_date"]) && $params["end_date"] != '' ? $params["end_date"] : date('Y-m-d');
1797
+ $metric = isset($params["metric"]) ? $params["metric"] : 'ga:sessions';
1798
+ $metric = is_array($metric) ? count($metric) > 1 ? implode(",", $metric) : $metric[0] : $metric;
1799
+ $dimension = isset($params["dimension"]) ? $params["dimension"] : 'date';
1800
+
1801
+ $country_filter = isset($params["country_filter"]) ? $params["country_filter"] : '';
1802
+ $geo_type = isset($params["geo_type"]) ? $params["geo_type"] : '';
1803
+ $filter_type = isset($params["filter_type"]) && $params["filter_type"] != '' ? $params["filter_type"] : '';
1804
+ $custom = isset($params["custom"]) && $params["custom"] != '' ? $params["custom"] : '';
1805
+ $same_dimension = $dimension;
1806
+
1807
+ $dimension = $filter_type != '' && $dimension == 'date' ? $filter_type : $dimension;
1808
+ if ($dimension == 'week' || $dimension == 'month') {
1809
+ $same_dimension = $dimension;
1810
+ }
1811
+
1812
+
1813
+ $timezone = isset($params["timezone"]) && $params["timezone"] != '' ? $params["timezone"] : 0;
1814
+ if ($dimension == 'pagePath' || $dimension == 'PagePath' || $dimension == 'landingPagePath' || $dimension == 'LandingPagePath') {
1815
+ if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date)) {
1816
+ $grid_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1817
+ } else {
1818
+ $grid_data = $gawd_client->get_page_data($dimension, $start_date, $end_date, $timezone);
1819
+ }
1820
+ if ($return) {
1821
+ return $grid_data;
1822
+ }
1823
+ echo $grid_data;
1824
+ die();
1825
+ }
1826
+ elseif ($dimension == 'goals') {
1827
+ if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date)) {
1828
+ $goal_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1829
+ } else {
1830
+ $goal_data = $gawd_client->get_goal_data('date', $start_date, $end_date, $timezone,$same_dimension);
1831
+ }
1832
+ if ($return) {
1833
+ return $goal_data;
1834
+ }
1835
+ echo $goal_data;
1836
+ die();
1837
+ }
1838
+ elseif (($dimension == 'region' || $dimension == 'city') || ($dimension == 'Region' || $dimension == 'City')) {
1839
+ if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $country_filter . '-' . $start_date . '-' . $end_date)) {
1840
+ $chart_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $country_filter . '-' . $start_date . '-' . $end_date);
1841
+ } else {
1842
+
1843
+ $chart_data = $gawd_client->get_country_data($metric, $dimension, $start_date, $end_date, $country_filter, $geo_type, $timezone);
1844
+ }
1845
+ if ($return) {
1846
+ return $chart_data;
1847
+ }
1848
+ echo $chart_data;
1849
+ die();
1850
+ }
1851
+ else {
1852
+ if($custom != ''){
1853
+ $chart_data = $gawd_client->get_data($metric, $dimension, $start_date, $end_date, $filter_type, $timezone, $same_dimension);
1854
+ }
1855
+ else{
1856
+ if($dimension == 'siteSpeed'){
1857
+ if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $same_dimension . '_' . $filter_type . '-' . $start_date . '-' . $end_date)) {
1858
+ $chart_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1859
+ } else {
1860
+ $chart_data = $gawd_client->get_data($metric, $dimension, $start_date, $end_date, $filter_type, $timezone, $same_dimension);
1861
+ }
1862
+ if ($return) {
1863
+ return $chart_data;
1864
+ }
1865
+ }
1866
+ else{
1867
+
1868
+ /* if (get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date)) {
1869
+ $chart_data = get_transient('gawd-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1870
+ } */
1871
+ //else {
1872
+
1873
+ $chart_data = $gawd_client->get_data($metric, $dimension, $start_date, $end_date, $filter_type, $timezone, $same_dimension);
1874
+ //}
1875
+ if ($return) {
1876
+ return $chart_data;
1877
+ }
1878
+ }
1879
+ }
1880
+ echo $chart_data;
1881
+ die();
1882
+ }
1883
+ }
1884
+
1885
+ public function show_data_compact() {
1886
+ check_ajax_referer('gawd_admin_page_nonce', 'security');
1887
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1888
+ $gawd_client = GAWD_google_client::get_instance();
1889
+ $start_date = isset($_POST["start_date"]) && $_POST["start_date"] != '' ? $_POST["start_date"] : date('Y-m-d', strtotime('-30 days'));
1890
+ $end_date = isset($_POST["end_date"]) && $_POST["end_date"] != '' ? $_POST["end_date"] : date('Y-m-d');
1891
+ $metric = isset($_POST["metric"]) ? $_POST["metric"] : 'sessions';
1892
+ $metric = is_array($metric) ? count($metric) > 1 ? implode(",", $metric) : $metric[0] : 'ga:' . $metric;
1893
+ $dimension = isset($_POST["dimension"]) ? $_POST["dimension"] : 'date';
1894
+ $timezone = isset($_POST["timezone"]) ? $_POST["timezone"] : 0;
1895
+ if (get_transient('gawd-compact-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date)) {
1896
+ $chart_data = get_transient('gawd-compact-' . $gawd_client->get_profile_id() . '-' . $dimension . '-' . $start_date . '-' . $end_date);
1897
+ } else {
1898
+ $chart_data = $gawd_client->get_data_compact($metric, $dimension, $start_date, $end_date, $timezone);
1899
+ }
1900
+ echo $chart_data;
1901
+ die();
1902
+ }
1903
+
1904
+ public function show_page_post_data() {
1905
+ check_ajax_referer('gawd_admin_page_nonce', 'security');
1906
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1907
+ $gawd_client = GAWD_google_client::get_instance();
1908
+ $start_date = isset($_POST["start_date"]) && $_POST["start_date"] != '' ? $_POST["start_date"] : date('Y-m-d', strtotime('-30 days'));
1909
+ $end_date = isset($_POST["end_date"]) && $_POST["end_date"] != '' ? $_POST["end_date"] : date('Y-m-d');
1910
+ $metric = isset($_POST["metric"]) ? $_POST["metric"] : 'ga:sessions';
1911
+ $metric = is_array($metric) ? count($metric) > 1 ? implode(",", $metric) : $metric[0] : $metric;
1912
+ $dimension = isset($_POST["dimension"]) ? $_POST["dimension"] : 'date';
1913
+ $timezone = isset($_POST["timezone"]) ? $_POST["timezone"] : 0;
1914
+ $filter = isset($_POST["filter"]) ? substr($_POST["filter"], 1) : '';
1915
+ $chart = isset($_POST["chart"]) ? $_POST["chart"] : '';
1916
+ $chart_data = get_transient('gawd-page-post-' . $gawd_client->get_profile_id() . '-' . $filter . '-' . '-' . $dimension . '-' . $start_date . '-' . $end_date. '-' . $chart);
1917
+ if (!$chart_data) {
1918
+ $chart_data = $gawd_client->get_post_page_data($metric, $dimension, $start_date, $end_date, $filter, $timezone, $chart);
1919
+ }
1920
+ echo $chart_data;
1921
+ die();
1922
+ }
1923
+
1924
+ public function get_realtime() {
1925
+ check_ajax_referer('gawd_admin_page_nonce', 'security');
1926
+ require_once(GAWD_DIR . '/admin/gawd_google_class.php');
1927
+ $gawd_client = GAWD_google_client::get_instance();
1928
+ $chart_data = get_transient('gawd-real' . $gawd_client->get_profile_id());
1929
+ if (!$chart_data) {
1930
+ $chart_data = $gawd_client->gawd_realtime_data();
1931
+ }
1932
+ return $chart_data;
1933
+ }
1934
+
1935
+ /**
1936
+ * Checks if the protocol is secure.
1937
+ *
1938
+ * @return boolean
1939
+ */
1940
+ public static function is_ssl() {
1941
+ if (isset($_SERVER['HTTPS'])) {
1942
+ if ('on' == strtolower($_SERVER['HTTPS']))
1943
+ return true;
1944
+ if ('1' == $_SERVER['HTTPS'])
1945
+ return true;
1946
+ } elseif (isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] )) {
1947
+ return true;
1948
+ }
1949
+ return false;
1950
+ }
1951
+
1952
+ /**
1953
+ * Returns the Singleton instance of this class.
1954
+ *
1955
+ * @return GAWD The Singleton instance.
1956
+ */
1957
+ public static function get_instance() {
1958
+ if (null === static::$instance) {
1959
+ static::$instance = new static();
1960
+ }
1961
+ return static::$instance;
1962
+ }
1963
+
1964
+ /**
1965
+ * Private clone method to prevent cloning of the instance of the
1966
+ * Singleton instance.
1967
+ *
1968
+ * @return void
1969
+ */
1970
+ private function __clone() {
1971
+
1972
+ }
1973
+
1974
+ /**
1975
+ * Private unserialize method to prevent unserializing of the Singleton
1976
+ * instance.
1977
+ *
1978
+ * @return void
1979
+ */
1980
+ private function __wakeup() {
1981
+
1982
+ }
1983
+
1984
+ public static function add_dashboard_menu() {
1985
+ $get_custom_reports = get_option('gawd_custom_reports');
1986
+ if (!$get_custom_reports) {
1987
+ $custom_report = array();
1988
+ } else {
1989
+ foreach ($get_custom_reports as $name => $report) {
1990
+ $custom_report['custom_report_' . $name] = __($name, "gawd");
1991
+ }
1992
+ }
1993
+ $tabs = array(
1994
+ "general" => array(
1995
+ "title" => __("Audience", "gawd"),
1996
+ "childs" => array(),
1997
+ "desc" => "Report of your website audience. Provides details about new and returning users of your website, sessions, bounces, pageviews and session durations."
1998
+ ),
1999
+ "realtime" => array(
2000
+ "title" => __("Real Time", "gawd"),
2001
+ "childs" => array(),
2002
+ "desc" => "Real Time statistics show the number of active users currently visiting your website pages."
2003
+ ),
2004
+ "demographics" => array(
2005
+ "title" => __("Demographics", "gawd"),
2006
+ "childs" => array(
2007
+ "userGender" => __("User Gender", "gawd"),
2008
+ "userAge" => __("User Age", "gawd")
2009
+ ),
2010
+ "desc" => "Demographics display tracking statistics of your website users based on their age and gender. "
2011
+
2012
+ ),
2013
+ "interests" => array(
2014
+ "title" => __("Interests", "gawd"),
2015
+ "childs" => array(
2016
+ "inMarket" => __("In-Market Segment", "gawd"),
2017
+ "affinityCategory" => __("Affinity Category", "gawd"),
2018
+ "otherCategory" => __("Other Category", "gawd")
2019
+ ),
2020
+ "desc" => "Provides tracking information about site users depending on Affinity Categories (e.g. Music Lovers or Mobile Enthusiasts), In-Market Segments (based on online product purchase interests) and Other Categories (most specific identification, for example, tennis lovers among Sports Fans)."
2021
+ ),
2022
+ "geo" => array(
2023
+ "title" => __("GEO", "gawd"),
2024
+ "childs" => array(
2025
+ "location" => __("Location", "gawd"),
2026
+ "language" => __("Language", "gawd")
2027
+ ),
2028
+ "desc" => "Geo-identifier report is built from interactions of location (countries, cities) and language of your website users."
2029
+ ),
2030
+ "behavior" => array(
2031
+ "title" => __("Behavior", "gawd"),
2032
+ "childs" => array(
2033
+ "behaviour" => __("New vs Returning", "gawd"),
2034
+ "engagement" => __("Engagement", "gawd")
2035
+ ),
2036
+ "desc" => "Compares number of New visitors and Returning users of your website in percents. You can check the duration of sessions with Engagement report."
2037
+ ),
2038
+ "technology" => array(
2039
+ "title" => __("Technology", "gawd"),
2040
+ "childs" => array(
2041
+ "os" => __("OS", "gawd"),
2042
+ "browser" => __("Browser", "gawd")
2043
+ ),
2044
+ "desc" => "Identifies tracking of the site based on operating systems and browsers visitors use."
2045
+ ),
2046
+ "mobile" => array(
2047
+ "title" => __("Mobile", "gawd"),
2048
+ "childs" => array(
2049
+ "device_overview" => __("Overview", "gawd"),
2050
+ "devices" => __("Devices", "gawd")
2051
+ ),
2052
+ "desc" => "Shows statistics of mobile and desktop devices visitors have used while interacting with your website."
2053
+ ),
2054
+ "custom" => array(
2055
+ "title" => __("Custom Dimensions", "gawd"),
2056
+ "childs" => array(),
2057
+ "desc" => "Set up Custom Dimensions based on Users, Post type, Author, Category, Publication date and Tags in Custom Dimensions page, and view their report in this tab."
2058
+ ),
2059
+ "trafficSource" => array(
2060
+ "title" => __("Traffic Source", "gawd"),
2061
+ "childs" => array(),
2062
+ "desc" => "Displays overall graph of traffic sources directing to your website."
2063
+ ),
2064
+ "adWords" => array(
2065
+ "title" => __("AdWords", "gawd"),
2066
+ "childs" => array(),
2067
+ "desc" => "If your website is registered on Google AdWords, you can link its Google Analytics to AdWords, and gather relevant tracking information with this report."
2068
+ ),
2069
+ /* "pagePath" => array(
2070
+ "title" => __("Pages", "gawd"),
2071
+ "childs" => array(),
2072
+ "desc" => "Pages report table will provide you information about Bounces, Entrances, Pageviews, Unique Pageviews, time spent on pages, Exits and Average page loading time."
2073
+ ), */
2074
+ "siteContent" => array(
2075
+ "title" => __("Site Content", "gawd"),
2076
+ "childs" => array(
2077
+ "pagePath" => __("All Pages", "gawd"),
2078
+ "landingPagePath" => __("Landing Pages", "gawd"),
2079
+ ),
2080
+ "desc" => "Pages report table will provide you information about Bounces, Entrances, Pageviews, Unique Pageviews, time spent on pages, Exits and Average page loading time."
2081
+ ),
2082
+ "siteSpeed" => array(
2083
+ "title" => __("Site Speed", "gawd"),
2084
+ "childs" => array(),
2085
+ "desc" => "Shows the average load time of your website users experienced during specified date range."
2086
+ ),
2087
+ "events" => array(
2088
+ "title" => __("Events", "gawd"),
2089
+ "childs" => array(
2090
+ "eventsLabel" => __("Events by Label", "gawd"),
2091
+ "eventsAction" => __("Events by Action", "gawd"),
2092
+ "eventsCategory" => __("Events by Category", "gawd")
2093
+ ),
2094
+ "desc" => "Displays the report based on Events you set up on Google Analytics of your website. Graphs are built based on Event Labels, Categories and Actions."
2095
+ ),
2096
+ "goals" => array(
2097
+ "title" => __("Goals", "gawd"),
2098
+ "childs" => array(),
2099
+ "desc" => "Set Goals from Goal Management and review their Google Analytics reports under this tab."
2100
+ ),
2101
+ "ecommerce" => array(
2102
+ "title" => __("Ecommerce", "gawd"),
2103
+ "childs" => array(
2104
+ "daysToTransaction" => __("TIme to Purchase", "gawd"),
2105
+ "transactionId" => __("Transaction ID", "gawd"),
2106
+ "sales_performance" => __("Sales Performance", "gawd"),
2107
+ "productSku" => __("Product Sku", "gawd"),
2108
+ "productCategory" => __("Product Category ", "gawd"),
2109
+ "productName" => __("Product Name", "gawd"),
2110
+ ),
2111
+ "desc" => "Check sales statistics of your website identified by revenues, transactions, products and performance."
2112
+ ),
2113
+ "adsense" => array(
2114
+ "title" => __("AdSense", "gawd"),
2115
+ "childs" => array(),
2116
+ "desc" => "Link your Google Analytics and AdSense accounts from Google Analytics Admin setting and keep track of AdSense tracking under this report."
2117
+ ),
2118
+ "customReport" => array(
2119
+ "title" => __("Custom Report", "gawd"),
2120
+ "childs" => $custom_report,
2121
+ "desc" => "Add Custom Reports from any metric and dimension in Custom Reports page, and view relevant Google Analytics tracking information in this tab."
2122
+ ),
2123
+ );
2124
+ update_option('gawd_menu_items', $tabs);
2125
+ }
2126
+ public function remove_zoom_message(){
2127
+ check_ajax_referer('gawd_admin_page_nonce', 'security');
2128
+ $got_it = isset($_REQUEST["got_it"]) ? sanitize_text_field($_REQUEST["got_it"]) : '';
2129
+ if($got_it != ''){
2130
+ add_option('gawd_zoom_message',$got_it);
2131
+ }
2132
+ }
2133
+ }
google-analytics-wd.php CHANGED
@@ -1,37 +1,37 @@
1
- <?php
2
-
3
- /**
4
- * Plugin Name: WD Google Analytics
5
- * Plugin URI: https://web-dorado.com/products/wordpress-google-analytics-plugin.html
6
- * Description: WD Google Analytics is a user-friendly all in one plugin, which allows to manage and monitor your website analytics from WordPress dashboard.
7
- * Version: 1.0.1
8
- * Author: WebDorado
9
- * Author URI: https://web-dorado.com
10
- * License: GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
11
- */
12
- if (!defined('GAWD_DIR')) {
13
- define('GAWD_DIR', dirname(__FILE__));
14
- }
15
-
16
- if (!defined('GWD_NAME')) {
17
- define('GWD_NAME', plugin_basename(dirname(__FILE__)));
18
- }
19
-
20
- if (!defined('GAWD_URL')) {
21
- define('GAWD_URL', plugins_url(plugin_basename(dirname(__FILE__))));
22
- }
23
-
24
- if (!defined('GAWD_INC')) {
25
- define('GAWD_INC', GAWD_URL . '/inc');
26
- }
27
-
28
- if (!defined('GAWD_VERSION')) {
29
- define('GAWD_VERSION', '0.0.0');
30
- }
31
-
32
- require_once( 'gawd_class.php' );
33
-
34
- add_action('plugins_loaded', array('GAWD', 'get_instance'));
35
-
36
- register_activation_hook(__FILE__, array('GAWD', 'activate'));
37
- register_deactivation_hook(__FILE__, array('GAWD', 'deactivate'));
1
+ <?php
2
+
3
+ /**
4
+ * Plugin Name: WD Google Analytics
5
+ * Plugin URI: https://web-dorado.com/products/wordpress-google-analytics-plugin.html
6
+ * Description: WD Google Analytics is a user-friendly all in one plugin, which allows to manage and monitor your website analytics from WordPress dashboard.
7
+ * Version: 1.0.2
8
+ * Author: WebDorado
9
+ * Author URI: https://web-dorado.com
10
+ * License: GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
11
+ */
12
+ if (!defined('GAWD_DIR')) {
13
+ define('GAWD_DIR', dirname(__FILE__));
14
+ }
15
+
16
+ if (!defined('GWD_NAME')) {
17
+ define('GWD_NAME', plugin_basename(dirname(__FILE__)));
18
+ }
19
+
20
+ if (!defined('GAWD_URL')) {
21
+ define('GAWD_URL', plugins_url(plugin_basename(dirname(__FILE__))));
22
+ }
23
+
24
+ if (!defined('GAWD_INC')) {
25
+ define('GAWD_INC', GAWD_URL . '/inc');
26
+ }
27
+
28
+ if (!defined('GAWD_VERSION')) {
29
+ define('GAWD_VERSION', '1.0.2');
30
+ }
31
+
32
+ require_once( 'gawd_class.php' );
33
+
34
+ add_action('plugins_loaded', array('GAWD', 'get_instance'));
35
+
36
+ register_activation_hook(__FILE__, array('GAWD', 'activate'));
37
+ register_deactivation_hook(__FILE__, array('GAWD', 'deactivate'));
google/Auth/Abstract.php CHANGED
@@ -1,38 +1,38 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * Abstract class for the Authentication in the API client
24
- * @author Chris Chabot <chabotc@google.com>
25
- *
26
- */
27
- abstract class Google_Auth_Abstract
28
- {
29
- /**
30
- * An utility function that first calls $this->auth->sign($request) and then
31
- * executes makeRequest() on that signed request. Used for when a request
32
- * should be authenticated
33
- * @param Google_Http_Request $request
34
- * @return Google_Http_Request $request
35
- */
36
- abstract public function authenticatedRequest(Google_Http_Request $request);
37
- abstract public function sign(Google_Http_Request $request);
38
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * Abstract class for the Authentication in the API client
24
+ * @author Chris Chabot <chabotc@google.com>
25
+ *
26
+ */
27
+ abstract class Google_Auth_Abstract
28
+ {
29
+ /**
30
+ * An utility function that first calls $this->auth->sign($request) and then
31
+ * executes makeRequest() on that signed request. Used for when a request
32
+ * should be authenticated
33
+ * @param Google_Http_Request $request
34
+ * @return Google_Http_Request $request
35
+ */
36
+ abstract public function authenticatedRequest(Google_Http_Request $request);
37
+ abstract public function sign(Google_Http_Request $request);
38
+ }
google/Auth/AppIdentity.php CHANGED
@@ -1,120 +1,120 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /*
19
- * WARNING - this class depends on the Google App Engine PHP library
20
- * which is 5.3 and above only, so if you include this in a PHP 5.2
21
- * setup or one without 5.3 things will blow up.
22
- */
23
- use google\appengine\api\app_identity\AppIdentityService;
24
-
25
- if (!class_exists('Google_Client')) {
26
- require_once dirname(__FILE__) . '/../autoload.php';
27
- }
28
-
29
- /**
30
- * Authentication via the Google App Engine App Identity service.
31
- */
32
- class Google_Auth_AppIdentity extends Google_Auth_Abstract
33
- {
34
- const CACHE_PREFIX = "Google_Auth_AppIdentity::";
35
- private $client;
36
- private $token = false;
37
- private $tokenScopes = false;
38
-
39
- public function __construct(Google_Client $client, $config = null)
40
- {
41
- $this->client = $client;
42
- }
43
-
44
- /**
45
- * Retrieve an access token for the scopes supplied.
46
- */
47
- public function authenticateForScope($scopes)
48
- {
49
- if ($this->token && $this->tokenScopes == $scopes) {
50
- return $this->token;
51
- }
52
-
53
- $cacheKey = self::CACHE_PREFIX;
54
- if (is_string($scopes)) {
55
- $cacheKey .= $scopes;
56
- } else if (is_array($scopes)) {
57
- $cacheKey .= implode(":", $scopes);
58
- }
59
-
60
- $this->token = $this->client->getCache()->get($cacheKey);
61
- if (!$this->token) {
62
- $this->retrieveToken($scopes, $cacheKey);
63
- } else if ($this->token['expiration_time'] < time()) {
64
- $this->client->getCache()->delete($cacheKey);
65
- $this->retrieveToken($scopes, $cacheKey);
66
- }
67
-
68
- $this->tokenScopes = $scopes;
69
- return $this->token;
70
- }
71
-
72
- /**
73
- * Retrieve a new access token and store it in cache
74
- * @param mixed $scopes
75
- * @param string $cacheKey
76
- */
77
- private function retrieveToken($scopes, $cacheKey)
78
- {
79
- $this->token = AppIdentityService::getAccessToken($scopes);
80
- if ($this->token) {
81
- $this->client->getCache()->set(
82
- $cacheKey,
83
- $this->token
84
- );
85
- }
86
- }
87
-
88
- /**
89
- * Perform an authenticated / signed apiHttpRequest.
90
- * This function takes the apiHttpRequest, calls apiAuth->sign on it
91
- * (which can modify the request in what ever way fits the auth mechanism)
92
- * and then calls apiCurlIO::makeRequest on the signed request
93
- *
94
- * @param Google_Http_Request $request
95
- * @return Google_Http_Request The resulting HTTP response including the
96
- * responseHttpCode, responseHeaders and responseBody.
97
- */
98
- public function authenticatedRequest(Google_Http_Request $request)
99
- {
100
- $request = $this->sign($request);
101
- return $this->client->getIo()->makeRequest($request);
102
- }
103
-
104
- public function sign(Google_Http_Request $request)
105
- {
106
- if (!$this->token) {
107
- // No token, so nothing to do.
108
- return $request;
109
- }
110
-
111
- $this->client->getLogger()->debug('App Identity authentication');
112
-
113
- // Add the OAuth2 header to the request
114
- $request->setRequestHeaders(
115
- array('Authorization' => 'Bearer ' . $this->token['access_token'])
116
- );
117
-
118
- return $request;
119
- }
120
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /*
19
+ * WARNING - this class depends on the Google App Engine PHP library
20
+ * which is 5.3 and above only, so if you include this in a PHP 5.2
21
+ * setup or one without 5.3 things will blow up.
22
+ */
23
+ use google\appengine\api\app_identity\AppIdentityService;
24
+
25
+ if (!class_exists('Google_Client')) {
26
+ require_once dirname(__FILE__) . '/../autoload.php';
27
+ }
28
+
29
+ /**
30
+ * Authentication via the Google App Engine App Identity service.
31
+ */
32
+ class Google_Auth_AppIdentity extends Google_Auth_Abstract
33
+ {
34
+ const CACHE_PREFIX = "Google_Auth_AppIdentity::";
35
+ private $client;
36
+ private $token = false;
37
+ private $tokenScopes = false;
38
+
39
+ public function __construct(Google_Client $client, $config = null)
40
+ {
41
+ $this->client = $client;
42
+ }
43
+
44
+ /**
45
+ * Retrieve an access token for the scopes supplied.
46
+ */
47
+ public function authenticateForScope($scopes)
48
+ {
49
+ if ($this->token && $this->tokenScopes == $scopes) {
50
+ return $this->token;
51
+ }
52
+
53
+ $cacheKey = self::CACHE_PREFIX;
54
+ if (is_string($scopes)) {
55
+ $cacheKey .= $scopes;
56
+ } else if (is_array($scopes)) {
57
+ $cacheKey .= implode(":", $scopes);
58
+ }
59
+
60
+ $this->token = $this->client->getCache()->get($cacheKey);
61
+ if (!$this->token) {
62
+ $this->retrieveToken($scopes, $cacheKey);
63
+ } else if ($this->token['expiration_time'] < time()) {
64
+ $this->client->getCache()->delete($cacheKey);
65
+ $this->retrieveToken($scopes, $cacheKey);
66
+ }
67
+
68
+ $this->tokenScopes = $scopes;
69
+ return $this->token;
70
+ }
71
+
72
+ /**
73
+ * Retrieve a new access token and store it in cache
74
+ * @param mixed $scopes
75
+ * @param string $cacheKey
76
+ */
77
+ private function retrieveToken($scopes, $cacheKey)
78
+ {
79
+ $this->token = AppIdentityService::getAccessToken($scopes);
80
+ if ($this->token) {
81
+ $this->client->getCache()->set(
82
+ $cacheKey,
83
+ $this->token
84
+ );
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Perform an authenticated / signed apiHttpRequest.
90
+ * This function takes the apiHttpRequest, calls apiAuth->sign on it
91
+ * (which can modify the request in what ever way fits the auth mechanism)
92
+ * and then calls apiCurlIO::makeRequest on the signed request
93
+ *
94
+ * @param Google_Http_Request $request
95
+ * @return Google_Http_Request The resulting HTTP response including the
96
+ * responseHttpCode, responseHeaders and responseBody.
97
+ */
98
+ public function authenticatedRequest(Google_Http_Request $request)
99
+ {
100
+ $request = $this->sign($request);
101
+ return $this->client->getIo()->makeRequest($request);
102
+ }
103
+
104
+ public function sign(Google_Http_Request $request)
105
+ {
106
+ if (!$this->token) {
107
+ // No token, so nothing to do.
108
+ return $request;
109
+ }
110
+
111
+ $this->client->getLogger()->debug('App Identity authentication');
112
+
113
+ // Add the OAuth2 header to the request
114
+ $request->setRequestHeaders(
115
+ array('Authorization' => 'Bearer ' . $this->token['access_token'])
116
+ );
117
+
118
+ return $request;
119
+ }
120
+ }
google/Auth/AssertionCredentials.php CHANGED
@@ -1,136 +1,136 @@
1
- <?php
2
- /*
3
- * Copyright 2012 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * Credentials object used for OAuth 2.0 Signed JWT assertion grants.
24
- */
25
- class Google_Auth_AssertionCredentials
26
- {
27
- const MAX_TOKEN_LIFETIME_SECS = 3600;
28
-
29
- public $serviceAccountName;
30
- public $scopes;
31
- public $privateKey;
32
- public $privateKeyPassword;
33
- public $assertionType;
34
- public $sub;
35
- /**
36
- * @deprecated
37
- * @link http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
38
- */
39
- public $prn;
40
- private $useCache;
41
-
42
- /**
43
- * @param $serviceAccountName
44
- * @param $scopes array List of scopes
45
- * @param $privateKey
46
- * @param string $privateKeyPassword
47
- * @param string $assertionType
48
- * @param bool|string $sub The email address of the user for which the
49
- * application is requesting delegated access.
50
- * @param bool useCache Whether to generate a cache key and allow
51
- * automatic caching of the generated token.
52
- */
53
- public function __construct(
54
- $serviceAccountName,
55
- $scopes,
56
- $privateKey,
57
- $privateKeyPassword = 'notasecret',
58
- $assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
59
- $sub = false,
60
- $useCache = true
61
- ) {
62
- $this->serviceAccountName = $serviceAccountName;
63
- $this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
64
- $this->privateKey = $privateKey;
65
- $this->privateKeyPassword = $privateKeyPassword;
66
- $this->assertionType = $assertionType;
67
- $this->sub = $sub;
68
- $this->prn = $sub;
69
- $this->useCache = $useCache;
70
- }
71
-
72
- /**
73
- * Generate a unique key to represent this credential.
74
- * @return string
75
- */
76
- public function getCacheKey()
77
- {
78
- if (!$this->useCache) {
79
- return false;
80
- }
81
- $h = $this->sub;
82
- $h .= $this->assertionType;
83
- $h .= $this->privateKey;
84
- $h .= $this->scopes;
85
- $h .= $this->serviceAccountName;
86
- return md5($h);
87
- }
88
-
89
- public function generateAssertion()
90
- {
91
- $now = time();
92
-
93
- $jwtParams = array(
94
- 'aud' => Google_Auth_OAuth2::OAUTH2_TOKEN_URI,
95
- 'scope' => $this->scopes,
96
- 'iat' => $now,
97
- 'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
98
- 'iss' => $this->serviceAccountName,
99
- );
100
-
101
- if ($this->sub !== false) {
102
- $jwtParams['sub'] = $this->sub;
103
- } else if ($this->prn !== false) {
104
- $jwtParams['prn'] = $this->prn;
105
- }
106
-
107
- return $this->makeSignedJwt($jwtParams);
108
- }
109
-
110
- /**
111
- * Creates a signed JWT.
112
- * @param array $payload
113
- * @return string The signed JWT.
114
- */
115
- private function makeSignedJwt($payload)
116
- {
117
- $header = array('typ' => 'JWT', 'alg' => 'RS256');
118
-
119
- $payload = json_encode($payload);
120
- // Handle some overzealous escaping in PHP json that seemed to cause some errors
121
- // with claimsets.
122
- $payload = str_replace('\/', '/', $payload);
123
-
124
- $segments = array(
125
- Google_Utils::urlSafeB64Encode(json_encode($header)),
126
- Google_Utils::urlSafeB64Encode($payload)
127
- );
128
-
129
- $signingInput = implode('.', $segments);
130
- $signer = new Google_Signer_P12($this->privateKey, $this->privateKeyPassword);
131
- $signature = $signer->sign($signingInput);
132
- $segments[] = Google_Utils::urlSafeB64Encode($signature);
133
-
134
- return implode(".", $segments);
135
- }
136
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2012 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * Credentials object used for OAuth 2.0 Signed JWT assertion grants.
24
+ */
25
+ class Google_Auth_AssertionCredentials
26
+ {
27
+ const MAX_TOKEN_LIFETIME_SECS = 3600;
28
+
29
+ public $serviceAccountName;
30
+ public $scopes;
31
+ public $privateKey;
32
+ public $privateKeyPassword;
33
+ public $assertionType;
34
+ public $sub;
35
+ /**
36
+ * @deprecated
37
+ * @link http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
38
+ */
39
+ public $prn;
40
+ private $useCache;
41
+
42
+ /**
43
+ * @param $serviceAccountName
44
+ * @param $scopes array List of scopes
45
+ * @param $privateKey
46
+ * @param string $privateKeyPassword
47
+ * @param string $assertionType
48
+ * @param bool|string $sub The email address of the user for which the
49
+ * application is requesting delegated access.
50
+ * @param bool useCache Whether to generate a cache key and allow
51
+ * automatic caching of the generated token.
52
+ */
53
+ public function __construct(
54
+ $serviceAccountName,
55
+ $scopes,
56
+ $privateKey,
57
+ $privateKeyPassword = 'notasecret',
58
+ $assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
59
+ $sub = false,
60
+ $useCache = true
61
+ ) {
62
+ $this->serviceAccountName = $serviceAccountName;
63
+ $this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
64
+ $this->privateKey = $privateKey;
65
+ $this->privateKeyPassword = $privateKeyPassword;
66
+ $this->assertionType = $assertionType;
67
+ $this->sub = $sub;
68
+ $this->prn = $sub;
69
+ $this->useCache = $useCache;
70
+ }
71
+
72
+ /**
73
+ * Generate a unique key to represent this credential.
74
+ * @return string
75
+ */
76
+ public function getCacheKey()
77
+ {
78
+ if (!$this->useCache) {
79
+ return false;
80
+ }
81
+ $h = $this->sub;
82
+ $h .= $this->assertionType;
83
+ $h .= $this->privateKey;
84
+ $h .= $this->scopes;
85
+ $h .= $this->serviceAccountName;
86
+ return md5($h);
87
+ }
88
+
89
+ public function generateAssertion()
90
+ {
91
+ $now = time();
92
+
93
+ $jwtParams = array(
94
+ 'aud' => Google_Auth_OAuth2::OAUTH2_TOKEN_URI,
95
+ 'scope' => $this->scopes,
96
+ 'iat' => $now,
97
+ 'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
98
+ 'iss' => $this->serviceAccountName,
99
+ );
100
+
101
+ if ($this->sub !== false) {
102
+ $jwtParams['sub'] = $this->sub;
103
+ } else if ($this->prn !== false) {
104
+ $jwtParams['prn'] = $this->prn;
105
+ }
106
+
107
+ return $this->makeSignedJwt($jwtParams);
108
+ }
109
+
110
+ /**
111
+ * Creates a signed JWT.
112
+ * @param array $payload
113
+ * @return string The signed JWT.
114
+ */
115
+ private function makeSignedJwt($payload)
116
+ {
117
+ $header = array('typ' => 'JWT', 'alg' => 'RS256');
118
+
119
+ $payload = json_encode($payload);
120
+ // Handle some overzealous escaping in PHP json that seemed to cause some errors
121
+ // with claimsets.
122
+ $payload = str_replace('\/', '/', $payload);
123
+
124
+ $segments = array(
125
+ Google_Utils::urlSafeB64Encode(json_encode($header)),
126
+ Google_Utils::urlSafeB64Encode($payload)
127
+ );
128
+
129
+ $signingInput = implode('.', $segments);
130
+ $signer = new Google_Signer_P12($this->privateKey, $this->privateKeyPassword);
131
+ $signature = $signer->sign($signingInput);
132
+ $segments[] = Google_Utils::urlSafeB64Encode($signature);
133
+
134
+ return implode(".", $segments);
135
+ }
136
+ }
google/Auth/ComputeEngine.php CHANGED
@@ -1,146 +1,146 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * Authentication via built-in Compute Engine service accounts.
24
- * The instance must be pre-configured with a service account
25
- * and the appropriate scopes.
26
- * @author Jonathan Parrott <jon.wayne.parrott@gmail.com>
27
- */
28
- class Google_Auth_ComputeEngine extends Google_Auth_Abstract
29
- {
30
- const METADATA_AUTH_URL =
31
- 'http://metadata/computeMetadata/v1/instance/service-accounts/default/token';
32
- private $client;
33
- private $token;
34
-
35
- public function __construct(Google_Client $client, $config = null)
36
- {
37
- $this->client = $client;
38
- }
39
-
40
- /**
41
- * Perform an authenticated / signed apiHttpRequest.
42
- * This function takes the apiHttpRequest, calls apiAuth->sign on it
43
- * (which can modify the request in what ever way fits the auth mechanism)
44
- * and then calls apiCurlIO::makeRequest on the signed request
45
- *
46
- * @param Google_Http_Request $request
47
- * @return Google_Http_Request The resulting HTTP response including the
48
- * responseHttpCode, responseHeaders and responseBody.
49
- */
50
- public function authenticatedRequest(Google_Http_Request $request)
51
- {
52
- $request = $this->sign($request);
53
- return $this->client->getIo()->makeRequest($request);
54
- }
55
-
56
- /**
57
- * @param string $token
58
- * @throws Google_Auth_Exception
59
- */
60
- public function setAccessToken($token)
61
- {
62
- $token = json_decode($token, true);
63
- if ($token == null) {
64
- throw new Google_Auth_Exception('Could not json decode the token');
65
- }
66
- if (! isset($token['access_token'])) {
67
- throw new Google_Auth_Exception("Invalid token format");
68
- }
69
- $token['created'] = time();
70
- $this->token = $token;
71
- }
72
-
73
- public function getAccessToken()
74
- {
75
- return json_encode($this->token);
76
- }
77
-
78
- /**
79
- * Acquires a new access token from the compute engine metadata server.
80
- * @throws Google_Auth_Exception
81
- */
82
- public function acquireAccessToken()
83
- {
84
- $request = new Google_Http_Request(
85
- self::METADATA_AUTH_URL,
86
- 'GET',
87
- array(
88
- 'Metadata-Flavor' => 'Google'
89
- )
90
- );
91
- $request->disableGzip();
92
- $response = $this->client->getIo()->makeRequest($request);
93
-
94
- if ($response->getResponseHttpCode() == 200) {
95
- $this->setAccessToken($response->getResponseBody());
96
- $this->token['created'] = time();
97
- return $this->getAccessToken();
98
- } else {
99
- throw new Google_Auth_Exception(
100
- sprintf(
101
- "Error fetching service account access token, message: '%s'",
102
- $response->getResponseBody()
103
- ),
104
- $response->getResponseHttpCode()
105
- );
106
- }
107
- }
108
-
109
- /**
110
- * Include an accessToken in a given apiHttpRequest.
111
- * @param Google_Http_Request $request
112
- * @return Google_Http_Request
113
- * @throws Google_Auth_Exception
114
- */
115
- public function sign(Google_Http_Request $request)
116
- {
117
- if ($this->isAccessTokenExpired()) {
118
- $this->acquireAccessToken();
119
- }
120
-
121
- $this->client->getLogger()->debug('Compute engine service account authentication');
122
-
123
- $request->setRequestHeaders(
124
- array('Authorization' => 'Bearer ' . $this->token['access_token'])
125
- );
126
-
127
- return $request;
128
- }
129
-
130
- /**
131
- * Returns if the access_token is expired.
132
- * @return bool Returns True if the access_token is expired.
133
- */
134
- public function isAccessTokenExpired()
135
- {
136
- if (!$this->token || !isset($this->token['created'])) {
137
- return true;
138
- }
139
-
140
- // If the token is set to expire in the next 30 seconds.
141
- $expired = ($this->token['created']
142
- + ($this->token['expires_in'] - 30)) < time();
143
-
144
- return $expired;
145
- }
146
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * Authentication via built-in Compute Engine service accounts.
24
+ * The instance must be pre-configured with a service account
25
+ * and the appropriate scopes.
26
+ * @author Jonathan Parrott <jon.wayne.parrott@gmail.com>
27
+ */
28
+ class Google_Auth_ComputeEngine extends Google_Auth_Abstract
29
+ {
30
+ const METADATA_AUTH_URL =
31
+ 'http://metadata/computeMetadata/v1/instance/service-accounts/default/token';
32
+ private $client;
33
+ private $token;
34
+
35
+ public function __construct(Google_Client $client, $config = null)
36
+ {
37
+ $this->client = $client;
38
+ }
39
+
40
+ /**
41
+ * Perform an authenticated / signed apiHttpRequest.
42
+ * This function takes the apiHttpRequest, calls apiAuth->sign on it
43
+ * (which can modify the request in what ever way fits the auth mechanism)
44
+ * and then calls apiCurlIO::makeRequest on the signed request
45
+ *
46
+ * @param Google_Http_Request $request
47
+ * @return Google_Http_Request The resulting HTTP response including the
48
+ * responseHttpCode, responseHeaders and responseBody.
49
+ */
50
+ public function authenticatedRequest(Google_Http_Request $request)
51
+ {
52
+ $request = $this->sign($request);
53
+ return $this->client->getIo()->makeRequest($request);
54
+ }
55
+
56
+ /**
57
+ * @param string $token
58
+ * @throws Google_Auth_Exception
59
+ */
60
+ public function setAccessToken($token)
61
+ {
62
+ $token = json_decode($token, true);
63
+ if ($token == null) {
64
+ throw new Google_Auth_Exception('Could not json decode the token');
65
+ }
66
+ if (! isset($token['access_token'])) {
67
+ throw new Google_Auth_Exception("Invalid token format");
68
+ }
69
+ $token['created'] = time();
70
+ $this->token = $token;
71
+ }
72
+
73
+ public function getAccessToken()
74
+ {
75
+ return json_encode($this->token);
76
+ }
77
+
78
+ /**
79
+ * Acquires a new access token from the compute engine metadata server.
80
+ * @throws Google_Auth_Exception
81
+ */
82
+ public function acquireAccessToken()
83
+ {
84
+ $request = new Google_Http_Request(
85
+ self::METADATA_AUTH_URL,
86
+ 'GET',
87
+ array(
88
+ 'Metadata-Flavor' => 'Google'
89
+ )
90
+ );
91
+ $request->disableGzip();
92
+ $response = $this->client->getIo()->makeRequest($request);
93
+
94
+ if ($response->getResponseHttpCode() == 200) {
95
+ $this->setAccessToken($response->getResponseBody());
96
+ $this->token['created'] = time();
97
+ return $this->getAccessToken();
98
+ } else {
99
+ throw new Google_Auth_Exception(
100
+ sprintf(
101
+ "Error fetching service account access token, message: '%s'",
102
+ $response->getResponseBody()
103
+ ),
104
+ $response->getResponseHttpCode()
105
+ );
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Include an accessToken in a given apiHttpRequest.
111
+ * @param Google_Http_Request $request
112
+ * @return Google_Http_Request
113
+ * @throws Google_Auth_Exception
114
+ */
115
+ public function sign(Google_Http_Request $request)
116
+ {
117
+ if ($this->isAccessTokenExpired()) {
118
+ $this->acquireAccessToken();
119
+ }
120
+
121
+ $this->client->getLogger()->debug('Compute engine service account authentication');
122
+
123
+ $request->setRequestHeaders(
124
+ array('Authorization' => 'Bearer ' . $this->token['access_token'])
125
+ );
126
+
127
+ return $request;
128
+ }
129
+
130
+ /**
131
+ * Returns if the access_token is expired.
132
+ * @return bool Returns True if the access_token is expired.
133
+ */
134
+ public function isAccessTokenExpired()
135
+ {
136
+ if (!$this->token || !isset($this->token['created'])) {
137
+ return true;
138
+ }
139
+
140
+ // If the token is set to expire in the next 30 seconds.
141
+ $expired = ($this->token['created']
142
+ + ($this->token['expires_in'] - 30)) < time();
143
+
144
+ return $expired;
145
+ }
146
+ }
google/Auth/Exception.php CHANGED
@@ -1,24 +1,24 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- class Google_Auth_Exception extends Google_Exception
23
- {
24
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ class Google_Auth_Exception extends Google_Exception
23
+ {
24
+ }
google/Auth/LoginTicket.php CHANGED
@@ -1,71 +1,71 @@
1
- <?php
2
- /*
3
- * Copyright 2011 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * Class to hold information about an authenticated login.
24
- *
25
- * @author Brian Eaton <beaton@google.com>
26
- */
27
- class Google_Auth_LoginTicket
28
- {
29
- const USER_ATTR = "sub";
30
-
31
- // Information from id token envelope.
32
- private $envelope;
33
-
34
- // Information from id token payload.
35
- private $payload;
36
-
37
- /**
38
- * Creates a user based on the supplied token.
39
- *
40
- * @param string $envelope Header from a verified authentication token.
41
- * @param string $payload Information from a verified authentication token.
42
- */
43
- public function __construct($envelope, $payload)
44
- {
45
- $this->envelope = $envelope;
46
- $this->payload = $payload;
47
- }
48
-
49
- /**
50
- * Returns the numeric identifier for the user.
51
- * @throws Google_Auth_Exception
52
- * @return
53
- */
54
- public function getUserId()
55
- {
56
- if (array_key_exists(self::USER_ATTR, $this->payload)) {
57
- return $this->payload[self::USER_ATTR];
58
- }
59
- throw new Google_Auth_Exception("No user_id in token");
60
- }
61
-
62
- /**
63
- * Returns attributes from the login ticket. This can contain
64
- * various information about the user session.
65
- * @return array
66
- */
67
- public function getAttributes()
68
- {
69
- return array("envelope" => $this->envelope, "payload" => $this->payload);
70
- }
71
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2011 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * Class to hold information about an authenticated login.
24
+ *
25
+ * @author Brian Eaton <beaton@google.com>
26
+ */
27
+ class Google_Auth_LoginTicket
28
+ {
29
+ const USER_ATTR = "sub";
30
+
31
+ // Information from id token envelope.
32
+ private $envelope;
33
+
34
+ // Information from id token payload.
35
+ private $payload;
36
+
37
+ /**
38
+ * Creates a user based on the supplied token.
39
+ *
40
+ * @param string $envelope Header from a verified authentication token.
41
+ * @param string $payload Information from a verified authentication token.
42
+ */
43
+ public function __construct($envelope, $payload)
44
+ {
45
+ $this->envelope = $envelope;
46
+ $this->payload = $payload;
47
+ }
48
+
49
+ /**
50
+ * Returns the numeric identifier for the user.
51
+ * @throws Google_Auth_Exception
52
+ * @return
53
+ */
54
+ public function getUserId()
55
+ {
56
+ if (array_key_exists(self::USER_ATTR, $this->payload)) {
57
+ return $this->payload[self::USER_ATTR];
58
+ }
59
+ throw new Google_Auth_Exception("No user_id in token");
60
+ }
61
+
62
+ /**
63
+ * Returns attributes from the login ticket. This can contain
64
+ * various information about the user session.
65
+ * @return array
66
+ */
67
+ public function getAttributes()
68
+ {
69
+ return array("envelope" => $this->envelope, "payload" => $this->payload);
70
+ }
71
+ }
google/Auth/OAuth2.php CHANGED
@@ -1,646 +1,646 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * Authentication class that deals with the OAuth 2 web-server authentication flow
24
- *
25
- */
26
- class Google_Auth_OAuth2 extends Google_Auth_Abstract
27
- {
28
- const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
29
- const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
30
- const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
31
- const CLOCK_SKEW_SECS = 300; // five minutes in seconds
32
- const AUTH_TOKEN_LIFETIME_SECS = 300; // five minutes in seconds
33
- const MAX_TOKEN_LIFETIME_SECS = 86400; // one day in seconds
34
- const OAUTH2_ISSUER = 'accounts.google.com';
35
- const OAUTH2_ISSUER_HTTPS = 'https://accounts.google.com';
36
-
37
- /** @var Google_Auth_AssertionCredentials $assertionCredentials */
38
- private $assertionCredentials;
39
-
40
- /**
41
- * @var string The state parameters for CSRF and other forgery protection.
42
- */
43
- private $state;
44
-
45
- /**
46
- * @var array The token bundle.
47
- */
48
- private $token = array();
49
-
50
- /**
51
- * @var Google_Client the base client
52
- */
53
- private $client;
54
-
55
- /**
56
- * Instantiates the class, but does not initiate the login flow, leaving it
57
- * to the discretion of the caller.
58
- */
59
- public function __construct(Google_Client $client)
60
- {
61
- $this->client = $client;
62
- }
63
-
64
- /**
65
- * Perform an authenticated / signed apiHttpRequest.
66
- * This function takes the apiHttpRequest, calls apiAuth->sign on it
67
- * (which can modify the request in what ever way fits the auth mechanism)
68
- * and then calls apiCurlIO::makeRequest on the signed request
69
- *
70
- * @param Google_Http_Request $request
71
- * @return Google_Http_Request The resulting HTTP response including the
72
- * responseHttpCode, responseHeaders and responseBody.
73
- */
74
- public function authenticatedRequest(Google_Http_Request $request)
75
- {
76
- $request = $this->sign($request);
77
- return $this->client->getIo()->makeRequest($request);
78
- }
79
-
80
- /**
81
- * @param string $code
82
- * @param boolean $crossClient
83
- * @throws Google_Auth_Exception
84
- * @return string
85
- */
86
- public function authenticate($code, $crossClient = false)
87
- {
88
- if (strlen($code) == 0) {
89
- throw new Google_Auth_Exception("Invalid code");
90
- }
91
-
92
- $arguments = array(
93
- 'code' => $code,
94
- 'grant_type' => 'authorization_code',
95
- 'client_id' => $this->client->getClassConfig($this, 'client_id'),
96
- 'client_secret' => $this->client->getClassConfig($this, 'client_secret')
97
- );
98
-
99
- if ($crossClient !== true) {
100
- $arguments['redirect_uri'] = $this->client->getClassConfig($this, 'redirect_uri');
101
- }
102
-
103
- // We got here from the redirect from a successful authorization grant,
104
- // fetch the access token
105
- $request = new Google_Http_Request(
106
- self::OAUTH2_TOKEN_URI,
107
- 'POST',
108
- array(),
109
- $arguments
110
- );
111
- $request->disableGzip();
112
- $response = $this->client->getIo()->makeRequest($request);
113
-
114
- if ($response->getResponseHttpCode() == 200) {
115
- $this->setAccessToken($response->getResponseBody());
116
- $this->token['created'] = time();
117
- return $this->getAccessToken();
118
- } else {
119
- $decodedResponse = json_decode($response->getResponseBody(), true);
120
- if ($decodedResponse != null && $decodedResponse['error']) {
121
- $errorText = $decodedResponse['error'];
122
- if (isset($decodedResponse['error_description'])) {
123
- $errorText .= ": " . $decodedResponse['error_description'];
124
- }
125
- }
126
- throw new Google_Auth_Exception(
127
- sprintf(
128
- "Error fetching OAuth2 access token, message: '%s'",
129
- $errorText
130
- ),
131
- $response->getResponseHttpCode()
132
- );
133
- }
134
- }
135
-
136
- /**
137
- * Create a URL to obtain user authorization.
138
- * The authorization endpoint allows the user to first
139
- * authenticate, and then grant/deny the access request.
140
- * @param string $scope The scope is expressed as a list of space-delimited strings.
141
- * @return string
142
- */
143
- public function createAuthUrl($scope)
144
- {
145
- $params = array(
146
- 'response_type' => 'code',
147
- 'redirect_uri' => $this->client->getClassConfig($this, 'redirect_uri'),
148
- 'client_id' => $this->client->getClassConfig($this, 'client_id'),
149
- 'scope' => $scope,
150
- 'access_type' => $this->client->getClassConfig($this, 'access_type'),
151
- );
152
-
153
- // Prefer prompt to approval prompt.
154
- if ($this->client->getClassConfig($this, 'prompt')) {
155
- $params = $this->maybeAddParam($params, 'prompt');
156
- } else {
157
- $params = $this->maybeAddParam($params, 'approval_prompt');
158
- }
159
- $params = $this->maybeAddParam($params, 'login_hint');
160
- $params = $this->maybeAddParam($params, 'hd');
161
- $params = $this->maybeAddParam($params, 'openid.realm');
162
- $params = $this->maybeAddParam($params, 'include_granted_scopes');
163
-
164
- // If the list of scopes contains plus.login, add request_visible_actions
165
- // to auth URL.
166
- $rva = $this->client->getClassConfig($this, 'request_visible_actions');
167
- if (strpos($scope, 'plus.login') && strlen($rva) > 0) {
168
- $params['request_visible_actions'] = $rva;
169
- }
170
-
171
- if (isset($this->state)) {
172
- $params['state'] = $this->state;
173
- }
174
-
175
- return self::OAUTH2_AUTH_URL . "?" . http_build_query($params, '', '&');
176
- }
177
-
178
- /**
179
- * @param string $token
180
- * @throws Google_Auth_Exception
181
- */
182
- public function setAccessToken($token)
183
- {
184
- $token = json_decode($token, true);
185
- if ($token == null) {
186
- throw new Google_Auth_Exception('Could not json decode the token');
187
- }
188
- if (! isset($token['access_token'])) {
189
- throw new Google_Auth_Exception("Invalid token format");
190
- }
191
- $this->token = $token;
192
- }
193
-
194
- public function getAccessToken()
195
- {
196
- return json_encode($this->token);
197
- }
198
-
199
- public function getRefreshToken()
200
- {
201
- if (array_key_exists('refresh_token', $this->token)) {
202
- return $this->token['refresh_token'];
203
- } else {
204
- return null;
205
- }
206
- }
207
-
208
- public function setState($state)
209
- {
210
- $this->state = $state;
211
- }
212
-
213
- public function setAssertionCredentials(Google_Auth_AssertionCredentials $creds)
214
- {
215
- $this->assertionCredentials = $creds;
216
- }
217
-
218
- /**
219
- * Include an accessToken in a given apiHttpRequest.
220
- * @param Google_Http_Request $request
221
- * @return Google_Http_Request
222
- * @throws Google_Auth_Exception
223
- */
224
- public function sign(Google_Http_Request $request)
225
- {
226
- // add the developer key to the request before signing it
227
- if ($this->client->getClassConfig($this, 'developer_key')) {
228
- $request->setQueryParam('key', $this->client->getClassConfig($this, 'developer_key'));
229
- }
230
-
231
- // Cannot sign the request without an OAuth access token.
232
- if (null == $this->token && null == $this->assertionCredentials) {
233
- return $request;
234
- }
235
-
236
- // Check if the token is set to expire in the next 30 seconds
237
- // (or has already expired).
238
- if ($this->isAccessTokenExpired()) {
239
- if ($this->assertionCredentials) {
240
- $this->refreshTokenWithAssertion();
241
- } else {
242
- $this->client->getLogger()->debug('OAuth2 access token expired');
243
- if (! array_key_exists('refresh_token', $this->token)) {
244
- $error = "The OAuth 2.0 access token has expired,"
245
- ." and a refresh token is not available. Refresh tokens"
246
- ." are not returned for responses that were auto-approved.";
247
-
248
- $this->client->getLogger()->error($error);
249
- throw new Google_Auth_Exception($error);
250
- }
251
- $this->refreshToken($this->token['refresh_token']);
252
- }
253
- }
254
-
255
- $this->client->getLogger()->debug('OAuth2 authentication');
256
-
257
- // Add the OAuth2 header to the request
258
- $request->setRequestHeaders(
259
- array('Authorization' => 'Bearer ' . $this->token['access_token'])
260
- );
261
-
262
- return $request;
263
- }
264
-
265
- /**
266
- * Fetches a fresh access token with the given refresh token.
267
- * @param string $refreshToken
268
- * @return void
269
- */
270
- public function refreshToken($refreshToken)
271
- {
272
- $this->refreshTokenRequest(
273
- array(
274
- 'client_id' => $this->client->getClassConfig($this, 'client_id'),
275
- 'client_secret' => $this->client->getClassConfig($this, 'client_secret'),
276
- 'refresh_token' => $refreshToken,
277
- 'grant_type' => 'refresh_token'
278
- )
279
- );
280
- }
281
-
282
- /**
283
- * Fetches a fresh access token with a given assertion token.
284
- * @param Google_Auth_AssertionCredentials $assertionCredentials optional.
285
- * @return void
286
- */
287
- public function refreshTokenWithAssertion($assertionCredentials = null)
288
- {
289
- if (!$assertionCredentials) {
290
- $assertionCredentials = $this->assertionCredentials;
291
- }
292
-
293
- $cacheKey = $assertionCredentials->getCacheKey();
294
-
295
- if ($cacheKey) {
296
- // We can check whether we have a token available in the
297
- // cache. If it is expired, we can retrieve a new one from
298
- // the assertion.
299
- $token = $this->client->getCache()->get($cacheKey);
300
- if ($token) {
301
- $this->setAccessToken($token);
302
- }
303
- if (!$this->isAccessTokenExpired()) {
304
- return;
305
- }
306
- }
307
-
308
- $this->client->getLogger()->debug('OAuth2 access token expired');
309
- $this->refreshTokenRequest(
310
- array(
311
- 'grant_type' => 'assertion',
312
- 'assertion_type' => $assertionCredentials->assertionType,
313
- 'assertion' => $assertionCredentials->generateAssertion(),
314
- )
315
- );
316
-
317
- if ($cacheKey) {
318
- // Attempt to cache the token.
319
- $this->client->getCache()->set(
320
- $cacheKey,
321
- $this->getAccessToken()
322
- );
323
- }
324
- }
325
-
326
- private function refreshTokenRequest($params)
327
- {
328
- if (isset($params['assertion'])) {
329
- $this->client->getLogger()->info(
330
- 'OAuth2 access token refresh with Signed JWT assertion grants.'
331
- );
332
- } else {
333
- $this->client->getLogger()->info('OAuth2 access token refresh');
334
- }
335
-
336
- $http = new Google_Http_Request(
337
- self::OAUTH2_TOKEN_URI,
338
- 'POST',
339
- array(),
340
- $params
341
- );
342
- $http->disableGzip();
343
- $request = $this->client->getIo()->makeRequest($http);
344
-
345
- $code = $request->getResponseHttpCode();
346
- $body = $request->getResponseBody();
347
- if (200 == $code) {
348
- $token = json_decode($body, true);
349
- if ($token == null) {
350
- throw new Google_Auth_Exception("Could not json decode the access token");
351
- }
352
-
353
- if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
354
- throw new Google_Auth_Exception("Invalid token format");
355
- }
356
-
357
- if (isset($token['id_token'])) {
358
- $this->token['id_token'] = $token['id_token'];
359
- }
360
- $this->token['access_token'] = $token['access_token'];
361
- $this->token['expires_in'] = $token['expires_in'];
362
- $this->token['created'] = time();
363
- } else {
364
- throw new Google_Auth_Exception("Error refreshing the OAuth2 token, message: '$body'", $code);
365
- }
366
- }
367
-
368
- /**
369
- * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
370
- * token, if a token isn't provided.
371
- * @throws Google_Auth_Exception
372
- * @param string|null $token The token (access token or a refresh token) that should be revoked.
373
- * @return boolean Returns True if the revocation was successful, otherwise False.
374
- */
375
- public function revokeToken($token = null)
376
- {
377
- if (!$token) {
378
- if (!$this->token) {
379
- // Not initialized, no token to actually revoke
380
- return false;
381
- } elseif (array_key_exists('refresh_token', $this->token)) {
382
- $token = $this->token['refresh_token'];
383
- } else {
384
- $token = $this->token['access_token'];
385
- }
386
- }
387
- $request = new Google_Http_Request(
388
- self::OAUTH2_REVOKE_URI,
389
- 'POST',
390
- array(),
391
- "token=$token"
392
- );
393
- $request->disableGzip();
394
- $response = $this->client->getIo()->makeRequest($request);
395
- $code = $response->getResponseHttpCode();
396
- if ($code == 200) {
397
- $this->token = null;
398
- return true;
399
- }
400
-
401
- return false;
402
- }
403
-
404
- /**
405
- * Returns if the access_token is expired.
406
- * @return bool Returns True if the access_token is expired.
407
- */
408
- public function isAccessTokenExpired()
409
- {
410
- if (!$this->token || !isset($this->token['created'])) {
411
- return true;
412
- }
413
-
414
- // If the token is set to expire in the next 30 seconds.
415
- $expired = ($this->token['created']
416
- + ($this->token['expires_in'] - 30)) < time();
417
-
418
- return $expired;
419
- }
420
-
421
- // Gets federated sign-on certificates to use for verifying identity tokens.
422
- // Returns certs as array structure, where keys are key ids, and values
423
- // are PEM encoded certificates.
424
- private function getFederatedSignOnCerts()
425
- {
426
- return $this->retrieveCertsFromLocation(
427
- $this->client->getClassConfig($this, 'federated_signon_certs_url')
428
- );
429
- }
430
-
431
- /**
432
- * Retrieve and cache a certificates file.
433
- *
434
- * @param $url string location
435
- * @throws Google_Auth_Exception
436
- * @return array certificates
437
- */
438
- public function retrieveCertsFromLocation($url)
439
- {
440
- // If we're retrieving a local file, just grab it.
441
- if ("http" != substr($url, 0, 4)) {
442
- $file = file_get_contents($url);
443
- if ($file) {
444
- return json_decode($file, true);
445
- } else {
446
- throw new Google_Auth_Exception(
447
- "Failed to retrieve verification certificates: '" .
448
- $url . "'."
449
- );
450
- }
451
- }
452
-
453
- // This relies on makeRequest caching certificate responses.
454
- $request = $this->client->getIo()->makeRequest(
455
- new Google_Http_Request(
456
- $url
457
- )
458
- );
459
- if ($request->getResponseHttpCode() == 200) {
460
- $certs = json_decode($request->getResponseBody(), true);
461
- if ($certs) {
462
- return $certs;
463
- }
464
- }
465
- throw new Google_Auth_Exception(
466
- "Failed to retrieve verification certificates: '" .
467
- $request->getResponseBody() . "'.",
468
- $request->getResponseHttpCode()
469
- );
470
- }
471
-
472
- /**
473
- * Verifies an id token and returns the authenticated apiLoginTicket.
474
- * Throws an exception if the id token is not valid.
475
- * The audience parameter can be used to control which id tokens are
476
- * accepted. By default, the id token must have been issued to this OAuth2 client.
477
- *
478
- * @param $id_token
479
- * @param $audience
480
- * @return Google_Auth_LoginTicket
481
- */
482
- public function verifyIdToken($id_token = null, $audience = null)
483
- {
484
- if (!$id_token) {
485
- $id_token = $this->token['id_token'];
486
- }
487
- $certs = $this->getFederatedSignonCerts();
488
- if (!$audience) {
489
- $audience = $this->client->getClassConfig($this, 'client_id');
490
- }
491
-
492
- return $this->verifySignedJwtWithCerts(
493
- $id_token,
494
- $certs,
495
- $audience,
496
- array(self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS)
497
- );
498
- }
499
-
500
- /**
501
- * Verifies the id token, returns the verified token contents.
502
- *
503
- * @param $jwt string the token
504
- * @param $certs array of certificates
505
- * @param $required_audience string the expected consumer of the token
506
- * @param [$issuer] the expected issues, defaults to Google
507
- * @param [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS
508
- * @throws Google_Auth_Exception
509
- * @return mixed token information if valid, false if not
510
- */
511
- public function verifySignedJwtWithCerts(
512
- $jwt,
513
- $certs,
514
- $required_audience,
515
- $issuer = null,
516
- $max_expiry = null
517
- ) {
518
- if (!$max_expiry) {
519
- // Set the maximum time we will accept a token for.
520
- $max_expiry = self::MAX_TOKEN_LIFETIME_SECS;
521
- }
522
-
523
- $segments = explode(".", $jwt);
524
- if (count($segments) != 3) {
525
- throw new Google_Auth_Exception("Wrong number of segments in token: $jwt");
526
- }
527
- $signed = $segments[0] . "." . $segments[1];
528
- $signature = Google_Utils::urlSafeB64Decode($segments[2]);
529
-
530
- // Parse envelope.
531
- $envelope = json_decode(Google_Utils::urlSafeB64Decode($segments[0]), true);
532
- if (!$envelope) {
533
- throw new Google_Auth_Exception("Can't parse token envelope: " . $segments[0]);
534
- }
535
-
536
- // Parse token
537
- $json_body = Google_Utils::urlSafeB64Decode($segments[1]);
538
- $payload = json_decode($json_body, true);
539
- if (!$payload) {
540
- throw new Google_Auth_Exception("Can't parse token payload: " . $segments[1]);
541
- }
542
-
543
- // Check signature
544
- $verified = false;
545
- foreach ($certs as $keyName => $pem) {
546
- $public_key = new Google_Verifier_Pem($pem);
547
- if ($public_key->verify($signed, $signature)) {
548
- $verified = true;
549
- break;
550
- }
551
- }
552
-
553
- if (!$verified) {
554
- throw new Google_Auth_Exception("Invalid token signature: $jwt");
555
- }
556
-
557
- // Check issued-at timestamp
558
- $iat = 0;
559
- if (array_key_exists("iat", $payload)) {
560
- $iat = $payload["iat"];
561
- }
562
- if (!$iat) {
563
- throw new Google_Auth_Exception("No issue time in token: $json_body");
564
- }
565
- $earliest = $iat - self::CLOCK_SKEW_SECS;
566
-
567
- // Check expiration timestamp
568
- $now = time();
569
- $exp = 0;
570
- if (array_key_exists("exp", $payload)) {
571
- $exp = $payload["exp"];
572
- }
573
- if (!$exp) {
574
- throw new Google_Auth_Exception("No expiration time in token: $json_body");
575
- }
576
- if ($exp >= $now + $max_expiry) {
577
- throw new Google_Auth_Exception(
578
- sprintf("Expiration time too far in future: %s", $json_body)
579
- );
580
- }
581
-
582
- $latest = $exp + self::CLOCK_SKEW_SECS;
583
- if ($now < $earliest) {
584
- throw new Google_Auth_Exception(
585
- sprintf(
586
- "Token used too early, %s < %s: %s",
587
- $now,
588
- $earliest,
589
- $json_body
590
- )
591
- );
592
- }
593
- if ($now > $latest) {
594
- throw new Google_Auth_Exception(
595
- sprintf(
596
- "Token used too late, %s > %s: %s",
597
- $now,
598
- $latest,
599
- $json_body
600
- )
601
- );
602
- }
603
-
604
- // support HTTP and HTTPS issuers
605
- // @see https://developers.google.com/identity/sign-in/web/backend-auth
606
- $iss = $payload['iss'];
607
- if ($issuer && !in_array($iss, (array) $issuer)) {
608
- throw new Google_Auth_Exception(
609
- sprintf(
610
- "Invalid issuer, %s not in %s: %s",
611
- $iss,
612
- "[".implode(",", (array) $issuer)."]",
613
- $json_body
614
- )
615
- );
616
- }
617
-
618
- // Check audience
619
- $aud = $payload["aud"];
620
- if ($aud != $required_audience) {
621
- throw new Google_Auth_Exception(
622
- sprintf(
623
- "Wrong recipient, %s != %s:",
624
- $aud,
625
- $required_audience,
626
- $json_body
627
- )
628
- );
629
- }
630
-
631
- // All good.
632
- return new Google_Auth_LoginTicket($envelope, $payload);
633
- }
634
-
635
- /**
636
- * Add a parameter to the auth params if not empty string.
637
- */
638
- private function maybeAddParam($params, $name)
639
- {
640
- $param = $this->client->getClassConfig($this, $name);
641
- if ($param != '') {
642
- $params[$name] = $param;
643
- }
644
- return $params;
645
- }
646
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2008 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * Authentication class that deals with the OAuth 2 web-server authentication flow
24
+ *
25
+ */
26
+ class Google_Auth_OAuth2 extends Google_Auth_Abstract
27
+ {
28
+ const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
29
+ const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
30
+ const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
31
+ const CLOCK_SKEW_SECS = 300; // five minutes in seconds
32
+ const AUTH_TOKEN_LIFETIME_SECS = 300; // five minutes in seconds
33
+ const MAX_TOKEN_LIFETIME_SECS = 86400; // one day in seconds
34
+ const OAUTH2_ISSUER = 'accounts.google.com';
35
+ const OAUTH2_ISSUER_HTTPS = 'https://accounts.google.com';
36
+
37
+ /** @var Google_Auth_AssertionCredentials $assertionCredentials */
38
+ private $assertionCredentials;
39
+
40
+ /**
41
+ * @var string The state parameters for CSRF and other forgery protection.
42
+ */
43
+ private $state;
44
+
45
+ /**
46
+ * @var array The token bundle.
47
+ */
48
+ private $token = array();
49
+
50
+ /**
51
+ * @var Google_Client the base client
52
+ */
53
+ private $client;
54
+
55
+ /**
56
+ * Instantiates the class, but does not initiate the login flow, leaving it
57
+ * to the discretion of the caller.
58
+ */
59
+ public function __construct(Google_Client $client)
60
+ {
61
+ $this->client = $client;
62
+ }
63
+
64
+ /**
65
+ * Perform an authenticated / signed apiHttpRequest.
66
+ * This function takes the apiHttpRequest, calls apiAuth->sign on it
67
+ * (which can modify the request in what ever way fits the auth mechanism)
68
+ * and then calls apiCurlIO::makeRequest on the signed request
69
+ *
70
+ * @param Google_Http_Request $request
71
+ * @return Google_Http_Request The resulting HTTP response including the
72
+ * responseHttpCode, responseHeaders and responseBody.
73
+ */
74
+ public function authenticatedRequest(Google_Http_Request $request)
75
+ {
76
+ $request = $this->sign($request);
77
+ return $this->client->getIo()->makeRequest($request);
78
+ }
79
+
80
+ /**
81
+ * @param string $code
82
+ * @param boolean $crossClient
83
+ * @throws Google_Auth_Exception
84
+ * @return string
85
+ */
86
+ public function authenticate($code, $crossClient = false)
87
+ {
88
+ if (strlen($code) == 0) {
89
+ throw new Google_Auth_Exception("Invalid code");
90
+ }
91
+
92
+ $arguments = array(
93
+ 'code' => $code,
94
+ 'grant_type' => 'authorization_code',
95
+ 'client_id' => $this->client->getClassConfig($this, 'client_id'),
96
+ 'client_secret' => $this->client->getClassConfig($this, 'client_secret')
97
+ );
98
+
99
+ if ($crossClient !== true) {
100
+ $arguments['redirect_uri'] = $this->client->getClassConfig($this, 'redirect_uri');
101
+ }
102
+
103
+ // We got here from the redirect from a successful authorization grant,
104
+ // fetch the access token
105
+ $request = new Google_Http_Request(
106
+ self::OAUTH2_TOKEN_URI,
107
+ 'POST',
108
+ array(),
109
+ $arguments
110
+ );
111
+ $request->disableGzip();
112
+ $response = $this->client->getIo()->makeRequest($request);
113
+
114
+ if ($response->getResponseHttpCode() == 200) {
115
+ $this->setAccessToken($response->getResponseBody());
116
+ $this->token['created'] = time();
117
+ return $this->getAccessToken();
118
+ } else {
119
+ $decodedResponse = json_decode($response->getResponseBody(), true);
120
+ if ($decodedResponse != null && $decodedResponse['error']) {
121
+ $errorText = $decodedResponse['error'];
122
+ if (isset($decodedResponse['error_description'])) {
123
+ $errorText .= ": " . $decodedResponse['error_description'];
124
+ }
125
+ }
126
+ throw new Google_Auth_Exception(
127
+ sprintf(
128
+ "Error fetching OAuth2 access token, message: '%s'",
129
+ $errorText
130
+ ),
131
+ $response->getResponseHttpCode()
132
+ );
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Create a URL to obtain user authorization.
138
+ * The authorization endpoint allows the user to first
139
+ * authenticate, and then grant/deny the access request.
140
+ * @param string $scope The scope is expressed as a list of space-delimited strings.
141
+ * @return string
142
+ */
143
+ public function createAuthUrl($scope)
144
+ {
145
+ $params = array(
146
+ 'response_type' => 'code',
147
+ 'redirect_uri' => $this->client->getClassConfig($this, 'redirect_uri'),
148
+ 'client_id' => $this->client->getClassConfig($this, 'client_id'),
149
+ 'scope' => $scope,
150
+ 'access_type' => $this->client->getClassConfig($this, 'access_type'),
151
+ );
152
+
153
+ // Prefer prompt to approval prompt.
154
+ if ($this->client->getClassConfig($this, 'prompt')) {
155
+ $params = $this->maybeAddParam($params, 'prompt');
156
+ } else {
157
+ $params = $this->maybeAddParam($params, 'approval_prompt');
158
+ }
159
+ $params = $this->maybeAddParam($params, 'login_hint');
160
+ $params = $this->maybeAddParam($params, 'hd');
161
+ $params = $this->maybeAddParam($params, 'openid.realm');
162
+ $params = $this->maybeAddParam($params, 'include_granted_scopes');
163
+
164
+ // If the list of scopes contains plus.login, add request_visible_actions
165
+ // to auth URL.
166
+ $rva = $this->client->getClassConfig($this, 'request_visible_actions');
167
+ if (strpos($scope, 'plus.login') && strlen($rva) > 0) {
168
+ $params['request_visible_actions'] = $rva;
169
+ }
170
+
171
+ if (isset($this->state)) {
172
+ $params['state'] = $this->state;
173
+ }
174
+
175
+ return self::OAUTH2_AUTH_URL . "?" . http_build_query($params, '', '&');
176
+ }
177
+
178
+ /**
179
+ * @param string $token
180
+ * @throws Google_Auth_Exception
181
+ */
182
+ public function setAccessToken($token)
183
+ {
184
+ $token = json_decode($token, true);
185
+ if ($token == null) {
186
+ throw new Google_Auth_Exception('Could not json decode the token');
187
+ }
188
+ if (! isset($token['access_token'])) {
189
+ throw new Google_Auth_Exception("Invalid token format");
190
+ }
191
+ $this->token = $token;
192
+ }
193
+
194
+ public function getAccessToken()
195
+ {
196
+ return json_encode($this->token);
197
+ }
198
+
199
+ public function getRefreshToken()
200
+ {
201
+ if (array_key_exists('refresh_token', $this->token)) {
202
+ return $this->token['refresh_token'];
203
+ } else {
204
+ return null;
205
+ }
206
+ }
207
+
208
+ public function setState($state)
209
+ {
210
+ $this->state = $state;
211
+ }
212
+
213
+ public function setAssertionCredentials(Google_Auth_AssertionCredentials $creds)
214
+ {
215
+ $this->assertionCredentials = $creds;
216
+ }
217
+
218
+ /**
219
+ * Include an accessToken in a given apiHttpRequest.
220
+ * @param Google_Http_Request $request
221
+ * @return Google_Http_Request
222
+ * @throws Google_Auth_Exception
223
+ */
224
+ public function sign(Google_Http_Request $request)
225
+ {
226
+ // add the developer key to the request before signing it
227
+ if ($this->client->getClassConfig($this, 'developer_key')) {
228
+ $request->setQueryParam('key', $this->client->getClassConfig($this, 'developer_key'));
229
+ }
230
+
231
+ // Cannot sign the request without an OAuth access token.
232
+ if (null == $this->token && null == $this->assertionCredentials) {
233
+ return $request;
234
+ }
235
+
236
+ // Check if the token is set to expire in the next 30 seconds
237
+ // (or has already expired).
238
+ if ($this->isAccessTokenExpired()) {
239
+ if ($this->assertionCredentials) {
240
+ $this->refreshTokenWithAssertion();
241
+ } else {
242
+ $this->client->getLogger()->debug('OAuth2 access token expired');
243
+ if (! array_key_exists('refresh_token', $this->token)) {
244
+ $error = "The OAuth 2.0 access token has expired,"
245
+ ." and a refresh token is not available. Refresh tokens"
246
+ ." are not returned for responses that were auto-approved.";
247
+
248
+ $this->client->getLogger()->error($error);
249
+ throw new Google_Auth_Exception($error);
250
+ }
251
+ $this->refreshToken($this->token['refresh_token']);
252
+ }
253
+ }
254
+
255
+ $this->client->getLogger()->debug('OAuth2 authentication');
256
+
257
+ // Add the OAuth2 header to the request
258
+ $request->setRequestHeaders(
259
+ array('Authorization' => 'Bearer ' . $this->token['access_token'])
260
+ );
261
+
262
+ return $request;
263
+ }
264
+
265
+ /**
266
+ * Fetches a fresh access token with the given refresh token.
267
+ * @param string $refreshToken
268
+ * @return void
269
+ */
270
+ public function refreshToken($refreshToken)
271
+ {
272
+ $this->refreshTokenRequest(
273
+ array(
274
+ 'client_id' => $this->client->getClassConfig($this, 'client_id'),
275
+ 'client_secret' => $this->client->getClassConfig($this, 'client_secret'),
276
+ 'refresh_token' => $refreshToken,
277
+ 'grant_type' => 'refresh_token'
278
+ )
279
+ );
280
+ }
281
+
282
+ /**
283
+ * Fetches a fresh access token with a given assertion token.
284
+ * @param Google_Auth_AssertionCredentials $assertionCredentials optional.
285
+ * @return void
286
+ */
287
+ public function refreshTokenWithAssertion($assertionCredentials = null)
288
+ {
289
+ if (!$assertionCredentials) {
290
+ $assertionCredentials = $this->assertionCredentials;
291
+ }
292
+
293
+ $cacheKey = $assertionCredentials->getCacheKey();
294
+
295
+ if ($cacheKey) {
296
+ // We can check whether we have a token available in the
297
+ // cache. If it is expired, we can retrieve a new one from
298
+ // the assertion.
299
+ $token = $this->client->getCache()->get($cacheKey);
300
+ if ($token) {
301
+ $this->setAccessToken($token);
302
+ }
303
+ if (!$this->isAccessTokenExpired()) {
304
+ return;
305
+ }
306
+ }
307
+
308
+ $this->client->getLogger()->debug('OAuth2 access token expired');
309
+ $this->refreshTokenRequest(
310
+ array(
311
+ 'grant_type' => 'assertion',
312
+ 'assertion_type' => $assertionCredentials->assertionType,
313
+ 'assertion' => $assertionCredentials->generateAssertion(),
314
+ )
315
+ );
316
+
317
+ if ($cacheKey) {
318
+ // Attempt to cache the token.
319
+ $this->client->getCache()->set(
320
+ $cacheKey,
321
+ $this->getAccessToken()
322
+ );
323
+ }
324
+ }
325
+
326
+ private function refreshTokenRequest($params)
327
+ {
328
+ if (isset($params['assertion'])) {
329
+ $this->client->getLogger()->info(
330
+ 'OAuth2 access token refresh with Signed JWT assertion grants.'
331
+ );
332
+ } else {
333
+ $this->client->getLogger()->info('OAuth2 access token refresh');
334
+ }
335
+
336
+ $http = new Google_Http_Request(
337
+ self::OAUTH2_TOKEN_URI,
338
+ 'POST',
339
+ array(),
340
+ $params
341
+ );
342
+ $http->disableGzip();
343
+ $request = $this->client->getIo()->makeRequest($http);
344
+
345
+ $code = $request->getResponseHttpCode();
346
+ $body = $request->getResponseBody();
347
+ if (200 == $code) {
348
+ $token = json_decode($body, true);
349
+ if ($token == null) {
350
+ throw new Google_Auth_Exception("Could not json decode the access token");
351
+ }
352
+
353
+ if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
354
+ throw new Google_Auth_Exception("Invalid token format");
355
+ }
356
+
357
+ if (isset($token['id_token'])) {
358
+ $this->token['id_token'] = $token['id_token'];
359
+ }
360
+ $this->token['access_token'] = $token['access_token'];
361
+ $this->token['expires_in'] = $token['expires_in'];
362
+ $this->token['created'] = time();
363
+ } else {
364
+ throw new Google_Auth_Exception("Error refreshing the OAuth2 token, message: '$body'", $code);
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
370
+ * token, if a token isn't provided.
371
+ * @throws Google_Auth_Exception
372
+ * @param string|null $token The token (access token or a refresh token) that should be revoked.
373
+ * @return boolean Returns True if the revocation was successful, otherwise False.
374
+ */
375
+ public function revokeToken($token = null)
376
+ {
377
+ if (!$token) {
378
+ if (!$this->token) {
379
+ // Not initialized, no token to actually revoke
380
+ return false;
381
+ } elseif (array_key_exists('refresh_token', $this->token)) {
382
+ $token = $this->token['refresh_token'];
383
+ } else {
384
+ $token = $this->token['access_token'];
385
+ }
386
+ }
387
+ $request = new Google_Http_Request(
388
+ self::OAUTH2_REVOKE_URI,
389
+ 'POST',
390
+ array(),
391
+ "token=$token"
392
+ );
393
+ $request->disableGzip();
394
+ $response = $this->client->getIo()->makeRequest($request);
395
+ $code = $response->getResponseHttpCode();
396
+ if ($code == 200) {
397
+ $this->token = null;
398
+ return true;
399
+ }
400
+
401
+ return false;
402
+ }
403
+
404
+ /**
405
+ * Returns if the access_token is expired.
406
+ * @return bool Returns True if the access_token is expired.
407
+ */
408
+ public function isAccessTokenExpired()
409
+ {
410
+ if (!$this->token || !isset($this->token['created'])) {
411
+ return true;
412
+ }
413
+
414
+ // If the token is set to expire in the next 30 seconds.
415
+ $expired = ($this->token['created']
416
+ + ($this->token['expires_in'] - 30)) < time();
417
+
418
+ return $expired;
419
+ }
420
+
421
+ // Gets federated sign-on certificates to use for verifying identity tokens.
422
+ // Returns certs as array structure, where keys are key ids, and values
423
+ // are PEM encoded certificates.
424
+ private function getFederatedSignOnCerts()
425
+ {
426
+ return $this->retrieveCertsFromLocation(
427
+ $this->client->getClassConfig($this, 'federated_signon_certs_url')
428
+ );
429
+ }
430
+
431
+ /**
432
+ * Retrieve and cache a certificates file.
433
+ *
434
+ * @param $url string location
435
+ * @throws Google_Auth_Exception
436
+ * @return array certificates
437
+ */
438
+ public function retrieveCertsFromLocation($url)
439
+ {
440
+ // If we're retrieving a local file, just grab it.
441
+ if ("http" != substr($url, 0, 4)) {
442
+ $file = file_get_contents($url);
443
+ if ($file) {
444
+ return json_decode($file, true);
445
+ } else {
446
+ throw new Google_Auth_Exception(
447
+ "Failed to retrieve verification certificates: '" .
448
+ $url . "'."
449
+ );
450
+ }
451
+ }
452
+
453
+ // This relies on makeRequest caching certificate responses.
454
+ $request = $this->client->getIo()->makeRequest(
455
+ new Google_Http_Request(
456
+ $url
457
+ )
458
+ );
459
+ if ($request->getResponseHttpCode() == 200) {
460
+ $certs = json_decode($request->getResponseBody(), true);
461
+ if ($certs) {
462
+ return $certs;
463
+ }
464
+ }
465
+ throw new Google_Auth_Exception(
466
+ "Failed to retrieve verification certificates: '" .
467
+ $request->getResponseBody() . "'.",
468
+ $request->getResponseHttpCode()
469
+ );
470
+ }
471
+
472
+ /**
473
+ * Verifies an id token and returns the authenticated apiLoginTicket.
474
+ * Throws an exception if the id token is not valid.
475
+ * The audience parameter can be used to control which id tokens are
476
+ * accepted. By default, the id token must have been issued to this OAuth2 client.
477
+ *
478
+ * @param $id_token
479
+ * @param $audience
480
+ * @return Google_Auth_LoginTicket
481
+ */
482
+ public function verifyIdToken($id_token = null, $audience = null)
483
+ {
484
+ if (!$id_token) {
485
+ $id_token = $this->token['id_token'];
486
+ }
487
+ $certs = $this->getFederatedSignonCerts();
488
+ if (!$audience) {
489
+ $audience = $this->client->getClassConfig($this, 'client_id');
490
+ }
491
+
492
+ return $this->verifySignedJwtWithCerts(
493
+ $id_token,
494
+ $certs,
495
+ $audience,
496
+ array(self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS)
497
+ );
498
+ }
499
+
500
+ /**
501
+ * Verifies the id token, returns the verified token contents.
502
+ *
503
+ * @param $jwt string the token
504
+ * @param $certs array of certificates
505
+ * @param $required_audience string the expected consumer of the token
506
+ * @param [$issuer] the expected issues, defaults to Google
507
+ * @param [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS
508
+ * @throws Google_Auth_Exception
509
+ * @return mixed token information if valid, false if not
510
+ */
511
+ public function verifySignedJwtWithCerts(
512
+ $jwt,
513
+ $certs,
514
+ $required_audience,
515
+ $issuer = null,
516
+ $max_expiry = null
517
+ ) {
518
+ if (!$max_expiry) {
519
+ // Set the maximum time we will accept a token for.
520
+ $max_expiry = self::MAX_TOKEN_LIFETIME_SECS;
521
+ }
522
+
523
+ $segments = explode(".", $jwt);
524
+ if (count($segments) != 3) {
525
+ throw new Google_Auth_Exception("Wrong number of segments in token: $jwt");
526
+ }
527
+ $signed = $segments[0] . "." . $segments[1];
528
+ $signature = Google_Utils::urlSafeB64Decode($segments[2]);
529
+
530
+ // Parse envelope.
531
+ $envelope = json_decode(Google_Utils::urlSafeB64Decode($segments[0]), true);
532
+ if (!$envelope) {
533
+ throw new Google_Auth_Exception("Can't parse token envelope: " . $segments[0]);
534
+ }
535
+
536
+ // Parse token
537
+ $json_body = Google_Utils::urlSafeB64Decode($segments[1]);
538
+ $payload = json_decode($json_body, true);
539
+ if (!$payload) {
540
+ throw new Google_Auth_Exception("Can't parse token payload: " . $segments[1]);
541
+ }
542
+
543
+ // Check signature
544
+ $verified = false;
545
+ foreach ($certs as $keyName => $pem) {
546
+ $public_key = new Google_Verifier_Pem($pem);
547
+ if ($public_key->verify($signed, $signature)) {
548
+ $verified = true;
549
+ break;
550
+ }
551
+ }
552
+
553
+ if (!$verified) {
554
+ throw new Google_Auth_Exception("Invalid token signature: $jwt");
555
+ }
556
+
557
+ // Check issued-at timestamp
558
+ $iat = 0;
559
+ if (array_key_exists("iat", $payload)) {
560
+ $iat = $payload["iat"];
561
+ }
562
+ if (!$iat) {
563
+ throw new Google_Auth_Exception("No issue time in token: $json_body");
564
+ }
565
+ $earliest = $iat - self::CLOCK_SKEW_SECS;
566
+
567
+ // Check expiration timestamp
568
+ $now = time();
569
+ $exp = 0;
570
+ if (array_key_exists("exp", $payload)) {
571
+ $exp = $payload["exp"];
572
+ }
573
+ if (!$exp) {
574
+ throw new Google_Auth_Exception("No expiration time in token: $json_body");
575
+ }
576
+ if ($exp >= $now + $max_expiry) {
577
+ throw new Google_Auth_Exception(
578
+ sprintf("Expiration time too far in future: %s", $json_body)
579
+ );
580
+ }
581
+
582
+ $latest = $exp + self::CLOCK_SKEW_SECS;
583
+ if ($now < $earliest) {
584
+ throw new Google_Auth_Exception(
585
+ sprintf(
586
+ "Token used too early, %s < %s: %s",
587
+ $now,
588
+ $earliest,
589
+ $json_body
590
+ )
591
+ );
592
+ }
593
+ if ($now > $latest) {
594
+ throw new Google_Auth_Exception(
595
+ sprintf(
596
+ "Token used too late, %s > %s: %s",
597
+ $now,
598
+ $latest,
599
+ $json_body
600
+ )
601
+ );
602
+ }
603
+
604
+ // support HTTP and HTTPS issuers
605
+ // @see https://developers.google.com/identity/sign-in/web/backend-auth
606
+ $iss = $payload['iss'];
607
+ if ($issuer && !in_array($iss, (array) $issuer)) {
608
+ throw new Google_Auth_Exception(
609
+ sprintf(
610
+ "Invalid issuer, %s not in %s: %s",
611
+ $iss,
612
+ "[".implode(",", (array) $issuer)."]",
613
+ $json_body
614
+ )
615
+ );
616
+ }
617
+
618
+ // Check audience
619
+ $aud = $payload["aud"];
620
+ if ($aud != $required_audience) {
621
+ throw new Google_Auth_Exception(
622
+ sprintf(
623
+ "Wrong recipient, %s != %s:",
624
+ $aud,
625
+ $required_audience,
626
+ $json_body
627
+ )
628
+ );
629
+ }
630
+
631
+ // All good.
632
+ return new Google_Auth_LoginTicket($envelope, $payload);
633
+ }
634
+
635
+ /**
636
+ * Add a parameter to the auth params if not empty string.
637
+ */
638
+ private function maybeAddParam($params, $name)
639
+ {
640
+ $param = $this->client->getClassConfig($this, $name);
641
+ if ($param != '') {
642
+ $params[$name] = $param;
643
+ }
644
+ return $params;
645
+ }
646
+ }
google/Auth/Simple.php CHANGED
@@ -1,63 +1,63 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * Simple API access implementation. Can either be used to make requests
24
- * completely unauthenticated, or by using a Simple API Access developer
25
- * key.
26
- */
27
- class Google_Auth_Simple extends Google_Auth_Abstract
28
- {
29
- private $client;
30
-
31
- public function __construct(Google_Client $client, $config = null)
32
- {
33
- $this->client = $client;
34
- }
35
-
36
- /**
37
- * Perform an authenticated / signed apiHttpRequest.
38
- * This function takes the apiHttpRequest, calls apiAuth->sign on it
39
- * (which can modify the request in what ever way fits the auth mechanism)
40
- * and then calls apiCurlIO::makeRequest on the signed request
41
- *
42
- * @param Google_Http_Request $request
43
- * @return Google_Http_Request The resulting HTTP response including the
44
- * responseHttpCode, responseHeaders and responseBody.
45
- */
46
- public function authenticatedRequest(Google_Http_Request $request)
47
- {
48
- $request = $this->sign($request);
49
- return $this->io->makeRequest($request);
50
- }
51
-
52
- public function sign(Google_Http_Request $request)
53
- {
54
- $key = $this->client->getClassConfig($this, 'developer_key');
55
- if ($key) {
56
- $this->client->getLogger()->debug(
57
- 'Simple API Access developer key authentication'
58
- );
59
- $request->setQueryParam('key', $key);
60
- }
61
- return $request;
62
- }
63
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * Simple API access implementation. Can either be used to make requests
24
+ * completely unauthenticated, or by using a Simple API Access developer
25
+ * key.
26
+ */
27
+ class Google_Auth_Simple extends Google_Auth_Abstract
28
+ {
29
+ private $client;
30
+
31
+ public function __construct(Google_Client $client, $config = null)
32
+ {
33
+ $this->client = $client;
34
+ }
35
+
36
+ /**
37
+ * Perform an authenticated / signed apiHttpRequest.
38
+ * This function takes the apiHttpRequest, calls apiAuth->sign on it
39
+ * (which can modify the request in what ever way fits the auth mechanism)
40
+ * and then calls apiCurlIO::makeRequest on the signed request
41
+ *
42
+ * @param Google_Http_Request $request
43
+ * @return Google_Http_Request The resulting HTTP response including the
44
+ * responseHttpCode, responseHeaders and responseBody.
45
+ */
46
+ public function authenticatedRequest(Google_Http_Request $request)
47
+ {
48
+ $request = $this->sign($request);
49
+ return $this->io->makeRequest($request);
50
+ }
51
+
52
+ public function sign(Google_Http_Request $request)
53
+ {
54
+ $key = $this->client->getClassConfig($this, 'developer_key');
55
+ if ($key) {
56
+ $this->client->getLogger()->debug(
57
+ 'Simple API Access developer key authentication'
58
+ );
59
+ $request->setQueryParam('key', $key);
60
+ }
61
+ return $request;
62
+ }
63
+ }
google/Cache/Abstract.php CHANGED
@@ -1,53 +1,53 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * Abstract storage class
20
- *
21
- * @author Chris Chabot <chabotc@google.com>
22
- */
23
- abstract class Google_Cache_Abstract
24
- {
25
-
26
- abstract public function __construct(Google_Client $client);
27
-
28
- /**
29
- * Retrieves the data for the given key, or false if they
30
- * key is unknown or expired
31
- *
32
- * @param String $key The key who's data to retrieve
33
- * @param boolean|int $expiration Expiration time in seconds
34
- *
35
- */
36
- abstract public function get($key, $expiration = false);
37
-
38
- /**
39
- * Store the key => $value set. The $value is serialized
40
- * by this function so can be of any type
41
- *
42
- * @param string $key Key of the data
43
- * @param string $value data
44
- */
45
- abstract public function set($key, $value);
46
-
47
- /**
48
- * Removes the key/data pair for the given $key
49
- *
50
- * @param String $key
51
- */
52
- abstract public function delete($key);
53
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2008 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * Abstract storage class
20
+ *
21
+ * @author Chris Chabot <chabotc@google.com>
22
+ */
23
+ abstract class Google_Cache_Abstract
24
+ {
25
+
26
+ abstract public function __construct(Google_Client $client);
27
+
28
+ /**
29
+ * Retrieves the data for the given key, or false if they
30
+ * key is unknown or expired
31
+ *
32
+ * @param String $key The key who's data to retrieve
33
+ * @param boolean|int $expiration Expiration time in seconds
34
+ *
35
+ */
36
+ abstract public function get($key, $expiration = false);
37
+
38
+ /**
39
+ * Store the key => $value set. The $value is serialized
40
+ * by this function so can be of any type
41
+ *
42
+ * @param string $key Key of the data
43
+ * @param string $value data
44
+ */
45
+ abstract public function set($key, $value);
46
+
47
+ /**
48
+ * Removes the key/data pair for the given $key
49
+ *
50
+ * @param String $key
51
+ */
52
+ abstract public function delete($key);
53
+ }
google/Cache/Apc.php CHANGED
@@ -1,113 +1,113 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * A persistent storage class based on the APC cache, which is not
24
- * really very persistent, as soon as you restart your web server
25
- * the storage will be wiped, however for debugging and/or speed
26
- * it can be useful, and cache is a lot cheaper then storage.
27
- *
28
- * @author Chris Chabot <chabotc@google.com>
29
- */
30
- class Google_Cache_Apc extends Google_Cache_Abstract
31
- {
32
- /**
33
- * @var Google_Client the current client
34
- */
35
- private $client;
36
-
37
- public function __construct(Google_Client $client)
38
- {
39
- if (! function_exists('apc_add') ) {
40
- $error = "Apc functions not available";
41
-
42
- $client->getLogger()->error($error);
43
- throw new Google_Cache_Exception($error);
44
- }
45
-
46
- $this->client = $client;
47
- }
48
-
49
- /**
50
- * @inheritDoc
51
- */
52
- public function get($key, $expiration = false)
53
- {
54
- $ret = apc_fetch($key);
55
- if ($ret === false) {
56
- $this->client->getLogger()->debug(
57
- 'APC cache miss',
58
- array('key' => $key)
59
- );
60
- return false;
61
- }
62
- if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
63
- $this->client->getLogger()->debug(
64
- 'APC cache miss (expired)',
65
- array('key' => $key, 'var' => $ret)
66
- );
67
- $this->delete($key);
68
- return false;
69
- }
70
-
71
- $this->client->getLogger()->debug(
72
- 'APC cache hit',
73
- array('key' => $key, 'var' => $ret)
74
- );
75
-
76
- return $ret['data'];
77
- }
78
-
79
- /**
80
- * @inheritDoc
81
- */
82
- public function set($key, $value)
83
- {
84
- $var = array('time' => time(), 'data' => $value);
85
- $rc = apc_store($key, $var);
86
-
87
- if ($rc == false) {
88
- $this->client->getLogger()->error(
89
- 'APC cache set failed',
90
- array('key' => $key, 'var' => $var)
91
- );
92
- throw new Google_Cache_Exception("Couldn't store data");
93
- }
94
-
95
- $this->client->getLogger()->debug(
96
- 'APC cache set',
97
- array('key' => $key, 'var' => $var)
98
- );
99
- }
100
-
101
- /**
102
- * @inheritDoc
103
- * @param String $key
104
- */
105
- public function delete($key)
106
- {
107
- $this->client->getLogger()->debug(
108
- 'APC cache delete',
109
- array('key' => $key)
110
- );
111
- apc_delete($key);
112
- }
113
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * A persistent storage class based on the APC cache, which is not
24
+ * really very persistent, as soon as you restart your web server
25
+ * the storage will be wiped, however for debugging and/or speed
26
+ * it can be useful, and cache is a lot cheaper then storage.
27
+ *
28
+ * @author Chris Chabot <chabotc@google.com>
29
+ */
30
+ class Google_Cache_Apc extends Google_Cache_Abstract
31
+ {
32
+ /**
33
+ * @var Google_Client the current client
34
+ */
35
+ private $client;
36
+
37
+ public function __construct(Google_Client $client)
38
+ {
39
+ if (! function_exists('apc_add') ) {
40
+ $error = "Apc functions not available";
41
+
42
+ $client->getLogger()->error($error);
43
+ throw new Google_Cache_Exception($error);
44
+ }
45
+
46
+ $this->client = $client;
47
+ }
48
+
49
+ /**
50
+ * @inheritDoc
51
+ */
52
+ public function get($key, $expiration = false)
53
+ {
54
+ $ret = apc_fetch($key);
55
+ if ($ret === false) {
56
+ $this->client->getLogger()->debug(
57
+ 'APC cache miss',
58
+ array('key' => $key)
59
+ );
60
+ return false;
61
+ }
62
+ if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
63
+ $this->client->getLogger()->debug(
64
+ 'APC cache miss (expired)',
65
+ array('key' => $key, 'var' => $ret)
66
+ );
67
+ $this->delete($key);
68
+ return false;
69
+ }
70
+
71
+ $this->client->getLogger()->debug(
72
+ 'APC cache hit',
73
+ array('key' => $key, 'var' => $ret)
74
+ );
75
+
76
+ return $ret['data'];
77
+ }
78
+
79
+ /**
80
+ * @inheritDoc
81
+ */
82
+ public function set($key, $value)
83
+ {
84
+ $var = array('time' => time(), 'data' => $value);
85
+ $rc = apc_store($key, $var);
86
+
87
+ if ($rc == false) {
88
+ $this->client->getLogger()->error(
89
+ 'APC cache set failed',
90
+ array('key' => $key, 'var' => $var)
91
+ );
92
+ throw new Google_Cache_Exception("Couldn't store data");
93
+ }
94
+
95
+ $this->client->getLogger()->debug(
96
+ 'APC cache set',
97
+ array('key' => $key, 'var' => $var)
98
+ );
99
+ }
100
+
101
+ /**
102
+ * @inheritDoc
103
+ * @param String $key
104
+ */
105
+ public function delete($key)
106
+ {
107
+ $this->client->getLogger()->debug(
108
+ 'APC cache delete',
109
+ array('key' => $key)
110
+ );
111
+ apc_delete($key);
112
+ }
113
+ }
google/Cache/Exception.php CHANGED
@@ -1,24 +1,24 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- class Google_Cache_Exception extends Google_Exception
23
- {
24
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ class Google_Cache_Exception extends Google_Exception
23
+ {
24
+ }
google/Cache/File.php CHANGED
@@ -1,209 +1,209 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /*
23
- * This class implements a basic on disk storage. While that does
24
- * work quite well it's not the most elegant and scalable solution.
25
- * It will also get you into a heap of trouble when you try to run
26
- * this in a clustered environment.
27
- *
28
- * @author Chris Chabot <chabotc@google.com>
29
- */
30
- class Google_Cache_File extends Google_Cache_Abstract
31
- {
32
- const MAX_LOCK_RETRIES = 10;
33
- private $path;
34
- private $fh;
35
-
36
- /**
37
- * @var Google_Client the current client
38
- */
39
- private $client;
40
-
41
- public function __construct(Google_Client $client)
42
- {
43
- $this->client = $client;
44
- $this->path = $this->client->getClassConfig($this, 'directory');
45
- }
46
-
47
- public function get($key, $expiration = false)
48
- {
49
- $storageFile = $this->getCacheFile($key);
50
- $data = false;
51
-
52
- if (!file_exists($storageFile)) {
53
- $this->client->getLogger()->debug(
54
- 'File cache miss',
55
- array('key' => $key, 'file' => $storageFile)
56
- );
57
- return false;
58
- }
59
-
60
- if ($expiration) {
61
- $mtime = filemtime($storageFile);
62
- if ((time() - $mtime) >= $expiration) {
63
- $this->client->getLogger()->debug(
64
- 'File cache miss (expired)',
65
- array('key' => $key, 'file' => $storageFile)
66
- );
67
- $this->delete($key);
68
- return false;
69
- }
70
- }
71
-
72
- if ($this->acquireReadLock($storageFile)) {
73
- if (filesize($storageFile) > 0) {
74
- $data = fread($this->fh, filesize($storageFile));
75
- $data = unserialize($data);
76
- } else {
77
- $this->client->getLogger()->debug(
78
- 'Cache file was empty',
79
- array('file' => $storageFile)
80
- );
81
- }
82
- $this->unlock($storageFile);
83
- }
84
-
85
- $this->client->getLogger()->debug(
86
- 'File cache hit',
87
- array('key' => $key, 'file' => $storageFile, 'var' => $data)
88
- );
89
-
90
- return $data;
91
- }
92
-
93
- public function set($key, $value)
94
- {
95
- $storageFile = $this->getWriteableCacheFile($key);
96
- if ($this->acquireWriteLock($storageFile)) {
97
- // We serialize the whole request object, since we don't only want the
98
- // responseContent but also the postBody used, headers, size, etc.
99
- $data = serialize($value);
100
- $result = fwrite($this->fh, $data);
101
- $this->unlock($storageFile);
102
-
103
- $this->client->getLogger()->debug(
104
- 'File cache set',
105
- array('key' => $key, 'file' => $storageFile, 'var' => $value)
106
- );
107
- } else {
108
- $this->client->getLogger()->notice(
109
- 'File cache set failed',
110
- array('key' => $key, 'file' => $storageFile)
111
- );
112
- }
113
- }
114
-
115
- public function delete($key)
116
- {
117
- $file = $this->getCacheFile($key);
118
- if (file_exists($file) && !unlink($file)) {
119
- $this->client->getLogger()->error(
120
- 'File cache delete failed',
121
- array('key' => $key, 'file' => $file)
122
- );
123
- throw new Google_Cache_Exception("Cache file could not be deleted");
124
- }
125
-
126
- $this->client->getLogger()->debug(
127
- 'File cache delete',
128
- array('key' => $key, 'file' => $file)
129
- );
130
- }
131
-
132
- private function getWriteableCacheFile($file)
133
- {
134
- return $this->getCacheFile($file, true);
135
- }
136
-
137
- private function getCacheFile($file, $forWrite = false)
138
- {
139
- return $this->getCacheDir($file, $forWrite) . '/' . md5($file);
140
- }
141
-
142
- private function getCacheDir($file, $forWrite)
143
- {
144
- // use the first 2 characters of the hash as a directory prefix
145
- // this should prevent slowdowns due to huge directory listings
146
- // and thus give some basic amount of scalability
147
- $storageDir = $this->path . '/' . substr(md5($file), 0, 2);
148
- if ($forWrite && ! is_dir($storageDir)) {
149
- if (! mkdir($storageDir, 0700, true)) {
150
- $this->client->getLogger()->error(
151
- 'File cache creation failed',
152
- array('dir' => $storageDir)
153
- );
154
- throw new Google_Cache_Exception("Could not create storage directory: $storageDir");
155
- }
156
- }
157
- return $storageDir;
158
- }
159
-
160
- private function acquireReadLock($storageFile)
161
- {
162
- return $this->acquireLock(LOCK_SH, $storageFile);
163
- }
164
-
165
- private function acquireWriteLock($storageFile)
166
- {
167
- $rc = $this->acquireLock(LOCK_EX, $storageFile);
168
- if (!$rc) {
169
- $this->client->getLogger()->notice(
170
- 'File cache write lock failed',
171
- array('file' => $storageFile)
172
- );
173
- $this->delete($storageFile);
174
- }
175
- return $rc;
176
- }
177
-
178
- private function acquireLock($type, $storageFile)
179
- {
180
- $mode = $type == LOCK_EX ? "w" : "r";
181
- $this->fh = fopen($storageFile, $mode);
182
- if (!$this->fh) {
183
- $this->client->getLogger()->error(
184
- 'Failed to open file during lock acquisition',
185
- array('file' => $storageFile)
186
- );
187
- return false;
188
- }
189
- if ($type == LOCK_EX) {
190
- chmod($storageFile, 0600);
191
- }
192
- $count = 0;
193
- while (!flock($this->fh, $type | LOCK_NB)) {
194
- // Sleep for 10ms.
195
- usleep(10000);
196
- if (++$count < self::MAX_LOCK_RETRIES) {
197
- return false;
198
- }
199
- }
200
- return true;
201
- }
202
-
203
- public function unlock($storageFile)
204
- {
205
- if ($this->fh) {
206
- flock($this->fh, LOCK_UN);
207
- }
208
- }
209
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2008 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /*
23
+ * This class implements a basic on disk storage. While that does
24
+ * work quite well it's not the most elegant and scalable solution.
25
+ * It will also get you into a heap of trouble when you try to run
26
+ * this in a clustered environment.
27
+ *
28
+ * @author Chris Chabot <chabotc@google.com>
29
+ */
30
+ class Google_Cache_File extends Google_Cache_Abstract
31
+ {
32
+ const MAX_LOCK_RETRIES = 10;
33
+ private $path;
34
+ private $fh;
35
+
36
+ /**
37
+ * @var Google_Client the current client
38
+ */
39
+ private $client;
40
+
41
+ public function __construct(Google_Client $client)
42
+ {
43
+ $this->client = $client;
44
+ $this->path = $this->client->getClassConfig($this, 'directory');
45
+ }
46
+
47
+ public function get($key, $expiration = false)
48
+ {
49
+ $storageFile = $this->getCacheFile($key);
50
+ $data = false;
51
+
52
+ if (!file_exists($storageFile)) {
53
+ $this->client->getLogger()->debug(
54
+ 'File cache miss',
55
+ array('key' => $key, 'file' => $storageFile)
56
+ );
57
+ return false;
58
+ }
59
+
60
+ if ($expiration) {
61
+ $mtime = filemtime($storageFile);
62
+ if ((time() - $mtime) >= $expiration) {
63
+ $this->client->getLogger()->debug(
64
+ 'File cache miss (expired)',
65
+ array('key' => $key, 'file' => $storageFile)
66
+ );
67
+ $this->delete($key);
68
+ return false;
69
+ }
70
+ }
71
+
72
+ if ($this->acquireReadLock($storageFile)) {
73
+ if (filesize($storageFile) > 0) {
74
+ $data = fread($this->fh, filesize($storageFile));
75
+ $data = unserialize($data);
76
+ } else {
77
+ $this->client->getLogger()->debug(
78
+ 'Cache file was empty',
79
+ array('file' => $storageFile)
80
+ );
81
+ }
82
+ $this->unlock($storageFile);
83
+ }
84
+
85
+ $this->client->getLogger()->debug(
86
+ 'File cache hit',
87
+ array('key' => $key, 'file' => $storageFile, 'var' => $data)
88
+ );
89
+
90
+ return $data;
91
+ }
92
+
93
+ public function set($key, $value)
94
+ {
95
+ $storageFile = $this->getWriteableCacheFile($key);
96
+ if ($this->acquireWriteLock($storageFile)) {
97
+ // We serialize the whole request object, since we don't only want the
98
+ // responseContent but also the postBody used, headers, size, etc.
99
+ $data = serialize($value);
100
+ $result = fwrite($this->fh, $data);
101
+ $this->unlock($storageFile);
102
+
103
+ $this->client->getLogger()->debug(
104
+ 'File cache set',
105
+ array('key' => $key, 'file' => $storageFile, 'var' => $value)
106
+ );
107
+ } else {
108
+ $this->client->getLogger()->notice(
109
+ 'File cache set failed',
110
+ array('key' => $key, 'file' => $storageFile)
111
+ );
112
+ }
113
+ }
114
+
115
+ public function delete($key)
116
+ {
117
+ $file = $this->getCacheFile($key);
118
+ if (file_exists($file) && !unlink($file)) {
119
+ $this->client->getLogger()->error(
120
+ 'File cache delete failed',
121
+ array('key' => $key, 'file' => $file)
122
+ );
123
+ throw new Google_Cache_Exception("Cache file could not be deleted");
124
+ }
125
+
126
+ $this->client->getLogger()->debug(
127
+ 'File cache delete',
128
+ array('key' => $key, 'file' => $file)
129
+ );
130
+ }
131
+
132
+ private function getWriteableCacheFile($file)
133
+ {
134
+ return $this->getCacheFile($file, true);
135
+ }
136
+
137
+ private function getCacheFile($file, $forWrite = false)
138
+ {
139
+ return $this->getCacheDir($file, $forWrite) . '/' . md5($file);
140
+ }
141
+
142
+ private function getCacheDir($file, $forWrite)
143
+ {
144
+ // use the first 2 characters of the hash as a directory prefix
145
+ // this should prevent slowdowns due to huge directory listings
146
+ // and thus give some basic amount of scalability
147
+ $storageDir = $this->path . '/' . substr(md5($file), 0, 2);
148
+ if ($forWrite && ! is_dir($storageDir)) {
149
+ if (! mkdir($storageDir, 0700, true)) {
150
+ $this->client->getLogger()->error(
151
+ 'File cache creation failed',
152
+ array('dir' => $storageDir)
153
+ );
154
+ throw new Google_Cache_Exception("Could not create storage directory: $storageDir");
155
+ }
156
+ }
157
+ return $storageDir;
158
+ }
159
+
160
+ private function acquireReadLock($storageFile)
161
+ {
162
+ return $this->acquireLock(LOCK_SH, $storageFile);
163
+ }
164
+
165
+ private function acquireWriteLock($storageFile)
166
+ {
167
+ $rc = $this->acquireLock(LOCK_EX, $storageFile);
168
+ if (!$rc) {
169
+ $this->client->getLogger()->notice(
170
+ 'File cache write lock failed',
171
+ array('file' => $storageFile)
172
+ );
173
+ $this->delete($storageFile);
174
+ }
175
+ return $rc;
176
+ }
177
+
178
+ private function acquireLock($type, $storageFile)
179
+ {
180
+ $mode = $type == LOCK_EX ? "w" : "r";
181
+ $this->fh = fopen($storageFile, $mode);
182
+ if (!$this->fh) {
183
+ $this->client->getLogger()->error(
184
+ 'Failed to open file during lock acquisition',
185
+ array('file' => $storageFile)
186
+ );
187
+ return false;
188
+ }
189
+ if ($type == LOCK_EX) {
190
+ chmod($storageFile, 0600);
191
+ }
192
+ $count = 0;
193
+ while (!flock($this->fh, $type | LOCK_NB)) {
194
+ // Sleep for 10ms.
195
+ usleep(10000);
196
+ if (++$count < self::MAX_LOCK_RETRIES) {
197
+ return false;
198
+ }
199
+ }
200
+ return true;
201
+ }
202
+
203
+ public function unlock($storageFile)
204
+ {
205
+ if ($this->fh) {
206
+ flock($this->fh, LOCK_UN);
207
+ }
208
+ }
209
+ }
google/Cache/Memcache.php CHANGED
@@ -1,184 +1,184 @@
1
- <?php
2
- /*
3
- * Copyright 2008 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * A persistent storage class based on the memcache, which is not
24
- * really very persistent, as soon as you restart your memcache daemon
25
- * the storage will be wiped.
26
- *
27
- * Will use either the memcache or memcached extensions, preferring
28
- * memcached.
29
- *
30
- * @author Chris Chabot <chabotc@google.com>
31
- */
32
- class Google_Cache_Memcache extends Google_Cache_Abstract
33
- {
34
- private $connection = false;
35
- private $mc = false;
36
- private $host;
37
- private $port;
38
-
39
- /**
40
- * @var Google_Client the current client
41
- */
42
- private $client;
43
-
44
- public function __construct(Google_Client $client)
45
- {
46
- if (!function_exists('memcache_connect') && !class_exists("Memcached")) {
47
- $error = "Memcache functions not available";
48
-
49
- $client->getLogger()->error($error);
50
- throw new Google_Cache_Exception($error);
51
- }
52
-
53
- $this->client = $client;
54
-
55
- if ($client->isAppEngine()) {
56
- // No credentials needed for GAE.
57
- $this->mc = new Memcached();
58
- $this->connection = true;
59
- } else {
60
- $this->host = $client->getClassConfig($this, 'host');
61
- $this->port = $client->getClassConfig($this, 'port');
62
- if (empty($this->host) || (empty($this->port) && (string) $this->port != "0")) {
63
- $error = "You need to supply a valid memcache host and port";
64
-
65
- $client->getLogger()->error($error);
66
- throw new Google_Cache_Exception($error);
67
- }
68
- }
69
- }
70
-
71
- /**
72
- * @inheritDoc
73
- */
74
- public function get($key, $expiration = false)
75
- {
76
- $this->connect();
77
- $ret = false;
78
- if ($this->mc) {
79
- $ret = $this->mc->get($key);
80
- } else {
81
- $ret = memcache_get($this->connection, $key);
82
- }
83
- if ($ret === false) {
84
- $this->client->getLogger()->debug(
85
- 'Memcache cache miss',
86
- array('key' => $key)
87
- );
88
- return false;
89
- }
90
- if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
91
- $this->client->getLogger()->debug(
92
- 'Memcache cache miss (expired)',
93
- array('key' => $key, 'var' => $ret)
94
- );
95
- $this->delete($key);
96
- return false;
97
- }
98
-
99
- $this->client->getLogger()->debug(
100
- 'Memcache cache hit',
101
- array('key' => $key, 'var' => $ret)
102
- );
103
-
104
- return $ret['data'];
105
- }
106
-
107
- /**
108
- * @inheritDoc
109
- * @param string $key
110
- * @param string $value
111
- * @throws Google_Cache_Exception
112
- */
113
- public function set($key, $value)
114
- {
115
- $this->connect();
116
- // we store it with the cache_time default expiration so objects will at
117
- // least get cleaned eventually.
118
- $data = array('time' => time(), 'data' => $value);
119
- $rc = false;
120
- if ($this->mc) {
121
- $rc = $this->mc->set($key, $data);
122
- } else {
123
- $rc = memcache_set($this->connection, $key, $data, false);
124
- }
125
- if ($rc == false) {
126
- $this->client->getLogger()->error(
127
- 'Memcache cache set failed',
128
- array('key' => $key, 'var' => $data)
129
- );
130
-
131
- throw new Google_Cache_Exception("Couldn't store data in cache");
132
- }
133
-
134
- $this->client->getLogger()->debug(
135
- 'Memcache cache set',
136
- array('key' => $key, 'var' => $data)
137
- );
138
- }
139
-
140
- /**
141
- * @inheritDoc
142
- * @param String $key
143
- */
144
- public function delete($key)
145
- {
146
- $this->connect();
147
- if ($this->mc) {
148
- $this->mc->delete($key, 0);
149
- } else {
150
- memcache_delete($this->connection, $key, 0);
151
- }
152
-
153
- $this->client->getLogger()->debug(
154
- 'Memcache cache delete',
155
- array('key' => $key)
156
- );
157
- }
158
-
159
- /**
160
- * Lazy initialiser for memcache connection. Uses pconnect for to take
161
- * advantage of the persistence pool where possible.
162
- */
163
- private function connect()
164
- {
165
- if ($this->connection) {
166
- return;
167
- }
168
-
169
- if (class_exists("Memcached")) {
170
- $this->mc = new Memcached();
171
- $this->mc->addServer($this->host, $this->port);
172
- $this->connection = true;
173
- } else {
174
- $this->connection = memcache_pconnect($this->host, $this->port);
175
- }
176
-
177
- if (! $this->connection) {
178
- $error = "Couldn't connect to memcache server";
179
-
180
- $this->client->getLogger()->error($error);
181
- throw new Google_Cache_Exception($error);
182
- }
183
- }
184
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2008 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * A persistent storage class based on the memcache, which is not
24
+ * really very persistent, as soon as you restart your memcache daemon
25
+ * the storage will be wiped.
26
+ *
27
+ * Will use either the memcache or memcached extensions, preferring
28
+ * memcached.
29
+ *
30
+ * @author Chris Chabot <chabotc@google.com>
31
+ */
32
+ class Google_Cache_Memcache extends Google_Cache_Abstract
33
+ {
34
+ private $connection = false;
35
+ private $mc = false;
36
+ private $host;
37
+ private $port;
38
+
39
+ /**
40
+ * @var Google_Client the current client
41
+ */
42
+ private $client;
43
+
44
+ public function __construct(Google_Client $client)
45
+ {
46
+ if (!function_exists('memcache_connect') && !class_exists("Memcached")) {
47
+ $error = "Memcache functions not available";
48
+
49
+ $client->getLogger()->error($error);
50
+ throw new Google_Cache_Exception($error);
51
+ }
52
+
53
+ $this->client = $client;
54
+
55
+ if ($client->isAppEngine()) {
56
+ // No credentials needed for GAE.
57
+ $this->mc = new Memcached();
58
+ $this->connection = true;
59
+ } else {
60
+ $this->host = $client->getClassConfig($this, 'host');
61
+ $this->port = $client->getClassConfig($this, 'port');
62
+ if (empty($this->host) || (empty($this->port) && (string) $this->port != "0")) {
63
+ $error = "You need to supply a valid memcache host and port";
64
+
65
+ $client->getLogger()->error($error);
66
+ throw new Google_Cache_Exception($error);
67
+ }
68
+ }
69
+ }
70
+
71
+ /**
72
+ * @inheritDoc
73
+ */
74
+ public function get($key, $expiration = false)
75
+ {
76
+ $this->connect();
77
+ $ret = false;
78
+ if ($this->mc) {
79
+ $ret = $this->mc->get($key);
80
+ } else {
81
+ $ret = memcache_get($this->connection, $key);
82
+ }
83
+ if ($ret === false) {
84
+ $this->client->getLogger()->debug(
85
+ 'Memcache cache miss',
86
+ array('key' => $key)
87
+ );
88
+ return false;
89
+ }
90
+ if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
91
+ $this->client->getLogger()->debug(
92
+ 'Memcache cache miss (expired)',
93
+ array('key' => $key, 'var' => $ret)
94
+ );
95
+ $this->delete($key);
96
+ return false;
97
+ }
98
+
99
+ $this->client->getLogger()->debug(
100
+ 'Memcache cache hit',
101
+ array('key' => $key, 'var' => $ret)
102
+ );
103
+
104
+ return $ret['data'];
105
+ }
106
+
107
+ /**
108
+ * @inheritDoc
109
+ * @param string $key
110
+ * @param string $value
111
+ * @throws Google_Cache_Exception
112
+ */
113
+ public function set($key, $value)
114
+ {
115
+ $this->connect();
116
+ // we store it with the cache_time default expiration so objects will at
117
+ // least get cleaned eventually.
118
+ $data = array('time' => time(), 'data' => $value);
119
+ $rc = false;
120
+ if ($this->mc) {
121
+ $rc = $this->mc->set($key, $data);
122
+ } else {
123
+ $rc = memcache_set($this->connection, $key, $data, false);
124
+ }
125
+ if ($rc == false) {
126
+ $this->client->getLogger()->error(
127
+ 'Memcache cache set failed',
128
+ array('key' => $key, 'var' => $data)
129
+ );
130
+
131
+ throw new Google_Cache_Exception("Couldn't store data in cache");
132
+ }
133
+
134
+ $this->client->getLogger()->debug(
135
+ 'Memcache cache set',
136
+ array('key' => $key, 'var' => $data)
137
+ );
138
+ }
139
+
140
+ /**
141
+ * @inheritDoc
142
+ * @param String $key
143
+ */
144
+ public function delete($key)
145
+ {
146
+ $this->connect();
147
+ if ($this->mc) {
148
+ $this->mc->delete($key, 0);
149
+ } else {
150
+ memcache_delete($this->connection, $key, 0);
151
+ }
152
+
153
+ $this->client->getLogger()->debug(
154
+ 'Memcache cache delete',
155
+ array('key' => $key)
156
+ );
157
+ }
158
+
159
+ /**
160
+ * Lazy initialiser for memcache connection. Uses pconnect for to take
161
+ * advantage of the persistence pool where possible.
162
+ */
163
+ private function connect()
164
+ {
165
+ if ($this->connection) {
166
+ return;
167
+ }
168
+
169
+ if (class_exists("Memcached")) {
170
+ $this->mc = new Memcached();
171
+ $this->mc->addServer($this->host, $this->port);
172
+ $this->connection = true;
173
+ } else {
174
+ $this->connection = memcache_pconnect($this->host, $this->port);
175
+ }
176
+
177
+ if (! $this->connection) {
178
+ $error = "Couldn't connect to memcache server";
179
+
180
+ $this->client->getLogger()->error($error);
181
+ throw new Google_Cache_Exception($error);
182
+ }
183
+ }
184
+ }
google/Cache/Null.php CHANGED
@@ -1,57 +1,57 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * A blank storage class, for cases where caching is not
24
- * required.
25
- */
26
- class Google_Cache_Null extends Google_Cache_Abstract
27
- {
28
- public function __construct(Google_Client $client)
29
- {
30
-
31
- }
32
-
33
- /**
34
- * @inheritDoc
35
- */
36
- public function get($key, $expiration = false)
37
- {
38
- return false;
39
- }
40
-
41
- /**
42
- * @inheritDoc
43
- */
44
- public function set($key, $value)
45
- {
46
- // Nop.
47
- }
48
-
49
- /**
50
- * @inheritDoc
51
- * @param String $key
52
- */
53
- public function delete($key)
54
- {
55
- // Nop.
56
- }
57
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * A blank storage class, for cases where caching is not
24
+ * required.
25
+ */
26
+ class Google_Cache_Null extends Google_Cache_Abstract
27
+ {
28
+ public function __construct(Google_Client $client)
29
+ {
30
+
31
+ }
32
+
33
+ /**
34
+ * @inheritDoc
35
+ */
36
+ public function get($key, $expiration = false)
37
+ {
38
+ return false;
39
+ }
40
+
41
+ /**
42
+ * @inheritDoc
43
+ */
44
+ public function set($key, $value)
45
+ {
46
+ // Nop.
47
+ }
48
+
49
+ /**
50
+ * @inheritDoc
51
+ * @param String $key
52
+ */
53
+ public function delete($key)
54
+ {
55
+ // Nop.
56
+ }
57
+ }
google/Client.php CHANGED
@@ -1,715 +1,715 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/autoload.php';
20
- }
21
-
22
- /**
23
- * The Google API Client
24
- * https://github.com/google/google-api-php-client
25
- */
26
- class Google_Client
27
- {
28
- const LIBVER = "1.1.5";
29
- const USER_AGENT_SUFFIX = "google-api-php-client/";
30
- /**
31
- * @var Google_Auth_Abstract $auth
32
- */
33
- private $auth;
34
-
35
- /**
36
- * @var Google_IO_Abstract $io
37
- */
38
- private $io;
39
-
40
- /**
41
- * @var Google_Cache_Abstract $cache
42
- */
43
- private $cache;
44
-
45
- /**
46
- * @var Google_Config $config
47
- */
48
- private $config;
49
-
50
- /**
51
- * @var Google_Logger_Abstract $logger
52
- */
53
- private $logger;
54
-
55
- /**
56
- * @var boolean $deferExecution
57
- */
58
- private $deferExecution = false;
59
-
60
- /** @var array $scopes */
61
- // Scopes requested by the client
62
- protected $requestedScopes = array();
63
-
64
- // definitions of services that are discovered.
65
- protected $services = array();
66
-
67
- // Used to track authenticated state, can't discover services after doing authenticate()
68
- private $authenticated = false;
69
-
70
- /**
71
- * Construct the Google Client.
72
- *
73
- * @param $config Google_Config or string for the ini file to load
74
- */
75
- public function __construct($config = null)
76
- {
77
- if (is_string($config) && strlen($config)) {
78
- $config = new Google_Config($config);
79
- } else if ( !($config instanceof Google_Config)) {
80
- $config = new Google_Config();
81
-
82
- if ($this->isAppEngine()) {
83
- // Automatically use Memcache if we're in AppEngine.
84
- $config->setCacheClass('Google_Cache_Memcache');
85
- }
86
-
87
- if (version_compare(phpversion(), "5.3.4", "<=") || $this->isAppEngine()) {
88
- // Automatically disable compress.zlib, as currently unsupported.
89
- $config->setClassConfig('Google_Http_Request', 'disable_gzip', true);
90
- }
91
- }
92
-
93
- if ($config->getIoClass() == Google_Config::USE_AUTO_IO_SELECTION) {
94
- if (function_exists('curl_version') && function_exists('curl_exec')
95
- && !$this->isAppEngine()) {
96
- $config->setIoClass("Google_IO_Curl");
97
- } else {
98
- $config->setIoClass("Google_IO_Stream");
99
- }
100
- }
101
-
102
- $this->config = $config;
103
- }
104
-
105
- /**
106
- * Get a string containing the version of the library.
107
- *
108
- * @return string
109
- */
110
- public function getLibraryVersion()
111
- {
112
- return self::LIBVER;
113
- }
114
-
115
- /**
116
- * Attempt to exchange a code for an valid authentication token.
117
- * If $crossClient is set to true, the request body will not include
118
- * the request_uri argument
119
- * Helper wrapped around the OAuth 2.0 implementation.
120
- *
121
- * @param $code string code from accounts.google.com
122
- * @param $crossClient boolean, whether this is a cross-client authentication
123
- * @return string token
124
- */
125
- public function authenticate($code, $crossClient = false)
126
- {
127
- $this->authenticated = true;
128
- return $this->getAuth()->authenticate($code, $crossClient);
129
- }
130
-
131
- /**
132
- * Loads a service account key and parameters from a JSON
133
- * file from the Google Developer Console. Uses that and the
134
- * given array of scopes to return an assertion credential for
135
- * use with refreshTokenWithAssertionCredential.
136
- *
137
- * @param string $jsonLocation File location of the project-key.json.
138
- * @param array $scopes The scopes to assert.
139
- * @return Google_Auth_AssertionCredentials.
140
- * @
141
- */
142
- public function loadServiceAccountJson($jsonLocation, $scopes)
143
- {
144
- $data = json_decode(file_get_contents($jsonLocation));
145
- if (isset($data->type) && $data->type == 'service_account') {
146
- // Service Account format.
147
- $cred = new Google_Auth_AssertionCredentials(
148
- $data->client_email,
149
- $scopes,
150
- $data->private_key
151
- );
152
- return $cred;
153
- } else {
154
- throw new Google_Exception("Invalid service account JSON file.");
155
- }
156
- }
157
-
158
- /**
159
- * Set the auth config from the JSON string provided.
160
- * This structure should match the file downloaded from
161
- * the "Download JSON" button on in the Google Developer
162
- * Console.
163
- * @param string $json the configuration json
164
- * @throws Google_Exception
165
- */
166
- public function setAuthConfig($json)
167
- {
168
- $data = json_decode($json);
169
- $key = isset($data->installed) ? 'installed' : 'web';
170
- if (!isset($data->$key)) {
171
- throw new Google_Exception("Invalid client secret JSON file.");
172
- }
173
- $this->setClientId($data->$key->client_id);
174
- $this->setClientSecret($data->$key->client_secret);
175
- if (isset($data->$key->redirect_uris)) {
176
- $this->setRedirectUri($data->$key->redirect_uris[0]);
177
- }
178
- }
179
-
180
- /**
181
- * Set the auth config from the JSON file in the path
182
- * provided. This should match the file downloaded from
183
- * the "Download JSON" button on in the Google Developer
184
- * Console.
185
- * @param string $file the file location of the client json
186
- */
187
- public function setAuthConfigFile($file)
188
- {
189
- $this->setAuthConfig(file_get_contents($file));
190
- }
191
-
192
- /**
193
- * @throws Google_Auth_Exception
194
- * @return array
195
- * @visible For Testing
196
- */
197
- public function prepareScopes()
198
- {
199
- if (empty($this->requestedScopes)) {
200
- throw new Google_Auth_Exception("No scopes specified");
201
- }
202
- $scopes = implode(' ', $this->requestedScopes);
203
- return $scopes;
204
- }
205
-
206
- /**
207
- * Set the OAuth 2.0 access token using the string that resulted from calling createAuthUrl()
208
- * or Google_Client#getAccessToken().
209
- * @param string $accessToken JSON encoded string containing in the following format:
210
- * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
211
- * "expires_in":3600, "id_token":"TOKEN", "created":1320790426}
212
- */
213
- public function setAccessToken($accessToken)
214
- {
215
- if ($accessToken == 'null') {
216
- $accessToken = null;
217
- }
218
- $this->getAuth()->setAccessToken($accessToken);
219
- }
220
-
221
-
222
-
223
- /**
224
- * Set the authenticator object
225
- * @param Google_Auth_Abstract $auth
226
- */
227
- public function setAuth(Google_Auth_Abstract $auth)
228
- {
229
- $this->config->setAuthClass(get_class($auth));
230
- $this->auth = $auth;
231
- }
232
-
233
- /**
234
- * Set the IO object
235
- * @param Google_IO_Abstract $io
236
- */
237
- public function setIo(Google_IO_Abstract $io)
238
- {
239
- $this->config->setIoClass(get_class($io));
240
- $this->io = $io;
241
- }
242
-
243
- /**
244
- * Set the Cache object
245
- * @param Google_Cache_Abstract $cache
246
- */
247
- public function setCache(Google_Cache_Abstract $cache)
248
- {
249
- $this->config->setCacheClass(get_class($cache));
250
- $this->cache = $cache;
251
- }
252
-
253
- /**
254
- * Set the Logger object
255
- * @param Google_Logger_Abstract $logger
256
- */
257
- public function setLogger(Google_Logger_Abstract $logger)
258
- {
259
- $this->config->setLoggerClass(get_class($logger));
260
- $this->logger = $logger;
261
- }
262
-
263
- /**
264
- * Construct the OAuth 2.0 authorization request URI.
265
- * @return string
266
- */
267
- public function createAuthUrl()
268
- {
269
- $scopes = $this->prepareScopes();
270
- return $this->getAuth()->createAuthUrl($scopes);
271
- }
272
-
273
- /**
274
- * Get the OAuth 2.0 access token.
275
- * @return string $accessToken JSON encoded string in the following format:
276
- * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
277
- * "expires_in":3600,"id_token":"TOKEN", "created":1320790426}
278
- */
279
- public function getAccessToken()
280
- {
281
- $token = $this->getAuth()->getAccessToken();
282
- // The response is json encoded, so could be the string null.
283
- // It is arguable whether this check should be here or lower
284
- // in the library.
285
- return (null == $token || 'null' == $token || '[]' == $token) ? null : $token;
286
- }
287
-
288
- /**
289
- * Get the OAuth 2.0 refresh token.
290
- * @return string $refreshToken refresh token or null if not available
291
- */
292
- public function getRefreshToken()
293
- {
294
- return $this->getAuth()->getRefreshToken();
295
- }
296
-
297
- /**
298
- * Returns if the access_token is expired.
299
- * @return bool Returns True if the access_token is expired.
300
- */
301
- public function isAccessTokenExpired()
302
- {
303
- return $this->getAuth()->isAccessTokenExpired();
304
- }
305
-
306
- /**
307
- * Set OAuth 2.0 "state" parameter to achieve per-request customization.
308
- * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
309
- * @param string $state
310
- */
311
- public function setState($state)
312
- {
313
- $this->getAuth()->setState($state);
314
- }
315
-
316
- /**
317
- * @param string $accessType Possible values for access_type include:
318
- * {@code "offline"} to request offline access from the user.
319
- * {@code "online"} to request online access from the user.
320
- */
321
- public function setAccessType($accessType)
322
- {
323
- $this->config->setAccessType($accessType);
324
- }
325
-
326
- /**
327
- * @param string $approvalPrompt Possible values for approval_prompt include:
328
- * {@code "force"} to force the approval UI to appear. (This is the default value)
329
- * {@code "auto"} to request auto-approval when possible.
330
- */
331
- public function setApprovalPrompt($approvalPrompt)
332
- {
333
- $this->config->setApprovalPrompt($approvalPrompt);
334
- }
335
-
336
- /**
337
- * Set the login hint, email address or sub id.
338
- * @param string $loginHint
339
- */
340
- public function setLoginHint($loginHint)
341
- {
342
- $this->config->setLoginHint($loginHint);
343
- }
344
-
345
- /**
346
- * Set the application name, this is included in the User-Agent HTTP header.
347
- * @param string $applicationName
348
- */
349
- public function setApplicationName($applicationName)
350
- {
351
- $this->config->setApplicationName($applicationName);
352
- }
353
-
354
- /**
355
- * Set the OAuth 2.0 Client ID.
356
- * @param string $clientId
357
- */
358
- public function setClientId($clientId)
359
- {
360
- $this->config->setClientId($clientId);
361
- }
362
-
363
- /**
364
- * Set the OAuth 2.0 Client Secret.
365
- * @param string $clientSecret
366
- */
367
- public function setClientSecret($clientSecret)
368
- {
369
- $this->config->setClientSecret($clientSecret);
370
- }
371
-
372
- /**
373
- * Set the OAuth 2.0 Redirect URI.
374
- * @param string $redirectUri
375
- */
376
- public function setRedirectUri($redirectUri)
377
- {
378
- $this->config->setRedirectUri($redirectUri);
379
- }
380
-
381
- /**
382
- * If 'plus.login' is included in the list of requested scopes, you can use
383
- * this method to define types of app activities that your app will write.
384
- * You can find a list of available types here:
385
- * @link https://developers.google.com/+/api/moment-types
386
- *
387
- * @param array $requestVisibleActions Array of app activity types
388
- */
389
- public function setRequestVisibleActions($requestVisibleActions)
390
- {
391
- if (is_array($requestVisibleActions)) {
392
- $requestVisibleActions = join(" ", $requestVisibleActions);
393
- }
394
- $this->config->setRequestVisibleActions($requestVisibleActions);
395
- }
396
-
397
- /**
398
- * Set the developer key to use, these are obtained through the API Console.
399
- * @see http://code.google.com/apis/console-help/#generatingdevkeys
400
- * @param string $developerKey
401
- */
402
- public function setDeveloperKey($developerKey)
403
- {
404
- $this->config->setDeveloperKey($developerKey);
405
- }
406
-
407
- /**
408
- * Set the hd (hosted domain) parameter streamlines the login process for
409
- * Google Apps hosted accounts. By including the domain of the user, you
410
- * restrict sign-in to accounts at that domain.
411
- * @param $hd string - the domain to use.
412
- */
413
- public function setHostedDomain($hd)
414
- {
415
- $this->config->setHostedDomain($hd);
416
- }
417
-
418
- /**
419
- * Set the prompt hint. Valid values are none, consent and select_account.
420
- * If no value is specified and the user has not previously authorized
421
- * access, then the user is shown a consent screen.
422
- * @param $prompt string
423
- */
424
- public function setPrompt($prompt)
425
- {
426
- $this->config->setPrompt($prompt);
427
- }
428
-
429
- /**
430
- * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
431
- * 2.0. It is used in OpenID 2.0 requests to signify the URL-space for which
432
- * an authentication request is valid.
433
- * @param $realm string - the URL-space to use.
434
- */
435
- public function setOpenidRealm($realm)
436
- {
437
- $this->config->setOpenidRealm($realm);
438
- }
439
-
440
- /**
441
- * If this is provided with the value true, and the authorization request is
442
- * granted, the authorization will include any previous authorizations
443
- * granted to this user/application combination for other scopes.
444
- * @param $include boolean - the URL-space to use.
445
- */
446
- public function setIncludeGrantedScopes($include)
447
- {
448
- $this->config->setIncludeGrantedScopes($include);
449
- }
450
-
451
- /**
452
- * Fetches a fresh OAuth 2.0 access token with the given refresh token.
453
- * @param string $refreshToken
454
- */
455
- public function refreshToken($refreshToken)
456
- {
457
- $this->getAuth()->refreshToken($refreshToken);
458
- }
459
-
460
- /**
461
- * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
462
- * token, if a token isn't provided.
463
- * @throws Google_Auth_Exception
464
- * @param string|null $token The token (access token or a refresh token) that should be revoked.
465
- * @return boolean Returns True if the revocation was successful, otherwise False.
466
- */
467
- public function revokeToken($token = null)
468
- {
469
- return $this->getAuth()->revokeToken($token);
470
- }
471
-
472
- /**
473
- * Verify an id_token. This method will verify the current id_token, if one
474
- * isn't provided.
475
- * @throws Google_Auth_Exception
476
- * @param string|null $token The token (id_token) that should be verified.
477
- * @return Google_Auth_LoginTicket Returns an apiLoginTicket if the verification was
478
- * successful.
479
- */
480
- public function verifyIdToken($token = null)
481
- {
482
- return $this->getAuth()->verifyIdToken($token);
483
- }
484
-
485
- /**
486
- * Verify a JWT that was signed with your own certificates.
487
- *
488
- * @param $id_token string The JWT token
489
- * @param $cert_location array of certificates
490
- * @param $audience string the expected consumer of the token
491
- * @param $issuer string the expected issuer, defaults to Google
492
- * @param [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS
493
- * @return mixed token information if valid, false if not
494
- */
495
- public function verifySignedJwt($id_token, $cert_location, $audience, $issuer, $max_expiry = null)
496
- {
497
- $auth = new Google_Auth_OAuth2($this);
498
- $certs = $auth->retrieveCertsFromLocation($cert_location);
499
- return $auth->verifySignedJwtWithCerts($id_token, $certs, $audience, $issuer, $max_expiry);
500
- }
501
-
502
- /**
503
- * @param $creds Google_Auth_AssertionCredentials
504
- */
505
- public function setAssertionCredentials(Google_Auth_AssertionCredentials $creds)
506
- {
507
- $this->getAuth()->setAssertionCredentials($creds);
508
- }
509
-
510
- /**
511
- * Set the scopes to be requested. Must be called before createAuthUrl().
512
- * Will remove any previously configured scopes.
513
- * @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.login',
514
- * 'https://www.googleapis.com/auth/moderator')
515
- */
516
- public function setScopes($scopes)
517
- {
518
- $this->requestedScopes = array();
519
- $this->addScope($scopes);
520
- }
521
-
522
- /**
523
- * This functions adds a scope to be requested as part of the OAuth2.0 flow.
524
- * Will append any scopes not previously requested to the scope parameter.
525
- * A single string will be treated as a scope to request. An array of strings
526
- * will each be appended.
527
- * @param $scope_or_scopes string|array e.g. "profile"
528
- */
529
- public function addScope($scope_or_scopes)
530
- {
531
- if (is_string($scope_or_scopes) && !in_array($scope_or_scopes, $this->requestedScopes)) {
532
- $this->requestedScopes[] = $scope_or_scopes;
533
- } else if (is_array($scope_or_scopes)) {
534
- foreach ($scope_or_scopes as $scope) {
535
- $this->addScope($scope);
536
- }
537
- }
538
- }
539
-
540
- /**
541
- * Returns the list of scopes requested by the client
542
- * @return array the list of scopes
543
- *
544
- */
545
- public function getScopes()
546
- {
547
- return $this->requestedScopes;
548
- }
549
-
550
- /**
551
- * Declare whether batch calls should be used. This may increase throughput
552
- * by making multiple requests in one connection.
553
- *
554
- * @param boolean $useBatch True if the batch support should
555
- * be enabled. Defaults to False.
556
- */
557
- public function setUseBatch($useBatch)
558
- {
559
- // This is actually an alias for setDefer.
560
- $this->setDefer($useBatch);
561
- }
562
-
563
- /**
564
- * Declare whether making API calls should make the call immediately, or
565
- * return a request which can be called with ->execute();
566
- *
567
- * @param boolean $defer True if calls should not be executed right away.
568
- */
569
- public function setDefer($defer)
570
- {
571
- $this->deferExecution = $defer;
572
- }
573
-
574
- /**
575
- * Helper method to execute deferred HTTP requests.
576
- *
577
- * @param $request Google_Http_Request|Google_Http_Batch
578
- * @throws Google_Exception
579
- * @return object of the type of the expected class or array.
580
- */
581
- public function execute($request)
582
- {
583
- if ($request instanceof Google_Http_Request) {
584
- $request->setUserAgent(
585
- $this->getApplicationName()
586
- . " " . self::USER_AGENT_SUFFIX
587
- . $this->getLibraryVersion()
588
- );
589
- if (!$this->getClassConfig("Google_Http_Request", "disable_gzip")) {
590
- $request->enableGzip();
591
- }
592
- $request->maybeMoveParametersToBody();
593
- return Google_Http_REST::execute($this, $request);
594
- } else if ($request instanceof Google_Http_Batch) {
595
- return $request->execute();
596
- } else {
597
- throw new Google_Exception("Do not know how to execute this type of object.");
598
- }
599
- }
600
-
601
- /**
602
- * Whether or not to return raw requests
603
- * @return boolean
604
- */
605
- public function shouldDefer()
606
- {
607
- return $this->deferExecution;
608
- }
609
-
610
- /**
611
- * @return Google_Auth_Abstract Authentication implementation
612
- */
613
- public function getAuth()
614
- {
615
- if (!isset($this->auth)) {
616
- $class = $this->config->getAuthClass();
617
- $this->auth = new $class($this);
618
- }
619
- return $this->auth;
620
- }
621
-
622
- /**
623
- * @return Google_IO_Abstract IO implementation
624
- */
625
- public function getIo()
626
- {
627
- if (!isset($this->io)) {
628
- $class = $this->config->getIoClass();
629
- $this->io = new $class($this);
630
- }
631
- return $this->io;
632
- }
633
-
634
- /**
635
- * @return Google_Cache_Abstract Cache implementation
636
- */
637
- public function getCache()
638
- {
639
- if (!isset($this->cache)) {
640
- $class = $this->config->getCacheClass();
641
- $this->cache = new $class($this);
642
- }
643
- return $this->cache;
644
- }
645
-
646
- /**
647
- * @return Google_Logger_Abstract Logger implementation
648
- */
649
- public function getLogger()
650
- {
651
- if (!isset($this->logger)) {
652
- $class = $this->config->getLoggerClass();
653
- $this->logger = new $class($this);
654
- }
655
- return $this->logger;
656
- }
657
-
658
- /**
659
- * Retrieve custom configuration for a specific class.
660
- * @param $class string|object - class or instance of class to retrieve
661
- * @param $key string optional - key to retrieve
662
- * @return array
663
- */
664
- public function getClassConfig($class, $key = null)
665
- {
666
- if (!is_string($class)) {
667
- $class = get_class($class);
668
- }
669
- return $this->config->getClassConfig($class, $key);
670
- }
671
-
672
- /**
673
- * Set configuration specific to a given class.
674
- * $config->setClassConfig('Google_Cache_File',
675
- * array('directory' => '/tmp/cache'));
676
- * @param $class string|object - The class name for the configuration
677
- * @param $config string key or an array of configuration values
678
- * @param $value string optional - if $config is a key, the value
679
- *
680
- */
681
- public function setClassConfig($class, $config, $value = null)
682
- {
683
- if (!is_string($class)) {
684
- $class = get_class($class);
685
- }
686
- $this->config->setClassConfig($class, $config, $value);
687
-
688
- }
689
-
690
- /**
691
- * @return string the base URL to use for calls to the APIs
692
- */
693
- public function getBasePath()
694
- {
695
- return $this->config->getBasePath();
696
- }
697
-
698
- /**
699
- * @return string the name of the application
700
- */
701
- public function getApplicationName()
702
- {
703
- return $this->config->getApplicationName();
704
- }
705
-
706
- /**
707
- * Are we running in Google AppEngine?
708
- * return bool
709
- */
710
- public function isAppEngine()
711
- {
712
- return (isset($_SERVER['SERVER_SOFTWARE']) &&
713
- strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false);
714
- }
715
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/autoload.php';
20
+ }
21
+
22
+ /**
23
+ * The Google API Client
24
+ * https://github.com/google/google-api-php-client
25
+ */
26
+ class Google_Client
27
+ {
28
+ const LIBVER = "1.1.5";
29
+ const USER_AGENT_SUFFIX = "google-api-php-client/";
30
+ /**
31
+ * @var Google_Auth_Abstract $auth
32
+ */
33
+ private $auth;
34
+
35
+ /**
36
+ * @var Google_IO_Abstract $io
37
+ */
38
+ private $io;
39
+
40
+ /**
41
+ * @var Google_Cache_Abstract $cache
42
+ */
43
+ private $cache;
44
+
45
+ /**
46
+ * @var Google_Config $config
47
+ */
48
+ private $config;
49
+
50
+ /**
51
+ * @var Google_Logger_Abstract $logger
52
+ */
53
+ private $logger;
54
+
55
+ /**
56
+ * @var boolean $deferExecution
57
+ */
58
+ private $deferExecution = false;
59
+
60
+ /** @var array $scopes */
61
+ // Scopes requested by the client
62
+ protected $requestedScopes = array();
63
+
64
+ // definitions of services that are discovered.
65
+ protected $services = array();
66
+
67
+ // Used to track authenticated state, can't discover services after doing authenticate()
68
+ private $authenticated = false;
69
+
70
+ /**
71
+ * Construct the Google Client.
72
+ *
73
+ * @param $config Google_Config or string for the ini file to load
74
+ */
75
+ public function __construct($config = null)
76
+ {
77
+ if (is_string($config) && strlen($config)) {
78
+ $config = new Google_Config($config);
79
+ } else if ( !($config instanceof Google_Config)) {
80
+ $config = new Google_Config();
81
+
82
+ if ($this->isAppEngine()) {
83
+ // Automatically use Memcache if we're in AppEngine.
84
+ $config->setCacheClass('Google_Cache_Memcache');
85
+ }
86
+
87
+ if (version_compare(phpversion(), "5.3.4", "<=") || $this->isAppEngine()) {
88
+ // Automatically disable compress.zlib, as currently unsupported.
89
+ $config->setClassConfig('Google_Http_Request', 'disable_gzip', true);
90
+ }
91
+ }
92
+
93
+ if ($config->getIoClass() == Google_Config::USE_AUTO_IO_SELECTION) {
94
+ if (function_exists('curl_version') && function_exists('curl_exec')
95
+ && !$this->isAppEngine()) {
96
+ $config->setIoClass("Google_IO_Curl");
97
+ } else {
98
+ $config->setIoClass("Google_IO_Stream");
99
+ }
100
+ }
101
+
102
+ $this->config = $config;
103
+ }
104
+
105
+ /**
106
+ * Get a string containing the version of the library.
107
+ *
108
+ * @return string
109
+ */
110
+ public function getLibraryVersion()
111
+ {
112
+ return self::LIBVER;
113
+ }
114
+
115
+ /**
116
+ * Attempt to exchange a code for an valid authentication token.
117
+ * If $crossClient is set to true, the request body will not include
118
+ * the request_uri argument
119
+ * Helper wrapped around the OAuth 2.0 implementation.
120
+ *
121
+ * @param $code string code from accounts.google.com
122
+ * @param $crossClient boolean, whether this is a cross-client authentication
123
+ * @return string token
124
+ */
125
+ public function authenticate($code, $crossClient = false)
126
+ {
127
+ $this->authenticated = true;
128
+ return $this->getAuth()->authenticate($code, $crossClient);
129
+ }
130
+
131
+ /**
132
+ * Loads a service account key and parameters from a JSON
133
+ * file from the Google Developer Console. Uses that and the
134
+ * given array of scopes to return an assertion credential for
135
+ * use with refreshTokenWithAssertionCredential.
136
+ *
137
+ * @param string $jsonLocation File location of the project-key.json.
138
+ * @param array $scopes The scopes to assert.
139
+ * @return Google_Auth_AssertionCredentials.
140
+ * @
141
+ */
142
+ public function loadServiceAccountJson($jsonLocation, $scopes)
143
+ {
144
+ $data = json_decode(file_get_contents($jsonLocation));
145
+ if (isset($data->type) && $data->type == 'service_account') {
146
+ // Service Account format.
147
+ $cred = new Google_Auth_AssertionCredentials(
148
+ $data->client_email,
149
+ $scopes,
150
+ $data->private_key
151
+ );
152
+ return $cred;
153
+ } else {
154
+ throw new Google_Exception("Invalid service account JSON file.");
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Set the auth config from the JSON string provided.
160
+ * This structure should match the file downloaded from
161
+ * the "Download JSON" button on in the Google Developer
162
+ * Console.
163
+ * @param string $json the configuration json
164
+ * @throws Google_Exception
165
+ */
166
+ public function setAuthConfig($json)
167
+ {
168
+ $data = json_decode($json);
169
+ $key = isset($data->installed) ? 'installed' : 'web';
170
+ if (!isset($data->$key)) {
171
+ throw new Google_Exception("Invalid client secret JSON file.");
172
+ }
173
+ $this->setClientId($data->$key->client_id);
174
+ $this->setClientSecret($data->$key->client_secret);
175
+ if (isset($data->$key->redirect_uris)) {
176
+ $this->setRedirectUri($data->$key->redirect_uris[0]);
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Set the auth config from the JSON file in the path
182
+ * provided. This should match the file downloaded from
183
+ * the "Download JSON" button on in the Google Developer
184
+ * Console.
185
+ * @param string $file the file location of the client json
186
+ */
187
+ public function setAuthConfigFile($file)
188
+ {
189
+ $this->setAuthConfig(file_get_contents($file));
190
+ }
191
+
192
+ /**
193
+ * @throws Google_Auth_Exception
194
+ * @return array
195
+ * @visible For Testing
196
+ */
197
+ public function prepareScopes()
198
+ {
199
+ if (empty($this->requestedScopes)) {
200
+ throw new Google_Auth_Exception("No scopes specified");
201
+ }
202
+ $scopes = implode(' ', $this->requestedScopes);
203
+ return $scopes;
204
+ }
205
+
206
+ /**
207
+ * Set the OAuth 2.0 access token using the string that resulted from calling createAuthUrl()
208
+ * or Google_Client#getAccessToken().
209
+ * @param string $accessToken JSON encoded string containing in the following format:
210
+ * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
211
+ * "expires_in":3600, "id_token":"TOKEN", "created":1320790426}
212
+ */
213
+ public function setAccessToken($accessToken)
214
+ {
215
+ if ($accessToken == 'null') {
216
+ $accessToken = null;
217
+ }
218
+ $this->getAuth()->setAccessToken($accessToken);
219
+ }
220
+
221
+
222
+
223
+ /**
224
+ * Set the authenticator object
225
+ * @param Google_Auth_Abstract $auth
226
+ */
227
+ public function setAuth(Google_Auth_Abstract $auth)
228
+ {
229
+ $this->config->setAuthClass(get_class($auth));
230
+ $this->auth = $auth;
231
+ }
232
+
233
+ /**
234
+ * Set the IO object
235
+ * @param Google_IO_Abstract $io
236
+ */
237
+ public function setIo(Google_IO_Abstract $io)
238
+ {
239
+ $this->config->setIoClass(get_class($io));
240
+ $this->io = $io;
241
+ }
242
+
243
+ /**
244
+ * Set the Cache object
245
+ * @param Google_Cache_Abstract $cache
246
+ */
247
+ public function setCache(Google_Cache_Abstract $cache)
248
+ {
249
+ $this->config->setCacheClass(get_class($cache));
250
+ $this->cache = $cache;
251
+ }
252
+
253
+ /**
254
+ * Set the Logger object
255
+ * @param Google_Logger_Abstract $logger
256
+ */
257
+ public function setLogger(Google_Logger_Abstract $logger)
258
+ {
259
+ $this->config->setLoggerClass(get_class($logger));
260
+ $this->logger = $logger;
261
+ }
262
+
263
+ /**
264
+ * Construct the OAuth 2.0 authorization request URI.
265
+ * @return string
266
+ */
267
+ public function createAuthUrl()
268
+ {
269
+ $scopes = $this->prepareScopes();
270
+ return $this->getAuth()->createAuthUrl($scopes);
271
+ }
272
+
273
+ /**
274
+ * Get the OAuth 2.0 access token.
275
+ * @return string $accessToken JSON encoded string in the following format:
276
+ * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
277
+ * "expires_in":3600,"id_token":"TOKEN", "created":1320790426}
278
+ */
279
+ public function getAccessToken()
280
+ {
281
+ $token = $this->getAuth()->getAccessToken();
282
+ // The response is json encoded, so could be the string null.
283
+ // It is arguable whether this check should be here or lower
284
+ // in the library.
285
+ return (null == $token || 'null' == $token || '[]' == $token) ? null : $token;
286
+ }
287
+
288
+ /**
289
+ * Get the OAuth 2.0 refresh token.
290
+ * @return string $refreshToken refresh token or null if not available
291
+ */
292
+ public function getRefreshToken()
293
+ {
294
+ return $this->getAuth()->getRefreshToken();
295
+ }
296
+
297
+ /**
298
+ * Returns if the access_token is expired.
299
+ * @return bool Returns True if the access_token is expired.
300
+ */
301
+ public function isAccessTokenExpired()
302
+ {
303
+ return $this->getAuth()->isAccessTokenExpired();
304
+ }
305
+
306
+ /**
307
+ * Set OAuth 2.0 "state" parameter to achieve per-request customization.
308
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
309
+ * @param string $state
310
+ */
311
+ public function setState($state)
312
+ {
313
+ $this->getAuth()->setState($state);
314
+ }
315
+
316
+ /**
317
+ * @param string $accessType Possible values for access_type include:
318
+ * {@code "offline"} to request offline access from the user.
319
+ * {@code "online"} to request online access from the user.
320
+ */
321
+ public function setAccessType($accessType)
322
+ {
323
+ $this->config->setAccessType($accessType);
324
+ }
325
+
326
+ /**
327
+ * @param string $approvalPrompt Possible values for approval_prompt include:
328
+ * {@code "force"} to force the approval UI to appear. (This is the default value)
329
+ * {@code "auto"} to request auto-approval when possible.
330
+ */
331
+ public function setApprovalPrompt($approvalPrompt)
332
+ {
333
+ $this->config->setApprovalPrompt($approvalPrompt);
334
+ }
335
+
336
+ /**
337
+ * Set the login hint, email address or sub id.
338
+ * @param string $loginHint
339
+ */
340
+ public function setLoginHint($loginHint)
341
+ {
342
+ $this->config->setLoginHint($loginHint);
343
+ }
344
+
345
+ /**
346
+ * Set the application name, this is included in the User-Agent HTTP header.
347
+ * @param string $applicationName
348
+ */
349
+ public function setApplicationName($applicationName)
350
+ {
351
+ $this->config->setApplicationName($applicationName);
352
+ }
353
+
354
+ /**
355
+ * Set the OAuth 2.0 Client ID.
356
+ * @param string $clientId
357
+ */
358
+ public function setClientId($clientId)
359
+ {
360
+ $this->config->setClientId($clientId);
361
+ }
362
+
363
+ /**
364
+ * Set the OAuth 2.0 Client Secret.
365
+ * @param string $clientSecret
366
+ */
367
+ public function setClientSecret($clientSecret)
368
+ {
369
+ $this->config->setClientSecret($clientSecret);
370
+ }
371
+
372
+ /**
373
+ * Set the OAuth 2.0 Redirect URI.
374
+ * @param string $redirectUri
375
+ */
376
+ public function setRedirectUri($redirectUri)
377
+ {
378
+ $this->config->setRedirectUri($redirectUri);
379
+ }
380
+
381
+ /**
382
+ * If 'plus.login' is included in the list of requested scopes, you can use
383
+ * this method to define types of app activities that your app will write.
384
+ * You can find a list of available types here:
385
+ * @link https://developers.google.com/+/api/moment-types
386
+ *
387
+ * @param array $requestVisibleActions Array of app activity types
388
+ */
389
+ public function setRequestVisibleActions($requestVisibleActions)
390
+ {
391
+ if (is_array($requestVisibleActions)) {
392
+ $requestVisibleActions = join(" ", $requestVisibleActions);
393
+ }
394
+ $this->config->setRequestVisibleActions($requestVisibleActions);
395
+ }
396
+
397
+ /**
398
+ * Set the developer key to use, these are obtained through the API Console.
399
+ * @see http://code.google.com/apis/console-help/#generatingdevkeys
400
+ * @param string $developerKey
401
+ */
402
+ public function setDeveloperKey($developerKey)
403
+ {
404
+ $this->config->setDeveloperKey($developerKey);
405
+ }
406
+
407
+ /**
408
+ * Set the hd (hosted domain) parameter streamlines the login process for
409
+ * Google Apps hosted accounts. By including the domain of the user, you
410
+ * restrict sign-in to accounts at that domain.
411
+ * @param $hd string - the domain to use.
412
+ */
413
+ public function setHostedDomain($hd)
414
+ {
415
+ $this->config->setHostedDomain($hd);
416
+ }
417
+
418
+ /**
419
+ * Set the prompt hint. Valid values are none, consent and select_account.
420
+ * If no value is specified and the user has not previously authorized
421
+ * access, then the user is shown a consent screen.
422
+ * @param $prompt string
423
+ */
424
+ public function setPrompt($prompt)
425
+ {
426
+ $this->config->setPrompt($prompt);
427
+ }
428
+
429
+ /**
430
+ * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
431
+ * 2.0. It is used in OpenID 2.0 requests to signify the URL-space for which
432
+ * an authentication request is valid.
433
+ * @param $realm string - the URL-space to use.
434
+ */
435
+ public function setOpenidRealm($realm)
436
+ {
437
+ $this->config->setOpenidRealm($realm);
438
+ }
439
+
440
+ /**
441
+ * If this is provided with the value true, and the authorization request is
442
+ * granted, the authorization will include any previous authorizations
443
+ * granted to this user/application combination for other scopes.
444
+ * @param $include boolean - the URL-space to use.
445
+ */
446
+ public function setIncludeGrantedScopes($include)
447
+ {
448
+ $this->config->setIncludeGrantedScopes($include);
449
+ }
450
+
451
+ /**
452
+ * Fetches a fresh OAuth 2.0 access token with the given refresh token.
453
+ * @param string $refreshToken
454
+ */
455
+ public function refreshToken($refreshToken)
456
+ {
457
+ $this->getAuth()->refreshToken($refreshToken);
458
+ }
459
+
460
+ /**
461
+ * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
462
+ * token, if a token isn't provided.
463
+ * @throws Google_Auth_Exception
464
+ * @param string|null $token The token (access token or a refresh token) that should be revoked.
465
+ * @return boolean Returns True if the revocation was successful, otherwise False.
466
+ */
467
+ public function revokeToken($token = null)
468
+ {
469
+ return $this->getAuth()->revokeToken($token);
470
+ }
471
+
472
+ /**
473
+ * Verify an id_token. This method will verify the current id_token, if one
474
+ * isn't provided.
475
+ * @throws Google_Auth_Exception
476
+ * @param string|null $token The token (id_token) that should be verified.
477
+ * @return Google_Auth_LoginTicket Returns an apiLoginTicket if the verification was
478
+ * successful.
479
+ */
480
+ public function verifyIdToken($token = null)
481
+ {
482
+ return $this->getAuth()->verifyIdToken($token);
483
+ }
484
+
485
+ /**
486
+ * Verify a JWT that was signed with your own certificates.
487
+ *
488
+ * @param $id_token string The JWT token
489
+ * @param $cert_location array of certificates
490
+ * @param $audience string the expected consumer of the token
491
+ * @param $issuer string the expected issuer, defaults to Google
492
+ * @param [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS
493
+ * @return mixed token information if valid, false if not
494
+ */
495
+ public function verifySignedJwt($id_token, $cert_location, $audience, $issuer, $max_expiry = null)
496
+ {
497
+ $auth = new Google_Auth_OAuth2($this);
498
+ $certs = $auth->retrieveCertsFromLocation($cert_location);
499
+ return $auth->verifySignedJwtWithCerts($id_token, $certs, $audience, $issuer, $max_expiry);
500
+ }
501
+
502
+ /**
503
+ * @param $creds Google_Auth_AssertionCredentials
504
+ */
505
+ public function setAssertionCredentials(Google_Auth_AssertionCredentials $creds)
506
+ {
507
+ $this->getAuth()->setAssertionCredentials($creds);
508
+ }
509
+
510
+ /**
511
+ * Set the scopes to be requested. Must be called before createAuthUrl().
512
+ * Will remove any previously configured scopes.
513
+ * @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.login',
514
+ * 'https://www.googleapis.com/auth/moderator')
515
+ */
516
+ public function setScopes($scopes)
517
+ {
518
+ $this->requestedScopes = array();
519
+ $this->addScope($scopes);
520
+ }
521
+
522
+ /**
523
+ * This functions adds a scope to be requested as part of the OAuth2.0 flow.
524
+ * Will append any scopes not previously requested to the scope parameter.
525
+ * A single string will be treated as a scope to request. An array of strings
526
+ * will each be appended.
527
+ * @param $scope_or_scopes string|array e.g. "profile"
528
+ */
529
+ public function addScope($scope_or_scopes)
530
+ {
531
+ if (is_string($scope_or_scopes) && !in_array($scope_or_scopes, $this->requestedScopes)) {
532
+ $this->requestedScopes[] = $scope_or_scopes;
533
+ } else if (is_array($scope_or_scopes)) {
534
+ foreach ($scope_or_scopes as $scope) {
535
+ $this->addScope($scope);
536
+ }
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Returns the list of scopes requested by the client
542
+ * @return array the list of scopes
543
+ *
544
+ */
545
+ public function getScopes()
546
+ {
547
+ return $this->requestedScopes;
548
+ }
549
+
550
+ /**
551
+ * Declare whether batch calls should be used. This may increase throughput
552
+ * by making multiple requests in one connection.
553
+ *
554
+ * @param boolean $useBatch True if the batch support should
555
+ * be enabled. Defaults to False.
556
+ */
557
+ public function setUseBatch($useBatch)
558
+ {
559
+ // This is actually an alias for setDefer.
560
+ $this->setDefer($useBatch);
561
+ }
562
+
563
+ /**
564
+ * Declare whether making API calls should make the call immediately, or
565
+ * return a request which can be called with ->execute();
566
+ *
567
+ * @param boolean $defer True if calls should not be executed right away.
568
+ */
569
+ public function setDefer($defer)
570
+ {
571
+ $this->deferExecution = $defer;
572
+ }
573
+
574
+ /**
575
+ * Helper method to execute deferred HTTP requests.
576
+ *
577
+ * @param $request Google_Http_Request|Google_Http_Batch
578
+ * @throws Google_Exception
579
+ * @return object of the type of the expected class or array.
580
+ */
581
+ public function execute($request)
582
+ {
583
+ if ($request instanceof Google_Http_Request) {
584
+ $request->setUserAgent(
585
+ $this->getApplicationName()
586
+ . " " . self::USER_AGENT_SUFFIX
587
+ . $this->getLibraryVersion()
588
+ );
589
+ if (!$this->getClassConfig("Google_Http_Request", "disable_gzip")) {
590
+ $request->enableGzip();
591
+ }
592
+ $request->maybeMoveParametersToBody();
593
+ return Google_Http_REST::execute($this, $request);
594
+ } else if ($request instanceof Google_Http_Batch) {
595
+ return $request->execute();
596
+ } else {
597
+ throw new Google_Exception("Do not know how to execute this type of object.");
598
+ }
599
+ }
600
+
601
+ /**
602
+ * Whether or not to return raw requests
603
+ * @return boolean
604
+ */
605
+ public function shouldDefer()
606
+ {
607
+ return $this->deferExecution;
608
+ }
609
+
610
+ /**
611
+ * @return Google_Auth_Abstract Authentication implementation
612
+ */
613
+ public function getAuth()
614
+ {
615
+ if (!isset($this->auth)) {
616
+ $class = $this->config->getAuthClass();
617
+ $this->auth = new $class($this);
618
+ }
619
+ return $this->auth;
620
+ }
621
+
622
+ /**
623
+ * @return Google_IO_Abstract IO implementation
624
+ */
625
+ public function getIo()
626
+ {
627
+ if (!isset($this->io)) {
628
+ $class = $this->config->getIoClass();
629
+ $this->io = new $class($this);
630
+ }
631
+ return $this->io;
632
+ }
633
+
634
+ /**
635
+ * @return Google_Cache_Abstract Cache implementation
636
+ */
637
+ public function getCache()
638
+ {
639
+ if (!isset($this->cache)) {
640
+ $class = $this->config->getCacheClass();
641
+ $this->cache = new $class($this);
642
+ }
643
+ return $this->cache;
644
+ }
645
+
646
+ /**
647
+ * @return Google_Logger_Abstract Logger implementation
648
+ */
649
+ public function getLogger()
650
+ {
651
+ if (!isset($this->logger)) {
652
+ $class = $this->config->getLoggerClass();
653
+ $this->logger = new $class($this);
654
+ }
655
+ return $this->logger;
656
+ }
657
+
658
+ /**
659
+ * Retrieve custom configuration for a specific class.
660
+ * @param $class string|object - class or instance of class to retrieve
661
+ * @param $key string optional - key to retrieve
662
+ * @return array
663
+ */
664
+ public function getClassConfig($class, $key = null)
665
+ {
666
+ if (!is_string($class)) {
667
+ $class = get_class($class);
668
+ }
669
+ return $this->config->getClassConfig($class, $key);
670
+ }
671
+
672
+ /**
673
+ * Set configuration specific to a given class.
674
+ * $config->setClassConfig('Google_Cache_File',
675
+ * array('directory' => '/tmp/cache'));
676
+ * @param $class string|object - The class name for the configuration
677
+ * @param $config string key or an array of configuration values
678
+ * @param $value string optional - if $config is a key, the value
679
+ *
680
+ */
681
+ public function setClassConfig($class, $config, $value = null)
682
+ {
683
+ if (!is_string($class)) {
684
+ $class = get_class($class);
685
+ }
686
+ $this->config->setClassConfig($class, $config, $value);
687
+
688
+ }
689
+
690
+ /**
691
+ * @return string the base URL to use for calls to the APIs
692
+ */
693
+ public function getBasePath()
694
+ {
695
+ return $this->config->getBasePath();
696
+ }
697
+
698
+ /**
699
+ * @return string the name of the application
700
+ */
701
+ public function getApplicationName()
702
+ {
703
+ return $this->config->getApplicationName();
704
+ }
705
+
706
+ /**
707
+ * Are we running in Google AppEngine?
708
+ * return bool
709
+ */
710
+ public function isAppEngine()
711
+ {
712
+ return (isset($_SERVER['SERVER_SOFTWARE']) &&
713
+ strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false);
714
+ }
715
+ }
google/Collection.php CHANGED
@@ -1,101 +1,101 @@
1
- <?php
2
-
3
- if (!class_exists('Google_Client')) {
4
- require_once dirname(__FILE__) . '/autoload.php';
5
- }
6
-
7
- /**
8
- * Extension to the regular Google_Model that automatically
9
- * exposes the items array for iteration, so you can just
10
- * iterate over the object rather than a reference inside.
11
- */
12
- class Google_Collection extends Google_Model implements Iterator, Countable
13
- {
14
- protected $collection_key = 'items';
15
-
16
- public function rewind()
17
- {
18
- if (isset($this->modelData[$this->collection_key])
19
- && is_array($this->modelData[$this->collection_key])) {
20
- reset($this->modelData[$this->collection_key]);
21
- }
22
- }
23
-
24
- public function current()
25
- {
26
- $this->coerceType($this->key());
27
- if (is_array($this->modelData[$this->collection_key])) {
28
- return current($this->modelData[$this->collection_key]);
29
- }
30
- }
31
-
32
- public function key()
33
- {
34
- if (isset($this->modelData[$this->collection_key])
35
- && is_array($this->modelData[$this->collection_key])) {
36
- return key($this->modelData[$this->collection_key]);
37
- }
38
- }
39
-
40
- public function next()
41
- {
42
- return next($this->modelData[$this->collection_key]);
43
- }
44
-
45
- public function valid()
46
- {
47
- $key = $this->key();
48
- return $key !== null && $key !== false;
49
- }
50
-
51
- public function count()
52
- {
53
- if (!isset($this->modelData[$this->collection_key])) {
54
- return 0;
55
- }
56
- return count($this->modelData[$this->collection_key]);
57
- }
58
-
59
- public function offsetExists($offset)
60
- {
61
- if (!is_numeric($offset)) {
62
- return parent::offsetExists($offset);
63
- }
64
- return isset($this->modelData[$this->collection_key][$offset]);
65
- }
66
-
67
- public function offsetGet($offset)
68
- {
69
- if (!is_numeric($offset)) {
70
- return parent::offsetGet($offset);
71
- }
72
- $this->coerceType($offset);
73
- return $this->modelData[$this->collection_key][$offset];
74
- }
75
-
76
- public function offsetSet($offset, $value)
77
- {
78
- if (!is_numeric($offset)) {
79
- return parent::offsetSet($offset, $value);
80
- }
81
- $this->modelData[$this->collection_key][$offset] = $value;
82
- }
83
-
84
- public function offsetUnset($offset)
85
- {
86
- if (!is_numeric($offset)) {
87
- return parent::offsetUnset($offset);
88
- }
89
- unset($this->modelData[$this->collection_key][$offset]);
90
- }
91
-
92
- private function coerceType($offset)
93
- {
94
- $typeKey = $this->keyType($this->collection_key);
95
- if (isset($this->$typeKey) && !is_object($this->modelData[$this->collection_key][$offset])) {
96
- $type = $this->$typeKey;
97
- $this->modelData[$this->collection_key][$offset] =
98
- new $type($this->modelData[$this->collection_key][$offset]);
99
- }
100
- }
101
- }
1
+ <?php
2
+
3
+ if (!class_exists('Google_Client')) {
4
+ require_once dirname(__FILE__) . '/autoload.php';
5
+ }
6
+
7
+ /**
8
+ * Extension to the regular Google_Model that automatically
9
+ * exposes the items array for iteration, so you can just
10
+ * iterate over the object rather than a reference inside.
11
+ */
12
+ class Google_Collection extends Google_Model implements Iterator, Countable
13
+ {
14
+ protected $collection_key = 'items';
15
+
16
+ public function rewind()
17
+ {
18
+ if (isset($this->modelData[$this->collection_key])
19
+ && is_array($this->modelData[$this->collection_key])) {
20
+ reset($this->modelData[$this->collection_key]);
21
+ }
22
+ }
23
+
24
+ public function current()
25
+ {
26
+ $this->coerceType($this->key());
27
+ if (is_array($this->modelData[$this->collection_key])) {
28
+ return current($this->modelData[$this->collection_key]);
29
+ }
30
+ }
31
+
32
+ public function key()
33
+ {
34
+ if (isset($this->modelData[$this->collection_key])
35
+ && is_array($this->modelData[$this->collection_key])) {
36
+ return key($this->modelData[$this->collection_key]);
37
+ }
38
+ }
39
+
40
+ public function next()
41
+ {
42
+ return next($this->modelData[$this->collection_key]);
43
+ }
44
+
45
+ public function valid()
46
+ {
47
+ $key = $this->key();
48
+ return $key !== null && $key !== false;
49
+ }
50
+
51
+ public function count()
52
+ {
53
+ if (!isset($this->modelData[$this->collection_key])) {
54
+ return 0;
55
+ }
56
+ return count($this->modelData[$this->collection_key]);
57
+ }
58
+
59
+ public function offsetExists($offset)
60
+ {
61
+ if (!is_numeric($offset)) {
62
+ return parent::offsetExists($offset);
63
+ }
64
+ return isset($this->modelData[$this->collection_key][$offset]);
65
+ }
66
+
67
+ public function offsetGet($offset)
68
+ {
69
+ if (!is_numeric($offset)) {
70
+ return parent::offsetGet($offset);
71
+ }
72
+ $this->coerceType($offset);
73
+ return $this->modelData[$this->collection_key][$offset];
74
+ }
75
+
76
+ public function offsetSet($offset, $value)
77
+ {
78
+ if (!is_numeric($offset)) {
79
+ return parent::offsetSet($offset, $value);
80
+ }
81
+ $this->modelData[$this->collection_key][$offset] = $value;
82
+ }
83
+
84
+ public function offsetUnset($offset)
85
+ {
86
+ if (!is_numeric($offset)) {
87
+ return parent::offsetUnset($offset);
88
+ }
89
+ unset($this->modelData[$this->collection_key][$offset]);
90
+ }
91
+
92
+ private function coerceType($offset)
93
+ {
94
+ $typeKey = $this->keyType($this->collection_key);
95
+ if (isset($this->$typeKey) && !is_object($this->modelData[$this->collection_key][$offset])) {
96
+ $type = $this->$typeKey;
97
+ $this->modelData[$this->collection_key][$offset] =
98
+ new $type($this->modelData[$this->collection_key][$offset]);
99
+ }
100
+ }
101
+ }
google/Config.php CHANGED
@@ -1,452 +1,452 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * A class to contain the library configuration for the Google API client.
20
- */
21
- class Google_Config
22
- {
23
- const GZIP_DISABLED = true;
24
- const GZIP_ENABLED = false;
25
- const GZIP_UPLOADS_ENABLED = true;
26
- const GZIP_UPLOADS_DISABLED = false;
27
- const USE_AUTO_IO_SELECTION = "auto";
28
- const TASK_RETRY_NEVER = 0;
29
- const TASK_RETRY_ONCE = 1;
30
- const TASK_RETRY_ALWAYS = -1;
31
- protected $configuration;
32
-
33
- /**
34
- * Create a new Google_Config. Can accept an ini file location with the
35
- * local configuration. For example:
36
- * application_name="My App"
37
- *
38
- * @param [$ini_file_location] - optional - The location of the ini file to load
39
- */
40
- public function __construct($ini_file_location = null)
41
- {
42
- $this->configuration = array(
43
- // The application_name is included in the User-Agent HTTP header.
44
- 'application_name' => '',
45
-
46
- // Which Authentication, Storage and HTTP IO classes to use.
47
- 'auth_class' => 'Google_Auth_OAuth2',
48
- 'io_class' => self::USE_AUTO_IO_SELECTION,
49
- 'cache_class' => 'Google_Cache_File',
50
- 'logger_class' => 'Google_Logger_Null',
51
-
52
- // Don't change these unless you're working against a special development
53
- // or testing environment.
54
- 'base_path' => 'https://www.googleapis.com',
55
-
56
- // Definition of class specific values, like file paths and so on.
57
- 'classes' => array(
58
- 'Google_IO_Abstract' => array(
59
- 'request_timeout_seconds' => 100,
60
- ),
61
- 'Google_Logger_Abstract' => array(
62
- 'level' => 'debug',
63
- 'log_format' => "[%datetime%] %level%: %message% %context%\n",
64
- 'date_format' => 'd/M/Y:H:i:s O',
65
- 'allow_newlines' => true
66
- ),
67
- 'Google_Logger_File' => array(
68
- 'file' => 'php://stdout',
69
- 'mode' => 0640,
70
- 'lock' => false,
71
- ),
72
- 'Google_Http_Request' => array(
73
- // Disable the use of gzip on calls if set to true. Defaults to false.
74
- 'disable_gzip' => self::GZIP_ENABLED,
75
-
76
- // We default gzip to disabled on uploads even if gzip is otherwise
77
- // enabled, due to some issues seen with small packet sizes for uploads.
78
- // Please test with this option before enabling gzip for uploads in
79
- // a production environment.
80
- 'enable_gzip_for_uploads' => self::GZIP_UPLOADS_DISABLED,
81
- ),
82
- // If you want to pass in OAuth 2.0 settings, they will need to be
83
- // structured like this.
84
- 'Google_Auth_OAuth2' => array(
85
- // Keys for OAuth 2.0 access, see the API console at
86
- // https://developers.google.com/console
87
- 'client_id' => '',
88
- 'client_secret' => '',
89
- 'redirect_uri' => '',
90
-
91
- // Simple API access key, also from the API console. Ensure you get
92
- // a Server key, and not a Browser key.
93
- 'developer_key' => '',
94
-
95
- // Other parameters.
96
- 'hd' => '',
97
- 'prompt' => '',
98
- 'openid.realm' => '',
99
- 'include_granted_scopes' => '',
100
- 'login_hint' => '',
101
- 'request_visible_actions' => '',
102
- 'access_type' => 'online',
103
- 'approval_prompt' => 'auto',
104
- 'federated_signon_certs_url' =>
105
- 'https://www.googleapis.com/oauth2/v1/certs',
106
- ),
107
- 'Google_Task_Runner' => array(
108
- // Delays are specified in seconds
109
- 'initial_delay' => 1,
110
- 'max_delay' => 60,
111
- // Base number for exponential backoff
112
- 'factor' => 2,
113
- // A random number between -jitter and jitter will be added to the
114
- // factor on each iteration to allow for better distribution of
115
- // retries.
116
- 'jitter' => .5,
117
- // Maximum number of retries allowed
118
- 'retries' => 0
119
- ),
120
- 'Google_Service_Exception' => array(
121
- 'retry_map' => array(
122
- '500' => self::TASK_RETRY_ALWAYS,
123
- '503' => self::TASK_RETRY_ALWAYS,
124
- 'rateLimitExceeded' => self::TASK_RETRY_ALWAYS,
125
- 'userRateLimitExceeded' => self::TASK_RETRY_ALWAYS
126
- )
127
- ),
128
- 'Google_IO_Exception' => array(
129
- 'retry_map' => !extension_loaded('curl') ? array() : array(
130
- CURLE_COULDNT_RESOLVE_HOST => self::TASK_RETRY_ALWAYS,
131
- CURLE_COULDNT_CONNECT => self::TASK_RETRY_ALWAYS,
132
- CURLE_OPERATION_TIMEOUTED => self::TASK_RETRY_ALWAYS,
133
- CURLE_SSL_CONNECT_ERROR => self::TASK_RETRY_ALWAYS,
134
- CURLE_GOT_NOTHING => self::TASK_RETRY_ALWAYS
135
- )
136
- ),
137
- // Set a default directory for the file cache.
138
- 'Google_Cache_File' => array(
139
- 'directory' => sys_get_temp_dir() . '/Google_Client'
140
- )
141
- ),
142
- );
143
- if ($ini_file_location) {
144
- $ini = parse_ini_file($ini_file_location, true);
145
- if (is_array($ini) && count($ini)) {
146
- $merged_configuration = $ini + $this->configuration;
147
- if (isset($ini['classes']) && isset($this->configuration['classes'])) {
148
- $merged_configuration['classes'] = $ini['classes'] + $this->configuration['classes'];
149
- }
150
- $this->configuration = $merged_configuration;
151
- }
152
- }
153
- }
154
-
155
- /**
156
- * Set configuration specific to a given class.
157
- * $config->setClassConfig('Google_Cache_File',
158
- * array('directory' => '/tmp/cache'));
159
- * @param $class string The class name for the configuration
160
- * @param $config string key or an array of configuration values
161
- * @param $value string optional - if $config is a key, the value
162
- */
163
- public function setClassConfig($class, $config, $value = null)
164
- {
165
- if (!is_array($config)) {
166
- if (!isset($this->configuration['classes'][$class])) {
167
- $this->configuration['classes'][$class] = array();
168
- }
169
- $this->configuration['classes'][$class][$config] = $value;
170
- } else {
171
- $this->configuration['classes'][$class] = $config;
172
- }
173
- }
174
-
175
- public function getClassConfig($class, $key = null)
176
- {
177
- if (!isset($this->configuration['classes'][$class])) {
178
- return null;
179
- }
180
- if ($key === null) {
181
- return $this->configuration['classes'][$class];
182
- } else {
183
- return $this->configuration['classes'][$class][$key];
184
- }
185
- }
186
-
187
- /**
188
- * Return the configured cache class.
189
- * @return string
190
- */
191
- public function getCacheClass()
192
- {
193
- return $this->configuration['cache_class'];
194
- }
195
-
196
- /**
197
- * Return the configured logger class.
198
- * @return string
199
- */
200
- public function getLoggerClass()
201
- {
202
- return $this->configuration['logger_class'];
203
- }
204
-
205
- /**
206
- * Return the configured Auth class.
207
- * @return string
208
- */
209
- public function getAuthClass()
210
- {
211
- return $this->configuration['auth_class'];
212
- }
213
-
214
- /**
215
- * Set the auth class.
216
- *
217
- * @param $class string the class name to set
218
- */
219
- public function setAuthClass($class)
220
- {
221
- $prev = $this->configuration['auth_class'];
222
- if (!isset($this->configuration['classes'][$class]) &&
223
- isset($this->configuration['classes'][$prev])) {
224
- $this->configuration['classes'][$class] =
225
- $this->configuration['classes'][$prev];
226
- }
227
- $this->configuration['auth_class'] = $class;
228
- }
229
-
230
- /**
231
- * Set the IO class.
232
- *
233
- * @param $class string the class name to set
234
- */
235
- public function setIoClass($class)
236
- {
237
- $prev = $this->configuration['io_class'];
238
- if (!isset($this->configuration['classes'][$class]) &&
239
- isset($this->configuration['classes'][$prev])) {
240
- $this->configuration['classes'][$class] =
241
- $this->configuration['classes'][$prev];
242
- }
243
- $this->configuration['io_class'] = $class;
244
- }
245
-
246
- /**
247
- * Set the cache class.
248
- *
249
- * @param $class string the class name to set
250
- */
251
- public function setCacheClass($class)
252
- {
253
- $prev = $this->configuration['cache_class'];
254
- if (!isset($this->configuration['classes'][$class]) &&
255
- isset($this->configuration['classes'][$prev])) {
256
- $this->configuration['classes'][$class] =
257
- $this->configuration['classes'][$prev];
258
- }
259
- $this->configuration['cache_class'] = $class;
260
- }
261
-
262
- /**
263
- * Set the logger class.
264
- *
265
- * @param $class string the class name to set
266
- */
267
- public function setLoggerClass($class)
268
- {
269
- $prev = $this->configuration['logger_class'];
270
- if (!isset($this->configuration['classes'][$class]) &&
271
- isset($this->configuration['classes'][$prev])) {
272
- $this->configuration['classes'][$class] =
273
- $this->configuration['classes'][$prev];
274
- }
275
- $this->configuration['logger_class'] = $class;
276
- }
277
-
278
- /**
279
- * Return the configured IO class.
280
- *
281
- * @return string
282
- */
283
- public function getIoClass()
284
- {
285
- return $this->configuration['io_class'];
286
- }
287
-
288
- /**
289
- * Set the application name, this is included in the User-Agent HTTP header.
290
- * @param string $name
291
- */
292
- public function setApplicationName($name)
293
- {
294
- $this->configuration['application_name'] = $name;
295
- }
296
-
297
- /**
298
- * @return string the name of the application
299
- */
300
- public function getApplicationName()
301
- {
302
- return $this->configuration['application_name'];
303
- }
304
-
305
- /**
306
- * Set the client ID for the auth class.
307
- * @param $clientId string - the API console client ID
308
- */
309
- public function setClientId($clientId)
310
- {
311
- $this->setAuthConfig('client_id', $clientId);
312
- }
313
-
314
- /**
315
- * Set the client secret for the auth class.
316
- * @param $secret string - the API console client secret
317
- */
318
- public function setClientSecret($secret)
319
- {
320
- $this->setAuthConfig('client_secret', $secret);
321
- }
322
-
323
- /**
324
- * Set the redirect uri for the auth class. Note that if using the
325
- * Javascript based sign in flow, this should be the string 'postmessage'.
326
- *
327
- * @param $uri string - the URI that users should be redirected to
328
- */
329
- public function setRedirectUri($uri)
330
- {
331
- $this->setAuthConfig('redirect_uri', $uri);
332
- }
333
-
334
- /**
335
- * Set the app activities for the auth class.
336
- * @param $rva string a space separated list of app activity types
337
- */
338
- public function setRequestVisibleActions($rva)
339
- {
340
- $this->setAuthConfig('request_visible_actions', $rva);
341
- }
342
-
343
- /**
344
- * Set the the access type requested (offline or online.)
345
- * @param $access string - the access type
346
- */
347
- public function setAccessType($access)
348
- {
349
- $this->setAuthConfig('access_type', $access);
350
- }
351
-
352
- /**
353
- * Set when to show the approval prompt (auto or force)
354
- * @param $approval string - the approval request
355
- */
356
- public function setApprovalPrompt($approval)
357
- {
358
- $this->setAuthConfig('approval_prompt', $approval);
359
- }
360
-
361
- /**
362
- * Set the login hint (email address or sub identifier)
363
- * @param $hint string
364
- */
365
- public function setLoginHint($hint)
366
- {
367
- $this->setAuthConfig('login_hint', $hint);
368
- }
369
-
370
- /**
371
- * Set the developer key for the auth class. Note that this is separate value
372
- * from the client ID - if it looks like a URL, its a client ID!
373
- * @param $key string - the API console developer key
374
- */
375
- public function setDeveloperKey($key)
376
- {
377
- $this->setAuthConfig('developer_key', $key);
378
- }
379
-
380
- /**
381
- * Set the hd (hosted domain) parameter streamlines the login process for
382
- * Google Apps hosted accounts. By including the domain of the user, you
383
- * restrict sign-in to accounts at that domain.
384
- *
385
- * This should not be used to ensure security on your application - check
386
- * the hd values within an id token (@see Google_Auth_LoginTicket) after sign
387
- * in to ensure that the user is from the domain you were expecting.
388
- *
389
- * @param $hd string - the domain to use.
390
- */
391
- public function setHostedDomain($hd)
392
- {
393
- $this->setAuthConfig('hd', $hd);
394
- }
395
-
396
- /**
397
- * Set the prompt hint. Valid values are none, consent and select_account.
398
- * If no value is specified and the user has not previously authorized
399
- * access, then the user is shown a consent screen.
400
- * @param $prompt string
401
- */
402
- public function setPrompt($prompt)
403
- {
404
- $this->setAuthConfig('prompt', $prompt);
405
- }
406
-
407
- /**
408
- * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
409
- * 2.0. It is used in OpenID 2.0 requests to signify the URL-space for which
410
- * an authentication request is valid.
411
- * @param $realm string - the URL-space to use.
412
- */
413
- public function setOpenidRealm($realm)
414
- {
415
- $this->setAuthConfig('openid.realm', $realm);
416
- }
417
-
418
- /**
419
- * If this is provided with the value true, and the authorization request is
420
- * granted, the authorization will include any previous authorizations
421
- * granted to this user/application combination for other scopes.
422
- * @param $include boolean - the URL-space to use.
423
- */
424
- public function setIncludeGrantedScopes($include)
425
- {
426
- $this->setAuthConfig(
427
- 'include_granted_scopes',
428
- $include ? "true" : "false"
429
- );
430
- }
431
-
432
- /**
433
- * @return string the base URL to use for API calls
434
- */
435
- public function getBasePath()
436
- {
437
- return $this->configuration['base_path'];
438
- }
439
-
440
- /**
441
- * Set the auth configuration for the current auth class.
442
- * @param $key - the key to set
443
- * @param $value - the parameter value
444
- */
445
- private function setAuthConfig($key, $value)
446
- {
447
- if (!isset($this->configuration['classes'][$this->getAuthClass()])) {
448
- $this->configuration['classes'][$this->getAuthClass()] = array();
449
- }
450
- $this->configuration['classes'][$this->getAuthClass()][$key] = $value;
451
- }
452
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * A class to contain the library configuration for the Google API client.
20
+ */
21
+ class Google_Config
22
+ {
23
+ const GZIP_DISABLED = true;
24
+ const GZIP_ENABLED = false;
25
+ const GZIP_UPLOADS_ENABLED = true;
26
+ const GZIP_UPLOADS_DISABLED = false;
27
+ const USE_AUTO_IO_SELECTION = "auto";
28
+ const TASK_RETRY_NEVER = 0;
29
+ const TASK_RETRY_ONCE = 1;
30
+ const TASK_RETRY_ALWAYS = -1;
31
+ protected $configuration;
32
+
33
+ /**
34
+ * Create a new Google_Config. Can accept an ini file location with the
35
+ * local configuration. For example:
36
+ * application_name="My App"
37
+ *
38
+ * @param [$ini_file_location] - optional - The location of the ini file to load
39
+ */
40
+ public function __construct($ini_file_location = null)
41
+ {
42
+ $this->configuration = array(
43
+ // The application_name is included in the User-Agent HTTP header.
44
+ 'application_name' => '',
45
+
46
+ // Which Authentication, Storage and HTTP IO classes to use.
47
+ 'auth_class' => 'Google_Auth_OAuth2',
48
+ 'io_class' => self::USE_AUTO_IO_SELECTION,
49
+ 'cache_class' => 'Google_Cache_File',
50
+ 'logger_class' => 'Google_Logger_Null',
51
+
52
+ // Don't change these unless you're working against a special development
53
+ // or testing environment.
54
+ 'base_path' => 'https://www.googleapis.com',
55
+
56
+ // Definition of class specific values, like file paths and so on.
57
+ 'classes' => array(
58
+ 'Google_IO_Abstract' => array(
59
+ 'request_timeout_seconds' => 100,
60
+ ),
61
+ 'Google_Logger_Abstract' => array(
62
+ 'level' => 'debug',
63
+ 'log_format' => "[%datetime%] %level%: %message% %context%\n",
64
+ 'date_format' => 'd/M/Y:H:i:s O',
65
+ 'allow_newlines' => true
66
+ ),
67
+ 'Google_Logger_File' => array(
68
+ 'file' => 'php://stdout',
69
+ 'mode' => 0640,
70
+ 'lock' => false,
71
+ ),
72
+ 'Google_Http_Request' => array(
73
+ // Disable the use of gzip on calls if set to true. Defaults to false.
74
+ 'disable_gzip' => self::GZIP_ENABLED,
75
+
76
+ // We default gzip to disabled on uploads even if gzip is otherwise
77
+ // enabled, due to some issues seen with small packet sizes for uploads.
78
+ // Please test with this option before enabling gzip for uploads in
79
+ // a production environment.
80
+ 'enable_gzip_for_uploads' => self::GZIP_UPLOADS_DISABLED,
81
+ ),
82
+ // If you want to pass in OAuth 2.0 settings, they will need to be
83
+ // structured like this.
84
+ 'Google_Auth_OAuth2' => array(
85
+ // Keys for OAuth 2.0 access, see the API console at
86
+ // https://developers.google.com/console
87
+ 'client_id' => '',
88
+ 'client_secret' => '',
89
+ 'redirect_uri' => '',
90
+
91
+ // Simple API access key, also from the API console. Ensure you get
92
+ // a Server key, and not a Browser key.
93
+ 'developer_key' => '',
94
+
95
+ // Other parameters.
96
+ 'hd' => '',
97
+ 'prompt' => '',
98
+ 'openid.realm' => '',
99
+ 'include_granted_scopes' => '',
100
+ 'login_hint' => '',
101
+ 'request_visible_actions' => '',
102
+ 'access_type' => 'online',
103
+ 'approval_prompt' => 'auto',
104
+ 'federated_signon_certs_url' =>
105
+ 'https://www.googleapis.com/oauth2/v1/certs',
106
+ ),
107
+ 'Google_Task_Runner' => array(
108
+ // Delays are specified in seconds
109
+ 'initial_delay' => 1,
110
+ 'max_delay' => 60,
111
+ // Base number for exponential backoff
112
+ 'factor' => 2,
113
+ // A random number between -jitter and jitter will be added to the
114
+ // factor on each iteration to allow for better distribution of
115
+ // retries.
116
+ 'jitter' => .5,
117
+ // Maximum number of retries allowed
118
+ 'retries' => 0
119
+ ),
120
+ 'Google_Service_Exception' => array(
121
+ 'retry_map' => array(
122
+ '500' => self::TASK_RETRY_ALWAYS,
123
+ '503' => self::TASK_RETRY_ALWAYS,
124
+ 'rateLimitExceeded' => self::TASK_RETRY_ALWAYS,
125
+ 'userRateLimitExceeded' => self::TASK_RETRY_ALWAYS
126
+ )
127
+ ),
128
+ 'Google_IO_Exception' => array(
129
+ 'retry_map' => !extension_loaded('curl') ? array() : array(
130
+ CURLE_COULDNT_RESOLVE_HOST => self::TASK_RETRY_ALWAYS,
131
+ CURLE_COULDNT_CONNECT => self::TASK_RETRY_ALWAYS,
132
+ CURLE_OPERATION_TIMEOUTED => self::TASK_RETRY_ALWAYS,
133
+ CURLE_SSL_CONNECT_ERROR => self::TASK_RETRY_ALWAYS,
134
+ CURLE_GOT_NOTHING => self::TASK_RETRY_ALWAYS
135
+ )
136
+ ),
137
+ // Set a default directory for the file cache.
138
+ 'Google_Cache_File' => array(
139
+ 'directory' => sys_get_temp_dir() . '/Google_Client'
140
+ )
141
+ ),
142
+ );
143
+ if ($ini_file_location) {
144
+ $ini = parse_ini_file($ini_file_location, true);
145
+ if (is_array($ini) && count($ini)) {
146
+ $merged_configuration = $ini + $this->configuration;
147
+ if (isset($ini['classes']) && isset($this->configuration['classes'])) {
148
+ $merged_configuration['classes'] = $ini['classes'] + $this->configuration['classes'];
149
+ }
150
+ $this->configuration = $merged_configuration;
151
+ }
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Set configuration specific to a given class.
157
+ * $config->setClassConfig('Google_Cache_File',
158
+ * array('directory' => '/tmp/cache'));
159
+ * @param $class string The class name for the configuration
160
+ * @param $config string key or an array of configuration values
161
+ * @param $value string optional - if $config is a key, the value
162
+ */
163
+ public function setClassConfig($class, $config, $value = null)
164
+ {
165
+ if (!is_array($config)) {
166
+ if (!isset($this->configuration['classes'][$class])) {
167
+ $this->configuration['classes'][$class] = array();
168
+ }
169
+ $this->configuration['classes'][$class][$config] = $value;
170
+ } else {
171
+ $this->configuration['classes'][$class] = $config;
172
+ }
173
+ }
174
+
175
+ public function getClassConfig($class, $key = null)
176
+ {
177
+ if (!isset($this->configuration['classes'][$class])) {
178
+ return null;
179
+ }
180
+ if ($key === null) {
181
+ return $this->configuration['classes'][$class];
182
+ } else {
183
+ return $this->configuration['classes'][$class][$key];
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Return the configured cache class.
189
+ * @return string
190
+ */
191
+ public function getCacheClass()
192
+ {
193
+ return $this->configuration['cache_class'];
194
+ }
195
+
196
+ /**
197
+ * Return the configured logger class.
198
+ * @return string
199
+ */
200
+ public function getLoggerClass()
201
+ {
202
+ return $this->configuration['logger_class'];
203
+ }
204
+
205
+ /**
206
+ * Return the configured Auth class.
207
+ * @return string
208
+ */
209
+ public function getAuthClass()
210
+ {
211
+ return $this->configuration['auth_class'];
212
+ }
213
+
214
+ /**
215
+ * Set the auth class.
216
+ *
217
+ * @param $class string the class name to set
218
+ */
219
+ public function setAuthClass($class)
220
+ {
221
+ $prev = $this->configuration['auth_class'];
222
+ if (!isset($this->configuration['classes'][$class]) &&
223
+ isset($this->configuration['classes'][$prev])) {
224
+ $this->configuration['classes'][$class] =
225
+ $this->configuration['classes'][$prev];
226
+ }
227
+ $this->configuration['auth_class'] = $class;
228
+ }
229
+
230
+ /**
231
+ * Set the IO class.
232
+ *
233
+ * @param $class string the class name to set
234
+ */
235
+ public function setIoClass($class)
236
+ {
237
+ $prev = $this->configuration['io_class'];
238
+ if (!isset($this->configuration['classes'][$class]) &&
239
+ isset($this->configuration['classes'][$prev])) {
240
+ $this->configuration['classes'][$class] =
241
+ $this->configuration['classes'][$prev];
242
+ }
243
+ $this->configuration['io_class'] = $class;
244
+ }
245
+
246
+ /**
247
+ * Set the cache class.
248
+ *
249
+ * @param $class string the class name to set
250
+ */
251
+ public function setCacheClass($class)
252
+ {
253
+ $prev = $this->configuration['cache_class'];
254
+ if (!isset($this->configuration['classes'][$class]) &&
255
+ isset($this->configuration['classes'][$prev])) {
256
+ $this->configuration['classes'][$class] =
257
+ $this->configuration['classes'][$prev];
258
+ }
259
+ $this->configuration['cache_class'] = $class;
260
+ }
261
+
262
+ /**
263
+ * Set the logger class.
264
+ *
265
+ * @param $class string the class name to set
266
+ */
267
+ public function setLoggerClass($class)
268
+ {
269
+ $prev = $this->configuration['logger_class'];
270
+ if (!isset($this->configuration['classes'][$class]) &&
271
+ isset($this->configuration['classes'][$prev])) {
272
+ $this->configuration['classes'][$class] =
273
+ $this->configuration['classes'][$prev];
274
+ }
275
+ $this->configuration['logger_class'] = $class;
276
+ }
277
+
278
+ /**
279
+ * Return the configured IO class.
280
+ *
281
+ * @return string
282
+ */
283
+ public function getIoClass()
284
+ {
285
+ return $this->configuration['io_class'];
286
+ }
287
+
288
+ /**
289
+ * Set the application name, this is included in the User-Agent HTTP header.
290
+ * @param string $name
291
+ */
292
+ public function setApplicationName($name)
293
+ {
294
+ $this->configuration['application_name'] = $name;
295
+ }
296
+
297
+ /**
298
+ * @return string the name of the application
299
+ */
300
+ public function getApplicationName()
301
+ {
302
+ return $this->configuration['application_name'];
303
+ }
304
+
305
+ /**
306
+ * Set the client ID for the auth class.
307
+ * @param $clientId string - the API console client ID
308
+ */
309
+ public function setClientId($clientId)
310
+ {
311
+ $this->setAuthConfig('client_id', $clientId);
312
+ }
313
+
314
+ /**
315
+ * Set the client secret for the auth class.
316
+ * @param $secret string - the API console client secret
317
+ */
318
+ public function setClientSecret($secret)
319
+ {
320
+ $this->setAuthConfig('client_secret', $secret);
321
+ }
322
+
323
+ /**
324
+ * Set the redirect uri for the auth class. Note that if using the
325
+ * Javascript based sign in flow, this should be the string 'postmessage'.
326
+ *
327
+ * @param $uri string - the URI that users should be redirected to
328
+ */
329
+ public function setRedirectUri($uri)
330
+ {
331
+ $this->setAuthConfig('redirect_uri', $uri);
332
+ }
333
+
334
+ /**
335
+ * Set the app activities for the auth class.
336
+ * @param $rva string a space separated list of app activity types
337
+ */
338
+ public function setRequestVisibleActions($rva)
339
+ {
340
+ $this->setAuthConfig('request_visible_actions', $rva);
341
+ }
342
+
343
+ /**
344
+ * Set the the access type requested (offline or online.)
345
+ * @param $access string - the access type
346
+ */
347
+ public function setAccessType($access)
348
+ {
349
+ $this->setAuthConfig('access_type', $access);
350
+ }
351
+
352
+ /**
353
+ * Set when to show the approval prompt (auto or force)
354
+ * @param $approval string - the approval request
355
+ */
356
+ public function setApprovalPrompt($approval)
357
+ {
358
+ $this->setAuthConfig('approval_prompt', $approval);
359
+ }
360
+
361
+ /**
362
+ * Set the login hint (email address or sub identifier)
363
+ * @param $hint string
364
+ */
365
+ public function setLoginHint($hint)
366
+ {
367
+ $this->setAuthConfig('login_hint', $hint);
368
+ }
369
+
370
+ /**
371
+ * Set the developer key for the auth class. Note that this is separate value
372
+ * from the client ID - if it looks like a URL, its a client ID!
373
+ * @param $key string - the API console developer key
374
+ */
375
+ public function setDeveloperKey($key)
376
+ {
377
+ $this->setAuthConfig('developer_key', $key);
378
+ }
379
+
380
+ /**
381
+ * Set the hd (hosted domain) parameter streamlines the login process for
382
+ * Google Apps hosted accounts. By including the domain of the user, you
383
+ * restrict sign-in to accounts at that domain.
384
+ *
385
+ * This should not be used to ensure security on your application - check
386
+ * the hd values within an id token (@see Google_Auth_LoginTicket) after sign
387
+ * in to ensure that the user is from the domain you were expecting.
388
+ *
389
+ * @param $hd string - the domain to use.
390
+ */
391
+ public function setHostedDomain($hd)
392
+ {
393
+ $this->setAuthConfig('hd', $hd);
394
+ }
395
+
396
+ /**
397
+ * Set the prompt hint. Valid values are none, consent and select_account.
398
+ * If no value is specified and the user has not previously authorized
399
+ * access, then the user is shown a consent screen.
400
+ * @param $prompt string
401
+ */
402
+ public function setPrompt($prompt)
403
+ {
404
+ $this->setAuthConfig('prompt', $prompt);
405
+ }
406
+
407
+ /**
408
+ * openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
409
+ * 2.0. It is used in OpenID 2.0 requests to signify the URL-space for which
410
+ * an authentication request is valid.
411
+ * @param $realm string - the URL-space to use.
412
+ */
413
+ public function setOpenidRealm($realm)
414
+ {
415
+ $this->setAuthConfig('openid.realm', $realm);
416
+ }
417
+
418
+ /**
419
+ * If this is provided with the value true, and the authorization request is
420
+ * granted, the authorization will include any previous authorizations
421
+ * granted to this user/application combination for other scopes.
422
+ * @param $include boolean - the URL-space to use.
423
+ */
424
+ public function setIncludeGrantedScopes($include)
425
+ {
426
+ $this->setAuthConfig(
427
+ 'include_granted_scopes',
428
+ $include ? "true" : "false"
429
+ );
430
+ }
431
+
432
+ /**
433
+ * @return string the base URL to use for API calls
434
+ */
435
+ public function getBasePath()
436
+ {
437
+ return $this->configuration['base_path'];
438
+ }
439
+
440
+ /**
441
+ * Set the auth configuration for the current auth class.
442
+ * @param $key - the key to set
443
+ * @param $value - the parameter value
444
+ */
445
+ private function setAuthConfig($key, $value)
446
+ {
447
+ if (!isset($this->configuration['classes'][$this->getAuthClass()])) {
448
+ $this->configuration['classes'][$this->getAuthClass()] = array();
449
+ }
450
+ $this->configuration['classes'][$this->getAuthClass()][$key] = $value;
451
+ }
452
+ }
google/Exception.php CHANGED
@@ -1,20 +1,20 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- class Google_Exception extends Exception
19
- {
20
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ class Google_Exception extends Exception
19
+ {
20
+ }
google/Http/Batch.php CHANGED
@@ -1,145 +1,145 @@
1
- <?php
2
- /*
3
- * Copyright 2012 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * Class to handle batched requests to the Google API service.
24
- */
25
- class Google_Http_Batch
26
- {
27
- /** @var string Multipart Boundary. */
28
- private $boundary;
29
-
30
- /** @var array service requests to be executed. */
31
- private $requests = array();
32
-
33
- /** @var Google_Client */
34
- private $client;
35
-
36
- private $expected_classes = array();
37
-
38
- private $root_url;
39
-
40
- private $batch_path;
41
-
42
- public function __construct(Google_Client $client, $boundary = false, $rootUrl = '', $batchPath = '')
43
- {
44
- $this->client = $client;
45
- $this->root_url = rtrim($rootUrl ? $rootUrl : $this->client->getBasePath(), '/');
46
- $this->batch_path = $batchPath ? $batchPath : 'batch';
47
- $this->expected_classes = array();
48
- $boundary = (false == $boundary) ? mt_rand() : $boundary;
49
- $this->boundary = str_replace('"', '', $boundary);
50
- }
51
-
52
- public function add(Google_Http_Request $request, $key = false)
53
- {
54
- if (false == $key) {
55
- $key = mt_rand();
56
- }
57
-
58
- $this->requests[$key] = $request;
59
- }
60
-
61
- public function execute()
62
- {
63
- $body = '';
64
-
65
- /** @var Google_Http_Request $req */
66
- foreach ($this->requests as $key => $req) {
67
- $body .= "--{$this->boundary}\n";
68
- $body .= $req->toBatchString($key) . "\n\n";
69
- $this->expected_classes["response-" . $key] = $req->getExpectedClass();
70
- }
71
-
72
- $body .= "--{$this->boundary}--";
73
-
74
- $url = $this->root_url . '/' . $this->batch_path;
75
- $httpRequest = new Google_Http_Request($url, 'POST');
76
- $httpRequest->setRequestHeaders(
77
- array('Content-Type' => 'multipart/mixed; boundary=' . $this->boundary)
78
- );
79
-
80
- $httpRequest->setPostBody($body);
81
- $response = $this->client->getIo()->makeRequest($httpRequest);
82
-
83
- return $this->parseResponse($response);
84
- }
85
-
86
- public function parseResponse(Google_Http_Request $response)
87
- {
88
- $contentType = $response->getResponseHeader('content-type');
89
- $contentType = explode(';', $contentType);
90
- $boundary = false;
91
- foreach ($contentType as $part) {
92
- $part = (explode('=', $part, 2));
93
- if (isset($part[0]) && 'boundary' == trim($part[0])) {
94
- $boundary = $part[1];
95
- }
96
- }
97
-
98
- $body = $response->getResponseBody();
99
- if ($body) {
100
- $body = str_replace("--$boundary--", "--$boundary", $body);
101
- $parts = explode("--$boundary", $body);
102
- $responses = array();
103
-
104
- foreach ($parts as $part) {
105
- $part = trim($part);
106
- if (!empty($part)) {
107
- list($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
108
- $metaHeaders = $this->client->getIo()->getHttpResponseHeaders($metaHeaders);
109
-
110
- $status = substr($part, 0, strpos($part, "\n"));
111
- $status = explode(" ", $status);
112
- $status = $status[1];
113
-
114
- list($partHeaders, $partBody) = $this->client->getIo()->ParseHttpResponse($part, false);
115
- $response = new Google_Http_Request("");
116
- $response->setResponseHttpCode($status);
117
- $response->setResponseHeaders($partHeaders);
118
- $response->setResponseBody($partBody);
119
-
120
- // Need content id.
121
- $key = $metaHeaders['content-id'];
122
-
123
- if (isset($this->expected_classes[$key]) &&
124
- strlen($this->expected_classes[$key]) > 0) {
125
- $class = $this->expected_classes[$key];
126
- $response->setExpectedClass($class);
127
- }
128
-
129
- try {
130
- $response = Google_Http_REST::decodeHttpResponse($response, $this->client);
131
- $responses[$key] = $response;
132
- } catch (Google_Service_Exception $e) {
133
- // Store the exception as the response, so successful responses
134
- // can be processed.
135
- $responses[$key] = $e;
136
- }
137
- }
138
- }
139
-
140
- return $responses;
141
- }
142
-
143
- return null;
144
- }
145
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2012 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * Class to handle batched requests to the Google API service.
24
+ */
25
+ class Google_Http_Batch
26
+ {
27
+ /** @var string Multipart Boundary. */
28
+ private $boundary;
29
+
30
+ /** @var array service requests to be executed. */
31
+ private $requests = array();
32
+
33
+ /** @var Google_Client */
34
+ private $client;
35
+
36
+ private $expected_classes = array();
37
+
38
+ private $root_url;
39
+
40
+ private $batch_path;
41
+
42
+ public function __construct(Google_Client $client, $boundary = false, $rootUrl = '', $batchPath = '')
43
+ {
44
+ $this->client = $client;
45
+ $this->root_url = rtrim($rootUrl ? $rootUrl : $this->client->getBasePath(), '/');
46
+ $this->batch_path = $batchPath ? $batchPath : 'batch';
47
+ $this->expected_classes = array();
48
+ $boundary = (false == $boundary) ? mt_rand() : $boundary;
49
+ $this->boundary = str_replace('"', '', $boundary);
50
+ }
51
+
52
+ public function add(Google_Http_Request $request, $key = false)
53
+ {
54
+ if (false == $key) {
55
+ $key = mt_rand();
56
+ }
57
+
58
+ $this->requests[$key] = $request;
59
+ }
60
+
61
+ public function execute()
62
+ {
63
+ $body = '';
64
+
65
+ /** @var Google_Http_Request $req */
66
+ foreach ($this->requests as $key => $req) {
67
+ $body .= "--{$this->boundary}\n";
68
+ $body .= $req->toBatchString($key) . "\n\n";
69
+ $this->expected_classes["response-" . $key] = $req->getExpectedClass();
70
+ }
71
+
72
+ $body .= "--{$this->boundary}--";
73
+
74
+ $url = $this->root_url . '/' . $this->batch_path;
75
+ $httpRequest = new Google_Http_Request($url, 'POST');
76
+ $httpRequest->setRequestHeaders(
77
+ array('Content-Type' => 'multipart/mixed; boundary=' . $this->boundary)
78
+ );
79
+
80
+ $httpRequest->setPostBody($body);
81
+ $response = $this->client->getIo()->makeRequest($httpRequest);
82
+
83
+ return $this->parseResponse($response);
84
+ }
85
+
86
+ public function parseResponse(Google_Http_Request $response)
87
+ {
88
+ $contentType = $response->getResponseHeader('content-type');
89
+ $contentType = explode(';', $contentType);
90
+ $boundary = false;
91
+ foreach ($contentType as $part) {
92
+ $part = (explode('=', $part, 2));
93
+ if (isset($part[0]) && 'boundary' == trim($part[0])) {
94
+ $boundary = $part[1];
95
+ }
96
+ }
97
+
98
+ $body = $response->getResponseBody();
99
+ if ($body) {
100
+ $body = str_replace("--$boundary--", "--$boundary", $body);
101
+ $parts = explode("--$boundary", $body);
102
+ $responses = array();
103
+
104
+ foreach ($parts as $part) {
105
+ $part = trim($part);
106
+ if (!empty($part)) {
107
+ list($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
108
+ $metaHeaders = $this->client->getIo()->getHttpResponseHeaders($metaHeaders);
109
+
110
+ $status = substr($part, 0, strpos($part, "\n"));
111
+ $status = explode(" ", $status);
112
+ $status = $status[1];
113
+
114
+ list($partHeaders, $partBody) = $this->client->getIo()->ParseHttpResponse($part, false);
115
+ $response = new Google_Http_Request("");
116
+ $response->setResponseHttpCode($status);
117
+ $response->setResponseHeaders($partHeaders);
118
+ $response->setResponseBody($partBody);
119
+
120
+ // Need content id.
121
+ $key = $metaHeaders['content-id'];
122
+
123
+ if (isset($this->expected_classes[$key]) &&
124
+ strlen($this->expected_classes[$key]) > 0) {
125
+ $class = $this->expected_classes[$key];
126
+ $response->setExpectedClass($class);
127
+ }
128
+
129
+ try {
130
+ $response = Google_Http_REST::decodeHttpResponse($response, $this->client);
131
+ $responses[$key] = $response;
132
+ } catch (Google_Service_Exception $e) {
133
+ // Store the exception as the response, so successful responses
134
+ // can be processed.
135
+ $responses[$key] = $e;
136
+ }
137
+ }
138
+ }
139
+
140
+ return $responses;
141
+ }
142
+
143
+ return null;
144
+ }
145
+ }
google/Http/CacheParser.php CHANGED
@@ -1,185 +1,185 @@
1
- <?php
2
- /*
3
- * Copyright 2012 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * Implement the caching directives specified in rfc2616. This
24
- * implementation is guided by the guidance offered in rfc2616-sec13.
25
- */
26
- class Google_Http_CacheParser
27
- {
28
- public static $CACHEABLE_HTTP_METHODS = array('GET', 'HEAD');
29
- public static $CACHEABLE_STATUS_CODES = array('200', '203', '300', '301');
30
-
31
- /**
32
- * Check if an HTTP request can be cached by a private local cache.
33
- *
34
- * @static
35
- * @param Google_Http_Request $resp
36
- * @return bool True if the request is cacheable.
37
- * False if the request is uncacheable.
38
- */
39
- public static function isRequestCacheable(Google_Http_Request $resp)
40
- {
41
- $method = $resp->getRequestMethod();
42
- if (! in_array($method, self::$CACHEABLE_HTTP_METHODS)) {
43
- return false;
44
- }
45
-
46
- // Don't cache authorized requests/responses.
47
- // [rfc2616-14.8] When a shared cache receives a request containing an
48
- // Authorization field, it MUST NOT return the corresponding response
49
- // as a reply to any other request...
50
- if ($resp->getRequestHeader("authorization")) {
51
- return false;
52
- }
53
-
54
- return true;
55
- }
56
-
57
- /**
58
- * Check if an HTTP response can be cached by a private local cache.
59
- *
60
- * @static
61
- * @param Google_Http_Request $resp
62
- * @return bool True if the response is cacheable.
63
- * False if the response is un-cacheable.
64
- */
65
- public static function isResponseCacheable(Google_Http_Request $resp)
66
- {
67
- // First, check if the HTTP request was cacheable before inspecting the
68
- // HTTP response.
69
- if (false == self::isRequestCacheable($resp)) {
70
- return false;
71
- }
72
-
73
- $code = $resp->getResponseHttpCode();
74
- if (! in_array($code, self::$CACHEABLE_STATUS_CODES)) {
75
- return false;
76
- }
77
-
78
- // The resource is uncacheable if the resource is already expired and
79
- // the resource doesn't have an ETag for revalidation.
80
- $etag = $resp->getResponseHeader("etag");
81
- if (self::isExpired($resp) && $etag == false) {
82
- return false;
83
- }
84
-
85
- // [rfc2616-14.9.2] If [no-store is] sent in a response, a cache MUST NOT
86
- // store any part of either this response or the request that elicited it.
87
- $cacheControl = $resp->getParsedCacheControl();
88
- if (isset($cacheControl['no-store'])) {
89
- return false;
90
- }
91
-
92
- // Pragma: no-cache is an http request directive, but is occasionally
93
- // used as a response header incorrectly.
94
- $pragma = $resp->getResponseHeader('pragma');
95
- if ($pragma == 'no-cache' || strpos($pragma, 'no-cache') !== false) {
96
- return false;
97
- }
98
-
99
- // [rfc2616-14.44] Vary: * is extremely difficult to cache. "It implies that
100
- // a cache cannot determine from the request headers of a subsequent request
101
- // whether this response is the appropriate representation."
102
- // Given this, we deem responses with the Vary header as uncacheable.
103
- $vary = $resp->getResponseHeader('vary');
104
- if ($vary) {
105
- return false;
106
- }
107
-
108
- return true;
109
- }
110
-
111
- /**
112
- * @static
113
- * @param Google_Http_Request $resp
114
- * @return bool True if the HTTP response is considered to be expired.
115
- * False if it is considered to be fresh.
116
- */
117
- public static function isExpired(Google_Http_Request $resp)
118
- {
119
- // HTTP/1.1 clients and caches MUST treat other invalid date formats,
120
- // especially including the value “0”, as in the past.
121
- $parsedExpires = false;
122
- $responseHeaders = $resp->getResponseHeaders();
123
-
124
- if (isset($responseHeaders['expires'])) {
125
- $rawExpires = $responseHeaders['expires'];
126
- // Check for a malformed expires header first.
127
- if (empty($rawExpires) || (is_numeric($rawExpires) && $rawExpires <= 0)) {
128
- return true;
129
- }
130
-
131
- // See if we can parse the expires header.
132
- $parsedExpires = strtotime($rawExpires);
133
- if (false == $parsedExpires || $parsedExpires <= 0) {
134
- return true;
135
- }
136
- }
137
-
138
- // Calculate the freshness of an http response.
139
- $freshnessLifetime = false;
140
- $cacheControl = $resp->getParsedCacheControl();
141
- if (isset($cacheControl['max-age'])) {
142
- $freshnessLifetime = $cacheControl['max-age'];
143
- }
144
-
145
- $rawDate = $resp->getResponseHeader('date');
146
- $parsedDate = strtotime($rawDate);
147
-
148
- if (empty($rawDate) || false == $parsedDate) {
149
- // We can't default this to now, as that means future cache reads
150
- // will always pass with the logic below, so we will require a
151
- // date be injected if not supplied.
152
- throw new Google_Exception("All cacheable requests must have creation dates.");
153
- }
154
-
155
- if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
156
- $freshnessLifetime = $parsedExpires - $parsedDate;
157
- }
158
-
159
- if (false == $freshnessLifetime) {
160
- return true;
161
- }
162
-
163
- // Calculate the age of an http response.
164
- $age = max(0, time() - $parsedDate);
165
- if (isset($responseHeaders['age'])) {
166
- $age = max($age, strtotime($responseHeaders['age']));
167
- }
168
-
169
- return $freshnessLifetime <= $age;
170
- }
171
-
172
- /**
173
- * Determine if a cache entry should be revalidated with by the origin.
174
- *
175
- * @param Google_Http_Request $response
176
- * @return bool True if the entry is expired, else return false.
177
- */
178
- public static function mustRevalidate(Google_Http_Request $response)
179
- {
180
- // [13.3] When a cache has a stale entry that it would like to use as a
181
- // response to a client's request, it first has to check with the origin
182
- // server to see if its cached entry is still usable.
183
- return self::isExpired($response);
184
- }
185
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2012 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * Implement the caching directives specified in rfc2616. This
24
+ * implementation is guided by the guidance offered in rfc2616-sec13.
25
+ */
26
+ class Google_Http_CacheParser
27
+ {
28
+ public static $CACHEABLE_HTTP_METHODS = array('GET', 'HEAD');
29
+ public static $CACHEABLE_STATUS_CODES = array('200', '203', '300', '301');
30
+
31
+ /**
32
+ * Check if an HTTP request can be cached by a private local cache.
33
+ *
34
+ * @static
35
+ * @param Google_Http_Request $resp
36
+ * @return bool True if the request is cacheable.
37
+ * False if the request is uncacheable.
38
+ */
39
+ public static function isRequestCacheable(Google_Http_Request $resp)
40
+ {
41
+ $method = $resp->getRequestMethod();
42
+ if (! in_array($method, self::$CACHEABLE_HTTP_METHODS)) {
43
+ return false;
44
+ }
45
+
46
+ // Don't cache authorized requests/responses.
47
+ // [rfc2616-14.8] When a shared cache receives a request containing an
48
+ // Authorization field, it MUST NOT return the corresponding response
49
+ // as a reply to any other request...
50
+ if ($resp->getRequestHeader("authorization")) {
51
+ return false;
52
+ }
53
+
54
+ return true;
55
+ }
56
+
57
+ /**
58
+ * Check if an HTTP response can be cached by a private local cache.
59
+ *
60
+ * @static
61
+ * @param Google_Http_Request $resp
62
+ * @return bool True if the response is cacheable.
63
+ * False if the response is un-cacheable.
64
+ */
65
+ public static function isResponseCacheable(Google_Http_Request $resp)
66
+ {
67
+ // First, check if the HTTP request was cacheable before inspecting the
68
+ // HTTP response.
69
+ if (false == self::isRequestCacheable($resp)) {
70
+ return false;
71
+ }
72
+
73
+ $code = $resp->getResponseHttpCode();
74
+ if (! in_array($code, self::$CACHEABLE_STATUS_CODES)) {
75
+ return false;
76
+ }
77
+
78
+ // The resource is uncacheable if the resource is already expired and
79
+ // the resource doesn't have an ETag for revalidation.
80
+ $etag = $resp->getResponseHeader("etag");
81
+ if (self::isExpired($resp) && $etag == false) {
82
+ return false;
83
+ }
84
+
85
+ // [rfc2616-14.9.2] If [no-store is] sent in a response, a cache MUST NOT
86
+ // store any part of either this response or the request that elicited it.
87
+ $cacheControl = $resp->getParsedCacheControl();
88
+ if (isset($cacheControl['no-store'])) {
89
+ return false;
90
+ }
91
+
92
+ // Pragma: no-cache is an http request directive, but is occasionally
93
+ // used as a response header incorrectly.
94
+ $pragma = $resp->getResponseHeader('pragma');
95
+ if ($pragma == 'no-cache' || strpos($pragma, 'no-cache') !== false) {
96
+ return false;
97
+ }
98
+
99
+ // [rfc2616-14.44] Vary: * is extremely difficult to cache. "It implies that
100
+ // a cache cannot determine from the request headers of a subsequent request
101
+ // whether this response is the appropriate representation."
102
+ // Given this, we deem responses with the Vary header as uncacheable.
103
+ $vary = $resp->getResponseHeader('vary');
104
+ if ($vary) {
105
+ return false;
106
+ }
107
+
108
+ return true;
109
+ }
110
+
111
+ /**
112
+ * @static
113
+ * @param Google_Http_Request $resp
114
+ * @return bool True if the HTTP response is considered to be expired.
115
+ * False if it is considered to be fresh.
116
+ */
117
+ public static function isExpired(Google_Http_Request $resp)
118
+ {
119
+ // HTTP/1.1 clients and caches MUST treat other invalid date formats,
120
+ // especially including the value “0”, as in the past.
121
+ $parsedExpires = false;
122
+ $responseHeaders = $resp->getResponseHeaders();
123
+
124
+ if (isset($responseHeaders['expires'])) {
125
+ $rawExpires = $responseHeaders['expires'];
126
+ // Check for a malformed expires header first.
127
+ if (empty($rawExpires) || (is_numeric($rawExpires) && $rawExpires <= 0)) {
128
+ return true;
129
+ }
130
+
131
+ // See if we can parse the expires header.
132
+ $parsedExpires = strtotime($rawExpires);
133
+ if (false == $parsedExpires || $parsedExpires <= 0) {
134
+ return true;
135
+ }
136
+ }
137
+
138
+ // Calculate the freshness of an http response.
139
+ $freshnessLifetime = false;
140
+ $cacheControl = $resp->getParsedCacheControl();
141
+ if (isset($cacheControl['max-age'])) {
142
+ $freshnessLifetime = $cacheControl['max-age'];
143
+ }
144
+
145
+ $rawDate = $resp->getResponseHeader('date');
146
+ $parsedDate = strtotime($rawDate);
147
+
148
+ if (empty($rawDate) || false == $parsedDate) {
149
+ // We can't default this to now, as that means future cache reads
150
+ // will always pass with the logic below, so we will require a
151
+ // date be injected if not supplied.
152
+ throw new Google_Exception("All cacheable requests must have creation dates.");
153
+ }
154
+
155
+ if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
156
+ $freshnessLifetime = $parsedExpires - $parsedDate;
157
+ }
158
+
159
+ if (false == $freshnessLifetime) {
160
+ return true;
161
+ }
162
+
163
+ // Calculate the age of an http response.
164
+ $age = max(0, time() - $parsedDate);
165
+ if (isset($responseHeaders['age'])) {
166
+ $age = max($age, strtotime($responseHeaders['age']));
167
+ }
168
+
169
+ return $freshnessLifetime <= $age;
170
+ }
171
+
172
+ /**
173
+ * Determine if a cache entry should be revalidated with by the origin.
174
+ *
175
+ * @param Google_Http_Request $response
176
+ * @return bool True if the entry is expired, else return false.
177
+ */
178
+ public static function mustRevalidate(Google_Http_Request $response)
179
+ {
180
+ // [13.3] When a cache has a stale entry that it would like to use as a
181
+ // response to a client's request, it first has to check with the origin
182
+ // server to see if its cached entry is still usable.
183
+ return self::isExpired($response);
184
+ }
185
+ }
google/Http/MediaFileUpload.php CHANGED
@@ -1,341 +1,341 @@
1
- <?php
2
- /**
3
- * Copyright 2012 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * Manage large file uploads, which may be media but can be any type
24
- * of sizable data.
25
- */
26
- class Google_Http_MediaFileUpload
27
- {
28
- const UPLOAD_MEDIA_TYPE = 'media';
29
- const UPLOAD_MULTIPART_TYPE = 'multipart';
30
- const UPLOAD_RESUMABLE_TYPE = 'resumable';
31
-
32
- /** @var string $mimeType */
33
- private $mimeType;
34
-
35
- /** @var string $data */
36
- private $data;
37
-
38
- /** @var bool $resumable */
39
- private $resumable;
40
-
41
- /** @var int $chunkSize */
42
- private $chunkSize;
43
-
44
- /** @var int $size */
45
- private $size;
46
-
47
- /** @var string $resumeUri */
48
- private $resumeUri;
49
-
50
- /** @var int $progress */
51
- private $progress;
52
-
53
- /** @var Google_Client */
54
- private $client;
55
-
56
- /** @var Google_Http_Request */
57
- private $request;
58
-
59
- /** @var string */
60
- private $boundary;
61
-
62
- /**
63
- * Result code from last HTTP call
64
- * @var int
65
- */
66
- private $httpResultCode;
67
-
68
- /**
69
- * @param $mimeType string
70
- * @param $data string The bytes you want to upload.
71
- * @param $resumable bool
72
- * @param bool $chunkSize File will be uploaded in chunks of this many bytes.
73
- * only used if resumable=True
74
- */
75
- public function __construct(
76
- Google_Client $client,
77
- Google_Http_Request $request,
78
- $mimeType,
79
- $data,
80
- $resumable = false,
81
- $chunkSize = false,
82
- $boundary = false
83
- ) {
84
- $this->client = $client;
85
- $this->request = $request;
86
- $this->mimeType = $mimeType;
87
- $this->data = $data;
88
- $this->size = strlen($this->data);
89
- $this->resumable = $resumable;
90
- if (!$chunkSize) {
91
- $chunkSize = 256 * 1024;
92
- }
93
- $this->chunkSize = $chunkSize;
94
- $this->progress = 0;
95
- $this->boundary = $boundary;
96
-
97
- // Process Media Request
98
- $this->process();
99
- }
100
-
101
- /**
102
- * Set the size of the file that is being uploaded.
103
- * @param $size - int file size in bytes
104
- */
105
- public function setFileSize($size)
106
- {
107
- $this->size = $size;
108
- }
109
-
110
- /**
111
- * Return the progress on the upload
112
- * @return int progress in bytes uploaded.
113
- */
114
- public function getProgress()
115
- {
116
- return $this->progress;
117
- }
118
-
119
- /**
120
- * Return the HTTP result code from the last call made.
121
- * @return int code
122
- */
123
- public function getHttpResultCode()
124
- {
125
- return $this->httpResultCode;
126
- }
127
-
128
- /**
129
- * Sends a PUT-Request to google drive and parses the response,
130
- * setting the appropiate variables from the response()
131
- *
132
- * @param Google_Http_Request $httpRequest the Reuqest which will be send
133
- *
134
- * @return false|mixed false when the upload is unfinished or the decoded http response
135
- *
136
- */
137
- private function makePutRequest(Google_Http_Request $httpRequest)
138
- {
139
- if ($this->client->getClassConfig("Google_Http_Request", "enable_gzip_for_uploads")) {
140
- $httpRequest->enableGzip();
141
- } else {
142
- $httpRequest->disableGzip();
143
- }
144
-
145
- $response = $this->client->getIo()->makeRequest($httpRequest);
146
- $response->setExpectedClass($this->request->getExpectedClass());
147
- $code = $response->getResponseHttpCode();
148
- $this->httpResultCode = $code;
149
-
150
- if (308 == $code) {
151
- // Track the amount uploaded.
152
- $range = explode('-', $response->getResponseHeader('range'));
153
- $this->progress = $range[1] + 1;
154
-
155
- // Allow for changing upload URLs.
156
- $location = $response->getResponseHeader('location');
157
- if ($location) {
158
- $this->resumeUri = $location;
159
- }
160
-
161
- // No problems, but upload not complete.
162
- return false;
163
- } else {
164
- return Google_Http_REST::decodeHttpResponse($response, $this->client);
165
- }
166
- }
167
-
168
- /**
169
- * Send the next part of the file to upload.
170
- * @param [$chunk] the next set of bytes to send. If false will used $data passed
171
- * at construct time.
172
- */
173
- public function nextChunk($chunk = false)
174
- {
175
- if (false == $this->resumeUri) {
176
- $this->resumeUri = $this->fetchResumeUri();
177
- }
178
-
179
- if (false == $chunk) {
180
- $chunk = substr($this->data, $this->progress, $this->chunkSize);
181
- }
182
- $lastBytePos = $this->progress + strlen($chunk) - 1;
183
- $headers = array(
184
- 'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
185
- 'content-type' => $this->request->getRequestHeader('content-type'),
186
- 'content-length' => $this->chunkSize,
187
- 'expect' => '',
188
- );
189
-
190
- $httpRequest = new Google_Http_Request(
191
- $this->resumeUri,
192
- 'PUT',
193
- $headers,
194
- $chunk
195
- );
196
- return $this->makePutRequest($httpRequest);
197
- }
198
-
199
- /**
200
- * Resume a previously unfinished upload
201
- * @param $resumeUri the resume-URI of the unfinished, resumable upload.
202
- */
203
- public function resume($resumeUri)
204
- {
205
- $this->resumeUri = $resumeUri;
206
- $headers = array(
207
- 'content-range' => "bytes */$this->size",
208
- 'content-length' => 0,
209
- );
210
- $httpRequest = new Google_Http_Request(
211
- $this->resumeUri,
212
- 'PUT',
213
- $headers
214
- );
215
- return $this->makePutRequest($httpRequest);
216
- }
217
-
218
- /**
219
- * @return array|bool
220
- * @visible for testing
221
- */
222
- private function process()
223
- {
224
- $postBody = false;
225
- $contentType = false;
226
-
227
- $meta = $this->request->getPostBody();
228
- $meta = is_string($meta) ? json_decode($meta, true) : $meta;
229
-
230
- $uploadType = $this->getUploadType($meta);
231
- $this->request->setQueryParam('uploadType', $uploadType);
232
- $this->transformToUploadUrl();
233
- $mimeType = $this->mimeType ?
234
- $this->mimeType :
235
- $this->request->getRequestHeader('content-type');
236
-
237
- if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
238
- $contentType = $mimeType;
239
- $postBody = is_string($meta) ? $meta : json_encode($meta);
240
- } else if (self::UPLOAD_MEDIA_TYPE == $uploadType) {
241
- $contentType = $mimeType;
242
- $postBody = $this->data;
243
- } else if (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
244
- // This is a multipart/related upload.
245
- $boundary = $this->boundary ? $this->boundary : mt_rand();
246
- $boundary = str_replace('"', '', $boundary);
247
- $contentType = 'multipart/related; boundary=' . $boundary;
248
- $related = "--$boundary\r\n";
249
- $related .= "Content-Type: application/json; charset=UTF-8\r\n";
250
- $related .= "\r\n" . json_encode($meta) . "\r\n";
251
- $related .= "--$boundary\r\n";
252
- $related .= "Content-Type: $mimeType\r\n";
253
- $related .= "Content-Transfer-Encoding: base64\r\n";
254
- $related .= "\r\n" . base64_encode($this->data) . "\r\n";
255
- $related .= "--$boundary--";
256
- $postBody = $related;
257
- }
258
-
259
- $this->request->setPostBody($postBody);
260
-
261
- if (isset($contentType) && $contentType) {
262
- $contentTypeHeader['content-type'] = $contentType;
263
- $this->request->setRequestHeaders($contentTypeHeader);
264
- }
265
- }
266
-
267
- private function transformToUploadUrl()
268
- {
269
- $base = $this->request->getBaseComponent();
270
- $this->request->setBaseComponent($base . '/upload');
271
- }
272
-
273
- /**
274
- * Valid upload types:
275
- * - resumable (UPLOAD_RESUMABLE_TYPE)
276
- * - media (UPLOAD_MEDIA_TYPE)
277
- * - multipart (UPLOAD_MULTIPART_TYPE)
278
- * @param $meta
279
- * @return string
280
- * @visible for testing
281
- */
282
- public function getUploadType($meta)
283
- {
284
- if ($this->resumable) {
285
- return self::UPLOAD_RESUMABLE_TYPE;
286
- }
287
-
288
- if (false == $meta && $this->data) {
289
- return self::UPLOAD_MEDIA_TYPE;
290
- }
291
-
292
- return self::UPLOAD_MULTIPART_TYPE;
293
- }
294
-
295
- public function getResumeUri()
296
- {
297
- return ( $this->resumeUri !== null ? $this->resumeUri : $this->fetchResumeUri() );
298
- }
299
-
300
- private function fetchResumeUri()
301
- {
302
- $result = null;
303
- $body = $this->request->getPostBody();
304
- if ($body) {
305
- $headers = array(
306
- 'content-type' => 'application/json; charset=UTF-8',
307
- 'content-length' => Google_Utils::getStrLen($body),
308
- 'x-upload-content-type' => $this->mimeType,
309
- 'x-upload-content-length' => $this->size,
310
- 'expect' => '',
311
- );
312
- $this->request->setRequestHeaders($headers);
313
- }
314
-
315
- $response = $this->client->getIo()->makeRequest($this->request);
316
- $location = $response->getResponseHeader('location');
317
- $code = $response->getResponseHttpCode();
318
-
319
- if (200 == $code && true == $location) {
320
- return $location;
321
- }
322
- $message = $code;
323
- $body = @json_decode($response->getResponseBody());
324
- if (!empty($body->error->errors) ) {
325
- $message .= ': ';
326
- foreach ($body->error->errors as $error) {
327
- $message .= "{$error->domain}, {$error->message};";
328
- }
329
- $message = rtrim($message, ';');
330
- }
331
-
332
- $error = "Failed to start the resumable upload (HTTP {$message})";
333
- $this->client->getLogger()->error($error);
334
- throw new Google_Exception($error);
335
- }
336
-
337
- public function setChunkSize($chunkSize)
338
- {
339
- $this->chunkSize = $chunkSize;
340
- }
341
- }
1
+ <?php
2
+ /**
3
+ * Copyright 2012 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * Manage large file uploads, which may be media but can be any type
24
+ * of sizable data.
25
+ */
26
+ class Google_Http_MediaFileUpload
27
+ {
28
+ const UPLOAD_MEDIA_TYPE = 'media';
29
+ const UPLOAD_MULTIPART_TYPE = 'multipart';
30
+ const UPLOAD_RESUMABLE_TYPE = 'resumable';
31
+
32
+ /** @var string $mimeType */
33
+ private $mimeType;
34
+
35
+ /** @var string $data */
36
+ private $data;
37
+
38
+ /** @var bool $resumable */
39
+ private $resumable;
40
+
41
+ /** @var int $chunkSize */
42
+ private $chunkSize;
43
+
44
+ /** @var int $size */
45
+ private $size;
46
+
47
+ /** @var string $resumeUri */
48
+ private $resumeUri;
49
+
50
+ /** @var int $progress */
51
+ private $progress;
52
+
53
+ /** @var Google_Client */
54
+ private $client;
55
+
56
+ /** @var Google_Http_Request */
57
+ private $request;
58
+
59
+ /** @var string */
60
+ private $boundary;
61
+
62
+ /**
63
+ * Result code from last HTTP call
64
+ * @var int
65
+ */
66
+ private $httpResultCode;
67
+
68
+ /**
69
+ * @param $mimeType string
70
+ * @param $data string The bytes you want to upload.
71
+ * @param $resumable bool
72
+ * @param bool $chunkSize File will be uploaded in chunks of this many bytes.
73
+ * only used if resumable=True
74
+ */
75
+ public function __construct(
76
+ Google_Client $client,
77
+ Google_Http_Request $request,
78
+ $mimeType,
79
+ $data,
80
+ $resumable = false,
81
+ $chunkSize = false,
82
+ $boundary = false
83
+ ) {
84
+ $this->client = $client;
85
+ $this->request = $request;
86
+ $this->mimeType = $mimeType;
87
+ $this->data = $data;
88
+ $this->size = strlen($this->data);
89
+ $this->resumable = $resumable;
90
+ if (!$chunkSize) {
91
+ $chunkSize = 256 * 1024;
92
+ }
93
+ $this->chunkSize = $chunkSize;
94
+ $this->progress = 0;
95
+ $this->boundary = $boundary;
96
+
97
+ // Process Media Request
98
+ $this->process();
99
+ }
100
+
101
+ /**
102
+ * Set the size of the file that is being uploaded.
103
+ * @param $size - int file size in bytes
104
+ */
105
+ public function setFileSize($size)
106
+ {
107
+ $this->size = $size;
108
+ }
109
+
110
+ /**
111
+ * Return the progress on the upload
112
+ * @return int progress in bytes uploaded.
113
+ */
114
+ public function getProgress()
115
+ {
116
+ return $this->progress;
117
+ }
118
+
119
+ /**
120
+ * Return the HTTP result code from the last call made.
121
+ * @return int code
122
+ */
123
+ public function getHttpResultCode()
124
+ {
125
+ return $this->httpResultCode;
126
+ }
127
+
128
+ /**
129
+ * Sends a PUT-Request to google drive and parses the response,
130
+ * setting the appropiate variables from the response()
131
+ *
132
+ * @param Google_Http_Request $httpRequest the Reuqest which will be send
133
+ *
134
+ * @return false|mixed false when the upload is unfinished or the decoded http response
135
+ *
136
+ */
137
+ private function makePutRequest(Google_Http_Request $httpRequest)
138
+ {
139
+ if ($this->client->getClassConfig("Google_Http_Request", "enable_gzip_for_uploads")) {
140
+ $httpRequest->enableGzip();
141
+ } else {
142
+ $httpRequest->disableGzip();
143
+ }
144
+
145
+ $response = $this->client->getIo()->makeRequest($httpRequest);
146
+ $response->setExpectedClass($this->request->getExpectedClass());
147
+ $code = $response->getResponseHttpCode();
148
+ $this->httpResultCode = $code;
149
+
150
+ if (308 == $code) {
151
+ // Track the amount uploaded.
152
+ $range = explode('-', $response->getResponseHeader('range'));
153
+ $this->progress = $range[1] + 1;
154
+
155
+ // Allow for changing upload URLs.
156
+ $location = $response->getResponseHeader('location');
157
+ if ($location) {
158
+ $this->resumeUri = $location;
159
+ }
160
+
161
+ // No problems, but upload not complete.
162
+ return false;
163
+ } else {
164
+ return Google_Http_REST::decodeHttpResponse($response, $this->client);
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Send the next part of the file to upload.
170
+ * @param [$chunk] the next set of bytes to send. If false will used $data passed
171
+ * at construct time.
172
+ */
173
+ public function nextChunk($chunk = false)
174
+ {
175
+ if (false == $this->resumeUri) {
176
+ $this->resumeUri = $this->fetchResumeUri();
177
+ }
178
+
179
+ if (false == $chunk) {
180
+ $chunk = substr($this->data, $this->progress, $this->chunkSize);
181
+ }
182
+ $lastBytePos = $this->progress + strlen($chunk) - 1;
183
+ $headers = array(
184
+ 'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
185
+ 'content-type' => $this->request->getRequestHeader('content-type'),
186
+ 'content-length' => $this->chunkSize,
187
+ 'expect' => '',
188
+ );
189
+
190
+ $httpRequest = new Google_Http_Request(
191
+ $this->resumeUri,
192
+ 'PUT',
193
+ $headers,
194
+ $chunk
195
+ );
196
+ return $this->makePutRequest($httpRequest);
197
+ }
198
+
199
+ /**
200
+ * Resume a previously unfinished upload
201
+ * @param $resumeUri the resume-URI of the unfinished, resumable upload.
202
+ */
203
+ public function resume($resumeUri)
204
+ {
205
+ $this->resumeUri = $resumeUri;
206
+ $headers = array(
207
+ 'content-range' => "bytes */$this->size",
208
+ 'content-length' => 0,
209
+ );
210
+ $httpRequest = new Google_Http_Request(
211
+ $this->resumeUri,
212
+ 'PUT',
213
+ $headers
214
+ );
215
+ return $this->makePutRequest($httpRequest);
216
+ }
217
+
218
+ /**
219
+ * @return array|bool
220
+ * @visible for testing
221
+ */
222
+ private function process()
223
+ {
224
+ $postBody = false;
225
+ $contentType = false;
226
+
227
+ $meta = $this->request->getPostBody();
228
+ $meta = is_string($meta) ? json_decode($meta, true) : $meta;
229
+
230
+ $uploadType = $this->getUploadType($meta);
231
+ $this->request->setQueryParam('uploadType', $uploadType);
232
+ $this->transformToUploadUrl();
233
+ $mimeType = $this->mimeType ?
234
+ $this->mimeType :
235
+ $this->request->getRequestHeader('content-type');
236
+
237
+ if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
238
+ $contentType = $mimeType;
239
+ $postBody = is_string($meta) ? $meta : json_encode($meta);
240
+ } else if (self::UPLOAD_MEDIA_TYPE == $uploadType) {
241
+ $contentType = $mimeType;
242
+ $postBody = $this->data;
243
+ } else if (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
244
+ // This is a multipart/related upload.
245
+ $boundary = $this->boundary ? $this->boundary : mt_rand();
246
+ $boundary = str_replace('"', '', $boundary);
247
+ $contentType = 'multipart/related; boundary=' . $boundary;
248
+ $related = "--$boundary\r\n";
249
+ $related .= "Content-Type: application/json; charset=UTF-8\r\n";
250
+ $related .= "\r\n" . json_encode($meta) . "\r\n";
251
+ $related .= "--$boundary\r\n";
252
+ $related .= "Content-Type: $mimeType\r\n";
253
+ $related .= "Content-Transfer-Encoding: base64\r\n";
254
+ $related .= "\r\n" . base64_encode($this->data) . "\r\n";
255
+ $related .= "--$boundary--";
256
+ $postBody = $related;
257
+ }
258
+
259
+ $this->request->setPostBody($postBody);
260
+
261
+ if (isset($contentType) && $contentType) {
262
+ $contentTypeHeader['content-type'] = $contentType;
263
+ $this->request->setRequestHeaders($contentTypeHeader);
264
+ }
265
+ }
266
+
267
+ private function transformToUploadUrl()
268
+ {
269
+ $base = $this->request->getBaseComponent();
270
+ $this->request->setBaseComponent($base . '/upload');
271
+ }
272
+
273
+ /**
274
+ * Valid upload types:
275
+ * - resumable (UPLOAD_RESUMABLE_TYPE)
276
+ * - media (UPLOAD_MEDIA_TYPE)
277
+ * - multipart (UPLOAD_MULTIPART_TYPE)
278
+ * @param $meta
279
+ * @return string
280
+ * @visible for testing
281
+ */
282
+ public function getUploadType($meta)
283
+ {
284
+ if ($this->resumable) {
285
+ return self::UPLOAD_RESUMABLE_TYPE;
286
+ }
287
+
288
+ if (false == $meta && $this->data) {
289
+ return self::UPLOAD_MEDIA_TYPE;
290
+ }
291
+
292
+ return self::UPLOAD_MULTIPART_TYPE;
293
+ }
294
+
295
+ public function getResumeUri()
296
+ {
297
+ return ( $this->resumeUri !== null ? $this->resumeUri : $this->fetchResumeUri() );
298
+ }
299
+
300
+ private function fetchResumeUri()
301
+ {
302
+ $result = null;
303
+ $body = $this->request->getPostBody();
304
+ if ($body) {
305
+ $headers = array(
306
+ 'content-type' => 'application/json; charset=UTF-8',
307
+ 'content-length' => Google_Utils::getStrLen($body),
308
+ 'x-upload-content-type' => $this->mimeType,
309
+ 'x-upload-content-length' => $this->size,
310
+ 'expect' => '',
311
+ );
312
+ $this->request->setRequestHeaders($headers);
313
+ }
314
+
315
+ $response = $this->client->getIo()->makeRequest($this->request);
316
+ $location = $response->getResponseHeader('location');
317
+ $code = $response->getResponseHttpCode();
318
+
319
+ if (200 == $code && true == $location) {
320
+ return $location;
321
+ }
322
+ $message = $code;
323
+ $body = @json_decode($response->getResponseBody());
324
+ if (!empty($body->error->errors) ) {
325
+ $message .= ': ';
326
+ foreach ($body->error->errors as $error) {
327
+ $message .= "{$error->domain}, {$error->message};";
328
+ }
329
+ $message = rtrim($message, ';');
330
+ }
331
+
332
+ $error = "Failed to start the resumable upload (HTTP {$message})";
333
+ $this->client->getLogger()->error($error);
334
+ throw new Google_Exception($error);
335
+ }
336
+
337
+ public function setChunkSize($chunkSize)
338
+ {
339
+ $this->chunkSize = $chunkSize;
340
+ }
341
+ }
google/Http/REST.php CHANGED
@@ -1,178 +1,178 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * This class implements the RESTful transport of apiServiceRequest()'s
24
- */
25
- class Google_Http_REST
26
- {
27
- /**
28
- * Executes a Google_Http_Request and (if applicable) automatically retries
29
- * when errors occur.
30
- *
31
- * @param Google_Client $client
32
- * @param Google_Http_Request $req
33
- * @return array decoded result
34
- * @throws Google_Service_Exception on server side error (ie: not authenticated,
35
- * invalid or malformed post body, invalid url)
36
- */
37
- public static function execute(Google_Client $client, Google_Http_Request $req)
38
- {
39
- $runner = new Google_Task_Runner(
40
- $client,
41
- sprintf('%s %s', $req->getRequestMethod(), $req->getUrl()),
42
- array(get_class(), 'doExecute'),
43
- array($client, $req)
44
- );
45
-
46
- return $runner->run();
47
- }
48
-
49
- /**
50
- * Executes a Google_Http_Request
51
- *
52
- * @param Google_Client $client
53
- * @param Google_Http_Request $req
54
- * @return array decoded result
55
- * @throws Google_Service_Exception on server side error (ie: not authenticated,
56
- * invalid or malformed post body, invalid url)
57
- */
58
- public static function doExecute(Google_Client $client, Google_Http_Request $req)
59
- {
60
- $httpRequest = $client->getIo()->makeRequest($req);
61
- $httpRequest->setExpectedClass($req->getExpectedClass());
62
- return self::decodeHttpResponse($httpRequest, $client);
63
- }
64
-
65
- /**
66
- * Decode an HTTP Response.
67
- * @static
68
- * @throws Google_Service_Exception
69
- * @param Google_Http_Request $response The http response to be decoded.
70
- * @param Google_Client $client
71
- * @return mixed|null
72
- */
73
- public static function decodeHttpResponse($response, Google_Client $client = null)
74
- {
75
- $code = $response->getResponseHttpCode();
76
- $body = $response->getResponseBody();
77
- $decoded = null;
78
-
79
- if ((intVal($code)) >= 300) {
80
- $decoded = json_decode($body, true);
81
- $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
82
- if (isset($decoded['error']) &&
83
- isset($decoded['error']['message']) &&
84
- isset($decoded['error']['code'])) {
85
- // if we're getting a json encoded error definition, use that instead of the raw response
86
- // body for improved readability
87
- $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
88
- } else {
89
- $err .= ": ($code) $body";
90
- }
91
-
92
- $errors = null;
93
- // Specific check for APIs which don't return error details, such as Blogger.
94
- if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
95
- $errors = $decoded['error']['errors'];
96
- }
97
-
98
- $map = null;
99
- if ($client) {
100
- $client->getLogger()->error(
101
- $err,
102
- array('code' => $code, 'errors' => $errors)
103
- );
104
-
105
- $map = $client->getClassConfig(
106
- 'Google_Service_Exception',
107
- 'retry_map'
108
- );
109
- }
110
- throw new Google_Service_Exception($err, $code, null, $errors, $map);
111
- }
112
-
113
- // Only attempt to decode the response, if the response code wasn't (204) 'no content'
114
- if ($code != '204') {
115
- if ($response->getExpectedRaw()) {
116
- return $body;
117
- }
118
-
119
- $decoded = json_decode($body, true);
120
- if ($decoded === null || $decoded === "") {
121
- $error = "Invalid json in service response: $body";
122
- if ($client) {
123
- $client->getLogger()->error($error);
124
- }
125
- throw new Google_Service_Exception($error);
126
- }
127
-
128
- if ($response->getExpectedClass()) {
129
- $class = $response->getExpectedClass();
130
- $decoded = new $class($decoded);
131
- }
132
- }
133
- return $decoded;
134
- }
135
-
136
- /**
137
- * Parse/expand request parameters and create a fully qualified
138
- * request uri.
139
- * @static
140
- * @param string $servicePath
141
- * @param string $restPath
142
- * @param array $params
143
- * @return string $requestUrl
144
- */
145
- public static function createRequestUri($servicePath, $restPath, $params)
146
- {
147
- $requestUrl = $servicePath . $restPath;
148
- $uriTemplateVars = array();
149
- $queryVars = array();
150
- foreach ($params as $paramName => $paramSpec) {
151
- if ($paramSpec['type'] == 'boolean') {
152
- $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
153
- }
154
- if ($paramSpec['location'] == 'path') {
155
- $uriTemplateVars[$paramName] = $paramSpec['value'];
156
- } else if ($paramSpec['location'] == 'query') {
157
- if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
158
- foreach ($paramSpec['value'] as $value) {
159
- $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($value));
160
- }
161
- } else {
162
- $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($paramSpec['value']));
163
- }
164
- }
165
- }
166
-
167
- if (count($uriTemplateVars)) {
168
- $uriTemplateParser = new Google_Utils_URITemplate();
169
- $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
170
- }
171
-
172
- if (count($queryVars)) {
173
- $requestUrl .= '?' . implode($queryVars, '&');
174
- }
175
-
176
- return $requestUrl;
177
- }
178
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * This class implements the RESTful transport of apiServiceRequest()'s
24
+ */
25
+ class Google_Http_REST
26
+ {
27
+ /**
28
+ * Executes a Google_Http_Request and (if applicable) automatically retries
29
+ * when errors occur.
30
+ *
31
+ * @param Google_Client $client
32
+ * @param Google_Http_Request $req
33
+ * @return array decoded result
34
+ * @throws Google_Service_Exception on server side error (ie: not authenticated,
35
+ * invalid or malformed post body, invalid url)
36
+ */
37
+ public static function execute(Google_Client $client, Google_Http_Request $req)
38
+ {
39
+ $runner = new Google_Task_Runner(
40
+ $client,
41
+ sprintf('%s %s', $req->getRequestMethod(), $req->getUrl()),
42
+ array(get_class(), 'doExecute'),
43
+ array($client, $req)
44
+ );
45
+
46
+ return $runner->run();
47
+ }
48
+
49
+ /**
50
+ * Executes a Google_Http_Request
51
+ *
52
+ * @param Google_Client $client
53
+ * @param Google_Http_Request $req
54
+ * @return array decoded result
55
+ * @throws Google_Service_Exception on server side error (ie: not authenticated,
56
+ * invalid or malformed post body, invalid url)
57
+ */
58
+ public static function doExecute(Google_Client $client, Google_Http_Request $req)
59
+ {
60
+ $httpRequest = $client->getIo()->makeRequest($req);
61
+ $httpRequest->setExpectedClass($req->getExpectedClass());
62
+ return self::decodeHttpResponse($httpRequest, $client);
63
+ }
64
+
65
+ /**
66
+ * Decode an HTTP Response.
67
+ * @static
68
+ * @throws Google_Service_Exception
69
+ * @param Google_Http_Request $response The http response to be decoded.
70
+ * @param Google_Client $client
71
+ * @return mixed|null
72
+ */
73
+ public static function decodeHttpResponse($response, Google_Client $client = null)
74
+ {
75
+ $code = $response->getResponseHttpCode();
76
+ $body = $response->getResponseBody();
77
+ $decoded = null;
78
+
79
+ if ((intVal($code)) >= 300) {
80
+ $decoded = json_decode($body, true);
81
+ $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
82
+ if (isset($decoded['error']) &&
83
+ isset($decoded['error']['message']) &&
84
+ isset($decoded['error']['code'])) {
85
+ // if we're getting a json encoded error definition, use that instead of the raw response
86
+ // body for improved readability
87
+ $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
88
+ } else {
89
+ $err .= ": ($code) $body";
90
+ }
91
+
92
+ $errors = null;
93
+ // Specific check for APIs which don't return error details, such as Blogger.
94
+ if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
95
+ $errors = $decoded['error']['errors'];
96
+ }
97
+
98
+ $map = null;
99
+ if ($client) {
100
+ $client->getLogger()->error(
101
+ $err,
102
+ array('code' => $code, 'errors' => $errors)
103
+ );
104
+
105
+ $map = $client->getClassConfig(
106
+ 'Google_Service_Exception',
107
+ 'retry_map'
108
+ );
109
+ }
110
+ throw new Google_Service_Exception($err, $code, null, $errors, $map);
111
+ }
112
+
113
+ // Only attempt to decode the response, if the response code wasn't (204) 'no content'
114
+ if ($code != '204') {
115
+ if ($response->getExpectedRaw()) {
116
+ return $body;
117
+ }
118
+
119
+ $decoded = json_decode($body, true);
120
+ if ($decoded === null || $decoded === "") {
121
+ $error = "Invalid json in service response: $body";
122
+ if ($client) {
123
+ $client->getLogger()->error($error);
124
+ }
125
+ throw new Google_Service_Exception($error);
126
+ }
127
+
128
+ if ($response->getExpectedClass()) {
129
+ $class = $response->getExpectedClass();
130
+ $decoded = new $class($decoded);
131
+ }
132
+ }
133
+ return $decoded;
134
+ }
135
+
136
+ /**
137
+ * Parse/expand request parameters and create a fully qualified
138
+ * request uri.
139
+ * @static
140
+ * @param string $servicePath
141
+ * @param string $restPath
142
+ * @param array $params
143
+ * @return string $requestUrl
144
+ */
145
+ public static function createRequestUri($servicePath, $restPath, $params)
146
+ {
147
+ $requestUrl = $servicePath . $restPath;
148
+ $uriTemplateVars = array();
149
+ $queryVars = array();
150
+ foreach ($params as $paramName => $paramSpec) {
151
+ if ($paramSpec['type'] == 'boolean') {
152
+ $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
153
+ }
154
+ if ($paramSpec['location'] == 'path') {
155
+ $uriTemplateVars[$paramName] = $paramSpec['value'];
156
+ } else if ($paramSpec['location'] == 'query') {
157
+ if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
158
+ foreach ($paramSpec['value'] as $value) {
159
+ $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($value));
160
+ }
161
+ } else {
162
+ $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($paramSpec['value']));
163
+ }
164
+ }
165
+ }
166
+
167
+ if (count($uriTemplateVars)) {
168
+ $uriTemplateParser = new Google_Utils_URITemplate();
169
+ $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
170
+ }
171
+
172
+ if (count($queryVars)) {
173
+ $requestUrl .= '?' . implode($queryVars, '&');
174
+ }
175
+
176
+ return $requestUrl;
177
+ }
178
+ }
google/Http/Request.php CHANGED
@@ -1,504 +1,504 @@
1
- <?php
2
- /*
3
- * Copyright 2010 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- /**
23
- * HTTP Request to be executed by IO classes. Upon execution, the
24
- * responseHttpCode, responseHeaders and responseBody will be filled in.
25
- *
26
- * @author Chris Chabot <chabotc@google.com>
27
- * @author Chirag Shah <chirags@google.com>
28
- *
29
- */
30
- class Google_Http_Request
31
- {
32
- const GZIP_UA = " (gzip)";
33
-
34
- private $batchHeaders = array(
35
- 'Content-Type' => 'application/http',
36
- 'Content-Transfer-Encoding' => 'binary',
37
- 'MIME-Version' => '1.0',
38
- );
39
-
40
- protected $queryParams;
41
- protected $requestMethod;
42
- protected $requestHeaders;
43
- protected $baseComponent = null;
44
- protected $path;
45
- protected $postBody;
46
- protected $userAgent;
47
- protected $canGzip = null;
48
-
49
- protected $responseHttpCode;
50
- protected $responseHeaders;
51
- protected $responseBody;
52
-
53
- protected $expectedClass;
54
- protected $expectedRaw = false;
55
-
56
- public $accessKey;
57
-
58
- public function __construct(
59
- $url,
60
- $method = 'GET',
61
- $headers = array(),
62
- $postBody = null
63
- ) {
64
- $this->setUrl($url);
65
- $this->setRequestMethod($method);
66
- $this->setRequestHeaders($headers);
67
- $this->setPostBody($postBody);
68
- }
69
-
70
- /**
71
- * Misc function that returns the base url component of the $url
72
- * used by the OAuth signing class to calculate the base string
73
- * @return string The base url component of the $url.
74
- */
75
- public function getBaseComponent()
76
- {
77
- return $this->baseComponent;
78
- }
79
-
80
- /**
81
- * Set the base URL that path and query parameters will be added to.
82
- * @param $baseComponent string
83
- */
84
- public function setBaseComponent($baseComponent)
85
- {
86
- $this->baseComponent = rtrim($baseComponent, '/');
87
- }
88
-
89
- /**
90
- * Enable support for gzipped responses with this request.
91
- */
92
- public function enableGzip()
93
- {
94
- $this->setRequestHeaders(array("Accept-Encoding" => "gzip"));
95
- $this->canGzip = true;
96
- $this->setUserAgent($this->userAgent);
97
- }
98
-
99
- /**
100
- * Disable support for gzip responses with this request.
101
- */
102
- public function disableGzip()
103
- {
104
- if (
105
- isset($this->requestHeaders['accept-encoding']) &&
106
- $this->requestHeaders['accept-encoding'] == "gzip"
107
- ) {
108
- unset($this->requestHeaders['accept-encoding']);
109
- }
110
- $this->canGzip = false;
111
- $this->userAgent = str_replace(self::GZIP_UA, "", $this->userAgent);
112
- }
113
-
114
- /**
115
- * Can this request accept a gzip response?
116
- * @return bool
117
- */
118
- public function canGzip()
119
- {
120
- return $this->canGzip;
121
- }
122
-
123
- /**
124
- * Misc function that returns an array of the query parameters of the current
125
- * url used by the OAuth signing class to calculate the signature
126
- * @return array Query parameters in the query string.
127
- */
128
- public function getQueryParams()
129
- {
130
- return $this->queryParams;
131
- }
132
-
133
- /**
134
- * Set a new query parameter.
135
- * @param $key - string to set, does not need to be URL encoded
136
- * @param $value - string to set, does not need to be URL encoded
137
- */
138
- public function setQueryParam($key, $value)
139
- {
140
- $this->queryParams[$key] = $value;
141
- }
142
-
143
- /**
144
- * @return string HTTP Response Code.
145
- */
146
- public function getResponseHttpCode()
147
- {
148
- return (int) $this->responseHttpCode;
149
- }
150
-
151
- /**
152
- * @param int $responseHttpCode HTTP Response Code.
153
- */
154
- public function setResponseHttpCode($responseHttpCode)
155
- {
156
- $this->responseHttpCode = $responseHttpCode;
157
- }
158
-
159
- /**
160
- * @return $responseHeaders (array) HTTP Response Headers.
161
- */
162
- public function getResponseHeaders()
163
- {
164
- return $this->responseHeaders;
165
- }
166
-
167
- /**
168
- * @return string HTTP Response Body
169
- */
170
- public function getResponseBody()
171
- {
172
- return $this->responseBody;
173
- }
174
-
175
- /**
176
- * Set the class the response to this request should expect.
177
- *
178
- * @param $class string the class name
179
- */
180
- public function setExpectedClass($class)
181
- {
182
- $this->expectedClass = $class;
183
- }
184
-
185
- /**
186
- * Retrieve the expected class the response should expect.
187
- * @return string class name
188
- */
189
- public function getExpectedClass()
190
- {
191
- return $this->expectedClass;
192
- }
193
-
194
- /**
195
- * Enable expected raw response
196
- */
197
- public function enableExpectedRaw()
198
- {
199
- $this->expectedRaw = true;
200
- }
201
-
202
- /**
203
- * Disable expected raw response
204
- */
205
- public function disableExpectedRaw()
206
- {
207
- $this->expectedRaw = false;
208
- }
209
-
210
- /**
211
- * Expected raw response or not.
212
- * @return boolean expected raw response
213
- */
214
- public function getExpectedRaw()
215
- {
216
- return $this->expectedRaw;
217
- }
218
-
219
- /**
220
- * @param array $headers The HTTP response headers
221
- * to be normalized.
222
- */
223
- public function setResponseHeaders($headers)
224
- {
225
- $headers = Google_Utils::normalize($headers);
226
- if ($this->responseHeaders) {
227
- $headers = array_merge($this->responseHeaders, $headers);
228
- }
229
-
230
- $this->responseHeaders = $headers;
231
- }
232
-
233
- /**
234
- * @param string $key
235
- * @return array|boolean Returns the requested HTTP header or
236
- * false if unavailable.
237
- */
238
- public function getResponseHeader($key)
239
- {
240
- return isset($this->responseHeaders[$key])
241
- ? $this->responseHeaders[$key]
242
- : false;
243
- }
244
-
245
- /**
246
- * @param string $responseBody The HTTP response body.
247
- */
248
- public function setResponseBody($responseBody)
249
- {
250
- $this->responseBody = $responseBody;
251
- }
252
-
253
- /**
254
- * @return string $url The request URL.
255
- */
256
- public function getUrl()
257
- {
258
- return $this->baseComponent . $this->path .
259
- (count($this->queryParams) ?
260
- "?" . $this->buildQuery($this->queryParams) :
261
- '');
262
- }
263
-
264
- /**
265
- * @return string $method HTTP Request Method.
266
- */
267
- public function getRequestMethod()
268
- {
269
- return $this->requestMethod;
270
- }
271
-
272
- /**
273
- * @return array $headers HTTP Request Headers.
274
- */
275
- public function getRequestHeaders()
276
- {
277
- return $this->requestHeaders;
278
- }
279
-
280
- /**
281
- * @param string $key
282
- * @return array|boolean Returns the requested HTTP header or
283
- * false if unavailable.
284
- */
285
- public function getRequestHeader($key)
286
- {
287
- return isset($this->requestHeaders[$key])
288
- ? $this->requestHeaders[$key]
289
- : false;
290
- }
291
-
292
- /**
293
- * @return string $postBody HTTP Request Body.
294
- */
295
- public function getPostBody()
296
- {
297
- return $this->postBody;
298
- }
299
-
300
- /**
301
- * @param string $url the url to set
302
- */
303
- public function setUrl($url)
304
- {
305
- if (substr($url, 0, 4) != 'http') {
306
- // Force the path become relative.
307
- if (substr($url, 0, 1) !== '/') {
308
- $url = '/' . $url;
309
- }
310
- }
311
- $parts = parse_url($url);
312
- if (isset($parts['host'])) {
313
- $this->baseComponent = sprintf(
314
- "%s%s%s",
315
- isset($parts['scheme']) ? $parts['scheme'] . "://" : '',
316
- isset($parts['host']) ? $parts['host'] : '',
317
- isset($parts['port']) ? ":" . $parts['port'] : ''
318
- );
319
- }
320
- $this->path = isset($parts['path']) ? $parts['path'] : '';
321
- $this->queryParams = array();
322
- if (isset($parts['query'])) {
323
- $this->queryParams = $this->parseQuery($parts['query']);
324
- }
325
- }
326
-
327
- /**
328
- * @param string $method Set he HTTP Method and normalize
329
- * it to upper-case, as required by HTTP.
330
- *
331
- */
332
- public function setRequestMethod($method)
333
- {
334
- $this->requestMethod = strtoupper($method);
335
- }
336
-
337
- /**
338
- * @param array $headers The HTTP request headers
339
- * to be set and normalized.
340
- */
341
- public function setRequestHeaders($headers)
342
- {
343
- $headers = Google_Utils::normalize($headers);
344
- if ($this->requestHeaders) {
345
- $headers = array_merge($this->requestHeaders, $headers);
346
- }
347
- $this->requestHeaders = $headers;
348
- }
349
-
350
- /**
351
- * @param string $postBody the postBody to set
352
- */
353
- public function setPostBody($postBody)
354
- {
355
- $this->postBody = $postBody;
356
- }
357
-
358
- /**
359
- * Set the User-Agent Header.
360
- * @param string $userAgent The User-Agent.
361
- */
362
- public function setUserAgent($userAgent)
363
- {
364
- $this->userAgent = $userAgent;
365
- if ($this->canGzip) {
366
- $this->userAgent = $userAgent . self::GZIP_UA;
367
- }
368
- }
369
-
370
- /**
371
- * @return string The User-Agent.
372
- */
373
- public function getUserAgent()
374
- {
375
- return $this->userAgent;
376
- }
377
-
378
- /**
379
- * Returns a cache key depending on if this was an OAuth signed request
380
- * in which case it will use the non-signed url and access key to make this
381
- * cache key unique per authenticated user, else use the plain request url
382
- * @return string The md5 hash of the request cache key.
383
- */
384
- public function getCacheKey()
385
- {
386
- $key = $this->getUrl();
387
-
388
- if (isset($this->accessKey)) {
389
- $key .= $this->accessKey;
390
- }
391
-
392
- if (isset($this->requestHeaders['authorization'])) {
393
- $key .= $this->requestHeaders['authorization'];
394
- }
395
-
396
- return md5($key);
397
- }
398
-
399
- public function getParsedCacheControl()
400
- {
401
- $parsed = array();
402
- $rawCacheControl = $this->getResponseHeader('cache-control');
403
- if ($rawCacheControl) {
404
- $rawCacheControl = str_replace(', ', '&', $rawCacheControl);
405
- parse_str($rawCacheControl, $parsed);
406
- }
407
-
408
- return $parsed;
409
- }
410
-
411
- /**
412
- * @param string $id
413
- * @return string A string representation of the HTTP Request.
414
- */
415
- public function toBatchString($id)
416
- {
417
- $str = '';
418
- $path = parse_url($this->getUrl(), PHP_URL_PATH) . "?" .
419
- http_build_query($this->queryParams);
420
- $str .= $this->getRequestMethod() . ' ' . $path . " HTTP/1.1\n";
421
-
422
- foreach ($this->getRequestHeaders() as $key => $val) {
423
- $str .= $key . ': ' . $val . "\n";
424
- }
425
-
426
- if ($this->getPostBody()) {
427
- $str .= "\n";
428
- $str .= $this->getPostBody();
429
- }
430
-
431
- $headers = '';
432
- foreach ($this->batchHeaders as $key => $val) {
433
- $headers .= $key . ': ' . $val . "\n";
434
- }
435
-
436
- $headers .= "Content-ID: $id\n";
437
- $str = $headers . "\n" . $str;
438
-
439
- return $str;
440
- }
441
-
442
- /**
443
- * Our own version of parse_str that allows for multiple variables
444
- * with the same name.
445
- * @param $string - the query string to parse
446
- */
447
- private function parseQuery($string)
448
- {
449
- $return = array();
450
- $parts = explode("&", $string);
451
- foreach ($parts as $part) {
452
- list($key, $value) = explode('=', $part, 2);
453
- $value = urldecode($value);
454
- if (isset($return[$key])) {
455
- if (!is_array($return[$key])) {
456
- $return[$key] = array($return[$key]);
457
- }
458
- $return[$key][] = $value;
459
- } else {
460
- $return[$key] = $value;
461
- }
462
- }
463
- return $return;
464
- }
465
-
466
- /**
467
- * A version of build query that allows for multiple
468
- * duplicate keys.
469
- * @param $parts array of key value pairs
470
- */
471
- private function buildQuery($parts)
472
- {
473
- $return = array();
474
- foreach ($parts as $key => $value) {
475
- if (is_array($value)) {
476
- foreach ($value as $v) {
477
- $return[] = urlencode($key) . "=" . urlencode($v);
478
- }
479
- } else {
480
- $return[] = urlencode($key) . "=" . urlencode($value);
481
- }
482
- }
483
- return implode('&', $return);
484
- }
485
-
486
- /**
487
- * If we're POSTing and have no body to send, we can send the query
488
- * parameters in there, which avoids length issues with longer query
489
- * params.
490
- */
491
- public function maybeMoveParametersToBody()
492
- {
493
- if ($this->getRequestMethod() == "POST" && empty($this->postBody)) {
494
- $this->setRequestHeaders(
495
- array(
496
- "content-type" =>
497
- "application/x-www-form-urlencoded; charset=UTF-8"
498
- )
499
- );
500
- $this->setPostBody($this->buildQuery($this->queryParams));
501
- $this->queryParams = array();
502
- }
503
- }
504
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2010 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ /**
23
+ * HTTP Request to be executed by IO classes. Upon execution, the
24
+ * responseHttpCode, responseHeaders and responseBody will be filled in.
25
+ *
26
+ * @author Chris Chabot <chabotc@google.com>
27
+ * @author Chirag Shah <chirags@google.com>
28
+ *
29
+ */
30
+ class Google_Http_Request
31
+ {
32
+ const GZIP_UA = " (gzip)";
33
+
34
+ private $batchHeaders = array(
35
+ 'Content-Type' => 'application/http',
36
+ 'Content-Transfer-Encoding' => 'binary',
37
+ 'MIME-Version' => '1.0',
38
+ );
39
+
40
+ protected $queryParams;
41
+ protected $requestMethod;
42
+ protected $requestHeaders;
43
+ protected $baseComponent = null;
44
+ protected $path;
45
+ protected $postBody;
46
+ protected $userAgent;
47
+ protected $canGzip = null;
48
+
49
+ protected $responseHttpCode;
50
+ protected $responseHeaders;
51
+ protected $responseBody;
52
+
53
+ protected $expectedClass;
54
+ protected $expectedRaw = false;
55
+
56
+ public $accessKey;
57
+
58
+ public function __construct(
59
+ $url,
60
+ $method = 'GET',
61
+ $headers = array(),
62
+ $postBody = null
63
+ ) {
64
+ $this->setUrl($url);
65
+ $this->setRequestMethod($method);
66
+ $this->setRequestHeaders($headers);
67
+ $this->setPostBody($postBody);
68
+ }
69
+
70
+ /**
71
+ * Misc function that returns the base url component of the $url
72
+ * used by the OAuth signing class to calculate the base string
73
+ * @return string The base url component of the $url.
74
+ */
75
+ public function getBaseComponent()
76
+ {
77
+ return $this->baseComponent;
78
+ }
79
+
80
+ /**
81
+ * Set the base URL that path and query parameters will be added to.
82
+ * @param $baseComponent string
83
+ */
84
+ public function setBaseComponent($baseComponent)
85
+ {
86
+ $this->baseComponent = rtrim($baseComponent, '/');
87
+ }
88
+
89
+ /**
90
+ * Enable support for gzipped responses with this request.
91
+ */
92
+ public function enableGzip()
93
+ {
94
+ $this->setRequestHeaders(array("Accept-Encoding" => "gzip"));
95
+ $this->canGzip = true;
96
+ $this->setUserAgent($this->userAgent);
97
+ }
98
+
99
+ /**
100
+ * Disable support for gzip responses with this request.
101
+ */
102
+ public function disableGzip()
103
+ {
104
+ if (
105
+ isset($this->requestHeaders['accept-encoding']) &&
106
+ $this->requestHeaders['accept-encoding'] == "gzip"
107
+ ) {
108
+ unset($this->requestHeaders['accept-encoding']);
109
+ }
110
+ $this->canGzip = false;
111
+ $this->userAgent = str_replace(self::GZIP_UA, "", $this->userAgent);
112
+ }
113
+
114
+ /**
115
+ * Can this request accept a gzip response?
116
+ * @return bool
117
+ */
118
+ public function canGzip()
119
+ {
120
+ return $this->canGzip;
121
+ }
122
+
123
+ /**
124
+ * Misc function that returns an array of the query parameters of the current
125
+ * url used by the OAuth signing class to calculate the signature
126
+ * @return array Query parameters in the query string.
127
+ */
128
+ public function getQueryParams()
129
+ {
130
+ return $this->queryParams;
131
+ }
132
+
133
+ /**
134
+ * Set a new query parameter.
135
+ * @param $key - string to set, does not need to be URL encoded
136
+ * @param $value - string to set, does not need to be URL encoded
137
+ */
138
+ public function setQueryParam($key, $value)
139
+ {
140
+ $this->queryParams[$key] = $value;
141
+ }
142
+
143
+ /**
144
+ * @return string HTTP Response Code.
145
+ */
146
+ public function getResponseHttpCode()
147
+ {
148
+ return (int) $this->responseHttpCode;
149
+ }
150
+
151
+ /**
152
+ * @param int $responseHttpCode HTTP Response Code.
153
+ */
154
+ public function setResponseHttpCode($responseHttpCode)
155
+ {
156
+ $this->responseHttpCode = $responseHttpCode;
157
+ }
158
+
159
+ /**
160
+ * @return $responseHeaders (array) HTTP Response Headers.
161
+ */
162
+ public function getResponseHeaders()
163
+ {
164
+ return $this->responseHeaders;
165
+ }
166
+
167
+ /**
168
+ * @return string HTTP Response Body
169
+ */
170
+ public function getResponseBody()
171
+ {
172
+ return $this->responseBody;
173
+ }
174
+
175
+ /**
176
+ * Set the class the response to this request should expect.
177
+ *
178
+ * @param $class string the class name
179
+ */
180
+ public function setExpectedClass($class)
181
+ {
182
+ $this->expectedClass = $class;
183
+ }
184
+
185
+ /**
186
+ * Retrieve the expected class the response should expect.
187
+ * @return string class name
188
+ */
189
+ public function getExpectedClass()
190
+ {
191
+ return $this->expectedClass;
192
+ }
193
+
194
+ /**
195
+ * Enable expected raw response
196
+ */
197
+ public function enableExpectedRaw()
198
+ {
199
+ $this->expectedRaw = true;
200
+ }
201
+
202
+ /**
203
+ * Disable expected raw response
204
+ */
205
+ public function disableExpectedRaw()
206
+ {
207
+ $this->expectedRaw = false;
208
+ }
209
+
210
+ /**
211
+ * Expected raw response or not.
212
+ * @return boolean expected raw response
213
+ */
214
+ public function getExpectedRaw()
215
+ {
216
+ return $this->expectedRaw;
217
+ }
218
+
219
+ /**
220
+ * @param array $headers The HTTP response headers
221
+ * to be normalized.
222
+ */
223
+ public function setResponseHeaders($headers)
224
+ {
225
+ $headers = Google_Utils::normalize($headers);
226
+ if ($this->responseHeaders) {
227
+ $headers = array_merge($this->responseHeaders, $headers);
228
+ }
229
+
230
+ $this->responseHeaders = $headers;
231
+ }
232
+
233
+ /**
234
+ * @param string $key
235
+ * @return array|boolean Returns the requested HTTP header or
236
+ * false if unavailable.
237
+ */
238
+ public function getResponseHeader($key)
239
+ {
240
+ return isset($this->responseHeaders[$key])
241
+ ? $this->responseHeaders[$key]
242
+ : false;
243
+ }
244
+
245
+ /**
246
+ * @param string $responseBody The HTTP response body.
247
+ */
248
+ public function setResponseBody($responseBody)
249
+ {
250
+ $this->responseBody = $responseBody;
251
+ }
252
+
253
+ /**
254
+ * @return string $url The request URL.
255
+ */
256
+ public function getUrl()
257
+ {
258
+ return $this->baseComponent . $this->path .
259
+ (count($this->queryParams) ?
260
+ "?" . $this->buildQuery($this->queryParams) :
261
+ '');
262
+ }
263
+
264
+ /**
265
+ * @return string $method HTTP Request Method.
266
+ */
267
+ public function getRequestMethod()
268
+ {
269
+ return $this->requestMethod;
270
+ }
271
+
272
+ /**
273
+ * @return array $headers HTTP Request Headers.
274
+ */
275
+ public function getRequestHeaders()
276
+ {
277
+ return $this->requestHeaders;
278
+ }
279
+
280
+ /**
281
+ * @param string $key
282
+ * @return array|boolean Returns the requested HTTP header or
283
+ * false if unavailable.
284
+ */
285
+ public function getRequestHeader($key)
286
+ {
287
+ return isset($this->requestHeaders[$key])
288
+ ? $this->requestHeaders[$key]
289
+ : false;
290
+ }
291
+
292
+ /**
293
+ * @return string $postBody HTTP Request Body.
294
+ */
295
+ public function getPostBody()
296
+ {
297
+ return $this->postBody;
298
+ }
299
+
300
+ /**
301
+ * @param string $url the url to set
302
+ */
303
+ public function setUrl($url)
304
+ {
305
+ if (substr($url, 0, 4) != 'http') {
306
+ // Force the path become relative.
307
+ if (substr($url, 0, 1) !== '/') {
308
+ $url = '/' . $url;
309
+ }
310
+ }
311
+ $parts = parse_url($url);
312
+ if (isset($parts['host'])) {
313
+ $this->baseComponent = sprintf(
314
+ "%s%s%s",
315
+ isset($parts['scheme']) ? $parts['scheme'] . "://" : '',
316
+ isset($parts['host']) ? $parts['host'] : '',
317
+ isset($parts['port']) ? ":" . $parts['port'] : ''
318
+ );
319
+ }
320
+ $this->path = isset($parts['path']) ? $parts['path'] : '';
321
+ $this->queryParams = array();
322
+ if (isset($parts['query'])) {
323
+ $this->queryParams = $this->parseQuery($parts['query']);
324
+ }
325
+ }
326
+
327
+ /**
328
+ * @param string $method Set he HTTP Method and normalize
329
+ * it to upper-case, as required by HTTP.
330
+ *
331
+ */
332
+ public function setRequestMethod($method)
333
+ {
334
+ $this->requestMethod = strtoupper($method);
335
+ }
336
+
337
+ /**
338
+ * @param array $headers The HTTP request headers
339
+ * to be set and normalized.
340
+ */
341
+ public function setRequestHeaders($headers)
342
+ {
343
+ $headers = Google_Utils::normalize($headers);
344
+ if ($this->requestHeaders) {
345
+ $headers = array_merge($this->requestHeaders, $headers);
346
+ }
347
+ $this->requestHeaders = $headers;
348
+ }
349
+
350
+ /**
351
+ * @param string $postBody the postBody to set
352
+ */
353
+ public function setPostBody($postBody)
354
+ {
355
+ $this->postBody = $postBody;
356
+ }
357
+
358
+ /**
359
+ * Set the User-Agent Header.
360
+ * @param string $userAgent The User-Agent.
361
+ */
362
+ public function setUserAgent($userAgent)
363
+ {
364
+ $this->userAgent = $userAgent;
365
+ if ($this->canGzip) {
366
+ $this->userAgent = $userAgent . self::GZIP_UA;
367
+ }
368
+ }
369
+
370
+ /**
371
+ * @return string The User-Agent.
372
+ */
373
+ public function getUserAgent()
374
+ {
375
+ return $this->userAgent;
376
+ }
377
+
378
+ /**
379
+ * Returns a cache key depending on if this was an OAuth signed request
380
+ * in which case it will use the non-signed url and access key to make this
381
+ * cache key unique per authenticated user, else use the plain request url
382
+ * @return string The md5 hash of the request cache key.
383
+ */
384
+ public function getCacheKey()
385
+ {
386
+ $key = $this->getUrl();
387
+
388
+ if (isset($this->accessKey)) {
389
+ $key .= $this->accessKey;
390
+ }
391
+
392
+ if (isset($this->requestHeaders['authorization'])) {
393
+ $key .= $this->requestHeaders['authorization'];
394
+ }
395
+
396
+ return md5($key);
397
+ }
398
+
399
+ public function getParsedCacheControl()
400
+ {
401
+ $parsed = array();
402
+ $rawCacheControl = $this->getResponseHeader('cache-control');
403
+ if ($rawCacheControl) {
404
+ $rawCacheControl = str_replace(', ', '&', $rawCacheControl);
405
+ parse_str($rawCacheControl, $parsed);
406
+ }
407
+
408
+ return $parsed;
409
+ }
410
+
411
+ /**
412
+ * @param string $id
413
+ * @return string A string representation of the HTTP Request.
414
+ */
415
+ public function toBatchString($id)
416
+ {
417
+ $str = '';
418
+ $path = parse_url($this->getUrl(), PHP_URL_PATH) . "?" .
419
+ http_build_query($this->queryParams);
420
+ $str .= $this->getRequestMethod() . ' ' . $path . " HTTP/1.1\n";
421
+
422
+ foreach ($this->getRequestHeaders() as $key => $val) {
423
+ $str .= $key . ': ' . $val . "\n";
424
+ }
425
+
426
+ if ($this->getPostBody()) {
427
+ $str .= "\n";
428
+ $str .= $this->getPostBody();
429
+ }
430
+
431
+ $headers = '';
432
+ foreach ($this->batchHeaders as $key => $val) {
433
+ $headers .= $key . ': ' . $val . "\n";
434
+ }
435
+
436
+ $headers .= "Content-ID: $id\n";
437
+ $str = $headers . "\n" . $str;
438
+
439
+ return $str;
440
+ }
441
+
442
+ /**
443
+ * Our own version of parse_str that allows for multiple variables
444
+ * with the same name.
445
+ * @param $string - the query string to parse
446
+ */
447
+ private function parseQuery($string)
448
+ {
449
+ $return = array();
450
+ $parts = explode("&", $string);
451
+ foreach ($parts as $part) {
452
+ list($key, $value) = explode('=', $part, 2);
453
+ $value = urldecode($value);
454
+ if (isset($return[$key])) {
455
+ if (!is_array($return[$key])) {
456
+ $return[$key] = array($return[$key]);
457
+ }
458
+ $return[$key][] = $value;
459
+ } else {
460
+ $return[$key] = $value;
461
+ }
462
+ }
463
+ return $return;
464
+ }
465
+
466
+ /**
467
+ * A version of build query that allows for multiple
468
+ * duplicate keys.
469
+ * @param $parts array of key value pairs
470
+ */
471
+ private function buildQuery($parts)
472
+ {
473
+ $return = array();
474
+ foreach ($parts as $key => $value) {
475
+ if (is_array($value)) {
476
+ foreach ($value as $v) {
477
+ $return[] = urlencode($key) . "=" . urlencode($v);
478
+ }
479
+ } else {
480
+ $return[] = urlencode($key) . "=" . urlencode($value);
481
+ }
482
+ }
483
+ return implode('&', $return);
484
+ }
485
+
486
+ /**
487
+ * If we're POSTing and have no body to send, we can send the query
488
+ * parameters in there, which avoids length issues with longer query
489
+ * params.
490
+ */
491
+ public function maybeMoveParametersToBody()
492
+ {
493
+ if ($this->getRequestMethod() == "POST" && empty($this->postBody)) {
494
+ $this->setRequestHeaders(
495
+ array(
496
+ "content-type" =>
497
+ "application/x-www-form-urlencoded; charset=UTF-8"
498
+ )
499
+ );
500
+ $this->setPostBody($this->buildQuery($this->queryParams));
501
+ $this->queryParams = array();
502
+ }
503
+ }
504
+ }
google/IO/Abstract.php CHANGED
@@ -1,339 +1,339 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * Abstract IO base class
20
- */
21
-
22
- if (!class_exists('Google_Client')) {
23
- require_once dirname(__FILE__) . '/../autoload.php';
24
- }
25
-
26
- abstract class Google_IO_Abstract
27
- {
28
- const UNKNOWN_CODE = 0;
29
- const FORM_URLENCODED = 'application/x-www-form-urlencoded';
30
- private static $CONNECTION_ESTABLISHED_HEADERS = array(
31
- "HTTP/1.0 200 Connection established\r\n\r\n",
32
- "HTTP/1.1 200 Connection established\r\n\r\n",
33
- );
34
- private static $ENTITY_HTTP_METHODS = array("POST" => null, "PUT" => null);
35
- private static $HOP_BY_HOP = array(
36
- 'connection' => true,
37
- 'keep-alive' => true,
38
- 'proxy-authenticate' => true,
39
- 'proxy-authorization' => true,
40
- 'te' => true,
41
- 'trailers' => true,
42
- 'transfer-encoding' => true,
43
- 'upgrade' => true
44
- );
45
-
46
-
47
- /** @var Google_Client */
48
- protected $client;
49
-
50
- public function __construct(Google_Client $client)
51
- {
52
- $this->client = $client;
53
- $timeout = $client->getClassConfig('Google_IO_Abstract', 'request_timeout_seconds');
54
- if ($timeout > 0) {
55
- $this->setTimeout($timeout);
56
- }
57
- }
58
-
59
- /**
60
- * Executes a Google_Http_Request
61
- * @param Google_Http_Request $request the http request to be executed
62
- * @return array containing response headers, body, and http code
63
- * @throws Google_IO_Exception on curl or IO error
64
- */
65
- abstract public function executeRequest(Google_Http_Request $request);
66
-
67
- /**
68
- * Set options that update the transport implementation's behavior.
69
- * @param $options
70
- */
71
- abstract public function setOptions($options);
72
-
73
- /**
74
- * Set the maximum request time in seconds.
75
- * @param $timeout in seconds
76
- */
77
- abstract public function setTimeout($timeout);
78
-
79
- /**
80
- * Get the maximum request time in seconds.
81
- * @return timeout in seconds
82
- */
83
- abstract public function getTimeout();
84
-
85
- /**
86
- * Test for the presence of a cURL header processing bug
87
- *
88
- * The cURL bug was present in versions prior to 7.30.0 and caused the header
89
- * length to be miscalculated when a "Connection established" header added by
90
- * some proxies was present.
91
- *
92
- * @return boolean
93
- */
94
- abstract protected function needsQuirk();
95
-
96
- /**
97
- * @visible for testing.
98
- * Cache the response to an HTTP request if it is cacheable.
99
- * @param Google_Http_Request $request
100
- * @return bool Returns true if the insertion was successful.
101
- * Otherwise, return false.
102
- */
103
- public function setCachedRequest(Google_Http_Request $request)
104
- {
105
- // Determine if the request is cacheable.
106
- if (Google_Http_CacheParser::isResponseCacheable($request)) {
107
- $this->client->getCache()->set($request->getCacheKey(), $request);
108
- return true;
109
- }
110
-
111
- return false;
112
- }
113
-
114
- /**
115
- * Execute an HTTP Request
116
- *
117
- * @param Google_Http_Request $request the http request to be executed
118
- * @return Google_Http_Request http request with the response http code,
119
- * response headers and response body filled in
120
- * @throws Google_IO_Exception on curl or IO error
121
- */
122
- public function makeRequest(Google_Http_Request $request)
123
- {
124
- // First, check to see if we have a valid cached version.
125
- $cached = $this->getCachedRequest($request);
126
- if ($cached !== false && $cached instanceof Google_Http_Request) {
127
- if (!$this->checkMustRevalidateCachedRequest($cached, $request)) {
128
- return $cached;
129
- }
130
- }
131
-
132
- if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
133
- $request = $this->processEntityRequest($request);
134
- }
135
-
136
- list($responseData, $responseHeaders, $respHttpCode) = $this->executeRequest($request);
137
-
138
- if ($respHttpCode == 304 && $cached) {
139
- // If the server responded NOT_MODIFIED, return the cached request.
140
- $this->updateCachedRequest($cached, $responseHeaders);
141
- return $cached;
142
- }
143
-
144
- if (!isset($responseHeaders['Date']) && !isset($responseHeaders['date'])) {
145
- $responseHeaders['date'] = date("r");
146
- }
147
-
148
- $request->setResponseHttpCode($respHttpCode);
149
- $request->setResponseHeaders($responseHeaders);
150
- $request->setResponseBody($responseData);
151
- // Store the request in cache (the function checks to see if the request
152
- // can actually be cached)
153
- $this->setCachedRequest($request);
154
- return $request;
155
- }
156
-
157
- /**
158
- * @visible for testing.
159
- * @param Google_Http_Request $request
160
- * @return Google_Http_Request|bool Returns the cached object or
161
- * false if the operation was unsuccessful.
162
- */
163
- public function getCachedRequest(Google_Http_Request $request)
164
- {
165
- if (false === Google_Http_CacheParser::isRequestCacheable($request)) {
166
- return false;
167
- }
168
-
169
- return $this->client->getCache()->get($request->getCacheKey());
170
- }
171
-
172
- /**
173
- * @visible for testing
174
- * Process an http request that contains an enclosed entity.
175
- * @param Google_Http_Request $request
176
- * @return Google_Http_Request Processed request with the enclosed entity.
177
- */
178
- public function processEntityRequest(Google_Http_Request $request)
179
- {
180
- $postBody = $request->getPostBody();
181
- $contentType = $request->getRequestHeader("content-type");
182
-
183
- // Set the default content-type as application/x-www-form-urlencoded.
184
- if (false == $contentType) {
185
- $contentType = self::FORM_URLENCODED;
186
- $request->setRequestHeaders(array('content-type' => $contentType));
187
- }
188
-
189
- // Force the payload to match the content-type asserted in the header.
190
- if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
191
- $postBody = http_build_query($postBody, '', '&');
192
- $request->setPostBody($postBody);
193
- }
194
-
195
- // Make sure the content-length header is set.
196
- if (!$postBody || is_string($postBody)) {
197
- $postsLength = strlen($postBody);
198
- $request->setRequestHeaders(array('content-length' => $postsLength));
199
- }
200
-
201
- return $request;
202
- }
203
-
204
- /**
205
- * Check if an already cached request must be revalidated, and if so update
206
- * the request with the correct ETag headers.
207
- * @param Google_Http_Request $cached A previously cached response.
208
- * @param Google_Http_Request $request The outbound request.
209
- * return bool If the cached object needs to be revalidated, false if it is
210
- * still current and can be re-used.
211
- */
212
- protected function checkMustRevalidateCachedRequest($cached, $request)
213
- {
214
- if (Google_Http_CacheParser::mustRevalidate($cached)) {
215
- $addHeaders = array();
216
- if ($cached->getResponseHeader('etag')) {
217
- // [13.3.4] If an entity tag has been provided by the origin server,
218
- // we must use that entity tag in any cache-conditional request.
219
- $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
220
- } elseif ($cached->getResponseHeader('date')) {
221
- $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
222
- }
223
-
224
- $request->setRequestHeaders($addHeaders);
225
- return true;
226
- } else {
227
- return false;
228
- }
229
- }
230
-
231
- /**
232
- * Update a cached request, using the headers from the last response.
233
- * @param Google_Http_Request $cached A previously cached response.
234
- * @param mixed Associative array of response headers from the last request.
235
- */
236
- protected function updateCachedRequest($cached, $responseHeaders)
237
- {
238
- $hopByHop = self::$HOP_BY_HOP;
239
- if (!empty($responseHeaders['connection'])) {
240
- $connectionHeaders = array_map(
241
- 'strtolower',
242
- array_filter(
243
- array_map('trim', explode(',', $responseHeaders['connection']))
244
- )
245
- );
246
- $hopByHop += array_fill_keys($connectionHeaders, true);
247
- }
248
-
249
- $endToEnd = array_diff_key($responseHeaders, $hopByHop);
250
- $cached->setResponseHeaders($endToEnd);
251
- }
252
-
253
- /**
254
- * Used by the IO lib and also the batch processing.
255
- *
256
- * @param $respData
257
- * @param $headerSize
258
- * @return array
259
- */
260
- public function parseHttpResponse($respData, $headerSize)
261
- {
262
- // check proxy header
263
- foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) {
264
- if (stripos($respData, $established_header) !== false) {
265
- // existed, remove it
266
- $respData = str_ireplace($established_header, '', $respData);
267
- // Subtract the proxy header size unless the cURL bug prior to 7.30.0
268
- // is present which prevented the proxy header size from being taken into
269
- // account.
270
- if (!$this->needsQuirk()) {
271
- $headerSize -= strlen($established_header);
272
- }
273
- break;
274
- }
275
- }
276
-
277
- if ($headerSize) {
278
- $responseBody = substr($respData, $headerSize);
279
- $responseHeaders = substr($respData, 0, $headerSize);
280
- } else {
281
- $responseSegments = explode("\r\n\r\n", $respData, 2);
282
- $responseHeaders = $responseSegments[0];
283
- $responseBody = isset($responseSegments[1]) ? $responseSegments[1] :
284
- null;
285
- }
286
-
287
- $responseHeaders = $this->getHttpResponseHeaders($responseHeaders);
288
- return array($responseHeaders, $responseBody);
289
- }
290
-
291
- /**
292
- * Parse out headers from raw headers
293
- * @param rawHeaders array or string
294
- * @return array
295
- */
296
- public function getHttpResponseHeaders($rawHeaders)
297
- {
298
- if (is_array($rawHeaders)) {
299
- return $this->parseArrayHeaders($rawHeaders);
300
- } else {
301
- return $this->parseStringHeaders($rawHeaders);
302
- }
303
- }
304
-
305
- private function parseStringHeaders($rawHeaders)
306
- {
307
- $headers = array();
308
- $responseHeaderLines = explode("\r\n", $rawHeaders);
309
- foreach ($responseHeaderLines as $headerLine) {
310
- if ($headerLine && strpos($headerLine, ':') !== false) {
311
- list($header, $value) = explode(': ', $headerLine, 2);
312
- $header = strtolower($header);
313
- if (isset($headers[$header])) {
314
- $headers[$header] .= "\n" . $value;
315
- } else {
316
- $headers[$header] = $value;
317
- }
318
- }
319
- }
320
- return $headers;
321
- }
322
-
323
- private function parseArrayHeaders($rawHeaders)
324
- {
325
- $header_count = count($rawHeaders);
326
- $headers = array();
327
-
328
- for ($i = 0; $i < $header_count; $i++) {
329
- $header = $rawHeaders[$i];
330
- // Times will have colons in - so we just want the first match.
331
- $header_parts = explode(': ', $header, 2);
332
- if (count($header_parts) == 2) {
333
- $headers[strtolower($header_parts[0])] = $header_parts[1];
334
- }
335
- }
336
-
337
- return $headers;
338
- }
339
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * Abstract IO base class
20
+ */
21
+
22
+ if (!class_exists('Google_Client')) {
23
+ require_once dirname(__FILE__) . '/../autoload.php';
24
+ }
25
+
26
+ abstract class Google_IO_Abstract
27
+ {
28
+ const UNKNOWN_CODE = 0;
29
+ const FORM_URLENCODED = 'application/x-www-form-urlencoded';
30
+ private static $CONNECTION_ESTABLISHED_HEADERS = array(
31
+ "HTTP/1.0 200 Connection established\r\n\r\n",
32
+ "HTTP/1.1 200 Connection established\r\n\r\n",
33
+ );
34
+ private static $ENTITY_HTTP_METHODS = array("POST" => null, "PUT" => null);
35
+ private static $HOP_BY_HOP = array(
36
+ 'connection' => true,
37
+ 'keep-alive' => true,
38
+ 'proxy-authenticate' => true,
39
+ 'proxy-authorization' => true,
40
+ 'te' => true,
41
+ 'trailers' => true,
42
+ 'transfer-encoding' => true,
43
+ 'upgrade' => true
44
+ );
45
+
46
+
47
+ /** @var Google_Client */
48
+ protected $client;
49
+
50
+ public function __construct(Google_Client $client)
51
+ {
52
+ $this->client = $client;
53
+ $timeout = $client->getClassConfig('Google_IO_Abstract', 'request_timeout_seconds');
54
+ if ($timeout > 0) {
55
+ $this->setTimeout($timeout);
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Executes a Google_Http_Request
61
+ * @param Google_Http_Request $request the http request to be executed
62
+ * @return array containing response headers, body, and http code
63
+ * @throws Google_IO_Exception on curl or IO error
64
+ */
65
+ abstract public function executeRequest(Google_Http_Request $request);
66
+
67
+ /**
68
+ * Set options that update the transport implementation's behavior.
69
+ * @param $options
70
+ */
71
+ abstract public function setOptions($options);
72
+
73
+ /**
74
+ * Set the maximum request time in seconds.
75
+ * @param $timeout in seconds
76
+ */
77
+ abstract public function setTimeout($timeout);
78
+
79
+ /**
80
+ * Get the maximum request time in seconds.
81
+ * @return timeout in seconds
82
+ */
83
+ abstract public function getTimeout();
84
+
85
+ /**
86
+ * Test for the presence of a cURL header processing bug
87
+ *
88
+ * The cURL bug was present in versions prior to 7.30.0 and caused the header
89
+ * length to be miscalculated when a "Connection established" header added by
90
+ * some proxies was present.
91
+ *
92
+ * @return boolean
93
+ */
94
+ abstract protected function needsQuirk();
95
+
96
+ /**
97
+ * @visible for testing.
98
+ * Cache the response to an HTTP request if it is cacheable.
99
+ * @param Google_Http_Request $request
100
+ * @return bool Returns true if the insertion was successful.
101
+ * Otherwise, return false.
102
+ */
103
+ public function setCachedRequest(Google_Http_Request $request)
104
+ {
105
+ // Determine if the request is cacheable.
106
+ if (Google_Http_CacheParser::isResponseCacheable($request)) {
107
+ $this->client->getCache()->set($request->getCacheKey(), $request);
108
+ return true;
109
+ }
110
+
111
+ return false;
112
+ }
113
+
114
+ /**
115
+ * Execute an HTTP Request
116
+ *
117
+ * @param Google_Http_Request $request the http request to be executed
118
+ * @return Google_Http_Request http request with the response http code,
119
+ * response headers and response body filled in
120
+ * @throws Google_IO_Exception on curl or IO error
121
+ */
122
+ public function makeRequest(Google_Http_Request $request)
123
+ {
124
+ // First, check to see if we have a valid cached version.
125
+ $cached = $this->getCachedRequest($request);
126
+ if ($cached !== false && $cached instanceof Google_Http_Request) {
127
+ if (!$this->checkMustRevalidateCachedRequest($cached, $request)) {
128
+ return $cached;
129
+ }
130
+ }
131
+
132
+ if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
133
+ $request = $this->processEntityRequest($request);
134
+ }
135
+
136
+ list($responseData, $responseHeaders, $respHttpCode) = $this->executeRequest($request);
137
+
138
+ if ($respHttpCode == 304 && $cached) {
139
+ // If the server responded NOT_MODIFIED, return the cached request.
140
+ $this->updateCachedRequest($cached, $responseHeaders);
141
+ return $cached;
142
+ }
143
+
144
+ if (!isset($responseHeaders['Date']) && !isset($responseHeaders['date'])) {
145
+ $responseHeaders['date'] = date("r");
146
+ }
147
+
148
+ $request->setResponseHttpCode($respHttpCode);
149
+ $request->setResponseHeaders($responseHeaders);
150
+ $request->setResponseBody($responseData);
151
+ // Store the request in cache (the function checks to see if the request
152
+ // can actually be cached)
153
+ $this->setCachedRequest($request);
154
+ return $request;
155
+ }
156
+
157
+ /**
158
+ * @visible for testing.
159
+ * @param Google_Http_Request $request
160
+ * @return Google_Http_Request|bool Returns the cached object or
161
+ * false if the operation was unsuccessful.
162
+ */
163
+ public function getCachedRequest(Google_Http_Request $request)
164
+ {
165
+ if (false === Google_Http_CacheParser::isRequestCacheable($request)) {
166
+ return false;
167
+ }
168
+
169
+ return $this->client->getCache()->get($request->getCacheKey());
170
+ }
171
+
172
+ /**
173
+ * @visible for testing
174
+ * Process an http request that contains an enclosed entity.
175
+ * @param Google_Http_Request $request
176
+ * @return Google_Http_Request Processed request with the enclosed entity.
177
+ */
178
+ public function processEntityRequest(Google_Http_Request $request)
179
+ {
180
+ $postBody = $request->getPostBody();
181
+ $contentType = $request->getRequestHeader("content-type");
182
+
183
+ // Set the default content-type as application/x-www-form-urlencoded.
184
+ if (false == $contentType) {
185
+ $contentType = self::FORM_URLENCODED;
186
+ $request->setRequestHeaders(array('content-type' => $contentType));
187
+ }
188
+
189
+ // Force the payload to match the content-type asserted in the header.
190
+ if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
191
+ $postBody = http_build_query($postBody, '', '&');
192
+ $request->setPostBody($postBody);
193
+ }
194
+
195
+ // Make sure the content-length header is set.
196
+ if (!$postBody || is_string($postBody)) {
197
+ $postsLength = strlen($postBody);
198
+ $request->setRequestHeaders(array('content-length' => $postsLength));
199
+ }
200
+
201
+ return $request;
202
+ }
203
+
204
+ /**
205
+ * Check if an already cached request must be revalidated, and if so update
206
+ * the request with the correct ETag headers.
207
+ * @param Google_Http_Request $cached A previously cached response.
208
+ * @param Google_Http_Request $request The outbound request.
209
+ * return bool If the cached object needs to be revalidated, false if it is
210
+ * still current and can be re-used.
211
+ */
212
+ protected function checkMustRevalidateCachedRequest($cached, $request)
213
+ {
214
+ if (Google_Http_CacheParser::mustRevalidate($cached)) {
215
+ $addHeaders = array();
216
+ if ($cached->getResponseHeader('etag')) {
217
+ // [13.3.4] If an entity tag has been provided by the origin server,
218
+ // we must use that entity tag in any cache-conditional request.
219
+ $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
220
+ } elseif ($cached->getResponseHeader('date')) {
221
+ $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
222
+ }
223
+
224
+ $request->setRequestHeaders($addHeaders);
225
+ return true;
226
+ } else {
227
+ return false;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Update a cached request, using the headers from the last response.
233
+ * @param Google_Http_Request $cached A previously cached response.
234
+ * @param mixed Associative array of response headers from the last request.
235
+ */
236
+ protected function updateCachedRequest($cached, $responseHeaders)
237
+ {
238
+ $hopByHop = self::$HOP_BY_HOP;
239
+ if (!empty($responseHeaders['connection'])) {
240
+ $connectionHeaders = array_map(
241
+ 'strtolower',
242
+ array_filter(
243
+ array_map('trim', explode(',', $responseHeaders['connection']))
244
+ )
245
+ );
246
+ $hopByHop += array_fill_keys($connectionHeaders, true);
247
+ }
248
+
249
+ $endToEnd = array_diff_key($responseHeaders, $hopByHop);
250
+ $cached->setResponseHeaders($endToEnd);
251
+ }
252
+
253
+ /**
254
+ * Used by the IO lib and also the batch processing.
255
+ *
256
+ * @param $respData
257
+ * @param $headerSize
258
+ * @return array
259
+ */
260
+ public function parseHttpResponse($respData, $headerSize)
261
+ {
262
+ // check proxy header
263
+ foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) {
264
+ if (stripos($respData, $established_header) !== false) {
265
+ // existed, remove it
266
+ $respData = str_ireplace($established_header, '', $respData);
267
+ // Subtract the proxy header size unless the cURL bug prior to 7.30.0
268
+ // is present which prevented the proxy header size from being taken into
269
+ // account.
270
+ if (!$this->needsQuirk()) {
271
+ $headerSize -= strlen($established_header);
272
+ }
273
+ break;
274
+ }
275
+ }
276
+
277
+ if ($headerSize) {
278
+ $responseBody = substr($respData, $headerSize);
279
+ $responseHeaders = substr($respData, 0, $headerSize);
280
+ } else {
281
+ $responseSegments = explode("\r\n\r\n", $respData, 2);
282
+ $responseHeaders = $responseSegments[0];
283
+ $responseBody = isset($responseSegments[1]) ? $responseSegments[1] :
284
+ null;
285
+ }
286
+
287
+ $responseHeaders = $this->getHttpResponseHeaders($responseHeaders);
288
+ return array($responseHeaders, $responseBody);
289
+ }
290
+
291
+ /**
292
+ * Parse out headers from raw headers
293
+ * @param rawHeaders array or string
294
+ * @return array
295
+ */
296
+ public function getHttpResponseHeaders($rawHeaders)
297
+ {
298
+ if (is_array($rawHeaders)) {
299
+ return $this->parseArrayHeaders($rawHeaders);
300
+ } else {
301
+ return $this->parseStringHeaders($rawHeaders);
302
+ }
303
+ }
304
+
305
+ private function parseStringHeaders($rawHeaders)
306
+ {
307
+ $headers = array();
308
+ $responseHeaderLines = explode("\r\n", $rawHeaders);
309
+ foreach ($responseHeaderLines as $headerLine) {
310
+ if ($headerLine && strpos($headerLine, ':') !== false) {
311
+ list($header, $value) = explode(': ', $headerLine, 2);
312
+ $header = strtolower($header);
313
+ if (isset($headers[$header])) {
314
+ $headers[$header] .= "\n" . $value;
315
+ } else {
316
+ $headers[$header] = $value;
317
+ }
318
+ }
319
+ }
320
+ return $headers;
321
+ }
322
+
323
+ private function parseArrayHeaders($rawHeaders)
324
+ {
325
+ $header_count = count($rawHeaders);
326
+ $headers = array();
327
+
328
+ for ($i = 0; $i < $header_count; $i++) {
329
+ $header = $rawHeaders[$i];
330
+ // Times will have colons in - so we just want the first match.
331
+ $header_parts = explode(': ', $header, 2);
332
+ if (count($header_parts) == 2) {
333
+ $headers[strtolower($header_parts[0])] = $header_parts[1];
334
+ }
335
+ }
336
+
337
+ return $headers;
338
+ }
339
+ }
google/IO/Curl.php CHANGED
@@ -1,182 +1,182 @@
1
- <?php
2
- /*
3
- * Copyright 2014 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * Curl based implementation of Google_IO.
20
- *
21
- * @author Stuart Langley <slangley@google.com>
22
- */
23
-
24
- if (!class_exists('Google_Client')) {
25
- require_once dirname(__FILE__) . '/../autoload.php';
26
- }
27
-
28
- class Google_IO_Curl extends Google_IO_Abstract
29
- {
30
- // cURL hex representation of version 7.30.0
31
- const NO_QUIRK_VERSION = 0x071E00;
32
-
33
- private $options = array();
34
-
35
- public function __construct(Google_Client $client)
36
- {
37
- if (!extension_loaded('curl')) {
38
- $error = 'The cURL IO handler requires the cURL extension to be enabled';
39
- $client->getLogger()->critical($error);
40
- throw new Google_IO_Exception($error);
41
- }
42
-
43
- parent::__construct($client);
44
- }
45
-
46
- /**
47
- * Execute an HTTP Request
48
- *
49
- * @param Google_Http_Request $request the http request to be executed
50
- * @return array containing response headers, body, and http code
51
- * @throws Google_IO_Exception on curl or IO error
52
- */
53
- public function executeRequest(Google_Http_Request $request)
54
- {
55
- $curl = curl_init();
56
-
57
- if ($request->getPostBody()) {
58
- curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getPostBody());
59
- }
60
-
61
- $requestHeaders = $request->getRequestHeaders();
62
- if ($requestHeaders && is_array($requestHeaders)) {
63
- $curlHeaders = array();
64
- foreach ($requestHeaders as $k => $v) {
65
- $curlHeaders[] = "$k: $v";
66
- }
67
- curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
68
- }
69
- curl_setopt($curl, CURLOPT_URL, $request->getUrl());
70
-
71
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
72
- curl_setopt($curl, CURLOPT_USERAGENT, $request->getUserAgent());
73
-
74
- curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
75
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
76
-
77
- // The SSL version will be determined by the underlying library
78
- // @see https://github.com/google/google-api-php-client/pull/644
79
- //curl_setopt($curl, CURLOPT_SSLVERSION, 1);
80
-
81
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
82
- curl_setopt($curl, CURLOPT_HEADER, true);
83
-
84
- if ($request->canGzip()) {
85
- curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
86
- }
87
-
88
- $options = $this->client->getClassConfig('Google_IO_Curl', 'options');
89
- if (is_array($options)) {
90
- $this->setOptions($options);
91
- }
92
-
93
- foreach ($this->options as $key => $var) {
94
- curl_setopt($curl, $key, $var);
95
- }
96
-
97
- if (!isset($this->options[CURLOPT_CAINFO])) {
98
- curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
99
- }
100
-
101
- $this->client->getLogger()->debug(
102
- 'cURL request',
103
- array(
104
- 'url' => $request->getUrl(),
105
- 'method' => $request->getRequestMethod(),
106
- 'headers' => $requestHeaders,
107
- 'body' => $request->getPostBody()
108
- )
109
- );
110
-
111
- $response = curl_exec($curl);
112
- if ($response === false) {
113
- $error = curl_error($curl);
114
- $code = curl_errno($curl);
115
- $map = $this->client->getClassConfig('Google_IO_Exception', 'retry_map');
116
-
117
- $this->client->getLogger()->error('cURL ' . $error);
118
- throw new Google_IO_Exception($error, $code, null, $map);
119
- }
120
- $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
121
-
122
- list($responseHeaders, $responseBody) = $this->parseHttpResponse($response, $headerSize);
123
- $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
124
-
125
- $this->client->getLogger()->debug(
126
- 'cURL response',
127
- array(
128
- 'code' => $responseCode,
129
- 'headers' => $responseHeaders,
130
- 'body' => $responseBody,
131
- )
132
- );
133
-
134
- return array($responseBody, $responseHeaders, $responseCode);
135
- }
136
-
137
- /**
138
- * Set options that update the transport implementation's behavior.
139
- * @param $options
140
- */
141
- public function setOptions($options)
142
- {
143
- $this->options = $options + $this->options;
144
- }
145
-
146
- /**
147
- * Set the maximum request time in seconds.
148
- * @param $timeout in seconds
149
- */
150
- public function setTimeout($timeout)
151
- {
152
- // Since this timeout is really for putting a bound on the time
153
- // we'll set them both to the same. If you need to specify a longer
154
- // CURLOPT_TIMEOUT, or a higher CONNECTTIMEOUT, the best thing to
155
- // do is use the setOptions method for the values individually.
156
- $this->options[CURLOPT_CONNECTTIMEOUT] = $timeout;
157
- $this->options[CURLOPT_TIMEOUT] = $timeout;
158
- }
159
-
160
- /**
161
- * Get the maximum request time in seconds.
162
- * @return timeout in seconds
163
- */
164
- public function getTimeout()
165
- {
166
- return $this->options[CURLOPT_TIMEOUT];
167
- }
168
-
169
- /**
170
- * Test for the presence of a cURL header processing bug
171
- *
172
- * {@inheritDoc}
173
- *
174
- * @return boolean
175
- */
176
- protected function needsQuirk()
177
- {
178
- $ver = curl_version();
179
- $versionNum = $ver['version_number'];
180
- return $versionNum < Google_IO_Curl::NO_QUIRK_VERSION;
181
- }
182
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2014 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * Curl based implementation of Google_IO.
20
+ *
21
+ * @author Stuart Langley <slangley@google.com>
22
+ */
23
+
24
+ if (!class_exists('Google_Client')) {
25
+ require_once dirname(__FILE__) . '/../autoload.php';
26
+ }
27
+
28
+ class Google_IO_Curl extends Google_IO_Abstract
29
+ {
30
+ // cURL hex representation of version 7.30.0
31
+ const NO_QUIRK_VERSION = 0x071E00;
32
+
33
+ private $options = array();
34
+
35
+ public function __construct(Google_Client $client)
36
+ {
37
+ if (!extension_loaded('curl')) {
38
+ $error = 'The cURL IO handler requires the cURL extension to be enabled';
39
+ $client->getLogger()->critical($error);
40
+ throw new Google_IO_Exception($error);
41
+ }
42
+
43
+ parent::__construct($client);
44
+ }
45
+
46
+ /**
47
+ * Execute an HTTP Request
48
+ *
49
+ * @param Google_Http_Request $request the http request to be executed
50
+ * @return array containing response headers, body, and http code
51
+ * @throws Google_IO_Exception on curl or IO error
52
+ */
53
+ public function executeRequest(Google_Http_Request $request)
54
+ {
55
+ $curl = curl_init();
56
+
57
+ if ($request->getPostBody()) {
58
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getPostBody());
59
+ }
60
+
61
+ $requestHeaders = $request->getRequestHeaders();
62
+ if ($requestHeaders && is_array($requestHeaders)) {
63
+ $curlHeaders = array();
64
+ foreach ($requestHeaders as $k => $v) {
65
+ $curlHeaders[] = "$k: $v";
66
+ }
67
+ curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
68
+ }
69
+ curl_setopt($curl, CURLOPT_URL, $request->getUrl());
70
+
71
+ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
72
+ curl_setopt($curl, CURLOPT_USERAGENT, $request->getUserAgent());
73
+
74
+ curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
75
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
76
+
77
+ // The SSL version will be determined by the underlying library
78
+ // @see https://github.com/google/google-api-php-client/pull/644
79
+ //curl_setopt($curl, CURLOPT_SSLVERSION, 1);
80
+
81
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
82
+ curl_setopt($curl, CURLOPT_HEADER, true);
83
+
84
+ if ($request->canGzip()) {
85
+ curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
86
+ }
87
+
88
+ $options = $this->client->getClassConfig('Google_IO_Curl', 'options');
89
+ if (is_array($options)) {
90
+ $this->setOptions($options);
91
+ }
92
+
93
+ foreach ($this->options as $key => $var) {
94
+ curl_setopt($curl, $key, $var);
95
+ }
96
+
97
+ if (!isset($this->options[CURLOPT_CAINFO])) {
98
+ curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
99
+ }
100
+
101
+ $this->client->getLogger()->debug(
102
+ 'cURL request',
103
+ array(
104
+ 'url' => $request->getUrl(),
105
+ 'method' => $request->getRequestMethod(),
106
+ 'headers' => $requestHeaders,
107
+ 'body' => $request->getPostBody()
108
+ )
109
+ );
110
+
111
+ $response = curl_exec($curl);
112
+ if ($response === false) {
113
+ $error = curl_error($curl);
114
+ $code = curl_errno($curl);
115
+ $map = $this->client->getClassConfig('Google_IO_Exception', 'retry_map');
116
+
117
+ $this->client->getLogger()->error('cURL ' . $error);
118
+ throw new Google_IO_Exception($error, $code, null, $map);
119
+ }
120
+ $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
121
+
122
+ list($responseHeaders, $responseBody) = $this->parseHttpResponse($response, $headerSize);
123
+ $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
124
+
125
+ $this->client->getLogger()->debug(
126
+ 'cURL response',
127
+ array(
128
+ 'code' => $responseCode,
129
+ 'headers' => $responseHeaders,
130
+ 'body' => $responseBody,
131
+ )
132
+ );
133
+
134
+ return array($responseBody, $responseHeaders, $responseCode);
135
+ }
136
+
137
+ /**
138
+ * Set options that update the transport implementation's behavior.
139
+ * @param $options
140
+ */
141
+ public function setOptions($options)
142
+ {
143
+ $this->options = $options + $this->options;
144
+ }
145
+
146
+ /**
147
+ * Set the maximum request time in seconds.
148
+ * @param $timeout in seconds
149
+ */
150
+ public function setTimeout($timeout)
151
+ {
152
+ // Since this timeout is really for putting a bound on the time
153
+ // we'll set them both to the same. If you need to specify a longer
154
+ // CURLOPT_TIMEOUT, or a higher CONNECTTIMEOUT, the best thing to
155
+ // do is use the setOptions method for the values individually.
156
+ $this->options[CURLOPT_CONNECTTIMEOUT] = $timeout;
157
+ $this->options[CURLOPT_TIMEOUT] = $timeout;
158
+ }
159
+
160
+ /**
161
+ * Get the maximum request time in seconds.
162
+ * @return timeout in seconds
163
+ */
164
+ public function getTimeout()
165
+ {
166
+ return $this->options[CURLOPT_TIMEOUT];
167
+ }
168
+
169
+ /**
170
+ * Test for the presence of a cURL header processing bug
171
+ *
172
+ * {@inheritDoc}
173
+ *
174
+ * @return boolean
175
+ */
176
+ protected function needsQuirk()
177
+ {
178
+ $ver = curl_version();
179
+ $versionNum = $ver['version_number'];
180
+ return $versionNum < Google_IO_Curl::NO_QUIRK_VERSION;
181
+ }
182
+ }
google/IO/Exception.php CHANGED
@@ -1,69 +1,69 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- if (!class_exists('Google_Client')) {
19
- require_once dirname(__FILE__) . '/../autoload.php';
20
- }
21
-
22
- class Google_IO_Exception extends Google_Exception implements Google_Task_Retryable
23
- {
24
- /**
25
- * @var array $retryMap Map of errors with retry counts.
26
- */
27
- private $retryMap = array();
28
-
29
- /**
30
- * Creates a new IO exception with an optional retry map.
31
- *
32
- * @param string $message
33
- * @param int $code
34
- * @param Exception|null $previous
35
- * @param array|null $retryMap Map of errors with retry counts.
36
- */
37
- public function __construct(
38
- $message,
39
- $code = 0,
40
- Exception $previous = null,
41
- array $retryMap = null
42
- ) {
43
- if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
44
- parent::__construct($message, $code, $previous);
45
- } else {
46
- parent::__construct($message, $code);
47
- }
48
-
49
- if (is_array($retryMap)) {
50
- $this->retryMap = $retryMap;
51
- }
52
- }
53
-
54
- /**
55
- * Gets the number of times the associated task can be retried.
56
- *
57
- * NOTE: -1 is returned if the task can be retried indefinitely
58
- *
59
- * @return integer
60
- */
61
- public function allowedRetries()
62
- {
63
- if (isset($this->retryMap[$this->code])) {
64
- return $this->retryMap[$this->code];
65
- }
66
-
67
- return 0;
68
- }
69
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ if (!class_exists('Google_Client')) {
19
+ require_once dirname(__FILE__) . '/../autoload.php';
20
+ }
21
+
22
+ class Google_IO_Exception extends Google_Exception implements Google_Task_Retryable
23
+ {
24
+ /**
25
+ * @var array $retryMap Map of errors with retry counts.
26
+ */
27
+ private $retryMap = array();
28
+
29
+ /**
30
+ * Creates a new IO exception with an optional retry map.
31
+ *
32
+ * @param string $message
33
+ * @param int $code
34
+ * @param Exception|null $previous
35
+ * @param array|null $retryMap Map of errors with retry counts.
36
+ */
37
+ public function __construct(
38
+ $message,
39
+ $code = 0,
40
+ Exception $previous = null,
41
+ array $retryMap = null
42
+ ) {
43
+ if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
44
+ parent::__construct($message, $code, $previous);
45
+ } else {
46
+ parent::__construct($message, $code);
47
+ }
48
+
49
+ if (is_array($retryMap)) {
50
+ $this->retryMap = $retryMap;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Gets the number of times the associated task can be retried.
56
+ *
57
+ * NOTE: -1 is returned if the task can be retried indefinitely
58
+ *
59
+ * @return integer
60
+ */
61
+ public function allowedRetries()
62
+ {
63
+ if (isset($this->retryMap[$this->code])) {
64
+ return $this->retryMap[$this->code];
65
+ }
66
+
67
+ return 0;
68
+ }
69
+ }
google/IO/Stream.php CHANGED
@@ -1,243 +1,243 @@
1
- <?php
2
- /*
3
- * Copyright 2013 Google Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /**
19
- * Http Streams based implementation of Google_IO.
20
- *
21
- * @author Stuart Langley <slangley@google.com>
22
- */
23
-
24
- if (!class_exists('Google_Client')) {
25
- require_once dirname(__FILE__) . '/../autoload.php';
26
- }
27
-
28
- class Google_IO_Stream extends Google_IO_Abstract
29
- {
30
- const TIMEOUT = "timeout";
31
- const ZLIB = "compress.zlib://";
32
- private $options = array();
33
- private $trappedErrorNumber;
34
- private $trappedErrorString;
35
-
36
- private static $DEFAULT_HTTP_CONTEXT = array(
37
- "follow_location" => 0,
38
- "ignore_errors" => 1,
39
- );
40
-
41
- private static $DEFAULT_SSL_CONTEXT = array(
42
- "verify_peer" => true,
43
- );
44
-
45
- public function __construct(Google_Client $client)
46
- {
47
- if (!ini_get('allow_url_fopen')) {
48
- $error = 'The stream IO handler requires the allow_url_fopen runtime ' .
49
- 'configuration to be enabled';
50
- $client->getLogger()->critical($error);
51
- throw new Google_IO_Exception($error);
52
- }
53
-
54
- parent::__construct($client);
55
- }
56
-
57
- /**
58
- * Execute an HTTP Request
59
- *
60
- * @param Google_Http_Request $request the http request to be executed
61
- * @return array containing response headers, body, and http code
62
- * @throws Google_IO_Exception on curl or IO error
63
- */
64
- public function executeRequest(Google_Http_Request $request)
65
- {
66
- $default_options = stream_context_get_options(stream_context_get_default());
67
-
68
- $requestHttpContext = array_key_exists('http', $default_options) ?
69
- $default_options['http'] : array();
70
-
71
- if ($request->getPostBody()) {
72
- $requestHttpContext["content"] = $request->getPostBody();
73
- }
74
-
75
- $requestHeaders = $request->getRequestHeaders();
76
- if ($requestHeaders && is_array($requestHeaders)) {
77
- $headers = "";
78
- foreach ($requestHeaders as $k => $v) {
79
- $headers .= "$k: $v\r\n";
80
- }
81
- $requestHttpContext["header"] = $headers;
82
- }
83
-
84
- $requestHttpContext["method"] = $request->getRequestMethod();
85
- $requestHttpContext["user_agent"] = $request->getUserAgent();
86
-
87
- $requestSslContext = array_key_exists('ssl', $default_options) ?
88
- $default_options['ssl'] : array();
89
-
90
- if (!$this->client->isAppEngine() && !array_key_exists("cafile", $requestSslContext)) {
91
- $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
92
- }
93
-
94
- $options = array(
95
- "http" => array_merge(
96
- self::$DEFAULT_HTTP_CONTEXT,
97
- $requestHttpContext
98
- ),
99
- "ssl" => array_merge(
100
- self::$DEFAULT_SSL_CONTEXT,
101
- $requestSslContext
102
- )
103
- );
104
-
105
- $context = stream_context_create($options);
106
-
107
- $url = $request->getUrl();
108
-
109
- if ($request->canGzip()) {
110
- $url = self::ZLIB . $url;
111
- }
112
-
113
- $this->client->getLogger()->debug(
114
- 'Stream request',
115
- array(
116
- 'url' => $url,
117
- 'method' => $request->getRequestMethod(),
118
- 'headers' => $requestHeaders,
119
- 'body' => $request->getPostBody()
120
- )
121
- );
122
-
123
- // We are trapping any thrown errors in this method only and
124
- // throwing an exception.
125
- $this->trappedErrorNumber = null;
126
- $this->trappedErrorString = null;
127
-
128
- // START - error trap.
129
- set_error_handler(array($this, 'trapError'));
130
- $fh = fopen($url, 'r', false, $context);
131
- restore_error_handler();
132
- // END - error trap.
133
-
134
- if ($this->trappedErrorNumber) {
135
- $error = sprintf(
136
- "HTTP Error: Unable to connect: '%s'",
137
- $this->trappedErrorString
138
- );
139
-
140
- $this->client->getLogger()->error('Stream ' . $error);
141
- throw new Google_IO_Exception($error, $this->trappedErrorNumber);
142
- }
143
-
144
- $response_data = false;
145
- $respHttpCode = self::UNKNOWN_CODE;
146
- if ($fh) {
147
- if (isset($this->options[self::TIMEOUT])) {
148
- stream_set_timeout($fh, $this->options[self::TIMEOUT]);
149
- }
150
-
151
- $response_data = stream_get_contents($fh);
152
- fclose($fh);
153
-
154
- $respHttpCode = $this->getHttpResponseCode($http_response_header);
155
- }
156
-
157
- if (false === $response_data) {
158
- $error = sprintf(
159
- "HTTP Error: Unable to connect: '%s'",
160
- $respHttpCode
161
- );
162
-
163
- $this->client->getLogger()->error('Stream ' . $error);
164
- throw new Google_IO_Exception($error, $respHttpCode);
165
- }
166
-
167
- $responseHeaders = $this->getHttpResponseHeaders($http_response_header);
168
-
169
- $this->client->getLogger()->debug(
170
- 'Stream response',
171
- array(
172
- 'code' => $respHttpCode,
173
- 'headers' => $responseHeaders,
174
- 'body' => $response_data,
175
- )
176
- );
177
-
178
- return array($response_data, $responseHeaders, $respHttpCode);
179
- }
180
-
181
- /**
182
- * Set options that update the transport implementation's behavior.
183
- * @param $options
184
- */
185
- public function setOptions($options)
186
- {
187
- $this->options = $options + $this->options;
188
- }
189
-
190
- /**
191
- * Method to handle errors, used for error handling around
192
- * stream connection methods.
193
- */
194
- public function trapError($errno, $errstr)
195
- {
196
- $this->trappedErrorNumber = $errno;
197
- $this->trappedErrorString = $errstr;
198
- }
199
-
200
- /**
201
- * Set the maximum request time in seconds.
202
- * @param $timeout in seconds
203
- */
204
- public function setTimeout($timeout)
205
- {
206
- $this->options[self::TIMEOUT] = $timeout;
207
- }
208
-
209
- /**
210
- * Get the maximum request time in seconds.
211
- * @return timeout in seconds
212
- */
213
- public function getTimeout()
214
- {
215
- return $this->options[self::TIMEOUT];
216
- }
217
-
218
- /**
219
- * Test for the presence of a cURL header processing bug
220
- *
221
- * {@inheritDoc}
222
- *
223
- * @return boolean
224
- */
225
- protected function needsQuirk()
226
- {
227
- return false;
228
- }
229
-
230
- protected function getHttpResponseCode($response_headers)
231
- {
232
- $header_count = count($response_headers);
233
-
234
- for ($i = 0; $i < $header_count; $i++) {
235
- $header = $response_headers[$i];
236
- if (strncasecmp("HTTP", $header, strlen("HTTP")) == 0) {
237
- $response = explode(' ', $header);
238
- return $response[1];
239
- }
240
- }
241
- return self::UNKNOWN_CODE;
242
- }
243
- }
1
+ <?php
2
+ /*
3
+ * Copyright 2013 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * Http Streams based implementation of Google_IO.
20
+ *
21
+ * @author Stuart Langley <slangley@google.com>
22
+ */
23
+
24
+ if (!class_exists('Google_Client')) {
25
+ require_once dirname(__FILE__) . '/../autoload.php';
26
+ }
27
+
28
+ class Google_IO_Stream extends Google_IO_Abstract
29
+ {
30
+ const TIMEOUT = "timeout";
31
+ const ZLIB = "compress.zlib://";
32
+ private $options = array();
33
+ private $trappedErrorNumber;
34
+ private $trappedErrorString;
35
+
36
+ private static $DEFAULT_HTTP_CONTEXT = array(
37
+ "follow_location" => 0,
38
+ "ignore_errors" => 1,
39
+ );
40
+
41
+ private static $DEFAULT_SSL_CONTEXT = array(
42
+ "verify_peer" => true,
43
+ );
44
+
45
+ public function __construct(Google_Client $client)
46
+ {
47
+ if (!ini_get('allow_url_fopen')) {
48
+ $error = 'The stream IO handler requires the allow_url_fopen runtime ' .
49
+ 'configuration to be enabled';
50
+ $client->getLogger()->critical($error);
51
+ throw new Google_IO_Exception($error);
52
+ }
53
+
54
+ parent::__construct($client);
55
+ }
56
+
57
+ /**
58
+ * Execute an HTTP Request
59
+ *
60
+ * @param Google_Http_Request $request the http request to be executed
61
+ * @return array containing response headers, body, and http code
62
+ * @throws Google_IO_Exception on curl or IO error
63
+ */
64
+ public function executeRequest(Google_Http_Request $request)
65
+ {
66
+ $default_options = stream_context_get_options(stream_context_get_default());
67
+
68
+ $requestHttpContext = array_key_exists('http', $default_options) ?
69
+ $default_options['http'] : array();
70
+
71
+ if ($request->getPostBody()) {
72
+ $requestHttpContext["content"] = $request->getPostBody();
73
+ }
74
+
75
+ $requestHeaders = $request->getRequestHeaders();
76
+ if ($requestHeaders && is_array($requestHeaders)) {
77
+ $headers = "";
78
+ foreach ($requestHeaders as $k => $v) {
79
+ $headers .= "$k: $v\r\n";
80
+ }
81
+ $requestHttpContext["header"] = $headers;
82
+ }
83
+
84
+ $requestHttpContext["method"] = $request->getRequestMethod();
85
+ $requestHttpContext["user_agent"] = $request->getUserAgent();
86
+
87
+ $requestSslContext = array_key_exists('ssl', $default_options) ?
88
+ $default_options['ssl'] : array();
89
+
90
+ if (!$this->client->isAppEngine() && !array_key_exists("cafile", $requestSslContext)) {
91
+ $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
92
+ }
93
+
94
+ $options = array(
95
+ "http" => array_merge(
96
+ self::$DEFAULT_HTTP_CONTEXT,
97
+ $requestHttpContext
98
+ ),
99
+ "ssl" => array_merge(
100
+ self::$DEFAULT_SSL_CONTEXT,
101
+ $requestSslContext
102
+ )
103
+ );
104
+
105
+ $context = stream_context_create($options);
106
+
107
+ $url = $request->getUrl();
108
+
109
+ if ($request->canGzip()) {
110
+ $url = self::ZLIB . $url;
111
+ }
112
+
113
+ $this->client->getLogger()->debug(
114
+ 'Stream request',
115
+ array(
116
+ 'url' => $url,
117
+ 'method' => $request->getRequestMethod(),
118
+ 'headers' => $requestHeaders,
119
+ 'body' => $request->getPostBody()
120
+ )
121
+ );
122
+
123
+ // We are trapping any thrown errors in this method only and
124
+ // throwing an exception.
125
+ $this->trappedErrorNumber = null;
126
+ $this->trappedErrorString = null;
127
+
128
+ // START - error trap.
129
+ set_error_handler(array($this, 'trapError'));
130
+ $fh = fopen($url, 'r', false, $context);
131
+ restore_error_handler();
132
+ // END - error trap.
133
+
134
+ if ($this->trappedErrorNumber) {
135
+ $error = sprintf(
136
+ "HTTP Error: Unable to connect: '%s'",
137
+ $this->trappedErrorString
138
+ );
139
+
140
+ $this->client->getLogger()->error('Stream ' . $error);
141
+ throw new Google_IO_Exception($error, $this->trappedErrorNumber);
142
+ }
143
+
144
+ $response_data = false;
145
+ $respHttpCode = self::UNKNOWN_CODE;
146
+ if ($fh) {
147
+ if (isset($this->options[self::TIMEOUT])) {
148
+ stream_set_timeout($fh, $this->options[self::TIMEOUT]);
149
+ }
150
+
151
+ $response_data = stream_get_contents($fh);
152
+ fclose($fh);
153
+
154
+ $respHttpCode = $this->getHttpResponseCode($http_response_header);
155
+ }
156
+
157
+ if (false === $response_data) {
158
+ $error = sprintf(
159
+ "HTTP Error: Unable to connect: '%s'",
160
+ $respHttpCode
161
+ );
162
+
163
+ $this->client->getLogger()->error('Stream ' . $error);
164
+ throw new Google_IO_Exception($error, $respHttpCode);
165
+ }
166
+
167
+ $responseHeaders = $this->getHttpResponseHeaders($http_response_header);
168
+
169
+ $this->client->getLogger()->debug(
170
+ 'Stream response',
171
+ array(
172
+ 'code' => $respHttpCode,
173
+ 'headers' => $responseHeaders,
174
+ 'body' => $response_data,
175
+ )
176
+ );
177
+
178
+ return array($response_data, $responseHeaders, $respHttpCode);
179
+ }
180
+
181
+ /**
182
+ * Set options that update the transport implementation's behavior.
183
+ * @param $options
184
+ */
185
+ public function setOptions($options)
186
+ {
187
+ $this->options = $options + $this->options;
188
+ }
189
+
190
+ /**
191
+ * Method to handle errors, used for error handling around
192
+ * stream connection methods.
193
+ */
194
+ public function trapError($errno, $errstr)
195
+ {
196
+ $this->trappedErrorNumber = $errno;
197
+ $this->trappedErrorString = $errstr;
198
+ }
199
+
200
+ /**
201
+ * Set the maximum request time in seconds.
202
+ * @param $timeout in seconds
203
+ */
204
+ public function setTimeout($timeout)
205
+ {
206
+ $this->options[self::TIMEOUT] = $timeout;
207
+ }
208
+
209
+ /**
210
+ * Get the maximum request time in seconds.
211
+ * @return timeout in seconds
212
+ */
213
+ public function getTimeout()
214
+ {
215
+ return $this->options[self::TIMEOUT];
216
+ }
217
+
218
+ /**
219
+ * Test for the presence of a cURL header processing bug
220
+ *
221
+ * {@inheritDoc}
222
+ *
223
+ * @return boolean
224
+ */
225
+ protected function needsQuirk()
226
+ {
227
+ return false;
228
+ }
229
+
230
+ protected function getHttpResponseCode($response_headers)
231
+ {
232
+ $header_count = count($response_headers);
233
+
234
+ for ($i = 0; $i < $header_count; $i++) {
235
+ $header = $response_headers[$i];
236
+ if (strncasecmp("HTTP", $header, strlen("HTTP")) == 0) {
237
+ $response = explode(' ', $header);
238
+ return $response[1];
239
+ }
240
+ }
241
+ return self::UNKNOWN_CODE;
242
+ }
243
+ }