Jump to content

Recommended Posts

I am trying to call from a api the bit i want is CurrentActivity so then i can add it to the line on my block to show user online on the website there name on the website ( them bits are done ) then activity on xbox so

dont expect anyone to do all the work for me just a bit of a clue where to start would be great

 

need to add somthing to the end of

<img src="', $member['online']['image_href'], '" alt="', $member['online']['label'], '" /> <span class="smalltext">', $member['link'], '</span><br />';

 

 

the api is

 

<?php
/* No errors pl0x */
if ( !isset( $_REQUEST['debug'] ) )
ini_set( 'display_errors', 0 );

/**
* cURL Multiple Requester
*
* @author Jackson Owens (http://debugsober.com/blog/CURL-multi-object-oriented-class-for-parallel-requests)
* @version 1.0
*/
class MultipleRequester
{
private $multiHandle;
private $singleHandles = array();
private $completedHandles = array();

public function addGetRequest($id, $url, $curlOptions = array())
{
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_POST, 0);

// extra options?
if (!empty($curlOptions)) {
curl_setopt_array($ch, $curlOptions);
}

// Add handle to our array of single handles
$this->singleHandles[$id] = &$ch;
}

public function addPostRequest($id, $url, $postData, $curlOptions = array())
{
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Turn post fields into a string
$postString = "";
$count = 1;
$length = count($postData);
foreach($postData as $key => $val)
{
$postString .= rawurlencode($key) . '=' . rawurlencode($val);
if($count != $length) {
$postString .= "&";
}
$count++;
}

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);

// More options?
if (!empty($curlOptions)) {
curl_setopt_array($ch, $curlOptions);
}

$this->singleHandles[$id] = &$ch;

}

public function execute($howMany = -1) {

$this->multiHandle = curl_multi_init();

$currentHandles = array();

$count = 0;
foreach($this->singleHandles as $id => $ch) {

if($howMany != -1 && $howMany <= $count) {
// They don't want to request any more than this right now...
break;
}

$currentHandles[$id] = $this->singleHandles[$id];

unset($this->singleHandles[$id]);

curl_multi_add_handle($this->multiHandle, $currentHandles[$id]);


$count++;
}

$running = null;

do {

curl_multi_exec($this->multiHandle,$running);

} while ($running > 0);

// Remove the individual handles
foreach($currentHandles as $id => $ch) {

curl_multi_remove_handle($this->multiHandle, $ch);
$this->completedHandles[$id] = $ch;

}

curl_multi_close($this->multiHandle);
$this->multiHandle = null;

}

public function getCompletedIds() {

$ids = array();

foreach($this->completedHandles as $id => $handle) {

array_push($ids, $id);
}

return $ids;

}

public function deleteCompletedHandle($id) {

@curl_close($this->completedHandles[$id]);
unset($this->completedHandles[$id]);


}

public function moreRemaining() {

if(count($this->singleHandles) > 0) {
return true;
}
else {
return false;
}

}

public function getContent($id) {

return curl_multi_getcontent($this->completedHandles[$id]);

}

public function getStatusCode($id) {
return curl_getinfo($this->completedHandles[$id], CURLINFO_HTTP_CODE);
}

public function getContentType($id) {
return curl_getinfo($this->completedHandles[$id], CURLINFO_CONTENT_TYPE );
}

public function finish() {

// Close single handles...

foreach($this->singleHandles as $id => $ch) {

@curl_close($ch);
$this->singleHandles[$id] = null;

}

// Close completed handles

foreach($this->completedHandles as $id => $ch) {

@curl_close($ch);
$this->completedHandles[$id] = null;

}
}

public function __destruct() {

if(count($this->singleHandles) > 0) {
$this->finish();
}

}
}

