Facebook Graph api get Posts starting from x post (PHP SDK) - php

Hello i've serched a lot without find an answer to this.
is possible to retrieve Fb posts of a certain public page starting from a post id?(for example tomorrow start collecting posts from the last post of today)
Let's take for example Bill Gates page
the idea would be to do something similar to:
$id = 216311481960; //Bill's fb id
$last_post = 10153219939326961 // last bill posts
try {
$request= $id.'/posts?since='.$last_post.'&access_token=xxxxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxx-xxxxxx';
$search = $fb->get($request);
if (isset($search)){
//do something
}
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage()."<h1>".$id."</h1>";
}
obviously since parameter has to be a date and that code wont work.
Any Idea?
Thanks in advance.
Edit
i try to search for all posts of a specific Facebook user starting not at a certain date but from a certain post, lets say that today i grab users postid1,postid2,postid3 (postid3 is the last post i've taken, and i save that id) next time i would to grab new posts published after postid3 (since postid3)

You can do it in the url, I just made it work recently. This is from a python code, but the URL should work the same way.
"https://graph.facebook.com/?ids=" + ids[:-1] +
"&fields=name,posts.limit(5).since(10+days+ago)" +
"{from,to,full_picture,message,caption,description," +
"link,name,shares,likes.summary(true)," +
"comments.summary(true),created_time,is_hidden," +
"message_tags,place,type,with_tags}")
This will get the last 5 posts from the last 10 days for several page ids. It will also get the total number of likes and comments as summary.
It took me a while to dig this info from the net, I found that since= has changed to since().
I tried to retrieve some reference where it's documented, so far with no success. I'll give you an update if I find it.

Related

Using PHP classes to output html

