Skip to content

Instantly share code, notes, and snippets.

@battis
Created July 22, 2013 13:26
Show Gist options
  • Save battis/6053792 to your computer and use it in GitHub Desktop.
Save battis/6053792 to your computer and use it in GitHub Desktop.
<html><body><pre>
<?php
require_once('.ignore.canvas-authentication.inc.php');
require_once('Pest.php');
/**
* Generate the Canvas API authorization header
**/
function buildCanvasAuthorizationHeader() {
return array ('Authorization' => 'Bearer ' . CANVAS_API_TOKEN);
}
/**
* Pass-through a Pest request with added Canvas authorization token
**/
$PEST = new Pest(CANVAS_API_URL);
function callCanvasApi($verb, $url, $data) {
global $PEST;
$json = null;
echo "\nSTART callCanvasApi()\n";
echo "$verb\n";
echo "$url\n";
print_r($data);
try {
$json = $PEST->$verb($url, $data, buildCanvasAuthorizationHeader());
} catch (Exception $e) {
echo 'API ERROR';
print_r($e->getMessage());
exit;
}
echo "\nAPI RESPONSE\n";
print_r($json);
return $json;
}
/**
* build a file path out of component directories and filenames
**/
function buildPath() {
$args = func_get_args();
$path = '';
foreach ($args as $arg) {
if (strlen($path)) {
$path .= "/$arg";
} else {
$path = $arg;
}
}
return $path;
}
$localPath = "/var/www/project/canvas/api";
$fileName = 'test.txt';
$fileInfo['name'] = $fileName;
$fileInfo['size'] = filesize(buildPath($localPath, $fileName));
$fileInfo['path'] = '';
$json = callCanvasApi('post', "/courses/903/files",
array(
'name' => $fileInfo['name'],
'size' => $fileInfo['size'],
//'parent_folder_path' => $fileInfo['path'],
'on_duplicate' => 'rename'
)
);
$fileUpload = json_decode($json, true);
echo "\nAPI RESPONSE (FORMATTED)\n";
print_r($fileUpload);
if ($fileUpload) {
$uploadRequest = new Pest($fileUpload['upload_url']);
$uploadParams = $fileUpload['upload_params'];
$uploadParams['file'] = '@' . buildPath($localPath, $fileName);
$response = null;
try {
echo "\nSTART uploadRequest->post({$fileUpload['upload_url']})\n";
print_r($uploadParams);
$response = $uploadRequest->post('', $uploadParams);
} catch (Exception $e) {
echo "\nAPI ERROR\n";
print_r($e->getMessage());
exit;
}
echo "\nAPI RESPONSE\n";
echo "$response\n";
} else {
echo 'PROBLEM STARTING FILE UPLOAD';
exit;
}
echo "END OF SCRIPT\n";
?></pre></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment