How can I ingest an image into Fedora Commons using PHP? - php

I am trying to ingest an image into a Fedora Commons repository using PHP. Here is the code I'm using:
$queryArgs = array(
"label" => "label goes here",
"format" => "info:fedora/fedora-system:METSFedoraExt-1.1",
"namespace" => $prefix,
"ownerID" => $fedoraUsername,
"logMessage" => "log message goes here"
);
$url = sprintf(
"%s://%s:%d/%s/objects/%s?%s",
"http",
$host,
$port,
"fedora",
$prefix . ":" . $identifier,
http_build_query($queryArgs)
);
$headers = array("Accept: text/xml", "Content-Type: image/jpg");
$userPassword = $fedoraUsername . ":" . $fedoraPassword;
$verifyPeer = false;
$fileContents = file_get_contents("http://localhost/path/to/image.jpg");
$curlOptions = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userPassword,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_SSL_VERIFYPEER => $verifyPeer,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fileContents
);
$curlHandle = curl_init();
curl_setopt_array($curlHandle, $curlOptions);
curl_exec($curlHandle);
error_log(print_r(curl_getinfo($curlHandle), true));
At the end I print out whatever curl_getinfo has to say, notably [http_code] => 415.
HTTP Error 415 Unsupported media type
What am I doing wrong here?

I finally figured it out. I ended up making two different requests: one to create a new empty object in Fedora, the other to attach a datastream to that object. Here is the code (I put all this in a class named Fedora, but this is not necessary and might not fit your needs):
<?php
class Fedora {
// Use cURL with the provided functions and return the result if the HTTP Code recieved matches the expected HTTP Code
private function curlThis($curlOptions, $expectedHttpCode) {
$returnValue = false;
try {
$curlHandle = curl_init();
if ($curlHandle === false) {
throw new Exception(
"`curl_init()` returned `false`"
);
}
$settingOptionsSucceeded = curl_setopt_array($curlHandle, $curlOptions);
if ($settingOptionsSucceeded === false) {
throw new Exception(
sprintf(
"`curl_setopt_array(...)` returned false. Error: %s. Info: %s",
curl_error($curlHandle),
print_r(curl_getinfo($curlHandle), true)
),
curl_errno($curlHandle)
);
}
$curlReturn = curl_exec($curlHandle);
if ($curlReturn === false) {
throw new Exception(
sprintf(
"`curl_exec(...)` returned false. Error: %s. Info: %s",
curl_error($curlHandle),
print_r(curl_getinfo($curlHandle), true)
),
curl_errno($curlHandle)
);
}
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
if ($httpCode === false) {
throw new Exception(
sprintf(
"`curl_getinfo(...)` returned false. Error: %s.",
curl_error($curlHandle)
),
curl_errno($curlHandle)
);
}
if ($httpCode !== $expectedHttpCode) {
throw new Exception(
sprintf(
"`curl_getinfo(...)` returned an unexpected http code (expected %s, but got %s). Error: %s. Complete info: %s",
$expectedHttpCode,
$httpCode,
curl_error($curlHandle),
print_r(curl_getinfo($curlHandle), true)
),
curl_errno($curlHandle)
);
}
$returnValue = $curlReturn;
} catch (Exception $e) {
trigger_error(
sprintf(
"(%d) %s",
$e->getCode(),
$e->getMessage()
),
E_USER_ERROR
);
}
return $returnValue;
}
// Create a new empty object in Fedora Commons and return its pid
private function createNewEmptyObject($prefix, $id) {
$returnValue = false;
// Build URL
$protocol = variable_get("fedora_protocol"); // 'http'
$host = variable_get("fedora_host");
$port = variable_get("fedora_port"); // '8082'
$context = variable_get("fedora_context"); // 'fedora'
$pid = $prefix . ":" . $id;
$url = sprintf(
"%s://%s:%d/%s/objects/%s",
$protocol,
$host,
$port,
$context,
$pid
);
// Build cURL options
$userPassword = variable_get("fedora_username") . ":" . variable_get("fedora_password"); // username:password
$verifyPeer = false; // false for ignoring self signed certificates
$headers = array("Accept: text/xml", "Content-Type: text/xml");
$curlOptions = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userPassword,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_SSL_VERIFYPEER => $verifyPeer,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true
);
// Try `cURL`ing
$result = $this->curlThis($curlOptions, 201);
if ($result === $pid) {
$returnValue = $result;
}
return $returnValue;
}
private function attachDatastream ($pid, $file, $datastreamID) {
$returnValue = false;
// Build URL
$protocol = variable_get("fedora_protocol"); // "http"
$host = variable_get("fedora_host");
$port = variable_get("fedora_port"); // 8082
$context = variable_get("fedora_context"); // fedora
$url = sprintf(
"%s://%s:%d/%s/objects/%s/datastreams/%s?controlGroup=M", // M stands for 'Managed Content'
$protocol,
$host,
$port,
$context,
$pid,
$datastreamID
);
// Build cURL options
$userPassword = variable_get("fedora_username") . ":" . variable_get("fedora_password"); // username:password
$verifyPeer = false; // false for ignoring self signed certificates
$headers = array("Accept: text/xml", "Content-Type: " . $file->filemime);
$fileContents = file_get_contents("sites/default/files/images/" . $file->filename);
$curlOptions = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userPassword,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_SSL_VERIFYPEER => $verifyPeer,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fileContents
);
// Try `cURL`ing
$result = $this->curlThis($curlOptions, 201);
if ($result === $pid) {
$returnValue = $result;
}
return $returnValue;
}
public function ingest($namespace, $identifier, $file) {
$pid = $this->createNewEmptyObject($namespace, $identifier);
if ($pid) {
$result = $this->attachDatastream($pid, $file, "IMAGE");
if ($result) {
error_log("Successfully ingested a file!");
} else {
error_log("FAILED ATTACHING DATASTREAM TO NEW OBJECT");
}
} else {
error_log("FAILED CREATING NEW EMPTY OBJECT");
}
}
}
$fedora = new Fedora();
/*
* $file is an object obtained by uploading a file into a drupal file system (at /drupal/sites/default/files/images/singe.jpg). It has the following attributes:
* $file->filemime === "image/jpeg"
* $file->filename === "singe.jpg"
*/
$fedora->ingest('namespace', 'identifier', $file);
?>

