using Zend_Gdata_Spreadsheets for public spreadsheets? - zend-framework

I have this code which is working, to load a Google Spreadsheet and load some data from it. If the spreadsheet in question is public, how do i modify the code to not require a username/password?
$key="keytothespreadsheet";
$user="test#example.com";
$pass="*****";
$authService = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService);
$gdClient = new Zend_Gdata_Spreadsheets($httpClient);
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($key);
$feed = $gdClient->getWorksheetFeed($query);
print_r($feed);

In the following line, the HTTP client is optional:
$gdClient = new Zend_Gdata_Spreadsheets($httpClient);
So, just don't pass it. The following are equivalent:
$gdClient = new Zend_Gdata_Spreadsheets();
// or
$gdClient = new Zend_Gdata_Spreadsheets(null);
// or
$gdClient = new Zend_Gdata_Spreadsheets(new Zend_Http_Client());

Like #Matt, I wanted to access a public spreadsheet without supplying credentials. Thanks to #Derek Illchuk, I got part of the way there. It still wasn't working, however, until I learned the following:
Note that the File > Publish to the Web feature is not the same thing as Sharing Settings > Public On The Web. If you forget to enable "Publish to the Web", you'll get this error: "Expected response code 200, got 400 The spreadsheet at this URL could not be found. Make sure that you have the right URL and that the owner of the spreadsheet hasn't deleted it."
In the "Publish to the Web" settings, be sure to uncheck "Require viewers to sign in with their ___ account.". Otherwise you'll get this error: "Expected response code 200, got 403 You do not have view access to the spreadsheet. Make sure you are properly authenticated."
According to Google's documentation, "The spreadsheets feed only supports the 'private' visibility and the 'full' projection." However, I found that I needed to specify 'public' visibility and 'basic' projection. Otherwise I got this error:
"Expected response code 200, got 501 Bad or unsupported projection for this type of operation."
Here is what worked for me:
$spreadsheetService = new Zend_Gdata_Spreadsheets(null);
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($spreadsheetKey);
$query->setWorksheetId($worksheetId);
$query->setVisibility('public'); //options are 'private' or 'public'
$query->setProjection('basic'); //options are 'full' or 'basic'
$cellFeed = $spreadsheetService->getCellFeed($query);
foreach ($cellFeed as $cellEntry) {
$text = $cellEntry->content->text;
//Do something
break; //I only wanted the first cell (R1C1).
}

Related

I POST my image by python through WP REST API, but the response is just the array of items in media library

First of all, I have found out what's wrong with my python code, but I really want some one to tell me how it popped out because I'm just a noob amateur.
I tried to post my album collected on my wordpress by using my python script as usual, but I got an unexpected throw-out when it start to image upload. My img upload function just like this:
def restImgUL(imgPath,imgName,token):
url='http://www.rainloongmusic.com/wp-json/wp/v2/media/'
file_extension = os.path.splitext(imgPath)[-1]
img = open(imgPath,'rb')
imgName = imgName.replace(";","")
_json = {
"title":imgName,
'caption': imgName,
"alt_text":imgName,
"description":imgName,
"status":"publish"
}
image_name = f"{imgName}{file_extension}"
headers = { 'Content-Type': '','Content-Disposition' : 'attachment; filename=%s'%image_name.encode("utf-8").decode("latin1"),"Authorization":"Bearer %s"%token}
res = requests.post(url=url,data=img,headers=headers,json=_json)
rrr = res.json()
if "id" in rrr:
return rrr["id"]
else:
print(rrr)
sys.exit()
The wrong response is an array include items in my first page of media library. I found some clues in rest api handbooks. If I attempt to GET /wp/v2/media, response will be like what I've recieved. But I use POST type request in my python code, I don't really understand what happened there. I have no choice but to try some other methods to bypass this problem. I tried to make a new endpoint and write something like this:
add_action( 'rest_api_init', function () {
register_rest_route( 'rlra/v1', '/media', array(
'methods' => 'POST',
'callback' => 'cmupload',
) );
} );
function cmupload(){
return "This is a test!!!"
}
However, I got rest_no_route when I POST to it. I changed the methods to GET eventually, and got the right text from my server. I think maybe something changed my POST request into a GET one? I tried to figure out with Charles, and found my connection with 302 permanent redirect. So I check my request link and change http into https, everything works.
So, could anyone tell me why a 302 redirect will change my POST request into GET, I've been worn-out due to the lost letter "s" in these days.

