foldergrid php client get folder info - php

I am trying to implement a simple foldergrid php client. I am using the simple php client from the foldergrid api documentation. The client code that I got from the api documentation is:
class FolderGridClient {
protected $_cookieFileLocation = './cookie.txt';
public $_webpage;
public $_status;
public $_location;
const SERVER_HOST = 'https://secure.foldergrid.com';
public function authenticate($username,$password, $domain){
$params = array("domain"=>$domain,"username"=>$username,"password"=>$password);
$this->createCurl(self::SERVER_HOST."/login",$params);
}
public function createDomain($adminemail,$adminpassword, $domainname, $adminfname, $adminlname){
$json = json_encode( array('invite'=>true, 'admin' => array('email'=>$adminemail,'password'=>$adminpassword,'firstname'=>$adminfname,'lastname'=>$adminlname) ) );
$this->createCurl(self::SERVER_HOST."/domain/".$domainname,$json,true);
}
public function uploadFile($file,$name,$parentDuid) {
$fh = fopen($file, "rb");
if($fh) {
$json = json_encode( array('parentDuid'=>$parentDuid, 'name' => $name, 'parts' => 1) );
$this->createCurl(self::SERVER_HOST."/file/provision",$json,true);
if($this->_location){
$headers = array(
'fg-eap: false',
'fg-md5:'.md5_file($file),
'Content-Type: binary/octet-stream'
);
$curl = curl_init();
curl_setopt($curl,CURLOPT_PUT,true);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_URL, $this->_location);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLOPT_INFILE, $fh);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($file));
curl_setopt( $curl, CURLOPT_VERBOSE, true );
$this->_webpage = curl_exec($curl);
$this->_status = curl_getinfo($curl,CURLINFO_HTTP_CODE);
fclose($fh);
curl_close($curl);
}
}else{
echo "File not found: $file \n";
}
}
public function fetchFolder($pathOrDuid){
$this->createCurl(self::SERVER_HOST."/folder/$pathOrDuid");
return $this->_webpage;
}
public function fetchFile($fileid){
$this->createCurl(self::SERVER_HOST."/file/$fileid");
return $this->_webpage;
}
public function createCurl($url,$postFields = null, $put = false)
{
$s = curl_init();
curl_setopt($s, CURLOPT_VERBOSE, true);
curl_setopt($s,CURLOPT_URL,$url);
curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
curl_setopt($s, CURLOPT_HEADER, TRUE);
curl_setopt($s,CURLOPT_FOLLOWLOCATION,false);
curl_setopt($s,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
curl_setopt($s,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);
if($postFields)
{
curl_setopt($s,CURLOPT_POST,true);
if($put) {
curl_setopt($s, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($postFields)));
curl_setopt($s,CURLOPT_CUSTOMREQUEST, "PUT");
}else{
curl_setopt($s, CURLOPT_HTTPHEADER, array('Expect:'));
}
curl_setopt($s,CURLOPT_POSTFIELDS,$postFields);
}
$this->_webpage = curl_exec($s);
$this->_status = curl_getinfo($s,CURLINFO_HTTP_CODE);
preg_match_all('/^Location:(.*)$/mi', $this->_webpage, $matches);
$this->_location = !empty($matches[1]) ? trim($matches[1][0]) : null;
curl_close($s);
}
}
Using this client, I was able to successfully upload a file to my folder grid root folder. Now I have created a test folder under the root, and I am trying to use the API to get the duid of the folder. I used the following code:
$uname='myuname';
$pwd='mypwd';
$domain='mydomain';
$rootDUID='duidOFRootFolder';
$client = new FolderGridClient;
$client->authenticate( $uname,$pwd,$domain);
if($client->_status < 400){
echo "fetchFolder: " . $client->fetchFolder($domain.'/TestNewFolder') . "<BR>";
}
TestNewFolder is the name of the folder I created using the foldergrid javascript reference client at https://mydomain.foldergrid.com/show/*.html
The root foldername is the same as my domain name, which i think is standard for foldergrid.
However, when I run that code, I always get a folder not found response. I have tried various different permutations of the folder path as an input to the fetchFolder function with no success. so two questions:
1. how should I use the fetchFolder function in the php simple client to get the folder info - specifically the duid.
2. Does anyone have an addition to the php simple client to create a sub folder, once I have discovered the duid of the target folder?
THANKS