I asked the same question earlier and it got down voted and I have no idea why. I'm building a class that outputs a news feed, but it's a very structured html that I'm going to use a lot on the site (hundreds of times), so I'm using a class method to display the feed html and everything. And I just echo the whole thing.
The method is set up this way:
private function feed ($var)
{
$Statement = $this->Database->prepare("SELECT * FROM feed WHERE col = ? ORDER BY timestamp DESC LIMIT 50");
$Statement->execute(array($var));
while ($row = $Statement->fetch(PDO::FETCH_ASSOC))
{
echo ' <div class="feed-box">
' . /*facebook name retrieved from the facebook */ . '
' . $row["post"] . '
<br/>
</div>';
}
} //end feed
The class is set up so that another method that has more of the html template calls this feed method. (I'm not trying to be too redundant here, but again the last time I asked this question it got down voted). So I'm pretty new to oop, and I'm looking to display the profile pictures of people who are logged in with facebook. This isn't necessarily a facebook question because I know how to do it normally, but I don't know how to get the facebook information within the class scope using just their id. Normally I;d get their picture by going linking to this url https://graph.facebook.com//picture. How do I do this within the class when I only sotre their facebook id in the database? I've been working on this problem for a couple days now, and I can't figure it out on my own. So I really appreciate your help.
It's getting to the point where I just want to statically type everything out because I know I could easily do that, but I'd really love to learn what the proper way is, especially since editing so many of these little boxes if I want to change something one day would be a real hassle. Thanks for your help. I really appreciate it. Let me know if anything is unclear I'll update the questino as soon as I can.
How do I do this within the class when I only sotre their facebook id in the database
echo '<img src="https://graph.facebook.com/' . $row['facebook_id'] . '/picture" />' ;
You say you only store the facebook id in your database. That is all you need to display the picture. Just append /picture to the user's FB graph link to get the picture.

how to : define and get a custom report from google analytics using gapi

I have a custom report called my-newsletters in Google analytics. I want to fetch this report with a php call to $ga->requestReportData(...) and then parse the response and format it up.
First I made an account to collect all my newsletter open and click hits - each time someone opens a newsletter or clicks on a link in the newsletter I capture that with a call to the __utm.gif on Google. That part is working and I include in the call ( in the Landing Page aka utmp parameter) some data such as the word 'open' and 'click' to distinguish the events and also some other data i hope to parse out later, plus i use the campaign field and maybe I should do something with the source field too - now I just dup the utmp field. So far that part seems to work.
Now I need help to define a report that will return that utmp and campaign field info and the number of hits each has taken, sorted by date of hit I guess. then i need to call that report from my php and then later parse it - the parsing part I'm not worried about yet.
PS: here is the code I use to generate the utm url
function getGoogleUtmUrl($source='Emails', $referer='opens', $estid='0',$mailid='0', $campaign){
$stat_id='MO-xxx31982-1';
$var_utmcs=urlencode( 'UTF-8');
$var_utmac = $stat_id;
$var_utmhn = 'mysite.com'; //enter your domain
$var_utmn = rand(1000000000,9999999999); //random request number
$var_cookie = rand(10000000,99999999); //random cookie number
$var_random = rand(1000000000,2147483647); //number under 2147483647
$var_today = time(); //today
$var_referer = $referer; //referer url
$utm_source = 'my_newsletter';
$utm_medium = 'Emails';
$utm_campaign = $campaign;//$_GET['url'];
$var_uservar = $estid.'_'.$mailid; //enter your own user defined variable
$var_utmp = 'mysite.com/newsletters/'.$referer.'/'.$estid.'/'.$mailid;//.$estid;//$_GET['url']; //this example adds a fake file request to the (fake) tracker directory (the image/pdf filename).
$urchinUrl1 = 'http://www.google-analytics.com/__utm.gif?utmwv=4.3&utmn='.$var_utmn.'&utmsr='.$referer.'&utmcs='.$var_utmcs.
'&utmul=en&utmje=0&utmfl=-&utmdt='.$utm_campaign.'&utmhn='.$var_utmhn.
'&utm_source='.$var_utmp.'&utm_medium='.$utm_medium.'&utm_campaign='.$utm_campaign.'&utmr='.$var_referer.
'&utmp='.$var_utmp.'&utmac='.$var_utmac.
'&utmcc=__utma%3D'.$var_cookie.'.'.$var_random.'.'.
$var_today.'.'.$var_today.'.'.$var_today.
'.2%3B%2B__utmb%3D'.$var_cookie.'%3B%2B__utmc%3D'.
$var_cookie.'%3B%2B__utmz%3D'.$var_cookie.'.'.$var_today.
'.2.2.utmccn%3D(direct)%7Cutmcsr%3D(direct)%7Cutmcmd%3D(none)%3B%2B__utmv%3D'.
$var_cookie.'.'.'%3B';
// Now fire off the HTTP request
echo "urchinURL1 == ".$urchinUrl1.' '.__FILE__.' '.__LINE__.'<br/>';
return $urchinUrl1;
seems like over kill to me but it works, I tried the code at https://developers.google.com/analytics/devguides/collection/other/mobileWebsites and it doesn't work - the opens and clicks do not register in analytics - at least not on the real time page.
Please help.
I suggest that you build your report query first, I recommend that you use Google Analytics Query Explorer for that.
And next use the reporting API from PHP to transpose the resulting query and extract the data from within your app.

Count of comments and likes are not shown in feed and comments

Hy well how does the url looks when you use a PageID and at the same time want the count of all comments and likes back I tried it hard way
$feed_profile = $facebook->api('/'.$row[0].'/feed&access_token=$access_token&limit=500',"get");
$post_profile = $facebook->api('/'.$row[0].'/comments?access_token=$access_token&limit=500',"get");
also tried comments& instead of comments?
I dont know how to get back the comments and likes what must I exactly do my var $row[0] stores various Pages from fb
the feed has connections EG: comments, likes that provide the count.
$feed_profile = $facebook->api('/'.$row[0].'/feed&access_token=$access_token&limit=5',"get");
// get comment/like count for first post in array. this can be done with a loop.
echo 'Comments: '.$feed_profile[data][0][comments][count].'<br />';
echo 'Likes: '.$feed_profile[data][0][likes][count].'';
NOTE: you will have to account for error handling, when no comments or
likes have been made the connections arrays do not exsist

preventing duplicates infinite scrolling ajax loader

it might just be too late at night for me to see a clear solution here, but I figured I'd get some thoughts from anybody with an opinion...
the site i'm working on has a long list of user posts. i've got all the scroll event handlers working to ajax in the next batch of 100 posts when you reach or approach the bottom.
my question is... How do i prevent the following scenario?
UserX visits the site and loads posts 1-100
10 more users visit the site and add 10 more posts
UserX scrolls to bottom and loads posts 101-200, which used to to be posts 91-190
UserX ends up with duplicates of posts 91-100 on the page
i'll include a stripped down version of my code below in case it helps anybody else along
$.ajax({
type:'POST',
url:"/userposts.php",
data:{ limit: postCount },
success:function(data) {
$("postsContainer").append(data);
if ( $("postsContainer").find("div[id='lastPostReached']") ) {
// unbind infinite scrolling event handlers
}
},
dataType:'html'
});
in my PHP script I have essentially the following:
if ( ! isset($_POST["limit"]) ) {
$sql .= " LIMIT 101"; // initial request
} else {
$sql .= " LIMIT {$_POST["limit"]},101
}
$posts = mysql_query($sql);
while( $post = mysql_fetch_assoc($posts) ) {
/* output formatted posts */
}
// inform callback handler to disable infinite scrolling
if ( mysql_num_rows($posts) < 101 ) {
echo '<div id="lastPostReached"></div>';
}
This gives me infinite scrolling nice and easy, but how can I prevent the hypothetical duplicates that would show up when new records have been added to the table between ajax requests?
You define a timestamp from php that indicates the servertime at the time the page loads (eg var _loadTime = <?php echo time(); ?>) and then pass this value as part of the Ajax data config object along with limit.
Then on the server side you can exclude any posts that were created after this time and hense preserve your list.
You can also go a step further and use this time along with a basic ajax long polling technique to notify the user of new posts since the page loaded/last loading of new posts - similar to Facebook and Twitters feeds.
Update your ajax request, so that in addition to the limit parameter you pass through the current range of post ids (I'm assuming the posts have some kind of unique id). Update your php to take those parameters into account when retrieving the next set of posts.
That is, instead of saying "give me another 100" the request is "give me 100 starting at id x".
(Sorry, I don't have time now to write an example code for this.)
Just use a unique identifier ID for the posts and count backwards.
First visit user requests posts 603-503
Ten users get on the page and add comments so the highest comment is now 613
User scolls down and requests 503-403
Problem solved? :)

Understanding Twitter API's "Cursor" parameter

I don't really get how to use the Curesor parameter in Twitter's API, for an exmaple - here.
Am I supposed to make a new API call for each 100 followers?
I'd love it if someone could provide a PHP example for getting a full list of followers assuming I have more than 100...
Thanks in advance!
You need to pass the cursor value back to the API to get the next "chunk" of followers. Then you take the cursor parameter from that chunk and pass it back to get the next chunk. It is like a "get the next page" mechanism.
Since this question was asked, Twitter API has changed in many ways.
Cursor is used to paginate API responses with many results. For example, a single API call to obtain followers will retrieve a maximum of 5000 ids.
If you want to obtain all the followers of a user you will have to make a new API call, but this time you have to indicate the "next_cursor" number that was in your first response.
If it's useful, the following python code will retrieve followers from a given user.
It will retrieve a maximum of pages indicated by a constant.
Be careful not to be banned (i.e.: don't make more than 150 api calls/hour in anonymous calls)
import requests
import json
import sys
screen_name = sys.argv[1]
max_pages = 5
next_cursor = -1
followers_ids = []
for i in range(0,max_pages):
url = 'https://api.twitter.com/1/followers/ids.json?screen_name=%s&cursor=%s' % (screen_name, next_cursor)
content = requests.get(url).content
data = json.loads(content)
next_cursor = data['next_cursor']
followers_ids.extend(data['ids'])
print "%s have %s followers!" % (screen_name, str(len(followers_ids)))
Despite you asked it some time ago, I hope this will be the more accurated answer.
Twitter does not offer info about what next_cursor means. Only how cursor works.
It is only an easy way for Twitter to manage pagination.
«The function is intended to be used linearly, one cursor set at a time per user.» Source
«It's potentially less efficient for you but much more efficient
for us.» Twitter Staff
BUT...
Someone ask before in a broken link «are cursors persistents? seem that the answer is "yes"»
This means you can save your last cursor before 0 and continue with it next time.
Check out http://code.google.com/p/twitter-boot/source/browse/trunk/twitter-bot.php
foreach ($this->twitter->getFollowers(,0 ) as $follower)//the 0 is the page
{
if ($this->twitter->existsFriendship($this->user, $follower['screen_name'])) //If You Follow this user
continue; //no need to follow now;
try
{
$this->twitter->createFriendship($follower['screen_name'], true); // If you dont Follow Followit now
$this->logger->debug('Following new follower: '.$follower['screen_name']);
}
catch (Exception $e)
{
$this->logger->debug("Skipping:".$follower['screen_name']." ".$e->getMessage());
}
}
}

Categories