diff --git a/admin.php b/admin.php index 6162ca4..5dc38f9 100644 --- a/admin.php +++ b/admin.php @@ -1,142 +1,142 @@ - -
-

- -
- -

-

-

%1$s Application List', 'social_connect'), 'Facebook', 'https://developers.facebook.com/apps/'); ?>

-

-
    -
  1. Facebook Application Setup page', 'social_connect'), 'https://developers.facebook.com/apps/'); ?>
  2. -
  3. Facebook Application List', 'social_connect'), 'https://developers.facebook.com/apps/'); ?>
  4. -
  5. -
- - - - - - - - - - - - - - -
- />
- -
- -

-

API Key and a API Secret.', 'social_connect'); ?>

-

%1$s Application List', 'social_connect'), 'Twitter', 'https://dev.twitter.com/apps'); ?>

-

Register an Application and fill the form with the details below:', 'social_connect'), 'http://dev.twitter.com/apps/new'); ?>

-
    -
  1. %1$s', 'social_connect'), SOCIAL_CONNECT_PLUGIN_URL . '/twitter/callback.php'); ?>
  2. -
  3. Read-only', 'social_connect'); ?>
  4. -
- - - - - - - - - - - - - -
- />
- Please check with your domain administrator as this may require changes to your mail server.', 'social_connect'); ?> -
- -

-

Client ID and a Client Secret.', 'social_connect'); ?>

-

Google+ Project List', 'social_connect'), 'https://console.developers.google.com/project'); ?>

-

Create a project, enable Google+ API and create a new Client ID with the details below:', 'social_connect'), 'https://console.developers.google.com/project'); ?>

-
    -
  1. Web Application', 'social_connect'); ?>
  2. -
  3. <YOUR SITE DOMAIN>', 'social_connect'); ?>
  4. -
  5. %1$s', 'social_connect'), SOCIAL_CONNECT_GOOGLE_PLUS_REDIRECT_URL); ?>
  6. -
- - - - - - - - - - - - - -
- />
-
- -

-

- - - - - - - - - - - - - -
deprecated)', 'social_connect'), 'https://developers.google.com/+/api/auth-migration'); ?> - /> -
Yahoo - /> -
WordPress.com - /> -
- -

- -

-
-
+
+

+ +
+ +

+

+

%1$s Application List', 'social_connect'), 'Facebook', 'https://developers.facebook.com/apps/'); ?>

+

+
    +
  1. Facebook Application Setup page', 'social_connect'), 'https://developers.facebook.com/apps/'); ?>
  2. +
  3. Facebook Application List', 'social_connect'), 'https://developers.facebook.com/apps/'); ?>
  4. +
  5. +
+ + + + + + + + + + + + + + +
+ />
+ +
+ +

+

API Key and a API Secret.', 'social_connect'); ?>

+

%1$s Application List', 'social_connect'), 'Twitter', 'https://dev.twitter.com/apps'); ?>

+

Register an Application and fill the form with the details below:', 'social_connect'), 'http://dev.twitter.com/apps/new'); ?>

+
    +
  1. %1$s', 'social_connect'), SOCIAL_CONNECT_PLUGIN_URL . '/twitter/callback.php'); ?>
  2. +
  3. Read-only', 'social_connect'); ?>
  4. +
+ + + + + + + + + + + + + +
+ />
+ Please check with your domain administrator as this may require changes to your mail server.', 'social_connect'); ?> +
+ +

+

Client ID and a Client Secret.', 'social_connect'); ?>

+

Google+ Project List', 'social_connect'), 'https://console.developers.google.com/project'); ?>

+

Create a project, enable Google+ API and create a new Client ID with the details below:', 'social_connect'), 'https://console.developers.google.com/project'); ?>

+
    +
  1. Web Application', 'social_connect'); ?>
  2. +
  3. <YOUR SITE DOMAIN>', 'social_connect'); ?>
  4. +
  5. %1$s', 'social_connect'), SOCIAL_CONNECT_GOOGLE_PLUS_REDIRECT_URL); ?>
  6. +
+ + + + + + + + + + + + + +
+ />
+
+ +

+

+ + + + + + + + + + + + + +
deprecated)', 'social_connect'), 'https://developers.google.com/+/api/auth-migration'); ?> + /> +
Yahoo + /> +
WordPress.com + /> +
+ +

+ +

