Get content from facebook by hashtag - facebook-php-sdk

Why is there information about facebook hashtags if it's not supported by the graph API? https://developers.facebook.com/docs/graph-api/reference/hashtag Is there a way to get images and content by hashtag?
I.e #summerhangout:
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/%23summerhangout'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
Result:
Fatal error: Uncaught exception 'Facebook\FacebookAuthorizationException' with message '(#803) Some of the aliases you requested do not exist: #summerhangout' in /Library/WebServer/Documents/projname/vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequestException.php:134
Stack trace:
#0 /Library/WebServer/Documents/projname/vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequest.php(280): Facebook\FacebookRequestException::create('{"error":{"mess...', Object(stdClass), 404)
#1 /Library/WebServer/Documents/projname/helper/facebook.php(127): Facebook\FacebookRequest->execute()
#2 {main}
thrown in /Library/WebServer/Documents/projname/vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequestException.php on line 134

Why is there information about facebook hashtags if it's not supported by the graph API?
It is stated in the first line
Information about hashtags. Used in Facebook's Trending APIs
Trending API is a whitelisted feature only available to a select few companies.
Is there a way to get images and content by hashtag?
Yes using the Trending API.
$request = new FacebookRequest(
$session,
'GET',
'/%23summerhangout'
);
This should be using the hashtag-id which was stated in the documentation.
So the hashtag id for #summerhangout is 147811522058338
$request = new FacebookRequest(
$session,
'GET',
'/147811522058338'
);
I am not even sure why you are calling this edge when the documentation tells you that the only fields you will get here is the name and the id (which you already know)
{
"id": "147811522058338",
"name": "#Summerhangout"
}

Related

WordPress endpoint plugin shows SyntaxError: JSON.parse

i have read many pages to find out howto create a simple endpoint into my simple WP-Plugin.
links of good articles i have read for that:
https://developers.shopware.com/developers-guide/rest-api/plugin-api-extension/ , https://wptips.dev/custom-rest-api/ , https://torquemag.io/2016/07/adding-custom-endpoints-extra-touches/ , https://www.cloudways.com/blog/wordpress-rest-api-to-fetch-posts/#get-wp-v2-posts , https://www.cloudways.com/blog/wordpress-rest-api-to-fetch-posts/#wordpress-rest-api-using-json , https://developer.wordpress.org/rest-api/
this gives me most hope to get success with it and i used the source from here:
https://stackoverflow.com/a/64331655/2891692
My URL i using in Web-Browser:
http://localhost/wordpress/wp-json/a0plugin/v1/testing
excerpt of my complete source from gist
htdocs/wp-content/plugins/a0plugin/a0plugin.php
<?php
/**
* Plugin Name: a0plugin
*/
function at_rest_testing_endpoint(){
return new WP_REST_Response('Howdy!!');
}
function at_rest_init(){
$namespace = 'a0plugin/v1';
$route = 'testing';
register_rest_route($namespace, $route, array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'at_rest_testing_endpoint'
));
}
add_action('rest_api_init', 'at_rest_init');
?>
complete source:
https://gist.github.com/sl5net/10d21e8bd358b9149968885a93862424
SyntaxError: JSON.parse
Error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
if the comments are left out, the error disappears. these are not listed in the so-called relevant source text excerpt. the cause is unknown to me.

Get current user inside register_rest_route method

