inital commit

This commit is contained in:
2026-06-19 20:08:01 +06:00
commit 8a5abeeae4
13128 changed files with 3192007 additions and 0 deletions

View File

@@ -0,0 +1,651 @@
<?php
/**
* DropPHP - A simple Dropbox client that works without cURL.
*/
require_once("OAuthSimple.php");
class DropboxClient {
const API_URL = "https://api.dropbox.com/1/";
const API_CONTENT_URL = "https://api-content.dropbox.com/1/";
const BUFFER_SIZE = 4096;
const MAX_UPLOAD_CHUNK_SIZE = 150000000; // 150MB
const UPLOAD_CHUNK_SIZE = 4000000; // 4MB
private $appParams;
private $consumerToken;
private $requestToken;
private $accessToken;
private $locale;
private $rootPath;
private $useCurl;
function __construct ($app_params, $locale = "en"){
$this->appParams = $app_params;
if(empty($app_params['app_key']))
throw new DropboxException("App Key is empty!");
$this->consumerToken = array('t' => $this->appParams['app_key'], 's' => $this->appParams['app_secret']);
$this->locale = $locale;
$this->rootPath = empty($app_params['app_full_access']) ? "sandbox" : "dropbox";
$this->requestToken = null;
$this->accessToken = null;
$this->useCurl = function_exists('curl_init');
}
/**
* Sets whether to use cURL if its available or PHP HTTP wrappers otherwise
*
* @access public
* @return boolean Whether to actually use cURL (always false if not installed)
*/
public function SetUseCUrl($use_it)
{
return ($this->useCurl = $use_it && function_exists('curl_init'));
}
// ##################################################
// Authorization
/**
* Step 1 of authentication process. Retrieves a request token or returns a previously retrieved one.
*
* @access public
* @param boolean $get_new_token Optional (default false). Wether to retrieve a new request token.
* @return array Request Token array.
*/
public function GetRequestToken($get_new_token=false)
{
if(!empty($this->requestToken) && !$get_new_token)
return $this->requestToken;
$rt = $this->authCall("oauth/request_token");
if(empty($rt) || empty($rt['oauth_token']))
throw new DropboxException('Could not get request token!');
return ($this->requestToken = array('t'=>$rt['oauth_token'], 's'=>$rt['oauth_token_secret']));
}
/**
* Step 2. Returns a URL the user must be redirected to in order to connect the app to their Dropbox account
*
* @access public
* @param string $return_url URL users are redirected after authorization
* @return string URL
*/
public function BuildAuthorizeUrl($return_url)
{
$rt = $this->GetRequestToken();
if(empty($rt) || empty($rt['t'])) throw new DropboxException('Request Token Invalid ('.print_r($rt,true).').');
return "https://www.dropbox.com/1/oauth/authorize?oauth_token=".$rt['t']."&oauth_callback=".urlencode($return_url);
}
/**
* Step 3. Acquires an access token. This is the final step of authentication.
*
* @access public
* @param array $request_token Optional. The previously retrieved request token. This parameter can only be skipped if the DropboxClient object has been (de)serialized.
* @return array Access Token array.
*/
public function GetAccessToken($request_token = null)
{
if(!empty($this->accessToken)) return $this->accessToken;
if(empty($request_token)) $request_token = $this->requestToken;
if(empty($request_token)) throw new DropboxException('Request token required!');
$at = $this->authCall("oauth/access_token", $request_token);
if(empty($at))
throw new DropboxException(sprintf('Could not get access token! (request token: %s)', $request_token['t']));
return ($this->accessToken = array('t'=>$at['oauth_token'], 's'=>$at['oauth_token_secret']));
}
/**
* Sets a previously retrieved (and stored) access token.
*
* @access public
* @param string|object $token The Access Token
* @return none
*/
public function SetAccessToken($token)
{
if(empty($token['t']) || empty($token['s'])) throw new DropboxException('Passed invalid access token.');
$this->accessToken = $token;
}
/**
* Checks if an access token has been set.
*
* @access public
* @return boolean Authorized or not
*/
public function IsAuthorized()
{
if(empty($this->accessToken)) return false;
return true;
}
// ##################################################
// API Functions
/**
* Retrieves information about the user's account.
*
* @access public
* @return object Account info object. See https://www.dropbox.com/developers/reference/api#account-info
*/
public function GetAccountInfo()
{
return $this->apiCall("account/info", "GET");
}
/**
* Get file list of a dropbox folder.
*
* @access public
* @param string|object $dropbox_path Dropbox path of the folder
* @return array An array with metadata of files/folders keyed by paths
*/
public function GetFiles($dropbox_path='', $recursive=false, $include_deleted=false)
{
if(is_object($dropbox_path) && !empty($dropbox_path->path)) $dropbox_path = $dropbox_path->path;
return $this->getFileTree($dropbox_path, $include_deleted, $recursive ? 1000 : 0);
}
/**
* Get file or folder metadata
*
* @access public
* @param $dropbox_path string Dropbox path of the file or folder
*/
public function GetMetadata($dropbox_path, $include_deleted=false, $rev=null)
{
if(is_object($dropbox_path) && !empty($dropbox_path->path)) $dropbox_path = $dropbox_path->path;
return $this->apiCall("metadata/$this->rootPath/$dropbox_path", "GET", compact('include_deleted','rev'));
}
/**
* Download a file to the webserver
*
* @access public
* @param string|object $dropbox_file Dropbox path or metadata object of the file to download.
* @param string $dest_path Local path for destination
* @param string $rev Optional. The revision of the file to retrieve. This defaults to the most recent revision.
* @param callback $progress_changed_callback Optional. Callback that will be called during download with 2 args: 1. bytes loaded, 2. file size
* @return object Dropbox file metadata
*/
public function DownloadFile($dropbox_file, $dest_path='', $rev=null, $progress_changed_callback = null)
{
if(is_object($dropbox_file) && !empty($dropbox_file->path))
$dropbox_file = $dropbox_file->path;
if(empty($dest_path)) $dest_path = basename($dropbox_file);
$url = $this->cleanUrl(self::API_CONTENT_URL."/files/$this->rootPath/$dropbox_file")
. (!empty($rev) ? ('?'.http_build_query(array('rev' => $rev),'','&')) : '');
$context = $this->createRequestContext($url, "GET");
$fh = @fopen($dest_path, 'wb'); // write binary
if($fh === false) {
@fclose($rh);
throw new DropboxException("Could not create file $dest_path !");
}
if($this->useCurl) {
curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
curl_setopt($context, CURLOPT_RETURNTRANSFER, true);
curl_setopt($context, CURLOPT_FILE, $fh);
$response_headers = array();
self::execCurlAndClose($context, $response_headers);
fclose($fh);
$meta = self::getMetaFromHeaders($response_headers);
$bytes_loaded = filesize($dest_path);
} else {
$rh = @fopen($url, 'rb', false, $context); // read binary
if($rh === false)
throw new DropboxException("HTTP request to $url failed!");
// get file meta from HTTP header
$s_meta = stream_get_meta_data($rh);
$meta = self::getMetaFromHeaders($s_meta['wrapper_data']);
$bytes_loaded = 0;
while (!feof($rh)) {
if(($s=fwrite($fh, fread($rh, self::BUFFER_SIZE))) === false) {
@fclose($rh);
@fclose($fh);
throw new DropboxException("Writing to file $dest_path failed!'");
}
$bytes_loaded += $s;
if(!empty($progress_changed_callback)) {
call_user_func($progress_changed_callback, $bytes_loaded, $meta->bytes);
}
}
fclose($rh);
fclose($fh);
}
if($meta->bytes != $bytes_loaded)
throw new DropboxException("Download size mismatch! (header:{$meta->bytes} vs actual:{$bytes_loaded}");
return $meta;
}
/**
* Upload a file to dropbox
*
* @access public
* @param $src_file string Local file to upload
* @param $dropbox_path string Dropbox path for destination
* @return object Dropbox file metadata
*/
public function UploadFile($src_file, $dropbox_path='', $overwrite=true, $parent_rev=null)
{
if(empty($dropbox_path)) $dropbox_path = basename($src_file);
elseif(is_object($dropbox_path) && !empty($dropbox_path->path)) $dropbox_path = $dropbox_path->path;
$file_size = filesize($src_file);
if($file_size > self::MAX_UPLOAD_CHUNK_SIZE)
{
$fh = fopen($src_file,'rb');
if($fh === false)
throw new DropboxException();
$upload_id = null;
$offset = 0;
while(!feof($fh)) {
$url = $this->cleanUrl(self::API_CONTENT_URL."/chunked_upload").'?'.http_build_query(compact('upload_id', 'offset'),'','&');
if($this->useCurl) {
$context = $this->createRequestContext($url, "PUT");
curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
curl_setopt($context, CURLOPT_PUT, 1);
curl_setopt($context, CURLOPT_INFILE, $fh);
$chunk_size = min(self::UPLOAD_CHUNK_SIZE, $file_size - $offset);
$offset += $chunk_size;
curl_setopt($context, CURLOPT_INFILESIZE, $chunk_size);
$response = json_decode(self::execCurlAndClose($context));
fseek($fh,$offset);
if($offset >= $file_size)
break;
} else {
$content = fread($fh, self::UPLOAD_CHUNK_SIZE);
$context = $this->createRequestContext($url, "PUT", $content);
$offset += strlen($content);
unset($content);
$response = json_decode(file_get_contents($url, false, $context));
}
unset($context);
if(empty($upload_id)) {
$upload_id = $response->upload_id;
if(empty($upload_id)) throw new DropboxException("Upload ID empty!");
}
}
@fclose($fh);
$this->useCurl = $prev_useCurl;
return $this->apiCall("commit_chunked_upload/$this->rootPath/$dropbox_path", "POST", compact('overwrite','parent_rev','upload_id'), true);
}
$query = http_build_query(array_merge(compact('overwrite', 'parent_rev'), array('locale' => $this->locale)),'','&');
$url = $this->cleanUrl(self::API_CONTENT_URL."/files_put/$this->rootPath/$dropbox_path")."?$query";
if($this->useCurl) {
$context = $this->createRequestContext($url, "PUT");
curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
$fh = fopen($src_file, 'rb');
curl_setopt($context, CURLOPT_PUT, 1);
curl_setopt($context, CURLOPT_INFILE, $fh); // file pointer
curl_setopt($context, CURLOPT_INFILESIZE, filesize($src_file));
$meta = json_decode(self::execCurlAndClose($context));
fclose($fh);
return $meta;
} else {
$content = file_get_contents($src_file);
if(strlen($content) == 0)
throw new DropboxException("Could not read file $src_file or file is empty!");
$context = $this->createRequestContext($url, "PUT", $content);
return json_decode(file_get_contents($url, false, $context));
}
}
/**
* Get thumbnail for a specified image
*
* @access public
* @param $dropbox_file string Path to the image
* @param $format string Image format of the thumbnail (jpeg or png)
* @param $size string Thumbnail size (xs, s, m, l, xl)
* @return mime/* Returns the thumbnail as binary image data
*/
public function GetThumbnail($dropbox_file, $size = 's', $format = 'jpeg', $echo = false)
{
if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
$url = $this->cleanUrl(self::API_CONTENT_URL."thumbnails/$this->rootPath/$dropbox_file")
. '?' . http_build_query(array('format' => $format, 'size' => $size),'','&');
$context = $this->createRequestContext($url, "GET");
if($this->useCurl) {
curl_setopt($context, CURLOPT_BINARYTRANSFER, true);
curl_setopt($context, CURLOPT_RETURNTRANSFER, true);
}
$thumb = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, NULL, $context);
if($echo) {
header('Content-type: image/'.$format);
echo $thumb;
unset($thumb);
return;
}
return $thumb;
}
function GetLink($dropbox_file, $preview=true, $short=true, &$expires=null)
{
if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
$url = $this->apiCall(($preview?"shares":"media")."/$this->rootPath/$dropbox_file", "POST", array('locale' => null, 'short_url'=> $preview ? $short : null));
$expires = strtotime($url->expires);
return $url->url;
}
function Delta($cursor)
{
return $this->apiCall("delta", "POST", compact('cursor'));
}
function GetRevisions($dropbox_file, $rev_limit=10)
{
if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
return $this->apiCall("revisions/$this->rootPath/$dropbox_file", "GET", compact('rev_limit'));
}
function Restore($dropbox_file, $rev)
{
if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
return $this->apiCall("restore/$this->rootPath/$dropbox_file", "POST", compact('rev'));
}
function Search($path, $query, $file_limit=1000, $include_deleted=false)
{
return $this->apiCall("search/$this->rootPath/$path", "POST", compact('query','file_limit','include_deleted'));
}
function GetCopyRef($dropbox_file, &$expires=null)
{
if(is_object($dropbox_file) && !empty($dropbox_file->path)) $dropbox_file = $dropbox_file->path;
$ref = $this->apiCall("copy_ref/$this->rootPath/$dropbox_file", "GET", array('locale' => null));
$expires = strtotime($ref->expires);
return $ref->copy_ref;
}
function Copy($from_path, $to_path, $copy_ref=false)
{
if(is_object($from_path) && !empty($from_path->path)) $from_path = $from_path->path;
return $this->apiCall("fileops/copy", "POST", array('root'=> $this->rootPath, ($copy_ref ? 'from_copy_ref' : 'from_path') => $from_path, 'to_path' => $to_path));
}
/**
* Creates a new folder in the DropBox
*
* @access public
* @param $path string The path to the new folder to create
* @return object Dropbox folder metadata
*/
function CreateFolder($path)
{
return $this->apiCall("fileops/create_folder", "POST", array('root'=> $this->rootPath, 'path' => $path));
}
/**
* Delete file or folder
*
* @access public
* @param $path mixed The path or metadata of the file/folder to be deleted.
* @return object Dropbox metadata of deleted file or folder
*/
function Delete($path)
{
if(is_object($path) && !empty($path->path)) $path = $path->path;
return $this->apiCall("fileops/delete", "POST", array('locale' =>null, 'root'=> $this->rootPath, 'path' => $path));
}
function Move($from_path, $to_path)
{
if(is_object($from_path) && !empty($from_path->path)) $from_path = $from_path->path;
return $this->apiCall("fileops/move", "POST", array('root'=> $this->rootPath, 'from_path' => $from_path, 'to_path' => $to_path));
}
function getFileTree($path="", $include_deleted = false, $max_depth = 0, $depth=0)
{
static $files;
if($depth == 0) $files = array();
$dir = $this->apiCall("metadata/$this->rootPath/$path", "GET", compact('include_deleted'));
if(empty($dir) || !is_object($dir)) return false;
if(!empty($dir->error)) throw new DropboxException($dir->error);
foreach($dir->contents as $item)
{
$files[trim($item->path,'/')] = $item;
if($item->is_dir && $depth < $max_depth)
{
$this->getFileTree($item->path, $include_deleted, $max_depth, $depth+1);
}
}
return $files;
}
function createCurl($url, $http_context)
{
$ch = curl_init($url);
$curl_opts = array(
CURLOPT_HEADER => false, // exclude header from output
//CURLOPT_MUTE => true, // no output!
CURLOPT_RETURNTRANSFER => true, // but return!
CURLOPT_SSL_VERIFYPEER => false,
);
$curl_opts[CURLOPT_CUSTOMREQUEST] = $http_context['method'];
if(!empty($http_context['content'])) {
$curl_opts[CURLOPT_POSTFIELDS] =& $http_context['content'];
if(defined("CURLOPT_POSTFIELDSIZE"))
$curl_opts[CURLOPT_POSTFIELDSIZE] = strlen($http_context['content']);
}
$curl_opts[CURLOPT_HTTPHEADER] = array_map('trim',explode("\n",$http_context['header']));
curl_setopt_array($ch, $curl_opts);
return $ch;
}
static private $_curlHeadersRef;
static function _curlHeaderCallback($ch, $header)
{
self::$_curlHeadersRef[] = trim($header);
return strlen($header);
}
static function &execCurlAndClose($ch, &$out_response_headers = null)
{
if(is_array($out_response_headers)) {
self::$_curlHeadersRef =& $out_response_headers;
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(__CLASS__, '_curlHeaderCallback'));
}
$res = curl_exec($ch);
$err_no = curl_errno($ch);
$err_str = curl_error($ch);
curl_close($ch);
if($err_no || $res === false) {
throw new DropboxException("cURL-Error ($err_no): $err_str");
}
return $res;
}
private function createRequestContext($url, $method, &$content=null, $oauth_token=-1)
{
if($oauth_token === -1)
$oauth_token = $this->accessToken;
$method = strtoupper($method);
$http_context = array('method'=>$method, 'header'=> '');
$oauth = new OAuthSimple($this->consumerToken['t'],$this->consumerToken['s']);
if(empty($oauth_token) && !empty($this->accessToken))
$oauth_token = $this->accessToken;
if(!empty($oauth_token)) {
$oauth->setParameters(array('oauth_token' => $oauth_token['t']));
$oauth->signatures(array('oauth_secret'=>$oauth_token['s']));
}
if(!empty($content)) {
$post_vars = ($method != "PUT" && preg_match("/^[a-z][a-z0-9_]*=/i", substr($content, 0, 32)));
$http_context['header'] .= "Content-Length: ".strlen($content)."\r\n";
$http_context['header'] .= "Content-Type: application/".($post_vars?"x-www-form-urlencoded":"octet-stream")."\r\n";
$http_context['content'] =& $content;
if($method == "POST" && $post_vars)
$oauth->setParameters($content);
} elseif($method == "POST") {
// make sure that content-length is always set when post request (otherwise some wrappers fail!)
$http_context['content'] = "";
$http_context['header'] .= "Content-Length: 0\r\n";
}
// check for query vars in url and add them to oauth parameters (and remove from path)
$path = $url;
$query = strrchr($url,'?');
if(!empty($query)) {
$oauth->setParameters(substr($query,1));
$path = substr($url, 0, -strlen($query));
}
$signed = $oauth->sign(array(
'action' => $method,
'path'=> $path));
//print_r($signed);
$http_context['header'] .= "Authorization: ".$signed['header']."\r\n";
return $this->useCurl ? $this->createCurl($url, $http_context) : stream_context_create(array('http'=>$http_context));
}
private function authCall($path, $request_token=null)
{
$url = $this->cleanUrl(self::API_URL.$path);
$dummy = null;
$context = $this->createRequestContext($url, "POST", $dummy, $request_token);
$contents = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, false, $context);
$data = array();
parse_str($contents, $data);
return $data;
}
private function apiCall($path, $method, $params=array(), $content_call=false)
{
$url = $this->cleanUrl(($content_call ? self::API_CONTENT_URL : self::API_URL).$path);
$content = http_build_query(array_merge(array('locale'=>$this->locale), $params),'','&');
if($method == "GET") {
$url .= "?".$content;
$content = null;
}
$context = $this->createRequestContext($url, $method, $content);
$json = $this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, false, $context);
//if($json === false)
// throw new DropboxException();
$resp = json_decode($json);
if(!empty($resp->error))
throw new DropboxException($resp->error);
return $resp;
}
private static function getMetaFromHeaders(&$header_array)
{
return json_decode(substr(@array_shift(array_filter($header_array, create_function('$s', 'return strpos($s, "x-dropbox-metadata:") === 0;'))), 20));
}
function cleanUrl($url) {
$p = substr($url,0,8);
$url = str_replace('//','/', str_replace('\\','/',substr($url,8)));
$url = rawurlencode($url);
$url = str_replace('%2F', '/', $url);
return $p.$url;
}
}
class DropboxException extends Exception {
public function __construct($err = null, $isDebug = FALSE)
{
if(is_null($err)) {
$el = error_get_last();
$this->message = $el['message'];
$this->file = $el['file'];
$this->line = $el['line'];
} else
$this->message = $err;
self::log_error($err);
if ($isDebug)
{
self::display_error($err, TRUE);
}
}
public static function log_error($err)
{
error_log($err, 0);
}
public static function display_error($err, $kill = FALSE)
{
print_r($err);
if ($kill === FALSE)
{
die();
}
}
}

