Getting Like and Comment - php

I'm using facebook PHP SDK , facebook api version 2.2.
I want to display the user news feed. I'm using the following api get this.
$facebookConncetion->api("$oauthUserId/home",
'GET',
array("access_token" => $accessToken,
"limit" => '15',
"comments.limit" => 10,
"likes.limit" => 10
)
);
But it returns all the post in the user home page with 10 comment and 10 likes and it does not return summary of like and comment. How can I format this api to get the like and comment summary per post?

You have to add .summary(true) and .filter(stream) to the like and comment request just like you added the limit.
Summary will return something like this:
"comments" : {
"data" : [ ARRAY OF COMMENTS ] },
"paging" : { PAGING CURSORS/URLS }.
"summary" : {
"total_count" : NUMBER OF COMMENTS
}
},
Adding .filter(stream) will return ALL comments/likes. With out this there may be some missing due to Facebook filtering them out due to their low "story" value. It will also order all comments/likes in true chronological order.
https://developers.facebook.com/docs/graph-api/reference/v2.2/object/comments
Look under "Modifiers" works with both comments and likes.

Related

WP Rest API Custom endpoint - JSON returns NULL

I am trying to slim down the JSON returned when using the Rest API. I am able to get it to work using the "_embed" parameter in the query, but it returns a HUGE amount of data I don't need. So, per WP best practices I want to set up a custom end point and in it's callback call a function to output the three items I need. Seems simple, however it returns NULL for all nodes when I try. In my functions.php file I have:
function get_all_posts( WP_REST_Request $request ) {
return [
'id' => $data->data['id'],
'title' => $data->data['title']['rendered'],
'link' => $data->data['link'],
'date' => $data->data['date'], //not correct
//similar calls to get thumbnail image and category
];
}
Then the route and call back for the custom endpoint
add_action( 'rest_api_init', function () {
register_rest_route( 'mydata/v1', '/all', array(
'methods' => 'GET',
'callback' => 'get_all_posts',
) );
} );
when I use the url - https://somedomain.com/blog/wp-json/mydata/v1/all I get the following on page:
{
"id": null,
"title": null,
"link": null
}
You can pass field arguments to the API
Like so:
[url]/wp-json/wp/v2/tags?fields=id,name
Note this is example is /tags, you can use /categories etc, and still specify the fields.
I recommend installing the JSONView chrome plugin so that the dump of your JSON is readable when you test the endpoint .

YouTube API v3 get last video in playlist

