package.xml0000644000076500000240000002311312023301616011625 0ustar joestaff Dropbox pear.dropbox-php.com Dropbox API library for PHP Dropbox API library for PHP. Requires oauth and json Joe Constant lazyguru lazyguru@jofee.com yes Naoki Sawada nao-pon yes Evan Kaufman EvanK yes Evert Pot evert evert@rooftopsolutions.nl no 2012-09-10 1.0.0 1.0.0 stable stable MIT - Added composer support - PR-13 - DropBox API returns 500 errors rarely. For example, when the thumbnail of the broken picture is acquired etc. - PR-8 - Methods delta, media, and copy_ref plus additional fixes 5.2 1.4.0 HTTP_OAuth pear.php.net 0.1.18 oauth 0.1.0 0.1.0 alpha alpha 2010-05-08 MIT First release 0.1.1 0.1.0 alpha alpha 2010-05-08 MIT Automatically trimming double slashes from path. Fixed error output 0.1.2 0.1.0 alpha alpha 2010-05-09 MIT Uploading now works 0.2.0 0.2.0 alpha alpha 2010-05-10 MIT Added support for a callback url, for a more streamlined user experience 0.3.0 0.3.0 alpha alpha 2010-07-20 MIT There's now a choice between PEAR's HTTP_OAuth and the OAuth PECL extension 0.4.0 0.4.0 alpha alpha 2010-08-04 MIT Support for creating new accounts. Support for 'token' api call, for easy authentication. Moved the responsibility of storing/retrieving oauth tokens to the user. Proven to be much for flexible. A lot more examples. Consistent error handling between PECL extension and PEAR package. Fixed responses in the API. Fixed retrieval of Thumbnails. Fixed retrieval of hash-based getMetaData. 0.4.1 0.4.1 alpha alpha 2011-06-22 MIT Fixes for the following issues: Issue #10 - spaces in file name for getFile Issue #13 - spaces in file name for putFile (and move) Issue #15 - putFile always returns true Issue #21 - spaces in filename (for getMetaData) 0.4.2 0.4.2 alpha alpha 2011-07-20 MIT Fixes for the following issues: Issue #25 - Patch for /Dropbox/API.php / Error using putfile Issue #27 - Wordpress OAuth Support 0.4.3 0.4.3 alpha alpha 2011-09-04 MIT Issue #28 - Oauth Curl class based on Wordpress class Issue #30 - Can't open files with tilde in the name Issue #34 - Change API URLs to use HTTPS Issue #35 - Change hard-coded API URLs to use a class constant 0.4.4 0.4.4 alpha alpha 2011-09-26 MIT - Added useSSL flag to constructor to allow turning off SSL use - Added code to turn off SSL validation during OAuth calls 0.4.5 0.4.5 alpha alpha 2011-10-31 MIT - Updated to work with Dropbox API version 1. - Some PHPUnit tests 0.5.0 0.5.0 beta beta 2012-01-14 MIT - Minor bug fixes - Added share method from Issue #42 - Added search method from Issue #42 - Added ant build script and phpunit config file - Updated status to "Beta" 0.5.1 0.5.1 beta beta 2012-01-14 MIT - Fixed a packaging issue 1.0.0 1.0.0 stable stable 2012-09-10 MIT - Added composer support - PR-13 - DropBox API returns 500 errors rarely. For example, when the thumbnail of the broken picture is acquired etc. - PR-8 - Methods delta, media, and copy_ref plus additional fixes Dropbox-1.0.0/LICENSE0000644000076500000240000000204512023301616012565 0ustar joestaffCopyright (c) 2010 Rooftop Solutions Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Dropbox-1.0.0/Dropbox/API.php0000644000076500000240000003153512023301616014325 0ustar joestaffoauth = $oauth; $this->root = $root; $this->useSSL = $useSSL; if (!$this->useSSL) { throw new Dropbox_Exception('Dropbox REST API now requires that all requests use SSL'); } } /** * Returns information about the current dropbox account * * @return stdclass */ public function getAccountInfo() { $data = $this->oauth->fetch($this->api_url . 'account/info'); return json_decode($data['body'],true); } /** * Returns a file's contents * * @param string $path path * @param string $root Use this to override the default root path (sandbox/dropbox) * @return string */ public function getFile($path = '', $root = null) { if (is_null($root)) $root = $this->root; $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); $result = $this->oauth->fetch($this->api_content_url . 'files/' . $root . '/' . ltrim($path,'/')); return $result['body']; } /** * Uploads a new file * * @param string $path Target path (including filename) * @param string $file Either a path to a file or a stream resource * @param string $root Use this to override the default root path (sandbox/dropbox) * @return bool */ public function putFile($path, $file, $root = null) { $directory = dirname($path); $filename = basename($path); if($directory==='.') $directory = ''; $directory = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($directory)); $filename = str_replace('~', '%7E', rawurlencode($filename)); if (is_null($root)) $root = $this->root; if (is_string($file)) { $file = fopen($file,'rb'); } elseif (!is_resource($file)) { throw new Dropbox_Exception('File must be a file-resource or a string'); } $result=$this->multipartFetch($this->api_content_url . 'files/' . $root . '/' . trim($directory,'/'), $file, $filename); if(!isset($result["httpStatus"]) || $result["httpStatus"] != 200) throw new Dropbox_Exception("Uploading file to Dropbox failed"); return true; } /** * Copies a file or directory from one location to another * * This method returns the file information of the newly created file. * * @param string $from source path * @param string $to destination path * @param string $root Use this to override the default root path (sandbox/dropbox) * @return stdclass */ public function copy($from, $to, $root = null) { if (is_null($root)) $root = $this->root; $response = $this->oauth->fetch($this->api_url . 'fileops/copy', array('from_path' => $from, 'to_path' => $to, 'root' => $root)); return json_decode($response['body'],true); } /** * Creates a new folder * * This method returns the information from the newly created directory * * @param string $path * @param string $root Use this to override the default root path (sandbox/dropbox) * @return stdclass */ public function createFolder($path, $root = null) { if (is_null($root)) $root = $this->root; // Making sure the path starts with a / $path = '/' . ltrim($path,'/'); $response = $this->oauth->fetch($this->api_url . 'fileops/create_folder', array('path' => $path, 'root' => $root),'POST'); return json_decode($response['body'],true); } /** * Deletes a file or folder. * * This method will return the metadata information from the deleted file or folder, if successful. * * @param string $path Path to new folder * @param string $root Use this to override the default root path (sandbox/dropbox) * @return array */ public function delete($path, $root = null) { if (is_null($root)) $root = $this->root; $response = $this->oauth->fetch($this->api_url . 'fileops/delete', array('path' => $path, 'root' => $root)); return json_decode($response['body']); } /** * Moves a file or directory to a new location * * This method returns the information from the newly created directory * * @param mixed $from Source path * @param mixed $to destination path * @param string $root Use this to override the default root path (sandbox/dropbox) * @return stdclass */ public function move($from, $to, $root = null) { if (is_null($root)) $root = $this->root; $response = $this->oauth->fetch($this->api_url . 'fileops/move', array('from_path' => rawurldecode($from), 'to_path' => rawurldecode($to), 'root' => $root)); return json_decode($response['body'],true); } /** * Returns file and directory information * * @param string $path Path to receive information from * @param bool $list When set to true, this method returns information from all files in a directory. When set to false it will only return infromation from the specified directory. * @param string $hash If a hash is supplied, this method simply returns true if nothing has changed since the last request. Good for caching. * @param int $fileLimit Maximum number of file-information to receive * @param string $root Use this to override the default root path (sandbox/dropbox) * @return array|true */ public function getMetaData($path, $list = true, $hash = null, $fileLimit = null, $root = null) { if (is_null($root)) $root = $this->root; $args = array( 'list' => $list, ); if (!is_null($hash)) $args['hash'] = $hash; if (!is_null($fileLimit)) $args['file_limit'] = $fileLimit; $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); $response = $this->oauth->fetch($this->api_url . 'metadata/' . $root . '/' . ltrim($path,'/'), $args); /* 304 is not modified */ if ($response['httpStatus']==304) { return true; } else { return json_decode($response['body'],true); } } /** * A way of letting you keep up with changes to files and folders in a user's Dropbox. You can periodically call /delta to get a list of "delta entries", which are instructions on how to update your local state to match the server's state. * * This method returns the information from the newly created directory * * @param string $cursor A string that is used to keep track of your current state. On the next call pass in this value to return delta entries that have been recorded since the cursor was returned. * @return stdclass */ public function delta($cursor) { $arg['cursor'] = $cursor; $response = $this->oauth->fetch($this->api_url . 'delta', $arg, 'POST'); return json_decode($response['body'],true); } /** * Returns a thumbnail (as a string) for a file path. * * @param string $path Path to file * @param string $size small, medium or large * @param string $root Use this to override the default root path (sandbox/dropbox) * @return string */ public function getThumbnail($path, $size = 'small', $root = null) { if (is_null($root)) $root = $this->root; $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); $response = $this->oauth->fetch($this->api_content_url . 'thumbnails/' . $root . '/' . ltrim($path,'/'),array('size' => $size)); return $response['body']; } /** * This method is used to generate multipart POST requests for file upload * * @param string $uri * @param array $arguments * @return bool */ protected function multipartFetch($uri, $file, $filename) { /* random string */ $boundary = 'R50hrfBj5JYyfR3vF3wR96GPCC9Fd2q2pVMERvEaOE3D8LZTgLLbRpNwXek3'; $headers = array( 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, ); $body="--" . $boundary . "\r\n"; $body.="Content-Disposition: form-data; name=file; filename=".rawurldecode($filename)."\r\n"; $body.="Content-type: application/octet-stream\r\n"; $body.="\r\n"; $body.=stream_get_contents($file); $body.="\r\n"; $body.="--" . $boundary . "--"; // Dropbox requires the filename to also be part of the regular arguments, so it becomes // part of the signature. $uri.='?file=' . $filename; return $this->oauth->fetch($uri, $body, 'POST', $headers); } /** * Search * * Returns metadata for all files and folders that match the search query. * * @added by: diszo.sasil * * @param string $query * @param string $root Use this to override the default root path (sandbox/dropbox) * @param string $path * @return array */ public function search($query = '', $root = null, $path = ''){ if (is_null($root)) $root = $this->root; if(!empty($path)){ $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); } $response = $this->oauth->fetch($this->api_url . 'search/' . $root . '/' . ltrim($path,'/'),array('query' => $query)); return json_decode($response['body'],true); } /** * Creates and returns a shareable link to files or folders. * * Note: Links created by the /shares API call expire after thirty days. * * @param type $path * @param type $root * @return type */ public function share($path, $root = null) { if (is_null($root)) $root = $this->root; $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); $response = $this->oauth->fetch($this->api_url. 'shares/'. $root . '/' . ltrim($path, '/'), array(), 'POST'); return json_decode($response['body'],true); } /** * Returns a link directly to a file. * Similar to /shares. The difference is that this bypasses the Dropbox webserver, used to provide a preview of the file, so that you can effectively stream the contents of your media. * * Note: The /media link expires after four hours, allotting enough time to stream files, but not enough to leave a connection open indefinitely. * * @param type $path * @param type $root * @return type */ public function media($path, $root = null) { if (is_null($root)) $root = $this->root; $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); $response = $this->oauth->fetch($this->api_url. 'media/'. $root . '/' . ltrim($path, '/'), array(), 'POST'); return json_decode($response['body'],true); } /** * Creates and returns a copy_ref to a file. This reference string can be used to copy that file to another user's Dropbox by passing it in as the from_copy_ref parameter on /fileops/copy. * * @param type $path * @param type $root * @return type */ public function copy_ref($path, $root = null) { if (is_null($root)) $root = $this->root; $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); $response = $this->oauth->fetch($this->api_url. 'copy_ref/'. $root . '/' . ltrim($path, '/')); return json_decode($response['body'],true); } } Dropbox-1.0.0/Dropbox/autoload.php0000644000076500000240000000116112023301616015514 0ustar joestaffoauth_token = $token['token']; $this->oauth_token_secret = $token['token_secret']; } else { $this->oauth_token = $token; $this->oauth_token_secret = $token_secret; } } /** * Returns the oauth request tokens as an associative array. * * The array will contain the elements 'token' and 'token_secret'. * * @return array */ public function getToken() { return array( 'token' => $this->oauth_token, 'token_secret' => $this->oauth_token_secret, ); } /** * Returns the authorization url * * @param string $callBack Specify a callback url to automatically redirect the user back * @return string */ public function getAuthorizeUrl($callBack = null) { // Building the redirect uri $token = $this->getToken(); $uri = self::URI_AUTHORIZE . '?oauth_token=' . $token['token']; if ($callBack) $uri.='&oauth_callback=' . $callBack; return $uri; } /** * Fetches a secured oauth url and returns the response body. * * @param string $uri * @param mixed $arguments * @param string $method * @param array $httpHeaders * @return string */ public abstract function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()); /** * Requests the OAuth request token. * * @return array */ abstract public function getRequestToken(); /** * Requests the OAuth access tokens. * * @return array */ abstract public function getAccessToken(); } Dropbox-1.0.0/Dropbox/Exception/Forbidden.php0000644000076500000240000000063412023301616017542 0ustar joestaffconsumerKey = $consumerKey; $this->consumerSecret = $consumerSecret; } /** * Fetches a secured oauth url and returns the response body. * * @param string $uri * @param mixed $arguments * @param string $method * @param array $httpHeaders * @return string */ public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) { $uri=str_replace('http://', 'https://', $uri); // all https, upload makes problems if not if (is_string($arguments) and strtoupper($method) == 'POST') { preg_match("/\?file=(.*)$/i", $uri, $matches); if (isset($matches[1])) { $uri = str_replace($matches[0], "", $uri); $filename = $matches[1]; $httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, array("file" => $filename), $method)); } } else { $httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, $arguments, $method)); } $ch = curl_init(); if (strtoupper($method) == 'POST') { curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_POST, true); if (is_array($arguments)) $arguments=http_build_query($arguments); curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments); $httpHeaders['Content-Length']=strlen($arguments); } else { curl_setopt($ch, CURLOPT_URL, $uri.'?'.http_build_query($arguments)); curl_setopt($ch, CURLOPT_POST, false); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 300); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_CAINFO, "rootca"); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); //Build header $headers = array(); foreach ($httpHeaders as $name => $value) { $headers[] = "{$name}: $value"; } curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); if (!ini_get('safe_mode') && !ini_get('open_basedir')) curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true ); if (function_exists($this->ProgressFunction) and defined('CURLOPT_PROGRESSFUNCTION')) { curl_setopt($ch, CURLOPT_NOPROGRESS, false); curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $this->ProgressFunction); curl_setopt($ch, CURLOPT_BUFFERSIZE, 512); } $response=curl_exec($ch); $errorno=curl_errno($ch); $error=curl_error($ch); $status=curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch); if (!empty($errorno)) throw new Dropbox_Exception_NotFound('Curl error: ('.$errorno.') '.$error."\n"); if ($status>=300) { $body = json_decode($response,true); switch ($status) { // Not modified case 304 : return array( 'httpStatus' => 304, 'body' => null, ); break; case 403 : throw new Dropbox_Exception_Forbidden('Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location. ' . $body["error"] . "\n"); case 404 : throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found. ' . $body["error"] . "\n"); case 507 : throw new Dropbox_Exception_OverQuota('This dropbox is full. ' . $body["error"] . "\n"); } if (!empty($body["error"])) throw new Dropbox_Exception_RequestToken('Error: ('.$status.') '.$body["error"]."\n"); } return array( 'body' => $response, 'httpStatus' => $status ); } /** * Returns named array with oauth parameters for further use * @return array Array with oauth_ parameters */ private function getOAuthBaseParams() { $params['oauth_version'] = '1.0'; $params['oauth_signature_method'] = 'HMAC-SHA1'; $params['oauth_consumer_key'] = $this->consumerKey; $tokens = $this->getToken(); if (isset($tokens['token']) && $tokens['token']) { $params['oauth_token'] = $tokens['token']; } $params['oauth_timestamp'] = time(); $params['oauth_nonce'] = md5(microtime() . mt_rand()); return $params; } /** * Creates valid Authorization header for OAuth, based on URI and Params * * @param string $uri * @param array $params * @param string $method GET or POST, standard is GET * @param array $oAuthParams optional, pass your own oauth_params here * @return array Array for request's headers section like * array('Authorization' => 'OAuth ...'); */ private function getOAuthHeader($uri, $params, $method = 'GET', $oAuthParams = null) { $oAuthParams = $oAuthParams ? $oAuthParams : $this->getOAuthBaseParams(); // create baseString to encode for the sent parameters $baseString = $method . '&'; $baseString .= $this->oauth_urlencode($uri) . "&"; // OAuth header does not include GET-Parameters $signatureParams = array_merge($params, $oAuthParams); // sorting the parameters ksort($signatureParams); $encodedParams = array(); foreach ($signatureParams as $key => $value) { $encodedParams[] = $this->oauth_urlencode($key) . '=' . $this->oauth_urlencode($value); } $baseString .= $this->oauth_urlencode(implode('&', $encodedParams)); // encode the signature $tokens = $this->getToken(); $hash = $this->hash_hmac_sha1($this->consumerSecret.'&'.$tokens['token_secret'], $baseString); $signature = base64_encode($hash); // add signature to oAuthParams $oAuthParams['oauth_signature'] = $signature; $oAuthEncoded = array(); foreach ($oAuthParams as $key => $value) { $oAuthEncoded[] = $key . '="' . $this->oauth_urlencode($value) . '"'; } return array('Authorization' => 'OAuth ' . implode(', ', $oAuthEncoded)); } /** * Requests the OAuth request token. * * @return void */ public function getRequestToken() { $result = $this->fetch(self::URI_REQUEST_TOKEN, array(), 'POST'); if ($result['httpStatus'] == "200") { $tokens = array(); parse_str($result['body'], $tokens); $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']); return $this->getToken(); } else { throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.'); } } /** * Requests the OAuth access tokens. * * This method requires the 'unauthorized' request tokens * and, if successful will set the authorized request tokens. * * @return void */ public function getAccessToken() { $result = $this->fetch(self::URI_ACCESS_TOKEN, array(), 'POST'); if ($result['httpStatus'] == "200") { $tokens = array(); parse_str($result['body'], $tokens); $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']); return $this->getToken(); } else { throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.'); } } /** * Helper function to properly urlencode parameters. * See http://php.net/manual/en/function.oauth-urlencode.php * * @param string $string * @return string */ private function oauth_urlencode($string) { return str_replace('%E7', '~', rawurlencode($string)); } /** * Hash function for hmac_sha1; uses native function if available. * * @param string $key * @param string $data * @return string */ private function hash_hmac_sha1($key, $data) { if (function_exists('hash_hmac') && in_array('sha1', hash_algos())) { return hash_hmac('sha1', $data, $key, true); } else { $blocksize = 64; $hashfunc = 'sha1'; if (strlen($key) > $blocksize) { $key = pack('H*', $hashfunc($key)); } $key = str_pad($key, $blocksize, chr(0x00)); $ipad = str_repeat(chr(0x36), $blocksize); $opad = str_repeat(chr(0x5c), $blocksize); $hash = pack('H*', $hashfunc(( $key ^ $opad ) . pack('H*', $hashfunc(($key ^ $ipad) . $data)))); return $hash; } } }Dropbox-1.0.0/Dropbox/OAuth/PEAR.php0000644000076500000240000001335012023301616015456 0ustar joestaffOAuth = new Dropbox_OAuth_Consumer_Dropbox($consumerKey, $consumerSecret); $this->consumerKey = $consumerKey; } /** * Sets the request token and secret. * * The tokens can also be passed as an array into the first argument. * The array must have the elements token and token_secret. * * @param string|array $token * @param string $token_secret * @return void */ public function setToken($token, $token_secret = null) { parent::setToken($token,$token_secret); $this->OAuth->setToken($this->oauth_token); $this->OAuth->setTokenSecret($this->oauth_token_secret); } /** * Fetches a secured oauth url and returns the response body. * * @param string $uri * @param mixed $arguments * @param string $method * @param array $httpHeaders * @return string */ public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) { $httpRequest = new HTTP_Request2(null, HTTP_Request2::METHOD_GET, array( 'ssl_verify_peer' => false, 'ssl_verify_host' => false ) ); $consumerRequest = new HTTP_OAuth_Consumer_Request(); $consumerRequest->accept($httpRequest); $consumerRequest->setUrl($uri); $consumerRequest->setMethod($method); $consumerRequest->setSecrets($this->OAuth->getSecrets()); $parameters = array( 'oauth_consumer_key' => $this->consumerKey, 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_token' => $this->oauth_token, ); if (is_array($arguments)) { $parameters = array_merge($parameters,$arguments); } elseif (is_string($arguments)) { $consumerRequest->setBody($arguments); } $consumerRequest->setParameters($parameters); if (count($httpHeaders)) { foreach($httpHeaders as $k=>$v) { $consumerRequest->setHeader($k, $v); } } $response = $consumerRequest->send(); switch($response->getStatus()) { // Not modified case 304 : return array( 'httpStatus' => 304, 'body' => null, ); break; case 400 : throw new Dropbox_Exception_Forbidden('Forbidden. Bad input parameter. Error message should indicate which one and why.'); case 401 : throw new Dropbox_Exception_Forbidden('Forbidden. Bad or expired token. This can happen if the user or Dropbox revoked or expired an access token. To fix, you should re-authenticate the user.'); case 403 : throw new Dropbox_Exception_Forbidden('Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location.'); case 404 : throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found'); case 405 : throw new Dropbox_Exception_Forbidden('Forbidden. Request method not expected (generally should be GET or POST).'); case 500 : throw new Dropbox_Exception_Forbidden('Server error. ' . $e->getMessage()); case 503 : throw new Dropbox_Exception_Forbidden('Forbidden. Your app is making too many requests and is being rate limited. 503s can trigger on a per-app or per-user basis.'); case 507 : throw new Dropbox_Exception_OverQuota('This dropbox is full'); } return array( 'httpStatus' => $response->getStatus(), 'body' => $response->getBody() ); } /** * Requests the OAuth request token. * * @return void */ public function getRequestToken() { $this->OAuth->getRequestToken(self::URI_REQUEST_TOKEN); $this->setToken($this->OAuth->getToken(), $this->OAuth->getTokenSecret()); return $this->getToken(); } /** * Requests the OAuth access tokens. * * This method requires the 'unauthorized' request tokens * and, if successful will set the authorized request tokens. * * @return void */ public function getAccessToken() { $this->OAuth->getAccessToken(self::URI_ACCESS_TOKEN); $this->setToken($this->OAuth->getToken(), $this->OAuth->getTokenSecret()); return $this->getToken(); } } Dropbox-1.0.0/Dropbox/OAuth/PHP.php0000644000076500000240000001202712023301616015356 0ustar joestaffOAuth = new OAuth($consumerKey, $consumerSecret,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI); $this->OAuth->enableDebug(); } /** * Sets the request token and secret. * * The tokens can also be passed as an array into the first argument. * The array must have the elements token and token_secret. * * @param string|array $token * @param string $token_secret * @return void */ public function setToken($token, $token_secret = null) { parent::setToken($token,$token_secret); $this->OAuth->setToken($this->oauth_token, $this->oauth_token_secret); } /** * Fetches a secured oauth url and returns the response body. * * @param string $uri * @param mixed $arguments * @param string $method * @param array $httpHeaders * @return string */ public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) { try { $this->OAuth->fetch($uri, $arguments, $method, $httpHeaders); $result = $this->OAuth->getLastResponse(); $lastResponseInfo = $this->OAuth->getLastResponseInfo(); return array( 'httpStatus' => $lastResponseInfo['http_code'], 'body' => $result, ); } catch (OAuthException $e) { $lastResponseInfo = $this->OAuth->getLastResponseInfo(); switch($lastResponseInfo['http_code']) { // Not modified case 304 : return array( 'httpStatus' => 304, 'body' => null, ); break; case 400 : throw new Dropbox_Exception_Forbidden('Forbidden. Bad input parameter. Error message should indicate which one and why.'); case 401 : throw new Dropbox_Exception_Forbidden('Forbidden. Bad or expired token. This can happen if the user or Dropbox revoked or expired an access token. To fix, you should re-authenticate the user.'); case 403 : throw new Dropbox_Exception_Forbidden('Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location.'); case 404 : throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found'); case 405 : throw new Dropbox_Exception_Forbidden('Forbidden. Request method not expected (generally should be GET or POST).'); case 500 : throw new Dropbox_Exception_Forbidden('Server error. ' . $e->getMessage()); case 503 : throw new Dropbox_Exception_Forbidden('Forbidden. Your app is making too many requests and is being rate limited. 503s can trigger on a per-app or per-user basis.'); case 507 : throw new Dropbox_Exception_OverQuota('This dropbox is full'); default: // rethrowing throw $e; } } } /** * Requests the OAuth request token. * * @return void */ public function getRequestToken() { try { $tokens = $this->OAuth->getRequestToken(self::URI_REQUEST_TOKEN); $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']); return $this->getToken(); } catch (OAuthException $e) { throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.',0,$e); } } /** * Requests the OAuth access tokens. * * This method requires the 'unauthorized' request tokens * and, if successful will set the authorized request tokens. * * @return void */ public function getAccessToken() { $uri = self::URI_ACCESS_TOKEN; $tokens = $this->OAuth->getAccessToken($uri); $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']); return $this->getToken(); } } Dropbox-1.0.0/Dropbox/OAuth/Wordpress.php0000644000076500000240000001617212023301616016724 0ustar joestaffconsumerKey = $consumerKey; $this->consumerSecret = $consumerSecret; } /** * Fetches a secured oauth url and returns the response body. * * @param string $uri * @param mixed $arguments * @param string $method * @param array $httpHeaders * @return string */ public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) { $requestParams = array(); $requestParams['method'] = $method; $oAuthHeader = $this->getOAuthHeader($uri, $arguments, $method); $requestParams['headers'] = array_merge($httpHeaders, $oAuthHeader); // arguments will be passed to uri for GET, to body for POST etc. if ($method == 'GET') { $uri .= '?' . http_build_query($arguments); } else { if (count($arguments)) { $requestParams['body'] = $arguments; } } $request = new WP_Http; //$uri = str_replace('api.dropbox.com', 'localhost:12346', $uri); $result = $request->request($uri, $requestParams); return array( 'httpStatus' => $result['response']['code'], 'body' => $result['body'], ); } /** * Returns named array with oauth parameters for further use * @return array Array with oauth_ parameters */ private function getOAuthBaseParams() { $params['oauth_version'] = '1.0'; $params['oauth_signature_method'] = 'HMAC-SHA1'; $params['oauth_consumer_key'] = $this->consumerKey; $tokens = $this->getToken(); if (isset($tokens['token']) && $tokens['token']) { $params['oauth_token'] = $tokens['token']; } $params['oauth_timestamp'] = time(); $params['oauth_nonce'] = md5(microtime() . mt_rand()); return $params; } /** * Creates valid Authorization header for OAuth, based on URI and Params * * @param string $uri * @param array $params * @param string $method GET or POST, standard is GET * @param array $oAuthParams optional, pass your own oauth_params here * @return array Array for request's headers section like * array('Authorization' => 'OAuth ...'); */ private function getOAuthHeader($uri, $params, $method = 'GET', $oAuthParams = null) { $oAuthParams = $oAuthParams ? $oAuthParams : $this->getOAuthBaseParams(); // create baseString to encode for the sent parameters $baseString = $method . '&'; $baseString .= $this->oauth_urlencode($uri) . "&"; // OAuth header does not include GET-Parameters $signatureParams = array_merge($params, $oAuthParams); // sorting the parameters ksort($signatureParams); $encodedParams = array(); foreach ($signatureParams as $key => $value) { $encodedParams[] = $this->oauth_urlencode($key) . '=' . $this->oauth_urlencode($value); } $baseString .= $this->oauth_urlencode(implode('&', $encodedParams)); // encode the signature $tokens = $this->getToken(); $hash = $this->hash_hmac_sha1($this->consumerSecret.'&'.$tokens['token_secret'], $baseString); $signature = base64_encode($hash); // add signature to oAuthParams $oAuthParams['oauth_signature'] = $signature; $oAuthEncoded = array(); foreach ($oAuthParams as $key => $value) { $oAuthEncoded[] = $key . '="' . $this->oauth_urlencode($value) . '"'; } return array('Authorization' => 'OAuth ' . implode(', ', $oAuthEncoded)); } /** * Requests the OAuth request token. * * @return void */ public function getRequestToken() { $result = $this->fetch(self::URI_REQUEST_TOKEN, array(), 'POST'); if ($result['httpStatus'] == "200") { $tokens = array(); parse_str($result['body'], $tokens); $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']); return $this->getToken(); } else { throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.'); } } /** * Requests the OAuth access tokens. * * This method requires the 'unauthorized' request tokens * and, if successful will set the authorized request tokens. * * @return void */ public function getAccessToken() { $result = $this->fetch(self::URI_ACCESS_TOKEN, array(), 'POST'); if ($result['httpStatus'] == "200") { $tokens = array(); parse_str($result['body'], $tokens); $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']); return $this->getToken(); } else { throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.'); } } /** * Helper function to properly urlencode parameters. * See http://php.net/manual/en/function.oauth-urlencode.php * * @param string $string * @return string */ private function oauth_urlencode($string) { return str_replace('%E7', '~', rawurlencode($string)); } /** * Hash function for hmac_sha1; uses native function if available. * * @param string $key * @param string $data * @return string */ private function hash_hmac_sha1($key, $data) { if (function_exists('hash_hmac') && in_array('sha1', hash_algos())) { return hash_hmac('sha1', $data, $key, true); } else { $blocksize = 64; $hashfunc = 'sha1'; if (strlen($key) > $blocksize) { $key = pack('H*', $hashfunc($key)); } $key = str_pad($key, $blocksize, chr(0x00)); $ipad = str_repeat(chr(0x36), $blocksize); $opad = str_repeat(chr(0x5c), $blocksize); $hash = pack('H*', $hashfunc(( $key ^ $opad ) . pack('H*', $hashfunc(($key ^ $ipad) . $data)))); return $hash; } } }Dropbox-1.0.0/Dropbox/OAuth/Zend.php0000644000076500000240000002022412023301616015625 0ustar joestaff * @license http://code.google.com/p/dropbox-php/wiki/License MIT */ /** * This class is used to sign all requests to dropbox * * This classes use the Zend_Oauth package. */ class Dropbox_OAuth_Zend extends Dropbox_OAuth { /** * OAuth object * * @var Zend_Oauth_Consumer */ protected $oAuth; /** * OAuth consumer key * * We need to keep this around for later. * * @var string */ protected $consumerKey; /** * * @var Zend_Oauth_Token */ protected $zend_oauth_token; /** * Constructor * * @param string $consumerKey * @param string $consumerSecret */ public function __construct($consumerKey, $consumerSecret) { if (!class_exists('Zend_Oauth_Consumer')) { // We're going to try to load in manually include 'Zend/Oauth/Consumer.php'; } if (!class_exists('Zend_Oauth_Consumer')) throw new Dropbox_Exception('The Zend_Oauth_Consumer class could not be found!'); $this->OAuth = new Zend_Oauth_Consumer(array( "consumerKey" => $consumerKey, "consumerSecret" => $consumerSecret, "requestTokenUrl" => self::URI_REQUEST_TOKEN, "accessTokenUrl" => self::URI_ACCESS_TOKEN, "authorizeUrl" => self::URI_AUTHORIZE, "signatureMethod" => "HMAC-SHA1", )); $this->consumerKey = $consumerKey; } /** * Sets the request token and secret. * * The tokens can also be passed as an array into the first argument. * The array must have the elements token and token_secret. * * @param string|array $token * @param string $token_secret * @return void */ public function setToken($token, $token_secret = null) { if (is_a($token, "Zend_Oauth_Token")) { if (is_a($token, "Zend_Oauth_Token_Access")) { $this->OAuth->setToken($token); } $this->zend_oauth_token = $token; return parent::setToken($token->getToken(), $token->getTokenSecret()); } elseif (is_string($token) && is_null($token_secret)) { return $this->setToken(unserialize($token)); } elseif (isset($token['zend_oauth_token'])) { return $this->setToken(unserialize($token['zend_oauth_token'])); } else { parent::setToken($token, $token_secret); return; } } /** * Fetches a secured oauth url and returns the response body. * * @param string $uri * @param mixed $arguments * @param string $method * @param array $httpHeaders * @return string */ public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) { $token = $this->OAuth->getToken(); if (!is_a($token, "Zend_Oauth_Token")) { if (is_a($this->zend_oauth_token, "Zend_Oauth_Token_Access")) { $token = $this->zend_oauth_token; } else { $token = new Zend_Oauth_Token_Access(); $token->setToken($this->oauth_token); $token->setTokenSecret($this->oauth_token_secret); } } /* @var $token Zend_Oauth_Token_Access */ $oauthOptions = array( 'consumerKey' => $this->consumerKey, 'signatureMethod' => "HMAC-SHA1", 'consumerSecret' => $this->OAuth->getConsumerSecret(), ); $config = array("timeout" => 15); /* @var $consumerRequest Zend_Oauth_Client */ $consumerRequest = $token->getHttpClient($oauthOptions); $consumerRequest->setMethod($method); if (is_array($arguments)) { $consumerRequest->setUri($uri); if ($method == "GET") { foreach ($arguments as $param => $value) { $consumerRequest->setParameterGet($param, $value); } } else { foreach ($arguments as $param => $value) { $consumerRequest->setParameterPost($param, $value); } } } elseif (is_string($arguments)) { preg_match("/\?file=(.*)$/i", $uri, $matches); if (isset($matches[1])) { $uri = str_replace($matches[0], "", $uri); $filename = $matches[1]; $uri = Zend_Uri::factory($uri); $uri->addReplaceQueryParameters(array("file" => $filename)); $consumerRequest->setParameterGet("file", $filename); } $consumerRequest->setUri($uri); $consumerRequest->setRawData($arguments); } elseif (is_resource($arguments)) { $consumerRequest->setUri($uri); /** Placeholder for Oauth streaming support. */ } if (count($httpHeaders)) { foreach ($httpHeaders as $k => $v) { $consumerRequest->setHeaders($k, $v); } } $response = $consumerRequest->request(); $body = Zend_Json::decode($response->getBody()); switch ($response->getStatus()) { // Not modified case 304 : return array( 'httpStatus' => 304, 'body' => null, ); break; case 403 : throw new Dropbox_Exception_Forbidden('Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location. ' . $body["error"] . "\n"); case 404 : throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found. ' . $body["error"] . "\n"); case 507 : throw new Dropbox_Exception_OverQuota('This dropbox is full. ' . $body["error"] . "\n"); } return array( 'httpStatus' => $response->getStatus(), 'body' => $response->getBody(), ); } /** * Requests the OAuth request token. * * @return void */ public function getRequestToken() { $token = $this->OAuth->getRequestToken(); $this->setToken($token); return $this->getToken(); } /** * Requests the OAuth access tokens. * * This method requires the 'unauthorized' request tokens * and, if successful will set the authorized request tokens. * * @return void */ public function getAccessToken() { if (is_a($this->zend_oauth_token, "Zend_Oauth_Token_Request")) { $requestToken = $this->zend_oauth_token; } else { $requestToken = new Zend_Oauth_Token_Request(); $requestToken->setToken($this->oauth_token); $requestToken->setTokenSecret($this->oauth_token_secret); } $token = $this->OAuth->getAccessToken($_GET, $requestToken); $this->setToken($token); return $this->getToken(); } /** * Returns the oauth request tokens as an associative array. * * The array will contain the elements 'token' and 'token_secret' and the serialized * Zend_Oauth_Token object. * * @return array */ public function getToken() { //$token = $this->OAuth->getToken(); //return serialize($token); return array( 'token' => $this->oauth_token, 'token_secret' => $this->oauth_token_secret, 'zend_oauth_token' => serialize($this->zend_oauth_token), ); } /** * Returns the authorization url * * Overloading Dropbox_OAuth to use the built in functions in Zend_Oauth * * @param string $callBack Specify a callback url to automatically redirect the user back * @return string */ public function getAuthorizeUrl($callBack = null) { if ($callBack) $this->OAuth->setCallbackUrl($callBack); return $this->OAuth->getRedirectUrl(); } } Dropbox-1.0.0/Dropbox/OAuth/Consumer/Dropbox.php0000644000076500000240000000217412023301616020141 0ustar joestaffconsumerRequest instanceof HTTP_OAuth_Consumer_Request) { $this->consumerRequest = new HTTP_OAuth_Consumer_Request; } // TODO: Change this and add in code to validate the SSL cert. // see https://github.com/bagder/curl/blob/master/lib/mk-ca-bundle.pl $this->consumerRequest->setConfig(array( 'ssl_verify_peer' => false, 'ssl_verify_host' => false )); return $this->consumerRequest; } }