summaryrefslogtreecommitdiff
path: root/modules/openid/openid.inc
blob: a1da1d0b57c5851949d01f752298064abbb8bf01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
<?php

/**
 * @file
 * OpenID utility functions.
 */

/**
 * Diffie-Hellman Key Exchange Default Value.
 *
 * This is used to establish an association between the Relying Party and the
 * OpenID Provider.
 *
 * See RFC 2631: http://www.ietf.org/rfc/rfc2631.txt
 */
define('OPENID_DH_DEFAULT_MOD', '155172898181473697471232257763715539915724801' .
       '966915404479707795314057629378541917580651227423698188993727816152646631' .
       '438561595825688188889951272158842675419950341258706556549803580104870537' .
       '681476726513255747040765857479291291572334510643245094715007229621094194' .
       '349783925984760375594985848253359305585439638443');

/**
 * Diffie-Hellman generator; used for Diffie-Hellman key exchange computations.
 */
define('OPENID_DH_DEFAULT_GEN', '2');

/**
 * SHA-1 hash block size; used for Diffie-Hellman key exchange computations.
 */
define('OPENID_SHA1_BLOCKSIZE', 64);

/**
 * Random number generator; used for Diffie-Hellman key exchange computations.
 */
define('OPENID_RAND_SOURCE', '/dev/urandom');

/**
 * OpenID Authentication 2.0 namespace URL.
 */
define('OPENID_NS_2_0', 'http://specs.openid.net/auth/2.0');

/**
 * OpenID Authentication 1.1 namespace URL; used for backwards-compatibility.
 */
define('OPENID_NS_1_1', 'http://openid.net/signon/1.1');

/**
 * OpenID Authentication 1.0 namespace URL; used for backwards-compatibility.
 */
define('OPENID_NS_1_0', 'http://openid.net/signon/1.0');

/**
 * OpenID namespace used in Yadis documents.
 */
define('OPENID_NS_OPENID', 'http://openid.net/xmlns/1.0');

/**
 * OpenID Simple Registration extension.
 */
define('OPENID_NS_SREG', 'http://openid.net/extensions/sreg/1.1');

/**
 * OpenID Attribute Exchange extension.
 */
define('OPENID_NS_AX', 'http://openid.net/srv/ax/1.0');

/**
 * Extensible Resource Descriptor documents.
 */
define('OPENID_NS_XRD', 'xri://$xrd*($v*2.0)');

/**
 * Performs an HTTP 302 redirect (for the 1.x protocol).
 */
function openid_redirect_http($url, $message) {
  $query = array();
  foreach ($message as $key => $val) {
    $query[] = $key . '=' . urlencode($val);
  }

  $sep = (strpos($url, '?') === FALSE) ? '?' : '&';
  header('Location: ' . $url . $sep . implode('&', $query), TRUE, 302);

  drupal_exit();
}

/**
 * Creates a js auto-submit redirect for (for the 2.x protocol)
 */
function openid_redirect($url, $message) {
  global $language;

  $output = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
  $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . $language->language . '" lang="' . $language->language . '">' . "\n";
  $output .= "<head>\n";
  $output .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
  $output .= "<title>" . t('OpenID redirect') . "</title>\n";
  $output .= "</head>\n";
  $output .= "<body>\n";
  $elements = drupal_get_form('openid_redirect_form', $url, $message);
  $output .= drupal_render($elements);
  $output .= '<script type="text/javascript">document.getElementById("openid-redirect-form").submit();</script>' . "\n";
  $output .= "</body>\n";
  $output .= "</html>\n";
  print $output;

  drupal_exit();
}

function openid_redirect_form($form, &$form_state, $url, $message) {
  $form['#action'] = $url;
  $form['#method'] = "post";
  foreach ($message as $key => $value) {
    $form[$key] = array(
      '#type' => 'hidden',
      '#name' => $key,
      '#value' => $value,
    );
  }
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#prefix' => '<noscript><div>',
    '#suffix' => '</div></noscript>',
    '#value' => t('Send'),
  );

  return $form;
}

/**
 * Parse an XRDS document.
 *
 * @param $raw_xml
 *   A string containing the XRDS document.
 * @return
 *   An array of service entries.
 */
function _openid_xrds_parse($raw_xml) {
  $services = array();

  // For PHP version >= 5.2.11, we can use this function to protect against
  // malicious doctype declarations and other unexpected entity loading.
  // However, we will not rely on it, and reject any XML with a DOCTYPE.
  $disable_entity_loader = function_exists('libxml_disable_entity_loader');
  if ($disable_entity_loader) {
    $load_entities = libxml_disable_entity_loader(TRUE);
  }

  // Load the XML into a DOM document.
  $dom = new DOMDocument();
  @$dom->loadXML($raw_xml);

  // Since DOCTYPE declarations from an untrusted source could be malicious, we
  // stop parsing here and treat the XML as invalid since XRDS documents do not
  // require, and are not expected to have, a DOCTYPE.
  if (isset($dom->doctype)) {
    return array();
  }

  // Also stop parsing if there is an unreasonably large number of tags.
  if ($dom->getElementsByTagName('*')->length > variable_get('openid_xrds_maximum_tag_count', 30000)) {
    return array();
  }

  // Parse the DOM document for the information we need.
  if ($xml = simplexml_import_dom($dom)) {
    foreach ($xml->children(OPENID_NS_XRD)->XRD as $xrd) {
      foreach ($xrd->children(OPENID_NS_XRD)->Service as $service_element) {
        $service = array(
          'priority' => $service_element->attributes()->priority ? (int)$service_element->attributes()->priority : PHP_INT_MAX,
          'types' => array(),
          'uri' => (string)$service_element->children(OPENID_NS_XRD)->URI,
          'service' => $service_element,
          'xrd' => $xrd,
        );
        foreach ($service_element->Type as $type) {
          $service['types'][] = (string)$type;
        }
        if ($service_element->children(OPENID_NS_XRD)->LocalID) {
          $service['identity'] = (string)$service_element->children(OPENID_NS_XRD)->LocalID;
        }
        elseif ($service_element->children(OPENID_NS_OPENID)->Delegate) {
          $service['identity'] = (string)$service_element->children(OPENID_NS_OPENID)->Delegate;
        }
        else {
          $service['identity'] = FALSE;
        }
        $services[] = $service;
      }
    }
  }

  // Return the LIBXML options to the previous state before returning.
  if ($disable_entity_loader) {
    libxml_disable_entity_loader($load_entities);
  }

  return $services;
}

/**
 * Select a service element.
 *
 * The procedure is described in OpenID Authentication 2.0, section 7.3.2.
 *
 * A new entry is added to the returned array with the key 'version' and the
 * value 1 or 2 specifying the protocol version used by the service.
 *
 * @param $services
 *   An array of service arrays as returned by openid_discovery().
 * @return
 *   The selected service array, or NULL if no valid services were found.
 */
function _openid_select_service(array $services) {
  // Extensible Resource Identifier (XRI) Resolution Version 2.0, section 4.3.3:
  // Find the service with the highest priority (lowest integer value). If there
  // is a tie, select a random one, not just the first in the XML document.
  shuffle($services);
  $selected_service = NULL;
  $selected_type_priority = FALSE;

  // Search for an OP Identifier Element.
  foreach ($services as $service) {
    if (!empty($service['uri'])) {
      $type_priority = FALSE;
      if (in_array('http://specs.openid.net/auth/2.0/server', $service['types'])) {
        $service['version'] = 2;
        $type_priority = 1;
      }
      elseif (in_array('http://specs.openid.net/auth/2.0/signon', $service['types'])) {
        $service['version'] = 2;
        $type_priority = 2;
      }
      elseif (in_array(OPENID_NS_1_0, $service['types']) || in_array(OPENID_NS_1_1, $service['types'])) {
        $service['version'] = 1;
        $type_priority = 3;
      }

      if ($type_priority
          && (!$selected_service
              || $type_priority < $selected_type_priority
              || ($type_priority == $selected_type_priority && $service['priority'] < $selected_service['priority']))) {
        $selected_service = $service;
        $selected_type_priority = $type_priority;
      }
    }
  }

  if ($selected_service) {
    // Unset SimpleXMLElement instances that cannot be saved in $_SESSION.
    unset($selected_service['xrd']);
    unset($selected_service['service']);
  }

  return $selected_service;
}

/**
 * Determine if the given identifier is an XRI ID.
 */
function _openid_is_xri($identifier) {
  // Strip the xri:// scheme from the identifier if present.
  if (stripos($identifier, 'xri://') === 0) {
    $identifier = substr($identifier, 6);
  }

  // Test whether the identifier starts with an XRI global context symbol or (.
  $firstchar = substr($identifier, 0, 1);
  if (strpos("=@+$!(", $firstchar) !== FALSE) {
    return TRUE;
  }

  return FALSE;
}

/**
 * Normalize the given identifier.
 *
 * The procedure is described in OpenID Authentication 2.0, section 7.2.
 */
function openid_normalize($identifier) {
  $methods = module_invoke_all('openid_normalization_method_info');
  drupal_alter('openid_normalization_method_info', $methods);

  // Execute each method in turn, stopping after the first method accepted
  // the identifier.
  foreach ($methods as $method) {
    $result = $method($identifier);
    if ($result !== NULL) {
      $identifier = $result;
      break;
    }
  }

  return $identifier;
}

/**
 * OpenID normalization method: normalize XRI identifiers.
 */
function _openid_xri_normalize($identifier) {
  if (_openid_is_xri($identifier)) {
    if (stristr($identifier, 'xri://') !== FALSE) {
      $identifier = substr($identifier, 6);
    }
    return $identifier;
  }
}

/**
 * OpenID normalization method: normalize URL identifiers.
 */
function _openid_url_normalize($url) {
  $normalized_url = $url;

  if (stristr($url, '://') === FALSE) {
    $normalized_url = 'http://' . $url;
  }

  // Strip the fragment and fragment delimiter if present.
  $normalized_url = strtok($normalized_url, '#');

  if (substr_count($normalized_url, '/') < 3) {
    $normalized_url .= '/';
  }

  return $normalized_url;
}

/**
 * Create a serialized message packet as per spec: $key:$value\n .
 */
function _openid_create_message($data) {
  $serialized = '';

  foreach ($data as $key => $value) {
    if ((strpos($key, ':') !== FALSE) || (strpos($key, "\n") !== FALSE) || (strpos($value, "\n") !== FALSE)) {
      return NULL;
    }
    $serialized .= "$key:$value\n";
  }
  return $serialized;
}

/**
 * Encode a message from _openid_create_message for HTTP Post
 */
function _openid_encode_message($message) {
  $encoded_message = '';

  $items = explode("\n", $message);
  foreach ($items as $item) {
    $parts = explode(':', $item, 2);

    if (count($parts) == 2) {
      if ($encoded_message != '') {
        $encoded_message .= '&';
      }
      $encoded_message .= rawurlencode(trim($parts[0])) . '=' . rawurlencode(trim($parts[1]));
    }
  }

  return $encoded_message;
}

/**
 * Convert a direct communication message
 * into an associative array.
 */
function _openid_parse_message($message) {
  $parsed_message = array();

  $items = explode("\n", $message);
  foreach ($items as $item) {
    $parts = explode(':', $item, 2);

    if (count($parts) == 2) {
      $parsed_message[$parts[0]] = $parts[1];
    }
  }

  return $parsed_message;
}

/**
 * Return a nonce value - formatted per OpenID spec.
 *
 * NOTE: This nonce is not cryptographically secure and only suitable for use
 * by the test framework.
 */
function _openid_nonce() {
  // YYYY-MM-DDThh:mm:ssZ, plus some optional extra unique characters.
  return gmdate('Y-m-d\TH:i:s\Z') .
    chr(mt_rand(0, 25) + 65) .
    chr(mt_rand(0, 25) + 65) .
    chr(mt_rand(0, 25) + 65) .
    chr(mt_rand(0, 25) + 65);
}

/**
 * Pull the href attribute out of an html link element.
 */
function _openid_link_href($rel, $html) {
  $rel = preg_quote($rel);
  preg_match('|<link\s+rel=["\'](.*)' . $rel . '(.*)["\'](.*)/?>|iUs', $html, $matches);
  if (isset($matches[3])) {
    preg_match('|href=["\']([^"]+)["\']|iU', $matches[3], $href);
    return trim($href[1]);
  }
  return FALSE;
}

/**
 * Pull the http-equiv attribute out of an html meta element
 */
function _openid_meta_httpequiv($equiv, $html) {
  preg_match('|<meta\s+http-equiv=["\']' . $equiv . '["\'](.*)/?>|iUs', $html, $matches);
  if (isset($matches[1])) {
    preg_match('|content=["\']([^"]+)["\']|iUs', $matches[1], $content);
    if (isset($content[1])) {
      return $content[1];
    }
  }
  return FALSE;
}

/**
 * Sign certain keys in a message
 * @param $association - object loaded from openid_association or openid_server_association table
 *              - important fields are ->assoc_type and ->mac_key
 * @param $message_array - array of entire message about to be sent
 * @param $keys_to_sign - keys in the message to include in signature (without
 *  'openid.' appended)
 */
function _openid_signature($association, $message_array, $keys_to_sign) {
  $signature = '';
  $sign_data = array();

  foreach ($keys_to_sign as $key) {
    if (isset($message_array['openid.' . $key])) {
      $sign_data[$key] = $message_array['openid.' . $key];
    }
  }

  $message = _openid_create_message($sign_data);
  $secret = base64_decode($association->mac_key);
  $signature = _openid_hmac($secret, $message);

  return base64_encode($signature);
}

function _openid_hmac($key, $text) {
  if (strlen($key) > OPENID_SHA1_BLOCKSIZE) {
    $key = sha1($key, TRUE);
  }

  $key = str_pad($key, OPENID_SHA1_BLOCKSIZE, chr(0x00));
  $ipad = str_repeat(chr(0x36), OPENID_SHA1_BLOCKSIZE);
  $opad = str_repeat(chr(0x5c), OPENID_SHA1_BLOCKSIZE);
  $hash1 = sha1(($key ^ $ipad) . $text, TRUE);
  $hmac = sha1(($key ^ $opad) . $hash1, TRUE);

  return $hmac;
}

function _openid_dh_base64_to_long($str) {
  $b64 = base64_decode($str);

  return _openid_dh_binary_to_long($b64);
}

function _openid_dh_long_to_base64($str) {
  return base64_encode(_openid_dh_long_to_binary($str));
}

function _openid_dh_binary_to_long($str) {
  $bytes = array_merge(unpack('C*', $str));

  $n = 0;
  foreach ($bytes as $byte) {
    $n = _openid_math_mul($n, pow(2, 8));
    $n = _openid_math_add($n, $byte);
  }

  return $n;
}

function _openid_dh_long_to_binary($long) {
  $cmp = _openid_math_cmp($long, 0);
  if ($cmp < 0) {
    return FALSE;
  }

  if ($cmp == 0) {
    return "\x00";
  }

  $bytes = array();

  while (_openid_math_cmp($long, 0) > 0) {
    array_unshift($bytes, _openid_math_mod($long, 256));
    $long = _openid_math_div($long, pow(2, 8));
  }

  if ($bytes && ($bytes[0] > 127)) {
    array_unshift($bytes, 0);
  }

  $string = '';
  foreach ($bytes as $byte) {
    $string .= pack('C', $byte);
  }

  return $string;
}

function _openid_dh_xorsecret($shared, $secret) {
  $dh_shared_str = _openid_dh_long_to_binary($shared);
  $sha1_dh_shared = sha1($dh_shared_str, TRUE);
  $xsecret = "";
  for ($i = 0; $i < strlen($secret); $i++) {
    $xsecret .= chr(ord($secret[$i]) ^ ord($sha1_dh_shared[$i]));
  }

  return $xsecret;
}

