? openid.js
Index: README.txt
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/openid/README.txt,v
retrieving revision 1.1.2.1
diff -u -u -r1.1.2.1 README.txt
--- README.txt	13 Jan 2007 06:12:53 -0000	1.1.2.1
+++ README.txt	21 Jan 2008 05:35:45 -0000
@@ -1,9 +1,8 @@
-OpenID 2.0 module for Drupal 4.7
-
-Authors: Rowan Kerr <rowan@standardinteractive.com>
-	 James Walker <james@bryght.com>
-
-Links
------
-OpenID 2.0 Pre-Draft 11
-http://openid.net/specs/openid-authentication-2_0-pre11.html
+OpenID 2.0 module for Drupal 5.0
+
+Authors: James Walker <james@bryght.com>
+
+Links
+-----
+OpenID 2.0 Pre-Draft 11
+http://openid.net/specs/openid-authentication-2_0-pre11.html
Index: openid.css
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/openid/openid.css,v
retrieving revision 1.1.2.2
diff -u -u -r1.1.2.2 openid.css
--- openid.css	18 Jan 2007 05:03:08 -0000	1.1.2.2
+++ openid.css	21 Jan 2008 05:35:45 -0000
@@ -1,7 +1,34 @@
-#openid_login_form #edit-openid_url,
-#user_edit #edit-openid_delegate {
-  background-image: url("login-bg.png");
-  background-position: 0% 50%;
-  background-repeat: no-repeat;
-  padding-left: 20px; 
-}
+/* $Id: openid.css,v 1.2.2.2 2007/07/28 03:05:47 walkah Exp $ */
+
+a.openid-link, a.user-link, #edit-openid-url {
+  background-image: url("login-bg.png");
+  background-position: 0% 50%;
+  background-repeat: no-repeat;
+  padding-left: 20px;
+}
+
+div#edit-openid-url-wrapper {
+  display: block;
+}
+
+html.js #user-login-form div#edit-openid-url-wrapper,
+html.js #user-login div#edit-openid-url-wrapper {
+  display: none;
+}
+
+html.js #user-login-form a.openid-link,
+html.js #user-login a.openid-link {
+  display : block;
+}
+
+#user-login-form a.openid-link,
+#user-login-form a.user-link,
+#user-login a.openid-link,
+#user-login a.user-link {
+  display: none;
+}
+
+#user-login-form a.openid-link,
+#user-login-form a.user-link {
+  text-align : left;
+}
Index: openid.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/openid/openid.inc,v
retrieving revision 1.1.2.8
diff -u -u -r1.1.2.8 openid.inc
--- openid.inc	25 Mar 2007 06:33:52 -0000	1.1.2.8
+++ openid.inc	21 Jan 2008 05:35:45 -0000
@@ -1,107 +1,132 @@
 <?php
-// $Id: openid.inc,v 1.1.2.8 2007/03/25 06:33:52 walkah Exp $
+// $Id: openid.inc,v 1.2.2.3 2007/10/14 20:19:21 walkah Exp $
 
 /**
- * OpenID utility functions that are
- * used by both Server and Consumer.
+ * @file
+ * OpenID utility functions.
  */
 
-/**
- * From Appendix B: Diffie-Hellman Key Exchange Default Value
- */
+// Diffie-Hellman Key Exchange Default Value.
 define('OPENID_DH_DEFAULT_MOD', '155172898181473697471232257763715539915724801'.
        '966915404479707795314057629378541917580651227423698188993727816152646631'.
        '438561595825688188889951272158842675419950341258706556549803580104870537'.
        '681476726513255747040765857479291291572334510643245094715007229621094194'.
        '349783925984760375594985848253359305585439638443');
 
+// Constants for Diffie-Hellman key exchange computations.
 define('OPENID_DH_DEFAULT_GEN', '2');
-
 define('OPENID_SHA1_BLOCKSIZE', 64);
-
 define('OPENID_RAND_SOURCE', '/dev/urandom');
 
-// 6.2.1. HTTP Redirect
-function openid_redirect_http($url, $encoded_message) {
-  header('Status: 302 Found');
-  header('Location: ' . $url . '?' . $encoded_message);
+// OpenID namespace URLs
+define('OPENID_NS_2_0', 'http://specs.openid.net/auth/2.0');
+define('OPENID_NS_1_1', 'http://openid.net/signon/1.1');
+define('OPENID_NS_1_0', 'http://openid.net/signon/1.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);
+  exit;
+}
+
+/**
+ * Creates a js auto-submit redirect for (for the 2.x protocol)
+ */
+function openid_redirect($url, $message) {
+  $output = '<html><head><title>'.t('OpenID redirect'). "</title></head>\n<body>";
+  $output .= drupal_get_form('openid_redirect_form', $url, $message);
+  $output .= '<script type="text/javascript">document.getElementById("openid-redirect-form").submit();</script>';
+  $output .= "</body></html>\n";
+  print $output;
   exit;
 }
 
-// 6.2.2. HTML FORM Redirection
 function openid_redirect_form($url, $message) {
   $form = array();
   $form['#action'] = $url;
-  $form['#method'] = "get";
-  $items = explode("\n", $message);
-  // Preserve GET parameters in url
-  $parts = parse_url($url);
-  $query = $parts['query'];
-  if ($query) {
-    $parts = explode('&', $query);
-    foreach ($parts as $part) {
-      list($key, $value) = explode('=', $part);
-      $form[$key] = array('#type' => 'hidden',
-                          '#name' => $key,
-                          '#value' => urldecode($value));
-    }
-  }
-  foreach ($items as $item) {
-    list($key, $value) = explode(':', $item, 2);
-    if ($key) {
-      $form[$key] = array(
-        '#type' => 'hidden',
-        '#name' => $key,
-        '#value' => $value);
-    }
+  $form['#method'] = "post";
+  foreach ($message as $key => $value) {
+    $form[$key] = array(
+      '#type' => 'hidden',
+      '#name' => $key,
+      '#value' => $value,
+    );
   }
   $form['submit'] = array(
     '#type' => 'submit',
     '#prefix' => '<noscript>',
     '#suffix' => '</noscript>',
-    '#value' => t('Send'));
+    '#value' => t('Send'),
+  );
 
-  $output = '<html><head><title>'.t('OpenID redirect'). "</title></head>\n<body>";
-  $output .= drupal_get_form('openid_redirect_form', $form);
-  $output .= '<script type="text/javascript">document.getElementById("openid_redirect_form").submit();</script>';
-  $output .= "</body></html>\n";
-  print $output;
-  exit;
+  return $form;
+}
+
+/**
+ * Determine if the given identifier is an XRI ID.
+ */
+function _openid_is_xri($identifier) {
+  $firstchar = substr($identifier, 0, 1);
+  if ($firstchar == "@" || $firstchar == "=")
+    return TRUE;
+
+  if (stristr($identifier, 'xri://') !== FALSE) {
+    return TRUE;
+  }
+
+  return FALSE;
+}
+
+/**
+ * Normalize the given identifier as per spec.
+ */
+function _openid_normalize($identifier) {
+  if (_openid_is_xri($identifier)) {
+    return _openid_normalize_xri($identifier);
+  }
+  else {
+    return _openid_normalize_url($identifier);
+  }
+}
+
+function _openid_normalize_xri($xri) {
+  $normalized_xri = $xri;
+  if (stristr($xri, 'xri://') !== FALSE) {
+    $normalized_xri = substr($xri, 6);
+  }
+  return $normalized_xri;
 }
 
 function _openid_normalize_url($url) {
   $normalized_url = $url;
 
   if (stristr($url, '://') === FALSE) {
-    $normalized_url = 'http://' . $url;
+    $normalized_url = 'http://'. $url;
   }
 
-  return $normalized_url;
-}
-
-function _openid_form($form, $action = '', $autosubmit = FALSE, $name = 'openid_fetch_form') {
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Submit'));
+  if (substr_count($normalized_url, '/') < 3) {
+    $normalized_url .= '/';
+  }
 
-  $form['#name'] = $name;
-  $content = drupal_get_form('openid_form', $form);
-  return $content;
+  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) {
-      return null;
-    }
-    
-    if (strpos($key, "\n") !== false) {
-      return null;
-    }
-    
-    if (strpos($value, "\n") !== false) {
+    if ((strpos($key, ':') !== FALSE) || (strpos($key, "\n") !== FALSE) || (strpos($value, "\n") !== FALSE)) {
       return null;
     }
     $serialized .= "$key:$value\n";
@@ -109,19 +134,21 @@
   return $serialized;
 }
 
+/**
+ * Encode a message from _openid_create_message for HTTP Post
+ */
 function _openid_encode_message($message) {
   $encoded_message = '';
 
-  // Content-Type: application/x-www-form-urlencoded
   $items = explode("\n", $message);
   foreach ($items as $item) {
-    list($key, $value) = explode(':', $item, 2);
+    $parts = explode(':', $item, 2);
 
-    if ($key != '') {
+    if (count($parts) == 2) {
       if ($encoded_message != '') {
         $encoded_message .= '&';
       }
-      $encoded_message .= rawurlencode(trim($key)) . '=' . rawurlencode(trim($value));
+      $encoded_message .= rawurlencode(trim($parts[0])) .'='. rawurlencode(trim($parts[1]));
     }
   }
 
@@ -137,16 +164,19 @@
 
   $items = explode("\n", $message);
   foreach ($items as $item) {
-    list($key, $value) = explode(':', $item, 2);
+    $parts = explode(':', $item, 2);
 
-    if ($key != '') {
-      $parsed_message[$key] = $value;
+    if (count($parts) == 2) {
+      $parsed_message[$parts[0]] = $parts[1];
     }
   }
 
   return $parsed_message;
 }
 
+/**
+ * Return a nonce value - formatted per OpenID spec.
+ */
 function _openid_nonce() {
   // YYYY-MM-DDThh:mm:ssTZD UTC, plus some optional extra unique chars
   return gmstrftime('%Y-%m-%dT%H:%M:%S%Z') .
@@ -156,43 +186,46 @@
     chr(mt_rand(0, 25) + 65);
 }
 
-// Pull the href attribute out of an html link element
+/**
+ * Pull the href attribute out of an html link element.
+ */
 function _openid_link_href($rel, $html) {
-  $rel = str_replace('.', '\.', $rel);
-  preg_match('|<link\s+rel="' . $rel . '"(.*)/?>|iU', $html, $matches);
-  if ($matches[1]) {
-    preg_match('|href="([^"]+)"|iU', $matches[1], $href);
-    return $href[1];
+  $rel = preg_quote($rel);
+  preg_match('|<link\s+rel=["\'](.*)'. $rel .'(.*)["\'](.*)/?>|iU', $html, $matches);
+  if (isset($matches[3])) {
+    preg_match('|href=["\']([^"]+)["\']|iU', $matches[0], $href);
+    return trim($href[1]);
   }
   return FALSE;
 }
 
-// Pull the http-equiv attribute out of an html meta element
+/**
+ * Pull the http-equiv attribute out of an html meta element
+ */
 function _openid_meta_httpequiv($equiv, $html) {
-  preg_match('|<meta\s+http-equiv="' . $equiv . '"(.*)/?>|iU', $html, $matches);
-  if ($matches[1]) {
-    preg_match('|content="([^"]+)"|iU', $matches[1], $content);
+  preg_match('|<meta\s+http-equiv=["\']'. $equiv .'["\'](.*)/?>|iU', $html, $matches);
+  if (isset($matches[1])) {
+    preg_match('|content=["\']([^"]+)["\']|iU', $matches[1], $content);
     return $content[1];
   }
   return FALSE;
 }
 
 /**
- * Signatures
  * Sign certain keys in a message
- * $association - object loaded from openid_association or openid_server_association table
+ * @param $association - object loaded from openid_association or openid_server_association table
  *              - important fields are ->assoc_type and ->mac_key
- * $message_array - array of entire message about to be sent
- * $keys_to_sign - keys in the message to include in signature (without
- * 'openid.' appended)
+ * @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];
+    if (isset($message_array['openid.'. $key])) {
+      $sign_data[$key] = $message_array['openid.'. $key];
     }
   }
 
@@ -204,16 +237,17 @@
 }
 
 function _openid_hmac($key, $text) {
-   if (strlen($key) > OPENID_SHA1_BLOCKSIZE) {
-        $key = _openid_sha1($key, true);
-    }
+  if (strlen($key) > OPENID_SHA1_BLOCKSIZE) {
+    $key = _openid_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 = _openid_sha1(($key ^ $ipad) . $text, true);
-    $hmac = _openid_sha1(($key ^ $opad) . $hash1, true);
-    return $hmac;
+  $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 = _openid_sha1(($key ^ $ipad) . $text, true);
+  $hmac = _openid_sha1(($key ^ $opad) . $hash1, true);
+
+  return $hmac;
 }
 
 function _openid_sha1($text) {
@@ -240,6 +274,7 @@
 function _openid_dh_binary_to_long($str) {
   $bytes = array_merge(unpack('C*', $str));
 
+  $n = 0;
   foreach ($bytes as $byte) {
     $n = bcmul($n, pow(2, 8));
     $n = bcadd($n, $byte);
@@ -259,21 +294,21 @@
   }
 
   $bytes = array();
-  
+
   while (bccomp($long, 0) > 0) {
     array_unshift($bytes, bcmod($long, 256));
     $long = bcdiv($long, pow(2, 8));
   }
-  
+
   if ($bytes && ($bytes[0] > 127)) {
     array_unshift($bytes, 0);
   }
-  
+
   $string = '';
   foreach ($bytes as $byte) {
     $string .= pack('C', $byte);
   }
-  
+
   return $string;
 }
 
@@ -284,25 +319,27 @@
   for ($i = 0; $i < strlen($secret); $i++) {
     $xsecret .= chr(ord($secret[$i]) ^ ord($sha1_dh_shared[$i]));
   }
-  
+
   return $xsecret;
 }
 
 function _openid_dh_rand($stop) {
   static $duplicate_cache = array();
-  
+
   // Used as the key for the duplicate cache
   $rbytes = _openid_dh_long_to_binary($stop);
-  
+
   if (array_key_exists($rbytes, $duplicate_cache)) {
     list($duplicate, $nbytes) = $duplicate_cache[$rbytes];
-  } else {
+  }
+  else {
     if ($rbytes[0] == "\x00") {
       $nbytes = strlen($rbytes) - 1;
-    } else {
+    }
+    else {
       $nbytes = strlen($rbytes);
     }
-    
+
     $mxrand = bcpow(256, $nbytes);
 
     // If we get a number less than this, then it is in the
@@ -312,14 +349,14 @@
     if (count($duplicate_cache) > 10) {
       $duplicate_cache = array();
     }
-    
+
     $duplicate_cache[$rbytes] = array($duplicate, $nbytes);
   }
-  
+
   do {
     $bytes = "\x00" . _openid_get_bytes($nbytes);
     $n = _openid_dh_binary_to_long($bytes);
-    // Keep looping if this value is in the low duplicated range
+    // Keep looping if this value is in the low duplicated range.
   } while (bccomp($n, $duplicate) < 0);
 
   return bcmod($n, $stop);
@@ -328,38 +365,33 @@
 function _openid_get_bytes($num_bytes) {
   static $f = null;
   $bytes = '';
-  if ($f === null) {
-    if (OPENID_RAND_SOURCE === null) {
-      $f = FALSE;
-    } else {
-      $f = @fopen(OPENID_RAND_SOURCE, "r");
-    }
+  if (!isset($f)) {
+    $f = @fopen(OPENID_RAND_SOURCE, "r");
   }
-  if ($f === FALSE) {
+  if (!$f) {
     // pseudorandom used
     $bytes = '';
     for ($i = 0; $i < $num_bytes; $i += 4) {
       $bytes .= pack('L', mt_rand());
     }
     $bytes = substr($bytes, 0, $num_bytes);
-  } else {
+  }
+  else {
     $bytes = fread($f, $num_bytes);
   }
   return $bytes;
 }
 
-// 7.4.4.1. Integer Representations
-function _openid_btwoc($num) {
-  return pack('H*', $num);
-}
-
-// Fix PHP's braindead handling of POST data
+/**
+ * Fix PHP's habit of replacing '.' by '_' in posted data.
+ */
 function _openid_fix_post(&$post) {
   $extensions = module_invoke_all('openid', 'extension');
   foreach ($post as $key => $value) {
     if (strpos($key, 'openid_') === 0) {
       $fixed_key = str_replace('openid_', 'openid.', $key);
       $fixed_key = str_replace('openid.ns_', 'openid.ns.', $fixed_key);
+      $fixed_key = str_replace('openid.sreg_', 'openid.sreg.', $fixed_key);
       foreach ($extensions as $ext) {
         $fixed_key = str_replace('openid.'.$ext.'_', 'openid.'.$ext.'.', $fixed_key);
       }
@@ -369,7 +401,9 @@
   }
 }
 
-// Provide bcpowmod support for PHP4
+/**
+ * Provide bcpowmod support for PHP4.
+ */
 if (!function_exists('bcpowmod')) {
   function bcpowmod($base, $exp, $mod) {
     $square = bcmod($base, $mod);
Index: openid.info
===================================================================
RCS file: openid.info
diff -N openid.info
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ openid.info	21 Jan 2008 05:35:45 -0000
@@ -0,0 +1,4 @@
+; $Id: openid.info,v 1.1.2.4 2007/06/18 23:06:56 dww Exp $
+name = OpenID
+description = "Allows Drupal to act as an OpenID relying party."
+package = OpenID
Index: openid.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/openid/openid.install,v
retrieving revision 1.1.2.4
diff -u -u -r1.1.2.4 openid.install
--- openid.install	19 Feb 2007 04:40:47 -0000	1.1.2.4
+++ openid.install	21 Jan 2008 05:35:45 -0000
@@ -1,5 +1,5 @@
 <?php
-// $Id: openid.install,v 1.1.2.4 2007/02/19 04:40:47 walkah Exp $
+// $Id: openid.install,v 1.2.2.3 2007/05/24 15:01:21 walkah Exp $
 
 /**
  * Implementation of hook_install
@@ -9,22 +9,41 @@
     case 'mysql':
     case 'mysqli':
       db_query("CREATE TABLE {openid_association} (
-  `idp_endpoint_uri` VARCHAR(255) NOT NULL DEFAULT '',
-  `assoc_handle` VARCHAR(255) NOT NULL DEFAULT '',
-  `assoc_type` VARCHAR(20) NOT NULL DEFAULT '',
-  `session_type` VARCHAR(20) NOT NULL DEFAULT '',
-  `mac_key` VARCHAR(255) NOT NULL DEFAULT '',
-  `created` INT(11) NOT NULL DEFAULT '0',
-  `expires_in` INT(11) NOT NULL DEFAULT '0',
-  PRIMARY KEY(assoc_handle)) /*!40100 DEFAULT CHARACTER SET utf8 */;");
-
-      db_query("CREATE TABLE {openid_assertion} (
-  `assertion_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
-  `idp_endpoint_uri` VARCHAR(255) NOT NULL DEFAULT '',
-  `response_nonce` VARCHAR(255) NOT NULL DEFAULT '',
-  `created` INT(11) NOT NULL DEFAULT '0'
-  ) /*!40100 DEFAULT CHARACTER SET utf8 */;");
+        idp_endpoint_uri VARCHAR(255) NOT NULL DEFAULT '',
+        assoc_handle VARCHAR(255) NOT NULL DEFAULT '',
+        assoc_type VARCHAR(20) NOT NULL DEFAULT '',
+        session_type VARCHAR(20) NOT NULL DEFAULT '',
+        mac_key VARCHAR(255) NOT NULL DEFAULT '',
+        created INT(11) NOT NULL DEFAULT '0',
+        expires_in INT(11) NOT NULL DEFAULT '0',
+        PRIMARY KEY (assoc_handle)
+        ) /*!40100 DEFAULT CHARACTER SET utf8 */;");
       break;
+  case 'pgsql':
+      db_query("CREATE TABLE {openid_association} (
+		idp_endpoint_uri varchar(255) NOT NULL default '',
+		assoc_handle varchar(255) NOT NULL default '',
+		assoc_type varchar(20) NOT NULL default '',
+		session_type varchar(20) NOT NULL default '',
+		mac_key varchar(255) NOT NULL default '',
+		created int NOT NULL default '0',
+		expires_in int NOT NULL default '0',
+		PRIMARY KEY (assoc_handle)
+		);");
   }
 }
 
+/**
+ * Implementation of hook_uninstall
+ */
+function openid_uninstall() {
+  switch ($GLOBALS['db_type']) {
+    case 'mysql':
+    case 'mysqli':
+      db_query('DROP TABLE IF EXISTS {openid_association}');
+      break;
+    case 'pgsql':
+      db_query('DROP TABLE {openid_association}');
+      break;
+  }
+}
Index: openid.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/openid/openid.module,v
retrieving revision 1.1.2.3.2.15
diff -u -u -r1.1.2.3.2.15 openid.module
--- openid.module	17 Apr 2007 20:39:33 -0000	1.1.2.3.2.15
+++ openid.module	21 Jan 2008 05:35:45 -0000
@@ -1,245 +1,390 @@
 <?php
-// $Id: openid.module,v 1.1.2.3.2.15 2007/04/17 20:39:33 walkah Exp $
+// $Id: openid.module,v 1.2.2.6 2007/10/14 20:29:27 walkah Exp $
 
 /**
- * OpenID consumer implementation for Drupal
+ * @file
+ * Impelement OpenID Relying Party support for Drupal
  */
 
-// Centralized openid functions
-require_once 'openid.inc';
-
-/* Drupal hooks */
-function openid_help($section) {
-  switch ($section) {
-    case 'admin/modules#description':
-      return t('Allows Drupal to act as an OpenID client.');
-  }
-} 
-
+/**
+ * Implementation of hook_menu.
+ */
 function openid_menu($may_cache) {
   $items = array();
-
   if ($may_cache) {
     $items[] = array(
-      'path' => 'openid/discover',
-      'title' => 'OpenID discover',
-      'callback' => 'openid_discover',
-      'access' => TRUE,
-      'type' => MENU_CALLBACK
-    );
-
-    $items[] = array(
       'path' => 'openid/authenticate',
-      'title' => 'OpenID authentication handler',
+      'title' => t('OpenID Login'),
       'callback' => 'openid_authentication_page',
       'access' => TRUE,
-      'type' => MENU_CALLBACK
-    );
+      'type' => MENU_CALLBACK,
+      );
   }
+  else {
+    if (arg(0) == 'user' && is_numeric(arg(1))) {
+      $account = user_load(array('uid' => arg(1)));
 
+      if ($account->uid) {
+        global $user;
+        
+        $access = (user_access('administer users') || $user->uid == arg(1));
+        $items[] = array(
+          'path' => 'user/'. arg(1) .'/openid',
+          'title' => t('OpenID Identities'),
+          'callback' => 'openid_user_identities',
+          'callback arguments' => array($account),
+          'access' => $access,
+          'type' => MENU_LOCAL_TASK
+          );
+        $items[] = array(
+          'path' => 'user/'. arg(1) .'/openid/delete',
+          'title' => t('Delete OpenID'),
+          'callback' => 'openid_user_delete',
+          'callback arguments' => array($account),
+          'access' => $access,
+          'type' => MENU_CALLBACK
+          );
+      }
+    }
+  }
   return $items;
 }
 
 /**
- * Implementation of hook_settings
+ * Implementation of hook_help().
  */
-function openid_settings() {
-  $form['openid_idp_policy'] = array(
-    '#type' => 'radios',
-    '#title' => t('Identity Provider policy'),
-    '#default_value' => variable_get('openid_idp_policy', 'public'),
-    '#options' => array('public' => t('Allow user to specify any Identity Provider'), 'protected' => t('Allow only the Identity Providers listed below')));
-  $form['openid_idp_allow'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Allowed Identity Providers'),
-    '#default_value' => variable_get('openid_idp_allow', ''),
-    '#cols' => 40, '#rows' => 6,
-    '#description' => t('Enter one URL per line.'));
-  $form['openid_request_mode'] = array(
-    '#type' => 'select',
-    '#title' => t('Request Mode'),
-    '#default_value' => variable_get('openid_request_mode', 'checkid_setup'),
-    '#options' => array('checkid_immediate' => t('Immediate'), 'checkid_setup' => t('Interactive')));
-  $form['openid_session_type'] = array(
-    '#type' => 'select',
-    '#title' => t('Session Type'),
-    '#default_value' => variable_get('openid_session_type', 'DH-SHA1'),
-    '#options' => array('no-encryption' => 'no-encryption', 'DH-SHA1' => 'DH-SHA1', 'DH-SHA256' => 'DH-SHA256'));
-  return $form;
+function openid_help($section) {
+  switch ($section) {
+    case 'user/'. arg(1) .'/openid':
+      return t('You may login to this site using an OpenID. You may add your OpenId URLs below, and also see a list of any OpenIDs which have already been added.');
+    case 'admin/help#openid':
+      $output = '<p>'. t('OpenID is a secure way to use one user ID and password to log in to many web sites without special software, giving the same password to each site, or losing control over which information is shared with each site that you visit.') .'</p>';
+      $output .= '<p>'. t('Users can create accounts using their OpenID, assign one or more OpenIDs to an existing account, and log in using an OpenID. This lowers the barrier to registration, which is good for the site, and offers convenience and security to the users. Logging in via OpenID is far more secure than cross-site logins using drupal.module.') .'</p>';
+      $output .= '<p>'. t('More information on OpenID is available at <a href="@url">OpenID.net</a>', array('@url' => url('http://openid.net'))) .'</p>';
+      return $output;
+  }
 }
 
-function openid_block($op = 'list', $delta = 0, $edit = array()) {
-  // log in with OpenID... enter your url
-  switch ($op) {
-    case 'list':
-      return array(array('info' => t('OpenID login form')));
-
-    case 'view':
-      theme('add_style', drupal_get_path('module', 'openid') . '/openid.css');
-      return array(
-        'subject' => t('OpenID login'),
-        'content' => openid_login_form()
-      );
+/**
+ * Implementation of hook_user().
+ */
+function openid_user($op, &$edit, &$account, $category = NULL) {
+  if ($op == 'insert' && isset($_SESSION['openid'])) {
+    // The user has registered after trying to login via OpenID.
+    if (variable_get('user_email_verification', TRUE)) {
+      drupal_set_message(t('Once you have verified your email address, you may log in via OpenID.'));
+    }
+    unset($_SESSION['openid']);
   }
 }
 
-/* Public functions */
-function openid_login_form() {
-  global $user;
-
-  if (!$user->uid) {
-    $form = array();
-    if (variable_get('openid_idp_policy', 'public') == 'public') {
-      $form['openid_url'] = array(
-        '#type' => 'textfield',
-        '#title' => t('OpenID'),
-        '#default_value' => '',
-        '#size' => 30,
-        '#maxlength' => 255,
-        '#description' => t('For example: myblog.bloghost.com')
-        );
-    }
-    else {
-      $lines = split("[,\n\r]", variable_get('openid_idp_allow', ''));
-      foreach ($lines as $line) {
-        if ($line = trim($line)) {
-          $idp_options[$line] = $line;
-        }
-      }
-      $form['openid_url'] = array(
-          '#type'=> 'select',
-          '#title' => t('OpenID'),
-          '#default_value' => '',
-          '#options' => $idp_options);        
+/**
+ * Implementation of hook_form_alter : adds OpenID login to the login forms.
+ */
+function openid_form_alter($form_id, &$form) {
+  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
+    drupal_add_css(drupal_get_path('module', 'openid') .'/openid.css', 'module');
+    drupal_add_js(drupal_get_path('module', 'openid') .'/openid.js');
+
+    if (!empty($form['#post']['openid_url'])) {
+      $form['name']['#required'] = FALSE;
+      $form['pass']['#required'] = FALSE;
+      unset($form['#submit']);
+      $form['#validate'] = array('openid_login_validate' => array());
+    }
+
+    $form['openid_link'] = array('#value' => l(t('Log in using OpenID'), '#', array('class' => 'openid-link')));
+    $form['user_link'] = array('#value' => l(t('Cancel OpenID login'), '#', array('class' => 'user-link')));
+
+    $form['openid_url'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Log in using OpenID'),
+      '#size' => ($form_id == 'user_login') ? 58 : 13,
+      '#maxlength' => 255,
+      '#weight' => -1,
+      '#description' => l(t('What is OpenID?'), 'http://openid.net/'),
+      '#prefix' => '<div id="edit-openid-url-wrapper">',
+      '#suffix' => '</div>'      
+      );
+    $form['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', drupal_get_destination(), NULL, TRUE));
+    $form['name']['#prefix'] = '<div id="edit-name-wrapper">';
+    $form['name']['#suffix'] = '</div>';
+    $form['pass']['#prefix'] = '<div id="edit-pass-wrapper">';
+    $form['pass']['#suffix'] = '</div>';
+  }
+  elseif($form_id == 'user_register' && isset($_SESSION['openid'])) {
+    // We were unable to auto-register a new user. Prefill the registration
+    // form with the values we have.
+    $form['name']['#default_value'] = $_SESSION['openid']['name'];
+    $form['mail']['#default_value'] = $_SESSION['openid']['mail'];
+    // If user_email_verification is off, hide the password field and just fill
+    // with random password to avoid confusion.
+    if (!variable_get('user_email_verification', TRUE)) {
+      $form['pass']['#type'] = 'hidden';
+      $form['pass']['#value'] = user_password();
     }
+    $form['auth_openid'] = array('#type' => 'hidden', '#value' => $_SESSION['openid']['auth_openid']);
+  }
+  return $form;
+}
+
+/**
+ * Login form _validate hook.
+ */
+function openid_login_validate($form_id, $form_values) {
+  $return_to = $form_values['openid.return_to'];
+  if (empty($return_to)) {
+    $return_to = url('', NULL, NULL, TRUE);
+  }
+  return openid_begin($form_values['openid_url'], $return_to);
+}
 
-    $form['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', NULL, NULL, TRUE));
+function openid_authentication_page() {
+  $result = openid_complete($_REQUEST);
+  switch ($result['status']) {
+    case 'success':
+      return openid_authentication($result);
+    case 'failed':
+      drupal_set_message(t('OpenID login failed.'), 'error');
+      break;
+    case 'cancel':
+      drupal_set_message(t('OpenID login cancelled.'));
+      break;
+  }
+  drupal_goto();
+}
 
+function openid_user_identities($account) {
+  drupal_add_css(drupal_get_path('module', 'openid') .'/openid.css', 'module');
 
-    $form['submit'] = array(
-      '#type' => 'submit',
-      '#value' => t('Login')
-      );
+  // Check to see if we got a response
+  $result = openid_complete($_REQUEST);
+  if ($result['status'] == 'success') {
+    db_query("INSERT INTO {authmap} (uid, authname, module) VALUES (%d, '%s','openid')", $account->uid, $result['openid.identity']);
+    drupal_set_message(t('Successfully added %identity', array('%identity' => $result['openid.identity'])));
+  }
+  
+  $header = array(t('OpenID'), t('Operations'));
+  $rows = array();
 
-    return drupal_get_form('openid_login_form', $form);
+  $result = db_query("SELECT * FROM {authmap} WHERE module='openid' AND uid=%d", $account->uid);
+  while ($identity = db_fetch_object($result)) {
+    $rows[] = array($identity->authname, l(t('Delete'), 'user/'. $account->uid .'/openid/delete/'. $identity->aid));
   }
+
+  $output = theme('table', $header, $rows);
+  $output .= drupal_get_form('openid_user_add');
+  return $output;
+}
+
+function openid_user_add() {
+  $form['openid_url'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Add an OpenID')
+    );
+  $form['submit'] = array('#type' => 'submit', '#value' => t('Add'));
+  return $form;
+}
+
+function openid_user_add_validate($form_id, $form_values) {
+  // Check for existing entries.
+  $claimed_id = _openid_normalize($form_values['openid_url']);
+  if (db_result(db_query("SELECT authname FROM {authmap} WHERE authname='%s'", $claimed_id))) {
+    form_set_error('openid_url', t('That OpenID is already in use on this site.'));
+  }
+  else {
+    $return_to = url('user/'. arg(1)  .'/openid', NULL, NULL, TRUE);
+    openid_begin($form_values['openid_url'], $return_to);
+  }
+}
+
+function openid_user_delete($account, $aid = 0) {
+  db_query("DELETE FROM {authmap} WHERE uid=%d AND aid=%d AND module='openid'", $account->uid, $aid);
+  if (db_affected_rows()) {
+    drupal_set_message(t('OpenID deleted.'));
+  }
+  drupal_goto('user/'. $account->uid .'/openid');
 }
 
 /**
- * Login form _submit hook
- */
-function openid_login_form_submit($formid, $form_values) {
-  $claimed_id = _openid_normalize_url($form_values['openid_url']); 
+ * The initial step of OpenID authentication responsible for the following:
+ *  - Perform discovery on the claimed OpenID.
+ *  - If possible, create an association with the Provider's endpoint.
+ *  - Create the authentication request.
+ *  - Perform the appropriate redirect.
+ *
+ * @param $claimed_id The OpenID to authenticate
+ * @param $return_to The endpoint to return to from the OpenID Provider
+ */ 
+function openid_begin($claimed_id, $return_to = '') {
+  include_once drupal_get_path('module', 'openid') .'/openid.inc';
+  
+  $claimed_id = _openid_normalize($claimed_id); 
 
   $services = openid_discovery($claimed_id);
   if (count($services) == 0) {
-    drupal_set_message(t('OpenID Discovery failed'), 'error');
+    form_set_error('openid_url', t('Sorry, that is not a valid OpenID. Please ensure you have spelled your ID correctly.'));
     return;
   }
 
-  $idp_endpoint = $services[0]['uri'];
-  $_SESSION['openid_idp_endpoint'] = $idp_endpoint;
-  $assoc_handle = openid_association($claimed_id, $idp_endpoint);
-  if (empty($assoc_handle)) {
-    drupal_set_message(t('OpenID Association failed'), 'error');
-    return;    
+  $op_endpoint = $services[0]['uri'];
+  // Store the discovered endpoint in the session (so we don't have to rediscover).
+  $_SESSION['openid_op_endpoint'] = $op_endpoint;
+  // Store the claimed_id in the session (for handling delegation).
+  $_SESSION['openid_claimed_id'] = $claimed_id;
+  
+  // If bcmath is present, then create an association
+  $assoc_handle = '';
+  if (function_exists('bcadd')) {
+    $assoc_handle = openid_association($op_endpoint);
   }
   
   // Now that there is an association created, move on
   // to request authentication from the IdP
-  $return_to = $form_values['openid.return_to'];
-  if (empty($return_to)) {
-    $return_to = url('', NULL, NULL, TRUE);
+  // First check for LocalID. If not found, check for Delegate. Fall
+  // back to $claimed_id if neither is found.
+  if (!empty($services[0]['localid'])) {
+    $identity = $services[0]['localid'];
   }
-
-  $identity = $claimed_id;
-  if (is_array($services[0]['types']) && in_array('http://openid.net/server/2.0', $services[0]['types'])) {
+  else if (!empty($services[0]['delegate'])) {
+    $identity = $services[0]['delegate'];
+  }
+  else {
+    $identity = $claimed_id;
+  }
+  
+  if (isset($services[0]['types']) && is_array($services[0]['types']) && in_array(OPENID_NS_2_0 .'/server', $services[0]['types'])) {
     $identity = 'http://openid.net/identifier_select/2.0';
   }
-  $authn_request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle);
+  $authn_request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $services[0]['version']);
 
-  $authn_message = _openid_create_message($authn_request);
-  if (variable_get('openid_request_mode', 'checkid_setup') == 'checkid_immediate') {
-    // Direct communication
-    $authn_headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
-    $authn_result = drupal_http_request($idp_endpoint, $authn_headers, 'POST', _openid_encode_message($authn_message));
-    
-    $authn_response = _openid_parse_message($authn_result->data);
-    if (!empty($authn_response['openid.user_setup_url'])) {
-      drupal_set_message(t('Authentication failed. Please visit %url to continue.', array('%url' => l($authn_response['openid.user_setup_url'], $authn_response['openid.user_setup_url']))), 'error');
-      return;
-    }
-    else {
-      // Authentication successful!
-      if (openid_verify_assertion($idp_endpoint, $authn_response)) {
-        openid_authentication($authn_response);
+  if ($services[0]['version'] == 2) {
+    openid_redirect($op_endpoint, $authn_request);
+  }
+  else {
+    openid_redirect_http($op_endpoint, $authn_request);
+  }  
+}
+
+/**
+ * Completes OpenID authentication by validating returned data from the OpenID
+ * Provider.
+ *
+ * @param $response Array of returned from the OpenID provider (typically $_REQUEST).
+ *
+ * @return $response Response values for further processing with
+ *   $response['status'] set to one of 'success', 'failed' or 'cancel'.
+ */
+function openid_complete($response) {
+  include_once drupal_get_path('module', 'openid') .'/openid.inc';
+
+  // Default to failed response
+  $response['status'] = 'failed';
+  if (isset($_SESSION['openid_op_endpoint']) && isset($_SESSION['openid_claimed_id'])) {
+    _openid_fix_post($response);
+    $op_endpoint = $_SESSION['openid_op_endpoint'];
+    $claimed_id = $_SESSION['openid_claimed_id'];
+    unset($_SESSION['openid_op_endpoint']);
+    unset($_SESSION['openid_claimed_id']);
+    if (isset($response['openid.mode'])) {
+      if ($response['openid.mode'] == 'cancel') {
+        $response['status'] = 'cancel';
       }
       else {
-        drupal_set_message(t('OpenID verification failed'), 'error');
-        return;    
+        if (openid_verify_assertion($op_endpoint, $response)) {
+          $response['openid.identity'] = $claimed_id;
+          $response['status'] = 'success';
+        }
       }
     }
   }
-  else {
-    openid_redirect_form($idp_endpoint, $authn_message);
-  }
+  return $response;
 }
 
+/**
+ * Perform discovery on a claimed ID to determine the OpenID provider endpoint.
+ *
+ * @param $claimed_id The OpenID URL to perform discovery on.
+ *
+ * @return Array of services discovered (including OpenID version, endpoint
+ * URI, etc).
+ */
 function openid_discovery($claimed_id) {
-  // Externalize XRDS parsing
-  include_once 'xrds.inc';
-
-  $url = @parse_url($claimed_id);
-  if (!$url) {
-    return FALSE;
-  }
+  include_once drupal_get_path('module', 'openid') .'/openid.inc';
+  include_once drupal_get_path('module', 'openid') .'/xrds.inc';
 
-  $xrds_url = '';
   $services = array();
 
-  if ($url['scheme'] == 'xri') {
-    // Attempt XRI resolution if they have passed in an XRI
-    $xrds_url = str_replace('xri', 'http', $claimed_id);
+  $xrds_url = $claimed_id;
+  if (_openid_is_xri($claimed_id)) {
+    $xrds_url = 'http://xri.net/'. $claimed_id;
   }
-  elseif ($url['scheme'] == 'http' || $url['scheme'] == 'https') {
+  $url = @parse_url($xrds_url);
+  if ($url['scheme'] == 'http' || $url['scheme'] == 'https') {
     // For regular URLs, try Yadis resolution first, then HTML-based discovery
     $headers = array('Accept' => 'application/xrds+xml');
-    $result = drupal_http_request($claimed_id, $headers);
+    $result = drupal_http_request($xrds_url, $headers);
 
-    if ($result->headers['Content-Type'] == 'application/xrds+xml') {
-      // Parse XML document to find URL
-      $services = xrds_parse($result->data);
-    }
-    else {
-      if (isset($result->headers['X-XRDS-Location'])) {
-        $xrds_url = $result->headers['X-XRDS-Location'];
+    if (!isset($result->error)) {
+      if (isset($result->headers['Content-Type']) && preg_match("/application\/xrds\+xml/", $result->headers['Content-Type'])) {
+        // Parse XML document to find URL
+        $services = xrds_parse($result->data);
       }
       else {
-        // Look for meta http-equiv link in HTML head
-        $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
+        $xrds_url = NULL;
+        if (isset($result->headers['X-XRDS-Location'])) {
+          $xrds_url = $result->headers['X-XRDS-Location'];
+        }
+        else {
+          // Look for meta http-equiv link in HTML head
+          $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
+        }
+        if (!empty($xrds_url)) {
+          $headers = array('Accept' => 'application/xrds+xml');
+          $xrds_result = drupal_http_request($xrds_url, $headers);
+          if (!isset($xrds_result->error)) {
+            $services = xrds_parse($xrds_result->data);
+          }
+        }
       }
-    }
 
-    if (count($services) == 0 && $xrds_url) {
-      $headers = array('Accept' => 'application/xrds+xml');
-      $result = drupal_http_request($xrds_url, $headers);
-      $services = xrds_parse($result->data);
-    }
-    else {
-      $services[] = array('uri' => _openid_link_href('openid.server', $result->data),
-                          'delegate' => _openid_link_href('openid.delegate', $result->data));
+      // Check for HTML delegation
+      if (count($services) == 0) {
+        // Look for 2.0 links
+        $uri = _openid_link_href('openid2.provider', $result->data);
+        $delegate = _openid_link_href('openid2.local_id', $result->data);
+        $version = 2;
+        
+        // 1.0 links
+        if (empty($uri)) {
+          $uri = _openid_link_href('openid.server', $result->data);
+          $delegate = _openid_link_href('openid.delegate', $result->data);
+          $version = 1;
+        }
+        if (!empty($uri)) {
+          $services[] = array('uri' => $uri, 'delegate' => $delegate, 'version' => $version);
+        }
+      }
     }
   }
-
   return $services;
 }
 
-function openid_association($claimed_id, $idp_endpoint) {
+/**
+ * Attempt to create a shared secret with the OpenID Provider.
+ *
+ * @param $op_endpoint URL of the OpenID Provider endpoint.
+ *
+ * @return $assoc_handle The association handle.
+ */
+function openid_association($op_endpoint) {
+  include_once drupal_get_path('module', 'openid') .'/openid.inc';
+
   // Remove Old Associations:
   db_query("DELETE FROM {openid_association} WHERE created + expires_in < %d", time());
 
   // Check to see if we have an association for this IdP already
-  $assoc_handle = db_result(db_query("SELECT assoc_handle FROM {openid_association} WHERE idp_endpoint_uri = '%s'", $idp_endpoint));
+  $assoc_handle = db_result(db_query("SELECT assoc_handle FROM {openid_association} WHERE idp_endpoint_uri = '%s'", $op_endpoint));
   if (empty($assoc_handle)) {
     $mod = OPENID_DH_DEFAULT_MOD;
     $gen = OPENID_DH_DEFAULT_GEN;
@@ -251,10 +396,13 @@
     $assoc_request = openid_association_request($public);
     $assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
     $assoc_headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
-    $assoc_result = drupal_http_request($idp_endpoint, $assoc_headers, 'POST', $assoc_message);
+    $assoc_result = drupal_http_request($op_endpoint, $assoc_headers, 'POST', $assoc_message);
+    if (isset($assoc_result->error)) {
+      return FALSE;
+    }
     
     $assoc_response = _openid_parse_message($assoc_result->data);
-    if ($assoc_response['mode'] == 'error') {
+    if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
         return FALSE;
     }
 
@@ -265,7 +413,7 @@
       $assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
     }
     db_query("INSERT INTO {openid_association} (idp_endpoint_uri, session_type, assoc_handle, assoc_type, expires_in, mac_key, created) VALUES('%s', '%s', '%s', '%s', %d, '%s', %d)",
-             $idp_endpoint, $assoc_response['session_type'], $assoc_response['assoc_handle'], $assoc_response['assoc_type'], $assoc_response['expires_in'], $assoc_response['mac_key'], time());
+             $op_endpoint, $assoc_response['session_type'], $assoc_response['assoc_handle'], $assoc_response['assoc_type'], $assoc_response['expires_in'], $assoc_response['mac_key'], time());
     
     $assoc_handle = $assoc_response['assoc_handle'];
   }
@@ -273,64 +421,71 @@
   return $assoc_handle;
 }
 
-function openid_authentication_page() {
-  _openid_fix_post($_REQUEST);
-
-  $idp_endpoint = $_SESSION['openid_idp_endpoint'];
-  unset($_SESSION['openid_idp_endpoint']);
-  
-  if ($idp_endpoint) {
-    if (openid_verify_assertion($idp_endpoint, $_REQUEST)) {
-      openid_authentication($_REQUEST);
-    }
-    else {
-      drupal_set_message(t('OpenID assertion failed'), 'error');
-    }
-  }
-  else {
-    drupal_set_message(t('OpenID session invalid'), 'error');
-  }
-  drupal_goto();
-}
-
-
+/**
+ * Authenticate a user or attempt registration.
+ *
+ * @param $response Response values from the OpenID Provider.
+ */
 function openid_authentication($response) {
+  include_once drupal_get_path('module', 'openid') .'/openid.inc';
+
   $identity = $response['openid.identity'];
 
   $account = user_external_load($identity);
-  if ($account->uid) {
-    global $user;
-    $user = $account;
+  if (isset($account->uid)) {
+    if (!variable_get('user_email_verification', TRUE) || $account->login) {
+      global $user;
+      $user = $account;
+      user_login_submit('user_login', array());
+    }
+    else {
+      drupal_set_message(t('You must validate your email address for this account before logging in via OpenID'));
+    }
   }
-  else {
+  elseif (variable_get('user_register', 1)) {
     // Register new user
-    $edit['name'] = $identity;
+    $form = drupal_retrieve_form('user_register');
+    $edit['name'] = (empty($response['openid.sreg.nickname'])) ? $identity : $response['openid.sreg.nickname'];
+    $edit['mail'] = (empty($response['openid.sreg.email'])) ? '' : $response['openid.sreg.email'];
     $edit['pass']  = user_password();
-    $edit['status'] = 1;
+    $edit['status'] = variable_get('user_register', 1) == 1;
+    $edit['response'] = $response;
     $edit['auth_openid'] = $identity;
-    $edit['openid'] = $response;
-    
-    // Build up the new user array an then call user_save().
-    user_module_invoke('submit', $edit, $account);
-    unset($edit['openid']);
-    $new_user = user_save('', $edit);
-    if ($new_user && $new_user->uid > 0) {
-      global $user;
-      $user = $new_user;
-      user_login_submit('', '');
+    $form['#post'] = $edit;
+    drupal_prepare_form('user_register', $form);
+    drupal_validate_form('user_register', $form);
+    if (form_get_errors()) {
+      // We were unable to register a valid new user, redirect to standard
+      // user/register and prefill with the values we received.
+      drupal_set_message(t('OpenID registration failed for the reasons listed. You may register now, or if you already have an account you can <a href="@login">log in</a> now and add your OpenID under "My Account"', array('@login' => url('user/login'))), 'error');
+       $_SESSION['openid'] = $edit;
+      // We'll want to redirect back to the same place.
+      $destination = drupal_get_destination();
+      unset($_REQUEST['destination']);
+      drupal_goto('user/register', $destination);
     }
     else {
-      drupal_set_message(t('Unable to create the account'), 'error');
+      unset($edit['response']);
+      $account = user_save('', $edit);
+      global $user;
+      $user = $account;
+      user_login_submit('user_login', array());
     }
   }
+  else {
+    drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
+  }
+  drupal_goto();
 }
 
 function openid_association_request($public) {
+  include_once drupal_get_path('module', 'openid') .'/openid.inc';
+
   $request = array(
-    'openid.ns' => 'http://openid.net/signon/2.0',
+    'openid.ns' => OPENID_NS_2_0,
     'openid.mode' => 'associate',
-    'openid.session_type' => variable_get('openid_session_type', 'DH-SHA1'),
-    'openid.assoc_type' => variable_get('openid_assoc_type', 'HMAC-SHA1')
+    'openid.session_type' => 'DH-SHA1',
+    'openid.assoc_type' => 'HMAC-SHA1'
   );
 
   if ($request['openid.session_type'] == 'DH-SHA1' || $request['openid.session_type'] == 'DH-SHA256') {
@@ -341,41 +496,52 @@
   return $request;
 }
 
-function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '') {
+function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $version = 2) {
+  global $base_url;
+  include_once drupal_get_path('module', 'openid') .'/openid.inc';
+
   $realm = '';
   if ($return_to != '') {
-    $return_to_url = parse_url($return_to);
-    if ($return_to_url) {
-      $realm = $return_to_url['scheme'] . '://' . $return_to_url['host'] . '/*';
-    }
+    $realm = $base_url;
   }
 
+  $ns = ($version == 2) ? OPENID_NS_2_0 : OPENID_NS_1_0;
   $request =  array(
-    'openid.ns' => 'http://openid.net/signon/2.0',
-    'openid.mode' => variable_get('openid_request_mode', 'checkid_setup'),
+    'openid.ns' => $ns,
+    'openid.mode' => 'checkid_setup',
     'openid.identity' => $identity,
     'openid.claimed_id' => $claimed_id,
     'openid.assoc_handle' => $assoc_handle,
     'openid.return_to' => $return_to,
-    'openid.realm' => $realm // 10.2. Realms, default: $return_to
-  );
+    );
+
+  if ($version == 2) {
+    $request['openid.realm'] = $realm;
+  }
+  else {
+    $request['openid.trust_root'] = $realm;
+  }
+
+  // Simple Registration
+  $request['openid.sreg.required'] = 'nickname,email';
+  $request['openid.ns.sreg'] = "http://openid.net/extensions/sreg/1.1";
+  
   $request = array_merge($request, module_invoke_all('openid', 'request', $request));
 
   return $request;
 }
 
-function openid_check_authentication($idp_uri, $response_fields) {
- if (isset($response_fields['openid.mode'])) {
-   unset($response_fields['openid.mode']);
- }
-
- $request = array('openid.mode' => 'check_authentication');
- foreach ($response_fields as $key => $value) {
-   $request[$key] = $value;
- }
-}
+/**
+ * Attempt to verify the response received from the OpenID Provider.
+ *
+ * @param $op_endpoint The OpenID Provider URL.
+ * @param $response Array of repsonse values from the provider.
+ *
+ * @return boolean
+ */
+function openid_verify_assertion($op_endpoint, $response) {
+  include_once drupal_get_path('module', 'openid') .'/openid.inc';
 
-function openid_verify_assertion($idp_endpoint_uri, $response) {
   $valid = FALSE;
   
   $association = db_fetch_object(db_query("SELECT * FROM {openid_association} WHERE assoc_handle = '%s'", $response['openid.assoc_handle']));
@@ -385,23 +551,18 @@
     if ($self_sig == $response['openid.sig']) {
       $valid = TRUE;
     }
-    else {
-      $valid = FALSE;
-    }
   }
   else {
-    // Make the IdP do the verification
     $request = $response;
     $request['openid.mode'] = 'check_authentication';
     $message = _openid_create_message($request);
     $headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
-    $result = drupal_http_request($idp_endpoint_uri, $headers, 'POST', _openid_encode_message($message));
-    $response = _openid_parse_message($result->data);
-    if (strtolower(trim($response['is_valid'])) == 'true') {
-      $valid = TRUE;
-    }
-    else {
-      $valid = FALSE;
+    $result = drupal_http_request($op_endpoint, $headers, 'POST', _openid_encode_message($message));
+    if (!isset($result->error)) {
+      $response = _openid_parse_message($result->data);
+      if (strtolower(trim($response['is_valid'])) == 'true') {
+        $valid = TRUE;
+      }
     }
   }
 
Index: openid_server.info
===================================================================
RCS file: openid_server.info
diff -N openid_server.info
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ openid_server.info	21 Jan 2008 05:35:45 -0000
@@ -0,0 +1,4 @@
+; $Id$
+name = OpenID Server
+description = Allows Drupal to act as an OpenID server.
+package = OpenID
Index: openid_server.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/openid/Attic/openid_server.install,v
retrieving revision 1.1.2.4
diff -u -u -r1.1.2.4 openid_server.install
--- openid_server.install	19 Feb 2007 03:07:09 -0000	1.1.2.4
+++ openid_server.install	21 Jan 2008 05:35:45 -0000
@@ -43,3 +43,18 @@
       break;
   }
 }
+
+function openid_server_uninstall() {
+  switch ($GLOBALS['db_type']) {
+    case 'mysql':
+    case 'mysqli':
+      db_query("DROP TABLE IF EXISTS {openid_server_relying_party}");
+      db_query("DROP TABLE IF EXISTS {openid_server_association}");
+      break;
+
+    case 'pgsql': 
+      db_query("DROP TABLE {openid_server_relying_party}");
+      db_query("DROP TABLE {openid_server_association}");
+      break;
+  }
+} 
Index: openid_server.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/openid/Attic/openid_server.module,v
retrieving revision 1.1.2.7
diff -u -u -r1.1.2.7 openid_server.module
--- openid_server.module	19 Feb 2007 03:08:26 -0000	1.1.2.7
+++ openid_server.module	21 Jan 2008 05:35:46 -0000
@@ -21,6 +21,13 @@
 
   if ($may_cache) {
     $items[] = array(
+      'path' => 'admin/settings/openid-server',
+      'title' => t('OpenID Server'),
+      'callback' => 'drupal_get_form',
+      'callback arguments' => array('openid_server_settings'),
+    );
+
+    $items[] = array(
       'path' => 'openid/server',
       'title' => t('OpenID Login'),
       'callback' => 'openid_server_endpoint',
@@ -86,8 +93,8 @@
     '#type' => 'checkbox',
     '#title' => t('Allow users to delegate their OpenID to another server'),
     '#default_value' => variable_get('openid_delegate_enabled', 0));
-  
-  return $form;
+   
+  return system_settings_form($form);
 }
 
 /**
@@ -101,7 +108,7 @@
       }
       $items[] = array(
           'title' => t('OpenID'),
-          'value' => t('You may login to other OpenID enabled sites using %url', array('%url' => theme('placeholder', url('user/' . $account->uid, NULL, NULL, TRUE))))
+          'value' => t('You may login to other OpenID enabled sites using %url', array('%url' =>  url('user/' . $account->uid, NULL, NULL, TRUE)))
           );
                                    
       return array('' => $items);
@@ -171,14 +178,14 @@
   $rows = array();
   foreach (element_children($form) as $key) {
     $row = array();
-    $row[] = form_render($form[$key]['realm']);
-    $row[] = form_render($form[$key]['last_time']);
-    $row[] = form_render($form[$key]['auto_release']);
+    $row[] = drupal_render($form[$key]['realm']);
+    $row[] = drupal_render($form[$key]['last_time']);
+    $row[] = drupal_render($form[$key]['auto_release']);
     $rows[] = $row;
   }
   
   $output = theme('table', $header, $rows);
-  $output .= form_render($form);
+  $output .= drupal_render($form);
 
   return $output;
 }
@@ -466,10 +473,10 @@
       $response = _openid_server_sign($response);
       $message = _openid_create_message($response);
       $message_encoded = _openid_encode_message($message);
-      return openid_redirect_form($request['openid.return_to'], $message);
+      return openid_redirect($request['openid.return_to'], $message);
     }
     else {
-      return openid_server_form($request, $response);
+      return drupal_get_form('openid_server_form', $request, $response);
     }
   }
 }
@@ -550,7 +557,7 @@
   if (isset($_SESSION['openidrequest'])) {
     $message = _openid_create_message($_SESSION['openidrequest']);
     unset($_SESSION['openidrequest']);
-    openid_redirect_form(url('openid/server', NULL, NULL, TRUE), $message);
+    openid_redirect(url('openid/server', NULL, NULL, TRUE), $message);
   }
 }
 
@@ -599,8 +606,7 @@
     '#value' => t('OK'));
 
   $form['#action'] = url('openid/send');
-  $content = drupal_get_form('openid_server_form', $form);
-  return $content;
+  return $form;
 }
 
 /**
@@ -653,7 +659,7 @@
 
   $response = _openid_server_sign($response);
   $message = _openid_create_message($response);
-  openid_redirect_form($response['openid.return_to'], $message);
+  openid_redirect($response['openid.return_to'], $message);
 }
 
 function _openid_server_sign($response) {
Index: xrds.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/openid/xrds.inc,v
retrieving revision 1.1.2.1
diff -u -u -r1.1.2.1 xrds.inc
--- xrds.inc	17 Jan 2007 20:10:40 -0000	1.1.2.1
+++ xrds.inc	21 Jan 2008 05:35:46 -0000
@@ -1,5 +1,5 @@
 <?php
-// $Id: xrds.inc,v 1.1.2.1 2007/01/17 20:10:40 walkah Exp $
+// $Id: xrds.inc,v 1.2.2.3 2007/10/14 20:29:27 walkah Exp $
 
 // Global variables to track parsing state
 $xrds_open_elements = array();
@@ -36,7 +36,17 @@
 
   $name = _xrds_strip_namespace($name);
   if ($name == 'SERVICE') {
-    $xrds_services[] = $xrds_current_service;
+    if (in_array(OPENID_NS_2_0 .'/signon', $xrds_current_service['types']) ||
+        in_array(OPENID_NS_2_0 .'/server', $xrds_current_service['types'])) {
+      $xrds_current_service['version'] = 2;
+    }
+    elseif (in_array(OPENID_NS_1_1, $xrds_current_service['types']) ||
+            in_array(OPENID_NS_1_0, $xrds_current_service['types'])) {
+      $xrds_current_service['version'] = 1;
+    }
+    if (!empty($xrds_current_service['version'])) {
+      $xrds_services[] = $xrds_current_service;
+    }
     $xrds_current_service = array();
   }
   array_pop($xrds_open_elements);
@@ -55,6 +65,9 @@
     case 'XRDS/XRD/SERVICE/DELEGATE':
       $xrds_current_service['delegate'] = $data;
       break;
+    case 'XRDS/XRD/SERVICE/LOCALID':
+      $xrds_current_service['localid'] = $data;
+      break;
   }
 }
 
