Browse files

Initial commit

  • Loading branch information...
0 parents commit 98c0a6251cf5545de8a403da28b9c258c798aa91 @tboronczyk tboronczyk committed Aug 3, 2012
Showing with 911 additions and 0 deletions.
  1. +80 −0 authorize.php
  2. +41 −0 bootstrap.php
  3. BIN data/.DS_Store
  4. +46 −0 download.php
  5. +34 −0 index.php
  6. BIN lib/.DS_Store
  7. +170 −0 lib/dropbox/client.php
  8. +180 −0 lib/dropbox/rest.php
  9. +284 −0 lib/dropbox/session.php
  10. +37 −0 list.php
  11. +39 −0 upload.php
80 authorize.php
@@ -0,0 +1,80 @@
+<?php
+require_once "bootstrap.php";
+
+if (isset($access_token)) {
+ header("Location: ./");
+ exit;
+}
+
+try {
+ // Start a new Dropbox session
+ $session = new DropboxSession(
+ $config["dropbox"]["app_key"],
+ $config["dropbox"]["app_secret"],
+ $config["dropbox"]["access_type"]
+ );
+
+ // The user is redirected here by Dropbox after the authorization screen
+ if (!empty($_GET["oauth_token"]) && !empty($_GET["uid"])) {
+ $uid = $_GET["uid"];
+ $token = array(
+ "oauth_token" => $_GET["oauth_token"],
+ "oauth_token_secret" => ""
+ );
+
+ if (!empty($_SESSION["request_token"])) {
+ $token["oauth_token_secret"] = $_SESSION["request_token"]["oauth_token_secret"];
+ }
+
+ /**
+ * The access token is all you'll need for all future API requests on
+ * behalf of this user, so you should store it away for safe-keeping
+ * (even though we don't for this article). By storing the access
+ * token, you won't need to go through the authorization process again
+ * unless the user revokes access via the Dropbox website.
+ */
+ if ($access_token = $session->obtainAccessToken($token)) {
+ parse_str($access_token, $token);
+ $access_token = $token;
+ unset($token);
+
+ // The output ov var_export is similar to:
+ // array("oauth_token_secret" => "aaaa", "oauth_token" => "bbbb", "uid" => "123456")
+ $data = '<?php $access_token = ' . var_export($access_token, true) . ";";
+ if (file_put_contents($config["app"]["authfile"], $data) === false) {
+ throw new Exception("Unable save access token");
+ }
+
+ // Authorized, redirect to index
+ header("Location: index.php");
+ exit;
+ }
+ // The access token should be stored somewhere to be reused until
+ // it expires or is revoked by the user
+ }
+ else {
+ // We must start a new authorization cycle
+ if ($request_token = $session->obtainRequestToken()) {
+ // The request token must be subdivided in the two components
+ // oauth_token_secret and oauth_token and kept in the session
+ // because is needed in the next step
+ parse_str($request_token, $token);
+ $_SESSION["request_token"] = $token;
+
+ $url = $session->buildAuthorizeURL(
+ $token,
+ $config["app"]["root"] . basename($_SERVER["SCRIPT_NAME"]),
+ "en-US");
+
+ // Display or redirect to auth URL
+ echo '<p>Please visit <a href="' . $url . '">Dropbox</a> and authorize this application.</p>';
+ exit;
+ }
+ else {
+ throw new Exception("Unable to get request token");
+ }
+ }
+}
+catch (Exception $e) {
+ echo $e->getMessage();
+}
41 bootstrap.php
@@ -0,0 +1,41 @@
+<?php
+// Prevent calling this script directly
+if ($_SERVER["SCRIPT_FILENAME"] == __FILE__) {
+ exit("Access denied!");
+}
+
+// app settings
+$config = array();
+$config["dropbox"]["app_key"] = "1uxmkgiimkmevgq";
+$config["dropbox"]["app_secret"] = "a7v9u2a7bwa0ubv";
+// ACCESS_TYPE should be "dropbox" or "app_folder"
+$config["dropbox"]["access_type"] = "app_folder";
+
+$config["app"]["root"] = ((!empty($_SERVER["HTTPS"])) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . "/mydropbox/";
+$config["app"]["datadir"] = dirname(__FILE__) . "/data";
+$config["app"]["authfile"] = $config["app"]["datadir"] . "/auth.php";
+
+// turn on error reporting for development
+error_reporting(E_ALL|E_STRICT);
+ini_set("display_errors", true);
+
+// environment check
+if (!is_dir($config["app"]["datadir"]) || !is_writable($config["app"]["datadir"])) {
+ exit("The data directory is not writeable!");
+}
+if (file_exists($config["app"]["authfile"]) && !is_writable($config["app"]["authfile"])) {
+ exit("The auth storage file is not writeable!");
+}
+
+// Load libraries and start a new session
+require_once "lib/dropbox/rest.php";
+require_once "lib/dropbox/session.php";
+require_once "lib/dropbox/client.php";
+
+session_start();
+
+// Search for a previously obtained access token
+$access_token = null;
+if (file_exists($config["app"]["authfile"])) {
+ include_once $config["app"]["authfile"];
+}
BIN data/.DS_Store
Binary file not shown.
46 download.php
@@ -0,0 +1,46 @@
+<?php
+require_once "bootstrap.php";
+
+if (!isset($access_token)) {
+ header("Location: authorize.php");
+ exit;
+}
+
+try {
+ // Start a new Dropbox session
+ // The access token should exist
+ // The session should verify if the token is valid and throw an exception
+ $session = new DropboxSession(
+ $config["dropbox"]["app_key"],
+ $config["dropbox"]["app_secret"],
+ $config["dropbox"]["access_type"],
+ $access_token
+ );
+ $client = new DropboxClient($session);
+
+ $path = (!empty($_GET["path"])) ? $_GET["path"] : "/test.png";
+ $dest = $config["app"]["datadir"] . "/" . basename($path);
+
+ // Download a file
+ if ($file = $client->getFile($path, $dest)) {
+ if (!empty($dest)) {
+ unset($file["data"]);
+ echo "<p>File saved to: <code>" . $dest . "</code></p>";
+ echo "<pre>" . print_r($file, true) . "</pre>";
+ }
+ else {
+ header("Content-type: " . $file["mime"]);
+ echo $file["data"];
+ exit;
+ }
+ }
+}
+catch (Exception $e) {
+ echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
+ if ($e->getCode() == 401) {
+ // Remove auth file
+ unlink($config["app"]["authfile"]);
+ // Re auth
+ echo '<p><a href="authorize.php">Click Here to re-authenticate</a></p>';
+ }
+}
34 index.php
@@ -0,0 +1,34 @@
+<?php
+require_once "bootstrap.php";
+
+if (!isset($access_token)) {
+ header("Location: ./authorize.php");
+ exit;
+}
+try {
+ // Start a new Dropbox session
+ $session = new DropboxSession(
+ $config["dropbox"]["app_key"],
+ $config["dropbox"]["app_secret"],
+ $config["dropbox"]["access_type"],
+ $access_token
+ );
+
+ $client = new DropboxClient($session);
+
+ // Retrieve account info
+ if ($info = $client->accountInfo()) {
+ echo "<p>Account Details for User <strong>" . $info["display_name"] . "</strong> - ";
+ echo '<a href="list.php">View Files</a></p>';
+ echo "<pre>" . print_r($info, true) . "</pre>";
+ }
+}
+catch (Exception $e) {
+ echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
+ if ($e->getCode() == 401) {
+ // Remove auth file
+ unlink($config["app"]["authfile"]);
+ // Re auth
+ echo '<p><a href="authorize.php">Click Here to re-authenticate</a></p>';
+ }
+}
BIN lib/.DS_Store
Binary file not shown.
170 lib/dropbox/client.php
@@ -0,0 +1,170 @@
+<?php
+/**
+ * An API client for Dropbox
+ */
+class DropboxClient
+{
+ protected $Session = null;
+
+ /**
+ * Common API URL
+ * @var
+ */
+ protected $dropboxAPIURL = "https://api.dropbox.com/1";
+
+ /**
+ * Content-related API URL
+ * @var
+ */
+ protected $dropboxContentAPIURL = "https://api-content.dropbox.com/1";
+
+ /**
+ * Constructor
+ *
+ * Initialize the client wit a valid session
+ *
+ * @param object $session
+ * @return void
+ */
+ function __construct( DropboxSession $session) {
+ $this->Session = $session;
+ $this->accessType = $this->Session->getAccessType();
+ }
+
+ /**
+ * Retrieve information from the user's account
+ *
+ * @return string
+ */
+ public function accountInfo() {
+ $response = $this->Session->fetch("GET", $this->dropboxAPIURL, "/account/info");
+ return $response["body"];
+ }
+
+ /**
+ * Fetch metadata for a file or folder
+ *
+ * The path is relative to a root (ex /<root>/<path>) that can be 'sandbox' or 'dropbox'
+ *
+ * @param string $path The path of the resource to fetch
+ * @param boolean $list Whether to list all contained files (applies only to folders)
+ * @param int $fileLimit Max items returned with the listing mode
+ * @param string $hash Hash value for a previous call
+ * @param string $revision Specific revision for the object
+ * @param bool $includeDeleted Whether to include deleted files and folders
+ * @return string
+ */
+ public function metadata($path, $list = true, $fileLimit = 10000, $hash = null, $revision = null, $includeDeleted = false) {
+ // Prepare argument list
+ $args = array(
+ "file_limit" => $fileLimit,
+ "hash" => $hash,
+ "list" => (int) $list,
+ "include_deleted" => (int) $includeDeleted,
+ "rev" => $revision
+ );
+
+ // Prepend the right access string to the desired path
+ if ("dropbox" == $this->accessType) {
+ $path = "dropbox" . $path;
+ }
+ else {
+ $path = "sandbox" . $path;
+ }
+
+ // Execute
+ $response = $this->Session->fetch("GET", $this->dropboxAPIURL, "/metadata/" . $path, $args);
+ return $response["body"];
+ }
+
+ /**
+ * Downloads a file from the user's Dropbox
+ *
+ * The path is relative to a root (ex /<root>/<path>) that can be 'sandbox' or 'dropbox'
+ *
+ * @param string $path The path of the resource to fetch
+ * @param string $outFile The download path for the file
+ * @param string $revision Specific revision for the object
+ * @return array
+ */
+ public function getFile($path, $outFile = null, $revision = null) {
+
+ $args = array();
+ if (!empty($revision)) {
+ $args["rev"] = $revision;
+ }
+
+ // Prepend the right access string to the desired path
+ if ("dropbox" == $this->accessType) {
+ $path = "dropbox" . $path;
+ }
+ else {
+ $path = "sandbox" . $path;
+ }
+
+ // Get the raw response body
+ $response = $this->Session->fetch("GET", $this->dropboxContentAPIURL, "/files/" . $path, $args, true);
+
+ if ($outFile != null) {
+ if (file_put_contents($outFile, $response["body"]) === false) {
+ throw new Exception("Unable to write file '$outfile'");
+ }
+ }
+
+ return array(
+ "name" => ($outFile) ? $outFile : basename($path),
+ "mime" => $response["headers"]["content-type"],
+ "meta" => json_decode($response["headers"]["x-dropbox-metadata"]),
+ "data" => $response["body"]
+ );
+ }
+
+ /**
+ * Upload a file to the user's Dropbox
+ *
+ * The path is relative to a root (ex /<root>/<path>) that can be 'sandbox' or 'dropbox'
+ *
+ * @param string $file The full path of the file to upload
+ * @param string $path The destination path (default = root)
+ * @param string $name Specifies a different name for the uploaded file
+ * @param boolean $overwrite Overwrite any existing file
+ * @return array
+ */
+ public function putFile($file, $path = "/", $name = null, $overwrite = true) {
+ // Check for file existence before
+ if (!file_exists($file)) {
+ throw new Exception("Local file '" . $file . "' does not exist");\
+ }
+
+ // Dropbox has a 150MB limit upload for the API
+ if (filesize($file) > 157286400) {
+ throw new Exception("File exceeds 150MB upload limit");
+ }
+
+ $args = array(
+ "overwrite" => (int) $overwrite,
+ "inputfile" => $file
+ );
+
+ // Prepend the right access string to the desired path
+ if ("dropbox" == $this->accessType) {
+ $path = "dropbox" . $path;
+ }
+ else {
+ $path = "sandbox" . $path;
+ }
+
+ // Determine the full path
+ if (!empty($name)) {
+ $path = dirname($path) . "/" . $name;
+ }
+ else {
+ $path .= basename($file);
+ }
+
+ // Get the raw response body
+ $response = $this->Session->fetch("PUT", $this->dropboxContentAPIURL, "/files_put/" . $path, $args);
+
+ return $response["body"];
+ }
+}
180 lib/dropbox/rest.php
@@ -0,0 +1,180 @@
+<?php
+/**
+ * A simple JSON REST request abstraction layer that is used by the DropboxClient and DropboxSession modules.
+ */
+class DropboxRESTClient
+{
+ /**
+ * Handle for the current cURL session
+ * @var
+ */
+ private $curl = null;
+
+ /**
+ * Default cURL settings
+ * @var
+ */
+ protected $curlDefaults = array(
+ // BOOLEANS
+ CURLOPT_AUTOREFERER => true, // Update referer on redirects
+ CURLOPT_FAILONERROR => false, // Return false on HTTP code > 400
+ CURLOPT_FOLLOWLOCATION => true, // Follow redirects
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_FRESH_CONNECT => true, // Don't use cached connection
+ CURLOPT_FORBID_REUSE => true, // Close connection
+
+ // INTEGERS
+ CURLOPT_TIMEOUT => 10, // cURL timeout
+ CURLOPT_CONNECTTIMEOUT => 10, // Connection timeout
+
+ // STRINGS
+ CURLOPT_ENCODING => "", // "identity", "deflate", and "gzip"
+ CURLOPT_USERAGENT => "Dropbox REST PHP Client/1.0"
+ );
+
+ /**
+ * Basic constructor
+ *
+ * Checks for cURL and initialize options
+ * @return void
+ */
+ function __construct() {
+ if (!function_exists("curl_init")) {
+ throw new Exception("cURL is not installed on this system");
+ }
+
+ $this->curl = curl_init();
+ if (!is_resource($this->curl) || !isset($this->curl)) {
+ throw new Exception("Unable to create cURL session");
+ }
+
+ $success = curl_setopt_array( $this->curl, $this->curlDefaults );
+ if ($success !== true) {
+ throw new Exception("cURL Error: " . curl_error($this->curl));
+ }
+ }
+
+ /**
+ * Closes the current cURL connection
+ */
+ public function close() {
+ @curl_close($this->curl);
+ }
+
+ function __destruct() {
+ $this->close();
+ }
+
+ /**
+ * Returns last error message
+ * @return string Error message
+ */
+ public function error() {
+ return curl_error($this->curl);
+ }
+
+ /**
+ * Returns last error code
+ * @return int
+ */
+ public function errno() {
+ return curl_errno($this->curl);
+ } // end function
+
+ public function get($url, $headers = array(), $raw = false) {
+ return $this->request($url, "GET", $headers, null, null, $raw);
+ }
+
+ public function post($url, $params = array(), $headers = array(), $raw = false) {
+ return $this->request($url, "POST", $headers, $params, null, $raw);
+ }
+
+ public function put($url, $body, $headers = array(), $raw = false) {
+ return $this->request($url, "PUT", $headers, null, $body, $raw);
+ }
+
+ public function request($url, $method = "GET", $headers = array(), $params = array(), $body = null, $raw = false) {
+ // Set the URL
+ curl_setopt($this->curl, CURLOPT_URL, $url);
+
+ // Set the method and related options
+ switch ($method) {
+ case "PUT":
+ curl_setopt($this->curl, CURLOPT_PUT, true);
+
+ //The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
+ if ($f = @fopen($body, "r")) {
+ curl_setopt($this->curl, CURLOPT_INFILE, $f);
+ curl_setopt($this->curl, CURLOPT_INFILESIZE, filesize($body));
+ $headers["Content-Length"] = filesize($body);
+ }
+ else {
+ throw new Exception("Unable to load resource '$body'");
+ }
+ break;
+
+ case "POST":
+ curl_setopt($this->curl, CURLOPT_POST, true);
+ break;
+
+ case "GET":
+ default:
+ break;
+ }
+
+ // Set the headers
+ if (!empty($headers) && is_array($headers)) {
+ // An array of HTTP header fields to set, in the format
+ //array("Content-type: text/plain", "Content-length: 100")
+ curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
+ }
+
+ if (!empty($params) && is_array($params)) {
+ curl_setopt($this->curl, CURLOPT_POSTFIELDS, $params);
+ }
+
+ // Retrieve HTTP response headers
+ curl_setopt($this->curl, CURLOPT_HEADER, true);
+
+ $response = curl_exec($this->curl);
+ $info = curl_getinfo($this->curl);
+
+ // Close any open resource handle
+ if (isset($f) && is_resource($f)) {
+ @fclose($f);
+ }
+
+ $status = $info["http_code"];
+ $header = substr($response, 0, $info["header_size"]);
+ $body = substr( $response, $info["header_size"]);
+
+ if ($raw !== true) {
+ $body = json_decode($body, true); // The second parameter set to true returns objects as associative arrays
+ }
+
+ if ($status > 400) {
+
+ if ($raw === true) {
+ $body = json_decode($body, true);
+ }
+
+ $error = (!empty($body['error'])) ? $body["error"] : "Unknown error";
+ throw new Exception($error, $status);
+ }
+
+ // Parse response headers
+ $response_headers = array();
+ $lines = explode("\r\n", $header);
+ array_shift($lines);
+ foreach ($lines as $line) {
+ // Skip empty lines
+ if ("" == trim($line)) {
+ continue;
+ }
+ @list($k, $v) = explode(": ", $line, 2);
+ $response_headers[strtolower($k)] = $v;
+ }
+
+ return array("code" => $status, "body" => $body, "headers" => $response_headers);
+ }
+}
284 lib/dropbox/session.php
@@ -0,0 +1,284 @@
+<?php
+/**
+ *
+ */
+class DropboxSession extends DropboxRESTClient
+{
+ /**
+ * Application Key
+ * @var
+ */
+ private $key;
+
+ /**
+ * Application Secret
+ * @var
+ */
+ private $secret;
+
+ /**
+ * Application Access Type
+ * @var
+ */
+ private $access;
+
+ /**
+ * Dropbox token
+ * @var
+ */
+ private $token = null;
+
+ /**
+ * @var
+ */
+ private $oauthSignatureMethod = "HMAC-SHA1";
+
+ /**
+ * OAuth API version implemented by this class
+ * @var
+ */
+ private $oauthVersion = "1.0";
+
+ /**
+ * @var
+ */
+ private $oauthBaseURL = "https://api.dropbox.com/1";
+
+ /**
+ * Default constructor
+ *
+ * @param string $key Application Key provided by Dropbox
+ * @param string $secret Application Secret provided by Dropbox
+ * @param string $access Application access type (can be 'dropbox' or 'app_folder')
+ * @param array $token Previously obteined token, if exists
+ * @return void
+ */
+ function __construct($key, $secret, $access, $token = null) {
+ parent::__construct();
+
+ $this->key = $key;
+ $this->secret = $secret;
+ $this->access = $access;
+
+ if ($token != null) {
+ $this->token = $token;
+ }
+ }
+
+ /**
+ * Gets the access type allowed for this session
+ *
+ * @return string
+ */
+ public function getAccessType() {
+ return $this->access;
+ }
+
+ /**
+ * URL encode each parameter to RFC3986 for use in the base string
+ *
+ * @param array $params Associative array of parameters to encode
+ * @return array
+ */
+ protected function encodeParams($params) {
+ ksort($params);
+ $encoded = array();
+
+ foreach ($params as $param => $value) {
+ if ($value !== null) {
+ $encoded[] = rawurlencode($param) . '=' . rawurlencode($value);
+ }
+ else {
+ unset($params[$param]);
+ }
+ }
+
+ return $encoded;
+ }
+
+ /**
+ * Generates OAuth signature for a request
+ *
+ * @param string $method The HTTP method of the request
+ * @param string $url The destination URL
+ * @param array $params The parameters to send
+ * @return string
+ */
+ protected function getSignature($method, $url, $params) {
+
+ $encoded = $this->encodeParams($params);
+
+ $sigBase = $method . "&" . rawurlencode($url) . "&";
+
+ $sigBase .= rawurlencode(implode("&", $encoded));
+
+ if (!empty($this->token)) {
+ // Signature key for all the other requests
+ $sigKey = $this->secret . "&" . $this->token["oauth_token_secret"];
+ }
+ else {
+ // Signature key for temporary token requests
+ $sigKey = $this->secret . "&";
+ }
+
+ // Compute signature
+ $oauthSig = base64_encode(hash_hmac("sha1", $sigBase, $sigKey, true));
+
+ return $oauthSig;
+
+ }
+
+ /**
+ * Request a temparary unprivileged request token from Dropbox
+ *
+ * @return string The token
+ */
+ public function obtainRequestToken() {
+ $requestTokenUrl = $this->oauthBaseURL . "/oauth/request_token";
+ $oauthTimestamp = time();
+ $nonce = md5(mt_rand());
+
+ $params = array(
+ "oauth_consumer_key" => $this->key,
+ "oauth_nonce" => $nonce,
+ "oauth_signature_method" => $this->oauthSignatureMethod,
+ "oauth_timestamp" => $oauthTimestamp,
+ "oauth_version" => $this->oauthVersion,
+ );
+ //ksort($params);
+
+ // Generate a signature for the request parameters
+ $oauthSig = $this->getSignature("GET", $requestTokenUrl, $params);
+
+ // Enqueue the signature to the request
+ $params["oauth_signature"] = $oauthSig;
+
+ // Build the full URL and call the API
+ $query = http_build_query($params, "", "&");
+ $response = $this->get($requestTokenUrl . "?" . $query, null, true);
+
+ return $response["body"];
+
+ }
+
+ /**
+ * Builds the URL needed to authorize the application
+ *
+ * @param string $token The temporary unprivileged access token
+ * @param string $callback An URL to redirect the user when the authorization is granted
+ * @param string $locale Locale of the user/app
+ * @return string
+ */
+ public function buildAuthorizeURL($token, $callback = null, $locale = "en-US") {
+
+ $url = "https://www.dropbox.com/1/oauth/authorize?" . http_build_query($token, "", "&");
+
+ if (!empty($callback)) {
+ $url .= "&oauth_callback=" . rawurlencode($callback);
+ }
+
+ if (!empty($locale)) {
+ $url .= "&locale=" . rawurlencode($locale);
+ }
+
+ return $url;
+ }
+
+ /**
+ * Request a permanent access token
+ *
+ * @param array $token The token returned from the authorization URL
+ * @return array
+ */
+ public function obtainAccessToken($token) {
+
+ $this->token = $token;
+
+ $nonce = md5(mt_rand());
+
+ $requestTokenUrl = $this->oauthBaseURL . "/oauth/access_token";
+
+ $oauthTimestamp = time();
+
+ // Prepare the standard request parameters
+ $params = array(
+ "oauth_consumer_key" => $this->key,
+ "oauth_token" => $this->token["oauth_token"],
+ "oauth_signature_method" => $this->oauthSignatureMethod,
+ "oauth_version" => $this->oauthVersion,
+ // Generate nonce and timestamp if signature method is HMAC-SHA1
+ "oauth_timestamp" => ($this->oauthSignatureMethod == "HMAC-SHA1") ? time() : null,
+ "oauth_nonce" => ($this->oauthSignatureMethod == "HMAC-SHA1") ? $nonce : null
+ );
+ //ksort($params);
+
+ $oauthSig = $this->getSignature("POST", $requestTokenUrl, $params, $sigKey);
+
+ $params["oauth_signature"] = $oauthSig;
+
+ $response = $this->post($requestTokenUrl, $params, null, true);
+ return $response["body"];
+
+ }
+
+ /**
+ *
+ * @param string $method The HTTP method
+ * @param string $url The Dropbox base API URL
+ * @param string $api The Dropbox API method to call
+ * @param string $args Arguments to pass
+ * @param boolean $raw If true doesn't decode JSON data
+ */
+ public function fetch($method, $url, $api, $args = array(), $raw = false) {
+
+ $token = $this->token;
+ $nonce = ($this->oauthSignatureMethod == "HMAC-SHA1") ? md5(mt_rand()) : null;
+ $oauthTimestamp = ($this->oauthSignatureMethod == "HMAC-SHA1") ? time() : null;
+
+ // Prepare the standard request parameters
+ $params = array(
+ "oauth_consumer_key" => $this->key,
+ "oauth_token" => $token["oauth_token"],
+ "oauth_signature_method" => $this->oauthSignatureMethod,
+ "oauth_version" => $this->oauthVersion,
+ // Generate nonce and timestamp if signature method is HMAC-SHA1
+ "oauth_timestamp" => $oauthTimestamp,
+ "oauth_nonce" => $nonce
+ );
+
+ $inputFile = null;
+ if ("PUT" == $method && $args["inputfile"]) {
+ $inputFile = $args["inputfile"];
+ unset($args["inputfile"]);
+ }
+
+ // Merge with the additional request parameters
+ $params = array_merge($params, $args);
+ //ksort($params);
+
+ $oauthSig = $this->getSignature($method, $url . $api, $params);
+
+ $params["oauth_signature"] = $oauthSig;
+
+ $query = "";
+
+ switch ($method) {
+ case "POST":
+ $response = $this->post($url . $api, $params, null, $raw);
+ break;
+
+ case "PUT":
+ $query = "?" . http_build_query($params, "", "&");
+ $response = $this->put($url . $api . $query, $inputFile, null, $raw);
+ break;
+
+ case "GET":
+ default:
+ $query = "?" . http_build_query($params, "", "&");
+ $response = $this->get($url . $api . $query, null, $raw);
+ break;
+ }
+
+ return $response;
+ }
+}
37 list.php
@@ -0,0 +1,37 @@
+<?php
+require_once "bootstrap.php";
+
+if (!isset($access_token)) {
+ header("Location: authorize.php");
+ exit;
+}
+
+try {
+ // Start a new Dropbox session
+ // The access token should be defined
+ // The session should verify if the token is valid and throw an exception
+ $session = new DropboxSession(
+ $config["dropbox"]["app_key"],
+ $config["dropbox"]["app_secret"],
+ $config["dropbox"]["access_type"],
+ $access_token
+ );
+ $client = new DropboxClient($session);
+
+ $path = (!empty($_GET["path"])) ? $_GET["path"] : "/";
+
+ // List contents of home directory
+ if ($home = $client->metadata($path)) {
+ echo "<p>Metadata content for <code>" . $path . "</code></p>";
+ echo "<pre>" . print_r($home, true) . "</pre>";
+ }
+}
+catch (Exception $e) {
+ echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
+ if ($e->getCode() == 401) {
+ // Remove auth file
+ unlink($config["app"]["authfile"]);
+ // Re auth
+ echo '<p><a href="authorize.php">Click Here to re-authenticate</a></p>';
+ }
+}
39 upload.php
@@ -0,0 +1,39 @@
+<?php
+require_once "bootstrap.php";
+
+if (!isset($access_token)) {
+ header("Location: authorize.php");
+ exit;
+}
+
+try {
+ // Start a new Dropbox session
+ // The access token should be passed
+ // The session should verify if the token is valid and throw an exception
+ $session = new DropboxSession(
+ $config["dropbox"]["app_key"],
+ $config["dropbox"]["app_secret"],
+ $config["dropbox"]["access_type"],
+ $access_token
+ );
+
+ $client = new DropboxClient($session);
+
+ $src = $config["app"]["datadir"] . "/test.png";
+ $dest = "/";
+
+ // Upload a file
+ if ($response = $client->putFile($src, $dest)) {
+ echo "<p>File successfully uploaded!</p>";
+ echo "<pre>" . print_r($response, true) . "</pre>";
+ }
+}
+catch (Exception $e) {
+ echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
+ if ($e->getCode() == 401) {
+ // Remove auth file
+ unlink($config["app"]["authfile"]);
+ // Re auth
+ echo '<p><a href="authorize.php">Click Here to re-authenticate</a></p>';
+ }
+}

0 comments on commit 98c0a62

Please sign in to comment.