function _openid_dh_rand($stop) {
  $duplicate_cache = &drupal_static(__FUNCTION__, array());

  // Used as the key for the duplicate cache
  $rbytes = _openid_dh_long_to_binary($stop);

  if (isset($duplicate_cache[$rbytes])) {
    list($duplicate, $nbytes) = $duplicate_cache[$rbytes];
  }
  else {
    if ($rbytes[0] == "\x00") {
      $nbytes = strlen($rbytes) - 1;
    }
    else {
      $nbytes = strlen($rbytes);
    }

    $mxrand = _openid_math_pow(256, $nbytes);

    // If we get a number less than this, then it is in the
    // duplicated range.
    $duplicate = _openid_math_mod($mxrand, $stop);

    if (count($duplicate_cache) > 10) {
      $duplicate_cache = array();
    }

    $duplicate_cache[$rbytes] = array($duplicate, $nbytes);
  }

  do {
    $bytes = "\x00" . drupal_random_bytes($nbytes);
    $n = _openid_dh_binary_to_long($bytes);
    // Keep looping if this value is in the low duplicated range.
  } while (_openid_math_cmp($n, $duplicate) < 0);

  return _openid_math_mod($n, $stop);
}

function _openid_get_bytes($num_bytes) {
  return drupal_random_bytes($num_bytes);
}

function _openid_response($str = NULL) {
  $data = array();

  if (isset($_SERVER['REQUEST_METHOD'])) {
    $data = _openid_get_params($_SERVER['QUERY_STRING']);

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      $str = file_get_contents('php://input');

      $post = array();
      if ($str !== FALSE) {
        $post = _openid_get_params($str);
      }

      $data = array_merge($data, $post);
    }
  }

  return $data;
}

function _openid_get_params($str) {
  $chunks = explode("&", $str);

  $data = array();
  foreach ($chunks as $chunk) {
    $parts = explode("=", $chunk, 2);

    if (count($parts) == 2) {
      list($k, $v) = $parts;
      $data[$k] = urldecode($v);
    }
  }
  return $data;
}

/**
 * Extract all the parameters belonging to an extension in a response message.
 *
 * OpenID 2.0 defines a simple extension mechanism, based on a namespace prefix.
 *
 * Each request or response can define a prefix using:
 * @code
 *   openid.ns.[prefix] = [extension_namespace]
 *   openid.[prefix].[key1] = [value1]
 *   openid.[prefix].[key2] = [value2]
 *   ...
 * @endcode
 *
 * This function extracts all the keys belonging to an extension namespace in a
 * response, optionally using a fallback prefix if none is provided in the response.
 *
 * Note that you cannot assume that a given extension namespace will use the same
 * prefix on the response and the request: each party may use a different prefix
 * to refer to the same namespace.
 *
 * @param $response
 *   The response array.
 * @param $extension_namespace
 *   The namespace of the extension.
 * @param $fallback_prefix
 *   An optional prefix that will be used in case no prefix is found for the
 *   target extension namespace.
 * @param $only_signed
 *   Return only keys that are included in the message signature in openid.sig.
 *   Unsigned fields may have been modified or added by other parties than the
 *   OpenID Provider.
 *
 * @return
 *   An associative array containing all the parameters in the response message
 *   that belong to the extension. The keys are stripped from their namespace
 *   prefix.
 *
 * @see http://openid.net/specs/openid-authentication-2_0.html#extensions
 */