+
+
$wordpress_enabled ) ); -} -add_action( 'login_enqueue_scripts', 'sc_add_javascripts' ); -add_action( 'wp_enqueue_scripts', 'sc_add_javascripts' ); + $wordpress_enabled ) ); +} +add_action( 'login_enqueue_scripts', 'sc_add_javascripts' ); +add_action( 'wp_enqueue_scripts', 'sc_add_javascripts' ); diff --git a/openid/openid.php b/openid/openid.php index 126896b..50b0505 100644 --- a/openid/openid.php +++ b/openid/openid.php @@ -1,706 +1,706 @@ - -* $openid = new LightOpenID; -* $openid->identity = 'ID supplied by user'; -* header('Location: ' . $openid->authUrl()); -* -* The provider then sends various parameters via GET, one of them is openid_mode. -* Step two is verification: -* -* if ($this->data['openid_mode']) { -* $openid = new LightOpenID; -* echo $openid->validate() ? 'Logged in.' : 'Failed'; -* } -* -* -* Optionally, you can set $returnUrl and $realm (or $trustRoot, which is an alias). -* The default values for those are: -* $openid->realm = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']; -* $openid->returnUrl = $openid->realm . $_SERVER['REQUEST_URI']; # without the query part, if present -* If you don't know their meaning, refer to any openid tutorial, or specification. Or just guess. -* -* AX and SREG extensions are supported. -* To use them, specify $openid->required and/or $openid->optional before calling $openid->authUrl(). -* These are arrays, with values being AX schema paths (the 'path' part of the URL). -* For example: -* $openid->required = array('namePerson/friendly', 'contact/email'); -* $openid->optional = array('namePerson/first'); -* If the server supports only SREG or OpenID 1.1, these are automaticaly -* mapped to SREG names, so that user doesn't have to know anything about the server. -* -* To get the values, use $openid->getAttributes(). -* -* -* The library requires PHP >= 5.1.2 with curl or http/https stream wrappers enabled.. -* @author Mewp -* @copyright Copyright (c) 2010, Mewp -* @license http://www.opensource.org/licenses/mit-license.php MIT -*/ -class LightOpenID -{ - public $returnUrl - , $required = array() - , $optional = array(); - private $identity, $claimed_id; - protected $server, $version, $trustRoot, $aliases, $identifier_select = false - , $ax = false, $sreg = false, $data; - static protected $ax_to_sreg = array( - 'namePerson/friendly' => 'nickname', - 'contact/email' => 'email', - 'namePerson' => 'fullname', - 'birthDate' => 'dob', - 'person/gender' => 'gender', - 'contact/postalCode/home' => 'postcode', - 'contact/country/home' => 'country', - 'pref/language' => 'language', - 'pref/timezone' => 'timezone', - ); - - function __construct() - { - $this->trustRoot = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']; - $uri = $_SERVER['REQUEST_URI']; - $uri = strpos($uri, '?') ? substr($uri, 0, strpos($uri, '?')) : $uri; - $this->returnUrl = $this->trustRoot . $uri; - - $this->data = $_POST + $_GET; # OPs may send data as POST or GET. - } - - function __set($name, $value) - { - switch ($name) { - case 'identity': - if (strlen($value = trim((String) $value))) { - if (preg_match('#^xri:/*#i', $value, $m)) { - $value = substr($value, strlen($m[0])); - } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) { - $value = "http://$value"; - } - if (preg_match('#^https?://[^/]+$#i', $value, $m)) { - $value .= '/'; - } - } - $this->$name = $this->claimed_id = $value; - break; - case 'trustRoot': - case 'realm': - $this->trustRoot = trim($value); - } - } - - function __get($name) - { - switch ($name) { - case 'identity': - # We return claimed_id instead of identity, - # because the developer should see the claimed identifier, - # i.e. what he set as identity, not the op-local identifier (which is what we verify) - return $this->claimed_id; - case 'trustRoot': - case 'realm': - return $this->trustRoot; - } - } - - /** - * Checks if the server specified in the url exists. - * - * @param $url url to check - * @return true, if the server exists; false otherwise - */ - function hostExists($url) - { - if (strpos($url, '/') === false) { - $server = $url; - } else { - $server = @parse_url($url, PHP_URL_HOST); - } - - if (!$server) { - return false; - } - - return !!gethostbynamel($server); - } - - protected function request_curl($url, $method='GET', $params=array()) - { - $params = http_build_query($params, '', '&'); - $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : '')); - curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($curl, CURLOPT_HEADER, false); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*')); - if ($method == 'POST') { - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $params); - } elseif ($method == 'HEAD') { - curl_setopt($curl, CURLOPT_HEADER, true); - curl_setopt($curl, CURLOPT_NOBODY, true); - } else { - curl_setopt($curl, CURLOPT_HTTPGET, true); - } - $response = curl_exec($curl); - - if($method == 'HEAD') { - $headers = array(); - foreach(explode("\n", $response) as $header) { - $pos = strpos($header,':'); - $name = strtolower(trim(substr($header, 0, $pos))); - $headers[$name] = trim(substr($header, $pos+1)); - } - - # Updating claimed_id in case of redirections. - $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); - if($effective_url != $url) { - $this->claimed_id = $effective_url; - } - - return $headers; - } - - if (curl_errno($curl)) { - throw new ErrorException(curl_error($curl), curl_errno($curl)); - } - - return $response; - } - - protected function request_streams($url, $method='GET', $params=array()) - { - if(!$this->hostExists($url)) { - throw new ErrorException('Invalid request.'); - } - - $params = http_build_query($params, '', '&'); - switch($method) { - case 'GET': - $opts = array( - 'http' => array( - 'method' => 'GET', - 'header' => 'Accept: application/xrds+xml, */*', - 'ignore_errors' => true, - ) - ); - $url = $url . ($params ? '?' . $params : ''); - break; - case 'POST': - $opts = array( - 'http' => array( - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', - 'content' => $params, - 'ignore_errors' => true, - ) - ); - break; - case 'HEAD': - # We want to send a HEAD request, - # but since get_headers doesn't accept $context parameter, - # we have to change the defaults. - $default = stream_context_get_options(stream_context_get_default()); - stream_context_get_default( - array('http' => array( - 'method' => 'HEAD', - 'header' => 'Accept: application/xrds+xml, */*', - 'ignore_errors' => true, - )) - ); - - $url = $url . ($params ? '?' . $params : ''); - $headers_tmp = get_headers ($url); - if(!$headers_tmp) { - return array(); - } - - # Parsing headers. - $headers = array(); - foreach($headers_tmp as $header) { - $pos = strpos($header,':'); - $name = strtolower(trim(substr($header, 0, $pos))); - $headers[$name] = trim(substr($header, $pos+1)); - - # Following possible redirections. The point is just to have - # claimed_id change with them, because get_headers() will - # follow redirections automatically. - # We ignore redirections with relative paths. - # If any known provider uses them, file a bug report. - if($name == 'location') { - if(strpos($headers[$name], 'http') === 0) { - $this->claimed_id = $headers[$name]; - } elseif($headers[$name][0] == '/') { - $parsed_url = parse_url($this->claimed_id); - $this->claimed_id = $parsed_url['scheme'] . '://' - . $parsed_url['host'] - . $headers[$name]; - } - } - } - - # And restore them. - stream_context_get_default($default); - return $headers; - } - $context = stream_context_create ($opts); - - return file_get_contents($url, false, $context); - } - - protected function request($url, $method='GET', $params=array()) - { - if(function_exists('curl_init') && !ini_get('safe_mode')) { - return $this->request_curl($url, $method, $params); - } - return $this->request_streams($url, $method, $params); - } - - protected function build_url($url, $parts) - { - if (isset($url['query'], $parts['query'])) { - $parts['query'] = $url['query'] . '&' . $parts['query']; - } - - $url = $parts + $url; - $url = $url['scheme'] . '://' - . (empty($url['username'])?'' - :(empty($url['password'])? "{$url['username']}@" - :"{$url['username']}:{$url['password']}@")) - . $url['host'] - . (empty($url['port'])?'':":{$url['port']}") - . (empty($url['path'])?'':$url['path']) - . (empty($url['query'])?'':"?{$url['query']}") - . (empty($url['fragment'])?'':":{$url['fragment']}"); - return $url; - } - - /** - * Helper function used to scan for / tags and extract information - * from them - */ - protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName) - { - preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1); - preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2); - - $result = array_merge($matches1[1], $matches2[1]); - return empty($result)?false:$result[0]; - } - - /** - * Performs Yadis and HTML discovery. Normally not used. - * @param $url Identity URL. - * @return String OP Endpoint (i.e. OpenID provider address). - * @throws ErrorException - */ - function discover($url) - { - if (!$url) throw new ErrorException('No identity supplied.'); - # Use xri.net proxy to resolve i-name identities - if (!preg_match('#^https?:#', $url)) { - $url = "https://xri.net/$url"; - } - - # We save the original url in case of Yadis discovery failure. - # It can happen when we'll be lead to an XRDS document - # which does not have any OpenID2 services. - $originalUrl = $url; - - # A flag to disable yadis discovery in case of failure in headers. - $yadis = true; - - # We'll jump a maximum of 5 times, to avoid endless redirections. - for ($i = 0; $i < 5; $i ++) { - if ($yadis) { - $headers = $this->request($url, 'HEAD'); - - $next = false; - if (isset($headers['x-xrds-location'])) { - $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location']))); - $next = true; - } - - if (isset($headers['content-type']) - && strpos($headers['content-type'], 'application/xrds+xml') !== false - ) { - # Found an XRDS document, now let's find the server, and optionally delegate. - $content = $this->request($url, 'GET'); - - preg_match_all('#(.*?)#s', $content, $m); - foreach($m[1] as $content) { - $content = ' ' . $content; # The space is added, so that strpos doesn't return 0. - - # OpenID 2 - $ns = preg_quote('http://specs.openid.net/auth/2.0/'); - if(preg_match('#\s*'.$ns.'(server|signon)\s*#s', $content, $type)) { - if ($type[1] == 'server') $this->identifier_select = true; - - preg_match('#(.*)#', $content, $server); - preg_match('#<(Local|Canonical)ID>(.*)#', $content, $delegate); - if (empty($server)) { - return false; - } - # Does the server advertise support for either AX or SREG? - $this->ax = (bool) strpos($content, 'http://openid.net/srv/ax/1.0'); - $this->sreg = strpos($content, 'http://openid.net/sreg/1.0') - || strpos($content, 'http://openid.net/extensions/sreg/1.1'); - - $server = $server[1]; - if (isset($delegate[2])) $this->identity = trim($delegate[2]); - $this->version = 2; - - $this->server = $server; - return $server; - } - - # OpenID 1.1 - $ns = preg_quote('http://openid.net/signon/1.1'); - if (preg_match('#\s*'.$ns.'\s*#s', $content)) { - - preg_match('#(.*)#', $content, $server); - preg_match('#<.*?Delegate>(.*)#', $content, $delegate); - if (empty($server)) { - return false; - } - # AX can be used only with OpenID 2.0, so checking only SREG - $this->sreg = strpos($content, 'http://openid.net/sreg/1.0') - || strpos($content, 'http://openid.net/extensions/sreg/1.1'); - - $server = $server[1]; - if (isset($delegate[1])) $this->identity = $delegate[1]; - $this->version = 1; - - $this->server = $server; - return $server; - } - } - - $next = true; - $yadis = false; - $url = $originalUrl; - $content = null; - break; - } - if ($next) continue; - - # There are no relevant information in headers, so we search the body. - $content = $this->request($url, 'GET'); - if ($location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content')) { - $url = $this->build_url(parse_url($url), parse_url($location)); - continue; - } - } - - if (!$content) $content = $this->request($url, 'GET'); - - # At this point, the YADIS Discovery has failed, so we'll switch - # to openid2 HTML discovery, then fallback to openid 1.1 discovery. - $server = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href'); - $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href'); - $this->version = 2; - - if (!$server) { - # The same with openid 1.1 - $server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href'); - $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href'); - $this->version = 1; - } - - if ($server) { - # We found an OpenID2 OP Endpoint - if ($delegate) { - # We have also found an OP-Local ID. - $this->identity = $delegate; - } - $this->server = $server; - return $server; - } - - throw new ErrorException('No servers found!'); - } - throw new ErrorException('Endless redirection!'); - } - - protected function sregParams() - { - $params = array(); - # We always use SREG 1.1, even if the server is advertising only support for 1.0. - # That's because it's fully backwards compatibile with 1.0, and some providers - # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com - $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1'; - if ($this->required) { - $params['openid.sreg.required'] = array(); - foreach ($this->required as $required) { - if (!isset(self::$ax_to_sreg[$required])) continue; - $params['openid.sreg.required'][] = self::$ax_to_sreg[$required]; - } - $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']); - } - - if ($this->optional) { - $params['openid.sreg.optional'] = array(); - foreach ($this->optional as $optional) { - if (!isset(self::$ax_to_sreg[$optional])) continue; - $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional]; - } - $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']); - } - return $params; - } - - protected function axParams() - { - $params = array(); - if ($this->required || $this->optional) { - $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0'; - $params['openid.ax.mode'] = 'fetch_request'; - $this->aliases = array(); - $counts = array(); - $required = array(); - $optional = array(); - foreach (array('required','optional') as $type) { - foreach ($this->$type as $alias => $field) { - if (is_int($alias)) $alias = strtr($field, '/', '_'); - $this->aliases[$alias] = 'http://axschema.org/' . $field; - if (empty($counts[$alias])) $counts[$alias] = 0; - $counts[$alias] += 1; - ${$type}[] = $alias; - } - } - foreach ($this->aliases as $alias => $ns) { - $params['openid.ax.type.' . $alias] = $ns; - } - foreach ($counts as $alias => $count) { - if ($count == 1) continue; - $params['openid.ax.count.' . $alias] = $count; - } - - # Don't send empty ax.requied and ax.if_available. - # Google and possibly other providers refuse to support ax when one of these is empty. - if($required) { - $params['openid.ax.required'] = implode(',', $required); - } - if($optional) { - $params['openid.ax.if_available'] = implode(',', $optional); - } - } - return $params; - } - - protected function authUrl_v1() - { - $returnUrl = $this->returnUrl; - # If we have an openid.delegate that is different from our claimed id, - # we need to somehow preserve the claimed id between requests. - # The simplest way is to just send it along with the return_to url. - if($this->identity != $this->claimed_id) { - $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id; - } - - $params = array( - 'openid.return_to' => $returnUrl, - 'openid.mode' => 'checkid_setup', - 'openid.identity' => $this->identity, - 'openid.trust_root' => $this->trustRoot, - ) + $this->sregParams(); - - return $this->build_url(parse_url($this->server) - , array('query' => http_build_query($params, '', '&'))); - } - - protected function authUrl_v2($identifier_select) - { - $params = array( - 'openid.ns' => 'http://specs.openid.net/auth/2.0', - 'openid.mode' => 'checkid_setup', - 'openid.return_to' => $this->returnUrl, - 'openid.realm' => $this->trustRoot, - ); - if ($this->ax) { - $params += $this->axParams(); - } - if ($this->sreg) { - $params += $this->sregParams(); - } - if (!$this->ax && !$this->sreg) { - # If OP doesn't advertise either SREG, nor AX, let's send them both - # in worst case we don't get anything in return. - $params += $this->axParams() + $this->sregParams(); - } - - if ($identifier_select) { - $params['openid.identity'] = $params['openid.claimed_id'] - = 'http://specs.openid.net/auth/2.0/identifier_select'; - } else { - $params['openid.identity'] = $this->identity; - $params['openid.claimed_id'] = $this->claimed_id; - } - - return $this->build_url(parse_url($this->server) - , array('query' => http_build_query($params, '', '&'))); - } - - /** - * Returns authentication url. Usually, you want to redirect your user to it. - * @return String The authentication url. - * @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1. - * @throws ErrorException - */ -function authUrl($identifier_select = null) -{ - if (!$this->server) $this->discover($this->identity); - - if ($this->version == 2) { - if ($identifier_select === null) { - return $this->authUrl_v2($this->identifier_select); - } - return $this->authUrl_v2($identifier_select); - } - return $this->authUrl_v1(); -} - -/** -* Performs OpenID verification with the OP. -* @return Bool Whether the verification was successful. -* @throws ErrorException -*/ -function validate() -{ - $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity']; - $params = array( - 'openid.assoc_handle' => $this->data['openid_assoc_handle'], - 'openid.signed' => $this->data['openid_signed'], - 'openid.sig' => $this->data['openid_sig'], - ); - - if (isset($this->data['openid_ns'])) { - # We're dealing with an OpenID 2.0 server, so let's set an ns - # Even though we should know location of the endpoint, - # we still need to verify it by discovery, so $server is not set here - $params['openid.ns'] = 'http://specs.openid.net/auth/2.0'; - } elseif(isset($this->data['openid_claimed_id'])) { - # If it's an OpenID 1 provider, and we've got claimed_id, - # we have to append it to the returnUrl, like authUrl_v1 does. - $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?') - . 'openid.claimed_id=' . $this->claimed_id; - } - - if ($this->data['openid_return_to'] != $this->returnUrl) { - # The return_to url must match the url of current request. - # I'm assuing that noone will set the returnUrl to something that doesn't make sense. - return false; - } - - $server = $this->discover($this->data['openid_identity']); - - foreach (explode(',', $this->data['openid_signed']) as $item) { - # Checking whether magic_quotes_gpc is turned on, because - # the function may fail if it is. For example, when fetching - # AX namePerson, it might containg an apostrophe, which will be escaped. - # In such case, validation would fail, since we'd send different data than OP - # wants to verify. stripslashes() should solve that problem, but we can't - # use it when magic_quotes is off. - $value = $this->data['openid_' . str_replace('.','_',$item)]; - $params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($value) : $value; - - } - - $params['openid.mode'] = 'check_authentication'; - - $response = $this->request($server, 'POST', $params); - - return preg_match('/is_valid\s*:\s*true/i', $response); - } - - protected function getAxAttributes() - { - $alias = null; - if (isset($this->data['openid_ns_ax']) - && $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0' - ) { # It's the most likely case, so we'll check it before - $alias = 'ax'; - } else { - # 'ax' prefix is either undefined, or points to another extension, - # so we search for another prefix - foreach ($this->data as $key => $val) { - if (substr($key, 0, strlen('openid_ns_')) == 'openid_ns_' - && $val == 'http://openid.net/srv/ax/1.0' - ) { - $alias = substr($key, strlen('openid_ns_')); - break; - } - } - } - if (!$alias) { - # An alias for AX schema has not been found, - # so there is no AX data in the OP's response - return array(); - } - - $attributes = array(); - foreach ($this->data as $key => $value) { - $keyMatch = 'openid_' . $alias . '_value_'; - if (substr($key, 0, strlen($keyMatch)) != $keyMatch) { - continue; - } - $key = substr($key, strlen($keyMatch)); - if (!isset($this->data['openid_' . $alias . '_type_' . $key])) { - # OP is breaking the spec by returning a field without - # associated ns. This shouldn't happen, but it's better - # to check, than cause an E_NOTICE. - continue; - } - $key = substr($this->data['openid_' . $alias . '_type_' . $key], - strlen('http://axschema.org/')); - $attributes[$key] = $value; - } - return $attributes; -} - -protected function getSregAttributes() -{ - $attributes = array(); - $sreg_to_ax = array_flip(self::$ax_to_sreg); - foreach ($this->data as $key => $value) { - $keyMatch = 'openid_sreg_'; - if (substr($key, 0, strlen($keyMatch)) != $keyMatch) { - continue; - } - $key = substr($key, strlen($keyMatch)); - if (!isset($sreg_to_ax[$key])) { - # The field name isn't part of the SREG spec, so we ignore it. - continue; - } - $attributes[$sreg_to_ax[$key]] = $value; - } - return $attributes; -} - -/** -* Gets AX/SREG attributes provided by OP. should be used only after successful validaton. -* Note that it does not guarantee that any of the required/optional parameters will be present, -* or that there will be no other attributes besides those specified. -* In other words. OP may provide whatever information it wants to. -* * SREG names will be mapped to AX names. -* * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email' -* @see http://www.axschema.org/types/ -*/ -function getAttributes() -{ - if (isset($this->data['openid_ns']) - && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0' - ) { # OpenID 2.0 - # We search for both AX and SREG attributes, with AX taking precedence. - return $this->getAxAttributes() + $this->getSregAttributes(); - } - return $this->getSregAttributes(); -} -} + +* $openid = new LightOpenID; +* $openid->identity = 'ID supplied by user'; +* header('Location: ' . $openid->authUrl()); +* +* The provider then sends various parameters via GET, one of them is openid_mode. +* Step two is verification: +* +* if ($this->data['openid_mode']) { +* $openid = new LightOpenID; +* echo $openid->validate() ? 'Logged in.' : 'Failed'; +* } +* +* +* Optionally, you can set $returnUrl and $realm (or $trustRoot, which is an alias). +* The default values for those are: +* $openid->realm = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']; +* $openid->returnUrl = $openid->realm . $_SERVER['REQUEST_URI']; # without the query part, if present +* If you don't know their meaning, refer to any openid tutorial, or specification. Or just guess. +* +* AX and SREG extensions are supported. +* To use them, specify $openid->required and/or $openid->optional before calling $openid->authUrl(). +* These are arrays, with values being AX schema paths (the 'path' part of the URL). +* For example: +* $openid->required = array('namePerson/friendly', 'contact/email'); +* $openid->optional = array('namePerson/first'); +* If the server supports only SREG or OpenID 1.1, these are automaticaly +* mapped to SREG names, so that user doesn't have to know anything about the server. +* +* To get the values, use $openid->getAttributes(). +* +* +* The library requires PHP >= 5.1.2 with curl or http/https stream wrappers enabled.. +* @author Mewp +* @copyright Copyright (c) 2010, Mewp +* @license http://www.opensource.org/licenses/mit-license.php MIT +*/ +class LightOpenID +{ + public $returnUrl + , $required = array() + , $optional = array(); + private $identity, $claimed_id; + protected $server, $version, $trustRoot, $aliases, $identifier_select = false + , $ax = false, $sreg = false, $data; + static protected $ax_to_sreg = array( + 'namePerson/friendly' => 'nickname', + 'contact/email' => 'email', + 'namePerson' => 'fullname', + 'birthDate' => 'dob', + 'person/gender' => 'gender', + 'contact/postalCode/home' => 'postcode', + 'contact/country/home' => 'country', + 'pref/language' => 'language', + 'pref/timezone' => 'timezone', + ); + + function __construct() + { + $this->trustRoot = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']; + $uri = $_SERVER['REQUEST_URI']; + $uri = strpos($uri, '?') ? substr($uri, 0, strpos($uri, '?')) : $uri; + $this->returnUrl = $this->trustRoot . $uri; + + $this->data = $_POST + $_GET; # OPs may send data as POST or GET. + } + + function __set($name, $value) + { + switch ($name) { + case 'identity': + if (strlen($value = trim((String) $value))) { + if (preg_match('#^xri:/*#i', $value, $m)) { + $value = substr($value, strlen($m[0])); + } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) { + $value = "http://$value"; + } + if (preg_match('#^https?://[^/]+$#i', $value, $m)) { + $value .= '/'; + } + } + $this->$name = $this->claimed_id = $value; + break; + case 'trustRoot': + case 'realm': + $this->trustRoot = trim($value); + } + } + + function __get($name) + { + switch ($name) { + case 'identity': + # We return claimed_id instead of identity, + # because the developer should see the claimed identifier, + # i.e. what he set as identity, not the op-local identifier (which is what we verify) + return $this->claimed_id; + case 'trustRoot': + case 'realm': + return $this->trustRoot; + } + } + + /** + * Checks if the server specified in the url exists. + * + * @param $url url to check + * @return true, if the server exists; false otherwise + */ + function hostExists($url) + { + if (strpos($url, '/') === false) { + $server = $url; + } else { + $server = @parse_url($url, PHP_URL_HOST); + } + + if (!$server) { + return false; + } + + return !!gethostbynamel($server); + } + + protected function request_curl($url, $method='GET', $params=array()) + { + $params = http_build_query($params, '', '&'); + $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : '')); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($curl, CURLOPT_HEADER, false); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*')); + if ($method == 'POST') { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $params); + } elseif ($method == 'HEAD') { + curl_setopt($curl, CURLOPT_HEADER, true); + curl_setopt($curl, CURLOPT_NOBODY, true); + } else { + curl_setopt($curl, CURLOPT_HTTPGET, true); + } + $response = curl_exec($curl); + + if($method == 'HEAD') { + $headers = array(); + foreach(explode("\n", $response) as $header) { + $pos = strpos($header,':'); + $name = strtolower(trim(substr($header, 0, $pos))); + $headers[$name] = trim(substr($header, $pos+1)); + } + + # Updating claimed_id in case of redirections. + $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); + if($effective_url != $url) { + $this->claimed_id = $effective_url; + } + + return $headers; + } + + if (curl_errno($curl)) { + throw new ErrorException(curl_error($curl), curl_errno($curl)); + } + + return $response; + } + + protected function request_streams($url, $method='GET', $params=array()) + { + if(!$this->hostExists($url)) { + throw new ErrorException('Invalid request.'); + } + + $params = http_build_query($params, '', '&'); + switch($method) { + case 'GET': + $opts = array( + 'http' => array( + 'method' => 'GET', + 'header' => 'Accept: application/xrds+xml, */*', + 'ignore_errors' => true, + ) + ); + $url = $url . ($params ? '?' . $params : ''); + break; + case 'POST': + $opts = array( + 'http' => array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => $params, + 'ignore_errors' => true, + ) + ); + break; + case 'HEAD': + # We want to send a HEAD request, + # but since get_headers doesn't accept $context parameter, + # we have to change the defaults. + $default = stream_context_get_options(stream_context_get_default()); + stream_context_get_default( + array('http' => array( + 'method' => 'HEAD', + 'header' => 'Accept: application/xrds+xml, */*', + 'ignore_errors' => true, + )) + ); + + $url = $url . ($params ? '?' . $params : ''); + $headers_tmp = get_headers ($url); + if(!$headers_tmp) { + return array(); + } + + # Parsing headers. + $headers = array(); + foreach($headers_tmp as $header) { + $pos = strpos($header,':'); + $name = strtolower(trim(substr($header, 0, $pos))); + $headers[$name] = trim(substr($header, $pos+1)); + + # Following possible redirections. The point is just to have + # claimed_id change with them, because get_headers() will + # follow redirections automatically. + # We ignore redirections with relative paths. + # If any known provider uses them, file a bug report. + if($name == 'location') { + if(strpos($headers[$name], 'http') === 0) { + $this->claimed_id = $headers[$name]; + } elseif($headers[$name][0] == '/') { + $parsed_url = parse_url($this->claimed_id); + $this->claimed_id = $parsed_url['scheme'] . '://' + . $parsed_url['host'] + . $headers[$name]; + } + } + } + + # And restore them. + stream_context_get_default($default); + return $headers; + } + $context = stream_context_create ($opts); + + return file_get_contents($url, false, $context); + } + + protected function request($url, $method='GET', $params=array()) + { + if(function_exists('curl_init') && !ini_get('safe_mode')) { + return $this->request_curl($url, $method, $params); + } + return $this->request_streams($url, $method, $params); + } + + protected function build_url($url, $parts) + { + if (isset($url['query'], $parts['query'])) { + $parts['query'] = $url['query'] . '&' . $parts['query']; + } + + $url = $parts + $url; + $url = $url['scheme'] . '://' + . (empty($url['username'])?'' + :(empty($url['password'])? "{$url['username']}@" + :"{$url['username']}:{$url['password']}@")) + . $url['host'] + . (empty($url['port'])?'':":{$url['port']}") + . (empty($url['path'])?'':$url['path']) + . (empty($url['query'])?'':"?{$url['query']}") + . (empty($url['fragment'])?'':":{$url['fragment']}"); + return $url; + } + + /** + * Helper function used to scan for / tags and extract information + * from them + */ + protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName) + { + preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1); + preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2); + + $result = array_merge($matches1[1], $matches2[1]); + return empty($result)?false:$result[0]; + } + + /** + * Performs Yadis and HTML discovery. Normally not used. + * @param $url Identity URL. + * @return String OP Endpoint (i.e. OpenID provider address). + * @throws ErrorException + */ + function discover($url) + { + if (!$url) throw new ErrorException('No identity supplied.'); + # Use xri.net proxy to resolve i-name identities + if (!preg_match('#^https?:#', $url)) { + $url = "https://xri.net/$url"; + } + + # We save the original url in case of Yadis discovery failure. + # It can happen when we'll be lead to an XRDS document + # which does not have any OpenID2 services. + $originalUrl = $url; + + # A flag to disable yadis discovery in case of failure in headers. + $yadis = true; + + # We'll jump a maximum of 5 times, to avoid endless redirections. + for ($i = 0; $i < 5; $i ++) { + if ($yadis) { + $headers = $this->request($url, 'HEAD'); + + $next = false; + if (isset($headers['x-xrds-location'])) { + $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location']))); + $next = true; + } + + if (isset($headers['content-type']) + && strpos($headers['content-type'], 'application/xrds+xml') !== false + ) { + # Found an XRDS document, now let's find the server, and optionally delegate. + $content = $this->request($url, 'GET'); + + preg_match_all('#(.*?)#s', $content, $m); + foreach($m[1] as $content) { + $content = ' ' . $content; # The space is added, so that strpos doesn't return 0. + + # OpenID 2 + $ns = preg_quote('http://specs.openid.net/auth/2.0/'); + if(preg_match('#\s*'.$ns.'(server|signon)\s*#s', $content, $type)) { + if ($type[1] == 'server') $this->identifier_select = true; + + preg_match('#(.*)#', $content, $server); + preg_match('#<(Local|Canonical)ID>(.*)#', $content, $delegate); + if (empty($server)) { + return false; + } + # Does the server advertise support for either AX or SREG? + $this->ax = (bool) strpos($content, 'http://openid.net/srv/ax/1.0'); + $this->sreg = strpos($content, 'http://openid.net/sreg/1.0') + || strpos($content, 'http://openid.net/extensions/sreg/1.1'); + + $server = $server[1]; + if (isset($delegate[2])) $this->identity = trim($delegate[2]); + $this->version = 2; + + $this->server = $server; + return $server; + } + + # OpenID 1.1 + $ns = preg_quote('http://openid.net/signon/1.1'); + if (preg_match('#\s*'.$ns.'\s*#s', $content)) { + + preg_match('#(.*)#', $content, $server); + preg_match('#<.*?Delegate>(.*)#', $content, $delegate); + if (empty($server)) { + return false; + } + # AX can be used only with OpenID 2.0, so checking only SREG + $this->sreg = strpos($content, 'http://openid.net/sreg/1.0') + || strpos($content, 'http://openid.net/extensions/sreg/1.1'); + + $server = $server[1]; + if (isset($delegate[1])) $this->identity = $delegate[1]; + $this->version = 1; + + $this->server = $server; + return $server; + } + } + + $next = true; + $yadis = false; + $url = $originalUrl; + $content = null; + break; + } + if ($next) continue; + + # There are no relevant information in headers, so we search the body. + $content = $this->request($url, 'GET'); + if ($location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content')) { + $url = $this->build_url(parse_url($url), parse_url($location)); + continue; + } + } + + if (!$content) $content = $this->request($url, 'GET'); + + # At this point, the YADIS Discovery has failed, so we'll switch + # to openid2 HTML discovery, then fallback to openid 1.1 discovery. + $server = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href'); + $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href'); + $this->version = 2; + + if (!$server) { + # The same with openid 1.1 + $server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href'); + $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href'); + $this->version = 1; + } + + if ($server) { + # We found an OpenID2 OP Endpoint + if ($delegate) { + # We have also found an OP-Local ID. + $this->identity = $delegate; + } + $this->server = $server; + return $server; + } + + throw new ErrorException('No servers found!'); + } + throw new ErrorException('Endless redirection!'); + } + + protected function sregParams() + { + $params = array(); + # We always use SREG 1.1, even if the server is advertising only support for 1.0. + # That's because it's fully backwards compatibile with 1.0, and some providers + # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com + $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1'; + if ($this->required) { + $params['openid.sreg.required'] = array(); + foreach ($this->required as $required) { + if (!isset(self::$ax_to_sreg[$required])) continue; + $params['openid.sreg.required'][] = self::$ax_to_sreg[$required]; + } + $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']); + } + + if ($this->optional) { + $params['openid.sreg.optional'] = array(); + foreach ($this->optional as $optional) { + if (!isset(self::$ax_to_sreg[$optional])) continue; + $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional]; + } + $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']); + } + return $params; + } + + protected function axParams() + { + $params = array(); + if ($this->required || $this->optional) { + $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0'; + $params['openid.ax.mode'] = 'fetch_request'; + $this->aliases = array(); + $counts = array(); + $required = array(); + $optional = array(); + foreach (array('required','optional') as $type) { + foreach ($this->$type as $alias => $field) { + if (is_int($alias)) $alias = strtr($field, '/', '_'); + $this->aliases[$alias] = 'http://axschema.org/' . $field; + if (empty($counts[$alias])) $counts[$alias] = 0; + $counts[$alias] += 1; + ${$type}[] = $alias; + } + } + foreach ($this->aliases as $alias => $ns) { + $params['openid.ax.type.' . $alias] = $ns; + } + foreach ($counts as $alias => $count) { + if ($count == 1) continue; + $params['openid.ax.count.' . $alias] = $count; + } + + # Don't send empty ax.requied and ax.if_available. + # Google and possibly other providers refuse to support ax when one of these is empty. + if($required) { + $params['openid.ax.required'] = implode(',', $required); + } + if($optional) { + $params['openid.ax.if_available'] = implode(',', $optional); + } + } + return $params; + } + + protected function authUrl_v1() + { + $returnUrl = $this->returnUrl; + # If we have an openid.delegate that is different from our claimed id, + # we need to somehow preserve the claimed id between requests. + # The simplest way is to just send it along with the return_to url. + if($this->identity != $this->claimed_id) { + $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id; + } + + $params = array( + 'openid.return_to' => $returnUrl, + 'openid.mode' => 'checkid_setup', + 'openid.identity' => $this->identity, + 'openid.trust_root' => $this->trustRoot, + ) + $this->sregParams(); + + return $this->build_url(parse_url($this->server) + , array('query' => http_build_query($params, '', '&'))); + } + + protected function authUrl_v2($identifier_select) + { + $params = array( + 'openid.ns' => 'http://specs.openid.net/auth/2.0', + 'openid.mode' => 'checkid_setup', + 'openid.return_to' => $this->returnUrl, + 'openid.realm' => $this->trustRoot, + ); + if ($this->ax) { + $params += $this->axParams(); + } + if ($this->sreg) { + $params += $this->sregParams(); + } + if (!$this->ax && !$this->sreg) { + # If OP doesn't advertise either SREG, nor AX, let's send them both + # in worst case we don't get anything in return. + $params += $this->axParams() + $this->sregParams(); + } + + if ($identifier_select) { + $params['openid.identity'] = $params['openid.claimed_id'] + = 'http://specs.openid.net/auth/2.0/identifier_select'; + } else { + $params['openid.identity'] = $this->identity; + $params['openid.claimed_id'] = $this->claimed_id; + } + + return $this->build_url(parse_url($this->server) + , array('query' => http_build_query($params, '', '&'))); + } + + /** + * Returns authentication url. Usually, you want to redirect your user to it. + * @return String The authentication url. + * @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1. + * @throws ErrorException + */ +function authUrl($identifier_select = null) +{ + if (!$this->server) $this->discover($this->identity); + + if ($this->version == 2) { + if ($identifier_select === null) { + return $this->authUrl_v2($this->identifier_select); + } + return $this->authUrl_v2($identifier_select); + } + return $this->authUrl_v1(); +} + +/** +* Performs OpenID verification with the OP. +* @return Bool Whether the verification was successful. +* @throws ErrorException +*/ +function validate() +{ + $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity']; + $params = array( + 'openid.assoc_handle' => $this->data['openid_assoc_handle'], + 'openid.signed' => $this->data['openid_signed'], + 'openid.sig' => $this->data['openid_sig'], + ); + + if (isset($this->data['openid_ns'])) { + # We're dealing with an OpenID 2.0 server, so let's set an ns + # Even though we should know location of the endpoint, + # we still need to verify it by discovery, so $server is not set here + $params['openid.ns'] = 'http://specs.openid.net/auth/2.0'; + } elseif(isset($this->data['openid_claimed_id'])) { + # If it's an OpenID 1 provider, and we've got claimed_id, + # we have to append it to the returnUrl, like authUrl_v1 does. + $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?') + . 'openid.claimed_id=' . $this->claimed_id; + } + + if ($this->data['openid_return_to'] != $this->returnUrl) { + # The return_to url must match the url of current request. + # I'm assuing that noone will set the returnUrl to something that doesn't make sense. + return false; + } + + $server = $this->discover($this->data['openid_identity']); + + foreach (explode(',', $this->data['openid_signed']) as $item) { + # Checking whether magic_quotes_gpc is turned on, because + # the function may fail if it is. For example, when fetching + # AX namePerson, it might containg an apostrophe, which will be escaped. + # In such case, validation would fail, since we'd send different data than OP + # wants to verify. stripslashes() should solve that problem, but we can't + # use it when magic_quotes is off. + $value = $this->data['openid_' . str_replace('.','_',$item)]; + $params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($value) : $value; + + } + + $params['openid.mode'] = 'check_authentication'; + + $response = $this->request($server, 'POST', $params); + + return preg_match('/is_valid\s*:\s*true/i', $response); + } + + protected function getAxAttributes() + { + $alias = null; + if (isset($this->data['openid_ns_ax']) + && $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0' + ) { # It's the most likely case, so we'll check it before + $alias = 'ax'; + } else { + # 'ax' prefix is either undefined, or points to another extension, + # so we search for another prefix + foreach ($this->data as $key => $val) { + if (substr($key, 0, strlen('openid_ns_')) == 'openid_ns_' + && $val == 'http://openid.net/srv/ax/1.0' + ) { + $alias = substr($key, strlen('openid_ns_')); + break; + } + } + } + if (!$alias) { + # An alias for AX schema has not been found, + # so there is no AX data in the OP's response + return array(); + } + + $attributes = array(); + foreach ($this->data as $key => $value) { + $keyMatch = 'openid_' . $alias . '_value_'; + if (substr($key, 0, strlen($keyMatch)) != $keyMatch) { + continue; + } + $key = substr($key, strlen($keyMatch)); + if (!isset($this->data['openid_' . $alias . '_type_' . $key])) { + # OP is breaking the spec by returning a field without + # associated ns. This shouldn't happen, but it's better + # to check, than cause an E_NOTICE. + continue; + } + $key = substr($this->data['openid_' . $alias . '_type_' . $key], + strlen('http://axschema.org/')); + $attributes[$key] = $value; + } + return $attributes; +} + +protected function getSregAttributes() +{ + $attributes = array(); + $sreg_to_ax = array_flip(self::$ax_to_sreg); + foreach ($this->data as $key => $value) { + $keyMatch = 'openid_sreg_'; + if (substr($key, 0, strlen($keyMatch)) != $keyMatch) { + continue; + } + $key = substr($key, strlen($keyMatch)); + if (!isset($sreg_to_ax[$key])) { + # The field name isn't part of the SREG spec, so we ignore it. + continue; + } + $attributes[$sreg_to_ax[$key]] = $value; + } + return $attributes; +} + +/** +* Gets AX/SREG attributes provided by OP. should be used only after successful validaton. +* Note that it does not guarantee that any of the required/optional parameters will be present, +* or that there will be no other attributes besides those specified. +* In other words. OP may provide whatever information it wants to. +* * SREG names will be mapped to AX names. +* * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email' +* @see http://www.axschema.org/types/ +*/ +function getAttributes() +{ + if (isset($this->data['openid_ns']) + && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0' + ) { # OpenID 2.0 + # We search for both AX and SREG attributes, with AX taking precedence. + return $this->getAxAttributes() + $this->getSregAttributes(); + } + return $this->getSregAttributes(); +} +} diff --git a/social-connect.php b/social-connect.php index 55ce50e..4346b06 100644 --- a/social-connect.php +++ b/social-connect.php @@ -1,391 +1,391 @@ -upgrading your WordPress installation, it's worth the effort.
Return to Plugins Admin page »", 'social_connect'), admin_url( 'plugins.php' ) ), 'social-connect' ); - elseif ( !function_exists( 'curl_version' ) ) - wp_die( sprintf( __( "Sorry, but you can not run Social Connect. It requires the PHP libcurl extension be installed. Please contact your web host and request libcurl be installed.
Return to Plugins Admin page »", 'social_connect'), admin_url( 'plugins.php' ) ), 'social-connect' ); - elseif ( !function_exists( 'hash' ) ) - wp_die( sprintf( __( "Sorry, but you can not run Social Connect. It requires the PHP Hash Engine. Please contact your web host and request Hash engine be installed.
Return to Plugins Admin page »", 'social_connect'), admin_url( 'plugins.php' ) ), 'social-connect' ); - else - wp_die( sprintf( __( "Sorry, but you can not run Social Connect. It requires PHP 5.1.2 or newer. Please contact your web host and request they migrate your PHP installation to run Social Connect.
Return to Plugins Admin page »", 'social_connect'), admin_url( 'plugins.php' ) ), 'social-connect' ); - } - do_action( 'sc_activation' ); -} -register_activation_hook( __FILE__, 'sc_activate' ); - -/** - * Internationalization of the plugin - **/ -function sc_social_connect_l10n() { - $plugin_dir = basename( dirname( __FILE__ ) ); - load_plugin_textdomain( 'social_connect', null, "$plugin_dir/languages" ); -} -add_action( 'init', 'sc_social_connect_l10n', -1000 ); - -require_once( dirname( __FILE__ ) . '/constants.php' ); -require_once( dirname( __FILE__ ) . '/utils.php' ); -require_once( dirname( __FILE__ ) . '/media.php' ); -require_once( dirname( __FILE__ ) . '/admin.php' ); -require_once( dirname( __FILE__ ) . '/ui.php' ); - -/** - * Add valid query vars to WordPress for Social Connect. - */ -function sc_query_vars($vars) { - $vars[] = 'social-connect'; - return $vars; -} -add_action('query_vars', 'sc_query_vars'); - -/** - * Parse the WordPress request. If the query var 'social-connect' is present, - * then handle the request accordingly. - * - * @param WP $wp WP instance for the current request - */ -function sc_parse_request($wp) { - if (array_key_exists('social-connect', $wp->query_vars)) { - if (!session_id()) { - session_start(); - } - - switch ($wp->query_vars['social-connect']) { - case 'twitter': - require_once 'twitter/connect.php'; - break; - case 'twitter-callback': - require_once 'twitter/callback.php'; - break; - case 'facebook-callback': - require_once 'facebook/callback.php'; - break; - case 'google': - require_once 'google/connect.php'; - break; - case 'google-plus': - require_once 'google-plus/connect.php'; - break; - case 'google-plus-callback': - require_once 'google-plus/callback.php'; - break; - case 'yahoo': - require_once 'yahoo/connect.php'; - break; - case 'wordpress': - require_once 'wordpress/connect.php'; - break; - default: - break; - } - - wp_die(); - } -} -add_action('parse_request', 'sc_parse_request'); - -function sc_social_connect_process_login( $is_ajax = false ) { - if ( isset( $_REQUEST[ 'redirect_to' ] ) && $_REQUEST[ 'redirect_to' ] != '' ) { - $redirect_to = $_REQUEST[ 'redirect_to' ]; - // Redirect to https if user wants ssl - if ( isset( $secure_cookie ) && $secure_cookie && false !== strpos( $redirect_to, 'wp-admin') ) - $redirect_to = preg_replace( '|^http://|', 'https://', $redirect_to ); - } else { - $redirect_to = admin_url(); - } - $redirect_to = apply_filters( 'social_connect_redirect_to', $redirect_to ); - - $social_connect_provider = $_REQUEST[ 'social_connect_provider' ]; - $sc_provider_identity_key = 'social_connect_' . $social_connect_provider . '_id'; - $sc_provided_signature = $_REQUEST[ 'social_connect_signature' ]; - - switch( $social_connect_provider ) { - case 'facebook': - social_connect_verify_signature( $_REQUEST[ 'social_connect_access_token' ], $sc_provided_signature, $redirect_to ); - $fb_json = json_decode( sc_http_get_contents("https://graph.facebook.com/me?access_token=" . $_REQUEST['social_connect_access_token']) ); - $sc_provider_identity = $fb_json->{ 'id' }; - $sc_email = $fb_json->{ 'email' }; - $sc_first_name = $fb_json->{ 'first_name' }; - $sc_last_name = $fb_json->{ 'last_name' }; - $sc_profile_url = $fb_json->{ 'link' }; - $sc_name = $sc_first_name . ' ' . $sc_last_name; - $user_login = strtolower( str_replace( ' ', '', $sc_first_name . $sc_last_name ) ); - break; - case 'twitter': - $sc_provider_identity = $_REQUEST[ 'social_connect_twitter_identity' ]; - social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); - $sc_name = $_REQUEST[ 'social_connect_name' ]; - $names = explode( ' ', $sc_name, 2 ); - $sc_first_name = $names[0]; - $sc_last_name = $names[1]; - $sc_screen_name = $_REQUEST[ 'social_connect_screen_name' ]; - $sc_avatar = isset( $_REQUEST['social_connect_avatar'] ) ? str_replace( 'http:', '', $_REQUEST['social_connect_avatar'] ) : ''; - $sc_profile_url = ''; - // Get host name from URL - $site_url = parse_url( site_url() ); - $sc_email = 'tw_' . md5( $sc_provider_identity ) . '@' . $site_url['host']; - $user_login = $sc_screen_name; - break; - case 'google': - $sc_provider_identity = $_REQUEST[ 'social_connect_openid_identity' ]; - social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); - $sc_email = $_REQUEST[ 'social_connect_email' ]; - $sc_first_name = $_REQUEST[ 'social_connect_first_name' ]; - $sc_last_name = $_REQUEST[ 'social_connect_last_name' ]; - $sc_profile_url = ''; - $sc_name = $sc_first_name . ' ' . $sc_last_name; - $user_login = strtolower( str_replace( ' ', '', $sc_first_name . $sc_last_name ) ); - break; - case 'google-plus': - $sc_provider_identity = $_REQUEST['social_connect_google_id']; - social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); - $sc_email = $_REQUEST['social_connect_email']; - $sc_first_name = $_REQUEST['social_connect_first_name']; - $sc_last_name = $_REQUEST['social_connect_last_name']; - $sc_profile_url = $_REQUEST['social_connect_profile_url']; - $user_login = strtolower( $sc_first_name.$sc_last_name ); - break; - case 'yahoo': - $sc_provider_identity = $_REQUEST[ 'social_connect_openid_identity' ]; - social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); - $sc_email = $_REQUEST[ 'social_connect_email' ]; - $sc_name = $_REQUEST[ 'social_connect_name' ]; - $sc_username = $_REQUEST[ 'social_connect_username' ]; - $sc_profile_url = ''; - if ( $sc_name == '') { - if ( $sc_username == '') { - $names = explode("@", $sc_email ); - $sc_name = $names[0]; - $sc_first_name = $sc_name; - $sc_last_name = ''; - } else { - $names = explode( ' ', $sc_username, 2 ); - $sc_first_name = $names[0]; - $sc_last_name = $names[1]; - } - } else { - $names = explode( ' ', $sc_name, 2 ); - $sc_first_name = $names[0]; - $sc_last_name = $names[1]; - } - $user_login = strtolower( str_replace( ' ', '', $sc_first_name . $sc_last_name ) ); - break; - case 'wordpress': - $sc_provider_identity = $_REQUEST[ 'social_connect_openid_identity' ]; - social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); - $sc_email = $_REQUEST[ 'social_connect_email' ]; - $sc_name = $_REQUEST[ 'social_connect_name' ]; - $sc_profile_url = ''; - if ( trim( $sc_name ) == '') { - $names = explode("@", $sc_email ); - $sc_name = $names[0]; - $sc_first_name = $sc_name; - $sc_last_name = ''; - } else { - $names = explode( ' ', $sc_name, 2 ); - $sc_first_name = $names[0]; - $sc_last_name = $names[1]; - } - $user_login = strtolower( str_replace( ' ', '', $sc_first_name . $sc_last_name ) ); - break; - default: - break; - } - - // Cookies used to display welcome message if already signed in recently using some provider - setcookie("social_connect_current_provider", $social_connect_provider, time()+3600, SITECOOKIEPATH, COOKIE_DOMAIN, false, true ); - - // Get user by meta - $user_id = social_connect_get_user_by_meta( $sc_provider_identity_key, $sc_provider_identity ); - if ( $user_id ) { - $user_data = get_userdata( $user_id ); - $user_login = $user_data->user_login; - } elseif ( $user_id = email_exists( $sc_email ) ) { // User not found by provider identity, check by email - update_user_meta( $user_id, $sc_provider_identity_key, $sc_provider_identity ); - - $user_data = get_userdata( $user_id ); - $user_login = $user_data->user_login; - - } else { // Create new user and associate provider identity - if ( get_option( 'users_can_register' ) ) { - $user_login = sc_get_unique_username($user_login); - - $userdata = array( 'user_login' => $user_login, 'user_email' => $sc_email, 'first_name' => $sc_first_name, 'last_name' => $sc_last_name, 'user_url' => $sc_profile_url, 'user_pass' => wp_generate_password() ); - - // Create a new user - $user_id = wp_insert_user( apply_filters( 'social_connect_insert_user', $userdata ) ); - - if ( $user_id && is_integer( $user_id ) ) { - update_user_meta( $user_id, $sc_provider_identity_key, $sc_provider_identity ); - } - - if( isset( $sc_avatar ) && $sc_avatar ){ - update_user_meta( $user_id, 'social_connect_twitter_avatar', $sc_avatar ); - } - do_action( 'social_connect_inserted_user', $user_id, $social_connect_provider ); - } else { - add_filter( 'wp_login_errors', 'sc_login_errors' ); - - return; - } - } - - wp_set_auth_cookie( $user_id ); - - do_action( 'social_connect_login', $user_login ); - - if ( $is_ajax ) { - echo '{"redirect":"' . $redirect_to . '"}'; - } else { - wp_safe_redirect( $redirect_to ); - } - - exit(); -} - -/** - * Add error message when user try to login - * with an nonexistent e-mail and registration is disabled - * - * @param WP_Error $errors - * @return WP_Error - */ -function sc_login_errors( $errors ) { - $errors->errors = array(); - $errors->add( 'registration_disabled', __( 'ERROR: Registration is disabled.', 'social-connect' ) ); - - return $errors; -} - -function sc_get_unique_username($user_login, $c = 1) { - if ( username_exists( $user_login ) ) { - if ($c > 5) - $append = '_'.substr(md5($user_login),0,3) . $c; - else - $append = $c; - - $user_login = apply_filters( 'social_connect_username_exists', $user_login . $append ); - return sc_get_unique_username($user_login,++$c); - } else { - return $user_login; - } -} - -// Hook to 'login_form_' . $action -add_action( 'login_form_social_connect', 'sc_social_connect_process_login'); - -// Handle calls from plugins that use an Ajax for login -function sc_ajax_login(){ - if ( isset( $_POST[ 'login_submit' ] ) && $_POST[ 'login_submit' ] == 'ajax' && // Plugins will need to pass this param - isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'social_connect' ) - sc_social_connect_process_login( true ); -} -add_action( 'init', 'sc_ajax_login'); - -/** - * Use avatars in priority order - * @author Aaron Oneal - * @link http://aarononeal.info - * - */ -function sc_filter_avatar($avatar, $id_or_email, $size, $default, $alt) { - $custom_avatar = ''; - $social_id = ''; - $provider_id = ''; - $user_id = (!is_integer($id_or_email) && !is_string($id_or_email) && get_class($id_or_email)) ? $id_or_email->user_id : $id_or_email; - - if (!empty($user_id)) { - // Providers to search for (assume user prefers their current logged in service) - // Note: OpenID providers use gravatars - $providers = array('facebook', 'twitter'); - - $social_connect_provider = isset( $_COOKIE['social_connect_current_provider']) ? $_COOKIE['social_connect_current_provider'] : ''; - if (!empty($social_connect_provider) && $social_connect_provider == 'twitter') { - $providers = array('twitter', 'facebook'); - } - - foreach($providers as $search_provider) { - $social_id = get_user_meta($user_id, 'social_connect_'.$search_provider.'_id', true); - if (!empty($social_id)) { - $provider_id = $search_provider; - break; - } - } - } - - // At least one social ID was found - if (!empty($social_id)) { - switch($provider_id) { - case 'facebook': - // square (50x50) - // small (50 pixels wide, variable height) - // normal (100 pixels wide, variable height) - // large (about 200 pixels wide, variable height) - - $size_label = 'large'; - - if($size <= 100) - $size_label = 'normal'; - else if($size <= 50) - $size_label = 'small'; - - $custom_avatar = "http://graph.facebook.com/$social_id/picture?type=$size_label"; - break; - case 'twitter': - // bigger - 73px by 73px - // normal - 48px by 48px - // mini - 24px by 24px - - $size_label = 'bigger'; - - if ($size <= 48) { - $size_label = 'normal'; - } else if ($size <= 24) { - $size_label = 'mini'; - } - - $custom_avatar = get_user_meta( $user_id, 'social_connect_twitter_avatar', true ); - $custom_avatar = str_replace( '_normal', '_' . $size_label, $custom_avatar ); - break; - } - } - - if (!empty($custom_avatar)) { - // return the custom avatar from the social network - $return = ''.$alt.''; - } else if ($avatar) { - // gravatar - $return = $avatar; - } else { - // default - $return = ''.$alt.''; - } - - return $return; -} -add_filter('get_avatar', 'sc_filter_avatar', 10, 5); - -/** - * Add link to Social Connect settings page in the plugins page - * - * @return array plugin links -*/ -function sc_add_settings_link( $default_links ) { - $links = array('' . __('Settings', 'social_connect') . ''); - return array_merge($links, $default_links); -} -add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'sc_add_settings_link' ); +upgrading your WordPress installation, it's worth the effort.
Return to Plugins Admin page »", 'social_connect'), admin_url( 'plugins.php' ) ), 'social-connect' ); + elseif ( !function_exists( 'curl_version' ) ) + wp_die( sprintf( __( "Sorry, but you can not run Social Connect. It requires the PHP libcurl extension be installed. Please contact your web host and request libcurl be installed.
Return to Plugins Admin page »", 'social_connect'), admin_url( 'plugins.php' ) ), 'social-connect' ); + elseif ( !function_exists( 'hash' ) ) + wp_die( sprintf( __( "Sorry, but you can not run Social Connect. It requires the PHP Hash Engine. Please contact your web host and request Hash engine be installed.
Return to Plugins Admin page »", 'social_connect'), admin_url( 'plugins.php' ) ), 'social-connect' ); + else + wp_die( sprintf( __( "Sorry, but you can not run Social Connect. It requires PHP 5.1.2 or newer. Please contact your web host and request they migrate your PHP installation to run Social Connect.
Return to Plugins Admin page »", 'social_connect'), admin_url( 'plugins.php' ) ), 'social-connect' ); + } + do_action( 'sc_activation' ); +} +register_activation_hook( __FILE__, 'sc_activate' ); + +/** + * Internationalization of the plugin + **/ +function sc_social_connect_l10n() { + $plugin_dir = basename( dirname( __FILE__ ) ); + load_plugin_textdomain( 'social_connect', null, "$plugin_dir/languages" ); +} +add_action( 'init', 'sc_social_connect_l10n', -1000 ); + +require_once( dirname( __FILE__ ) . '/constants.php' ); +require_once( dirname( __FILE__ ) . '/utils.php' ); +require_once( dirname( __FILE__ ) . '/media.php' ); +require_once( dirname( __FILE__ ) . '/admin.php' ); +require_once( dirname( __FILE__ ) . '/ui.php' ); + +/** + * Add valid query vars to WordPress for Social Connect. + */ +function sc_query_vars($vars) { + $vars[] = 'social-connect'; + return $vars; +} +add_action('query_vars', 'sc_query_vars'); + +/** + * Parse the WordPress request. If the query var 'social-connect' is present, + * then handle the request accordingly. + * + * @param WP $wp WP instance for the current request + */ +function sc_parse_request($wp) { + if (array_key_exists('social-connect', $wp->query_vars)) { + if (!session_id()) { + session_start(); + } + + switch ($wp->query_vars['social-connect']) { + case 'twitter': + require_once 'twitter/connect.php'; + break; + case 'twitter-callback': + require_once 'twitter/callback.php'; + break; + case 'facebook-callback': + require_once 'facebook/callback.php'; + break; + case 'google': + require_once 'google/connect.php'; + break; + case 'google-plus': + require_once 'google-plus/connect.php'; + break; + case 'google-plus-callback': + require_once 'google-plus/callback.php'; + break; + case 'yahoo': + require_once 'yahoo/connect.php'; + break; + case 'wordpress': + require_once 'wordpress/connect.php'; + break; + default: + break; + } + + wp_die(); + } +} +add_action('parse_request', 'sc_parse_request'); + +function sc_social_connect_process_login( $is_ajax = false ) { + if ( isset( $_REQUEST[ 'redirect_to' ] ) && $_REQUEST[ 'redirect_to' ] != '' ) { + $redirect_to = $_REQUEST[ 'redirect_to' ]; + // Redirect to https if user wants ssl + if ( isset( $secure_cookie ) && $secure_cookie && false !== strpos( $redirect_to, 'wp-admin') ) + $redirect_to = preg_replace( '|^http://|', 'https://', $redirect_to ); + } else { + $redirect_to = admin_url(); + } + $redirect_to = apply_filters( 'social_connect_redirect_to', $redirect_to ); + + $social_connect_provider = $_REQUEST[ 'social_connect_provider' ]; + $sc_provider_identity_key = 'social_connect_' . $social_connect_provider . '_id'; + $sc_provided_signature = $_REQUEST[ 'social_connect_signature' ]; + + switch( $social_connect_provider ) { + case 'facebook': + social_connect_verify_signature( $_REQUEST[ 'social_connect_access_token' ], $sc_provided_signature, $redirect_to ); + $fb_json = json_decode( sc_http_get_contents("https://graph.facebook.com/me?access_token=" . $_REQUEST['social_connect_access_token']) ); + $sc_provider_identity = $fb_json->{ 'id' }; + $sc_email = $fb_json->{ 'email' }; + $sc_first_name = $fb_json->{ 'first_name' }; + $sc_last_name = $fb_json->{ 'last_name' }; + $sc_profile_url = $fb_json->{ 'link' }; + $sc_name = $sc_first_name . ' ' . $sc_last_name; + $user_login = strtolower( str_replace( ' ', '', $sc_first_name . $sc_last_name ) ); + break; + case 'twitter': + $sc_provider_identity = $_REQUEST[ 'social_connect_twitter_identity' ]; + social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); + $sc_name = $_REQUEST[ 'social_connect_name' ]; + $names = explode( ' ', $sc_name, 2 ); + $sc_first_name = $names[0]; + $sc_last_name = $names[1]; + $sc_screen_name = $_REQUEST[ 'social_connect_screen_name' ]; + $sc_avatar = isset( $_REQUEST['social_connect_avatar'] ) ? str_replace( 'http:', '', $_REQUEST['social_connect_avatar'] ) : ''; + $sc_profile_url = ''; + // Get host name from URL + $site_url = parse_url( site_url() ); + $sc_email = 'tw_' . md5( $sc_provider_identity ) . '@' . $site_url['host']; + $user_login = $sc_screen_name; + break; + case 'google': + $sc_provider_identity = $_REQUEST[ 'social_connect_openid_identity' ]; + social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); + $sc_email = $_REQUEST[ 'social_connect_email' ]; + $sc_first_name = $_REQUEST[ 'social_connect_first_name' ]; + $sc_last_name = $_REQUEST[ 'social_connect_last_name' ]; + $sc_profile_url = ''; + $sc_name = $sc_first_name . ' ' . $sc_last_name; + $user_login = strtolower( str_replace( ' ', '', $sc_first_name . $sc_last_name ) ); + break; + case 'google-plus': + $sc_provider_identity = $_REQUEST['social_connect_google_id']; + social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); + $sc_email = $_REQUEST['social_connect_email']; + $sc_first_name = $_REQUEST['social_connect_first_name']; + $sc_last_name = $_REQUEST['social_connect_last_name']; + $sc_profile_url = $_REQUEST['social_connect_profile_url']; + $user_login = strtolower( $sc_first_name.$sc_last_name ); + break; + case 'yahoo': + $sc_provider_identity = $_REQUEST[ 'social_connect_openid_identity' ]; + social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); + $sc_email = $_REQUEST[ 'social_connect_email' ]; + $sc_name = $_REQUEST[ 'social_connect_name' ]; + $sc_username = $_REQUEST[ 'social_connect_username' ]; + $sc_profile_url = ''; + if ( $sc_name == '') { + if ( $sc_username == '') { + $names = explode("@", $sc_email ); + $sc_name = $names[0]; + $sc_first_name = $sc_name; + $sc_last_name = ''; + } else { + $names = explode( ' ', $sc_username, 2 ); + $sc_first_name = $names[0]; + $sc_last_name = $names[1]; + } + } else { + $names = explode( ' ', $sc_name, 2 ); + $sc_first_name = $names[0]; + $sc_last_name = $names[1]; + } + $user_login = strtolower( str_replace( ' ', '', $sc_first_name . $sc_last_name ) ); + break; + case 'wordpress': + $sc_provider_identity = $_REQUEST[ 'social_connect_openid_identity' ]; + social_connect_verify_signature( $sc_provider_identity, $sc_provided_signature, $redirect_to ); + $sc_email = $_REQUEST[ 'social_connect_email' ]; + $sc_name = $_REQUEST[ 'social_connect_name' ]; + $sc_profile_url = ''; + if ( trim( $sc_name ) == '') { + $names = explode("@", $sc_email ); + $sc_name = $names[0]; + $sc_first_name = $sc_name; + $sc_last_name = ''; + } else { + $names = explode( ' ', $sc_name, 2 ); + $sc_first_name = $names[0]; + $sc_last_name = $names[1]; + } + $user_login = strtolower( str_replace( ' ', '', $sc_first_name . $sc_last_name ) ); + break; + default: + break; + } + + // Cookies used to display welcome message if already signed in recently using some provider + setcookie("social_connect_current_provider", $social_connect_provider, time()+3600, SITECOOKIEPATH, COOKIE_DOMAIN, false, true ); + + // Get user by meta + $user_id = social_connect_get_user_by_meta( $sc_provider_identity_key, $sc_provider_identity ); + if ( $user_id ) { + $user_data = get_userdata( $user_id ); + $user_login = $user_data->user_login; + } elseif ( $user_id = email_exists( $sc_email ) ) { // User not found by provider identity, check by email + update_user_meta( $user_id, $sc_provider_identity_key, $sc_provider_identity ); + + $user_data = get_userdata( $user_id ); + $user_login = $user_data->user_login; + + } else { // Create new user and associate provider identity + if ( get_option( 'users_can_register' ) ) { + $user_login = sc_get_unique_username($user_login); + + $userdata = array( 'user_login' => $user_login, 'user_email' => $sc_email, 'first_name' => $sc_first_name, 'last_name' => $sc_last_name, 'user_url' => $sc_profile_url, 'user_pass' => wp_generate_password() ); + + // Create a new user + $user_id = wp_insert_user( apply_filters( 'social_connect_insert_user', $userdata ) ); + + if ( $user_id && is_integer( $user_id ) ) { + update_user_meta( $user_id, $sc_provider_identity_key, $sc_provider_identity ); + } + + if( isset( $sc_avatar ) && $sc_avatar ){ + update_user_meta( $user_id, 'social_connect_twitter_avatar', $sc_avatar ); + } + do_action( 'social_connect_inserted_user', $user_id, $social_connect_provider ); + } else { + add_filter( 'wp_login_errors', 'sc_login_errors' ); + + return; + } + } + + wp_set_auth_cookie( $user_id ); + + do_action( 'social_connect_login', $user_login ); + + if ( $is_ajax ) { + echo '{"redirect":"' . $redirect_to . '"}'; + } else { + wp_safe_redirect( $redirect_to ); + } + + exit(); +} + +/** + * Add error message when user try to login + * with an nonexistent e-mail and registration is disabled + * + * @param WP_Error $errors + * @return WP_Error + */ +function sc_login_errors( $errors ) { + $errors->errors = array(); + $errors->add( 'registration_disabled', __( 'ERROR: Registration is disabled.', 'social-connect' ) ); + + return $errors; +} + +function sc_get_unique_username($user_login, $c = 1) { + if ( username_exists( $user_login ) ) { + if ($c > 5) + $append = '_'.substr(md5($user_login),0,3) . $c; + else + $append = $c; + + $user_login = apply_filters( 'social_connect_username_exists', $user_login . $append ); + return sc_get_unique_username($user_login,++$c); + } else { + return $user_login; + } +} + +// Hook to 'login_form_' . $action +add_action( 'login_form_social_connect', 'sc_social_connect_process_login'); + +// Handle calls from plugins that use an Ajax for login +function sc_ajax_login(){ + if ( isset( $_POST[ 'login_submit' ] ) && $_POST[ 'login_submit' ] == 'ajax' && // Plugins will need to pass this param + isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'social_connect' ) + sc_social_connect_process_login( true ); +} +add_action( 'init', 'sc_ajax_login'); + +/** + * Use avatars in priority order + * @author Aaron Oneal + * @link http://aarononeal.info + * + */ +function sc_filter_avatar($avatar, $id_or_email, $size, $default, $alt) { + $custom_avatar = ''; + $social_id = ''; + $provider_id = ''; + $user_id = (!is_integer($id_or_email) && !is_string($id_or_email) && get_class($id_or_email)) ? $id_or_email->user_id : $id_or_email; + + if (!empty($user_id)) { + // Providers to search for (assume user prefers their current logged in service) + // Note: OpenID providers use gravatars + $providers = array('facebook', 'twitter'); + + $social_connect_provider = isset( $_COOKIE['social_connect_current_provider']) ? $_COOKIE['social_connect_current_provider'] : ''; + if (!empty($social_connect_provider) && $social_connect_provider == 'twitter') { + $providers = array('twitter', 'facebook'); + } + + foreach($providers as $search_provider) { + $social_id = get_user_meta($user_id, 'social_connect_'.$search_provider.'_id', true); + if (!empty($social_id)) { + $provider_id = $search_provider; + break; + } + } + } + + // At least one social ID was found + if (!empty($social_id)) { + switch($provider_id) { + case 'facebook': + // square (50x50) + // small (50 pixels wide, variable height) + // normal (100 pixels wide, variable height) + // large (about 200 pixels wide, variable height) + + $size_label = 'large'; + + if($size <= 100) + $size_label = 'normal'; + else if($size <= 50) + $size_label = 'small'; + + $custom_avatar = "http://graph.facebook.com/$social_id/picture?type=$size_label"; + break; + case 'twitter': + // bigger - 73px by 73px + // normal - 48px by 48px + // mini - 24px by 24px + + $size_label = 'bigger'; + + if ($size <= 48) { + $size_label = 'normal'; + } else if ($size <= 24) { + $size_label = 'mini'; + } + + $custom_avatar = get_user_meta( $user_id, 'social_connect_twitter_avatar', true ); + $custom_avatar = str_replace( '_normal', '_' . $size_label, $custom_avatar ); + break; + } + } + + if (!empty($custom_avatar)) { + // return the custom avatar from the social network + $return = ''.$alt.''; + } else if ($avatar) { + // gravatar + $return = $avatar; + } else { + // default + $return = ''.$alt.''; + } + + return $return; +} +add_filter('get_avatar', 'sc_filter_avatar', 10, 5); + +/** + * Add link to Social Connect settings page in the plugins page + * + * @return array plugin links +*/ +function sc_add_settings_link( $default_links ) { + $links = array('' . __('Settings', 'social_connect') . ''); + return array_merge($links, $default_links); +} +add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'sc_add_settings_link' ); diff --git a/ui.php b/ui.php index 42bee1a..fd60f4a 100644 --- a/ui.php +++ b/ui.php @@ -1,209 +1,209 @@ - - - - - comment_ID, 'social_connect_comment_via_provider', true ); - if( $social_connect_comment_via_provider && current_user_can( 'manage_options' )) { - return $link . ' '; - } else { - return $link; - } -} -add_action( 'get_comment_author_link', 'sc_social_connect_render_comment_meta' ); - - -function sc_render_comment_form_social_connect() { - if( comments_open() && !is_user_logged_in()) { - sc_render_login_form_social_connect(); - } -} -add_action( 'comment_form_top', 'sc_render_comment_form_social_connect' ); - - -function sc_render_login_page_uri(){ - ?> - - __( 'Login or register with Facebook, Twitter, Yahoo, Google or a Wordpress.com account', 'social_connect' )) - ); - } - - /** This is rendered widget content */ - function widget( $args, $instance ) { - extract( $args ); - - if($instance['hide_for_logged_in']==1 && is_user_logged_in()) return; - - echo $before_widget; - - if( !empty( $instance['title'] ) ){ - $title = apply_filters( 'widget_title', $instance[ 'title' ] ); - echo $before_title . $title . $after_title; - } - - if( !empty( $instance['before_widget_content'] ) ){ - echo $instance['before_widget_content']; - } - - sc_render_login_form_social_connect( array( 'display_label' => false ) ); - - if( !empty( $instance['after_widget_content'] ) ){ - echo $instance['after_widget_content']; - } - - echo $after_widget; - } - - /** Everything which should happen when user edit widget at admin panel */ - function update( $new_instance, $old_instance ) { - $instance = $old_instance; - $instance['title'] = strip_tags( $new_instance['title'] ); - $instance['before_widget_content'] = $new_instance['before_widget_content']; - $instance['after_widget_content'] = $new_instance['after_widget_content']; - $instance['hide_for_logged_in'] = $new_instance['hide_for_logged_in']; - - return $instance; - } - - /** Widget edit form at admin panel */ - function form( $instance ) { - /* Set up default widget settings. */ - $defaults = array( 'title' => '', 'before_widget_content' => '', 'after_widget_content' => '' ); - - foreach( $instance as $key => $value ) - $instance[ $key ] = esc_attr( $value ); - - $instance = wp_parse_args( (array)$instance, $defaults ); - ?> -

- - - - - - -

- /> -

- + + + + comment_ID, 'social_connect_comment_via_provider', true ); + if( $social_connect_comment_via_provider && current_user_can( 'manage_options' )) { + return $link . ' '; + } else { + return $link; + } +} +add_action( 'get_comment_author_link', 'sc_social_connect_render_comment_meta' ); + + +function sc_render_comment_form_social_connect() { + if( comments_open() && !is_user_logged_in()) { + sc_render_login_form_social_connect(); + } +} +add_action( 'comment_form_top', 'sc_render_comment_form_social_connect' ); + + +function sc_render_login_page_uri(){ + ?> + + __( 'Login or register with Facebook, Twitter, Yahoo, Google or a Wordpress.com account', 'social_connect' )) + ); + } + + /** This is rendered widget content */ + function widget( $args, $instance ) { + extract( $args ); + + if($instance['hide_for_logged_in']==1 && is_user_logged_in()) return; + + echo $before_widget; + + if( !empty( $instance['title'] ) ){ + $title = apply_filters( 'widget_title', $instance[ 'title' ] ); + echo $before_title . $title . $after_title; + } + + if( !empty( $instance['before_widget_content'] ) ){ + echo $instance['before_widget_content']; + } + + sc_render_login_form_social_connect( array( 'display_label' => false ) ); + + if( !empty( $instance['after_widget_content'] ) ){ + echo $instance['after_widget_content']; + } + + echo $after_widget; + } + + /** Everything which should happen when user edit widget at admin panel */ + function update( $new_instance, $old_instance ) { + $instance = $old_instance; + $instance['title'] = strip_tags( $new_instance['title'] ); + $instance['before_widget_content'] = $new_instance['before_widget_content']; + $instance['after_widget_content'] = $new_instance['after_widget_content']; + $instance['hide_for_logged_in'] = $new_instance['hide_for_logged_in']; + + return $instance; + } + + /** Widget edit form at admin panel */ + function form( $instance ) { + /* Set up default widget settings. */ + $defaults = array( 'title' => '', 'before_widget_content' => '', 'after_widget_content' => '' ); + + foreach( $instance as $key => $value ) + $instance[ $key ] = esc_attr( $value ); + + $instance = wp_parse_args( (array)$instance, $defaults ); + ?> +

+ + + + + + +

+ /> +

+ usermeta WHERE meta_key = '%s' AND meta_value = '%s'"; - return $wpdb->get_var( $wpdb->prepare( $sql, $meta_key, $meta_value ) ); -} - -function social_connect_generate_signature( $data ) { - return hash( 'SHA256', AUTH_KEY . $data ); -} - -function social_connect_verify_signature( $data, $signature, $redirect_to ) { - $generated_signature = social_connect_generate_signature( $data ); - - if( $generated_signature != $signature ) { - wp_safe_redirect( $redirect_to ); - exit(); - } -} - -function sc_http_get_contents( $url ) { - $response = wp_remote_get( $url ); - - if ( is_wp_error( $response ) ) { - die( sprintf( __( 'Something went wrong: %s', 'social-connect' ), $response->get_error_message() ) ); - } else { - return $response['body']; - } -} +usermeta WHERE meta_key = '%s' AND meta_value = '%s'"; + return $wpdb->get_var( $wpdb->prepare( $sql, $meta_key, $meta_value ) ); +} + +function social_connect_generate_signature( $data ) { + return hash( 'SHA256', AUTH_KEY . $data ); +} + +function social_connect_verify_signature( $data, $signature, $redirect_to ) { + $generated_signature = social_connect_generate_signature( $data ); + + if( $generated_signature != $signature ) { + wp_safe_redirect( $redirect_to ); + exit(); + } +} + +function sc_http_get_contents( $url ) { + $response = wp_remote_get( $url ); + + if ( is_wp_error( $response ) ) { + die( sprintf( __( 'Something went wrong: %s', 'social-connect' ), $response->get_error_message() ) ); + } else { + return $response['body']; + } +}