updated@21:40msk 02nov2009
source:code.txt
#!/usr/bin/php5
<?
/*
CLI interface for gropbox.
requires php5 && php_curl
Copyright Alexander N Lazutov (ñ) 2009; mailto: web@lazutov.ru ;
This script if free of charge and licensed under BSD license.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Based on Dropbox Uploader written by Jaka Jancar [jaka@kubje.org] [http://jaka.kubje.org/]
*/
if (!isset($argv)) die ("run me from cli, nasial`nik :)\n");
function getfname($file){
$p=strrpos($file,'/');
if ($p===false) return $file; else return substr($file,$p+1);
}
function parseargv(){
global $argv;
$conf=array();
foreach ($argv as $k=>$v)
{
$next=@$argv[$k+1];
if (($v=='-u') OR ($v=='--user')) $conf['user']=$next;
elseif (($v=='-p') OR ($v=='--password'))$conf['pass']=$next;
/*elseif (($v=='-s') OR ($v=='--source')) $conf['source']=$next;
elseif (($v=='-d') OR ($v=='--dest')) $conf['dest']=$next; not implemented*/
elseif (($v=='-f') OR ($v=='--file')) $conf['file']=$next;
elseif (($v=='-c') OR ($v=='--config')) $conf['conf']=$next;
}
$conf['act']=$argv[1];
if (!isset($conf['conf'])) $conf['conf']='.phpdropboxconfig';
if ((!isset($conf['user'])) OR (!isset($conf['pass'])))
if (file_exists($conf['conf'])) list ($conf['user'],$conf['pass'])=file($conf['conf'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
else die("No username/password to use; use --user (-u) and --password(-p) flags or --config(-c)\n");
@file_put_contents($conf['conf'],$conf['user']."\n".$conf['pass']);
return $conf;
}
$conf=parseargv();
$link= new Dropbox($conf['user'],$conf['pass']);
$time=time();
switch ($conf['act']){
case 'send':
$link->upload($conf['file'], '/');
$speed= (string) round (filesize($conf['file'])/1024/1024/(time()-$time),3);
$time=time()-$time;
echo "\nSpeed: {$speed} MB/s; {$time} sec.\n";
break;
case 'list':
$files=$link->getfiles('/');
foreach ($files as $file) echo "{$file[0]}\n";
$time=time()-$time;
echo "\n----\n{$time} sec.\n";
break;
case 'get':
$files=$link->getfiles('/');
foreach ($files as $file) if ($file[0]==$conf['file']) $key=$file[1];
$file=getfname($conf['file']);
$r=$link->getfile($file,$key);
if ($r===1) echo "OK!\n";
$speed= (string) round (filesize($conf['file'])/1024/1024/($time-time()),3);
$time=time()-$time;
echo "\nSpeed: {$speed} MB/s; {$time} sec.\n";
break;
default: echo "".
"Usage: [get|send|list] -u user -p pwd -f file
get: get file specified in -f or --file
send: send file specified in -f or --file
list: get filelist
FLAGS:
-u, --user username to use, eg lazutov@qwerty.name
-p, -- password, using both -u & -p updates data in config file.
-f, --file file to work with.
-c, --conf file to get username & pwd from. [default: .phpdropboxconfig]
EXAMPLEs:
job.php list -u lazutov@qwerty.name -p yourpwd - gets filelist & writes username & password to config. so you may use the script without -u & -p. So:
job.php list
job.php send -f cat.zip
job.php get -f cat.zip - files are saved as _filename in script directory.
TODO: dest & source flags; recursive processing; removing fils from remote space.
";
break;
}
class Dropbox {
protected $email;
protected $password;
protected $caCertSourceType = self::CACERT_SOURCE_SYSTEM;
const CACERT_SOURCE_SYSTEM = 0;
const CACERT_SOURCE_FILE = 1;
const CACERT_SOURCE_DIR = 2;
protected $caCertSource;
protected $loggedIn = false;
protected $cookies = array();
public function __construct($email, $password) {
if (!extension_loaded('curl'))
throw new Exception('Need curl extension. Check php.ini');
$this->email = $email;
$this->password = $password;
}
public function setCaCertificateFile($file)
{
$this->caCertSourceType = self::CACERT_SOURCE_FILE;
$this->caCertSource = $file;
}
public function setCaCertificateDir($dir)
{
$this->caCertSourceType = self::CACERT_SOURCE_DIR;
$this->caCertSource = $dir;
}
public function upload($filename, $remoteDir='/') {
if (!file_exists($filename) or !is_file($filename) or !is_readable($filename))
throw new Exception("Can not open '$filename'. Maybe dir? (IOerr)");
if (preg_match("/.+\.\..+/",$remoteDir))
throw new Exception("Remote dir has a strange format. (CHerr)");
if (!$this->loggedIn) $this->login();
$data = $this->request('https://www.getdropbox.com/home');
$token = $this->extractToken($data, 'https://dl-web.getdropbox.com/upload');
$data = $this->request('https://dl-web.getdropbox.com/upload', true, array('plain'=>'yes', 'file'=>'@'.$filename, 'dest'=>$remoteDir, 't'=>$token));
if (strpos($data, 'HTTP/1.1 302 FOUND') === false)
throw new Exception('Upload failed! ');
}
//return all sub-directories in the $remoteDir
public function getdirs($remoteDir='/') {
$directory_names=array();
if (preg_match("/\.\./",$remoteDir))
throw new Exception("Remote dir has a strange format. (CHerr)");
if (preg_match("/.+\.\..+/",$remoteDir))
throw new Exception("Remote dir has a strange format. (CHerr)");
if (!$this->loggedIn) $this->login();
$data = $this->request('https://www.getdropbox.com/browse_plain/'.$remoteDir.'?no_js=true');
preg_match_all ( '/<div.*details-filename.*>(.*?)<\/div>/', $data, $file_array );
foreach ( $file_array[0] as $file_name )
{
$file_name = explode('</a>', $file_name);
$file_name = spliti('<a href="\/.*true">', $file_name[0]);
if ($file_name[1]!='')
array_push($directory_names, $file_name[1]);
}
return $directory_names;
}
public function getfiles($remoteDir='/') {
if (preg_match("/.+\.\..+/",$remoteDir))
throw new Exception("Remote dir has a strange format. (CHerr)");
$file_names=array();
if (!$this->loggedIn) $this->login();
$data = $this->request('https://www.getdropbox.com/browse_plain/'.$remoteDir.'?no_js=true');
preg_match_all ( '/<div.*details-filename.*>(.*?)<\/div>/', $data, $file_array );
foreach ( $file_array[0] as $file_name )
{
$href = explode('</a>', $file_name);
$file_name = spliti('<a href=".*dl.*">', $href[0]);
if ($file_name[1]!='')
{
$href = spliti('<a href=".*w=', $href[0]);
$href = explode('">', $href[1]);
array_push($file_names, array($file_name[1],$href[0]));
}
}
return $file_names;
}
public function getfile($remoteFile='/',$w) {
$file_names=array();
if (preg_match("/.+\.\..+/",$remoteFile))
throw new Exception("Remote dir has a strange format. (CHerr)");
if (!preg_match('(^[a-z0-9]+$)',$w))
throw new Exception("Filename is corrupted. (CHerr)");
if (!$this->loggedIn) $this->login();
$data = $this->request('https://dl-web.getdropbox.com/get/'.$remoteFile.'?w='.$w,false,array(),$remoteFile);
//preg_match ( '/Content-Type: .+\/.+/', $data, $content_type );
return 1;
//$data=substr(stristr($data, "\r\n\r\n"),4);
//return array("data"=>$data,"content_type"=>$content_type[0]);
}
protected function login() {
$data = $this->request('https://www.getdropbox.com/login');
$token = $this->extractToken($data, '/login');
$data = $this->request('https://www.getdropbox.com/login', true, array('login_email'=>$this->email, 'login_password'=>$this->password, 't'=>$token));
if (stripos($data, 'location: /home') === false)
throw new Exception('Login unsuccessful.(LIerr)');
$this->loggedIn = true;
}
protected function request($url, $post=false, $postData=array(),$tofile=false) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($tofile!==false) { $fs=fopen ('_'.$tofile,'w'); curl_setopt($ch, CURLOPT_FILE, $fs); }
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
switch ($this->caCertSourceType) {
case self::CACERT_SOURCE_FILE:
curl_setopt($ch, CURLOPT_CAINFO, $this->caCertSource);
break;
case self::CACERT_SOURCE_DIR:
curl_setopt($ch, CURLOPT_CAPATH, $this->caCertSource);
break;
}
if ($tofile==false) curl_setopt($ch, CURLOPT_HEADER, 1);
if ($tofile===false) curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($post) {
curl_setopt($ch, CURLOPT_POST, $post);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
$rawCookies = array();
foreach ($this->cookies as $k=>$v)
$rawCookies[] = "$k=$v";
$rawCookies = implode(';', $rawCookies);
curl_setopt($ch, CURLOPT_COOKIE, $rawCookies);
$data = curl_exec($ch);
if ($tofile!==false) {fclose($fs); return 1;}
if ($data === false)
throw new Exception('Cannot execute curl: '.curl_error($ch));
preg_match_all('/Set-Cookie: ([^=]+)=(.*?);/i', $data, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
$this->cookies[$match[1]] = $match[2];
curl_close($ch);
return $data;
}
protected function extractToken($html, $formAction) {
if (!preg_match('/<form [^>]*'.preg_quote($formAction, '/').'[^>]*>.*?(<input [^>]*name="t" [^>]*value="(.*?)"[^>]*>).*?<\/form>/is', $html, $matches) || !isset($matches[2]))
throw new Exception("Cannot get token! (PARSEerr)");
return $matches[2];
}
}
?>
1