function openid_extract_namespace($response, $extension_namespace, $fallback_prefix = NULL, $only_signed = FALSE) {
  $signed_keys = explode(',', $response['openid.signed']);

  // Find the namespace prefix.
  $prefix = $fallback_prefix;
  foreach ($response as $key => $value) {
    if ($value == $extension_namespace && preg_match('/^openid\.ns\.([^.]+)$/', $key, $matches)) {
      $prefix = $matches[1];
      if ($only_signed && !in_array('ns.' . $matches[1], $signed_keys)) {
        // The namespace was defined but was not signed as required. In this
        // case we do not fall back to $fallback_prefix.
        $prefix = NULL;
      }
      break;
    }
  }

  // Now extract the namespace keys from the response.
  $output = array();
  if (!isset($prefix)) {
    return $output;
  }
  foreach ($response as $key => $value) {
    if (preg_match('/^openid\.' . $prefix . '\.(.+)$/', $key, $matches)) {
      $local_key = $matches[1];
      if (!$only_signed || in_array($prefix . '.' . $local_key, $signed_keys)) {
        $output[$local_key] = $value;
      }
    }
  }

  return $output;
}

/**
 * Extracts values from an OpenID AX Response.
 *
 * The values can be returned in two forms:
 *   - only openid.ax.value.<alias> (for single-valued answers)
 *   - both openid.ax.count.<alias> and openid.ax.value.<alias>.<count> (for both
 *     single and multiple-valued answers)
 *
 * @param $values
 *   An array as returned by openid_extract_namespace(..., OPENID_NS_AX).
 * @param $uris
 *   An array of identifier URIs.
 * @return
 *   An array of values.
 * @see http://openid.net/specs/openid-attribute-exchange-1_0.html#fetch_response
 */
function openid_extract_ax_values($values, $uris) {
  $output = array();
  foreach ($values as $key => $value) {
    if (in_array($value, $uris) && preg_match('/^type\.([^.]+)$/', $key, $matches)) {
      $alias = $matches[1];
      if (isset($values['count.' . $alias])) {
        for ($i = 1; $i <= $values['count.' . $alias]; $i++) {
          $output[] = $values['value.' . $alias . '.' . $i];
        }
      }
      elseif (isset($values['value.' . $alias])) {
        $output[] = $values['value.' . $alias];
      }
      break;
    }
  }
  return $output;
}

/**
 * Determine the available math library GMP vs. BCMath, favouring GMP for performance.
 */
function _openid_get_math_library() {
  // Not drupal_static(), because a function is not going to disappear and
  // change the output of this under any circumstances.
  static $library;

  if (empty($library)) {
    if (function_exists('gmp_add')) {
      $library =  'gmp';
    }
    elseif (function_exists('bcadd')) {
      $library = 'bcmath';
    }
  }

  return $library;
}

/**
 * Calls the add function from the available math library for OpenID.
 */
function _openid_math_add($x, $y) {
  $library = _openid_get_math_library();
  switch ($library) {
    case 'gmp':
      return gmp_strval(gmp_add($x, $y));
    case 'bcmath':
      return bcadd($x, $y);
  }
}

/**
 * Calls the mul function from the available math library for OpenID.
 */
function _openid_math_mul($x, $y) {
  $library = _openid_get_math_library();
  switch ($library) {
    case 'gmp':
      return gmp_mul($x, $y);
    case 'bcmath':
      return bcmul($x, $y);
  }
}

/**
 * Calls the div function from the available math library for OpenID.
 */
function _openid_math_div($x, $y) {
  $library = _openid_get_math_library();
  switch ($library) {
    case 'gmp':
      return gmp_div($x, $y);
    case 'bcmath':
      return bcdiv($x, $y);
  }
}

/**
 * Calls the cmp function from the available math library for OpenID.
 */
function _openid_math_cmp($x, $y) {
  $library = _openid_get_math_library();
  switch ($library) {
    case 'gmp':
      return gmp_cmp($x, $y);
    case 'bcmath':
      return bccomp($x, $y);
  }
}

/**
 * Calls the mod function from the available math library for OpenID.
 */
function _openid_math_mod($x, $y) {
  $library = _openid_get_math_library();
  switch ($library) {
    case 'gmp':
      return gmp_mod($x, $y);
    case 'bcmath':
      return bcmod($x, $y);
  }
}

/**
 * Calls the pow function from the available math library for OpenID.
 */
function _openid_math_pow($x, $y) {
  $library = _openid_get_math_library();
  switch ($library) {
    case 'gmp':
      return gmp_pow($x, $y);
    case 'bcmath':
      return bcpow($x, $y);
  }
}

