diff --git a/apps/files_external/3rdparty/Dropbox/API.php b/apps/files_external/3rdparty/Dropbox/API.php new file mode 100644 index 0000000000..8cdce678e1 --- /dev/null +++ b/apps/files_external/3rdparty/Dropbox/API.php @@ -0,0 +1,380 @@ +oauth = $oauth; + $this->root = $root; + $this->useSSL = $useSSL; + if (!$this->useSSL) + { + throw new Dropbox_Exception('Dropbox REST API now requires that all requests use SSL'); + } + + } + + /** + * Returns information about the current dropbox account + * + * @return stdclass + */ + public function getAccountInfo() { + + $data = $this->oauth->fetch($this->api_url . 'account/info'); + return json_decode($data['body'],true); + + } + + /** + * Returns a file's contents + * + * @param string $path path + * @param string $root Use this to override the default root path (sandbox/dropbox) + * @return string + */ + public function getFile($path = '', $root = null) { + + if (is_null($root)) $root = $this->root; + $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); + $result = $this->oauth->fetch($this->api_content_url . 'files/' . $root . '/' . ltrim($path,'/')); + return $result['body']; + + } + + /** + * Uploads a new file + * + * @param string $path Target path (including filename) + * @param string $file Either a path to a file or a stream resource + * @param string $root Use this to override the default root path (sandbox/dropbox) + * @return bool + */ + public function putFile($path, $file, $root = null) { + + $directory = dirname($path); + $filename = basename($path); + + if($directory==='.') $directory = ''; + $directory = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($directory)); +// $filename = str_replace('~', '%7E', rawurlencode($filename)); + if (is_null($root)) $root = $this->root; + + if (is_string($file)) { + + $file = fopen($file,'rb'); + + } elseif (!is_resource($file)) { + throw new Dropbox_Exception('File must be a file-resource or a string'); + } + $result=$this->multipartFetch($this->api_content_url . 'files/' . + $root . '/' . trim($directory,'/'), $file, $filename); + + if(!isset($result["httpStatus"]) || $result["httpStatus"] != 200) + throw new Dropbox_Exception("Uploading file to Dropbox failed"); + + return true; + } + + + /** + * Copies a file or directory from one location to another + * + * This method returns the file information of the newly created file. + * + * @param string $from source path + * @param string $to destination path + * @param string $root Use this to override the default root path (sandbox/dropbox) + * @return stdclass + */ + public function copy($from, $to, $root = null) { + + if (is_null($root)) $root = $this->root; + $response = $this->oauth->fetch($this->api_url . 'fileops/copy', array('from_path' => $from, 'to_path' => $to, 'root' => $root), 'POST'); + + return json_decode($response['body'],true); + + } + + /** + * Creates a new folder + * + * This method returns the information from the newly created directory + * + * @param string $path + * @param string $root Use this to override the default root path (sandbox/dropbox) + * @return stdclass + */ + public function createFolder($path, $root = null) { + + if (is_null($root)) $root = $this->root; + + // Making sure the path starts with a / +// $path = '/' . ltrim($path,'/'); + + $response = $this->oauth->fetch($this->api_url . 'fileops/create_folder', array('path' => $path, 'root' => $root),'POST'); + return json_decode($response['body'],true); + + } + + /** + * Deletes a file or folder. + * + * This method will return the metadata information from the deleted file or folder, if successful. + * + * @param string $path Path to new folder + * @param string $root Use this to override the default root path (sandbox/dropbox) + * @return array + */ + public function delete($path, $root = null) { + + if (is_null($root)) $root = $this->root; + $response = $this->oauth->fetch($this->api_url . 'fileops/delete', array('path' => $path, 'root' => $root), 'POST'); + return json_decode($response['body']); + + } + + /** + * Moves a file or directory to a new location + * + * This method returns the information from the newly created directory + * + * @param mixed $from Source path + * @param mixed $to destination path + * @param string $root Use this to override the default root path (sandbox/dropbox) + * @return stdclass + */ + public function move($from, $to, $root = null) { + + if (is_null($root)) $root = $this->root; + $response = $this->oauth->fetch($this->api_url . 'fileops/move', array('from_path' => rawurldecode($from), 'to_path' => rawurldecode($to), 'root' => $root), 'POST'); + + return json_decode($response['body'],true); + + } + + /** + * Returns file and directory information + * + * @param string $path Path to receive information from + * @param bool $list When set to true, this method returns information from all files in a directory. When set to false it will only return infromation from the specified directory. + * @param string $hash If a hash is supplied, this method simply returns true if nothing has changed since the last request. Good for caching. + * @param int $fileLimit Maximum number of file-information to receive + * @param string $root Use this to override the default root path (sandbox/dropbox) + * @return array|true + */ + public function getMetaData($path, $list = true, $hash = null, $fileLimit = null, $root = null) { + + if (is_null($root)) $root = $this->root; + + $args = array( + 'list' => $list, + ); + + if (!is_null($hash)) $args['hash'] = $hash; + if (!is_null($fileLimit)) $args['file_limit'] = $fileLimit; + + $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); + $response = $this->oauth->fetch($this->api_url . 'metadata/' . $root . '/' . ltrim($path,'/'), $args); + + /* 304 is not modified */ + if ($response['httpStatus']==304) { + return true; + } else { + return json_decode($response['body'],true); + } + + } + + /** + * A way of letting you keep up with changes to files and folders in a user's Dropbox. You can periodically call /delta to get a list of "delta entries", which are instructions on how to update your local state to match the server's state. + * + * This method returns the information from the newly created directory + * + * @param string $cursor A string that is used to keep track of your current state. On the next call pass in this value to return delta entries that have been recorded since the cursor was returned. + * @return stdclass + */ + public function delta($cursor) { + + $arg['cursor'] = $cursor; + + $response = $this->oauth->fetch($this->api_url . 'delta', $arg, 'POST'); + return json_decode($response['body'],true); + + } + + /** + * Returns a thumbnail (as a string) for a file path. + * + * @param string $path Path to file + * @param string $size small, medium or large + * @param string $root Use this to override the default root path (sandbox/dropbox) + * @return string + */ + public function getThumbnail($path, $size = 'small', $root = null) { + + if (is_null($root)) $root = $this->root; + $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); + $response = $this->oauth->fetch($this->api_content_url . 'thumbnails/' . $root . '/' . ltrim($path,'/'),array('size' => $size)); + + return $response['body']; + + } + + /** + * This method is used to generate multipart POST requests for file upload + * + * @param string $uri + * @param array $arguments + * @return bool + */ + protected function multipartFetch($uri, $file, $filename) { + + /* random string */ + $boundary = 'R50hrfBj5JYyfR3vF3wR96GPCC9Fd2q2pVMERvEaOE3D8LZTgLLbRpNwXek3'; + + $headers = array( + 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, + ); + + $body="--" . $boundary . "\r\n"; + $body.="Content-Disposition: form-data; name=file; filename=".rawurldecode($filename)."\r\n"; + $body.="Content-type: application/octet-stream\r\n"; + $body.="\r\n"; + $body.=stream_get_contents($file); + $body.="\r\n"; + $body.="--" . $boundary . "--"; + + // Dropbox requires the filename to also be part of the regular arguments, so it becomes + // part of the signature. + $uri.='?file=' . $filename; + + return $this->oauth->fetch($uri, $body, 'POST', $headers); + + } + + + /** + * Search + * + * Returns metadata for all files and folders that match the search query. + * + * @added by: diszo.sasil + * + * @param string $query + * @param string $root Use this to override the default root path (sandbox/dropbox) + * @param string $path + * @return array + */ + public function search($query = '', $root = null, $path = ''){ + if (is_null($root)) $root = $this->root; + if(!empty($path)){ + $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); + } + $response = $this->oauth->fetch($this->api_url . 'search/' . $root . '/' . ltrim($path,'/'),array('query' => $query)); + return json_decode($response['body'],true); + } + + /** + * Creates and returns a shareable link to files or folders. + * + * Note: Links created by the /shares API call expire after thirty days. + * + * @param type $path + * @param type $root + * @return type + */ + public function share($path, $root = null) { + if (is_null($root)) $root = $this->root; + $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); + $response = $this->oauth->fetch($this->api_url. 'shares/'. $root . '/' . ltrim($path, '/'), array(), 'POST'); + return json_decode($response['body'],true); + + } + + /** + * Returns a link directly to a file. + * Similar to /shares. The difference is that this bypasses the Dropbox webserver, used to provide a preview of the file, so that you can effectively stream the contents of your media. + * + * Note: The /media link expires after four hours, allotting enough time to stream files, but not enough to leave a connection open indefinitely. + * + * @param type $path + * @param type $root + * @return type + */ + public function media($path, $root = null) { + + if (is_null($root)) $root = $this->root; + $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); + $response = $this->oauth->fetch($this->api_url. 'media/'. $root . '/' . ltrim($path, '/'), array(), 'POST'); + return json_decode($response['body'],true); + + } + + /** + * Creates and returns a copy_ref to a file. This reference string can be used to copy that file to another user's Dropbox by passing it in as the from_copy_ref parameter on /fileops/copy. + * + * @param type $path + * @param type $root + * @return type + */ + public function copy_ref($path, $root = null) { + + if (is_null($root)) $root = $this->root; + $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path)); + $response = $this->oauth->fetch($this->api_url. 'copy_ref/'. $root . '/' . ltrim($path, '/')); + return json_decode($response['body'],true); + + } + + +} diff --git a/apps/files_external/3rdparty/Dropbox/Exception.php b/apps/files_external/3rdparty/Dropbox/Exception.php new file mode 100644 index 0000000000..50cbc4c791 --- /dev/null +++ b/apps/files_external/3rdparty/Dropbox/Exception.php @@ -0,0 +1,15 @@ +oauth_token = $token['token']; + $this->oauth_token_secret = $token['token_secret']; + } else { + $this->oauth_token = $token; + $this->oauth_token_secret = $token_secret; + } + + } + + /** + * Returns the oauth request tokens as an associative array. + * + * The array will contain the elements 'token' and 'token_secret'. + * + * @return array + */ + public function getToken() { + + return array( + 'token' => $this->oauth_token, + 'token_secret' => $this->oauth_token_secret, + ); + + } + + /** + * Returns the authorization url + * + * @param string $callBack Specify a callback url to automatically redirect the user back + * @return string + */ + public function getAuthorizeUrl($callBack = null) { + + // Building the redirect uri + $token = $this->getToken(); + $uri = self::URI_AUTHORIZE . '?oauth_token=' . $token['token']; + if ($callBack) $uri.='&oauth_callback=' . $callBack; + return $uri; + } + + /** + * Fetches a secured oauth url and returns the response body. + * + * @param string $uri + * @param mixed $arguments + * @param string $method + * @param array $httpHeaders + * @return string + */ + public abstract function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()); + + /** + * Requests the OAuth request token. + * + * @return array + */ + abstract public function getRequestToken(); + + /** + * Requests the OAuth access tokens. + * + * @return array + */ + abstract public function getAccessToken(); + +} diff --git a/apps/files_external/3rdparty/Dropbox/OAuth/Consumer/Dropbox.php b/apps/files_external/3rdparty/Dropbox/OAuth/Consumer/Dropbox.php new file mode 100644 index 0000000000..204a659de0 --- /dev/null +++ b/apps/files_external/3rdparty/Dropbox/OAuth/Consumer/Dropbox.php @@ -0,0 +1,37 @@ +consumerRequest instanceof HTTP_OAuth_Consumer_Request) { + $this->consumerRequest = new HTTP_OAuth_Consumer_Request; + } + + // TODO: Change this and add in code to validate the SSL cert. + // see https://github.com/bagder/curl/blob/master/lib/mk-ca-bundle.pl + $this->consumerRequest->setConfig(array( + 'ssl_verify_peer' => false, + 'ssl_verify_host' => false + )); + + return $this->consumerRequest; + } +} diff --git a/apps/files_external/3rdparty/Dropbox/OAuth/Curl.php b/apps/files_external/3rdparty/Dropbox/OAuth/Curl.php new file mode 100644 index 0000000000..b75b27bb36 --- /dev/null +++ b/apps/files_external/3rdparty/Dropbox/OAuth/Curl.php @@ -0,0 +1,282 @@ +consumerKey = $consumerKey; + $this->consumerSecret = $consumerSecret; + } + + /** + * Fetches a secured oauth url and returns the response body. + * + * @param string $uri + * @param mixed $arguments + * @param string $method + * @param array $httpHeaders + * @return string + */ + public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) { + + $uri=str_replace('http://', 'https://', $uri); // all https, upload makes problems if not + if (is_string($arguments) and strtoupper($method) == 'POST') { + preg_match("/\?file=(.*)$/i", $uri, $matches); + if (isset($matches[1])) { + $uri = str_replace($matches[0], "", $uri); + $filename = $matches[1]; + $httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, array("file" => $filename), $method)); + } + } else { + $httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, $arguments, $method)); + } + $ch = curl_init(); + if (strtoupper($method) == 'POST') { + curl_setopt($ch, CURLOPT_URL, $uri); + curl_setopt($ch, CURLOPT_POST, true); +// if (is_array($arguments)) +// $arguments=http_build_query($arguments); + curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments); +// $httpHeaders['Content-Length']=strlen($arguments); + } else { + curl_setopt($ch, CURLOPT_URL, $uri.'?'.http_build_query($arguments)); + curl_setopt($ch, CURLOPT_POST, false); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_TIMEOUT, 300); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); +// curl_setopt($ch, CURLOPT_CAINFO, "rootca"); + curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); + //Build header + $headers = array(); + foreach ($httpHeaders as $name => $value) { + $headers[] = "{$name}: $value"; + } + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + if (!ini_get('safe_mode') && !ini_get('open_basedir')) + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true ); + if (function_exists($this->ProgressFunction) and defined('CURLOPT_PROGRESSFUNCTION')) { + curl_setopt($ch, CURLOPT_NOPROGRESS, false); + curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $this->ProgressFunction); + curl_setopt($ch, CURLOPT_BUFFERSIZE, 512); + } + $response=curl_exec($ch); + $errorno=curl_errno($ch); + $error=curl_error($ch); + $status=curl_getinfo($ch,CURLINFO_HTTP_CODE); + curl_close($ch); + + + if (!empty($errorno)) + throw new Dropbox_Exception_NotFound('Curl error: ('.$errorno.') '.$error."\n"); + + if ($status>=300) { + $body = json_decode($response,true); + switch ($status) { + // Not modified + case 304 : + return array( + 'httpStatus' => 304, + 'body' => null, + ); + break; + case 403 : + throw new Dropbox_Exception_Forbidden('Forbidden. + This could mean a bad OAuth request, or a file or folder already existing at the target location. + ' . $body["error"] . "\n"); + case 404 : + throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found. ' . + $body["error"] . "\n"); + case 507 : + throw new Dropbox_Exception_OverQuota('This dropbox is full. ' . + $body["error"] . "\n"); + } + if (!empty($body["error"])) + throw new Dropbox_Exception_RequestToken('Error: ('.$status.') '.$body["error"]."\n"); + } + + return array( + 'body' => $response, + 'httpStatus' => $status + ); + } + + /** + * Returns named array with oauth parameters for further use + * @return array Array with oauth_ parameters + */ + private function getOAuthBaseParams() { + $params['oauth_version'] = '1.0'; + $params['oauth_signature_method'] = 'HMAC-SHA1'; + + $params['oauth_consumer_key'] = $this->consumerKey; + $tokens = $this->getToken(); + if (isset($tokens['token']) && $tokens['token']) { + $params['oauth_token'] = $tokens['token']; + } + $params['oauth_timestamp'] = time(); + $params['oauth_nonce'] = md5(microtime() . mt_rand()); + return $params; + } + + /** + * Creates valid Authorization header for OAuth, based on URI and Params + * + * @param string $uri + * @param array $params + * @param string $method GET or POST, standard is GET + * @param array $oAuthParams optional, pass your own oauth_params here + * @return array Array for request's headers section like + * array('Authorization' => 'OAuth ...'); + */ + private function getOAuthHeader($uri, $params, $method = 'GET', $oAuthParams = null) { + $oAuthParams = $oAuthParams ? $oAuthParams : $this->getOAuthBaseParams(); + + // create baseString to encode for the sent parameters + $baseString = $method . '&'; + $baseString .= $this->oauth_urlencode($uri) . "&"; + + // OAuth header does not include GET-Parameters + $signatureParams = array_merge($params, $oAuthParams); + + // sorting the parameters + ksort($signatureParams); + + $encodedParams = array(); + foreach ($signatureParams as $key => $value) { + $encodedParams[] = $this->oauth_urlencode($key) . '=' . $this->oauth_urlencode($value); + } + + $baseString .= $this->oauth_urlencode(implode('&', $encodedParams)); + + // encode the signature + $tokens = $this->getToken(); + $hash = $this->hash_hmac_sha1($this->consumerSecret.'&'.$tokens['token_secret'], $baseString); + $signature = base64_encode($hash); + + // add signature to oAuthParams + $oAuthParams['oauth_signature'] = $signature; + + $oAuthEncoded = array(); + foreach ($oAuthParams as $key => $value) { + $oAuthEncoded[] = $key . '="' . $this->oauth_urlencode($value) . '"'; + } + + return array('Authorization' => 'OAuth ' . implode(', ', $oAuthEncoded)); + } + + /** + * Requests the OAuth request token. + * + * @return void + */ + public function getRequestToken() { + $result = $this->fetch(self::URI_REQUEST_TOKEN, array(), 'POST'); + if ($result['httpStatus'] == "200") { + $tokens = array(); + parse_str($result['body'], $tokens); + $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']); + return $this->getToken(); + } else { + throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.'); + } + } + + /** + * Requests the OAuth access tokens. + * + * This method requires the 'unauthorized' request tokens + * and, if successful will set the authorized request tokens. + * + * @return void + */ + public function getAccessToken() { + $result = $this->fetch(self::URI_ACCESS_TOKEN, array(), 'POST'); + if ($result['httpStatus'] == "200") { + $tokens = array(); + parse_str($result['body'], $tokens); + $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']); + return $this->getToken(); + } else { + throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.'); + } + } + + /** + * Helper function to properly urlencode parameters. + * See http://php.net/manual/en/function.oauth-urlencode.php + * + * @param string $string + * @return string + */ + private function oauth_urlencode($string) { + return str_replace('%E7', '~', rawurlencode($string)); + } + + /** + * Hash function for hmac_sha1; uses native function if available. + * + * @param string $key + * @param string $data + * @return string + */ + private function hash_hmac_sha1($key, $data) { + if (function_exists('hash_hmac') && in_array('sha1', hash_algos())) { + return hash_hmac('sha1', $data, $key, true); + } else { + $blocksize = 64; + $hashfunc = 'sha1'; + if (strlen($key) > $blocksize) { + $key = pack('H*', $hashfunc($key)); + } + + $key = str_pad($key, $blocksize, chr(0x00)); + $ipad = str_repeat(chr(0x36), $blocksize); + $opad = str_repeat(chr(0x5c), $blocksize); + $hash = pack('H*', $hashfunc(( $key ^ $opad ) . pack('H*', $hashfunc(($key ^ $ipad) . $data)))); + + return $hash; + } + } + + +} \ No newline at end of file diff --git a/apps/files_external/3rdparty/Dropbox/README.md b/apps/files_external/3rdparty/Dropbox/README.md new file mode 100644 index 0000000000..54e05db762 --- /dev/null +++ b/apps/files_external/3rdparty/Dropbox/README.md @@ -0,0 +1,31 @@ +Dropbox-php +=========== + +This PHP library allows you to easily integrate dropbox with PHP. + +The following PHP extension is required: + +* json + +The library makes use of OAuth. At the moment you can use either of these libraries: + +[PHP OAuth extension](http://pecl.php.net/package/oauth) +[PEAR's HTTP_OAUTH package](http://pear.php.net/package/http_oauth) + +The extension is recommended, but if you can't install php extensions you should go for the pear package. +Installing +---------- + + pear channel-discover pear.dropbox-php.com + pear install dropbox-php/Dropbox-alpha + +Documentation +------------- +Check out the [documentation](http://www.dropbox-php.com/docs). + +Questions? +---------- + +[Dropbox-php Mailing list](http://groups.google.com/group/dropbox-php) +[Official Dropbox developer forum](http://forums.dropbox.com/forum.php?id=5) + diff --git a/apps/files_external/3rdparty/Dropbox/autoload.php b/apps/files_external/3rdparty/Dropbox/autoload.php new file mode 100644 index 0000000000..5388ea6334 --- /dev/null +++ b/apps/files_external/3rdparty/Dropbox/autoload.php @@ -0,0 +1,29 @@ + +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +################################################################### + +define ('SMB4PHP_VERSION', '0.8'); + +################################################################### +# CONFIGURATION SECTION - Change for your needs +################################################################### + +define ('SMB4PHP_SMBCLIENT', 'smbclient'); +define ('SMB4PHP_SMBOPTIONS', 'TCP_NODELAY IPTOS_LOWDELAY SO_KEEPALIVE SO_RCVBUF=8192 SO_SNDBUF=8192'); +define ('SMB4PHP_AUTHMODE', 'arg'); # set to 'env' to use USER enviroment variable + +################################################################### +# SMB - commands that does not need an instance +################################################################### + +$GLOBALS['__smb_cache'] = array ('stat' => array (), 'dir' => array ()); + +class smb { + + function parse_url ($url) { + $pu = parse_url (trim($url)); + foreach (array ('domain', 'user', 'pass', 'host', 'port', 'path') as $i) { + if (! isset($pu[$i])) { + $pu[$i] = ''; + } + } + if (count ($userdomain = explode (';', urldecode ($pu['user']))) > 1) { + @list ($pu['domain'], $pu['user']) = $userdomain; + } + $path = preg_replace (array ('/^\//', '/\/$/'), '', urldecode ($pu['path'])); + list ($pu['share'], $pu['path']) = (preg_match ('/^([^\/]+)\/(.*)/', $path, $regs)) + ? array ($regs[1], preg_replace ('/\//', '\\', $regs[2])) + : array ($path, ''); + $pu['type'] = $pu['path'] ? 'path' : ($pu['share'] ? 'share' : ($pu['host'] ? 'host' : '**error**')); + if (! ($pu['port'] = intval(@$pu['port']))) { + $pu['port'] = 139; + } + + // decode user and password + $pu['user'] = urldecode($pu['user']); + $pu['pass'] = urldecode($pu['pass']); + return $pu; + } + + + function look ($purl) { + return smb::client ('-L ' . escapeshellarg ($purl['host']), $purl); + } + + + function execute ($command, $purl) { + return smb::client ('-d 0 ' + . escapeshellarg ('//' . $purl['host'] . '/' . $purl['share']) + . ' -c ' . escapeshellarg ($command), $purl + ); + } + + function client ($params, $purl) { + + static $regexp = array ( + '^added interface ip=(.*) bcast=(.*) nmask=(.*)$' => 'skip', + 'Anonymous login successful' => 'skip', + '^Domain=\[(.*)\] OS=\[(.*)\] Server=\[(.*)\]$' => 'skip', + '^\tSharename[ ]+Type[ ]+Comment$' => 'shares', + '^\t---------[ ]+----[ ]+-------$' => 'skip', + '^\tServer [ ]+Comment$' => 'servers', + '^\t---------[ ]+-------$' => 'skip', + '^\tWorkgroup[ ]+Master$' => 'workg', + '^\t(.*)[ ]+(Disk|IPC)[ ]+IPC.*$' => 'skip', + '^\tIPC\\\$(.*)[ ]+IPC' => 'skip', + '^\t(.*)[ ]+(Disk)[ ]+(.*)$' => 'share', + '^\t(.*)[ ]+(Printer)[ ]+(.*)$' => 'skip', + '([0-9]+) blocks of size ([0-9]+)\. ([0-9]+) blocks available' => 'skip', + 'Got a positive name query response from ' => 'skip', + '^(session setup failed): (.*)$' => 'error', + '^(.*): ERRSRV - ERRbadpw' => 'error', + '^Error returning browse list: (.*)$' => 'error', + '^tree connect failed: (.*)$' => 'error', + '^(Connection to .* failed)(.*)$' => 'error-connect', + '^NT_STATUS_(.*) ' => 'error', + '^NT_STATUS_(.*)\$' => 'error', + 'ERRDOS - ERRbadpath \((.*).\)' => 'error', + 'cd (.*): (.*)$' => 'error', + '^cd (.*): NT_STATUS_(.*)' => 'error', + '^\t(.*)$' => 'srvorwg', + '^([0-9]+)[ ]+([0-9]+)[ ]+(.*)$' => 'skip', + '^Job ([0-9]+) cancelled' => 'skip', + '^[ ]+(.*)[ ]+([0-9]+)[ ]+(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[ ](Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[ ]+([0-9]+)[ ]+([0-9]{2}:[0-9]{2}:[0-9]{2})[ ]([0-9]{4})$' => 'files', + '^message start: ERRSRV - (ERRmsgoff)' => 'error' + ); + + if (SMB4PHP_AUTHMODE == 'env') { + putenv("USER={$purl['user']}%{$purl['pass']}"); + $auth = ''; + } else { + $auth = ($purl['user'] <> '' ? (' -U ' . escapeshellarg ($purl['user'] . '%' . $purl['pass'])) : ''); + } + if ($purl['domain'] <> '') { + $auth .= ' -W ' . escapeshellarg ($purl['domain']); + } + $port = ($purl['port'] <> 139 ? ' -p ' . escapeshellarg ($purl['port']) : ''); + $options = '-O ' . escapeshellarg(SMB4PHP_SMBOPTIONS); + + // this put env is necessary to read the output of smbclient correctly + $old_locale = getenv('LC_ALL'); + putenv('LC_ALL=en_US.UTF-8'); + $output = popen (SMB4PHP_SMBCLIENT." -N {$auth} {$options} {$port} {$options} {$params} 2>/dev/null", 'r'); + $info = array (); + $info['info']= array (); + $mode = ''; + while ($line = fgets ($output, 4096)) { + list ($tag, $regs, $i) = array ('skip', array (), array ()); + reset ($regexp); + foreach ($regexp as $r => $t) if (preg_match ('/'.$r.'/', $line, $regs)) { + $tag = $t; + break; + } + switch ($tag) { + case 'skip': continue; + case 'shares': $mode = 'shares'; break; + case 'servers': $mode = 'servers'; break; + case 'workg': $mode = 'workgroups'; break; + case 'share': + list($name, $type) = array ( + trim(substr($line, 1, 15)), + trim(strtolower(substr($line, 17, 10))) + ); + $i = ($type <> 'disk' && preg_match('/^(.*) Disk/', $line, $regs)) + ? array(trim($regs[1]), 'disk') + : array($name, 'disk'); + break; + case 'srvorwg': + list ($name, $master) = array ( + strtolower(trim(substr($line,1,21))), + strtolower(trim(substr($line, 22))) + ); + $i = ($mode == 'servers') ? array ($name, "server") : array ($name, "workgroup", $master); + break; + case 'files': + list ($attr, $name) = preg_match ("/^(.*)[ ]+([D|A|H|S|R]+)$/", trim ($regs[1]), $regs2) + ? array (trim ($regs2[2]), trim ($regs2[1])) + : array ('', trim ($regs[1])); + list ($his, $im) = array ( + explode(':', $regs[6]), 1 + strpos("JanFebMarAprMayJunJulAugSepOctNovDec", $regs[4]) / 3); + $i = ($name <> '.' && $name <> '..') + ? array ( + $name, + (strpos($attr,'D') === FALSE) ? 'file' : 'folder', + 'attr' => $attr, + 'size' => intval($regs[2]), + 'time' => mktime ($his[0], $his[1], $his[2], $im, $regs[5], $regs[7]) + ) + : array(); + break; + case 'error': + if(substr($regs[0],0,22)=='NT_STATUS_NO_SUCH_FILE'){ + return false; + }elseif(substr($regs[0],0,31)=='NT_STATUS_OBJECT_NAME_COLLISION'){ + return false; + }elseif(substr($regs[0],0,31)=='NT_STATUS_OBJECT_PATH_NOT_FOUND'){ + return false; + }elseif(substr($regs[0],0,29)=='NT_STATUS_FILE_IS_A_DIRECTORY'){ + return false; + } + trigger_error($regs[0].' params('.$params.')', E_USER_ERROR); + case 'error-connect': + return false; + } + if ($i) switch ($i[1]) { + case 'file': + case 'folder': $info['info'][$i[0]] = $i; + case 'disk': + case 'server': + case 'workgroup': $info[$i[1]][] = $i[0]; + } + } + pclose($output); + + + // restore previous locale + if ($old_locale===false) { + putenv('LC_ALL'); + } else { + putenv('LC_ALL='.$old_locale); + } + + return $info; + } + + + # stats + + function url_stat ($url, $flags = STREAM_URL_STAT_LINK) { + if ($s = smb::getstatcache($url)) { + return $s; + } + list ($stat, $pu) = array (false, smb::parse_url ($url)); + switch ($pu['type']) { + case 'host': + if ($o = smb::look ($pu)) + $stat = stat ("/tmp"); + else + trigger_error ("url_stat(): list failed for host '{$pu['host']}'", E_USER_WARNING); + break; + case 'share': + if ($o = smb::look ($pu)) { + $found = FALSE; + $lshare = strtolower ($pu['share']); # fix by Eric Leung + foreach ($o['disk'] as $s) if ($lshare == strtolower($s)) { + $found = TRUE; + $stat = stat ("/tmp"); + break; + } + if (! $found) + trigger_error ("url_stat(): disk resource '{$lshare}' not found in '{$pu['host']}'", E_USER_WARNING); + } + break; + case 'path': + if ($o = smb::execute ('dir "'.$pu['path'].'"', $pu)) { + $p = explode('\\', $pu['path']); + $name = $p[count($p)-1]; + if (isset ($o['info'][$name])) { + $stat = smb::addstatcache ($url, $o['info'][$name]); + } else { + trigger_error ("url_stat(): path '{$pu['path']}' not found", E_USER_WARNING); + } + } else { + return false; +// trigger_error ("url_stat(): dir failed for path '{$pu['path']}'", E_USER_WARNING); + } + break; + default: trigger_error ('error in URL', E_USER_ERROR); + } + return $stat; + } + + function addstatcache ($url, $info) { + $url = str_replace('//', '/', $url); + $url = rtrim($url, '/'); + global $__smb_cache; + $is_file = (strpos ($info['attr'],'D') === FALSE); + $s = ($is_file) ? stat ('/etc/passwd') : stat ('/tmp'); + $s[7] = $s['size'] = $info['size']; + $s[8] = $s[9] = $s[10] = $s['atime'] = $s['mtime'] = $s['ctime'] = $info['time']; + return $__smb_cache['stat'][$url] = $s; + } + + function getstatcache ($url) { + $url = str_replace('//', '/', $url); + $url = rtrim($url, '/'); + global $__smb_cache; + return isset ($__smb_cache['stat'][$url]) ? $__smb_cache['stat'][$url] : FALSE; + } + + function clearstatcache ($url='') { + $url = str_replace('//', '/', $url); + $url = rtrim($url, '/'); + global $__smb_cache; + if ($url == '') $__smb_cache['stat'] = array (); else unset ($__smb_cache['stat'][$url]); + } + + + # commands + + function unlink ($url) { + $pu = smb::parse_url($url); + if ($pu['type'] <> 'path') trigger_error('unlink(): error in URL', E_USER_ERROR); + smb::clearstatcache ($url); + smb_stream_wrapper::cleardircache (dirname($url)); + return smb::execute ('del "'.$pu['path'].'"', $pu); + } + + function rename ($url_from, $url_to) { + list ($from, $to) = array (smb::parse_url($url_from), smb::parse_url($url_to)); + if ($from['host'] <> $to['host'] || + $from['share'] <> $to['share'] || + $from['user'] <> $to['user'] || + $from['pass'] <> $to['pass'] || + $from['domain'] <> $to['domain']) { + trigger_error('rename(): FROM & TO must be in same server-share-user-pass-domain', E_USER_ERROR); + } + if ($from['type'] <> 'path' || $to['type'] <> 'path') { + trigger_error('rename(): error in URL', E_USER_ERROR); + } + smb::clearstatcache ($url_from); + return smb::execute ('rename "'.$from['path'].'" "'.$to['path'].'"', $to); + } + + function mkdir ($url, $mode, $options) { + $pu = smb::parse_url($url); + if ($pu['type'] <> 'path') trigger_error('mkdir(): error in URL', E_USER_ERROR); + return smb::execute ('mkdir "'.$pu['path'].'"', $pu)!==false; + } + + function rmdir ($url) { + $pu = smb::parse_url($url); + if ($pu['type'] <> 'path') trigger_error('rmdir(): error in URL', E_USER_ERROR); + smb::clearstatcache ($url); + smb_stream_wrapper::cleardircache (dirname($url)); + return smb::execute ('rmdir "'.$pu['path'].'"', $pu)!==false; + } + +} + +################################################################### +# SMB_STREAM_WRAPPER - class to be registered for smb:// URLs +################################################################### + +class smb_stream_wrapper extends smb { + + # variables + + private $stream, $url, $parsed_url = array (), $mode, $tmpfile; + private $need_flush = FALSE; + private $dir = array (), $dir_index = -1; + + + # directories + + function dir_opendir ($url, $options) { + if ($d = $this->getdircache ($url)) { + $this->dir = $d; + $this->dir_index = 0; + return TRUE; + } + $pu = smb::parse_url ($url); + switch ($pu['type']) { + case 'host': + if ($o = smb::look ($pu)) { + $this->dir = $o['disk']; + $this->dir_index = 0; + } else { + trigger_error ("dir_opendir(): list failed for host '{$pu['host']}'", E_USER_WARNING); + return false; + } + break; + case 'share': + case 'path': + if (is_array($o = smb::execute ('dir "'.$pu['path'].'\*"', $pu))) { + $this->dir = array_keys($o['info']); + $this->dir_index = 0; + $this->adddircache ($url, $this->dir); + if(substr($url,-1,1)=='/'){ + $url=substr($url,0,-1); + } + foreach ($o['info'] as $name => $info) { + smb::addstatcache($url . '/' . $name, $info); + } + } else { + trigger_error ("dir_opendir(): dir failed for path '".$pu['path']."'", E_USER_WARNING); + return false; + } + break; + default: + trigger_error ('dir_opendir(): error in URL', E_USER_ERROR); + return false; + } + return TRUE; + } + + function dir_readdir () { + return ($this->dir_index < count($this->dir)) ? $this->dir[$this->dir_index++] : FALSE; + } + + function dir_rewinddir () { $this->dir_index = 0; } + + function dir_closedir () { $this->dir = array(); $this->dir_index = -1; return TRUE; } + + + # cache + + function adddircache ($url, $content) { + $url = str_replace('//', '/', $url); + $url = rtrim($url, '/'); + global $__smb_cache; + return $__smb_cache['dir'][$url] = $content; + } + + function getdircache ($url) { + $url = str_replace('//', '/', $url); + $url = rtrim($url, '/'); + global $__smb_cache; + return isset ($__smb_cache['dir'][$url]) ? $__smb_cache['dir'][$url] : FALSE; + } + + function cleardircache ($url='') { + $url = str_replace('//', '/', $url); + $url = rtrim($url, '/'); + global $__smb_cache; + if ($url == ''){ + $__smb_cache['dir'] = array (); + }else{ + unset ($__smb_cache['dir'][$url]); + } + } + + + # streams + + function stream_open ($url, $mode, $options, $opened_path) { + $this->url = $url; + $this->mode = $mode; + $this->parsed_url = $pu = smb::parse_url($url); + if ($pu['type'] <> 'path') trigger_error('stream_open(): error in URL', E_USER_ERROR); + switch ($mode) { + case 'r': + case 'r+': + case 'rb': + case 'a': + case 'a+': $this->tmpfile = tempnam('/tmp', 'smb.down.'); + smb::execute ('get "'.$pu['path'].'" "'.$this->tmpfile.'"', $pu); + break; + case 'w': + case 'w+': + case 'wb': + case 'x': + case 'x+': $this->cleardircache(); + $this->tmpfile = tempnam('/tmp', 'smb.up.'); + $this->need_flush=true; + } + $this->stream = fopen ($this->tmpfile, $mode); + return TRUE; + } + + function stream_close () { return fclose($this->stream); } + + function stream_read ($count) { return fread($this->stream, $count); } + + function stream_write ($data) { $this->need_flush = TRUE; return fwrite($this->stream, $data); } + + function stream_eof () { return feof($this->stream); } + + function stream_tell () { return ftell($this->stream); } + + function stream_seek ($offset, $whence=null) { return fseek($this->stream, $offset, $whence); } + + function stream_flush () { + if ($this->mode <> 'r' && $this->need_flush) { + smb::clearstatcache ($this->url); + smb::execute ('put "'.$this->tmpfile.'" "'.$this->parsed_url['path'].'"', $this->parsed_url); + $this->need_flush = FALSE; + } + } + + function stream_stat () { return smb::url_stat ($this->url); } + + function __destruct () { + if ($this->tmpfile <> '') { + if ($this->need_flush) $this->stream_flush (); + unlink ($this->tmpfile); + + } + } + +} + +################################################################### +# Register 'smb' protocol ! +################################################################### + +stream_wrapper_register('smb', 'smb_stream_wrapper') + or die ('Failed to register protocol'); diff --git a/apps/files_external/lib/dropbox.php b/apps/files_external/lib/dropbox.php index 081c547888..60f6767e31 100755 --- a/apps/files_external/lib/dropbox.php +++ b/apps/files_external/lib/dropbox.php @@ -22,7 +22,7 @@ namespace OC\Files\Storage; -require_once 'Dropbox/autoload.php'; +require_once '../3rdparty/Dropbox/autoload.php'; class Dropbox extends \OC\Files\Storage\Common { diff --git a/apps/files_external/lib/smb.php b/apps/files_external/lib/smb.php index 81a6c95638..effc0088c2 100644 --- a/apps/files_external/lib/smb.php +++ b/apps/files_external/lib/smb.php @@ -8,7 +8,7 @@ namespace OC\Files\Storage; -require_once 'smb4php/smb.php'; +require_once '../3rdparty/smb4php/smb.php'; class SMB extends \OC\Files\Storage\StreamWrapper{ private $password;