Кто-нибудь может сказать, почему $ auth_url становится пустым в этом коде?

Мой код приведен ниже: я пытаюсь использовать этот код для импорта контактов Yahoo, в которых я указал app_id, URL-адрес обратного вызова, идентификатор клиента и секрет клиента. Я не понимаю, почему ссылка создает всплывающие окна с тем же URL-адресом. Может быть, это из-за $ auth_url, кто-нибудь может помочь, что я пропускаю?
FILE) ‘/ Lib / Yahoo.inc’.

//for converting xml to array
function XmltoArray($xml) {
$array = json_decode(json_encode($xml), TRUE);

foreach ( array_slice($array, 0) as $key => $value ) {
if ( empty($value) ) $array[$key] = NULL;
elseif ( is_array($value) ) $array[$key] = XmltoArray($value);
}

return $array;
}

// debug settings
//error_reporting(E_ALL | E_NOTICE); # do not show notices as library is php4 compatable
//ini_set('display_errors', true);
YahooLogger::setDebug(true);
YahooLogger::setDebugDestination('LOG');

// use memcache to store oauth credentials via php native sessions
//ini_set('session.save_handler', 'files');
//session_save_path('/tmp/');
session_start();

// Make sure you obtain application keys before continuing by visiting:
// https://developer.yahoo.com/dashboard/createKey.html

define('OAUTH_CONSUMER_KEY', '****');
define('OAUTH_CONSUMER_SECRET', '****');
define('OAUTH_DOMAIN', '*****');
define('OAUTH_APP_ID', '****');

if(array_key_exists("logout", $_GET)) {
// if a session exists and the logout flag is detected
// clear the session tokens and reload the page.
YahooSession::clearSession();
header("Location: index.php");
}

// check for the existance of a session.
// this will determine if we need to show a pop-up and fetch the auth url,
// or fetch the user's social data.
$hasSession = YahooSession::hasSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);

if($hasSession == FALSE) {
// create the callback url,
$callback = YahooUtil::current_url()."?in_popup";
$sessionStore = new NativeSessionStore();
// pass the credentials to get an auth url.
// this URL will be used for the pop-up.
$auth_url = YahooSession::createAuthorizationUrl(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, $callback, $sessionStore);



}
else {
// pass the credentials to initiate a session
$session = YahooSession::requireSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);

// if the in_popup flag is detected,
// the pop-up has loaded the callback_url and we can close this window.
if(array_key_exists("in_popup", $_GET)) {
close_popup();
exit;
}

// if a session is initialized, fetch the user's profile information
if($session) {
// Get the currently sessioned user.
$user = $session->getSessionedUser();

// Load the profile for the current user.
$profile = $user->getProfile();
$profile_contacts=XmltoArray($user->getContactSync());
$contacts=array();
foreach($profile_contacts['contactsync']['contacts'] as $key=>$profileContact){
foreach($profileContact['fields'] as $contact){
$contacts[$key][$contact['type']]=$contact['value'];
}
}
// echo "<pre/>";
// print_r($contacts);exit;

}
}
//echo "<pre />";
//print_r($_SESSION);exit;
/**
* Helper method to close the pop-up window via javascript.
*/
function close_popup() {
?>
<script type="text/javascript">
window.close();
</script>
<?php
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Get the contact list from Yahoo-Idiot Minds</title>
<style type="text/css">
body{
background-color: #F2F2F2;
}
.yh_frnds{
list-style:none;
}
.yh_frnds li{
padding:10px;
float:left;
width:30%;
}
.frnd_list{
margin-top:-25px;
margin-left:40px;
}
.fb_frnds a{
text-decoration:none;
background: #333;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#333', endColorstr='#D95858'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#333), to(#D95858)); /* for webkit browsers */
background: -moz-linear-gradient(top,  #333,  #D95858)/* for firefox 3.6+ */ ;
color: #FFFFFF;
float: right;
font: bold 13px arial;
margin-right:110px ;


}
</style>

<!-- Combo-handled YUI JS files: -->
<script type="text/javascript" src="yahoo-dom-event.js"></script>
<script type="text/javascript" src="popupmanager.js"></script>

</head>
<body>
<?php
if($hasSession == FALSE) {
// if a session does not exist, output the
// login / share button linked to the auth_url.
?>
<a href="<?php echo $auth_url; ?>" id="yloginLink"><img src="yahoo-oauth-connect.png" style="width:150px;margin-left: 350px;" title="Get the contact list from Yahoo-Idiot Minds" alt="Get the contact list from Yahoo-Idiot Minds" /></a>
<?php  }
else if($hasSession && $profile) {

// if a session does exist and the profile data was
// fetched without error, print out a simple usercard.
?>
<img src="<?php echo $profile->image->imageUrl; ?>" style="width:10%;" />
<h2>Hi <a href="<?php echo $profile->profileUrl; ?>" target="_blank"><?php echo $profile->nickname; ?></a>
</h2>

<?php
if($profile->status->message != "") {
$statusDate = date('F j, y, g:i a', strtotime($profile->status->lastStatusModified));
echo sprintf("<p><strong>&#8220;</strong>%s<strong>&#8221;</strong> on %s</p>", $profile->status->message, $statusDate);
}

echo "<p><a href=\"?logout\">Logout</a></p>"; ?>

<ul  class="yh_frnds">
<?php
foreach($contacts as $user_friend){

if(isset($user_friend['email'])){
?>
<li ><img src="yahoo1.png" width="30" height="30"/>
<div  class="frnd_list"><strong><?php echo $user_friend['name']['givenName']; ?></strong><br /><?php echo $user_friend['email'];?></div>
</li>

<?php }
}  ?>
</ul>
<?php     }
?>
<script type="text/javascript">
var Event = YAHOO.util.Event;
var _gel = function(el) {return document.getElementById(el)};

function handleDOMReady() {
if(_gel("yloginLink")) {
Event.addListener("yloginLink", "click", handleLoginClick);
}
}

function handleLoginClick(event) {
// block the url from opening like normal
Event.preventDefault(event);

// open pop-up using the auth_url
var auth_url = _gel("yloginLink").href;
PopupManager.open(auth_url,600,435);
}

Event.onDOMReady(handleDOMReady);
</script>
</body>
</html>

0

Решение

Вы никогда не меняли стрелку hasSession. Представьте себе: вы проверяете, есть ли у пользователя активный сеанс. Если у вас нет активного сеанса, вы авторизуетесь, используя тот же сервис. Но после этого входа в систему — вы никогда не перепроверяете сессию / или не обновляете стрелку hasSession. Используйте следующий код:

(Ищите @Tyralcori, чтобы найти мои изменения)

//for converting xml to array
function XmltoArray($xml) {
$array = json_decode(json_encode($xml), TRUE);

foreach ( array_slice($array, 0) as $key => $value ) {
if ( empty($value) ) $array[$key] = NULL;
elseif ( is_array($value) ) $array[$key] = XmltoArray($value);
}

return $array;
}

// debug settings
//error_reporting(E_ALL | E_NOTICE); # do not show notices as library is php4 compatable
//ini_set('display_errors', true);
YahooLogger::setDebug(true);
YahooLogger::setDebugDestination('LOG');

// use memcache to store oauth credentials via php native sessions
//ini_set('session.save_handler', 'files');
//session_save_path('/tmp/');
session_start();

// Make sure you obtain application keys before continuing by visiting:
// https://developer.yahoo.com/dashboard/createKey.html

define('OAUTH_CONSUMER_KEY', '****');
define('OAUTH_CONSUMER_SECRET', '****');
define('OAUTH_DOMAIN', '*****');
define('OAUTH_APP_ID', '****');

if(array_key_exists("logout", $_GET)) {
// if a session exists and the logout flag is detected
// clear the session tokens and reload the page.
YahooSession::clearSession();
header("Location: index.php");
}

// check for the existance of a session.
// this will determine if we need to show a pop-up and fetch the auth url,
// or fetch the user's social data.
$hasSession = YahooSession::hasSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);

if($hasSession == FALSE) {
// create the callback url,
$callback = YahooUtil::current_url()."?in_popup";
$sessionStore = new NativeSessionStore();
// pass the credentials to get an auth url.
// this URL will be used for the pop-up.
$auth_url = YahooSession::createAuthorizationUrl(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, $callback, $sessionStore);

// @Tyralcori Changes: RE-Check the session after authorization
$hasSession = YahooSession::hasSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);
}
else {
// pass the credentials to initiate a session
$session = YahooSession::requireSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);

// if the in_popup flag is detected,
// the pop-up has loaded the callback_url and we can close this window.
if(array_key_exists("in_popup", $_GET)) {
close_popup();
exit;
}

// if a session is initialized, fetch the user's profile information
if($session) {
// Get the currently sessioned user.
$user = $session->getSessionedUser();

// Load the profile for the current user.
$profile = $user->getProfile();
$profile_contacts=XmltoArray($user->getContactSync());
$contacts=array();
foreach($profile_contacts['contactsync']['contacts'] as $key=>$profileContact){
foreach($profileContact['fields'] as $contact){
$contacts[$key][$contact['type']]=$contact['value'];
}
}
// echo "<pre/>";
// print_r($contacts);exit;

}
}
//echo "<pre />";
//print_r($_SESSION);exit;
/**
* Helper method to close the pop-up window via javascript.
*/
function close_popup() {
?>
<script type="text/javascript">
window.close();
</script>
<?php
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Get the contact list from Yahoo-Idiot Minds</title>
<style type="text/css">
body{
background-color: #F2F2F2;
}
.yh_frnds{
list-style:none;
}
.yh_frnds li{
padding:10px;
float:left;
width:30%;
}
.frnd_list{
margin-top:-25px;
margin-left:40px;
}
.fb_frnds a{
text-decoration:none;
background: #333;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#333', endColorstr='#D95858'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#333), to(#D95858)); /* for webkit browsers */
background: -moz-linear-gradient(top,  #333,  #D95858)/* for firefox 3.6+ */ ;
color: #FFFFFF;
float: right;
font: bold 13px arial;
margin-right:110px ;


}
</style>

<!-- Combo-handled YUI JS files: -->
<script type="text/javascript" src="yahoo-dom-event.js"></script>
<script type="text/javascript" src="popupmanager.js"></script>

</head>
<body>
<?php
if($hasSession == FALSE) {
// if a session does not exist, output the
// login / share button linked to the auth_url.
?>
<a href="<?php echo $auth_url; ?>" id="yloginLink"><img src="yahoo-oauth-connect.png" style="width:150px;margin-left: 350px;" title="Get the contact list from Yahoo-Idiot Minds" alt="Get the contact list from Yahoo-Idiot Minds" /></a>
<?php  }
else if($hasSession && $profile) {

// if a session does exist and the profile data was
// fetched without error, print out a simple usercard.
?>
<img src="<?php echo $profile->image->imageUrl; ?>" style="width:10%;" />
<h2>Hi <a href="<?php echo $profile->profileUrl; ?>" target="_blank"><?php echo $profile->nickname; ?></a>
</h2>

<?php
if($profile->status->message != "") {
$statusDate = date('F j, y, g:i a', strtotime($profile->status->lastStatusModified));
echo sprintf("<p><strong>&#8220;</strong>%s<strong>&#8221;</strong> on %s</p>", $profile->status->message, $statusDate);
}

echo "<p><a href=\"?logout\">Logout</a></p>"; ?>

<ul  class="yh_frnds">
<?php
foreach($contacts as $user_friend){

if(isset($user_friend['email'])){
?>
<li ><img src="yahoo1.png" width="30" height="30"/>
<div  class="frnd_list"><strong><?php echo $user_friend['name']['givenName']; ?></strong><br /><?php echo $user_friend['email'];?></div>
</li>

<?php }
}  ?>
</ul>
<?php     }
?>
<script type="text/javascript">
var Event = YAHOO.util.Event;
var _gel = function(el) {return document.getElementById(el)};

function handleDOMReady() {
if(_gel("yloginLink")) {
Event.addListener("yloginLink", "click", handleLoginClick);
}
}

function handleLoginClick(event) {
// block the url from opening like normal
Event.preventDefault(event);

// open pop-up using the auth_url
var auth_url = _gel("yloginLink").href;
PopupManager.open(auth_url,600,435);
}

Event.onDOMReady(handleDOMReady);
</script>
</body>
</html>
0

Другие решения

Других решений пока нет …