View File

@@ -0,0 +1,525 @@
<?php
/**
* OAuthSimple - A simpler version of OAuth
*/
class OAuthSimple {
private $_secrets;
private $_default_signature_method;
private $_action;
private $_nonce_chars;
/**
* Constructor
*
* @access public
* @param api_key (String) The API Key (sometimes referred to as the consumer key) This value is usually supplied by the site you wish to use.
* @param shared_secret (String) The shared secret. This value is also usually provided by the site you wish to use.
* @return OAuthSimple (Object)
*/
function __construct ($APIKey = "", $sharedSecret=""){
if (!empty($APIKey))
{
$this->_secrets['consumer_key'] = $APIKey;
}
if (!empty($sharedSecret))
{
$this->_secrets['shared_secret'] = $sharedSecret;
}
$this->_default_signature_method = "HMAC-SHA1";
$this->_action = "GET";
$this->_nonce_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return $this;
}
/**
* Reset the parameters and URL
*
* @access public
* @return OAuthSimple (Object)
*/
public function reset() {
$this->_parameters = Array();
$this->path = NULL;
$this->sbs = NULL;
return $this;
}
/**
* Set the parameters either from a hash or a string
*
* @access public
* @param(string, object) List of parameters for the call, this can either be a URI string (e.g. "foo=bar&gorp=banana" or an object/hash)
* @return OAuthSimple (Object)
*/
public function setParameters ($parameters=Array()) {
if (is_string($parameters))
{
$parameters = $this->_parseParameterString($parameters);
}
if (empty($this->_parameters))
{
$this->_parameters = $parameters;
}
else if (!empty($parameters))
{
$this->_parameters = array_merge($this->_parameters,$parameters);
}
if (empty($this->_parameters['oauth_nonce']))
{
$this->_getNonce();
}
if (empty($this->_parameters['oauth_timestamp']))
{
$this->_getTimeStamp();
}
if (empty($this->_parameters['oauth_consumer_key']))
{
$this->_getApiKey();
}
if (empty($this->_parameters['oauth_token']))
{
$this->_getAccessToken();
}
if (empty($this->_parameters['oauth_signature_method']))
{
$this->setSignatureMethod();
}
if (empty($this->_parameters['oauth_version']))
{
$this->_parameters['oauth_version']="1.0";
}
return $this;
}
/**
* Convenience method for setParameters
*
* @access public
* @see setParameters
*/
public function setQueryString ($parameters)
{
return $this->setParameters($parameters);
}
/**
* Set the target URL (does not include the parameters)
*
* @param path (String) the fully qualified URI (excluding query arguments) (e.g "http://example.org/foo")
* @return OAuthSimple (Object)
*/
public function setURL ($path)
{
if (empty($path))
{
throw new OAuthSimpleException('No path specified for OAuthSimple.setURL');
}
$this->_path=$path;
return $this;
}
/**
* Convenience method for setURL
*
* @param path (String)
* @see setURL
*/
public function setPath ($path)
{
return $this->_path=$path;
}
/**
* Set the "action" for the url, (e.g. GET,POST, DELETE, etc.)
*
* @param action (String) HTTP Action word.
* @return OAuthSimple (Object)
*/
public function setAction ($action)
{
if (empty($action))
{
$action = 'GET';
}
$action = strtoupper($action);
if (preg_match('/[^A-Z]/',$action))
{
throw new OAuthSimpleException('Invalid action specified for OAuthSimple.setAction');
}
$this->_action = $action;
return $this;
}
/**
* Set the signatures (as well as validate the ones you have)
*
* @param signatures (object) object/hash of the token/signature pairs {api_key:, shared_secret:, oauth_token: oauth_secret:}
* @return OAuthSimple (Object)
*/
public function signatures ($signatures)
{
if (!empty($signatures) && !is_array($signatures))
{
throw new OAuthSimpleException('Must pass dictionary array to OAuthSimple.signatures');
}
if (!empty($signatures))
{
if (empty($this->_secrets))
{
$this->_secrets=Array();
}
$this->_secrets=array_merge($this->_secrets,$signatures);
}
if (isset($this->_secrets['api_key']))
{
$this->_secrets['consumer_key'] = $this->_secrets['api_key'];
}
if (isset($this->_secrets['access_token']))
{
$this->_secrets['oauth_token'] = $this->_secrets['access_token'];
}
if (isset($this->_secrets['access_secret']))
{
$this->_secrets['oauth_secret'] = $this->_secrets['access_secret'];
}
if (isset($this->_secrets['access_token_secret']))
{
$this->_secrets['oauth_secret'] = $this->_secrets['access_token_secret'];
}
if (empty($this->_secrets['consumer_key']))
{
throw new OAuthSimpleException('Missing required consumer_key in OAuthSimple.signatures');
}
if (empty($this->_secrets['shared_secret']))
{
throw new OAuthSimpleException('Missing requires shared_secret in OAuthSimple.signatures');
}
if (!empty($this->_secrets['oauth_token']) && empty($this->_secrets['oauth_secret']))
{
throw new OAuthSimpleException('Missing oauth_secret for supplied oauth_token in OAuthSimple.signatures');
}
return $this;
}
public function setTokensAndSecrets($signatures)
{
return $this->signatures($signatures);
}
/**
* Set the signature method (currently only Plaintext or SHA-MAC1)
*
* @param method (String) Method of signing the transaction (only PLAINTEXT and SHA-MAC1 allowed for now)
* @return OAuthSimple (Object)
*/
public function setSignatureMethod ($method="")
{
if (empty($method))
{
$method = $this->_default_signature_method;
}
$method = strtoupper($method);
switch($method)
{
case 'PLAINTEXT':
case 'HMAC-SHA1':
$this->_parameters['oauth_signature_method']=$method;
break;
default:
throw new OAuthSimpleException ("Unknown signing method $method specified for OAuthSimple.setSignatureMethod");
break;
}
return $this;
}
/** sign the request
*
* note: all arguments are optional, provided you've set them using the
* other helper functions.
*
* @param args (Array) hash of arguments for the call {action, path, parameters (array), method, signatures (array)} all arguments are optional.
* @return (Array) signed values
*/
public function sign($args=array())
{
if (!empty($args['action']))
{
$this->setAction($args['action']);
}
if (!empty($args['path']))
{
$this->setPath($args['path']);
}
if (!empty($args['method']))
{
$this->setSignatureMethod($args['method']);
}
if (!empty($args['signatures']))
{
$this->signatures($args['signatures']);
}
if (empty($args['parameters']))
{
$args['parameters']=array();
}
$this->setParameters($args['parameters']);
$normParams = $this->_normalizedParameters();
$this->_parameters['oauth_signature'] = $this->_generateSignature($normParams);
return Array (
'parameters' => $this->_parameters,
'signature' => self::_oauthEscape($this->_parameters['oauth_signature']),
'signed_url' => $this->_path . '?' . $this->_normalizedParameters(),
'header' => $this->getHeaderString(),
'sbs'=> $this->sbs
);
}
/**
* Return a formatted "header" string
*
* NOTE: This doesn't set the "Authorization: " prefix, which is required.
* It's not set because various set header functions prefer different
* ways to do that.
*
* @param args (Array)
* @return $result (String)
*/
public function getHeaderString ($args=array())
{
if (empty($this->_parameters['oauth_signature']))
{
$this->sign($args);
}
$result = 'OAuth ';
foreach ($this->_parameters as $pName => $pValue)
{
if (strpos($pName,'oauth_') !== 0 || $pName == 'oauth_token_secret2')
{
continue;
}
if (is_array($pValue))
{
foreach ($pValue as $val)
{
$result .= $pName .'="' . self::_oauthEscape($val) . '", ';
}
}
else
{
$result .= $pName . '="' . self::_oauthEscape($pValue) . '", ';
}
}
return preg_replace('/, $/','',$result);
}
private function _parseParameterString ($paramString)
{
$elements = explode('&',$paramString);
$result = array();
foreach ($elements as $element)
{
list ($key,$token) = explode('=',$element);
if ($token)
{
$token = urldecode($token);
}
if (!empty($result[$key]))
{
if (!is_array($result[$key]))
{
$result[$key] = array($result[$key],$token);
}
else
{
array_push($result[$key],$token);
}
}
else
$result[$key]=$token;
}
return $result;
}
private static function _oauthEscape($string)
{
if ($string === 0) { return 0; }
if ($string == '0') { return '0'; }
if (strlen($string) == 0) { return ''; }
if (is_array($string)) {
throw new OAuthSimpleException('Array passed to _oauthEscape');
}
$string = rawurlencode($string);
$string = str_replace('+','%20',$string);
$string = str_replace('!','%21',$string);
$string = str_replace('*','%2A',$string);
$string = str_replace('\'','%27',$string);
$string = str_replace('(','%28',$string);
$string = str_replace(')','%29',$string);
return $string;
}
private function _getNonce($length=5)
{
$result = '';
$cLength = strlen($this->_nonce_chars);
for ($i=0; $i < $length; $i++)
{
$rnum = rand(0,$cLength);
$result .= substr($this->_nonce_chars,$rnum,1);
}
$result = md5($result);
$this->_parameters['oauth_nonce'] = $result;
return $result;
}
private function _getApiKey()
{
if (empty($this->_secrets['consumer_key']))
{
throw new OAuthSimpleException('No consumer_key set for OAuthSimple');
}
$this->_parameters['oauth_consumer_key']=$this->_secrets['consumer_key'];
return $this->_parameters['oauth_consumer_key'];
}
private function _getAccessToken()
{
if (!isset($this->_secrets['oauth_secret']))
{
return '';
}
if (!isset($this->_secrets['oauth_token']))
{
throw new OAuthSimpleException('No access token (oauth_token) set for OAuthSimple.');
}
$this->_parameters['oauth_token'] = $this->_secrets['oauth_token'];
return $this->_parameters['oauth_token'];
}
private function _getTimeStamp()
{
return $this->_parameters['oauth_timestamp'] = time();
}
private function _normalizedParameters()
{
$normalized_keys = array();
$return_array = array();
foreach ( $this->_parameters as $paramName=>$paramValue) {
if (!preg_match('/\w+_secret/',$paramName) OR (strpos($paramValue, '@') !== 0 && !file_exists(substr($paramValue, 1))) )
{
if (is_array($paramValue))
{
$normalized_keys[self::_oauthEscape($paramName)] = array();
foreach($paramValue as $item)
{
array_push($normalized_keys[self::_oauthEscape($paramName)], self::_oauthEscape($item));
}
}
else
{
$normalized_keys[self::_oauthEscape($paramName)] = self::_oauthEscape($paramValue);
}
}
}
ksort($normalized_keys);
foreach($normalized_keys as $key=>$val)
{
if (is_array($val))
{
sort($val);
foreach($val as $element)
{
array_push($return_array, $key . "=" . $element);
}
}
else
{
array_push($return_array, $key .'='. $val);
}
}
return join("&", $return_array);
}
private function _generateSignature ()
{
$secretKey = '';
if(isset($this->_secrets['shared_secret']))
{
$secretKey = self::_oauthEscape($this->_secrets['shared_secret']);
}
$secretKey .= '&';
if(isset($this->_secrets['oauth_secret']))
{
$secretKey .= self::_oauthEscape($this->_secrets['oauth_secret']);
}
switch($this->_parameters['oauth_signature_method'])
{
case 'PLAINTEXT':
return urlencode($secretKey);;
case 'HMAC-SHA1':
$this->sbs = self::_oauthEscape($this->_action).'&'.self::_oauthEscape($this->_path).'&'.self::_oauthEscape($this->_normalizedParameters());
return base64_encode(hash_hmac('sha1',$this->sbs,$secretKey,TRUE));
default:
throw new OAuthSimpleException('Unknown signature method for OAuthSimple');
break;
}
}
}
class OAuthSimpleException extends Exception {
public function __construct($err, $isDebug = FALSE)
{
self::log_error($err);
if ($isDebug)
{
self::display_error($err, TRUE);
}
}
public static function log_error($err)
{
error_log($err, 0);
}
public static function display_error($err, $kill = FALSE)
{
print_r($err);
if ($kill === FALSE)
{
die();
}
}
}

