Twitter Followers - Want to jump from page 1 to 3 - php

I'm trying to to display all Twitter followers for specific account in PHP, using this API request
https://api.twitter.com/1.1/followers/list.json
As per this page Cursoring - Twitter Documentation I have the use the next cursor to receive the next batch of responses.
That will allow me to make pagination button for the next page and previous page since I don't know what is the value of next_cursor for 3rd,4th, ... pages.
Is there a way to make paging links like 1,[2],[3],[4],[5],[..] so I can jump to the 3rd page without visiting the 2nd page?
I'm using Yii, Abraham Williams TwitterOAuth class.

I usually use this method to obtain all twitter followers of an account with Abraham Williams TwitterOAuth class:
$arrayFollowersIds = array();
// Cursor pointing the first page
$cursorFollowers = -1;
for ($i = 0; $i < 15; $i++) {
// If we have reached the last page...
if ($cursorFollowers == 0) break;
$followersArray = get_object_vars($connection->get('followers/ids', array('user_id' => $targetUserId, 'cursor' => $cursorFollowers)));
if (array_key_exists('ids', $followersArray)) {
$cursorFollowersActual = $followersArray['next_cursor'];
$arrayFollowersIds = array_merge($arrayFollowersIds, $followersArray['ids']);
}
else {
// An error ocurred
break;
}
}
// Show all user ids
var_dump($arrayFollowersIds);
The for loop has a limit because as you can see in the documentation, you are only allowed to make 15 calls every 15 minutes. You will have to store ids for big accounts and merge them later.
Hope this helps!

Related

phpredis zRange return

I'm getting a http 500 error when trying to post to this leaderboard index:
<?php
$reference = "sorted";
$printboard = "leaderboard";
$my_win = 0;
$my_check = 0;
//get the name or member or element of the lowest score
$my_check = $redis->zRange($reference, 0, 0);
//I have the lowest ranking member now get that members score to check against
$my_win = $redis->zScore($reference, $my_check[0]);
//$wins is what I'm posting to this index
if ($my_win < $wins) {
$redis->zDelete($reference, $my_check);//I beat the lowest ranking user so take his spot
//update the new score and push the new user to the print list
$redis->zAdd($reference,$wins, $name);
//if im adding someone new I need to remove someone
//if this is running I want to strip the list of it's 99th user so don't use 1188 use 1176
$redis->listTrim($printboard, 0, 1176);
//then rpush the new player to have made the list
$redis->rpush($printboard,$name,$avatar,$wins,$losses,$ties,$fave,$meter,$game1,$game2,$game3,$game4,$game5);
}
?>
Is my use of zRange correct?
$my_check = $redis->zRange($reference, 0, 0);
And then checking the first array spot?
$my_win = $redis->zScore($reference, $my_check[0]);
I think this may be my issue am I using the return of $my_check incorrectly?
Also, with Redis do you ever need to initialize anything?
I frequently go over the phpredis GitHub manual and the redis website itself and didn't note any details about what happens if you use zRange on an empty sorted set.

Google Adwords Incorrect statistics

I'm using the Google AdWords PHP API to access statistics from our account. However, I'm getting some really strange read outs from the statistics through the api. I'm trying to access the stats for individuals Ads or Adgroups. The statistics returned, however, are way off what they are in the client center. The code I'm using:
$user->SetClientCustomerId($clientId);
$adService = $user->GetService("AdGroupAdService", ADWORDS_VERSION);
$selector = new Selector();
$selector->fields = array("Id", "Name", "Clicks", "Impressions", "Cost");
$selector->predicates[] = new Predicate("AdGroupId", "IN", array($adGroupId));
$selector->dateRange = $dateRange;
$selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
do {
// Make the get request.
$page = $adService->get($selector);
if (isset($page->entries)) {
foreach ($page->entries as $ad) {
$newLineObject->adName = $ad->name;
$newLineObject->clicks = $ad->ad->AdStats->clicks;
$newLineObject->impressions = $ad->adStats->impressions;
$newLineObject->cost = $ad->ad->AdStats->cost->microAmount/ AdWordsConstants::MICROS_PER_DOLLAR;
}
}
else {
print "No matching ads were found.\n";
}
$selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
} while ($page->totalNumEntries > $selector->paging->startIndex);
When I print the results I get numbers that are considerably larger than those displayed in the client center. For example, for one partiuclar Ad the API reported 2.000.000 impressions, while the client center showed 56.000.
What am I doing wrong?
Your code seems correct to me. However, you problem may be that your date range in your code is different to the one you see in your client center. Make sure that you keep the same date range when you cross check.
Having tried using the method detailed above extensively, I have altered my code completely. I now use AdHoc Reporting (described here https://developers.google.com/adwords/api/docs/guides/reporting). This method was suggested to me by an AdWords developer. While this does not literally solve my question (i.e. why does the above code return incorrect statistics), it does provide an easy and clean way to obtain the data correctly.

GET Json API Results

I searched for this but most of the questions related to this are for API's with other services.
I'm building an API that allows game developers to send and retrieve user info from my database.
I was finally able to put together the API, but now I need to call the API.
1st when the game initiates, it sends us the game developers key their developer id and game id.
//Game loads, get developer key, send token and current high score
// == [ FIRST FILTER - FILTER GET REQUEST ] == //
$_GET = array_map('_INPUT', $_GET); // filter all input
// ====================================== //
// ============[ ACTION MENU ]=========== //
// ====================================== //
if(!empty($_GET['action']) && !empty($_GET['user']) && !empty($_GET['key']) && !empty($_GET['email']) && !empty($_GET['password'])): // if key data exists
switch($_GET['action']):
//athenticate game developer return and high score
case 'authenticate':
$db = new PDO('mysql:host=localhost;dbname=xxxx', 'xxxx', 'xxxx');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$st = $db->prepare("SELECT * FROM `game_developers_games` WHERE `id` = :gameid AND `developer_id`=:user AND `key`= :key AND `developer_active` = '1'"); // need to filter for next auction
$st->bindParam(':user', $_GET['user']); // filter
$st->bindParam(':key', $_GET['key']); // filter
$st->execute();
$r = $st->fetch(PDO::FETCH_ASSOC);
if($st->rowCount() == 0):
$return = array('DBA_id'=>'0000');
echo json_encode($return);
else:
$token = initToken($_GET['key'],$_GET['user']);
if($token == $r['API_Token']):
$return = array(
'DBA_id'=>$token,
'DBA_servertime'=>time(),
'DBA_highscore'=>$r['score'],
);
echo json_encode($return);
endif;
endif;
break;
Here's the script the game developer will have to add to their game to get the data when the game loads. Found this on another stackoverflow question but it's not working.
$.getJSON("https://www.gamerholic.com/gamerholic_api/db_api_v1.php? user=1&key=6054abe3517a4da6db255e7fa27f4ba001083311&gameid=1&action=authenticate", function () {
alert("aaa");
});
Try adding &callback=? to the end of the url you are constructing. This will enable jsonp that is accepted by cors.
$.getJSON("https://www.gamerholic.com/gamerholic_api/db_api_v1.php?user=1&key=6054abe3517a4da6db255e7fa27f4ba001083311&gameid=1&action=authenticate&callback=?", function () {
alert("aaa");
});
As per cross domain origin policy you cannot access cross domain url using jquery getJson function.
A callback is required to manage cross domain request using json and it needs to be handled on the server as well as the client end.
Also make sure to check the response using firebug or similar tool because as of now it is returning response code as 200.
I am mentioning two threads here which can guide you the right way
Jquery getJSON cross domain problems
http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/

Retrieve top 10 friends of user on Facebook (get their UIDs) PHP, Facebook API

How do I get a user's top 10 friends' uids, and wrap each uid with specified string?
From: Get list of top friends for facebook app, I see this:
$statuses = $facebook->api('/me/statuses');
foreach($statuses['data'] as $status){
// processing likes array for calculating fanbase.
foreach($status['likes']['data'] as $likesData){
$frid = $likesData['id'];
$frname = $likesData['name'];
$friendArray[$frid] = $frname;
}
foreach($status['comments']['data'] as $comArray){
// processing comments array for calculating fanbase
$frid = $comArray['from']['id'];
$frname = $comArray['from']['name'];
}
But what does that return? Does it return the user IDs of friends in an array? I would like to get it in an array, the result of the search, so I can wrap each ID using foreach and do what I please with it.
If the above code is enough, should I be calling $frid for the array of top friends? I just need comprehension. :o)
Thank you for your time.
Assume that permissions are granted.
(This happens only after the user allows permission, so assume we already have that.)
Ensure you have the latest SDK by going to https://github.com/facebook/facebook-php-sdk/zipball/master
Unzip and you have a layout as shown below
/facebook-php-sdk
index.php
Where index.php with the file being used to display in the browser the number of friends
Include the SDK at the start of the PHP file
require('sdk/src/facebook.php');
Go to https://developers.facebook.com/apps, select your app and get your App ID and App Secret, create an instance within the PHP file
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID_HERE',
'secret' => 'YOUR_SECRET_HERE',
));
Then retrieve the $user data so we know that the current user is authenticated
$user = $facebook->getUser();
Before sending any calls check whether the authentication was right
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
Now make a call to /me/statuses the documentation is available at https://developers.facebook.com/docs/reference/api/user/#statuses
$statuses = $facebook->api('/me/statuses');
This should return an array of the structure Status message defined at http://developers.facebook.com/docs/reference/api/status/ of all the current user status messages.
Now you need to decide what determines top friends
number of likes + comments
number of comments
number of likes
Let's choose option 1, and give each weight of 1. That is a like and a comment are equivalent in value for determining the amount of friends
So create a variable to hold this, for example $friendArray
Then make an iteration over all the status messages but the entire JSON reponse starts with a wrapped data
{
"data": [
So access $statuses['data'], the foreach will give all status messages as a status item
foreach($statuses['data'] as $status){
Within this loop iterate all the likes and increment the value of each id that appears
foreach($status['likes']['data'] as $likesData){
$frid = $likesData['id'];
$friendArray[$frid] = $friendArray[$frid] + 1;
}
Within this loop iterate all the comments and increment the value of each id that appears
foreach($status['comments']['data'] as $comArray){
$frid = $comArray['from']['id'];
$friendArray[$frid] = $friendArray[$frid] + 1;
}
At the end of the outer loop foreach($statuses['data'] as $status){ you should have the an array $friendArray which has the scores.
Call asort http://www.php.net/manual/en/function.asort.php to sort the array and you can then loop for the top x scores.
The code you showed isn't a function and is actually missing a closing brace, it does not actually return anything as it is not a function.
Caveats: The /me/statuses only returns a limited set of status messages per call you need to get previous page calls to iterate all your messages. The top friends returned are only based on the restriction I made up above.

facebook api: count attendees for event (limit problem)

Okay normally I'm all fine about the facebook API but I'm having a problem which just keeps me wondering. (I think it's a bug (Check ticket http://bugs.developers.facebook.net/show_bug.cgi?id=13694) but I wanted to throw it here if somebody has an idea).
I'm usng the facebook PHP library to count all attendees for a specific event
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending');
this works without a problem it correctly returns an array with all attendees...
now heres the problem:
This event has about 18.000 attendees right now.
The api call returns a max number of 992 attendees (and not 18000 as it should).
I tried
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending?limit=20000');
for testing but it doesn't change anything.
So my actual question is:
If I can't get it to work by using the graph api what would be a good alternative? (Parsing the html of the event page maybe?) Right now I'm changing the value by hand every few hours which is tedious and unnecessary.
Actually there are two parameters, limit and offset. I think that you will have to play with both and continue making calls until one returns less than the max. limit.
Something like this, but in a recursive approach (I'm writting pseudo-code):
offset = 0;
maxLimit = 992;
totalAttendees = count(result)
if (totalAttendees >= maxLimit)
{
// do your stuff with each attendee
offset += totalAttendees;
// make a new call with the updated offset
// and check again
}
I've searched a lot and this is how I fixed it:
The requested URL should look something like this.
Here is where you can test it and here is the code I used:
function events_get_facebook_data($event_id) {
if (!$event_id) {
return false;
}
$token = klicango_friends_facebook_token();
if ($token) {
$parameters['access_token'] = $token;
$parameters['fields']= 'attending_count,invited_count';
$graph_url = url('https://graph.facebook.com/v2.2/' . $event_id , array('absolute' => TRUE, 'query' => $parameters));
$graph_result = drupal_http_request($graph_url, array(), 'GET');
if(is_object($graph_result) && !empty($graph_result->data)) {
$data = json_decode($graph_result->data);
$going = $data->attending_count;
$invited = $data->invited_count;
return array('going' => $going, 'invited' => $invited);
}
return false;
}
return false;
}
Try
SELECT eid , attending_count, unsure_count,all_members_count FROM event WHERE eid ="event"

Categories