PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/gmailoauthexample/oauth/gmailoauth.php

http://github.com/petewarden/handmadeimap
PHP | 174 lines | 99 code | 23 blank | 52 comment | 10 complexity | 2a3a284debb55fd0f2f0e32cf9daaa48 MD5 | raw file
  1. <?php
  2. /*
  3. * A class handling the IMAP verification procedure for Gmail
  4. *
  5. * Based on the Twitter version by Abraham Williams (abraham@abrah.am) http://abrah.am
  6. *
  7. */
  8. /* Load OAuth lib. You can find it at http://oauth.net */
  9. require_once('oauth.php');
  10. class GmailOAuth {
  11. // Contains the last HTTP status code returned
  12. private $http_status;
  13. // Contains the last API call
  14. private $last_api_call;
  15. // The base of the Gmail OAuth URLs
  16. public static $GMAIL_API_PREFIX = 'https://mail.google.com/mail/b/';
  17. public static $GMAIL_API_SUFFIX = '/imap/';
  18. public $GMAIL_API_ROOT = 'https://www.google.com/accounts/';
  19. public $request_options = array(
  20. 'scope' => 'https://mail.google.com/',
  21. );
  22. /**
  23. * Set API URLS
  24. */
  25. function requestTokenURL() { return $this->GMAIL_API_ROOT.'OAuthGetRequestToken'; }
  26. function authorizeURL() { return $this->GMAIL_API_ROOT.'OAuthAuthorizeToken'; }
  27. function accessTokenURL() { return $this->GMAIL_API_ROOT.'OAuthGetAccessToken'; }
  28. /**
  29. * Debug helpers
  30. */
  31. function lastStatusCode() { return $this->http_status; }
  32. function lastAPICall() { return $this->last_api_call; }
  33. function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {/*{{{*/
  34. $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
  35. $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
  36. if (!empty($oauth_token) && !empty($oauth_token_secret)) {
  37. $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
  38. } else {
  39. $this->token = NULL;
  40. }
  41. }/*}}}*/
  42. /**
  43. * Get a request_token from Gmail
  44. *
  45. * @returns a key/value array containing oauth_token and oauth_token_secret
  46. */
  47. function getRequestToken() {/*{{{*/
  48. $requesturl = $this->requestTokenURL();
  49. $r = $this->oAuthRequest($requesturl, $this->request_options, 'GET');
  50. error_log('OAuth request: '.$requesturl);
  51. error_log('OAuth Response: '.print_r($r, true));
  52. $token = $this->oAuthParseResponse($r);
  53. $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
  54. return $token;
  55. }/*}}}*/
  56. /**
  57. * Parse a URL-encoded OAuth response
  58. *
  59. * @return a key/value array
  60. */
  61. function oAuthParseResponse($responseString) {
  62. $r = array();
  63. foreach (explode('&', $responseString) as $param) {
  64. $pair = explode('=', $param, 2);
  65. if (count($pair) != 2) continue;
  66. $r[urldecode($pair[0])] = urldecode($pair[1]);
  67. }
  68. return $r;
  69. }
  70. /**
  71. * Get the authorize URL
  72. *
  73. * @returns a string
  74. */
  75. function getAuthorizeURL($token, $callbackurl) {/*{{{*/
  76. if (is_array($token)) $token = $token['oauth_token'];
  77. $result = $this->authorizeURL();
  78. $result .= '?oauth_token=' . $token;
  79. $result .= '&oauth_callback=' . urlencode($callbackurl);
  80. return $result;
  81. }/*}}}*/
  82. /**
  83. * Exchange the request token and secret for an access token and
  84. * secret, to sign API calls.
  85. *
  86. * @returns array("oauth_token" => the access token,
  87. * "oauth_token_secret" => the access secret)
  88. */
  89. function getAccessToken($token = NULL) {/*{{{*/
  90. $r = $this->oAuthRequest($this->accessTokenURL());
  91. $token = $this->oAuthParseResponse($r);
  92. $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
  93. return $token;
  94. }/*}}}*/
  95. /**
  96. * Format and sign an OAuth / API request
  97. */
  98. function oAuthRequest($url, $args = array(), $method = NULL) {/*{{{*/
  99. if (empty($method)) $method = empty($args) ? "GET" : "POST";
  100. $req = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $args);
  101. $req->sign_request($this->sha1_method, $this->consumer, $this->token);
  102. switch ($method) {
  103. case 'GET': return $this->http($req->to_url());
  104. case 'POST': return $this->http($req->get_normalized_http_url(), $req->to_postdata());
  105. }
  106. }/*}}}*/
  107. /**
  108. * Get the base64 string to pass in to the IMAP authentication method
  109. */
  110. function getLoginString($email) {/*{{{*/
  111. $method = 'GET';
  112. $url = 'https://mail.google.com/mail/b/'.$email.'/imap/';
  113. $args = array();
  114. $req = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $args);
  115. $req->sign_request($this->sha1_method, $this->consumer, $this->token);
  116. $requesturl = $req->to_url();
  117. $requestparts = explode('?', $requesturl);
  118. $oauthparamslist = explode('&', $requestparts[1]);
  119. $oauthparamsstring = implode(',', $oauthparamslist);
  120. $clientrequest = 'GET '.$url.' '.$oauthparamsstring;
  121. $result = base64_encode($clientrequest);
  122. return $result;
  123. }/*}}}*/
  124. /**
  125. * Make an HTTP request
  126. *
  127. * @return API results
  128. */
  129. function http($url, $post_data = null) {/*{{{*/
  130. $ch = curl_init();
  131. if (defined("CURL_CA_BUNDLE_PATH")) curl_setopt($ch, CURLOPT_CAINFO, CURL_CA_BUNDLE_PATH);
  132. curl_setopt($ch, CURLOPT_URL, $url);
  133. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  134. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  135. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  136. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
  137. //////////////////////////////////////////////////
  138. ///// Set to 1 to verify Twitter's SSL Cert //////
  139. //////////////////////////////////////////////////
  140. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  141. if (isset($post_data)) {
  142. curl_setopt($ch, CURLOPT_POST, 1);
  143. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  144. }
  145. $response = curl_exec($ch);
  146. $this->http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  147. $this->last_api_call = $url;
  148. curl_close ($ch);
  149. return $response;
  150. }/*}}}*/
  151. }/*}}}*/