View File

@@ -0,0 +1,62 @@
<?php
require_once("DropboxClient.php");
//$dropbox = new DropboxClient(array(
// 'app_key' => "77q37l8xr39jzim",
// 'app_secret' => "c8yg4nf87ur1mlr",
// 'app_full_access' => false,
//),'en');
//handle_dropbox_auth($dropbox); // see below
// if there is no upload, show the form
$app_params = array(
'app_key' => '\'yR0gg4AYBcIAAAAAAAADl7YdrTJPsHBEBszCe0TnTMOoOSkWKIQVszhaHZzK5Fjg\''
);
$dropbox = new DropboxClient($app_params);
//$dropbox->SetAccessToken('yR0gg4AYBcIAAAAAAAADl7YdrTJPsHBEBszCe0TnTMOoOSkWKIQVszhaHZzK5Fjg');
$upload_name = 'index.php';
$result = $dropbox->UploadFile($upload_name, $upload_name);
print_r($result);
// store_token, load_token, delete_token are SAMPLE functions! please replace with your own!
//function store_token($token, $name)
//{
// file_put_contents("dropbox/tokens/$name.token", serialize($token));
//}
//function load_token($name)
//{
// if(!file_exists("dropbox/tokens/$name.token")) return null;
// return @unserialize(@file_get_contents("dropbox/tokens/$name.token"));
//}
//function delete_token($name)
//{
// @unlink("dropbox/tokens/$name.token");
//}
//function handle_dropbox_auth($dropbox)
//{
// first try to load existing access token
//$access_token = load_token("access");
//if(!empty($access_token)) {
// $dropbox->SetAccessToken('');
//}
// elseif(!empty($_GET['auth_callback'])) // are we coming from dropbox's oauth page?
//{
// then load our previosly created request token
// $request_token = load_token($_GET['oauth_token']);
//if(empty($request_token)) die('Request token not found!');
// get & store access token, the request token is not needed anymore
// $access_token = $dropbox->GetAccessToken($request_token);
// store_token($access_token, "access");
// delete_token($_GET['oauth_token']);
// }
// checks if access token is required
// if(!$dropbox->IsAuthorized())
// {
// redirect user to dropbox oauth page
// $return_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?auth_callback=1";
// $auth_url = $dropbox->BuildAuthorizeUrl($return_url);
// $request_token = $dropbox->GetRequestToken();
// store_token($request_token, $request_token['t']);
// die("Authentication required".$auth_url);
// }
?>

View File

@@ -0,0 +1,7 @@
{
"require": {
"php": "^7.1",
"dropbox/dropbox-sdk": "1.1.*",
"kunalvarma05/dropbox-php-sdk": "^0.2.1"
}
}

146
webroot/dropbox/index.php Normal file
View File

@@ -0,0 +1,146 @@
<?php
// Make sure the script can handle large folders/files
ini_set('max_execution_time', 600);
ini_set('memory_limit','1024M');
//echo __DIR__;exit;
// Start the backup!
if(file_exists('vendor/autoload.php')){
require 'vendor/autoload.php';
//set access token
$token = 'yR0gg4AYBcIAAAAAAAADkngaO49IM1c4SJ2BTMbl-dBcTHJMAUVP2kgjZupkOOgg';
$projectFolder = 'uploadBackupchtl';
$zipfile=zipData('../dropbox', __DIR__.'/backup.zip');
echo 'Finished.';
if($zipfile){
$bk = new Backup($token,$projectFolder);
$bk->uploadFile('backup.zip');//file or folder to upload to dropbox
//echo '<pre>';print_r($bk);exit;
@unlink('backup.zip');
echo 'Upload Complete';
}
} else {
echo "<h1>Please install via composer.json</h1>";
echo "<p>Install Composer instructions: <a href='https://getcomposer.org/doc/00-intro.md#globally'>https://getcomposer.org/doc/00-intro.md#globally</a></p>";
echo "<p>Once composer is installed navigate to the working directory in your terminal/command promt and enter 'composer install'</p>";
exit;
}
// Here the magic happens :)
function zipData($source, $destination) {
if (extension_loaded('zip')) {
if (file_exists($source)) {
$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE)) {
//$source = realpath($source);
//echo $source;exit;
if (is_dir($source)) {
$iterator = new RecursiveDirectoryIterator($source);
// skip dot files while iterating
$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
// $file = realpath($file);
if (is_dir($file)) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} else if (is_file($file)) {
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
} else if (is_file($source)) {
$zip->addFromString(basename($source), file_get_contents($source));
}
}
return $zip->close();
}
}
return false;
}
class Backup
{
private $dbxClient;
private $projectFolder;
/**
* __construct pass token and project to the client method
* @param string $token authorization token for Dropbox API
* @param string $project name of project and version
* @param string $projectFolder name of the folder to upload into
*/
public function __construct($token, $projectFolder)
{
$this->dbxClient = new Spatie\Dropbox\Client($token);
$this->projectFolder = $projectFolder;
}
/**
* upload set the file or directory to upload
* @param [type] $dirtocopy [description]
* @return [type] [description]
*/
public function upload($dirtocopy)
{
if (!file_exists($dirtocopy)) {
exit("File $dirtocopy does not exist");
} else {
//if dealing with a file upload it
if (is_file($dirtocopy)) {
$this->uploadFile($dirtocopy);
} else { //otherwise collect all files and folders
$iter = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dirtocopy, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST,
\RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
//loop through all entries
foreach ($iter as $file) {
$words = explode('/',$file);
$stop = end($words);
//if file is not in the ignore list pass to uploadFile method
if (!in_array($stop, $this->ignoreList())) {
$this->uploadFile($file);
}
}
}
}
}
/**
* uploadFile upload file to dropbox using the Dropbox API
* @param string $file path to file
*/
public function uploadFile($file, $mode = 'add')
{
$path = "/".$this->projectFolder."/$file";
$contents = file_get_contents($file);
//if the contents is not empty upload otherwise do nothing
if (! empty($contents)) {
$this->dbxClient->upload($path, $contents, $mode);
}
}
/**
* ignoreList array of filenames or directories to ignore
* @return array
*/
public function ignoreList()
{
return array(
'.DS_Store',
'cgi-bin'
);
}
}

View File

@@ -0,0 +1,111 @@
<?php
require 'vendor/autoload.php';
use Kunnu\Dropbox\DropboxApp;
use Kunnu\Dropbox\DropboxFile;
use Kunnu\Dropbox\Dropbox;
ini_set('max_execution_time', 6000);
ini_set('memory_limit','1024M');
ini_set('upload_max_filesize','256M');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$day = date("d");
$month = date("F");
$year = date("Y");
$time = date("h:i A");
//setting database credentials
//setting dropbox credentials
$token = 'mTUgzAuCqsYAAAAAAAFrTdSe4rpzPQ3UH0GcnAxboMa3Wofi_RzdNetez54oHfWb';
$clientId = 'nunj4s97gyjqn4t';
$clientSecret = 'o1ycollvjjbo0xk';
$app = new DropboxApp($clientId, $clientSecret, $token);
$dropbox = new Dropbox($app);
if($dropbox){
$projectFolder = $month.","."$year"."/".$day."-".$month." ".$time." GMT +6";
$src_file = "backup_".$day."_".$month."_".$year.".zip";
$file_path = '../../../html';
deleteZipAndSqlFiles(__DIR__);
$zipfile = zipData($file_path, __DIR__.'/'.$src_file);
$database = 'rtg';
$user = 'root';
$pass = 'Nop@MySQL2017!#';
$host = 'localhost';
$db_file = "rtg_".$day."_".$month."_".$year.".sql";
exec("mysqldump --user={$user} --password={$pass} --host={$host} {$database} --result-file={$db_file} 2>&1", $output);
if($zipfile){
$src_path = __DIR__."/$src_file";
$dpx_src_path = "/".$projectFolder."/".$src_file;
$dropboxFile = new DropboxFile($src_path);
$file = $dropbox->upload($dropboxFile, $dpx_src_path, ['autorename' => false]);
$db_path = __DIR__."/$db_file";
$dpx_db_path = "/".$projectFolder."/".$db_file;
$dropboxDbFile = new DropboxFile($db_path);
$file = $dropbox->upload($dropboxDbFile, $dpx_db_path, ['autorename' => false]);
if($file){
echo "upload successfull";
unlink($src_file);
unlink($db_path);
}
}
}else{
echo "Your given dropbox credentials are wrong";
}
function zipData($source, $destination) {
if (extension_loaded('zip')) {
if (file_exists($source)) {
$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE)) {
$source = realpath($source);
if (is_dir($source)) {
$iterator = new RecursiveDirectoryIterator($source);
// skip dot files while iterating
$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = realpath($file);
if (is_dir($file)) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} else if (is_file($file)) {
$zip->addFile($file, str_replace($source . '/', '', $file));
}
}
} else if (is_file($source)) {
$zip->addFromString(basename($source), file_get_contents($source));
}
}
return $zip->close();
}
}
return false;
}
function deleteZipAndSqlFiles($dir){
$zipfiles = glob($dir."/*.zip");
$sqlfiles = glob($dir."/*.sql");
if(!empty($zipfiles)){
foreach($zipfiles as $zip){
@unlink($zip);
}
}
if(!empty($sqlfiles)){
foreach($sqlfiles as $sql){
@unlink($sql);
}
}
}

View File

@@ -0,0 +1,51 @@
<?php
require '../functions.php';
if (!$auth_user = getAuthUser()) {
exit('Invalid request');
}
require("../Staff/dbconfig.php");
$final_result = "failed";
try {
if ($_GET) {
$code = $_GET['code'];
$redirectUri = APP_SERVER_HOST_URL_DEFAULT . 'dropbox/success.php';
$app_key = $_SESSION['dropbox_app_key'];
$app_secret = $_SESSION['dropbox_app_secret'];
$appName = "RTG";
list($access_token, $refresh_token) = dropboxWebAuthFinish($code, $redirectUri, $app_key, $app_secret, $appName);
if (!empty($access_token)) {
$_SESSION['dropbox_access_token'] = $access_token;
$sql = "SELECT input_json from automations where member_id = " . $auth_user['id'] . " AND export_id = 2 AND id = " . $_SESSION['db_id'];
$result = $conn->query($sql);
$input_json = $result->fetch_assoc()['input_json'];
$input_json_array = [];
if (!empty($input_json)) {
$input_json_array = json_decode($input_json, true);
}
if (!empty($input_json_array) && !empty($refresh_token)) {
$input_json_array['dropbox_refresh_token'] = $refresh_token;
}
$final_result = "Your dropbox cannot authorize successfully";
if ($json_data = json_encode($input_json_array)) {
$sql = "UPDATE `automations` SET `input_json`='$json_data' WHERE id = " . $_SESSION['db_id'];
if ($conn->query($sql)) {
$final_result = "Your dropbox has authorized successfully";
unset($_SESSION['dropbox_app_key']);
unset($_SESSION['dropbox_app_secret']);
}
}
}
echo $final_result;
exit;
}
} catch (\Exception $ex) {
$final_result = $ex->getMessage();
}
echo $final_result;
exit;