/**
* Xbox API Scraper
*
* Collects data for a given gamertag from the
* Xbox LIVE website, and parses it into an object
* for later use.
*
* @author Jason Clemons (http://about.me/jason_clemons)
* @version 1.0
*/
class XboxAPI
{
/* Whether or not to enable caching of results */
public $enable_cache = false;

/* The path where you want to save the cached results */
public $cache_dir = 'cache';

/* Number of seconds cached results should expire */
public $cache_time = 3600;

/**
* Cache the response
*
* @access private
* @var string
* @var object
* @return bool
*/
private function cache_response( $gamertag, $data )
{
/* Serialize the data and add a timestamp */
$to_cache = array( 'timestamp' => time(), 'xml' => $data );
$to_cache = serialize( $to_cache );

/* Create the cache file */
if ( $handle = fopen( $this->cache_dir . '/' . $this->convert_gamertag( $gamertag ), 'w' ) )
{
/* Attempt to write */
if ( fwrite( $handle, $to_cache ) )
{
return true;
}
else
{
return false;
}
}
/* We've failed... */
else
{
return false;
}
}

/**
* Reads the data from the cache
*
* @access private
* @var string
* @return bool
*/
private function read_cache( $gamertag )
{
/* Open the cache */
if ( $handle = @fopen( $this->cache_dir . '/' . $this->convert_gamertag( $gamertag ), 'r' ) )
{
/* Read the file */
if ( !$data = fread( $handle, filesize( $this->cache_dir . '/' . $this->convert_gamertag( $gamertag ) ) ) )
{
return false;
}

/* Unserialize the data */
$data = unserialize( $data );

/* Remove the cache file? */
if ( time() - $this->cache_time >= $data['timestamp'] )
{
/* Attempt to delete the file */
if ( !unlink( $this->cache_dir . '/' . $this->convert_gamertag( $gamertag ) ) )
{
return false;
}
}

/* Return the XML data */
return $data['xml'];
}
/* We've failed... again */
else
{
return false;
}
}

/**
* Converts a gamertag to a more URL-friendly form
*
* @access private
* @var string
* @return string
*/
private function convert_gamertag( $gamertag )
{
return strtolower( str_replace( array( ' ', '+' ), '%20', $gamertag ) );
}

/**
* Returns the tid value from a game URL
*
* @access private
* @var string
* @return int
*/
private function get_tid( $string )
{
$tid = parse_url( $string );
$tid = explode( '&', html_entity_decode( $tid['query'] ) );
$tid = explode( '=', $tid['0'] );

return (int)$tid['1'];
}

/**
* Cleans the response, and puts the data into an object
*
* @access private
* @var string
* @return object
*/
private function clean_dirty_response( $object )
{
$final_object = new stdClass();

/* Gamertag */
preg_match( '~<a id="Gamertag" href=".*?">(.*?)</a>~si', $object[1], $gamertag );
$final_object->user->gamertag = $gamertag[1];
/* Is Valid */
preg_match( '~<img id="Gamerpic" src="(.*?)" alt~si', $object[1], $avatar );
$final_object->user->is_valid = $avatar[1] === 'http://image.xboxlive.com//global/t.FFFE07D1/tile/0/20000' ? 0 : 1;
/* Profile Link */
$final_object->user->profile_link = 'http://live.xbox.com/member/' . $this->convert_gamertag( $gamertag[1] );
/* Xbox360 Launch Team */
$final_object->user->launch_team->xbl = preg_match( '~<div id="Xbc360Launch"~', $object[1] ) ? 1 : 0;
/* NXE Launch Team */
$final_object->user->launch_team->nxe = preg_match( '~<div id="XbcNXELaunch"~', $object[1] ) ? 1 : 0;
/* Kinect Launch Team */
$final_object->user->launch_team->kinect = preg_match( '~<div id="XbcKinectLaunch"~', $object[1] ) ? 1 : 0;
/* Account Status */
preg_match( '~<div class="XbcGamercard (.*?)">~si', $object[1], $status );
$final_object->user->account_status = preg_match( '~Gold~si', $status[1] ) ? 'Gold' : 'Silver';
/* Gender */
preg_match( '~<div class="XbcGamercard (.*?)">~si', $object[1], $gender );
$final_object->user->gender = preg_match( '~Male~si', $gender[1] ) ? 'Male' : 'Female';
/* Is Cheater */
preg_match( '~<div class="XbcGamercard (.*?)">~si', $object[1], $cheater );
$final_object->user->is_cheater = preg_match( '~Cheater~si', $cheater[1] ) ? 1 : 0;
/* Online */
preg_match( '~<div id="CurrentActivity">(.*?)</div>~si', $object[0], $online);
$final_object->user->is_online = ( preg_match( '~Last seen~si', $online[1] ) or trim( $online[1] ) === '' ) ? 0 : 1;
/* Online Status */
preg_match( '~<div id="CurrentActivity">(.*?)</div>~si', $object[0], $onlinestatus);
$final_object->user->online_status = ( trim( $onlinestatus[1] ) !== '' ) ? trim( $onlinestatus[1] ) : 'Unknown';
/* Avatars */
$final_object->user->avatars->gamer_tile = $avatar[1];
$final_object->user->avatars->small_gamerpic = 'http://avatar.xboxlive.com/avatar/' . $this->convert_gamertag( $gamertag[1] ) . '/avatarpic-s.png';
$final_object->user->avatars->large_gamerpic = 'http://avatar.xboxlive.com/avatar/' . $this->convert_gamertag( $gamertag[1] ) . '/avatarpic-l.png';
$final_object->user->avatars->body_gamerpic = 'http://avatar.xboxlive.com/avatar/' . $this->convert_gamertag( $gamertag[1] ) . '/avatar-body.png';
/* Reputation */
preg_match_all( '~<div class="Star (.*?)">~si', $object[1], $rep );
$total_rep = 0;
foreach ($rep[1] as $k => $v)
{
$starvalue = array(
'Empty' => 0,
'Quarter' => 5,
'Half' => 10,
'ThreeQuarter' => 15,
'Full' => 20
);

$total_rep = $total_rep + $starvalue[$v];
}
$final_object->user->reputation = (int)$total_rep;
/* Gamerscore */
preg_match( '~<div id="Gamerscore">(.*?)</div>~si', $object[1], $gamerscore );
$final_object->user->gamerscore = (int)$gamerscore[1];
/* Location */
preg_match( '~<div id="Location">(.*?)</div>~si', $object[1], $location );
$final_object->user->location = (string)$location[1];
/* Motto */
preg_match( '~<div id="Motto">(.*?)</div>~si', $object[1], $motto );
$final_object->user->motto = (string)$motto[1];
/* Name */
preg_match( '~<div id="Name">(.*?)</div>~si', $object[1], $name );
$final_object->user->name = (string)$name[1];
/* Bio */
preg_match( '~<div id="Bio">(.*?)</div>~si', $object[1], $bio );
$final_object->user->bio = (string)$bio[1];

/* Recent Games */
if ( !preg_match( '~<ol id="PlayedGames" class="NoGames">~', $object[1] ) )
{
preg_match( '~<ol id="PlayedGames" >(.*?)</ol>~si', $object[1], $recent_games );

/**
* 1. Link
* 2. Tile
* 3. Title
* 4. Last Played
* 5. Earned Gamerscore
* 6. Available Gamerscore
* 7. Earned Achievements
* 8. Available Achievements
* 9. Percentage Complete
*/
preg_match_all( '~<li.*?>.*?<a href="(.*?)">.*?<img src="(.*?)" alt=".*?" title=".*?" />.*?<span class="Title">(.*?)</span>.*?<span class="LastPlayed">(.*?)</span>.*?<span class="EarnedGamerscore">(.*?)</span>.*?<span class="AvailableGamerscore">(.*?)</span>.*?<span class="EarnedAchievements">(.*?)</span>.*?<span class="AvailableAchievements">(.*?)</span>.*?<span class="PercentageComplete">(.*?)%</span>.*?</a>.*?</li>~si', $recent_games[1], $lastplayed, PREG_SET_ORDER );

$i = 1;
foreach ( $lastplayed as $recent_game )
{
$obj = new stdClass();

$obj->title = (string)$recent_game[3];
$obj->tid = (int)$this->get_tid( $recent_game[1] );
$obj->marketplace_url = (string)'http://marketplace.xbox.com/Title/' . $this->get_tid( $recent_game[1] );
$obj->compare_url = (string)$recent_game[1];
$obj->image = (string)$recent_game[2];
$obj->last_played = (string)strtotime( $recent_game[4] );
$obj->earned_gamerscore = (int)$recent_game[5];
$obj->available_gamerscore = (int)$recent_game[6];
$obj->earned_achievements = (int)$recent_game[7];
$obj->available_achievements = (int)$recent_game[8];
$obj->percentage_complete = (int)$recent_game[9];

$final_object->recent_games->$i = $obj;
++$i;
}
}
else
{
$final_object->recent_games = false;
}

return $final_object;
}

/**
* Makes a request using the MultipleRequester class to fetch data
* from a URL.
*
* @access private
* @var array
* @var string
* @return array
*/
private function build_request( $urls )
{
/* Create a new MultipleRequester object */
$requester = new MultipleRequester();

/* Loop through the URLs getting the data */
foreach ( $urls as $k => $v )
{
$requester->addGetRequest( $k, $v );
}

/* Keep looping through */
while ( $requester->moreRemaining() )
{
$requester->execute(1);
}

/* Put the data into an array */
$html = array();
foreach ( $urls as $k => $v )
{
$html[$k] = $requester->getContent( $k );
}

return $html;
}

/**
* Builds the request to output data
*
* @access public
* @var string
* @return object
*/
public function make_request( $gamertag )
{
/* Convert the gamertag */
$gamertag = $this->convert_gamertag( $gamertag );

/* Are we caching our data? */
if ( $this->enable_cache === true )
{
/* Attempt to read the cache. Create it if it fails. */
$clean_response = $this->read_cache( $gamertag );

if ( $clean_response === false )
{
/* Get the data from the server */
$response = $this->build_request( array(
'http://live.xbox.com/en-US/member/' . $gamertag . '/',
'http://gamercard.xbox.com/en-US/' . $gamertag . '.card'
), $gamertag );

// By default the server returns the data in a rather ugly and unstructured way, let's clean this mess up!
$clean_response = $this->clean_dirty_response( $response );

// Cache it
$this->cache_response( $gamertag, $clean_response );
}
}
// Cache has been disabled, slowness behold!
else
{
/* Get the data from the server */
$response = $this->build_request( array(
'http://live.xbox.com/en-US/member/' . $gamertag,
'http://gamercard.xbox.com/en-US/' . $gamertag . '.card'
), $gamertag );

$clean_response = $this->clean_dirty_response( $response );
}

/* Return the cleaned data */
return $clean_response;
}
}

/**
* REST API class
*
* @author Ian Selby (http://www.gen-x-design.com/archives/create-a-rest-api-with-php/)
* @version 1.0
*/
class RestAPI
{
public static function getStatusCodeMessage( $status )
{
$codes = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => '(Unused)',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);

return ( isset( $codes[$status] ) ) ? $codes[$status] : '';
}

public static function sendResponse( $status = 200, $body = '', $content_type = 'text/html' )
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . self::getStatusCodeMessage( $status );
header( $status_header );
header( 'Content-type: ' . $content_type );

if($body != '')
{
echo $body;
exit;
}
else
{
$message = '';
switch($status)
{
case 401:
$message = 'You must be authorized to view this page.';
break;
case 404:
$message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
break;
case 500:
$message = 'The server encountered an error processing your request.';
break;
case 501:
$message = 'The requested method is not implemented.';
break;
}
$signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
$body = '<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>' . $status . ' ' . self::getStatusCodeMessage($status) . '</title>
</head>
<body>
<h1>' . self::getStatusCodeMessage($status) . '</h1>
<p>' . $message . '</p>
<hr />
<address>' . $signature . '</address>
</body>
</html>';

echo $body;
exit;
}
}
}

/* Instantiate! */
$rest = new RestAPI();
$xbox = new XboxAPI();

