Google Analyticator - Version 6.4.5

Version Description

  • Introduce Remarketing support
  • Introduce Option to remove tracking on wp-login.
  • Add link to Analytics training and option to remove.
Download this release

Release Info

Developer VideoUserManuals
Plugin Icon 128x128 Google Analyticator
Version 6.4.5
Comparing to
See all releases

Code changes from version 6.4.4.3 to 6.4.5

Files changed (67) hide show
  1. ga-plugin-advert-sidebar.png +0 -0
  2. gapro-plugin-advert-sidebar.png +0 -0
  3. google-analyticator.php +112 -48
  4. google-analytics-summary-widget.php +8 -0
  5. google-api-php-client/src/Google_Client.php +0 -453
  6. google-api-php-client/src/auth/Google_AssertionCredentials.php +0 -95
  7. google-api-php-client/src/auth/Google_Auth.php +0 -36
  8. google-api-php-client/src/auth/Google_AuthNone.php +0 -48
  9. google-api-php-client/src/auth/Google_LoginTicket.php +0 -63
  10. google-api-php-client/src/auth/Google_OAuth2.php +0 -444
  11. google-api-php-client/src/auth/Google_P12Signer.php +0 -70
  12. google-api-php-client/src/auth/Google_PemVerifier.php +0 -66
  13. google-api-php-client/src/auth/Google_Signer.php +0 -30
  14. google-api-php-client/src/auth/Google_Verifier.php +0 -31
  15. google-api-php-client/src/cache/Google_ApcCache.php +0 -98
  16. google-api-php-client/src/cache/Google_Cache.php +0 -55
  17. google-api-php-client/src/cache/Google_FileCache.php +0 -137
  18. google-api-php-client/src/cache/Google_MemcacheCache.php +0 -130
  19. google-api-php-client/src/config.php +0 -81
  20. google-api-php-client/src/contrib/Google_AdexchangebuyerService.php +0 -567
  21. google-api-php-client/src/contrib/Google_AdsenseService.php +0 -1140
  22. google-api-php-client/src/contrib/Google_AdsensehostService.php +0 -1378
  23. google-api-php-client/src/contrib/Google_AnalyticsService.php +0 -1887
  24. google-api-php-client/src/contrib/Google_BigqueryService.php +0 -1821
  25. google-api-php-client/src/contrib/Google_BloggerService.php +0 -1301
  26. google-api-php-client/src/contrib/Google_BooksService.php +0 -2793
  27. google-api-php-client/src/contrib/Google_CalendarService.php +0 -1931
  28. google-api-php-client/src/contrib/Google_ComputeService.php +0 -2629
  29. google-api-php-client/src/contrib/Google_CustomsearchService.php +0 -836
  30. google-api-php-client/src/contrib/Google_DriveService.php +0 -2157
  31. google-api-php-client/src/contrib/Google_FreebaseService.php +0 -89
  32. google-api-php-client/src/contrib/Google_FusiontablesService.php +0 -1326
  33. google-api-php-client/src/contrib/Google_GanService.php +0 -1605
  34. google-api-php-client/src/contrib/Google_LatitudeService.php +0 -283
  35. google-api-php-client/src/contrib/Google_LicensingService.php +0 -285
  36. google-api-php-client/src/contrib/Google_ModeratorService.php +0 -1888
  37. google-api-php-client/src/contrib/Google_Oauth2Service.php +0 -265
  38. google-api-php-client/src/contrib/Google_OrkutService.php +0 -2554
  39. google-api-php-client/src/contrib/Google_PagespeedonlineService.php +0 -474
  40. google-api-php-client/src/contrib/Google_PlusMomentsService.php +0 -567
  41. google-api-php-client/src/contrib/Google_PlusService.php +0 -1525
  42. google-api-php-client/src/contrib/Google_PredictionService.php +0 -429
  43. google-api-php-client/src/contrib/Google_ShoppingService.php +0 -1311
  44. google-api-php-client/src/contrib/Google_SiteVerificationService.php +0 -287
  45. google-api-php-client/src/contrib/Google_StorageService.php +0 -1076
  46. google-api-php-client/src/contrib/Google_TaskqueueService.php +0 -423
  47. google-api-php-client/src/contrib/Google_TasksService.php +0 -580
  48. google-api-php-client/src/contrib/Google_TranslateService.php +0 -244
  49. google-api-php-client/src/contrib/Google_UrlshortenerService.php +0 -325
  50. google-api-php-client/src/contrib/Google_WebfontsService.php +0 -130
  51. google-api-php-client/src/contrib/Google_YoutubeService.php +0 -996
  52. google-api-php-client/src/external/URITemplateParser.php +0 -214
  53. google-api-php-client/src/io/Google_CacheParser.php +0 -173
  54. google-api-php-client/src/io/Google_CurlIO.php +0 -278
  55. google-api-php-client/src/io/Google_HttpRequest.php +0 -304
  56. google-api-php-client/src/io/Google_IO.php +0 -49
  57. google-api-php-client/src/io/Google_REST.php +0 -128
  58. google-api-php-client/src/io/cacerts.pem +0 -714
  59. google-api-php-client/src/local_config.php +0 -81
  60. google-api-php-client/src/service/Google_BatchRequest.php +0 -110
  61. google-api-php-client/src/service/Google_MediaFileUpload.php +0 -244
  62. google-api-php-client/src/service/Google_Model.php +0 -115
  63. google-api-php-client/src/service/Google_Service.php +0 -22
  64. google-api-php-client/src/service/Google_ServiceResource.php +0 -196
  65. google-api-php-client/src/service/Google_Utils.php +0 -117
  66. google-api-php-client/static/Credentials.png +0 -0
  67. readme.txt +7 -2
ga-plugin-advert-sidebar.png ADDED
Binary file
gapro-plugin-advert-sidebar.png ADDED
Binary file
google-analyticator.php CHANGED
@@ -1,7 +1,7 @@
1
<?php
2
/*
3
* Plugin Name: Google Analyticator
4
- * Version: 6.4.4.3
5
* Plugin URI: http://www.videousermanuals.com/google-analyticator/?utm_campaign=analyticator&utm_medium=plugin&utm_source=readme-txt
6
* Description: Adds the necessary JavaScript code to enable <a href="http://www.google.com/analytics/">Google's Analytics</a>. After enabling this plugin you need to authenticate with Google, then select your domain and you're set.
7
* Author: Video User Manuals Pty Ltd
@@ -9,7 +9,7 @@
9
* Text Domain: google-analyticator
10
*/
11
12
- define('GOOGLE_ANALYTICATOR_VERSION', '6.4.4.3');
13
14
define('GOOGLE_ANALYTICATOR_CLIENTID', '1007949979410.apps.googleusercontent.com');
15
define('GOOGLE_ANALYTICATOR_CLIENTSECRET', 'q06U41XDXtzaXD14E-KO1hti'); //don't worry - this don't need to be secret in our case
@@ -25,6 +25,9 @@ define("key_ga_uid", "ga_uid", true);
25
define("key_ga_status", "ga_status", true);
26
define("key_ga_admin", "ga_admin_status", true);
27
define("key_ga_admin_disable", "ga_admin_disable", true);
28
define("key_ga_admin_role", "ga_admin_role", true);
29
define("key_ga_dashboard_role", "ga_dashboard_role", true);
30
define("key_ga_adsense", "ga_adsense", true);
@@ -61,6 +64,7 @@ add_option(key_ga_admin, ga_admin_default, '');
61
add_option(key_ga_admin_disable, ga_admin_disable_default, '');
62
add_option(key_ga_admin_role, array('administrator'), '');
63
add_option(key_ga_dashboard_role, array('administrator'), '');
64
add_option(key_ga_adsense, ga_adsense_default, '');
65
add_option(key_ga_extra, ga_extra_default, '');
66
add_option(key_ga_extra_after, ga_extra_after_default, '');
@@ -107,7 +111,10 @@ function ga_admin_init() {
107
108
# Add the core Google Analytics script, with a high priority to ensure last script for async tracking
109
add_action('wp_head', 'add_google_analytics',99);
110
- add_action('login_head', 'add_google_analytics', 999999);
111
112
# Initialize outbound link tracking
113
add_action('init', 'ga_outgoing_links');
@@ -370,6 +377,15 @@ function ga_options_page() {
370
371
// Update the widgets option
372
update_option(key_ga_annon, wp_filter_kses( $_POST[key_ga_annon] ) );
373
374
375
// Give an updated message
@@ -386,7 +402,7 @@ function ga_options_page() {
386
387
<div class="wrap">
388
389
- <h2><?php _e('Google Analyticator Settings', 'google-analyticator'); ?></h2>
390
<form method="post" action="<?php echo admin_url('options-general.php?page=google-analyticator.php');?>">
391
<?php
392
# Add a nonce
@@ -403,6 +419,13 @@ function ga_options_page() {
403
<?php _e('Google Analytics integration is currently enabled, but you did not enter a UID. Tracking will not occur.', 'google-analyticator'); ?>
404
</div>
405
<?php } ?>
406
<table class="form-table" cellspacing="2" cellpadding="5" width="100%">
407
408
<tr>
@@ -569,6 +592,56 @@ function ga_options_page() {
569
<p class="setting-description"><?php _e('Selecting the "Remove" option will physically remove the tracking code from logged in users. Selecting the "Use \'admin\' variable" option will assign a variable called \'admin\' to logged in users. This option will allow Google Analytics\' site overlay feature to work, but you will have to manually configure Google Analytics to exclude tracking from pageviews with the \'admin\' variable.', 'google-analyticator'); ?></p>
570
</td>
571
</tr>
572
<tr>
573
<td colspan="2">
574
<h3>Link Tracking Settings</h3>
@@ -742,6 +815,32 @@ function ga_options_page() {
742
<p class="setting-description"><?php _e('Disabling this option will completely remove the Dashboard Summary widget and the theme Stats widget. Use this option if you would prefer to not see the widgets.', 'google-analyticator'); ?></p>
743
</td>
744
</tr>
745
<tr<?php if(!$useAuth){echo ' style="display:none"';}?>>
746
<th width="30%" valign="top" style="padding-top: 10px;">
747
<label for="<?php echo key_ga_dashboard_role ?>"><?php _e('User roles that can see the dashboard widget', 'google-analyticator'); ?>:</label>
@@ -775,49 +874,10 @@ function ga_options_page() {
775
<a href="<?php echo admin_url('/options-general.php?page=ga_reset'); ?>"><?php _e('Deauthorize &amp; Reset Google Analyticator.', 'google-analyticator'); ?></a>
776
777
</form>
778
779
- </form>
780
-
781
-
782
- <?php if (!get_option('wpm_o_user_id')): ?>
783
- <img src="<?php echo plugins_url('ga-plugin-advert.jpg', __FILE__ ); ?>" alt="Google Analytics Getting It Right" />
784
- <form accept-charset="utf-8" action="https://app.getresponse.com/add_contact_webform.html" method="post" onsubmit="return quickValidate()" target="_blank">
785
- <div style="display: none;">
786
- <input type="hidden" name="webform_id" value="416798" />
787
- </div>
788
- <table style="text-align:center;margin-left: 20px;">
789
- <tr>
790
- <td><label class="previewLabel" for="awf_field-37978044"><strong>Name: </strong></label><input id="sub_name" type="text" name="name" class="text" tabindex="500" value="" /></td>
791
- <td><label class="previewLabel" for="awf_field-37978045"><strong>Email: </strong></label> <input class="text" id="sub_email" type="text" name="email" tabindex="501" value="" /></td>
792
- <td><span class="submit"><input name="submit" type="image" alt="submit" tabindex="502" src="<?php echo plugins_url('download-button.png', __FILE__); ?>" width="157" height="40" style="background: none; border: 0;" /></span></td>
793
- </tr>
794
- <tr>
795
- <td colspan="3" style="padding-top: 20px;">
796
- <a title="Privacy Policy" href="http://www.getresponse.com/permission-seal?lang=en" target="_blank"><img src="<?php echo plugins_url('privacy.png', __FILE__); ?>" alt="" title="" /></a>
797
- </td>
798
- </tr>
799
- </table>
800
- </form>
801
-
802
- <script type="text/javascript">
803
- function quickValidate()
804
- {
805
- if (! jQuery('#sub_name').val() )
806
- {
807
- alert('Your Name is required');
808
- return false;
809
- }
810
- if(! jQuery('#sub_email').val() )
811
- {
812
- alert('Your Email is required');
813
- return false;
814
- }
815
-
816
- return true;
817
- }
818
- </script>
819
- <?php endif;?>
820
-
821
822
<?php
823
}
@@ -972,8 +1032,12 @@ function add_google_analytics()
972
973
(function() {
974
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
975
- ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
976
- var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
977
})();
978
</script>
979
<?php
1
<?php
2
/*
3
* Plugin Name: Google Analyticator
4
+ * Version: 6.4.5
5
* Plugin URI: http://www.videousermanuals.com/google-analyticator/?utm_campaign=analyticator&utm_medium=plugin&utm_source=readme-txt
6
* Description: Adds the necessary JavaScript code to enable <a href="http://www.google.com/analytics/">Google's Analytics</a>. After enabling this plugin you need to authenticate with Google, then select your domain and you're set.
7
* Author: Video User Manuals Pty Ltd
9
* Text Domain: google-analyticator
10
*/
11
12
+ define('GOOGLE_ANALYTICATOR_VERSION', '6.4.5');
13
14
define('GOOGLE_ANALYTICATOR_CLIENTID', '1007949979410.apps.googleusercontent.com');
15
define('GOOGLE_ANALYTICATOR_CLIENTSECRET', 'q06U41XDXtzaXD14E-KO1hti'); //don't worry - this don't need to be secret in our case
25
define("key_ga_status", "ga_status", true);
26
define("key_ga_admin", "ga_admin_status", true);
27
define("key_ga_admin_disable", "ga_admin_disable", true);
28
+ define("key_ga_remarketing", 'ga_enable_remarketing', true );
29
+ define("key_ga_track_login", "key_ga_track_login", true );
30
+ define("key_ga_show_ad", "key_ga_show_ad", true );
31
define("key_ga_admin_role", "ga_admin_role", true);
32
define("key_ga_dashboard_role", "ga_dashboard_role", true);
33
define("key_ga_adsense", "ga_adsense", true);
64
add_option(key_ga_admin_disable, ga_admin_disable_default, '');
65
add_option(key_ga_admin_role, array('administrator'), '');
66
add_option(key_ga_dashboard_role, array('administrator'), '');
67
+ add_option(key_ga_show_ad, '1' );
68
add_option(key_ga_adsense, ga_adsense_default, '');
69
add_option(key_ga_extra, ga_extra_default, '');
70
add_option(key_ga_extra_after, ga_extra_after_default, '');
111
112
# Add the core Google Analytics script, with a high priority to ensure last script for async tracking
113
add_action('wp_head', 'add_google_analytics',99);
114
+
115
+ // ONly track WP login if requested.
116
+ if( get_option( key_ga_track_login ) )
117
+ add_action('login_head', 'add_google_analytics', 99);
118
119
# Initialize outbound link tracking
120
add_action('init', 'ga_outgoing_links');
377
378
// Update the widgets option
379
update_option(key_ga_annon, wp_filter_kses( $_POST[key_ga_annon] ) );
380
+
381
+ // Update enable remarketing
382
+ update_option(key_ga_remarketing, wp_filter_kses( $_POST[key_ga_remarketing] ) );
383
+
384
+ // Update key_ga_hide_ad
385
+ update_option(key_ga_show_ad, wp_filter_kses( $_POST[key_ga_show_ad] ) );
386
+
387
+ // Update enable tracking login
388
+ update_option(key_ga_track_login, wp_filter_kses( $_POST[key_ga_track_login] ) );
389
390
391
// Give an updated message
402
403
<div class="wrap">
404
405
+ <h2><?php _e('Google Analyticator Settings', 'google-analyticator'); ?></h2>
406
<form method="post" action="<?php echo admin_url('options-general.php?page=google-analyticator.php');?>">
407
<?php
408
# Add a nonce
419
<?php _e('Google Analytics integration is currently enabled, but you did not enter a UID. Tracking will not occur.', 'google-analyticator'); ?>
420
</div>
421
<?php } ?>
422
+
423
+ <div id="vumga-container" style="position:relative;">
424
+ <div id="vumga-sidebar" style="position: absolute; top: 0; right: 0; width: 250px; border: 1px solid #ccc; padding: 20px;">
425
+ <a href="http://get.videousermanuals.com/ga-pro/?utm_campaign=analyticatorpro&utm_medium=plugin&utm_source=settings" target="_blank"><img src="<?php echo plugins_url('gapro-plugin-advert-sidebar.png', __FILE__ ); ?>" alt="Learn More" title="Learn More" /></a>
426
+ </div>
427
+
428
+ <div style="margin-right: 320px;">
429
<table class="form-table" cellspacing="2" cellpadding="5" width="100%">
430
431
<tr>
592
<p class="setting-description"><?php _e('Selecting the "Remove" option will physically remove the tracking code from logged in users. Selecting the "Use \'admin\' variable" option will assign a variable called \'admin\' to logged in users. This option will allow Google Analytics\' site overlay feature to work, but you will have to manually configure Google Analytics to exclude tracking from pageviews with the \'admin\' variable.', 'google-analyticator'); ?></p>
593
</td>
594
</tr>
595
+ <tr>
596
+ <th width="30%" valign="top" style="padding-top: 10px;">
597
+ <label><?php _e('Enable remarketing', 'google-analyticator'); ?>:</label>
598
+ </th>
599
+ <td>
600
+ <?php
601
+ echo "<select name='".key_ga_remarketing."' id='".key_ga_remarketing."'>\n";
602
+
603
+ echo "<option value='0'";
604
+ if(get_option(key_ga_remarketing) == '0' )
605
+ echo" selected='selected'";
606
+ echo ">" . __('No', 'google-analyticator') . "</option>\n";
607
+
608
+
609
+ echo "<option value='1'";
610
+ if(get_option(key_ga_remarketing) == '1' )
611
+ echo " selected='selected'";
612
+ echo ">" . __('Yes', 'google-analyticator') . "</option>\n";
613
+
614
+
615
+ echo "</select>\n";
616
+
617
+ ?>
618
+ <p class="setting-description"><?php _e( 'In order to use remarketing, <a href="https://support.google.com/analytics/answer/2611270" target="_blank">please make sure you complete this checklist from Google</a>', 'google-analyticator'); ?></p>
619
+ </td>
620
+ </tr>
621
+ <tr>
622
+ <th width="30%" valign="top" style="padding-top: 10px;">
623
+ <label><?php _e('Track WordPress Login Page', 'google-analyticator'); ?>:</label>
624
+ </th>
625
+ <td>
626
+ <?php
627
+ echo "<select name='".key_ga_track_login."' id='".key_ga_track_login."'>\n";
628
+
629
+ echo "<option value='1'";
630
+ if(get_option(key_ga_track_login) == '1' )
631
+ echo " selected='selected'";
632
+ echo ">" . __('Yes', 'google-analyticator') . "</option>\n";
633
+
634
+ echo "<option value='0'";
635
+ if(get_option(key_ga_track_login) == '0' )
636
+ echo" selected='selected'";
637
+ echo ">" . __('No', 'google-analyticator') . "</option>\n";
638
+
639
+ echo "</select>\n";
640
+
641
+ ?>
642
+ <p class="setting-description"><?php _e( 'This will track all access to wp-login.php', 'google-analyticator'); ?></p>
643
+ </td>
644
+ </tr>
645
<tr>
646
<td colspan="2">
647
<h3>Link Tracking Settings</h3>
815
<p class="setting-description"><?php _e('Disabling this option will completely remove the Dashboard Summary widget and the theme Stats widget. Use this option if you would prefer to not see the widgets.', 'google-analyticator'); ?></p>
816
</td>
817
</tr>
818
+
819
+ <tr>
820
+ <th width="30%" valign="top" style="padding-top: 10px;">
821
+ <label for="<?php echo key_ga_widgets; ?>"><?php _e('Display Ad', 'google-analyticator'); ?>:</label>
822
+ </th>
823
+ <td>
824
+ <?php
825
+ echo "<select name='".key_ga_show_ad."' id='".key_ga_show_ad."'>\n";
826
+
827
+ echo "<option value='1'";
828
+ if(get_option(key_ga_show_ad) == '1')
829
+ echo " selected='selected'";
830
+ echo ">" . __('Yes', 'google-analyticator') . "</option>\n";
831
+
832
+ echo "<option value='0' ";
833
+ if(get_option(key_ga_show_ad) == '0')
834
+ echo" selected='selected'";
835
+ echo ">" . __('No', 'google-analyticator') . "</option>\n";
836
+
837
+ echo "</select>\n";
838
+ ?>
839
+ <p class="setting-description"><?php _e('You can disbale the ad on the admin dashboard.', 'google-analyticator'); ?></p>
840
+ </td>
841
+ </tr>
842
+
843
+
844
<tr<?php if(!$useAuth){echo ' style="display:none"';}?>>
845
<th width="30%" valign="top" style="padding-top: 10px;">
846
<label for="<?php echo key_ga_dashboard_role ?>"><?php _e('User roles that can see the dashboard widget', 'google-analyticator'); ?>:</label>
874
<a href="<?php echo admin_url('/options-general.php?page=ga_reset'); ?>"><?php _e('Deauthorize &amp; Reset Google Analyticator.', 'google-analyticator'); ?></a>
875
876
</form>
877
+ </div>
878
879
+ </div><!-- end wrap -->
880
+ </div><!-- end vumga-container -->
881
882
<?php
883
}
1032
1033
(function() {
1034
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
1035
+ <?php if( get_option( key_ga_remarketing ) ) : ?>
1036
+ ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
1037
+ <?php else: ?>
1038
+ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
1039
+ <?php endif; ?>
1040
+ var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
1041
})();
1042
</script>
1043
<?php
google-analytics-summary-widget.php CHANGED
@@ -298,6 +298,7 @@ class GoogleAnalyticsSummary
298
# Close the table
299
echo '</td></tr></table>';
300
301
# Grab the above outputs and cache it!
302
$ga_output = ob_get_flush();
303
@@ -311,6 +312,13 @@ class GoogleAnalyticsSummary
311
312
if( ! $doing_transient )
313
echo $ga_output;
314
315
die();
316
}
298
# Close the table
299
echo '</td></tr></table>';
300
301
+
302
# Grab the above outputs and cache it!
303
$ga_output = ob_get_flush();
304
312
313
if( ! $doing_transient )
314
echo $ga_output;
315
+
316
+ if( get_option( key_ga_show_ad ) ) {
317
+ echo '<p style="text-align:center">
318
+ <a href="http://www.videousermanuals.com/rd/ga-dashboard/" target="_BLANK">
319
+ Learn how to use Google Analytics <br />
320
+ To remove the guess work from your business </a></p>';
321
+ }
322
323
die();
324
}
google-api-php-client/src/Google_Client.php DELETED
@@ -1,453 +0,0 @@
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
- // Check for the required json and curl extensions, the Google APIs PHP Client
19
- // won't function without them.
20
- if (! function_exists('curl_init')) {
21
- throw new Exception('Google PHP API Client requires the CURL PHP extension');
22
- }
23
-
24
- if (! function_exists('json_decode')) {
25
- throw new Exception('Google PHP API Client requires the JSON PHP extension');
26
- }
27
-
28
- if (! function_exists('http_build_query')) {
29
- throw new Exception('Google PHP API Client requires http_build_query()');
30
- }
31
-
32
- if (! ini_get('date.timezone') && function_exists('date_default_timezone_set')) {
33
- date_default_timezone_set('UTC');
34
- }
35
-
36
- // hack around with the include paths a bit so the library 'just works'
37
- set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path());
38
-
39
- require_once "config.php";
40
- // If a local configuration file is found, merge it's values with the default configuration
41
- if (file_exists(dirname(__FILE__) . '/local_config.php')) {
42
- $defaultConfig = $apiConfig;
43
- require_once (dirname(__FILE__) . '/local_config.php');
44
- $apiConfig = array_merge($defaultConfig, $apiConfig);
45
- }
46
-
47
- // Include the top level classes, they each include their own dependencies
48
- require_once 'service/Google_Model.php';
49
- require_once 'service/Google_Service.php';
50
- require_once 'service/Google_ServiceResource.php';
51
- require_once 'auth/Google_AssertionCredentials.php';
52
- require_once 'auth/Google_Signer.php';
53
- require_once 'auth/Google_P12Signer.php';
54
- require_once 'service/Google_BatchRequest.php';
55
- require_once 'external/URITemplateParser.php';
56
- require_once 'auth/Google_Auth.php';
57
- require_once 'cache/Google_Cache.php';
58
- require_once 'io/Google_IO.php';
59
- require_once('service/Google_MediaFileUpload.php');
60
-
61
- /**
62
- * The Google API Client
63
- * http://code.google.com/p/google-api-php-client/
64
- *
65
- * @author Chris Chabot <chabotc@google.com>
66
- * @author Chirag Shah <chirags@google.com>
67
- */
68
- class Google_Client {
69
- /**
70
- * @static
71
- * @var Google_Auth $auth
72
- */
73
- static $auth;
74
-
75
- /**
76
- * @static
77
- * @var Google_IO $io
78
- */
79
- static $io;
80
-
81
- /**
82
- * @static
83
- * @var Google_Cache $cache
84
- */
85
- static $cache;
86
-
87
- /**
88
- * @static
89
- * @var boolean $useBatch
90
- */
91
- static $useBatch = false;
92
-
93
- /** @var array $scopes */
94
- protected $scopes = array();
95
-
96
- /** @var bool $useObjects */
97
- protected $useObjects = false;
98
-
99
- // definitions of services that are discovered.
100
- protected $services = array();
101
-
102
- // Used to track authenticated state, can't discover services after doing authenticate()
103
- private $authenticated = false;
104
-
105
- public function __construct($config = array()) {
106
- global $apiConfig;
107
- $apiConfig = array_merge($apiConfig, $config);
108
- self::$cache = new $apiConfig['cacheClass']();
109
- self::$auth = new $apiConfig['authClass']();
110
- self::$io = new $apiConfig['ioClass']();
111
- }
112
-
113
- /**
114
- * Add a service
115
- */
116
- public function addService($service, $version = false) {
117
- global $apiConfig;
118
- if ($this->authenticated) {
119
- throw new Google_Exception('Cant add services after having authenticated');
120
- }
121
- $this->services[$service] = array();
122
- if (isset($apiConfig['services'][$service])) {
123
- // Merge the service descriptor with the default values
124
- $this->services[$service] = array_merge($this->services[$service], $apiConfig['services'][$service]);
125
- }
126
- }
127
-
128
- public function authenticate($code = null) {
129
- $service = $this->prepareService();
130
- $this->authenticated = true;
131
- return self::$auth->authenticate($service, $code);
132
- }
133
-
134
- /**
135
- * @return array
136
- * @visible For Testing
137
- */
138
- public function prepareService() {
139
- $service = array();
140
- $scopes = array();
141
- if ($this->scopes) {
142
- $scopes = $this->scopes;
143
- } else {
144
- foreach ($this->services as $key => $val) {
145
- if (isset($val['scope'])) {
146
- if (is_array($val['scope'])) {
147
- $scopes = array_merge($val['scope'], $scopes);
148
- } else {
149
- $scopes[] = $val['scope'];
150
- }
151
- } else {
152
- $scopes[] = 'https://www.googleapis.com/auth/' . $key;
153
- }
154
- unset($val['discoveryURI']);
155
- unset($val['scope']);
156
- $service = array_merge($service, $val);
157
- }
158
- }
159
- $service['scope'] = implode(' ', $scopes);
160
- return $service;
161
- }
162
-
163
- /**
164
- * Set the OAuth 2.0 access token using the string that resulted from calling authenticate()
165
- * or Google_Client#getAccessToken().
166
- * @param string $accessToken JSON encoded string containing in the following format:
167
- * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
168
- * "expires_in":3600, "id_token":"TOKEN", "created":1320790426}
169
- */
170
- public function setAccessToken($accessToken) {
171
- if ($accessToken == null || 'null' == $accessToken) {
172
- $accessToken = null;
173
- }
174
- self::$auth->setAccessToken($accessToken);
175
- }
176
-
177
- /**
178
- * Set the type of Auth class the client should use.
179
- * @param string $authClassName
180
- */
181
- public function setAuthClass($authClassName) {
182
- self::$auth = new $authClassName();
183
- }
184
-
185
- /**
186
- * Construct the OAuth 2.0 authorization request URI.
187
- * @return string
188
- */
189
- public function createAuthUrl() {
190
- $service = $this->prepareService();
191
- return self::$auth->createAuthUrl($service['scope']);
192
- }
193
-
194
- /**
195
- * Get the OAuth 2.0 access token.
196
- * @return string $accessToken JSON encoded string in the following format:
197
- * {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
198
- * "expires_in":3600,"id_token":"TOKEN", "created":1320790426}
199
- */
200
- public function getAccessToken() {
201
- $token = self::$auth->getAccessToken();
202
- return (null == $token || 'null' == $token) ? null : $token;
203
- }
204
-
205
- /**
206
- * Returns if the access_token is expired.
207
- * @return bool Returns True if the access_token is expired.
208
- */
209
- public function isAccessTokenExpired() {
210
- return self::$auth->isAccessTokenExpired();
211
- }
212
-
213
- /**
214
- * Set the developer key to use, these are obtained through the API Console.
215
- * @see http://code.google.com/apis/console-help/#generatingdevkeys
216
- * @param string $developerKey
217
- */
218
- public function setDeveloperKey($developerKey) {
219
- self::$auth->setDeveloperKey($developerKey);
220
- }
221
-
222
- /**
223
- * Set OAuth 2.0 "state" parameter to achieve per-request customization.
224
- * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
225
- * @param string $state
226
- */
227
- public function setState($state) {
228
- self::$auth->setState($state);
229
- }
230
-
231
- /**
232
- * @param string $accessType Possible values for access_type include:
233
- * {@code "offline"} to request offline access from the user. (This is the default value)
234
- * {@code "online"} to request online access from the user.
235
- */
236
- public function setAccessType($accessType) {
237
- self::$auth->setAccessType($accessType);
238
- }
239
-
240
- /**
241
- * @param string $approvalPrompt Possible values for approval_prompt include:
242
- * {@code "force"} to force the approval UI to appear. (This is the default value)
243
- * {@code "auto"} to request auto-approval when possible.
244
- */
245
- public function setApprovalPrompt($approvalPrompt) {
246
- self::$auth->setApprovalPrompt($approvalPrompt);
247
- }
248
-
249
- /**
250
- * Set the application name, this is included in the User-Agent HTTP header.
251
- * @param string $applicationName
252
- */
253
- public function setApplicationName($applicationName) {
254
- global $apiConfig;
255
- $apiConfig['application_name'] = $applicationName;
256
- }
257
-
258
- /**
259
- * Set the OAuth 2.0 Client ID.
260
- * @param string $clientId
261
- */
262
- public function setClientId($clientId) {
263
- global $apiConfig;
264
- $apiConfig['oauth2_client_id'] = $clientId;
265
- self::$auth->clientId = $clientId;
266
- }
267
-
268
- /**
269
- * Get the OAuth 2.0 Client ID.
270
- */
271
- public function getClientId() {
272
- return self::$auth->clientId;
273
- }
274
-
275
- /**
276
- * Set the OAuth 2.0 Client Secret.
277
- * @param string $clientSecret
278
- */
279
- public function setClientSecret($clientSecret) {
280
- global $apiConfig;
281
- $apiConfig['oauth2_client_secret'] = $clientSecret;
282
- self::$auth->clientSecret = $clientSecret;
283
- }
284
-
285
- /**
286
- * Get the OAuth 2.0 Client Secret.
287
- */
288
- public function getClientSecret() {
289
- return self::$auth->clientSecret;
290
- }
291
-
292
- /**
293
- * Set the OAuth 2.0 Redirect URI.
294
- * @param string $redirectUri
295
- */
296
- public function setRedirectUri($redirectUri) {
297
- global $apiConfig;
298
- $apiConfig['oauth2_redirect_uri'] = $redirectUri;
299
- self::$auth->redirectUri = $redirectUri;
300
- }
301
-
302
- /**
303
- * Get the OAuth 2.0 Redirect URI.
304
- */
305
- public function getRedirectUri() {
306
- return self::$auth->redirectUri;
307
- }
308
-
309
- /**
310
- * Fetches a fresh OAuth 2.0 access token with the given refresh token.
311
- * @param string $refreshToken
312
- * @return void
313
- */
314
- public function refreshToken($refreshToken) {
315
- self::$auth->refreshToken($refreshToken);
316
- }
317
-
318
- /**
319
- * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
320
- * token, if a token isn't provided.
321
- * @throws Google_AuthException
322
- * @param string|null $token The token (access token or a refresh token) that should be revoked.
323
- * @return boolean Returns True if the revocation was successful, otherwise False.
324
- */
325
- public function revokeToken($token = null) {
326
- self::$auth->revokeToken($token);
327
- }
328
-
329
- /**
330
- * Verify an id_token. This method will verify the current id_token, if one
331
- * isn't provided.
332
- * @throws Google_AuthException
333
- * @param string|null $token The token (id_token) that should be verified.
334
- * @return Google_LoginTicket Returns an apiLoginTicket if the verification was
335
- * successful.
336
- */
337
- public function verifyIdToken($token = null) {
338
- return self::$auth->verifyIdToken($token);
339
- }
340
-
341
- /**
342
- * @param Google_AssertionCredentials $creds
343
- * @return void
344
- */
345
- public function setAssertionCredentials(Google_AssertionCredentials $creds) {
346
- self::$auth->setAssertionCredentials($creds);
347
- }
348
-
349
- /**
350
- * This function allows you to overrule the automatically generated scopes,
351
- * so that you can ask for more or less permission in the auth flow
352
- * Set this before you call authenticate() though!
353
- * @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/moderator')
354
- */
355
- public function setScopes($scopes) {
356
- $this->scopes = is_string($scopes) ? explode(" ", $scopes) : $scopes;
357
- }
358
-
359
- /**
360
- * Declare if objects should be returned by the api service classes.
361
- *
362
- * @param boolean $useObjects True if objects should be returned by the service classes.
363
- * False if associative arrays should be returned (default behavior).
364
- * @experimental
365
- */
366
- public function setUseObjects($useObjects) {
367
- global $apiConfig;
368
- $apiConfig['use_objects'] = $useObjects;
369
- }
370
-
371
- /**
372
- * Declare if objects should be returned by the api service classes.
373
- *
374
- * @param boolean $useBatch True if the experimental batch support should
375
- * be enabled. Defaults to False.
376
- * @experimental
377
- */
378
- public function setUseBatch($useBatch) {
379
- self::$useBatch = $useBatch;
380
- }
381
-
382
- /**
383
- * @static
384
- * @return Google_Auth the implementation of apiAuth.
385
- */
386
- public static function getAuth() {
387
- return Google_Client::$auth;
388
- }
389
-
390
- /**
391
- * @static
392
- * @return Google_IO the implementation of apiIo.
393
- */
394
- public static function getIo() {
395
- return Google_Client::$io;
396
- }
397
-
398
- /**
399
- * @return Google_Cache the implementation of apiCache.
400
- */
401
- public function getCache() {
402
- return Google_Client::$cache;
403
- }
404
- }
405
-
406
- // Exceptions that the Google PHP API Library can throw
407
- class Google_Exception extends Exception {}
408
- class Google_AuthException extends Google_Exception {}
409
- class Google_CacheException extends Google_Exception {}
410
- class Google_IOException extends Google_Exception {}
411
- class Google_ServiceException extends Google_Exception {
412
- /**
413
- * Optional list of errors returned in a JSON body of an HTTP error response.
414
- */
415
- protected $errors = array();
416
-
417
- /**
418
- * Override default constructor to add ability to set $errors.
419
- *
420
- * @param string $message
421
- * @param int $code
422
- * @param Exception|null $previous
423
- * @param [{string, string}] errors List of errors returned in an HTTP
424
- * response. Defaults to [].
425
- */
426
- public function __construct($message, $code = 0, Exception $previous = null,
427
- $errors = array()) {
428
- if(version_compare(PHP_VERSION, '5.3.0') >= 0) {
429
- parent::__construct($message, $code, $previous);
430
- } else {
431
- parent::__construct($message, $code);
432
- }
433
-
434
- $this->errors = $errors;
435
- }
436
-
437
- /**
438
- * An example of the possible errors returned.
439
- *
440
- * {
441
- * "domain": "global",
442
- * "reason": "authError",
443
- * "message": "Invalid Credentials",
444
- * "locationType": "header",
445
- * "location": "Authorization",
446
- * }
447
- *
448
- * @return [{string, string}] List of errors return in an HTTP response or [].
449
- */
450
- public function getErrors() {
451
- return $this->errors;
452
- }
453
- }
google-api-php-client/src/auth/Google_AssertionCredentials.php DELETED
@@ -1,95 +0,0 @@
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
- /**
19
- * Credentials object used for OAuth 2.0 Signed JWT assertion grants.
20
- *
21
- * @author Chirag Shah <chirags@google.com>
22
- */
23
- class Google_AssertionCredentials {
24
- const MAX_TOKEN_LIFETIME_SECS = 3600;
25
-
26
- public $serviceAccountName;
27
- public $scopes;
28
- public $privateKey;
29
- public $privateKeyPassword;
30
- public $assertionType;
31
- public $prn;
32
-
33
- /**
34
- * @param $serviceAccountName
35
- * @param $scopes array List of scopes
36
- * @param $privateKey
37
- * @param string $privateKeyPassword
38
- * @param string $assertionType
39
- * @param bool|string $prn The email address of the user for which the
40
- * application is requesting delegated access.
41
- */
42
- public function __construct(
43
- $serviceAccountName,
44
- $scopes,
45
- $privateKey,
46
- $privateKeyPassword = 'notasecret',
47
- $assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
48
- $prn = false) {
49
- $this->serviceAccountName = $serviceAccountName;
50
- $this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
51
- $this->privateKey = $privateKey;
52
- $this->privateKeyPassword = $privateKeyPassword;
53
- $this->assertionType = $assertionType;
54
- $this->prn = $prn;
55
- }
56
-
57
- public function generateAssertion() {
58
- $now = time();
59
-
60
- $jwtParams = array(
61
- 'aud' => Google_OAuth2::OAUTH2_TOKEN_URI,
62
- 'scope' => $this->scopes,
63
- 'iat' => $now,
64
- 'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
65
- 'iss' => $this->serviceAccountName,
66
- );
67
-
68
- if ($this->prn !== false) {
69
- $jwtParams['prn'] = $this->prn;
70
- }
71
-
72
- return $this->makeSignedJwt($jwtParams);
73
- }
74
-
75
- /**
76
- * Creates a signed JWT.
77
- * @param array $payload
78
- * @return string The signed JWT.
79
- */
80
- private function makeSignedJwt($payload) {
81
- $header = array('typ' => 'JWT', 'alg' => 'RS256');
82
-
83
- $segments = array(
84
- Google_Utils::urlSafeB64Encode(json_encode($header)),
85
- Google_Utils::urlSafeB64Encode(json_encode($payload))
86
- );
87
-
88
- $signingInput = implode('.', $segments);
89
- $signer = new Google_P12Signer($this->privateKey, $this->privateKeyPassword);
90
- $signature = $signer->sign($signingInput);
91
- $segments[] = Google_Utils::urlSafeB64Encode($signature);
92
-
93
- return implode(".", $segments);
94
- }
95
- }
google-api-php-client/src/auth/Google_Auth.php DELETED
@@ -1,36 +0,0 @@
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
- require_once "Google_AuthNone.php";
19
- require_once "Google_OAuth2.php";
20
-
21
- /**
22
- * Abstract class for the Authentication in the API client
23
- * @author Chris Chabot <chabotc@google.com>
24
- *
25
- */
26
- abstract class Google_Auth {
27
- abstract public function authenticate($service);
28
- abstract public function sign(Google_HttpRequest $request);
29
- abstract public function createAuthUrl($scope);
30
-
31
- abstract public function getAccessToken();
32
- abstract public function setAccessToken($accessToken);
33
- abstract public function setDeveloperKey($developerKey);
34
- abstract public function refreshToken($refreshToken);
35
- abstract public function revokeToken();
36
- }
google-api-php-client/src/auth/Google_AuthNone.php DELETED
@@ -1,48 +0,0 @@
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
- * Do-nothing authentication implementation, use this if you want to make un-authenticated calls
20
- * @author Chris Chabot <chabotc@google.com>
21
- * @author Chirag Shah <chirags@google.com>
22
- */
23
- class Google_AuthNone extends Google_Auth {
24
- public $key = null;
25
-
26
- public function __construct() {
27
- global $apiConfig;
28
- if (!empty($apiConfig['developer_key'])) {
29
- $this->setDeveloperKey($apiConfig['developer_key']);
30
- }
31
- }
32
-
33
- public function setDeveloperKey($key) {$this->key = $key;}
34
- public function authenticate($service) {/*noop*/}
35
- public function setAccessToken($accessToken) {/* noop*/}
36
- public function getAccessToken() {return null;}
37
- public function createAuthUrl($scope) {return null;}
38
- public function refreshToken($refreshToken) {/* noop*/}
39
- public function revokeToken() {/* noop*/}
40
-
41
- public function sign(Google_HttpRequest $request) {
42
- if ($this->key) {
43
- $request->setUrl($request->getUrl() . ((strpos($request->getUrl(), '?') === false) ? '?' : '&')
44
- . 'key='.urlencode($this->key));
45
- }
46
- return $request;
47
- }
48
- }
google-api-php-client/src/auth/Google_LoginTicket.php DELETED
@@ -1,63 +0,0 @@
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
- /**
19
- * Class to hold information about an authenticated login.
20
- *
21
- * @author Brian Eaton <beaton@google.com>
22
- */
23
- class Google_LoginTicket {
24
- const USER_ATTR = "id";
25
-
26
- // Information from id token envelope.
27
- private $envelope;
28
-
29
- // Information from id token payload.
30
- private $payload;
31
-
32
- /**
33
- * Creates a user based on the supplied token.
34
- *
35
- * @param string $envelope Header from a verified authentication token.
36
- * @param string $payload Information from a verified authentication token.
37
- */
38
- public function __construct($envelope, $payload) {
39
- $this->envelope = $envelope;
40
- $this->payload = $payload;
41
- }
42
-
43
- /**
44
- * Returns the numeric identifier for the user.
45
- * @throws Google_AuthException
46
- * @return
47
- */
48
- public function getUserId() {
49
- if (array_key_exists(self::USER_ATTR, $this->payload)) {
50
- return $this->payload[self::USER_ATTR];
51
- }
52
- throw new Google_AuthException("No user_id in token");
53
- }
54
-
55
- /**
56
- * Returns attributes from the login ticket. This can contain
57
- * various information about the user session.
58
- * @return array
59
- */
60
- public function getAttributes() {
61
- return array("envelope" => $this->envelope, "payload" => $this->payload);
62
- }
63
- }
google-api-php-client/src/auth/Google_OAuth2.php DELETED
@@ -1,444 +0,0 @@
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
- require_once "Google_Verifier.php";
19
- require_once "Google_LoginTicket.php";
20
- require_once "service/Google_Utils.php";
21
-
22
- /**
23
- * Authentication class that deals with the OAuth 2 web-server authentication flow
24
- *
25
- * @author Chris Chabot <chabotc@google.com>
26
- * @author Chirag Shah <chirags@google.com>
27
- *
28
- */
29
- class Google_OAuth2 extends Google_Auth {
30
- public $clientId;
31
- public $clientSecret;
32
- public $developerKey;
33
- public $token;
34
- public $redirectUri;
35
- public $state;
36
- public $accessType = 'offline';
37
- public $approvalPrompt = 'force';
38
-
39
- /** @var Google_AssertionCredentials $assertionCredentials */
40
- public $assertionCredentials;
41
-
42
- const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
43
- const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
44
- const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
45
- const OAUTH2_FEDERATED_SIGNON_CERTS_URL = 'https://www.googleapis.com/oauth2/v1/certs';
46
- const CLOCK_SKEW_SECS = 300; // five minutes in seconds
47
- const AUTH_TOKEN_LIFETIME_SECS = 300; // five minutes in seconds
48
- const MAX_TOKEN_LIFETIME_SECS = 86400; // one day in seconds
49
-
50
- /**
51
- * Instantiates the class, but does not initiate the login flow, leaving it
52
- * to the discretion of the caller (which is done by calling authenticate()).
53
- */
54
- public function __construct() {
55
- global $apiConfig;
56
-
57
- if (! empty($apiConfig['developer_key'])) {
58
- $this->developerKey = $apiConfig['developer_key'];
59
- }
60
-
61
- if (! empty($apiConfig['oauth2_client_id'])) {
62
- $this->clientId = $apiConfig['oauth2_client_id'];
63
- }
64
-
65
- if (! empty($apiConfig['oauth2_client_secret'])) {
66
- $this->clientSecret = $apiConfig['oauth2_client_secret'];
67
- }
68
-
69
- if (! empty($apiConfig['oauth2_redirect_uri'])) {
70
- $this->redirectUri = $apiConfig['oauth2_redirect_uri'];
71
- }
72
-
73
- if (! empty($apiConfig['oauth2_access_type'])) {
74
- $this->accessType = $apiConfig['oauth2_access_type'];
75
- }
76
-
77
- if (! empty($apiConfig['oauth2_approval_prompt'])) {
78
- $this->approvalPrompt = $apiConfig['oauth2_approval_prompt'];
79
- }
80
- }
81
-
82
- /**
83
- * @param $service
84
- * @param string|null $code
85
- * @throws Google_AuthException
86
- * @return string
87
- */
88
- public function authenticate($service, $code = null) {
89
- if (!$code && isset($_GET['code'])) {
90
- $code = $_GET['code'];
91
- }
92
-
93
- if ($code) {
94
- // We got here from the redirect from a successful authorization grant, fetch the access token
95
- $request = Google_Client::$io->makeRequest(new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
96
- 'code' => $code,
97
- 'grant_type' => 'authorization_code',
98
- 'redirect_uri' => $this->redirectUri,
99
- 'client_id' => $this->clientId,
100
- 'client_secret' => $this->clientSecret
101
- )));
102
-
103
- if ($request->getResponseHttpCode() == 200) {
104
- $this->setAccessToken($request->getResponseBody());
105
- $this->token['created'] = time();
106
- return $this->getAccessToken();
107
- } else {
108
- $response = $request->getResponseBody();
109
- $decodedResponse = json_decode($response, true);
110
- if ($decodedResponse != null && $decodedResponse['error']) {
111
- $response = $decodedResponse['error'];
112
- }
113
- throw new Google_AuthException("Error fetching OAuth2 access token, message: '$response'", $request->getResponseHttpCode());
114
- }
115
- }
116
-
117
- $authUrl = $this->createAuthUrl($service['scope']);
118
- header('Location: ' . $authUrl);
119
- return true;
120
- }
121
-
122
- /**
123
- * Create a URL to obtain user authorization.
124
- * The authorization endpoint allows the user to first
125
- * authenticate, and then grant/deny the access request.
126
- * @param string $scope The scope is expressed as a list of space-delimited strings.
127
- * @return string
128
- */
129
- public function createAuthUrl($scope) {
130
- $params = array(
131
- 'response_type=code',
132
- 'redirect_uri=' . urlencode($this->redirectUri),
133
- 'client_id=' . urlencode($this->clientId),
134
- 'scope=' . urlencode($scope),
135
- 'access_type=' . urlencode($this->accessType),
136
- 'approval_prompt=' . urlencode($this->approvalPrompt)
137
- );
138
-
139
- if (isset($this->state)) {
140
- $params[] = 'state=' . urlencode($this->state);
141
- }
142
- $params = implode('&', $params);
143
- return self::OAUTH2_AUTH_URL . "?$params";
144
- }
145
-
146
- /**
147
- * @param string $token
148
- * @throws Google_AuthException
149
- */
150
- public function setAccessToken($token) {
151
- $token = json_decode($token, true);
152
- if ($token == null) {
153
- throw new Google_AuthException('Could not json decode the token');
154
- }
155
- if (! isset($token['access_token'])) {
156
- throw new Google_AuthException("Invalid token format");
157
- }
158
- $this->token = $token;
159
- }
160
-
161
- public function getAccessToken() {
162
- return json_encode($this->token);
163
- }
164
-
165
- public function setDeveloperKey($developerKey) {
166
- $this->developerKey = $developerKey;
167
- }
168
-
169
- public function setState($state) {
170
- $this->state = $state;
171
- }
172
-
173
- public function setAccessType($accessType) {
174
- $this->accessType = $accessType;
175
- }
176
-
177
- public function setApprovalPrompt($approvalPrompt) {
178
- $this->approvalPrompt = $approvalPrompt;
179
- }
180
-
181
- public function setAssertionCredentials(Google_AssertionCredentials $creds) {
182
- $this->assertionCredentials = $creds;
183
- }
184
-
185
- /**
186
- * Include an accessToken in a given apiHttpRequest.
187
- * @param Google_HttpRequest $request
188
- * @return Google_HttpRequest
189
- * @throws Google_AuthException
190
- */
191
- public function sign(Google_HttpRequest $request) {
192
- // add the developer key to the request before signing it
193
- if ($this->developerKey) {
194
- $requestUrl = $request->getUrl();
195
- $requestUrl .= (strpos($request->getUrl(), '?') === false) ? '?' : '&';
196
- $requestUrl .= 'key=' . urlencode($this->developerKey);
197
- $request->setUrl($requestUrl);
198
- }
199
-
200
- // Cannot sign the request without an OAuth access token.
201
- if (null == $this->token && null == $this->assertionCredentials) {
202
- return $request;
203
- }
204
-
205
- // Check if the token is set to expire in the next 30 seconds
206
- // (or has already expired).
207
- if ($this->isAccessTokenExpired()) {
208
- if ($this->assertionCredentials) {
209
- $this->refreshTokenWithAssertion();
210
- } else {
211
- if (! array_key_exists('refresh_token', $this->token)) {
212
- throw new Google_AuthException("The OAuth 2.0 access token has expired, "
213
- . "and a refresh token is not available. Refresh tokens are not "
214
- . "returned for responses that were auto-approved.");
215
- }
216
- $this->refreshToken($this->token['refresh_token']);
217
- }
218
- }
219
-
220
- // Add the OAuth2 header to the request
221
- $request->setRequestHeaders(
222
- array('Authorization' => 'Bearer ' . $this->token['access_token'])
223
- );
224
-
225
- return $request;
226
- }
227
-
228
- /**
229
- * Fetches a fresh access token with the given refresh token.
230
- * @param string $refreshToken
231
- * @return void
232
- */
233
- public function refreshToken($refreshToken) {
234
- $this->refreshTokenRequest(array(
235
- 'client_id' => $this->clientId,
236
- 'client_secret' => $this->clientSecret,
237
- 'refresh_token' => $refreshToken,
238
- 'grant_type' => 'refresh_token'
239
- ));
240
- }
241
-
242
- /**
243
- * Fetches a fresh access token with a given assertion token.
244
- * @param Google_AssertionCredentials $assertionCredentials optional.
245
- * @return void
246
- */
247
- public function refreshTokenWithAssertion($assertionCredentials = null) {
248
- if (!$assertionCredentials) {
249
- $assertionCredentials = $this->assertionCredentials;
250
- }
251
-
252
- $this->refreshTokenRequest(array(
253
- 'grant_type' => 'assertion',
254
- 'assertion_type' => $assertionCredentials->assertionType,
255
- 'assertion' => $assertionCredentials->generateAssertion(),
256
- ));
257
- }
258
-
259
- private function refreshTokenRequest($params) {
260
- $http = new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), $params);
261
- $request = Google_Client::$io->makeRequest($http);
262
-
263
- $code = $request->getResponseHttpCode();
264
- $body = $request->getResponseBody();
265
- if (200 == $code) {
266
- $token = json_decode($body, true);
267
- if ($token == null) {
268
- throw new Google_AuthException("Could not json decode the access token");
269
- }
270
-
271
- if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
272
- throw new Google_AuthException("Invalid token format");
273
- }
274
-
275
- $this->token['access_token'] = $token['access_token'];
276
- $this->token['expires_in'] = $token['expires_in'];
277
- $this->token['created'] = time();
278
- } else {
279
- throw new Google_AuthException("Error refreshing the OAuth2 token, message: '$body'", $code);
280
- }
281
- }
282
-
283
- /**
284
- * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
285
- * token, if a token isn't provided.
286
- * @throws Google_AuthException
287
- * @param string|null $token The token (access token or a refresh token) that should be revoked.
288
- * @return boolean Returns True if the revocation was successful, otherwise False.
289
- */
290
- public function revokeToken($token = null) {
291
- if (!$token) {
292
- $token = $this->token['access_token'];
293
- }
294
- $request = new Google_HttpRequest(self::OAUTH2_REVOKE_URI, 'POST', array(), "token=$token");
295
- $response = Google_Client::$io->makeRequest($request);
296
- $code = $response->getResponseHttpCode();
297
- if ($code == 200) {
298
- $this->token = null;
299
- return true;
300
- }
301
-
302
- return false;
303
- }
304
-
305
- /**
306
- * Returns if the access_token is expired.
307
- * @return bool Returns True if the access_token is expired.
308
- */
309
- public function isAccessTokenExpired() {
310
- if (null == $this->token) {
311
- return true;
312
- }
313
-
314
- // If the token is set to expire in the next 30 seconds.
315
- $expired = ($this->token['created']
316
- + ($this->token['expires_in'] - 30)) < time();
317
-
318
- return $expired;
319
- }
320
-
321
- // Gets federated sign-on certificates to use for verifying identity tokens.
322
- // Returns certs as array structure, where keys are key ids, and values
323
- // are PEM encoded certificates.
324
- private function getFederatedSignOnCerts() {
325
- // This relies on makeRequest caching certificate responses.
326
- $request = Google_Client::$io->makeRequest(new Google_HttpRequest(
327
- self::OAUTH2_FEDERATED_SIGNON_CERTS_URL));
328
- if ($request->getResponseHttpCode() == 200) {
329
- $certs = json_decode($request->getResponseBody(), true);
330
- if ($certs) {
331
- return $certs;
332
- }
333
- }
334
- throw new Google_AuthException(
335
- "Failed to retrieve verification certificates: '" .
336
- $request->getResponseBody() . "'.",
337
- $request->getResponseHttpCode());
338
- }
339
-
340
- /**
341
- * Verifies an id token and returns the authenticated apiLoginTicket.
342
- * Throws an exception if the id token is not valid.
343
- * The audience parameter can be used to control which id tokens are
344
- * accepted. By default, the id token must have been issued to this OAuth2 client.
345
- *
346
- * @param $id_token
347
- * @param $audience
348
- * @return Google_LoginTicket
349
- */
350
- public function verifyIdToken($id_token = null, $audience = null) {
351
- if (!$id_token) {
352
- $id_token = $this->token['id_token'];
353
- }
354
-
355
- $certs = $this->getFederatedSignonCerts();
356
- if (!$audience) {
357
- $audience = $this->clientId;
358
- }
359
- return $this->verifySignedJwtWithCerts($id_token, $certs, $audience);
360
- }
361
-
362
- // Verifies the id token, returns the verified token contents.
363
- // Visible for testing.
364
- function verifySignedJwtWithCerts($jwt, $certs, $required_audience) {
365
- $segments = explode(".", $jwt);
366
- if (count($segments) != 3) {
367
- throw new Google_AuthException("Wrong number of segments in token: $jwt");
368
- }
369
- $signed = $segments[0] . "." . $segments[1];
370
- $signature = Google_Utils::urlSafeB64Decode($segments[2]);
371
-
372
- // Parse envelope.
373
- $envelope = json_decode(Google_Utils::urlSafeB64Decode($segments[0]), true);
374
- if (!$envelope) {
375
- throw new Google_AuthException("Can't parse token envelope: " . $segments[0]);
376
- }
377
-
378
- // Parse token
379
- $json_body = Google_Utils::urlSafeB64Decode($segments[1]);
380
- $payload = json_decode($json_body, true);
381
- if (!$payload) {
382
- throw new Google_AuthException("Can't parse token payload: " . $segments[1]);
383
- }
384
-
385
- // Check signature
386
- $verified = false;
387
- foreach ($certs as $keyName => $pem) {
388
- $public_key = new Google_PemVerifier($pem);
389
- if ($public_key->verify($signed, $signature)) {
390
- $verified = true;
391
- break;
392
- }
393
- }
394
-
395
- if (!$verified) {
396
- throw new Google_AuthException("Invalid token signature: $jwt");
397
- }
398
-
399
- // Check issued-at timestamp
400
- $iat = 0;
401
- if (array_key_exists("iat", $payload)) {
402
- $iat = $payload["iat"];
403
- }
404
- if (!$iat) {
405
- throw new Google_AuthException("No issue time in token: $json_body");
406
- }
407
- $earliest = $iat - self::CLOCK_SKEW_SECS;
408
-
409
- // Check expiration timestamp
410
- $now = time();
411
- $exp = 0;
412
- if (array_key_exists("exp", $payload)) {
413
- $exp = $payload["exp"];
414
- }
415
- if (!$exp) {
416
- throw new Google_AuthException("No expiration time in token: $json_body");
417
- }
418
- if ($exp >= $now + self::MAX_TOKEN_LIFETIME_SECS) {
419
- throw new Google_AuthException(
420
- "Expiration time too far in future: $json_body");
421
- }
422
-
423
- $latest = $exp + self::CLOCK_SKEW_SECS;
424
- if ($now < $earliest) {
425
- throw new Google_AuthException(
426
- "Token used too early, $now < $earliest: $json_body");
427
- }
428
- if ($now > $latest) {
429
- throw new Google_AuthException(
430
- "Token used too late, $now > $latest: $json_body");
431
- }
432
-
433
- // TODO(beaton): check issuer field?
434
-
435
- // Check audience
436
- $aud = $payload["aud"];
437
- if ($aud != $required_audience) {
438
- throw new Google_AuthException("Wrong recipient, $aud != $required_audience: $json_body");
439
- }
440
-
441
- // All good.
442
- return new Google_LoginTicket($envelope, $payload);
443
- }
444
- }
google-api-php-client/src/auth/Google_P12Signer.php DELETED
@@ -1,70 +0,0 @@
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
- /**
19
- * Signs data.
20
- *
21
- * Only used for testing.
22
- *
23
- * @author Brian Eaton <beaton@google.com>
24
- */
25
- class Google_P12Signer extends Google_Signer {
26
- // OpenSSL private key resource
27
- private $privateKey;
28
-
29
- // Creates a new signer from a .p12 file.
30
- function __construct($p12, $password) {
31
- if (!function_exists('openssl_x509_read')) {
32
- throw new Exception(
33
- 'The Google PHP API library needs the openssl PHP extension');
34
- }
35
-
36
- // This throws on error
37
- $certs = array();
38
- if (!openssl_pkcs12_read($p12, $certs, $password)) {
39
- throw new Google_AuthException("Unable to parse the p12 file. " .
40
- "Is this a .p12 file? Is the password correct? OpenSSL error: " .
41
- openssl_error_string());
42
- }
43
- // TODO(beaton): is this part of the contract for the openssl_pkcs12_read
44
- // method? What happens if there are multiple private keys? Do we care?
45
- if (!array_key_exists("pkey", $certs) || !$certs["pkey"]) {
46
- throw new Google_AuthException("No private key found in p12 file.");
47
- }
48
- $this->privateKey = openssl_pkey_get_private($certs["pkey"]);
49
- if (!$this->privateKey) {
50
- throw new Google_AuthException("Unable to load private key in ");
51
- }
52
- }
53
-
54
- function __destruct() {
55
- if ($this->privateKey) {
56
- openssl_pkey_free($this->privateKey);
57
- }
58
- }
59
-
60
- function sign($data) {
61
- if(version_compare(PHP_VERSION, '5.3.0') < 0) {
62
- throw new Google_AuthException(
63
- "PHP 5.3.0 or higher is required to use service accounts.");
64
- }
65
- if (!openssl_sign($data, $signature, $this->privateKey, "sha256")) {
66
- throw new Google_AuthException("Unable to sign data");
67
- }
68
- return $signature;
69
- }
70
- }
google-api-php-client/src/auth/Google_PemVerifier.php DELETED
@@ -1,66 +0,0 @@
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
- /**
19
- * Verifies signatures using PEM encoded certificates.
20
- *
21
- * @author Brian Eaton <beaton@google.com>
22
- */
23
- class Google_PemVerifier extends Google_Verifier {
24
- private $publicKey;
25
-
26
- /**
27
- * Constructs a verifier from the supplied PEM-encoded certificate.
28
- *
29
- * $pem: a PEM encoded certificate (not a file).
30
- * @param $pem
31
- * @throws Google_AuthException
32
- * @throws Google_Exception
33
- */
34
- function __construct($pem) {
35
- if (!function_exists('openssl_x509_read')) {
36
- throw new Google_Exception('Google API PHP client needs the openssl PHP extension');
37
- }
38
- $this->publicKey = openssl_x509_read($pem);
39
- if (!$this->publicKey) {
40
- throw new Google_AuthException("Unable to parse PEM: $pem");
41
- }
42
- }
43
-
44
- function __destruct() {
45
- if ($this->publicKey) {
46
- openssl_x509_free($this->publicKey);
47
- }
48
- }
49
-
50
- /**
51
- * Verifies the signature on data.
52
- *
53
- * Returns true if the signature is valid, false otherwise.
54
- * @param $data
55
- * @param $signature
56
- * @throws Google_AuthException
57
- * @return bool
58
- */
59
- function verify($data, $signature) {
60
- $status = openssl_verify($data, $signature, $this->publicKey, "sha256");
61
- if ($status === -1) {
62
- throw new Google_AuthException('Signature verification error: ' . openssl_error_string());
63
- }
64
- return $status === 1;
65
- }
66
- }
google-api-php-client/src/auth/Google_Signer.php DELETED
@@ -1,30 +0,0 @@
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
- require_once "Google_P12Signer.php";
19
-
20
- /**
21
- * Signs data.
22
- *
23
- * @author Brian Eaton <beaton@google.com>
24
- */
25
- abstract class Google_Signer {
26
- /**
27
- * Signs data, returns the signature as binary data.
28
- */
29
- abstract public function sign($data);
30
- }
google-api-php-client/src/auth/Google_Verifier.php DELETED
@@ -1,31 +0,0 @@
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
- require_once "Google_PemVerifier.php";
19
-
20
- /**
21
- * Verifies signatures.
22
- *
23
- * @author Brian Eaton <beaton@google.com>
24
- */
25
- abstract class Google_Verifier {
26
- /**
27
- * Checks a signature, returns true if the signature is correct,
28
- * false otherwise.
29
- */
30
- abstract public function verify($data, $signature);
31
- }
google-api-php-client/src/cache/Google_ApcCache.php DELETED
@@ -1,98 +0,0 @@
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 persistent storage class based on the APC cache, which is not
20
- * really very persistent, as soon as you restart your web server
21
- * the storage will be wiped, however for debugging and/or speed
22
- * it can be useful, kinda, and cache is a lot cheaper then storage.
23
- *
24
- * @author Chris Chabot <chabotc@google.com>
25
- */
26
- class googleApcCache extends Google_Cache {
27
-
28
- public function __construct() {
29
- if (! function_exists('apc_add')) {
30
- throw new Google_CacheException("Apc functions not available");
31
- }
32
- }
33
-
34
- private function isLocked($key) {
35
- if ((@apc_fetch($key . '.lock')) === false) {
36
- return false;
37
- }
38
- return true;
39
- }
40
-
41
- private function createLock($key) {
42
- // the interesting thing is that this could fail if the lock was created in the meantime..
43
- // but we'll ignore that out of convenience
44
- @apc_add($key . '.lock', '', 5);
45
- }
46
-
47
- private function removeLock($key) {
48
- // suppress all warnings, if some other process removed it that's ok too
49
- @apc_delete($key . '.lock');
50
- }
51
-
52
- private function waitForLock($key) {
53
- // 20 x 250 = 5 seconds
54
- $tries = 20;
55
- $cnt = 0;
56
- do {
57
- // 250 ms is a long time to sleep, but it does stop the server from burning all resources on polling locks..
58
- usleep(250);
59
- $cnt ++;
60
- } while ($cnt <= $tries && $this->isLocked($key));
61
- if ($this->isLocked($key)) {
62
- // 5 seconds passed, assume the owning process died off and remove it
63
- $this->removeLock($key);
64
- }
65
- }
66
-
67
- /**
68
- * @inheritDoc
69
- */
70
- public function get($key, $expiration = false) {
71
-
72
- if (($ret = @apc_fetch($key)) === false) {
73
- return false;
74
- }
75
- if (!$expiration || (time() - $ret['time'] > $expiration)) {
76
- $this->delete($key);
77
- return false;
78
- }
79
- return unserialize($ret['data']);
80
- }
81
-
82
- /**
83
- * @inheritDoc
84
- */
85
- public function set($key, $value) {
86
- if (@apc_store($key, array('time' => time(), 'data' => serialize($value))) == false) {
87
- throw new Google_CacheException("Couldn't store data");
88
- }
89
- }
90
-
91
- /**
92
- * @inheritDoc
93
- * @param String $key
94
- */
95
- public function delete($key) {
96
- @apc_delete($key);
97
- }
98
- }
google-api-php-client/src/cache/Google_Cache.php DELETED
@@ -1,55 +0,0 @@
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
- require_once "Google_FileCache.php";
19
- require_once "Google_MemcacheCache.php";
20
-
21
- /**
22
- * Abstract storage class
23
- *
24
- * @author Chris Chabot <chabotc@google.com>
25
- */
26
- abstract class Google_Cache {
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 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 function set($key, $value);
46
-
47
- /**
48
- * Removes the key/data pair for the given $key
49
- *
50
- * @param String $key
51
- */
52
- abstract function delete($key);
53
- }
54
-
55
-
google-api-php-client/src/cache/Google_FileCache.php DELETED
@@ -1,137 +0,0 @@
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
- * This class implements a basic on disk storage. While that does
20
- * work quite well it's not the most elegant and scalable solution.
21
- * It will also get you into a heap of trouble when you try to run
22
- * this in a clustered environment. In those cases please use the
23
- * MySql back-end
24
- *
25
- * @author Chris Chabot <chabotc@google.com>
26
- */
27
- class Google_FileCache extends Google_Cache {
28
- private $path;
29
-
30
- public function __construct() {
31
- global $apiConfig;
32
- $this->path = $apiConfig['ioFileCache_directory'];
33
- }
34
-
35
- private function isLocked($storageFile) {
36
- // our lock file convention is simple: /the/file/path.lock
37
- return file_exists($storageFile . '.lock');
38
- }
39
-
40
- private function createLock($storageFile) {
41
- $storageDir = dirname($storageFile);
42
- if (! is_dir($storageDir)) {
43
- // @codeCoverageIgnoreStart
44
- if (! @mkdir($storageDir, 0755, true)) {
45
- // make sure the failure isn't because of a concurrency issue
46
- if (! is_dir($storageDir)) {
47
- throw new Google_CacheException("Could not create storage directory: $storageDir");
48
- }
49
- }
50
- // @codeCoverageIgnoreEnd
51
- }
52
- @touch($storageFile . '.lock');
53
- }
54
-
55
- private function removeLock($storageFile) {
56
- // suppress all warnings, if some other process removed it that's ok too
57
- @unlink($storageFile . '.lock');
58
- }
59
-
60
- private function waitForLock($storageFile) {
61
- // 20 x 250 = 5 seconds
62
- $tries = 20;
63
- $cnt = 0;
64
- do {
65
- // make sure PHP picks up on file changes. This is an expensive action but really can't be avoided
66
- clearstatcache();
67
- // 250 ms is a long time to sleep, but it does stop the server from burning all resources on polling locks..
68
- usleep(250);
69
- $cnt ++;
70
- } while ($cnt <= $tries && $this->isLocked($storageFile));
71
- if ($this->isLocked($storageFile)) {
72
- // 5 seconds passed, assume the owning process died off and remove it
73
- $this->removeLock($storageFile);
74
- }
75
- }
76
-
77
- private function getCacheDir($hash) {
78
- // use the first 2 characters of the hash as a directory prefix
79
- // this should prevent slowdowns due to huge directory listings
80
- // and thus give some basic amount of scalability
81
- return $this->path . '/' . substr($hash, 0, 2);
82
- }
83
-
84
- private function getCacheFile($hash) {
85
- return $this->getCacheDir($hash) . '/' . $hash;
86
- }
87
-
88
- public function get($key, $expiration = false) {
89
- $storageFile = $this->getCacheFile(md5($key));
90
- // See if this storage file is locked, if so we wait upto 5 seconds for the lock owning process to
91
- // complete it's work. If the lock is not released within that time frame, it's cleaned up.
92
- // This should give us a fair amount of 'Cache Stampeding' protection
93
- if ($this->isLocked($storageFile)) {
94
- $this->waitForLock($storageFile);
95
- }
96
- if (file_exists($storageFile) && is_readable($storageFile)) {
97
- $now = time();
98
- if (! $expiration || (($mtime = @filemtime($storageFile)) !== false && ($now - $mtime) < $expiration)) {
99
- if (($data = @file_get_contents($storageFile)) !== false) {
100
- $data = unserialize($data);
101
- return $data;
102
- }
103
- }
104
- }
105
- return false;
106
- }
107
-
108
- public function set($key, $value) {
109
- $storageDir = $this->getCacheDir(md5($key));
110
- $storageFile = $this->getCacheFile(md5($key));
111
- if ($this->isLocked($storageFile)) {
112
- // some other process is writing to this file too, wait until it's done to prevent hickups
113
- $this->waitForLock($storageFile);
114
- }
115
- if (! is_dir($storageDir)) {
116
- if (! @mkdir($storageDir, 0755, true)) {
117
- throw new Google_CacheException("Could not create storage directory: $storageDir");
118
- }
119
- }
120
- // we serialize the whole request object, since we don't only want the
121
- // responseContent but also the postBody used, headers, size, etc
122
- $data = serialize($value);
123
- $this->createLock($storageFile);
124
- if (! @file_put_contents($storageFile, $data)) {
125
- $this->removeLock($storageFile);
126
- throw new Google_CacheException("Could not store data in the file");
127
- }
128
- $this->removeLock($storageFile);
129
- }
130
-
131
- public function delete($key) {
132
- $file = $this->getCacheFile(md5($key));
133
- if (! @unlink($file)) {
134
- throw new Google_CacheException("Cache file could not be deleted");
135
- }
136
- }
137
- }