PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Zend/Oauth2.php

https://github.com/A-Shevchenko/oauth-2---facebook---zend-framework-components
PHP | 361 lines | 148 code | 58 blank | 155 comment | 38 complexity | 13d5773a699a20c0f1310fdcfc161e24 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Oauth2
  17. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id: Oauth.php 21071 2010-02-16 14:35:00Z padraic $
  20. */
  21. /**
  22. * @see Zend_Oauth2_Config
  23. */
  24. require_once 'Zend/Oauth2/Config.php';
  25. /**
  26. * @see Zend_Rest_Client
  27. */
  28. require_once 'Zend/Rest/Client.php';
  29. /**
  30. * @see Zend_Json
  31. */
  32. require_once 'Zend/Json.php';
  33. class Zend_Oauth2
  34. {
  35. const authentification_uri = '/authorize';
  36. const access_token_uri = '/access_token';
  37. /**
  38. *
  39. * @var string
  40. */
  41. protected $_verificationCode = null;
  42. /**
  43. *
  44. * @varmixed
  45. */
  46. protected $_config = null;
  47. /**
  48. *
  49. * @var <type>
  50. */
  51. protected static $_localHttpClient = null;
  52. public function __construct($options = null)
  53. {
  54. $this->_config = new Zend_Oauth2_Config;
  55. if (!is_null($options)) {
  56. if ($options instanceof Zend_Config) {
  57. $options = $options->toArray();
  58. }
  59. $this->_config->setOptions($options);
  60. }
  61. }
  62. /**
  63. *
  64. * redirecting the end user's user-agent to the authorization page
  65. *
  66. * adter accepting or denying user will be redirected to callback page
  67. * if user accepts url will include a parameter "code" and optional a parameter "state"
  68. * if user denies url will include a parameter "error" set to "user_denied"
  69. * and an optional parameter "state"
  70. *
  71. * - type REQUIRED (The type of user delegation authorization flow)
  72. *
  73. * - client_id REQUIRED (The client identifier)
  74. *
  75. * - redirect_uri REQUIRED (An absolute URI to which the authorization server will
  76. * redirect the user-agent to when the end user authorization step is completed)
  77. *
  78. * - state OPTIONAL (An opaque value used by the client to maintain state between
  79. * the request and callback)
  80. *
  81. * - immediate OPTIONAL (The parameter value must be set to "true" or "false"
  82. * (case sensitive). If set to "true", the authorization server MUST NOT prompt
  83. * the end user to authenticate or approve access. Instead, the authorization
  84. * server attempts to establish the end user's identity via other means (e.g.
  85. * browser cookies) and checks if the end user has previously approved an
  86. * identical access request by the same client and if that access grant is
  87. * still active. If the authorization server does not support an immediate
  88. * check or if it is unable to establish the end user's identity or approval
  89. * status, it MUST deny the request without prompting the end user. Defaults
  90. * to "false" if omitted.)
  91. *
  92. * @param <type> $siteUrl
  93. * @param <type> $callbackUrl
  94. * @param <type> $clientId
  95. * @param <type> $type
  96. * @param <type> $state
  97. * @param <type> $immediate
  98. * @param <type> $requestedRights
  99. */
  100. public function authorizationRedirect($siteUrl = null, $callbackUrl = null, $clientId = null, $type = null, $state = null, $immediate = null, $requestedRights = null)
  101. {
  102. if (is_null($siteUrl)) $siteUrl = $this->_config->getSiteUrl();
  103. if (is_null($callbackUrl)) $callbackUrl = $this->_config->getCallbackUrl();
  104. if (is_null($clientId)) $clientId = $this->_config->getClientId();
  105. if (is_null($type)) $type = $this->_config->getType();
  106. if (is_null($state)) $state = $this->_config->getState();
  107. if (is_null($immediate)) $immediate = $this->_config->getImmediate();
  108. if (is_null($requestedRights)) $requestedRights = $this->_config->getRequestedRights();
  109. $requiredValuesArray = array('siteUrl', 'callbackUrl', 'clientId', 'type');
  110. // throw exception if one of the required values is missing
  111. foreach($requiredValuesArray as $requiredValue) {
  112. if (is_null($$requiredValue)) {
  113. require_once 'Zend/Oauth2/Exception.php';
  114. throw new Zend_Oauth2_Exception('value '. $requiredValue.' is empty, pass '.ucfirst($requiredValue).' as parameter when calling the '.__METHOD__.' method or add it to the options array you pass when creating an instance of the '.get_class($this).' class');
  115. }
  116. }
  117. // convert rights array to string
  118. $scope = '';
  119. if (is_array($requestedRights)) {
  120. $requestedRightsString = implode(',', $requestedRights);
  121. $scope = $requestedRightsString;
  122. } else {
  123. $scope = $requestedRights;
  124. }
  125. // construct request url with required values
  126. if (substr($siteUrl, -1) == '/') $siteUrl = substr($siteUrl, 0, strlen($siteUrl)-1);
  127. $requestUrl = $siteUrl.self::authentification_uri.'?client_id='.$clientId.'&redirect_uri='.$callbackUrl.'&type='.$type;
  128. //Zend_Debug::dump($requestUrl);
  129. //exit;
  130. // add optional values to request url
  131. if (!empty($scope)) $requestUrl .= '&scope='.$scope;
  132. if (!empty($state)) $requestUrl .= '&state='.$state;
  133. if (!empty($immediate)) $requestUrl .= '&immediate='.$immediate;
  134. //Zend_Debug::dump($requestUrl);
  135. //exit;
  136. header('Location: '.$requestUrl);
  137. exit(1);
  138. }
  139. /**
  140. *
  141. * @param string $right
  142. */
  143. public function addRequestedRight($right) {
  144. $rights = $this->getRequestedRights();
  145. if (is_array($rights)) {
  146. $rights[] = $right;
  147. } elseif (is_string($rights)) {
  148. $rightsArray = array();
  149. $rightsArray[] = $rights;
  150. $rightsArray[] = $right;
  151. $rights = $rightsArray;
  152. } else {
  153. $rights = $right;
  154. }
  155. $this->setRequestedRights($rights);
  156. }
  157. /**
  158. *
  159. * @param string $right
  160. */
  161. public function removeRequestedRight($right) {
  162. $rights = $this->getRequestedRights();
  163. $key = array_search($right, $rights);
  164. if ($key !== false) {
  165. unset($rights[$key]);
  166. }
  167. $this->setRequestedRights($rights);
  168. }
  169. /**
  170. * Set verification code
  171. *
  172. * @param string $verificationCode
  173. * @return Zend_Oauth2
  174. */
  175. public function setVerificationCode($verificationCode)
  176. {
  177. $this->_verificationCode = $verificationCode;
  178. return $this;
  179. }
  180. /**
  181. * Get verification code
  182. *
  183. * @return string
  184. */
  185. public function getVerificationCode()
  186. {
  187. return $this->_verificationCode;
  188. }
  189. /**
  190. * Set local HTTP client as distinct from the static HTTP client
  191. * as inherited from Zend_Rest_Client.
  192. *
  193. * @param Zend_Http_Client $client
  194. * @return self
  195. */
  196. public static function setLocalHttpClient(Zend_Http_Client $httpClient)
  197. {
  198. self::$_localHttpClient = $httpClient;
  199. }
  200. /**
  201. *
  202. * @return <type>
  203. */
  204. public static function getLocalHttpClient()
  205. {
  206. if (!isset(self::$_localHttpClient)) {
  207. self::$_localHttpClient = new Zend_Http_Client;
  208. }
  209. return self::$_localHttpClient;
  210. }
  211. /**
  212. * Simple mechanism to delete the entire singleton HTTP Client instance
  213. * which forces an new instantiation for subsequent requests.
  214. *
  215. * @return void
  216. */
  217. public static function clearHttpClient()
  218. {
  219. self::$httpClient = null;
  220. }
  221. /**
  222. *
  223. * requests an access token from the authorization server
  224. *
  225. * The client obtains an access token from the authorization server by
  226. * making an HTTP "POST" request to the token endpoint. The client
  227. * constructs a request URI by adding the following parameters to the
  228. * request:
  229. *
  230. * - type REQUIRED (The type of user delegation authorization flow)
  231. *
  232. * - client_id REQUIRED (The client identifier)
  233. *
  234. * - client_secret REQUIRED (The matching client secret)
  235. *
  236. * - code REQUIRED (The verification code received from the authorization server)
  237. *
  238. * - redirect_uri REQUIRED (The redirection URI used in the initial request)
  239. *
  240. * - secret_type OPTIONAL (The access token secret type. If omitted, the authorization
  241. * server will issue a bearer token (an access token without a matching secret))
  242. *
  243. * @param string $verificationCode
  244. * @return string
  245. */
  246. public function requestAccessToken($verificationCode = null, $siteUrl = null, $callbackUrl = null, $clientId = null, $clientSecret = null, $type = null, $secretTtype = null)
  247. {
  248. if (is_null($verificationCode)) $verificationCode = $this->getVerificationCode();
  249. if (is_null($siteUrl)) $siteUrl = $this->_config->getSiteUrl();
  250. if (is_null($callbackUrl)) $callbackUrl = $this->_config->getCallbackUrl();
  251. if (is_null($clientId)) $clientId = $this->_config->getClientId();
  252. if (is_null($clientSecret)) $clientSecret = $this->_config->getClientSecret();
  253. if (is_null($type)) $type = $this->_config->getType();
  254. if (is_null($secretTtype)) $secretTtype = $this->_config->getSecretType();
  255. if (is_null(self::$_localHttpClient)) $this->setLocalHttpClient($this->getLocalHttpClient());
  256. $requiredValuesArray = array('verificationCode', 'type', 'clientId', 'clientSecret', 'callbackUrl');
  257. // throw exception if one of the required values is missing
  258. foreach($requiredValuesArray as $requiredValue) {
  259. if (is_null($$requiredValue)) {
  260. require_once 'Zend/Oauth2/Exception.php';
  261. throw new Zend_Oauth2_Exception('value '. $requiredValue.' is empty, pass the '.ucfirst($requiredValue).' as parameter when calling the '.__METHOD__.' method or add it to the options array you pass when creating an instance of the '.get_class($this).' class');
  262. }
  263. }
  264. if (substr($siteUrl, -1) == '/') $siteUrl = substr($siteUrl, 0, strlen($siteUrl)-1);
  265. self::$_localHttpClient ->resetParameters()
  266. ->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8')
  267. ->setUri($siteUrl.self::access_token_uri)
  268. ->setParameterPost(array(
  269. 'type' => $type,
  270. 'client_id' => $clientId,
  271. 'client_secret' => $clientSecret,
  272. 'code' => $verificationCode,
  273. 'redirect_uri' => $callbackUrl,
  274. 'secret_type' => $secretTtype
  275. ));
  276. //Zend_Debug::dump(self::$_localHttpClient->getUri());
  277. //exit;
  278. $response = self::$_localHttpClient->request('POST');
  279. //Zend_Debug::dump($body, 'body');
  280. //Zend_Debug::dump($status, 'status');
  281. //exit;
  282. if (!is_null($response)) {
  283. $body = $response->getBody();
  284. $status = $response->getStatus();
  285. } else {
  286. require_once 'Zend/Oauth2/Exception.php';
  287. throw new Zend_Oauth2_Exception('the response we recieved is emtpy');
  288. }
  289. //Zend_Debug::dump($body, 'body');
  290. //exit;
  291. if ($status != '200') {
  292. $errorArray = Zend_Json::decode($body);
  293. require_once 'Zend/Oauth2/Exception.php';
  294. throw new Zend_Oauth2_Exception('we recieved an error ('.$status.') as response: '.$errorArray['error']['type'].' => '.$errorArray['error']['message']);
  295. }
  296. $explodedBody = explode('=', $body);
  297. if ($explodedBody[0] != 'access_token') {
  298. require_once 'Zend/Oauth2/Exception.php';
  299. throw new Zend_Oauth2_Exception('WTF?');
  300. }
  301. return $explodedBody[1];
  302. }
  303. }