if ( !isset( $_REQUEST['gamertag'] ) )
$rest->sendResponse( 404, json_encode( array( 'response' => array( 'error' => 'No gamertag specified' ), 'stat' => 'fail' ) ), 'application/json' );
//elseif ( !isset( $_REQUEST['apikey'] ) )
// $rest->sendResponse( 404, json_encode( array( 'response' => array( 'error' => 'Invalid API key' ), 'stat' => 'fail' ) ), 'application/json' );
else
{
/* Make sure the key is valid */
//if ( $valid === false )
// $data->sendResponse( 404, json_encode( array( 'response' => array( 'error' => 'Invalid API key' ), 'stat' => 'fail' ) ), 'application/json' );

/* Clean up */
$gamertag = urldecode( $_REQUEST['gamertag'] );
$format = strtolower( $_REQUEST['format'] );
$apikey = $_REQUEST['apikey'];

/* Make sure the gamertag format is valid */
if ( !preg_match( '/^(?=.{1,15}$)[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*$/', $gamertag ) )
$rest->sendResponse( 404, json_encode( array( 'response' => array( 'error' => 'Invalid gamertag' ), 'stat' => 'fail' ) ), 'application/json' );

/* Make the request */
$data = $xbox->make_request( $gamertag );

/* Check to make sure the gamertag exists */
if ( $data->user->is_valid === 0 )
$rest->sendResponse( 404, json_encode( array( 'response' => array( 'error' => 'Gamertag does not exist' ), 'stat' => 'fail' ) ), 'application/json' );

/* Prelim checks OK, send the full response! */
$rest->sendResponse( 200, json_encode( array( 'response' => array( $data ), 'stat' => 'ok' ) ), 'application/json' );
}

Link to comment
https://forums.phpfreaks.com/topic/242133-call-from-api/
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.