Some basic background: I help run a gaming channel on YouTube, and I'm building a utility (using PHP) to integrate the channel's content with a companion website. Our playlists are primarily "let's play" series ordered by publication date that follow chronological progress through various games, and I would like the website to display the "latest episode" from a select number of series.
I know that I can work my way to the last video by chaining calls to the following:
$youtubeService->playlistItems->listPlaylistItems(
"snippet",
array(
"playlistId" => $playlistId
"pageToken" => $nextPageToken
)
)
And simply grab the last item in the response set when $nextPageToken is unset.
However, this strikes me as incredibly inefficient--partly because I believe it eats away at my API request quota, but mostly because it's going to slow down the overall response time of the site. Neither of those are ideal.
It seems like there should be an easier way to grab the "latest" video in a playlist either by changing the order of the response, or with some handy function, but I can't find any documentation on it.
I've looked at using the Search functions over the PlaylistItems, but (according to the documentation), Search only accepts Channel IDs as a parameter and not Playlist IDs, which makes me think that its the wrong direction to head.
The short answer here is that this appears to be impossible under the current version of the API. There is no apparent way to essentially select videos in reverse, but I did make a minor change which resulted in whole process being a tad more efficient.
This is the original code:
$items = $youtube->playlistItems->listPlaylistItems(
"snippet",
array(
"playlistId" => $playlistId,
"maxResults" => 50
)
);
while ($items->nextPageToken) {
$items = $youtube->playlistItems->listPlaylistItems(
"snippet",
array(
"playlistId" => $playlistId,
"maxResults" => 50,
"pageToken" => $items->nextPageToken
)
);
}
if ($items) {
return end($items->getItems());
}
This is the fix:
First, I added an object to assist with caching:
class PlaylistCache {
protected $expirationDate;
protected $playlistId;
protected $latestEpisode;
__construct($playlistId, $latestEpisode) {
$this-playlistId = $playlistId;
$this->latestEpisode = $latestEpisode;
$this->expirationDate = time() + 86400;
// get current time + 24 hours
}
public function getLatestEpisode() {
return $this->latestEpisode;
}
public function getPlaylistId() {
return $this->playlistId;
}
public function isExpired() {
return $this->expirationDate < time();
}
}
Then, before polling the API, I look to see if I have a cached version available, and I only resort to the API if that cached version is expired.
$playlistCache = json_decode(get_option('playlist_cache_' . $playlistId));
if ($playlistCache->isExpired()) {
$items = $youtube->playlistItems->listPlaylistItems(
"id",
array(
"playlistId" => $playlistId,
"maxResults" => 50
)
);
while ($items->nextPageToken) {
$items = $youtube->playlistItems->listPlaylistItems(
"id",
array(
"playlistId" => $playlistId,
"maxResults" => 50,
"pageToken" => $items->nextPageToken
)
);
}
if ($items) {
$videoId = end($items->getItems()[0]->getId());
$video = $youtube->videos->listVideos("snippet", array('id' => $videoId))
$video = $video->getItems()[0];
$playlistCache = new PlaylistCache($playlistId, $video);
update_option('playlist_cache_' . $playlistId, json_encode($playlistCache)));
}
}
return $playlistCache->getLatestEpisode();
The other big change here is that my calls to listPlaylistItems() are requesting the id instead of the snippet.
According to the documentation, the snippet costs 2 units of the API quota while requests for the id are 0. So, I don't need to snag the snippet for every single item on every single page. I only need to grab the snippet of the final video in the results, which I can do with the more refined call to
$youtube->videos->listVideos()
With the addition of the PlaylistCache class I only reach out to the API when the cached version of the Playlist returns true on the $playlistCache->isExpired() call, so I only need to poll the entire playlist one time every 24 hours instead of 1 time every page load for every user.
It's still not exactly ideal, but as far as I can tell, it's the best option available right now.
Firstly, you need to get the channelId for the user via HTTP request:
Sample request:
https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername={0}&key={1}
where {0} is the USERNAME and key is you API key
Then, get the list of videos by calling 'PlaylistItems:list', it returns a collection of playlist items that match the API request parameters. You can retrieve all of the playlist items in a specified playlist or retrieve one or more playlist items by their unique IDs.
Sample request:
https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId={0}&key={1}
From there, you can create an array to get the last video in the playlist. Include max-results parameter, the max-results specifies the maximum number of results that included in the result set.
Typically, the latest video in a playlist in added to the front, not the end.

Displaying Output from Basic API (PHP)

So I am using an API (SendInBlue - a transactional email service) and I am trying to use the API to display a list of the users on my webpage.
Below, SendInBlue has given me sample code to use, however when I put them together I just get a blank screen.
I know this is a total beginner question... but how do I put these 2 pieces of code together so that it actually displays the list of contacts on my website?
Thank you so much!!
EXAMPLE
require('../mailin.php');
$mailin = new Mailin("https://api.sendinblue.com/v2.0","your access key");
$data = array( "listids" => array(1,2),
"timestamp" =>"2015-05-22 14:30:00",
"page" => 1,
"page_limit" => 2
);
var_dump($mailin->display_list_users($data));
SAMPLE OUTPUT
{
"code":"success",
"message":"Retrieved details of all users for the given lists",
"data":{
"data":[
{
"blacklisted":0,
"email":"email1#domain.com",
"id":1,
"listid":[1],
"blacklisted_sms":1,
"last_modified" : "2015-05-22 15:30:00"
},
{
"blacklisted":1,
"email":"email2#domain.com",
"id":2,
"listid":[1,2],
"blacklisted_sms":0 ,
"last_modified" : "2015-05-25 19:10:30"
}
],
"page":1,
"page_limit":2,
"total_list_records":100
}
}
Ok I figured this out. I turned every attribute into a variable like so...
$subscriberemail = $getemails['data']['data'][$number]['email'];
This took ages to figure out!

Facebook real time page update php