How to retrive wp_get_current_user() inside a register_rest_route callback (Wordpress site)?
I'm just trying to do a simple hello wp_get_current_user()->user_login on a php test page:
add_action('rest_api_init', 'helloTest');
function helloTest() {
register_rest_route('hello', 'hello/(?P<id>\d+)', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'showHello'
));
}
function showHello($someVariable) {
echo "Hello " . wp_get_current_user()->user_login . $someVariable;
}
But wp_get_current_user() is null and wp_get_current_user->ID is 0;
I dont want to authenticate the user again. I just want to retrieve his username. If he is not logged in, just show empty an empty string.
If I have to authenticate again, how to add a "nonce" to it? On internet I just have examples using javascript, but not directly on PHP methods.
Issues in your code
First off, you should understand properly how to add custom WP REST API endpoints:
An endpoint's namespace (the first parameter passed to register_rest_route()) should be in this format: your-plugin/v<version>. E.g. hello/v1 or hello-world/v1 and not just hello or hello-world.
$someVariable (the first parameter passed to your endpoint callback function) is not just any variable — it's an instance of the WP_REST_Request class — and shouldn't be echo-ed like what you did here:
function showHello($someVariable) {
echo "Hello " . wp_get_current_user()->user_login . $someVariable;
}
And normally, the $someVariable is better be changed to $request (i.e. rename it to "request").
And you should return a valid WP REST API response. For example, to return just the username:
return new WP_REST_Response( wp_get_current_user()->user_login, 200 );
And know your own API endpoint URL..
(based on your original namespace)
/wp-json/hello/hello/1 <- correct
/wp-json/hello/?John <- incorrect
because in your code, the parameter is a number and not string: (?P<id>\d+)
I hope those help you, and once again, do read the handbook for a more detailed guide.
The Corrected Code
add_action( 'rest_api_init', 'helloTest' );
function helloTest() {
register_rest_route( 'hello/v1', 'hello/(?P<id>\d+)', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'showHello'
) );
}
function showHello( $request ) {
return new WP_REST_Response( wp_get_current_user()->user_login, 200 );
}
Now about getting the user (from the API endpoint — showHello())
If I have to authenticate again, how to add a "nonce" to it?
Just because the user is logged-in/authenticated to the (WordPress) site, it doesn't mean the user is automatically logged-in to the WP REST API. So yes, you'd need to either provide a nonce along with your API request, or use one of the authentication plugins mentioned right here.
Now in most cases, GET (i.e. read-only) requests to the API do not need any authentication, but if you'd like to retrieve the data of the currently logged-in user on your site, then one way is via the _wpnonce data parameter (either POST data or in the query for GET requests).
Example for a GET request:
http://example.com/wp-json/wp/v2/posts?_wpnonce=<nonce>
So based on your comment and the corrected code (above):
Theres no "code" that make the request. Its is just an anchor that
calls my route: Hello
You can add the nonce as part of the URL query string like so: (the namespace is hello/v1 and the <id> is 1)
// Make request to /wp-json/hello/v1/hello/<id>
$nonce = wp_create_nonce( 'wp_rest' );
echo 'Hello';
So try that out along with the corrected code and let me know how it goes. :)
And once again, be sure to read the REST API authentication handbook.

Filtering results from Google Analytics Reporting API