When you create a new folder programmatically using the FolderGrid API you assign the immutable DUID which uniquely identifies that folder. One easy method to determine the DUID for any existing folder is to simply open the FolderGrid Web App and right click the folder to choose "Show Info".
To determine an unknown DUID programmatically using API calls, you simply traverse the folder path from a higher folder with a known DUID using calls to Show Folder Details which display the DUIDs of all subfolders. For example, you would execute a GET /folder/DUID on your root folder which will return (among other things) a json array of the names and DUIDs of all the subfolders of your root folder - including TestNewFolder
One useful shortcut is mentioned in the API docs for Show Folder Details which is that you can substitute asterisk '*' for DUID in that call as a shorthand reference to the root folder.
The sample PHP client code uses the name "pathOrDuid" for the parameter to fetchFolder but that's misleading because the call to retrieve a folder's details by path is a distinct call as documented here.

So following Simmerman's suggestions, here is some php code that I used to get the duid of a sub folder if I know the parent folders duid (like '*' for the root folder). I have added the following function to the php simple client that foldergrid provided in their documentation:
public function getSubFolderDuid($parentDuid,$folderName) {
$fetchParent = $this->fetchFolder($parentDuid);
$parentJsonMatch = array();
preg_match("/\{.*\}/",$fetchParent,&$parentJsonMatch);
$returnArray=true;
$parentJsonArray = json_decode($parentJsonMatch[0],$returnArray);
$subFolders = $parentJsonArray['folders'];
foreach($subFolders as $folderData) {
if ($folderData['name'] == $folderName) return $folderData['duid'];
}
return '';
}
obviously there is plenty of room to add error handling to this function in case the parent folder is not returned. This function is assuming the parent folder exists and is returned as json data.
Here is the code I used to call the function:
if($client->_status < 400){
$parentDuid = '*';
$folderName = 'TestNewFolder';
$folderDuid = $client->getSubFolderDuid($parentDuid,$folderName);
echo "$folderName: $folderDuid<br>";
}
With these building blocks I can now build code to traverse the directory tree or find a specific folder duid at an arbitrary depth in the tree.
Thanks for the pointing me in the right direction Simmerman

Related

create folder if not exist on google drive with Curl php

I'm uploading files to google drive through Curl php. But now I need to upload all these files in specific folder eg: "My Folder"
I need to get all root folders and evaluate if "My folder" isn't exist on google drive.
For first step. I need get all folders in root of google drive
I've founded this function in ahother post
public function getAllGoogleDriveFolders($token)
{
echo "Buscando Folders en Drive \n";
$folderID = "root";
$folderName = "My Folder";
$baseUrl = "https://www.googleapis.com/drive/v3/files";
$query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='$folderName' and '$folderID' in parents";
$url = $baseUrl . "?q=" . urlencode($query);
//print_r($url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
$response = curl_exec($ch);
var_dump($response);die();
curl_close($ch);
}
but this function returns "files": [] empty.
string(72) "{
"kind": "drive#fileList",
"incompleteSearch": false,
"files": []
}
Once I get all folders,
Second step, is evaluate these folders
foreach ($data as $folder) {
if ($folder["name"] != "My Folder") {
//.. steps to create folder with name My folder and get its fodler_id
} else {
// if folder exists in google drive // get the folder id
}
}
Note: I'm using service account for authenticate. and the app is old for this reason I can't use the php service package.
thanks in advance

Upload large files to Dropbox via HTTP API

I am currently implementing an upload mechanism for files on my webserver into my Dropbox app directory.
As stated on the API docs, there is the /upload endpoint (https://www.dropbox.com/developers/documentation/http/documentation#files-upload) which accepts files up to 150MB in size. However I‘m dealing with images and videos with a potential size of up to 2GB.
Therefore I need to use the upload_session endpoints. There is an endpoint to start the session (https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start), to append data and to finish the session.
What currently is unclear to me is how to exactly use these endpoints. Do I have to split my file on my server into 150MB chunks (how would I do that with a video file?) and then upload the first chunk with /start, the next chunks with /append and the last one with /finish? Or can I just specify the file and the API somehow (??) does the splitting for me? Obviously not, but I somehow can‘t get my head around on how I should calculate, split and store the chunks on my webserver and not lose the session inbetween...
Any advice or further leading links are greatly appreciated. Thank you!
As Greg mentioned in the comments, you decide how to manage the "chunks" of the files. In addition to his .NET example, Dropbox has a good upload session implementation in the JavaScript upload example of the Dropbox API v2 JavaScript SDK.
At a high-level, you're splitting up the file into smaller sizes (aka "chunks") and passing those to the upload_session mechanism in a specific order. The upload mechanism has a few parts that need to be used in the following order:
Call /files/upload_session/start. Use the resulting session_id as a parameter in the following methods so Dropbox knows which session you're interacting with.
Incrementally pass each "chunk" of the file to /files/upload_session/append_v2. A couple things to be aware of:
The first call will return a cursor, which is used to iterate over the file's chunks in a specific order. It gets passed as a parameter in each consecutive call to this method (with the cursor being updated on every response).
The final call must include the property "close": true, which closes the session so it can be uploaded.
Pass the final cursor (and commit info) to /files/upload_session/finish. If you see the new file metadata in the response, then you did it!!
If you're uploading many files instead of large ones, then the /files/upload_session/finish_batch and /files/upload_session/finish_batch/check are the way to go.
I know this is an old post, but here is a fully functional solution for your problem. Maybe anyone else finds it usefull. :)
<?php
$backup_folder = glob('/var/www/test_folder/*.{sql,gz,rar,zip}', GLOB_BRACE); // Accepted file types (sql,gz,rar,zip)
$token = '<ACCESS TOKEN>'; // Dropbox Access Token;
$append_url = 'https://content.dropboxapi.com/2/files/upload_session/append_v2';
$start_url = 'https://content.dropboxapi.com/2/files/upload_session/start';
$finish_url = 'https://content.dropboxapi.com/2/files/upload_session/finish';
if (!empty($backup_folder)) {
foreach ($backup_folder as $single_folder_file) {
$file_name= basename($single_folder_file); // File name
$destination_folder = 'destination_folder'; // Dropbox destination folder
$info_array = array();
$info_array["close"] = false;
$headers = array(
'Authorization: Bearer ' . $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: '.json_encode($info_array)
);
$chunk_size = 50000000; // 50mb
$fp = fopen($single_folder_file, 'rb');
$fileSize = filesize($single_folder_file); // File size
$tosend = $fileSize;
$first = $tosend > $chunk_size ? $chunk_size : $tosend;
$ch = curl_init($start_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, fread($fp, $first));
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($ch);
$tosend -= $first;
$resp = explode('"',$response);
$sesion = $resp[3];
$position = $first;
$info_array["cursor"] = array();
$info_array["cursor"]["session_id"] = $sesion;
while ($tosend > $chunk_size)
{
$info_array["cursor"]["offset"] = $position;
$headers[2] = 'Dropbox-API-Arg: '.json_encode($info_array);
curl_setopt($ch, CURLOPT_URL, $append_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, fread($fp, $chunk_size));
curl_exec($ch);
$tosend -= $chunk_size;
$position += $chunk_size;
}
unset($info_array["close"]);
$info_array["cursor"]["offset"] = $position;
$info_array["commit"] = array();
$info_array["commit"]["path"] = '/'. $destination_folder . '/' . $file_name;
$info_array["commit"]["mode"] = array();
$info_array["commit"]["mode"][".tag"] = "overwrite";
$info_array["commit"]["autorename"] = true;
$info_array["commit"]["mute"] = false;
$info_array["commit"]["strict_conflict"] = false;
$headers[2] = 'Dropbox-API-Arg: '. json_encode($info_array);
curl_setopt($ch, CURLOPT_URL, $finish_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $tosend > 0 ? fread($fp, $tosend) : null);
curl_exec($ch);
curl_close($ch);
fclose($fp);
unlink($single_folder_file); // Remove files from server folder
}
}