Related

Issues sending larger files via curl

Afternoon all,
Having some issues sending large files via curl, we can send the first one which is 5mb but the second test file is 34mb and is not sending. We have increased the post and max upload sizes on both the sending and receiving servers and still no joy.
This is the sending script:
function send_files($directory, $file, $dir_parts) {
$url = 'https://test.com/App_processing/transfer_videos';
$handle = fopen($directory."video.mp4", "r");
$stats = fstat($handle);
$data = stream_get_contents($handle);
$payload = array(
'file' => base64_encode($data),
'parts' => $dir_parts
);
$postfields = array( serialize( $payload ) );
$ssl = strstr($url, '://', true);
$port = ($ssl == 'https') ? 443 : 80;
$verify_ssl = false;
$ch = curl_init();
$curlConfig = array(
CURLOPT_PORT => $port,
CURLOPT_URL => $url,
CURLOPT_SSL_VERIFYPEER => $verify_ssl,
CURLOPT_FORBID_REUSE => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_FAILONERROR => false,
CURLOPT_VERBOSE => true,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_POSTFIELDS => $postfields,
);
$headers = null;
$apikey = 'testAPIkey';
$headers = array(
"apikey: ".$apikey
);
$curlConfig[CURLOPT_HTTPHEADER] = $headers;
curl_setopt_array( $ch, $curlConfig );
$response = curl_exec( $ch );
}
Receiving script:
public function transfer_videos() {
$return_arr = array();
ini_set('max_execution_time', '999');
ini_set('memory_limit', '512M');
ini_set('post_max_size', '512M');
if(count($this->post_data) > 0) {
$image = $this->post_data['file'];
$file = base64_decode($image);
$filename = $this->post_data['parts'][2];
$return_arr = array();
$office_path = $this->config->item('_path') . '_videos/';
$path = $o_path.$this->post_data['parts'][0]."/".$this->post_data['parts'][1]."/";
$name = $filename;
if( !is_dir( $path ) ) {
mkdir( $path, 0750, true );
}
try {
$return_arr = file_put_contents($path.$name, $file);
} catch (Exception $e) {
$this->curl_helper->error($path.$name, "failed to upload file");
}
}
echo serialize($return_arr);
}
The current error we are getting is:
Recv failure: Connection reset by peer
What the hell are we doing wrong?

Create folder in root directiry of and upload file to that folder google drive api

I want to create folder in googledrive root directory using CURL. File is uploaded to drive but I need to create a folder and upload file to that folder.
As per #hanshenrik Code Create Folder is working Move file is not work
My Updated code :
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath,$folderId)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
//$content = { title "mypdf.pdf", description = "mypdf.pdf", mimeType = "application/pdf" };
$contentArry = array('name' =>'veridoc', 'parents' => array('17dVe2GYpaHYFdFn1by5-TYKU1LXSAwkp'));
$contentArry = json_encode($contentArry);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS,$contentArry);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : application/pdf','Content-Length:' . filesize($filename),'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function RenameUploadedFile($id,$credentials,$filename)
{
$ch = curl_init();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . urlencode ( $id ),
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode ( array (
'name' => $filename
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
curl_exec($ch);
curl_close($ch);
return true;
}
function CreateGDFolder($credentials,$foldername)
{
$curl = curl_init();
curl_setopt_array ( $curl, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files',
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode ( array (
// Earlier it was title changed to name
"name" => $foldername,
"mimeType" => "application/vnd.google-apps.folder"
) ),
// Earlier it was PATCH changed to post
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
$response = curl_exec($curl);
return json_decode($response, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
{
return $credentials;
}
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$folderresponse=CreateGDFolder($credentials,"veridoc");
$folderID= $folderresponse['id'];
$folder_id=$folderID;
$filename="veridoc".date('_Y_m_d_H_i_s').".pdf";
$result = uploadFile($credentials, 'veridoc.pdf', '',$folderID);
// File rename to original
$id=$result['id'];
$file_id=$id;
if(isset($folderID)){
//Upload a file
if(RenameUploadedFile($id,$credentials,$filename))
{
echo "We have uploaded ".$filename." to drive";
}
else{
echo "can't rename file";
}
}
try {
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files/' . urlencode ( $file_id ),
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode (array(
'addParents' => $folder_id,
'removeParents' => 'root',
'fields' => 'id, parents') ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/pdf',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
$resp = curl_exec ( $ch );
$parsed = json_decode ( $resp, true );
} finally{
curl_close ( $ch );
}
This is my working example:
To connect Google Driver:
public function connect(Request $request)
{
$user = Auth::user();
$client = new \Google_Client();
$client->setHttpClient(new \GuzzleHttp\Client(['verify' => false]));
$client->setClientId('xxxx');
$client->setClientSecret('xxxxxx');
$client->setRedirectUri(url('copywriter/connect'));
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setScopes(array('https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.appfolder'));
if (isset($request->code)) {
$authCode = trim($request->code);
$accessToken = $client->authenticate($authCode);
$copywriter->gd_access_token=json_encode($accessToken, JSON_PRETTY_PRINT);
$copywriter->save();
} else {
$authUrl = $client->createAuthUrl();
return redirect($authUrl);
}
$found=$this->search_gd("files");
if (!isset($found['file_id'])) {
$found=$this->create_folder_gd("copify_files");
$copywriter->gd_folder_id=$found["file_id"];
$copywriter->save();
}
return redirect(route("copywriter.index"));
}
Send to Google Drive
public function send_to_gd($name)
{
$user = Auth::user();
$copywriter=Copywriter::where('user_id', $user->id)->first();
$folderId = $copywriter->gd_folder_id;
$client=$this->getClient();
$service = new \Google_Service_Drive($client);
$fileMetadata = new \Google_Service_Drive_DriveFile(array(
'name' => $name,'mimeType' => 'application/vnd.google-apps.document','parents' => array($folderId)));
$file = $service->files->create($fileMetadata, array(
'mimeType' => 'application/vnd.google-apps.document',
'uploadType' => 'multipart',
'fields' => 'id'));
return $file->id;
}
Client of Request:
public function getClient($user=null)
{
if ($user==null) {
$user = Auth::user();
}
$copywriter=Copywriter::where('user_id', $user->id)->first();
$client = new \Google_Client();
$client->setHttpClient(new \GuzzleHttp\Client(['verify' => false]));
$client->setClientId('xxxx');
$client->setClientSecret('xxxxx');
$client->setRedirectUri(url('copywriter/connect'));
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setScopes(array('https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.appfolder'));
$data=json_decode($copywriter->gd_access_token, true);
$client->setAccessToken($data);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$oldAccessToken=$client->getAccessToken();
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$accessToken=$client->getAccessToken();
$accessToken['refresh_token']=$oldAccessToken['refresh_token'];
$copywriter->gd_access_token=json_encode($accessToken, JSON_PRETTY_PRINT);
$copywriter->save();
}
return $client;
}
Search in Google Drive
public function search_gd($name)
{
$client=$this->getClient();
$service = new \Google_Service_Drive($client);
$pageToken = null;
do {
$response = $service->files->listFiles(array(
'q' => "mimeType='application/vnd.google-apps.folder' and name='".$name."'",
'spaces' => 'drive',
'pageToken' => $pageToken,
'fields' => 'nextPageToken, files(id, name)',
));
foreach ($response->files as $file) {
return ['file_name'=>$file->name,'file_id'=>$file->id];
printf("Found file: %s (%s)\n", $file->name, $file->id);
}
if (isset($repsonse)) {
$pageToken = $repsonse->pageToken;
}
} while ($pageToken != null);
}
Create a folder on Google Drive
public function create_folder_gd($name)
{
$client=$this->getClient();
$service = new \Google_Service_Drive($client);
$fileMetadata = new \Google_Service_Drive_DriveFile(array(
'name' => $name,
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'));
return ['file_name'=>$name,'file_id'=>$file->id];
}
Create a document on Google Drive:
public function create_document($name, $content_id=null)
{
$user = Auth::user();
$copywriter=Copywriter::where('user_id', $user->id)->first();
$folderId = $copywriter->gd_folder_id;
$client=$this->getClient();
$service = new \Google_Service_Drive($client);
$fileMetadata = new \Google_Service_Drive_DriveFile(array(
'name' => $name,'mimeType' => 'application/vnd.google-apps.document','parents' => array($folderId)));
$file = $service->files->create($fileMetadata, array(
'mimeType' => 'application/vnd.google-apps.document',
'uploadType' => 'multipart',
'fields' => 'id'));
if ($content_id!=null) {
$content=Content::findOrFail($content_id);
$content->file_id=$file->id;
$content->save();
}
return ['file_name'=>$name,'file_id'=>$file->id];
}
My Models is Copywriter and Content replace it with your's.
going by the documentation on folders here https://developers.google.com/drive/api/v2/folder , seems like you create folders by uploading an empty "file" with the content-type set to application/vnd.google-apps.folder.
here is documentation on how to upload files, in a simple way: https://developers.google.com/drive/api/v2/simple-upload
problem with that upload method is the the created file (or folder, in this case) won't have a name, it will just be called untitled<whatever>, so finally, here's documentation on how to rename files: https://developers.google.com/drive/api/v3/reference/files/update (or in this case, a folder)
putting it all together, you'll probably end up with something like:
<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array (
'Content-Type: application/vnd.google-apps.folder',
'Authorization: Bearer '.getAccessToken ( $credentials )
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => '', // "empty file"
CURLOPT_RETURNTRANSFER => 1
) );
try {
// this will create the folder, with no name
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
$id = $parsed ['id'];
// now to give the folder a name:
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . urlencode ( $id ),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode ( array (
'name' => 'the_folders_name'
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
} finally{
curl_close ( $ch );
}
var_dump ( $resp );
and finally, to move files inside this folder, send a PATCH request to https://www.googleapis.com/upload/drive/v3/files/<file_you_want_to_move_id> with the folder's id as the addParents parameter of the request body, eg something like:
<?php
try {
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files/' . urlencode ( $file_id ),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode ( array (
'addParents' => $folder_id,
'removeParents'=> 'root',
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
} finally{
curl_close ( $ch );
}
This will help You:
https://developers.google.com/drive/api/v3/folder
Creating a folder:
In the Drive API, a folder is essentially a file — one identified by the special folder MIME type application/vnd.google-apps.folder. You can create a new folder by inserting a file with this MIME type and a folder title. Do not include an extension when setting a folder title.
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'Invoices',
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $driveService->files->create($fileMetadata, array(
'fields' => 'id'));
printf("Folder ID: %s\n", $file->id);
Inserting a file in a folder:
To insert a file in a particular folder, specify the correct ID in the parents property of the file, as shown:
$folderId = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E';
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'photo.jpg',
'parents' => array($folderId)
));
$content = file_get_contents('files/photo.jpg');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
The parents property can be used when creating a folder as well to create a subfolder.
Moving files between folders:
To add or remove parents for an exiting file, use the addParents and removeParents query parameters on the files.update method.
Both parameters may be used to move a file from one folder to another, as shown:
$fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
$folderId = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E';
$emptyFileMetadata = new Google_Service_Drive_DriveFile();
// Retrieve the existing parents to remove
$file = $driveService->files->get($fileId, array('fields' => 'parents'));
$previousParents = join(',', $file->parents);
// Move the file to the new folder
$file = $driveService->files->update($fileId, $emptyFileMetadata, array(
'addParents' => $folderId,
'removeParents' => $previousParents,
'fields' => 'id, parents'));
See this if it is working. I have made changes like "name" => "", CURLOPT_CUSTOMREQUEST => 'POST',
function CreateGDFolder($credentials)
{
$ch = curl_init();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode ( array (
// Earlier it was title changed to name
"name" => "pets",
"mimeType" => "application/vnd.google-apps.folder"
) ),
// Earlier it was PATCH changed to post
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
$response=curl_exec($ch);
$response = json_decode($response, true);
print_r($response);
curl_close($ch);
}

Digest Authentication using Request PHP or any other in codeigniter

I have used
http://requests.ryanmccue.info/ and https://github.com/rmccue/Requests
I am using Request library, but any other library can also be suggested.
My code for CodeIgniter
class Home extends CI_Controller{
public function index(){
$this->load->library('PHPRequest');
$this->rest_client();
}
function rest_client(){
$user = 'myusername';
$pass = 'mypass';
$BaseApiUrl = 'myurl';
$headers = array('Accept' => 'application/json');
$options = array('auth' => new Requests_Auth_Basic(array($user, $pass)));
$request = Requests::get($BaseApiUrl, $headers, $options);
var_dump($request->status_code);
var_dump($request->body);
}
}
But I am getting the following error:
int(401) string(28) "HTTP Digest: Access denied. "
Using Curl PHP Now
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_VERBOSE => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false, // for https
CURLOPT_USERPWD => $username . ":" . $password,
CURLOPT_HTTPAUTH => CURLAUTH_DIGEST
);
$ch = curl_init();
curl_setopt_array( $ch, $options );
try {
$raw_response = curl_exec( $ch );
// validate CURL status
if(curl_errno($ch))
throw new Exception(curl_error($ch), 500);
// validate HTTP status code (user/password credential issues)
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status_code != 200)
throw new Exception("Response with Status Code [" . $status_code . "].", 500);
} catch(Exception $ex) {
if ($ch != null) curl_close($ch);
throw new Exception($ex);
}
if ($ch != null) curl_close($ch);
return json_decode($raw_response);

php Length Required HTTP Error 411. The request must be chunked or have a content length

I currently have a web server set up, but when I use this code, I get the error "Length Required HTTP Error 411. The request must be chunked or have a content length."
I'm unsure what's causing this. What this does is communicate with the servers of the game, and promote a user in a certain group on that game..
<?php
$group_id = $_GET['groupId'];
$new_role_set_id = $_GET['newRoleSetId'];
$target_user_id = $_GET['targetUserId'];
$login_user = 'username=BotUsername&password=BotPassword';
$file_path_rs = 'rs.txt';
$file_path_token = 'token.txt';
$current_rs = file_get_contents($file_path_rs);
$current_token = file_get_contents($file_path_token);
function getRS()
{
global $login_user, $file_path_rs;
$get_cookies = curl_init('https://www.roblox.com/newlogin');
curl_setopt_array($get_cookies,
array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array("Content-Length: " . strlen($login_user)),
CURLOPT_POSTFIELDS => $login_user
)
);
$rs = (preg_match('/(\.ROBLOSECURITY=.*?);/', curl_exec($get_cookies), $matches) ? $matches[1] : '');
file_put_contents($file_path_rs, $rs, true);
curl_close($get_cookies);
return $rs;
}
function changeRank($rs, $token)
{
global $group_id, $new_role_set_id, $target_user_id, $file_path_token;
$promote_user = curl_init("http://www.roblox.com/groups/api/change-member-rank?groupId=$group_id&newRoleSetId=$new_role_set_id&targetUserId=$target_user_id");
curl_setopt_array($promote_user,
array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => array("Cookie: $rs", "X-CSRF-TOKEN: $token")
)
);
$resp = curl_exec($promote_user);
$resp_header_size = curl_getinfo($promote_user, CURLINFO_HEADER_SIZE);
$resp_header = substr($resp, 0, $resp_header_size);
$resp_body = substr($resp, $resp_header_size);
if (preg_match('/GuestData/', $resp_header)) {
$resp_body = changeRank( getRS(), $token );
} else if (preg_match('/Token Validation Failed/', $resp_header)) {
$new_token = (preg_match('/X-CSRF-TOKEN: (\S+)/', $resp_header, $matches) ? $matches[1] : '');
file_put_contents($file_path_token, $new_token, true);
$resp_body = changeRank( $rs, $new_token );
}
curl_close($promote_user);
return $resp_body;
}
echo changeRank($current_rs, $current_token);

php curl multi init HTTP 401 Unauthorized

I have used a curl single init to issue an HTTP Get and all worked fine.
Now I tried to use a multi init (as I need to get multiple URLs) and I get a 401 message with "This request requires HTTP authentication" on the response to the Get.
Same Curl options where used on both cases.
Here is the code for th multi init and below it the single init function.
protected function _multiQueryRunkeeper($uri, $subscribersInfo,$acceptHeader) {
$curlOptions = array(
CURLOPT_URL => 'https://api.runkeeper.com' . $uri,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 8,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_HTTPGET => true
);
$curl_array = array();
$mh = curl_multi_init();
foreach ($subscribersInfo as $i => $subscriber) {
$curl_array[$i] = curl_init();
curl_setopt_array($curl_array[$i],$curlOptions);
curl_setopt($curl_array[$i], CURLOPT_HEADER,
array('Authorization: Bearer '.$subscriber['token'],
'Accept: application/vnd.com.runkeeper.' . $acceptHeader));
curl_multi_add_handle($mh,$curl_array[$i]);
}
$running = NULL;
do {
usleep(10000);
curl_multi_exec($mh,$running);
} while($running > 0);
$subscribersWorkoutFeed = array();
foreach($subscribersInfo as $i => $subscriber)
{
$subscribersWorkoutFeed[$i] = curl_multi_getcontent($curl_array[$i]);
curl_multi_remove_handle($mh, $curl_array[$i]);
}
curl_multi_close($mh);
return $subscribersWorkoutFeed;
}
protected function _singleQueryRunkeeper($uri, $subscriberToken,$acceptHeader) {
try{
// get fitness user's fitness activities from Runkeeper
$this->_curl = isset($this->_curl)? $this->_curl : curl_init();
$curlOptions = array(
CURLOPT_URL => 'https://api.runkeeper.com' . $uri,
CURLOPT_HTTPHEADER => array('Authorization: Bearer '.$subscriberToken,
'Accept: application/vnd.com.runkeeper.' . $acceptHeader),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 8,
CURLOPT_HTTPGET => true
);
curl_setopt_array($this->_curl,$curlOptions);
$response = curl_exec($this->_curl);
if($response == false) {
if (Zend_Registry::isRegistered('logger')) {
$logger = Zend_Registry::get('logger');
$logger->log('Curl error on _singleQueryRunkeeper: '
. curl_error($this->_curl), Zend_Log::INFO);
}
return null;
}
$data = Zend_Json::decode($response);
return($data);
} catch(Exception $e){
if (Zend_Registry::isRegistered('logger')) {
$logger = Zend_Registry::get('logger');
$logger->log('exception occured on getUsersLatestWorkoutsFromRK. Curl error'
. curl_error($this->_curl), Zend_Log::INFO);
}
}
}

Categories