PageRenderTime 46ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/Zend/Oauth/Provider.php

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