Advertisement
virushsality

OAuth.php

Jul 3rd, 2015
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.30 KB | None | 0 0
  1. <?php
  2. class TwitterAPIExchange
  3. {
  4.     /**
  5.      * @var string
  6.      */
  7.     private $oauth_access_token;
  8.  
  9.     /**
  10.      * @var string
  11.      */
  12.     private $oauth_access_token_secret;
  13.  
  14.     /**
  15.      * @var string
  16.      */
  17.     private $consumer_key;
  18.  
  19.     /**
  20.      * @var string
  21.      */
  22.     private $consumer_secret;
  23.  
  24.     /**
  25.      * @var array
  26.      */
  27.     private $postfields;
  28.  
  29.     /**
  30.      * @var string
  31.      */
  32.     private $getfield;
  33.  
  34.     /**
  35.      * @var mixed
  36.      */
  37.     protected $oauth;
  38.  
  39.     /**
  40.      * @var string
  41.      */
  42.     public $url;
  43.  
  44.     /**
  45.      * @var string
  46.      */
  47.     public $requestMethod;
  48.  
  49.     /**
  50.      * Create the API access object. Requires an array of settings::
  51.      * oauth access token, oauth access token secret, consumer key, consumer secret
  52.      * These are all available by creating your own application on dev.twitter.com
  53.      * Requires the cURL library
  54.      *
  55.      * @throws \Exception When cURL isn't installed or incorrect settings parameters are provided
  56.      *
  57.      * @param array $settings
  58.      */
  59.     public function __construct(array $settings)
  60.     {
  61.         if (!in_array('curl', get_loaded_extensions()))
  62.         {
  63.             throw new Exception('You need to install cURL, see: http://curl.haxx.se/docs/install.html');
  64.         }
  65.        
  66.         if (!isset($settings['oauth_access_token'])
  67.             || !isset($settings['oauth_access_token_secret'])
  68.             || !isset($settings['consumer_key'])
  69.             || !isset($settings['consumer_secret']))
  70.         {
  71.             throw new Exception('Make sure you are passing in the correct parameters');
  72.         }
  73.  
  74.         $this->oauth_access_token = $settings['oauth_access_token'];
  75.         $this->oauth_access_token_secret = $settings['oauth_access_token_secret'];
  76.         $this->consumer_key = $settings['consumer_key'];
  77.         $this->consumer_secret = $settings['consumer_secret'];
  78.     }
  79.  
  80.     /**
  81.      * Set postfields array, example: array('screen_name' => 'J7mbo')
  82.      *
  83.      * @param array $array Array of parameters to send to API
  84.      *
  85.      * @throws \Exception When you are trying to set both get and post fields
  86.      *
  87.      * @return TwitterAPIExchange Instance of self for method chaining
  88.      */
  89.     public function setPostfields(array $array)
  90.     {
  91.         if (!is_null($this->getGetfield()))
  92.         {
  93.             throw new Exception('You can only choose get OR post fields.');
  94.         }
  95.        
  96.         if (isset($array['status']) && substr($array['status'], 0, 1) === '@')
  97.         {
  98.             $array['status'] = sprintf("\0%s", $array['status']);
  99.         }
  100.        
  101.         $this->postfields = $array;
  102.        
  103.         // rebuild oAuth
  104.         if (isset($this->oauth['oauth_signature'])) {
  105.             $this->buildOauth($this->url, $this->requestMethod);
  106.         }
  107.  
  108.         return $this;
  109.     }
  110.    
  111.     /**
  112.      * Set getfield string, example: '?screen_name=J7mbo'
  113.      *
  114.      * @param string $string Get key and value pairs as string
  115.      *
  116.      * @throws \Exception
  117.      *
  118.      * @return \TwitterAPIExchange Instance of self for method chaining
  119.      */
  120.     public function setGetfield($string)
  121.     {
  122.         if (!is_null($this->getPostfields()))
  123.         {
  124.             throw new Exception('You can only choose get OR post fields.');
  125.         }
  126.        
  127.         $getfields = preg_replace('/^\?/', '', explode('&', $string));
  128.         $params = array();
  129.  
  130.         foreach ($getfields as $field)
  131.         {
  132.             if ($field !== '')
  133.             {
  134.                 list($key, $value) = explode('=', $field);
  135.                 $params[$key] = $value;
  136.             }
  137.         }
  138.  
  139.         $this->getfield = '?' . http_build_query($params);
  140.        
  141.         return $this;
  142.     }
  143.    
  144.     /**
  145.      * Get getfield string (simple getter)
  146.      *
  147.      * @return string $this->getfields
  148.      */
  149.     public function getGetfield()
  150.     {
  151.         return $this->getfield;
  152.     }
  153.    
  154.     /**
  155.      * Get postfields array (simple getter)
  156.      *
  157.      * @return array $this->postfields
  158.      */
  159.     public function getPostfields()
  160.     {
  161.         return $this->postfields;
  162.     }
  163.    
  164.     /**
  165.      * Build the Oauth object using params set in construct and additionals
  166.      * passed to this method. For v1.1, see: https://dev.twitter.com/docs/api/1.1
  167.      *
  168.      * @param string $url           The API url to use. Example: https://api.twitter.com/1.1/search/tweets.json
  169.      * @param string $requestMethod Either POST or GET
  170.      *
  171.      * @throws \Exception
  172.      *
  173.      * @return \TwitterAPIExchange Instance of self for method chaining
  174.      */
  175.     public function buildOauth($url, $requestMethod)
  176.     {
  177.         if (!in_array(strtolower($requestMethod), array('post', 'get')))
  178.         {
  179.             throw new Exception('Request method must be either POST or GET');
  180.         }
  181.        
  182.         $consumer_key              = $this->consumer_key;
  183.         $consumer_secret           = $this->consumer_secret;
  184.         $oauth_access_token        = $this->oauth_access_token;
  185.         $oauth_access_token_secret = $this->oauth_access_token_secret;
  186.        
  187.         $oauth = array(
  188.             'oauth_consumer_key' => $consumer_key,
  189.             'oauth_nonce' => time(),
  190.             'oauth_signature_method' => 'HMAC-SHA1',
  191.             'oauth_token' => $oauth_access_token,
  192.             'oauth_timestamp' => time(),
  193.             'oauth_version' => '1.0'
  194.         );
  195.        
  196.         $getfield = $this->getGetfield();
  197.        
  198.         if (!is_null($getfield))
  199.         {
  200.             $getfields = str_replace('?', '', explode('&', $getfield));
  201.  
  202.             foreach ($getfields as $g)
  203.             {
  204.                 $split = explode('=', $g);
  205.  
  206.                 /** In case a null is passed through **/
  207.                 if (isset($split[1]))
  208.                 {
  209.                     $oauth[$split[0]] = urldecode($split[1]);
  210.                 }
  211.             }
  212.         }
  213.        
  214.         $postfields = $this->getPostfields();
  215.  
  216.         if (!is_null($postfields)) {
  217.             foreach ($postfields as $key => $value) {
  218.                 $oauth[$key] = $value;
  219.             }
  220.         }
  221.  
  222.         $base_info = $this->buildBaseString($url, $requestMethod, $oauth);
  223.         $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
  224.         $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
  225.         $oauth['oauth_signature'] = $oauth_signature;
  226.        
  227.         $this->url = $url;
  228.         $this->requestMethod = $requestMethod;
  229.         $this->oauth = $oauth;
  230.        
  231.         return $this;
  232.     }
  233.    
  234.     /**
  235.      * Perform the actual data retrieval from the API
  236.      *
  237.      * @param boolean $return      If true, returns data. This is left in for backward compatibility reasons
  238.      * @param array   $curlOptions Additional Curl options for this request
  239.      *
  240.      * @throws \Exception
  241.      *
  242.      * @return string json If $return param is true, returns json data.
  243.      */
  244.     public function performRequest($return = true, $curlOptions = array())
  245.     {
  246.         if (!is_bool($return))
  247.         {
  248.             throw new Exception('performRequest parameter must be true or false');
  249.         }
  250.  
  251.         $header =  array($this->buildAuthorizationHeader($this->oauth), 'Expect:');
  252.  
  253.         $getfield = $this->getGetfield();
  254.         $postfields = $this->getPostfields();
  255.  
  256.         $options = array(
  257.             CURLOPT_HTTPHEADER => $header,
  258.             CURLOPT_HEADER => false,
  259.             CURLOPT_URL => $this->url,
  260.             CURLOPT_RETURNTRANSFER => true,
  261.             CURLOPT_TIMEOUT => 10,
  262.         ) + $curlOptions;
  263.  
  264.         if (!is_null($postfields))
  265.         {
  266.             $options[CURLOPT_POSTFIELDS] = http_build_query($postfields);
  267.         }
  268.         else
  269.         {
  270.             if ($getfield !== '')
  271.             {
  272.                 $options[CURLOPT_URL] .= $getfield;
  273.             }
  274.         }
  275.  
  276.         $feed = curl_init();
  277.         curl_setopt_array($feed, $options);
  278.         $json = curl_exec($feed);
  279.  
  280.         if (($error = curl_error($feed)) !== '')
  281.         {
  282.             curl_close($feed);
  283.  
  284.             throw new \Exception($error);
  285.         }
  286.  
  287.         curl_close($feed);
  288.  
  289.         return $json;
  290.     }
  291.    
  292.     /**
  293.      * Private method to generate the base string used by cURL
  294.      *
  295.      * @param string $baseURI
  296.      * @param string $method
  297.      * @param array  $params
  298.      *
  299.      * @return string Built base string
  300.      */
  301.     private function buildBaseString($baseURI, $method, $params)
  302.     {
  303.         $return = array();
  304.         ksort($params);
  305.        
  306.         foreach($params as $key => $value)
  307.         {
  308.             $return[] = rawurlencode($key) . '=' . rawurlencode($value);
  309.         }
  310.        
  311.         return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $return));
  312.     }
  313.    
  314.     /**
  315.      * Private method to generate authorization header used by cURL
  316.      *
  317.      * @param array $oauth Array of oauth data generated by buildOauth()
  318.      *
  319.      * @return string $return Header used by cURL for request
  320.      */    
  321.     private function buildAuthorizationHeader(array $oauth)
  322.     {
  323.         $return = 'Authorization: OAuth ';
  324.         $values = array();
  325.        
  326.         foreach($oauth as $key => $value)
  327.         {
  328.             if (in_array($key, array('oauth_consumer_key', 'oauth_nonce', 'oauth_signature',
  329.                 'oauth_signature_method', 'oauth_timestamp', 'oauth_token', 'oauth_version'))) {
  330.                 $values[] = "$key=\"" . rawurlencode($value) . "\"";
  331.             }
  332.         }
  333.        
  334.         $return .= implode(', ', $values);
  335.         return $return;
  336.     }
  337.  
  338.     /**
  339.      * Helper method to perform our request
  340.      *
  341.      * @param string $url
  342.      * @param string $method
  343.      * @param string $data
  344.      * @param array  $curlOptions
  345.      *
  346.      * @throws \Exception
  347.      *
  348.      * @return string The json response from the server
  349.      */
  350.     public function request($url, $method = 'get', $data = null, $curlOptions = array())
  351.     {
  352.         if (strtolower($method) === 'get')
  353.         {
  354.             $this->setGetfield($data);
  355.         }
  356.         else
  357.         {
  358.             $this->setPostfields($data);
  359.         }
  360.  
  361.         return $this->buildOauth($url, $method)->performRequest(true, $curlOptions);
  362.     }
  363. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement