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