]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - Zend/Oauth/Provider.php
Release 6.5.0
[Github/sugarcrm.git] / Zend / Oauth / Provider.php
1 <?php
2 require_once 'Zend/Oauth/Exception.php';
3 require_once 'Zend/Oauth/Http/Utility.php';
4 require_once 'Zend/Uri/Http.php';
5
6 /**
7  *
8  * Basic OAuth provider class
9  */
10 class Zend_Oauth_Provider
11 {
12     /**
13      * OAuth result statuses
14      */
15     const OK = 0;
16     const BAD_NONCE = 1;
17     const BAD_TIMESTAMP = 2;
18     const CONSUMER_KEY_UNKNOWN = 3;
19     const CONSUMER_KEY_REFUSED = 4;
20     const INVALID_SIGNATURE = 5;
21     const TOKEN_USED = 6;
22     const TOKEN_EXPIRED = 7;
23     const TOKEN_REVOKED = 8;
24     const TOKEN_REJECTED = 9;
25     const PARAMETER_ABSENT = 10;
26     const SIGNATURE_METHOD_REJECTED = 11;
27     const OAUTH_VERIFIER_INVALID = 12;
28
29     /**
30      * Error names for error reporting
31      * @var array
32      */
33     protected $errnames = array(
34      self::BAD_NONCE => "nonce_used",
35      self::BAD_TIMESTAMP => "timestamp_refused",
36      self::CONSUMER_KEY_UNKNOWN => "consumer_key_unknown",
37      self::CONSUMER_KEY_REFUSED => "consumer_key_refused",
38      self::INVALID_SIGNATURE => "signature_invalid",
39      self::TOKEN_USED => "token_used",
40      self::TOKEN_EXPIRED => "token_expired",
41      self::TOKEN_REVOKED => "token_revoked",
42      self::TOKEN_REJECTED => "token_rejected",
43      self::PARAMETER_ABSENT => "parameter_absent",
44      self::SIGNATURE_METHOD_REJECTED => "signature_method_rejected",
45      self::OAUTH_VERIFIER_INVALID => "verifier_invalid",
46      );
47
48     public $token;
49     public $token_secret;
50     public $consumer_key;
51     public $consumer_secret;
52     public $verifier;
53
54     protected $problem;
55
56     protected $tokenHandler;
57     protected $consumerHandler;
58     protected $nonceHandler;
59     protected $oauth_params;
60
61     protected $requestPath;
62     /**
63      * Current URL
64      * @var Zend_Uri_Http
65      */
66     protected $url;
67     /**
68      *
69      * Required OAuth parameters
70      * @var array
71      */
72     protected $required = array("oauth_consumer_key", "oauth_signature", "oauth_signature_method", "oauth_nonce", "oauth_timestamp");
73
74     /**
75      * Set consumer key handler
76      * @param string $callback
77          * @return Zend_Oauth_Provider
78      */
79     public function setConsumerHandler($callback)
80     {
81         $this->consumerHandler = $callback;
82         return $this;
83     }
84
85     /**
86      * Set nonce/ts handler
87      * @param string $callback
88          * @return Zend_Oauth_Provider
89      */
90     public function setTimestampNonceHandler($callback)
91     {
92         $this->nonceHandler = $callback;
93         return $this;
94     }
95
96     /**
97      * Set token handler
98      * @param string $callback
99          * @return Zend_Oauth_Provider
100      */
101     public function setTokenHandler($callback)
102     {
103         $this->tokenHandler = $callback;
104         return $this;
105     }
106
107     /**
108      * Set URL for requesting token (doesn't need token)
109      * @param string $req_path
110          * @return Zend_Oauth_Provider
111      */
112     public function setRequestTokenPath($req_path)
113         {
114             $this->requestPath = $req_path;
115             return $this;
116         }
117
118         /**
119          * Set this request as token endpoint
120          * @param string $request
121          * @return Zend_Oauth_Provider
122          */
123         public function isRequestTokenEndpoint($request)
124         {
125             $this->is_request = $request;
126             return $this;
127         }
128
129     /**
130      * Report problem in OAuth as string
131      * @param Zend_Oauth_Exception $e
132      * @return string
133      */
134         public function reportProblem(Zend_Oauth_Exception $e)
135         {
136             $code = $e->getCode();
137             if($code == self::PARAMETER_ABSENT) {
138                 return "oauth_problem=parameter_absent&oauth_parameters_absent={$this->problem}";
139             }
140             if($code == self::INVALID_SIGNATURE) {
141                 return "oauth_problem=signature_invalid&debug_sbs={$this->problem}";
142             }
143             if(isset($this->errnames[$code])) {
144             return "oauth_problem=".$this->errnames[$code];
145         }
146         return "oauth_problem=unknown_problem&code=$code";
147         }
148
149         /**
150          * Check if this request needs token
151          * @return bool
152          */
153         protected function needsToken()
154         {
155             if(!empty($this->is_request)) {
156                 return false;
157             }
158             if(empty($this->requestPath)) {
159                 return true;
160             }
161             $GLOBALS['log']->debug("URLs: now: ".$this->url->getUri(). " req: {$this->requestPath}");
162             if($this->requestPath[0] == '/') {
163                 return $this->url->getPath() != $this->requestPath;
164             }
165             return $this->url->getUri() != $this->requestPath;
166         }
167
168         /**
169          * Check if all required parameters are there
170          * @param array $params
171          * @throws Zend_Oauth_Exception
172          */
173         protected function checkRequiredParams($params)
174         {
175         foreach($this->required as $param) {
176             if(!isset($params[$param])) {
177                 $this->problem = $param;
178                 throw new Zend_Oauth_Exception("Missing parameter: $param", self::PARAMETER_ABSENT);
179             }
180         }
181         if($this->needsToken() && !isset($params["oauth_token"])) {
182             $this->problem = "oauth_token";
183             throw new Zend_Oauth_Exception("Missing parameter: oauth_token", self::PARAMETER_ABSENT);
184         }
185         return true;
186         }
187
188         /**
189          * Check if signature method is supported
190          * @param string $signatureMethod
191          * @throws Zend_Oauth_Exception
192          */
193         protected function checkSignatureMethod($signatureMethod)
194         {
195         $className = '';
196         $hashAlgo  = null;
197         $parts     = explode('-', $signatureMethod);
198         if (count($parts) > 1) {
199             $className = 'Zend_Oauth_Signature_' . ucfirst(strtolower($parts[0]));
200         } else {
201             $className = 'Zend_Oauth_Signature_' . ucfirst(strtolower($signatureMethod));
202         }
203         $filename = str_replace('_', '/', $className) . '.php';
204         if(file_exists($filename)) {
205             require_once $filename;
206         }
207         if(!class_exists($className)) {
208             throw new Zend_Oauth_Exception("Invalid signature method", self::SIGNATURE_METHOD_REJECTED);
209         }
210         }
211
212         /**
213          * Collect request parameters from the environment
214          * @param string $method HTTP method being used
215          * @param string $params Extra parameters
216          */
217         protected function assembleParams($method, $params = array())
218         {
219             $params = array_merge($_GET, $params);
220             if($method == 'POST') {
221                 $params = array_merge($_POST, $params);
222             }
223             $auth = null;
224             if(function_exists('apache_request_headers')) {
225                 $headers = apache_request_headers();
226                 if(isset($headers['Authorization'])) {
227                     $auth = $headers['Authorization'];
228                 } elseif(isset($headers['authorization'])) {
229                     $auth = $headers['authorization'];
230                 }
231             }
232             if(empty($auth) && !empty($_SERVER['HTTP_AUTHORIZATION'])) {
233                 $auth = $_SERVER['HTTP_AUTHORIZATION'];
234             }
235
236             if(!empty($auth) && substr($auth, 0, 6) == 'OAuth ') {
237                 // import header data
238                 if (preg_match_all('/(oauth_[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $auth, $matches)) {
239               foreach ($matches[1] as $num => $header) {
240                   if($header == 'realm') {
241                       continue;
242                   }
243                   $params[$header] = urldecode(empty($matches[3][$num])? $matches[4][$num] : $matches[3][$num]);
244               }
245                 }
246             }
247             return $params;
248         }
249
250         /**
251          * Get current request URL
252          */
253         protected function getRequestUrl()
254         {
255             $proto = "http";
256             if(empty($_SERVER['SERVER_PORT']) || empty($_SERVER['HTTP_HOST']) || empty($_SERVER['REQUEST_URI'])) {
257                 return Zend_Uri_Http::fromString("http://localhost/");
258             }
259             if($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) &&  $_SERVER['HTTPS'] == 'on')) {
260                 $proto = 'https';
261             }
262             return Zend_Uri_Http::fromString("$proto://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
263         }
264
265         /**
266      * Returns oauth parameters
267      * @return array
268      */
269     public function getOAuthParams()
270     {
271         return $this->oauth_params;
272     }
273
274     /**
275          * Validate OAuth request
276          * @param Zend_Uri_Http $url Request URL, will use current if null
277          * @param array $params Additional parameters
278          * @return bool
279          * @throws Zend_Oauth_Exception
280          */
281         public function checkOAuthRequest(Zend_Uri_Http $url = null, $params = array())
282         {
283             if(empty($url)) {
284                 $this->url = $this->getRequestUrl();
285             } else {
286                 $this->url = clone $url;
287             }
288             // We'll ignore query for the pruposes of URL matching
289             $this->url->setQuery('');
290
291             if(isset($_SERVER['REQUEST_METHOD'])) {
292                 $method = $_SERVER['REQUEST_METHOD'];
293             } elseif(isset($_SERVER['HTTP_METHOD'])) {
294                 $method = $_SERVER['HTTP_METHOD'];
295             } else {
296                 $method = 'GET';
297             }
298         $params = $this->assembleParams($method, $params);
299         $this->oauth_params = $params;
300         $this->checkSignatureMethod($params['oauth_signature_method']);
301         $this->checkRequiredParams($params);
302
303         $this->timestamp = $params['oauth_timestamp'];
304         $this->nonce = $params['oauth_nonce'];
305         $this->consumer_key = $params['oauth_consumer_key'];
306
307         if(!is_callable($this->nonceHandler)) {
308             throw new Zend_Oauth_Exception("Nonce handler not callable", self::BAD_NONCE);
309         }
310
311         $res = call_user_func($this->nonceHandler, $this);
312         if($res != self::OK) {
313             throw new Zend_Oauth_Exception("Invalid request", $res);
314         }
315
316         if(!is_callable($this->consumerHandler)) {
317             throw new Zend_Oauth_Exception("Consumer handler not callable", self::CONSUMER_KEY_UNKNOWN);
318         }
319
320         $res = call_user_func($this->consumerHandler, $this);
321         // this will set $this->consumer_secret if OK
322         if($res != self::OK) {
323             throw new Zend_Oauth_Exception("Consumer key invalid", $res);
324         }
325
326         if($this->needsToken()) {
327             $this->token = $params['oauth_token'];
328             if(isset($params['oauth_verifier'])) {
329                 $this->verifier = $params['oauth_verifier'];
330             }
331             if(!is_callable($this->tokenHandler)) {
332                 throw new Zend_Oauth_Exception("Token handler not callable", self::TOKEN_REJECTED);
333             }
334             $res = call_user_func($this->tokenHandler, $this);
335             // this will set $this->token_secret if OK
336             if($res != self::OK) {
337                 throw new Zend_Oauth_Exception("Token invalid", $res);
338             }
339         }
340
341         $util = new Zend_Oauth_Http_Utility();
342         $req_sign = $params['oauth_signature'];
343         unset($params['oauth_signature']);
344         $our_sign = $util->sign($params, $params['oauth_signature_method'], $this->consumer_secret,
345             $this->token_secret, $method, $this->url->getUri());
346         if($req_sign != $our_sign) {
347             // TODO: think how to extract signature base string
348             $this->problem = $our_sign;
349             $GLOBALS['log']->fatal("Bad signature: $req_sign != $our_sign");
350             throw new Zend_Oauth_Exception("Invalid signature", self::INVALID_SIGNATURE);
351         }
352
353         return true;
354         }
355
356     /**
357      * Generate new token
358      * @param int $size How many characters?
359      */
360         public function generateToken($size)
361         {
362             $str = '';
363             while(strlen($str) < $size) {
364                 $str .= md5(uniqid(mt_rand(), true), true);
365             }
366             return substr($str, 0, $size);
367         }
368 }