24 | The Dropbox API class is the main class to interact with the dropbox API.
25 | It has all the convenience methods to access and modify dropbox information.
26 |
27 |
Creating the object
28 |
29 | The constructor takes at least 2 arguments:
30 | * $consumerKey
31 | * $consumerSecret
32 |
33 | You can find these keys on the Dropbox developer site, under [My applications](https://www.dropbox.com/developers/apps).
34 |
35 | example:
36 |
37 |
54 |
55 |
Authentication
56 |
57 |
OAuth workflow
58 |
59 | $oauth = new Dropbox_OAuth_PHP($consumerKey,$consumerSecret);
60 | $dropbox = new Dropbox_API($oauth);
61 |
62 | // For convenience, definitely not required
63 | header('Content-Type: text/plain');
64 |
65 | // We need to start a session
66 | session_start();
67 |
68 | // There are multiple steps in this workflow, we keep a 'state number' here
69 | if (isset($_SESSION['state'])) {
70 | $state = $_SESSION['state'];
71 | } else {
72 | $state = 1;
73 | }
74 |
75 | switch($state) {
76 |
77 | /* In this phase we grab the initial request tokens
78 | and redirect the user to the 'authorize' page hosted
79 | on dropbox */
80 | case 1 :
81 | echo "Step 1: Acquire request tokens\n";
82 | $tokens = $oauth->getRequestToken();
83 | print_r($tokens);
84 |
85 | // Note that if you want the user to automatically redirect back, you can
86 | // add the 'callback' argument to getAuthorizeUrl.
87 | echo "Step 2: You must now redirect the user to:\n";
88 | echo $oauth->getAuthorizeUrl() . "\n";
89 | $_SESSION['state'] = 2;
90 | $_SESSION['oauth_tokens'] = $tokens;
91 | die();
92 |
93 | /* In this phase, the user just came back from authorizing
94 | and we're going to fetch the real access tokens */
95 | case 2 :
96 | echo "Step 3: Acquiring access tokens\n";
97 | $oauth->setToken($_SESSION['oauth_tokens']);
98 | $tokens = $oauth->getAccessToken();
99 | print_r($tokens);
100 | $_SESSION['state'] = 3;
101 | $_SESSION['oauth_tokens'] = $tokens;
102 | // There is no break here, intentional
103 |
104 | /* This part gets called if the authentication process
105 | already succeeded. We can use our stored tokens and the api
106 | should work. Store these tokens somewhere, like a database */
107 | case 3 :
108 | echo "The user is authenticated\n";
109 | echo "You should really save the oauth tokens somewhere, so the first steps will no longer be needed\n";
110 | print_r($_SESSION['oauth_tokens']);
111 | $oauth->setToken($_SESSION['oauth_tokens']);
112 | break;
113 | }
114 |
115 | }
116 |
117 |
118 |
Roots
119 |
120 | By default Dropbox works with 2 different 'roots', the
121 | * Sandbox, which is 1 specific directory assigned for your application
122 | * Dropbox, which is the users' entire dropbox directory.
123 |
124 | Before 'sandbox' was the default root, but sandbox is disabled for new applications so now
125 | 'dropbox' is the default. In most cases you don't have to worry about this.
126 |
127 |
128 | // If you do need the sandbox, specify it as the 2nd argument
129 | $dropbox = new Dropbox_API($oauth, 'sandbox');
130 |
131 |
The API methods
132 |
133 |
getAccountInfo
134 |
135 | Using the getAccountInfo you can grab a users account information, such as their quota.
136 | Simply call $dropbox->getAccountInfo();
137 |
138 |
getFile
139 |
140 | Using getFile you can download a file. At the moment the function returns the entire file's body as a string. This might be fixed in the future once PHP's OAuth extension no longer requires this.
141 |
142 | $dropbox->getFile('filename');
143 |
144 | You can override the default root by specifying it as a second argument:
145 |
146 | $dropbox->getFile('filename','dropbox');
147 |
148 |
putFile
149 |
150 | Using putFile you can upload a file. At the moment the function will store the entire file temporarily as a string. This might be fixed in the future once PHP's OAuth extension no longer requires this.
151 |
152 | You can specify the file as a local path, or as an open file stream.
153 |
154 | Example 1:
155 |
156 | $dropbox->putFile('newPath.txt','/local/path/tofile');
157 |
158 | Example 2:
159 |
160 | $h = fopen('/local/path/to/file','r');
161 | $dropbox->putFile('newPath.txt',$h);
162 |
163 | You can override the default root by specifying it as a third argument:
164 |
165 | $dropbox->putFile('newPath.txt','/local/path/tofile','dropbox');
166 |
167 |
copy
168 |
169 | Copy makes an exact copy of a file or directory.
170 |
171 | Example:
172 |
173 | $dropbox->copy('oldfile.txt','newfile.txt');
174 |
175 | You can override the default root by specifying it as a third argument:
176 |
177 | $dropbox->copy('oldfile.txt','newfile.txt','sandbox');
178 |
179 |
createFolder
180 |
181 | createFolder creates a new, empty, folder.
182 |
183 | Example:
184 |
185 | $dropbox->createFolder('new folder');
186 |
187 | You can override the default root by specifying it as a second argument:
188 |
189 | $dropbox->createFolder('new folder','sandbox');
190 |
191 |
delete
192 |
193 | delete deletes a file or directory (and all it's contents).
194 |
195 | Example:
196 |
197 | $dropbox->delete('myfolder');
198 |
199 | You can override the default root by specifying it as a second argument:
200 |
201 | $dropbox->delete('myfolder','sandbox');
202 |
203 |
move
204 |
205 | Move moves a file or directory to a new location:
206 |
207 | Example:
208 |
209 | $dropbox->move('oldfile.txt','newfile.txt');
210 |
211 | You can override the default root by specifying it as a third argument:
212 |
213 | $dropbox->move('oldfile.txt','newfile.txt','sandbox');
214 |
215 |
216 |
getMetaData
217 |
218 | getMetadata is used to retrieve information about files, or about the contents of a directory.
219 |
220 | Example 1:
221 |
222 | $info = $dropbox->getMetaData('directory');
223 | print_r($info);
224 |
225 | The second parameter specifies what you want to retrieve. If you're fetching info about a
226 | directory, and it is set to true, the directories contents will be returned. If it's set to 'false', only the directories' information will be returned:
227 |
228 | Example 2:
229 |
230 | // Doesn't return directory contents
231 | $info = $dropbox->getMetaData('directory',false);
232 | print_r($info);
233 |
234 |
getThumbnail
235 |
236 | The getThumbnail method works like getFile, except it can be used to retrieve an image's thumbnail.
237 |
238 | The first argument specifies the filename, the second specifies the size (small, medium, large).
239 |
240 | header('Content-Type: image/jpeg');
241 | echo $dropbox->getThumbnail('image.jpg','large');
242 |
243 | The optional third argument can be used to change the default root:
244 |
245 | header('Content-Type: image/jpeg');
246 | echo $dropbox->getThumbnail('image.jpg','small','dropbox');
247 |
248 |
More examples
249 |
250 | The unit test in the package is quite complete, everything you need to know should be in there. You can also [browse the source](https://github.com/Dropbox-PHP/dropbox-php).
--------------------------------------------------------------------------------
/docs/posts/2011/06/20110622-01-a-new-hope-a-new-home.md:
--------------------------------------------------------------------------------
1 | A New Hope, A New Home
2 | ======================
3 | Published: 2011-06-22 12:00:00am
4 | Type: link
5 | Tags: _news, dropbox
6 |
7 | Welcome to the new home for Dropbox-PHP related news and announcements. Look here for announcements about new releases and general news about development on the Dropbox-PHP library. The [mailing list](http://groups.google.com/group/dropbox-php) will still be used for general discussions, but this will serve as a point of general notices for those that don’t take part on the mailing list.
8 |
9 | Recently, Evert announced on his [blog](http://www.rooftopsolutions.nl/blog/throwing-in-the-towel-with-sabreamf-and-dropbox-php-lib) and the [mailing list](http://groups.google.com/group/dropbox-php/browse_thread/thread/57b6808c093dd3a6) that he no longer had the time to continue to keep up the Dropbox-PHP library. As such it has sat dormant for a few months. I recently stumbled across it and decided to join in and help support it. Look for a release announcement tomorrow morning for the first PEAR release since August which includes several community contributed fixes. I plan to get to the rest of the open issues and begin working to add new functionality to Dropbox-PHP over the next few months.
--------------------------------------------------------------------------------
/docs/posts/2011/06/20110623-01-0-4-1-alpha-release.md:
--------------------------------------------------------------------------------
1 | 0.4.1 Alpha Release
2 | ===================
3 | Published: 2011-06-23 12:00:00am
4 | Type: link
5 | Tags: _news, _php, dropbox
6 |
7 | Version 0.4.1 (Alpha) build has been released and is now available to install via PEAR. New with this release is a dedicated domain for hosting the PEAR releases.
8 |
9 | You can install using the following:
10 |
11 | pear channel-discover pear.dropbox-php.com
12 | pear install dropbox-php/Dropbox-alpha
13 |
14 | ### Changes for this release: ###
15 |
16 | * Issue #10 API getFile() fails if spaces in path.
17 | * Issue #13 API putFile() fails if spaces in filename.
18 | * Issue #15 putFile always returns true, regardless of the result of the request
19 | * Issue #21 space in filename
--------------------------------------------------------------------------------
/docs/posts/2011/07/20110720-01-0-4-2-alpha-release.md:
--------------------------------------------------------------------------------
1 | 0.4.2 Alpha Release
2 | ===================
3 | Published: 2011-07-20 12:00:00am
4 | Type: link
5 | Tags: _news, _php, dropbox
6 |
7 | Version 0.4.2 (Alpha) build has been released and is now available to install via PEAR.
8 |
9 | You can install using the following:
10 |
11 | pear channel-discover pear.dropbox-php.com
12 | pear install dropbox-php/Dropbox-alpha
13 |
14 | ### Changes for this release: ###
15 |
16 | * Issue #25 Patch for /Dropbox/API.php / Error using putfile
17 | * Issue #27 WordPress OAuth Support
--------------------------------------------------------------------------------
/docs/posts/2011/09/20110904-01-0-4-3-alpha-release.md:
--------------------------------------------------------------------------------
1 | 0.4.3 Alpha Release
2 | ===================
3 | Published: 2011-09-04 12:00:00am
4 | Type: link
5 | Tags: _news, _php, dropbox
6 |
7 | Version 0.4.3 (Alpha) build has been released and is now available to install via PEAR.
8 |
9 | You can install using the following:
10 |
11 | pear channel-discover pear.dropbox-php.com
12 | pear install dropbox-php/Dropbox-alpha
13 |
14 | ### Changes for this release: ###
15 |
16 | * Issue #28 – oAuth Curl class based on WordPress class
17 | * Issue #30 – Can’t open files with tilde in the name
18 | * Issue #34 – Change API URLs to use HTTPS
19 | * Issue #35 – Change hard-coded API URLs to use a class constant
--------------------------------------------------------------------------------
/docs/posts/2011/09/20110927-01-0-4-4-alpha-release.md:
--------------------------------------------------------------------------------
1 | 0.4.4 Alpha Release
2 | ===================
3 | Published: 2011-09-27 12:00:00am
4 | Type: link
5 | Tags: _news, _php, dropbox
6 |
7 | Version 0.4.4 (Alpha) build has been released and is now available to install via PEAR.
8 |
9 | You can install using the following:
10 |
11 | pear channel-discover pear.dropbox-php.com
12 | pear install dropbox-php/Dropbox-alpha
13 |
14 | ### Changes for this release: ###
15 |
16 | * Added useSSL flag to constructor to allow turning off SSL use
17 | * Added code to turn off SSL validation during OAuth calls
--------------------------------------------------------------------------------
/docs/posts/2011/10/20111031-01-0-4-5-alpha-release.md:
--------------------------------------------------------------------------------
1 | 0.4.5 Alpha Release
2 | ===================
3 | Published: 2011-10-31 12:00:00am
4 | Type: link
5 | Tags: _news, _php, dropbox
6 |
7 | Version 0.4.5 (Alpha) build has been released and is now available to install via PEAR.
8 |
9 | You can install using the following:
10 |
11 | pear channel-discover pear.dropbox-php.com
12 | pear install dropbox-php/Dropbox-alpha
13 |
14 | ### Changes for this release: ###
15 |
16 | * Updated to work with Dropbox API version 1
17 | * Some PHP Unit tests
--------------------------------------------------------------------------------
/docs/posts/2012/01/20120114-01-0-5-0-beta-release.md:
--------------------------------------------------------------------------------
1 | 0.5.0 Beta Release
2 | ==================
3 | Published: 2012-01-14 05:43:55pm
4 | Type: link
5 | Tags: __php, _dropbox, _news
6 |
7 | Version 0.5.0 (Beta) build has been released and is now available to install via PEAR.
8 |
9 | You can install using the following:
10 |
11 | pear channel-discover pear.dropbox-php.com
12 | pear install dropbox-php/Dropbox-beta
13 |
14 | ### Changes for this release: ###
15 |
16 | - Minor bug fixes
17 | - Added share method from Issue #42
18 | - Added search method from Issue #42
19 | - Added ant build script and phpunit config file
20 | - Updated status to "Beta"
21 |
22 | ### Additional Changes ###
23 | New with this release is the status change to "Beta". With the addition
24 | of tests added in the last release and with a build script added in this
25 | release, we are getting closer to a stable release. Additionally, code
26 | hosting has been moved to GitHub only. Issue tracking will happen on
27 | GitHub only now as well. The Google groups mailing list will remain
28 | for the foreseeable future.
--------------------------------------------------------------------------------
/docs/posts/2012/01/20120115-01-0-5-1-beta-release.md:
--------------------------------------------------------------------------------
1 | 0.5.1 Beta Release
2 | ==================
3 | Published: 2012-01-15 12:25:38am
4 | Type: link
5 | Tags: __dropbox, __news, __php
6 |
7 | Let's try this again, same as 0.5.0 except packaging has been fixed:
8 |
9 | Version 0.5.1 (Beta) build has been released and is now available to install via PEAR.
10 |
11 | You can install using the following:
12 |
13 | pear channel-discover pear.dropbox-php.com
14 | pear install dropbox-php/Dropbox-beta
15 |
16 | ### Changes for this release: ###
17 |
18 | - Minor bug fixes
19 | - Added share method from Issue #42
20 | - Added search method from Issue #42
21 | - Added ant build script and phpunit config file
22 | - Updated status to "Beta"
23 |
24 | ### Additional Changes ###
25 | New with this release is the status change to "Beta". With the addition
26 | of tests added in the last release and with a build script added in this
27 | release, we are getting closer to a stable release. Additionally, code
28 | hosting has been moved to GitHub only. Issue tracking will happen on
29 | GitHub only now as well. The Google groups mailing list will remain
30 | for the foreseeable future.
--------------------------------------------------------------------------------
/docs/posts/2012/06/20120616-01-end-of-line.md:
--------------------------------------------------------------------------------
1 | End of Line?
2 | ============
3 | Published: 2012-06-16 12:01:59am
4 | Type: link
5 | Tags: dropbox, php
6 |
7 | ### Development has stopped ###
8 | Well, if it hasn't been obvious before, it should be now. Just like Evan before me, I no longer have free time to work on this library. Also, it seems Dropbox dropped the link to this library from their list of [3rd party APIs](https://www.dropbox.com/developers/reference/sdk). I tried to get them to add it back, but…
9 |
10 | If anyone is interested in working on this library, I'll find time to manage pull requests. And if you submit often enough, I'll consider adding you as a committer to the Github project so you can commit directly.
11 |
12 | Alternatively, if someone is interested in taking over altogether, I'm willing to consult with Evan and hand over control.
13 |
14 | Lastly, if you aren't willing/able to contribute to this library, but still need one that is staying current, it appears there is one that is very similar to this library. You can find it [here](https://github.com/BenTheDesigner/Dropbox)
--------------------------------------------------------------------------------
/docs/posts/2012/09/20120909-01-1-0-0-stable-release.md:
--------------------------------------------------------------------------------
1 | 1.0.0 Stable Release
2 | ====================
3 | Published: 2012-09-09 11:29:38pm
4 | Type: link
5 | Tags: dropbox, php
6 |
7 | Version 1.0.0 (Stable) build has been released and is now available to install via PEAR or Composer (new with this release).
8 |
9 | You can install using the following:
10 |
11 | pear channel-discover pear.dropbox-php.com
12 | pear install dropbox-php/Dropbox
13 |
14 | Or by adding the following to your composer.json:
15 |
16 | "require": {
17 | "dropbox-php/dropbox-php": “1.*”
18 | }
19 |
20 |
21 | ### Changes for this release: ###
22 |
23 | - Minor bug fixes
24 | - Added composer support
25 | - PR-13 - DropBox API returns 500 errors rarely. For example, when the thumbnail of the broken picture is acquired etc.
26 | - PR-8 - Methods delta, media, and copy_ref plus additional fixes
27 | - Updated status to “Stable”
28 |
29 | ### Additional Changes ###
30 | New with this release is the status change to “Stable”. Since the code has been relatively stable for the last 8 months and the addition of the missing API methods (delta, media, and copy_ref). I feel this is close enough to be declared stable. The documentation is still missing, however you can use the unit tests for examples on how to use the various method calls. Initial composer support has been added and the repository has been setup to notify packagist on code pushes. However, I haven’t yet tested to confirm I have things fully configured correctly. Again, since I don’t have very much free time, I don’t know when (or if) I will get around to testing on the composer setup so PEAR is still the recommended way to install the library.
31 |
32 | Special thanks to Naoki Sawada for your work on this release.
--------------------------------------------------------------------------------
/docs/roadmap.md:
--------------------------------------------------------------------------------
1 | Roadmap
2 | ===================
3 |
4 | * [0.5.2-RC1](#0.5.2-RC1)
5 | * [0.5.3-RC1](#0.5.3-RC2)
6 | * [1.0-STABLE](#1.0-STABLE)
7 |
8 |
0.5.2-RC1
9 | * Prelude to 1.0 and first "stable" release
10 | * Better documentation on site
11 | * Update Curl OAuth support to validate SSL certificate
12 |
13 |
0.5.3-RC2
14 | * New examples
15 | * Last release prior to 1.0 release
16 | * Support for [/delta](https://www.dropbox.com/developers/reference/api#delta_beta) API call (currently a beta API call with Dropbox)
17 | * Support for [/copy_ref](https://www.dropbox.com/developers/reference/api#copy_ref_beta) API call (currently a beta API call with Dropbox)"
18 | * Update the [/files](http://www.dropbox.com/developers/reference/api#files-GET) API call to support the [single call for metadata and file content](https://www.dropbox.com/developers/announcements/14) support that Dropbox recently added
19 |
20 |
1.0-STABLE
21 | * First stable release
22 | * Full documentation support
23 | * A fully functioning sample implementation
24 |
25 |
--------------------------------------------------------------------------------
/rootca:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCB
3 | qTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf
4 | Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw
5 | MDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNV
6 | BAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3MDAwMDAwWhcNMzYw
7 | NzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5j
8 | LjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYG
9 | A1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
10 | IG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqG
11 | SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCsoPD7gFnUnMekz52hWXMJEEUMDSxuaPFs
12 | W0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ1CRfBsDMRJSUjQJib+ta
13 | 3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGcq/gcfomk
14 | 6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6
15 | Sk/KaAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94J
16 | NqR32HuHUETVPm4pafs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBA
17 | MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XP
18 | r87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUFAAOCAQEAeRHAS7ORtvzw6WfU
19 | DW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeEuzLlQRHAd9mz
20 | YJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX
21 | xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2
22 | /qxAeeWsEG89jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/
23 | LHbTY5xZ3Y+m4Q6gLkH3LpVHz7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7
24 | jVaMaA==
25 | -----END CERTIFICATE-----
26 |
--------------------------------------------------------------------------------
/src/Dropbox/API.php:
--------------------------------------------------------------------------------
1 | oauth = $oauth;
71 | $this->root = $root;
72 | $this->useSSL = $useSSL;
73 | $this->isSafeMode = (version_compare(PHP_VERSION, '5.4', '<') && get_cfg_var('safe_mode'));
74 | if (!$this->useSSL)
75 | {
76 | throw new Dropbox_Exception('Dropbox REST API now requires that all requests use SSL');
77 | }
78 |
79 | }
80 |
81 | /**
82 | * Returns information about the current dropbox account
83 | *
84 | * @return stdclass
85 | */
86 | public function getAccountInfo() {
87 |
88 | $data = $this->oauth->fetch($this->api_url . 'account/info');
89 | return json_decode($data['body'],true);
90 |
91 | }
92 |
93 | /**
94 | * Returns a file's contents
95 | *
96 | * @param string $path path
97 | * @param string $root Use this to override the default root path (sandbox/dropbox)
98 | * @return string
99 | */
100 | public function getFile($path = '', $root = null) {
101 |
102 | if (is_null($root)) $root = $this->root;
103 | $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
104 | $result = $this->oauth->fetch($this->api_content_url . 'files/' . $root . '/' . ltrim($path,'/'));
105 | return $result['body'];
106 |
107 | }
108 |
109 | /**
110 | * Uploads a new file
111 | *
112 | * @param string $path Target path (including filename)
113 | * @param string $file Either a path to a file or a stream resource
114 | * @param string $root Use this to override the default root path (sandbox/dropbox)
115 | * @return bool
116 | */
117 | public function putFile($path, $file, $root = null) {
118 |
119 | if (is_resource($file)) {
120 | $stat = fstat($file);
121 | $size = $stat['size'];
122 | } else if (is_string($file) && is_readable($file)) {
123 | $size = filesize($file);
124 | } else {
125 | throw new Dropbox_Exception('File must be a file-resource or a file path string');
126 | }
127 |
128 | if ($this->oauth->isPutSupport()) {
129 | if ($size) {
130 | if ($size > $this->chunkSize) {
131 | $res = array('uploadID' => null, 'offset' => 0);
132 | $i[$res['offset']] = 0;
133 | while($i[$res['offset']] < 5) {
134 | $res = $this->chunkedUpload($path, $file, $root, true, $res['offset'], $res['uploadID']);
135 | if (isset($res['uploadID'])) {
136 | if (!isset($i[$res['offset']])) {
137 | $i[$res['offset']] = 0;
138 | } else {
139 | $i[$res['offset']]++;
140 | }
141 | } else {
142 | break;
143 | }
144 | }
145 | return true;
146 | } else {
147 | return $this->putStream($path, $file, $root);
148 | }
149 | }
150 | }
151 |
152 | if ($size > 157286400) {
153 | // Dropbox API /files has a maximum file size limit of 150 MB.
154 | // https://www.dropbox.com/developers/core/docs#files-POST
155 | throw new Dropbox_Exception("Uploading file to Dropbox failed");
156 | }
157 |
158 | $directory = dirname($path);
159 | $filename = basename($path);
160 |
161 | if($directory==='.') $directory = '';
162 | $directory = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($directory));
163 | $filename = str_replace('~', '%7E', rawurlencode($filename));
164 | if (is_null($root)) $root = $this->root;
165 |
166 | if (is_string($file)) {
167 |
168 | $file = fopen($file,'rb');
169 |
170 | } elseif (!is_resource($file)) {
171 | throw new Dropbox_Exception('File must be a file-resource or a file path string');
172 | }
173 |
174 | if (!$this->isSafeMode) {
175 | set_time_limit(600);
176 | }
177 | $result=$this->multipartFetch($this->api_content_url . 'files/' .
178 | $root . '/' . trim($directory,'/'), $file, $filename);
179 |
180 | if(!isset($result["httpStatus"]) || $result["httpStatus"] != 200)
181 | throw new Dropbox_Exception("Uploading file to Dropbox failed");
182 |
183 | return true;
184 | }
185 |
186 | /**
187 | * Uploads large files to Dropbox in mulitple chunks
188 | *
189 | * @param string $file Absolute path to the file to be uploaded
190 | * @param string|bool $filename The destination filename of the uploaded file
191 | * @param string $path Path to upload the file to, relative to root
192 | * @param boolean $overwrite Should the file be overwritten? (Default: true)
193 | * @return stdClass
194 | */
195 | public function chunkedUpload($path, $handle, $root = null, $overwrite = true, $offset = 0, $uploadID = null)
196 | {
197 | if (is_string($handle) && is_readable($handle)) {
198 | $handle = fopen($handle, 'rb');
199 | }
200 |
201 | if (is_resource($handle)) {
202 | // Seek to the correct position on the file pointer
203 | fseek($handle, $offset);
204 |
205 | // Read from the file handle until EOF, uploading each chunk
206 | while ($data = fread($handle, $this->chunkSize)) {
207 | if (!$this->isSafeMode) {
208 | set_time_limit(600);
209 | }
210 |
211 | // Open a temporary file handle and write a chunk of data to it
212 | $chunkHandle = fopen('php://temp', 'rwb');
213 | fwrite($chunkHandle, $data);
214 |
215 | // Set the file, request parameters and send the request
216 | $this->oauth->setInFile($chunkHandle);
217 | $params = array('upload_id' => $uploadID, 'offset' => $offset);
218 |
219 | try {
220 | // Attempt to upload the current chunk
221 | $res = $this->oauth->fetch($this->api_content_url . 'chunked_upload', $params, 'PUT');
222 | $response = json_decode($res['body'], true);
223 | } catch (Exception $e) {
224 | $res = $this->oauth->getLastResponse();
225 | if ($response['httpStatus'] == 400) {
226 | // Incorrect offset supplied, return expected offset and upload ID
227 | $response = json_decode($res['body'], true);
228 | $uploadID = $response['upload_id'];
229 | $offset = $response['offset'];
230 | return array('uploadID' => $uploadID, 'offset' => $offset);
231 | } else {
232 | // Re-throw the caught Exception
233 | throw $e;
234 | }
235 | throw $e;
236 | }
237 |
238 | // On subsequent chunks, use the upload ID returned by the previous request
239 | if (isset($response['upload_id'])) {
240 | $uploadID = $response['upload_id'];
241 | }
242 |
243 | // Set the data offset
244 | if (isset($response['offset'])) {
245 | $offset = $response['offset'];
246 | }
247 |
248 | // Close the file handle for this chunk
249 | fclose($chunkHandle);
250 | }
251 |
252 | // Complete the chunked upload
253 | $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
254 | if (is_null($root)) {
255 | $root = $this->root;
256 | }
257 | $params = array('overwrite' => (int) $overwrite, 'upload_id' => $uploadID);
258 | return $this->oauth->fetch($this->api_content_url . 'commit_chunked_upload/' .
259 | $root . '/' . ltrim($path,'/'), $params, 'POST');
260 | } else {
261 | throw new Dropbox_Exception('Could not open ' . $handle . ' for reading');
262 | }
263 | }
264 |
265 | /**
266 | * Uploads file data from a stream
267 | *
268 | * Note: This function is experimental and requires further testing
269 | * @param resource $stream A readable stream created using fopen()
270 | * @param string $filename The destination filename, including path
271 | * @param boolean $overwrite Should the file be overwritten? (Default: true)
272 | * @return array
273 | */
274 | public function putStream($path, $file, $root = null, $overwrite = true)
275 | {
276 | if ($this->isSafeMode) {
277 | set_time_limit(600);
278 | }
279 |
280 | $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
281 | if (is_null($root)) {
282 | $root = $this->root;
283 | }
284 |
285 | $params = array('overwrite' => (int) $overwrite);
286 | $this->oauth->setInfile($file);
287 | $result=$this->oauth->fetch($this->api_content_url . 'files_put/' .
288 | $root . '/' . ltrim($path,'/'), $params, 'PUT');
289 |
290 | if (!isset($result["httpStatus"]) || $result["httpStatus"] != 200) {
291 | throw new Dropbox_Exception("Uploading file to Dropbox failed");
292 | }
293 |
294 | return true;
295 | }
296 |
297 | /**
298 | * Copies a file or directory from one location to another
299 | *
300 | * This method returns the file information of the newly created file.
301 | *
302 | * @param string $from source path
303 | * @param string $to destination path
304 | * @param string $root Use this to override the default root path (sandbox/dropbox)
305 | * @return stdclass
306 | */
307 | public function copy($from, $to, $root = null) {
308 |
309 | if (is_null($root)) $root = $this->root;
310 | $response = $this->oauth->fetch($this->api_url . 'fileops/copy', array('from_path' => $from, 'to_path' => $to, 'root' => $root), 'POST');
311 |
312 | return json_decode($response['body'],true);
313 |
314 | }
315 |
316 | /**
317 | * Creates a new folder
318 | *
319 | * This method returns the information from the newly created directory
320 | *
321 | * @param string $path
322 | * @param string $root Use this to override the default root path (sandbox/dropbox)
323 | * @return stdclass
324 | */
325 | public function createFolder($path, $root = null) {
326 |
327 | if (is_null($root)) $root = $this->root;
328 |
329 | // Making sure the path starts with a /
330 | $path = '/' . ltrim($path,'/');
331 |
332 | $response = $this->oauth->fetch($this->api_url . 'fileops/create_folder', array('path' => $path, 'root' => $root),'POST');
333 | return json_decode($response['body'],true);
334 |
335 | }
336 |
337 | /**
338 | * Deletes a file or folder.
339 | *
340 | * This method will return the metadata information from the deleted file or folder, if successful.
341 | *
342 | * @param string $path Path to new folder
343 | * @param string $root Use this to override the default root path (sandbox/dropbox)
344 | * @return array
345 | */
346 | public function delete($path, $root = null) {
347 |
348 | if (is_null($root)) $root = $this->root;
349 | $response = $this->oauth->fetch($this->api_url . 'fileops/delete', array('path' => $path, 'root' => $root), 'POST');
350 | return json_decode($response['body']);
351 |
352 | }
353 |
354 | /**
355 | * Moves a file or directory to a new location
356 | *
357 | * This method returns the information from the newly created directory
358 | *
359 | * @param mixed $from Source path
360 | * @param mixed $to destination path
361 | * @param string $root Use this to override the default root path (sandbox/dropbox)
362 | * @return stdclass
363 | */
364 | public function move($from, $to, $root = null) {
365 |
366 | if (is_null($root)) $root = $this->root;
367 | $response = $this->oauth->fetch($this->api_url . 'fileops/move', array('from_path' => rawurldecode($from), 'to_path' => rawurldecode($to), 'root' => $root), 'POST');
368 |
369 | return json_decode($response['body'],true);
370 |
371 | }
372 |
373 | /**
374 | * Returns file and directory information
375 | *
376 | * @param string $path Path to receive information from
377 | * @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.
378 | * @param string $hash If a hash is supplied, this method simply returns true if nothing has changed since the last request. Good for caching.
379 | * @param int $fileLimit Maximum number of file-information to receive
380 | * @param string $root Use this to override the default root path (sandbox/dropbox)
381 | * @return array|true
382 | */
383 | public function getMetaData($path, $list = true, $hash = null, $fileLimit = null, $root = null) {
384 |
385 | if (is_null($root)) $root = $this->root;
386 |
387 | $args = array(
388 | 'list' => $list,
389 | );
390 |
391 | if (!is_null($hash)) $args['hash'] = $hash;
392 | if (!is_null($fileLimit)) $args['file_limit'] = $fileLimit;
393 |
394 | $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
395 | $response = $this->oauth->fetch($this->api_url . 'metadata/' . $root . '/' . ltrim($path,'/'), $args);
396 |
397 | /* 304 is not modified */
398 | if ($response['httpStatus']==304) {
399 | return true;
400 | } else {
401 | return json_decode($response['body'],true);
402 | }
403 |
404 | }
405 |
406 | /**
407 | * 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.
408 | *
409 | * This method returns the information from the newly created directory
410 | *
411 | * @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.
412 | * @return stdclass
413 | */
414 | public function delta($cursor) {
415 |
416 | $arg['cursor'] = $cursor;
417 |
418 | $response = $this->oauth->fetch($this->api_url . 'delta', $arg, 'POST');
419 | return json_decode($response['body'],true);
420 |
421 | }
422 |
423 | /**
424 | * Returns a thumbnail (as a string) for a file path.
425 | *
426 | * @param string $path Path to file
427 | * @param string $size small, medium or large
428 | * @param string $root Use this to override the default root path (sandbox/dropbox)
429 | * @return string
430 | */
431 | public function getThumbnail($path, $size = 'small', $root = null) {
432 |
433 | if (is_null($root)) $root = $this->root;
434 | $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
435 | $response = $this->oauth->fetch($this->api_content_url . 'thumbnails/' . $root . '/' . ltrim($path,'/'),array('size' => $size));
436 |
437 | return $response['body'];
438 |
439 | }
440 |
441 | /**
442 | * This method is used to generate multipart POST requests for file upload
443 | *
444 | * @param string $uri
445 | * @param array $arguments
446 | * @return bool
447 | */
448 | protected function multipartFetch($uri, $file, $filename) {
449 |
450 | /* random string */
451 | $boundary = 'R50hrfBj5JYyfR3vF3wR96GPCC9Fd2q2pVMERvEaOE3D8LZTgLLbRpNwXek3';
452 |
453 | $headers = array(
454 | 'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
455 | );
456 |
457 | $body="--" . $boundary . "\r\n";
458 | $body.="Content-Disposition: form-data; name=file; filename=".rawurldecode($filename)."\r\n";
459 | $body.="Content-type: application/octet-stream\r\n";
460 | $body.="\r\n";
461 | $body.=stream_get_contents($file);
462 | $body.="\r\n";
463 | $body.="--" . $boundary . "--";
464 |
465 | // Dropbox requires the filename to also be part of the regular arguments, so it becomes
466 | // part of the signature.
467 | $uri.='?file=' . $filename;
468 |
469 | return $this->oauth->fetch($uri, $body, 'POST', $headers);
470 |
471 | }
472 |
473 |
474 | /**
475 | * Search
476 | *
477 | * Returns metadata for all files and folders that match the search query.
478 | *
479 | * @author: diszo.sasil
480 | *
481 | * @param string $query
482 | * @param string $root Use this to override the default root path (sandbox/dropbox)
483 | * @param string $path
484 | * @return array
485 | */
486 | public function search($query = '', $root = null, $path = ''){
487 | if (is_null($root)) $root = $this->root;
488 | if(!empty($path)){
489 | $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
490 | }
491 | $response = $this->oauth->fetch($this->api_url . 'search/' . $root . '/' . ltrim($path,'/'),array('query' => $query));
492 | return json_decode($response['body'],true);
493 | }
494 |
495 | /**
496 | * Creates and returns a shareable link to files or folders.
497 | *
498 | * Note: Links created by the /shares API call expire after thirty days.
499 | *
500 | * @param string $path
501 | * @param string $root Use this to override the default root path (sandbox/dropbox)
502 | * @param string $short_url When true (default), the URL returned will be shortened using the Dropbox URL shortener
503 | * @return array
504 | */
505 | public function share($path, $root = null, $short_url = true) {
506 | if (is_null($root)) $root = $this->root;
507 | $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
508 | $short_url = ((is_string($short_url) && strtolower($short_url) === 'false') || !$short_url)? 'false' : 'true';
509 | $response = $this->oauth->fetch($this->api_url. 'shares/'. $root . '/' . ltrim($path, '/'), array('short_url' => $short_url), 'POST');
510 | return json_decode($response['body'],true);
511 |
512 | }
513 |
514 | /**
515 | * Returns a link directly to a file.
516 | * 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.
517 | *
518 | * Note: The /media link expires after four hours, allotting enough time to stream files, but not enough to leave a connection open indefinitely.
519 | *
520 | * @param type $path
521 | * @param type $root
522 | * @return type
523 | */
524 | public function media($path, $root = null) {
525 |
526 | if (is_null($root)) $root = $this->root;
527 | $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
528 | $response = $this->oauth->fetch($this->api_url. 'media/'. $root . '/' . ltrim($path, '/'), array(), 'POST');
529 | return json_decode($response['body'],true);
530 |
531 | }
532 |
533 | /**
534 | * 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.
535 | *
536 | * @param type $path
537 | * @param type $root
538 | * @return type
539 | */
540 | public function copy_ref($path, $root = null) {
541 |
542 | if (is_null($root)) $root = $this->root;
543 | $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
544 | $response = $this->oauth->fetch($this->api_url. 'copy_ref/'. $root . '/' . ltrim($path, '/'));
545 | return json_decode($response['body'],true);
546 |
547 | }
548 |
549 |
550 | }
551 |
--------------------------------------------------------------------------------
/src/Dropbox/Exception.php:
--------------------------------------------------------------------------------
1 | oauth_token = $token['token'];
114 | $this->oauth_token_secret = $token['token_secret'];
115 | } else {
116 | $this->oauth_token = $token;
117 | $this->oauth_token_secret = $token_secret;
118 | }
119 |
120 | }
121 |
122 | /**
123 | * Returns the oauth request tokens as an associative array.
124 | *
125 | * The array will contain the elements 'token' and 'token_secret'.
126 | *
127 | * @return array
128 | */
129 | public function getToken() {
130 |
131 | return array(
132 | 'token' => $this->oauth_token,
133 | 'token_secret' => $this->oauth_token_secret,
134 | );
135 |
136 | }
137 |
138 | /**
139 | * Returns the authorization url
140 | *
141 | * @param string $callBack Specify a callback url to automatically redirect the user back
142 | * @return string
143 | */
144 | public function getAuthorizeUrl($callBack = null) {
145 |
146 | // Building the redirect uri
147 | $token = $this->getToken();
148 | $uri = self::URI_AUTHORIZE . '?oauth_token=' . $token['token'];
149 | if ($callBack) $uri.='&oauth_callback=' . $callBack;
150 | return $uri;
151 | }
152 |
153 | /**
154 | * Set input file for PUT method
155 | *
156 | * @param resource|string $file
157 | * @throws Dropbox_Exception
158 | */
159 | public function setInfile($file) {
160 | if (is_resource($file)) {
161 | $stat = fstat($file);
162 | $this->inFileSize = $stat['size'];
163 | } else if (is_string($file) && is_readable($file)) {
164 | $this->inFileSize = filesize($file);
165 | $file = fopen($file, 'rb');
166 | }
167 | if (!is_resource($file)) {
168 | throw new Dropbox_Exception('File must be a file-resource or a string');
169 | }
170 | $this->inFile = $file;
171 | }
172 |
173 | /**
174 | * Return is PUT method supported
175 | *
176 | * @return boolean
177 | */
178 | public function isPutSupport() {
179 | return $this->putSupported;
180 | }
181 |
182 | /**
183 | * Get last request response
184 | *
185 | * @return array:
186 | */
187 | public function getLastResponse() {
188 | return $this->lastResponse;
189 | }
190 |
191 | /**
192 | * Fetches a secured oauth url and returns the response body.
193 | *
194 | * @param string $uri
195 | * @param mixed $arguments
196 | * @param string $method
197 | * @param array $httpHeaders
198 | * @return string
199 | */
200 | public abstract function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array());
201 |
202 | /**
203 | * Requests the OAuth request token.
204 | *
205 | * @return array
206 | */
207 | abstract public function getRequestToken();
208 |
209 | /**
210 | * Requests the OAuth access tokens.
211 | *
212 | * @return array
213 | */
214 | abstract public function getAccessToken();
215 |
216 | }
217 |
--------------------------------------------------------------------------------
/src/Dropbox/OAuth/Consumer/Dropbox.php:
--------------------------------------------------------------------------------
1 | consumerRequest instanceof HTTP_OAuth_Consumer_Request) {
25 | $this->consumerRequest = new HTTP_OAuth_Consumer_Request;
26 | }
27 |
28 | // TODO: Change this and add in code to validate the SSL cert.
29 | // see https://github.com/bagder/curl/blob/master/lib/mk-ca-bundle.pl
30 | $this->consumerRequest->setConfig(array(
31 | 'ssl_verify_peer' => false,
32 | 'ssl_verify_host' => false
33 | ));
34 |
35 | return $this->consumerRequest;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/Dropbox/OAuth/Curl.php:
--------------------------------------------------------------------------------
1 | consumerKey = $consumerKey;
46 | $this->consumerSecret = $consumerSecret;
47 | $this->putSupported = true;
48 | }
49 |
50 | /**
51 | * Fetches a secured oauth url and returns the response body.
52 | *
53 | * @param string $uri
54 | * @param mixed $arguments
55 | * @param string $method
56 | * @param array $httpHeaders
57 | * @return string
58 | */
59 | public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) {
60 |
61 | $uri=str_replace('http://', 'https://', $uri); // all https, upload makes problems if not
62 | if (is_string($arguments) and strtoupper($method) == 'POST') {
63 | preg_match("/\?file=(.*)$/i", $uri, $matches);
64 | if (isset($matches[1])) {
65 | $uri = str_replace($matches[0], "", $uri);
66 | $filename = rawurldecode(str_replace('%7E', '~', $matches[1]));
67 | $httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, array("file" => $filename), $method));
68 | }
69 | } else {
70 | $httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, $arguments, $method));
71 | }
72 | $ch = curl_init();
73 | if (strtoupper($method) == 'POST') {
74 | curl_setopt($ch, CURLOPT_URL, $uri);
75 | curl_setopt($ch, CURLOPT_POST, true);
76 | if (is_array($arguments)) {
77 | $arguments=http_build_query($arguments);
78 | }
79 | curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments);
80 | $httpHeaders['Content-Length']=strlen($arguments);
81 | } else if (strtoupper($method) == 'PUT' && $this->inFile) {
82 | curl_setopt($ch, CURLOPT_URL, $uri.'?'.http_build_query($arguments));
83 | curl_setopt($ch, CURLOPT_PUT, true);
84 | curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
85 | curl_setopt($ch, CURLOPT_INFILE, $this->inFile);
86 | curl_setopt($ch, CURLOPT_INFILESIZE, $this->inFileSize);
87 | fseek($this->inFile, 0);
88 | $this->inFileSize = $this->inFile = null;
89 | } else {
90 | curl_setopt($ch, CURLOPT_URL, $uri.'?'.http_build_query($arguments));
91 | curl_setopt($ch, CURLOPT_POST, false);
92 | }
93 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
94 | curl_setopt($ch, CURLOPT_TIMEOUT, 600);
95 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
96 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
97 | curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
98 | curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ca-bundle.pem');
99 | //Build header
100 | $headers = array();
101 | foreach ($httpHeaders as $name => $value) {
102 | $headers[] = "{$name}: $value";
103 | }
104 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
105 | if (!ini_get('safe_mode') && !ini_get('open_basedir'))
106 | curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
107 | if (function_exists($this->ProgressFunction) and defined('CURLOPT_PROGRESSFUNCTION')) {
108 | curl_setopt($ch, CURLOPT_NOPROGRESS, false);
109 | curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $this->ProgressFunction);
110 | curl_setopt($ch, CURLOPT_BUFFERSIZE, 512);
111 | }
112 | $response=curl_exec($ch);
113 | $errorno=curl_errno($ch);
114 | $error=curl_error($ch);
115 | $status=curl_getinfo($ch,CURLINFO_HTTP_CODE);
116 | curl_close($ch);
117 |
118 | $this->lastResponse = array(
119 | 'httpStatus' => $status,
120 | 'body' => $response
121 | );
122 |
123 | if (!empty($errorno))
124 | throw new Dropbox_Exception_NotFound('Curl error: ('.$errorno.') '.$error."\n");
125 |
126 | if ($status>=300) {
127 | $body = array();
128 | $body = json_decode($response, true);
129 | if (!is_array($body)) {
130 | $body = array();
131 | }
132 | $jsonErr = isset($body['error'])? $body['error'] : '';
133 | switch ($status) {
134 | // Not modified
135 | case 304 :
136 | return array(
137 | 'httpStatus' => 304,
138 | 'body' => null,
139 | );
140 | break;
141 | case 400 :
142 | throw new Dropbox_Exception_Forbidden('Forbidden. Bad input parameter. Error message should indicate which one and why.');
143 | case 401 :
144 | 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.');
145 | case 403 :
146 | throw new Dropbox_Exception_Forbidden('Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location.');
147 | case 404 :
148 | throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found');
149 | case 405 :
150 | throw new Dropbox_Exception_Forbidden('Forbidden. Request method not expected (generally should be GET or POST).');
151 | case 500 :
152 | throw new Dropbox_Exception_Forbidden('Server error. ' . $jsonErr);
153 | case 503 :
154 | 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.');
155 | case 507 :
156 | throw new Dropbox_Exception_OverQuota('This dropbox is full');
157 | default:
158 | throw new Dropbox_Exception_RequestToken('Error: ('.$status.') ' . $jsonErr);
159 |
160 | }
161 | if (!empty($body["error"]))
162 | throw new Dropbox_Exception_RequestToken('Error: ('.$status.') ' . $jsonErr);
163 | }
164 |
165 | return array(
166 | 'body' => $response,
167 | 'httpStatus' => $status
168 | );
169 | }
170 |
171 | /**
172 | * Returns named array with oauth parameters for further use
173 | * @return array Array with oauth_ parameters
174 | */
175 | private function getOAuthBaseParams() {
176 | $params['oauth_version'] = '1.0';
177 | $params['oauth_signature_method'] = 'HMAC-SHA1';
178 |
179 | $params['oauth_consumer_key'] = $this->consumerKey;
180 | $tokens = $this->getToken();
181 | if (isset($tokens['token']) && $tokens['token']) {
182 | $params['oauth_token'] = $tokens['token'];
183 | }
184 | $params['oauth_timestamp'] = time();
185 | $params['oauth_nonce'] = md5(microtime() . mt_rand());
186 | return $params;
187 | }
188 |
189 | /**
190 | * Creates valid Authorization header for OAuth, based on URI and Params
191 | *
192 | * @param string $uri
193 | * @param array $params
194 | * @param string $method GET or POST, standard is GET
195 | * @param array $oAuthParams optional, pass your own oauth_params here
196 | * @return array Array for request's headers section like
197 | * array('Authorization' => 'OAuth ...');
198 | */
199 | private function getOAuthHeader($uri, $params, $method = 'GET', $oAuthParams = null) {
200 | $oAuthParams = $oAuthParams ? $oAuthParams : $this->getOAuthBaseParams();
201 |
202 | // create baseString to encode for the sent parameters
203 | $baseString = $method . '&';
204 | $baseString .= $this->oauth_urlencode($uri) . "&";
205 |
206 | // OAuth header does not include GET-Parameters
207 | $signatureParams = array_merge($params, $oAuthParams);
208 |
209 | // sorting the parameters
210 | ksort($signatureParams);
211 |
212 | $encodedParams = array();
213 | foreach ($signatureParams as $key => $value) {
214 | if (!is_null($value)) $encodedParams[] = rawurlencode($key) . '=' . rawurlencode($value);
215 | }
216 |
217 | $baseString .= $this->oauth_urlencode(implode('&', $encodedParams));
218 |
219 | // encode the signature
220 | $tokens = $this->getToken();
221 | $hash = $this->hash_hmac_sha1($this->consumerSecret.'&'.$tokens['token_secret'], $baseString);
222 | $signature = base64_encode($hash);
223 |
224 | // add signature to oAuthParams
225 | $oAuthParams['oauth_signature'] = $signature;
226 |
227 | $oAuthEncoded = array();
228 | foreach ($oAuthParams as $key => $value) {
229 | $oAuthEncoded[] = $key . '="' . $this->oauth_urlencode($value) . '"';
230 | }
231 |
232 | return array('Authorization' => 'OAuth ' . implode(', ', $oAuthEncoded));
233 | }
234 |
235 | /**
236 | * Requests the OAuth request token.
237 | *
238 | * @return void
239 | */
240 | public function getRequestToken() {
241 | $result = $this->fetch(self::URI_REQUEST_TOKEN, array(), 'POST');
242 | if ($result['httpStatus'] == "200") {
243 | $tokens = array();
244 | parse_str($result['body'], $tokens);
245 | $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
246 | return $this->getToken();
247 | } else {
248 | throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.');
249 | }
250 | }
251 |
252 | /**
253 | * Requests the OAuth access tokens.
254 | *
255 | * This method requires the 'unauthorized' request tokens
256 | * and, if successful will set the authorized request tokens.
257 | *
258 | * @return void
259 | */
260 | public function getAccessToken() {
261 | $result = $this->fetch(self::URI_ACCESS_TOKEN, array(), 'POST');
262 | if ($result['httpStatus'] == "200") {
263 | $tokens = array();
264 | parse_str($result['body'], $tokens);
265 | $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
266 | return $this->getToken();
267 | } else {
268 | throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.');
269 | }
270 | }
271 |
272 | /**
273 | * Helper function to properly urlencode parameters.
274 | * See http://php.net/manual/en/function.oauth-urlencode.php
275 | *
276 | * @param string $string
277 | * @return string
278 | */
279 | private function oauth_urlencode($string) {
280 | return str_replace('%E7', '~', rawurlencode($string));
281 | }
282 |
283 | /**
284 | * Hash function for hmac_sha1; uses native function if available.
285 | *
286 | * @param string $key
287 | * @param string $data
288 | * @return string
289 | */
290 | private function hash_hmac_sha1($key, $data) {
291 | if (function_exists('hash_hmac') && in_array('sha1', hash_algos())) {
292 | return hash_hmac('sha1', $data, $key, true);
293 | } else {
294 | $blocksize = 64;
295 | $hashfunc = 'sha1';
296 | if (strlen($key) > $blocksize) {
297 | $key = pack('H*', $hashfunc($key));
298 | }
299 |
300 | $key = str_pad($key, $blocksize, chr(0x00));
301 | $ipad = str_repeat(chr(0x36), $blocksize);
302 | $opad = str_repeat(chr(0x5c), $blocksize);
303 | $hash = pack('H*', $hashfunc(( $key ^ $opad ) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));
304 |
305 | return $hash;
306 | }
307 | }
308 |
309 |
310 | }
311 |
--------------------------------------------------------------------------------
/src/Dropbox/OAuth/PEAR.php:
--------------------------------------------------------------------------------
1 | OAuth = new Dropbox_OAuth_Consumer_Dropbox($consumerKey, $consumerSecret);
53 | $this->consumerKey = $consumerKey;
54 | }
55 |
56 | /**
57 | * Sets the request token and secret.
58 | *
59 | * The tokens can also be passed as an array into the first argument.
60 | * The array must have the elements token and token_secret.
61 | *
62 | * @param string|array $token
63 | * @param string $token_secret
64 | * @return void
65 | */
66 | public function setToken($token, $token_secret = null) {
67 |
68 | parent::setToken($token,$token_secret);
69 | $this->OAuth->setToken($this->oauth_token);
70 | $this->OAuth->setTokenSecret($this->oauth_token_secret);
71 |
72 | }
73 |
74 | /**
75 | * Fetches a secured oauth url and returns the response body.
76 | *
77 | * @param string $uri
78 | * @param mixed $arguments
79 | * @param string $method
80 | * @param array $httpHeaders
81 | * @return string
82 | */
83 | public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array())
84 | {
85 | $httpRequest = new HTTP_Request2(null,
86 | HTTP_Request2::METHOD_GET,
87 | array(
88 | 'ssl_verify_peer' => false,
89 | 'ssl_verify_host' => false
90 | )
91 | );
92 |
93 | $consumerRequest = new HTTP_OAuth_Consumer_Request();
94 | $consumerRequest->accept($httpRequest);
95 | $consumerRequest->setUrl($uri);
96 | $consumerRequest->setMethod($method);
97 | $consumerRequest->setSecrets($this->OAuth->getSecrets());
98 |
99 | $parameters = array(
100 | 'oauth_consumer_key' => $this->consumerKey,
101 | 'oauth_signature_method' => 'HMAC-SHA1',
102 | 'oauth_token' => $this->oauth_token,
103 | );
104 |
105 |
106 | if (is_array($arguments)) {
107 | $parameters = array_merge($parameters,$arguments);
108 | } elseif (is_string($arguments)) {
109 | $consumerRequest->setBody($arguments);
110 | }
111 | $consumerRequest->setParameters($parameters);
112 |
113 |
114 | if (count($httpHeaders)) {
115 | foreach($httpHeaders as $k=>$v) {
116 | $consumerRequest->setHeader($k, $v);
117 | }
118 | }
119 |
120 | $response = $consumerRequest->send();
121 |
122 | switch($response->getStatus()) {
123 |
124 | // Not modified
125 | case 304 :
126 | return array(
127 | 'httpStatus' => 304,
128 | 'body' => null,
129 | );
130 | break;
131 | case 400 :
132 | throw new Dropbox_Exception_Forbidden('Forbidden. Bad input parameter. Error message should indicate which one and why.');
133 | case 401 :
134 | 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.');
135 | case 403 :
136 | throw new Dropbox_Exception_Forbidden('Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location.');
137 | case 404 :
138 | throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found');
139 | case 405 :
140 | throw new Dropbox_Exception_Forbidden('Forbidden. Request method not expected (generally should be GET or POST).');
141 | case 500 :
142 | throw new Dropbox_Exception_Forbidden('Server error. ' . $e->getMessage());
143 | case 503 :
144 | 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.');
145 | case 507 :
146 | throw new Dropbox_Exception_OverQuota('This dropbox is full');
147 |
148 | }
149 |
150 | return array(
151 | 'httpStatus' => $response->getStatus(),
152 | 'body' => $response->getBody()
153 | );
154 |
155 | }
156 |
157 | /**
158 | * Requests the OAuth request token.
159 | *
160 | * @return void
161 | */
162 | public function getRequestToken() {
163 |
164 | $this->OAuth->getRequestToken(self::URI_REQUEST_TOKEN);
165 | $this->setToken($this->OAuth->getToken(), $this->OAuth->getTokenSecret());
166 | return $this->getToken();
167 |
168 | }
169 |
170 | /**
171 | * Requests the OAuth access tokens.
172 | *
173 | * This method requires the 'unauthorized' request tokens
174 | * and, if successful will set the authorized request tokens.
175 | *
176 | * @return void
177 | */
178 | public function getAccessToken() {
179 |
180 | $this->OAuth->getAccessToken(self::URI_ACCESS_TOKEN);
181 | $this->setToken($this->OAuth->getToken(), $this->OAuth->getTokenSecret());
182 | return $this->getToken();
183 |
184 | }
185 |
186 |
187 | }
188 |
--------------------------------------------------------------------------------
/src/Dropbox/OAuth/PHP.php:
--------------------------------------------------------------------------------
1 | OAuth = new OAuth($consumerKey, $consumerSecret,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
39 | $this->OAuth->enableDebug();
40 |
41 | }
42 |
43 | /**
44 | * Sets the request token and secret.
45 | *
46 | * The tokens can also be passed as an array into the first argument.
47 | * The array must have the elements token and token_secret.
48 | *
49 | * @param string|array $token
50 | * @param string $token_secret
51 | * @return void
52 | */
53 | public function setToken($token, $token_secret = null) {
54 |
55 | parent::setToken($token,$token_secret);
56 | $this->OAuth->setToken($this->oauth_token, $this->oauth_token_secret);
57 |
58 | }
59 |
60 |
61 | /**
62 | * Fetches a secured oauth url and returns the response body.
63 | *
64 | * @param string $uri
65 | * @param mixed $arguments
66 | * @param string $method
67 | * @param array $httpHeaders
68 | * @return string
69 | */
70 | public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) {
71 |
72 | try {
73 | $this->OAuth->fetch($uri, $arguments, $method, $httpHeaders);
74 | $result = $this->OAuth->getLastResponse();
75 | $lastResponseInfo = $this->OAuth->getLastResponseInfo();
76 | return array(
77 | 'httpStatus' => $lastResponseInfo['http_code'],
78 | 'body' => $result,
79 | );
80 | } catch (OAuthException $e) {
81 |
82 | $lastResponseInfo = $this->OAuth->getLastResponseInfo();
83 | switch($lastResponseInfo['http_code']) {
84 |
85 | // Not modified
86 | case 304 :
87 | return array(
88 | 'httpStatus' => 304,
89 | 'body' => null,
90 | );
91 | break;
92 | case 400 :
93 | throw new Dropbox_Exception_Forbidden('Forbidden. Bad input parameter. Error message should indicate which one and why.');
94 | case 401 :
95 | 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.');
96 | case 403 :
97 | throw new Dropbox_Exception_Forbidden('Forbidden. This could mean a bad OAuth request, or a file or folder already existing at the target location.');
98 | case 404 :
99 | throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found');
100 | case 405 :
101 | throw new Dropbox_Exception_Forbidden('Forbidden. Request method not expected (generally should be GET or POST).');
102 | case 500 :
103 | throw new Dropbox_Exception_Forbidden('Server error. ' . $e->getMessage());
104 | case 503 :
105 | 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.');
106 | case 507 :
107 | throw new Dropbox_Exception_OverQuota('This dropbox is full');
108 | default:
109 | // rethrowing
110 | throw $e;
111 | }
112 |
113 | }
114 |
115 | }
116 |
117 | /**
118 | * Requests the OAuth request token.
119 | *
120 | * @return void
121 | */
122 | public function getRequestToken() {
123 |
124 | try {
125 |
126 | $tokens = $this->OAuth->getRequestToken(self::URI_REQUEST_TOKEN);
127 | $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
128 | return $this->getToken();
129 |
130 | } catch (OAuthException $e) {
131 |
132 | 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);
133 |
134 | }
135 |
136 | }
137 |
138 |
139 | /**
140 | * Requests the OAuth access tokens.
141 | *
142 | * This method requires the 'unauthorized' request tokens
143 | * and, if successful will set the authorized request tokens.
144 | *
145 | * @return void
146 | */
147 | public function getAccessToken() {
148 |
149 | $uri = self::URI_ACCESS_TOKEN;
150 | $tokens = $this->OAuth->getAccessToken($uri);
151 | $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
152 | return $this->getToken();
153 |
154 | }
155 |
156 |
157 | }
158 |
--------------------------------------------------------------------------------
/src/Dropbox/OAuth/Wordpress.php:
--------------------------------------------------------------------------------
1 | consumerKey = $consumerKey;
44 | $this->consumerSecret = $consumerSecret;
45 | }
46 |
47 | /**
48 | * Fetches a secured oauth url and returns the response body.
49 | *
50 | * @param string $uri
51 | * @param mixed $arguments
52 | * @param string $method
53 | * @param array $httpHeaders
54 | * @return string
55 | */
56 | public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) {
57 |
58 | $requestParams = array();
59 |
60 | $requestParams['method'] = $method;
61 | $oAuthHeader = $this->getOAuthHeader($uri, $arguments, $method);
62 | $requestParams['headers'] = array_merge($httpHeaders, $oAuthHeader);
63 |
64 | // arguments will be passed to uri for GET, to body for POST etc.
65 | if ($method == 'GET') {
66 | $uri .= '?' . http_build_query($arguments);
67 | } else {
68 | if (count($arguments)) {
69 | $requestParams['body'] = $arguments;
70 | }
71 | }
72 |
73 | $request = new WP_Http;
74 |
75 | //$uri = str_replace('api.dropbox.com', 'localhost:12346', $uri);
76 |
77 | $result = $request->request($uri, $requestParams);
78 |
79 | return array(
80 | 'httpStatus' => $result['response']['code'],
81 | 'body' => $result['body'],
82 | );
83 | }
84 |
85 | /**
86 | * Returns named array with oauth parameters for further use
87 | * @return array Array with oauth_ parameters
88 | */
89 | private function getOAuthBaseParams() {
90 | $params['oauth_version'] = '1.0';
91 | $params['oauth_signature_method'] = 'HMAC-SHA1';
92 |
93 | $params['oauth_consumer_key'] = $this->consumerKey;
94 | $tokens = $this->getToken();
95 | if (isset($tokens['token']) && $tokens['token']) {
96 | $params['oauth_token'] = $tokens['token'];
97 | }
98 | $params['oauth_timestamp'] = time();
99 | $params['oauth_nonce'] = md5(microtime() . mt_rand());
100 | return $params;
101 | }
102 |
103 | /**
104 | * Creates valid Authorization header for OAuth, based on URI and Params
105 | *
106 | * @param string $uri
107 | * @param array $params
108 | * @param string $method GET or POST, standard is GET
109 | * @param array $oAuthParams optional, pass your own oauth_params here
110 | * @return array Array for request's headers section like
111 | * array('Authorization' => 'OAuth ...');
112 | */
113 | private function getOAuthHeader($uri, $params, $method = 'GET', $oAuthParams = null) {
114 | $oAuthParams = $oAuthParams ? $oAuthParams : $this->getOAuthBaseParams();
115 |
116 | // create baseString to encode for the sent parameters
117 | $baseString = $method . '&';
118 | $baseString .= $this->oauth_urlencode($uri) . "&";
119 |
120 | // OAuth header does not include GET-Parameters
121 | $signatureParams = array_merge($params, $oAuthParams);
122 |
123 | // sorting the parameters
124 | ksort($signatureParams);
125 |
126 | $encodedParams = array();
127 | foreach ($signatureParams as $key => $value) {
128 | $encodedParams[] = $this->oauth_urlencode($key) . '=' . $this->oauth_urlencode($value);
129 | }
130 |
131 | $baseString .= $this->oauth_urlencode(implode('&', $encodedParams));
132 |
133 | // encode the signature
134 | $tokens = $this->getToken();
135 | $hash = $this->hash_hmac_sha1($this->consumerSecret.'&'.$tokens['token_secret'], $baseString);
136 | $signature = base64_encode($hash);
137 |
138 | // add signature to oAuthParams
139 | $oAuthParams['oauth_signature'] = $signature;
140 |
141 | $oAuthEncoded = array();
142 | foreach ($oAuthParams as $key => $value) {
143 | $oAuthEncoded[] = $key . '="' . $this->oauth_urlencode($value) . '"';
144 | }
145 |
146 | return array('Authorization' => 'OAuth ' . implode(', ', $oAuthEncoded));
147 | }
148 |
149 | /**
150 | * Requests the OAuth request token.
151 | *
152 | * @return void
153 | */
154 | public function getRequestToken() {
155 | $result = $this->fetch(self::URI_REQUEST_TOKEN, array(), 'POST');
156 | if ($result['httpStatus'] == "200") {
157 | $tokens = array();
158 | parse_str($result['body'], $tokens);
159 | $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
160 | return $this->getToken();
161 | } else {
162 | throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.');
163 | }
164 | }
165 |
166 | /**
167 | * Requests the OAuth access tokens.
168 | *
169 | * This method requires the 'unauthorized' request tokens
170 | * and, if successful will set the authorized request tokens.
171 | *
172 | * @return void
173 | */
174 | public function getAccessToken() {
175 | $result = $this->fetch(self::URI_ACCESS_TOKEN, array(), 'POST');
176 | if ($result['httpStatus'] == "200") {
177 | $tokens = array();
178 | parse_str($result['body'], $tokens);
179 | $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
180 | return $this->getToken();
181 | } else {
182 | throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.');
183 | }
184 | }
185 |
186 | /**
187 | * Helper function to properly urlencode parameters.
188 | * See http://php.net/manual/en/function.oauth-urlencode.php
189 | *
190 | * @param string $string
191 | * @return string
192 | */
193 | private function oauth_urlencode($string) {
194 | return str_replace('%E7', '~', rawurlencode($string));
195 | }
196 |
197 | /**
198 | * Hash function for hmac_sha1; uses native function if available.
199 | *
200 | * @param string $key
201 | * @param string $data
202 | * @return string
203 | */
204 | private function hash_hmac_sha1($key, $data) {
205 | if (function_exists('hash_hmac') && in_array('sha1', hash_algos())) {
206 | return hash_hmac('sha1', $data, $key, true);
207 | } else {
208 | $blocksize = 64;
209 | $hashfunc = 'sha1';
210 | if (strlen($key) > $blocksize) {
211 | $key = pack('H*', $hashfunc($key));
212 | }
213 |
214 | $key = str_pad($key, $blocksize, chr(0x00));
215 | $ipad = str_repeat(chr(0x36), $blocksize);
216 | $opad = str_repeat(chr(0x5c), $blocksize);
217 | $hash = pack('H*', $hashfunc(( $key ^ $opad ) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));
218 |
219 | return $hash;
220 | }
221 | }
222 |
223 | }
--------------------------------------------------------------------------------
/src/Dropbox/OAuth/Zend.php:
--------------------------------------------------------------------------------
1 |
9 | * @license http://code.google.com/p/dropbox-php/wiki/License MIT
10 | */
11 |
12 | /**
13 | * This class is used to sign all requests to dropbox
14 | *
15 | * This classes use the Zend_Oauth package.
16 | */
17 | class Dropbox_OAuth_Zend extends Dropbox_OAuth {
18 |
19 | /**
20 | * OAuth object
21 | *
22 | * @var Zend_Oauth_Consumer
23 | */
24 | protected $oAuth;
25 | /**
26 | * OAuth consumer key
27 | *
28 | * We need to keep this around for later.
29 | *
30 | * @var string
31 | */
32 | protected $consumerKey;
33 | /**
34 | *
35 | * @var Zend_Oauth_Token
36 | */
37 | protected $zend_oauth_token;
38 |
39 | /**
40 | * Constructor
41 | *
42 | * @param string $consumerKey
43 | * @param string $consumerSecret
44 | */
45 | public function __construct($consumerKey, $consumerSecret) {
46 | if (!class_exists('Zend_Oauth_Consumer')) {
47 | // We're going to try to load in manually
48 | include 'Zend/Oauth/Consumer.php';
49 | }
50 | if (!class_exists('Zend_Oauth_Consumer'))
51 | throw new Dropbox_Exception('The Zend_Oauth_Consumer class could not be found!');
52 | $this->OAuth = new Zend_Oauth_Consumer(array(
53 | "consumerKey" => $consumerKey,
54 | "consumerSecret" => $consumerSecret,
55 | "requestTokenUrl" => self::URI_REQUEST_TOKEN,
56 | "accessTokenUrl" => self::URI_ACCESS_TOKEN,
57 | "authorizeUrl" => self::URI_AUTHORIZE,
58 | "signatureMethod" => "HMAC-SHA1",
59 | ));
60 | $this->consumerKey = $consumerKey;
61 | }
62 |
63 | /**
64 | * Sets the request token and secret.
65 | *
66 | * The tokens can also be passed as an array into the first argument.
67 | * The array must have the elements token and token_secret.
68 | *
69 | * @param string|array $token
70 | * @param string $token_secret
71 | * @return void
72 | */
73 | public function setToken($token, $token_secret = null) {
74 | if (is_a($token, "Zend_Oauth_Token")) {
75 | if (is_a($token, "Zend_Oauth_Token_Access")) {
76 | $this->OAuth->setToken($token);
77 | }
78 | $this->zend_oauth_token = $token;
79 | return parent::setToken($token->getToken(), $token->getTokenSecret());
80 | } elseif (is_string($token) && is_null($token_secret)) {
81 | return $this->setToken(unserialize($token));
82 | } elseif (isset($token['zend_oauth_token'])) {
83 | return $this->setToken(unserialize($token['zend_oauth_token']));
84 | } else {
85 | parent::setToken($token, $token_secret);
86 | return;
87 | }
88 | }
89 |
90 | /**
91 | * Fetches a secured oauth url and returns the response body.
92 | *
93 | * @param string $uri
94 | * @param mixed $arguments
95 | * @param string $method
96 | * @param array $httpHeaders
97 | * @return string
98 | */
99 | public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) {
100 | $token = $this->OAuth->getToken();
101 | if (!is_a($token, "Zend_Oauth_Token")) {
102 | if (is_a($this->zend_oauth_token, "Zend_Oauth_Token_Access")) {
103 | $token = $this->zend_oauth_token;
104 | } else {
105 | $token = new Zend_Oauth_Token_Access();
106 | $token->setToken($this->oauth_token);
107 | $token->setTokenSecret($this->oauth_token_secret);
108 | }
109 | }
110 | /* @var $token Zend_Oauth_Token_Access */
111 | $oauthOptions = array(
112 | 'consumerKey' => $this->consumerKey,
113 | 'signatureMethod' => "HMAC-SHA1",
114 | 'consumerSecret' => $this->OAuth->getConsumerSecret(),
115 | );
116 | $config = array("timeout" => 15);
117 |
118 | /* @var $consumerRequest Zend_Oauth_Client */
119 | $consumerRequest = $token->getHttpClient($oauthOptions);
120 | $consumerRequest->setMethod($method);
121 | if (is_array($arguments)) {
122 | $consumerRequest->setUri($uri);
123 | if ($method == "GET") {
124 | foreach ($arguments as $param => $value) {
125 | $consumerRequest->setParameterGet($param, $value);
126 | }
127 | } else {
128 | foreach ($arguments as $param => $value) {
129 | $consumerRequest->setParameterPost($param, $value);
130 | }
131 | }
132 | } elseif (is_string($arguments)) {
133 | preg_match("/\?file=(.*)$/i", $uri, $matches);
134 | if (isset($matches[1])) {
135 | $uri = str_replace($matches[0], "", $uri);
136 | $filename = $matches[1];
137 | $uri = Zend_Uri::factory($uri);
138 | $uri->addReplaceQueryParameters(array("file" => $filename));
139 | $consumerRequest->setParameterGet("file", $filename);
140 | }
141 | $consumerRequest->setUri($uri);
142 | $consumerRequest->setRawData($arguments);
143 | } elseif (is_resource($arguments)) {
144 | $consumerRequest->setUri($uri);
145 | /** Placeholder for Oauth streaming support. */
146 | }
147 | if (count($httpHeaders)) {
148 | foreach ($httpHeaders as $k => $v) {
149 | $consumerRequest->setHeaders($k, $v);
150 | }
151 | }
152 | $response = $consumerRequest->request();
153 | $body = Zend_Json::decode($response->getBody());
154 | switch ($response->getStatus()) {
155 | // Not modified
156 | case 304 :
157 | return array(
158 | 'httpStatus' => 304,
159 | 'body' => null,
160 | );
161 | break;
162 | case 403 :
163 | throw new Dropbox_Exception_Forbidden('Forbidden.
164 | This could mean a bad OAuth request, or a file or folder already existing at the target location.
165 | ' . $body["error"] . "\n");
166 | case 404 :
167 | throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found. ' .
168 | $body["error"] . "\n");
169 | case 507 :
170 | throw new Dropbox_Exception_OverQuota('This dropbox is full. ' .
171 | $body["error"] . "\n");
172 | }
173 |
174 | return array(
175 | 'httpStatus' => $response->getStatus(),
176 | 'body' => $response->getBody(),
177 | );
178 | }
179 |
180 | /**
181 | * Requests the OAuth request token.
182 | *
183 | * @return void
184 | */
185 | public function getRequestToken() {
186 | $token = $this->OAuth->getRequestToken();
187 | $this->setToken($token);
188 | return $this->getToken();
189 | }
190 |
191 | /**
192 | * Requests the OAuth access tokens.
193 | *
194 | * This method requires the 'unauthorized' request tokens
195 | * and, if successful will set the authorized request tokens.
196 | *
197 | * @return void
198 | */
199 | public function getAccessToken() {
200 | if (is_a($this->zend_oauth_token, "Zend_Oauth_Token_Request")) {
201 | $requestToken = $this->zend_oauth_token;
202 | } else {
203 | $requestToken = new Zend_Oauth_Token_Request();
204 | $requestToken->setToken($this->oauth_token);
205 | $requestToken->setTokenSecret($this->oauth_token_secret);
206 | }
207 | $token = $this->OAuth->getAccessToken($_GET, $requestToken);
208 | $this->setToken($token);
209 | return $this->getToken();
210 | }
211 |
212 | /**
213 | * Returns the oauth request tokens as an associative array.
214 | *
215 | * The array will contain the elements 'token' and 'token_secret' and the serialized
216 | * Zend_Oauth_Token object.
217 | *
218 | * @return array
219 | */
220 | public function getToken() {
221 | //$token = $this->OAuth->getToken();
222 | //return serialize($token);
223 | return array(
224 | 'token' => $this->oauth_token,
225 | 'token_secret' => $this->oauth_token_secret,
226 | 'zend_oauth_token' => serialize($this->zend_oauth_token),
227 | );
228 | }
229 |
230 | /**
231 | * Returns the authorization url
232 | *
233 | * Overloading Dropbox_OAuth to use the built in functions in Zend_Oauth
234 | *
235 | * @param string $callBack Specify a callback url to automatically redirect the user back
236 | * @return string
237 | */
238 | public function getAuthorizeUrl($callBack = null) {
239 | if ($callBack)
240 | $this->OAuth->setCallbackUrl($callBack);
241 | return $this->OAuth->getRedirectUrl();
242 | }
243 |
244 | }
245 |
--------------------------------------------------------------------------------
/src/Dropbox/OAuth/ca-bundle.pem:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dropbox-PHP/dropbox-php/04eca35de48574e31c7559224438c403fb38a094/src/Dropbox/OAuth/ca-bundle.pem
--------------------------------------------------------------------------------
/src/Dropbox/autoload.php:
--------------------------------------------------------------------------------
1 |
2 |
6 | Dropbox
7 | pear.dropbox-php.com
8 | Dropbox API library for PHP
9 |
10 | Dropbox API library for PHP. Requires oauth and json
11 |
12 |
13 | Joe Constant
14 | lazyguru
15 | lazyguru@jofee.com
16 | yes
17 |
18 |
19 | Naoki Sawada
20 | nao-pon
21 |
22 | yes
23 |
24 |
25 | Evan Kaufman
26 | EvanK
27 |
28 | yes
29 |
30 |
31 | Evert Pot
32 | evert
33 | evert@rooftopsolutions.nl
34 | no
35 |
36 | 2012-09-10
37 |
38 |
39 | 1.0.0
40 | 1.0.0
41 |
42 |
43 | stable
44 | stable
45 |
46 | MIT
47 |
48 | - Added composer support
49 | - PR-13 - DropBox API returns 500 errors rarely. For example, when the thumbnail of the broken picture is acquired etc.
50 | - PR-8 - Methods delta, media, and copy_ref plus additional fixes
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 | 5.2
75 |
76 |
77 | 1.4.0
78 |
79 |
80 |
81 |
82 | HTTP_OAuth
83 | pear.php.net
84 | 0.1.18
85 |
86 |
87 | oauth
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 | 0.1.0
96 | 0.1.0
97 |
98 |
99 | alpha
100 | alpha
101 |
102 | 2010-05-08
103 | MIT
104 |
105 | First release
106 |
107 |
108 |
109 |
110 | 0.1.1
111 | 0.1.0
112 |
113 |
114 | alpha
115 | alpha
116 |
117 | 2010-05-08
118 | MIT
119 |
120 | Automatically trimming double slashes from path. Fixed error output
121 |
122 |
123 |
124 |
125 | 0.1.2
126 | 0.1.0
127 |
128 |
129 | alpha
130 | alpha
131 |
132 | 2010-05-09
133 | MIT
134 |
135 | Uploading now works
136 |
137 |
138 |
139 |
140 | 0.2.0
141 | 0.2.0
142 |
143 |
144 | alpha
145 | alpha
146 |
147 | 2010-05-10
148 | MIT
149 |
150 | Added support for a callback url, for a more streamlined user experience
151 |
152 |
153 |
154 |
155 | 0.3.0
156 | 0.3.0
157 |
158 |
159 | alpha
160 | alpha
161 |
162 | 2010-07-20
163 | MIT
164 |
165 | There's now a choice between PEAR's HTTP_OAuth and the OAuth PECL extension
166 |
167 |
168 |
169 |
170 | 0.4.0
171 | 0.4.0
172 |
173 |
174 | alpha
175 | alpha
176 |
177 | 2010-08-04
178 | MIT
179 |
180 | Support for creating new accounts.
181 | Support for 'token' api call, for easy authentication.
182 | Moved the responsibility of storing/retrieving oauth tokens to the user. Proven to be much for flexible.
183 | A lot more examples.
184 | Consistent error handling between PECL extension and PEAR package.
185 | Fixed responses in the API.
186 | Fixed retrieval of Thumbnails.
187 | Fixed retrieval of hash-based getMetaData.
188 |
189 |
190 |
191 |
192 | 0.4.1
193 | 0.4.1
194 |
195 |
196 | alpha
197 | alpha
198 |
199 | 2011-06-22
200 | MIT
201 |
202 | Fixes for the following issues:
203 |
204 | Issue #10 - spaces in file name for getFile
205 | Issue #13 - spaces in file name for putFile (and move)
206 | Issue #15 - putFile always returns true
207 | Issue #21 - spaces in filename (for getMetaData)
208 |
209 |
210 |
211 |
212 | 0.4.2
213 | 0.4.2
214 |
215 |
216 | alpha
217 | alpha
218 |
219 | 2011-07-20
220 | MIT
221 |
222 | Fixes for the following issues:
223 |
224 | Issue #25 - Patch for /Dropbox/API.php / Error using putfile
225 | Issue #27 - Wordpress OAuth Support
226 |
227 |
228 |
229 |
230 | 0.4.3
231 | 0.4.3
232 |
233 |
234 | alpha
235 | alpha
236 |
237 | 2011-09-04
238 | MIT
239 |
240 | Issue #28 - Oauth Curl class based on Wordpress class
241 | Issue #30 - Can't open files with tilde in the name
242 | Issue #34 - Change API URLs to use HTTPS
243 | Issue #35 - Change hard-coded API URLs to use a class constant
244 |
245 |
246 |
247 |
248 | 0.4.4
249 | 0.4.4
250 |
251 |
252 | alpha
253 | alpha
254 |
255 | 2011-09-26
256 | MIT
257 |
258 | - Added useSSL flag to constructor to allow turning off SSL use
259 | - Added code to turn off SSL validation during OAuth calls
260 |
261 |
262 |
263 |
264 | 0.4.5
265 | 0.4.5
266 |
267 |
268 | alpha
269 | alpha
270 |
271 | 2011-10-31
272 | MIT
273 |
274 | - Updated to work with Dropbox API version 1.
275 | - Some PHPUnit tests
276 |
277 |
278 |
279 |
280 | 0.5.0
281 | 0.5.0
282 |
283 |
284 | beta
285 | beta
286 |
287 | 2012-01-14
288 | MIT
289 |
290 | - Minor bug fixes
291 | - Added share method from Issue #42
292 | - Added search method from Issue #42
293 | - Added ant build script and phpunit config file
294 | - Updated status to "Beta"
295 |
296 |
297 |
298 |
299 | 0.5.1
300 | 0.5.1
301 |
302 |
303 | beta
304 | beta
305 |
306 | 2012-01-14
307 | MIT
308 |
309 | - Fixed a packaging issue
310 |
311 |
312 |
313 |
314 | 1.0.0
315 | 1.0.0
316 |
317 |
318 | stable
319 | stable
320 |
321 | 2012-09-10
322 | MIT
323 |
324 | - Added composer support
325 | - PR-13 - DropBox API returns 500 errors rarely. For example, when the thumbnail of the broken picture is acquired etc.
326 | - PR-8 - Methods delta, media, and copy_ref plus additional fixes
327 |
328 |
329 |
330 |
331 |
--------------------------------------------------------------------------------