PageRenderTime 32ms CodeModel.GetById 18ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/common/libraries/plugin/pear/OAuth/Request.php

https://bitbucket.org/chamilo/chamilo/
PHP | 341 lines | 123 code | 33 blank | 185 comment | 15 complexity | da3d98736ae90e29be82654c686ff985 MD5 | raw file
  1<?php
  2/**
  3 * OAuth Request
  4 * 
  5 * Adapted from Andy Smith's OAuth library for PHP
  6 * 
  7 * @link http://oauth.net/core/1.0
  8 * @link http://oauth.googlecode.com/svn/spec/ext/consumer_request/1.0/drafts/1/spec.html
  9 * @link http://oauth.googlecode.com/svn/code/php/
 10 * @link http://term.ie/oauth/example/
 11 * 
 12 * @package OAuth
 13 * 
 14 * @author jhart
 15 * @copyright Copyright (c) 2008, Photobucket, Inc.
 16 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
 17 */
 18
 19/**
 20 * Utilities
 21 */
 22require_once('OAuth/Utils.php');
 23/**
 24 * Signing methods
 25 */
 26require_once('OAuth/Signature.php');
 27/**
 28 * Consumer Model
 29 */
 30require_once('OAuth/Consumer.php');
 31/**
 32 * Token Model
 33 */
 34require_once('OAuth/Token.php');
 35
 36/**
 37 * OAuth Request Representation
 38 * 
 39 * @package OAuth
 40 */
 41class OAuth_Request {
 42    
 43    /**
 44     * holds all parameters for request
 45     *
 46     * @access protected
 47     * @var array
 48     */
 49    protected $parameters = array();
 50    /**
 51     * Holds HTTP method (normalized, strtoupper)
 52     *
 53     * @var string
 54     */
 55    protected $http_method = '';
 56    /**
 57     * Holds url (normalized, per function)
 58     *
 59     * @var string
 60     */
 61    protected $http_url = '';
 62
 63    /**
 64     * generated base string for this request (debugging)
 65     *
 66     * @var string
 67     */
 68    public $base_string = '';
 69    /**
 70     * generated key string for this request (debugging)
 71     *
 72     * @var string
 73     */
 74    public $key_string = '';
 75    
 76    /**
 77     * Allowed version that we support with this library
 78     *
 79     * @var string
 80     */
 81    public static $version = '1.0';
 82
 83    /**
 84     * Request Constructor
 85     *
 86     * @uses getNormalizedHttpUrl()
 87     * @param string $http_method http method
 88     * @param string $http_url url
 89     * @param array $parameters array of parameters
 90     */
 91    public function __construct($http_method, $http_url, $parameters = null) {
 92        @$parameters or $parameters = array();
 93        $this->parameters = $parameters;
 94        $this->http_method = strtoupper($http_method);
 95        $this->http_url = self::getNormalizedHttpUrl($http_url);
 96    }
 97
 98    /**
 99     * build up a request from what was passed to the server
100     * 
101     * @param string $http_method [optional, default=_SERVER[HTTP_METHOD]] HTTP method (get|put|post|delete)
102     * @param string $http_url [optional, default=http://_SERVER[HTTP_HOST]._SERVER[REQUEST_URI]] request url to sign
103     * @param array $parameters [optional, default=_REQUEST] parameters to sign
104     * @return self
105     */ 
106    public static function fromRequest($http_method=null, $http_url=null, $parameters=null) {
107        @$http_url or $http_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
108        @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
109
110        if ($parameters) {
111            $req = new self($http_method, $http_url, $parameters);
112        } else {
113            $parameters = array_diff_assoc($_REQUEST, $_COOKIE);
114            
115            $request_headers = apache_request_headers();
116            if (array_key_exists('Authorization', $request_headers) && substr($request_headers['Authorization'], 0, 5) == 'OAuth') {
117                $header_parameters = self::splitHeader($request_headers['Authorization']);
118                $parameters = array_merge($header_parameters, $parameters);
119            }
120     
121            $req = new self($http_method, $http_url, $parameters);
122        }
123        return $req;
124    }
125    
126    /**
127     * build up a request form just a URL+querystring
128     *
129     * @param string $url a whole url, querystring included.
130     * @param string $http_method [optional, default=GET] http method
131     * @param OAuth_Consumer $consumer [optional] consumer to sign with
132     * @param OAuth_Token $token [optional] token to sign with
133     * @return self
134     */
135    public static function fromUrl($url, $http_method = 'GET', $consumer = null, $token = null) {
136        $parts = parse_url($url);
137        $qs = array();
138        parse_str($parts['query'], $qs);
139        if (!$consumer) {
140            return self::fromRequest($http_method, $url, $qs);
141        } else {
142            return self::fromConsumerAndToken($consumer, $token, $http_method, $url, $qs);
143        }
144    }
145
146    /**
147     * Create request from consumer and token as well (for a new request)
148     *
149     * @param OAuth_Consumer $consumer consumer
150     * @param OAuth_Token $token token
151     * @param string $http_method method
152     * @param string $http_url url
153     * @param array $parameters parameters
154     * @return self
155     */
156    public static function fromConsumerAndToken(OAuth_Consumer $consumer, $token, $http_method, $http_url, $parameters) {
157        @$parameters or $parameters = array();
158        $defaults = array('oauth_version' => self::$version,
159                          'oauth_nonce' => self::getNonce(),
160                          'oauth_timestamp' => self::getTimestamp(),
161                          'oauth_consumer_key' => $consumer->getKey());
162        $parameters = array_merge($defaults, $parameters);
163        
164        if ($token) {
165            $parameters['oauth_token'] = $token->getKey();
166        }
167        return new self($http_method, $http_url, $parameters);
168    }
169
170    /**
171     * set a parameter
172     *
173     * @param string $name
174     * @param string $value
175     */
176    public function setParameter($name, $value) {
177        $this->parameters[$name] = $value;
178    }
179    
180    /**
181     * get a parameter
182     *
183     * @param string $name
184     * @return string
185     */
186    public function getParameter($name) {
187        if (!array_key_exists($name, $this->parameters)) return null;
188        return $this->parameters[$name];
189    }
190    
191    /**
192     * Get parameters array
193     *
194     * @return array of key=>value
195     */
196    public function getParameters() {
197        return $this->parameters;
198    }
199    
200    /**
201     * normalize input url
202     *
203     * @param string $url url to normalize
204     * @return string normalized url
205     */
206    public static function getNormalizedHttpUrl($url) {
207        $parts = parse_url($url);
208        $port = '';
209        if (array_key_exists('port', $parts) && $parts['port'] != '80') {
210            $port = ':' . $parts['port'];
211        }
212        return $parts['scheme'] . '://' . $parts['host'] . $port . '/' . trim($parts['path'], '/'); 
213    }
214
215    /**
216     * get HTTP url in this request (normalized)
217     *
218     * @return string
219     */
220    public function getHttpUrl() {
221        return $this->http_url;
222    }
223    
224    /**
225     * get HTTP method in this request (normalized)
226     *
227     * @return unknown
228     */
229    public function getHttpMethod() {
230        return $this->http_method;
231    }
232    
233    /**
234     * Build whole url for request
235     *
236     * @uses toPostdata()
237     * @uses getHttpUrl()
238     * @return string http://httpurl?parameters
239     */
240    public function toUrl() {
241        $out = $this->getHttpUrl() . '?';
242        $out .= $this->toPostdata();
243        return $out;
244    }
245
246    /**
247     * build querystring for post or get
248     *
249     * @return string param=value&param=value...
250     */
251    public function toPostdata() {
252        return OAuth_Utils::normalizeKeyValueParameters($this->getParameters());
253    }
254
255    /**
256     * Builds Authorization: header for request
257     *
258     * @return string Authorization: OAuth ...
259     */
260    public function toHeader() {
261        $out = '"Authorization: OAuth realm="",';
262        return $out . OAuth_Utils::normalizeKeyValueParameters($this->getParameters(), ',');
263    }
264    
265    /**
266     * gets url
267     *
268     * @uses toUrl()
269     * @return string
270     */
271    public function __toString() {
272        return $this->toUrl();
273    }
274
275    /**
276     * Signs this request - adds parameters for signature method and the signed signature
277     *
278     * @param string $signature_method signing method identifier
279     * @param OAuth_Consumer $consumer to sign against
280     * @param OAuth_Token $token to sign against
281     */
282    public function signRequest($signature_method, OAuth_Consumer $consumer, $token = null) {
283        if (!($method = OAuth_Signature::getSignatureMethod($signature_method))) return false;
284        
285        $this->setParameter('oauth_signature_method', $method->getMethodName());
286        $consumer_secret = $consumer->getSecret();
287        $token_secret = ($token) ? $token->getSecret() : '';
288        
289        $signature = $method->signRequest($this, $consumer_secret, $token_secret);
290        $this->setParameter('oauth_signature', $signature);
291    }
292
293    /**
294     * Get current timestamp
295     *
296     * @return int
297     */
298    public static function getTimestamp() {
299        //return 1191242096; //example from spec
300        return time();
301    }
302
303    /**
304     * get current nonce
305     *
306     * @return string
307     */
308    public static function getNonce() {
309        //return 'kllo9940pd9333jh'; //example from spec
310        $mt = microtime();
311        $rand = mt_rand();
312        
313        return md5($mt . $rand); // md5s look nicer than numbers
314    }
315
316    /**
317    * util function for turning the Authorization: header into
318    * parameters, has to do some unescaping
319    * 
320    * @param string $header string to split up
321    * @return array array of oauth params
322    */
323    public static function splitHeader($header) {
324        // error cases: commas in parameter values
325        $parts = explode(',', $header);
326        $out = array();
327        foreach ($parts as $param) {
328            $param = trim($param);
329            // skip the 'realm' param, nobody ever uses it anyway
330            if (substr($param, 0, 5) != 'oauth') continue;
331            
332            $param_parts = explode('=', $param);
333            
334            // rawurldecode() used because urldecode() will turn a '+' in the
335            // value into a space
336            $out[OAuth_Utils::urldecodeRFC3986($param_parts[0])] = OAuth_Utils::urldecodeRFC3986_UTF8($param_parts[1]);
337        }
338        return $out;
339    }
340    
341}