this is my first question to stackoverflow, so if's something wrong please advise..
Well the problem is Facebook real time updates :
I have successfully created subscription to page and it's admin user ( test page and test app created ), user has agreed permissions to manage_page, read_stream, read_friendlist, read_insights,publish_actions and a lot of user's data ( about,email etc etc )
When i query GET to Graph api with edge /subscriptions i get the result :
{
"data": [
{
"object": "user",
"callback_url": "LIVE_CALLBACK_URL",
"fields": [
"feed"
],
"active": true
},
{
"object": "page",
"callback_url": "LIVE_CALLBACK_URL",
"fields": [
"built",
"description",
"email",
"feed",
"location",
"name",
"personal_info",
"written_by"
],
"active": true
}
]
}
So, that's taken care of, after that i searched why Facebook isn't sending me any updates ( which I log to somefile.txt ) So i found out you need to query the Graph api with /tabs to create page tab for my api. When i query that it returned "success" so that's created ( can't find out where it's stored, but it working ... ).
After that i have created some data on my profile, to test and also on the page to see if the Facebook is sending any updates, and it's suddenly send one update that was comment on my user profile post ( shared on timeline ).
The response was :
14:17 05.02.2015
Array
(
[object] => user
[entry] => Array
(
[0] => Array
(
[uid] => ****my_fb_id****
[id] => ****my_fb_id - not_someone_else****
[time] => 1423146339
[changed_fields] => Array
(
[0] => feed
)
)
)
)
So Facebook send's the empty feed, and it's ok, probably some permissions or something else, but after that i have made more posts and ppl commented on it ( on user profile and test page ) but Facebook didn't send any updates, or any call to my web page.
So has anyone facing this problem in the past, and how he solved that ?
The part that is for receiving the update from Facebook is :
$method = $_SERVER['REQUEST_METHOD'];
if(isset($_GET['hub_mode']) && isset($_GET['hub_verify_token'])){
if (trim($method) == 'GET' && trim($_GET['hub_mode']) == 'subscribe' && trim($_GET['hub_verify_token']) == VERIFY_TOKEN) {
print $_GET['hub_challenge'];
}
}
else if ($method == 'POST') {
$updates = json_decode(file_get_contents("php://input"), true);
$file = 'log.txt';
$current = file_get_contents($file);
#$results = print_r($updates,true);
$current .= $results;
file_put_contents($file, $current);
}
I have tried to detail my problem as much i as could... Searched but don't really understand why it's not working.
Apart from using an outdated method as #CBroe outlined, I think you have a misunderstanding: Facebook will not send you the data that has changed, but the object (and it's fields/edges) the change occurred for User object changes.
For Pages, you can receive the changes itself (changed_fields vs. changes fields in the FB request).
See
https://developers.facebook.com/docs/graph-api/real-time-updates/v2.2#receiveupdates
Once a subscription is successfully created, Facebook will make an HTTP POST request to your callback URL every time that there are changes (to the chosen fields or edges).
That means you need to contruct a separate request from the info object you get from Facebook. In your example it would be a request to your user's feed
GET /{user_id}/feed
to query for recent changes.

how to query two collections in once with mongodb

I have two collections like this:
var Users = [
{
'ID' : 1,
'NAME' : 'Seth'
},
{
'ID' : 2,
'NAME' : 'John'
}
];
var Posts = [
{
'ID' : 1,
'TEXT' : 'blalalalalala...',
'USER' : 1
},
{
'ID' : 3,
'TEXT' : 'blalalalalala....',
'USER' : 2
}
];
How can I get the posts created by Seth without his ID? (Query By NAME : Seth)
If this is your schema, then there is no way of getting the posts for a given user by name in one query. In your application, you would have to perform two queries. The first to get the ID given a NAME and the second to get the posts given that USER. This is referred to in the MongoDB documentation as "manual referencing" and it would work something like this:
var id = db.Users.findOne({ "NAME" : "Seth" });
var posts = db.Posts.find({ "USER" : id });
If you indeed want to do this with one query, then you will have to look into embedding posts in an array inside the user documents, using DBRefs (which you need to be careful with), or in the case of some ODMs like Mongoose, using "population".
UPDATE:
Given the new information presented by the OP, in the case where you want to find all posts for users that have not been deleted, and if you don't want to iterate through a large array every time, I would suggest adding a USER_DELETED field that can be set to true when a user is deleted.
So in the event that a user with { "ID" : id } is deleted, you would run a query as follows:
db.Posts.update({ "USER" : id }, { "$set" : { "USER_DELETED" : true } });
That would then mark all of the posts for that user as belonging to a user that has been deleted. So when you want to retrieve the posts for all users that are still around, you would run:
db.Posts.find({ "USER_DELETED" : { "$ne" : true } });
Or you could do something along those lines. If you know that all the documents have a USER_DELETED field set to false if the user is still around, then you can just query for those that have the flag set to false.
Of course you will still have to transform the old data to follow this pattern, but that can be achieved with a one time operation that consists of:
Finding all of the users that have been deleted.
Finding the posts for each of those users.
Adding the USER_DELETED flag for each of those posts.
That should be a better way of approaching the problem you are facing.

Categories