I am successfully downloading results from Google Analytics using the reporting API (version 4), with the PHP client library. But I have not figured out how to correctly filter these results.
I see how this would work via cURL, but not through the client library. I looked through the client library code, and there is a class method:
apiclient-services/Google/Service/AnalyticsReporting/ReportRequest.php:
public function setMetricFilterClauses($metricFilterClauses)
I do not see any documentation or any usage of the associated get method:
public function getMetricFilterClauses()
Are there examples of using filters through the PHP client library?
Background
The Google API Client libraries are generated from the Google Discovery Service. And the PHP client library generates a setProperty and getProperty for every property of a resource.
Analytics Reporting API V4
The Analytics Reporting API V4 reference docs exhustively describe the API. The Developer Guide gives the underlying JSON example which the client libraries will generate:
POST https://analyticsreporting.googleapis.com/v4/reports:batchGet
{
"reportRequests":
[
{
"viewId": "XXXX",
"dateRanges": [
{"endDate": "2014-11-30", "startDate": "2014-11-01"}
],
"metrics": [
{"expression": "ga:pageviews"},
{"expression": "ga:sessions"}
],
"dimensions": [{"name": "ga:browser"}, {"name": "ga:country"}],
"dimensionFilterClauses": [
{
"filters": [
{
"dimensionName": "ga:browser",
"operator": "EXACT",
"expressions": ["Chrome"]
}
]
}
]
}
]
}
And the Samples page gives many examples requests in Python, Java, PHP and JavaScript, which should give you a good sense of how to work with the individual client libraries. But you are correct there is not an explicit example of PHP using a filter.
PHP Filter Example
Below is the same example as the request above:
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2014-11-01");
$dateRange->setEndDate("2014-11-30");
// Create the Metrics object.
$pageviews = new Google_Service_AnalyticsReporting_Metric();
$pageviews->setExpression("ga:pageviews");
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
//Create the Dimensions object.
$browser = new Google_Service_AnalyticsReporting_Dimension();
$browser->setName("ga:browser");
$country = new Google_Service_AnalyticsReporting_Dimension();
$country->setName("ga:country");
// Create the DimensionFilter.
$dimensionFilter = new Google_Service_AnalyticsReporting_DimensionFilter();
$dimensionFilter->setDimensionName('ga:browser');
$dimensionFilter->setOperator('EXACT');
$dimensionFilter->setExpressions(array('Chrome'));
// Create the DimensionFilterClauses
$dimensionFilterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause();
$dimensionFilterClause->setFilters(array($dimensionFilter));
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("XXXX");
$request->setDateRanges($dateRange);
$request->setDimensions(array($browser, $country));
$request->setDimensionFilterClauses(array($dimensionFilterClause));
$request->setMetrics(array($pageviews, $sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analyticsreporting->reports->batchGet( $body );
As you probably noticed I never once used a $object->getProperty(). Basically All it would do is give me its current value. When Calling the API you should only ever need to $object->setProperty($value); Hence why I gave you the background that the client libraries are generated.
Conclusion
The Analytics Reporting API itself is complex and there are many client library languages. It is not always possible to give an example every possible usage of an API in every possible client library language. That is why it is necessary to understand how to look at the reference docs and understand how the client libraries are generated from the structure described.
There is an issue with DimensionFilter() class in a script above, i get error that it is not defined, but i have changed it to Google_Service_AnalyticsReporting_DimensionFilter() class and now it is working hope that will help to someone.

Symfony profiler url to last request

Is there any url like
http://mysymfony.app/_profiler/LAST_ID?panel=db ???
Have no Symfony Profile Footer when profile a json API and it cost time to go back to the overview everytime.
There should be a response header called: "X-Debug-Token-Link" which is a direct link to the latest profiler. You can inspect that in google chrome devtools after each request.
There is no way to do this that I'm aware of. I checked the bundle and there's no route that seems to cover this.
It seems plausible to me, however, that you could write you own route and action for it. Start here and then I think the basic logic of your action would look like this
$token = array_pop($this->profiler->find(null, null, 1, null, null, null));
return new RedirectResponse(
$this->generator->generate(
'_profiler',
array('token' => $token, 'panel' => 'db')
),
302,
array('Content-Type' => 'text/html')
);

How to integrate Dropzonejs with wordpress media handler in frontend?

How can I integrate Dropzonejs file uploader library in wordpress front end just like the built in one and have the uploaded one available in my media library?
Dropzonejs is a very extensive javascript library that provides a lot of options to handle media uploading.
To integrate dropzonejs with wordpress the process is pretty straight forward. Assume the following piece of code is where you want to appear your uploader.
<div id="media-uploader" class="dropzone"></div>
<input type="hidden" name="media-ids" value="">
Having a class dropzone will automatically attach the dropzone event with the element. That will stop us from overriding default parameters. So we would like to disable the auto discover feature of the library.
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
Now we will use jQuery to bind our configuration with the element.
jQuery("#media-uploader").dropzone({
url: dropParam.upload,
acceptedFiles: 'image/*',
success: function (file, response) {
file.previewElement.classList.add("dz-success");
file['attachment_id'] = response; // push the id for future reference
var ids = jQuery('#media-ids').val() + ',' + response;
jQuery('#media-ids').val(ids);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
// update the following section is for removing image from library
addRemoveLinks: true,
removedfile: function(file) {
var attachment_id = file.attachment_id;
jQuery.ajax({
type: 'POST',
url: dropParam.delete,
data: {
media_id : attachment_id
}
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
});
In the code above what we have done is we attached dropzone with our element with some parameters-
url - location where we want to send our files to upload. I'll initialize the variable later.
acceptedFiles - since we are only interested in uploading images, we will limit the files to be attached only to images. You can find about more in the website of this library.
success - a callback that is fired when the file/image is uploaded successfully. It accepts two parameter the reference of the uploaded file itself and the response from the server. This is very important, here we stored the attachment id in our form. You can perform a validation here prior to store the id.
error - if the file failed to upload then you can perform any task here.
addRemoveLinks - add the remove file link below the preview panel, you can style it with your css.
removedfile - handles the operation while you click on the remove file link for an image in the preview panel. In this function we sent an ajax call to our server to remove the image from the library
Of course there are a lot of option available, but I found these are the most basic parameters I required to setup my drag-n-drop media uploader.
Now the most important thing is to decide about the file uploader url. You can have a custom file where you would want to process the operation. But I found another way.
From this question and the answer I found using admin-post.php file is pretty amazing.
Many people complained about this admin-post.php, so think sticking to the wp_ajax.php is the best option.
So I initialized the drophandler variable prior to my dropzone initialization as follows-
wp_enqueue_script('dropzone','path/to/dropzone', array('jquery'));
wp_enqueue_script('my-script','path/to/script',array('jquery','dropzone'));
$drop_param = array(
'upload'=>admin_url( 'admin-ajax.php?action=handle_dropped_media' ),
'delete'=>admin_url( 'admin-ajax.php?action=handle_deleted_media' ),
)
wp_localize_script('my-script','dropParam', $drop_param);
Now we are ready to send our images to the server. Here we will add some php code whether in the theme's function.php file or in our plugin file, but we need to be assured that it is loaded.
The following function will take care of the uploading the image and saving as an attachment in the library.
add_action( 'wp_ajax_handle_dropped_media', 'handle_dropped_media' );
// if you want to allow your visitors of your website to upload files, be cautious.
add_action( 'wp_ajax_nopriv_handle_dropped_media', 'handle_dropped_media' );
function handle_dropped_media() {
status_header(200);
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['path'] . DIRECTORY_SEPARATOR;
$num_files = count($_FILES['file']['tmp_name']);
$newupload = 0;
if ( !empty($_FILES) ) {
$files = $_FILES;
foreach($files as $file) {
$newfile = array (
'name' => $file['name'],
'type' => $file['type'],
'tmp_name' => $file['tmp_name'],
'error' => $file['error'],
'size' => $file['size']
);
$_FILES = array('upload'=>$newfile);
foreach($_FILES as $file => $array) {
$newupload = media_handle_upload( $file, 0 );
}
}
}
echo $newupload;
die();
}
The following action take care of the deletion of the media element. Second parameter of wp_delete_attachment() function allows us to decide whether we want to trash the image or completely delete it. I wanted to delete it completely so passed true.
add_action( 'wp_ajax_handle_deleted_media', 'handle_deleted_media' );
function handle_deleted_media(){
if( isset($_REQUEST['media_id']) ){
$post_id = absint( $_REQUEST['media_id'] );
$status = wp_delete_attachment($post_id, true);
if( $status )
echo json_encode(array('status' => 'OK'));
else
echo json_encode(array('status' => 'FAILED'));
}
die();
}
This will return the attachment_id in the response and we'll get it in the success function. In the media_handle_upload( $file, 0 ); I passed the reference of the file and a 0 because I didn't wanted to assign the media with any post yet (0 for no post, but if you want to assign then pass the post ID here. More reference in the codex.)
This is all for uploading media in wordpress.
Note: I haven't completed the removing uploaded file part. I'll complete this in a moment.
UPDATE
The post is updated. Now we can remove uploaded media elements from the uploader container. Thanks to this question and the answer I could figure out the actual process.
Those who are having problems getting this to work for non-admin users; please use admin-ajax.php instead of admin-post.php.
I had faced a strange issue that admin-post.php would work for non-admin users on my local server; but my live server refused to let non-admins upload files. php would echo entire page instead of the echoed value.
I replaced admin-post.php with admin-ajax.php and uploads work super cool.
I hope this helps.
The solution added to this post is incorrect unless I've misunderstood the question. Basically the solution won't work for anyone who isn't logged in as an admin. It took me 30 minutes to work it out plus the solution for removing images doesn't delete it from the media library.

Resources