Socialite facebook driver get only first name

I know that this question is asked before but read before marking as dublicate.
So I am trying to get user's first name using Socialite 3.0, however I am not able to get it. I am getting the following error:
Undefined index: first_name
I know it was possible before but not anymore. Is it impossible now? According to the Facebook's documentation, I should be able to get it.
I tried pretty much every possible answer I found by googling and from StackOverflow without success.
This is what I did:
$providerUser = Socialite::driver('facebook')->stateless()->userFromToken($request->fb_token);
$attributes = ['first_name' => $providerUser->user['first_name']];
return $attributes;
I also tried like this:
$driver = Socialite::driver('facebook')
->fields([
'first_name'
]);
$user = $driver->userFromToken($request->fb_token);
return $user;
which gives me the following error:
The Response content must be a string or object implementing
__toString(), "object" given.
I finally did manage to get it working. So I had to do the following:
$providerUser = Socialite::driver('facebook')
->fields([
'first_name'
])->stateless()->userFromToken($request->fb_token);
$first_name = $providerUser->user['first_name'];
return $first_name;

Error 403 - Forbidden on Loading Open Street Map to Win Form with GMap.Net and C#

Trying to load OSM on windows Form using C# and GMap.Net I am getting this error
Exception:The remote server returned an error: (403) Forbidden
private void Form1_Load(object sender, EventArgs e)
{
gMapControl1.DragButton = MouseButtons.Left;
gMapControl1.CanDragMap = true;
gMapControl1.MapProvider = GMapProviders.OpenStreetMap;
gMapControl1.Position = new GMap.NET.PointLatLng(54.6961334816182, 25.2985095977783);
gMapControl1.MinZoom = 0;
gMapControl1.MaxZoom = 24;
gMapControl1.Zoom = 9;
gMapControl1.AutoScroll = true;
}
Can you please let me know why this is happening and how I can fix it?
don't forget to set the instance mode to server/cache and set it to the instance of the open street map provider instead of 'GMapProviders.OpenStreetMap'
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerAndCache;
gMapControl1.MapProvider = GMap.NET.MapProviders.OpenStreetMapProvider.Instance;
It could also be your web proxy settings, see
https://stackoverflow.com/a/19609539/2368681
"Hi,
All libraries that send a fake user-agent and other faked headers to make the requests appear as if they are coming from web browsers are being blocked. Fix the headers and set a real User-Agent to identify your app and the requests will work again.
Please review our usage policy:
https://operations.osmfoundation.org/policies/tiles/ "
This is verbatim reply from OSM.
https://github.com/judero01col/GMap.NET/pull/45 is being used to track this issue. And hopefully a fix will be merged in a a day or two.
I changed Map Provider from "OpenStreetMapProvider" to "GoogleMapProvider" and the error disappeared.
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerAndCache;
mapView.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance;

In a REST API, to GET a resource, should I include the resource ID in the url?

I am trying to create an REST API for creating and retrieving files in my database. The tutorial I was following uses the following method to retrive a single file:
$app->get('/file/:file_id', 'authenticate', function($file_id) {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch file
$result = $db->getFile($file_id, $user_id);
if ($result != NULL) {
$response["error"] = false;
$response["id"] = $result["id"];
$response["file"] = $result["fileLocation"];
$response["status"] = $result["status"];
$response["createdAt"] = $result["created_at"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exist";
echoRespnse(404, $response);
}
});
Here they are using the HTTP GET method and are specifying the file ID in the URL, is it OK to do this, safety wise? Would it not be safer to use POST and hide the file ID in the body of the request, or should they not be putting the file ID in a header with the GET request? or is it not something I should be worried about?
In REST post method is used to create a new resource not to get it. Get method is used for fetching the resource and you need to specify the ID to determine particular resource. Passing it via URL is a common practice. You can randomly generate such ID to make it harder to guess.
As Opal said above, the ID is used to identify a resource. If you are unsure have a read of this - http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post

Facebook Graph API - Get ID from Facebook Page URL

I have seen this question but what I want is different.
I want to get the Facebook ID not from a general URL (and therefore conditional if it has Like button or not). I want to get the Facebook ID given a Facebook page using the Graph API.
Notice that Facebook pages can have several formats, such as:
http://www.facebook.com/my_page_name
http://www.facebook.com/pages/my_page_name
http://www.facebook.com/my_page_ID
I know I could do some regex to get either the my_page name or my_page_ID, but I am wondering if any one know if GraphAPI is supporting what I want.
It seems to me that the easiest solution to what you describe is to just get the id/name from the url you have using lastIndexOf("/") (which most languages have an equivalent for) and then get "https://graph.facebook.com/" + id.
The data that this url returns has the id (i.e.: 6708787004) and the username (i.e.: southpark), so regardless of which identifier you use (what you extract from the url using lastIndexOf), you should get the same result.
Edit
This code:
identifier = url.substring(url.lastIndexOf("/"))
graphUrl = "https://graph.facebook.com/" + identifier
urlJsonData = getGraphData(graphUrl)
Should work the same (that is result with the same data) for both:
url = http://www.facebook.com/southpark
And
url = http://www.facebook.com/6708787004
(you'll obviously need to implement the getGraphData method).
Also, the 2nd url form in the question is not a valid url for pages, at least not from my tests, I get:
You may have clicked an expired link or mistyped the address. Some web
addresses are case sensitive.
The answer to the question is posted above but the method shown below works fine we do not have to perform the regex on the facebook page urls
I got the answer by this method
FB.api('/any_fb_page_url', function(response){
console.log(response);
});
any_fb_page_url can be any of the following types
https://www.facebook.com/my_page_name
https://www.facebook.com/pages/my_page_name
https://www.facebook.com/my_page_ID
This are also listed in question above
This code is tested on JS console available on Facebook Developers site tools
You can get the page id by using the below api
https://graph.facebook.com/v2.7/smhackapp?fields=id,name,fan_count,picture,is_verified&access_token=access_token&format=json
Reference image
This answer is updated and checked in 2019:
and it is very simple because you do not need to extract anything from the link. for examples:
https://www.facebook.com/pg/Vaireo-Shop-2138395226250622/about/
https://www.facebook.com/withminta
https://www.facebook.com/2138395226250622
https://graph.facebook.com/?id=link&access_token=xxxxxxxx
response:
{
"name": "Vaireo Shop",
"id": "2138395226250622"
}
full nodeJS answer:
async function getBusinessFromFBByPageURL(pageURL: string) {
const accessToken = process.env.fb_app_access_token;
const graphUrl = `https://graph.facebook.com/?id=${pageURL}? access_token=${accessToken}`;
const fbGraphResponse = await Axios.get(graphUrl);
<?php
function getFacebookId($url) {
$id = substr(strrchr($url,'/'),1);
$json = file_get_contents('http://graph.facebook.com/'.$id);
$json = json_decode($json);
return $json->id;
}
echo getFacebookId($_GET['url']);
?>
Thats a PHP example of how to get the ID.
As of Nov 26 2021 none of these solutions work.
Facebook has locked down the API so you need an App Review.
https://developers.facebook.com/docs/pages/overview/permissions-features#features
This answer takes into account that a URL can end with a trailing slash, something that Facebook event pages seem to have in their URLs now.
function getId(url) {
var path = new URL(url).pathname;
var parts = path.split('/');
parts = parts.filter(function(part) {
return part.length !== 0;
});
return parts[parts.length - 1];
}
You can Use Requests and re Modules in python
Code:
import requests,re
profile_url = "https://www.facebook.com/alanwalker97"
idre = re.complie('"entity_id":"([0-9]+)"')
con = requests.get(profile_url).content
id = idre.findall(con)
print("\n[*] ID: "+id[0])
Output:
[*] ID: 100001013078780
Perhaps you can look through the https://developers.facebook.com/docs/reference/api/#searching docs: search against a couple of types and if you find what you're looking for go from there.