I'm trying to do a very basic setup of LinkedIn - accessing public profile data about people.
I've tried several ways of accessing with oAuth over several hours. I'm not getting anywhere.
All the existing class structures et'al seem to help with accessing a user's account to post, or add friends, find a fish etc. I don't need any of that. I just want to get basic profile data.
Some code of latest attempts; but I don't get it past here:-
$consumer = new OAuthConsumer($apiKey, $apiSecret);
$signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$req_req = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $linkedInURL . "/uas/oauth/requestToken");
$req_req->sign_request($signature_method, $consumer, NULL);
$signed_url = $req_req->to_url();
That should gives me a signed request of:-
https://api.linkedin.com/uas/oauth/requestToken?oauth_consumer_key=xxx&oauth_nonce=xx&oauth_signature=xxxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1316530337&oauth_version=1.0
Obviously, that's not what I need to get data. But, just out of interest I checked the URL with the API data request, as such:-
http://api.linkedin.com/v1/people/url=http%3A%2F%2Fwww.linkedin.com%2Fin%2Fchrisvoss:public?oauth_consumer_key=xxx&oauth_nonce=xxx&oauth_signature=xxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1316529463&oauth_version=1.0
And got :-
<error>
<status>401</status>
<timestamp>1316531835564</timestamp>
<request-id>L8A1M85MWN</request-id>
<error-code>0</error-code>
<message>
[unauthorized].OAU:tm6i3ke827xz|*01|*01|*01:1316529463:MSFHS3f4iaG9pg2gWYlf22W4NPo=
</message>
</error>
I'm just a bit clueless here. I know everyone says it's tears to implement oAuth and Linkedin. But, I don't need half of what most need, so how do I get to the basic data is only my question.
Thanks in advance for any help.
Try To Use the following code
session_start();
require_once("OAuth.php");
$domain = "https://api.linkedin.com/uas/oauth";
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer("DEHYU99peS88wDDAFOcSm3Af5VO1tdrdgq1xPu_fpSSjsqPcoeABUs_NCyY33WIH", "gZrZr2-7s80CEsGpAHqFgREMbRWkR3L8__tkje3j-oKtIDlmn5KCR6bXD8i0HFp1", NULL);
$callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?action=getaccesstoken";
# First time through, get a request token from LinkedIn.
if (!isset($_GET['action'])) {
$req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "POST", $domain . "/requestToken");
$req_req->set_parameter("oauth_callback", $callback); # part of OAuth 1.0a - callback now in requestToken
$req_req->sign_request($sig_method, $test_consumer, NULL);
$ch = curl_init();
// make sure we submit this as a post
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); //New Line
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$req_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $domain . "/requestToken");
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
curl_close($ch);
//print_r($req_req); //<---- add this line
//print("$output\n"); //<---- add this line
parse_str($output, $oauth);
# pop these in the session for now - there's probably a more secure way of doing this! We'll need them when the callback is called.
$_SESSION['oauth_token'] = $oauth['oauth_token'];
$_SESSION['oauth_token_secret'] = $oauth['oauth_token_secret'];
# Redirect the user to the authentication/authorisation page. This will authorise the token in LinkedIn
Header('Location: ' . $domain . '/authorize?oauth_token=' . $oauth['oauth_token']);
#print 'Location: ' . $domain . '/authorize?oauth_token=' . $oauth['oauth_token']; // <---- add this line
} else {
# this is called when the callback is invoked. At this stage, the user has authorised the token.
# Now use this token to get a real session token!
//print "oauth_token = [[".$_REQUEST['oauth_token']."]]\n";echo "<br/><br/>";
$req_token = new OAuthConsumer($_REQUEST['oauth_token'], $_SESSION['oauth_token_secret'], 1);
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "POST", $domain . '/accessToken');
$acc_req->set_parameter("oauth_verifier", $_REQUEST['oauth_verifier']); # need the verifier too!
$acc_req->sign_request($sig_method, $test_consumer, $req_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); //New Line
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$acc_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $domain . "/accessToken");
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error 1: ' . curl_error($ch);
}
curl_close($ch);
parse_str($output, $oauth);
$_SESSION['oauth_token'] = $oauth['oauth_token'];
$_SESSION['oauth_token_secret'] = $oauth['oauth_token_secret'];
# Now you have a session token and secret. Store these for future use. When the token fails, repeat the above process.
//$endpoint = "http://in.linkedin.com/in/intercom"; # need a + symbol here.
$endpoint = "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,industry,educations,site-standard-profile-request)";
//$req_token = new OAuthConsumer($oauth['oauth_token'], $oauth['oauth_token_secret'], 1);
$req_token = new OAuthConsumer($oauth['oauth_token'],$oauth['oauth_token_secret'], 1);
//$profile_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "GET", $endpoint, array("name" => "intercom")); # but no + symbol here!
$profile_req = OAuthRequest::from_consumer_and_token($test_consumer,$req_token, "GET", $endpoint, array());
$profile_req->sign_request($sig_method, $test_consumer, $req_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$profile_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $endpoint);
$output = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error 2: ' . curl_error($ch);
}
curl_close($ch);
//header ("Content-Type:text/xml");
//print $output;
$myFile = $_SERVER['DOCUMENT_ROOT']."/oauth/linkedin.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
//$stringData = "Bobby Bopper\n";
fwrite($fh, $output);
fclose($fh);
//Initialize the XML parser
global $currentTag;
global $profileArray;
$parser=xml_parser_create();
//Function to use at the start of an element
function start($parser,$element_name,$element_attrs) {
$element_name = strtolower($element_name);
global $currentTag;
$currentTag = $element_name;
/*switch($element_name) {
case "person":
$currentTag = $element_name;
break;
case "headline":
echo "headline: ";
break;
case "school-name":
echo "school-name: ";
break;
case "degree":
echo "degree: ";
break;
case "field-of-study":
echo "field-of-study: ";
}*/
}
//Function to use at the end of an element
function stop($parser,$element_name) {}
//Function to use when finding character data
function char($parser,$data){
//echo $data;
global $currentTag;
global $profileArray;
switch($currentTag) {
/* case "member-url":
if(!isset($profileArray['member-url'])) {
$profileArray['member-url'] = $data;//echo $profileArray['industry'];
}
break;*/
case "id":
if(!isset($profileArray['id'])) {
$profileArray['id'] = $data;//echo $profileArray['industry'];
}
break;
case "site-standard-profile-request":
if(!isset($profileArray['site-standard-profile-request'])) {
$profileArray['site-standard-profile-request'] = $data;//echo $profileArray['industry'];
}
break;
case "first-name":
if(!isset($profileArray['first-name'])) {
$profileArray['first-name'] = $data;//echo $profileArray['industry'];
}
break;
case "last-name":
if(!isset($profileArray['last-name'])) {
$profileArray['last-name'] = $data;//echo $profileArray['industry'];
}
break;
case "industry":
if(!isset($profileArray['industry'])) {
$profileArray['industry'] = $data;//echo $profileArray['industry'];
}
break;
case "headline":
if(!isset($profileArray['headline'])) {
$profileArray['headline'] = $data;
}
break;
case "school-name":
if(!isset($profileArray['school-name'])) {
$profileArray['school-name'] = $data;
}
break;
case "degree":
if(!isset($profileArray['degree'])) {
$profileArray['degree'] = $data;
}
break;
case "field-of-study":
if(!isset($profileArray['field-of-study'])) {
$profileArray['field-of-study'] = $data;
}
break;
}
}
//Specify element handler
xml_set_element_handler($parser,"start","stop");
//Specify data handler
xml_set_character_data_handler($parser,"char");
//Open XML file
$fp=fopen($_SERVER['DOCUMENT_ROOT']."/oauth/linkedin.xml","r");
//Read data
while ($data=fread($fp,4096)) {
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
//Free the XML parser
xml_parser_free($parser);
print_r($profileArray);
getCurrentCookieValue($name)
}
you can use linkedIn javascript API to retrieve profile information
Related
I've been trying to select values (students data) from mysql database table and looping through database to send to an API using PHP CURL Post request but it's not working.
This is the API body:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
Parameters I want to send are "admissionNumber" and "class" parameters while "appDomain" is same for all. Here's my code:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
The question is rather unclear; when you say "this is the API body", I presume this JSON fragment is what the REST API at https://url-of-the-endpoint expects. If so, you are building your request body wrong. http_build_query creates an URL-encoded form data block (like key=value&anotherKey=another_value), not a JSON. For a JSON, here's what you want:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
Also, you probably want to remove the HTTP headers from the response:
curl_setopt($curlHandle, CURLOPT_HEADER, false);
I have been working on a clients WP site which lists deals from Groupon. I am using the Groupon's official XML feed, importing via WP All Import. This works without much hassle. Now the issue is Groupon doesn't update that feed frequently but some of their deals get sold out or off the market often. So to get this resolved what I am trying is using a CURL script to crawl the links and check if the deal is available or not then turn the unavailable deals to draft posts (Once a day only).
The custom script is working almost perfectly, only after the first 14/24 requests the server starts responding with 502/503 HTTP status codes. To overcome the issue I have used the below precautions -
Using the proper header (captured from the requests made by the browser)
Parsing cookies from response header and sending back.
Using proper referrer and user agent.
Using proxies.
Trying to send request after a set interval. PHP - sleep(5);
Unfortunately, none of this got me the solution I wanted. I am attaching my code and I would like to request your expert insights on the issue, please.
Thanks in advance for your time.
Shahriar
PHP SCRIPT - https://pastebin.com/FF2cNm5q
<?php
// Error supressing and extend maximum execution time
error_reporting(0);
ini_set('max_execution_time', 50000);
// Sitemap URL List
$all_activity_urls = array();
$sitemap_url = array(
'https://www.groupon.de/sitemaps/deals-local0.xml.gz'
);
$cookies = Array();
// looping through sitemap url for scraping activity urls
for ($u = 0; $u < count($sitemap_url); $u++)
{
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch1, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0');
curl_setopt($ch1, CURLOPT_REFERER, "https://www.groupon.de/");
curl_setopt($ch1, CURLOPT_TIMEOUT, 40);
// curl_setopt($ch1, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_URL, $sitemap_url[$u]);
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, FALSE);
// Parsing Cookie from the response header
curl_setopt($ch1, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
$activity_url_source = curl_exec($ch1);
$status_code = curl_getinfo($ch1, CURLINFO_HTTP_CODE);
curl_close($ch1);
if ($status_code === 200)
{
// Parsing XML sitemap for activity urls
$activity_url_list = json_decode(json_encode(simplexml_load_string($activity_url_source)));
for ($a = 0; $a < count($activity_url_list->url); $a++)
{
array_push($all_activity_urls, $activity_url_list->url[$a]->loc);
}
}
}
if (count($all_activity_urls) > 0)
{
// URL Loop count
$loop_from = 0;
$loop_to = (count($all_activity_urls) > 0) ? 100 : 0;
// $loop_to = count($all_activity_urls);
$final_data = array();
echo 'script start - ' . date('h:i:s') . "<br>";
for ($u = $loop_from; $u < $loop_to; $u++)
{
//Pull source from webpage
$headers = array(
'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-language: en-US,en;q=0.9,bn-BD;q=0.8,bn;q=0.7,it;q=0.6',
'cache-control: max-age=0',
'cookie: ' . implode('; ', $cookies),
'upgrade-insecure-requests: 1',
'user-agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
);
$site = $all_activity_urls[$u];
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_REFERER, "https://www.groupon.de/");
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $site);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// Parsing Cookie from the response header
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
$data = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status_code === 200)
{
// Ready data for parsing
$document = new DOMDocument();
$document->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">' . $data);
$xpath = new DOMXpath($document);
$title = '';
$availability = '';
$price = '';
$base_price = '';
$link = '';
$image = '';
$link = $all_activity_urls[$u];
// Scraping Availability
$raw_availability = $xpath->query('//div[#data-bhw="DealHighlights"]/div[0]/div/div');
$availability = $raw_availability->item(0)->nodeValue;
// Scraping Title
$raw_title = $xpath->query('//h1[#id="deal-title"]');
$title = $raw_title->item(0)->nodeValue;
// Scraping Price
$raw_price = $xpath->query('//div[#class="price-discount-wrapper"]');
$price = trim(str_replace(array("$", "€", "US", " "), array("", "", "", ""), $raw_price->item(0)->nodeValue));
// Scraping Old Price
$raw_base_price = $xpath->query('//div[contains(#class, "value-source-wrapper")]');
$base_price = trim(str_replace(array("$", "€", "US", " "), array("", "", "", ""), $raw_base_price->item(0)->nodeValue));
// Creating Final Data Array
array_push($final_data, array(
'link' => $link,
'availability' => $availability,
'name' => $title,
'price' => $price,
'baseprice' => $base_price,
'img' => $image,
));
}
else
{
$link = $all_activity_urls[$u];
if ($status_code === 429)
{
$status_msg = ' - Too Many Requests';
}
else
{
$status_msg = '';
}
array_push($final_data, array(
'link' => $link,
'status' => $status_code . $status_msg,
));
}
echo 'before break - ' . date('h:i:s') . "<br>";
sleep(5);
echo 'after break - ' . date('h:i:s') . "<br>";
flush();
}
echo 'script end - ' . date('h:i:s') . "<br>";
// Converting data to XML
$activities = new SimpleXMLElement("<?xml version=\"1.0\"?><activities></activities>");
array_to_xml($final_data, $activities);
$xml_file = $activities->asXML('activities.xml');
if ($xml_file)
{
echo 'XML file have been generated successfully.';
}
else
{
echo 'XML file generation error.';
}
}
else
{
$activities = new SimpleXMLElement("<?xml version=\"1.0\"?><activities></activities>");
$activities->addChild("error", htmlspecialchars("No URL scraped from sitemap. Stoping script."));
$xml_file = $activities->asXML('activities.xml');
if ($xml_file)
{
echo 'XML file have been generated successfully.';
}
else
{
echo 'XML file generation error.';
}
}
// Recursive Function for creating XML Nodes
function array_to_xml($array, &$activities)
{
foreach ($array as $key => $value)
{
if (is_array($value))
{
if (!is_numeric($key))
{
$subnode = $activities->addChild("$key");
array_to_xml($value, $subnode);
}
else
{
$subnode = $activities->addChild("activity");
array_to_xml($value, $subnode);
}
}
else
{
$activities->addChild("$key", htmlspecialchars("$value"));
}
}
}
// Cookie Parsing Function
function curlResponseHeaderCallback($ch, $headerLine)
{
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
{
$cookies[] = $cookie[1];
}
return strlen($headerLine); // Needed by curl
}
There is a mess of cookies in your snippet. The callback function just appends cookies to the array regardingless of whether they already exist or not. Here is a new version which at least seems to work in this case since there are no semicolon-seperated multiple cookie definitions. Usually the cookie string should be even parsed. If you have installed the http extension you can use http_parse_cookie.
// Cookie Parsing Function
function curlResponseHeaderCallback($ch, $headerLine)
{
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]+)/mi', $headerLine, $match) == 1)
{
if(false !== ($p = strpos($match[1], '=')))
{
$replaced = false;
$cname = substr($match[1], 0, $p+1);
foreach ($cookies as &$cookie)
if(0 === strpos($cookie, $cname))
{
$cookie = $match[1];
$replaced = true;
break;
}
if(!$replaced)
$cookies[] = $match[1];
}
var_dump($cookies);
}
return strlen($headerLine); // Needed by curl
}
I am using Fat Secret API in my project and want to find the food names on search so I hard coded the food name say : banana and it is giving me error
8 Invalid signature: oauth_signature 'NECnoAOp6D2qLCg7YQ84fYyJYRE='
Below is my code
$consumer_key = "bcd69xxxxxxxxxxxxxxxxxxxxxxx52";
$secret_key = "62fe9xxxxxxxxxxxxxxxxxxxxxxxx54d";
$base = rawurlencode("GET")."&";
$base .= "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";
$params = "format=json&";
$params = "method=foods.search&";
$params .= "oauth_consumer_key=$consumer_key&";
$params .= "oauth_nonce=".uniqid()."&";
$params .= "oauth_signature_method=HMAC-SHA1&";
$params .= "oauth_timestamp=".time()."&";
$params .= "oauth_version=1.0&";
$params .= "search_expression=banana";
$params .= "oauth_callback=oob";
$params2 = rawurlencode($params);
$base .= $params2;
//encrypt it!
$sig= base64_encode(hash_hmac('sha1', $base, "62fe9d66898545a0b48d497a4394054d&", true));
$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig);
//$food_feed = file_get_contents($url);
list($output,$error,$info) = loadFoods($url);
echo '<pre>';
if($error == 0){
if($info['http_code'] == '200'){
echo $output;
} else {
die('Status INFO : '.$info['http_code']);
}
}else{
die('Status ERROR : '.$error);
}
function loadFoods($url)
{
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
// close curl resource to free up system resources
curl_close($ch);
return array($output,$error,$info);
}
Please Help me in this. I am new in OAuth and Fat Secret API, Please do share the necessary information if you know.
Thanks
I am trying to search (filter) for files in a Dropbox folder, but no files are being found when there are files that match the filter. I am not using the PHP library provided by Dropbox.
Here is an extract of the code:
class Dropbox {
private $headers = array();
private $authQueryString = "";
public $SubFolders = array();
public $Files = array();
function __construct() {
$this->headers = array('Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="'.DROPBOX_APP_KEY.'", oauth_token="'.DROPBOX_OAUTH_ACCESS_TOKEN.'", oauth_signature="'.DROPBOX_APP_SECRET.'&'.DROPBOX_OAUTH_ACCESS_SECRET.'"');
$this->authQueryString = "oauth_consumer_key=".DROPBOX_APP_KEY."&oauth_token=".DROPBOX_OAUTH_ACCESS_TOKEN."&oauth_signature_method=PLAINTEXT&oauth_signature=".DROPBOX_APP_SECRET."%26".DROPBOX_OAUTH_ACCESS_SECRET."&oauth_version=1.0";
}
public function GetFolder($folder, $fileFilter = "") {
//Add the required folder to the end of the base path for folder call
if ($fileFilter == "")
$subPath = "metadata/sandbox";
else
$subPath = "search/sandbox";
if (strlen($folder) > 1) {
$subPath .= (substr($folder, 0, 1) != "/" ? "/" : "")
.$folder;
}
//Set up the post parameters for the call
$params = null;
if ($fileFilter != "") {
$params = array(
"query" => $fileFilter
);
}
//Clear the sub folders and files logged
$this->SubFolders = array();
$this->Files = array();
//Make the call
$content = $this->doCall($subPath, $params);
//Log the files and folders
for ($i = 0; $i < sizeof($content->contents); $i++) {
$f = $content->contents[$i];
if ($f->is_dir == "1") {
array_push($this->SubFolders, $f->path);
} else {
array_push($this->Files, $f->path);
}
}
//Return the content
return $content;
}
private function doCall($urlSubPath, $params = null, $filePathName = null, $useAPIContentPath = false) {
//Create the full URL for the call
$url = "https://api".($useAPIContentPath ? "-content" : "").".dropbox.com/1/".$urlSubPath;
//Initialise the curl call
$ch = curl_init();
//Set up the curl call
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($params != null)
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$fh = null;
if ($filePathName != null) {
$fh = fopen($filePathName, "rb");
curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
curl_setopt($context, CURLOPT_INFILE, $fh);
curl_setopt($context, CURLOPT_INFILESIZE, filesize($filePathName));
}
//Excecute and get the response
$api_response = curl_exec($ch);
if ($fh != null)
fclose($fh);
//Process the response into an array
$json_response = json_decode($api_response);
//Has there been an error
if (isset($json_response->error )) {
throw new Exception($json_response["error"]);
}
//Send the response back
return $json_response;
}
}
I then call the GetFolder method of Dropbox as such:
$dbx = new Dropbox();
$filter = "MyFilter";
$dbx->GetFolder("MyFolder", $filter);
print "Num files: ".sizeof($dbx->Files);
As I am passing $filter into GetFolder, it uses the search/sandbox path and creates a parameter array ($params) with the required query parameter in it.
The process works fine if I don't provide the $fileFilter parameter to GetFolder and all files in the folder are returned (uses the metadata/sandbox path).
Other methods (that are not in the extract for brevity) of the Dropbox class use the $params feature and they to work fine.
I have been using the Dropbpox API reference for guidance (https://www.dropbox.com/developers/core/docs#search)
At first glance, it looks like you're making a GET request to /search but passing parameters via CURLOPT_POSTFIELDS. Try using a POST or encoding the search query as a query string parameter.
EDIT
Below is some code that works for me (usage: php search.php <term>). Note that I'm using OAuth 2 instead of OAuth 1, so my Authorization header looks different from yours.
<?php
$access_token = '<REDACTED>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.dropbox.com/1/search/auto');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:Bearer ' . $access_token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('query' => $argv[1]));
$api_response = curl_exec($ch);
echo "Matching files:\n\t" . join("\n\t",
array_map(function ($file) {
return $file['path'];
}, json_decode($api_response, true)))."\n";
?>
I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz