This commit is contained in:
Jaybe
2025-03-05 14:10:06 +09:00
commit 7a77932344
1905 changed files with 122510 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_AOL provider adapter based on OpenID protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_AOL.html
*/
class Hybrid_Providers_AOL extends Hybrid_Provider_Model_OpenID {
var $openidIdentifier = "http://openid.aol.com/";
}
@@ -0,0 +1,337 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Facebook provider adapter based on OAuth2 protocol
*
* Hybrid_Providers_Facebook use the Facebook PHP SDK created by Facebook
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Facebook.html
*/
class Hybrid_Providers_Facebook extends Hybrid_Provider_Model_OAuth2 {
/**
* default permissions, and a lot of them. You can change them from the configuration by setting the scope to what you want/need
* {@inheritdoc}
*/
//public $scope = "email, user_about_me, user_birthday, user_hometown, user_location, user_website, publish_actions, read_custom_friendlists";
public $scope = "email";
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider API end-points
$this->api->api_base_url = 'https://graph.facebook.com/';
$this->api->authorize_url = 'https://www.facebook.com/dialog/oauth';
$this->api->token_url = 'https://graph.facebook.com/v2.3/oauth/access_token';
$this->api->token_debug = 'https://graph.facebook.com/debug_token';
if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) {
throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4);
}
// redirect uri mismatches when authenticating with Facebook.
if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
$this->api->redirect_uri = $this->config['redirect_uri'];
}
}
/**
* {@inheritdoc}
*/
function loginBegin() {
$token = md5(uniqid(mt_rand(), true));
Hybrid_Auth::storage()->set('fb_auth_nonce', $token);
$parameters = array(
"response_type" => "code",
"client_id" => $this->api->client_id,
"redirect_uri" => $this->api->redirect_uri,
"state" => $token,
"scope" => $this->scope,
);
Hybrid_Auth::redirect($this->api->authorizeUrl($parameters));
}
/**
* {@inheritdoc}
*/
function loginFinish() {
// in case we get error_reason=user_denied&error=access_denied
if (isset($_REQUEST['error']) && $_REQUEST['error'] == "access_denied") {
throw new Exception("Authentication failed! The user denied your request.", 5);
}
// try to authenicate user
$code = (array_key_exists('code', $_REQUEST)) ? $_REQUEST['code'] : "";
try{
$response = $this->api->authenticate( $code );
}
catch( Exception $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
}
// check if authenticated
if ( ! $this->api->authenticated() ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 );
}
// store tokens
$this->token("access_token", $this->api->access_token);
$this->token("refresh_token", $this->api->refresh_token);
$this->token("expires_in", $this->api->access_token_expires_in);
$this->token("expires_at", $this->api->access_token_expires_at);
// set user connected locally
$this->setUserConnected();
}
/**
* {@inheritdoc}
*/
function logout() {
parent::logout();
}
/**
* {@inheritdoc}
*/
function getUserProfile() {
// request user profile from fb api
try {
$fields = array(
'id', 'name', 'first_name', 'last_name', 'link', 'website',
'gender', 'locale', 'about', 'email', 'hometown', 'location',
'birthday'
);
$data = $this->api->api('/me?fields=' . implode(',', $fields).'&access_token='.$this->token('access_token'));
} catch (Exception $e) {
$this->logout();
throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e);
}
if( is_object($data) ){
$data = json_decode(json_encode($data), true);
}
// if the provider identifier is not received, we assume the auth has failed
if (!isset($data["id"])) {
$this->logout();
throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData( $data ), 6);
}
# store the user profile.
$this->user->profile->identifier = (array_key_exists('id', $data)) ? $data['id'] : "";
$this->user->profile->username = (array_key_exists('username', $data)) ? $data['username'] : "";
$this->user->profile->displayName = (array_key_exists('name', $data)) ? $data['name'] : "";
$this->user->profile->firstName = (array_key_exists('first_name', $data)) ? $data['first_name'] : "";
$this->user->profile->lastName = (array_key_exists('last_name', $data)) ? $data['last_name'] : "";
$this->user->profile->photoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "/picture?width=150&height=150";
$this->user->profile->coverInfoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "?fields=cover&access_token=" . $this->token('access_token');
$this->user->profile->profileURL = (array_key_exists('link', $data)) ? $data['link'] : "";
$this->user->profile->webSiteURL = (array_key_exists('website', $data)) ? $data['website'] : "";
$this->user->profile->gender = (array_key_exists('gender', $data)) ? $data['gender'] : "";
$this->user->profile->language = (array_key_exists('locale', $data)) ? $data['locale'] : "";
$this->user->profile->description = (array_key_exists('about', $data)) ? $data['about'] : "";
$this->user->profile->email = (array_key_exists('email', $data)) ? $data['email'] : "";
$this->user->profile->emailVerified = (array_key_exists('email', $data)) ? $data['email'] : "";
$this->user->profile->region = (array_key_exists("location", $data) && array_key_exists("name", $data['location'])) ? $data['location']["name"] : "";
if (!empty($this->user->profile->region)) {
$regionArr = explode(',', $this->user->profile->region);
if (count($regionArr) > 1) {
$this->user->profile->city = trim($regionArr[0]);
$this->user->profile->country = trim($regionArr[1]);
}
}
if (array_key_exists('birthday', $data)) {
list($birthday_month, $birthday_day, $birthday_year) = explode("/", $data['birthday']);
$this->user->profile->birthDay = (int) $birthday_day;
$this->user->profile->birthMonth = (int) $birthday_month;
$this->user->profile->birthYear = (int) $birthday_year;
}
// $this->user->profile->sid = get_social_convert_id( $this->user->profile->identifier, $this->providerId );
// $this->user->profile->sid = $this->user->profile->identifier.'.'.$this->providerId;
return $this->user->profile;
}
/**
* Attempt to retrieve the url to the cover image given the coverInfoURL
*
* @param string $coverInfoURL coverInfoURL variable
* @return string url to the cover image OR blank string
*/
function getCoverURL($coverInfoURL) {
try {
$headers = get_headers($coverInfoURL);
if (substr($headers[0], 9, 3) != "404") {
$coverOBJ = json_decode(file_get_contents($coverInfoURL));
if (array_key_exists('cover', $coverOBJ)) {
return $coverOBJ->cover->source;
}
}
} catch (Exception $e) {
}
return "";
}
/**
* {@inheritdoc}
*/
function getUserContacts() {
$apiCall = '?fields=link,name';
$returnedContacts = array();
$pagedList = false;
do {
try {
$response = $this->api->api('/me/friends' . $apiCall);
} catch (Exception $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
}
// Prepare the next call if paging links have been returned
if (array_key_exists('paging', $response) && array_key_exists('next', $response['paging'])) {
$pagedList = true;
$next_page = explode('friends', $response['paging']['next']);
$apiCall = $next_page[1];
} else {
$pagedList = false;
}
// Add the new page contacts
$returnedContacts = array_merge($returnedContacts, $response['data']);
} while ($pagedList == true);
$contacts = array();
foreach ($returnedContacts as $item) {
$uc = new Hybrid_User_Contact();
$uc->identifier = (array_key_exists("id", $item)) ? $item["id"] : "";
$uc->displayName = (array_key_exists("name", $item)) ? $item["name"] : "";
$uc->profileURL = (array_key_exists("link", $item)) ? $item["link"] : "https://www.facebook.com/profile.php?id=" . $uc->identifier;
$uc->photoURL = "https://graph.facebook.com/" . $uc->identifier . "/picture?width=150&height=150";
$contacts[] = $uc;
}
return $contacts;
}
/**
* Update user status
*
* @param mixed $status An array describing the status, or string
* @param string $pageid (optional) User page id
* @return array
* @throw Exception
*/
function setUserStatus($status, $pageid = null) {
if (!is_array($status)) {
$status = array('message' => $status);
}
if (is_null($pageid)) {
$pageid = 'me';
// if post on page, get access_token page
} else {
$access_token = null;
foreach ($this->getUserPages(true) as $p) {
if (isset($p['id']) && intval($p['id']) == intval($pageid)) {
$access_token = $p['access_token'];
break;
}
}
if (is_null($access_token)) {
throw new Exception("Update user page failed, page not found or not writable!");
}
$status['access_token'] = $access_token;
}
try {
$response = $this->api->api('/' . $pageid . '/feed', 'post', $status);
} catch (Exception $e) {
throw new Exception("Update user status failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
}
return $response;
}
/**
* {@inheridoc}
*/
function getUserStatus($postid) {
try {
$postinfo = $this->api->api("/" . $postid);
} catch (Exception $e) {
throw new Exception("Cannot retrieve user status! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
return $postinfo;
}
/**
* {@inheridoc}
*/
function getUserPages($writableonly = false) {
if (( isset($this->config['scope']) && strpos($this->config['scope'], 'manage_pages') === false ) || (!isset($this->config['scope']) && strpos($this->scope, 'manage_pages') === false ))
throw new Exception("User status requires manage_page permission!");
try {
$pages = $this->api->api("/me/accounts", 'get');
} catch (Exception $e) {
throw new Exception("Cannot retrieve user pages! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (!isset($pages['data'])) {
return array();
}
if (!$writableonly) {
return $pages['data'];
}
$wrpages = array();
foreach ($pages['data'] as $p) {
if (isset($p['perms']) && in_array('CREATE_CONTENT', $p['perms'])) {
$wrpages[] = $p;
}
}
return $wrpages;
}
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
* {@inheritdoc}
*/
function getUserActivity($stream) {
try {
if ($stream == "me") {
$response = $this->api->api('/me/feed');
} else {
$response = $this->api->api('/me/home');
}
} catch (Exception $e) {
throw new Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (!$response || !count($response['data'])) {
return array();
}
$activities = array();
foreach ($response['data'] as $item) {
if ($stream == "me" && $item["from"]["id"] != $this->api->getUser()) {
continue;
}
$ua = new Hybrid_User_Activity();
$ua->id = (array_key_exists("id", $item)) ? $item["id"] : "";
$ua->date = (array_key_exists("created_time", $item)) ? strtotime($item["created_time"]) : "";
if ($item["type"] == "video") {
$ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
}
if ($item["type"] == "link") {
$ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
}
if (empty($ua->text) && isset($item["story"])) {
$ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
}
if (empty($ua->text) && isset($item["message"])) {
$ua->text = (array_key_exists("message", $item)) ? $item["message"] : "";
}
if (!empty($ua->text)) {
$ua->user->identifier = (array_key_exists("id", $item["from"])) ? $item["from"]["id"] : "";
$ua->user->displayName = (array_key_exists("name", $item["from"])) ? $item["from"]["name"] : "";
$ua->user->profileURL = "https://www.facebook.com/profile.php?id=" . $ua->user->identifier;
$ua->user->photoURL = "https://graph.facebook.com/" . $ua->user->identifier . "/picture?type=square";
$activities[] = $ua;
}
}
return $activities;
}
}
@@ -0,0 +1,121 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Foursquare provider adapter based on OAuth2 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Foursquare.html
*/
/**
* Howto define profile photo size:
* - add params key into hybridauth config
* ...
* "Foursquare" => array (
* "enabled" => true,
* "keys" => ...,
* "params" => array( "photo_size" => "16x16" )
* ),
* ...
* - list of valid photo_size values is described here https://developer.foursquare.com/docs/responses/photo.html
* - default photo_size is 100x100
*/
class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2 {
private static $apiVersion = array("v" => "20120610");
private static $defPhotoSize = "100x100";
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider apis end-points
$this->api->api_base_url = "https://api.foursquare.com/v2/";
$this->api->authorize_url = "https://foursquare.com/oauth2/authenticate";
$this->api->token_url = "https://foursquare.com/oauth2/access_token";
$this->api->sign_token_name = "oauth_token";
}
/**
* {@inheritdoc}
*/
function getUserProfile() {
$data = $this->api->api("users/self", "GET", Hybrid_Providers_Foursquare::$apiVersion);
if (!isset($data->response->user->id)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $data ), 6);
}
$data = $data->response->user;
$this->user->profile->identifier = $data->id;
$this->user->profile->firstName = $data->firstName;
$this->user->profile->lastName = $data->lastName;
$this->user->profile->displayName = $this->buildDisplayName($this->user->profile->firstName, $this->user->profile->lastName);
$this->user->profile->photoURL = $this->buildPhotoURL($data->photo->prefix, $data->photo->suffix);
$this->user->profile->profileURL = "https://www.foursquare.com/user/" . $data->id;
$this->user->profile->gender = $data->gender;
$this->user->profile->city = $data->homeCity;
$this->user->profile->email = $data->contact->email;
$this->user->profile->emailVerified = $data->contact->email;
return $this->user->profile;
}
/**
* {@inheritdoc}
*/
function getUserContacts() {
// refresh tokens if needed
$this->refreshToken();
//
$response = array();
$contacts = array();
try {
$response = $this->api->api("users/self/friends", "GET", Hybrid_Providers_Foursquare::$apiVersion);
} catch (Exception $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (isset($response) && $response->meta->code == 200) {
foreach ($response->response->friends->items as $contact) {
$uc = new Hybrid_User_Contact();
//
$uc->identifier = $contact->id;
//$uc->profileURL = ;
//$uc->webSiteURL = ;
$uc->photoURL = $this->buildPhotoURL($contact->photo->prefix, $contact->photo->suffix);
$uc->displayName = $this->buildDisplayName((isset($contact->firstName) ? ($contact->firstName) : ("")), (isset($contact->lastName) ? ($contact->lastName) : ("")));
//$uc->description = ;
$uc->email = (isset($contact->contact->email) ? ($contact->contact->email) : (""));
//
$contacts[] = $uc;
}
}
return $contacts;
}
/**
* {@inheritdoc}
*/
private function buildDisplayName($firstName, $lastName) {
return trim($firstName . " " . $lastName);
}
private function buildPhotoURL($prefix, $suffix) {
if (isset($prefix) && isset($suffix)) {
return $prefix . ((isset($this->config["params"]["photo_size"])) ? ($this->config["params"]["photo_size"]) : (Hybrid_Providers_Foursquare::$defPhotoSize)) . $suffix;
}
return ("");
}
}
+180
View File
@@ -0,0 +1,180 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Google provider adapter based on OAuth2 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Google.html
*/
class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 {
/**
* > more infos on google APIs: http://developer.google.com (official site)
* or here: http://discovery-check.appspot.com/ (unofficial but up to date)
* default permissions
* {@inheritdoc}
*/
public $scope = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds/";
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider api end-points
$this->api->authorize_url = "https://accounts.google.com/o/oauth2/auth";
$this->api->token_url = "https://accounts.google.com/o/oauth2/token";
$this->api->token_info_url = "https://www.googleapis.com/oauth2/v2/tokeninfo";
// Google POST methods require an access_token in the header
$this->api->curl_header = array("Authorization: OAuth " . $this->api->access_token);
// Override the redirect uri when it's set in the config parameters. This way we prevent
// redirect uri mismatches when authenticating with Google.
if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
$this->api->redirect_uri = $this->config['redirect_uri'];
}
}
/**
* {@inheritdoc}
*/
function loginBegin() {
$parameters = array("scope" => $this->scope, "access_type" => "offline");
$optionals = array("scope", "access_type", "redirect_uri", "approval_prompt", "hd", "state");
foreach ($optionals as $parameter) {
if (isset($this->config[$parameter]) && !empty($this->config[$parameter])) {
$parameters[$parameter] = $this->config[$parameter];
}
if (isset($this->config["scope"]) && !empty($this->config["scope"])) {
$this->scope = $this->config["scope"];
}
}
if (isset($this->config['force']) && $this->config['force'] === true) {
$parameters['approval_prompt'] = 'force';
}
Hybrid_Auth::redirect($this->api->authorizeUrl($parameters));
}
/**
* {@inheritdoc}
*/
function getUserProfile() {
// refresh tokens if needed
$this->refreshToken();
$response = $this->api->api("https://www.googleapis.com/oauth2/v3/userinfo");
if (!isset($response->sub) || isset($response->error)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $response ), 6);
}
$this->user->profile->identifier = (property_exists($response, 'sub')) ? $response->sub : "";
$this->user->profile->firstName = (property_exists($response, 'given_name')) ? $response->given_name : "";
$this->user->profile->lastName = (property_exists($response, 'family_name')) ? $response->family_name : "";
$this->user->profile->displayName = (property_exists($response, 'name')) ? $response->name : "";
$this->user->profile->photoURL = (property_exists($response, 'picture')) ? $response->picture : "";
$this->user->profile->profileURL = (property_exists($response, 'profile')) ? $response->profile : "";
$this->user->profile->gender = (property_exists($response, 'gender')) ? $response->gender : "";
$this->user->profile->language = (property_exists($response, 'locale')) ? $response->locale : "";
$this->user->profile->email = (property_exists($response, 'email')) ? $response->email : "";
$this->user->profile->emailVerified = (property_exists($response, 'email_verified')) ? ($response->email_verified === true || $response->email_verified === 1 ? $response->email : "") : "";
return $this->user->profile;
}
/**
* {@inheritdoc}
*/
function getUserContacts() {
// refresh tokens if needed
$this->refreshToken();
$contacts = array();
if (!isset($this->config['contacts_param'])) {
$this->config['contacts_param'] = array("max-results" => 500);
}
// Google Gmail and Android contacts
if (strpos($this->scope, '/m8/feeds/') !== false) {
$response = $this->api->api("https://www.google.com/m8/feeds/contacts/default/full?"
. http_build_query(array_merge(array('alt' => 'json'), $this->config['contacts_param'])));
if (!$response) {
return array();
}
if (isset($response->feed->entry)) {
foreach ($response->feed->entry as $idx => $entry) {
$uc = new Hybrid_User_Contact();
$uc->email = isset($entry->{'gd$email'}[0]->address) ? (string) $entry->{'gd$email'}[0]->address : '';
$uc->displayName = isset($entry->title->{'$t'}) ? (string) $entry->title->{'$t'} : '';
$uc->identifier = ($uc->email != '') ? $uc->email : '';
$uc->description = '';
if (property_exists($entry, 'link')) {
/**
* sign links with access_token
*/
if (is_array($entry->link)) {
foreach ($entry->link as $l) {
if (property_exists($l, 'gd$etag') && $l->type == "image/*") {
$uc->photoURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token));
} else if ($l->type == "self") {
$uc->profileURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token));
}
}
}
} else {
$uc->profileURL = '';
}
if (property_exists($response, 'website')) {
if (is_array($response->website)) {
foreach ($response->website as $w) {
if ($w->primary == true)
$uc->webSiteURL = $w->value;
}
} else {
$uc->webSiteURL = $response->website->value;
}
} else {
$uc->webSiteURL = '';
}
$contacts[] = $uc;
}
}
}
return $contacts;
}
/**
* Add query parameters to the $url
*
* @param string $url URL
* @param array $params Parameters to add
* @return string
*/
function addUrlParam($url, array $params){
$query = parse_url($url, PHP_URL_QUERY);
// Returns the URL string with new parameters
if ($query) {
$url .= '&' . http_build_query($params);
} else {
$url .= '?' . http_build_query($params);
}
return $url;
}
}
@@ -0,0 +1,306 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Google provider adapter based on OAuth2 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Google.html
*/
class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 {
/**
* > more infos on google APIs: http://developer.google.com (official site)
* or here: http://discovery-check.appspot.com/ (unofficial but up to date)
* default permissions
* {@inheritdoc}
*/
public $scope = "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/plus.profile.emails.read https://www.google.com/m8/feeds/";
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider api end-points
$this->api->authorize_url = "https://accounts.google.com/o/oauth2/auth";
$this->api->token_url = "https://accounts.google.com/o/oauth2/token";
$this->api->token_info_url = "https://www.googleapis.com/oauth2/v2/tokeninfo";
// Google POST methods require an access_token in the header
$this->api->curl_header = array("Authorization: OAuth " . $this->api->access_token);
// Override the redirect uri when it's set in the config parameters. This way we prevent
// redirect uri mismatches when authenticating with Google.
if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
$this->api->redirect_uri = $this->config['redirect_uri'];
}
}
/**
* {@inheritdoc}
*/
function loginBegin() {
$parameters = array("scope" => $this->scope, "access_type" => "offline");
$optionals = array("scope", "access_type", "redirect_uri", "approval_prompt", "hd", "state");
foreach ($optionals as $parameter) {
if (isset($this->config[$parameter]) && !empty($this->config[$parameter])) {
$parameters[$parameter] = $this->config[$parameter];
}
if (isset($this->config["scope"]) && !empty($this->config["scope"])) {
$this->scope = $this->config["scope"];
}
}
if (isset($this->config['force']) && $this->config['force'] === true) {
$parameters['approval_prompt'] = 'force';
}
Hybrid_Auth::redirect($this->api->authorizeUrl($parameters));
}
/**
* {@inheritdoc}
*/
function getUserProfile() {
// refresh tokens if needed
$this->refreshToken();
// ask google api for user infos
if (strpos($this->scope, '/auth/plus.profile.emails.read') !== false) {
$verified = $this->api->api("https://www.googleapis.com/plus/v1/people/me");
if (!isset($verified->id) || isset($verified->error))
$verified = new stdClass();
} else {
$verified = $this->api->api("https://www.googleapis.com/plus/v1/people/me/openIdConnect");
if (!isset($verified->sub) || isset($verified->error))
$verified = new stdClass();
}
$response = $this->api->api("https://www.googleapis.com/plus/v1/people/me");
if (!isset($response->id) || isset($response->error)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $response ), 6);
}
$this->user->profile->identifier = (property_exists($verified, 'id')) ? $verified->id : ((property_exists($response, 'id')) ? $response->id : "");
$this->user->profile->firstName = (property_exists($response, 'name')) ? $response->name->givenName : "";
$this->user->profile->lastName = (property_exists($response, 'name')) ? $response->name->familyName : "";
$this->user->profile->displayName = (property_exists($response, 'displayName')) ? $response->displayName : "";
$this->user->profile->photoURL = (property_exists($response, 'image')) ? ((property_exists($response->image, 'url')) ? substr($response->image->url, 0, -2) . "200" : '') : '';
$this->user->profile->profileURL = (property_exists($response, 'url')) ? $response->url : "";
$this->user->profile->description = (property_exists($response, 'aboutMe')) ? $response->aboutMe : "";
$this->user->profile->gender = (property_exists($response, 'gender')) ? $response->gender : "";
$this->user->profile->language = (property_exists($response, 'locale')) ? $response->locale : ((property_exists($verified, 'locale')) ? $verified->locale : "");
$this->user->profile->email = (property_exists($response, 'email')) ? $response->email : ((property_exists($verified, 'email')) ? $verified->email : "");
$this->user->profile->emailVerified = (property_exists($verified, 'email')) ? $verified->email : "";
if (property_exists($response, 'emails')) {
if (count($response->emails) == 1) {
$this->user->profile->email = $response->emails[0]->value;
} else {
foreach ($response->emails as $email) {
if ($email->type == 'account') {
$this->user->profile->email = $email->value;
break;
}
}
}
if (property_exists($verified, 'emails')) {
if (count($verified->emails) == 1) {
$this->user->profile->emailVerified = $verified->emails[0]->value;
} else {
foreach ($verified->emails as $email) {
if ($email->type == 'account') {
$this->user->profile->emailVerified = $email->value;
break;
}
}
}
}
}
$this->user->profile->phone = (property_exists($response, 'phone')) ? $response->phone : "";
$this->user->profile->country = (property_exists($response, 'country')) ? $response->country : "";
$this->user->profile->region = (property_exists($response, 'region')) ? $response->region : "";
$this->user->profile->zip = (property_exists($response, 'zip')) ? $response->zip : "";
if (property_exists($response, 'placesLived')) {
$this->user->profile->city = "";
$this->user->profile->address = "";
foreach ($response->placesLived as $c) {
if (property_exists($c, 'primary')) {
if ($c->primary == true) {
$this->user->profile->address = $c->value;
$this->user->profile->city = $c->value;
break;
}
} else {
if (property_exists($c, 'value')) {
$this->user->profile->address = $c->value;
$this->user->profile->city = $c->value;
}
}
}
}
// google API returns multiple urls, but a "website" only if it is verified
// see http://support.google.com/plus/answer/1713826?hl=en
if (property_exists($response, 'urls')) {
foreach ($response->urls as $u) {
if (property_exists($u, 'primary') && $u->primary == true)
$this->user->profile->webSiteURL = $u->value;
}
} else {
$this->user->profile->webSiteURL = '';
}
// google API returns age ranges min and/or max as of https://developers.google.com/+/web/api/rest/latest/people#resource
if (property_exists($response, 'ageRange')) {
if (property_exists($response->ageRange, 'min') && property_exists($response->ageRange, 'max')) {
$this->user->profile->age = $response->ageRange->min . ' - ' . $response->ageRange->max;
} else {
if (property_exists($response->ageRange, 'min')) {
$this->user->profile->age = '>= ' . $response->ageRange->min;
} else {
if (property_exists($response->ageRange, 'max')) {
$this->user->profile->age = '<= ' . $response->ageRange->max;
} else {
$this->user->profile->age = '';
}
}
}
} else {
$this->user->profile->age = '';
}
// google API returns birthdays only if a user set 'show in my account'
if (property_exists($response, 'birthday')) {
list($birthday_year, $birthday_month, $birthday_day) = explode('-', $response->birthday);
$this->user->profile->birthDay = (int) $birthday_day;
$this->user->profile->birthMonth = (int) $birthday_month;
$this->user->profile->birthYear = (int) $birthday_year;
} else {
$this->user->profile->birthDay = 0;
$this->user->profile->birthMonth = 0;
$this->user->profile->birthYear = 0;
}
return $this->user->profile;
}
/**
* {@inheritdoc}
*/
function getUserContacts() {
// refresh tokens if needed
$this->refreshToken();
$contacts = array();
if (!isset($this->config['contacts_param'])) {
$this->config['contacts_param'] = array("max-results" => 500);
}
// Google Gmail and Android contacts
if (strpos($this->scope, '/m8/feeds/') !== false) {
$response = $this->api->api("https://www.google.com/m8/feeds/contacts/default/full?"
. http_build_query(array_merge(array('alt' => 'json'), $this->config['contacts_param'])));
if (!$response) {
return array();
}
if (isset($response->feed->entry)) {
foreach ($response->feed->entry as $idx => $entry) {
$uc = new Hybrid_User_Contact();
$uc->email = isset($entry->{'gd$email'}[0]->address) ? (string) $entry->{'gd$email'}[0]->address : '';
$uc->displayName = isset($entry->title->{'$t'}) ? (string) $entry->title->{'$t'} : '';
$uc->identifier = ($uc->email != '') ? $uc->email : '';
$uc->description = '';
if (property_exists($entry, 'link')) {
/**
* sign links with access_token
*/
if (is_array($entry->link)) {
foreach ($entry->link as $l) {
if (property_exists($l, 'gd$etag') && $l->type == "image/*") {
$uc->photoURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token));
} else if ($l->type == "self") {
$uc->profileURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token));
}
}
}
} else {
$uc->profileURL = '';
}
if (property_exists($response, 'website')) {
if (is_array($response->website)) {
foreach ($response->website as $w) {
if ($w->primary == true)
$uc->webSiteURL = $w->value;
}
} else {
$uc->webSiteURL = $response->website->value;
}
} else {
$uc->webSiteURL = '';
}
$contacts[] = $uc;
}
}
}
// Google social contacts
if (strpos($this->scope, '/auth/plus.login') !== false) {
$response = $this->api->api("https://www.googleapis.com/plus/v1/people/me/people/visible?"
. http_build_query($this->config['contacts_param']));
if (!$response) {
return array();
}
foreach ($response->items as $idx => $item) {
$uc = new Hybrid_User_Contact();
$uc->email = (property_exists($item, 'email')) ? $item->email : '';
$uc->displayName = (property_exists($item, 'displayName')) ? $item->displayName : '';
$uc->identifier = (property_exists($item, 'id')) ? $item->id : '';
$uc->description = (property_exists($item, 'objectType')) ? $item->objectType : '';
$uc->photoURL = (property_exists($item, 'image')) ? ((property_exists($item->image, 'url')) ? $item->image->url : '') : '';
$uc->profileURL = (property_exists($item, 'url')) ? $item->url : '';
$uc->webSiteURL = '';
$contacts[] = $uc;
}
}
return $contacts;
}
/**
* Add query parameters to the $url
*
* @param string $url URL
* @param array $params Parameters to add
* @return string
*/
function addUrlParam($url, array $params){
$query = parse_url($url, PHP_URL_QUERY);
// Returns the URL string with new parameters
if ($query) {
$url .= '&' . http_build_query($params);
} else {
$url .= '?' . http_build_query($params);
}
return $url;
}
}
+204
View File
@@ -0,0 +1,204 @@
<?php
/**
* Copyright (c) 2014 Team TamedBitches.
* Written by Chuck JS. Oh <jinseokoh@hotmail.com>
* http://facebook.com/chuckoh
*
* Date: 11 10, 2014
* Time: 01:51 AM
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/txt/copying/ for more details.
*
*/
//https://github.com/jinseokoh/additional-providers
class Hybrid_Providers_Kakao extends Hybrid_Provider_Model_OAuth2
{
/**
* initialization
*/
function initialize()
{
parent::initialize();
// Provider API end-points
//$this->api->api_base_url = "https://kapi.kakao.com/v1/";
$this->api->api_base_url = "https://kapi.kakao.com/v2/";
$this->api->authorize_url = "https://kauth.kakao.com/oauth/authorize";
$this->api->token_url = "https://kauth.kakao.com/oauth/token";
// redirect uri mismatches when authenticating with Kakao.
if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
$this->api->redirect_uri = $this->config['redirect_uri'];
}
}
/**
* finish login step
*/
function loginFinish()
{
$error = (array_key_exists('error', $_REQUEST)) ? $_REQUEST['error'] : "";
// check for errors
if ( $error ){
throw new Exception( "Authentication failed! {$this->providerId} returned an error: $error", 5 );
}
// try to authenicate user
$code = (array_key_exists('code', $_REQUEST)) ? $_REQUEST['code'] : "";
try{
$this->authenticate( $code );
}
catch( Exception $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
}
// check if authenticated
if ( ! $this->api->access_token ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 );
}
// store tokens
$this->token("access_token", $this->api->access_token);
$this->token("refresh_token", $this->api->refresh_token);
$this->token("expires_in", $this->api->access_token_expires_in);
$this->token("expires_at", $this->api->access_token_expires_at);
// set user connected locally
$this->setUserConnected();
}
/**
* load the user profile
*/
function getUserProfile()
{
//$params = array('property_keys'=>'kaccount_email'); // v1 parameter
$params = array('property_keys'=>array('kakao_account.email')); // v2 parameter
$this->api->decode_json = false;
$this->api->curl_header = array( 'Authorization: Bearer ' . $this->api->access_token );
$data = $this->api->api("user/me", "POST", $params);
if ( ! isset( $data->id ) ) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response.", 6);
}
# store the user profile.
$this->user->profile->identifier = @ $data->id;
$this->user->profile->displayName = @ $data->properties->nickname;
$this->user->profile->photoURL = @ $data->properties->thumbnail_image;
//$email = @ $data->properties->kaccount_email; // v1 version
$phone_number = @ $data->kakao_account->phone_number; // 010-1111-2222의 경우, +82 10-1111-2222
if ($phone_number) {
// 국제번호 를 0 으로 변경
if (strpos($phone_number, '+82 ') === 0) $phone_number = str_replace('+82 ', '0', $phone_number);
$this->user->profile->phone = $phone_number;
}
$birthyear = @ $data->kakao_account->birthyear; // 1990
if ($birthyear) $this->user->profile->birthYear = $birthyear;
$birthday = @ $data->kakao_account->birthday; // 0708
if ($birthday) {
list($_m, $_d) = str_split($birthday, 2);
$this->user->profile->birthMonth = ltrim($_m, '0');
$this->user->profile->birthDay = ltrim($_d, '0');
}
$nickname = @ $data->kakao_account->profile->nickname;
if (!$this->user->profile->displayName && $nickname) {
$this->user->profile->displayName = $nickname;
}
$email = @ $data->kakao_account->email; // v2 version
if( $email ){
$this->user->profile->email = $email;
}
// $this->user->profile->sid = get_social_convert_id( $this->user->profile->identifier, $this->providerId );
// $this->user->profile->sid = $this->user->profile->identifier.'.'.$this->providerId;
return $this->user->profile;
}
private function authenticate($code)
{
$params = array(
"grant_type" => "authorization_code",
"client_id" => $this->api->client_id,
"redirect_uri" => $this->api->redirect_uri,
"code" => $code
);
if( $this->api->client_secret && ($this->api->client_secret !== $this->api->client_id) ){
$params['client_secret'] = $this->api->client_secret;
}
$response = $this->request($this->api->token_url, $params, $this->api->curl_authenticate_method);
$response = $this->parseRequestResult($response);
if ( ! $response || ! isset($response->access_token) ) {
throw new Exception("The Authorization Service has return: " . $response->error);
}
if ( isset($response->access_token) ) $this->api->access_token = $response->access_token;
if ( isset($response->refresh_token) ) $this->api->refresh_token = $response->refresh_token;
if ( isset($response->expires_in) ) $this->api->access_token_expires_in = $response->expires_in;
// calculate when the access token expire
if ( isset($response->expires_in) ) {
$this->api->access_token_expires_at = time() + $response->expires_in;
}
return $response;
}
private function request($url, $params=false, $type="GET")
{
if(Class_exists('Hybrid_Logger')){
Hybrid_Logger::info("Enter OAuth2Client::request( $url )");
Hybrid_Logger::debug("OAuth2Client::request(). dump request params: ", serialize( $params ));
}
$this->http_info = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT , $this->api->curl_time_out);
curl_setopt($ch, CURLOPT_USERAGENT , $this->api->curl_useragent);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->api->curl_connect_time_out);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->api->curl_ssl_verifypeer);
curl_setopt($ch, CURLOPT_HTTPHEADER , $this->api->curl_header);
if ( $this->api->curl_proxy ) {
curl_setopt( $ch, CURLOPT_PROXY, $this->curl_proxy);
}
if ( $type == "POST" ) {
curl_setopt($ch, CURLOPT_POST, 1);
if ($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($params) );
}
$response = curl_exec($ch);
if(Class_exists('Hybrid_Logger')){
Hybrid_Logger::debug( "OAuth2Client::request(). dump request info: ", serialize(curl_getinfo($ch)) );
Hybrid_Logger::debug( "OAuth2Client::request(). dump request result: ", serialize($response ));
}
$this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->http_info = array_merge($this->http_info, curl_getinfo($ch));
curl_close ($ch);
return $response;
}
private function parseRequestResult($result)
{
if ( json_decode($result) ) return json_decode($result);
parse_str( $result, $ouput );
$result = new StdClass();
foreach( $ouput as $k => $v )
$result->$k = $v;
return $result;
}
}
@@ -0,0 +1,170 @@
<?php
/* !
* Hybridauth
* https://hybridauth.github.io/hybridauth | https://github.com/hybridauth/hybridauth
* (c) 2017 Hybridauth authors | https://hybridauth.github.io/license.html
*/
/**
* Hybrid_Providers_LinkedIn OAuth2 provider adapter.
*/
class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model_OAuth2 {
/**
* {@inheritdoc}
*/
public $scope = "r_basicprofile r_emailaddress";
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider api end-points.
$this->api->api_base_url = "https://api.linkedin.com/v1/";
$this->api->authorize_url = "https://www.linkedin.com/oauth/v2/authorization";
$this->api->token_url = "https://www.linkedin.com/oauth/v2/accessToken";
}
/**
* {@inheritdoc}
*/
function loginBegin() {
if (is_array($this->scope)) {
$this->scope = implode(" ", $this->scope);
}
parent::loginBegin();
}
/**
* {@inheritdoc}
*
* @see https://developer.linkedin.com/docs/rest-api
*/
function getUserProfile() {
// Refresh tokens if needed.
$this->setHeaders("token");
$this->refreshToken();
// https://developer.linkedin.com/docs/fields.
$fields = isset($this->config["fields"]) ? $this->config["fields"] : [
"id",
"email-address",
"first-name",
"last-name",
"headline",
"location",
"industry",
"picture-url",
"public-profile-url",
];
$this->setHeaders();
$response = $this->api->get(
"people/~:(" . implode(",", $fields) . ")",
array(
"format" => "json",
)
);
if (!isset($response->id)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response), 6);
}
$this->user->profile->identifier = isset($response->id) ? $response->id : "";
$this->user->profile->firstName = isset($response->firstName) ? $response->firstName : "";
$this->user->profile->lastName = isset($response->lastName) ? $response->lastName : "";
$this->user->profile->photoURL = isset($response->pictureUrl) ? $response->pictureUrl : "";
$this->user->profile->profileURL = isset($response->publicProfileUrl) ? $response->publicProfileUrl : "";
$this->user->profile->email = isset($response->emailAddress) ? $response->emailAddress : "";
$this->user->profile->description = isset($response->headline) ? $response->headline : "";
$this->user->profile->country = isset($response->location) ? $response->location->name : "";
$this->user->profile->emailVerified = $this->user->profile->email;
$this->user->profile->displayName = trim($this->user->profile->firstName . " " . $this->user->profile->lastName);
return $this->user->profile;
}
/**
* {@inheritdoc}
*
* @param array $status
* An associative array containing:
* - content: A collection of fields describing the shared content.
* - comment: A comment by the member to associated with the share.
* - visibility: A collection of visibility information about the share.
*
* @return object
* An object containing:
* - updateKey - A unique ID for the shared content posting that was just created.
* - updateUrl - A direct link to the newly shared content on LinkedIn.com that you can direct the user's web browser to.
* @throws Exception
* @see https://developer.linkedin.com/docs/share-on-linkedin
*/
function setUserStatus($status) {
// Refresh tokens if needed.
$this->setHeaders("token");
$this->refreshToken();
try {
// Define default visibility.
if (!isset($status["visibility"])) {
$status["visibility"]["code"] = "anyone";
}
$this->setHeaders("share");
$response = $this->api->post(
"people/~/shares?format=json",
array(
"body" => $status,
)
);
} catch (Exception $e) {
throw new Exception("Update user status failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (!isset($response->updateKey)) {
throw new Exception("Update user status failed! {$this->providerId} returned an error: {$response->message}", $response->errorCode);
}
return $response;
}
/**
* Set correct request headers.
*
* @param string $api_type
* (optional) Specify api type.
*
* @return void
*/
private function setHeaders($api_type = null) {
$this->api->curl_header = array(
"Authorization: Bearer {$this->api->access_token}",
);
switch ($api_type) {
case "share":
$this->api->curl_header = array_merge(
$this->api->curl_header,
array(
"Content-Type: application/json",
"x-li-format: json",
)
);
break;
case "token":
$this->api->curl_header = array_merge(
$this->api->curl_header,
array(
"Content-Type: application/x-www-form-urlencoded",
)
);
break;
}
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Windows Live OAuth2 Class
*
* @package HybridAuth providers package
* @author Lukasz Koprowski <azram19@gmail.com>
* @version 0.2
* @license BSD License
*/
/**
* Hybrid_Providers_Live - Windows Live provider adapter based on OAuth2 protocol
*/
class Hybrid_Providers_Live extends Hybrid_Provider_Model_OAuth2 {
/**
* {@inheritdoc}
*/
public $scope = 'wl.basic wl.contacts_emails wl.emails wl.signin wl.share wl.birthday';
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider api end-points
$this->api->api_base_url = 'https://apis.live.net/v5.0/';
$this->api->authorize_url = 'https://login.live.com/oauth20_authorize.srf';
$this->api->token_url = 'https://login.live.com/oauth20_token.srf';
}
/**
* {@inheritdoc}
*/
function getUserProfile() {
$data = $this->api->get("me");
if (!isset($data->id)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $data ), 6);
}
$this->user->profile->identifier = (property_exists($data, 'id')) ? $data->id : "";
$this->user->profile->firstName = (property_exists($data, 'first_name')) ? $data->first_name : "";
$this->user->profile->lastName = (property_exists($data, 'last_name')) ? $data->last_name : "";
$this->user->profile->displayName = (property_exists($data, 'name')) ? trim($data->name) : "";
$this->user->profile->gender = (property_exists($data, 'gender')) ? $data->gender : "";
//wl.basic
$this->user->profile->profileURL = (property_exists($data, 'link')) ? $data->link : "";
//wl.emails
$this->user->profile->email = (property_exists($data, 'emails')) ? $data->emails->preferred : "";
$this->user->profile->emailVerified = (property_exists($data, 'emails')) ? $data->emails->account : "";
//wl.birthday
$this->user->profile->birthDay = (property_exists($data, 'birth_day')) ? $data->birth_day : "";
$this->user->profile->birthMonth = (property_exists($data, 'birth_month')) ? $data->birth_month : "";
$this->user->profile->birthYear = (property_exists($data, 'birth_year')) ? $data->birth_year : "";
return $this->user->profile;
}
/**
* Windows Live api does not support retrieval of email addresses (only hashes :/)
* {@inheritdoc}
*/
function getUserContacts() {
$response = $this->api->get('me/contacts');
if ($this->api->http_code != 200) {
throw new Exception('User contacts request failed! ' . $this->providerId . ' returned an error: ' . $this->errorMessageByStatus($this->api->http_code));
}
if (!isset($response->data) || ( isset($response->errcode) && $response->errcode != 0 )) {
return array();
}
$contacts = array();
foreach ($response->data as $item) {
$uc = new Hybrid_User_Contact();
$uc->identifier = (property_exists($item, 'id')) ? $item->id : "";
$uc->displayName = (property_exists($item, 'name')) ? $item->name : "";
$uc->email = (property_exists($item, 'emails')) ? $item->emails->preferred : "";
$contacts[] = $uc;
}
return $contacts;
}
}
+239
View File
@@ -0,0 +1,239 @@
<?php
/**
* Copyright (c) 2014 Team TamedBitches.
* Written by Chuck JS. Oh <jinseokoh@hotmail.com>
* http://facebook.com/chuckoh
*
* Date: 11 11, 2014
* Time: 11:38 AM
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/txt/copying/ for more details.
*
*/
//https://github.com/jinseokoh/additional-providers
class Hybrid_Providers_Naver extends Hybrid_Provider_Model_OAuth2
{
/**
* initialization
*/
function initialize()
{
parent::initialize();
// Provider API end-points
$this->api->api_base_url = "https://apis.naver.com/nidlogin/";
$this->api->authorize_url = "https://nid.naver.com/oauth2.0/authorize";
$this->api->token_url = "https://nid.naver.com/oauth2.0/token";
// redirect uri mismatches when authenticating with Naver.
if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
$this->api->redirect_uri = $this->config['redirect_uri'];
}
}
/**
* begin login step
*/
function loginBegin()
{
$token = $this->generate_state_token();
Hybrid_Auth::storage()->set("naver_state_token", $token);
$parameters = array(
"response_type" => "code",
"client_id" => $this->api->client_id,
"redirect_uri" => $this->api->redirect_uri,
"state" => $token,
);
Hybrid_Auth::redirect($this->api->authorizeUrl($parameters));
}
/**
* finish login step
*/
function loginFinish()
{
$error = (array_key_exists('error', $_REQUEST)) ? $_REQUEST['error'] : "";
// check for errors
if ( $error ){
throw new Exception( "Authentication failed! {$this->providerId} returned an error: $error", 5 );
}
// try to authenicate user
$code = (array_key_exists('code', $_REQUEST)) ? $_REQUEST['code'] : "";
try{
$this->authenticate( $code );
}
catch( Exception $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
}
// check if authenticated
if ( ! $this->api->access_token ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 );
}
// store tokens
$this->token("access_token", $this->api->access_token);
$this->token("refresh_token", $this->api->refresh_token);
$this->token("expires_in", $this->api->access_token_expires_in);
$this->token("expires_at", $this->api->access_token_expires_at);
// set user connected locally
$this->setUserConnected();
}
/**
* set propper headers
*/
function profile($url) {
$this->api->decode_json = false;
$this->api->curl_header = array( 'Authorization: Bearer ' . $this->api->access_token );
$response = $this->api->get($url, array(), false);
return $response;
}
/**
* load the user profile
*/
//https://developers.naver.com/docs/login/profile/
function getUserProfile()
{
$response = $this->profile("nid/getUserProfile.xml");
$xml = @ new SimpleXMLElement($response);
$data = array();
if ( $xml->result[0]->resultcode == '00' ) {
foreach ($xml->response->children() as $response => $k) {
$data[(string)$response] = (string) $k;
}
} else {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response.", 6);
}
# store the user profile.
//$this->user->profile->identifier = (array_key_exists('enc_id',$data))?$data['enc_id']:"";
$this->user->profile->identifier = (array_key_exists('id',$data))?$data['id']:"";
$this->user->profile->age = (array_key_exists('age',$data))?$data['age']:"";
$this->user->profile->username = (array_key_exists('name', $data)) ? $data['name'] : "";
/*
if( array_key_exists('email',$data) ){
$tmp = explode("@", $data['email']);
$this->user->profile->displayName = $tmp[0];
}
*/
$this->user->profile->displayName = (array_key_exists('nickname',$data))?$data['nickname']:"";
// 2020-06-12 username 값이 있는 경우 displayName을 username 으로 셋팅
if ($this->user->profile->username != '')
$this->user->profile->displayName = $this->user->profile->username;
$this->user->profile->birthDay = '';
$this->user->profile->birthMonth = '';
if( array_key_exists('birthday',$data) ){
$tmp = explode("-",$data['birthday']);
if( isset($tmp[0]) ){
$this->user->profile->birthDay = $tmp[0];
}
if( isset($tmp[1]) ){
$this->user->profile->birthMonth = $tmp[1];
}
}
$this->user->profile->email = (array_key_exists('email',$data))?$data['email']:"";
$this->user->profile->emailVerified = (array_key_exists('email',$data))?$data['email']:"";
$this->user->profile->gender = (array_key_exists('gender',$data))?(($data['gender'] == "M")?"male":"female"):"";
$this->user->profile->photoURL = (array_key_exists('profile_image',$data))?$data['profile_image']:"";
// $this->user->profile->sid = get_social_convert_id( $this->user->profile->identifier, $this->providerId );
// $this->user->profile->sid = $this->user->profile->identifier.'.'.$this->providerId;
return $this->user->profile;
}
private function authenticate($code)
{
$token = Hybrid_Auth::storage()->get("naver_state_token");
$params = array(
"grant_type" => "authorization_code",
"client_id" => $this->api->client_id,
"client_secret" => $this->api->client_secret,
// "redirect_uri" => $this->api->redirect_uri,
"code" => $code,
"state" => $token
);
Hybrid_Auth::storage()->set("naver_state_token", null);
$response = $this->request($this->api->token_url, $params, $this->api->curl_authenticate_method);
$response = $this->parseRequestResult($response);
if ( ! $response || ! isset($response->access_token) ) {
throw new Exception("The Authorization Service has return: " . $response->error);
}
if ( isset($response->access_token) ) $this->api->access_token = $response->access_token;
if ( isset($response->refresh_token) ) $this->api->refresh_token = $response->refresh_token;
if ( isset($response->expires_in) ) $this->api->access_token_expires_in = $response->expires_in;
// calculate when the access token expire
if ( isset($response->expires_in) ) {
$this->api->access_token_expires_at = time() + $response->expires_in;
}
return $response;
}
private function request($url, $params=false, $type="GET")
{
if(Class_exists('Hybrid_Logger')){
Hybrid_Logger::info("Enter OAuth2Client::request( $url )");
Hybrid_Logger::debug("OAuth2Client::request(). dump request params: ", serialize( $params ));
}
$this->http_info = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT , $this->api->curl_time_out);
curl_setopt($ch, CURLOPT_USERAGENT , $this->api->curl_useragent);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->api->curl_connect_time_out);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->api->curl_ssl_verifypeer);
curl_setopt($ch, CURLOPT_HTTPHEADER , $this->api->curl_header);
if ( $this->api->curl_proxy ) {
curl_setopt( $ch, CURLOPT_PROXY, $this->curl_proxy);
}
if ( $type == "POST" ) {
curl_setopt($ch, CURLOPT_POST, 1);
if ($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($params) );
}
$response = curl_exec($ch);
if(Class_exists('Hybrid_Logger')){
Hybrid_Logger::debug( "OAuth2Client::request(). dump request info: ", serialize(curl_getinfo($ch)) );
Hybrid_Logger::debug( "OAuth2Client::request(). dump request result: ", serialize($response ));
}
$this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->http_info = array_merge($this->http_info, curl_getinfo($ch));
curl_close ($ch);
return $response;
}
private function parseRequestResult($result)
{
if ( json_decode($result) ) return json_decode($result);
parse_str( $result, $ouput );
$result = new StdClass();
foreach( $ouput as $k => $v )
$result->$k = $v;
return $result;
}
private function generate_state_token() {
$mt = microtime();
$rand = mt_rand();
return md5($mt . $rand);
}
}
@@ -0,0 +1,16 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_OpenID provider adapter for any idp openid based
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_OpenID.html
*/
class Hybrid_Providers_OpenID extends Hybrid_Provider_Model_OpenID {
}
+264
View File
@@ -0,0 +1,264 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Twitter provider adapter based on OAuth1 protocol
*/
class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 {
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider api end-points
$this->api->api_base_url = "https://api.twitter.com/1.1/";
$this->api->authorize_url = "https://api.twitter.com/oauth/authenticate";
$this->api->request_token_url = "https://api.twitter.com/oauth/request_token";
$this->api->access_token_url = "https://api.twitter.com/oauth/access_token";
if (isset($this->config['api_version']) && $this->config['api_version']) {
$this->api->api_base_url = "https://api.twitter.com/{$this->config['api_version']}/";
}
if (isset($this->config['authorize']) && $this->config['authorize']) {
$this->api->authorize_url = "https://api.twitter.com/oauth/authorize";
}
$this->api->curl_auth_header = false;
}
/**
* {@inheritdoc}
*/
function loginBegin() {
// Initiate the Reverse Auth flow; cf. https://dev.twitter.com/docs/ios/using-reverse-auth
if (isset($_REQUEST['reverse_auth']) && ($_REQUEST['reverse_auth'] == 'yes')) {
$stage1 = $this->api->signedRequest($this->api->request_token_url, 'POST', array('x_auth_mode' => 'reverse_auth'));
if ($this->api->http_code != 200) {
throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
}
$responseObj = array('x_reverse_auth_parameters' => $stage1, 'x_reverse_auth_target' => $this->config["keys"]["key"]);
$response = json_encode($responseObj);
header("Content-Type: application/json", true, 200);
echo $response;
die();
}
$tokens = $this->api->requestToken($this->endpoint);
// request tokens as received from provider
$this->request_tokens_raw = $tokens;
// check the last HTTP status code returned
if ($this->api->http_code != 200) {
throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
}
if (!isset($tokens["oauth_token"])) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth token.", 5);
}
$this->token("request_token", $tokens["oauth_token"]);
$this->token("request_token_secret", $tokens["oauth_token_secret"]);
// redirect the user to the provider authentication url with force_login
if (( isset($this->config['force_login']) && $this->config['force_login'] ) || ( isset($this->config['force']) && $this->config['force'] === true )) {
Hybrid_Auth::redirect($this->api->authorizeUrl($tokens, array('force_login' => true)));
}
// else, redirect the user to the provider authentication url
Hybrid_Auth::redirect($this->api->authorizeUrl($tokens));
}
/**
* {@inheritdoc}
*/
function loginFinish() {
// in case we are completing a Reverse Auth flow; cf. https://dev.twitter.com/docs/ios/using-reverse-auth
if (isset($_REQUEST['oauth_token_secret'])) {
$tokens = $_REQUEST;
$this->access_tokens_raw = $tokens;
// we should have an access_token unless something has gone wrong
if (!isset($tokens["oauth_token"])) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
}
// Get rid of tokens we don't need
$this->deleteToken("request_token");
$this->deleteToken("request_token_secret");
// Store access_token and secret for later use
$this->token("access_token", $tokens['oauth_token']);
$this->token("access_token_secret", $tokens['oauth_token_secret']);
// set user as logged in to the current provider
$this->setUserConnected();
return;
}
parent::loginFinish();
}
/**
* {@inheritdoc}
*/
function getUserProfile() {
$includeEmail = isset($this->config['includeEmail']) ? (bool) $this->config['includeEmail'] : false;
$response = $this->api->get('account/verify_credentials.json'. ($includeEmail ? '?include_email=true' : ''));
// check the last HTTP status code returned
if ($this->api->http_code != 200) {
throw new Exception("User profile request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 6);
}
if (!is_object($response) || !isset($response->id)) {
throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6);
}
# store the user profile.
$this->user->profile->identifier = (property_exists($response, 'id')) ? $response->id : "";
$this->user->profile->displayName = (property_exists($response, 'screen_name')) ? $response->screen_name : "";
$this->user->profile->description = (property_exists($response, 'description')) ? $response->description : "";
$this->user->profile->firstName = (property_exists($response, 'name')) ? $response->name : "";
$this->user->profile->photoURL = (property_exists($response, 'profile_image_url')) ? (str_replace('_normal', '', $response->profile_image_url)) : "";
$this->user->profile->profileURL = (property_exists($response, 'screen_name')) ? ("http://twitter.com/" . $response->screen_name) : "";
$this->user->profile->webSiteURL = (property_exists($response, 'url')) ? $response->url : "";
$this->user->profile->region = (property_exists($response, 'location')) ? $response->location : "";
if($includeEmail) $this->user->profile->email = (property_exists($response, 'email')) ? $response->email : "";
if($includeEmail) $this->user->profile->emailVerified = (property_exists($response, 'email')) ? $response->email : "";
return $this->user->profile;
}
/**
* {@inheritdoc}
*/
function getUserContacts() {
$parameters = array('cursor' => '-1');
$response = $this->api->get('friends/ids.json', $parameters);
// check the last HTTP status code returned
if ($this->api->http_code != 200) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
if (!$response || !count($response->ids)) {
return array();
}
// 75 id per time should be okey
$contactsids = array_chunk($response->ids, 75);
$contacts = array();
foreach ($contactsids as $chunk) {
$parameters = array('user_id' => implode(",", $chunk));
$response = $this->api->get('users/lookup.json', $parameters);
// check the last HTTP status code returned
if ($this->api->http_code != 200) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
if ($response && count($response)) {
foreach ($response as $item) {
$uc = new Hybrid_User_Contact();
$uc->identifier = (property_exists($item, 'id')) ? $item->id : "";
$uc->displayName = (property_exists($item, 'name')) ? $item->name : "";
$uc->profileURL = (property_exists($item, 'screen_name')) ? ("http://twitter.com/" . $item->screen_name) : "";
$uc->photoURL = (property_exists($item, 'profile_image_url')) ? $item->profile_image_url : "";
$uc->description = (property_exists($item, 'description')) ? $item->description : "";
$contacts[] = $uc;
}
}
}
return $contacts;
}
/**
* {@inheritdoc}
*/
function setUserStatus($status) {
if (is_array($status) && isset($status['message']) && isset($status['picture'])) {
$response = $this->api->post('statuses/update_with_media.json', array('status' => $status['message'], 'media[]' => file_get_contents($status['picture'])), null, null, true);
} else {
$response = $this->api->post('statuses/update.json', array('status' => $status));
}
// check the last HTTP status code returned
if ($this->api->http_code != 200) {
throw new Exception("Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
return $response;
}
/**
* {@inheritdoc}
*/
function getUserStatus($tweetid) {
$info = $this->api->get('statuses/show.json?id=' . $tweetid . '&include_entities=true');
// check the last HTTP status code returned
if ($this->api->http_code != 200 || !isset($info->id)) {
throw new Exception("Cannot retrieve user status! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
return $info;
}
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
*
* by default return the timeline
* {@inheritdoc}
*/
function getUserActivity($stream) {
if ($stream == "me") {
$response = $this->api->get('statuses/user_timeline.json');
} else {
$response = $this->api->get('statuses/home_timeline.json');
}
// check the last HTTP status code returned
if ($this->api->http_code != 200) {
throw new Exception("User activity stream request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
if (!$response) {
return array();
}
$activities = array();
foreach ($response as $item) {
$ua = new Hybrid_User_Activity();
$ua->id = (property_exists($item, 'id')) ? $item->id : "";
$ua->date = (property_exists($item, 'created_at')) ? strtotime($item->created_at) : "";
$ua->text = (property_exists($item, 'text')) ? $item->text : "";
$ua->user->identifier = (property_exists($item->user, 'id')) ? $item->user->id : "";
$ua->user->displayName = (property_exists($item->user, 'name')) ? $item->user->name : "";
$ua->user->profileURL = (property_exists($item->user, 'screen_name')) ? ("http://twitter.com/" . $item->user->screen_name) : "";
$ua->user->photoURL = (property_exists($item->user, 'profile_image_url')) ? $item->user->profile_image_url : "";
$activities[] = $ua;
}
return $activities;
}
}
+269
View File
@@ -0,0 +1,269 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Yahoo OAuth Class.
*
* @package HybridAuth providers package
* @author Lukasz Koprowski <azram19@gmail.com>
* @author Oleg Kuzava <olegkuzava@gmail.com>
* @version 1.0
* @license BSD License
*/
/**
* Hybrid_Providers_Yahoo - Yahoo provider adapter based on OAuth2 protocol.
*/
class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth2 {
/**
* Define Yahoo scopes.
*
* @var array $scope
* If empty will be used YDN App scopes.
* @see https://developer.yahoo.com/oauth2/guide/yahoo_scopes.
*/
public $scope = [];
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider api end-points.
$this->api->api_base_url = "https://social.yahooapis.com/v1/";
$this->api->authorize_url = "https://api.login.yahoo.com/oauth2/request_auth";
$this->api->token_url = "https://api.login.yahoo.com/oauth2/get_token";
// Set token headers.
$this->setAuthorizationHeaders("basic");
}
/**
* {@inheritdoc}
*/
function loginBegin() {
if (is_array($this->scope)) {
$this->scope = implode(",", $this->scope);
}
parent::loginBegin();
}
/**
* {@inheritdoc}
*/
function getUserProfile() {
$userId = $this->getCurrentUserId();
$response = $this->api->get("user/{$userId}/profile", array(
"format" => "json",
));
if (!isset($response->profile)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response), 6);
}
$data = $response->profile;
$this->user->profile->identifier = isset($data->guid) ? $data->guid : "";
$this->user->profile->firstName = isset($data->givenName) ? $data->givenName : "";
$this->user->profile->lastName = isset($data->familyName) ? $data->familyName : "";
$this->user->profile->displayName = isset($data->nickname) ? trim($data->nickname) : "";
$this->user->profile->profileURL = isset($data->profileUrl) ? $data->profileUrl : "";
$this->user->profile->gender = isset($data->gender) ? $data->gender : "";
if ($this->user->profile->gender === "F") {
$this->user->profile->gender = "female";
}
elseif ($this->user->profile->gender === "M") {
$this->user->profile->gender = "male";
}
if (isset($data->emails)) {
$email = "";
foreach ($data->emails as $v) {
if (isset($v->primary) && $v->primary) {
$email = isset($v->handle) ? $v->handle : "";
break;
}
}
$this->user->profile->email = $email;
$this->user->profile->emailVerified = $email;
}
$this->user->profile->age = isset($data->displayAge) ? $data->displayAge : "";
$this->user->profile->photoURL = isset($data->image) ? $data->image->imageUrl : "";
$this->user->profile->address = isset($data->location) ? $data->location : "";
$this->user->profile->language = isset($data->lang) ? $data->lang : "";
return $this->user->profile;
}
/**
* {@inheritdoc}
*/
function getUserContacts() {
$userId = $this->getCurrentUserId();
$response = $this->api->get("user/{$userId}/contacts", array(
"format" => "json",
"count" => "max",
));
if ($this->api->http_code != 200) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error: " . $this->errorMessageByStatus());
}
if (!isset($response->contacts) || !isset($response->contacts->contact) || (isset($response->errcode) && $response->errcode != 0)) {
return array();
}
$contacts = array();
foreach ($response->contacts->contact as $item) {
$uc = new Hybrid_User_Contact();
$uc->identifier = isset($item->id) ? $item->id : "";
$uc->email = $this->selectEmail($item->fields);
$uc->displayName = $this->selectName($item->fields);
$uc->photoURL = $this->selectPhoto($item->fields);
$contacts[] = $uc;
}
return $contacts;
}
/**
* Returns current user id.
*
* @return string
* Current user ID.
* @throws Exception
*/
function getCurrentUserId() {
// Set headers to get refresh token.
$this->setAuthorizationHeaders("basic");
// Refresh tokens if needed.
$this->refreshToken();
// Set headers to make api call.
$this->setAuthorizationHeaders("bearer");
$response = $this->api->get("me/guid", array(
"format" => "json",
));
if (!isset($response->guid->value)) {
throw new Exception("User id request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response));
}
return $response->guid->value;
}
/**
* Utility function for returning values from XML-like objects.
*
* @param stdClass $vs
* Object.
* @param string $t
* Property name.
* @return mixed
*/
private function select($vs, $t) {
foreach ($vs as $v) {
if ($v->type == $t) {
return $v;
}
}
return null;
}
/**
* Parses user name.
*
* @param stdClass $v
* Object.
* @return string
* User name.
*/
private function selectName($v) {
$s = $this->select($v, "name");
if (!$s) {
$s = $this->select($v, "nickname");
return isset($s->value) ? $s->value : "";
}
return isset($s->value) ? "{$s->value->givenName} {$s->value->familyName}" : "";
}
/**
* Parses photo URL.
*
* @param stdClass $v
* Object.
* @return string
* Photo URL.
*/
private function selectPhoto($v) {
$s = $this->select($v, "image");
return isset($s->value) ? $s->value->imageUrl : "";
}
/**
* Parses email.
*
* @param stdClass $v
* Object
* @return string
* An email address.
*/
private function selectEmail($v) {
$s = $this->select($v, "email");
if (empty($s)) {
$s = $this->select($v, "yahooid");
if (isset($s->value) && strpos($s->value, "@") === FALSE) {
$s->value .= "@yahoo.com";
}
}
return isset($s->value) ? $s->value : "";
}
/**
* Set correct Authorization headers.
*
* @param string $token_type
* Specify token type.
*
* @return void
*/
private function setAuthorizationHeaders($token_type) {
switch ($token_type) {
case "basic":
// The /get_token requires authorization header.
$token = base64_encode("{$this->config["keys"]["id"]}:{$this->config["keys"]["secret"]}");
$this->api->curl_header = array(
"Authorization: Basic {$token}",
"Content-Type: application/x-www-form-urlencoded",
);
break;
case "bearer":
// Yahoo API requires the token to be passed as a Bearer within the authorization header.
$this->api->curl_header = array(
"Authorization: Bearer {$this->api->access_token}",
);
break;
}
}
}