PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/scotlandyardphp/openid/provider/provider.php

http://massey-se-c-team2.googlecode.com/
PHP | 845 lines | 547 code | 102 blank | 196 comment | 90 complexity | 598f1213e34ca38d403d32b4d00ae727 MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. /**
  3. * Using this class, you can easily set up an OpenID Provider.
  4. * It's independent of LightOpenID class.
  5. * It requires either GMP or BCMath for session encryption,
  6. * but will work without them (although either via SSL, or in stateless mode only).
  7. * Also, it requires PHP >= 5.1.2
  8. *
  9. * This is an alpha version, using it in production code is not recommended,
  10. * until you are *sure* that it works and is secure.
  11. *
  12. * Please send me messages about your testing results
  13. * (even if successful, so I know that it has been tested).
  14. * Also, if you think there's a way to make it easier to use, tell me -- it's an alpha for a reason.
  15. * Same thing applies to bugs in code, suggestions,
  16. * and everything else you'd like to say about the library.
  17. *
  18. * There's no usage documentation here, see the examples.
  19. *
  20. * @author Mewp
  21. * @copyright Copyright (c) 2010, Mewp
  22. * @license http://www.opensource.org/licenses/mit-license.php MIT
  23. */
  24. ini_set('error_log','log');
  25. abstract class LightOpenIDProvider
  26. {
  27. # URL-s to XRDS and server location.
  28. public $xrdsLocation, $serverLocation;
  29. # Should we operate in server, or signon mode?
  30. public $select_id = false;
  31. # Lifetime of an association.
  32. protected $assoc_lifetime = 600;
  33. # Variables below are either set automatically, or are constant.
  34. # -----
  35. # Can we support DH?
  36. protected $dh = true;
  37. protected $ns = 'http://specs.openid.net/auth/2.0';
  38. protected $data, $assoc;
  39. # Default DH parameters as defined in the specification.
  40. protected $default_modulus;
  41. protected $default_gen = 'Ag==';
  42. # AX <-> SREG transform
  43. protected $ax_to_sreg = array(
  44. 'namePerson/friendly' => 'nickname',
  45. 'contact/email' => 'email',
  46. 'namePerson' => 'fullname',
  47. 'birthDate' => 'dob',
  48. 'person/gender' => 'gender',
  49. 'contact/postalCode/home' => 'postcode',
  50. 'contact/country/home' => 'country',
  51. 'pref/language' => 'language',
  52. 'pref/timezone' => 'timezone',
  53. );
  54. # Math
  55. private $add, $mul, $pow, $mod, $div, $powmod;
  56. # -----
  57. # ------------------------------------------------------------------------ #
  58. # Functions you probably want to implement when extending the class.
  59. /**
  60. * Checks whether an user is authenticated.
  61. * The function should determine what fields it wants to send to the RP,
  62. * and put them in the $attributes array.
  63. * @param Array $attributes
  64. * @param String $realm Realm used for authentication.
  65. * @return String OP-local identifier of an authenticated user, or an empty value.
  66. */
  67. abstract function checkid($realm, &$attributes);
  68. /**
  69. * Displays an user interface for inputting user's login and password.
  70. * Attributes are always AX field namespaces, with stripped host part.
  71. * For example, the $attributes array may be:
  72. * array( 'required' => array('namePerson/friendly', 'contact/email'),
  73. * 'optional' => array('pref/timezone', 'pref/language')
  74. * @param String $identity Discovered identity string. May be used to extract login, unless using $this->select_id
  75. * @param String $realm Realm used for authentication.
  76. * @param String Association handle. must be sent as openid.assoc_handle in $_GET or $_POST in subsequent requests.
  77. * @param Array User attributes requested by the RP.
  78. */
  79. abstract function setup($identity, $realm, $assoc_handle, $attributes);
  80. /**
  81. * Stores an association.
  82. * If you want to use php sessions in your provider code, you have to replace it.
  83. * @param String $handle Association handle -- should be used as a key.
  84. * @param Array $assoc Association data.
  85. */
  86. protected function setAssoc($handle, $assoc)
  87. {
  88. $oldSession = session_id();
  89. session_commit();
  90. session_id($assoc['handle']);
  91. session_start();
  92. $_SESSION['assoc'] = $assoc;
  93. session_commit();
  94. if($oldSession) {
  95. session_id($oldSession);
  96. session_start();
  97. }
  98. }
  99. /**
  100. * Retreives association data.
  101. * If you want to use php sessions in your provider code, you have to replace it.
  102. * @param String $handle Association handle.
  103. * @return Array Association data.
  104. */
  105. protected function getAssoc($handle)
  106. {
  107. $oldSession = session_id();
  108. session_commit();
  109. session_id($handle);
  110. session_start();
  111. if(empty($_SESSION['assoc'])) {
  112. return null;
  113. }
  114. return $_SESSION['assoc'];
  115. session_commit();
  116. if($oldSession) {
  117. session_id($oldSession);
  118. session_start();
  119. }
  120. }
  121. /**
  122. * Deletes an association.
  123. * If you want to use php sessions in your provider code, you have to replace it.
  124. * @param String $handle Association handle.
  125. */
  126. protected function delAssoc($handle)
  127. {
  128. $oldSession = session_id();
  129. session_commit();
  130. session_id($handle);
  131. session_start();
  132. session_destroy();
  133. if($oldSession) {
  134. session_id($oldSession);
  135. session_start();
  136. }
  137. }
  138. # ------------------------------------------------------------------------ #
  139. # Functions that you might want to implement.
  140. /**
  141. * Redirects the user to an url.
  142. * @param String $location The url that the user will be redirected to.
  143. */
  144. protected function redirect($location)
  145. {
  146. header('Location: ' . $location);
  147. die();
  148. }
  149. /**
  150. * Generates a new association handle.
  151. * @return string
  152. */
  153. protected function assoc_handle()
  154. {
  155. return sha1(microtime());
  156. }
  157. /**
  158. * Generates a random shared secret.
  159. * @return string
  160. */
  161. protected function shared_secret($hash)
  162. {
  163. $length = 20;
  164. if($hash == 'sha256') {
  165. $length = 256;
  166. }
  167. $secret = '';
  168. for($i = 0; $i < $length; $i++) {
  169. $secret .= mt_rand(0,255);
  170. }
  171. return $secret;
  172. }
  173. /**
  174. * Generates a private key.
  175. * @param int $length Length of the key.
  176. */
  177. protected function keygen($length)
  178. {
  179. $key = '';
  180. for($i = 1; $i < $length; $i++) {
  181. $key .= mt_rand(0,9);
  182. }
  183. $key .= mt_rand(1,9);
  184. return $key;
  185. }
  186. # ------------------------------------------------------------------------ #
  187. # Functions that you probably shouldn't touch.
  188. function __construct()
  189. {
  190. $this->default_modulus =
  191. 'ANz5OguIOXLsDhmYmsWizjEOHTdxfo2Vcbt2I3MYZuYe91ouJ4mLBX+YkcLiemOcPy'
  192. . 'm2CBRYHNOyyjmG0mg3BVd9RcLn5S3IHHoXGHblzqdLFEi/368Ygo79JRnxTkXjgmY0'
  193. . 'rxlJ5bU1zIKaSDuKdiI+XUkKJX8Fvf8W8vsixYOr';
  194. $location = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://'
  195. . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  196. $location = preg_replace('/\?.*/','',$location);
  197. $this->serverLocation = $location;
  198. $location .= (strpos($location, '?') ? '&' : '?') . 'xrds';
  199. $this->xrdsLocation = $location;
  200. $this->data = $_GET + $_POST;
  201. # We choose GMP if avaiable, and bcmath otherwise
  202. if(function_exists('gmp_add')) {
  203. $this->add = 'gmp_add';
  204. $this->mul = 'gmp_mul';
  205. $this->pow = 'gmp_pow';
  206. $this->mod = 'gmp_mod';
  207. $this->div = 'gmp_div';
  208. $this->powmod = 'gmp_powm';
  209. } elseif(function_exists('bcadd')) {
  210. $this->add = 'bcadd';
  211. $this->mul = 'bcmul';
  212. $this->pow = 'bcpow';
  213. $this->mod = 'bcmod';
  214. $this->div = 'bcdiv';
  215. $this->powmod = 'bcpowmod';
  216. } else {
  217. # If neither are avaiable, we can't use DH
  218. $this->dh = false;
  219. }
  220. # However, we do require the hash functions.
  221. # They should be built-in anyway.
  222. if(!function_exists('hash_algos')) {
  223. $this->dh = false;
  224. }
  225. }
  226. /**
  227. * Displays an XRDS document, or redirects to it.
  228. * By default, it detects whether it should display or redirect automatically.
  229. * @param bool|null $force When true, always display the document, when false always redirect.
  230. */
  231. function xrds($force=null)
  232. {
  233. if($force) {
  234. echo $this->xrdsContent();
  235. die();
  236. } elseif($force === false) {
  237. header('X-XRDS-Location: '. $this->xrdsLocation);
  238. return;
  239. }
  240. if (isset($_GET['xrds'])
  241. || (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xrds+xml') !== false)
  242. ) {
  243. header('Content-Type: application/xrds+xml');
  244. echo $this->xrdsContent();
  245. die();
  246. }
  247. header('X-XRDS-Location: ' . $this->xrdsLocation);
  248. }
  249. /**
  250. * Returns the content of the XRDS document
  251. * @return String The XRDS document.
  252. */
  253. protected function xrdsContent()
  254. {
  255. $lines = array(
  256. '<?xml version="1.0" encoding="UTF-8"?>',
  257. '<xrds:XRDS xmlns:xrds="xri://$xrds" xmlns="xri://$xrd*($v*2.0)">',
  258. '<XRD>',
  259. ' <Service>',
  260. ' <Type>' . $this->ns . '/' . ($this->select_id ? 'server' : 'signon') .'</Type>',
  261. ' <URI>' . $this->serverLocation . '</URI>',
  262. ' </Service>',
  263. '</XRD>',
  264. '</xrds:XRDS>'
  265. );
  266. return implode("\n", $lines);
  267. }
  268. /**
  269. * Does everything that a provider has to -- in one function.
  270. */
  271. function server()
  272. {
  273. if(isset($this->data['openid_assoc_handle'])) {
  274. $this->assoc = $this->getAssoc($this->data['openid_assoc_handle']);
  275. if(isset($this->assoc['data'])) {
  276. # We have additional data stored for setup.
  277. $this->data += $this->assoc['data'];
  278. unset($this->assoc['data']);
  279. }
  280. }
  281. if (isset($this->data['openid_ns'])
  282. && $this->data['openid_ns'] == $this->ns
  283. ) {
  284. if(!isset($this->data['openid_mode'])) $this->errorResponse();
  285. switch($this->data['openid_mode'])
  286. {
  287. case 'checkid_immediate':
  288. case 'checkid_setup':
  289. $this->checkRealm();
  290. # We support AX xor SREG.
  291. $attributes = $this->ax();
  292. if(!$attributes) {
  293. $attributes = $this->sreg();
  294. }
  295. # Even if some user is authenticated, we need to know if it's
  296. # the same one that want's to authenticate.
  297. # Of course, if we use select_id, we accept any user.
  298. if (($identity = $this->checkid($this->data['openid_realm'], $attrValues))
  299. && ($this->select_id || $identity == $this->data['openid_identity'])
  300. ) {
  301. $this->positiveResponse($identity, $attrValues);
  302. } elseif($this->data['openid_mode'] == 'checkid_immediate') {
  303. $this->redirect($this->response(array('openid.mode' => 'setup_needed')));
  304. } else {
  305. if(!$this->assoc) {
  306. $this->generateAssociation();
  307. $this->assoc['private'] = true;
  308. }
  309. $this->assoc['data'] = $this->data;
  310. $this->setAssoc($this->assoc['handle'], $this->assoc);
  311. $this->setup($this->data['openid_identity'],
  312. $this->data['openid_realm'],
  313. $this->assoc['handle'],
  314. $attributes);
  315. }
  316. break;
  317. case 'associate':
  318. $this->associate();
  319. break;
  320. case 'check_authentication':
  321. $this->checkRealm();
  322. if($this->verify()) {
  323. echo "ns:$this->ns\nis_valid:true";
  324. if(strpos($this->data['openid_signed'],'invalidate_handle') !== false) {
  325. echo "\ninvalidate_handle:" . $this->data['openid_invalidate_handle'];
  326. }
  327. } else {
  328. echo "ns:$this->ns\nis_valid:false";
  329. }
  330. die();
  331. break;
  332. default:
  333. $this->errorResponse();
  334. }
  335. } else {
  336. $this->xrds();
  337. }
  338. }
  339. protected function checkRealm()
  340. {
  341. if (!isset($this->data['openid_return_to'], $this->data['openid_realm'])) {
  342. $this->errorResponse();
  343. }
  344. $realm = str_replace('\*', '[^/]', preg_quote($this->data['openid_realm']));
  345. if(!preg_match("#^$realm#", $this->data['openid_return_to'])) {
  346. $this->errorResponse();
  347. }
  348. }
  349. protected function ax()
  350. {
  351. # Namespace prefix that the fields must have.
  352. $ns = 'http://axschema.org/';
  353. # First, we must find out what alias is used for AX.
  354. # Let's check the most likely one
  355. $alias = null;
  356. if (isset($this->data['openid_ns_ax'])
  357. && $this->data['openid_ns_ax'] == 'http://openid.net/srv/ax/1.0'
  358. ) {
  359. $alias = 'ax';
  360. } else {
  361. foreach($this->data as $name => $value) {
  362. if ($value == 'http://openid.net/srv/ax/1.0'
  363. && preg_match('/openid_ns_(.+)/', $name, $m)
  364. ) {
  365. $alias = $m[1];
  366. break;
  367. }
  368. }
  369. }
  370. if(!$alias) {
  371. return null;
  372. }
  373. $fields = array();
  374. # Now, we must search again, this time for field aliases
  375. foreach($this->data as $name => $value) {
  376. if (strpos($name, 'openid_' . $alias . '_type') === false
  377. || strpos($value, $ns) === false) {
  378. continue;
  379. }
  380. $name = substr($name, strlen('openid_' . $alias . '_type_'));
  381. $value = substr($value, strlen($ns));
  382. $fields[$name] = $value;
  383. }
  384. # Then, we find out what fields are required and optional
  385. $required = array();
  386. $if_available = array();
  387. foreach(array('required','if_available') as $type) {
  388. if(empty($this->data["openid_{$alias}_{$type}"])) {
  389. continue;
  390. }
  391. $attributes = explode(',', $this->data["openid_{$alias}_{$type}"]);
  392. foreach($attributes as $attr) {
  393. if(empty($fields[$attr])) {
  394. # There is an undefined field here, so we ignore it.
  395. continue;
  396. }
  397. ${$type}[] = $fields[$attr];
  398. }
  399. }
  400. $this->data['ax'] = true;
  401. return array('required' => $required, 'optional' => $if_available);
  402. }
  403. protected function sreg()
  404. {
  405. $sreg_to_ax = array_flip($this->ax_to_sreg);
  406. $attributes = array('required' => array(), 'optional' => array());
  407. if (empty($this->data['openid_sreg_required'])
  408. && empty($this->data['openid_sreg_optional'])
  409. ) {
  410. return $attributes;
  411. }
  412. foreach(array('required', 'optional') as $type) {
  413. foreach(explode(',',$this->data['openid_sreg_' . $type]) as $attr) {
  414. if(empty($sreg_to_ax[$attr])) {
  415. # Undefined attribute in SREG request.
  416. # Shouldn't happen, but we check anyway.
  417. continue;
  418. }
  419. $attributes[$type][] = $sreg_to_ax[$attr];
  420. }
  421. }
  422. return $attributes;
  423. }
  424. /**
  425. * Aids an RP in assertion verification.
  426. * @return bool Information whether the verification suceeded.
  427. */
  428. protected function verify()
  429. {
  430. # Firstly, we need to make sure that there's an association.
  431. # Otherwise the verification will fail,
  432. # because we've signed assoc_handle in the assertion
  433. if(empty($this->assoc)) {
  434. return false;
  435. }
  436. # Next, we check that it's a private association,
  437. # i.e. one made without RP input.
  438. # Otherwise, the RP shouldn't ask us to verify.
  439. if(empty($this->assoc['private'])) {
  440. return false;
  441. }
  442. # Now we have to check if the nonce is correct, to prevent replay attacks.
  443. if($this->data['openid_response_nonce'] != $this->assoc['nonce']) {
  444. return false;
  445. }
  446. # Getting the signed fields for signature.
  447. $sig = array();
  448. $signed = explode(',', $this->data['openid_signed']);
  449. foreach($signed as $field) {
  450. $name = strtr($field, '.', '_');
  451. if(!isset($this->data['openid_' . $name])) {
  452. return false;
  453. }
  454. $sig[$field] = $this->data['openid_' . $name];
  455. }
  456. # Computing the signature and checking if it matches.
  457. $sig = $this->keyValueForm($sig);
  458. if ($this->data['openid_sig'] !=
  459. base64_encode(hash_hmac($this->assoc['hash'], $sig, $this->assoc['mac'], true))
  460. ) {
  461. return false;
  462. }
  463. # Clearing the nonce, so that it won't be used again.
  464. $this->assoc['nonce'] = null;
  465. if(empty($this->assoc['private'])) {
  466. # Commiting changes to the association.
  467. $this->setAssoc($this->assoc['handle'], $this->assoc);
  468. } else {
  469. # Private associations shouldn't be used again, se we can as well delete them.
  470. $this->delAssoc($this->assoc['handle']);
  471. }
  472. # Nothing has failed, so the verification was a success.
  473. return true;
  474. }
  475. /**
  476. * Performs association with an RP.
  477. */
  478. protected function associate()
  479. {
  480. # Rejecting no-encryption without TLS.
  481. if(empty($_SERVER['HTTPS']) && $this->data['openid_session_type'] == 'no-encryption') {
  482. $this->directErrorResponse();
  483. }
  484. # Checking whether we support DH at all.
  485. if (!$this->dh && substr($this->data['openid_session_type'], 0, 2) == 'DH') {
  486. $this->redirect($this->response(array(
  487. 'openid.error' => 'DH not supported',
  488. 'openid.error_code' => 'unsupported-type',
  489. 'openid.session_type' => 'no-encryption'
  490. )));
  491. }
  492. # Creating the association
  493. $this->assoc = array();
  494. $this->assoc['hash'] = $this->data['openid_assoc_type'] == 'HMAC-SHA256' ? 'sha256' : 'sha1';
  495. $this->assoc['handle'] = $this->assoc_handle();
  496. # Getting the shared secret
  497. if($this->data['openid_session_type'] == 'no-encryption') {
  498. $this->assoc['mac'] = base64_encode($this->shared_secret($this->assoc['hash']));
  499. } else {
  500. $this->dh();
  501. }
  502. # Preparing the direct response...
  503. $response = array(
  504. 'ns' => $this->ns,
  505. 'assoc_handle' => $this->assoc['handle'],
  506. 'assoc_type' => $this->data['openid_assoc_type'],
  507. 'session_type' => $this->data['openid_session_type'],
  508. 'expires_in' => $this->assoc_lifetime
  509. );
  510. if(isset($this->assoc['dh_server_public'])) {
  511. $response['dh_server_public'] = $this->assoc['dh_server_public'];
  512. $response['enc_mac_key'] = $this->assoc['mac'];
  513. } else {
  514. $response['mac_key'] = $this->assoc['mac'];
  515. }
  516. # ...and sending it.
  517. echo $this->keyValueForm($response);
  518. die();
  519. }
  520. /**
  521. * Creates a private association.
  522. */
  523. protected function generateAssociation()
  524. {
  525. $this->assoc = array();
  526. # We use sha1 by default.
  527. $this->assoc['hash'] = 'sha1';
  528. $this->assoc['mac'] = $this->shared_secret('sha1');
  529. $this->assoc['handle'] = $this->assoc_handle();
  530. }
  531. /**
  532. * Encrypts the MAC key using DH key exchange.
  533. */
  534. protected function dh()
  535. {
  536. if(empty($this->data['openid_dh_modulus'])) {
  537. $this->data['openid_dh_modulus'] = $this->default_modulus;
  538. }
  539. if(empty($this->data['openid_dh_gen'])) {
  540. $this->data['openid_dh_gen'] = $this->default_gen;
  541. }
  542. if(empty($this->data['openid_dh_consumer_public'])) {
  543. $this->directErrorResponse();
  544. }
  545. $modulus = $this->b64dec($this->data['openid_dh_modulus']);
  546. $gen = $this->b64dec($this->data['openid_dh_gen']);
  547. $consumerKey = $this->b64dec($this->data['openid_dh_consumer_public']);
  548. $privateKey = $this->keygen(strlen($modulus));
  549. $publicKey = $this->powmod($gen, $privateKey, $modulus);
  550. $ss = $this->powmod($consumerKey, $privateKey, $modulus);
  551. $mac = $this->x_or(hash($this->assoc['hash'], $ss, true), $this->shared_secret($this->assoc['hash']));
  552. $this->assoc['dh_server_public'] = $this->decb64($publicKey);
  553. $this->assoc['mac'] = base64_encode($mac);
  554. }
  555. /**
  556. * XORs two strings.
  557. * @param String $a
  558. * @param String $b
  559. * @return String $a ^ $b
  560. */
  561. protected function x_or($a, $b)
  562. {
  563. $length = strlen($a);
  564. for($i = 0; $i < $length; $i++) {
  565. $a[$i] = $a[$i] ^ $b[$i];
  566. }
  567. return $a;
  568. }
  569. /**
  570. * Prepares an indirect response url.
  571. * @param array $params Parameters to be sent.
  572. */
  573. protected function response($params)
  574. {
  575. $params += array('openid.ns' => $this->ns);
  576. return $this->data['openid_return_to']
  577. . (strpos($this->data['openid_return_to'],'?') ? '&' : '?')
  578. . http_build_query($params, '', '&');
  579. }
  580. /**
  581. * Outputs a direct error.
  582. */
  583. protected function errorResponse()
  584. {
  585. if(!empty($this->data['openid_return_to'])) {
  586. $response = array(
  587. 'openid.mode' => 'error',
  588. 'openid.error' => 'Invalid request'
  589. );
  590. $this->redirect($this->response($response));
  591. } else {
  592. header('HTTP/1.1 400 Bad Request');
  593. $response = array(
  594. 'ns' => $this->ns,
  595. 'error' => 'Invalid request'
  596. );
  597. echo $this->keyValueForm($response);
  598. }
  599. die();
  600. }
  601. /**
  602. * Sends an positive assertion.
  603. * @param String $identity the OP-Local Identifier that is being authenticated.
  604. * @param Array $attributes User attributes to be sent.
  605. */
  606. protected function positiveResponse($identity, $attributes)
  607. {
  608. # We generate a private association if there is none established.
  609. if(!$this->assoc) {
  610. $this->generateAssociation();
  611. $this->assoc['private'] = true;
  612. }
  613. # We set openid.identity (and openid.claimed_id if necessary) to our $identity
  614. if($this->data['openid_identity'] == $this->data['openid_claimed_id'] || $this->select_id) {
  615. $this->data['openid_claimed_id'] = $identity;
  616. }
  617. $this->data['openid_identity'] = $identity;
  618. # Preparing fields to be signed
  619. $params = array(
  620. 'op_endpoint' => $this->serverLocation,
  621. 'claimed_id' => $this->data['openid_claimed_id'],
  622. 'identity' => $this->data['openid_identity'],
  623. 'return_to' => $this->data['openid_return_to'],
  624. 'realm' => $this->data['openid_realm'],
  625. 'response_nonce' => gmdate("Y-m-d\TH:i:s\Z"),
  626. 'assoc_handle' => $this->assoc['handle'],
  627. );
  628. $params += $this->responseAttributes($attributes);
  629. # Has the RP used an invalid association handle?
  630. if (isset($this->data['openid_assoc_handle'])
  631. && $this->data['openid_assoc_handle'] != $this->assoc['handle']
  632. ) {
  633. $params['invalidate_handle'] = $this->data['openid_assoc_handle'];
  634. }
  635. # Signing the $params
  636. $sig = hash_hmac($this->assoc['hash'], $this->keyValueForm($params), $this->assoc['mac'], true);
  637. $req = array(
  638. 'openid.mode' => 'id_res',
  639. 'openid.signed' => implode(',', array_keys($params)),
  640. 'openid.sig' => base64_encode($sig),
  641. );
  642. # Saving the nonce and commiting the association.
  643. $this->assoc['nonce'] = $params['response_nonce'];
  644. $this->setAssoc($this->assoc['handle'], $this->assoc);
  645. # Preparing and sending the response itself
  646. foreach($params as $name => $value) {
  647. $req['openid.' . $name] = $value;
  648. }
  649. $this->redirect($this->response($req));
  650. }
  651. /**
  652. * Prepares an array of attributes to send
  653. */
  654. protected function responseAttributes($attributes)
  655. {
  656. if(!$attributes) return array();
  657. $ns = 'http://axschema.org/';
  658. $response = array();
  659. if(isset($this->data['ax'])) {
  660. $response['ns.ax'] = 'http://openid.net/srv/ax/1.0';
  661. foreach($attributes as $name => $value) {
  662. $alias = strtr($name, '/', '_');
  663. $response['ax.type.' . $alias] = $ns . $name;
  664. $response['ax.value.' . $alias] = $value;
  665. }
  666. return $response;
  667. }
  668. foreach($attributes as $name => $value) {
  669. if(!isset($this->ax_to_sreg[$name])) {
  670. continue;
  671. }
  672. $response['sreg.' . $this->ax_to_sreg[$name]] = $value;
  673. }
  674. return $response;
  675. }
  676. /**
  677. * Encodes fields in key-value form.
  678. * @param Array $params Fields to be encoded.
  679. * @return String $params in key-value form.
  680. */
  681. protected function keyValueForm($params)
  682. {
  683. $str = '';
  684. foreach($params as $name => $value) {
  685. $str .= "$name:$value\n";
  686. }
  687. return $str;
  688. }
  689. /**
  690. * Responds with an information that the user has canceled authentication.
  691. */
  692. protected function cancel()
  693. {
  694. $this->redirect($this->response(array('openid.mode' => 'cancel')));
  695. }
  696. /**
  697. * Converts base64 encoded number to it's decimal representation.
  698. * @param String $str base64 encoded number.
  699. * @return String Decimal representation of that number.
  700. */
  701. protected function b64dec($str)
  702. {
  703. $bytes = unpack('C*', base64_decode($str));
  704. $n = 0;
  705. foreach($bytes as $byte) {
  706. $n = $this->add($this->mul($n, 256), $byte);
  707. }
  708. return $n;
  709. }
  710. /**
  711. * Complements b64dec.
  712. */
  713. protected function decb64($num)
  714. {
  715. $bytes = array();
  716. while($num) {
  717. array_unshift($bytes, $this->mod($num, 256));
  718. $num = $this->div($num, 256);
  719. }
  720. if($bytes && $bytes[0] > 127) {
  721. array_unshift($bytes,0);
  722. }
  723. array_unshift($bytes, 'C*');
  724. return base64_encode(call_user_func_array('pack', $bytes));
  725. }
  726. function __call($name, $args)
  727. {
  728. switch($name) {
  729. case 'add':
  730. case 'mul':
  731. case 'pow':
  732. case 'mod':
  733. case 'div':
  734. case 'powmod':
  735. if(function_exists('gmp_strval')) {
  736. return gmp_strval(call_user_func_array($this->$name, $args));
  737. }
  738. return call_user_func_array($this->$name, $args);
  739. default:
  740. throw new BadMethodCallException();
  741. }
  742. }
  743. }