Advertisement
Guest User

Gmail Oauth with Zend

a guest
Feb 10th, 2011
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.23 KB | None | 0 0
  1. function newmail()
  2.     {
  3.         /**
  4.          * Copyright 2010 Google Inc.
  5.          *
  6.          * Licensed under the Apache License, Version 2.0 (the "License");
  7.          * you may not use this file except in compliance with the License.
  8.          * You may obtain a copy of the License at
  9.          *
  10.               * http://www.apache.org/licenses/LICENSE-2.0
  11.          *
  12.          * Unless required by applicable law or agreed to in writing, software
  13.          * distributed under the License is distributed on an "AS IS" BASIS,
  14.          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15.          * See the License for the specific language governing permissions and
  16.          * limitations under the License.
  17.          */
  18.        
  19.         session_start();
  20.        
  21.         // these need to be grabbed from database
  22.         $THREE_LEGGED_CONSUMER_KEY = 'www.mysite.com';
  23.         $THREE_LEGGED_SIGNATURE_METHOD = 'HMAC-SHA1';
  24.         $THREE_LEGGED_CONSUMER_SECRET_HMAC = 'mysecret';
  25.        
  26.         $THREE_LEGGED_SCOPES = array('https://mail.google.com/');
  27.        
  28.         ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries');
  29.        
  30.         require_once 'Zend/Oauth/Consumer.php';
  31.         require_once 'Zend/Crypt/Rsa/Key/Private.php';
  32.         require_once 'Zend/Mail/Protocol/Imap.php';
  33.         require_once 'Zend/Mail/Storage/Imap.php';
  34.        
  35.         /**
  36.          * If the e-mail address was just submitted via a
  37.          * form POST, set it in the session.  Else if we
  38.          * don't yet have an email address, prompt the user
  39.          * for their address.
  40.          */
  41.        
  42.         /**
  43.          * Setup OAuth
  44.          */
  45.         $options = array(
  46.             'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
  47.             'version' => '1.0',
  48.             'consumerKey' => $THREE_LEGGED_CONSUMER_KEY,
  49.             'callbackUrl' => current_url(),
  50.             'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
  51.             'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
  52.             'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken'
  53.         );
  54.        
  55.         if ($THREE_LEGGED_SIGNATURE_METHOD == 'RSA-SHA1') {
  56.             $options['signatureMethod'] = 'RSA-SHA1';
  57.             $options['consumerSecret'] = new Zend_Crypt_Rsa_Key_Private(
  58.                 file_get_contents(realpath($THREE_LEGGED_RSA_PRIVATE_KEY)));
  59.         } else {
  60.             $options['signatureMethod'] = 'HMAC-SHA1';
  61.             $options['consumerSecret'] = $THREE_LEGGED_CONSUMER_SECRET_HMAC;
  62.         }
  63.        
  64.         $consumer = new Zend_Oauth_Consumer($options);
  65.        
  66.         /**
  67.          * When using HMAC-SHA1, you need to persist the request token in some way.
  68.          * This is because you'll need the request token's token secret when upgrading
  69.          * to an access token later on. The example below saves the token object
  70.          * as a session variable.
  71.          */
  72.         if (!isset($_SESSION['ACCESS_TOKEN'])) {
  73.           if (!isset($_SESSION['REQUEST_TOKEN'])) {
  74.             // Get Request Token and redirect to Google
  75.             $_SESSION['REQUEST_TOKEN'] = serialize($consumer->getRequestToken(array('scope' => implode(' ', $THREE_LEGGED_SCOPES))));
  76.             $consumer->redirect();
  77.           } else {
  78.             echo 'have access token';
  79.             // Have Request Token already, Get Access Token
  80.             $_SESSION['ACCESS_TOKEN'] = serialize($consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN'])));
  81.             header('Location: ' . getCurrentUrl(false));
  82.             exit;
  83.           }
  84.         } else {
  85.           // Retrieve mail using Access Token
  86.           $accessToken = unserialize($_SESSION['ACCESS_TOKEN']);
  87.           $config = new Zend_Oauth_Config();
  88.           $config->setOptions($options);
  89.           $config->setToken($accessToken);
  90.           $config->setRequestMethod('GET');
  91.           $url = 'https://mail.google.com/mail/b/' .
  92.                $email_address .
  93.                '/imap/';
  94.        
  95.           $httpUtility = new Zend_Oauth_Http_Utility();
  96.          
  97.           /**
  98.            * Get an unsorted array of oauth params,
  99.            * including the signature based off those params.
  100.            */
  101.           $params = $httpUtility->assembleParams(
  102.               $url,
  103.               $config);
  104.          
  105.           /**
  106.            * Sort parameters based on their names, as required
  107.            * by OAuth.
  108.            */
  109.           ksort($params);
  110.          
  111.           /**
  112.            * Construct a comma-deliminated,ordered,quoted list of
  113.            * OAuth params as required by XOAUTH.
  114.            *
  115.            * Example: oauth_param1="foo",oauth_param2="bar"
  116.            */
  117.           $first = true;
  118.           $oauthParams = '';
  119.           foreach ($params as $key => $value) {
  120.             // only include standard oauth params
  121.             if (strpos($key, 'oauth_') === 0) {
  122.               if (!$first) {
  123.                 $oauthParams .= ',';
  124.               }
  125.               $oauthParams .= $key . '="' . urlencode($value) . '"';
  126.               $first = false;
  127.             }
  128.           }
  129.          
  130.           /**
  131.            * Generate SASL client request, using base64 encoded
  132.            * OAuth params
  133.            */
  134.           $initClientRequest = 'GET ' . $url . ' ' . $oauthParams;
  135.           $initClientRequestEncoded = base64_encode($initClientRequest);
  136.          
  137.           /**
  138.            * Make the IMAP connection and send the auth request
  139.            */
  140.           $imap = new Zend_Mail_Protocol_Imap('imap.gmail.com', '993', true);
  141.           $authenticateParams = array('XOAUTH', $initClientRequestEncoded);
  142.           $imap->requestAndResponse('AUTHENTICATE', $authenticateParams);
  143.          
  144.           /**
  145.            * Print the INBOX message count and the subject of all messages
  146.            * in the INBOX
  147.            */
  148.           $storage = new Zend_Mail_Storage_Imap($imap);
  149.          
  150.           $data = array(
  151.                 'imap'  => $storage
  152.             );
  153.  
  154.             $this->load->view('main',$data);
  155.         }
  156.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement