04efba3a by Jeff Balicki

Oauth

1 parent 329f0d2f
Showing 71 changed files with 4159 additions and 54 deletions
1 <?php
2 session_start();
3 if(!isset($_SESSION['google_data'])):header("Location:index.php");endif;
4 ?>
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
8 <title>Login with Google Account by CodexWorld</title>
9 <style type="text/css">
10 h1
11 {
12 font-family:Arial, Helvetica, sans-serif;
13 color:#999999;
14 }
15 .wrapper{width:600px; margin-left:auto;margin-right:auto;}
16 .welcome_txt{
17 margin: 20px;
18 background-color: #EBEBEB;
19 padding: 10px;
20 border: #D6D6D6 solid 1px;
21 -moz-border-radius:5px;
22 -webkit-border-radius:5px;
23 border-radius:5px;
24 }
25 .google_box{
26 margin: 20px;
27 background-color: #FFF0DD;
28 padding: 10px;
29 border: #F7CFCF solid 1px;
30 -moz-border-radius:5px;
31 -webkit-border-radius:5px;
32 border-radius:5px;
33 }
34 .google_box .image{ text-align:center;}
35 </style>
36 </head>
37 <body>
38 <div class="wrapper">
39 <h1>Google Profile Details </h1>
40 <?php
41 echo '<div class="welcome_txt">Welcome <b>'.$_SESSION['google_data']['given_name'].'</b></div>';
42 echo '<div class="google_box">';
43 echo '<p class="image"><img src="'.$_SESSION['google_data']['picture'].'" alt="" width="300" height="220"/></p>';
44 echo '<p><b>Google ID : </b>' . $_SESSION['google_data']['id'].'</p>';
45 echo '<p><b>Name : </b>' . $_SESSION['google_data']['name'].'</p>';
46 echo '<p><b>Email : </b>' . $_SESSION['google_data']['email'].'</p>';
47 echo '<p><b>Gender : </b>' . $_SESSION['google_data']['gender'].'</p>';
48 echo '<p><b>Locale : </b>' . $_SESSION['google_data']['locale'].'</p>';
49 echo '<p><b>Google+ Link : </b>' . $_SESSION['google_data']['link'].'</p>';
50 echo '<p><b>You are login with : </b>Google</p>';
51 echo '<p><b>Logout from <a href="logout.php?logout">Google</a></b></p>';
52 echo '</div>';
53 ?>
54 </div>
55 </body>
56 </html>
...\ No newline at end of file ...\ No newline at end of file
1 <?php
2 //session_start();
3 include_once("src/Google_Client.php");
4 include_once("src/contrib/Google_Oauth2Service.php");
5 ######### edit details ##########
6 $clientId = '326088686201-1llld5s7s3uhb2shl4g2g9djkvq584pc.apps.googleusercontent.com'; //Google CLIENT ID
7 $clientSecret = 'F4Fa8MdTT17f4voG4lRaOCuc'; //Google CLIENT SECRET
8 $redirectUrl = 'http://banners.gotenzing.com/oauth2callback'; //return url (url to script)
9 $homeUrl = 'http://banners.gotenzing.com/'; //return to home
10
11 ##################################
12
13 $gClient = new Google_Client();
14 $gClient->setApplicationName('banners.gotenzing.com');
15 $gClient->setClientId($clientId);
16 $gClient->setClientSecret($clientSecret);
17 $gClient->setRedirectUri($redirectUrl);
18
19 $google_oauthV2 = new Google_Oauth2Service($gClient);
20 ?>
...\ No newline at end of file ...\ No newline at end of file
1 <?php 1 <?php
2 2 if (!isset($_SESSION['token'])){
3
4 3
5 4 echo '<form>
6 5 <dl class="TzMenu"><a style="font-size: 25px; color: #fff !important;" href="./login.php" target="_parent">Login</a></dl></form>';
6 }else{
7 include('loggedin.php');
8 return;
7 9
8 include(' loggedin.php');
9 return;
10
11
12 ?>
13 10
14 <form method="post"> 11 };
15 <dl class="TzMenu">
16 <dt><label for="username">Username:</label></dt>
17 <dd><input type="text" name="username" id="username" /></dd>
18 </dl>
19
20 <dl class="TzMenu">
21 <dt><label for="password">Password:</label></dt>
22 <dd><input type="password" name="password" id="password" /></dd>
23 </dl>
24
25 <dl class="TzMenu">
26 <dt><input type="submit" value=" Log In " /></dt>
27 </dl>
28 </form>
29
30 <script type="text/javascript">
31 addEvent(window, 'load', function() {
32 document.getElementById('username').select();
33 });
34 </script>
...\ No newline at end of file ...\ No newline at end of file
......
1 <?php 1 <?php
2 session_start(); 2 session_start();
3 $clientId = $_POST['id']; 3 $clientId = $_POST['id'];
4 $dockets_obj = json_decode($_SESSION['lookup']); 4 $dockets_obj = json_decode($_SESSION['lookup']);
5 5
6 $opt = " "; 6 $opt = " ";
7 7
8 8
9 9
10 $dockets = Array(); 10 $dockets = Array();
11 11
12 12
13 $opt .= '<option value="home.html">Splash Page</option>'; 13 $opt .= '<option value="home.html">Splash Page</option>';
14 foreach ($dockets_obj as $docket => $key) { 14 foreach ($dockets_obj as $docket => $key) {
15 $dockets[$docket] = $key; 15 $dockets[$docket] = $key;
16 } 16 }
17 ksort($dockets); 17 ksort($dockets);
18 18
19 foreach ($dockets as $dir => $md5) { 19 foreach ($dockets as $dir => $md5) {
20 $client = explode("-",$dir); 20 $client = explode("-",$dir);
21 $clientIds = $client[1]; 21 $clientIds = $client[1];
22 if($clientIds == $clientId ){ 22 if($clientIds == $clientId ){
23 23
24 24
25 $opt .= '<option value="' . $md5 . '"' .' '. '>' . $dir . '</option>'; 25 $opt .= '<option value="' . $md5 . '"' .' '. '>' . $dir . '</option>';
26 } 26 }
27 } 27 }
28 // error_log('test error'. $opt); 28 // error_log('test error'. $opt);
29 echo $opt; 29 echo $opt;
......
1 <?php
2 class Users {
3 public $tableName = 'users';
4
5 function __construct(){
6 //database configuration
7 $dbServer = 'localhost'; //Define database server host
8 $dbUsername = 'root'; //Define database username
9 $dbPassword = 'root'; //Define database password
10 $dbName = 'banners'; //Define database name
11
12 //connect databse
13 $con = mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);
14 if(mysqli_connect_errno()){
15 die("Failed to connect with MySQL: ".mysqli_connect_error());
16 }else{
17 $this->connect = $con;
18 }
19 }
20
21 function checkUser($oauth_provider,$oauth_uid,$fname,$lname,$email,$gender,$locale,$link,$picture){
22 $prevQuery = mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
23 if(mysqli_num_rows($prevQuery) > 0){
24 $update = mysqli_query($this->connect,"UPDATE $this->tableName SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$oauth_uid."', fname = '".$fname."', lname = '".$lname."', email = '".$email."', gender = '".$gender."', locale = '".$locale."', picture = '".$picture."', gpluslink = '".$link."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
25 }else{
26 $insert = mysqli_query($this->connect,"INSERT INTO $this->tableName SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$oauth_uid."', fname = '".$fname."', lname = '".$lname."', email = '".$email."', gender = '".$gender."', locale = '".$locale."', picture = '".$picture."', gpluslink = '".$link."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'") or die(mysqli_error($this->connect));
27 }
28
29 $query = mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
30 $result = mysqli_fetch_array($query);
31 return $result;
32 }
33 }
34 ?>
...\ No newline at end of file ...\ No newline at end of file
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
2 if (!isset($_SESSION) && !isset($_SESSION['username'])) { 2 if (!isset($_SESSION) && !isset($_SESSION['username'])) {
3 return; 3 return;
4 } 4 }
5 5
6 6
7 $dockets = Array(); 7 $dockets = Array();
8 $dockets_obj = json_decode($_SESSION['lookup']); 8 $dockets_obj = json_decode($_SESSION['lookup']);
9 foreach ($dockets_obj as $docket => $key) { 9 foreach ($dockets_obj as $docket => $key) {
......
1 <?php 1 <?php
2 session_start(); 2 session_start();
3 3
4 //let it work please again 4 //let it work please again
5 $dockets = Array(); 5 $dockets = Array();
6 $valid = 'home.html'; 6 $valid = 'home.html';
7 $id = ''; 7 $id = '';
...@@ -20,8 +20,8 @@ ...@@ -20,8 +20,8 @@
20 closedir($handle); 20 closedir($handle);
21 21
22 $_SESSION['lookup'] = json_encode($dockets); 22 $_SESSION['lookup'] = json_encode($dockets);
23 23
24 24
25 ?> 25 ?>
26 <?php header("Access-Control-Allow-Origin", "*"); ?> 26 <?php header("Access-Control-Allow-Origin", "*"); ?>
27 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> 27 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
......
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
5 <title>Tenzing Communications Inc.</title>
6 <style type="text/css">
7 body {
8 margin:0;
9 padding:0;
10 background-color: #3b0d32;
11 color: #777;
12 }
13 #login{
14 display: table;
15 margin: 0 auto;
16
17 }
18 </style>
19
20 <script type="text/javascript">
21 // document.domain = 'gotenzing.com';
22 </script>
23 </head>
24
25
26
27 <body><div id="login"><?php
28
29 include_once("./config.php");
30 include_once("functions.php");
31
32 //print_r($_GET);die;
33
34 if(isset($_REQUEST['code'])){
35 $gClient->authenticate();
36 $_SESSION['token'] = $gClient->getAccessToken();
37 header('Location: ' . filter_var($redirect_url, FILTER_SANITIZE_URL));
38 }
39
40 if (isset($_SESSION['token'])) {
41 $gClient->setAccessToken($_SESSION['token']);
42 }
43
44 if ($gClient->getAccessToken()) {
45 $userProfile = $google_oauthV2->userinfo->get();
46 //DB Insert
47 $gUser = new Users();
48 $gUser->checkUser('google',$userProfile['id'],$userProfile['given_name'],$userProfile['family_name'],$userProfile['email'],$userProfile['gender'],$userProfile['locale'],$userProfile['link'],$userProfile['picture']);
49 $_SESSION['google_data'] = $userProfile; // Storing Google User Data in Session
50 header("location: account.php");
51 $_SESSION['token'] = $gClient->getAccessToken();
52 } else {
53 $authUrl = $gClient->createAuthUrl();
54 }
55 echo '<img src="tenzing.gif" width="259" alt="Tenzing" /></br>';
56 if(isset($authUrl)) {
57 echo '<a href="'.$authUrl.'"><img width="259" style="padding:20px;" src="./images/glogin.png" alt=""/></a>';
58 } else {
59
60 }
61
62 ?>
63 </div>
64 </body>
65
66
67 </html>
1 <?php
2 include_once("config.php");
3 if(array_key_exists('logout',$_GET))
4 {
5 unset($_SESSION['token']);
6 unset($_SESSION['google_data']); //Google session data unset
7 $gClient->revokeToken();
8 session_destroy();
9 header("Location:index.php");
10 }
11 ?>
...\ No newline at end of file ...\ No newline at end of file
1 <?php 1 <?php
2 session_start(); 2 session_start();
3 $db = new mysqli('localhost', 'root', 'root'); 3
4 ?> 4 ?>
5 5
6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
8 <head> 8 <head>
9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
10 <title>Tenzing Communications Inc.</title> 10 <title>Tenzing Communications Inc.</title>
11 11 <script src="https://apis.google.com/js/platform.js" async defer></script>
12 <style type="text/css"> 12 <style type="text/css">
13 body, h1 { 13 body, h1 {
14 margin: 0; 14 margin: 0;
...@@ -55,11 +55,13 @@ ...@@ -55,11 +55,13 @@
55 </head> 55 </head>
56 56
57 <body> 57 <body>
58 <?php 58 <?php
59 59 if (isset($_SESSION['username'])) {
60 include('includes/loggedin.php'); 60 include('includes/loggedin.php');
61 61 } else {
62 ?> 62 include('includes/auth.php');
63 }
64 ?>
63 65
64 <div id="TzLogo"> 66 <div id="TzLogo">
65 <img src="tenzing.gif" width="259" height="75" alt="Tenzing" /> 67 <img src="tenzing.gif" width="259" height="75" alt="Tenzing" />
......
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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
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 }
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 * A persistent storage class based on the memcache, which is not
20 * really very persistent, as soon as you restart your memcache daemon
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 Google_MemcacheCache extends Google_Cache {
27 private $connection = false;
28
29 public function __construct() {
30 global $apiConfig;
31 if (! function_exists('memcache_connect')) {
32 throw new Google_CacheException("Memcache functions not available");
33 }
34 $this->host = $apiConfig['ioMemCacheCache_host'];
35 $this->port = $apiConfig['ioMemCacheCache_port'];
36 if (empty($this->host) || empty($this->port)) {
37 throw new Google_CacheException("You need to supply a valid memcache host and port");
38 }
39 }
40
41 private function isLocked($key) {
42 $this->check();
43 if ((@memcache_get($this->connection, $key . '.lock')) === false) {
44 return false;
45 }
46 return true;
47 }
48
49 private function createLock($key) {
50 $this->check();
51 // the interesting thing is that this could fail if the lock was created in the meantime..
52 // but we'll ignore that out of convenience
53 @memcache_add($this->connection, $key . '.lock', '', 0, 5);
54 }
55
56 private function removeLock($key) {
57 $this->check();
58 // suppress all warnings, if some other process removed it that's ok too
59 @memcache_delete($this->connection, $key . '.lock');
60 }
61
62 private function waitForLock($key) {
63 $this->check();
64 // 20 x 250 = 5 seconds
65 $tries = 20;
66 $cnt = 0;
67 do {
68 // 250 ms is a long time to sleep, but it does stop the server from burning all resources on polling locks..
69 usleep(250);
70 $cnt ++;
71 } while ($cnt <= $tries && $this->isLocked($key));
72 if ($this->isLocked($key)) {
73 // 5 seconds passed, assume the owning process died off and remove it
74 $this->removeLock($key);
75 }
76 }
77
78 // I prefer lazy initialization since the cache isn't used every request
79 // so this potentially saves a lot of overhead
80 private function connect() {
81 if (! $this->connection = @memcache_pconnect($this->host, $this->port)) {
82 throw new Google_CacheException("Couldn't connect to memcache server");
83 }
84 }
85
86 private function check() {
87 if (! $this->connection) {
88 $this->connect();
89 }
90 }
91
92 /**
93 * @inheritDoc
94 */
95 public function get($key, $expiration = false) {
96 $this->check();
97 if (($ret = @memcache_get($this->connection, $key)) === false) {
98 return false;
99 }
100 if (! $expiration || (time() - $ret['time'] > $expiration)) {
101 $this->delete($key);
102 return false;
103 }
104 return $ret['data'];
105 }
106
107 /**
108 * @inheritDoc
109 * @param string $key
110 * @param string $value
111 * @throws Google_CacheException
112 */
113 public function set($key, $value) {
114 $this->check();
115 // we store it with the cache_time default expiration so objects will at least get cleaned eventually.
116 if (@memcache_set($this->connection, $key, array('time' => time(),
117 'data' => $value), false) == false) {
118 throw new Google_CacheException("Couldn't store data in cache");
119 }
120 }
121
122 /**
123 * @inheritDoc
124 * @param String $key
125 */
126 public function delete($key) {
127 $this->check();
128 @memcache_delete($this->connection, $key);
129 }
130 }
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 global $apiConfig;
19 $apiConfig = array(
20 // True if objects should be returned by the service classes.
21 // False if associative arrays should be returned (default behavior).
22 'use_objects' => false,
23
24 // The application_name is included in the User-Agent HTTP header.
25 'application_name' => '',
26
27 // OAuth2 Settings, you can get these keys at https://code.google.com/apis/console
28 'oauth2_client_id' => '',
29 'oauth2_client_secret' => '',
30 'oauth2_redirect_uri' => '',
31
32 // The developer key, you get this at https://code.google.com/apis/console
33 'developer_key' => '',
34
35 // Site name to show in the Google's OAuth 1 authentication screen.
36 'site_name' => 'www.example.org',
37
38 // Which Authentication, Storage and HTTP IO classes to use.
39 'authClass' => 'Google_OAuth2',
40 'ioClass' => 'Google_CurlIO',
41 'cacheClass' => 'Google_FileCache',
42
43 // Don't change these unless you're working against a special development or testing environment.
44 'basePath' => 'https://www.googleapis.com',
45
46 // IO Class dependent configuration, you only have to configure the values
47 // for the class that was configured as the ioClass above
48 'ioFileCache_directory' =>
49 (function_exists('sys_get_temp_dir') ?
50 sys_get_temp_dir() . '/Google_Client' :
51 '/tmp/Google_Client'),
52
53 // Definition of service specific values like scopes, oauth token URLs, etc
54 'services' => array(
55 'analytics' => array('scope' => 'https://www.googleapis.com/auth/analytics.readonly'),
56 'calendar' => array(
57 'scope' => array(
58 "https://www.googleapis.com/auth/calendar",
59 "https://www.googleapis.com/auth/calendar.readonly",
60 )
61 ),
62 'books' => array('scope' => 'https://www.googleapis.com/auth/books'),
63 'latitude' => array(
64 'scope' => array(
65 'https://www.googleapis.com/auth/latitude.all.best',
66 'https://www.googleapis.com/auth/latitude.all.city',
67 )
68 ),
69 'moderator' => array('scope' => 'https://www.googleapis.com/auth/moderator'),
70 'oauth2' => array(
71 'scope' => array(
72 'https://www.googleapis.com/auth/userinfo.profile',
73 'https://www.googleapis.com/auth/userinfo.email',
74 )
75 ),
76 'plus' => array('scope' => 'https://www.googleapis.com/auth/plus.me'),
77 'siteVerification' => array('scope' => 'https://www.googleapis.com/auth/siteverification'),
78 'tasks' => array('scope' => 'https://www.googleapis.com/auth/tasks'),
79 'urlshortener' => array('scope' => 'https://www.googleapis.com/auth/urlshortener')
80 )
81 );
...\ No newline at end of file ...\ No newline at end of file
This diff could not be displayed because it is too large.
1 <?php
2 /*
3 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 * use this file except in compliance with the License. You may obtain a copy of
5 * the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 * License for the specific language governing permissions and limitations under
13 * the License.
14 */
15
16
17 /**
18 * The "text" collection of methods.
19 * Typical usage is:
20 * <code>
21 * $freebaseService = new Google_FreebaseService(...);
22 * $text = $freebaseService->text;
23 * </code>
24 */
25 class Google_TextServiceResource extends Google_ServiceResource {
26
27
28 /**
29 * Returns blob attached to node at specified id as HTML (text.get)
30 *
31 * @param string $id The id of the item that you want data about
32 * @param array $optParams Optional parameters.
33 *
34 * @opt_param string maxlength The max number of characters to return. Valid only for 'plain' format.
35 * @opt_param string format Sanitizing transformation.
36 * @return Google_ContentserviceGet
37 */
38 public function get($id, $optParams = array()) {
39 $params = array('id' => $id);
40 $params = array_merge($params, $optParams);
41 $data = $this->__call('get', array($params));
42 if ($this->useObjects()) {
43 return new Google_ContentserviceGet($data);
44 } else {
45 return $data;
46 }
47 }
48 }
49
50 /**
51 * Service definition for Google_Freebase (v1).
52 *
53 * <p>
54 * Lets you access the Freebase repository of open data.
55 * </p>
56 *
57 * <p>
58 * For more information about this service, see the
59 * <a href="http://wiki.freebase.com/wiki/API" target="_blank">API Documentation</a>
60 * </p>
61 *
62 * @author Google, Inc.
63 */
64 class Google_FreebaseService extends Google_Service {
65 public $text;
66 /**
67 * Constructs the internal representation of the Freebase service.
68 *
69 * @param Google_Client $client
70 */
71 public function __construct(Google_Client $client) {
72 $this->servicePath = 'freebase/v1/';
73 $this->version = 'v1';
74 $this->serviceName = 'freebase';
75
76 $client->addService($this->serviceName, $this->version);
77 $this->text = new Google_TextServiceResource($this, $this->serviceName, 'text', json_decode('{"methods": {"get": {"httpMethod": "GET", "response": {"$ref": "ContentserviceGet"}, "id": "freebase.text.get", "parameters": {"maxlength": {"type": "integer", "location": "query", "format": "uint32"}, "id": {"repeated": true, "required": true, "type": "string", "location": "path"}, "format": {"default": "plain", "enum": ["html", "plain", "raw"], "type": "string", "location": "query"}}, "path": "text{/id*}"}}}', true));
78 }
79 }
80
81 class Google_ContentserviceGet extends Google_Model {
82 public $result;
83 public function setResult($result) {
84 $this->result = $result;
85 }
86 public function getResult() {
87 return $this->result;
88 }
89 }
1 <?php
2 /*
3 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 * use this file except in compliance with the License. You may obtain a copy of
5 * the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 * License for the specific language governing permissions and limitations under
13 * the License.
14 */
15
16
17 /**
18 * The "userinfo" collection of methods.
19 * Typical usage is:
20 * <code>
21 * $oauth2Service = new Google_Oauth2Service(...);
22 * $userinfo = $oauth2Service->userinfo;
23 * </code>
24 */
25 class Google_UserinfoServiceResource extends Google_ServiceResource {
26
27
28 /**
29 * (userinfo.get)
30 *
31 * @param array $optParams Optional parameters.
32 * @return Google_Userinfo
33 */
34 public function get($optParams = array()) {
35 $params = array();
36 $params = array_merge($params, $optParams);
37 $data = $this->__call('get', array($params));
38 if ($this->useObjects()) {
39 return new Google_Userinfo($data);
40 } else {
41 return $data;
42 }
43 }
44 }
45
46 /**
47 * The "v2" collection of methods.
48 * Typical usage is:
49 * <code>
50 * $oauth2Service = new Google_Oauth2Service(...);
51 * $v2 = $oauth2Service->v2;
52 * </code>
53 */
54 class Google_UserinfoV2ServiceResource extends Google_ServiceResource {
55
56
57 }
58
59 /**
60 * The "me" collection of methods.
61 * Typical usage is:
62 * <code>
63 * $oauth2Service = new Google_Oauth2Service(...);
64 * $me = $oauth2Service->me;
65 * </code>
66 */
67 class Google_UserinfoV2MeServiceResource extends Google_ServiceResource {
68
69
70 /**
71 * (me.get)
72 *
73 * @param array $optParams Optional parameters.
74 * @return Google_Userinfo
75 */
76 public function get($optParams = array()) {
77 $params = array();
78 $params = array_merge($params, $optParams);
79 $data = $this->__call('get', array($params));
80 if ($this->useObjects()) {
81 return new Google_Userinfo($data);
82 } else {
83 return $data;
84 }
85 }
86 }
87
88 /**
89 * Service definition for Google_Oauth2 (v2).
90 *
91 * <p>
92 * OAuth2 API
93 * </p>
94 *
95 * <p>
96 * For more information about this service, see the
97 * <a href="" target="_blank">API Documentation</a>
98 * </p>
99 *
100 * @author Google, Inc.
101 */
102 class Google_Oauth2Service extends Google_Service {
103 public $userinfo;
104 public $userinfo_v2_me;
105 /**
106 * Constructs the internal representation of the Oauth2 service.
107 *
108 * @param Google_Client $client
109 */
110 public function __construct(Google_Client $client) {
111 $this->servicePath = '';
112 $this->version = 'v2';
113 $this->serviceName = 'oauth2';
114
115 $client->addService($this->serviceName, $this->version);
116 $this->userinfo = new Google_UserinfoServiceResource($this, $this->serviceName, 'userinfo', json_decode('{"methods": {"get": {"path": "oauth2/v2/userinfo", "scopes": ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"], "id": "oauth2.userinfo.get", "httpMethod": "GET", "response": {"$ref": "Userinfo"}}}}', true));
117 $this->userinfo_v2_me = new Google_UserinfoV2MeServiceResource($this, $this->serviceName, 'me', json_decode('{"methods": {"get": {"path": "userinfo/v2/me", "scopes": ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"], "id": "oauth2.userinfo.v2.me.get", "httpMethod": "GET", "response": {"$ref": "Userinfo"}}}}', true));
118 }
119 }
120
121 class Google_Tokeninfo extends Google_Model {
122 public $issued_to;
123 public $user_id;
124 public $expires_in;
125 public $access_type;
126 public $audience;
127 public $scope;
128 public $email;
129 public $verified_email;
130 public function setIssued_to($issued_to) {
131 $this->issued_to = $issued_to;
132 }
133 public function getIssued_to() {
134 return $this->issued_to;
135 }
136 public function setUser_id($user_id) {
137 $this->user_id = $user_id;
138 }
139 public function getUser_id() {
140 return $this->user_id;
141 }
142 public function setExpires_in($expires_in) {
143 $this->expires_in = $expires_in;
144 }
145 public function getExpires_in() {
146 return $this->expires_in;
147 }
148 public function setAccess_type($access_type) {
149 $this->access_type = $access_type;
150 }
151 public function getAccess_type() {
152 return $this->access_type;
153 }
154 public function setAudience($audience) {
155 $this->audience = $audience;
156 }
157 public function getAudience() {
158 return $this->audience;
159 }
160 public function setScope($scope) {
161 $this->scope = $scope;
162 }
163 public function getScope() {
164 return $this->scope;
165 }
166 public function setEmail($email) {
167 $this->email = $email;
168 }
169 public function getEmail() {
170 return $this->email;
171 }
172 public function setVerified_email($verified_email) {
173 $this->verified_email = $verified_email;
174 }
175 public function getVerified_email() {
176 return $this->verified_email;
177 }
178 }
179
180 class Google_Userinfo extends Google_Model {
181 public $family_name;
182 public $name;
183 public $picture;
184 public $locale;
185 public $gender;
186 public $email;
187 public $birthday;
188 public $link;
189 public $given_name;
190 public $timezone;
191 public $id;
192 public $verified_email;
193 public function setFamily_name($family_name) {
194 $this->family_name = $family_name;
195 }
196 public function getFamily_name() {
197 return $this->family_name;
198 }
199 public function setName($name) {
200 $this->name = $name;
201 }
202 public function getName() {
203 return $this->name;
204 }
205 public function setPicture($picture) {
206 $this->picture = $picture;
207 }
208 public function getPicture() {
209 return $this->picture;
210 }
211 public function setLocale($locale) {
212 $this->locale = $locale;
213 }
214 public function getLocale() {
215 return $this->locale;
216 }
217 public function setGender($gender) {
218 $this->gender = $gender;
219 }
220 public function getGender() {
221 return $this->gender;
222 }
223 public function setEmail($email) {
224 $this->email = $email;
225 }
226 public function getEmail() {
227 return $this->email;
228 }
229 public function setBirthday($birthday) {
230 $this->birthday = $birthday;
231 }
232 public function getBirthday() {
233 return $this->birthday;
234 }
235 public function setLink($link) {
236 $this->link = $link;
237 }
238 public function getLink() {
239 return $this->link;
240 }
241 public function setGiven_name($given_name) {
242 $this->given_name = $given_name;
243 }
244 public function getGiven_name() {
245 return $this->given_name;
246 }
247 public function setTimezone($timezone) {
248 $this->timezone = $timezone;
249 }
250 public function getTimezone() {
251 return $this->timezone;
252 }
253 public function setId($id) {
254 $this->id = $id;
255 }
256 public function getId() {
257 return $this->id;
258 }
259 public function setVerified_email($verified_email) {
260 $this->verified_email = $verified_email;
261 }
262 public function getVerified_email() {
263 return $this->verified_email;
264 }
265 }
1 <?php
2 /*
3 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 * use this file except in compliance with the License. You may obtain a copy of
5 * the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 * License for the specific language governing permissions and limitations under
13 * the License.
14 */
15
16
17 /**
18 * The "languages" collection of methods.
19 * Typical usage is:
20 * <code>
21 * $translateService = new Google_TranslateService(...);
22 * $languages = $translateService->languages;
23 * </code>
24 */
25 class Google_LanguagesServiceResource extends Google_ServiceResource {
26
27
28 /**
29 * List the source/target languages supported by the API (languages.list)
30 *
31 * @param array $optParams Optional parameters.
32 *
33 * @opt_param string target the language and collation in which the localized results should be returned
34 * @return Google_LanguagesListResponse
35 */
36 public function listLanguages($optParams = array()) {
37 $params = array();
38 $params = array_merge($params, $optParams);
39 $data = $this->__call('list', array($params));
40 if ($this->useObjects()) {
41 return new Google_LanguagesListResponse($data);
42 } else {
43 return $data;
44 }
45 }
46 }
47
48 /**
49 * The "detections" collection of methods.
50 * Typical usage is:
51 * <code>
52 * $translateService = new Google_TranslateService(...);
53 * $detections = $translateService->detections;
54 * </code>
55 */
56 class Google_DetectionsServiceResource extends Google_ServiceResource {
57
58
59 /**
60 * Detect the language of text. (detections.list)
61 *
62 * @param string $q The text to detect
63 * @param array $optParams Optional parameters.
64 * @return Google_DetectionsListResponse
65 */
66 public function listDetections($q, $optParams = array()) {
67 $params = array('q' => $q);
68 $params = array_merge($params, $optParams);
69 $data = $this->__call('list', array($params));
70 if ($this->useObjects()) {
71 return new Google_DetectionsListResponse($data);
72 } else {
73 return $data;
74 }
75 }
76 }
77
78 /**
79 * The "translations" collection of methods.
80 * Typical usage is:
81 * <code>
82 * $translateService = new Google_TranslateService(...);
83 * $translations = $translateService->translations;
84 * </code>
85 */
86 class Google_TranslationsServiceResource extends Google_ServiceResource {
87
88
89 /**
90 * Returns text translations from one language to another. (translations.list)
91 *
92 * @param string $q The text to translate
93 * @param string $target The target language into which the text should be translated
94 * @param array $optParams Optional parameters.
95 *
96 * @opt_param string source The source language of the text
97 * @opt_param string format The format of the text
98 * @opt_param string cid The customization id for translate
99 * @return Google_TranslationsListResponse
100 */
101 public function listTranslations($q, $target, $optParams = array()) {
102 $params = array('q' => $q, 'target' => $target);
103 $params = array_merge($params, $optParams);
104 $data = $this->__call('list', array($params));
105 if ($this->useObjects()) {
106 return new Google_TranslationsListResponse($data);
107 } else {
108 return $data;
109 }
110 }
111 }
112
113 /**
114 * Service definition for Google_Translate (v2).
115 *
116 * <p>
117 * Lets you translate text from one language to another
118 * </p>
119 *
120 * <p>
121 * For more information about this service, see the
122 * <a href="http://code.google.com/apis/language/translate/v2/using_rest.html" target="_blank">API Documentation</a>
123 * </p>
124 *
125 * @author Google, Inc.
126 */
127 class Google_TranslateService extends Google_Service {
128 public $languages;
129 public $detections;
130 public $translations;
131 /**
132 * Constructs the internal representation of the Translate service.
133 *
134 * @param Google_Client $client
135 */
136 public function __construct(Google_Client $client) {
137 $this->servicePath = 'language/translate/';
138 $this->version = 'v2';
139 $this->serviceName = 'translate';
140
141 $client->addService($this->serviceName, $this->version);
142 $this->languages = new Google_LanguagesServiceResource($this, $this->serviceName, 'languages', json_decode('{"methods": {"list": {"httpMethod": "GET", "response": {"$ref": "LanguagesListResponse"}, "id": "language.languages.list", "parameters": {"target": {"type": "string", "location": "query"}}, "path": "v2/languages"}}}', true));
143 $this->detections = new Google_DetectionsServiceResource($this, $this->serviceName, 'detections', json_decode('{"methods": {"list": {"httpMethod": "GET", "response": {"$ref": "DetectionsListResponse"}, "id": "language.detections.list", "parameters": {"q": {"repeated": true, "required": true, "type": "string", "location": "query"}}, "path": "v2/detect"}}}', true));
144 $this->translations = new Google_TranslationsServiceResource($this, $this->serviceName, 'translations', json_decode('{"methods": {"list": {"httpMethod": "GET", "response": {"$ref": "TranslationsListResponse"}, "id": "language.translations.list", "parameters": {"q": {"repeated": true, "required": true, "type": "string", "location": "query"}, "source": {"type": "string", "location": "query"}, "format": {"enum": ["html", "text"], "type": "string", "location": "query"}, "target": {"required": true, "type": "string", "location": "query"}, "cid": {"repeated": true, "type": "string", "location": "query"}}, "path": "v2"}}}', true));
145
146 }
147 }
148
149 class Google_DetectionsListResponse extends Google_Model {
150 protected $__detectionsType = 'Google_DetectionsResourceItems';
151 protected $__detectionsDataType = 'array';
152 public $detections;
153 public function setDetections(/* array(Google_DetectionsResourceItems) */ $detections) {
154 $this->assertIsArray($detections, 'Google_DetectionsResourceItems', __METHOD__);
155 $this->detections = $detections;
156 }
157 public function getDetections() {
158 return $this->detections;
159 }
160 }
161
162 class Google_DetectionsResourceItems extends Google_Model {
163 public $isReliable;
164 public $confidence;
165 public $language;
166 public function setIsReliable($isReliable) {
167 $this->isReliable = $isReliable;
168 }
169 public function getIsReliable() {
170 return $this->isReliable;
171 }
172 public function setConfidence($confidence) {
173 $this->confidence = $confidence;
174 }
175 public function getConfidence() {
176 return $this->confidence;
177 }
178 public function setLanguage($language) {
179 $this->language = $language;
180 }
181 public function getLanguage() {
182 return $this->language;
183 }
184 }
185
186 class Google_LanguagesListResponse extends Google_Model {
187 protected $__languagesType = 'Google_LanguagesResource';
188 protected $__languagesDataType = 'array';
189 public $languages;
190 public function setLanguages(/* array(Google_LanguagesResource) */ $languages) {
191 $this->assertIsArray($languages, 'Google_LanguagesResource', __METHOD__);
192 $this->languages = $languages;
193 }
194 public function getLanguages() {
195 return $this->languages;
196 }
197 }
198
199 class Google_LanguagesResource extends Google_Model {
200 public $name;
201 public $language;
202 public function setName($name) {
203 $this->name = $name;
204 }
205 public function getName() {
206 return $this->name;
207 }
208 public function setLanguage($language) {
209 $this->language = $language;
210 }
211 public function getLanguage() {
212 return $this->language;
213 }
214 }
215
216 class Google_TranslationsListResponse extends Google_Model {
217 protected $__translationsType = 'Google_TranslationsResource';
218 protected $__translationsDataType = 'array';
219 public $translations;
220 public function setTranslations(/* array(Google_TranslationsResource) */ $translations) {
221 $this->assertIsArray($translations, 'Google_TranslationsResource', __METHOD__);
222 $this->translations = $translations;
223 }
224 public function getTranslations() {
225 return $this->translations;
226 }
227 }
228
229 class Google_TranslationsResource extends Google_Model {
230 public $detectedSourceLanguage;
231 public $translatedText;
232 public function setDetectedSourceLanguage($detectedSourceLanguage) {
233 $this->detectedSourceLanguage = $detectedSourceLanguage;
234 }
235 public function getDetectedSourceLanguage() {
236 return $this->detectedSourceLanguage;
237 }
238 public function setTranslatedText($translatedText) {
239 $this->translatedText = $translatedText;
240 }
241 public function getTranslatedText() {
242 return $this->translatedText;
243 }
244 }
1 <?php
2 /*
3 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 * use this file except in compliance with the License. You may obtain a copy of
5 * the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 * License for the specific language governing permissions and limitations under
13 * the License.
14 */
15
16
17 /**
18 * The "url" collection of methods.
19 * Typical usage is:
20 * <code>
21 * $urlshortenerService = new Google_UrlshortenerService(...);
22 * $url = $urlshortenerService->url;
23 * </code>
24 */
25 class Google_UrlServiceResource extends Google_ServiceResource {
26
27
28 /**
29 * Creates a new short URL. (url.insert)
30 *
31 * @param Google_Url $postBody
32 * @param array $optParams Optional parameters.
33 * @return Google_Url
34 */
35 public function insert(Google_Url $postBody, $optParams = array()) {
36 $params = array('postBody' => $postBody);
37 $params = array_merge($params, $optParams);
38 $data = $this->__call('insert', array($params));
39 if ($this->useObjects()) {
40 return new Google_Url($data);
41 } else {
42 return $data;
43 }
44 }
45 /**
46 * Retrieves a list of URLs shortened by a user. (url.list)
47 *
48 * @param array $optParams Optional parameters.
49 *
50 * @opt_param string start-token Token for requesting successive pages of results.
51 * @opt_param string projection Additional information to return.
52 * @return Google_UrlHistory
53 */
54 public function listUrl($optParams = array()) {
55 $params = array();
56 $params = array_merge($params, $optParams);
57 $data = $this->__call('list', array($params));
58 if ($this->useObjects()) {
59 return new Google_UrlHistory($data);
60 } else {
61 return $data;
62 }
63 }
64 /**
65 * Expands a short URL or gets creation time and analytics. (url.get)
66 *
67 * @param string $shortUrl The short URL, including the protocol.
68 * @param array $optParams Optional parameters.
69 *
70 * @opt_param string projection Additional information to return.
71 * @return Google_Url
72 */
73 public function get($shortUrl, $optParams = array()) {
74 $params = array('shortUrl' => $shortUrl);
75 $params = array_merge($params, $optParams);
76 $data = $this->__call('get', array($params));
77 if ($this->useObjects()) {
78 return new Google_Url($data);
79 } else {
80 return $data;
81 }
82 }
83 }
84
85 /**
86 * Service definition for Google_Urlshortener (v1).
87 *
88 * <p>
89 * Lets you create, inspect, and manage goo.gl short URLs
90 * </p>
91 *
92 * <p>
93 * For more information about this service, see the
94 * <a href="http://code.google.com/apis/urlshortener/v1/getting_started.html" target="_blank">API Documentation</a>
95 * </p>
96 *
97 * @author Google, Inc.
98 */
99 class Google_UrlshortenerService extends Google_Service {
100 public $url;
101 /**
102 * Constructs the internal representation of the Urlshortener service.
103 *
104 * @param Google_Client $client
105 */
106 public function __construct(Google_Client $client) {
107 $this->servicePath = 'urlshortener/v1/';
108 $this->version = 'v1';
109 $this->serviceName = 'urlshortener';
110
111 $client->addService($this->serviceName, $this->version);
112 $this->url = new Google_UrlServiceResource($this, $this->serviceName, 'url', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/urlshortener"], "request": {"$ref": "Url"}, "response": {"$ref": "Url"}, "httpMethod": "POST", "path": "url", "id": "urlshortener.url.insert"}, "list": {"scopes": ["https://www.googleapis.com/auth/urlshortener"], "parameters": {"start-token": {"type": "string", "location": "query"}, "projection": {"enum": ["ANALYTICS_CLICKS", "FULL"], "type": "string", "location": "query"}}, "response": {"$ref": "UrlHistory"}, "httpMethod": "GET", "path": "url/history", "id": "urlshortener.url.list"}, "get": {"httpMethod": "GET", "response": {"$ref": "Url"}, "id": "urlshortener.url.get", "parameters": {"shortUrl": {"required": true, "type": "string", "location": "query"}, "projection": {"enum": ["ANALYTICS_CLICKS", "ANALYTICS_TOP_STRINGS", "FULL"], "type": "string", "location": "query"}}, "path": "url"}}}', true));
113
114 }
115 }
116
117 class Google_AnalyticsSnapshot extends Google_Model {
118 public $shortUrlClicks;
119 protected $__countriesType = 'Google_StringCount';
120 protected $__countriesDataType = 'array';
121 public $countries;
122 protected $__platformsType = 'Google_StringCount';
123 protected $__platformsDataType = 'array';
124 public $platforms;
125 protected $__browsersType = 'Google_StringCount';
126 protected $__browsersDataType = 'array';
127 public $browsers;
128 protected $__referrersType = 'Google_StringCount';
129 protected $__referrersDataType = 'array';
130 public $referrers;
131 public $longUrlClicks;
132 public function setShortUrlClicks($shortUrlClicks) {
133 $this->shortUrlClicks = $shortUrlClicks;
134 }
135 public function getShortUrlClicks() {
136 return $this->shortUrlClicks;
137 }
138 public function setCountries(/* array(Google_StringCount) */ $countries) {
139 $this->assertIsArray($countries, 'Google_StringCount', __METHOD__);
140 $this->countries = $countries;
141 }
142 public function getCountries() {
143 return $this->countries;
144 }
145 public function setPlatforms(/* array(Google_StringCount) */ $platforms) {
146 $this->assertIsArray($platforms, 'Google_StringCount', __METHOD__);
147 $this->platforms = $platforms;
148 }
149 public function getPlatforms() {
150 return $this->platforms;
151 }
152 public function setBrowsers(/* array(Google_StringCount) */ $browsers) {
153 $this->assertIsArray($browsers, 'Google_StringCount', __METHOD__);
154 $this->browsers = $browsers;
155 }
156 public function getBrowsers() {
157 return $this->browsers;
158 }
159 public function setReferrers(/* array(Google_StringCount) */ $referrers) {
160 $this->assertIsArray($referrers, 'Google_StringCount', __METHOD__);
161 $this->referrers = $referrers;
162 }
163 public function getReferrers() {
164 return $this->referrers;
165 }
166 public function setLongUrlClicks($longUrlClicks) {
167 $this->longUrlClicks = $longUrlClicks;
168 }
169 public function getLongUrlClicks() {
170 return $this->longUrlClicks;
171 }
172 }
173
174 class Google_AnalyticsSummary extends Google_Model {
175 protected $__weekType = 'Google_AnalyticsSnapshot';
176 protected $__weekDataType = '';
177 public $week;
178 protected $__allTimeType = 'Google_AnalyticsSnapshot';
179 protected $__allTimeDataType = '';
180 public $allTime;
181 protected $__twoHoursType = 'Google_AnalyticsSnapshot';
182 protected $__twoHoursDataType = '';
183 public $twoHours;
184 protected $__dayType = 'Google_AnalyticsSnapshot';
185 protected $__dayDataType = '';
186 public $day;
187 protected $__monthType = 'Google_AnalyticsSnapshot';
188 protected $__monthDataType = '';
189 public $month;
190 public function setWeek(Google_AnalyticsSnapshot $week) {
191 $this->week = $week;
192 }
193 public function getWeek() {
194 return $this->week;
195 }
196 public function setAllTime(Google_AnalyticsSnapshot $allTime) {
197 $this->allTime = $allTime;
198 }
199 public function getAllTime() {
200 return $this->allTime;
201 }
202 public function setTwoHours(Google_AnalyticsSnapshot $twoHours) {
203 $this->twoHours = $twoHours;
204 }
205 public function getTwoHours() {
206 return $this->twoHours;
207 }
208 public function setDay(Google_AnalyticsSnapshot $day) {
209 $this->day = $day;
210 }
211 public function getDay() {
212 return $this->day;
213 }
214 public function setMonth(Google_AnalyticsSnapshot $month) {
215 $this->month = $month;
216 }
217 public function getMonth() {
218 return $this->month;
219 }
220 }
221
222 class Google_StringCount extends Google_Model {
223 public $count;
224 public $id;
225 public function setCount($count) {
226 $this->count = $count;
227 }
228 public function getCount() {
229 return $this->count;
230 }
231 public function setId($id) {
232 $this->id = $id;
233 }
234 public function getId() {
235 return $this->id;
236 }
237 }
238
239 class Google_Url extends Google_Model {
240 public $status;
241 public $kind;
242 public $created;
243 protected $__analyticsType = 'Google_AnalyticsSummary';
244 protected $__analyticsDataType = '';
245 public $analytics;
246 public $longUrl;
247 public $id;
248 public function setStatus($status) {
249 $this->status = $status;
250 }
251 public function getStatus() {
252 return $this->status;
253 }
254 public function setKind($kind) {
255 $this->kind = $kind;
256 }
257 public function getKind() {
258 return $this->kind;
259 }
260 public function setCreated($created) {
261 $this->created = $created;
262 }
263 public function getCreated() {
264 return $this->created;
265 }
266 public function setAnalytics(Google_AnalyticsSummary $analytics) {
267 $this->analytics = $analytics;
268 }
269 public function getAnalytics() {
270 return $this->analytics;
271 }
272 public function setLongUrl($longUrl) {
273 $this->longUrl = $longUrl;
274 }
275 public function getLongUrl() {
276 return $this->longUrl;
277 }
278 public function setId($id) {
279 $this->id = $id;
280 }
281 public function getId() {
282 return $this->id;
283 }
284 }
285
286 class Google_UrlHistory extends Google_Model {
287 public $nextPageToken;
288 protected $__itemsType = 'Google_Url';
289 protected $__itemsDataType = 'array';
290 public $items;
291 public $kind;
292 public $itemsPerPage;
293 public $totalItems;
294 public function setNextPageToken($nextPageToken) {
295 $this->nextPageToken = $nextPageToken;
296 }
297 public function getNextPageToken() {
298 return $this->nextPageToken;
299 }
300 public function setItems(/* array(Google_Url) */ $items) {
301 $this->assertIsArray($items, 'Google_Url', __METHOD__);
302 $this->items = $items;
303 }
304 public function getItems() {
305 return $this->items;
306 }
307 public function setKind($kind) {
308 $this->kind = $kind;
309 }
310 public function getKind() {
311 return $this->kind;
312 }
313 public function setItemsPerPage($itemsPerPage) {
314 $this->itemsPerPage = $itemsPerPage;
315 }
316 public function getItemsPerPage() {
317 return $this->itemsPerPage;
318 }
319 public function setTotalItems($totalItems) {
320 $this->totalItems = $totalItems;
321 }
322 public function getTotalItems() {
323 return $this->totalItems;
324 }
325 }
1 <?php
2 /*
3 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 * use this file except in compliance with the License. You may obtain a copy of
5 * the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 * License for the specific language governing permissions and limitations under
13 * the License.
14 */
15
16
17 /**
18 * The "webfonts" collection of methods.
19 * Typical usage is:
20 * <code>
21 * $webfontsService = new Google_WebfontsService(...);
22 * $webfonts = $webfontsService->webfonts;
23 * </code>
24 */
25 class Google_WebfontsServiceResource extends Google_ServiceResource {
26
27
28 /**
29 * Retrieves the list of fonts currently served by the Google Web Fonts Developer API
30 * (webfonts.list)
31 *
32 * @param array $optParams Optional parameters.
33 *
34 * @opt_param string sort Enables sorting of the list
35 * @return Google_WebfontList
36 */
37 public function listWebfonts($optParams = array()) {
38 $params = array();
39 $params = array_merge($params, $optParams);
40 $data = $this->__call('list', array($params));
41 if ($this->useObjects()) {
42 return new Google_WebfontList($data);
43 } else {
44 return $data;
45 }
46 }
47 }
48
49 /**
50 * Service definition for Google_Webfonts (v1).
51 *
52 * <p>
53 * The Google Web Fonts Developer API.
54 * </p>
55 *
56 * <p>
57 * For more information about this service, see the
58 * <a href="http://code.google.com/apis/webfonts/docs/developer_api.html" target="_blank">API Documentation</a>
59 * </p>
60 *
61 * @author Google, Inc.
62 */
63 class Google_WebfontsService extends Google_Service {
64 public $webfonts;
65 /**
66 * Constructs the internal representation of the Webfonts service.
67 *
68 * @param Google_Client $client
69 */
70 public function __construct(Google_Client $client) {
71 $this->servicePath = 'webfonts/v1/';
72 $this->version = 'v1';
73 $this->serviceName = 'webfonts';
74
75 $client->addService($this->serviceName, $this->version);
76 $this->webfonts = new Google_WebfontsServiceResource($this, $this->serviceName, 'webfonts', json_decode('{"methods": {"list": {"httpMethod": "GET", "response": {"$ref": "WebfontList"}, "id": "webfonts.webfonts.list", "parameters": {"sort": {"enum": ["alpha", "date", "popularity", "style", "trending"], "type": "string", "location": "query"}}, "path": "webfonts"}}}', true));
77
78 }
79 }
80
81 class Google_Webfont extends Google_Model {
82 public $kind;
83 public $variants;
84 public $subsets;
85 public $family;
86 public function setKind($kind) {
87 $this->kind = $kind;
88 }
89 public function getKind() {
90 return $this->kind;
91 }
92 public function setVariants($variants) {
93 $this->variants = $variants;
94 }
95 public function getVariants() {
96 return $this->variants;
97 }
98 public function setSubsets($subsets) {
99 $this->subsets = $subsets;
100 }
101 public function getSubsets() {
102 return $this->subsets;
103 }
104 public function setFamily($family) {
105 $this->family = $family;
106 }
107 public function getFamily() {
108 return $this->family;
109 }
110 }
111
112 class Google_WebfontList extends Google_Model {
113 protected $__itemsType = 'Google_Webfont';
114 protected $__itemsDataType = 'array';
115 public $items;
116 public $kind;
117 public function setItems(/* array(Google_Webfont) */ $items) {
118 $this->assertIsArray($items, 'Google_Webfont', __METHOD__);
119 $this->items = $items;
120 }
121 public function getItems() {
122 return $this->items;
123 }
124 public function setKind($kind) {
125 $this->kind = $kind;
126 }
127 public function getKind() {
128 return $this->kind;
129 }
130 }
1 <?php
2 /*
3 Copyright (c) 2010 Kevin M Burns Jr, http://kevburnsjr.com/
4
5 Permission is hereby granted, free of charge, to any person obtaining
6 a copy of this software and associated documentation files (the
7 "Software"), to deal in the Software without restriction, including
8 without limitation the rights to use, copy, modify, merge, publish,
9 distribute, sublicense, and/or sell copies of the Software, and to
10 permit persons to whom the Software is furnished to do so, subject to
11 the following conditions:
12
13 The above copyright notice and this permission notice shall be
14 included in all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 /**
26 * A URI Template Parser which is used by the apiREST class to resolve the REST requests
27 * Blogpost: http://lab.kevburnsjr.com/php-uri-template-parser
28 * Source: http://github.com/KevBurnsJr/php-uri-template-parser
29 */
30 class URI_Template_Parser {
31
32 public static $operators = array('+', ';', '?', '/', '.');
33 public static $reserved_operators = array('|', '!', '@');
34 public static $explode_modifiers = array('+', '*');
35 public static $partial_modifiers = array(':', '^');
36
37 public static $gen_delims = array(':', '/', '?', '#', '[', ']', '@');
38 public static $gen_delims_pct = array('%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40');
39 public static $sub_delims = array('!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=');
40 public static $sub_delims_pct = array('%21', '%24', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D');
41 public static $reserved;
42 public static $reserved_pct;
43
44 public function __construct($template) {
45 self::$reserved = array_merge(self::$gen_delims, self::$sub_delims);
46 self::$reserved_pct = array_merge(self::$gen_delims_pct, self::$sub_delims_pct);
47 $this->template = $template;
48 }
49
50 public function expand($data) {
51 // Modification to make this a bit more performant (since gettype is very slow)
52 if (! is_array($data)) {
53 $data = (array)$data;
54 }
55 /*
56 // Original code, which uses a slow gettype() statement, kept in place for if the assumption that is_array always works here is incorrect
57 switch (gettype($data)) {
58 case "boolean":
59 case "integer":
60 case "double":
61 case "string":
62 case "object":
63 $data = (array)$data;
64 break;
65 }
66 */
67
68 // Resolve template vars
69 preg_match_all('/\{([^\}]*)\}/', $this->template, $em);
70
71 foreach ($em[1] as $i => $bare_expression) {
72 preg_match('/^([\+\;\?\/\.]{1})?(.*)$/', $bare_expression, $lm);
73 $exp = new StdClass();
74 $exp->expression = $em[0][$i];
75 $exp->operator = $lm[1];
76 $exp->variable_list = $lm[2];
77 $exp->varspecs = explode(',', $exp->variable_list);
78 $exp->vars = array();
79 foreach ($exp->varspecs as $varspec) {
80 preg_match('/^([a-zA-Z0-9_]+)([\*\+]{1})?([\:\^][0-9-]+)?(\=[^,]+)?$/', $varspec, $vm);
81 $var = new StdClass();
82 $var->name = $vm[1];
83 $var->modifier = isset($vm[2]) && $vm[2] ? $vm[2] : null;
84 $var->modifier = isset($vm[3]) && $vm[3] ? $vm[3] : $var->modifier;
85 $var->default = isset($vm[4]) ? substr($vm[4], 1) : null;
86 $exp->vars[] = $var;
87 }
88
89 // Add processing flags
90 $exp->reserved = false;
91 $exp->prefix = '';
92 $exp->delimiter = ',';
93 switch ($exp->operator) {
94 case '+':
95 $exp->reserved = 'true';
96 break;
97 case ';':
98 $exp->prefix = ';';
99 $exp->delimiter = ';';
100 break;
101 case '?':
102 $exp->prefix = '?';
103 $exp->delimiter = '&';
104 break;
105 case '/':
106 $exp->prefix = '/';
107 $exp->delimiter = '/';
108 break;
109 case '.':
110 $exp->prefix = '.';
111 $exp->delimiter = '.';
112 break;
113 }
114 $expressions[] = $exp;
115 }
116
117 // Expansion
118 $this->expansion = $this->template;
119
120 foreach ($expressions as $exp) {
121 $part = $exp->prefix;
122 $exp->one_var_defined = false;
123 foreach ($exp->vars as $var) {
124 $val = '';
125 if ($exp->one_var_defined && isset($data[$var->name])) {
126 $part .= $exp->delimiter;
127 }
128 // Variable present
129 if (isset($data[$var->name])) {
130 $exp->one_var_defined = true;
131 $var->data = $data[$var->name];
132
133 $val = self::val_from_var($var, $exp);
134
135 // Variable missing
136 } else {
137 if ($var->default) {
138 $exp->one_var_defined = true;
139 $val = $var->default;
140 }
141 }
142 $part .= $val;
143 }
144 if (! $exp->one_var_defined) $part = '';
145 $this->expansion = str_replace($exp->expression, $part, $this->expansion);
146 }
147
148 return $this->expansion;
149 }
150
151 private function val_from_var($var, $exp) {
152 $val = '';
153 if (is_array($var->data)) {
154 $i = 0;
155 if ($exp->operator == '?' && ! $var->modifier) {
156 $val .= $var->name . '=';
157 }
158 foreach ($var->data as $k => $v) {
159 $del = $var->modifier ? $exp->delimiter : ',';
160 $ek = rawurlencode($k);
161 $ev = rawurlencode($v);
162
163 // Array
164 if ($k !== $i) {
165 if ($var->modifier == '+') {
166 $val .= $var->name . '.';
167 }
168 if ($exp->operator == '?' && $var->modifier || $exp->operator == ';' && $var->modifier == '*' || $exp->operator == ';' && $var->modifier == '+') {
169 $val .= $ek . '=';
170 } else {
171 $val .= $ek . $del;
172 }
173
174 // List
175 } else {
176 if ($var->modifier == '+') {
177 if ($exp->operator == ';' && $var->modifier == '*' || $exp->operator == ';' && $var->modifier == '+' || $exp->operator == '?' && $var->modifier == '+') {
178 $val .= $var->name . '=';
179 } else {
180 $val .= $var->name . '.';
181 }
182 }
183 }
184 $val .= $ev . $del;
185 $i ++;
186 }
187 $val = trim($val, $del);
188
189 // Strings, numbers, etc.
190 } else {
191 if ($exp->operator == '?') {
192 $val = $var->name . (isset($var->data) ? '=' : '');
193 } else if ($exp->operator == ';') {
194 $val = $var->name . ($var->data ? '=' : '');
195 }
196 $val .= rawurlencode($var->data);
197 if ($exp->operator == '+') {
198 $val = str_replace(self::$reserved_pct, self::$reserved, $val);
199 }
200 }
201 return $val;
202 }
203
204 public function match($uri) {}
205
206 public function __toString() {
207 return $this->template;
208 }
209 }
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 * Implement the caching directives specified in rfc2616. This
19 * implementation is guided by the guidance offered in rfc2616-sec13.
20 * @author Chirag Shah <chirags@google.com>
21 */
22 class Google_CacheParser {
23 public static $CACHEABLE_HTTP_METHODS = array('GET', 'HEAD');
24 public static $CACHEABLE_STATUS_CODES = array('200', '203', '300', '301');
25
26 private function __construct() {}
27
28 /**
29 * Check if an HTTP request can be cached by a private local cache.
30 *
31 * @static
32 * @param Google_HttpRequest $resp
33 * @return bool True if the request is cacheable.
34 * False if the request is uncacheable.
35 */
36 public static function isRequestCacheable (Google_HttpRequest $resp) {
37 $method = $resp->getRequestMethod();
38 if (! in_array($method, self::$CACHEABLE_HTTP_METHODS)) {
39 return false;
40 }
41
42 // Don't cache authorized requests/responses.
43 // [rfc2616-14.8] When a shared cache receives a request containing an
44 // Authorization field, it MUST NOT return the corresponding response
45 // as a reply to any other request...
46 if ($resp->getRequestHeader("authorization")) {
47 return false;
48 }
49
50 return true;
51 }
52
53 /**
54 * Check if an HTTP response can be cached by a private local cache.
55 *
56 * @static
57 * @param Google_HttpRequest $resp
58 * @return bool True if the response is cacheable.
59 * False if the response is un-cacheable.
60 */
61 public static function isResponseCacheable (Google_HttpRequest $resp) {
62 // First, check if the HTTP request was cacheable before inspecting the
63 // HTTP response.
64 if (false == self::isRequestCacheable($resp)) {
65 return false;
66 }
67
68 $code = $resp->getResponseHttpCode();
69 if (! in_array($code, self::$CACHEABLE_STATUS_CODES)) {
70 return false;
71 }
72
73 // The resource is uncacheable if the resource is already expired and
74 // the resource doesn't have an ETag for revalidation.
75 $etag = $resp->getResponseHeader("etag");
76 if (self::isExpired($resp) && $etag == false) {
77 return false;
78 }
79
80 // [rfc2616-14.9.2] If [no-store is] sent in a response, a cache MUST NOT
81 // store any part of either this response or the request that elicited it.
82 $cacheControl = $resp->getParsedCacheControl();
83 if (isset($cacheControl['no-store'])) {
84 return false;
85 }
86
87 // Pragma: no-cache is an http request directive, but is occasionally
88 // used as a response header incorrectly.
89 $pragma = $resp->getResponseHeader('pragma');
90 if ($pragma == 'no-cache' || strpos($pragma, 'no-cache') !== false) {
91 return false;
92 }
93
94 // [rfc2616-14.44] Vary: * is extremely difficult to cache. "It implies that
95 // a cache cannot determine from the request headers of a subsequent request
96 // whether this response is the appropriate representation."
97 // Given this, we deem responses with the Vary header as uncacheable.
98 $vary = $resp->getResponseHeader('vary');
99 if ($vary) {
100 return false;
101 }
102
103 return true;
104 }
105
106 /**
107 * @static
108 * @param Google_HttpRequest $resp
109 * @return bool True if the HTTP response is considered to be expired.
110 * False if it is considered to be fresh.
111 */
112 public static function isExpired(Google_HttpRequest $resp) {
113 // HTTP/1.1 clients and caches MUST treat other invalid date formats,
114 // especially including the value “0”, as in the past.
115 $parsedExpires = false;
116 $responseHeaders = $resp->getResponseHeaders();
117 if (isset($responseHeaders['expires'])) {
118 $rawExpires = $responseHeaders['expires'];
119 // Check for a malformed expires header first.
120 if (empty($rawExpires) || (is_numeric($rawExpires) && $rawExpires <= 0)) {
121 return true;
122 }
123
124 // See if we can parse the expires header.
125 $parsedExpires = strtotime($rawExpires);
126 if (false == $parsedExpires || $parsedExpires <= 0) {
127 return true;
128 }
129 }
130
131 // Calculate the freshness of an http response.
132 $freshnessLifetime = false;
133 $cacheControl = $resp->getParsedCacheControl();
134 if (isset($cacheControl['max-age'])) {
135 $freshnessLifetime = $cacheControl['max-age'];
136 }
137
138 $rawDate = $resp->getResponseHeader('date');
139 $parsedDate = strtotime($rawDate);
140
141 if (empty($rawDate) || false == $parsedDate) {
142 $parsedDate = time();
143 }
144 if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
145 $freshnessLifetime = $parsedExpires - $parsedDate;
146 }
147
148 if (false == $freshnessLifetime) {
149 return true;
150 }
151
152 // Calculate the age of an http response.
153 $age = max(0, time() - $parsedDate);
154 if (isset($responseHeaders['age'])) {
155 $age = max($age, strtotime($responseHeaders['age']));
156 }
157
158 return $freshnessLifetime <= $age;
159 }
160
161 /**
162 * Determine if a cache entry should be revalidated with by the origin.
163 *
164 * @param Google_HttpRequest $response
165 * @return bool True if the entry is expired, else return false.
166 */
167 public static function mustRevalidate(Google_HttpRequest $response) {
168 // [13.3] When a cache has a stale entry that it would like to use as a
169 // response to a client's request, it first has to check with the origin
170 // server to see if its cached entry is still usable.
171 return self::isExpired($response);
172 }
173 }
...\ No newline at end of file ...\ No newline at end of file
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 * Curl based implementation of apiIO.
20 *
21 * @author Chris Chabot <chabotc@google.com>
22 * @author Chirag Shah <chirags@google.com>
23 */
24
25 require_once 'Google_CacheParser.php';
26
27 class Google_CurlIO implements Google_IO {
28 const CONNECTION_ESTABLISHED = "HTTP/1.0 200 Connection established\r\n\r\n";
29 const FORM_URLENCODED = 'application/x-www-form-urlencoded';
30
31 private static $ENTITY_HTTP_METHODS = array("POST" => null, "PUT" => null);
32 private static $HOP_BY_HOP = array(
33 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
34 'te', 'trailers', 'transfer-encoding', 'upgrade');
35
36 private $curlParams = array (
37 CURLOPT_RETURNTRANSFER => true,
38 CURLOPT_FOLLOWLOCATION => 0,
39 CURLOPT_FAILONERROR => false,
40 CURLOPT_SSL_VERIFYPEER => true,
41 CURLOPT_HEADER => true,
42 CURLOPT_VERBOSE => false,
43 );
44
45 /**
46 * Perform an authenticated / signed apiHttpRequest.
47 * This function takes the apiHttpRequest, calls apiAuth->sign on it
48 * (which can modify the request in what ever way fits the auth mechanism)
49 * and then calls apiCurlIO::makeRequest on the signed request
50 *
51 * @param Google_HttpRequest $request
52 * @return Google_HttpRequest The resulting HTTP response including the
53 * responseHttpCode, responseHeaders and responseBody.
54 */
55 public function authenticatedRequest(Google_HttpRequest $request) {
56 $request = Google_Client::$auth->sign($request);
57 return $this->makeRequest($request);
58 }
59
60 /**
61 * Execute a apiHttpRequest
62 *
63 * @param Google_HttpRequest $request the http request to be executed
64 * @return Google_HttpRequest http request with the response http code, response
65 * headers and response body filled in
66 * @throws Google_IOException on curl or IO error
67 */
68 public function makeRequest(Google_HttpRequest $request) {
69 // First, check to see if we have a valid cached version.
70 $cached = $this->getCachedRequest($request);
71 if ($cached !== false) {
72 if (Google_CacheParser::mustRevalidate($cached)) {
73 $addHeaders = array();
74 if ($cached->getResponseHeader('etag')) {
75 // [13.3.4] If an entity tag has been provided by the origin server,
76 // we must use that entity tag in any cache-conditional request.
77 $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
78 } elseif ($cached->getResponseHeader('date')) {
79 $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
80 }
81
82 $request->setRequestHeaders($addHeaders);
83 } else {
84 // No need to revalidate the request, return it directly
85 return $cached;
86 }
87 }
88
89 if (array_key_exists($request->getRequestMethod(),
90 self::$ENTITY_HTTP_METHODS)) {
91 $request = $this->processEntityRequest($request);
92 }
93
94 $ch = curl_init();
95 curl_setopt_array($ch, $this->curlParams);
96 curl_setopt($ch, CURLOPT_URL, $request->getUrl());
97 if ($request->getPostBody()) {
98 curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPostBody());
99 }
100
101 $requestHeaders = $request->getRequestHeaders();
102 if ($requestHeaders && is_array($requestHeaders)) {
103 $parsed = array();
104 foreach ($requestHeaders as $k => $v) {
105 $parsed[] = "$k: $v";
106 }
107 curl_setopt($ch, CURLOPT_HTTPHEADER, $parsed);
108 }
109
110 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
111 curl_setopt($ch, CURLOPT_USERAGENT, $request->getUserAgent());
112 $respData = curl_exec($ch);
113
114 // Retry if certificates are missing.
115 if (curl_errno($ch) == CURLE_SSL_CACERT) {
116 error_log('SSL certificate problem, verify that the CA cert is OK.'
117 . ' Retrying with the CA cert bundle from google-api-php-client.');
118 curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
119 $respData = curl_exec($ch);
120 }
121
122 $respHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
123 $respHttpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
124 $curlErrorNum = curl_errno($ch);
125 $curlError = curl_error($ch);
126 curl_close($ch);
127 if ($curlErrorNum != CURLE_OK) {
128 throw new Google_IOException("HTTP Error: ($respHttpCode) $curlError");
129 }
130
131 // Parse out the raw response into usable bits
132 list($responseHeaders, $responseBody) =
133 self::parseHttpResponse($respData, $respHeaderSize);
134
135 if ($respHttpCode == 304 && $cached) {
136 // If the server responded NOT_MODIFIED, return the cached request.
137 if (isset($responseHeaders['connection'])) {
138 $hopByHop = array_merge(
139 self::$HOP_BY_HOP,
140 explode(',', $responseHeaders['connection'])
141 );
142
143 $endToEnd = array();
144 foreach($hopByHop as $key) {
145 if (isset($responseHeaders[$key])) {
146 $endToEnd[$key] = $responseHeaders[$key];
147 }
148 }
149 $cached->setResponseHeaders($endToEnd);
150 }
151 return $cached;
152 }
153
154 // Fill in the apiHttpRequest with the response values
155 $request->setResponseHttpCode($respHttpCode);
156 $request->setResponseHeaders($responseHeaders);
157 $request->setResponseBody($responseBody);
158 // Store the request in cache (the function checks to see if the request
159 // can actually be cached)
160 $this->setCachedRequest($request);
161 // And finally return it
162 return $request;
163 }
164
165 /**
166 * @visible for testing.
167 * Cache the response to an HTTP request if it is cacheable.
168 * @param Google_HttpRequest $request
169 * @return bool Returns true if the insertion was successful.
170 * Otherwise, return false.
171 */
172 public function setCachedRequest(Google_HttpRequest $request) {
173 // Determine if the request is cacheable.
174 if (Google_CacheParser::isResponseCacheable($request)) {
175 Google_Client::$cache->set($request->getCacheKey(), $request);
176 return true;
177 }
178
179 return false;
180 }
181
182 /**
183 * @visible for testing.
184 * @param Google_HttpRequest $request
185 * @return Google_HttpRequest|bool Returns the cached object or
186 * false if the operation was unsuccessful.
187 */
188 public function getCachedRequest(Google_HttpRequest $request) {
189 if (false == Google_CacheParser::isRequestCacheable($request)) {
190 false;
191 }
192
193 return Google_Client::$cache->get($request->getCacheKey());
194 }
195
196 /**
197 * @param $respData
198 * @param $headerSize
199 * @return array
200 */
201 public static function parseHttpResponse($respData, $headerSize) {
202 if (stripos($respData, self::CONNECTION_ESTABLISHED) !== false) {
203 $respData = str_ireplace(self::CONNECTION_ESTABLISHED, '', $respData);
204 }
205
206 if ($headerSize) {
207 $responseBody = substr($respData, $headerSize);
208 $responseHeaders = substr($respData, 0, $headerSize);
209 } else {
210 list($responseHeaders, $responseBody) = explode("\r\n\r\n", $respData, 2);
211 }
212
213 $responseHeaders = self::parseResponseHeaders($responseHeaders);
214 return array($responseHeaders, $responseBody);
215 }
216
217 public static function parseResponseHeaders($rawHeaders) {
218 $responseHeaders = array();
219
220 $responseHeaderLines = explode("\r\n", $rawHeaders);
221 foreach ($responseHeaderLines as $headerLine) {
222 if ($headerLine && strpos($headerLine, ':') !== false) {
223 list($header, $value) = explode(': ', $headerLine, 2);
224 $header = strtolower($header);
225 if (isset($responseHeaders[$header])) {
226 $responseHeaders[$header] .= "\n" . $value;
227 } else {
228 $responseHeaders[$header] = $value;
229 }
230 }
231 }
232 return $responseHeaders;
233 }
234
235 /**
236 * @visible for testing
237 * Process an http request that contains an enclosed entity.
238 * @param Google_HttpRequest $request
239 * @return Google_HttpRequest Processed request with the enclosed entity.
240 */
241 public function processEntityRequest(Google_HttpRequest $request) {
242 $postBody = $request->getPostBody();
243 $contentType = $request->getRequestHeader("content-type");
244
245 // Set the default content-type as application/x-www-form-urlencoded.
246 if (false == $contentType) {
247 $contentType = self::FORM_URLENCODED;
248 $request->setRequestHeaders(array('content-type' => $contentType));
249 }
250
251 // Force the payload to match the content-type asserted in the header.
252 if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
253 $postBody = http_build_query($postBody, '', '&');
254 $request->setPostBody($postBody);
255 }
256
257 // Make sure the content-length header is set.
258 if (!$postBody || is_string($postBody)) {
259 $postsLength = strlen($postBody);
260 $request->setRequestHeaders(array('content-length' => $postsLength));
261 }
262
263 return $request;
264 }
265
266 /**
267 * Set options that update cURL's default behavior.
268 * The list of accepted options are:
269 * {@link http://php.net/manual/en/function.curl-setopt.php]
270 *
271 * @param array $optCurlParams Multiple options used by a cURL session.
272 */
273 public function setOptions($optCurlParams) {
274 foreach ($optCurlParams as $key => $val) {
275 $this->curlParams[$key] = $val;
276 }
277 }
278 }
...\ No newline at end of file ...\ No newline at end of file
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 * HTTP Request to be executed by apiIO classes. Upon execution, the
20 * responseHttpCode, responseHeaders and responseBody will be filled in.
21 *
22 * @author Chris Chabot <chabotc@google.com>
23 * @author Chirag Shah <chirags@google.com>
24 *
25 */
26 class Google_HttpRequest {
27 const USER_AGENT_SUFFIX = "google-api-php-client/0.6.0";
28 private $batchHeaders = array(
29 'Content-Type' => 'application/http',
30 'Content-Transfer-Encoding' => 'binary',
31 'MIME-Version' => '1.0',
32 'Content-Length' => ''
33 );
34
35 protected $url;
36 protected $requestMethod;
37 protected $requestHeaders;
38 protected $postBody;
39 protected $userAgent;
40
41 protected $responseHttpCode;
42 protected $responseHeaders;
43 protected $responseBody;
44
45 public $accessKey;
46
47 public function __construct($url, $method = 'GET', $headers = array(), $postBody = null) {
48 $this->setUrl($url);
49 $this->setRequestMethod($method);
50 $this->setRequestHeaders($headers);
51 $this->setPostBody($postBody);
52
53 global $apiConfig;
54 if (empty($apiConfig['application_name'])) {
55 $this->userAgent = self::USER_AGENT_SUFFIX;
56 } else {
57 $this->userAgent = $apiConfig['application_name'] . " " . self::USER_AGENT_SUFFIX;
58 }
59 }
60
61 /**
62 * Misc function that returns the base url component of the $url
63 * used by the OAuth signing class to calculate the base string
64 * @return string The base url component of the $url.
65 * @see http://oauth.net/core/1.0a/#anchor13
66 */
67 public function getBaseUrl() {
68 if ($pos = strpos($this->url, '?')) {
69 return substr($this->url, 0, $pos);
70 }
71 return $this->url;
72 }
73
74 /**
75 * Misc function that returns an array of the query parameters of the current
76 * url used by the OAuth signing class to calculate the signature
77 * @return array Query parameters in the query string.
78 */
79 public function getQueryParams() {
80 if ($pos = strpos($this->url, '?')) {
81 $queryStr = substr($this->url, $pos + 1);
82 $params = array();
83 parse_str($queryStr, $params);
84 return $params;
85 }
86 return array();
87 }
88
89 /**
90 * @return string HTTP Response Code.
91 */
92 public function getResponseHttpCode() {
93 return (int) $this->responseHttpCode;
94 }
95
96 /**
97 * @param int $responseHttpCode HTTP Response Code.
98 */
99 public function setResponseHttpCode($responseHttpCode) {
100 $this->responseHttpCode = $responseHttpCode;
101 }
102
103 /**
104 * @return $responseHeaders (array) HTTP Response Headers.
105 */
106 public function getResponseHeaders() {
107 return $this->responseHeaders;
108 }
109
110 /**
111 * @return string HTTP Response Body
112 */
113 public function getResponseBody() {
114 return $this->responseBody;
115 }
116
117 /**
118 * @param array $headers The HTTP response headers
119 * to be normalized.
120 */
121 public function setResponseHeaders($headers) {
122 $headers = Google_Utils::normalize($headers);
123 if ($this->responseHeaders) {
124 $headers = array_merge($this->responseHeaders, $headers);
125 }
126
127 $this->responseHeaders = $headers;
128 }
129
130 /**
131 * @param string $key
132 * @return array|boolean Returns the requested HTTP header or
133 * false if unavailable.
134 */
135 public function getResponseHeader($key) {
136 return isset($this->responseHeaders[$key])
137 ? $this->responseHeaders[$key]
138 : false;
139 }
140
141 /**
142 * @param string $responseBody The HTTP response body.
143 */
144 public function setResponseBody($responseBody) {
145 $this->responseBody = $responseBody;
146 }
147
148 /**
149 * @return string $url The request URL.
150 */
151
152 public function getUrl() {
153 return $this->url;
154 }
155
156 /**
157 * @return string $method HTTP Request Method.
158 */
159 public function getRequestMethod() {
160 return $this->requestMethod;
161 }
162
163 /**
164 * @return array $headers HTTP Request Headers.
165 */
166 public function getRequestHeaders() {
167 return $this->requestHeaders;
168 }
169
170 /**
171 * @param string $key
172 * @return array|boolean Returns the requested HTTP header or
173 * false if unavailable.
174 */
175 public function getRequestHeader($key) {
176 return isset($this->requestHeaders[$key])
177 ? $this->requestHeaders[$key]
178 : false;
179 }
180
181 /**
182 * @return string $postBody HTTP Request Body.
183 */
184 public function getPostBody() {
185 return $this->postBody;
186 }
187
188 /**
189 * @param string $url the url to set
190 */
191 public function setUrl($url) {
192 if (substr($url, 0, 4) == 'http') {
193 $this->url = $url;
194 } else {
195 // Force the path become relative.
196 if (substr($url, 0, 1) !== '/') {
197 $url = '/' . $url;
198 }
199 global $apiConfig;
200 $this->url = $apiConfig['basePath'] . $url;
201 }
202 }
203
204 /**
205 * @param string $method Set he HTTP Method and normalize
206 * it to upper-case, as required by HTTP.
207 *
208 */
209 public function setRequestMethod($method) {
210 $this->requestMethod = strtoupper($method);
211 }
212
213 /**
214 * @param array $headers The HTTP request headers
215 * to be set and normalized.
216 */
217 public function setRequestHeaders($headers) {
218 $headers = Google_Utils::normalize($headers);
219 if ($this->requestHeaders) {
220 $headers = array_merge($this->requestHeaders, $headers);
221 }
222 $this->requestHeaders = $headers;
223 }
224
225 /**
226 * @param string $postBody the postBody to set
227 */
228 public function setPostBody($postBody) {
229 $this->postBody = $postBody;
230 }
231
232 /**
233 * Set the User-Agent Header.
234 * @param string $userAgent The User-Agent.
235 */
236 public function setUserAgent($userAgent) {
237 $this->userAgent = $userAgent;
238 }
239
240 /**
241 * @return string The User-Agent.
242 */
243 public function getUserAgent() {
244 return $this->userAgent;
245 }
246
247 /**
248 * Returns a cache key depending on if this was an OAuth signed request
249 * in which case it will use the non-signed url and access key to make this
250 * cache key unique per authenticated user, else use the plain request url
251 * @return string The md5 hash of the request cache key.
252 */
253 public function getCacheKey() {
254 $key = $this->getUrl();
255
256 if (isset($this->accessKey)) {
257 $key .= $this->accessKey;
258 }
259
260 if (isset($this->requestHeaders['authorization'])) {
261 $key .= $this->requestHeaders['authorization'];
262 }
263
264 return md5($key);
265 }
266
267 public function getParsedCacheControl() {
268 $parsed = array();
269 $rawCacheControl = $this->getResponseHeader('cache-control');
270 if ($rawCacheControl) {
271 $rawCacheControl = str_replace(', ', '&', $rawCacheControl);
272 parse_str($rawCacheControl, $parsed);
273 }
274
275 return $parsed;
276 }
277
278 /**
279 * @param string $id
280 * @return string A string representation of the HTTP Request.
281 */
282 public function toBatchString($id) {
283 $str = '';
284 foreach($this->batchHeaders as $key => $val) {
285 $str .= $key . ': ' . $val . "\n";
286 }
287
288 $str .= "Content-ID: $id\n";
289 $str .= "\n";
290
291 $path = parse_url($this->getUrl(), PHP_URL_PATH);
292 $str .= $this->getRequestMethod() . ' ' . $path . " HTTP/1.1\n";
293 foreach($this->getRequestHeaders() as $key => $val) {
294 $str .= $key . ': ' . $val . "\n";
295 }
296
297 if ($this->getPostBody()) {
298 $str .= "\n";
299 $str .= $this->getPostBody();
300 }
301
302 return $str;
303 }
304 }
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 'io/Google_HttpRequest.php';
19 require_once 'io/Google_CurlIO.php';
20 require_once 'io/Google_REST.php';
21
22 /**
23 * Abstract IO class
24 *
25 * @author Chris Chabot <chabotc@google.com>
26 */
27 interface Google_IO {
28 /**
29 * An utility function that first calls $this->auth->sign($request) and then executes makeRequest()
30 * on that signed request. Used for when a request should be authenticated
31 * @param Google_HttpRequest $request
32 * @return Google_HttpRequest $request
33 */
34 public function authenticatedRequest(Google_HttpRequest $request);
35
36 /**
37 * Executes a apIHttpRequest and returns the resulting populated httpRequest
38 * @param Google_HttpRequest $request
39 * @return Google_HttpRequest $request
40 */
41 public function makeRequest(Google_HttpRequest $request);
42
43 /**
44 * Set options that update the transport implementation's behavior.
45 * @param $options
46 */
47 public function setOptions($options);
48
49 }
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 * This class implements the RESTful transport of apiServiceRequest()'s
20 *
21 * @author Chris Chabot <chabotc@google.com>
22 * @author Chirag Shah <chirags@google.com>
23 */
24 class Google_REST {
25 /**
26 * Executes a apiServiceRequest using a RESTful call by transforming it into
27 * an apiHttpRequest, and executed via apiIO::authenticatedRequest().
28 *
29 * @param Google_HttpRequest $req
30 * @return array decoded result
31 * @throws Google_ServiceException on server side error (ie: not authenticated,
32 * invalid or malformed post body, invalid url)
33 */
34 static public function execute(Google_HttpRequest $req) {
35 $httpRequest = Google_Client::$io->makeRequest($req);
36 $decodedResponse = self::decodeHttpResponse($httpRequest);
37 $ret = isset($decodedResponse['data'])
38 ? $decodedResponse['data'] : $decodedResponse;
39 return $ret;
40 }
41
42
43 /**
44 * Decode an HTTP Response.
45 * @static
46 * @throws Google_ServiceException
47 * @param Google_HttpRequest $response The http response to be decoded.
48 * @return mixed|null
49 */
50 public static function decodeHttpResponse($response) {
51 $code = $response->getResponseHttpCode();
52 $body = $response->getResponseBody();
53 $decoded = null;
54
55 if ($code != '200' && $code != '201' && $code != '204') {
56 $decoded = json_decode($body, true);
57 $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
58 if ($decoded != null && isset($decoded['error']['message']) && isset($decoded['error']['code'])) {
59 // if we're getting a json encoded error definition, use that instead of the raw response
60 // body for improved readability
61 $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
62 } else {
63 $err .= ": ($code) $body";
64 }
65
66 throw new Google_ServiceException($err, $code, null, $decoded['error']['errors']);
67 }
68
69 // Only attempt to decode the response, if the response code wasn't (204) 'no content'
70 if ($code != '204') {
71 $decoded = json_decode($body, true);
72 if ($decoded === null || $decoded === "") {
73 throw new Google_ServiceException("Invalid json in service response: $body");
74 }
75 }
76 return $decoded;
77 }
78
79 /**
80 * Parse/expand request parameters and create a fully qualified
81 * request uri.
82 * @static
83 * @param string $servicePath
84 * @param string $restPath
85 * @param array $params
86 * @return string $requestUrl
87 */
88 static function createRequestUri($servicePath, $restPath, $params) {
89 $requestUrl = $servicePath . $restPath;
90 $uriTemplateVars = array();
91 $queryVars = array();
92 foreach ($params as $paramName => $paramSpec) {
93 // Discovery v1.0 puts the canonical location under the 'location' field.
94 if (! isset($paramSpec['location'])) {
95 $paramSpec['location'] = $paramSpec['restParameterType'];
96 }
97
98 if ($paramSpec['type'] == 'boolean') {
99 $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
100 }
101 if ($paramSpec['location'] == 'path') {
102 $uriTemplateVars[$paramName] = $paramSpec['value'];
103 } else {
104 if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
105 foreach ($paramSpec['value'] as $value) {
106 $queryVars[] = $paramName . '=' . rawurlencode($value);
107 }
108 } else {
109 $queryVars[] = $paramName . '=' . rawurlencode($paramSpec['value']);
110 }
111 }
112 }
113
114 if (count($uriTemplateVars)) {
115 $uriTemplateParser = new URI_Template_Parser($requestUrl);
116 $requestUrl = $uriTemplateParser->expand($uriTemplateVars);
117 }
118 //FIXME work around for the the uri template lib which url encodes
119 // the @'s & confuses our servers.
120 $requestUrl = str_replace('%40', '@', $requestUrl);
121
122 if (count($queryVars)) {
123 $requestUrl .= '?' . implode($queryVars, '&');
124 }
125
126 return $requestUrl;
127 }
128 }
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 * @author Chirag Shah <chirags@google.com>
20 */
21 class Google_BatchRequest {
22 /** @var string Multipart Boundary. */
23 private $boundary;
24
25 /** @var array service requests to be executed. */
26 private $requests = array();
27
28 public function __construct($boundary = false) {
29 $boundary = (false == $boundary) ? mt_rand() : $boundary;
30 $this->boundary = str_replace('"', '', $boundary);
31 }
32
33 public function add(Google_HttpRequest $request, $key = false) {
34 if (false == $key) {
35 $key = mt_rand();
36 }
37
38 $this->requests[$key] = $request;
39 }
40
41 public function execute() {
42 $body = '';
43
44 /** @var Google_HttpRequest $req */
45 foreach($this->requests as $key => $req) {
46 $body .= "--{$this->boundary}\n";
47 $body .= $req->toBatchString($key) . "\n";
48 }
49
50 $body = rtrim($body);
51 $body .= "\n--{$this->boundary}--";
52
53 global $apiConfig;
54 $url = $apiConfig['basePath'] . '/batch';
55 $httpRequest = new Google_HttpRequest($url, 'POST');
56 $httpRequest->setRequestHeaders(array(
57 'Content-Type' => 'multipart/mixed; boundary=' . $this->boundary));
58
59 $httpRequest->setPostBody($body);
60 $response = Google_Client::$io->makeRequest($httpRequest);
61
62 $response = $this->parseResponse($response);
63 return $response;
64 }
65
66 public function parseResponse(Google_HttpRequest $response) {
67 $contentType = $response->getResponseHeader('content-type');
68 $contentType = explode(';', $contentType);
69 $boundary = false;
70 foreach($contentType as $part) {
71 $part = (explode('=', $part, 2));
72 if (isset($part[0]) && 'boundary' == trim($part[0])) {
73 $boundary = $part[1];
74 }
75 }
76
77 $body = $response->getResponseBody();
78 if ($body) {
79 $body = str_replace("--$boundary--", "--$boundary", $body);
80 $parts = explode("--$boundary", $body);
81 $responses = array();
82
83 foreach($parts as $part) {
84 $part = trim($part);
85 if (!empty($part)) {
86 list($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
87 $metaHeaders = Google_CurlIO::parseResponseHeaders($metaHeaders);
88
89 $status = substr($part, 0, strpos($part, "\n"));
90 $status = explode(" ", $status);
91 $status = $status[1];
92
93 list($partHeaders, $partBody) = Google_CurlIO::parseHttpResponse($part, false);
94 $response = new Google_HttpRequest("");
95 $response->setResponseHttpCode($status);
96 $response->setResponseHeaders($partHeaders);
97 $response->setResponseBody($partBody);
98 $response = Google_REST::decodeHttpResponse($response);
99
100 // Need content id.
101 $responses[$metaHeaders['content-id']] = $response;
102 }
103 }
104
105 return $responses;
106 }
107
108 return null;
109 }
110 }
...\ No newline at end of file ...\ No newline at end of file
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 * @author Chirag Shah <chirags@google.com>
20 *
21 */
22 class Google_MediaFileUpload {
23 const UPLOAD_MEDIA_TYPE = 'media';
24 const UPLOAD_MULTIPART_TYPE = 'multipart';
25 const UPLOAD_RESUMABLE_TYPE = 'resumable';
26
27 /** @var string $mimeType */
28 public $mimeType;
29
30 /** @var string $data */
31 public $data;
32
33 /** @var bool $resumable */
34 public $resumable;
35
36 /** @var int $chunkSize */
37 public $chunkSize;
38
39 /** @var int $size */
40 public $size;
41
42 /** @var string $resumeUri */
43 public $resumeUri;
44
45 /** @var int $progress */
46 public $progress;
47
48 /**
49 * @param $mimeType string
50 * @param $data string The bytes you want to upload.
51 * @param $resumable bool
52 * @param bool $chunkSize File will be uploaded in chunks of this many bytes.
53 * only used if resumable=True
54 */
55 public function __construct($mimeType, $data, $resumable=false, $chunkSize=false) {
56 $this->mimeType = $mimeType;
57 $this->data = $data;
58 $this->size = strlen($this->data);
59 $this->resumable = $resumable;
60 if(!$chunkSize) {
61 $this->chunkSize = 256 * 1024;
62 }
63
64 $this->progress = 0;
65 }
66
67 /**
68 * @static
69 * @param $meta
70 * @param $params
71 * @return array|bool
72 */
73 public static function process($meta, &$params) {
74 $payload = array();
75 $meta = is_string($meta) ? json_decode($meta, true) : $meta;
76 $uploadType = self::getUploadType($meta, $payload, $params);
77 if (!$uploadType) {
78 // Process as a normal API request.
79 return false;
80 }
81
82 // Process as a media upload request.
83 $params['uploadType'] = array(
84 'type' => 'string',
85 'location' => 'query',
86 'value' => $uploadType,
87 );
88
89 if (isset($params['file'])) {
90 // This is a standard file upload with curl.
91 $file = $params['file']['value'];
92 unset($params['file']);
93 return self::processFileUpload($file);
94 }
95
96 $mimeType = isset($params['mimeType'])
97 ? $params['mimeType']['value']
98 : false;
99 unset($params['mimeType']);
100
101 $data = isset($params['data'])
102 ? $params['data']['value']
103 : false;
104 unset($params['data']);
105
106 if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
107 $payload['content-type'] = $mimeType;
108
109 } elseif (self::UPLOAD_MEDIA_TYPE == $uploadType) {
110 // This is a simple media upload.
111 $payload['content-type'] = $mimeType;
112 $payload['postBody'] = $data;
113 }
114
115 elseif (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
116 // This is a multipart/related upload.
117 $boundary = isset($params['boundary']['value']) ? $params['boundary']['value'] : mt_rand();
118 $boundary = str_replace('"', '', $boundary);
119 $payload['content-type'] = 'multipart/related; boundary=' . $boundary;
120 $related = "--$boundary\r\n";
121 $related .= "Content-Type: application/json; charset=UTF-8\r\n";
122 $related .= "\r\n" . json_encode($meta) . "\r\n";
123 $related .= "--$boundary\r\n";
124 $related .= "Content-Type: $mimeType\r\n";
125 $related .= "Content-Transfer-Encoding: base64\r\n";
126 $related .= "\r\n" . base64_encode($data) . "\r\n";
127 $related .= "--$boundary--";
128 $payload['postBody'] = $related;
129 }
130
131 return $payload;
132 }
133
134 /**
135 * Process standard file uploads.
136 * @param $file
137 * @internal param $fileName
138 * @return array Inclues the processed file name.
139 * @visible For testing.
140 */
141 public static function processFileUpload($file) {
142 if (!$file) return array();
143 if (substr($file, 0, 1) != '@') {
144 $file = '@' . $file;
145 }
146
147 // This is a standard file upload with curl.
148 return array('postBody' => array('file' => $file));
149 }
150
151 /**
152 * Valid upload types:
153 * - resumable (UPLOAD_RESUMABLE_TYPE)
154 * - media (UPLOAD_MEDIA_TYPE)
155 * - multipart (UPLOAD_MULTIPART_TYPE)
156 * - none (false)
157 * @param $meta
158 * @param $payload
159 * @param $params
160 * @return bool|string
161 */
162 public static function getUploadType($meta, &$payload, &$params) {
163 if (isset($params['mediaUpload'])
164 && get_class($params['mediaUpload']['value']) == 'Google_MediaFileUpload') {
165 $upload = $params['mediaUpload']['value'];
166 unset($params['mediaUpload']);
167 $payload['content-type'] = $upload->mimeType;
168 if (isset($upload->resumable) && $upload->resumable) {
169 return self::UPLOAD_RESUMABLE_TYPE;
170 }
171 }
172
173 // Allow the developer to override the upload type.
174 if (isset($params['uploadType'])) {
175 return $params['uploadType']['value'];
176 }
177
178 $data = isset($params['data']['value'])
179 ? $params['data']['value'] : false;
180
181 if (false == $data && false == isset($params['file'])) {
182 // No upload data available.
183 return false;
184 }
185
186 if (isset($params['file'])) {
187 return self::UPLOAD_MEDIA_TYPE;
188 }
189
190 if (false == $meta) {
191 return self::UPLOAD_MEDIA_TYPE;
192 }
193
194 return self::UPLOAD_MULTIPART_TYPE;
195 }
196
197
198 public function nextChunk(Google_HttpRequest $req) {
199 if (false == $this->resumeUri) {
200 $this->resumeUri = $this->getResumeUri($req);
201 }
202
203 $data = substr($this->data, $this->progress, $this->chunkSize);
204 $lastBytePos = $this->progress + strlen($data) - 1;
205 $headers = array(
206 'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
207 'content-type' => $req->getRequestHeader('content-type'),
208 'content-length' => $this->chunkSize,
209 'expect' => '',
210 );
211
212 $httpRequest = new Google_HttpRequest($this->resumeUri, 'PUT', $headers, $data);
213 $response = Google_Client::$io->authenticatedRequest($httpRequest);
214 $code = $response->getResponseHttpCode();
215 if (308 == $code) {
216 $range = explode('-', $response->getResponseHeader('range'));
217 $this->progress = $range[1] + 1;
218 return false;
219 } else {
220 return Google_REST::decodeHttpResponse($response);
221 }
222 }
223
224 private function getResumeUri(Google_HttpRequest $httpRequest) {
225 $result = null;
226 $body = $httpRequest->getPostBody();
227 if ($body) {
228 $httpRequest->setRequestHeaders(array(
229 'content-type' => 'application/json; charset=UTF-8',
230 'content-length' => Google_Utils::getStrLen($body),
231 'x-upload-content-type' => $this->mimeType,
232 'expect' => '',
233 ));
234 }
235
236 $response = Google_Client::$io->makeRequest($httpRequest);
237 $location = $response->getResponseHeader('location');
238 $code = $response->getResponseHttpCode();
239 if (200 == $code && true == $location) {
240 return $location;
241 }
242 throw new Google_Exception("Failed to start the resumable upload");
243 }
244 }
...\ No newline at end of file ...\ No newline at end of file
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 * This class defines attributes, valid values, and usage which is generated from
20 * a given json schema. http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
21 *
22 * @author Chirag Shah <chirags@google.com>
23 *
24 */
25 class Google_Model {
26 public function __construct( /* polymorphic */ ) {
27 if (func_num_args() == 1 && is_array(func_get_arg(0))) {
28 // Initialize the model with the array's contents.
29 $array = func_get_arg(0);
30 $this->mapTypes($array);
31 }
32 }
33
34 /**
35 * Initialize this object's properties from an array.
36 *
37 * @param array $array Used to seed this object's properties.
38 * @return void
39 */
40 protected function mapTypes($array) {
41 foreach ($array as $key => $val) {
42 $this->$key = $val;
43
44 $keyTypeName = "__$key" . 'Type';
45 $keyDataType = "__$key" . 'DataType';
46 if ($this->useObjects() && property_exists($this, $keyTypeName)) {
47 if ($this->isAssociativeArray($val)) {
48 if (isset($this->$keyDataType) && 'map' == $this->$keyDataType) {
49 foreach($val as $arrayKey => $arrayItem) {
50 $val[$arrayKey] = $this->createObjectFromName($keyTypeName, $arrayItem);
51 }
52 $this->$key = $val;
53 } else {
54 $this->$key = $this->createObjectFromName($keyTypeName, $val);
55 }
56 } else if (is_array($val)) {
57 $arrayObject = array();
58 foreach ($val as $arrayIndex => $arrayItem) {
59 $arrayObject[$arrayIndex] = $this->createObjectFromName($keyTypeName, $arrayItem);
60 }
61 $this->$key = $arrayObject;
62 }
63 }
64 }
65 }
66
67 /**
68 * Returns true only if the array is associative.
69 * @param array $array
70 * @return bool True if the array is associative.
71 */
72 protected function isAssociativeArray($array) {
73 if (!is_array($array)) {
74 return false;
75 }
76 $keys = array_keys($array);
77 foreach($keys as $key) {
78 if (is_string($key)) {
79 return true;
80 }
81 }
82 return false;
83 }
84
85 /**
86 * Given a variable name, discover its type.
87 *
88 * @param $name
89 * @param $item
90 * @return object The object from the item.
91 */
92 private function createObjectFromName($name, $item) {
93 $type = $this->$name;
94 return new $type($item);
95 }
96
97 protected function useObjects() {
98 global $apiConfig;
99 return (isset($apiConfig['use_objects']) && $apiConfig['use_objects']);
100 }
101
102 /**
103 * Verify if $obj is an array.
104 * @throws Google_Exception Thrown if $obj isn't an array.
105 * @param array $obj Items that should be validated.
106 * @param string $type Array items should be of this type.
107 * @param string $method Method expecting an array as an argument.
108 */
109 public function assertIsArray($obj, $type, $method) {
110 if ($obj && !is_array($obj)) {
111 throw new Google_Exception("Incorrect parameter type passed to $method(), expected an"
112 . " array containing items of type $type.");
113 }
114 }
115 }
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 class Google_Service {
19 public $version;
20 public $servicePath;
21 public $resource;
22 }
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 * Implements the actual methods/resources of the discovered Google API using magic function
20 * calling overloading (__call()), which on call will see if the method name (plus.activities.list)
21 * is available in this service, and if so construct an apiHttpRequest representing it.
22 *
23 * @author Chris Chabot <chabotc@google.com>
24 * @author Chirag Shah <chirags@google.com>
25 *
26 */
27 class Google_ServiceResource {
28 // Valid query parameters that work, but don't appear in discovery.
29 private $stackParameters = array(
30 'alt' => array('type' => 'string', 'location' => 'query'),
31 'boundary' => array('type' => 'string', 'location' => 'query'),
32 'fields' => array('type' => 'string', 'location' => 'query'),
33 'trace' => array('type' => 'string', 'location' => 'query'),
34 'userIp' => array('type' => 'string', 'location' => 'query'),
35 'userip' => array('type' => 'string', 'location' => 'query'),
36 'file' => array('type' => 'complex', 'location' => 'body'),
37 'data' => array('type' => 'string', 'location' => 'body'),
38 'mimeType' => array('type' => 'string', 'location' => 'header'),
39 'uploadType' => array('type' => 'string', 'location' => 'query'),
40 'mediaUpload' => array('type' => 'complex', 'location' => 'query'),
41 );
42
43 /** @var Google_Service $service */
44 private $service;
45
46 /** @var string $serviceName */
47 private $serviceName;
48
49 /** @var string $resourceName */
50 private $resourceName;
51
52 /** @var array $methods */
53 private $methods;
54
55 public function __construct($service, $serviceName, $resourceName, $resource) {
56 $this->service = $service;
57 $this->serviceName = $serviceName;
58 $this->resourceName = $resourceName;
59 $this->methods = isset($resource['methods']) ? $resource['methods'] : array($resourceName => $resource);
60 }
61
62 /**
63 * @param $name
64 * @param $arguments
65 * @return Google_HttpRequest|array
66 * @throws Google_Exception
67 */
68 public function __call($name, $arguments) {
69 if (! isset($this->methods[$name])) {
70 throw new Google_Exception("Unknown function: {$this->serviceName}->{$this->resourceName}->{$name}()");
71 }
72 $method = $this->methods[$name];
73 $parameters = $arguments[0];
74
75 // postBody is a special case since it's not defined in the discovery document as parameter, but we abuse the param entry for storing it
76 $postBody = null;
77 if (isset($parameters['postBody'])) {
78 if (is_object($parameters['postBody'])) {
79 $this->stripNull($parameters['postBody']);
80 }
81
82 // Some APIs require the postBody to be set under the data key.
83 if (is_array($parameters['postBody']) && 'latitude' == $this->serviceName) {
84 if (!isset($parameters['postBody']['data'])) {
85 $rawBody = $parameters['postBody'];
86 unset($parameters['postBody']);
87 $parameters['postBody']['data'] = $rawBody;
88 }
89 }
90
91 $postBody = is_array($parameters['postBody']) || is_object($parameters['postBody'])
92 ? json_encode($parameters['postBody'])
93 : $parameters['postBody'];
94 unset($parameters['postBody']);
95
96 if (isset($parameters['optParams'])) {
97 $optParams = $parameters['optParams'];
98 unset($parameters['optParams']);
99 $parameters = array_merge($parameters, $optParams);
100 }
101 }
102
103 if (!isset($method['parameters'])) {
104 $method['parameters'] = array();
105 }
106
107 $method['parameters'] = array_merge($method['parameters'], $this->stackParameters);
108 foreach ($parameters as $key => $val) {
109 if ($key != 'postBody' && ! isset($method['parameters'][$key])) {
110 throw new Google_Exception("($name) unknown parameter: '$key'");
111 }
112 }
113 if (isset($method['parameters'])) {
114 foreach ($method['parameters'] as $paramName => $paramSpec) {
115 if (isset($paramSpec['required']) && $paramSpec['required'] && ! isset($parameters[$paramName])) {
116 throw new Google_Exception("($name) missing required param: '$paramName'");
117 }
118 if (isset($parameters[$paramName])) {
119 $value = $parameters[$paramName];
120 $parameters[$paramName] = $paramSpec;
121 $parameters[$paramName]['value'] = $value;
122 unset($parameters[$paramName]['required']);
123 } else {
124 unset($parameters[$paramName]);
125 }
126 }
127 }
128
129 // Discovery v1.0 puts the canonical method id under the 'id' field.
130 if (! isset($method['id'])) {
131 $method['id'] = $method['rpcMethod'];
132 }
133
134 // Discovery v1.0 puts the canonical path under the 'path' field.
135 if (! isset($method['path'])) {
136 $method['path'] = $method['restPath'];
137 }
138
139 $servicePath = $this->service->servicePath;
140
141 // Process Media Request
142 $contentType = false;
143 if (isset($method['mediaUpload'])) {
144 $media = Google_MediaFileUpload::process($postBody, $parameters);
145 if ($media) {
146 $contentType = isset($media['content-type']) ? $media['content-type']: null;
147 $postBody = isset($media['postBody']) ? $media['postBody'] : null;
148 $servicePath = $method['mediaUpload']['protocols']['simple']['path'];
149 $method['path'] = '';
150 }
151 }
152
153 $url = Google_REST::createRequestUri($servicePath, $method['path'], $parameters);
154 $httpRequest = new Google_HttpRequest($url, $method['httpMethod'], null, $postBody);
155 if ($postBody) {
156 $contentTypeHeader = array();
157 if (isset($contentType) && $contentType) {
158 $contentTypeHeader['content-type'] = $contentType;
159 } else {
160 $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
161 $contentTypeHeader['content-length'] = Google_Utils::getStrLen($postBody);
162 }
163 $httpRequest->setRequestHeaders($contentTypeHeader);
164 }
165
166 $httpRequest = Google_Client::$auth->sign($httpRequest);
167 if (Google_Client::$useBatch) {
168 return $httpRequest;
169 }
170
171 // Terminate immediatly if this is a resumable request.
172 if (isset($parameters['uploadType']['value'])
173 && 'resumable' == $parameters['uploadType']['value']) {
174 return $httpRequest;
175 }
176
177 return Google_REST::execute($httpRequest);
178 }
179
180 public function useObjects() {
181 global $apiConfig;
182 return (isset($apiConfig['use_objects']) && $apiConfig['use_objects']);
183 }
184
185 protected function stripNull(&$o) {
186 $o = (array) $o;
187 foreach ($o as $k => $v) {
188 if ($v === null || strstr($k, "\0*\0__")) {
189 unset($o[$k]);
190 }
191 elseif (is_object($v) || is_array($v)) {
192 $this->stripNull($o[$k]);
193 }
194 }
195 }
196 }
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 * Collection of static utility methods used for convenience across
20 * the client library.
21 *
22 * @author Chirag Shah <chirags@google.com>
23 */
24 class Google_Utils {
25 public static function urlSafeB64Encode($data) {
26 $b64 = base64_encode($data);
27 $b64 = str_replace(array('+', '/', '\r', '\n', '='),
28 array('-', '_'),
29 $b64);
30 return $b64;
31 }
32
33 public static function urlSafeB64Decode($b64) {
34 $b64 = str_replace(array('-', '_'),
35 array('+', '/'),
36 $b64);
37 return base64_decode($b64);
38 }
39
40 /**
41 * Misc function used to count the number of bytes in a post body, in the world of multi-byte chars
42 * and the unpredictability of strlen/mb_strlen/sizeof, this is the only way to do that in a sane
43 * manner at the moment.
44 *
45 * This algorithm was originally developed for the
46 * Solar Framework by Paul M. Jones
47 *
48 * @link http://solarphp.com/
49 * @link http://svn.solarphp.com/core/trunk/Solar/Json.php
50 * @link http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Json/Decoder.php
51 * @param string $str
52 * @return int The number of bytes in a string.
53 */
54 static public function getStrLen($str) {
55 $strlenVar = strlen($str);
56 $d = $ret = 0;
57 for ($count = 0; $count < $strlenVar; ++ $count) {
58 $ordinalValue = ord($str{$ret});
59 switch (true) {
60 case (($ordinalValue >= 0x20) && ($ordinalValue <= 0x7F)):
61 // characters U-00000000 - U-0000007F (same as ASCII)
62 $ret ++;
63 break;
64
65 case (($ordinalValue & 0xE0) == 0xC0):
66 // characters U-00000080 - U-000007FF, mask 110XXXXX
67 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
68 $ret += 2;
69 break;
70
71 case (($ordinalValue & 0xF0) == 0xE0):
72 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
73 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
74 $ret += 3;
75 break;
76
77 case (($ordinalValue & 0xF8) == 0xF0):
78 // characters U-00010000 - U-001FFFFF, mask 11110XXX
79 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
80 $ret += 4;
81 break;
82
83 case (($ordinalValue & 0xFC) == 0xF8):
84 // characters U-00200000 - U-03FFFFFF, mask 111110XX
85 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
86 $ret += 5;
87 break;
88
89 case (($ordinalValue & 0xFE) == 0xFC):
90 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
91 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
92 $ret += 6;
93 break;
94 default:
95 $ret ++;
96 }
97 }
98 return $ret;
99 }
100
101 /**
102 * Normalize all keys in an array to lower-case.
103 * @param array $arr
104 * @return array Normalized array.
105 */
106 public static function normalize($arr) {
107 if (!is_array($arr)) {
108 return array();
109 }
110
111 $normalized = array();
112 foreach ($arr as $key => $val) {
113 $normalized[strtolower($key)] = $val;
114 }
115 return $normalized;
116 }
117 }
...\ No newline at end of file ...\ No newline at end of file