/**
 * Calls the mul function from the available math library for OpenID.
 */
function _openid_math_powmod($x, $y, $z) {
  $library = _openid_get_math_library();
  switch ($library) {
    case 'gmp':
      return gmp_powm($x, $y, $z);
    case 'bcmath':
      return bcpowmod($x, $y, $z);
  }
}

/**
 * Provides transition for accounts with possibly invalid OpenID identifiers in authmap.
 *
 * This function provides a less safe but more unobtrusive procedure for users
 * who cannot login with their OpenID identifiers. OpenID identifiers in the
 * authmap could be incomplete due to invalid OpenID implementation in previous
 * versions of Drupal (e.g. fragment part of the identifier could be missing).
 * For more information see http://drupal.org/node/1120290.
 *
 * @param string $identity
 *   The user's claimed OpenID identifier.
 *
 * @return
 *   A fully-loaded user object if the user is found or FALSE if not found.
 */
function _openid_invalid_openid_transition($identity, $response) {
  $account = FALSE;
  $fallback_account = NULL;
  $fallback_identity = $identity;

  // Try to strip the fragment if it is present.
  if (strpos($fallback_identity, '#') !== FALSE) {
    $fallback_identity = preg_replace('/#.*/', '', $fallback_identity);
    $fallback_account = user_external_load($fallback_identity);
  }

  // Try to replace HTTPS with HTTP. OpenID providers often redirect
  // from http to https, but Drupal didn't follow the redirect.
  if (!$fallback_account && strpos($fallback_identity, 'https://') !== FALSE) {
    $fallback_identity = str_replace('https://', 'http://', $fallback_identity);
    $fallback_account = user_external_load($fallback_identity);
  }

  // Try to use original identifier.
  if (!$fallback_account && isset($_SESSION['openid']['user_login_values']['openid_identifier'])) {
    $fallback_identity = openid_normalize($_SESSION['openid']['user_login_values']['openid_identifier']);
    $fallback_account = user_external_load($fallback_identity);
  }

  if ($fallback_account) {
    // Try to extract e-mail address from Simple Registration (SREG) or
    // Attribute Exchanges (AX) keys.
    $email = '';
    $sreg_values = openid_extract_namespace($response, OPENID_NS_SREG, 'sreg', TRUE);
    $ax_values = openid_extract_namespace($response, OPENID_NS_AX, 'ax', TRUE);
    if (!empty($sreg_values['email']) && valid_email_address($sreg_values['email'])) {
      $email = $sreg_values['email'];
    }
    elseif ($ax_mail_values = openid_extract_ax_values($ax_values, array('http://axschema.org/contact/email', 'http://schema.openid.net/contact/email'))) {
      $email = current($ax_mail_values);
    }

    // If this e-mail address is the same as the e-mail address found in user
    // account, login the user and update the claimed identifier.
    if ($email && ($email == $fallback_account->mail || $email == $fallback_account->init)) {
      $query = db_insert('authmap')
        ->fields(array(
          'authname' => $identity,
          'uid' => $fallback_account->uid,
          'module' => 'openid',
        ))
        ->execute();
      drupal_set_message(t('New OpenID identifier %identity was added as a replacement for invalid identifier %invalid_identity. To finish the invalid OpenID transition process, please go to your <a href="@openid_url">OpenID identities page</a> and remove the old identifier %invalid_identity.', array('%invalid_identity' => $fallback_identity, '%identity' => $identity, '@openid_url' => 'user/' . $fallback_account->uid . '/openid')));
      // Set the account to the found one.
      $account = $fallback_account;
    }
    else {
      drupal_set_message(t('There is already an existing account associated with the OpenID identifier that you have provided. However, due to a bug in the previous version of the authentication system, we can\'t be sure that this account belongs to you. If you are new on this site, please continue registering the new user account. If you already have a registered account on this site associated with the provided OpenID identifier, please try to <a href="@url_password">reset the password</a> or contact the site administrator.', array('@url_password' => 'user/password')), 'warning');
    }
  }

  return $account;
}