Advertisement
Guest User

Untitled

a guest
Jun 19th, 2014
695
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.46 KB | None | 0 0
  1. <?php
  2. /**
  3. * DropPHP - A simple Dropbox client that works without cURL.
  4. *
  5. * http://fabi.me/en/php-projects/dropphp-dropbox-api-client/
  6. *
  7. *
  8. * @author Fabian Schlieper <fabian@fabi.me>
  9. * @copyright Fabian Schlieper 2012
  10. * @version 1.7
  11. * @license See LICENSE
  12. *
  13. */
  14.  
  15. require_once(dirname(__FILE__)."/OAuthSimple.php");
  16.  
  17. class DropboxClient {
  18.  
  19. const API_URL = "https://api.dropbox.com/1/";
  20. const API_CONTENT_URL = "https://api-content.dropbox.com/1/";
  21.  
  22. const BUFFER_SIZE = 4096;
  23.  
  24. const MAX_UPLOAD_CHUNK_SIZE = 150000000; // 150MB
  25.  
  26. const UPLOAD_CHUNK_SIZE = 4000000; // 4MB
  27.  
  28. private $appParams;
  29. private $consumerToken;
  30.  
  31. private $requestToken;
  32. private $accessToken;
  33.  
  34. private $locale;
  35. private $rootPath;
  36.  
  37. private $useCurl;
  38.  
  39. function __construct ($app_params, $locale = "en"){
  40. $this->appParams = $app_params;
  41. if(empty($app_params['app_key']))
  42. throw new DropboxException("App Key is empty!");
  43.  
  44. $this->consumerToken = array('t' => $this->appParams['app_key'], 's' => $this->appParams['app_secret']);
  45. $this->locale = $locale;
  46. $this->rootPath = empty($app_params['app_full_access']) ? "dropbox" : "dropbox";
  47.  
  48. $this->requestToken = null;
  49. $this->accessToken = null;
  50.  
  51. $this->useCurl = function_exists('curl_init');
  52. }
  53.  
  54. /**
  55. * Sets whether to use cURL if its available or PHP HTTP wrappers otherwise
  56. *
  57. * @access public
  58. * @return boolean Whether to actually use cURL (always false if not installed)
  59. */
  60. public function SetUseCUrl($use_it)
  61. {
  62. return ($this->useCurl = ($use_it && function_exists('curl_init')));
  63. }
  64.  
  65. // ##################################################
  66. // Authorization
  67.  
  68. /**
  69. * Step 1 of authentication process. Retrieves a request token or returns a previously retrieved one.
  70. *
  71. * @access public
  72. * @param boolean $get_new_token Optional (default false). Wether to retrieve a new request token.
  73. * @return array Request Token array.
  74. */
  75. public function GetRequestToken($get_new_token=false)
  76. {
  77. if(!empty($this->requestToken) && !$get_new_token)
  78. return $this->requestToken;
  79.  
  80. $rt = $this->authCall("oauth/request_token");
  81. if(empty($rt) || empty($rt['oauth_token']))
  82. throw new DropboxException('Could not get request token!');
  83.  
  84. return ($this->requestToken = array('t'=>$rt['oauth_token'], 's'=>$rt['oauth_token_secret']));
  85. }
  86.  
  87. /**
  88. * Step 2. Returns a URL the user must be redirected to in order to connect the app to their Dropbox account
  89. *
  90. * @access public
  91. * @param string $return_url URL users are redirected after authorization
  92. * @return string URL
  93. */
  94. public function BuildAuthorizeUrl($return_url)
  95. {
  96. $rt = $this->GetRequestToken();
  97. if(empty($rt) || empty($rt['t'])) throw new DropboxException('Request Token Invalid ('.print_r($rt,true).').');
  98. return "https://www.dropbox.com/1/oauth/authorize?oauth_token=".$rt['t']."&oauth_callback=".urlencode($return_url);
  99. }
  100.  
  101. /**
  102. * Step 3. Acquires an access token. This is the final step of authentication.
  103. *
  104. * @access public
  105. * @param array $request_token Optional. The previously retrieved request token. This parameter can only be skipped if the DropboxClient object has been (de)serialized.
  106. * @return array Access Token array.
  107. */
  108. public function GetAccessToken($request_token = null)
  109. {
  110. if(!empty($this->accessToken)) return $this->accessToken;
  111.  
  112. if(empty($request_token)) $request_token = $this->requestToken;
  113. if(empty($request_token)) throw new DropboxException('Request token required!');
  114.  
  115. $at = $this->authCall("oauth/access_token", $request_token);
  116. if(empty($at))
  117. throw new DropboxException(sprintf('Could not get access token! (request token: %s)', $request_token['t']));
  118.  
  119. return ($this->accessToken = array('t'=>$at['oauth_token'], 's'=>$at['oauth_token_secret']));
  120. }
  121.  
  122. /**
  123. * Sets a previously retrieved (and stored) access token.
  124. *
  125. * @access public
  126. * @param string|object $token The Access Token
  127. * @return none
  128. */
  129. public function SetAccessToken($token)
  130. {
  131. if(empty($token['t']) || empty($token['s'])) throw new DropboxException('Passed invalid access token.');
  132. $this->accessToken = $token;
  133. }
  134.  
  135. /**
  136. * Checks if an access token has been set.
  137. *
  138. * @access public
  139. * @return boolean Authorized or not
  140. */
  141. public function IsAuthorized()
  142. {
  143. if(empty($this->accessToken)) return false;
  144. return true;
  145. }
  146.  
  147.  
  148. // ##################################################
  149. // API Functions
  150.  
  151.  
  152. /**
  153. * Retrieves information about the user's account.
  154. *
  155. * @access public
  156. * @return object Account info object. See https://www.dropbox.com/developers/reference/api#account-info
  157. */
  158. public function GetAccountInfo()
  159. {
  160. return $this->apiCall("account/info", "GET");
  161. }
  162.  
  163.  
  164. /**
  165. * Get file list of a dropbox folder.
  166. *
  167. * @access public
  168. * @param string|object $dropbox_path Dropbox path of the folder
  169. * @return array An array with metadata of files/folders keyed by paths
  170. */
  171. public function GetFiles($dropbox_path='', $recursive=false, $include_deleted=false)
  172. {
  173. if(is_object($dropbox_path) && !empty($dropbox_path->path)) $dropbox_path = $dropbox_path->path;
  174. return $this->getFileTree($dropbox_path, $include_deleted, $recursive ? 1000 : 0);
  175. }
  176.  
  177. /**
  178. * Get file or folder metadata
  179. *
  180. * @access public
  181. * @param $dropbox_path string Dropbox path of the file or folder
  182. */
  183. public function GetMetadata($dropbox_path, $include_deleted=false, $rev=null)
  184. {
  185. if(is_object($dropbox_path) && !empty($dropbox_path->path)) $dropbox_path = $dropbox_path->path;
  186. return $this->apiCall("metadata/$this->rootPath/$dropbox_path", "GET", compact('include_deleted','rev'));
  187. }
  188.  
  189. /**
  190. * Download a file to the webserver
  191. *
  192. * @access public
  193. * @param string|object $dropbox_file Dropbox path or metadata object of the file to download.
  194. * @param string $dest_path Local path for destination
  195. * @param string $rev Optional. The revision of the file to retrieve. This defaults to the most recent revision.
  196. * @param callback $progress_changed_callback Optional. Callback that will be called during download with 2 args: 1. bytes loaded, 2. file size
  197. * @return object Dropbox file metadata
  198. */
  199. public function DownloadFile($dropbox_file, $dest_path='', $rev=null, $progress_changed_callback = null)
  200. {
  201. if(is_object($dropbox_file) && !empty($dropbox_file->path))
  202. $dropbox_file = $dropbox_file->path;
  203.  
  204. if(empty($dest_path)) $dest_path = basename($dropbox_file);
  205.  
  206. $url = $this->cleanUrl(self::API_CONTENT_URL."/files/$this->rootPath/$dropbox_file")
  207. . (!empty($rev) ? ('?'.http_build_query(array('rev' => $rev),'','&')) : '');
  208. $context = $this->createRequestContext($url, "GET");
  209.  
  210. $fh = @fopen($dest_path, 'wb'); // write binary
  211. if($fh === false) {
  212. @fclose($rh);
  213. throw new DropboxException("Could not create file $dest_path !");
  214. }
  215.  
  216. if($this->useCurl) {
  217. curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
  218. curl_setopt($context, CURLOPT_RETURNTRANSFER, true);
  219. curl_setopt($context, CURLOPT_FILE, $fh);
  220. $response_headers = array();
  221. self::execCurlAndClose($context, $response_headers);
  222. fclose($fh);
  223. $meta = self::getMetaFromHeaders($response_headers, true);
  224. $bytes_loaded = filesize($dest_path);
  225. } else {
  226. $rh = @fopen($url, 'rb', false, $context); // read binary
  227. if($rh === false)
  228. throw new DropboxException("HTTP request to $url failed!");
  229.  
  230.  
  231. // get file meta from HTTP header
  232. $s_meta = stream_get_meta_data($rh);
  233. $meta = self::getMetaFromHeaders($s_meta['wrapper_data'], true);
  234. $bytes_loaded = 0;
  235. while (!feof($rh)) {
  236. if(($s=fwrite($fh, fread($rh, self::BUFFER_SIZE))) === false) {
  237. @fclose($rh);
  238. @fclose($fh);
  239. throw new DropboxException("Writing to file $dest_path failed!'");
  240. }
  241. $bytes_loaded += $s;
  242. if(!empty($progress_changed_callback)) {
  243. call_user_func($progress_changed_callback, $bytes_loaded, $meta->bytes);
  244. }
  245. }
  246.  
  247. fclose($rh);
  248. fclose($fh);
  249. }
  250.  
  251. if($meta->bytes != $bytes_loaded)
  252. throw new DropboxException("Download size mismatch! (header:{$meta->bytes} vs actual:{$bytes_loaded}; curl:{$this->useCurl})");
  253.  
  254. return $meta;
  255. }
  256.  
  257. /**
  258. * Upload a file to dropbox
  259. *
  260. * @access public
  261. * @param $src_file string Local file to upload
  262. * @param $dropbox_path string Dropbox path for destination
  263. * @return object Dropbox file metadata
  264. */
  265. public function UploadFile($src_file, $dropbox_path='', $overwrite=true, $parent_rev=null)
  266. {
  267. //if(empty($dropbox_path)) $dropbox_path = basename($src_file);
  268. if(empty($dropbox_path)) $dropbox_path = 'VideoStack'. '/'. basename($src_file);
  269. elseif(is_object($dropbox_path) && !empty($dropbox_path->path)) $dropbox_path = $dropbox_path->path;
  270.  
  271. // make sure the dropbox_path is not a dir. if it is, append baseneme of $src_file
  272. $dropbox_bn = basename($dropbox_path);
  273. if(strpos($dropbox_bn,'.') === false) { // check if ext. is missing -> could be a directory!
  274. try {
  275. $meta = $this->GetMetadata($dropbox_path);
  276. if($meta && $meta->is_dir)
  277. $dropbox_path = $dropbox_path . '/'. basename($src_file);
  278. //$dropbox_path = 'VideoStack'. '/'.basename($src_file);
  279. } catch(Exception $e) {}
  280. }
  281.  
  282. $file_size = filesize($src_file);
  283.  
  284. if($file_size > self::MAX_UPLOAD_CHUNK_SIZE)
  285. {
  286. $fh = fopen($src_file,'rb');
  287. if($fh === false)
  288. throw new DropboxException();
  289.  
  290. $upload_id = null;
  291. $offset = 0;
  292.  
  293.  
  294. while(!feof($fh)) {
  295. $url = $this->cleanUrl(self::API_CONTENT_URL."/chunked_upload").'?'.http_build_query(compact('upload_id', 'offset'),'','&');
  296.  
  297. if($this->useCurl) {
  298. $context = $this->createRequestContext($url, "PUT");
  299. curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
  300. curl_setopt($context, CURLOPT_PUT, 1);
  301. curl_setopt($context, CURLOPT_INFILE, $fh);
  302. $chunk_size = min(self::UPLOAD_CHUNK_SIZE, $file_size - $offset);
  303. $offset += $chunk_size;
  304. curl_setopt($context, CURLOPT_INFILESIZE, $chunk_size);
  305. $response = json_decode(self::execCurlAndClose($context));
  306.  
  307. fseek($fh,$offset);
  308. if($offset >= $file_size)
  309. break;
  310. } else {
  311. $content = fread($fh, self::UPLOAD_CHUNK_SIZE);
  312.  
  313. $context = $this->createRequestContext($url, "PUT", $content);
  314. $offset += strlen($content);
  315. unset($content);
  316.  
  317. $response = json_decode(file_get_contents($url, false, $context));
  318. }
  319. unset($context);
  320.  
  321. self::checkForError($response);
  322.  
  323. if(empty($upload_id)) {
  324. $upload_id = $response->upload_id;
  325. if(empty($upload_id)) throw new DropboxException("Upload ID empty!");
  326. }
  327. }
  328.  
  329. @fclose($fh);
  330.  
  331. $this->useCurl = $prev_useCurl;
  332.  
  333. return $this->apiCall("commit_chunked_upload/$this->rootPath/VideoStack/$dropbox_path", "POST", compact('overwrite','parent_rev','upload_id'), true);
  334. }
  335.  
  336. $query = http_build_query(array_merge(compact('overwrite', 'parent_rev'), array('locale' => $this->locale)),'','&');
  337. $url = $this->cleanUrl(self::API_CONTENT_URL."/files_put/$this->rootPath/VideoStack/$dropbox_path")."?$query";
  338.  
  339. if($this->useCurl) {
  340. $context = $this->createRequestContext($url, "PUT");
  341. curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
  342. $fh = fopen($src_file, 'rb');
  343. curl_setopt($context, CURLOPT_PUT, 1);
  344. curl_setopt($context, CURLOPT_INFILE, $fh); // file pointer
  345. curl_setopt($context, CURLOPT_INFILESIZE, filesize($src_file));
  346. $meta = json_decode(self::execCurlAndClose($context));
  347. fclose($fh);
  348. return self::checkForError($meta);
  349. } else {
  350. $content = file_get_contents($src_file);
  351. if(strlen($content) == 0)
  352. throw new DropboxException("Could not read file $src_file or file is empty!");
  353.  
  354. $context = $this->createRequestContext($url, "PUT", $content);
  355.  
  356. return self::checkForError(json_decode(file_get_contents($url, false, $context)));
  357. }
  358. }
  359.  
  360. /**
  361. * Get thumbnail for a specified image
  362. *
  363. * @access public
  364. * @param $dropbox_file string Path to the image
  365. * @param $format string Image format of the thumbnail (jpeg or png)
  366. * @param $size string Thumbnail size (xs, s, m, l, xl)
  367. * @return mime/* Returns the thumbnail as binary image data
  368. */
  369. public function GetThumbnail($dropbox_file, $size = 's', $format = 'jpeg', $echo = false)
  370. {
  371. if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
  372. $url = $this->cleanUrl(self::API_CONTENT_URL."thumbnails/$this->rootPath/$dropbox_file")
  373. . '?' . http_build_query(array('format' => $format, 'size' => $size),'','&');
  374. $context = $this->createRequestContext($url, "GET");
  375.  
  376. if($this->useCurl) {
  377. curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
  378. curl_setopt($context, CURLOPT_RETURNTRANSFER, true);
  379. }
  380.  
  381. $thumb = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, NULL, $context);
  382.  
  383. if($echo) {
  384. header('Content-type: image/'.$format);
  385. echo $thumb;
  386. unset($thumb);
  387. return;
  388. }
  389.  
  390. return $thumb;
  391. }
  392.  
  393.  
  394. function GetLink($dropbox_file, $preview=true, $short=true, &$expires=null)
  395. {
  396. if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
  397. $url = $this->apiCall(($preview?"shares":"media")."/$this->rootPath/$dropbox_file", "POST", array('locale' => null, 'short_url'=> $preview ? $short : null));
  398. $expires = strtotime($url->expires);
  399. return $url->url;
  400. }
  401.  
  402. function Delta($cursor)
  403. {
  404. return $this->apiCall("delta", "POST", compact('cursor'));
  405. }
  406.  
  407. function GetRevisions($dropbox_file, $rev_limit=10)
  408. {
  409. if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
  410. return $this->apiCall("revisions/$this->rootPath/$dropbox_file", "GET", compact('rev_limit'));
  411. }
  412.  
  413. function Restore($dropbox_file, $rev)
  414. {
  415. if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
  416. return $this->apiCall("restore/$this->rootPath/$dropbox_file", "POST", compact('rev'));
  417. }
  418.  
  419. function Search($path, $query, $file_limit=1000, $include_deleted=false)
  420. {
  421. return $this->apiCall("search/$this->rootPath/$path", "POST", compact('query','file_limit','include_deleted'));
  422. }
  423.  
  424. function GetCopyRef($dropbox_file, &$expires=null)
  425. {
  426. if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
  427. $ref = $this->apiCall("copy_ref/$this->rootPath/$dropbox_file", "GET", array('locale' => null));
  428. $expires = strtotime($ref->expires);
  429. return $ref->copy_ref;
  430. }
  431.  
  432.  
  433. function Copy($from_path, $to_path, $copy_ref=false)
  434. {
  435. if(is_object($from_path) && !empty($from_path->path)) $from_path = $from_path->path;
  436. return $this->apiCall("fileops/copy", "POST", array('root'=> $this->rootPath, ($copy_ref ? 'from_copy_ref' : 'from_path') => $from_path, 'to_path' => $to_path));
  437. }
  438.  
  439. /**
  440. * Creates a new folder in the DropBox
  441. *
  442. * @access public
  443. * @param $path string The path to the new folder to create
  444. * @return object Dropbox folder metadata
  445. */
  446.  
  447.  
  448. function CreateFolder($path)
  449. {
  450. return $this->apiCall(
  451. "fileops/create_folder",
  452. "POST",
  453. array('root'=> $this->rootPath, 'path' => $path)
  454. );
  455. }
  456.  
  457. $x = "test";
  458. CreateFolder($x);
  459. /**
  460. * Delete file or folder
  461. *
  462. * @access public
  463. * @param $path mixed The path or metadata of the file/folder to be deleted.
  464. * @return object Dropbox metadata of deleted file or folder
  465. */
  466. function Delete($path)
  467. {
  468. if(is_object($path) && !empty($path->path)) $path = $path->path;
  469. return $this->apiCall("fileops/delete", "POST", array('locale' =>null, 'root'=> $this->rootPath, 'path' => $path));
  470. }
  471.  
  472. function Move($from_path, $to_path)
  473. {
  474. if(is_object($from_path) && !empty($from_path->path)) $from_path = $from_path->path;
  475. return $this->apiCall("fileops/move", "POST", array('root'=> $this->rootPath, 'from_path' => $from_path, 'to_path' => $to_path));
  476. }
  477.  
  478. function getFileTree($path="", $include_deleted = false, $max_depth = 0, $depth=0)
  479. {
  480. static $files;
  481. if($depth == 0) $files = array();
  482.  
  483. $dir = $this->apiCall("metadata/$this->rootPath/$path", "GET", compact('include_deleted'));
  484.  
  485. if(empty($dir) || !is_object($dir)) return false;
  486.  
  487. if(!empty($dir->error)) throw new DropboxException($dir->error);
  488.  
  489. foreach($dir->contents as $item)
  490. {
  491. $files[trim($item->path,'/')] = $item;
  492. if($item->is_dir && $depth < $max_depth)
  493. {
  494. $this->getFileTree($item->path, $include_deleted, $max_depth, $depth+1);
  495. }
  496. }
  497.  
  498. return $files;
  499. }
  500.  
  501. function createCurl($url, $http_context)
  502. {
  503. $ch = curl_init($url);
  504.  
  505. $curl_opts = array(
  506. CURLOPT_HEADER => false, // exclude header from output
  507. //CURLOPT_MUTE => true, // no output!
  508. CURLOPT_RETURNTRANSFER => true, // but return!
  509. CURLOPT_SSL_VERIFYPEER => false,
  510. );
  511.  
  512. $curl_opts[CURLOPT_CUSTOMREQUEST] = $http_context['method'];
  513.  
  514. if(!empty($http_context['content'])) {
  515. $curl_opts[CURLOPT_POSTFIELDS] =& $http_context['content'];
  516. if(defined("CURLOPT_POSTFIELDSIZE"))
  517. $curl_opts[CURLOPT_POSTFIELDSIZE] = strlen($http_context['content']);
  518. }
  519.  
  520. $curl_opts[CURLOPT_HTTPHEADER] = array_map('trim',explode("\n",$http_context['header']));
  521.  
  522. curl_setopt_array($ch, $curl_opts);
  523. return $ch;
  524. }
  525.  
  526. static private $_curlHeadersRef;
  527. static function _curlHeaderCallback($ch, $header)
  528. {
  529. self::$_curlHeadersRef[] = trim($header);
  530. return strlen($header);
  531. }
  532.  
  533. static function &execCurlAndClose($ch, &$out_response_headers = null)
  534. {
  535. if(is_array($out_response_headers)) {
  536. self::$_curlHeadersRef =& $out_response_headers;
  537. curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(__CLASS__, '_curlHeaderCallback'));
  538. }
  539. $res = curl_exec($ch);
  540. $err_no = curl_errno($ch);
  541. $err_str = curl_error($ch);
  542. curl_close($ch);
  543. if($err_no || $res === false) {
  544. throw new DropboxException("cURL-Error ($err_no): $err_str");
  545. }
  546.  
  547. return $res;
  548. }
  549.  
  550. private function createRequestContext($url, $method, &$content=null, $oauth_token=-1)
  551. {
  552. if($oauth_token === -1)
  553. $oauth_token = $this->accessToken;
  554.  
  555. $method = strtoupper($method);
  556. $http_context = array('method'=>$method, 'header'=> '');
  557.  
  558. $oauth = new OAuthSimple($this->consumerToken['t'],$this->consumerToken['s']);
  559.  
  560. if(empty($oauth_token) && !empty($this->accessToken))
  561. $oauth_token = $this->accessToken;
  562.  
  563. if(!empty($oauth_token)) {
  564. $oauth->setParameters(array('oauth_token' => $oauth_token['t']));
  565. $oauth->signatures(array('oauth_secret'=>$oauth_token['s']));
  566. }
  567.  
  568. if(!empty($content)) {
  569. $post_vars = ($method != "PUT" && preg_match("/^[a-z][a-z0-9_]*=/i", substr($content, 0, 32)));
  570. $http_context['header'] .= "Content-Length: ".strlen($content)."\r\n";
  571. $http_context['header'] .= "Content-Type: application/".($post_vars?"x-www-form-urlencoded":"octet-stream")."\r\n";
  572. $http_context['content'] =& $content;
  573. if($method == "POST" && $post_vars)
  574. $oauth->setParameters($content);
  575. } elseif($method == "POST") {
  576. // make sure that content-length is always set when post request (otherwise some wrappers fail!)
  577. $http_context['content'] = "";
  578. $http_context['header'] .= "Content-Length: 0\r\n";
  579. }
  580.  
  581.  
  582. // check for query vars in url and add them to oauth parameters (and remove from path)
  583. $path = $url;
  584. $query = strrchr($url,'?');
  585. if(!empty($query)) {
  586. $oauth->setParameters(substr($query,1));
  587. $path = substr($url, 0, -strlen($query));
  588. }
  589.  
  590.  
  591. $signed = $oauth->sign(array(
  592. 'action' => $method,
  593. 'path'=> $path));
  594. //print_r($signed);
  595.  
  596. $http_context['header'] .= "Authorization: ".$signed['header']."\r\n";
  597.  
  598. return $this->useCurl ? $this->createCurl($url, $http_context) : stream_context_create(array('http'=>$http_context));
  599. }
  600.  
  601. private function authCall($path, $request_token=null)
  602. {
  603. $url = $this->cleanUrl(self::API_URL.$path);
  604. $dummy = null;
  605. $context = $this->createRequestContext($url, "POST", $dummy, $request_token);
  606.  
  607. $contents = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, false, $context);
  608. $data = array();
  609. parse_str($contents, $data);
  610. return $data;
  611. }
  612.  
  613. private static function checkForError($resp)
  614. {
  615. if(!empty($resp->error))
  616. throw new DropboxException($resp->error);
  617. return $resp;
  618. }
  619.  
  620.  
  621. private function apiCall($path, $method, $params=array(), $content_call=false)
  622. {
  623. $url = $this->cleanUrl(($content_call ? self::API_CONTENT_URL : self::API_URL).$path);
  624. $content = http_build_query(array_merge(array('locale'=>$this->locale), $params),'','&');
  625.  
  626. if($method == "GET") {
  627. $url .= "?".$content;
  628. $content = null;
  629. }
  630.  
  631. $context = $this->createRequestContext($url, $method, $content);
  632. $json = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, false, $context);
  633. //if($json === false)
  634. // throw new DropboxException();
  635. $resp = json_decode($json);
  636. return self::checkForError($resp);
  637. }
  638.  
  639.  
  640. private static function getMetaFromHeaders(&$header_array, $throw_on_error=false)
  641. {
  642. $obj = json_decode(substr(@array_shift(array_filter($header_array, create_function('$s', 'return stripos($s, "x-dropbox-metadata:") === 0;'))), 20));
  643. if($throw_on_error && (empty($obj)||!is_object($obj)))
  644. throw new DropboxException("Could not retrieve meta data from header data: ".print_r($header_array,true));
  645. if($throw_on_error)
  646. self::checkForError ($obj);
  647. return $obj;
  648. }
  649.  
  650.  
  651. function cleanUrl($url) {
  652. $p = substr($url,0,8);
  653. $url = str_replace('//','/', str_replace('\\','/',substr($url,8)));
  654. $url = rawurlencode($url);
  655. $url = str_replace('%2F', '/', $url);
  656. return $p.$url;
  657. }
  658. }
  659.  
  660. class DropboxException extends Exception {
  661.  
  662. public function __construct($err = null, $isDebug = FALSE)
  663. {
  664. if(is_null($err)) {
  665. $el = error_get_last();
  666. $this->message = $el['message'];
  667. $this->file = $el['file'];
  668. $this->line = $el['line'];
  669. } else
  670. $this->message = $err;
  671. self::log_error($err);
  672. if ($isDebug)
  673. {
  674. self::display_error($err, TRUE);
  675. }
  676. }
  677.  
  678. public static function log_error($err)
  679. {
  680. error_log($err, 0);
  681. }
  682.  
  683. public static function display_error($err, $kill = FALSE)
  684. {
  685. print_r($err);
  686. if ($kill === FALSE)
  687. {
  688. die();
  689. }
  690. }
  691. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement