FIX #993 Update Hybrid Auth

This commit is contained in:
Ulrich Block 2017-05-13 11:54:41 +02:00
parent 4c5a91dd02
commit 2a58188c4e
17 changed files with 677 additions and 699 deletions

View File

@ -15,7 +15,7 @@
*/
class Hybrid_Auth {
public static $version = "2.6.0";
public static $version = "2.9.5";
/**
* Configuration array
@ -352,9 +352,12 @@ class Hybrid_Auth {
* @param string $mode PHP|JS
*/
public static function redirect($url, $mode = "PHP") {
if(!$mode){
$mode = 'PHP';
}
Hybrid_Logger::info("Enter Hybrid_Auth::redirect( $url, $mode )");
// Ensure session is saved before sending response, see https://github.com/Symfony/Symfony/pull/12341
// Ensure session is saved before sending response, see https://github.com/symfony/symfony/pull/12341
if ((PHP_VERSION_ID >= 50400 && PHP_SESSION_ACTIVE === session_status()) || (PHP_VERSION_ID < 50400 && isset($_SESSION) && session_id())) {
session_write_close();
}

View File

@ -27,7 +27,7 @@ class Hybrid_Endpoint {
// with /index.php?hauth.done={provider}?{args}...
// >here we need to parse $_SERVER[QUERY_STRING]
$request = $_REQUEST;
if (strrpos($_SERVER["QUERY_STRING"], '?')) {
if (isset($_SERVER["QUERY_STRING"]) && strrpos($_SERVER["QUERY_STRING"], '?')) {
$_SERVER["QUERY_STRING"] = str_replace("?", "&", $_SERVER["QUERY_STRING"]);
parse_str($_SERVER["QUERY_STRING"], $request);
}

View File

@ -153,11 +153,26 @@ class Hybrid_Provider_Adapter {
# for default HybridAuth endpoint url hauth_login_start_url
# auth.start required the IDp ID
# auth.time optional login request timestamp
$this->params["login_start"] = $HYBRID_AUTH_URL_BASE . ( strpos($HYBRID_AUTH_URL_BASE, '?') ? '&' : '?' ) . "hauth.start={$this->id}&hauth.time={$this->params["hauth_time"]}";
if (!isset($this->params["login_start"]) ) {
$this->params["login_start"] = $HYBRID_AUTH_URL_BASE . ( strpos($HYBRID_AUTH_URL_BASE, '?') ? '&' : '?' ) . "hauth.start={$this->id}&hauth.time={$this->params["hauth_time"]}";
}
# for default HybridAuth endpoint url hauth_login_done_url
# auth.done required the IDp ID
$this->params["login_done"] = $HYBRID_AUTH_URL_BASE . ( strpos($HYBRID_AUTH_URL_BASE, '?') ? '&' : '?' ) . "hauth.done={$this->id}";
if (!isset($this->params["login_done"]) ) {
$this->params["login_done"] = $HYBRID_AUTH_URL_BASE . ( strpos($HYBRID_AUTH_URL_BASE, '?') ? '&' : '?' ) . "hauth.done={$this->id}";
}
# workaround to solve windows live authentication since microsoft disallowed redirect urls to contain any parameters
# http://mywebsite.com/path_to_hybridauth/?hauth.done=Live will not work
if ($this->id=="Live") {
$this->params["login_done"] = $HYBRID_AUTH_URL_BASE."live.php";
}
# Workaround to fix broken callback urls for the Facebook OAuth client
if ($this->adapter->useSafeUrls) {
$this->params['login_done'] = str_replace('hauth.done', 'hauth_done', $this->params['login_done']);
}
if (isset($this->params["hauth_return_to"])) {
Hybrid_Auth::storage()->set("hauth_session.{$this->id}.hauth_return_to", $this->params["hauth_return_to"]);
@ -173,7 +188,12 @@ class Hybrid_Provider_Adapter {
// move on
Hybrid_Logger::debug("Hybrid_Provider_Adapter::login( {$this->id} ), redirect the user to login_start URL.");
Hybrid_Auth::redirect($this->params["login_start"]);
// redirect
if (empty($this->params["redirect_mode"])) {
Hybrid_Auth::redirect($this->params["login_start"]);
} else {
Hybrid_Auth::redirect($this->params["login_start"],$this->params["redirect_mode"]);
}
}
/**
@ -219,14 +239,7 @@ class Hybrid_Provider_Adapter {
throw new Exception("Call to undefined function Hybrid_Providers_{$this->id}::$name().");
}
$counter = count($arguments);
if ($counter == 1) {
return $this->adapter->$name($arguments[0]);
} elseif ($counter == 2) {
return $this->adapter->$name($arguments[0], $arguments[1]);
} else {
return $this->adapter->$name();
}
return call_user_func_array(array($this->adapter, $name), $arguments);
}
/**
@ -281,6 +294,12 @@ class Hybrid_Provider_Adapter {
// get the stored callback url
$callback_url = Hybrid_Auth::storage()->get("hauth_session.{$this->id}.hauth_return_to");
// if the user presses the back button in the browser and we already deleted the hauth_return_to from
// the session in the previous request, we will redirect to '/' instead of displaying a blank page.
if (!$callback_url) {
$callback_url = '/';
}
// remove some unneeded stored data
Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_return_to");
Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_endpoint");

View File

@ -64,6 +64,9 @@ abstract class Hybrid_Provider_Model {
*/
public $compressed = false;
/** @var bool $useSafeUrls Enable this to replace '.' with '_' characters in the callback urls */
public $useSafeUrls = false;
/**
* Common providers adapter constructor
*
@ -118,14 +121,14 @@ abstract class Hybrid_Provider_Model {
* @return void
* @throws Exception
*/
abstract protected function loginBegin();
abstract public function loginBegin();
/**
* Finish login
* @return void
* @throws Exception
*/
abstract protected function loginFinish();
abstract public function loginFinish();
/**
* Generic logout, just erase current provider adapter stored data to let Hybrid_Auth all forget about it
@ -140,7 +143,7 @@ abstract class Hybrid_Provider_Model {
/**
* Grab the user profile from the IDp api client
* @return Hybrid_User_Profile
* @throw Exception
* @throws Exception
*/
function getUserProfile() {
Hybrid_Logger::error("HybridAuth do not provide users contacts list for {$this->providerId} yet.");

View File

@ -119,7 +119,7 @@ class Hybrid_Provider_Model_OAuth2 extends Hybrid_Provider_Model {
try {
$this->api->authenticate($code);
} catch (Exception $e) {
throw new Exception("User profile request failed! {$this->providerId} returned an error: $e", 6);
throw new Exception("User profile request failed! {$this->providerId} returned an error: " . $e->getMessage(), 6);
}
// check if authenticated

View File

@ -24,7 +24,6 @@ class Hybrid_Providers_Dropbox extends Hybrid_Provider_Model_OAuth2
$this->api->api_base_url = "https://api.dropbox.com/1/";
$this->api->authorize_url = "https://www.dropbox.com/1/oauth2/authorize";
$this->api->token_url = "https://api.dropbox.com/1/oauth2/token";
}
/**

View File

@ -1,5 +1,8 @@
<?php
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Facebook as FacebookSDK;
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
@ -8,424 +11,383 @@
/**
* 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 {
/**
* 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";
/**
* Provider API client
* @var Facebook
*/
public $api;
/**
* {@inheritdoc}
*/
function initialize() {
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);
}
if (!class_exists('FacebookApiException', false)) {
require_once Hybrid_Auth::$config["path_libraries"] . "Facebook/base_facebook.php";
require_once Hybrid_Auth::$config["path_libraries"] . "Facebook/facebook.php";
}
if (isset(Hybrid_Auth::$config["proxy"])) {
BaseFacebook::$CURL_OPTS[CURLOPT_PROXY] = Hybrid_Auth::$config["proxy"];
}
$trustForwarded = isset($this->config['trustForwarded']) ? (bool) $this->config['trustForwarded'] : false;
$this->api = new Facebook(array('appId' => $this->config["keys"]["id"], 'secret' => $this->config["keys"]["secret"], 'trustForwarded' => $trustForwarded));
if ($this->token("access_token")) {
$this->api->setAccessToken($this->token("access_token"));
$this->api->setExtendedAccessToken();
$access_token = $this->api->getAccessToken();
if ($access_token) {
$this->token("access_token", $access_token);
$this->api->setAccessToken($access_token);
}
$this->api->setAccessToken($this->token("access_token"));
}
$this->api->getUser();
}
/**
* {@inheritdoc}
*/
function loginBegin() {
$parameters = array("scope" => $this->scope, "redirect_uri" => $this->endpoint, "display" => "page");
$optionals = array("scope", "redirect_uri", "display", "auth_type");
foreach ($optionals as $parameter) {
if (isset($this->config[$parameter]) && !empty($this->config[$parameter])) {
$parameters[$parameter] = $this->config[$parameter];
//If the auth_type parameter is used, we need to generate a nonce and include it as a parameter
if ($parameter == "auth_type") {
$nonce = md5(uniqid(mt_rand(), true));
$parameters['auth_nonce'] = $nonce;
Hybrid_Auth::storage()->set('fb_auth_nonce', $nonce);
}
}
}
if (isset($this->config['force']) && $this->config['force'] === true) {
$parameters['auth_type'] = 'reauthenticate';
$parameters['auth_nonce'] = md5(uniqid(mt_rand(), true));
Hybrid_Auth::storage()->set('fb_auth_nonce', $parameters['auth_nonce']);
}
// get the login url
$url = $this->api->getLoginUrl($parameters);
// redirect to facebook
Hybrid_Auth::redirect($url);
}
/**
* {@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);
}
// in case we are using iOS/Facebook reverse authentication
if (isset($_REQUEST['access_token'])) {
$this->token("access_token", $_REQUEST['access_token']);
$this->api->setAccessToken($this->token("access_token"));
$this->api->setExtendedAccessToken();
$access_token = $this->api->getAccessToken();
if ($access_token) {
$this->token("access_token", $access_token);
$this->api->setAccessToken($access_token);
}
$this->api->setAccessToken($this->token("access_token"));
}
// if auth_type is used, then an auth_nonce is passed back, and we need to check it.
if (isset($_REQUEST['auth_nonce'])) {
$nonce = Hybrid_Auth::storage()->get('fb_auth_nonce');
//Delete the nonce
Hybrid_Auth::storage()->delete('fb_auth_nonce');
if ($_REQUEST['auth_nonce'] != $nonce) {
throw new Exception("Authentication failed! Invalid nonce used for reauthentication.", 5);
}
}
// try to get the UID of the connected user from fb, should be > 0
if (!$this->api->getUser()) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid user id.", 5);
}
// set user as logged in
$this->setUserConnected();
// store facebook access token
$this->token("access_token", $this->api->getAccessToken());
}
/**
* {@inheritdoc}
*/
function logout() {
$this->api->destroySession();
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));
} catch (FacebookApiException $e) {
throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e);
}
// if the provider identifier is not received, we assume the auth has failed
if (!isset($data["id"])) {
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->api->getAccessToken();
$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;
}
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 (FacebookApiException $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 (FacebookApiException $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 (FacebookApiException $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 (FacebookApiException $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 (FacebookApiException $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;
}
/**
* Default permissions, and a lot of them. You can change them from the configuration by setting the scope to what you want/need.
* For a complete list see: https://developers.facebook.com/docs/facebook-login/permissions
*
* @link https://developers.facebook.com/docs/facebook-login/permissions
* @var array $scope
*/
public $scope = ['email', 'user_about_me', 'user_birthday', 'user_hometown', 'user_location', 'user_website', 'publish_actions', 'read_custom_friendlists'];
/**
* Provider API client
*
* @var \Facebook\Facebook
*/
public $api;
public $useSafeUrls = true;
/**
* {@inheritdoc}
*/
function initialize() {
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);
}
if (isset($this->config['scope'])) {
$scope = $this->config['scope'];
if (is_string($scope)) {
$scope = explode(",", $scope);
}
$scope = array_map('trim', $scope);
$this->scope = $scope;
}
$trustForwarded = isset($this->config['trustForwarded']) ? (bool)$this->config['trustForwarded'] : false;
// Check if there is Graph SDK in thirdparty/Facebook.
if (file_exists(Hybrid_Auth::$config["path_libraries"] . "Facebook/autoload.php")) {
require_once Hybrid_Auth::$config["path_libraries"] . "Facebook/autoload.php";
}
else {
// If Composer install was executed, try to find autoload.php.
$vendorDir = dirname(Hybrid_Auth::$config['path_base']);
do {
if (file_exists($vendorDir . "/vendor/autoload.php")) {
require_once $vendorDir . "/vendor/autoload.php";
break;
}
} while (($vendorDir = dirname($vendorDir)) !== '/');
}
$this->api = new FacebookSDK([
'app_id' => $this->config["keys"]["id"],
'app_secret' => $this->config["keys"]["secret"],
'default_graph_version' => 'v2.8',
'trustForwarded' => $trustForwarded,
]);
}
/**
* {@inheritdoc}
*/
function loginBegin() {
$this->endpoint = $this->params['login_done'];
$helper = $this->api->getRedirectLoginHelper();
// Use re-request, because this will trigger permissions window if not all permissions are granted.
$url = $helper->getReRequestUrl($this->endpoint, $this->scope);
// Redirect to Facebook
Hybrid_Auth::redirect($url);
}
/**
* {@inheritdoc}
*/
function loginFinish() {
$helper = $this->api->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken($this->params['login_done']);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
throw new Hybrid_Exception('Facebook Graph returned an error: ' . $e->getMessage());
} catch (Facebook\Exceptions\FacebookSDKException $e) {
throw new Hybrid_Exception('Facebook SDK returned an error: ' . $e->getMessage());
}
if (!isset($accessToken)) {
if ($helper->getError()) {
throw new Hybrid_Exception(sprintf("Could not authorize user, reason: %s (%d)", $helper->getErrorDescription(), $helper->getErrorCode()));
} else {
throw new Hybrid_Exception("Could not authorize user. Bad request");
}
}
try {
// Validate token
$oAuth2Client = $this->api->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
$tokenMetadata->validateAppId($this->config["keys"]["id"]);
$tokenMetadata->validateExpiration();
// Exchanges a short-lived access token for a long-lived one
if (!$accessToken->isLongLived()) {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
}
} catch (FacebookSDKException $e) {
throw new Hybrid_Exception($e->getMessage(), 0, $e);
}
$this->setUserConnected();
$this->token("access_token", $accessToken->getValue());
}
/**
* {@inheritdoc}
*/
function logout() {
parent::logout();
}
/**
* 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);
}
$access_token = null;
if (is_null($pageid)) {
$pageid = 'me';
$access_token = $this->token('access_token');
// if post on page, get access_token page
} else {
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!");
}
}
try {
$response = $this->api->post('/' . $pageid . '/feed', $status, $access_token);
} catch (FacebookSDKException $e) {
throw new Exception("Update user status failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
}
return $response;
}
/**
* {@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->get("/me/accounts", $this->token('access_token'));
$pages = $pages->getDecodedBody();
} catch (FacebookApiException $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;
}
/**
* {@inheritdoc}
*/
function getUserProfile() {
try {
$fields = [
'id',
'name',
'first_name',
'last_name',
'link',
'website',
'gender',
'locale',
'about',
'email',
'hometown',
'location',
'birthday'
];
$response = $this->api->get('/me?fields=' . implode(',', $fields), $this->token('access_token'));
$data = $response->getDecodedBody();
} catch (FacebookSDKException $e) {
throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e);
}
// Store the user profile.
$this->user->profile->identifier = (array_key_exists('id', $data)) ? $data['id'] : "";
$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 = !empty($this->user->profile->identifier) ? "https://graph.facebook.com/" . $this->user->profile->identifier . "/picture?width=150&height=150" : '';
$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(end($regionArr));
}
}
if (array_key_exists('birthday', $data)) {
$birtydayPieces = explode('/', $data['birthday']);
if (count($birtydayPieces) == 1) {
$this->user->profile->birthYear = (int)$birtydayPieces[0];
} elseif (count($birtydayPieces) == 2) {
$this->user->profile->birthMonth = (int)$birtydayPieces[0];
$this->user->profile->birthDay = (int)$birtydayPieces[1];
} elseif (count($birtydayPieces) == 3) {
$this->user->profile->birthMonth = (int)$birtydayPieces[0];
$this->user->profile->birthDay = (int)$birtydayPieces[1];
$this->user->profile->birthYear = (int)$birtydayPieces[2];
}
}
return $this->user->profile;
}
/**
* Since the Graph API 2.0, the /friends endpoint only returns friend that also use your Facebook app.
* {@inheritdoc}
*/
function getUserContacts() {
$apiCall = '?fields=link,name';
$returnedContacts = [];
$pagedList = true;
while ($pagedList) {
try {
$response = $this->api->get('/me/friends' . $apiCall, $this->token('access_token'));
$response = $response->getDecodedBody();
} catch (FacebookSDKException $e) {
throw new Hybrid_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']);
}
$contacts = [];
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;
}
/**
* Load the user latest activity, needs 'read_stream' permission
*
* @param string $stream Which activity to fetch:
* - timeline : all the stream
* - me : the user activity only
* {@inheritdoc}
*/
function getUserActivity($stream = 'timeline') {
try {
if ($stream == "me") {
$response = $this->api->get('/me/feed', $this->token('access_token'));
} else {
$response = $this->api->get('/me/home', $this->token('access_token'));
}
$response = $response->getDecodedBody();
} catch (FacebookSDKException $e) {
throw new Hybrid_Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (!$response || !count($response['data'])) {
return [];
}
$activities = [];
foreach ($response['data'] as $item) {
$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;
}
}

View File

@ -82,7 +82,7 @@ class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2 {
$contacts = array();
try {
$response = $this->api->api("users/self/friends", "GET", Hybrid_Providers_Foursquare::$apiVersion);
} catch (LinkedInException $e) {
} catch (Exception $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}

View File

@ -65,6 +65,14 @@ class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2
&& property_exists($email, 'email')
) {
$this->user->profile->email = $email->email;
// record whether the email address is verified
if (property_exists($email, 'verified')
&& true === $email->verified
) {
$this->user->profile->emailVerified = $email->email;
}
break;
}
}
@ -89,7 +97,7 @@ class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2
$contacts = array();
try {
$response = $this->api->api( "user/followers" );
} catch (LinkedInException $e) {
} catch (Exception $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error: $e");
}
//
@ -97,7 +105,7 @@ class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2
foreach ($response as $contact) {
try {
$contactInfo = $this->api->api( "users/".$contact->login );
} catch (LinkedInException $e) {
} catch (Exception $e) {
throw new Exception("Contact info request failed for user {$contact->login}! {$this->providerId} returned an error: $e");
}
//

View File

@ -60,7 +60,7 @@ class Hybrid_Providers_Instagram extends Hybrid_Provider_Model_OAuth2
$profile = ( ( isset( $this->user->profile->identifier ) )?( $this->user->profile ):( $this->getUserProfile() ) );
try {
$response = $this->api->api( "users/{$this->user->profile->identifier}/follows" );
} catch (LinkedInException $e) {
} catch (Exception $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error: $e");
}
//
@ -69,7 +69,7 @@ class Hybrid_Providers_Instagram extends Hybrid_Provider_Model_OAuth2
foreach ($response->data as $contact) {
try {
$contactInfo = $this->api->api( "users/".$contact->id );
} catch (LinkedInException $e) {
} catch (Exception $e) {
throw new Exception("Contact info request failed for user {$contact->username}! {$this->providerId} returned an error: $e");
}
//

View File

@ -1,257 +1,170 @@
<?php
/* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
* Hybridauth
* https://hybridauth.github.io/hybridauth | https://github.com/hybridauth/hybridauth
* (c) 2017 Hybridauth authors | https://hybridauth.github.io/license.html
*/
/**
* Hybrid_Providers_LinkedIn provider adapter based on OAuth1 protocol
*
* Hybrid_Providers_LinkedIn use linkedinPHP library created by fiftyMission Inc.
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_LinkedIn.html
* Hybrid_Providers_LinkedIn OAuth2 provider adapter.
*/
class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model {
class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model_OAuth2 {
/**
* Provider API Wrapper
* @var LinkedIn
*/
public $api;
/**
* {@inheritdoc}
*/
public $scope = "r_basicprofile r_emailaddress";
/**
* {@inheritdoc}
*/
function initialize() {
if (!$this->config["keys"]["key"] || !$this->config["keys"]["secret"]) {
throw new Exception("Your application key and secret are required in order to connect to {$this->providerId}.", 4);
}
if (!class_exists('OAuthConsumer', false)) {
require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth.php";
}
require_once Hybrid_Auth::$config["path_libraries"] . "LinkedIn/LinkedIn.php";
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
$this->api = new LinkedIn(array('appKey' => $this->config["keys"]["key"], 'appSecret' => $this->config["keys"]["secret"], 'callbackUrl' => $this->endpoint));
// 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";
}
if ($this->token("access_token_linkedin")) {
$this->api->setTokenAccess($this->token("access_token_linkedin"));
}
}
/**
* {@inheritdoc}
*/
function loginBegin() {
if (is_array($this->scope)) {
$this->scope = implode(" ", $this->scope);
}
parent::loginBegin();
}
/**
* {@inheritdoc}
*/
function loginBegin() {
// send a request for a LinkedIn access token
$response = $this->api->retrieveTokenRequest();
/**
* {@inheritdoc}
*
* @see https://developer.linkedin.com/docs/rest-api
*/
function getUserProfile() {
// Refresh tokens if needed.
$this->setHeaders("token");
$this->refreshToken();
if (isset($response['success']) && $response['success'] === true) {
$this->token("oauth_token", $response['linkedin']['oauth_token']);
$this->token("oauth_token_secret", $response['linkedin']['oauth_token_secret']);
// 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",
];
# redirect user to LinkedIn authorisation web page
Hybrid_Auth::redirect(LINKEDIN::_URL_AUTH . $response['linkedin']['oauth_token']);
} else {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid Token in response: " . Hybrid_Logger::dumpData( $response ), 5);
}
}
$this->setHeaders();
$response = $this->api->get(
"people/~:(" . implode(",", $fields) . ")",
array(
"format" => "json",
)
);
/**
* {@inheritdoc}
*/
function loginFinish() {
// in case we get oauth_problem=user_refused
if (isset($_REQUEST['oauth_problem']) && $_REQUEST['oauth_problem'] == "user_refused") {
throw new Exception("Authentication failed! The user denied your request.", 5);
if (!isset($response->id)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($response), 6);
}
$oauth_token = isset($_REQUEST['oauth_token']) ? $_REQUEST['oauth_token'] : null;
$oauth_verifier = isset($_REQUEST['oauth_verifier']) ? $_REQUEST['oauth_verifier'] : null;
$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);
if (!$oauth_token || !$oauth_verifier) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid Token.", 5);
}
return $this->user->profile;
}
$response = $this->api->retrieveTokenAccess($oauth_token, $this->token("oauth_token_secret"), $oauth_verifier);
/**
* {@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();
if (isset($response['success']) && $response['success'] === true) {
$this->deleteToken("oauth_token");
$this->deleteToken("oauth_token_secret");
try {
// Define default visibility.
if (!isset($status["visibility"])) {
$status["visibility"]["code"] = "anyone";
}
$this->token("access_token_linkedin", $response['linkedin']);
$this->token("access_token", $response['linkedin']['oauth_token']);
$this->token("access_token_secret", $response['linkedin']['oauth_token_secret']);
$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);
}
// set user as logged in
$this->setUserConnected();
} else {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid Token in response: " . Hybrid_Logger::dumpData( $response ), 5);
}
}
if (!isset($response->updateKey)) {
throw new Exception("Update user status failed! {$this->providerId} returned an error: {$response->message}", $response->errorCode);
}
/**
* {@inheritdoc}
*/
function getUserProfile() {
try {
// http://developer.linkedin.com/docs/DOC-1061
$response = $this->api->profile('~:(id,first-name,last-name,public-profile-url,picture-url,email-address,date-of-birth,phone-numbers,summary)');
} catch (LinkedInException $e) {
throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e);
}
return $response;
}
if (isset($response['success']) && $response['success'] === true) {
$data = @ new SimpleXMLElement($response['linkedin']);
/**
* 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}",
);
if (!is_object($data)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid xml data: " . Hybrid_Logger::dumpData( $data ), 6);
}
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;
$this->user->profile->identifier = (string) $data->{'id'};
$this->user->profile->firstName = (string) $data->{'first-name'};
$this->user->profile->lastName = (string) $data->{'last-name'};
$this->user->profile->displayName = trim($this->user->profile->firstName . " " . $this->user->profile->lastName);
$this->user->profile->email = (string) $data->{'email-address'};
$this->user->profile->emailVerified = (string) $data->{'email-address'};
$this->user->profile->photoURL = (string) $data->{'picture-url'};
$this->user->profile->profileURL = (string) $data->{'public-profile-url'};
$this->user->profile->description = (string) $data->{'summary'};
if ($data->{'phone-numbers'} && $data->{'phone-numbers'}->{'phone-number'}) {
$this->user->profile->phone = (string) $data->{'phone-numbers'}->{'phone-number'}->{'phone-number'};
} else {
$this->user->profile->phone = null;
}
if ($data->{'date-of-birth'}) {
$this->user->profile->birthDay = (string) $data->{'date-of-birth'}->day;
$this->user->profile->birthMonth = (string) $data->{'date-of-birth'}->month;
$this->user->profile->birthYear = (string) $data->{'date-of-birth'}->year;
}
return $this->user->profile;
} else {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6);
}
}
/**
* {@inheritdoc}
*/
function getUserContacts() {
try {
$response = $this->api->profile('~/connections:(id,first-name,last-name,picture-url,public-profile-url,summary)');
} catch (LinkedInException $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (!$response || !$response['success']) {
return array();
}
$connections = new SimpleXMLElement($response['linkedin']);
$contacts = array();
foreach ($connections->person as $connection) {
$uc = new Hybrid_User_Contact();
$uc->identifier = (string) $connection->id;
$uc->displayName = (string) $connection->{'last-name'} . " " . $connection->{'first-name'};
$uc->profileURL = (string) $connection->{'public-profile-url'};
$uc->photoURL = (string) $connection->{'picture-url'};
$uc->description = (string) $connection->{'summary'};
$contacts[] = $uc;
}
return $contacts;
}
/**
* {@inheritdoc}
*/
function setUserStatus($status) {
$parameters = array();
$private = true; // share with your connections only
if (is_array($status)) {
if (isset($status[0]) && !empty($status[0]))
$parameters["title"] = $status[0]; // post title
if (isset($status[1]) && !empty($status[1]))
$parameters["comment"] = $status[1]; // post comment
if (isset($status[2]) && !empty($status[2]))
$parameters["submitted-url"] = $status[2]; // post url
if (isset($status[3]) && !empty($status[3]))
$parameters["submitted-image-url"] = $status[3]; // post picture url
if (isset($status[4]) && !empty($status[4]))
$private = $status[4]; // true or false
}
else {
$parameters["comment"] = $status;
}
try {
$response = $this->api->share('new', $parameters, $private);
} catch (LinkedInException $e) {
throw new Exception("Update user status update failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (!$response || !$response['success']) {
throw new Exception("Update user status update failed! {$this->providerId} returned an error in response: " . Hybrid_Logger::dumpData( $response ));
}
return $response;
}
/**
* 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->updates('?type=SHAR&scope=self&count=25');
} else {
$response = $this->api->updates('?type=SHAR&count=25');
}
} catch (LinkedInException $e) {
throw new Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (!$response || !$response['success']) {
return array();
}
$updates = new SimpleXMLElement($response['linkedin']);
$activities = array();
foreach ($updates->update as $update) {
$person = $update->{'update-content'}->person;
$share = $update->{'update-content'}->person->{'current-share'};
$ua = new Hybrid_User_Activity();
$ua->id = (string) $update->id;
$ua->date = (string) $update->timestamp;
$ua->text = (string) $share->{'comment'};
$ua->user->identifier = (string) $person->id;
$ua->user->displayName = (string) $person->{'first-name'} . ' ' . $person->{'last-name'};
$ua->user->profileURL = (string) $person->{'site-standard-profile-request'}->url;
$ua->user->photoURL = null;
$activities[] = $ua;
}
return $activities;
}
case "token":
$this->api->curl_header = array_merge(
$this->api->curl_header,
array(
"Content-Type: application/x-www-form-urlencoded",
)
);
break;
}
}
}

View File

@ -9,7 +9,7 @@
/**
* Windows Live OAuth2 Class
*
* @package HybridAuth providers package
* @package HybridAuth providers package
* @author Lukasz Koprowski <azram19@gmail.com>
* @version 0.2
* @license BSD License
@ -33,10 +33,16 @@ class Hybrid_Providers_Live extends Hybrid_Provider_Model_OAuth2 {
// 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->authorize_url = 'https://oauth.live.com/authorize';
$this->api->token_url = 'https://login.live.com/oauth20_token.srf';
$this->api->curl_authenticate_method = "GET";
// Override the redirect uri when it's set in the config parameters. This way we prevent
// redirect uri mismatches when authenticating with Live.com
if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
$this->api->redirect_uri = $this->config['redirect_uri'];
}
}
/**

View File

@ -63,8 +63,13 @@ class Hybrid_Providers_Steam extends Hybrid_Provider_Model_OpenID
{
$apiUrl = 'http://steamcommunity.com/profiles/' . $this->user->profile->identifier . '/?xml=1';
$data = @file_get_contents($apiUrl);
$data = @ new SimpleXMLElement($data);
try {
$data = @file_get_contents($apiUrl);
$data = @ new SimpleXMLElement($data);
} catch(Exception $e) {
Hybrid_Logger::error( "Steam::getUserProfileLegacyAPI() error: ", $e->getMessage());
return false;
}
if (!is_object($data)) {
return false;
@ -76,7 +81,7 @@ class Hybrid_Providers_Steam extends Hybrid_Provider_Model_OpenID
$this->user->profile->profileURL = 'http://steamcommunity.com/id/' . (string) $data->customURL . '/';
}
else {
$this->user->profile->profileURL = "http://steamcommunity.com/profiles/{$this->user->profile->identifier}/";
$this->user->profile->profileURL = "http://steamcommunity.com/profiles/{$this->user->profile->identifier}/";
}
$this->user->profile->webSiteURL = "";
@ -99,6 +104,5 @@ class Hybrid_Providers_Steam extends Hybrid_Provider_Model_OpenID
$this->user->profile->region = property_exists($data, 'location') ? (string)$data->location : '';
$this->user->profile->city = "";
$this->user->profile->zip = "";
}
}

View File

@ -18,10 +18,10 @@ class Hybrid_Providers_Tumblr extends Hybrid_Provider_Model_OAuth1
parent::initialize();
// provider api end-points
$this->api->api_base_url = "http://api.tumblr.com/v2/";
$this->api->authorize_url = "http://www.tumblr.com/oauth/authorize";
$this->api->request_token_url = "http://www.tumblr.com/oauth/request_token";
$this->api->access_token_url = "http://www.tumblr.com/oauth/access_token";
$this->api->api_base_url = "https://api.tumblr.com/v2/";
$this->api->authorize_url = "https://www.tumblr.com/oauth/authorize";
$this->api->request_token_url = "https://www.tumblr.com/oauth/request_token";
$this->api->access_token_url = "https://www.tumblr.com/oauth/access_token";
$this->api->curl_auth_header = false;
}
@ -64,18 +64,31 @@ class Hybrid_Providers_Tumblr extends Hybrid_Provider_Model_OAuth1
return $this->user->profile;
}
/**
* post to tumblr
*/
function setUserStatus( $status )
/**
* Post to Tumblr.
*
* @param string|array $data
* Data of post.
*
* @return mixed
* Response from Tumblr after posting.
*
* @throws \Exception
* If creating user post failed.
*
* @see https://www.tumblr.com/docs/en/api/v2#posting
*/
function setUserStatus( $data )
{
$parameters = array( 'type' => "text", 'body' => $status );
$response = $this->api->post( "blog/" . $this->token( "primary_blog" ) . '/post', $parameters );
if ( $response->meta->status != 201 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $response->meta->status ) );
if (is_string($data)) {
$data = array('type' => 'text', 'body' => $data );
}
return $response;
$response = $this->api->post( "blog/" . $this->token( "primary_blog" ) . '/post', $data );
if ( $response->meta->status != 201 ){
throw new Exception("Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $response->meta->status ));
}
return $response;
}
}

View File

@ -131,7 +131,8 @@ class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 {
$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;
}

View File

@ -149,4 +149,15 @@ class Hybrid_User_Profile {
*/
public $zip = null;
/**
* Job title
* @var string
*/
public $job_title = null;
/**
* Organization name
* @var string
*/
public $organization_name = null;
}

View File

@ -26,7 +26,6 @@ class OAuth2Client
//--
public $sign_token_name = "access_token";
public $decode_json = true;
public $curl_time_out = 30;
public $curl_connect_time_out = 30;
public $curl_ssl_verifypeer = false;
@ -127,7 +126,7 @@ class OAuth2Client
/**
* Format and sign an oauth for provider api
*/
public function api( $url, $method = "GET", $parameters = array() )
public function api( $url, $method = "GET", $parameters = array(), $decode_json = true )
{
if ( strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0 ) {
$url = $this->api_base_url . $url;
@ -139,9 +138,11 @@ class OAuth2Client
switch( $method ){
case 'GET' : $response = $this->request( $url, $parameters, "GET" ); break;
case 'POST' : $response = $this->request( $url, $parameters, "POST" ); break;
case 'DELETE' : $response = $this->request( $url, $parameters, "DELETE" ); break;
case 'PATCH' : $response = $this->request( $url, $parameters, "PATCH" ); break;
}
if( $response && $this->decode_json ){
if( $response && $decode_json ){
return $this->response = json_decode( $response );
}
@ -161,17 +162,17 @@ class OAuth2Client
/**
* GET wrapper for provider apis request
*/
function get( $url, $parameters = array() )
function get( $url, $parameters = array(), $decode_json = true )
{
return $this->api( $url, 'GET', $parameters );
return $this->api( $url, 'GET', $parameters, $decode_json );
}
/**
* POST wrapper for provider apis request
*/
function post( $url, $parameters = array() )
function post( $url, $parameters = array(), $decode_json = true )
{
return $this->api( $url, 'POST', $parameters );
return $this->api( $url, 'POST', $parameters, $decode_json );
}
// -- tokens
@ -206,8 +207,10 @@ class OAuth2Client
Hybrid_Logger::info( "Enter OAuth2Client::request( $url )" );
Hybrid_Logger::debug( "OAuth2Client::request(). dump request params: ", serialize( $params ) );
$urlEncodedParams = http_build_query($params, '', '&');
if( $type == "GET" ){
$url = $url . ( strpos( $url, '?' ) ? '&' : '?' ) . http_build_query($params, '', '&');
$url = $url . ( strpos( $url, '?' ) ? '&' : '?' ) . $urlEncodedParams;
}
$this->http_info = array();
@ -230,11 +233,30 @@ class OAuth2Client
curl_setopt( $ch, CURLOPT_PROXY , $this->curl_proxy);
}
if( $type == "POST" ){
if ($type == "POST") {
curl_setopt($ch, CURLOPT_POST, 1);
if($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
// If request body exists then encode it for "application/json".
if (isset($params['body'])) {
$urlEncodedParams = json_encode($params['body']);
}
// Using URL encoded params here instead of a more convenient array
// cURL will set a wrong HTTP Content-Type header if using an array (cf. http://www.php.net/manual/en/function.curl-setopt.php, Notes section for "CURLOPT_POSTFIELDS")
// OAuth requires application/x-www-form-urlencoded Content-Type (cf. https://tools.ietf.org/html/rfc6749#section-2.3.1)
if ($params) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $urlEncodedParams);
}
}
if( $type == "DELETE" ){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
}
if( $type == "PATCH" ){
curl_setopt($ch, CURLOPT_POST, 1);
if($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
}
$response = curl_exec($ch);
if( $response === false ) {
Hybrid_Logger::error( "OAuth2Client::request(). curl_exec error: ", curl_error($ch) );
@ -263,4 +285,18 @@ class OAuth2Client
return $result;
}
/**
* DELETE wrapper for provider apis request
*/
function delete( $url, $parameters = array() )
{
return $this->api( $url, 'DELETE', $parameters );
}
/**
* PATCH wrapper for provider apis request
*/
function patch( $url, $parameters = array() )
{
return $this->api( $url, 'PATCH', $parameters );
}
}