Including file from main domain on subdomain

I used to include files between sites routinely, until my webhost banned the practice. Now it appears that a recent PHP upgrade also tightened the screws, as I'm getting a "no suitable wrapper could be found" error - and I'm working with LOCAL sites.
Let's start with a website # www.gx.com and a subdomain at subdomain.mysite.com. However, they display locally as two separate websites - mysite.com and subdomain.com.
A page on subdomain.com features the following include request:
require_once($GX_URL."/2b/inc/D/Shared/Body/Bottom/Footer.php
$GX_URL displays as http[://]gx locally and http[://]gx.com online.
How can I modify this include so it works in both situations? I can use the following switch to hold two separate includes, one for online use and the other for local use:
switch(PHP_OS)
{
case 'Linux':
break;
default:
break;
}
I just figured the answer to my first question; I simply mapped out the entire path to the file in the other website on my computer:
/Applications/MAMP/htdocs/gx/2b/inc/D/Shared/Body/Bottom/Footer.php
So I guess I need to do something similar to include a file from my main domain. However, I'll leave this question open in case anyone has a more elegant solution.
I have more you can try one.
Try download html and include to your php page :).
Http Request or CURL request
Use Allow_url_include, example: http://wiki.dreamhost.com/Allow_url_include
Use Object download: http://php.net/manual/de/function.ob-start.php
Example::
1. Curl Download html string
function curl_get($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, $this->CURL_UA);
curl_setopt($ch, CURLOPT_REFERER, $this->YT_BASE_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
curl_close ($ch);
return $contents;
}
2. Http send request width file_get_contents
function sendRequest($url, $data = array())
{
$data = http_build_query($data);
$context_options = array('http' => array('method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($data) . "\r\n",
'content' => $data)
);
$context = stream_context_create($context_options);
$result = file_get_contents($url, false, $context);
return $result;
}
3 Object : http://php.net/manual/de/function.ob-start.php

curl is not working in Yii

when i am using curl in my core php file it's working fine for me and getting expected result also... my core php code is...
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://stage.auth.stunnerweb.com/index.php?r=site/getUser");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
echo $data; //here i am getting respond proper
here in above i am making call to getUser function and i am getting respond from that function...
but now my problem is when i am using this same code in my any Yii controller (tried to use it in SiteController & Controller) but it's not working...
public function beforeAction()
{
if(!Yii::app()->user->isGuest)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL ,"http://stage.auth.stunnerweb.com/index.php?r=site/kalpit");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
echo $data;
}
else
return true;
}
in yii can't we use curl like this?
Can you please suggest me how to use curl in yii?
Thanks in advance
Better use yii-curl
Setup instructions
Place Curl.php into protected/extensions folder of your project
in main.php, add the following to 'components':
php
'curl' => array(
'class' => 'ext.Curl',
'options' => array(/.. additional curl options ../)
);
Usage
to GET a page with default params
php
$output = Yii::app()->curl->get($url, $params);
// output will contain the result of the query
// $params - query that'll be appended to the url
to POST data to a page
php
$output = Yii::app()->curl->post($url, $data);
// $data - data that will be POSTed
to PUT data
php
$output = Yii::app()->curl->put($url, $data, $params);
// $data - data that will be sent in the body of the PUT
to set options before GET or POST or PUT
php
$output = Yii::app()->curl->setOption($name, $value)->get($url, $params);
// $name & $value - CURL options
$output = Yii::app()->curl->setOptions(array($name => $value))->get($get, $params);
// pass key value pairs containing the CURL options
You are running your code inside a beforeAction() method which is not supposed to render any data at all. On top of that, you do not let the method return anything if the current user is a guest. Please read the API docs concerning this.

PHP - Run function for each file in a directory passing two parameters

I should start by saying I have no php experience what so ever, but I know this script can't be that ambitious.
I'm using Wordpress' metaWeblog API to batch the creation of several hundred posts. Each post needs a discrete title, a description, and url's for two images, the latter being custom fields.
I have been successful producing one post by manually entering data into the following file;
<?php // metaWeblog.Post.php
$BLOGURL = "http://path/to/your/wordpress";
$USERNAME = "username";
$PASSWORD = "password";
function get_response($URL, $context) {
if(!function_exists('curl_init')) {
die ("Curl PHP package not installed\n");
}
/*Initializing CURL*/
$curlHandle = curl_init();
/*The URL to be downloaded is set*/
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $context);
/*Now execute the CURL, download the URL specified*/
$response = curl_exec($curlHandle);
return $response;
}
function createPost(){
/*The contents of your post*/
$description = "post description";
/*Forming the content of blog post*/
$content['title'] = $postTitle;
$content['description'] = $description;
/*Pass custom fields*/
$content['custom_fields'] = array(
array( 'key' => 'port_thumb_image_url', 'value' => "$imagePath" ),
array( 'key' => 'port_large_image_url', 'value' => "$imagePath" )
);
/*Whether the post has to be published*/
$toPublish = false;//false means post will be draft
$request = xmlrpc_encode_request("metaWeblog.newPost",
array(1,$USERNAME, $PASSWORD, $content, $toPublish));
/*Making the request to wordpress XMLRPC of your blog*/
$xmlresponse = get_response($BLOGURL."/xmlrpc.php", $request);
$postID = xmlrpc_decode($xmlresponse);
echo $postID;
}
?>
In an attempt to keep this short, here is the most basic example of the script that iterates through a directory and is "supposed" to pass the variables $postTitle, and $imagePath and create the posts.
<?php // fileLoop.php
require('path/to/metaWeblog.Post.php');
$folder = 'foldername';
$urlBase = "images/portfolio/$folder";//truncate path to images
if ($handle = opendir("path/to/local/images/portfolio/$folder/")) {
/*Loop through files in truncated directory*/
while (false !== ($file = readdir($handle))) {
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']); // strip file extension
$postTitle = preg_replace("/\.0|\./", " ", $file_name); // Make file name suitable for post title !LEAVE!
echo "<tr><td>$postTitle</td>";
$imagePath = "$urlBase/$file";
echo " <td>$urlBase/$file</td>";
createPost($postTitle, $imagePath);
}
closedir($handle);
}
?>
It's supposed to work like this,
fileLoop.php opens the directory and iterates through each file
for each file in the directory, a suitable post title(postTitle) is created and a url path(imagePath) to the server's file is made
each postTitle and imagePath is passed to the function createPost in metaWeblog.php
metaWeblog.php creates the post and passes back the post id to finish creating the table row for each file in the directory.
I've tried declaring the function in fileLoop.php, I've tried combining the files completely. It either creates the table with all files, or doesn't step through the directory that way. I'm missing something, I know it.
I don't know how to incorporate $POST_ here, or use sessions as I said I'm very new to programming in php.
You need to update your declaration of the createPost() function so that it takes into account the parameters you are attempting to send it.
So it should be something like this:
function createPost($postTitle, $imagePath){
/*The contents of your post*/
$description = "post description";
...
}
More information about PHP function arguments can be found on the associated manual page.
Once this has been remedied you can use CURL debugging to get more information about your external request. To get more information about a CURL request try setting the following options:
/*Initializing CURL*/
$curlHandle = curl_init();
/*The URL to be downloaded is set*/
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $context);
curl_setopt($curlHandle, CURLOPT_HEADER, true); // Display headers
curl_setopt($curlHandle, CURLOPT_VERBOSE, true); // Display communication with server
/*Now execute the CURL, download the URL specified*/
$response = curl_exec($curlHandle);
print "<pre>\n";
print_r(curl_getinfo($ch)); // get error info
echo "\n\ncURL error number:" .curl_errno($ch); // print error info
echo "\n\ncURL error:" . curl_error($ch);
print "</pre>\n";
The above debug example code is from eBay's help pages.
It should show you if Wordpress is rejecting the request.

Categories