adding space between) and {

This commit is contained in:
Thomas Mueller 2012-09-07 15:22:01 +02:00
parent 785aa751bb
commit 3829460ab8
168 changed files with 1834 additions and 1834 deletions

View File

@ -33,7 +33,7 @@ $upload_max_filesize = OCP\Util::computerFileSize(ini_get('upload_max_filesize')
$post_max_size = OCP\Util::computerFileSize(ini_get('post_max_size')); $post_max_size = OCP\Util::computerFileSize(ini_get('post_max_size'));
$maxUploadFilesize = OCP\Util::humanFileSize(min($upload_max_filesize, $post_max_size)); $maxUploadFilesize = OCP\Util::humanFileSize(min($upload_max_filesize, $post_max_size));
if($_POST) { if($_POST) {
if(isset($_POST['maxUploadSize'])){ if(isset($_POST['maxUploadSize'])) {
if(($setMaxSize = OC_Files::setUploadLimit(OCP\Util::computerFileSize($_POST['maxUploadSize']))) !== false) { if(($setMaxSize = OC_Files::setUploadLimit(OCP\Util::computerFileSize($_POST['maxUploadSize']))) !== false) {
$maxUploadFilesize = OCP\Util::humanFileSize($setMaxSize); $maxUploadFilesize = OCP\Util::humanFileSize($setMaxSize);
} }

View File

@ -17,7 +17,7 @@ $data = array();
if($doBreadcrumb) { if($doBreadcrumb) {
$breadcrumb = array(); $breadcrumb = array();
$pathtohere = "/"; $pathtohere = "/";
foreach( explode( "/", $dir ) as $i ){ foreach( explode( "/", $dir ) as $i ) {
if( $i != "" ) { if( $i != "" ) {
$pathtohere .= "$i/"; $pathtohere .= "$i/";
$breadcrumb[] = array( "dir" => $pathtohere, "name" => $i ); $breadcrumb[] = array( "dir" => $pathtohere, "name" => $i );
@ -32,7 +32,7 @@ if($doBreadcrumb) {
// make filelist // make filelist
$files = array(); $files = array();
foreach( OC_Files::getdirectorycontent( $dir ) as $i ){ foreach( OC_Files::getdirectorycontent( $dir ) as $i ) {
$i["date"] = OCP\Util::formatDate($i["mtime"] ); $i["date"] = OCP\Util::formatDate($i["mtime"] );
$files[] = $i; $files[] = $i;
} }

View File

@ -35,7 +35,7 @@ $dir = $_POST['dir'];
$error=''; $error='';
$totalSize=0; $totalSize=0;
foreach($files['size'] as $size){ foreach($files['size'] as $size) {
$totalSize+=$size; $totalSize+=$size;
} }
if($totalSize>OC_Filesystem::free_space('/')) { if($totalSize>OC_Filesystem::free_space('/')) {
@ -46,7 +46,7 @@ if($totalSize>OC_Filesystem::free_space('/')) {
$result=array(); $result=array();
if(strpos($dir, '..') === false) { if(strpos($dir, '..') === false) {
$fileCount=count($files['name']); $fileCount=count($files['name']);
for($i=0;$i<$fileCount;$i++){ for($i=0;$i<$fileCount;$i++) {
$target = OCP\Files::buildNotExistingFileName(stripslashes($dir), $files['name'][$i]); $target = OCP\Files::buildNotExistingFileName(stripslashes($dir), $files['name'][$i]);
if(is_uploaded_file($files['tmp_name'][$i]) and OC_Filesystem::fromTmpFile($files['tmp_name'][$i], $target)) { if(is_uploaded_file($files['tmp_name'][$i]) and OC_Filesystem::fromTmpFile($files['tmp_name'][$i], $target)) {
$meta=OC_FileCache_Cached::get($target); $meta=OC_FileCache_Cached::get($target);

View File

@ -23,14 +23,14 @@
// only need filesystem apps // only need filesystem apps
$RUNTIME_APPTYPES=array('filesystem','authentication'); $RUNTIME_APPTYPES=array('filesystem','authentication');
OC_App::loadApps($RUNTIME_APPTYPES); OC_App::loadApps($RUNTIME_APPTYPES);
if(!OC_User::isLoggedIn()){ if(!OC_User::isLoggedIn()) {
if(!isset($_SERVER['PHP_AUTH_USER'])){ if(!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="ownCloud Server"'); header('WWW-Authenticate: Basic realm="ownCloud Server"');
header('HTTP/1.0 401 Unauthorized'); header('HTTP/1.0 401 Unauthorized');
echo 'Valid credentials must be supplied'; echo 'Valid credentials must be supplied';
exit(); exit();
} else { } else {
if(!OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])){ if(!OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
exit(); exit();
} }
} }

View File

@ -5,7 +5,7 @@ $installedVersion=OCP\Config::getAppValue('files', 'installed_version');
if (version_compare($installedVersion, '1.1.4', '<')) { if (version_compare($installedVersion, '1.1.4', '<')) {
$query = OC_DB::prepare( "SELECT `propertyname`, `propertypath`, `userid` FROM `*PREFIX*properties`" ); $query = OC_DB::prepare( "SELECT `propertyname`, `propertypath`, `userid` FROM `*PREFIX*properties`" );
$result = $query->execute(); $result = $query->execute();
while( $row = $result->fetchRow()){ while( $row = $result->fetchRow()) {
$query = OC_DB::prepare( 'UPDATE `*PREFIX*properties` SET `propertyname` = ? WHERE `userid` = ? AND `propertypath` = ?' ); $query = OC_DB::prepare( 'UPDATE `*PREFIX*properties` SET `propertyname` = ? WHERE `userid` = ? AND `propertypath` = ?' );
$query->execute( array( preg_replace("/^{.*}/", "", $row["propertyname"]),$row["userid"], $row["propertypath"] )); $query->execute( array( preg_replace("/^{.*}/", "", $row["propertyname"]),$row["userid"], $row["propertypath"] ));
} }

View File

@ -29,7 +29,7 @@ OCP\User::checkLoggedIn();
$filename = $_GET["file"]; $filename = $_GET["file"];
if(!OC_Filesystem::file_exists($filename)){ if(!OC_Filesystem::file_exists($filename)) {
header("HTTP/1.0 404 Not Found"); header("HTTP/1.0 404 Not Found");
$tmpl = new OCP\Template( '', '404', 'guest' ); $tmpl = new OCP\Template( '', '404', 'guest' );
$tmpl->assign('file',$filename); $tmpl->assign('file',$filename);

View File

@ -31,7 +31,7 @@ OCP\Util::addscript( 'files', 'jquery.fileupload' );
OCP\Util::addscript( 'files', 'files' ); OCP\Util::addscript( 'files', 'files' );
OCP\Util::addscript( 'files', 'filelist' ); OCP\Util::addscript( 'files', 'filelist' );
OCP\Util::addscript( 'files', 'fileactions' ); OCP\Util::addscript( 'files', 'fileactions' );
if(!isset($_SESSION['timezone'])){ if(!isset($_SESSION['timezone'])) {
OCP\Util::addscript( 'files', 'timezone' ); OCP\Util::addscript( 'files', 'timezone' );
} }
OCP\App::setActiveNavigationEntry( 'files_index' ); OCP\App::setActiveNavigationEntry( 'files_index' );
@ -44,9 +44,9 @@ if(!OC_Filesystem::is_dir($dir.'/')) {
} }
$files = array(); $files = array();
foreach( OC_Files::getdirectorycontent( $dir ) as $i ){ foreach( OC_Files::getdirectorycontent( $dir ) as $i ) {
$i['date'] = OCP\Util::formatDate($i['mtime'] ); $i['date'] = OCP\Util::formatDate($i['mtime'] );
if($i['type']=='file'){ if($i['type']=='file') {
$fileinfo=pathinfo($i['name']); $fileinfo=pathinfo($i['name']);
$i['basename']=$fileinfo['filename']; $i['basename']=$fileinfo['filename'];
if (!empty($fileinfo['extension'])) { if (!empty($fileinfo['extension'])) {
@ -56,7 +56,7 @@ foreach( OC_Files::getdirectorycontent( $dir ) as $i ){
$i['extension']=''; $i['extension']='';
} }
} }
if($i['directory']=='/'){ if($i['directory']=='/') {
$i['directory']=''; $i['directory']='';
} }
$files[] = $i; $files[] = $i;
@ -65,8 +65,8 @@ foreach( OC_Files::getdirectorycontent( $dir ) as $i ){
// Make breadcrumb // Make breadcrumb
$breadcrumb = array(); $breadcrumb = array();
$pathtohere = ''; $pathtohere = '';
foreach( explode( '/', $dir ) as $i ){ foreach( explode( '/', $dir ) as $i ) {
if( $i != '' ){ if( $i != '' ) {
$pathtohere .= '/'.str_replace('+','%20', urlencode($i)); $pathtohere .= '/'.str_replace('+','%20', urlencode($i));
$breadcrumb[] = array( 'dir' => $pathtohere, 'name' => $i ); $breadcrumb[] = array( 'dir' => $pathtohere, 'name' => $i );
} }

View File

@ -36,7 +36,7 @@ OCP\Util::addscript( "files", "files" );
$dir = isset( $_GET['dir'] ) ? $_GET['dir'] : ''; $dir = isset( $_GET['dir'] ) ? $_GET['dir'] : '';
$files = array(); $files = array();
foreach( OC_Files::getdirectorycontent( $dir ) as $i ){ foreach( OC_Files::getdirectorycontent( $dir ) as $i ) {
$i["date"] = date( $CONFIG_DATEFORMAT, $i["mtime"] ); $i["date"] = date( $CONFIG_DATEFORMAT, $i["mtime"] );
$files[] = $i; $files[] = $i;
} }
@ -44,8 +44,8 @@ foreach( OC_Files::getdirectorycontent( $dir ) as $i ){
// Make breadcrumb // Make breadcrumb
$breadcrumb = array(); $breadcrumb = array();
$pathtohere = "/"; $pathtohere = "/";
foreach( explode( "/", $dir ) as $i ){ foreach( explode( "/", $dir ) as $i ) {
if( $i != "" ){ if( $i != "" ) {
$pathtohere .= "$i/"; $pathtohere .= "$i/";
$breadcrumb[] = array( "dir" => $pathtohere, "name" => $i ); $breadcrumb[] = array( "dir" => $pathtohere, "name" => $i );
} }

View File

@ -10,7 +10,7 @@ OCP\Util::connectHook('OC_User','post_login','OC_Crypt','loginListener');
stream_wrapper_register('crypt','OC_CryptStream'); stream_wrapper_register('crypt','OC_CryptStream');
if(!isset($_SESSION['enckey']) and OCP\User::isLoggedIn()){//force the user to re-loggin if the encryption key isn't unlocked (happens when a user is logged in before the encryption app is enabled) if(!isset($_SESSION['enckey']) and OCP\User::isLoggedIn()) {//force the user to re-loggin if the encryption key isn't unlocked (happens when a user is logged in before the encryption app is enabled)
OCP\User::logout(); OCP\User::logout();
header("Location: ".OC::$WEBROOT.'/'); header("Location: ".OC::$WEBROOT.'/');
exit(); exit();

View File

@ -39,18 +39,18 @@ require_once 'Crypt_Blowfish/Blowfish.php';
class OC_Crypt { class OC_Crypt {
static private $bf = null; static private $bf = null;
public static function loginListener($params){ public static function loginListener($params) {
self::init($params['uid'],$params['password']); self::init($params['uid'],$params['password']);
} }
public static function init($login,$password) { public static function init($login,$password) {
$view=new OC_FilesystemView('/'); $view=new OC_FilesystemView('/');
if(!$view->file_exists('/'.$login)){ if(!$view->file_exists('/'.$login)) {
$view->mkdir('/'.$login); $view->mkdir('/'.$login);
} }
OC_FileProxy::$enabled=false; OC_FileProxy::$enabled=false;
if(!$view->file_exists('/'.$login.'/encryption.key')){// does key exist? if(!$view->file_exists('/'.$login.'/encryption.key')) {// does key exist?
OC_Crypt::createkey($login,$password); OC_Crypt::createkey($login,$password);
} }
$key=$view->file_get_contents('/'.$login.'/encryption.key'); $key=$view->file_get_contents('/'.$login.'/encryption.key');
@ -66,14 +66,14 @@ class OC_Crypt {
* *
* if the key is left out, the default handeler will be used * if the key is left out, the default handeler will be used
*/ */
public static function getBlowfish($key=''){ public static function getBlowfish($key='') {
if($key){ if($key) {
return new Crypt_Blowfish($key); return new Crypt_Blowfish($key);
}else{ }else{
if(!isset($_SESSION['enckey'])){ if(!isset($_SESSION['enckey'])) {
return false; return false;
} }
if(!self::$bf){ if(!self::$bf) {
self::$bf=new Crypt_Blowfish($_SESSION['enckey']); self::$bf=new Crypt_Blowfish($_SESSION['enckey']);
} }
return self::$bf; return self::$bf;
@ -96,7 +96,7 @@ class OC_Crypt {
} }
public static function changekeypasscode($oldPassword, $newPassword) { public static function changekeypasscode($oldPassword, $newPassword) {
if(OCP\User::isLoggedIn()){ if(OCP\User::isLoggedIn()) {
$username=OCP\USER::getUser(); $username=OCP\USER::getUser();
$view=new OC_FilesystemView('/'.$username); $view=new OC_FilesystemView('/'.$username);
@ -179,7 +179,7 @@ class OC_Crypt {
while (!feof($handleread)) { while (!feof($handleread)) {
$content = fread($handleread, 8192); $content = fread($handleread, 8192);
$enccontent=OC_CRYPT::decrypt( $content, $key); $enccontent=OC_CRYPT::decrypt( $content, $key);
if(feof($handleread)){ if(feof($handleread)) {
$enccontent=rtrim($enccontent, "\0"); $enccontent=rtrim($enccontent, "\0");
} }
fwrite($handlewrite, $enccontent); fwrite($handlewrite, $enccontent);
@ -192,9 +192,9 @@ class OC_Crypt {
/** /**
* encrypt data in 8192b sized blocks * encrypt data in 8192b sized blocks
*/ */
public static function blockEncrypt($data, $key=''){ public static function blockEncrypt($data, $key='') {
$result=''; $result='';
while(strlen($data)){ while(strlen($data)) {
$result.=self::encrypt(substr($data,0,8192),$key); $result.=self::encrypt(substr($data,0,8192),$key);
$data=substr($data,8192); $data=substr($data,8192);
} }
@ -204,13 +204,13 @@ class OC_Crypt {
/** /**
* decrypt data in 8192b sized blocks * decrypt data in 8192b sized blocks
*/ */
public static function blockDecrypt($data, $key='',$maxLength=0){ public static function blockDecrypt($data, $key='',$maxLength=0) {
$result=''; $result='';
while(strlen($data)){ while(strlen($data)) {
$result.=self::decrypt(substr($data,0,8192),$key); $result.=self::decrypt(substr($data,0,8192),$key);
$data=substr($data,8192); $data=substr($data,8192);
} }
if($maxLength>0){ if($maxLength>0) {
return substr($result,0,$maxLength); return substr($result,0,$maxLength);
}else{ }else{
return rtrim($result, "\0"); return rtrim($result, "\0");

View File

@ -36,18 +36,18 @@ class OC_CryptStream{
private $size; private $size;
private static $rootView; private static $rootView;
public function stream_open($path, $mode, $options, &$opened_path){ public function stream_open($path, $mode, $options, &$opened_path) {
if(!self::$rootView){ if(!self::$rootView) {
self::$rootView=new OC_FilesystemView(''); self::$rootView=new OC_FilesystemView('');
} }
$path=str_replace('crypt://','',$path); $path=str_replace('crypt://','',$path);
if(dirname($path)=='streams' and isset(self::$sourceStreams[basename($path)])){ if(dirname($path)=='streams' and isset(self::$sourceStreams[basename($path)])) {
$this->source=self::$sourceStreams[basename($path)]['stream']; $this->source=self::$sourceStreams[basename($path)]['stream'];
$this->path=self::$sourceStreams[basename($path)]['path']; $this->path=self::$sourceStreams[basename($path)]['path'];
$this->size=self::$sourceStreams[basename($path)]['size']; $this->size=self::$sourceStreams[basename($path)]['size'];
}else{ }else{
$this->path=$path; $this->path=$path;
if($mode=='w' or $mode=='w+' or $mode=='wb' or $mode=='wb+'){ if($mode=='w' or $mode=='w+' or $mode=='wb' or $mode=='wb+') {
$this->size=0; $this->size=0;
}else{ }else{
$this->size=self::$rootView->filesize($path,$mode); $this->size=self::$rootView->filesize($path,$mode);
@ -55,55 +55,55 @@ class OC_CryptStream{
OC_FileProxy::$enabled=false;//disable fileproxies so we can open the source file OC_FileProxy::$enabled=false;//disable fileproxies so we can open the source file
$this->source=self::$rootView->fopen($path,$mode); $this->source=self::$rootView->fopen($path,$mode);
OC_FileProxy::$enabled=true; OC_FileProxy::$enabled=true;
if(!is_resource($this->source)){ if(!is_resource($this->source)) {
OCP\Util::writeLog('files_encryption','failed to open '.$path,OCP\Util::ERROR); OCP\Util::writeLog('files_encryption','failed to open '.$path,OCP\Util::ERROR);
} }
} }
if(is_resource($this->source)){ if(is_resource($this->source)) {
$this->meta=stream_get_meta_data($this->source); $this->meta=stream_get_meta_data($this->source);
} }
return is_resource($this->source); return is_resource($this->source);
} }
public function stream_seek($offset, $whence=SEEK_SET){ public function stream_seek($offset, $whence=SEEK_SET) {
$this->flush(); $this->flush();
fseek($this->source,$offset,$whence); fseek($this->source,$offset,$whence);
} }
public function stream_tell(){ public function stream_tell() {
return ftell($this->source); return ftell($this->source);
} }
public function stream_read($count){ public function stream_read($count) {
//$count will always be 8192 https://bugs.php.net/bug.php?id=21641 //$count will always be 8192 https://bugs.php.net/bug.php?id=21641
//This makes this function a lot simpler but will breake everything the moment it's fixed //This makes this function a lot simpler but will breake everything the moment it's fixed
$this->writeCache=''; $this->writeCache='';
if($count!=8192){ if($count!=8192) {
OCP\Util::writeLog('files_encryption','php bug 21641 no longer holds, decryption will not work',OCP\Util::FATAL); OCP\Util::writeLog('files_encryption','php bug 21641 no longer holds, decryption will not work',OCP\Util::FATAL);
die(); die();
} }
$pos=ftell($this->source); $pos=ftell($this->source);
$data=fread($this->source,8192); $data=fread($this->source,8192);
if(strlen($data)){ if(strlen($data)) {
$result=OC_Crypt::decrypt($data); $result=OC_Crypt::decrypt($data);
}else{ }else{
$result=''; $result='';
} }
$length=$this->size-$pos; $length=$this->size-$pos;
if($length<8192){ if($length<8192) {
$result=substr($result,0,$length); $result=substr($result,0,$length);
} }
return $result; return $result;
} }
public function stream_write($data){ public function stream_write($data) {
$length=strlen($data); $length=strlen($data);
$currentPos=ftell($this->source); $currentPos=ftell($this->source);
if($this->writeCache){ if($this->writeCache) {
$data=$this->writeCache.$data; $data=$this->writeCache.$data;
$this->writeCache=''; $this->writeCache='';
} }
if($currentPos%8192!=0){ if($currentPos%8192!=0) {
//make sure we always start on a block start //make sure we always start on a block start
fseek($this->source,-($currentPos%8192),SEEK_CUR); fseek($this->source,-($currentPos%8192),SEEK_CUR);
$encryptedBlock=fread($this->source,8192); $encryptedBlock=fread($this->source,8192);
@ -113,8 +113,8 @@ class OC_CryptStream{
fseek($this->source,-($currentPos%8192),SEEK_CUR); fseek($this->source,-($currentPos%8192),SEEK_CUR);
} }
$currentPos=ftell($this->source); $currentPos=ftell($this->source);
while($remainingLength=strlen($data)>0){ while($remainingLength=strlen($data)>0) {
if($remainingLength<8192){ if($remainingLength<8192) {
$this->writeCache=$data; $this->writeCache=$data;
$data=''; $data='';
}else{ }else{
@ -127,8 +127,8 @@ class OC_CryptStream{
return $length; return $length;
} }
public function stream_set_option($option,$arg1,$arg2){ public function stream_set_option($option,$arg1,$arg2) {
switch($option){ switch($option) {
case STREAM_OPTION_BLOCKING: case STREAM_OPTION_BLOCKING:
stream_set_blocking($this->source,$arg1); stream_set_blocking($this->source,$arg1);
break; break;
@ -140,33 +140,33 @@ class OC_CryptStream{
} }
} }
public function stream_stat(){ public function stream_stat() {
return fstat($this->source); return fstat($this->source);
} }
public function stream_lock($mode){ public function stream_lock($mode) {
flock($this->source,$mode); flock($this->source,$mode);
} }
public function stream_flush(){ public function stream_flush() {
return fflush($this->source); return fflush($this->source);
} }
public function stream_eof(){ public function stream_eof() {
return feof($this->source); return feof($this->source);
} }
private function flush(){ private function flush() {
if($this->writeCache){ if($this->writeCache) {
$encrypted=OC_Crypt::encrypt($this->writeCache); $encrypted=OC_Crypt::encrypt($this->writeCache);
fwrite($this->source,$encrypted); fwrite($this->source,$encrypted);
$this->writeCache=''; $this->writeCache='';
} }
} }
public function stream_close(){ public function stream_close() {
$this->flush(); $this->flush();
if($this->meta['mode']!='r' and $this->meta['mode']!='rb'){ if($this->meta['mode']!='r' and $this->meta['mode']!='rb') {
OC_FileCache::put($this->path,array('encrypted'=>true,'size'=>$this->size),''); OC_FileCache::put($this->path,array('encrypted'=>true,'size'=>$this->size),'');
} }
return fclose($this->source); return fclose($this->source);

View File

@ -34,21 +34,21 @@ class OC_FileProxy_Encryption extends OC_FileProxy{
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
private static function shouldEncrypt($path){ private static function shouldEncrypt($path) {
if(is_null(self::$enableEncryption)){ if(is_null(self::$enableEncryption)) {
self::$enableEncryption=(OCP\Config::getAppValue('files_encryption','enable_encryption','true')=='true'); self::$enableEncryption=(OCP\Config::getAppValue('files_encryption','enable_encryption','true')=='true');
} }
if(!self::$enableEncryption){ if(!self::$enableEncryption) {
return false; return false;
} }
if(is_null(self::$blackList)){ if(is_null(self::$blackList)) {
self::$blackList=explode(',',OCP\Config::getAppValue('files_encryption','type_blacklist','jpg,png,jpeg,avi,mpg,mpeg,mkv,mp3,oga,ogv,ogg')); self::$blackList=explode(',',OCP\Config::getAppValue('files_encryption','type_blacklist','jpg,png,jpeg,avi,mpg,mpeg,mkv,mp3,oga,ogv,ogg'));
} }
if(self::isEncrypted($path)){ if(self::isEncrypted($path)) {
return true; return true;
} }
$extension=substr($path,strrpos($path,'.')+1); $extension=substr($path,strrpos($path,'.')+1);
if(array_search($extension,self::$blackList)===false){ if(array_search($extension,self::$blackList)===false) {
return true; return true;
} }
} }
@ -58,13 +58,13 @@ class OC_FileProxy_Encryption extends OC_FileProxy{
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
private static function isEncrypted($path){ private static function isEncrypted($path) {
$metadata=OC_FileCache_Cached::get($path,''); $metadata=OC_FileCache_Cached::get($path,'');
return isset($metadata['encrypted']) and (bool)$metadata['encrypted']; return isset($metadata['encrypted']) and (bool)$metadata['encrypted'];
} }
public function preFile_put_contents($path,&$data){ public function preFile_put_contents($path,&$data) {
if(self::shouldEncrypt($path)){ if(self::shouldEncrypt($path)) {
if (!is_resource($data)) {//stream put contents should have been converter to fopen if (!is_resource($data)) {//stream put contents should have been converter to fopen
$size=strlen($data); $size=strlen($data);
$data=OC_Crypt::blockEncrypt($data); $data=OC_Crypt::blockEncrypt($data);
@ -73,24 +73,24 @@ class OC_FileProxy_Encryption extends OC_FileProxy{
} }
} }
public function postFile_get_contents($path,$data){ public function postFile_get_contents($path,$data) {
if(self::isEncrypted($path)){ if(self::isEncrypted($path)) {
$cached=OC_FileCache_Cached::get($path,''); $cached=OC_FileCache_Cached::get($path,'');
$data=OC_Crypt::blockDecrypt($data,'',$cached['size']); $data=OC_Crypt::blockDecrypt($data,'',$cached['size']);
} }
return $data; return $data;
} }
public function postFopen($path,&$result){ public function postFopen($path,&$result) {
if(!$result){ if(!$result) {
return $result; return $result;
} }
$meta=stream_get_meta_data($result); $meta=stream_get_meta_data($result);
if(self::isEncrypted($path)){ if(self::isEncrypted($path)) {
fclose($result); fclose($result);
$result=fopen('crypt://'.$path,$meta['mode']); $result=fopen('crypt://'.$path,$meta['mode']);
}elseif(self::shouldEncrypt($path) and $meta['mode']!='r' and $meta['mode']!='rb'){ }elseif(self::shouldEncrypt($path) and $meta['mode']!='r' and $meta['mode']!='rb') {
if(OC_Filesystem::file_exists($path) and OC_Filesystem::filesize($path)>0){ if(OC_Filesystem::file_exists($path) and OC_Filesystem::filesize($path)>0) {
//first encrypt the target file so we don't end up with a half encrypted file //first encrypt the target file so we don't end up with a half encrypted file
OCP\Util::writeLog('files_encryption','Decrypting '.$path.' before writing',OCP\Util::DEBUG); OCP\Util::writeLog('files_encryption','Decrypting '.$path.' before writing',OCP\Util::DEBUG);
$tmp=fopen('php://temp'); $tmp=fopen('php://temp');
@ -104,23 +104,23 @@ class OC_FileProxy_Encryption extends OC_FileProxy{
return $result; return $result;
} }
public function postGetMimeType($path,$mime){ public function postGetMimeType($path,$mime) {
if(self::isEncrypted($path)){ if(self::isEncrypted($path)) {
$mime=OCP\Files::getMimeType('crypt://'.$path,'w'); $mime=OCP\Files::getMimeType('crypt://'.$path,'w');
} }
return $mime; return $mime;
} }
public function postStat($path,$data){ public function postStat($path,$data) {
if(self::isEncrypted($path)){ if(self::isEncrypted($path)) {
$cached=OC_FileCache_Cached::get($path,''); $cached=OC_FileCache_Cached::get($path,'');
$data['size']=$cached['size']; $data['size']=$cached['size'];
} }
return $data; return $data;
} }
public function postFileSize($path,$size){ public function postFileSize($path,$size) {
if(self::isEncrypted($path)){ if(self::isEncrypted($path)) {
$cached=OC_FileCache_Cached::get($path,''); $cached=OC_FileCache_Cached::get($path,'');
return $cached['size']; return $cached['size'];
}else{ }else{

View File

@ -7,6 +7,6 @@
<option selected="selected" value="<?php echo $type;?>"><?php echo $type;?></option> <option selected="selected" value="<?php echo $type;?>"><?php echo $type;?></option>
<?php endforeach;?> <?php endforeach;?>
</select> </select>
<input type='checkbox' id='enable_encryption' <?php if($_['encryption_enabled']){echo 'checked="checked"';} ?>></input><label for='enable_encryption'><?php echo $l->t('Enable Encryption')?></label> <input type='checkbox' id='enable_encryption' <?php if($_['encryption_enabled']) {echo 'checked="checked"';} ?>></input><label for='enable_encryption'><?php echo $l->t('Enable Encryption')?></label>
</fieldset> </fieldset>
</form> </form>

View File

@ -7,7 +7,7 @@
*/ */
class Test_Encryption extends UnitTestCase { class Test_Encryption extends UnitTestCase {
function testEncryption(){ function testEncryption() {
$key=uniqid(); $key=uniqid();
$file=OC::$SERVERROOT.'/3rdparty/MDB2.php'; $file=OC::$SERVERROOT.'/3rdparty/MDB2.php';
$source=file_get_contents($file); //nice large text file $source=file_get_contents($file); //nice large text file
@ -54,7 +54,7 @@ class Test_Encryption extends UnitTestCase {
} }
function testBinary(){ function testBinary() {
$key=uniqid(); $key=uniqid();
$file=__DIR__.'/binary'; $file=__DIR__.'/binary';

View File

@ -10,7 +10,7 @@ class Test_CryptProxy extends UnitTestCase {
private $oldConfig; private $oldConfig;
private $oldKey; private $oldKey;
public function setUp(){ public function setUp() {
$user=OC_User::getUser(); $user=OC_User::getUser();
$this->oldConfig=OCP\Config::getAppValue('files_encryption','enable_encryption','true'); $this->oldConfig=OCP\Config::getAppValue('files_encryption','enable_encryption','true');
@ -40,14 +40,14 @@ class Test_CryptProxy extends UnitTestCase {
$rootView->mkdir('/'.$user.'/files'); $rootView->mkdir('/'.$user.'/files');
} }
public function tearDown(){ public function tearDown() {
OCP\Config::setAppValue('files_encryption','enable_encryption',$this->oldConfig); OCP\Config::setAppValue('files_encryption','enable_encryption',$this->oldConfig);
if(!is_null($this->oldKey)){ if(!is_null($this->oldKey)) {
$_SESSION['enckey']=$this->oldKey; $_SESSION['enckey']=$this->oldKey;
} }
} }
public function testSimple(){ public function testSimple() {
$file=OC::$SERVERROOT.'/3rdparty/MDB2.php'; $file=OC::$SERVERROOT.'/3rdparty/MDB2.php';
$original=file_get_contents($file); $original=file_get_contents($file);
@ -64,7 +64,7 @@ class Test_CryptProxy extends UnitTestCase {
} }
public function testView(){ public function testView() {
$file=OC::$SERVERROOT.'/3rdparty/MDB2.php'; $file=OC::$SERVERROOT.'/3rdparty/MDB2.php';
$original=file_get_contents($file); $original=file_get_contents($file);
@ -86,7 +86,7 @@ class Test_CryptProxy extends UnitTestCase {
$this->assertEqual($original,$fromFile); $this->assertEqual($original,$fromFile);
} }
public function testBinary(){ public function testBinary() {
$file=__DIR__.'/binary'; $file=__DIR__.'/binary';
$original=file_get_contents($file); $original=file_get_contents($file);

View File

@ -9,7 +9,7 @@
class Test_CryptStream extends UnitTestCase { class Test_CryptStream extends UnitTestCase {
private $tmpFiles=array(); private $tmpFiles=array();
function testStream(){ function testStream() {
$stream=$this->getStream('test1','w',strlen('foobar')); $stream=$this->getStream('test1','w',strlen('foobar'));
fwrite($stream,'foobar'); fwrite($stream,'foobar');
fclose($stream); fclose($stream);
@ -40,11 +40,11 @@ class Test_CryptStream extends UnitTestCase {
* @param int size * @param int size
* @return resource * @return resource
*/ */
function getStream($id,$mode,$size){ function getStream($id,$mode,$size) {
if($id===''){ if($id==='') {
$id=uniqid(); $id=uniqid();
} }
if(!isset($this->tmpFiles[$id])){ if(!isset($this->tmpFiles[$id])) {
$file=OCP\Files::tmpFile(); $file=OCP\Files::tmpFile();
$this->tmpFiles[$id]=$file; $this->tmpFiles[$id]=$file;
}else{ }else{
@ -55,7 +55,7 @@ class Test_CryptStream extends UnitTestCase {
return fopen('crypt://streams/'.$id,$mode); return fopen('crypt://streams/'.$id,$mode);
} }
function testBinary(){ function testBinary() {
$file=__DIR__.'/binary'; $file=__DIR__.'/binary';
$source=file_get_contents($file); $source=file_get_contents($file);

View File

@ -15,13 +15,13 @@ class OC_FileStorage_FTP extends OC_FileStorage_StreamWrapper{
private static $tempFiles=array(); private static $tempFiles=array();
public function __construct($params){ public function __construct($params) {
$this->host=$params['host']; $this->host=$params['host'];
$this->user=$params['user']; $this->user=$params['user'];
$this->password=$params['password']; $this->password=$params['password'];
$this->secure=isset($params['secure'])?(bool)$params['secure']:false; $this->secure=isset($params['secure'])?(bool)$params['secure']:false;
$this->root=isset($params['root'])?$params['root']:'/'; $this->root=isset($params['root'])?$params['root']:'/';
if(!$this->root || $this->root[0]!='/'){ if(!$this->root || $this->root[0]!='/') {
$this->root='/'.$this->root; $this->root='/'.$this->root;
} }
//create the root folder if necesary //create the root folder if necesary
@ -35,16 +35,16 @@ class OC_FileStorage_FTP extends OC_FileStorage_StreamWrapper{
* @param string path * @param string path
* @return string * @return string
*/ */
public function constructUrl($path){ public function constructUrl($path) {
$url='ftp'; $url='ftp';
if($this->secure){ if($this->secure) {
$url.='s'; $url.='s';
} }
$url.='://'.$this->user.':'.$this->password.'@'.$this->host.$this->root.$path; $url.='://'.$this->user.':'.$this->password.'@'.$this->host.$this->root.$path;
return $url; return $url;
} }
public function fopen($path,$mode){ public function fopen($path,$mode) {
switch($mode){ switch($mode) {
case 'r': case 'r':
case 'rb': case 'rb':
case 'w': case 'w':
@ -63,14 +63,14 @@ class OC_FileStorage_FTP extends OC_FileStorage_StreamWrapper{
case 'c': case 'c':
case 'c+': case 'c+':
//emulate these //emulate these
if(strrpos($path,'.')!==false){ if(strrpos($path,'.')!==false) {
$ext=substr($path,strrpos($path,'.')); $ext=substr($path,strrpos($path,'.'));
}else{ }else{
$ext=''; $ext='';
} }
$tmpFile=OCP\Files::tmpFile($ext); $tmpFile=OCP\Files::tmpFile($ext);
OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack'); OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack');
if($this->file_exists($path)){ if($this->file_exists($path)) {
$this->getFile($path,$tmpFile); $this->getFile($path,$tmpFile);
} }
self::$tempFiles[$tmpFile]=$path; self::$tempFiles[$tmpFile]=$path;
@ -78,8 +78,8 @@ class OC_FileStorage_FTP extends OC_FileStorage_StreamWrapper{
} }
} }
public function writeBack($tmpFile){ public function writeBack($tmpFile) {
if(isset(self::$tempFiles[$tmpFile])){ if(isset(self::$tempFiles[$tmpFile])) {
$this->uploadFile($tmpFile,self::$tempFiles[$tmpFile]); $this->uploadFile($tmpFile,self::$tempFiles[$tmpFile]);
unlink($tmpFile); unlink($tmpFile);
} }

View File

@ -15,40 +15,40 @@ class OC_FileStorage_SMB extends OC_FileStorage_StreamWrapper{
private $root; private $root;
private $share; private $share;
public function __construct($params){ public function __construct($params) {
$this->host=$params['host']; $this->host=$params['host'];
$this->user=$params['user']; $this->user=$params['user'];
$this->password=$params['password']; $this->password=$params['password'];
$this->share=$params['share']; $this->share=$params['share'];
$this->root=isset($params['root'])?$params['root']:'/'; $this->root=isset($params['root'])?$params['root']:'/';
if(!$this->root || $this->root[0]!='/'){ if(!$this->root || $this->root[0]!='/') {
$this->root='/'.$this->root; $this->root='/'.$this->root;
} }
if(substr($this->root,-1,1)!='/'){ if(substr($this->root,-1,1)!='/') {
$this->root.='/'; $this->root.='/';
} }
if(!$this->share || $this->share[0]!='/'){ if(!$this->share || $this->share[0]!='/') {
$this->share='/'.$this->share; $this->share='/'.$this->share;
} }
if(substr($this->share,-1,1)=='/'){ if(substr($this->share,-1,1)=='/') {
$this->share=substr($this->share,0,-1); $this->share=substr($this->share,0,-1);
} }
//create the root folder if necesary //create the root folder if necesary
if(!$this->is_dir('')){ if(!$this->is_dir('')) {
$this->mkdir(''); $this->mkdir('');
} }
} }
public function constructUrl($path){ public function constructUrl($path) {
if(substr($path,-1)=='/'){ if(substr($path,-1)=='/') {
$path=substr($path,0,-1); $path=substr($path,0,-1);
} }
return 'smb://'.$this->user.':'.$this->password.'@'.$this->host.$this->share.$this->root.$path; return 'smb://'.$this->user.':'.$this->password.'@'.$this->host.$this->share.$this->root.$path;
} }
public function stat($path){ public function stat($path) {
if(!$path and $this->root=='/'){//mtime doesn't work for shares if(!$path and $this->root=='/') {//mtime doesn't work for shares
$mtime=$this->shareMTime(); $mtime=$this->shareMTime();
$stat=stat($this->constructUrl($path)); $stat=stat($this->constructUrl($path));
$stat['mtime']=$mtime; $stat['mtime']=$mtime;
@ -58,7 +58,7 @@ class OC_FileStorage_SMB extends OC_FileStorage_StreamWrapper{
} }
} }
public function filetype($path){ public function filetype($path) {
return (bool)@$this->opendir($path);//using opendir causes the same amount of requests and caches the content of the folder in one go return (bool)@$this->opendir($path);//using opendir causes the same amount of requests and caches the content of the folder in one go
} }
@ -67,8 +67,8 @@ class OC_FileStorage_SMB extends OC_FileStorage_StreamWrapper{
* @param int $time * @param int $time
* @return bool * @return bool
*/ */
public function hasUpdated($path,$time){ public function hasUpdated($path,$time) {
if(!$path and $this->root=='/'){ if(!$path and $this->root=='/') {
//mtime doesn't work for shares, but giving the nature of the backend, doing a full update is still just fast enough //mtime doesn't work for shares, but giving the nature of the backend, doing a full update is still just fast enough
return true; return true;
}else{ }else{
@ -80,13 +80,13 @@ class OC_FileStorage_SMB extends OC_FileStorage_StreamWrapper{
/** /**
* get the best guess for the modification time of the share * get the best guess for the modification time of the share
*/ */
private function shareMTime(){ private function shareMTime() {
$dh=$this->opendir(''); $dh=$this->opendir('');
$lastCtime=0; $lastCtime=0;
while($file=readdir($dh)){ while($file=readdir($dh)) {
if($file!='.' and $file!='..'){ if($file!='.' and $file!='..') {
$ctime=$this->filemtime($file); $ctime=$this->filemtime($file);
if($ctime>$lastCtime){ if($ctime>$lastCtime) {
$lastCtime=$ctime; $lastCtime=$ctime;
} }
} }

View File

@ -10,12 +10,12 @@
abstract class OC_FileStorage_StreamWrapper extends OC_Filestorage_Common{ abstract class OC_FileStorage_StreamWrapper extends OC_Filestorage_Common{
abstract public function constructUrl($path); abstract public function constructUrl($path);
public function mkdir($path){ public function mkdir($path) {
return mkdir($this->constructUrl($path)); return mkdir($this->constructUrl($path));
} }
public function rmdir($path){ public function rmdir($path) {
if($this->file_exists($path)){ if($this->file_exists($path)) {
$succes=rmdir($this->constructUrl($path)); $succes=rmdir($this->constructUrl($path));
clearstatcache(); clearstatcache();
return $succes; return $succes;
@ -24,42 +24,42 @@ abstract class OC_FileStorage_StreamWrapper extends OC_Filestorage_Common{
} }
} }
public function opendir($path){ public function opendir($path) {
return opendir($this->constructUrl($path)); return opendir($this->constructUrl($path));
} }
public function filetype($path){ public function filetype($path) {
return filetype($this->constructUrl($path)); return filetype($this->constructUrl($path));
} }
public function isReadable($path){ public function isReadable($path) {
return true;//not properly supported return true;//not properly supported
} }
public function isUpdatable($path){ public function isUpdatable($path) {
return true;//not properly supported return true;//not properly supported
} }
public function file_exists($path){ public function file_exists($path) {
return file_exists($this->constructUrl($path)); return file_exists($this->constructUrl($path));
} }
public function unlink($path){ public function unlink($path) {
$succes=unlink($this->constructUrl($path)); $succes=unlink($this->constructUrl($path));
clearstatcache(); clearstatcache();
return $succes; return $succes;
} }
public function fopen($path,$mode){ public function fopen($path,$mode) {
return fopen($this->constructUrl($path),$mode); return fopen($this->constructUrl($path),$mode);
} }
public function free_space($path){ public function free_space($path) {
return 0; return 0;
} }
public function touch($path,$mtime=null){ public function touch($path,$mtime=null) {
if(is_null($mtime)){ if(is_null($mtime)) {
$fh=$this->fopen($path,'a'); $fh=$this->fopen($path,'a');
fwrite($fh,''); fwrite($fh,'');
fclose($fh); fclose($fh);
@ -68,19 +68,19 @@ abstract class OC_FileStorage_StreamWrapper extends OC_Filestorage_Common{
} }
} }
public function getFile($path,$target){ public function getFile($path,$target) {
return copy($this->constructUrl($path),$target); return copy($this->constructUrl($path),$target);
} }
public function uploadFile($path,$target){ public function uploadFile($path,$target) {
return copy($path,$this->constructUrl($target)); return copy($path,$this->constructUrl($target));
} }
public function rename($path1,$path2){ public function rename($path1,$path2) {
return rename($this->constructUrl($path1),$this->constructUrl($path2)); return rename($this->constructUrl($path1),$this->constructUrl($path2));
} }
public function stat($path){ public function stat($path) {
return stat($this->constructUrl($path)); return stat($this->constructUrl($path));
} }

View File

@ -38,7 +38,7 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param string path * @param string path
* @return string * @return string
*/ */
private function getContainerName($path){ private function getContainerName($path) {
$path=trim($this->root.$path,'/'); $path=trim($this->root.$path,'/');
return str_replace('/','\\',$path); return str_replace('/','\\',$path);
} }
@ -48,18 +48,18 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param string path * @param string path
* @return CF_Container * @return CF_Container
*/ */
private function getContainer($path){ private function getContainer($path) {
if($path=='' or $path=='/'){ if($path=='' or $path=='/') {
return $this->rootContainer; return $this->rootContainer;
} }
if(isset($this->containers[$path])){ if(isset($this->containers[$path])) {
return $this->containers[$path]; return $this->containers[$path];
} }
try{ try{
$container=$this->conn->get_container($this->getContainerName($path)); $container=$this->conn->get_container($this->getContainerName($path));
$this->containers[$path]=$container; $this->containers[$path]=$container;
return $container; return $container;
}catch(NoSuchContainerException $e){ }catch(NoSuchContainerException $e) {
return null; return null;
} }
} }
@ -69,15 +69,15 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param string path * @param string path
* @return CF_Container * @return CF_Container
*/ */
private function createContainer($path){ private function createContainer($path) {
if($path=='' or $path=='/'){ if($path=='' or $path=='/') {
return $this->conn->create_container($this->getContainerName($path)); return $this->conn->create_container($this->getContainerName($path));
} }
$parent=dirname($path); $parent=dirname($path);
if($parent=='' or $parent=='/'){ if($parent=='' or $parent=='/') {
$parentContainer=$this->rootContainer; $parentContainer=$this->rootContainer;
}else{ }else{
if(!$this->containerExists($parent)){ if(!$this->containerExists($parent)) {
$parentContainer=$this->createContainer($parent); $parentContainer=$this->createContainer($parent);
}else{ }else{
$parentContainer=$this->getContainer($parent); $parentContainer=$this->getContainer($parent);
@ -92,19 +92,19 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param string path * @param string path
* @return CF_Object * @return CF_Object
*/ */
private function getObject($path){ private function getObject($path) {
if(isset($this->objects[$path])){ if(isset($this->objects[$path])) {
return $this->objects[$path]; return $this->objects[$path];
} }
$container=$this->getContainer(dirname($path)); $container=$this->getContainer(dirname($path));
if(is_null($container)){ if(is_null($container)) {
return null; return null;
}else{ }else{
try{ try{
$obj=$container->get_object(basename($path)); $obj=$container->get_object(basename($path));
$this->objects[$path]=$obj; $this->objects[$path]=$obj;
return $obj; return $obj;
}catch(NoSuchObjectException $e){ }catch(NoSuchObjectException $e) {
return null; return null;
} }
} }
@ -115,12 +115,12 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param CF_Container * @param CF_Container
* @return array * @return array
*/ */
private function getObjects($container){ private function getObjects($container) {
if(is_null($container)){ if(is_null($container)) {
return array(); return array();
}else{ }else{
$files=$container->get_objects(); $files=$container->get_objects();
foreach($files as &$file){ foreach($files as &$file) {
$file=$file->name; $file=$file->name;
} }
return $files; return $files;
@ -132,9 +132,9 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param string path * @param string path
* @return CF_Object * @return CF_Object
*/ */
private function createObject($path){ private function createObject($path) {
$container=$this->getContainer(dirname($path)); $container=$this->getContainer(dirname($path));
if(!is_null($container)){ if(!is_null($container)) {
$container=$this->createContainer($path); $container=$this->createContainer($path);
} }
return $container->create_object(basename($path)); return $container->create_object(basename($path));
@ -145,7 +145,7 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param string * @param string
* @return bool * @return bool
*/ */
private function objectExists($path){ private function objectExists($path) {
return !is_null($this->getObject($path)); return !is_null($this->getObject($path));
} }
@ -154,7 +154,7 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param string path * @param string path
* @return bool * @return bool
*/ */
private function containerExists($path){ private function containerExists($path) {
return !is_null($this->getContainer($path)); return !is_null($this->getContainer($path));
} }
@ -163,18 +163,18 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param CF_Container container * @param CF_Container container
* @return array * @return array
*/ */
private function getSubContainers($container){ private function getSubContainers($container) {
$tmpFile=OCP\Files::tmpFile(); $tmpFile=OCP\Files::tmpFile();
$obj=$this->getSubContainerFile($container); $obj=$this->getSubContainerFile($container);
try{ try{
$obj->save_to_filename($tmpFile); $obj->save_to_filename($tmpFile);
}catch(Exception $e){ }catch(Exception $e) {
return array(); return array();
} }
$obj->save_to_filename($tmpFile); $obj->save_to_filename($tmpFile);
$containers=file($tmpFile); $containers=file($tmpFile);
unlink($tmpFile); unlink($tmpFile);
foreach($containers as &$sub){ foreach($containers as &$sub) {
$sub=trim($sub); $sub=trim($sub);
} }
return $containers; return $containers;
@ -186,8 +186,8 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param string name * @param string name
* @return bool * @return bool
*/ */
private function addSubContainer($container,$name){ private function addSubContainer($container,$name) {
if(!$name){ if(!$name) {
return false; return false;
} }
$tmpFile=OCP\Files::tmpFile(); $tmpFile=OCP\Files::tmpFile();
@ -195,17 +195,17 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
try{ try{
$obj->save_to_filename($tmpFile); $obj->save_to_filename($tmpFile);
$containers=file($tmpFile); $containers=file($tmpFile);
foreach($containers as &$sub){ foreach($containers as &$sub) {
$sub=trim($sub); $sub=trim($sub);
} }
if(array_search($name,$containers)!==false){ if(array_search($name,$containers)!==false) {
unlink($tmpFile); unlink($tmpFile);
return false; return false;
}else{ }else{
$fh=fopen($tmpFile,'a'); $fh=fopen($tmpFile,'a');
fwrite($fh,$name."\n"); fwrite($fh,$name."\n");
} }
}catch(Exception $e){ }catch(Exception $e) {
$containers=array(); $containers=array();
file_put_contents($tmpFile,$name."\n"); file_put_contents($tmpFile,$name."\n");
} }
@ -221,8 +221,8 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param string name * @param string name
* @return bool * @return bool
*/ */
private function removeSubContainer($container,$name){ private function removeSubContainer($container,$name) {
if(!$name){ if(!$name) {
return false; return false;
} }
$tmpFile=OCP\Files::tmpFile(); $tmpFile=OCP\Files::tmpFile();
@ -230,14 +230,14 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
try{ try{
$obj->save_to_filename($tmpFile); $obj->save_to_filename($tmpFile);
$containers=file($tmpFile); $containers=file($tmpFile);
}catch(Exception $e){ }catch(Exception $e) {
return false; return false;
} }
foreach($containers as &$sub){ foreach($containers as &$sub) {
$sub=trim($sub); $sub=trim($sub);
} }
$i=array_search($name,$containers); $i=array_search($name,$containers);
if($i===false){ if($i===false) {
unlink($tmpFile); unlink($tmpFile);
return false; return false;
}else{ }else{
@ -255,21 +255,21 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* @param CF_Container container * @param CF_Container container
* @return CF_Object * @return CF_Object
*/ */
private function getSubContainerFile($container){ private function getSubContainerFile($container) {
try{ try{
return $container->get_object(self::SUBCONTAINER_FILE); return $container->get_object(self::SUBCONTAINER_FILE);
}catch(NoSuchObjectException $e){ }catch(NoSuchObjectException $e) {
return $container->create_object(self::SUBCONTAINER_FILE); return $container->create_object(self::SUBCONTAINER_FILE);
} }
} }
public function __construct($params){ public function __construct($params) {
$this->token=$params['token']; $this->token=$params['token'];
$this->host=$params['host']; $this->host=$params['host'];
$this->user=$params['user']; $this->user=$params['user'];
$this->root=isset($params['root'])?$params['root']:'/'; $this->root=isset($params['root'])?$params['root']:'/';
$this->secure=isset($params['secure'])?(bool)$params['secure']:true; $this->secure=isset($params['secure'])?(bool)$params['secure']:true;
if(!$this->root || $this->root[0]!='/'){ if(!$this->root || $this->root[0]!='/') {
$this->root='/'.$this->root; $this->root='/'.$this->root;
} }
$this->auth = new CF_Authentication($this->user, $this->token, null, $this->host); $this->auth = new CF_Authentication($this->user, $this->token, null, $this->host);
@ -277,7 +277,7 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
$this->conn = new CF_Connection($this->auth); $this->conn = new CF_Connection($this->auth);
if(!$this->containerExists($this->root)){ if(!$this->containerExists($this->root)) {
$this->rootContainer=$this->createContainer('/'); $this->rootContainer=$this->createContainer('/');
}else{ }else{
$this->rootContainer=$this->getContainer('/'); $this->rootContainer=$this->getContainer('/');
@ -285,8 +285,8 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
} }
public function mkdir($path){ public function mkdir($path) {
if($this->containerExists($path)){ if($this->containerExists($path)) {
return false; return false;
}else{ }else{
$this->createContainer($path); $this->createContainer($path);
@ -294,12 +294,12 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
} }
} }
public function rmdir($path){ public function rmdir($path) {
if(!$this->containerExists($path)){ if(!$this->containerExists($path)) {
return false; return false;
}else{ }else{
$this->emptyContainer($path); $this->emptyContainer($path);
if($path!='' and $path!='/'){ if($path!='' and $path!='/') {
$parentContainer=$this->getContainer(dirname($path)); $parentContainer=$this->getContainer(dirname($path));
$this->removeSubContainer($parentContainer,basename($path)); $this->removeSubContainer($parentContainer,basename($path));
} }
@ -310,14 +310,14 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
} }
} }
private function emptyContainer($path){ private function emptyContainer($path) {
$container=$this->getContainer($path); $container=$this->getContainer($path);
if(is_null($container)){ if(is_null($container)) {
return; return;
} }
$subContainers=$this->getSubContainers($container); $subContainers=$this->getSubContainers($container);
foreach($subContainers as $sub){ foreach($subContainers as $sub) {
if($sub){ if($sub) {
$this->emptyContainer($path.'/'.$sub); $this->emptyContainer($path.'/'.$sub);
$this->conn->delete_container($this->getContainerName($path.'/'.$sub)); $this->conn->delete_container($this->getContainerName($path.'/'.$sub));
unset($this->containers[$path.'/'.$sub]); unset($this->containers[$path.'/'.$sub]);
@ -325,17 +325,17 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
} }
$objects=$this->getObjects($container); $objects=$this->getObjects($container);
foreach($objects as $object){ foreach($objects as $object) {
$container->delete_object($object); $container->delete_object($object);
unset($this->objects[$path.'/'.$object]); unset($this->objects[$path.'/'.$object]);
} }
} }
public function opendir($path){ public function opendir($path) {
$container=$this->getContainer($path); $container=$this->getContainer($path);
$files=$this->getObjects($container); $files=$this->getObjects($container);
$i=array_search(self::SUBCONTAINER_FILE,$files); $i=array_search(self::SUBCONTAINER_FILE,$files);
if($i!==false){ if($i!==false) {
unset($files[$i]); unset($files[$i]);
} }
$subContainers=$this->getSubContainers($container); $subContainers=$this->getSubContainers($container);
@ -345,43 +345,43 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
return opendir('fakedir://'.$id); return opendir('fakedir://'.$id);
} }
public function filetype($path){ public function filetype($path) {
if($this->containerExists($path)){ if($this->containerExists($path)) {
return 'dir'; return 'dir';
}else{ }else{
return 'file'; return 'file';
} }
} }
public function isReadable($path){ public function isReadable($path) {
return true; return true;
} }
public function isUpdatable($path){ public function isUpdatable($path) {
return true; return true;
} }
public function file_exists($path){ public function file_exists($path) {
if($this->is_dir($path)){ if($this->is_dir($path)) {
return true; return true;
}else{ }else{
return $this->objectExists($path); return $this->objectExists($path);
} }
} }
public function file_get_contents($path){ public function file_get_contents($path) {
$obj=$this->getObject($path); $obj=$this->getObject($path);
if(is_null($obj)){ if(is_null($obj)) {
return false; return false;
} }
return $obj->read(); return $obj->read();
} }
public function file_put_contents($path,$content){ public function file_put_contents($path,$content) {
$obj=$this->getObject($path); $obj=$this->getObject($path);
if(is_null($obj)){ if(is_null($obj)) {
$container=$this->getContainer(dirname($path)); $container=$this->getContainer(dirname($path));
if(is_null($container)){ if(is_null($container)) {
return false; return false;
} }
$obj=$container->create_object(basename($path)); $obj=$container->create_object(basename($path));
@ -390,8 +390,8 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
return $obj->write($content); return $obj->write($content);
} }
public function unlink($path){ public function unlink($path) {
if($this->objectExists($path)){ if($this->objectExists($path)) {
$container=$this->getContainer(dirname($path)); $container=$this->getContainer(dirname($path));
$container->delete_object(basename($path)); $container->delete_object(basename($path));
unset($this->objects[$path]); unset($this->objects[$path]);
@ -400,12 +400,12 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
} }
} }
public function fopen($path,$mode){ public function fopen($path,$mode) {
$obj=$this->getObject($path); $obj=$this->getObject($path);
if(is_null($obj)){ if(is_null($obj)) {
return false; return false;
} }
switch($mode){ switch($mode) {
case 'r': case 'r':
case 'rb': case 'rb':
$fp = fopen('php://temp', 'r+'); $fp = fopen('php://temp', 'r+');
@ -432,23 +432,23 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
} }
} }
public function writeBack($tmpFile){ public function writeBack($tmpFile) {
if(isset(self::$tempFiles[$tmpFile])){ if(isset(self::$tempFiles[$tmpFile])) {
$this->fromTmpFile($tmpFile,self::$tempFiles[$tmpFile]); $this->fromTmpFile($tmpFile,self::$tempFiles[$tmpFile]);
unlink($tmpFile); unlink($tmpFile);
} }
} }
public function free_space($path){ public function free_space($path) {
return 0; return 0;
} }
public function touch($path,$mtime=null){ public function touch($path,$mtime=null) {
$obj=$this->getObject($path); $obj=$this->getObject($path);
if(is_null($obj)){ if(is_null($obj)) {
return false; return false;
} }
if(is_null($mtime)){ if(is_null($mtime)) {
$mtime=time(); $mtime=time();
} }
@ -457,36 +457,36 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
$obj->sync_metadata(); $obj->sync_metadata();
} }
public function rename($path1,$path2){ public function rename($path1,$path2) {
$sourceContainer=$this->getContainer(dirname($path1)); $sourceContainer=$this->getContainer(dirname($path1));
$targetContainer=$this->getContainer(dirname($path2)); $targetContainer=$this->getContainer(dirname($path2));
$result=$sourceContainer->move_object_to(basename($path1),$targetContainer,basename($path2)); $result=$sourceContainer->move_object_to(basename($path1),$targetContainer,basename($path2));
unset($this->objects[$path1]); unset($this->objects[$path1]);
if($result){ if($result) {
$targetObj=$this->getObject($path2); $targetObj=$this->getObject($path2);
$this->resetMTime($targetObj); $this->resetMTime($targetObj);
} }
return $result; return $result;
} }
public function copy($path1,$path2){ public function copy($path1,$path2) {
$sourceContainer=$this->getContainer(dirname($path1)); $sourceContainer=$this->getContainer(dirname($path1));
$targetContainer=$this->getContainer(dirname($path2)); $targetContainer=$this->getContainer(dirname($path2));
$result=$sourceContainer->copy_object_to(basename($path1),$targetContainer,basename($path2)); $result=$sourceContainer->copy_object_to(basename($path1),$targetContainer,basename($path2));
if($result){ if($result) {
$targetObj=$this->getObject($path2); $targetObj=$this->getObject($path2);
$this->resetMTime($targetObj); $this->resetMTime($targetObj);
} }
return $result; return $result;
} }
public function stat($path){ public function stat($path) {
$obj=$this->getObject($path); $obj=$this->getObject($path);
if(is_null($obj)){ if(is_null($obj)) {
return false; return false;
} }
if(isset($obj->metadata['Mtime']) and $obj->metadata['Mtime']>-1){ if(isset($obj->metadata['Mtime']) and $obj->metadata['Mtime']>-1) {
$mtime=$obj->metadata['Mtime']; $mtime=$obj->metadata['Mtime'];
}else{ }else{
$mtime=strtotime($obj->last_modified); $mtime=strtotime($obj->last_modified);
@ -498,9 +498,9 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
); );
} }
private function getTmpFile($path){ private function getTmpFile($path) {
$obj=$this->getObject($path); $obj=$this->getObject($path);
if(!is_null($obj)){ if(!is_null($obj)) {
$tmpFile=OCP\Files::tmpFile(); $tmpFile=OCP\Files::tmpFile();
$obj->save_to_filename($tmpFile); $obj->save_to_filename($tmpFile);
return $tmpFile; return $tmpFile;
@ -509,9 +509,9 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
} }
} }
private function fromTmpFile($tmpFile,$path){ private function fromTmpFile($tmpFile,$path) {
$obj=$this->getObject($path); $obj=$this->getObject($path);
if(is_null($obj)){ if(is_null($obj)) {
$obj=$this->createObject($path); $obj=$this->createObject($path);
} }
$obj->load_from_filename($tmpFile); $obj->load_from_filename($tmpFile);
@ -522,8 +522,8 @@ class OC_FileStorage_SWIFT extends OC_Filestorage_Common{
* remove custom mtime metadata * remove custom mtime metadata
* @param CF_Object obj * @param CF_Object obj
*/ */
private function resetMTime($obj){ private function resetMTime($obj) {
if(isset($obj->metadata['Mtime'])){ if(isset($obj->metadata['Mtime'])) {
$obj->metadata['Mtime']=-1; $obj->metadata['Mtime']=-1;
$obj->sync_metadata(); $obj->sync_metadata();
} }

View File

@ -19,7 +19,7 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
private static $tempFiles=array(); private static $tempFiles=array();
public function __construct($params){ public function __construct($params) {
$host = $params['host']; $host = $params['host'];
//remove leading http[s], will be generated in createBaseUri() //remove leading http[s], will be generated in createBaseUri()
if (substr($host,0,8) == "https://") $host = substr($host, 8); if (substr($host,0,8) == "https://") $host = substr($host, 8);
@ -29,10 +29,10 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
$this->password=$params['password']; $this->password=$params['password'];
$this->secure=(isset($params['secure']) && $params['secure'] == 'true')?true:false; $this->secure=(isset($params['secure']) && $params['secure'] == 'true')?true:false;
$this->root=isset($params['root'])?$params['root']:'/'; $this->root=isset($params['root'])?$params['root']:'/';
if(!$this->root || $this->root[0]!='/'){ if(!$this->root || $this->root[0]!='/') {
$this->root='/'.$this->root; $this->root='/'.$this->root;
} }
if(substr($this->root,-1,1)!='/'){ if(substr($this->root,-1,1)!='/') {
$this->root.='/'; $this->root.='/';
} }
@ -54,26 +54,26 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
$this->mkdir(''); $this->mkdir('');
} }
private function createBaseUri(){ private function createBaseUri() {
$baseUri='http'; $baseUri='http';
if($this->secure){ if($this->secure) {
$baseUri.='s'; $baseUri.='s';
} }
$baseUri.='://'.$this->host.$this->root; $baseUri.='://'.$this->host.$this->root;
return $baseUri; return $baseUri;
} }
public function mkdir($path){ public function mkdir($path) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
return $this->simpleResponse('MKCOL',$path,null,201); return $this->simpleResponse('MKCOL',$path,null,201);
} }
public function rmdir($path){ public function rmdir($path) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
return $this->simpleResponse('DELETE',$path,null,204); return $this->simpleResponse('DELETE',$path,null,204);
} }
public function opendir($path){ public function opendir($path) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
try{ try{
$response=$this->client->propfind($path, array(),1); $response=$this->client->propfind($path, array(),1);
@ -81,54 +81,54 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
OC_FakeDirStream::$dirs[$id]=array(); OC_FakeDirStream::$dirs[$id]=array();
$files=array_keys($response); $files=array_keys($response);
array_shift($files);//the first entry is the current directory array_shift($files);//the first entry is the current directory
foreach($files as $file){ foreach($files as $file) {
$file = urldecode(basename($file)); $file = urldecode(basename($file));
OC_FakeDirStream::$dirs[$id][]=$file; OC_FakeDirStream::$dirs[$id][]=$file;
} }
return opendir('fakedir://'.$id); return opendir('fakedir://'.$id);
}catch(Exception $e){ }catch(Exception $e) {
return false; return false;
} }
} }
public function filetype($path){ public function filetype($path) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
try{ try{
$response=$this->client->propfind($path, array('{DAV:}resourcetype')); $response=$this->client->propfind($path, array('{DAV:}resourcetype'));
$responseType=$response["{DAV:}resourcetype"]->resourceType; $responseType=$response["{DAV:}resourcetype"]->resourceType;
return (count($responseType)>0 and $responseType[0]=="{DAV:}collection")?'dir':'file'; return (count($responseType)>0 and $responseType[0]=="{DAV:}collection")?'dir':'file';
}catch(Exception $e){ }catch(Exception $e) {
error_log($e->getMessage()); error_log($e->getMessage());
\OCP\Util::writeLog("webdav client", \OCP\Util::sanitizeHTML($e->getMessage()), \OCP\Util::ERROR); \OCP\Util::writeLog("webdav client", \OCP\Util::sanitizeHTML($e->getMessage()), \OCP\Util::ERROR);
return false; return false;
} }
} }
public function isReadable($path){ public function isReadable($path) {
return true;//not properly supported return true;//not properly supported
} }
public function isUpdatable($path){ public function isUpdatable($path) {
return true;//not properly supported return true;//not properly supported
} }
public function file_exists($path){ public function file_exists($path) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
try{ try{
$this->client->propfind($path, array('{DAV:}resourcetype')); $this->client->propfind($path, array('{DAV:}resourcetype'));
return true;//no 404 exception return true;//no 404 exception
}catch(Exception $e){ }catch(Exception $e) {
return false; return false;
} }
} }
public function unlink($path){ public function unlink($path) {
return $this->simpleResponse('DELETE',$path,null,204); return $this->simpleResponse('DELETE',$path,null,204);
} }
public function fopen($path,$mode){ public function fopen($path,$mode) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
switch($mode){ switch($mode) {
case 'r': case 'r':
case 'rb': case 'rb':
//straight up curl instead of sabredav here, sabredav put's the entire get result in memory //straight up curl instead of sabredav here, sabredav put's the entire get result in memory
@ -155,14 +155,14 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
case 'c': case 'c':
case 'c+': case 'c+':
//emulate these //emulate these
if(strrpos($path,'.')!==false){ if(strrpos($path,'.')!==false) {
$ext=substr($path,strrpos($path,'.')); $ext=substr($path,strrpos($path,'.'));
}else{ }else{
$ext=''; $ext='';
} }
$tmpFile=OCP\Files::tmpFile($ext); $tmpFile=OCP\Files::tmpFile($ext);
OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack'); OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack');
if($this->file_exists($path)){ if($this->file_exists($path)) {
$this->getFile($path,$tmpFile); $this->getFile($path,$tmpFile);
} }
self::$tempFiles[$tmpFile]=$path; self::$tempFiles[$tmpFile]=$path;
@ -170,41 +170,41 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
} }
} }
public function writeBack($tmpFile){ public function writeBack($tmpFile) {
if(isset(self::$tempFiles[$tmpFile])){ if(isset(self::$tempFiles[$tmpFile])) {
$this->uploadFile($tmpFile,self::$tempFiles[$tmpFile]); $this->uploadFile($tmpFile,self::$tempFiles[$tmpFile]);
unlink($tmpFile); unlink($tmpFile);
} }
} }
public function free_space($path){ public function free_space($path) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
try{ try{
$response=$this->client->propfind($path, array('{DAV:}quota-available-bytes')); $response=$this->client->propfind($path, array('{DAV:}quota-available-bytes'));
if(isset($response['{DAV:}quota-available-bytes'])){ if(isset($response['{DAV:}quota-available-bytes'])) {
return (int)$response['{DAV:}quota-available-bytes']; return (int)$response['{DAV:}quota-available-bytes'];
}else{ }else{
return 0; return 0;
} }
}catch(Exception $e){ }catch(Exception $e) {
return 0; return 0;
} }
} }
public function touch($path,$mtime=null){ public function touch($path,$mtime=null) {
if(is_null($mtime)){ if(is_null($mtime)) {
$mtime=time(); $mtime=time();
} }
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
$this->client->proppatch($path, array('{DAV:}lastmodified' => $mtime)); $this->client->proppatch($path, array('{DAV:}lastmodified' => $mtime));
} }
public function getFile($path,$target){ public function getFile($path,$target) {
$source=$this->fopen($path,'r'); $source=$this->fopen($path,'r');
file_put_contents($target,$source); file_put_contents($target,$source);
} }
public function uploadFile($path,$target){ public function uploadFile($path,$target) {
$source=fopen($path,'r'); $source=fopen($path,'r');
$curl = curl_init(); $curl = curl_init();
@ -218,13 +218,13 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
curl_close ($curl); curl_close ($curl);
} }
public function rename($path1,$path2){ public function rename($path1,$path2) {
$path1=$this->cleanPath($path1); $path1=$this->cleanPath($path1);
$path2=$this->root.$this->cleanPath($path2); $path2=$this->root.$this->cleanPath($path2);
try{ try{
$response=$this->client->request('MOVE',$path1,null,array('Destination'=>$path2)); $response=$this->client->request('MOVE',$path1,null,array('Destination'=>$path2));
return true; return true;
}catch(Exception $e){ }catch(Exception $e) {
echo $e; echo $e;
echo 'fail'; echo 'fail';
var_dump($response); var_dump($response);
@ -232,13 +232,13 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
} }
} }
public function copy($path1,$path2){ public function copy($path1,$path2) {
$path1=$this->cleanPath($path1); $path1=$this->cleanPath($path1);
$path2=$this->root.$this->cleanPath($path2); $path2=$this->root.$this->cleanPath($path2);
try{ try{
$response=$this->client->request('COPY',$path1,null,array('Destination'=>$path2)); $response=$this->client->request('COPY',$path1,null,array('Destination'=>$path2));
return true; return true;
}catch(Exception $e){ }catch(Exception $e) {
echo $e; echo $e;
echo 'fail'; echo 'fail';
var_dump($response); var_dump($response);
@ -246,7 +246,7 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
} }
} }
public function stat($path){ public function stat($path) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
try{ try{
$response=$this->client->propfind($path, array('{DAV:}getlastmodified','{DAV:}getcontentlength')); $response=$this->client->propfind($path, array('{DAV:}getlastmodified','{DAV:}getcontentlength'));
@ -255,43 +255,43 @@ class OC_FileStorage_DAV extends OC_Filestorage_Common{
'size'=>(int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0, 'size'=>(int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
'ctime'=>-1, 'ctime'=>-1,
); );
}catch(Exception $e){ }catch(Exception $e) {
return array(); return array();
} }
} }
public function getMimeType($path){ public function getMimeType($path) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
try{ try{
$response=$this->client->propfind($path, array('{DAV:}getcontenttype','{DAV:}resourcetype')); $response=$this->client->propfind($path, array('{DAV:}getcontenttype','{DAV:}resourcetype'));
$responseType=$response["{DAV:}resourcetype"]->resourceType; $responseType=$response["{DAV:}resourcetype"]->resourceType;
$type=(count($responseType)>0 and $responseType[0]=="{DAV:}collection")?'dir':'file'; $type=(count($responseType)>0 and $responseType[0]=="{DAV:}collection")?'dir':'file';
if($type=='dir'){ if($type=='dir') {
return 'httpd/unix-directory'; return 'httpd/unix-directory';
}elseif(isset($response['{DAV:}getcontenttype'])){ }elseif(isset($response['{DAV:}getcontenttype'])) {
return $response['{DAV:}getcontenttype']; return $response['{DAV:}getcontenttype'];
}else{ }else{
return false; return false;
} }
}catch(Exception $e){ }catch(Exception $e) {
return false; return false;
} }
} }
private function cleanPath($path){ private function cleanPath($path) {
if(!$path || $path[0]=='/'){ if(!$path || $path[0]=='/') {
return substr($path,1); return substr($path,1);
}else{ }else{
return $path; return $path;
} }
} }
private function simpleResponse($method,$path,$body,$expected){ private function simpleResponse($method,$path,$body,$expected) {
$path=$this->cleanPath($path); $path=$this->cleanPath($path);
try{ try{
$response=$this->client->request($method,$path,$body); $response=$this->client->request($method,$path,$body);
return $response['statusCode']==$expected; return $response['statusCode']==$expected;
}catch(Exception $e){ }catch(Exception $e) {
return false; return false;
} }
} }

View File

@ -7,21 +7,21 @@
*/ */
$config=include('apps/files_external/tests/config.php'); $config=include('apps/files_external/tests/config.php');
if(!is_array($config) or !isset($config['ftp']) or !$config['ftp']['run']){ if(!is_array($config) or !isset($config['ftp']) or !$config['ftp']['run']) {
abstract class Test_Filestorage_FTP extends Test_FileStorage{} abstract class Test_Filestorage_FTP extends Test_FileStorage{}
return; return;
}else{ }else{
class Test_Filestorage_FTP extends Test_FileStorage { class Test_Filestorage_FTP extends Test_FileStorage {
private $config; private $config;
public function setUp(){ public function setUp() {
$id=uniqid(); $id=uniqid();
$this->config=include('apps/files_external/tests/config.php'); $this->config=include('apps/files_external/tests/config.php');
$this->config['ftp']['root'].='/'.$id;//make sure we have an new empty folder to work in $this->config['ftp']['root'].='/'.$id;//make sure we have an new empty folder to work in
$this->instance=new OC_Filestorage_FTP($this->config['ftp']); $this->instance=new OC_Filestorage_FTP($this->config['ftp']);
} }
public function tearDown(){ public function tearDown() {
OCP\Files::rmdirr($this->instance->constructUrl('')); OCP\Files::rmdirr($this->instance->constructUrl(''));
} }
} }

View File

@ -21,7 +21,7 @@
*/ */
$config=include('apps/files_external/tests/config.php'); $config=include('apps/files_external/tests/config.php');
if(!is_array($config) or !isset($config['google']) or !$config['google']['run']){ if(!is_array($config) or !isset($config['google']) or !$config['google']['run']) {
abstract class Test_Filestorage_Google extends Test_FileStorage{} abstract class Test_Filestorage_Google extends Test_FileStorage{}
return; return;
}else{ }else{
@ -29,14 +29,14 @@ if(!is_array($config) or !isset($config['google']) or !$config['google']['run'])
private $config; private $config;
public function setUp(){ public function setUp() {
$id=uniqid(); $id=uniqid();
$this->config=include('apps/files_external/tests/config.php'); $this->config=include('apps/files_external/tests/config.php');
$this->config['google']['root'].='/'.$id;//make sure we have an new empty folder to work in $this->config['google']['root'].='/'.$id;//make sure we have an new empty folder to work in
$this->instance=new OC_Filestorage_Google($this->config['google']); $this->instance=new OC_Filestorage_Google($this->config['google']);
} }
public function tearDown(){ public function tearDown() {
$this->instance->rmdir('/'); $this->instance->rmdir('/');
} }
} }

View File

@ -8,21 +8,21 @@
$config=include('apps/files_external/tests/config.php'); $config=include('apps/files_external/tests/config.php');
if(!is_array($config) or !isset($config['smb']) or !$config['smb']['run']){ if(!is_array($config) or !isset($config['smb']) or !$config['smb']['run']) {
abstract class Test_Filestorage_SMB extends Test_FileStorage{} abstract class Test_Filestorage_SMB extends Test_FileStorage{}
return; return;
}else{ }else{
class Test_Filestorage_SMB extends Test_FileStorage { class Test_Filestorage_SMB extends Test_FileStorage {
private $config; private $config;
public function setUp(){ public function setUp() {
$id=uniqid(); $id=uniqid();
$this->config=include('apps/files_external/tests/config.php'); $this->config=include('apps/files_external/tests/config.php');
$this->config['smb']['root'].=$id;//make sure we have an new empty folder to work in $this->config['smb']['root'].=$id;//make sure we have an new empty folder to work in
$this->instance=new OC_Filestorage_SMB($this->config['smb']); $this->instance=new OC_Filestorage_SMB($this->config['smb']);
} }
public function tearDown(){ public function tearDown() {
OCP\Files::rmdirr($this->instance->constructUrl('')); OCP\Files::rmdirr($this->instance->constructUrl(''));
} }
} }

View File

@ -7,14 +7,14 @@
*/ */
$config=include('apps/files_external/tests/config.php'); $config=include('apps/files_external/tests/config.php');
if(!is_array($config) or !isset($config['swift']) or !$config['swift']['run']){ if(!is_array($config) or !isset($config['swift']) or !$config['swift']['run']) {
abstract class Test_Filestorage_SWIFT extends Test_FileStorage{} abstract class Test_Filestorage_SWIFT extends Test_FileStorage{}
return; return;
}else{ }else{
class Test_Filestorage_SWIFT extends Test_FileStorage { class Test_Filestorage_SWIFT extends Test_FileStorage {
private $config; private $config;
public function setUp(){ public function setUp() {
$id=uniqid(); $id=uniqid();
$this->config=include('apps/files_external/tests/config.php'); $this->config=include('apps/files_external/tests/config.php');
$this->config['swift']['root'].='/'.$id;//make sure we have an new empty folder to work in $this->config['swift']['root'].='/'.$id;//make sure we have an new empty folder to work in
@ -22,7 +22,7 @@ if(!is_array($config) or !isset($config['swift']) or !$config['swift']['run']){
} }
public function tearDown(){ public function tearDown() {
$this->instance->rmdir(''); $this->instance->rmdir('');
} }

View File

@ -7,21 +7,21 @@
*/ */
$config=include('apps/files_external/tests/config.php'); $config=include('apps/files_external/tests/config.php');
if(!is_array($config) or !isset($config['webdav']) or !$config['webdav']['run']){ if(!is_array($config) or !isset($config['webdav']) or !$config['webdav']['run']) {
abstract class Test_Filestorage_DAV extends Test_FileStorage{} abstract class Test_Filestorage_DAV extends Test_FileStorage{}
return; return;
}else{ }else{
class Test_Filestorage_DAV extends Test_FileStorage { class Test_Filestorage_DAV extends Test_FileStorage {
private $config; private $config;
public function setUp(){ public function setUp() {
$id=uniqid(); $id=uniqid();
$this->config=include('apps/files_external/tests/config.php'); $this->config=include('apps/files_external/tests/config.php');
$this->config['webdav']['root'].='/'.$id;//make sure we have an new empty folder to work in $this->config['webdav']['root'].='/'.$id;//make sure we have an new empty folder to work in
$this->instance=new OC_Filestorage_DAV($this->config['webdav']); $this->instance=new OC_Filestorage_DAV($this->config['webdav']);
} }
public function tearDown(){ public function tearDown() {
$this->instance->rmdir('/'); $this->instance->rmdir('/');
} }
} }

View File

@ -443,7 +443,7 @@ class OC_Filestorage_Shared extends OC_Filestorage_Common {
* @param int $time * @param int $time
* @return bool * @return bool
*/ */
public function hasUpdated($path,$time){ public function hasUpdated($path,$time) {
//TODO //TODO
return false; return false;
} }

View File

@ -31,7 +31,7 @@ OCP\JSON::callCheck();
$versions = new OCA_Versions\Storage(); $versions = new OCA_Versions\Storage();
if( $versions->expireAll() ){ if( $versions->expireAll() ) {
OCP\JSON::success(); OCP\JSON::success();
die(); die();

View File

@ -9,7 +9,7 @@ $file = $_GET['file'];
$revision=(int)$_GET['revision']; $revision=(int)$_GET['revision'];
if( OCA_Versions\Storage::isversioned( $file ) ) { if( OCA_Versions\Storage::isversioned( $file ) ) {
if(OCA_Versions\Storage::rollback( $file, $revision )){ if(OCA_Versions\Storage::rollback( $file, $revision )) {
OCP\JSON::success(array("data" => array( "revision" => $revision, "file" => $file ))); OCP\JSON::success(array("data" => array( "revision" => $revision, "file" => $file )));
}else{ }else{
OCP\JSON::error(array("data" => array( "message" => "Could not revert:" . $file ))); OCP\JSON::error(array("data" => array( "message" => "Could not revert:" . $file )));

View File

@ -44,7 +44,7 @@ class Hooks {
$abs_path = \OCP\Config::getSystemValue('datadirectory').$versions_fileview->getAbsolutePath('').$rel_path.'.v'; $abs_path = \OCP\Config::getSystemValue('datadirectory').$versions_fileview->getAbsolutePath('').$rel_path.'.v';
if(Storage::isversioned($rel_path)) { if(Storage::isversioned($rel_path)) {
$versions = Storage::getVersions($rel_path); $versions = Storage::getVersions($rel_path);
foreach ($versions as $v){ foreach ($versions as $v) {
unlink($abs_path . $v['version']); unlink($abs_path . $v['version']);
} }
} }
@ -66,7 +66,7 @@ class Hooks {
$info=pathinfo($abs_newpath); $info=pathinfo($abs_newpath);
if(!file_exists($info['dirname'])) mkdir($info['dirname'],0700,true); if(!file_exists($info['dirname'])) mkdir($info['dirname'],0700,true);
$versions = Storage::getVersions($rel_oldpath); $versions = Storage::getVersions($rel_oldpath);
foreach ($versions as $v){ foreach ($versions as $v) {
rename($abs_oldpath.$v['version'], $abs_newpath.$v['version']); rename($abs_oldpath.$v['version'], $abs_newpath.$v['version']);
} }
} }

View File

@ -82,7 +82,7 @@ class Storage {
} }
// check if filename is a directory // check if filename is a directory
if($files_view->is_dir($filename)){ if($files_view->is_dir($filename)) {
return false; return false;
} }
@ -97,7 +97,7 @@ class Storage {
} }
// check filesize // check filesize
if($files_view->filesize($filename)>\OCP\Config::getSystemValue('files_versionsmaxfilesize', Storage::DEFAULTMAXFILESIZE)){ if($files_view->filesize($filename)>\OCP\Config::getSystemValue('files_versionsmaxfilesize', Storage::DEFAULTMAXFILESIZE)) {
return false; return false;
} }
@ -107,7 +107,7 @@ class Storage {
$matches=glob($versionsFolderName.'/'.$filename.'.v*'); $matches=glob($versionsFolderName.'/'.$filename.'.v*');
sort($matches); sort($matches);
$parts=explode('.v',end($matches)); $parts=explode('.v',end($matches));
if((end($parts)+Storage::DEFAULTMININTERVAL)>time()){ if((end($parts)+Storage::DEFAULTMININTERVAL)>time()) {
return false; return false;
} }
} }
@ -175,7 +175,7 @@ class Storage {
// check for old versions // check for old versions
$matches=glob($versionsFolderName.$filename.'.v*'); $matches=glob($versionsFolderName.$filename.'.v*');
if(count($matches)>0){ if(count($matches)>0) {
return true; return true;
}else{ }else{
return false; return false;

View File

@ -1,6 +1,6 @@
<?php <?php
$state = OCP\Config::getSystemValue('ldapIgnoreNamingRules', 'doSet'); $state = OCP\Config::getSystemValue('ldapIgnoreNamingRules', 'doSet');
if($state == 'doSet'){ if($state == 'doSet') {
OCP\Config::setSystemValue('ldapIgnoreNamingRules', false); OCP\Config::setSystemValue('ldapIgnoreNamingRules', false);
} }

View File

@ -18,7 +18,7 @@ if(!is_null($pw)) {
//detect if we can switch on naming guidelines. We won't do it on conflicts. //detect if we can switch on naming guidelines. We won't do it on conflicts.
//it's a bit spaghetti, but hey. //it's a bit spaghetti, but hey.
$state = OCP\Config::getSystemValue('ldapIgnoreNamingRules', 'unset'); $state = OCP\Config::getSystemValue('ldapIgnoreNamingRules', 'unset');
if($state == 'unset'){ if($state == 'unset') {
OCP\Config::setSystemValue('ldapIgnoreNamingRules', false); OCP\Config::setSystemValue('ldapIgnoreNamingRules', false);
} }

View File

@ -231,7 +231,7 @@ class GROUP_LDAP extends lib\Access implements \OCP\GroupInterface {
* @param string $gid * @param string $gid
* @return bool * @return bool
*/ */
public function groupExists($gid){ public function groupExists($gid) {
if($this->connection->isCached('groupExists'.$gid)) { if($this->connection->isCached('groupExists'.$gid)) {
return $this->connection->getFromCache('groupExists'.$gid); return $this->connection->getFromCache('groupExists'.$gid);
} }

View File

@ -26,8 +26,8 @@ OCP\Util::addscript('user_ldap', 'settings');
OCP\Util::addstyle('user_ldap', 'settings'); OCP\Util::addstyle('user_ldap', 'settings');
if ($_POST) { if ($_POST) {
foreach($params as $param){ foreach($params as $param) {
if(isset($_POST[$param])){ if(isset($_POST[$param])) {
if('ldap_agent_password' == $param) { if('ldap_agent_password' == $param) {
OCP\Config::setAppValue('user_ldap', $param, base64_encode($_POST[$param])); OCP\Config::setAppValue('user_ldap', $param, base64_encode($_POST[$param]));
} elseif('ldap_cache_ttl' == $param) { } elseif('ldap_cache_ttl' == $param) {
@ -58,7 +58,7 @@ if ($_POST) {
// fill template // fill template
$tmpl = new OCP\Template( 'user_ldap', 'settings'); $tmpl = new OCP\Template( 'user_ldap', 'settings');
foreach($params as $param){ foreach($params as $param) {
$value = OCP\Config::getAppValue('user_ldap', $param,''); $value = OCP\Config::getAppValue('user_ldap', $param,'');
$tmpl->assign($param, $value); $tmpl->assign($param, $value);
} }

View File

@ -21,11 +21,11 @@
*/ */
class Test_Group_Ldap extends UnitTestCase { class Test_Group_Ldap extends UnitTestCase {
function setUp(){ function setUp() {
OC_Group::clearBackends(); OC_Group::clearBackends();
} }
function testSingleBackend(){ function testSingleBackend() {
OC_Group::useBackend(new OCA\user_ldap\GROUP_LDAP()); OC_Group::useBackend(new OCA\user_ldap\GROUP_LDAP());
$group_ldap = new OCA\user_ldap\GROUP_LDAP(); $group_ldap = new OCA\user_ldap\GROUP_LDAP();

View File

@ -65,7 +65,7 @@ class USER_LDAP extends lib\Access implements \OCP\UserInterface {
* *
* Check if the password is correct without logging in the user * Check if the password is correct without logging in the user
*/ */
public function checkPassword($uid, $password){ public function checkPassword($uid, $password) {
//find out dn of the user name //find out dn of the user name
$filter = \OCP\Util::mb_str_replace('%uid', $uid, $this->connection->ldapLoginFilter, 'UTF-8'); $filter = \OCP\Util::mb_str_replace('%uid', $uid, $this->connection->ldapLoginFilter, 'UTF-8');
$ldap_users = $this->fetchListOfUsers($filter, 'dn'); $ldap_users = $this->fetchListOfUsers($filter, 'dn');
@ -82,7 +82,7 @@ class USER_LDAP extends lib\Access implements \OCP\UserInterface {
//do we have a username for him/her? //do we have a username for him/her?
$ocname = $this->dn2username($dn); $ocname = $this->dn2username($dn);
if($ocname){ if($ocname) {
//update some settings, if necessary //update some settings, if necessary
$this->updateQuota($dn); $this->updateQuota($dn);
$this->updateEmail($dn); $this->updateEmail($dn);
@ -100,7 +100,7 @@ class USER_LDAP extends lib\Access implements \OCP\UserInterface {
* *
* Get a list of all users. * Get a list of all users.
*/ */
public function getUsers($search = '', $limit = 10, $offset = 0){ public function getUsers($search = '', $limit = 10, $offset = 0) {
$ldap_users = $this->connection->getFromCache('getUsers'); $ldap_users = $this->connection->getFromCache('getUsers');
if(is_null($ldap_users)) { if(is_null($ldap_users)) {
$ldap_users = $this->fetchListOfUsers($this->connection->ldapUserFilter, array($this->connection->ldapUserDisplayName, 'dn')); $ldap_users = $this->fetchListOfUsers($this->connection->ldapUserFilter, array($this->connection->ldapUserDisplayName, 'dn'));
@ -126,7 +126,7 @@ class USER_LDAP extends lib\Access implements \OCP\UserInterface {
* @param string $uid the username * @param string $uid the username
* @return boolean * @return boolean
*/ */
public function userExists($uid){ public function userExists($uid) {
if($this->connection->isCached('userExists'.$uid)) { if($this->connection->isCached('userExists'.$uid)) {
return $this->connection->getFromCache('userExists'.$uid); return $this->connection->getFromCache('userExists'.$uid);
} }
@ -187,7 +187,7 @@ class USER_LDAP extends lib\Access implements \OCP\UserInterface {
* @param string $uid the username * @param string $uid the username
* @return boolean * @return boolean
*/ */
public function getHome($uid){ public function getHome($uid) {
if($this->userExists($uid)) { if($this->userExists($uid)) {
$homedir = \OCP\Config::getUserValue($uid, 'user_ldap', 'homedir', false); $homedir = \OCP\Config::getUserValue($uid, 'user_ldap', 'homedir', false);
if(!$homedir) { if(!$homedir) {

View File

@ -22,9 +22,9 @@
*/ */
print_r($_POST); print_r($_POST);
if($_POST){ if($_POST) {
if(isset($_POST['webdav_url'])){ if(isset($_POST['webdav_url'])) {
OC_CONFIG::setValue('user_webdavauth_url', strip_tags($_POST['webdav_url'])); OC_CONFIG::setValue('user_webdavauth_url', strip_tags($_POST['webdav_url']));
} }
} }

View File

@ -50,7 +50,7 @@ class OC_USER_WEBDAVAUTH extends OC_User_Backend {
$url= 'http://'.urlencode($uid).':'.urlencode($password).'@'.$this->webdavauth_url; $url= 'http://'.urlencode($uid).':'.urlencode($password).'@'.$this->webdavauth_url;
$headers = get_headers($url); $headers = get_headers($url);
if($headers==false){ if($headers==false) {
OC_Log::write('OC_USER_WEBDAVAUTH', 'Not possible to connect to WebDAV Url: "'.$this->webdavauth_url.'" ' ,3); OC_Log::write('OC_USER_WEBDAVAUTH', 'Not possible to connect to WebDAV Url: "'.$this->webdavauth_url.'" ' ,3);
return false; return false;
@ -68,14 +68,14 @@ class OC_USER_WEBDAVAUTH extends OC_User_Backend {
/* /*
* we don´t know if a user exists without the password. so we have to return false all the time * we don´t know if a user exists without the password. so we have to return false all the time
*/ */
public function userExists( $uid ){ public function userExists( $uid ) {
return false; return false;
} }
/* /*
* we don´t know the users so all we can do it return an empty array here * we don´t know the users so all we can do it return an empty array here
*/ */
public function getUsers(){ public function getUsers() {
$returnArray = array(); $returnArray = array();
return $returnArray; return $returnArray;

View File

@ -11,7 +11,7 @@ OCP\JSON::callCheck();
$action=isset($_POST['action'])?$_POST['action']:$_GET['action']; $action=isset($_POST['action'])?$_POST['action']:$_GET['action'];
$result=false; $result=false;
switch($action){ switch($action) {
case 'getValue': case 'getValue':
$result=OC_Appconfig::getValue($_GET['app'], $_GET['key'], $_GET['defaultValue']); $result=OC_Appconfig::getValue($_GET['app'], $_GET['key'], $_GET['defaultValue']);
break; break;

View File

@ -3,12 +3,12 @@ session_write_close();
OC_App::loadApps(); OC_App::loadApps();
if ($service == 'core.css'){ if ($service == 'core.css') {
$minimizer = new OC_Minimizer_CSS(); $minimizer = new OC_Minimizer_CSS();
$files = OC_TemplateLayout::findStylesheetFiles(OC_Util::$core_styles); $files = OC_TemplateLayout::findStylesheetFiles(OC_Util::$core_styles);
$minimizer->output($files, $service); $minimizer->output($files, $service);
} }
else if ($service == 'core.js'){ else if ($service == 'core.js') {
$minimizer = new OC_Minimizer_JS(); $minimizer = new OC_Minimizer_JS();
$files = OC_TemplateLayout::findJavascriptFiles(OC_Util::$core_scripts); $files = OC_TemplateLayout::findJavascriptFiles(OC_Util::$core_scripts);
$minimizer->output($files, $service); $minimizer->output($files, $service);

View File

@ -1,5 +1,5 @@
<?php <?php
if(!isset($_)){//also provide standalone error page if(!isset($_)) {//also provide standalone error page
require_once '../../lib/base.php'; require_once '../../lib/base.php';
$tmpl = new OC_Template( '', '403', 'guest' ); $tmpl = new OC_Template( '', '403', 'guest' );

View File

@ -1,5 +1,5 @@
<?php <?php
if(!isset($_)){//also provide standalone error page if(!isset($_)) {//also provide standalone error page
require_once '../../lib/base.php'; require_once '../../lib/base.php';
$tmpl = new OC_Template( '', '404', 'guest' ); $tmpl = new OC_Template( '', '404', 'guest' );

View File

@ -4,7 +4,7 @@
<summary class="error">We're sorry, but something went terribly wrong.<br></summary> <summary class="error">We're sorry, but something went terribly wrong.<br></summary>
<p class="exception"> <p class="exception">
<?php <?php
if($_['showsysinfo'] == true){ if($_['showsysinfo'] == true) {
echo 'If you would like to support ownCloud\'s developers and report this error in our <a href="http://bugs.owncloud.org">Bugtracker</a>, please copy the following informations into the description. <br><br><textarea readonly>'; echo 'If you would like to support ownCloud\'s developers and report this error in our <a href="http://bugs.owncloud.org">Bugtracker</a>, please copy the following informations into the description. <br><br><textarea readonly>';
echo 'Message: ' . $_['message'] . "\n"; echo 'Message: ' . $_['message'] . "\n";
echo 'Error Code: ' . $_['code'] . "\n"; echo 'Error Code: ' . $_['code'] . "\n";

View File

@ -24,7 +24,7 @@
<?php foreach($_['headers'] as $header): ?> <?php foreach($_['headers'] as $header): ?>
<?php <?php
echo '<'.$header['tag'].' '; echo '<'.$header['tag'].' ';
foreach($header['attributes'] as $name=>$value){ foreach($header['attributes'] as $name=>$value) {
echo "$name='$value' "; echo "$name='$value' ";
}; };
echo '/>'; echo '/>';

View File

@ -24,7 +24,7 @@
<?php foreach($_['headers'] as $header): ?> <?php foreach($_['headers'] as $header): ?>
<?php <?php
echo '<'.$header['tag'].' '; echo '<'.$header['tag'].' ';
foreach($header['attributes'] as $name=>$value){ foreach($header['attributes'] as $name=>$value) {
echo "$name='$value' "; echo "$name='$value' ";
}; };
echo '/>'; echo '/>';
@ -33,7 +33,7 @@
<script type="text/javascript"> <script type="text/javascript">
requesttoken = '<?php echo $_['requesttoken']; ?>'; requesttoken = '<?php echo $_['requesttoken']; ?>';
OC.EventSource.requesttoken=requesttoken; OC.EventSource.requesttoken=requesttoken;
$(document).bind('ajaxSend', function(elm, xhr, s){ $(document).bind('ajaxSend', function(elm, xhr, s) {
xhr.setRequestHeader('requesttoken', requesttoken); xhr.setRequestHeader('requesttoken', requesttoken);
}); });
</script> </script>
@ -44,7 +44,7 @@
<a href="<?php echo link_to('', 'index.php'); ?>" title="" id="owncloud"><img class="svg" src="<?php echo image_path('', 'logo-wide.svg'); ?>" alt="ownCloud" /></a> <a href="<?php echo link_to('', 'index.php'); ?>" title="" id="owncloud"><img class="svg" src="<?php echo image_path('', 'logo-wide.svg'); ?>" alt="ownCloud" /></a>
<a class="header-right header-action" id="logout" href="<?php echo link_to('', 'index.php'); ?>?logout=true"><img class="svg" alt="<?php echo $l->t('Log out');?>" title="<?php echo $l->t('Log out');?>" src="<?php echo image_path('', 'actions/logout.svg'); ?>" /></a> <a class="header-right header-action" id="logout" href="<?php echo link_to('', 'index.php'); ?>?logout=true"><img class="svg" alt="<?php echo $l->t('Log out');?>" title="<?php echo $l->t('Log out');?>" src="<?php echo image_path('', 'actions/logout.svg'); ?>" /></a>
<form class="searchbox header-right" action="#" method="post"> <form class="searchbox header-right" action="#" method="post">
<input id="searchbox" class="svg" type="search" name="query" value="<?php if(isset($_POST['query'])){echo OC_Util::sanitizeHTML($_POST['query']);};?>" autocomplete="off" x-webkit-speech /> <input id="searchbox" class="svg" type="search" name="query" value="<?php if(isset($_POST['query'])) {echo OC_Util::sanitizeHTML($_POST['query']);};?>" autocomplete="off" x-webkit-speech />
</form> </form>
</div></header> </div></header>

View File

@ -77,7 +77,7 @@ if( OC::$CLI ) {
OC_BackgroundJob_Worker::doAllSteps(); OC_BackgroundJob_Worker::doAllSteps();
} }
else{ else{
if( $appmode == 'cron' ){ if( $appmode == 'cron' ) {
OC_JSON::error( array( 'data' => array( 'message' => 'Backgroundjobs are using system cron!'))); OC_JSON::error( array( 'data' => array( 'message' => 'Backgroundjobs are using system cron!')));
} }
else{ else{

View File

@ -191,7 +191,7 @@ class MDB2_Driver_Datatype_sqlite3 extends MDB2_Driver_Datatype_Common
$notnull = empty($field['notnull']) ? '' : ' NOT NULL'; $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
$unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED'; $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
$name = $db->quoteIdentifier($name, true); $name = $db->quoteIdentifier($name, true);
if($autoinc){ if($autoinc) {
return $name.' '.$this->getTypeDeclaration($field).$autoinc; return $name.' '.$this->getTypeDeclaration($field).$autoinc;
}else{ }else{
return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc; return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;

View File

@ -531,7 +531,7 @@ class MDB2_Driver_Manager_sqlite3 extends MDB2_Driver_Manager_Common
return MDB2_OK; return MDB2_OK;
} }
if (empty($changes['remove']) and empty($changes['rename']) and empty($changes['change']) ){//if only rename or add changes are required, we can use ALTER TABLE if (empty($changes['remove']) and empty($changes['rename']) and empty($changes['change']) ) {//if only rename or add changes are required, we can use ALTER TABLE
$query = ''; $query = '';
if (!empty($changes['name'])) { if (!empty($changes['name'])) {
$change_name = $db->quoteIdentifier($changes['name'], true); $change_name = $db->quoteIdentifier($changes['name'], true);

View File

@ -150,7 +150,7 @@ class MDB2_Driver_sqlite3 extends MDB2_Driver_Common
*/ */
public function escape($text, $escape_wildcards = false) public function escape($text, $escape_wildcards = false)
{ {
if($this->connection){ if($this->connection) {
return $this->connection->escapeString($text); return $this->connection->escapeString($text);
}else{ }else{
return str_replace("'","''",$text);//TODO; more return str_replace("'","''",$text);//TODO; more
@ -324,7 +324,7 @@ class MDB2_Driver_sqlite3 extends MDB2_Driver_Common
**/ **/
function connect() function connect()
{ {
if($this->connection instanceof SQLite3){ if($this->connection instanceof SQLite3) {
return MDB2_OK; return MDB2_OK;
} }
$datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
@ -351,7 +351,7 @@ class MDB2_Driver_sqlite3 extends MDB2_Driver_Common
} }
if ($database_file !== ':memory:') { if ($database_file !== ':memory:') {
if(!strpos($database_file,'.db')){ if(!strpos($database_file,'.db')) {
$database_file="$datadir/$database_file.db"; $database_file="$datadir/$database_file.db";
} }
if (!file_exists($database_file)) { if (!file_exists($database_file)) {
@ -387,7 +387,7 @@ class MDB2_Driver_sqlite3 extends MDB2_Driver_Common
$php_errormsg = ''; $php_errormsg = '';
$this->connection = new SQLite3($database_file); $this->connection = new SQLite3($database_file);
if(is_callable(array($this->connection,'busyTimeout'))){//busy timout is only available in php>=5.3 if(is_callable(array($this->connection,'busyTimeout'))) {//busy timout is only available in php>=5.3
$this->connection->busyTimeout(100); $this->connection->busyTimeout(100);
} }
$this->_lasterror = $this->connection->lastErrorMsg(); $this->_lasterror = $this->connection->lastErrorMsg();
@ -1055,7 +1055,7 @@ class MDB2_BufferedResult_sqlite3 extends MDB2_Result_sqlite3
function seek($rownum = 0) function seek($rownum = 0)
{ {
$this->result->reset(); $this->result->reset();
for($i=0;$i<$rownum;$i++){ for($i=0;$i<$rownum;$i++) {
$this->result->fetchArray(); $this->result->fetchArray();
} }
$this->rownum = $rownum - 1; $this->rownum = $rownum - 1;
@ -1093,7 +1093,7 @@ class MDB2_BufferedResult_sqlite3 extends MDB2_Result_sqlite3
{ {
$rows = 0; $rows = 0;
$this->result->reset(); $this->result->reset();
while($this->result->fetchArray()){ while($this->result->fetchArray()) {
$rows++; $rows++;
} }
$this->result->reset(); $this->result->reset();
@ -1113,8 +1113,8 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
// }}} // }}}
// {{{ function bindValue($parameter, &$value, $type = null) // {{{ function bindValue($parameter, &$value, $type = null)
private function getParamType($type){ private function getParamType($type) {
switch(strtolower($type)){ switch(strtolower($type)) {
case 'text': case 'text':
return SQLITE3_TEXT; return SQLITE3_TEXT;
case 'boolean': case 'boolean':
@ -1139,8 +1139,8 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
* *
* @access public * @access public
*/ */
function bindValue($parameter, $value, $type = null){ function bindValue($parameter, $value, $type = null) {
if($type){ if($type) {
$type=$this->getParamType($type); $type=$this->getParamType($type);
$this->statement->bindValue($parameter,$value,$type); $this->statement->bindValue($parameter,$value,$type);
}else{ }else{
@ -1162,8 +1162,8 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
* *
* @access public * @access public
*/ */
function bindParam($parameter, &$value, $type = null){ function bindParam($parameter, &$value, $type = null) {
if($type){ if($type) {
$type=$this->getParamType($type); $type=$this->getParamType($type);
$this->statement->bindParam($parameter,$value,$type); $this->statement->bindParam($parameter,$value,$type);
}else{ }else{
@ -1193,7 +1193,7 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
* a MDB2 error on failure * a MDB2 error on failure
* @access private * @access private
*/ */
function _execute($result_class = true, $result_wrap_class = false){ function _execute($result_class = true, $result_wrap_class = false) {
if (is_null($this->statement)) { if (is_null($this->statement)) {
$result =& parent::_execute($result_class, $result_wrap_class); $result =& parent::_execute($result_class, $result_wrap_class);
return $result; return $result;
@ -1313,7 +1313,7 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
} }
$values = (array)$values; $values = (array)$values;
if (!empty($values)) { if (!empty($values)) {
if(count($this->types)){ if(count($this->types)) {
$types=$this->types; $types=$this->types;
}else{ }else{
$types=null; $types=null;

View File

@ -48,12 +48,12 @@ class OC_App{
* *
* if $types is set, only apps of those types will be loaded * if $types is set, only apps of those types will be loaded
*/ */
public static function loadApps($types=null){ public static function loadApps($types=null) {
// Load the enabled apps here // Load the enabled apps here
$apps = self::getEnabledApps(); $apps = self::getEnabledApps();
// prevent app.php from printing output // prevent app.php from printing output
ob_start(); ob_start();
foreach( $apps as $app ){ foreach( $apps as $app ) {
if((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) { if((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
self::loadApp($app); self::loadApp($app);
self::$loadedApps[] = $app; self::$loadedApps[] = $app;
@ -94,12 +94,12 @@ class OC_App{
* @param string $app * @param string $app
* @param string/array $types * @param string/array $types
*/ */
public static function isType($app,$types){ public static function isType($app,$types) {
if(is_string($types)) { if(is_string($types)) {
$types=array($types); $types=array($types);
} }
$appTypes=self::getAppTypes($app); $appTypes=self::getAppTypes($app);
foreach($types as $type){ foreach($types as $type) {
if(array_search($type, $appTypes)!==false) { if(array_search($type, $appTypes)!==false) {
return true; return true;
} }
@ -112,7 +112,7 @@ class OC_App{
* @param string $app * @param string $app
* @return array * @return array
*/ */
private static function getAppTypes($app){ private static function getAppTypes($app) {
//load the cache //load the cache
if(count(self::$appTypes)==0) { if(count(self::$appTypes)==0) {
self::$appTypes=OC_Appconfig::getValues(false, 'types'); self::$appTypes=OC_Appconfig::getValues(false, 'types');
@ -128,7 +128,7 @@ class OC_App{
/** /**
* read app types from info.xml and cache them in the database * read app types from info.xml and cache them in the database
*/ */
public static function setAppTypes($app){ public static function setAppTypes($app) {
$appData=self::getAppInfo($app); $appData=self::getAppInfo($app);
if(isset($appData['types'])) { if(isset($appData['types'])) {
@ -143,13 +143,13 @@ class OC_App{
/** /**
* get all enabled apps * get all enabled apps
*/ */
public static function getEnabledApps(){ public static function getEnabledApps() {
if(!OC_Config::getValue('installed', false)) if(!OC_Config::getValue('installed', false))
return array(); return array();
$apps=array('files'); $apps=array('files');
$query = OC_DB::prepare( 'SELECT `appid` FROM `*PREFIX*appconfig` WHERE `configkey` = \'enabled\' AND `configvalue`=\'yes\'' ); $query = OC_DB::prepare( 'SELECT `appid` FROM `*PREFIX*appconfig` WHERE `configkey` = \'enabled\' AND `configvalue`=\'yes\'' );
$result=$query->execute(); $result=$query->execute();
while($row=$result->fetchRow()){ while($row=$result->fetchRow()) {
if(array_search($row['appid'], $apps)===false) { if(array_search($row['appid'], $apps)===false) {
$apps[]=$row['appid']; $apps[]=$row['appid'];
} }
@ -164,7 +164,7 @@ class OC_App{
* *
* This function checks whether or not an app is enabled. * This function checks whether or not an app is enabled.
*/ */
public static function isEnabled( $app ){ public static function isEnabled( $app ) {
if( 'files'==$app or 'yes' == OC_Appconfig::getValue( $app, 'enabled' )) { if( 'files'==$app or 'yes' == OC_Appconfig::getValue( $app, 'enabled' )) {
return true; return true;
} }
@ -179,7 +179,7 @@ class OC_App{
* *
* This function set an app as enabled in appconfig. * This function set an app as enabled in appconfig.
*/ */
public static function enable( $app ){ public static function enable( $app ) {
if(!OC_Installer::isInstalled($app)) { if(!OC_Installer::isInstalled($app)) {
// check if app is a shipped app or not. OCS apps have an integer as id, shipped apps use a string // check if app is a shipped app or not. OCS apps have an integer as id, shipped apps use a string
if(!is_numeric($app)) { if(!is_numeric($app)) {
@ -215,7 +215,7 @@ class OC_App{
* *
* This function set an app as disabled in appconfig. * This function set an app as disabled in appconfig.
*/ */
public static function disable( $app ){ public static function disable( $app ) {
// check if app is a shiped app or not. if not delete // check if app is a shiped app or not. if not delete
OC_Appconfig::setValue( $app, 'enabled', 'no' ); OC_Appconfig::setValue( $app, 'enabled', 'no' );
} }
@ -237,7 +237,7 @@ class OC_App{
* - order: integer, that influences the position of your application in * - order: integer, that influences the position of your application in
* the navigation. Lower values come first. * the navigation. Lower values come first.
*/ */
public static function addNavigationEntry( $data ){ public static function addNavigationEntry( $data ) {
$data['active']=false; $data['active']=false;
if(!isset($data['icon'])) { if(!isset($data['icon'])) {
$data['icon']=''; $data['icon']='';
@ -255,7 +255,7 @@ class OC_App{
* property from all other entries. The templates can use this for * property from all other entries. The templates can use this for
* highlighting the current position of the user. * highlighting the current position of the user.
*/ */
public static function setActiveNavigationEntry( $id ){ public static function setActiveNavigationEntry( $id ) {
self::$activeapp = $id; self::$activeapp = $id;
return true; return true;
} }
@ -267,7 +267,7 @@ class OC_App{
* This function returns the id of the active navigation entry (set by * This function returns the id of the active navigation entry (set by
* setActiveNavigationEntry * setActiveNavigationEntry
*/ */
public static function getActiveNavigationEntry(){ public static function getActiveNavigationEntry() {
return self::$activeapp; return self::$activeapp;
} }
@ -278,7 +278,7 @@ class OC_App{
* This function returns an array containing all settings pages added. The * This function returns an array containing all settings pages added. The
* entries are sorted by the key 'order' ascending. * entries are sorted by the key 'order' ascending.
*/ */
public static function getSettingsNavigation(){ public static function getSettingsNavigation() {
$l=OC_L10N::get('lib'); $l=OC_L10N::get('lib');
$settings = array(); $settings = array();
@ -320,8 +320,8 @@ class OC_App{
} }
/// This is private as well. It simply works, so don't ask for more details /// This is private as well. It simply works, so don't ask for more details
private static function proceedNavigation( $list ){ private static function proceedNavigation( $list ) {
foreach( $list as &$naventry ){ foreach( $list as &$naventry ) {
$naventry['subnavigation'] = array(); $naventry['subnavigation'] = array();
if( $naventry['id'] == self::$activeapp ) { if( $naventry['id'] == self::$activeapp ) {
$naventry['active'] = true; $naventry['active'] = true;
@ -331,7 +331,7 @@ class OC_App{
} }
} unset( $naventry ); } unset( $naventry );
usort( $list, create_function( '$a, $b', 'if( $a["order"] == $b["order"] ){return 0;}elseif( $a["order"] < $b["order"] ){return -1;}else{return 1;}' )); usort( $list, create_function( '$a, $b', 'if( $a["order"] == $b["order"] ) {return 0;}elseif( $a["order"] < $b["order"] ) {return -1;}else{return 1;}' ));
return $list; return $list;
} }
@ -388,7 +388,7 @@ class OC_App{
/** /**
* get the last version of the app, either from appinfo/version or from appinfo/info.xml * get the last version of the app, either from appinfo/version or from appinfo/info.xml
*/ */
public static function getAppVersion($appid){ public static function getAppVersion($appid) {
$file= self::getAppPath($appid).'/appinfo/version'; $file= self::getAppPath($appid).'/appinfo/version';
$version=@file_get_contents($file); $version=@file_get_contents($file);
if($version) { if($version) {
@ -405,7 +405,7 @@ class OC_App{
* @param boolean path (optional) * @param boolean path (optional)
* @returns array * @returns array
*/ */
public static function getAppInfo($appid,$path=false){ public static function getAppInfo($appid,$path=false) {
if($path) { if($path) {
$file=$appid; $file=$appid;
}else{ }else{
@ -423,18 +423,18 @@ class OC_App{
$data['info']=array(); $data['info']=array();
$data['remote']=array(); $data['remote']=array();
$data['public']=array(); $data['public']=array();
foreach($xml->children() as $child){ foreach($xml->children() as $child) {
if($child->getName()=='remote') { if($child->getName()=='remote') {
foreach($child->children() as $remote){ foreach($child->children() as $remote) {
$data['remote'][$remote->getName()]=(string)$remote; $data['remote'][$remote->getName()]=(string)$remote;
} }
}elseif($child->getName()=='public') { }elseif($child->getName()=='public') {
foreach($child->children() as $public){ foreach($child->children() as $public) {
$data['public'][$public->getName()]=(string)$public; $data['public'][$public->getName()]=(string)$public;
} }
}elseif($child->getName()=='types') { }elseif($child->getName()=='types') {
$data['types']=array(); $data['types']=array();
foreach($child->children() as $type){ foreach($child->children() as $type) {
$data['types'][]=$type->getName(); $data['types'][]=$type->getName();
} }
}elseif($child->getName()=='description') { }elseif($child->getName()=='description') {
@ -459,7 +459,7 @@ class OC_App{
* - children: array that is empty if the key 'active' is false or * - children: array that is empty if the key 'active' is false or
* contains the subentries if the key 'active' is true * contains the subentries if the key 'active' is true
*/ */
public static function getNavigation(){ public static function getNavigation() {
$navigation = self::proceedNavigation( self::$navigation ); $navigation = self::proceedNavigation( self::$navigation );
return $navigation; return $navigation;
} }
@ -468,7 +468,7 @@ class OC_App{
* get the id of loaded app * get the id of loaded app
* @return string * @return string
*/ */
public static function getCurrentApp(){ public static function getCurrentApp() {
$script=substr($_SERVER["SCRIPT_NAME"], strlen(OC::$WEBROOT)+1); $script=substr($_SERVER["SCRIPT_NAME"], strlen(OC::$WEBROOT)+1);
$topFolder=substr($script, 0, strpos($script, '/')); $topFolder=substr($script, 0, strpos($script, '/'));
if($topFolder=='apps') { if($topFolder=='apps') {
@ -483,9 +483,9 @@ class OC_App{
/** /**
* get the forms for either settings, admin or personal * get the forms for either settings, admin or personal
*/ */
public static function getForms($type){ public static function getForms($type) {
$forms=array(); $forms=array();
switch($type){ switch($type) {
case 'settings': case 'settings':
$source=self::$settingsForms; $source=self::$settingsForms;
break; break;
@ -496,7 +496,7 @@ class OC_App{
$source=self::$personalForms; $source=self::$personalForms;
break; break;
} }
foreach($source as $form){ foreach($source as $form) {
$forms[]=include $form; $forms[]=include $form;
} }
return $forms; return $forms;
@ -505,32 +505,32 @@ class OC_App{
/** /**
* register a settings form to be shown * register a settings form to be shown
*/ */
public static function registerSettings($app,$page){ public static function registerSettings($app,$page) {
self::$settingsForms[]= $app.'/'.$page.'.php'; self::$settingsForms[]= $app.'/'.$page.'.php';
} }
/** /**
* register an admin form to be shown * register an admin form to be shown
*/ */
public static function registerAdmin($app,$page){ public static function registerAdmin($app,$page) {
self::$adminForms[]= $app.'/'.$page.'.php'; self::$adminForms[]= $app.'/'.$page.'.php';
} }
/** /**
* register a personal form to be shown * register a personal form to be shown
*/ */
public static function registerPersonal($app,$page){ public static function registerPersonal($app,$page) {
self::$personalForms[]= $app.'/'.$page.'.php'; self::$personalForms[]= $app.'/'.$page.'.php';
} }
/** /**
* get a list of all apps in the apps folder * get a list of all apps in the apps folder
*/ */
public static function getAllApps(){ public static function getAllApps() {
$apps=array(); $apps=array();
foreach(OC::$APPSROOTS as $apps_dir) { foreach(OC::$APPSROOTS as $apps_dir) {
$dh=opendir($apps_dir['path']); $dh=opendir($apps_dir['path']);
while($file=readdir($dh)){ while($file=readdir($dh)) {
if($file[0]!='.' and is_file($apps_dir['path'].'/'.$file.'/appinfo/app.php')) { if($file[0]!='.' and is_file($apps_dir['path'].'/'.$file.'/appinfo/app.php')) {
$apps[]=$file; $apps[]=$file;
} }
@ -565,7 +565,7 @@ class OC_App{
* This is important if you upgrade ownCloud and have non ported 3rd * This is important if you upgrade ownCloud and have non ported 3rd
* party apps installed. * party apps installed.
*/ */
public static function checkAppsRequirements($apps = array()){ public static function checkAppsRequirements($apps = array()) {
if (empty($apps)) { if (empty($apps)) {
$apps = OC_App::getEnabledApps(); $apps = OC_App::getEnabledApps();
} }
@ -583,7 +583,7 @@ class OC_App{
/** /**
* get the installed version of all apps * get the installed version of all apps
*/ */
public static function getAppVersions(){ public static function getAppVersions() {
static $versions; static $versions;
if (isset($versions)) { // simple cache, needs to be fixed if (isset($versions)) { // simple cache, needs to be fixed
return $versions; // when function is used besides in checkUpgrade return $versions; // when function is used besides in checkUpgrade
@ -591,7 +591,7 @@ class OC_App{
$versions=array(); $versions=array();
$query = OC_DB::prepare( 'SELECT `appid`, `configvalue` FROM `*PREFIX*appconfig` WHERE `configkey` = \'installed_version\'' ); $query = OC_DB::prepare( 'SELECT `appid`, `configvalue` FROM `*PREFIX*appconfig` WHERE `configkey` = \'installed_version\'' );
$result = $query->execute(); $result = $query->execute();
while($row = $result->fetchRow()){ while($row = $result->fetchRow()) {
$versions[$row['appid']]=$row['configvalue']; $versions[$row['appid']]=$row['configvalue'];
} }
return $versions; return $versions;
@ -601,7 +601,7 @@ class OC_App{
* update the database for the app and call the update script * update the database for the app and call the update script
* @param string appid * @param string appid
*/ */
public static function updateApp($appid){ public static function updateApp($appid) {
if(file_exists(self::getAppPath($appid).'/appinfo/database.xml')) { if(file_exists(self::getAppPath($appid).'/appinfo/database.xml')) {
OC_DB::updateDbFromStructure(self::getAppPath($appid).'/appinfo/database.xml'); OC_DB::updateDbFromStructure(self::getAppPath($appid).'/appinfo/database.xml');
} }
@ -615,10 +615,10 @@ class OC_App{
//set remote/public handelers //set remote/public handelers
$appData=self::getAppInfo($appid); $appData=self::getAppInfo($appid);
foreach($appData['remote'] as $name=>$path){ foreach($appData['remote'] as $name=>$path) {
OCP\CONFIG::setAppValue('core', 'remote_'.$name, $appid.'/'.$path); OCP\CONFIG::setAppValue('core', 'remote_'.$name, $appid.'/'.$path);
} }
foreach($appData['public'] as $name=>$path){ foreach($appData['public'] as $name=>$path) {
OCP\CONFIG::setAppValue('core', 'public_'.$name, $appid.'/'.$path); OCP\CONFIG::setAppValue('core', 'public_'.$name, $appid.'/'.$path);
} }
@ -629,7 +629,7 @@ class OC_App{
* @param string appid * @param string appid
* @return OC_FilesystemView * @return OC_FilesystemView
*/ */
public static function getStorage($appid){ public static function getStorage($appid) {
if(OC_App::isEnabled($appid)) {//sanity check if(OC_App::isEnabled($appid)) {//sanity check
if(OC_User::isLoggedIn()) { if(OC_User::isLoggedIn()) {
$view = new OC_FilesystemView('/'.OC_User::getUser()); $view = new OC_FilesystemView('/'.OC_User::getUser());

View File

@ -45,13 +45,13 @@ class OC_Appconfig{
* This function returns a list of all apps that have at least one * This function returns a list of all apps that have at least one
* entry in the appconfig table. * entry in the appconfig table.
*/ */
public static function getApps(){ public static function getApps() {
// No magic in here! // No magic in here!
$query = OC_DB::prepare( 'SELECT DISTINCT `appid` FROM `*PREFIX*appconfig`' ); $query = OC_DB::prepare( 'SELECT DISTINCT `appid` FROM `*PREFIX*appconfig`' );
$result = $query->execute(); $result = $query->execute();
$apps = array(); $apps = array();
while( $row = $result->fetchRow()){ while( $row = $result->fetchRow()) {
$apps[] = $row["appid"]; $apps[] = $row["appid"];
} }
@ -66,13 +66,13 @@ class OC_Appconfig{
* This function gets all keys of an app. Please note that the values are * This function gets all keys of an app. Please note that the values are
* not returned. * not returned.
*/ */
public static function getKeys( $app ){ public static function getKeys( $app ) {
// No magic in here as well // No magic in here as well
$query = OC_DB::prepare( 'SELECT `configkey` FROM `*PREFIX*appconfig` WHERE `appid` = ?' ); $query = OC_DB::prepare( 'SELECT `configkey` FROM `*PREFIX*appconfig` WHERE `appid` = ?' );
$result = $query->execute( array( $app )); $result = $query->execute( array( $app ));
$keys = array(); $keys = array();
while( $row = $result->fetchRow()){ while( $row = $result->fetchRow()) {
$keys[] = $row["configkey"]; $keys[] = $row["configkey"];
} }
@ -89,12 +89,12 @@ class OC_Appconfig{
* This function gets a value from the appconfig table. If the key does * This function gets a value from the appconfig table. If the key does
* not exist the default value will be returnes * not exist the default value will be returnes
*/ */
public static function getValue( $app, $key, $default = null ){ public static function getValue( $app, $key, $default = null ) {
// At least some magic in here :-) // At least some magic in here :-)
$query = OC_DB::prepare( 'SELECT `configvalue` FROM `*PREFIX*appconfig` WHERE `appid` = ? AND `configkey` = ?' ); $query = OC_DB::prepare( 'SELECT `configvalue` FROM `*PREFIX*appconfig` WHERE `appid` = ? AND `configkey` = ?' );
$result = $query->execute( array( $app, $key )); $result = $query->execute( array( $app, $key ));
$row = $result->fetchRow(); $row = $result->fetchRow();
if($row){ if($row) {
return $row["configvalue"]; return $row["configvalue"];
}else{ }else{
return $default; return $default;
@ -107,7 +107,7 @@ class OC_Appconfig{
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
public static function hasKey($app,$key){ public static function hasKey($app,$key) {
$exists = self::getKeys( $app ); $exists = self::getKeys( $app );
return in_array( $key, $exists ); return in_array( $key, $exists );
} }
@ -121,9 +121,9 @@ class OC_Appconfig{
* *
* Sets a value. If the key did not exist before it will be created. * Sets a value. If the key did not exist before it will be created.
*/ */
public static function setValue( $app, $key, $value ){ public static function setValue( $app, $key, $value ) {
// Does the key exist? yes: update. No: insert // Does the key exist? yes: update. No: insert
if(! self::hasKey($app,$key)){ if(! self::hasKey($app,$key)) {
$query = OC_DB::prepare( 'INSERT INTO `*PREFIX*appconfig` ( `appid`, `configkey`, `configvalue` ) VALUES( ?, ?, ? )' ); $query = OC_DB::prepare( 'INSERT INTO `*PREFIX*appconfig` ( `appid`, `configkey`, `configvalue` ) VALUES( ?, ?, ? )' );
$query->execute( array( $app, $key, $value )); $query->execute( array( $app, $key, $value ));
} }
@ -141,7 +141,7 @@ class OC_Appconfig{
* *
* Deletes a key. * Deletes a key.
*/ */
public static function deleteKey( $app, $key ){ public static function deleteKey( $app, $key ) {
// Boring! // Boring!
$query = OC_DB::prepare( 'DELETE FROM `*PREFIX*appconfig` WHERE `appid` = ? AND `configkey` = ?' ); $query = OC_DB::prepare( 'DELETE FROM `*PREFIX*appconfig` WHERE `appid` = ? AND `configkey` = ?' );
$query->execute( array( $app, $key )); $query->execute( array( $app, $key ));
@ -156,7 +156,7 @@ class OC_Appconfig{
* *
* Removes all keys in appconfig belonging to the app. * Removes all keys in appconfig belonging to the app.
*/ */
public static function deleteApp( $app ){ public static function deleteApp( $app ) {
// Nothing special // Nothing special
$query = OC_DB::prepare( 'DELETE FROM `*PREFIX*appconfig` WHERE `appid` = ?' ); $query = OC_DB::prepare( 'DELETE FROM `*PREFIX*appconfig` WHERE `appid` = ?' );
$query->execute( array( $app )); $query->execute( array( $app ));
@ -170,14 +170,14 @@ class OC_Appconfig{
* @param key * @param key
* @return array * @return array
*/ */
public static function getValues($app,$key){ public static function getValues($app,$key) {
if($app!==false and $key!==false){ if($app!==false and $key!==false) {
return false; return false;
} }
$fields='`configvalue`'; $fields='`configvalue`';
$where='WHERE'; $where='WHERE';
$params=array(); $params=array();
if($app!==false){ if($app!==false) {
$fields.=', `configkey`'; $fields.=', `configkey`';
$where.=' `appid` = ?'; $where.=' `appid` = ?';
$params[]=$app; $params[]=$app;
@ -192,7 +192,7 @@ class OC_Appconfig{
$query=OC_DB::prepare($queryString); $query=OC_DB::prepare($queryString);
$result=$query->execute($params); $result=$query->execute($params);
$values=array(); $values=array();
while($row=$result->fetchRow()){ while($row=$result->fetchRow()) {
$values[$row[$key]]=$row['configvalue']; $values[$row[$key]]=$row['configvalue'];
} }
return $values; return $values;

View File

@ -12,15 +12,15 @@ abstract class OC_Archive{
* @param string path * @param string path
* @return OC_Archive * @return OC_Archive
*/ */
public static function open($path){ public static function open($path) {
$ext=substr($path,strrpos($path,'.')); $ext=substr($path,strrpos($path,'.'));
switch($ext){ switch($ext) {
case '.zip': case '.zip':
return new OC_Archive_ZIP($path); return new OC_Archive_ZIP($path);
case '.gz': case '.gz':
case '.bz': case '.bz':
case '.bz2': case '.bz2':
if(strpos($path,'.tar.')){ if(strpos($path,'.tar.')) {
return new OC_Archive_TAR($path); return new OC_Archive_TAR($path);
} }
break; break;
@ -118,14 +118,14 @@ abstract class OC_Archive{
* @param string source * @param string source
* @return bool * @return bool
*/ */
function addRecursive($path,$source){ function addRecursive($path,$source) {
if($dh=opendir($source)){ if($dh=opendir($source)) {
$this->addFolder($path); $this->addFolder($path);
while($file=readdir($dh)){ while($file=readdir($dh)) {
if($file=='.' or $file=='..'){ if($file=='.' or $file=='..') {
continue; continue;
} }
if(is_dir($source.'/'.$file)){ if(is_dir($source.'/'.$file)) {
$this->addRecursive($path.'/'.$file,$source.'/'.$file); $this->addRecursive($path.'/'.$file,$source.'/'.$file);
}else{ }else{
$this->addFile($path.'/'.$file,$source.'/'.$file); $this->addFile($path.'/'.$file,$source.'/'.$file);

View File

@ -21,7 +21,7 @@ class OC_Archive_TAR extends OC_Archive{
private $tar=null; private $tar=null;
private $path; private $path;
function __construct($source){ function __construct($source) {
$types=array(null,'gz','bz'); $types=array(null,'gz','bz');
$this->path=$source; $this->path=$source;
$this->tar=new Archive_Tar($source,$types[self::getTarType($source)]); $this->tar=new Archive_Tar($source,$types[self::getTarType($source)]);
@ -32,10 +32,10 @@ class OC_Archive_TAR extends OC_Archive{
* @param string file * @param string file
* @return str * @return str
*/ */
static public function getTarType($file){ static public function getTarType($file) {
if(strpos($file,'.')){ if(strpos($file,'.')) {
$extension=substr($file,strrpos($file,'.')); $extension=substr($file,strrpos($file,'.'));
switch($extension){ switch($extension) {
case 'gz': case 'gz':
case 'tgz': case 'tgz':
return self::GZIP; return self::GZIP;
@ -55,19 +55,19 @@ class OC_Archive_TAR extends OC_Archive{
* @param string path * @param string path
* @return bool * @return bool
*/ */
function addFolder($path){ function addFolder($path) {
$tmpBase=OC_Helper::tmpFolder(); $tmpBase=OC_Helper::tmpFolder();
if(substr($path,-1,1)!='/'){ if(substr($path,-1,1)!='/') {
$path.='/'; $path.='/';
} }
if($this->fileExists($path)){ if($this->fileExists($path)) {
return false; return false;
} }
$parts=explode('/',$path); $parts=explode('/',$path);
$folder=$tmpBase; $folder=$tmpBase;
foreach($parts as $part){ foreach($parts as $part) {
$folder.='/'.$part; $folder.='/'.$part;
if(!is_dir($folder)){ if(!is_dir($folder)) {
mkdir($folder); mkdir($folder);
} }
} }
@ -82,11 +82,11 @@ class OC_Archive_TAR extends OC_Archive{
* @param string source either a local file or string data * @param string source either a local file or string data
* @return bool * @return bool
*/ */
function addFile($path,$source=''){ function addFile($path,$source='') {
if($this->fileExists($path)){ if($this->fileExists($path)) {
$this->remove($path); $this->remove($path);
} }
if($source and $source[0]=='/' and file_exists($source)){ if($source and $source[0]=='/' and file_exists($source)) {
$header=array(); $header=array();
$dummy=''; $dummy='';
$this->tar->_openAppend(); $this->tar->_openAppend();
@ -104,7 +104,7 @@ class OC_Archive_TAR extends OC_Archive{
* @param string dest * @param string dest
* @return bool * @return bool
*/ */
function rename($source,$dest){ function rename($source,$dest) {
//no proper way to delete, rename entire archive, rename file and remake archive //no proper way to delete, rename entire archive, rename file and remake archive
$tmp=OCP\Files::tmpFolder(); $tmp=OCP\Files::tmpFolder();
$this->tar->extract($tmp); $this->tar->extract($tmp);
@ -118,10 +118,10 @@ class OC_Archive_TAR extends OC_Archive{
return true; return true;
} }
private function getHeader($file){ private function getHeader($file) {
$headers=$this->tar->listContent(); $headers=$this->tar->listContent();
foreach($headers as $header){ foreach($headers as $header) {
if($file==$header['filename'] or $file.'/'==$header['filename'] or '/'.$file.'/'==$header['filename'] or '/'.$file==$header['filename']){ if($file==$header['filename'] or $file.'/'==$header['filename'] or '/'.$file.'/'==$header['filename'] or '/'.$file==$header['filename']) {
return $header; return $header;
} }
} }
@ -133,7 +133,7 @@ class OC_Archive_TAR extends OC_Archive{
* @param string path * @param string path
* @return int * @return int
*/ */
function filesize($path){ function filesize($path) {
$stat=$this->getHeader($path); $stat=$this->getHeader($path);
return $stat['size']; return $stat['size'];
} }
@ -142,7 +142,7 @@ class OC_Archive_TAR extends OC_Archive{
* @param string path * @param string path
* @return int * @return int
*/ */
function mtime($path){ function mtime($path) {
$stat=$this->getHeader($path); $stat=$this->getHeader($path);
return $stat['mtime']; return $stat['mtime'];
} }
@ -152,20 +152,20 @@ class OC_Archive_TAR extends OC_Archive{
* @param path * @param path
* @return array * @return array
*/ */
function getFolder($path){ function getFolder($path) {
$files=$this->getFiles(); $files=$this->getFiles();
$folderContent=array(); $folderContent=array();
$pathLength=strlen($path); $pathLength=strlen($path);
foreach($files as $file){ foreach($files as $file) {
if($file[0]=='/'){ if($file[0]=='/') {
$file=substr($file,1); $file=substr($file,1);
} }
if(substr($file,0,$pathLength)==$path and $file!=$path){ if(substr($file,0,$pathLength)==$path and $file!=$path) {
$result=substr($file,$pathLength); $result=substr($file,$pathLength);
if($pos=strpos($result,'/')){ if($pos=strpos($result,'/')) {
$result=substr($result,0,$pos+1); $result=substr($result,0,$pos+1);
} }
if(array_search($result,$folderContent)===false){ if(array_search($result,$folderContent)===false) {
$folderContent[]=$result; $folderContent[]=$result;
} }
} }
@ -176,13 +176,13 @@ class OC_Archive_TAR extends OC_Archive{
*get all files in the archive *get all files in the archive
* @return array * @return array
*/ */
function getFiles(){ function getFiles() {
if($this->fileList){ if($this->fileList) {
return $this->fileList; return $this->fileList;
} }
$headers=$this->tar->listContent(); $headers=$this->tar->listContent();
$files=array(); $files=array();
foreach($headers as $header){ foreach($headers as $header) {
$files[]=$header['filename']; $files[]=$header['filename'];
} }
$this->fileList=$files; $this->fileList=$files;
@ -193,7 +193,7 @@ class OC_Archive_TAR extends OC_Archive{
* @param string path * @param string path
* @return string * @return string
*/ */
function getFile($path){ function getFile($path) {
return $this->tar->extractInString($path); return $this->tar->extractInString($path);
} }
/** /**
@ -202,17 +202,17 @@ class OC_Archive_TAR extends OC_Archive{
* @param string dest * @param string dest
* @return bool * @return bool
*/ */
function extractFile($path,$dest){ function extractFile($path,$dest) {
$tmp=OCP\Files::tmpFolder(); $tmp=OCP\Files::tmpFolder();
if(!$this->fileExists($path)){ if(!$this->fileExists($path)) {
return false; return false;
} }
if($this->fileExists('/'.$path)){ if($this->fileExists('/'.$path)) {
$success=$this->tar->extractList(array('/'.$path),$tmp); $success=$this->tar->extractList(array('/'.$path),$tmp);
}else{ }else{
$success=$this->tar->extractList(array($path),$tmp); $success=$this->tar->extractList(array($path),$tmp);
} }
if($success){ if($success) {
rename($tmp.$path,$dest); rename($tmp.$path,$dest);
} }
OCP\Files::rmdirr($tmp); OCP\Files::rmdirr($tmp);
@ -224,7 +224,7 @@ class OC_Archive_TAR extends OC_Archive{
* @param string dest * @param string dest
* @return bool * @return bool
*/ */
function extract($dest){ function extract($dest) {
return $this->tar->extract($dest); return $this->tar->extract($dest);
} }
/** /**
@ -232,23 +232,23 @@ class OC_Archive_TAR extends OC_Archive{
* @param string path * @param string path
* @return bool * @return bool
*/ */
function fileExists($path){ function fileExists($path) {
$files=$this->getFiles(); $files=$this->getFiles();
if((array_search($path,$files)!==false) or (array_search($path.'/',$files)!==false)){ if((array_search($path,$files)!==false) or (array_search($path.'/',$files)!==false)) {
return true; return true;
}else{ }else{
$folderPath=$path; $folderPath=$path;
if(substr($folderPath,-1,1)!='/'){ if(substr($folderPath,-1,1)!='/') {
$folderPath.='/'; $folderPath.='/';
} }
$pathLength=strlen($folderPath); $pathLength=strlen($folderPath);
foreach($files as $file){ foreach($files as $file) {
if(strlen($file)>$pathLength and substr($file,0,$pathLength)==$folderPath){ if(strlen($file)>$pathLength and substr($file,0,$pathLength)==$folderPath) {
return true; return true;
} }
} }
} }
if($path[0]!='/'){//not all programs agree on the use of a leading / if($path[0]!='/') {//not all programs agree on the use of a leading /
return $this->fileExists('/'.$path); return $this->fileExists('/'.$path);
}else{ }else{
return false; return false;
@ -260,8 +260,8 @@ class OC_Archive_TAR extends OC_Archive{
* @param string path * @param string path
* @return bool * @return bool
*/ */
function remove($path){ function remove($path) {
if(!$this->fileExists($path)){ if(!$this->fileExists($path)) {
return false; return false;
} }
$this->fileList=false; $this->fileList=false;
@ -281,19 +281,19 @@ class OC_Archive_TAR extends OC_Archive{
* @param string mode * @param string mode
* @return resource * @return resource
*/ */
function getStream($path,$mode){ function getStream($path,$mode) {
if(strrpos($path,'.')!==false){ if(strrpos($path,'.')!==false) {
$ext=substr($path,strrpos($path,'.')); $ext=substr($path,strrpos($path,'.'));
}else{ }else{
$ext=''; $ext='';
} }
$tmpFile=OCP\Files::tmpFile($ext); $tmpFile=OCP\Files::tmpFile($ext);
if($this->fileExists($path)){ if($this->fileExists($path)) {
$this->extractFile($path,$tmpFile); $this->extractFile($path,$tmpFile);
}elseif($mode=='r' or $mode=='rb'){ }elseif($mode=='r' or $mode=='rb') {
return false; return false;
} }
if($mode=='r' or $mode=='rb'){ if($mode=='r' or $mode=='rb') {
return fopen($tmpFile,$mode); return fopen($tmpFile,$mode);
}else{ }else{
OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack'); OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack');
@ -306,8 +306,8 @@ class OC_Archive_TAR extends OC_Archive{
/** /**
* write back temporary files * write back temporary files
*/ */
function writeBack($tmpFile){ function writeBack($tmpFile) {
if(isset(self::$tempFiles[$tmpFile])){ if(isset(self::$tempFiles[$tmpFile])) {
$this->addFile(self::$tempFiles[$tmpFile],$tmpFile); $this->addFile(self::$tempFiles[$tmpFile],$tmpFile);
unlink($tmpFile); unlink($tmpFile);
} }
@ -316,8 +316,8 @@ class OC_Archive_TAR extends OC_Archive{
/** /**
* reopen the archive to ensure everything is written * reopen the archive to ensure everything is written
*/ */
private function reopen(){ private function reopen() {
if($this->tar){ if($this->tar) {
$this->tar->_close(); $this->tar->_close();
$this->tar=null; $this->tar=null;
} }

View File

@ -13,10 +13,10 @@ class OC_Archive_ZIP extends OC_Archive{
private $zip=null; private $zip=null;
private $path; private $path;
function __construct($source){ function __construct($source) {
$this->path=$source; $this->path=$source;
$this->zip=new ZipArchive(); $this->zip=new ZipArchive();
if($this->zip->open($source,ZipArchive::CREATE)){ if($this->zip->open($source,ZipArchive::CREATE)) {
}else{ }else{
OCP\Util::writeLog('files_archive','Error while opening archive '.$source,OCP\Util::WARN); OCP\Util::writeLog('files_archive','Error while opening archive '.$source,OCP\Util::WARN);
} }
@ -26,7 +26,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path * @param string path
* @return bool * @return bool
*/ */
function addFolder($path){ function addFolder($path) {
return $this->zip->addEmptyDir($path); return $this->zip->addEmptyDir($path);
} }
/** /**
@ -35,13 +35,13 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string source either a local file or string data * @param string source either a local file or string data
* @return bool * @return bool
*/ */
function addFile($path,$source=''){ function addFile($path,$source='') {
if($source and $source[0]=='/' and file_exists($source)){ if($source and $source[0]=='/' and file_exists($source)) {
$result=$this->zip->addFile($source,$path); $result=$this->zip->addFile($source,$path);
}else{ }else{
$result=$this->zip->addFromString($path,$source); $result=$this->zip->addFromString($path,$source);
} }
if($result){ if($result) {
$this->zip->close();//close and reopen to save the zip $this->zip->close();//close and reopen to save the zip
$this->zip->open($this->path); $this->zip->open($this->path);
} }
@ -53,7 +53,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string dest * @param string dest
* @return bool * @return bool
*/ */
function rename($source,$dest){ function rename($source,$dest) {
$source=$this->stripPath($source); $source=$this->stripPath($source);
$dest=$this->stripPath($dest); $dest=$this->stripPath($dest);
$this->zip->renameName($source,$dest); $this->zip->renameName($source,$dest);
@ -63,7 +63,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path * @param string path
* @return int * @return int
*/ */
function filesize($path){ function filesize($path) {
$stat=$this->zip->statName($path); $stat=$this->zip->statName($path);
return $stat['size']; return $stat['size'];
} }
@ -72,7 +72,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path * @param string path
* @return int * @return int
*/ */
function mtime($path){ function mtime($path) {
return filemtime($this->path); return filemtime($this->path);
} }
/** /**
@ -80,13 +80,13 @@ class OC_Archive_ZIP extends OC_Archive{
* @param path * @param path
* @return array * @return array
*/ */
function getFolder($path){ function getFolder($path) {
$files=$this->getFiles(); $files=$this->getFiles();
$folderContent=array(); $folderContent=array();
$pathLength=strlen($path); $pathLength=strlen($path);
foreach($files as $file){ foreach($files as $file) {
if(substr($file,0,$pathLength)==$path and $file!=$path){ if(substr($file,0,$pathLength)==$path and $file!=$path) {
if(strrpos(substr($file,0,-1),'/')<=$pathLength){ if(strrpos(substr($file,0,-1),'/')<=$pathLength) {
$folderContent[]=substr($file,$pathLength); $folderContent[]=substr($file,$pathLength);
} }
} }
@ -97,10 +97,10 @@ class OC_Archive_ZIP extends OC_Archive{
*get all files in the archive *get all files in the archive
* @return array * @return array
*/ */
function getFiles(){ function getFiles() {
$fileCount=$this->zip->numFiles; $fileCount=$this->zip->numFiles;
$files=array(); $files=array();
for($i=0;$i<$fileCount;$i++){ for($i=0;$i<$fileCount;$i++) {
$files[]=$this->zip->getNameIndex($i); $files[]=$this->zip->getNameIndex($i);
} }
return $files; return $files;
@ -110,7 +110,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path * @param string path
* @return string * @return string
*/ */
function getFile($path){ function getFile($path) {
return $this->zip->getFromName($path); return $this->zip->getFromName($path);
} }
/** /**
@ -119,7 +119,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string dest * @param string dest
* @return bool * @return bool
*/ */
function extractFile($path,$dest){ function extractFile($path,$dest) {
$fp = $this->zip->getStream($path); $fp = $this->zip->getStream($path);
file_put_contents($dest,$fp); file_put_contents($dest,$fp);
} }
@ -129,7 +129,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string dest * @param string dest
* @return bool * @return bool
*/ */
function extract($dest){ function extract($dest) {
return $this->zip->extractTo($dest); return $this->zip->extractTo($dest);
} }
/** /**
@ -137,7 +137,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path * @param string path
* @return bool * @return bool
*/ */
function fileExists($path){ function fileExists($path) {
return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false); return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
} }
/** /**
@ -145,8 +145,8 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path * @param string path
* @return bool * @return bool
*/ */
function remove($path){ function remove($path) {
if($this->fileExists($path.'/')){ if($this->fileExists($path.'/')) {
return $this->zip->deleteName($path.'/'); return $this->zip->deleteName($path.'/');
}else{ }else{
return $this->zip->deleteName($path); return $this->zip->deleteName($path);
@ -158,18 +158,18 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string mode * @param string mode
* @return resource * @return resource
*/ */
function getStream($path,$mode){ function getStream($path,$mode) {
if($mode=='r' or $mode=='rb'){ if($mode=='r' or $mode=='rb') {
return $this->zip->getStream($path); return $this->zip->getStream($path);
}else{//since we cant directly get a writable stream, make a temp copy of the file and put it back in the archive when the stream is closed }else{//since we cant directly get a writable stream, make a temp copy of the file and put it back in the archive when the stream is closed
if(strrpos($path,'.')!==false){ if(strrpos($path,'.')!==false) {
$ext=substr($path,strrpos($path,'.')); $ext=substr($path,strrpos($path,'.'));
}else{ }else{
$ext=''; $ext='';
} }
$tmpFile=OCP\Files::tmpFile($ext); $tmpFile=OCP\Files::tmpFile($ext);
OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack'); OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack');
if($this->fileExists($path)){ if($this->fileExists($path)) {
$this->extractFile($path,$tmpFile); $this->extractFile($path,$tmpFile);
} }
self::$tempFiles[$tmpFile]=$path; self::$tempFiles[$tmpFile]=$path;
@ -181,15 +181,15 @@ class OC_Archive_ZIP extends OC_Archive{
/** /**
* write back temporary files * write back temporary files
*/ */
function writeBack($tmpFile){ function writeBack($tmpFile) {
if(isset(self::$tempFiles[$tmpFile])){ if(isset(self::$tempFiles[$tmpFile])) {
$this->addFile(self::$tempFiles[$tmpFile],$tmpFile); $this->addFile(self::$tempFiles[$tmpFile],$tmpFile);
unlink($tmpFile); unlink($tmpFile);
} }
} }
private function stripPath($path){ private function stripPath($path) {
if(!$path || $path[0]=='/'){ if(!$path || $path[0]=='/') {
return substr($path,1); return substr($path,1);
}else{ }else{
return $path; return $path;

View File

@ -29,7 +29,7 @@ class OC_BackgroundJob_QueuedTask{
* @param $id ID of the task * @param $id ID of the task
* @return associative array * @return associative array
*/ */
public static function find( $id ){ public static function find( $id ) {
$stmt = OC_DB::prepare( 'SELECT * FROM `*PREFIX*queuedtasks` WHERE `id` = ?' ); $stmt = OC_DB::prepare( 'SELECT * FROM `*PREFIX*queuedtasks` WHERE `id` = ?' );
$result = $stmt->execute(array($id)); $result = $stmt->execute(array($id));
return $result->fetchRow(); return $result->fetchRow();
@ -39,14 +39,14 @@ class OC_BackgroundJob_QueuedTask{
* @brief Gets all queued tasks * @brief Gets all queued tasks
* @return array with associative arrays * @return array with associative arrays
*/ */
public static function all(){ public static function all() {
// Array for objects // Array for objects
$return = array(); $return = array();
// Get Data // Get Data
$stmt = OC_DB::prepare( 'SELECT * FROM `*PREFIX*queuedtasks`' ); $stmt = OC_DB::prepare( 'SELECT * FROM `*PREFIX*queuedtasks`' );
$result = $stmt->execute(array()); $result = $stmt->execute(array());
while( $row = $result->fetchRow()){ while( $row = $result->fetchRow()) {
$return[] = $row; $return[] = $row;
} }
@ -58,14 +58,14 @@ class OC_BackgroundJob_QueuedTask{
* @param $app app name * @param $app app name
* @return array with associative arrays * @return array with associative arrays
*/ */
public static function whereAppIs( $app ){ public static function whereAppIs( $app ) {
// Array for objects // Array for objects
$return = array(); $return = array();
// Get Data // Get Data
$stmt = OC_DB::prepare( 'SELECT * FROM `*PREFIX*queuedtasks` WHERE `app` = ?' ); $stmt = OC_DB::prepare( 'SELECT * FROM `*PREFIX*queuedtasks` WHERE `app` = ?' );
$result = $stmt->execute(array($app)); $result = $stmt->execute(array($app));
while( $row = $result->fetchRow()){ while( $row = $result->fetchRow()) {
$return[] = $row; $return[] = $row;
} }
@ -81,7 +81,7 @@ class OC_BackgroundJob_QueuedTask{
* @param $parameters all useful data as text * @param $parameters all useful data as text
* @return id of task * @return id of task
*/ */
public static function add( $app, $klass, $method, $parameters ){ public static function add( $app, $klass, $method, $parameters ) {
$stmt = OC_DB::prepare( 'INSERT INTO `*PREFIX*queuedtasks` (`app`, `klass`, `method`, `parameters`) VALUES(?,?,?,?)' ); $stmt = OC_DB::prepare( 'INSERT INTO `*PREFIX*queuedtasks` (`app`, `klass`, `method`, `parameters`) VALUES(?,?,?,?)' );
$result = $stmt->execute(array($app, $klass, $method, $parameters )); $result = $stmt->execute(array($app, $klass, $method, $parameters ));
@ -95,7 +95,7 @@ class OC_BackgroundJob_QueuedTask{
* *
* Deletes a report * Deletes a report
*/ */
public static function delete( $id ){ public static function delete( $id ) {
$stmt = OC_DB::prepare( 'DELETE FROM `*PREFIX*queuedtasks` WHERE `id` = ?' ); $stmt = OC_DB::prepare( 'DELETE FROM `*PREFIX*queuedtasks` WHERE `id` = ?' );
$result = $stmt->execute(array($id)); $result = $stmt->execute(array($id));

View File

@ -32,7 +32,7 @@ class OC_BackgroundJob_RegularTask{
* @param $method method name * @param $method method name
* @return true * @return true
*/ */
static public function register( $klass, $method ){ static public function register( $klass, $method ) {
// Create the data structure // Create the data structure
self::$registered["$klass-$method"] = array( $klass, $method ); self::$registered["$klass-$method"] = array( $klass, $method );
@ -46,7 +46,7 @@ class OC_BackgroundJob_RegularTask{
* *
* key is string "$klass-$method", value is array( $klass, $method ) * key is string "$klass-$method", value is array( $klass, $method )
*/ */
static public function all(){ static public function all() {
return self::$registered; return self::$registered;
} }
} }

View File

@ -34,14 +34,14 @@ class OC_BackgroundJob_Worker{
* This method should be called by cli scripts that do not let the user * This method should be called by cli scripts that do not let the user
* wait. * wait.
*/ */
public static function doAllSteps(){ public static function doAllSteps() {
// Do our regular work // Do our regular work
$lasttask = OC_Appconfig::getValue( 'core', 'backgroundjobs_task', '' ); $lasttask = OC_Appconfig::getValue( 'core', 'backgroundjobs_task', '' );
$regular_tasks = OC_BackgroundJob_RegularTask::all(); $regular_tasks = OC_BackgroundJob_RegularTask::all();
ksort( $regular_tasks ); ksort( $regular_tasks );
foreach( $regular_tasks as $key => $value ){ foreach( $regular_tasks as $key => $value ) {
if( strcmp( $key, $lasttask ) > 0 ){ if( strcmp( $key, $lasttask ) > 0 ) {
// Set "restart here" config value // Set "restart here" config value
OC_Appconfig::setValue( 'core', 'backgroundjobs_task', $key ); OC_Appconfig::setValue( 'core', 'backgroundjobs_task', $key );
call_user_func( $value ); call_user_func( $value );
@ -52,7 +52,7 @@ class OC_BackgroundJob_Worker{
// Do our queued tasks // Do our queued tasks
$queued_tasks = OC_BackgroundJob_QueuedTask::all(); $queued_tasks = OC_BackgroundJob_QueuedTask::all();
foreach( $queued_tasks as $task ){ foreach( $queued_tasks as $task ) {
OC_BackgroundJob_QueuedTask::delete( $task['id'] ); OC_BackgroundJob_QueuedTask::delete( $task['id'] );
call_user_func( array( $task['klass'], $task['method'] ), $task['parameters'] ); call_user_func( array( $task['klass'], $task['method'] ), $task['parameters'] );
} }
@ -68,10 +68,10 @@ class OC_BackgroundJob_Worker{
* with the next step. This method should be used by webcron and ajax * with the next step. This method should be used by webcron and ajax
* services. * services.
*/ */
public static function doNextStep(){ public static function doNextStep() {
$laststep = OC_Appconfig::getValue( 'core', 'backgroundjobs_step', 'regular_tasks' ); $laststep = OC_Appconfig::getValue( 'core', 'backgroundjobs_step', 'regular_tasks' );
if( $laststep == 'regular_tasks' ){ if( $laststep == 'regular_tasks' ) {
// get last app // get last app
$lasttask = OC_Appconfig::getValue( 'core', 'backgroundjobs_task', '' ); $lasttask = OC_Appconfig::getValue( 'core', 'backgroundjobs_task', '' );
@ -81,8 +81,8 @@ class OC_BackgroundJob_Worker{
$done = false; $done = false;
// search for next background job // search for next background job
foreach( $regular_tasks as $key => $value ){ foreach( $regular_tasks as $key => $value ) {
if( strcmp( $key, $lasttask ) > 0 ){ if( strcmp( $key, $lasttask ) > 0 ) {
OC_Appconfig::setValue( 'core', 'backgroundjobs_task', $key ); OC_Appconfig::setValue( 'core', 'backgroundjobs_task', $key );
$done = true; $done = true;
call_user_func( $value ); call_user_func( $value );
@ -90,14 +90,14 @@ class OC_BackgroundJob_Worker{
} }
} }
if( $done == false ){ if( $done == false ) {
// Next time load queued tasks // Next time load queued tasks
OC_Appconfig::setValue( 'core', 'backgroundjobs_step', 'queued_tasks' ); OC_Appconfig::setValue( 'core', 'backgroundjobs_step', 'queued_tasks' );
} }
} }
else{ else{
$tasks = OC_BackgroundJob_QueuedTask::all(); $tasks = OC_BackgroundJob_QueuedTask::all();
if( count( $tasks )){ if( count( $tasks )) {
$task = $tasks[0]; $task = $tasks[0];
// delete job before we execute it. This prevents endless loops // delete job before we execute it. This prevents endless loops
// of failing jobs. // of failing jobs.

View File

@ -70,7 +70,7 @@ class OC{
/** /**
* SPL autoload * SPL autoload
*/ */
public static function autoload($className){ public static function autoload($className) {
if(array_key_exists($className, OC::$CLASSPATH)) { if(array_key_exists($className, OC::$CLASSPATH)) {
/** @TODO: Remove this when necessary /** @TODO: Remove this when necessary
Remove "apps/" from inclusion path for smooth migration to mutli app dir Remove "apps/" from inclusion path for smooth migration to mutli app dir
@ -102,7 +102,7 @@ class OC{
return false; return false;
} }
public static function initPaths(){ public static function initPaths() {
// calculate the root directories // calculate the root directories
OC::$SERVERROOT=str_replace("\\", '/', substr(__FILE__, 0, -13)); OC::$SERVERROOT=str_replace("\\", '/', substr(__FILE__, 0, -13));
OC::$SUBURI= str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT))); OC::$SUBURI= str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
@ -260,7 +260,7 @@ class OC{
session_start(); session_start();
} }
public static function init(){ public static function init() {
// register autoloader // register autoloader
spl_autoload_register(array('OC','autoload')); spl_autoload_register(array('OC','autoload'));
setlocale(LC_ALL, 'en_US.UTF-8'); setlocale(LC_ALL, 'en_US.UTF-8');
@ -556,7 +556,7 @@ class OC{
protected static function tryBasicAuthLogin() { protected static function tryBasicAuthLogin() {
if (!isset($_SERVER["PHP_AUTH_USER"]) if (!isset($_SERVER["PHP_AUTH_USER"])
|| !isset($_SERVER["PHP_AUTH_PW"])){ || !isset($_SERVER["PHP_AUTH_PW"])) {
return false; return false;
} }
OC_App::loadApps(array('authentication')); OC_App::loadApps(array('authentication'));

2
lib/cache/apc.php vendored
View File

@ -43,7 +43,7 @@ class OC_Cache_APC {
return apc_delete($this->getNamespace().$key); return apc_delete($this->getNamespace().$key);
} }
public function clear($prefix=''){ public function clear($prefix='') {
$ns = $this->getNamespace().$prefix; $ns = $this->getNamespace().$prefix;
$cache = apc_cache_info('user'); $cache = apc_cache_info('user');
foreach($cache['cache_list'] as $entry) { foreach($cache['cache_list'] as $entry) {

View File

@ -46,7 +46,7 @@ class OC_Cache_Broker {
return $this->slow_cache->remove($key); return $this->slow_cache->remove($key);
} }
public function clear($prefix=''){ public function clear($prefix='') {
$this->fast_cache->clear($prefix); $this->fast_cache->clear($prefix);
$this->slow_cache->clear($prefix); $this->slow_cache->clear($prefix);
} }

12
lib/cache/file.php vendored
View File

@ -13,7 +13,7 @@ class OC_Cache_File{
if (isset($this->storage)) { if (isset($this->storage)) {
return $this->storage; return $this->storage;
} }
if(OC_User::isLoggedIn()){ if(OC_User::isLoggedIn()) {
$subdir = 'cache'; $subdir = 'cache';
$view = new OC_FilesystemView('/'.OC_User::getUser()); $view = new OC_FilesystemView('/'.OC_User::getUser());
if(!$view->file_exists($subdir)) { if(!$view->file_exists($subdir)) {
@ -61,18 +61,18 @@ class OC_Cache_File{
public function remove($key) { public function remove($key) {
$storage = $this->getStorage(); $storage = $this->getStorage();
if(!$storage){ if(!$storage) {
return false; return false;
} }
return $storage->unlink($key); return $storage->unlink($key);
} }
public function clear($prefix=''){ public function clear($prefix='') {
$storage = $this->getStorage(); $storage = $this->getStorage();
if($storage and $storage->is_dir('/')){ if($storage and $storage->is_dir('/')) {
$dh=$storage->opendir('/'); $dh=$storage->opendir('/');
while($file=readdir($dh)){ while($file=readdir($dh)) {
if($file!='.' and $file!='..' and ($prefix==='' || strpos($file, $prefix) === 0)){ if($file!='.' and $file!='..' and ($prefix==='' || strpos($file, $prefix) === 0)) {
$storage->unlink('/'.$file); $storage->unlink('/'.$file);
} }
} }

View File

@ -57,20 +57,20 @@ class OC_Cache_FileGlobal{
public function remove($key) { public function remove($key) {
$cache_dir = self::getCacheDir(); $cache_dir = self::getCacheDir();
if(!$cache_dir){ if(!$cache_dir) {
return false; return false;
} }
$key = $this->fixKey($key); $key = $this->fixKey($key);
return unlink($cache_dir.$key); return unlink($cache_dir.$key);
} }
public function clear($prefix=''){ public function clear($prefix='') {
$cache_dir = self::getCacheDir(); $cache_dir = self::getCacheDir();
$prefix = $this->fixKey($prefix); $prefix = $this->fixKey($prefix);
if($cache_dir and is_dir($cache_dir)){ if($cache_dir and is_dir($cache_dir)) {
$dh=opendir($cache_dir); $dh=opendir($cache_dir);
while($file=readdir($dh)){ while($file=readdir($dh)) {
if($file!='.' and $file!='..' and ($prefix==='' || strpos($file, $prefix) === 0)){ if($file!='.' and $file!='..' and ($prefix==='' || strpos($file, $prefix) === 0)) {
unlink($cache_dir.$file); unlink($cache_dir.$file);
} }
} }

View File

@ -28,7 +28,7 @@ class OC_Cache_XCache {
} }
public function set($key, $value, $ttl=0) { public function set($key, $value, $ttl=0) {
if($ttl>0){ if($ttl>0) {
return xcache_set($this->getNamespace().$key,$value,$ttl); return xcache_set($this->getNamespace().$key,$value,$ttl);
}else{ }else{
return xcache_set($this->getNamespace().$key,$value); return xcache_set($this->getNamespace().$key,$value);
@ -43,7 +43,7 @@ class OC_Cache_XCache {
return xcache_unset($this->getNamespace().$key); return xcache_unset($this->getNamespace().$key);
} }
public function clear($prefix=''){ public function clear($prefix='') {
xcache_unset_by_prefix($this->getNamespace().$prefix); xcache_unset_by_prefix($this->getNamespace().$prefix);
return true; return true;
} }

View File

@ -52,7 +52,7 @@ class OC_Config{
* This function returns all keys saved in config.php. Please note that it * This function returns all keys saved in config.php. Please note that it
* does not return the values. * does not return the values.
*/ */
public static function getKeys(){ public static function getKeys() {
self::readData(); self::readData();
return array_keys( self::$cache ); return array_keys( self::$cache );
@ -67,7 +67,7 @@ class OC_Config{
* This function gets the value from config.php. If it does not exist, * This function gets the value from config.php. If it does not exist,
* $default will be returned. * $default will be returned.
*/ */
public static function getValue( $key, $default = null ){ public static function getValue( $key, $default = null ) {
self::readData(); self::readData();
if( array_key_exists( $key, self::$cache )) { if( array_key_exists( $key, self::$cache )) {
@ -86,7 +86,7 @@ class OC_Config{
* This function sets the value and writes the config.php. If the file can * This function sets the value and writes the config.php. If the file can
* not be written, false will be returned. * not be written, false will be returned.
*/ */
public static function setValue( $key, $value ){ public static function setValue( $key, $value ) {
self::readData(); self::readData();
// Add change // Add change
@ -105,7 +105,7 @@ class OC_Config{
* This function removes a key from the config.php. If owncloud has no * This function removes a key from the config.php. If owncloud has no
* write access to config.php, the function will return false. * write access to config.php, the function will return false.
*/ */
public static function deleteKey( $key ){ public static function deleteKey( $key ) {
self::readData(); self::readData();
if( array_key_exists( $key, self::$cache )) { if( array_key_exists( $key, self::$cache )) {
@ -125,7 +125,7 @@ class OC_Config{
* *
* Reads the config file and saves it to the cache * Reads the config file and saves it to the cache
*/ */
private static function readData(){ private static function readData() {
if( self::$init ) { if( self::$init ) {
return true; return true;
} }
@ -153,7 +153,7 @@ class OC_Config{
* Saves the config to the config file. * Saves the config to the config file.
* *
*/ */
public static function writeData(){ public static function writeData() {
// Create a php file ... // Create a php file ...
$content = "<?php\n\$CONFIG = "; $content = "<?php\n\$CONFIG = ";
$content .= var_export(self::$cache, true); $content .= var_export(self::$cache, true);

View File

@ -30,13 +30,13 @@ class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic {
* *
* @return bool * @return bool
*/ */
protected function validateUserPass($username, $password){ protected function validateUserPass($username, $password) {
if (OC_User::isLoggedIn()) { if (OC_User::isLoggedIn()) {
OC_Util::setupFS($username); OC_Util::setupFS($username);
return true; return true;
} else { } else {
OC_Util::setUpFS();//login hooks may need early access to the filesystem OC_Util::setUpFS();//login hooks may need early access to the filesystem
if(OC_User::login($username,$password)){ if(OC_User::login($username,$password)) {
OC_Util::setUpFS($username); OC_Util::setUpFS($username);
return true; return true;
} }

View File

@ -119,7 +119,7 @@ class OC_Connector_Sabre_Directory extends OC_Connector_Sabre_Node implements Sa
$paths[] = $this->path.'/'.$info['name']; $paths[] = $this->path.'/'.$info['name'];
} }
$properties = array_fill_keys($paths, array()); $properties = array_fill_keys($paths, array());
if(count($paths)>0){ if(count($paths)>0) {
$placeholders = join(',', array_fill(0, count($paths), '?')); $placeholders = join(',', array_fill(0, count($paths), '?'));
$query = OC_DB::prepare( 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ?' . ' AND `propertypath` IN ('.$placeholders.')' ); $query = OC_DB::prepare( 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ?' . ' AND `propertypath` IN ('.$placeholders.')' );
array_unshift($paths, OC_User::getUser()); // prepend userid array_unshift($paths, OC_User::getUser()); // prepend userid

View File

@ -77,7 +77,7 @@ class OC_Connector_Sabre_Locks extends Sabre_DAV_Locks_Backend_Abstract {
$result = $stmt->execute( $params ); $result = $stmt->execute( $params );
$lockList = array(); $lockList = array();
while( $row = $result->fetchRow()){ while( $row = $result->fetchRow()) {
$lockInfo = new Sabre_DAV_Locks_LockInfo(); $lockInfo = new Sabre_DAV_Locks_LockInfo();
$lockInfo->owner = $row['owner']; $lockInfo->owner = $row['owner'];

View File

@ -145,7 +145,7 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr
$propertyName = preg_replace("/^{.*}/", "", $propertyName); // remove leading namespace from property name $propertyName = preg_replace("/^{.*}/", "", $propertyName); // remove leading namespace from property name
// If it was null, we need to delete the property // If it was null, we need to delete the property
if (is_null($propertyValue)) { if (is_null($propertyValue)) {
if(array_key_exists( $propertyName, $existing )){ if(array_key_exists( $propertyName, $existing )) {
$query = OC_DB::prepare( 'DELETE FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?' ); $query = OC_DB::prepare( 'DELETE FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?' );
$query->execute( array( OC_User::getUser(), $this->path, $propertyName )); $query->execute( array( OC_User::getUser(), $this->path, $propertyName ));
} }
@ -154,7 +154,7 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr
if( strcmp( $propertyName, "lastmodified") === 0) { if( strcmp( $propertyName, "lastmodified") === 0) {
$this->touch($propertyValue); $this->touch($propertyValue);
} else { } else {
if(!array_key_exists( $propertyName, $existing )){ if(!array_key_exists( $propertyName, $existing )) {
$query = OC_DB::prepare( 'INSERT INTO `*PREFIX*properties` (`userid`,`propertypath`,`propertyname`,`propertyvalue`) VALUES(?,?,?,?)' ); $query = OC_DB::prepare( 'INSERT INTO `*PREFIX*properties` (`userid`,`propertypath`,`propertyname`,`propertyvalue`) VALUES(?,?,?,?)' );
$query->execute( array( OC_User::getUser(), $this->path, $propertyName,$propertyValue )); $query->execute( array( OC_User::getUser(), $this->path, $propertyName,$propertyValue ));
} else { } else {
@ -186,13 +186,13 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr
$result = $query->execute( array( OC_User::getUser(), $this->path )); $result = $query->execute( array( OC_User::getUser(), $this->path ));
$this->property_cache = array(); $this->property_cache = array();
while( $row = $result->fetchRow()){ while( $row = $result->fetchRow()) {
$this->property_cache[$row['propertyname']] = $row['propertyvalue']; $this->property_cache[$row['propertyname']] = $row['propertyvalue'];
} }
} }
// if the array was empty, we need to return everything // if the array was empty, we need to return everything
if(count($properties) == 0){ if(count($properties) == 0) {
return $this->property_cache; return $this->property_cache;
} }

View File

@ -115,6 +115,6 @@ class OC_Connector_Sabre_Principal implements Sabre_DAVACL_IPrincipalBackend {
public function setGroupMemberSet($principal, array $members) { public function setGroupMemberSet($principal, array $members) {
throw new Sabre_DAV_Exception('Setting members of the group is not supported yet'); throw new Sabre_DAV_Exception('Setting members of the group is not supported yet');
} }
function updatePrincipal($path, $mutations){return 0;} function updatePrincipal($path, $mutations) {return 0;}
function searchPrincipals($prefixPath, array $searchProperties){return 0;} function searchPrincipals($prefixPath, array $searchProperties) {return 0;}
} }

View File

@ -41,7 +41,7 @@ class OC_DB {
* check which backend we should use * check which backend we should use
* @return BACKEND_MDB2 or BACKEND_PDO * @return BACKEND_MDB2 or BACKEND_PDO
*/ */
private static function getDBBackend(){ private static function getDBBackend() {
//check if we can use PDO, else use MDB2 (installation always needs to be done my mdb2) //check if we can use PDO, else use MDB2 (installation always needs to be done my mdb2)
if(class_exists('PDO') && OC_Config::getValue('installed', false)) { if(class_exists('PDO') && OC_Config::getValue('installed', false)) {
$type = OC_Config::getValue( "dbtype", "sqlite" ); $type = OC_Config::getValue( "dbtype", "sqlite" );
@ -63,7 +63,7 @@ class OC_DB {
* *
* Connects to the database as specified in config.php * Connects to the database as specified in config.php
*/ */
public static function connect($backend=null){ public static function connect($backend=null) {
if(self::$connection) { if(self::$connection) {
return; return;
} }
@ -84,7 +84,7 @@ class OC_DB {
/** /**
* connect to the database using pdo * connect to the database using pdo
*/ */
public static function connectPDO(){ public static function connectPDO() {
if(self::$connection) { if(self::$connection) {
if(self::$backend==self::BACKEND_MDB2) { if(self::$backend==self::BACKEND_MDB2) {
self::disconnect(); self::disconnect();
@ -149,7 +149,7 @@ class OC_DB {
} }
try{ try{
self::$PDO=new PDO($dsn, $user, $pass, $opts); self::$PDO=new PDO($dsn, $user, $pass, $opts);
}catch(PDOException $e){ }catch(PDOException $e) {
echo( '<b>can not connect to database, using '.$type.'. ('.$e->getMessage().')</center>'); echo( '<b>can not connect to database, using '.$type.'. ('.$e->getMessage().')</center>');
die(); die();
} }
@ -194,7 +194,7 @@ class OC_DB {
'quote_identifier' => true ); 'quote_identifier' => true );
// Add the dsn according to the database type // Add the dsn according to the database type
switch($type){ switch($type) {
case 'sqlite': case 'sqlite':
case 'sqlite3': case 'sqlite3':
$dsn = array( $dsn = array(
@ -262,7 +262,7 @@ class OC_DB {
* *
* SQL query via MDB2 prepare(), needs to be execute()'d! * SQL query via MDB2 prepare(), needs to be execute()'d!
*/ */
static public function prepare( $query , $limit=null, $offset=null ){ static public function prepare( $query , $limit=null, $offset=null ) {
if (!is_null($limit) && $limit != -1) { if (!is_null($limit) && $limit != -1) {
if (self::$backend == self::BACKEND_MDB2) { if (self::$backend == self::BACKEND_MDB2) {
@ -305,7 +305,7 @@ class OC_DB {
}else{ }else{
try{ try{
$result=self::$connection->prepare($query); $result=self::$connection->prepare($query);
}catch(PDOException $e){ }catch(PDOException $e) {
$entry = 'DB Error: "'.$e->getMessage().'"<br />'; $entry = 'DB Error: "'.$e->getMessage().'"<br />';
$entry .= 'Offending command was: '.$query.'<br />'; $entry .= 'Offending command was: '.$query.'<br />';
OC_Log::write('core', $entry,OC_Log::FATAL); OC_Log::write('core', $entry,OC_Log::FATAL);
@ -327,7 +327,7 @@ class OC_DB {
* Call this method right after the insert command or other functions may * Call this method right after the insert command or other functions may
* cause trouble! * cause trouble!
*/ */
public static function insertid($table=null){ public static function insertid($table=null) {
self::connect(); self::connect();
if($table !== null) { if($table !== null) {
$prefix = OC_Config::getValue( "dbtableprefix", "oc_" ); $prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
@ -343,7 +343,7 @@ class OC_DB {
* *
* This is good bye, good bye, yeah! * This is good bye, good bye, yeah!
*/ */
public static function disconnect(){ public static function disconnect() {
// Cut connection if required // Cut connection if required
if(self::$connection) { if(self::$connection) {
if(self::$backend==self::BACKEND_MDB2) { if(self::$backend==self::BACKEND_MDB2) {
@ -364,7 +364,7 @@ class OC_DB {
* *
* TODO: write more documentation * TODO: write more documentation
*/ */
public static function getDbStructure( $file ,$mode=MDB2_SCHEMA_DUMP_STRUCTURE){ public static function getDbStructure( $file ,$mode=MDB2_SCHEMA_DUMP_STRUCTURE) {
self::connectScheme(); self::connectScheme();
// write the scheme // write the scheme
@ -386,7 +386,7 @@ class OC_DB {
* *
* TODO: write more documentation * TODO: write more documentation
*/ */
public static function createDbFromStructure( $file ){ public static function createDbFromStructure( $file ) {
$CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" ); $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
$CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" ); $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
$CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" ); $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
@ -445,7 +445,7 @@ class OC_DB {
* @brief update the database scheme * @brief update the database scheme
* @param $file file to read structure from * @param $file file to read structure from
*/ */
public static function updateDbFromStructure($file){ public static function updateDbFromStructure($file) {
$CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" ); $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
$CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" ); $CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
@ -471,7 +471,7 @@ class OC_DB {
* http://www.postgresql.org/docs/8.1/static/functions-datetime.html * http://www.postgresql.org/docs/8.1/static/functions-datetime.html
* http://www.sqlite.org/lang_createtable.html * http://www.sqlite.org/lang_createtable.html
* http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm * http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions037.htm
if( $CONFIG_DBTYPE == 'pgsql' ){ //mysql support it too but sqlite doesn't if( $CONFIG_DBTYPE == 'pgsql' ) { //mysql support it too but sqlite doesn't
$content = str_replace( '<default>0000-00-00 00:00:00</default>', '<default>CURRENT_TIMESTAMP</default>', $content ); $content = str_replace( '<default>0000-00-00 00:00:00</default>', '<default>CURRENT_TIMESTAMP</default>', $content );
} }
*/ */
@ -496,7 +496,7 @@ class OC_DB {
* *
* Connects to a MDB2 database scheme * Connects to a MDB2 database scheme
*/ */
private static function connectScheme(){ private static function connectScheme() {
// We need a mdb2 database connection // We need a mdb2 database connection
self::connectMDB2(); self::connectMDB2();
self::$MDB2->loadModule('Manager'); self::$MDB2->loadModule('Manager');
@ -519,7 +519,7 @@ class OC_DB {
* This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX * This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX
* and replaces the ` woth ' or " according to the database driver. * and replaces the ` woth ' or " according to the database driver.
*/ */
private static function processQuery( $query ){ private static function processQuery( $query ) {
self::connect(); self::connect();
// We need Database type and table prefix // We need Database type and table prefix
if(is_null(self::$type)) { if(is_null(self::$type)) {
@ -554,7 +554,7 @@ class OC_DB {
* @brief drop a table * @brief drop a table
* @param string $tableNamme the table to drop * @param string $tableNamme the table to drop
*/ */
public static function dropTable($tableName){ public static function dropTable($tableName) {
self::connectMDB2(); self::connectMDB2();
self::$MDB2->loadModule('Manager'); self::$MDB2->loadModule('Manager');
self::$MDB2->dropTable($tableName); self::$MDB2->dropTable($tableName);
@ -564,7 +564,7 @@ class OC_DB {
* remove all tables defined in a database structure xml file * remove all tables defined in a database structure xml file
* @param string $file the xml file describing the tables * @param string $file the xml file describing the tables
*/ */
public static function removeDBStructure($file){ public static function removeDBStructure($file) {
$CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" ); $CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
$CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" ); $CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
self::connectScheme(); self::connectScheme();
@ -584,7 +584,7 @@ class OC_DB {
// Delete our temporary file // Delete our temporary file
unlink( $file2 ); unlink( $file2 );
$tables=array_keys($definition['tables']); $tables=array_keys($definition['tables']);
foreach($tables as $table){ foreach($tables as $table) {
self::dropTable($table); self::dropTable($table);
} }
} }
@ -593,13 +593,13 @@ class OC_DB {
* @brief replaces the owncloud tables with a new set * @brief replaces the owncloud tables with a new set
* @param $file string path to the MDB2 xml db export file * @param $file string path to the MDB2 xml db export file
*/ */
public static function replaceDB( $file ){ public static function replaceDB( $file ) {
$apps = OC_App::getAllApps(); $apps = OC_App::getAllApps();
self::beginTransaction(); self::beginTransaction();
// Delete the old tables // Delete the old tables
self::removeDBStructure( OC::$SERVERROOT . '/db_structure.xml' ); self::removeDBStructure( OC::$SERVERROOT . '/db_structure.xml' );
foreach($apps as $app){ foreach($apps as $app) {
$path = OC_App::getAppPath($app).'/appinfo/database.xml'; $path = OC_App::getAppPath($app).'/appinfo/database.xml';
if(file_exists($path)) { if(file_exists($path)) {
self::removeDBStructure( $path ); self::removeDBStructure( $path );
@ -614,7 +614,7 @@ class OC_DB {
/** /**
* Start a transaction * Start a transaction
*/ */
public static function beginTransaction(){ public static function beginTransaction() {
self::connect(); self::connect();
if (self::$backend==self::BACKEND_MDB2 && !self::$connection->supports('transactions')) { if (self::$backend==self::BACKEND_MDB2 && !self::$connection->supports('transactions')) {
return false; return false;
@ -640,10 +640,10 @@ class OC_DB {
* @param mixed $result * @param mixed $result
* @return bool * @return bool
*/ */
public static function isError($result){ public static function isError($result) {
if(!$result) { if(!$result) {
return true; return true;
}elseif(self::$backend==self::BACKEND_MDB2 and PEAR::isError($result)){ }elseif(self::$backend==self::BACKEND_MDB2 and PEAR::isError($result)) {
return true; return true;
}else{ }else{
return false; return false;
@ -658,16 +658,16 @@ class PDOStatementWrapper{
private $statement=null; private $statement=null;
private $lastArguments=array(); private $lastArguments=array();
public function __construct($statement){ public function __construct($statement) {
$this->statement=$statement; $this->statement=$statement;
} }
/** /**
* make execute return the result instead of a bool * make execute return the result instead of a bool
*/ */
public function execute($input=array()){ public function execute($input=array()) {
$this->lastArguments=$input; $this->lastArguments=$input;
if(count($input)>0){ if(count($input)>0) {
$result=$this->statement->execute($input); $result=$this->statement->execute($input);
}else{ }else{
$result=$this->statement->execute(); $result=$this->statement->execute();
@ -682,7 +682,7 @@ class PDOStatementWrapper{
/** /**
* provide numRows * provide numRows
*/ */
public function numRows(){ public function numRows() {
$regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i'; $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
if (preg_match($regex, $this->statement->queryString, $output) > 0) { if (preg_match($regex, $this->statement->queryString, $output) > 0) {
$query = OC_DB::prepare("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM); $query = OC_DB::prepare("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);
@ -695,14 +695,14 @@ class PDOStatementWrapper{
/** /**
* provide an alias for fetch * provide an alias for fetch
*/ */
public function fetchRow(){ public function fetchRow() {
return $this->statement->fetch(); return $this->statement->fetch();
} }
/** /**
* pass all other function directly to the PDOStatement * pass all other function directly to the PDOStatement
*/ */
public function __call($name,$arguments){ public function __call($name,$arguments) {
return call_user_func_array(array($this->statement,$name), $arguments); return call_user_func_array(array($this->statement,$name), $arguments);
} }
@ -711,7 +711,7 @@ class PDOStatementWrapper{
* fetch single column from the next row * fetch single column from the next row
* @param int $colnum the column number to fetch * @param int $colnum the column number to fetch
*/ */
public function fetchOne($colnum = 0){ public function fetchOne($colnum = 0) {
return $this->statement->fetchColumn($colnum); return $this->statement->fetchColumn($colnum);
} }
} }

View File

@ -31,18 +31,18 @@ class OC_EventSource{
private $fallback; private $fallback;
private $fallBackId=0; private $fallBackId=0;
public function __construct(){ public function __construct() {
@ob_end_clean(); @ob_end_clean();
header('Cache-Control: no-cache'); header('Cache-Control: no-cache');
$this->fallback=isset($_GET['fallback']) and $_GET['fallback']=='true'; $this->fallback=isset($_GET['fallback']) and $_GET['fallback']=='true';
if($this->fallback){ if($this->fallback) {
$this->fallBackId=$_GET['fallback_id']; $this->fallBackId=$_GET['fallback_id'];
header("Content-Type: text/html"); header("Content-Type: text/html");
echo str_repeat('<span></span>'.PHP_EOL,10); //dummy data to keep IE happy echo str_repeat('<span></span>'.PHP_EOL,10); //dummy data to keep IE happy
}else{ }else{
header("Content-Type: text/event-stream"); header("Content-Type: text/event-stream");
} }
if( !OC_Util::isCallRegistered()){ if( !OC_Util::isCallRegistered()) {
exit(); exit();
} }
flush(); flush();
@ -56,16 +56,16 @@ class OC_EventSource{
* *
* if only one paramater is given, a typeless message will be send with that paramater as data * if only one paramater is given, a typeless message will be send with that paramater as data
*/ */
public function send($type,$data=null){ public function send($type,$data=null) {
if(is_null($data)){ if(is_null($data)) {
$data=$type; $data=$type;
$type=null; $type=null;
} }
if($this->fallback){ if($this->fallback) {
$response='<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('.$this->fallBackId.',"'.$type.'",'.json_encode($data).')</script>'.PHP_EOL; $response='<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('.$this->fallBackId.',"'.$type.'",'.json_encode($data).')</script>'.PHP_EOL;
echo $response; echo $response;
}else{ }else{
if($type){ if($type) {
echo 'event: '.$type.PHP_EOL; echo 'event: '.$type.PHP_EOL;
} }
echo 'data: '.json_encode($data).PHP_EOL; echo 'data: '.json_encode($data).PHP_EOL;
@ -77,7 +77,7 @@ class OC_EventSource{
/** /**
* close the connection of the even source * close the connection of the even source
*/ */
public function close(){ public function close() {
$this->send('__internal__','close');//server side closing can be an issue, let the client do it $this->send('__internal__','close');//server side closing can be an issue, let the client do it
} }
} }

View File

@ -42,9 +42,9 @@ class OC_FileCache{
* - encrypted * - encrypted
* - versioned * - versioned
*/ */
public static function get($path,$root=false){ public static function get($path,$root=false) {
if(OC_FileCache_Update::hasUpdated($path,$root)){ if(OC_FileCache_Update::hasUpdated($path,$root)) {
if($root===false){//filesystem hooks are only valid for the default root if($root===false) {//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$path)); OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$path));
}else{ }else{
OC_FileCache_Update::update($path,$root); OC_FileCache_Update::update($path,$root);
@ -61,18 +61,18 @@ class OC_FileCache{
* *
* $data is an assiciative array in the same format as returned by get * $data is an assiciative array in the same format as returned by get
*/ */
public static function put($path,$data,$root=false){ public static function put($path,$data,$root=false) {
if($root===false){ if($root===false) {
$root=OC_Filesystem::getRoot(); $root=OC_Filesystem::getRoot();
} }
$fullpath=$root.$path; $fullpath=$root.$path;
$parent=self::getParentId($fullpath); $parent=self::getParentId($fullpath);
$id=self::getId($fullpath,''); $id=self::getId($fullpath,'');
if(isset(OC_FileCache_Cached::$savedData[$fullpath])){ if(isset(OC_FileCache_Cached::$savedData[$fullpath])) {
$data=array_merge(OC_FileCache_Cached::$savedData[$fullpath],$data); $data=array_merge(OC_FileCache_Cached::$savedData[$fullpath],$data);
unset(OC_FileCache_Cached::$savedData[$fullpath]); unset(OC_FileCache_Cached::$savedData[$fullpath]);
} }
if($id!=-1){ if($id!=-1) {
self::update($id,$data); self::update($id,$data);
return; return;
} }
@ -84,14 +84,14 @@ class OC_FileCache{
$parent = self::getParentId($fullpath); $parent = self::getParentId($fullpath);
} }
if(!isset($data['size']) or !isset($data['mtime'])){//save incomplete data for the next time we write it if(!isset($data['size']) or !isset($data['mtime'])) {//save incomplete data for the next time we write it
OC_FileCache_Cached::$savedData[$fullpath]=$data; OC_FileCache_Cached::$savedData[$fullpath]=$data;
return; return;
} }
if(!isset($data['encrypted'])){ if(!isset($data['encrypted'])) {
$data['encrypted']=false; $data['encrypted']=false;
} }
if(!isset($data['versioned'])){ if(!isset($data['versioned'])) {
$data['versioned']=false; $data['versioned']=false;
} }
$mimePart=dirname($data['mimetype']); $mimePart=dirname($data['mimetype']);
@ -103,11 +103,11 @@ class OC_FileCache{
$user=OC_User::getUser(); $user=OC_User::getUser();
$query=OC_DB::prepare('INSERT INTO `*PREFIX*fscache`(`parent`, `name`, `path`, `path_hash`, `size`, `mtime`, `ctime`, `mimetype`, `mimepart`,`user`,`writable`,`encrypted`,`versioned`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)'); $query=OC_DB::prepare('INSERT INTO `*PREFIX*fscache`(`parent`, `name`, `path`, `path_hash`, `size`, `mtime`, `ctime`, `mimetype`, `mimepart`,`user`,`writable`,`encrypted`,`versioned`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)');
$result=$query->execute(array($parent,basename($fullpath),$fullpath,md5($fullpath),$data['size'],$data['mtime'],$data['ctime'],$data['mimetype'],$mimePart,$user,$data['writable'],$data['encrypted'],$data['versioned'])); $result=$query->execute(array($parent,basename($fullpath),$fullpath,md5($fullpath),$data['size'],$data['mtime'],$data['ctime'],$data['mimetype'],$mimePart,$user,$data['writable'],$data['encrypted'],$data['versioned']));
if(OC_DB::isError($result)){ if(OC_DB::isError($result)) {
OC_Log::write('files','error while writing file('.$fullpath.') to cache',OC_Log::ERROR); OC_Log::write('files','error while writing file('.$fullpath.') to cache',OC_Log::ERROR);
} }
if($cache=OC_Cache::getUserCache(true)){ if($cache=OC_Cache::getUserCache(true)) {
$cache->remove('fileid/'.$fullpath);//ensure we don't have -1 cached $cache->remove('fileid/'.$fullpath);//ensure we don't have -1 cached
} }
} }
@ -117,13 +117,13 @@ class OC_FileCache{
* @param int $id * @param int $id
* @param array $data * @param array $data
*/ */
private static function update($id,$data){ private static function update($id,$data) {
$arguments=array(); $arguments=array();
$queryParts=array(); $queryParts=array();
foreach(array('size','mtime','ctime','mimetype','encrypted','versioned','writable') as $attribute){ foreach(array('size','mtime','ctime','mimetype','encrypted','versioned','writable') as $attribute) {
if(isset($data[$attribute])){ if(isset($data[$attribute])) {
//Convert to int it args are false //Convert to int it args are false
if($data[$attribute] === false){ if($data[$attribute] === false) {
$arguments[] = 0; $arguments[] = 0;
}else{ }else{
$arguments[] = $data[$attribute]; $arguments[] = $data[$attribute];
@ -131,7 +131,7 @@ class OC_FileCache{
$queryParts[]='`'.$attribute.'`=?'; $queryParts[]='`'.$attribute.'`=?';
} }
} }
if(isset($data['mimetype'])){ if(isset($data['mimetype'])) {
$arguments[]=dirname($data['mimetype']); $arguments[]=dirname($data['mimetype']);
$queryParts[]='`mimepart`=?'; $queryParts[]='`mimepart`=?';
} }
@ -140,7 +140,7 @@ class OC_FileCache{
$sql = 'UPDATE `*PREFIX*fscache` SET '.implode(' , ',$queryParts).' WHERE `id`=?'; $sql = 'UPDATE `*PREFIX*fscache` SET '.implode(' , ',$queryParts).' WHERE `id`=?';
$query=OC_DB::prepare($sql); $query=OC_DB::prepare($sql);
$result=$query->execute($arguments); $result=$query->execute($arguments);
if(OC_DB::isError($result)){ if(OC_DB::isError($result)) {
OC_Log::write('files','error while updating file('.$id.') in cache',OC_Log::ERROR); OC_Log::write('files','error while updating file('.$id.') in cache',OC_Log::ERROR);
} }
} }
@ -151,8 +151,8 @@ class OC_FileCache{
* @param string newPath * @param string newPath
* @param string root (optional) * @param string root (optional)
*/ */
public static function move($oldPath,$newPath,$root=false){ public static function move($oldPath,$newPath,$root=false) {
if($root===false){ if($root===false) {
$root=OC_Filesystem::getRoot(); $root=OC_Filesystem::getRoot();
} }
// If replacing an existing file, delete the file // If replacing an existing file, delete the file
@ -165,7 +165,7 @@ class OC_FileCache{
$query=OC_DB::prepare('UPDATE `*PREFIX*fscache` SET `parent`=? ,`name`=?, `path`=?, `path_hash`=? WHERE `path_hash`=?'); $query=OC_DB::prepare('UPDATE `*PREFIX*fscache` SET `parent`=? ,`name`=?, `path`=?, `path_hash`=? WHERE `path_hash`=?');
$query->execute(array($newParent,basename($newPath),$newPath,md5($newPath),md5($oldPath))); $query->execute(array($newParent,basename($newPath),$newPath,md5($newPath),md5($oldPath)));
if(($cache=OC_Cache::getUserCache(true)) && $cache->hasKey('fileid/'.$oldPath)){ if(($cache=OC_Cache::getUserCache(true)) && $cache->hasKey('fileid/'.$oldPath)) {
$cache->set('fileid/'.$newPath,$cache->get('fileid/'.$oldPath)); $cache->set('fileid/'.$newPath,$cache->get('fileid/'.$oldPath));
$cache->remove('fileid/'.$oldPath); $cache->remove('fileid/'.$oldPath);
} }
@ -173,12 +173,12 @@ class OC_FileCache{
$query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `path` LIKE ?'); $query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `path` LIKE ?');
$oldLength=strlen($oldPath); $oldLength=strlen($oldPath);
$updateQuery=OC_DB::prepare('UPDATE `*PREFIX*fscache` SET `path`=?, `path_hash`=? WHERE `path_hash`=?'); $updateQuery=OC_DB::prepare('UPDATE `*PREFIX*fscache` SET `path`=?, `path_hash`=? WHERE `path_hash`=?');
while($row= $query->execute(array($oldPath.'/%'))->fetchRow()){ while($row= $query->execute(array($oldPath.'/%'))->fetchRow()) {
$old=$row['path']; $old=$row['path'];
$new=$newPath.substr($old,$oldLength); $new=$newPath.substr($old,$oldLength);
$updateQuery->execute(array($new,md5($new),md5($old))); $updateQuery->execute(array($new,md5($new),md5($old)));
if(($cache=OC_Cache::getUserCache(true)) && $cache->hasKey('fileid/'.$old)){ if(($cache=OC_Cache::getUserCache(true)) && $cache->hasKey('fileid/'.$old)) {
$cache->set('fileid/'.$new,$cache->get('fileid/'.$old)); $cache->set('fileid/'.$new,$cache->get('fileid/'.$old));
$cache->remove('fileid/'.$old); $cache->remove('fileid/'.$old);
} }
@ -190,8 +190,8 @@ class OC_FileCache{
* @param string path * @param string path
* @param string root (optional) * @param string root (optional)
*/ */
public static function delete($path,$root=false){ public static function delete($path,$root=false) {
if($root===false){ if($root===false) {
$root=OC_Filesystem::getRoot(); $root=OC_Filesystem::getRoot();
} }
$query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE `path_hash`=?'); $query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE `path_hash`=?');
@ -211,20 +211,20 @@ class OC_FileCache{
* @param string root (optional) * @param string root (optional)
* @return array of filepaths * @return array of filepaths
*/ */
public static function search($search,$returnData=false,$root=false){ public static function search($search,$returnData=false,$root=false) {
if($root===false){ if($root===false) {
$root=OC_Filesystem::getRoot(); $root=OC_Filesystem::getRoot();
} }
$rootLen=strlen($root); $rootLen=strlen($root);
if(!$returnData){ if(!$returnData) {
$query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `name` LIKE ? AND `user`=?'); $query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `name` LIKE ? AND `user`=?');
}else{ }else{
$query=OC_DB::prepare('SELECT * FROM `*PREFIX*fscache` WHERE `name` LIKE ? AND `user`=?'); $query=OC_DB::prepare('SELECT * FROM `*PREFIX*fscache` WHERE `name` LIKE ? AND `user`=?');
} }
$result=$query->execute(array("%$search%",OC_User::getUser())); $result=$query->execute(array("%$search%",OC_User::getUser()));
$names=array(); $names=array();
while($row=$result->fetchRow()){ while($row=$result->fetchRow()) {
if(!$returnData){ if(!$returnData) {
$names[]=substr($row['path'],$rootLen); $names[]=substr($row['path'],$rootLen);
}else{ }else{
$row['path']=substr($row['path'],$rootLen); $row['path']=substr($row['path'],$rootLen);
@ -249,8 +249,8 @@ class OC_FileCache{
* - encrypted * - encrypted
* - versioned * - versioned
*/ */
public static function getFolderContent($path,$root=false,$mimetype_filter=''){ public static function getFolderContent($path,$root=false,$mimetype_filter='') {
if(OC_FileCache_Update::hasUpdated($path,$root,true)){ if(OC_FileCache_Update::hasUpdated($path,$root,true)) {
OC_FileCache_Update::updateFolder($path,$root); OC_FileCache_Update::updateFolder($path,$root);
} }
return OC_FileCache_Cached::getFolderContent($path,$root,$mimetype_filter); return OC_FileCache_Cached::getFolderContent($path,$root,$mimetype_filter);
@ -262,7 +262,7 @@ class OC_FileCache{
* @param string root (optional) * @param string root (optional)
* @return bool * @return bool
*/ */
public static function inCache($path,$root=false){ public static function inCache($path,$root=false) {
return self::getId($path,$root)!=-1; return self::getId($path,$root)!=-1;
} }
@ -272,30 +272,30 @@ class OC_FileCache{
* @param string root (optional) * @param string root (optional)
* @return int * @return int
*/ */
public static function getId($path,$root=false){ public static function getId($path,$root=false) {
if($root===false){ if($root===false) {
$root=OC_Filesystem::getRoot(); $root=OC_Filesystem::getRoot();
} }
$fullPath=$root.$path; $fullPath=$root.$path;
if(($cache=OC_Cache::getUserCache(true)) && $cache->hasKey('fileid/'.$fullPath)){ if(($cache=OC_Cache::getUserCache(true)) && $cache->hasKey('fileid/'.$fullPath)) {
return $cache->get('fileid/'.$fullPath); return $cache->get('fileid/'.$fullPath);
} }
$query=OC_DB::prepare('SELECT `id` FROM `*PREFIX*fscache` WHERE `path_hash`=?'); $query=OC_DB::prepare('SELECT `id` FROM `*PREFIX*fscache` WHERE `path_hash`=?');
$result=$query->execute(array(md5($fullPath))); $result=$query->execute(array(md5($fullPath)));
if(OC_DB::isError($result)){ if(OC_DB::isError($result)) {
OC_Log::write('files','error while getting file id of '.$path,OC_Log::ERROR); OC_Log::write('files','error while getting file id of '.$path,OC_Log::ERROR);
return -1; return -1;
} }
$result=$result->fetchRow(); $result=$result->fetchRow();
if(is_array($result)){ if(is_array($result)) {
$id=$result['id']; $id=$result['id'];
}else{ }else{
$id=-1; $id=-1;
} }
if($cache=OC_Cache::getUserCache(true)){ if($cache=OC_Cache::getUserCache(true)) {
$cache->set('fileid/'.$fullPath,$id); $cache->set('fileid/'.$fullPath,$id);
} }
@ -308,8 +308,8 @@ class OC_FileCache{
* @param string user (optional) * @param string user (optional)
* @return string * @return string
*/ */
public static function getPath($id,$user=''){ public static function getPath($id,$user='') {
if(!$user){ if(!$user) {
$user=OC_User::getUser(); $user=OC_User::getUser();
} }
$query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `id`=? AND `user`=?'); $query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `id`=? AND `user`=?');
@ -317,7 +317,7 @@ class OC_FileCache{
$row=$result->fetchRow(); $row=$result->fetchRow();
$path=$row['path']; $path=$row['path'];
$root='/'.$user.'/files'; $root='/'.$user.'/files';
if(substr($path,0,strlen($root))!=$root){ if(substr($path,0,strlen($root))!=$root) {
return false; return false;
} }
return substr($path,strlen($root)); return substr($path,strlen($root));
@ -328,8 +328,8 @@ class OC_FileCache{
* @param string $path * @param string $path
* @return int * @return int
*/ */
private static function getParentId($path){ private static function getParentId($path) {
if($path=='/'){ if($path=='/') {
return -1; return -1;
}else{ }else{
return self::getId(dirname($path),''); return self::getId(dirname($path),'');
@ -342,10 +342,10 @@ class OC_FileCache{
* @param int $sizeDiff * @param int $sizeDiff
* @param string root (optinal) * @param string root (optinal)
*/ */
public static function increaseSize($path,$sizeDiff, $root=false){ public static function increaseSize($path,$sizeDiff, $root=false) {
if($sizeDiff==0) return; if($sizeDiff==0) return;
$id=self::getId($path,$root); $id=self::getId($path,$root);
while($id!=-1){//walk up the filetree increasing the size of all parent folders while($id!=-1) {//walk up the filetree increasing the size of all parent folders
$query=OC_DB::prepare('UPDATE `*PREFIX*fscache` SET `size`=`size`+? WHERE `id`=?'); $query=OC_DB::prepare('UPDATE `*PREFIX*fscache` SET `size`=`size`+? WHERE `id`=?');
$query->execute(array($sizeDiff,$id)); $query->execute(array($sizeDiff,$id));
$id=self::getParentId($path); $id=self::getParentId($path);
@ -360,8 +360,8 @@ class OC_FileCache{
* @param int count (optional) * @param int count (optional)
* @param string root (optional) * @param string root (optional)
*/ */
public static function scan($path,$eventSource=false,&$count=0,$root=false){ public static function scan($path,$eventSource=false,&$count=0,$root=false) {
if($eventSource){ if($eventSource) {
$eventSource->send('scanning',array('file'=>$path,'count'=>$count)); $eventSource->send('scanning',array('file'=>$path,'count'=>$count));
} }
$lastSend=$count; $lastSend=$count;
@ -369,7 +369,7 @@ class OC_FileCache{
if (substr($path, 0, 7) == '/Shared') { if (substr($path, 0, 7) == '/Shared') {
return; return;
} }
if($root===false){ if($root===false) {
$view=OC_Filesystem::getView(); $view=OC_Filesystem::getView();
}else{ }else{
$view=new OC_FilesystemView($root); $view=new OC_FilesystemView($root);
@ -377,16 +377,16 @@ class OC_FileCache{
self::scanFile($path,$root); self::scanFile($path,$root);
$dh=$view->opendir($path.'/'); $dh=$view->opendir($path.'/');
$totalSize=0; $totalSize=0;
if($dh){ if($dh) {
while (($filename = readdir($dh)) !== false) { while (($filename = readdir($dh)) !== false) {
if($filename != '.' and $filename != '..'){ if($filename != '.' and $filename != '..') {
$file=$path.'/'.$filename; $file=$path.'/'.$filename;
if($view->is_dir($file.'/')){ if($view->is_dir($file.'/')) {
self::scan($file,$eventSource,$count,$root); self::scan($file,$eventSource,$count,$root);
}else{ }else{
$totalSize+=self::scanFile($file,$root); $totalSize+=self::scanFile($file,$root);
$count++; $count++;
if($count>$lastSend+25 and $eventSource){ if($count>$lastSend+25 and $eventSource) {
$lastSend=$count; $lastSend=$count;
$eventSource->send('scanning',array('file'=>$path,'count'=>$count)); $eventSource->send('scanning',array('file'=>$path,'count'=>$count));
} }
@ -405,12 +405,12 @@ class OC_FileCache{
* @param string root (optional) * @param string root (optional)
* @return int size of the scanned file * @return int size of the scanned file
*/ */
public static function scanFile($path,$root=false){ public static function scanFile($path,$root=false) {
// NOTE: Ugly hack to prevent shared files from going into the cache (the source already exists somewhere in the cache) // NOTE: Ugly hack to prevent shared files from going into the cache (the source already exists somewhere in the cache)
if (substr($path, 0, 7) == '/Shared') { if (substr($path, 0, 7) == '/Shared') {
return; return;
} }
if($root===false){ if($root===false) {
$view=OC_Filesystem::getView(); $view=OC_Filesystem::getView();
}else{ }else{
$view=new OC_FilesystemView($root); $view=new OC_FilesystemView($root);
@ -419,14 +419,14 @@ class OC_FileCache{
clearstatcache(); clearstatcache();
$mimetype=$view->getMimeType($path); $mimetype=$view->getMimeType($path);
$stat=$view->stat($path); $stat=$view->stat($path);
if($mimetype=='httpd/unix-directory'){ if($mimetype=='httpd/unix-directory') {
$writable=$view->is_writable($path.'/'); $writable=$view->is_writable($path.'/');
}else{ }else{
$writable=$view->is_writable($path); $writable=$view->is_writable($path);
} }
$stat['mimetype']=$mimetype; $stat['mimetype']=$mimetype;
$stat['writable']=$writable; $stat['writable']=$writable;
if($path=='/'){ if($path=='/') {
$path=''; $path='';
} }
self::put($path,$stat,$root); self::put($path,$stat,$root);
@ -446,14 +446,14 @@ class OC_FileCache{
* seccond mimetype part can be ommited * seccond mimetype part can be ommited
* e.g. searchByMime('audio') * e.g. searchByMime('audio')
*/ */
public static function searchByMime($part1,$part2=null,$root=false){ public static function searchByMime($part1,$part2=null,$root=false) {
if($root===false){ if($root===false) {
$root=OC_Filesystem::getRoot(); $root=OC_Filesystem::getRoot();
} }
$rootLen=strlen($root); $rootLen=strlen($root);
$root .= '%'; $root .= '%';
$user=OC_User::getUser(); $user=OC_User::getUser();
if(!$part2){ if(!$part2) {
$query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `mimepart`=? AND `user`=? AND `path` LIKE ?'); $query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `mimepart`=? AND `user`=? AND `path` LIKE ?');
$result=$query->execute(array($part1,$user, $root)); $result=$query->execute(array($part1,$user, $root));
}else{ }else{
@ -461,7 +461,7 @@ class OC_FileCache{
$result=$query->execute(array($part1.'/'.$part2,$user, $root)); $result=$query->execute(array($part1.'/'.$part2,$user, $root));
} }
$names=array(); $names=array();
while($row=$result->fetchRow()){ while($row=$result->fetchRow()) {
$names[]=substr($row['path'],$rootLen); $names[]=substr($row['path'],$rootLen);
} }
return $names; return $names;
@ -470,7 +470,7 @@ class OC_FileCache{
/** /**
* clean old pre-path_hash entries * clean old pre-path_hash entries
*/ */
public static function clean(){ public static function clean() {
$query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE LENGTH(`path_hash`)<30'); $query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE LENGTH(`path_hash`)<30');
$query->execute(); $query->execute();
} }
@ -479,8 +479,8 @@ class OC_FileCache{
* clear filecache entries * clear filecache entries
* @param string user (optonal) * @param string user (optonal)
*/ */
public static function clear($user=''){ public static function clear($user='') {
if($user){ if($user) {
$query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE user=?'); $query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE user=?');
$query->execute(array($user)); $query->execute(array($user));
}else{ }else{

View File

@ -13,20 +13,20 @@
class OC_FileCache_Cached{ class OC_FileCache_Cached{
public static $savedData=array(); public static $savedData=array();
public static function get($path,$root=false){ public static function get($path,$root=false) {
if($root===false){ if($root===false) {
$root=OC_Filesystem::getRoot(); $root=OC_Filesystem::getRoot();
} }
$path=$root.$path; $path=$root.$path;
$query=OC_DB::prepare('SELECT `path`,`ctime`,`mtime`,`mimetype`,`size`,`encrypted`,`versioned`,`writable` FROM `*PREFIX*fscache` WHERE `path_hash`=?'); $query=OC_DB::prepare('SELECT `path`,`ctime`,`mtime`,`mimetype`,`size`,`encrypted`,`versioned`,`writable` FROM `*PREFIX*fscache` WHERE `path_hash`=?');
$result=$query->execute(array(md5($path)))->fetchRow(); $result=$query->execute(array(md5($path)))->fetchRow();
if(is_array($result)){ if(is_array($result)) {
if(isset(self::$savedData[$path])){ if(isset(self::$savedData[$path])) {
$result=array_merge($result,self::$savedData[$path]); $result=array_merge($result,self::$savedData[$path]);
} }
return $result; return $result;
}else{ }else{
if(isset(self::$savedData[$path])){ if(isset(self::$savedData[$path])) {
return self::$savedData[$path]; return self::$savedData[$path];
}else{ }else{
return array(); return array();
@ -50,17 +50,17 @@ class OC_FileCache_Cached{
* - encrypted * - encrypted
* - versioned * - versioned
*/ */
public static function getFolderContent($path,$root=false,$mimetype_filter=''){ public static function getFolderContent($path,$root=false,$mimetype_filter='') {
if($root===false){ if($root===false) {
$root=OC_Filesystem::getRoot(); $root=OC_Filesystem::getRoot();
} }
$parent=OC_FileCache::getId($path,$root); $parent=OC_FileCache::getId($path,$root);
if($parent==-1){ if($parent==-1) {
return array(); return array();
} }
$query=OC_DB::prepare('SELECT `id`,`path`,`name`,`ctime`,`mtime`,`mimetype`,`size`,`encrypted`,`versioned`,`writable` FROM `*PREFIX*fscache` WHERE `parent`=? AND (`mimetype` LIKE ? OR `mimetype` = ?)'); $query=OC_DB::prepare('SELECT `id`,`path`,`name`,`ctime`,`mtime`,`mimetype`,`size`,`encrypted`,`versioned`,`writable` FROM `*PREFIX*fscache` WHERE `parent`=? AND (`mimetype` LIKE ? OR `mimetype` = ?)');
$result=$query->execute(array($parent, $mimetype_filter.'%', 'httpd/unix-directory'))->fetchAll(); $result=$query->execute(array($parent, $mimetype_filter.'%', 'httpd/unix-directory'))->fetchAll();
if(is_array($result)){ if(is_array($result)) {
return $result; return $result;
}else{ }else{
OC_Log::write('files','getFolderContent(): file not found in cache ('.$path.')',OC_Log::DEBUG); OC_Log::write('files','getFolderContent(): file not found in cache ('.$path.')',OC_Log::DEBUG);

View File

@ -18,25 +18,25 @@ class OC_FileCache_Update{
* @param boolean folder * @param boolean folder
* @return bool * @return bool
*/ */
public static function hasUpdated($path,$root=false,$folder=false){ public static function hasUpdated($path,$root=false,$folder=false) {
if($root===false){ if($root===false) {
$view=OC_Filesystem::getView(); $view=OC_Filesystem::getView();
}else{ }else{
$view=new OC_FilesystemView($root); $view=new OC_FilesystemView($root);
} }
if(!$view->file_exists($path)){ if(!$view->file_exists($path)) {
return false; return false;
} }
$cachedData=OC_FileCache_Cached::get($path,$root); $cachedData=OC_FileCache_Cached::get($path,$root);
if(isset($cachedData['mtime'])){ if(isset($cachedData['mtime'])) {
$cachedMTime=$cachedData['mtime']; $cachedMTime=$cachedData['mtime'];
if($folder){ if($folder) {
return $view->hasUpdated($path.'/',$cachedMTime); return $view->hasUpdated($path.'/',$cachedMTime);
}else{ }else{
return $view->hasUpdated($path,$cachedMTime); return $view->hasUpdated($path,$cachedMTime);
} }
}else{//file not in cache, so it has to be updated }else{//file not in cache, so it has to be updated
if(($path=='/' or $path=='') and $root===false){//dont auto update the home folder, it will be scanned if(($path=='/' or $path=='') and $root===false) {//dont auto update the home folder, it will be scanned
return false; return false;
} }
return true; return true;
@ -46,19 +46,19 @@ class OC_FileCache_Update{
/** /**
* delete non existing files from the cache * delete non existing files from the cache
*/ */
public static function cleanFolder($path,$root=false){ public static function cleanFolder($path,$root=false) {
if($root===false){ if($root===false) {
$view=OC_Filesystem::getView(); $view=OC_Filesystem::getView();
}else{ }else{
$view=new OC_FilesystemView($root); $view=new OC_FilesystemView($root);
} }
$cachedContent=OC_FileCache_Cached::getFolderContent($path,$root); $cachedContent=OC_FileCache_Cached::getFolderContent($path,$root);
foreach($cachedContent as $fileData){ foreach($cachedContent as $fileData) {
$path=$fileData['path']; $path=$fileData['path'];
$file=$view->getRelativePath($path); $file=$view->getRelativePath($path);
if(!$view->file_exists($file)){ if(!$view->file_exists($file)) {
if($root===false){//filesystem hooks are only valid for the default root if($root===false) {//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_delete',array('path'=>$file)); OC_Hook::emit('OC_Filesystem','post_delete',array('path'=>$file));
}else{ }else{
self::delete($file,$root); self::delete($file,$root);
@ -72,19 +72,19 @@ class OC_FileCache_Update{
* @param string path * @param string path
* @param string root (optional) * @param string root (optional)
*/ */
public static function updateFolder($path,$root=false){ public static function updateFolder($path,$root=false) {
if($root===false){ if($root===false) {
$view=OC_Filesystem::getView(); $view=OC_Filesystem::getView();
}else{ }else{
$view=new OC_FilesystemView($root); $view=new OC_FilesystemView($root);
} }
$dh=$view->opendir($path.'/'); $dh=$view->opendir($path.'/');
if($dh){//check for changed/new files if($dh) {//check for changed/new files
while (($filename = readdir($dh)) !== false) { while (($filename = readdir($dh)) !== false) {
if($filename != '.' and $filename != '..'){ if($filename != '.' and $filename != '..') {
$file=$path.'/'.$filename; $file=$path.'/'.$filename;
if(self::hasUpdated($file,$root)){ if(self::hasUpdated($file,$root)) {
if($root===false){//filesystem hooks are only valid for the default root if($root===false) {//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$file)); OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$file));
}else{ }else{
self::update($file,$root); self::update($file,$root);
@ -97,7 +97,7 @@ class OC_FileCache_Update{
self::cleanFolder($path,$root); self::cleanFolder($path,$root);
//update the folder last, so we can calculate the size correctly //update the folder last, so we can calculate the size correctly
if($root===false){//filesystem hooks are only valid for the default root if($root===false) {//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$path)); OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$path));
}else{ }else{
self::update($path,$root); self::update($path,$root);
@ -109,7 +109,7 @@ class OC_FileCache_Update{
* @param array $params * @param array $params
* @param string root (optional) * @param string root (optional)
*/ */
public static function fileSystemWatcherWrite($params){ public static function fileSystemWatcherWrite($params) {
$path=$params['path']; $path=$params['path'];
self::update($path); self::update($path);
} }
@ -119,7 +119,7 @@ class OC_FileCache_Update{
* @param array $params * @param array $params
* @param string root (optional) * @param string root (optional)
*/ */
public static function fileSystemWatcherDelete($params){ public static function fileSystemWatcherDelete($params) {
$path=$params['path']; $path=$params['path'];
self::delete($path); self::delete($path);
} }
@ -129,7 +129,7 @@ class OC_FileCache_Update{
* @param array $params * @param array $params
* @param string root (optional) * @param string root (optional)
*/ */
public static function fileSystemWatcherRename($params){ public static function fileSystemWatcherRename($params) {
$oldPath=$params['oldpath']; $oldPath=$params['oldpath'];
$newPath=$params['newpath']; $newPath=$params['newpath'];
self::rename($oldPath,$newPath); self::rename($oldPath,$newPath);
@ -140,8 +140,8 @@ class OC_FileCache_Update{
* @param string path * @param string path
* @param string root (optional) * @param string root (optional)
*/ */
public static function update($path,$root=false){ public static function update($path,$root=false) {
if($root===false){ if($root===false) {
$view=OC_Filesystem::getView(); $view=OC_Filesystem::getView();
}else{ }else{
$view=new OC_FilesystemView($root); $view=new OC_FilesystemView($root);
@ -153,10 +153,10 @@ class OC_FileCache_Update{
$cached=OC_FileCache_Cached::get($path,$root); $cached=OC_FileCache_Cached::get($path,$root);
$cachedSize=isset($cached['size'])?$cached['size']:0; $cachedSize=isset($cached['size'])?$cached['size']:0;
if($view->is_dir($path.'/')){ if($view->is_dir($path.'/')) {
if(OC_FileCache::inCache($path,$root)){ if(OC_FileCache::inCache($path,$root)) {
$cachedContent=OC_FileCache_Cached::getFolderContent($path,$root); $cachedContent=OC_FileCache_Cached::getFolderContent($path,$root);
foreach($cachedContent as $file){ foreach($cachedContent as $file) {
$size+=$file['size']; $size+=$file['size'];
} }
$mtime=$view->filemtime($path.'/'); $mtime=$view->filemtime($path.'/');
@ -179,9 +179,9 @@ class OC_FileCache_Update{
* @param string path * @param string path
* @param string root (optional) * @param string root (optional)
*/ */
public static function delete($path,$root=false){ public static function delete($path,$root=false) {
$cached=OC_FileCache_Cached::get($path,$root); $cached=OC_FileCache_Cached::get($path,$root);
if(!isset($cached['size'])){ if(!isset($cached['size'])) {
return; return;
} }
$size=$cached['size']; $size=$cached['size'];
@ -195,11 +195,11 @@ class OC_FileCache_Update{
* @param string newPath * @param string newPath
* @param string root (optional) * @param string root (optional)
*/ */
public static function rename($oldPath,$newPath,$root=false){ public static function rename($oldPath,$newPath,$root=false) {
if(!OC_FileCache::inCache($oldPath,$root)){ if(!OC_FileCache::inCache($oldPath,$root)) {
return; return;
} }
if($root===false){ if($root===false) {
$view=OC_Filesystem::getView(); $view=OC_Filesystem::getView();
}else{ }else{
$view=new OC_FilesystemView($root); $view=new OC_FilesystemView($root);

View File

@ -51,8 +51,8 @@ class OC_FileProxy{
* *
* this implements a dummy proxy for all operations * this implements a dummy proxy for all operations
*/ */
public function __call($function,$arguments){ public function __call($function,$arguments) {
if(substr($function,0,3)=='pre'){ if(substr($function,0,3)=='pre') {
return true; return true;
}else{ }else{
return $arguments[1]; return $arguments[1];
@ -63,33 +63,33 @@ class OC_FileProxy{
* register a proxy to be used * register a proxy to be used
* @param OC_FileProxy $proxy * @param OC_FileProxy $proxy
*/ */
public static function register($proxy){ public static function register($proxy) {
self::$proxies[]=$proxy; self::$proxies[]=$proxy;
} }
public static function getProxies($operation){ public static function getProxies($operation) {
$proxies=array(); $proxies=array();
foreach(self::$proxies as $proxy){ foreach(self::$proxies as $proxy) {
if(method_exists($proxy,$operation)){ if(method_exists($proxy,$operation)) {
$proxies[]=$proxy; $proxies[]=$proxy;
} }
} }
return $proxies; return $proxies;
} }
public static function runPreProxies($operation,&$filepath,&$filepath2=null){ public static function runPreProxies($operation,&$filepath,&$filepath2=null) {
if(!self::$enabled){ if(!self::$enabled) {
return true; return true;
} }
$operation='pre'.$operation; $operation='pre'.$operation;
$proxies=self::getProxies($operation); $proxies=self::getProxies($operation);
foreach($proxies as $proxy){ foreach($proxies as $proxy) {
if(!is_null($filepath2)){ if(!is_null($filepath2)) {
if($proxy->$operation($filepath,$filepath2)===false){ if($proxy->$operation($filepath,$filepath2)===false) {
return false; return false;
} }
}else{ }else{
if($proxy->$operation($filepath)===false){ if($proxy->$operation($filepath)===false) {
return false; return false;
} }
} }
@ -97,19 +97,19 @@ class OC_FileProxy{
return true; return true;
} }
public static function runPostProxies($operation,$path,$result){ public static function runPostProxies($operation,$path,$result) {
if(!self::$enabled){ if(!self::$enabled) {
return $result; return $result;
} }
$operation='post'.$operation; $operation='post'.$operation;
$proxies=self::getProxies($operation); $proxies=self::getProxies($operation);
foreach($proxies as $proxy){ foreach($proxies as $proxy) {
$result=$proxy->$operation($path,$result); $result=$proxy->$operation($path,$result);
} }
return $result; return $result;
} }
public static function clearProxies(){ public static function clearProxies() {
self::$proxies=array(); self::$proxies=array();
} }
} }

View File

@ -32,15 +32,15 @@ class OC_FileProxy_Quota extends OC_FileProxy{
* get the quota for the current user * get the quota for the current user
* @return int * @return int
*/ */
private function getQuota(){ private function getQuota() {
if($this->userQuota!=-1){ if($this->userQuota!=-1) {
return $this->userQuota; return $this->userQuota;
} }
$userQuota=OC_Preferences::getValue(OC_User::getUser(),'files','quota','default'); $userQuota=OC_Preferences::getValue(OC_User::getUser(),'files','quota','default');
if($userQuota=='default'){ if($userQuota=='default') {
$userQuota=OC_AppConfig::getValue('files','default_quota','none'); $userQuota=OC_AppConfig::getValue('files','default_quota','none');
} }
if($userQuota=='none'){ if($userQuota=='none') {
$this->userQuota=0; $this->userQuota=0;
}else{ }else{
$this->userQuota=OC_Helper::computerFileSize($userQuota); $this->userQuota=OC_Helper::computerFileSize($userQuota);
@ -53,7 +53,7 @@ class OC_FileProxy_Quota extends OC_FileProxy{
* get the free space in the users home folder * get the free space in the users home folder
* @return int * @return int
*/ */
private function getFreeSpace(){ private function getFreeSpace() {
$rootInfo=OC_FileCache_Cached::get(''); $rootInfo=OC_FileCache_Cached::get('');
// TODO Remove after merge of share_api // TODO Remove after merge of share_api
if (OC_FileCache::inCache('/Shared')) { if (OC_FileCache::inCache('/Shared')) {
@ -64,36 +64,36 @@ class OC_FileProxy_Quota extends OC_FileProxy{
$usedSpace=isset($rootInfo['size'])?$rootInfo['size']:0; $usedSpace=isset($rootInfo['size'])?$rootInfo['size']:0;
$usedSpace=isset($sharedInfo['size'])?$usedSpace-$sharedInfo['size']:$usedSpace; $usedSpace=isset($sharedInfo['size'])?$usedSpace-$sharedInfo['size']:$usedSpace;
$totalSpace=$this->getQuota(); $totalSpace=$this->getQuota();
if($totalSpace==0){ if($totalSpace==0) {
return 0; return 0;
} }
return $totalSpace-$usedSpace; return $totalSpace-$usedSpace;
} }
public function postFree_space($path,$space){ public function postFree_space($path,$space) {
$free=$this->getFreeSpace(); $free=$this->getFreeSpace();
if($free==0){ if($free==0) {
return $space; return $space;
} }
return min($free,$space); return min($free,$space);
} }
public function preFile_put_contents($path,$data){ public function preFile_put_contents($path,$data) {
if (is_resource($data)) { if (is_resource($data)) {
$data = '';//TODO: find a way to get the length of the stream without emptying it $data = '';//TODO: find a way to get the length of the stream without emptying it
} }
return (strlen($data)<$this->getFreeSpace() or $this->getFreeSpace()==0); return (strlen($data)<$this->getFreeSpace() or $this->getFreeSpace()==0);
} }
public function preCopy($path1,$path2){ public function preCopy($path1,$path2) {
return (OC_Filesystem::filesize($path1)<$this->getFreeSpace() or $this->getFreeSpace()==0); return (OC_Filesystem::filesize($path1)<$this->getFreeSpace() or $this->getFreeSpace()==0);
} }
public function preFromTmpFile($tmpfile,$path){ public function preFromTmpFile($tmpfile,$path) {
return (filesize($tmpfile)<$this->getFreeSpace() or $this->getFreeSpace()==0); return (filesize($tmpfile)<$this->getFreeSpace() or $this->getFreeSpace()==0);
} }
public function preFromUploadedFile($tmpfile,$path){ public function preFromUploadedFile($tmpfile,$path) {
return (filesize($tmpfile)<$this->getFreeSpace() or $this->getFreeSpace()==0); return (filesize($tmpfile)<$this->getFreeSpace() or $this->getFreeSpace()==0);
} }
} }

View File

@ -32,9 +32,9 @@ class OC_Files {
* get the content of a directory * get the content of a directory
* @param dir $directory path under datadirectory * @param dir $directory path under datadirectory
*/ */
public static function getDirectoryContent($directory, $mimetype_filter = ''){ public static function getDirectoryContent($directory, $mimetype_filter = '') {
$directory=OC_Filesystem::normalizePath($directory); $directory=OC_Filesystem::normalizePath($directory);
if($directory=='/'){ if($directory=='/') {
$directory=''; $directory='';
} }
$files = array(); $files = array();
@ -87,12 +87,12 @@ class OC_Files {
* @param file $file ; seperated list of files to download * @param file $file ; seperated list of files to download
* @param boolean $only_header ; boolean to only send header of the request * @param boolean $only_header ; boolean to only send header of the request
*/ */
public static function get($dir,$files, $only_header = false){ public static function get($dir,$files, $only_header = false) {
if(strpos($files,';')){ if(strpos($files,';')) {
$files=explode(';',$files); $files=explode(';',$files);
} }
if(is_array($files)){ if(is_array($files)) {
self::validateZipDownload($dir,$files); self::validateZipDownload($dir,$files);
$executionTime = intval(ini_get('max_execution_time')); $executionTime = intval(ini_get('max_execution_time'));
set_time_limit(0); set_time_limit(0);
@ -101,19 +101,19 @@ class OC_Files {
if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)!==TRUE) { if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)!==TRUE) {
exit("cannot open <$filename>\n"); exit("cannot open <$filename>\n");
} }
foreach($files as $file){ foreach($files as $file) {
$file=$dir.'/'.$file; $file=$dir.'/'.$file;
if(OC_Filesystem::is_file($file)){ if(OC_Filesystem::is_file($file)) {
$tmpFile=OC_Filesystem::toTmpFile($file); $tmpFile=OC_Filesystem::toTmpFile($file);
self::$tmpFiles[]=$tmpFile; self::$tmpFiles[]=$tmpFile;
$zip->addFile($tmpFile,basename($file)); $zip->addFile($tmpFile,basename($file));
}elseif(OC_Filesystem::is_dir($file)){ }elseif(OC_Filesystem::is_dir($file)) {
self::zipAddDir($file,$zip); self::zipAddDir($file,$zip);
} }
} }
$zip->close(); $zip->close();
set_time_limit($executionTime); set_time_limit($executionTime);
}elseif(OC_Filesystem::is_dir($dir.'/'.$files)){ }elseif(OC_Filesystem::is_dir($dir.'/'.$files)) {
self::validateZipDownload($dir,$files); self::validateZipDownload($dir,$files);
$executionTime = intval(ini_get('max_execution_time')); $executionTime = intval(ini_get('max_execution_time'));
set_time_limit(0); set_time_limit(0);
@ -131,18 +131,18 @@ class OC_Files {
$filename=$dir.'/'.$files; $filename=$dir.'/'.$files;
} }
@ob_end_clean(); @ob_end_clean();
if($zip or OC_Filesystem::is_readable($filename)){ if($zip or OC_Filesystem::is_readable($filename)) {
header('Content-Disposition: attachment; filename="'.basename($filename).'"'); header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Transfer-Encoding: binary'); header('Content-Transfer-Encoding: binary');
OC_Response::disableCaching(); OC_Response::disableCaching();
if($zip){ if($zip) {
ini_set('zlib.output_compression', 'off'); ini_set('zlib.output_compression', 'off');
header('Content-Type: application/zip'); header('Content-Type: application/zip');
header('Content-Length: ' . filesize($filename)); header('Content-Length: ' . filesize($filename));
}else{ }else{
header('Content-Type: '.OC_Filesystem::getMimeType($filename)); header('Content-Type: '.OC_Filesystem::getMimeType($filename));
} }
}elseif($zip or !OC_Filesystem::file_exists($filename)){ }elseif($zip or !OC_Filesystem::file_exists($filename)) {
header("HTTP/1.0 404 Not Found"); header("HTTP/1.0 404 Not Found");
$tmpl = new OC_Template( '', '404', 'guest' ); $tmpl = new OC_Template( '', '404', 'guest' );
$tmpl->assign('file',$filename); $tmpl->assign('file',$filename);
@ -151,12 +151,12 @@ class OC_Files {
header("HTTP/1.0 403 Forbidden"); header("HTTP/1.0 403 Forbidden");
die('403 Forbidden'); die('403 Forbidden');
} }
if($only_header){ if($only_header) {
if(!$zip) if(!$zip)
header("Content-Length: ".OC_Filesystem::filesize($filename)); header("Content-Length: ".OC_Filesystem::filesize($filename));
return ; return ;
} }
if($zip){ if($zip) {
$handle=fopen($filename,'r'); $handle=fopen($filename,'r');
if ($handle) { if ($handle) {
$chunkSize = 8*1024;// 1 MB chunks $chunkSize = 8*1024;// 1 MB chunks
@ -169,26 +169,26 @@ class OC_Files {
}else{ }else{
OC_Filesystem::readfile($filename); OC_Filesystem::readfile($filename);
} }
foreach(self::$tmpFiles as $tmpFile){ foreach(self::$tmpFiles as $tmpFile) {
if(file_exists($tmpFile) and is_file($tmpFile)){ if(file_exists($tmpFile) and is_file($tmpFile)) {
unlink($tmpFile); unlink($tmpFile);
} }
} }
} }
public static function zipAddDir($dir,$zip,$internalDir=''){ public static function zipAddDir($dir,$zip,$internalDir='') {
$dirname=basename($dir); $dirname=basename($dir);
$zip->addEmptyDir($internalDir.$dirname); $zip->addEmptyDir($internalDir.$dirname);
$internalDir.=$dirname.='/'; $internalDir.=$dirname.='/';
$files=OC_Files::getdirectorycontent($dir); $files=OC_Files::getdirectorycontent($dir);
foreach($files as $file){ foreach($files as $file) {
$filename=$file['name']; $filename=$file['name'];
$file=$dir.'/'.$filename; $file=$dir.'/'.$filename;
if(OC_Filesystem::is_file($file)){ if(OC_Filesystem::is_file($file)) {
$tmpFile=OC_Filesystem::toTmpFile($file); $tmpFile=OC_Filesystem::toTmpFile($file);
OC_Files::$tmpFiles[]=$tmpFile; OC_Files::$tmpFiles[]=$tmpFile;
$zip->addFile($tmpFile,$internalDir.$filename); $zip->addFile($tmpFile,$internalDir.$filename);
}elseif(OC_Filesystem::is_dir($file)){ }elseif(OC_Filesystem::is_dir($file)) {
self::zipAddDir($file,$zip,$internalDir); self::zipAddDir($file,$zip,$internalDir);
} }
} }
@ -201,8 +201,8 @@ class OC_Files {
* @param dir $targetDir * @param dir $targetDir
* @param file $target * @param file $target
*/ */
public static function move($sourceDir,$source,$targetDir,$target){ public static function move($sourceDir,$source,$targetDir,$target) {
if(OC_User::isLoggedIn() && ($sourceDir != '' || $source != 'Shared')){ if(OC_User::isLoggedIn() && ($sourceDir != '' || $source != 'Shared')) {
$targetFile=self::normalizePath($targetDir.'/'.$target); $targetFile=self::normalizePath($targetDir.'/'.$target);
$sourceFile=self::normalizePath($sourceDir.'/'.$source); $sourceFile=self::normalizePath($sourceDir.'/'.$source);
return OC_Filesystem::rename($sourceFile,$targetFile); return OC_Filesystem::rename($sourceFile,$targetFile);
@ -219,8 +219,8 @@ class OC_Files {
* @param dir $targetDir * @param dir $targetDir
* @param file $target * @param file $target
*/ */
public static function copy($sourceDir,$source,$targetDir,$target){ public static function copy($sourceDir,$source,$targetDir,$target) {
if(OC_User::isLoggedIn()){ if(OC_User::isLoggedIn()) {
$targetFile=$targetDir.'/'.$target; $targetFile=$targetDir.'/'.$target;
$sourceFile=$sourceDir.'/'.$source; $sourceFile=$sourceDir.'/'.$source;
return OC_Filesystem::copy($sourceFile,$targetFile); return OC_Filesystem::copy($sourceFile,$targetFile);
@ -234,14 +234,14 @@ class OC_Files {
* @param file $name * @param file $name
* @param type $type * @param type $type
*/ */
public static function newFile($dir,$name,$type){ public static function newFile($dir,$name,$type) {
if(OC_User::isLoggedIn()){ if(OC_User::isLoggedIn()) {
$file=$dir.'/'.$name; $file=$dir.'/'.$name;
if($type=='dir'){ if($type=='dir') {
return OC_Filesystem::mkdir($file); return OC_Filesystem::mkdir($file);
}elseif($type=='file'){ }elseif($type=='file') {
$fileHandle=OC_Filesystem::fopen($file, 'w'); $fileHandle=OC_Filesystem::fopen($file, 'w');
if($fileHandle){ if($fileHandle) {
fclose($fileHandle); fclose($fileHandle);
return true; return true;
}else{ }else{
@ -257,7 +257,7 @@ class OC_Files {
* @param dir $dir * @param dir $dir
* @param file $name * @param file $name
*/ */
public static function delete($dir,$file){ public static function delete($dir,$file) {
if(OC_User::isLoggedIn() && ($dir!= '' || $file != 'Shared')) { if(OC_User::isLoggedIn() && ($dir!= '' || $file != 'Shared')) {
$file=$dir.'/'.$file; $file=$dir.'/'.$file;
return OC_Filesystem::unlink($file); return OC_Filesystem::unlink($file);
@ -289,8 +289,8 @@ class OC_Files {
$zipLimit = OC_Config::getValue('maxZipInputSize', OC_Helper::computerFileSize('800 MB')); $zipLimit = OC_Config::getValue('maxZipInputSize', OC_Helper::computerFileSize('800 MB'));
if($zipLimit > 0) { if($zipLimit > 0) {
$totalsize = 0; $totalsize = 0;
if(is_array($files)){ if(is_array($files)) {
foreach($files as $file){ foreach($files as $file) {
$totalsize += OC_Filesystem::filesize($dir.'/'.$file); $totalsize += OC_Filesystem::filesize($dir.'/'.$file);
} }
}else{ }else{
@ -319,7 +319,7 @@ class OC_Files {
* @param string path * @param string path
* @return string guessed mime type * @return string guessed mime type
*/ */
static function getMimeType($path){ static function getMimeType($path) {
return OC_Filesystem::getMimeType($path); return OC_Filesystem::getMimeType($path);
} }
@ -329,7 +329,7 @@ class OC_Files {
* @param string path * @param string path
* @return array * @return array
*/ */
static function getTree($path){ static function getTree($path) {
return OC_Filesystem::getTree($path); return OC_Filesystem::getTree($path);
} }
@ -341,7 +341,7 @@ class OC_Files {
* @param string file * @param string file
* @return string guessed mime type * @return string guessed mime type
*/ */
static function pull($source,$token,$dir,$file){ static function pull($source,$token,$dir,$file) {
$tmpfile=tempnam(get_temp_dir(),'remoteCloudFile'); $tmpfile=tempnam(get_temp_dir(),'remoteCloudFile');
$fp=fopen($tmpfile,'w+'); $fp=fopen($tmpfile,'w+');
$url=$source.="/files/pull.php?token=$token"; $url=$source.="/files/pull.php?token=$token";
@ -353,7 +353,7 @@ class OC_Files {
$info=curl_getinfo($ch); $info=curl_getinfo($ch);
$httpCode=$info['http_code']; $httpCode=$info['http_code'];
curl_close($ch); curl_close($ch);
if($httpCode==200 or $httpCode==0){ if($httpCode==200 or $httpCode==0) {
OC_Filesystem::fromTmpFile($tmpfile,$dir.'/'.$file); OC_Filesystem::fromTmpFile($tmpfile,$dir.'/'.$file);
return true; return true;
}else{ }else{
@ -366,7 +366,7 @@ class OC_Files {
* @param int size filesisze in bytes * @param int size filesisze in bytes
* @return false on failure, size on success * @return false on failure, size on success
*/ */
static function setUploadLimit($size){ static function setUploadLimit($size) {
//don't allow user to break his config -- upper boundary //don't allow user to break his config -- upper boundary
if($size > PHP_INT_MAX) { if($size > PHP_INT_MAX) {
//max size is always 1 byte lower than computerFileSize returns //max size is always 1 byte lower than computerFileSize returns
@ -421,10 +421,10 @@ class OC_Files {
* @param string $path * @param string $path
* @return string * @return string
*/ */
static public function normalizePath($path){ static public function normalizePath($path) {
$path='/'.$path; $path='/'.$path;
$old=''; $old='';
while($old!=$path){//replace any multiplicity of slashes with a single one while($old!=$path) {//replace any multiplicity of slashes with a single one
$old=$path; $old=$path;
$path=str_replace('//','/',$path); $path=str_replace('//','/',$path);
} }
@ -432,10 +432,10 @@ class OC_Files {
} }
} }
function fileCmp($a,$b){ function fileCmp($a,$b) {
if($a['type']=='dir' and $b['type']!='dir'){ if($a['type']=='dir' and $b['type']!='dir') {
return -1; return -1;
}elseif($a['type']!='dir' and $b['type']=='dir'){ }elseif($a['type']!='dir' and $b['type']=='dir') {
return 1; return 1;
}else{ }else{
return strnatcasecmp($a['name'],$b['name']); return strnatcasecmp($a['name'],$b['name']);

View File

@ -34,20 +34,20 @@
abstract class OC_Filestorage_Common extends OC_Filestorage { abstract class OC_Filestorage_Common extends OC_Filestorage {
public function __construct($parameters){} public function __construct($parameters) {}
// abstract public function mkdir($path); // abstract public function mkdir($path);
// abstract public function rmdir($path); // abstract public function rmdir($path);
// abstract public function opendir($path); // abstract public function opendir($path);
public function is_dir($path){ public function is_dir($path) {
return $this->filetype($path)=='dir'; return $this->filetype($path)=='dir';
} }
public function is_file($path){ public function is_file($path) {
return $this->filetype($path)=='file'; return $this->filetype($path)=='file';
} }
// abstract public function stat($path); // abstract public function stat($path);
// abstract public function filetype($path); // abstract public function filetype($path);
public function filesize($path) { public function filesize($path) {
if($this->is_dir($path)){ if($this->is_dir($path)) {
return 0;//by definition return 0;//by definition
}else{ }else{
$stat = $this->stat($path); $stat = $this->stat($path);
@ -80,11 +80,11 @@ abstract class OC_Filestorage_Common extends OC_Filestorage {
} }
public function file_get_contents($path) { public function file_get_contents($path) {
$handle = $this->fopen($path, "r"); $handle = $this->fopen($path, "r");
if(!$handle){ if(!$handle) {
return false; return false;
} }
$size=$this->filesize($path); $size=$this->filesize($path);
if($size==0){ if($size==0) {
return ''; return '';
} }
return fread($handle, $size); return fread($handle, $size);
@ -94,8 +94,8 @@ abstract class OC_Filestorage_Common extends OC_Filestorage {
return fwrite($handle, $data); return fwrite($handle, $data);
} }
// abstract public function unlink($path); // abstract public function unlink($path);
public function rename($path1,$path2){ public function rename($path1,$path2) {
if($this->copy($path1,$path2)){ if($this->copy($path1,$path2)) {
return $this->unlink($path1); return $this->unlink($path1);
}else{ }else{
return false; return false;
@ -181,19 +181,19 @@ abstract class OC_Filestorage_Common extends OC_Filestorage {
} }
} }
public function getMimeType($path){ public function getMimeType($path) {
if(!$this->file_exists($path)){ if(!$this->file_exists($path)) {
return false; return false;
} }
if($this->is_dir($path)){ if($this->is_dir($path)) {
return 'httpd/unix-directory'; return 'httpd/unix-directory';
} }
$source=$this->fopen($path,'r'); $source=$this->fopen($path,'r');
if(!$source){ if(!$source) {
return false; return false;
} }
$head=fread($source,8192);//8kb should suffice to determine a mimetype $head=fread($source,8192);//8kb should suffice to determine a mimetype
if($pos=strrpos($path,'.')){ if($pos=strrpos($path,'.')) {
$extension=substr($path,$pos); $extension=substr($path,$pos);
}else{ }else{
$extension=''; $extension='';
@ -204,25 +204,25 @@ abstract class OC_Filestorage_Common extends OC_Filestorage {
unlink($tmpFile); unlink($tmpFile);
return $mime; return $mime;
} }
public function hash($type,$path,$raw = false){ public function hash($type,$path,$raw = false) {
$tmpFile=$this->getLocalFile(); $tmpFile=$this->getLocalFile();
$hash=hash($type,$tmpFile,$raw); $hash=hash($type,$tmpFile,$raw);
unlink($tmpFile); unlink($tmpFile);
return $hash; return $hash;
} }
// abstract public function free_space($path); // abstract public function free_space($path);
public function search($query){ public function search($query) {
return $this->searchInDir($query); return $this->searchInDir($query);
} }
public function getLocalFile($path){ public function getLocalFile($path) {
return $this->toTmpFile($path); return $this->toTmpFile($path);
} }
private function toTmpFile($path){//no longer in the storage api, still usefull here private function toTmpFile($path) {//no longer in the storage api, still usefull here
$source=$this->fopen($path,'r'); $source=$this->fopen($path,'r');
if(!$source){ if(!$source) {
return false; return false;
} }
if($pos=strrpos($path,'.')){ if($pos=strrpos($path,'.')) {
$extension=substr($path,$pos); $extension=substr($path,$pos);
}else{ }else{
$extension=''; $extension='';
@ -232,16 +232,16 @@ abstract class OC_Filestorage_Common extends OC_Filestorage {
OC_Helper::streamCopy($source,$target); OC_Helper::streamCopy($source,$target);
return $tmpFile; return $tmpFile;
} }
public function getLocalFolder($path){ public function getLocalFolder($path) {
$baseDir=OC_Helper::tmpFolder(); $baseDir=OC_Helper::tmpFolder();
$this->addLocalFolder($path,$baseDir); $this->addLocalFolder($path,$baseDir);
return $baseDir; return $baseDir;
} }
private function addLocalFolder($path,$target){ private function addLocalFolder($path,$target) {
if($dh=$this->opendir($path)){ if($dh=$this->opendir($path)) {
while($file=readdir($dh)){ while($file=readdir($dh)) {
if($file!=='.' and $file!=='..'){ if($file!=='.' and $file!=='..') {
if($this->is_dir($path.'/'.$file)){ if($this->is_dir($path.'/'.$file)) {
mkdir($target.'/'.$file); mkdir($target.'/'.$file);
$this->addLocalFolder($path.'/'.$file,$target.'/'.$file); $this->addLocalFolder($path.'/'.$file,$target.'/'.$file);
}else{ }else{
@ -254,16 +254,16 @@ abstract class OC_Filestorage_Common extends OC_Filestorage {
} }
// abstract public function touch($path, $mtime=null); // abstract public function touch($path, $mtime=null);
protected function searchInDir($query,$dir=''){ protected function searchInDir($query,$dir='') {
$files=array(); $files=array();
$dh=$this->opendir($dir); $dh=$this->opendir($dir);
if($dh){ if($dh) {
while($item=readdir($dh)){ while($item=readdir($dh)) {
if ($item == '.' || $item == '..') continue; if ($item == '.' || $item == '..') continue;
if(strstr(strtolower($item),strtolower($query))!==false){ if(strstr(strtolower($item),strtolower($query))!==false) {
$files[]=$dir.'/'.$item; $files[]=$dir.'/'.$item;
} }
if($this->is_dir($dir.'/'.$item)){ if($this->is_dir($dir.'/'.$item)) {
$files=array_merge($files,$this->searchInDir($query,$dir.'/'.$item)); $files=array_merge($files,$this->searchInDir($query,$dir.'/'.$item));
} }
} }
@ -276,7 +276,7 @@ abstract class OC_Filestorage_Common extends OC_Filestorage {
* @param int $time * @param int $time
* @return bool * @return bool
*/ */
public function hasUpdated($path,$time){ public function hasUpdated($path,$time) {
return $this->filemtime($path)>$time; return $this->filemtime($path)>$time;
} }
} }

View File

@ -32,44 +32,44 @@ class OC_Filestorage_CommonTest extends OC_Filestorage_Common{
*/ */
private $storage; private $storage;
public function __construct($params){ public function __construct($params) {
$this->storage=new OC_Filestorage_Local($params); $this->storage=new OC_Filestorage_Local($params);
} }
public function mkdir($path){ public function mkdir($path) {
return $this->storage->mkdir($path); return $this->storage->mkdir($path);
} }
public function rmdir($path){ public function rmdir($path) {
return $this->storage->rmdir($path); return $this->storage->rmdir($path);
} }
public function opendir($path){ public function opendir($path) {
return $this->storage->opendir($path); return $this->storage->opendir($path);
} }
public function stat($path){ public function stat($path) {
return $this->storage->stat($path); return $this->storage->stat($path);
} }
public function filetype($path){ public function filetype($path) {
return $this->storage->filetype($path); return $this->storage->filetype($path);
} }
public function isReadable($path){ public function isReadable($path) {
return $this->storage->isReadable($path); return $this->storage->isReadable($path);
} }
public function isUpdatable($path){ public function isUpdatable($path) {
return $this->storage->isUpdatable($path); return $this->storage->isUpdatable($path);
} }
public function file_exists($path){ public function file_exists($path) {
return $this->storage->file_exists($path); return $this->storage->file_exists($path);
} }
public function unlink($path){ public function unlink($path) {
return $this->storage->unlink($path); return $this->storage->unlink($path);
} }
public function fopen($path,$mode){ public function fopen($path,$mode) {
return $this->storage->fopen($path,$mode); return $this->storage->fopen($path,$mode);
} }
public function free_space($path){ public function free_space($path) {
return $this->storage->free_space($path); return $this->storage->free_space($path);
} }
public function touch($path, $mtime=null){ public function touch($path, $mtime=null) {
return $this->storage->touch($path,$mtime); return $this->storage->touch($path,$mtime);
} }
} }

View File

@ -4,67 +4,67 @@
*/ */
class OC_Filestorage_Local extends OC_Filestorage_Common{ class OC_Filestorage_Local extends OC_Filestorage_Common{
protected $datadir; protected $datadir;
public function __construct($arguments){ public function __construct($arguments) {
$this->datadir=$arguments['datadir']; $this->datadir=$arguments['datadir'];
if(substr($this->datadir,-1)!=='/'){ if(substr($this->datadir,-1)!=='/') {
$this->datadir.='/'; $this->datadir.='/';
} }
} }
public function mkdir($path){ public function mkdir($path) {
return @mkdir($this->datadir.$path); return @mkdir($this->datadir.$path);
} }
public function rmdir($path){ public function rmdir($path) {
return @rmdir($this->datadir.$path); return @rmdir($this->datadir.$path);
} }
public function opendir($path){ public function opendir($path) {
return opendir($this->datadir.$path); return opendir($this->datadir.$path);
} }
public function is_dir($path){ public function is_dir($path) {
if(substr($path,-1)=='/'){ if(substr($path,-1)=='/') {
$path=substr($path,0,-1); $path=substr($path,0,-1);
} }
return is_dir($this->datadir.$path); return is_dir($this->datadir.$path);
} }
public function is_file($path){ public function is_file($path) {
return is_file($this->datadir.$path); return is_file($this->datadir.$path);
} }
public function stat($path){ public function stat($path) {
return stat($this->datadir.$path); return stat($this->datadir.$path);
} }
public function filetype($path){ public function filetype($path) {
$filetype=filetype($this->datadir.$path); $filetype=filetype($this->datadir.$path);
if($filetype=='link'){ if($filetype=='link') {
$filetype=filetype(realpath($this->datadir.$path)); $filetype=filetype(realpath($this->datadir.$path));
} }
return $filetype; return $filetype;
} }
public function filesize($path){ public function filesize($path) {
if($this->is_dir($path)){ if($this->is_dir($path)) {
return 0; return 0;
}else{ }else{
return filesize($this->datadir.$path); return filesize($this->datadir.$path);
} }
} }
public function isReadable($path){ public function isReadable($path) {
return is_readable($this->datadir.$path); return is_readable($this->datadir.$path);
} }
public function isUpdatable($path){ public function isUpdatable($path) {
return is_writable($this->datadir.$path); return is_writable($this->datadir.$path);
} }
public function file_exists($path){ public function file_exists($path) {
return file_exists($this->datadir.$path); return file_exists($this->datadir.$path);
} }
public function filectime($path){ public function filectime($path) {
return filectime($this->datadir.$path); return filectime($this->datadir.$path);
} }
public function filemtime($path){ public function filemtime($path) {
return filemtime($this->datadir.$path); return filemtime($this->datadir.$path);
} }
public function touch($path, $mtime=null){ public function touch($path, $mtime=null) {
// sets the modification time of the file to the given value. // sets the modification time of the file to the given value.
// If mtime is nil the current time is set. // If mtime is nil the current time is set.
// note that the access time of the file always changes to the current time. // note that the access time of the file always changes to the current time.
if(!is_null($mtime)){ if(!is_null($mtime)) {
$result=touch( $this->datadir.$path, $mtime ); $result=touch( $this->datadir.$path, $mtime );
}else{ }else{
$result=touch( $this->datadir.$path); $result=touch( $this->datadir.$path);
@ -75,32 +75,32 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
return $result; return $result;
} }
public function file_get_contents($path){ public function file_get_contents($path) {
return file_get_contents($this->datadir.$path); return file_get_contents($this->datadir.$path);
} }
public function file_put_contents($path,$data){ public function file_put_contents($path,$data) {
return file_put_contents($this->datadir.$path,$data); return file_put_contents($this->datadir.$path,$data);
} }
public function unlink($path){ public function unlink($path) {
return $this->delTree($path); return $this->delTree($path);
} }
public function rename($path1,$path2){ public function rename($path1,$path2) {
if (!$this->isUpdatable($path1)) { if (!$this->isUpdatable($path1)) {
OC_Log::write('core','unable to rename, file is not writable : '.$path1,OC_Log::ERROR); OC_Log::write('core','unable to rename, file is not writable : '.$path1,OC_Log::ERROR);
return false; return false;
} }
if(! $this->file_exists($path1)){ if(! $this->file_exists($path1)) {
OC_Log::write('core','unable to rename, file does not exists : '.$path1,OC_Log::ERROR); OC_Log::write('core','unable to rename, file does not exists : '.$path1,OC_Log::ERROR);
return false; return false;
} }
if($return=rename($this->datadir.$path1,$this->datadir.$path2)){ if($return=rename($this->datadir.$path1,$this->datadir.$path2)) {
} }
return $return; return $return;
} }
public function copy($path1,$path2){ public function copy($path1,$path2) {
if($this->is_dir($path2)){ if($this->is_dir($path2)) {
if(!$this->file_exists($path2)){ if(!$this->file_exists($path2)) {
$this->mkdir($path2); $this->mkdir($path2);
} }
$source=substr($path1,strrpos($path1,'/')+1); $source=substr($path1,strrpos($path1,'/')+1);
@ -108,9 +108,9 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
} }
return copy($this->datadir.$path1,$this->datadir.$path2); return copy($this->datadir.$path1,$this->datadir.$path2);
} }
public function fopen($path,$mode){ public function fopen($path,$mode) {
if($return=fopen($this->datadir.$path,$mode)){ if($return=fopen($this->datadir.$path,$mode)) {
switch($mode){ switch($mode) {
case 'r': case 'r':
break; break;
case 'r+': case 'r+':
@ -127,8 +127,8 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
return $return; return $return;
} }
public function getMimeType($path){ public function getMimeType($path) {
if($this->isReadable($path)){ if($this->isReadable($path)) {
return OC_Helper::getMimeType($this->datadir.$path); return OC_Helper::getMimeType($this->datadir.$path);
}else{ }else{
return false; return false;
@ -142,46 +142,46 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
if (!is_dir($dir) || is_link($dir)) return unlink($dir); if (!is_dir($dir) || is_link($dir)) return unlink($dir);
foreach (scandir($dir) as $item) { foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue; if ($item == '.' || $item == '..') continue;
if(is_file($dir.'/'.$item)){ if(is_file($dir.'/'.$item)) {
if(unlink($dir.'/'.$item)){ if(unlink($dir.'/'.$item)) {
} }
}elseif(is_dir($dir.'/'.$item)){ }elseif(is_dir($dir.'/'.$item)) {
if (!$this->delTree($dirRelative. "/" . $item)){ if (!$this->delTree($dirRelative. "/" . $item)) {
return false; return false;
}; };
} }
} }
if($return=rmdir($dir)){ if($return=rmdir($dir)) {
} }
return $return; return $return;
} }
public function hash($path,$type,$raw=false){ public function hash($path,$type,$raw=false) {
return hash_file($type,$this->datadir.$path,$raw); return hash_file($type,$this->datadir.$path,$raw);
} }
public function free_space($path){ public function free_space($path) {
return disk_free_space($this->datadir.$path); return disk_free_space($this->datadir.$path);
} }
public function search($query){ public function search($query) {
return $this->searchInDir($query); return $this->searchInDir($query);
} }
public function getLocalFile($path){ public function getLocalFile($path) {
return $this->datadir.$path; return $this->datadir.$path;
} }
public function getLocalFolder($path){ public function getLocalFolder($path) {
return $this->datadir.$path; return $this->datadir.$path;
} }
protected function searchInDir($query,$dir=''){ protected function searchInDir($query,$dir='') {
$files=array(); $files=array();
foreach (scandir($this->datadir.$dir) as $item) { foreach (scandir($this->datadir.$dir) as $item) {
if ($item == '.' || $item == '..') continue; if ($item == '.' || $item == '..') continue;
if(strstr(strtolower($item),strtolower($query))!==false){ if(strstr(strtolower($item),strtolower($query))!==false) {
$files[]=$dir.'/'.$item; $files[]=$dir.'/'.$item;
} }
if(is_dir($this->datadir.$dir.'/'.$item)){ if(is_dir($this->datadir.$dir.'/'.$item)) {
$files=array_merge($files,$this->searchInDir($query,$dir.'/'.$item)); $files=array_merge($files,$this->searchInDir($query,$dir.'/'.$item));
} }
} }
@ -193,7 +193,7 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
* @param int $time * @param int $time
* @return bool * @return bool
*/ */
public function hasUpdated($path,$time){ public function hasUpdated($path,$time) {
return $this->filemtime($path)>$time; return $this->filemtime($path)>$time;
} }
} }

View File

@ -3,15 +3,15 @@
* local storage backnd in temporary folder for testing purpores * local storage backnd in temporary folder for testing purpores
*/ */
class OC_Filestorage_Temporary extends OC_Filestorage_Local{ class OC_Filestorage_Temporary extends OC_Filestorage_Local{
public function __construct($arguments){ public function __construct($arguments) {
$this->datadir=OC_Helper::tmpFolder(); $this->datadir=OC_Helper::tmpFolder();
} }
public function cleanUp(){ public function cleanUp() {
OC_Helper::rmdirr($this->datadir); OC_Helper::rmdirr($this->datadir);
} }
public function __destruct(){ public function __destruct() {
$this->cleanUp(); $this->cleanUp();
} }
} }

View File

@ -146,22 +146,22 @@ class OC_Filesystem{
* @param string path * @param string path
* @return string * @return string
*/ */
static public function getMountPoint($path){ static public function getMountPoint($path) {
OC_Hook::emit(self::CLASSNAME,'get_mountpoint',array('path'=>$path)); OC_Hook::emit(self::CLASSNAME,'get_mountpoint',array('path'=>$path));
if(!$path){ if(!$path) {
$path='/'; $path='/';
} }
if($path[0]!=='/'){ if($path[0]!=='/') {
$path='/'.$path; $path='/'.$path;
} }
$path=str_replace('//', '/',$path); $path=str_replace('//', '/',$path);
$foundMountPoint=''; $foundMountPoint='';
$mountPoints=array_keys(OC_Filesystem::$mounts); $mountPoints=array_keys(OC_Filesystem::$mounts);
foreach($mountPoints as $mountpoint){ foreach($mountPoints as $mountpoint) {
if($mountpoint==$path){ if($mountpoint==$path) {
return $mountpoint; return $mountpoint;
} }
if(strpos($path,$mountpoint)===0 and strlen($mountpoint)>strlen($foundMountPoint)){ if(strpos($path,$mountpoint)===0 and strlen($mountpoint)>strlen($foundMountPoint)) {
$foundMountPoint=$mountpoint; $foundMountPoint=$mountpoint;
} }
} }
@ -173,7 +173,7 @@ class OC_Filesystem{
* @param string path * @param string path
* @return bool * @return bool
*/ */
static public function getInternalPath($path){ static public function getInternalPath($path) {
$mountPoint=self::getMountPoint($path); $mountPoint=self::getMountPoint($path);
$internalPath=substr($path,strlen($mountPoint)); $internalPath=substr($path,strlen($mountPoint));
return $internalPath; return $internalPath;
@ -183,10 +183,10 @@ class OC_Filesystem{
* @param string path * @param string path
* @return OC_Filestorage * @return OC_Filestorage
*/ */
static public function getStorage($path){ static public function getStorage($path) {
$mountpoint=self::getMountPoint($path); $mountpoint=self::getMountPoint($path);
if($mountpoint){ if($mountpoint) {
if(!isset(OC_Filesystem::$storages[$mountpoint])){ if(!isset(OC_Filesystem::$storages[$mountpoint])) {
$mount=OC_Filesystem::$mounts[$mountpoint]; $mount=OC_Filesystem::$mounts[$mountpoint];
OC_Filesystem::$storages[$mountpoint]=OC_Filesystem::createStorage($mount['class'],$mount['arguments']); OC_Filesystem::$storages[$mountpoint]=OC_Filesystem::createStorage($mount['class'],$mount['arguments']);
} }
@ -194,27 +194,27 @@ class OC_Filesystem{
} }
} }
static public function init($root){ static public function init($root) {
if(self::$defaultInstance){ if(self::$defaultInstance) {
return false; return false;
} }
self::$defaultInstance=new OC_FilesystemView($root); self::$defaultInstance=new OC_FilesystemView($root);
//load custom mount config //load custom mount config
if(is_file(OC::$SERVERROOT.'/config/mount.php')){ if(is_file(OC::$SERVERROOT.'/config/mount.php')) {
$mountConfig=include(OC::$SERVERROOT.'/config/mount.php'); $mountConfig=include(OC::$SERVERROOT.'/config/mount.php');
if(isset($mountConfig['global'])){ if(isset($mountConfig['global'])) {
foreach($mountConfig['global'] as $mountPoint=>$options){ foreach($mountConfig['global'] as $mountPoint=>$options) {
self::mount($options['class'],$options['options'],$mountPoint); self::mount($options['class'],$options['options'],$mountPoint);
} }
} }
if(isset($mountConfig['group'])){ if(isset($mountConfig['group'])) {
foreach($mountConfig['group'] as $group=>$mounts){ foreach($mountConfig['group'] as $group=>$mounts) {
if(OC_Group::inGroup(OC_User::getUser(),$group)){ if(OC_Group::inGroup(OC_User::getUser(),$group)) {
foreach($mounts as $mountPoint=>$options){ foreach($mounts as $mountPoint=>$options) {
$mountPoint=self::setUserVars($mountPoint); $mountPoint=self::setUserVars($mountPoint);
foreach($options as &$option){ foreach($options as &$option) {
$option=self::setUserVars($option); $option=self::setUserVars($option);
} }
self::mount($options['class'],$options['options'],$mountPoint); self::mount($options['class'],$options['options'],$mountPoint);
@ -223,12 +223,12 @@ class OC_Filesystem{
} }
} }
if(isset($mountConfig['user'])){ if(isset($mountConfig['user'])) {
foreach($mountConfig['user'] as $user=>$mounts){ foreach($mountConfig['user'] as $user=>$mounts) {
if($user==='all' or strtolower($user)===strtolower(OC_User::getUser())){ if($user==='all' or strtolower($user)===strtolower(OC_User::getUser())) {
foreach($mounts as $mountPoint=>$options){ foreach($mounts as $mountPoint=>$options) {
$mountPoint=self::setUserVars($mountPoint); $mountPoint=self::setUserVars($mountPoint);
foreach($options as &$option){ foreach($options as &$option) {
$option=self::setUserVars($option); $option=self::setUserVars($option);
} }
self::mount($options['class'],$options['options'],$mountPoint); self::mount($options['class'],$options['options'],$mountPoint);
@ -239,7 +239,7 @@ class OC_Filesystem{
$mtime=filemtime(OC::$SERVERROOT.'/config/mount.php'); $mtime=filemtime(OC::$SERVERROOT.'/config/mount.php');
$previousMTime=OC_Appconfig::getValue('files','mountconfigmtime',0); $previousMTime=OC_Appconfig::getValue('files','mountconfigmtime',0);
if($mtime>$previousMTime){//mount config has changed, filecache needs to be updated if($mtime>$previousMTime) {//mount config has changed, filecache needs to be updated
OC_FileCache::clear(); OC_FileCache::clear();
OC_Appconfig::setValue('files','mountconfigmtime',$mtime); OC_Appconfig::setValue('files','mountconfigmtime',$mtime);
} }
@ -253,7 +253,7 @@ class OC_Filesystem{
* @param string intput * @param string intput
* @return string * @return string
*/ */
private static function setUserVars($input){ private static function setUserVars($input) {
return str_replace('$user',OC_User::getUser(),$input); return str_replace('$user',OC_User::getUser(),$input);
} }
@ -261,14 +261,14 @@ class OC_Filesystem{
* get the default filesystem view * get the default filesystem view
* @return OC_FilesystemView * @return OC_FilesystemView
*/ */
static public function getView(){ static public function getView() {
return self::$defaultInstance; return self::$defaultInstance;
} }
/** /**
* tear down the filesystem, removing all storage providers * tear down the filesystem, removing all storage providers
*/ */
static public function tearDown(){ static public function tearDown() {
self::$storages=array(); self::$storages=array();
} }
@ -278,8 +278,8 @@ class OC_Filesystem{
* @param array arguments * @param array arguments
* @return OC_Filestorage * @return OC_Filestorage
*/ */
static private function createStorage($class,$arguments){ static private function createStorage($class,$arguments) {
if(class_exists($class)){ if(class_exists($class)) {
try { try {
return new $class($arguments); return new $class($arguments);
} catch (Exception $exception) { } catch (Exception $exception) {
@ -297,7 +297,7 @@ class OC_Filesystem{
* @param string fakeRoot * @param string fakeRoot
* @return bool * @return bool
*/ */
static public function chroot($fakeRoot){ static public function chroot($fakeRoot) {
return self::$defaultInstance->chroot($fakeRoot); return self::$defaultInstance->chroot($fakeRoot);
} }
@ -307,14 +307,14 @@ class OC_Filesystem{
* *
* Returns path like /admin/files * Returns path like /admin/files
*/ */
static public function getRoot(){ static public function getRoot() {
return self::$defaultInstance->getRoot(); return self::$defaultInstance->getRoot();
} }
/** /**
* clear all mounts and storage backends * clear all mounts and storage backends
*/ */
public static function clearMounts(){ public static function clearMounts() {
self::$mounts=array(); self::$mounts=array();
self::$storages=array(); self::$storages=array();
} }
@ -324,11 +324,11 @@ class OC_Filesystem{
* @param OC_Filestorage storage * @param OC_Filestorage storage
* @param string mountpoint * @param string mountpoint
*/ */
static public function mount($class,$arguments,$mountpoint){ static public function mount($class,$arguments,$mountpoint) {
if($mountpoint[0]!='/'){ if($mountpoint[0]!='/') {
$mountpoint='/'.$mountpoint; $mountpoint='/'.$mountpoint;
} }
if(substr($mountpoint,-1)!=='/'){ if(substr($mountpoint,-1)!=='/') {
$mountpoint=$mountpoint.'/'; $mountpoint=$mountpoint.'/';
} }
self::$mounts[$mountpoint]=array('class'=>$class,'arguments'=>$arguments); self::$mounts[$mountpoint]=array('class'=>$class,'arguments'=>$arguments);
@ -340,14 +340,14 @@ class OC_Filesystem{
* @param string path * @param string path
* @return string * @return string
*/ */
static public function getLocalFile($path){ static public function getLocalFile($path) {
return self::$defaultInstance->getLocalFile($path); return self::$defaultInstance->getLocalFile($path);
} }
/** /**
* @param string path * @param string path
* @return string * @return string
*/ */
static public function getLocalFolder($path){ static public function getLocalFolder($path) {
return self::$defaultInstance->getLocalFolder($path); return self::$defaultInstance->getLocalFolder($path);
} }
@ -370,11 +370,11 @@ class OC_Filesystem{
* @param string path * @param string path
* @return bool * @return bool
*/ */
static public function isValidPath($path){ static public function isValidPath($path) {
if(!$path || $path[0]!=='/'){ if(!$path || $path[0]!=='/') {
$path='/'.$path; $path='/'.$path;
} }
if(strstr($path,'/../') || strrchr($path, '/') === '/..' ){ if(strstr($path,'/../') || strrchr($path, '/') === '/..' ) {
return false; return false;
} }
return true; return true;
@ -385,7 +385,7 @@ class OC_Filesystem{
* Listens to write and rename hooks * Listens to write and rename hooks
* @param array $data from hook * @param array $data from hook
*/ */
static public function isBlacklisted($data){ static public function isBlacklisted($data) {
$blacklist = array('.htaccess'); $blacklist = array('.htaccess');
if (isset($data['path'])) { if (isset($data['path'])) {
$path = $data['path']; $path = $data['path'];
@ -403,46 +403,46 @@ class OC_Filesystem{
/** /**
* following functions are equivilent to their php buildin equivilents for arguments/return values. * following functions are equivilent to their php buildin equivilents for arguments/return values.
*/ */
static public function mkdir($path){ static public function mkdir($path) {
return self::$defaultInstance->mkdir($path); return self::$defaultInstance->mkdir($path);
} }
static public function rmdir($path){ static public function rmdir($path) {
return self::$defaultInstance->rmdir($path); return self::$defaultInstance->rmdir($path);
} }
static public function opendir($path){ static public function opendir($path) {
return self::$defaultInstance->opendir($path); return self::$defaultInstance->opendir($path);
} }
static public function readdir($path){ static public function readdir($path) {
return self::$defaultInstance->readdir($path); return self::$defaultInstance->readdir($path);
} }
static public function is_dir($path){ static public function is_dir($path) {
return self::$defaultInstance->is_dir($path); return self::$defaultInstance->is_dir($path);
} }
static public function is_file($path){ static public function is_file($path) {
return self::$defaultInstance->is_file($path); return self::$defaultInstance->is_file($path);
} }
static public function stat($path){ static public function stat($path) {
return self::$defaultInstance->stat($path); return self::$defaultInstance->stat($path);
} }
static public function filetype($path){ static public function filetype($path) {
return self::$defaultInstance->filetype($path); return self::$defaultInstance->filetype($path);
} }
static public function filesize($path){ static public function filesize($path) {
return self::$defaultInstance->filesize($path); return self::$defaultInstance->filesize($path);
} }
static public function readfile($path){ static public function readfile($path) {
return self::$defaultInstance->readfile($path); return self::$defaultInstance->readfile($path);
} }
/** /**
* @deprecated Replaced by isReadable() as part of CRUDS * @deprecated Replaced by isReadable() as part of CRUDS
*/ */
static public function is_readable($path){ static public function is_readable($path) {
return self::$defaultInstance->is_readable($path); return self::$defaultInstance->is_readable($path);
} }
/** /**
* @deprecated Replaced by isCreatable(), isUpdatable(), isDeletable() as part of CRUDS * @deprecated Replaced by isCreatable(), isUpdatable(), isDeletable() as part of CRUDS
*/ */
static public function is_writable($path){ static public function is_writable($path) {
return self::$defaultInstance->is_writable($path); return self::$defaultInstance->is_writable($path);
} }
static public function isCreatable($path) { static public function isCreatable($path) {
@ -460,55 +460,55 @@ class OC_Filesystem{
static public function isSharable($path) { static public function isSharable($path) {
return self::$defaultInstance->isSharable($path); return self::$defaultInstance->isSharable($path);
} }
static public function file_exists($path){ static public function file_exists($path) {
return self::$defaultInstance->file_exists($path); return self::$defaultInstance->file_exists($path);
} }
static public function filectime($path){ static public function filectime($path) {
return self::$defaultInstance->filectime($path); return self::$defaultInstance->filectime($path);
} }
static public function filemtime($path){ static public function filemtime($path) {
return self::$defaultInstance->filemtime($path); return self::$defaultInstance->filemtime($path);
} }
static public function touch($path, $mtime=null){ static public function touch($path, $mtime=null) {
return self::$defaultInstance->touch($path, $mtime); return self::$defaultInstance->touch($path, $mtime);
} }
static public function file_get_contents($path){ static public function file_get_contents($path) {
return self::$defaultInstance->file_get_contents($path); return self::$defaultInstance->file_get_contents($path);
} }
static public function file_put_contents($path,$data){ static public function file_put_contents($path,$data) {
return self::$defaultInstance->file_put_contents($path,$data); return self::$defaultInstance->file_put_contents($path,$data);
} }
static public function unlink($path){ static public function unlink($path) {
return self::$defaultInstance->unlink($path); return self::$defaultInstance->unlink($path);
} }
static public function rename($path1,$path2){ static public function rename($path1,$path2) {
return self::$defaultInstance->rename($path1,$path2); return self::$defaultInstance->rename($path1,$path2);
} }
static public function copy($path1,$path2){ static public function copy($path1,$path2) {
return self::$defaultInstance->copy($path1,$path2); return self::$defaultInstance->copy($path1,$path2);
} }
static public function fopen($path,$mode){ static public function fopen($path,$mode) {
return self::$defaultInstance->fopen($path,$mode); return self::$defaultInstance->fopen($path,$mode);
} }
static public function toTmpFile($path){ static public function toTmpFile($path) {
return self::$defaultInstance->toTmpFile($path); return self::$defaultInstance->toTmpFile($path);
} }
static public function fromTmpFile($tmpFile,$path){ static public function fromTmpFile($tmpFile,$path) {
return self::$defaultInstance->fromTmpFile($tmpFile,$path); return self::$defaultInstance->fromTmpFile($tmpFile,$path);
} }
static public function getMimeType($path){ static public function getMimeType($path) {
return self::$defaultInstance->getMimeType($path); return self::$defaultInstance->getMimeType($path);
} }
static public function hash($type,$path, $raw = false){ static public function hash($type,$path, $raw = false) {
return self::$defaultInstance->hash($type,$path, $raw); return self::$defaultInstance->hash($type,$path, $raw);
} }
static public function free_space($path='/'){ static public function free_space($path='/') {
return self::$defaultInstance->free_space($path); return self::$defaultInstance->free_space($path);
} }
static public function search($query){ static public function search($query) {
return OC_FileCache::search($query); return OC_FileCache::search($query);
} }
@ -517,7 +517,7 @@ class OC_Filesystem{
* @param int $time * @param int $time
* @return bool * @return bool
*/ */
static public function hasUpdated($path,$time){ static public function hasUpdated($path,$time) {
return self::$defaultInstance->hasUpdated($path,$time); return self::$defaultInstance->hasUpdated($path,$time);
} }
@ -536,26 +536,26 @@ class OC_Filesystem{
* @param bool $stripTrailingSlash * @param bool $stripTrailingSlash
* @return string * @return string
*/ */
public static function normalizePath($path,$stripTrailingSlash=true){ public static function normalizePath($path,$stripTrailingSlash=true) {
if($path==''){ if($path=='') {
return '/'; return '/';
} }
//no windows style slashes //no windows style slashes
$path=str_replace('\\','/',$path); $path=str_replace('\\','/',$path);
//add leading slash //add leading slash
if($path[0]!=='/'){ if($path[0]!=='/') {
$path='/'.$path; $path='/'.$path;
} }
//remove trainling slash //remove trainling slash
if($stripTrailingSlash and strlen($path)>1 and substr($path,-1,1)==='/'){ if($stripTrailingSlash and strlen($path)>1 and substr($path,-1,1)==='/') {
$path=substr($path,0,-1); $path=substr($path,0,-1);
} }
//remove duplicate slashes //remove duplicate slashes
while(strpos($path,'//')!==false){ while(strpos($path,'//')!==false) {
$path=str_replace('//','/',$path); $path=str_replace('//','/',$path);
} }
//normalize unicode if possible //normalize unicode if possible
if(class_exists('Normalizer')){ if(class_exists('Normalizer')) {
$path=Normalizer::normalize($path); $path=Normalizer::normalize($path);
} }
return $path; return $path;

View File

@ -48,10 +48,10 @@ class OC_FilesystemView {
} }
public function getAbsolutePath($path) { public function getAbsolutePath($path) {
if(!$path){ if(!$path) {
$path='/'; $path='/';
} }
if($path[0]!=='/'){ if($path[0]!=='/') {
$path='/'.$path; $path='/'.$path;
} }
return $this->fakeRoot.$path; return $this->fakeRoot.$path;
@ -63,7 +63,7 @@ class OC_FilesystemView {
* @return bool * @return bool
*/ */
public function chroot($fakeRoot) { public function chroot($fakeRoot) {
if(!$fakeRoot==''){ if(!$fakeRoot=='') {
if($fakeRoot[0]!=='/') { if($fakeRoot[0]!=='/') {
$fakeRoot='/'.$fakeRoot; $fakeRoot='/'.$fakeRoot;
} }
@ -104,7 +104,7 @@ class OC_FilesystemView {
return null; return null;
}else{ }else{
$path=substr($path, strlen($this->fakeRoot)); $path=substr($path, strlen($this->fakeRoot));
if(strlen($path)===0){ if(strlen($path)===0) {
return '/'; return '/';
}else{ }else{
return $path; return $path;
@ -177,13 +177,13 @@ class OC_FilesystemView {
return $fsLocal->readdir( $handle ); return $fsLocal->readdir( $handle );
} }
public function is_dir($path) { public function is_dir($path) {
if($path=='/'){ if($path=='/') {
return true; return true;
} }
return $this->basicOperation('is_dir', $path); return $this->basicOperation('is_dir', $path);
} }
public function is_file($path) { public function is_file($path) {
if($path=='/'){ if($path=='/') {
return false; return false;
} }
return $this->basicOperation('is_file', $path); return $this->basicOperation('is_file', $path);
@ -214,13 +214,13 @@ class OC_FilesystemView {
/** /**
* @deprecated Replaced by isReadable() as part of CRUDS * @deprecated Replaced by isReadable() as part of CRUDS
*/ */
public function is_readable($path){ public function is_readable($path) {
return $this->basicOperation('isReadable',$path); return $this->basicOperation('isReadable',$path);
} }
/** /**
* @deprecated Replaced by isCreatable(), isUpdatable(), isDeletable() as part of CRUDS * @deprecated Replaced by isCreatable(), isUpdatable(), isDeletable() as part of CRUDS
*/ */
public function is_writable($path){ public function is_writable($path) {
return $this->basicOperation('isUpdatable',$path); return $this->basicOperation('isUpdatable',$path);
} }
public function isCreatable($path) { public function isCreatable($path) {
@ -239,7 +239,7 @@ class OC_FilesystemView {
return $this->basicOperation('isSharable', $path); return $this->basicOperation('isSharable', $path);
} }
public function file_exists($path) { public function file_exists($path) {
if($path=='/'){ if($path=='/') {
return true; return true;
} }
return $this->basicOperation('file_exists', $path); return $this->basicOperation('file_exists', $path);
@ -411,7 +411,7 @@ class OC_FilesystemView {
if($run) { if($run) {
$mp1=$this->getMountPoint($path1.$postFix1); $mp1=$this->getMountPoint($path1.$postFix1);
$mp2=$this->getMountPoint($path2.$postFix2); $mp2=$this->getMountPoint($path2.$postFix2);
if($mp1 == $mp2){ if($mp1 == $mp2) {
if($storage = $this->getStorage($path1.$postFix1)) { if($storage = $this->getStorage($path1.$postFix1)) {
$result=$storage->copy($this->getInternalPath($path1.$postFix1), $this->getInternalPath($path2.$postFix2)); $result=$storage->copy($this->getInternalPath($path1.$postFix1), $this->getInternalPath($path2.$postFix2));
} }
@ -579,7 +579,7 @@ class OC_FilesystemView {
return null; return null;
} }
private function runHooks($hooks,$path,$post=false){ private function runHooks($hooks,$path,$post=false) {
$prefix=($post)?'post_':''; $prefix=($post)?'post_':'';
$run=true; $run=true;
if(OC_Filesystem::$loaded and $this->fakeRoot==OC_Filesystem::getRoot()) { if(OC_Filesystem::$loaded and $this->fakeRoot==OC_Filesystem::getRoot()) {

View File

@ -12,11 +12,11 @@ class OC_Geo{
* @param (string) $longitude - Longitude * @param (string) $longitude - Longitude
* @return (string) $timezone - closest timezone * @return (string) $timezone - closest timezone
*/ */
public static function timezone($latitude, $longitude){ public static function timezone($latitude, $longitude) {
$alltimezones = DateTimeZone::listIdentifiers(); $alltimezones = DateTimeZone::listIdentifiers();
$variances = array(); $variances = array();
//calculate for all timezones the system know //calculate for all timezones the system know
foreach($alltimezones as $timezone){ foreach($alltimezones as $timezone) {
$datetimezoneobj = new DateTimeZone($timezone); $datetimezoneobj = new DateTimeZone($timezone);
$locationinformations = $datetimezoneobj->getLocation(); $locationinformations = $datetimezoneobj->getLocation();
$latitudeoftimezone = $locationinformations['latitude']; $latitudeoftimezone = $locationinformations['latitude'];

View File

@ -42,8 +42,8 @@ class OC_Group {
* @param string $backend The backend to use for user managment * @param string $backend The backend to use for user managment
* @returns true/false * @returns true/false
*/ */
public static function useBackend( $backend ){ public static function useBackend( $backend ) {
if($backend instanceof OC_Group_Interface){ if($backend instanceof OC_Group_Interface) {
self::$_usedBackends[]=$backend; self::$_usedBackends[]=$backend;
} }
} }
@ -51,7 +51,7 @@ class OC_Group {
/** /**
* remove all used backends * remove all used backends
*/ */
public static function clearBackends(){ public static function clearBackends() {
self::$_usedBackends=array(); self::$_usedBackends=array();
} }
@ -65,27 +65,27 @@ class OC_Group {
* *
* Allowed characters in the username are: "a-z", "A-Z", "0-9" and "_.@-" * Allowed characters in the username are: "a-z", "A-Z", "0-9" and "_.@-"
*/ */
public static function createGroup( $gid ){ public static function createGroup( $gid ) {
// Check the name for bad characters // Check the name for bad characters
// Allowed are: "a-z", "A-Z", "0-9" and "_.@-" // Allowed are: "a-z", "A-Z", "0-9" and "_.@-"
if( preg_match( '/[^a-zA-Z0-9 _\.@\-]/', $gid )){ if( preg_match( '/[^a-zA-Z0-9 _\.@\-]/', $gid )) {
return false; return false;
} }
// No empty group names! // No empty group names!
if( !$gid ){ if( !$gid ) {
return false; return false;
} }
// No duplicate group names // No duplicate group names
if( in_array( $gid, self::getGroups())){ if( in_array( $gid, self::getGroups())) {
return false; return false;
} }
$run = true; $run = true;
OC_Hook::emit( "OC_Group", "pre_createGroup", array( "run" => &$run, "gid" => $gid )); OC_Hook::emit( "OC_Group", "pre_createGroup", array( "run" => &$run, "gid" => $gid ));
if($run){ if($run) {
//create the group in the first backend that supports creating groups //create the group in the first backend that supports creating groups
foreach(self::$_usedBackends as $backend){ foreach(self::$_usedBackends as $backend) {
if(!$backend->implementsActions(OC_GROUP_BACKEND_CREATE_GROUP)) if(!$backend->implementsActions(OC_GROUP_BACKEND_CREATE_GROUP))
continue; continue;
@ -106,18 +106,18 @@ class OC_Group {
* *
* Deletes a group and removes it from the group_user-table * Deletes a group and removes it from the group_user-table
*/ */
public static function deleteGroup( $gid ){ public static function deleteGroup( $gid ) {
// Prevent users from deleting group admin // Prevent users from deleting group admin
if( $gid == "admin" ){ if( $gid == "admin" ) {
return false; return false;
} }
$run = true; $run = true;
OC_Hook::emit( "OC_Group", "pre_deleteGroup", array( "run" => &$run, "gid" => $gid )); OC_Hook::emit( "OC_Group", "pre_deleteGroup", array( "run" => &$run, "gid" => $gid ));
if($run){ if($run) {
//delete the group from all backends //delete the group from all backends
foreach(self::$_usedBackends as $backend){ foreach(self::$_usedBackends as $backend) {
if(!$backend->implementsActions(OC_GROUP_BACKEND_DELETE_GROUP)) if(!$backend->implementsActions(OC_GROUP_BACKEND_DELETE_GROUP))
continue; continue;
@ -139,9 +139,9 @@ class OC_Group {
* *
* Checks whether the user is member of a group or not. * Checks whether the user is member of a group or not.
*/ */
public static function inGroup( $uid, $gid ){ public static function inGroup( $uid, $gid ) {
foreach(self::$_usedBackends as $backend){ foreach(self::$_usedBackends as $backend) {
if($backend->inGroup($uid,$gid)){ if($backend->inGroup($uid,$gid)) {
return true; return true;
} }
} }
@ -156,9 +156,9 @@ class OC_Group {
* *
* Adds a user to a group. * Adds a user to a group.
*/ */
public static function addToGroup( $uid, $gid ){ public static function addToGroup( $uid, $gid ) {
// Does the group exist? // Does the group exist?
if( !OC_Group::groupExists($gid)){ if( !OC_Group::groupExists($gid)) {
return false; return false;
} }
@ -166,19 +166,19 @@ class OC_Group {
$run = true; $run = true;
OC_Hook::emit( "OC_Group", "pre_addToGroup", array( "run" => &$run, "uid" => $uid, "gid" => $gid )); OC_Hook::emit( "OC_Group", "pre_addToGroup", array( "run" => &$run, "uid" => $uid, "gid" => $gid ));
if($run){ if($run) {
$succes=false; $succes=false;
//add the user to the all backends that have the group //add the user to the all backends that have the group
foreach(self::$_usedBackends as $backend){ foreach(self::$_usedBackends as $backend) {
if(!$backend->implementsActions(OC_GROUP_BACKEND_ADD_TO_GROUP)) if(!$backend->implementsActions(OC_GROUP_BACKEND_ADD_TO_GROUP))
continue; continue;
if($backend->groupExists($gid)){ if($backend->groupExists($gid)) {
$succes|=$backend->addToGroup($uid, $gid); $succes|=$backend->addToGroup($uid, $gid);
} }
} }
if($succes){ if($succes) {
OC_Hook::emit( "OC_User", "post_addToGroup", array( "uid" => $uid, "gid" => $gid )); OC_Hook::emit( "OC_User", "post_addToGroup", array( "uid" => $uid, "gid" => $gid ));
} }
return $succes; return $succes;
@ -195,13 +195,13 @@ class OC_Group {
* *
* removes the user from a group. * removes the user from a group.
*/ */
public static function removeFromGroup( $uid, $gid ){ public static function removeFromGroup( $uid, $gid ) {
$run = true; $run = true;
OC_Hook::emit( "OC_Group", "pre_removeFromGroup", array( "run" => &$run, "uid" => $uid, "gid" => $gid )); OC_Hook::emit( "OC_Group", "pre_removeFromGroup", array( "run" => &$run, "uid" => $uid, "gid" => $gid ));
if($run){ if($run) {
//remove the user from the all backends that have the group //remove the user from the all backends that have the group
foreach(self::$_usedBackends as $backend){ foreach(self::$_usedBackends as $backend) {
if(!$backend->implementsActions(OC_GROUP_BACKEND_REMOVE_FROM_GOUP)) if(!$backend->implementsActions(OC_GROUP_BACKEND_REMOVE_FROM_GOUP))
continue; continue;
@ -222,9 +222,9 @@ class OC_Group {
* This function fetches all groups a user belongs to. It does not check * This function fetches all groups a user belongs to. It does not check
* if the user exists at all. * if the user exists at all.
*/ */
public static function getUserGroups( $uid ){ public static function getUserGroups( $uid ) {
$groups=array(); $groups=array();
foreach(self::$_usedBackends as $backend){ foreach(self::$_usedBackends as $backend) {
$groups=array_merge($backend->getUserGroups($uid),$groups); $groups=array_merge($backend->getUserGroups($uid),$groups);
} }
asort($groups); asort($groups);
@ -251,9 +251,9 @@ class OC_Group {
* @param string $gid * @param string $gid
* @return bool * @return bool
*/ */
public static function groupExists($gid){ public static function groupExists($gid) {
foreach(self::$_usedBackends as $backend){ foreach(self::$_usedBackends as $backend) {
if ($backend->groupExists($gid)){ if ($backend->groupExists($gid)) {
return true; return true;
} }
} }
@ -266,7 +266,7 @@ class OC_Group {
*/ */
public static function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { public static function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
$users=array(); $users=array();
foreach(self::$_usedBackends as $backend){ foreach(self::$_usedBackends as $backend) {
$users = array_merge($backend->usersInGroup($gid, $search, $limit, $offset), $users); $users = array_merge($backend->usersInGroup($gid, $search, $limit, $offset), $users);
} }
return $users; return $users;

View File

@ -52,9 +52,9 @@ abstract class OC_Group_Backend implements OC_Group_Interface {
* Returns the supported actions as int to be * Returns the supported actions as int to be
* compared with OC_USER_BACKEND_CREATE_USER etc. * compared with OC_USER_BACKEND_CREATE_USER etc.
*/ */
public function getSupportedActions(){ public function getSupportedActions() {
$actions = 0; $actions = 0;
foreach($this->possibleActions AS $action => $methodName){ foreach($this->possibleActions AS $action => $methodName) {
if(method_exists($this, $methodName)) { if(method_exists($this, $methodName)) {
$actions |= $action; $actions |= $action;
} }
@ -71,7 +71,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface {
* Returns the supported actions as int to be * Returns the supported actions as int to be
* compared with OC_GROUP_BACKEND_CREATE_GROUP etc. * compared with OC_GROUP_BACKEND_CREATE_GROUP etc.
*/ */
public function implementsActions($actions){ public function implementsActions($actions) {
return (bool)($this->getSupportedActions() & $actions); return (bool)($this->getSupportedActions() & $actions);
} }
@ -83,7 +83,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface {
* *
* Checks whether the user is member of a group or not. * Checks whether the user is member of a group or not.
*/ */
public function inGroup($uid, $gid){ public function inGroup($uid, $gid) {
return in_array($gid, $this->getUserGroups($uid)); return in_array($gid, $this->getUserGroups($uid));
} }
@ -95,7 +95,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface {
* This function fetches all groups a user belongs to. It does not check * This function fetches all groups a user belongs to. It does not check
* if the user exists at all. * if the user exists at all.
*/ */
public function getUserGroups($uid){ public function getUserGroups($uid) {
return array(); return array();
} }
@ -115,7 +115,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface {
* @param string $gid * @param string $gid
* @return bool * @return bool
*/ */
public function groupExists($gid){ public function groupExists($gid) {
return in_array($gid, $this->getGroups($gid, 1)); return in_array($gid, $this->getGroups($gid, 1));
} }

View File

@ -50,12 +50,12 @@ class OC_Group_Database extends OC_Group_Backend {
* Trys to create a new group. If the group name already exists, false will * Trys to create a new group. If the group name already exists, false will
* be returned. * be returned.
*/ */
public function createGroup( $gid ){ public function createGroup( $gid ) {
// Check for existence // Check for existence
$stmt = OC_DB::prepare( "SELECT `gid` FROM `*PREFIX*groups` WHERE `gid` = ?" ); $stmt = OC_DB::prepare( "SELECT `gid` FROM `*PREFIX*groups` WHERE `gid` = ?" );
$result = $stmt->execute( array( $gid )); $result = $stmt->execute( array( $gid ));
if( $result->fetchRow() ){ if( $result->fetchRow() ) {
// Can not add an existing group // Can not add an existing group
return false; return false;
} }
@ -75,7 +75,7 @@ class OC_Group_Database extends OC_Group_Backend {
* *
* Deletes a group and removes it from the group_user-table * Deletes a group and removes it from the group_user-table
*/ */
public function deleteGroup( $gid ){ public function deleteGroup( $gid ) {
// Delete the group // Delete the group
$stmt = OC_DB::prepare( "DELETE FROM `*PREFIX*groups` WHERE `gid` = ?" ); $stmt = OC_DB::prepare( "DELETE FROM `*PREFIX*groups` WHERE `gid` = ?" );
$result = $stmt->execute( array( $gid )); $result = $stmt->execute( array( $gid ));
@ -95,7 +95,7 @@ class OC_Group_Database extends OC_Group_Backend {
* *
* Checks whether the user is member of a group or not. * Checks whether the user is member of a group or not.
*/ */
public function inGroup( $uid, $gid ){ public function inGroup( $uid, $gid ) {
// check // check
$stmt = OC_DB::prepare( "SELECT `uid` FROM `*PREFIX*group_user` WHERE `gid` = ? AND `uid` = ?" ); $stmt = OC_DB::prepare( "SELECT `uid` FROM `*PREFIX*group_user` WHERE `gid` = ? AND `uid` = ?" );
$result = $stmt->execute( array( $gid, $uid )); $result = $stmt->execute( array( $gid, $uid ));
@ -111,9 +111,9 @@ class OC_Group_Database extends OC_Group_Backend {
* *
* Adds a user to a group. * Adds a user to a group.
*/ */
public function addToGroup( $uid, $gid ){ public function addToGroup( $uid, $gid ) {
// No duplicate entries! // No duplicate entries!
if( !$this->inGroup( $uid, $gid )){ if( !$this->inGroup( $uid, $gid )) {
$stmt = OC_DB::prepare( "INSERT INTO `*PREFIX*group_user` ( `uid`, `gid` ) VALUES( ?, ? )" ); $stmt = OC_DB::prepare( "INSERT INTO `*PREFIX*group_user` ( `uid`, `gid` ) VALUES( ?, ? )" );
$stmt->execute( array( $uid, $gid )); $stmt->execute( array( $uid, $gid ));
return true; return true;
@ -130,7 +130,7 @@ class OC_Group_Database extends OC_Group_Backend {
* *
* removes the user from a group. * removes the user from a group.
*/ */
public function removeFromGroup( $uid, $gid ){ public function removeFromGroup( $uid, $gid ) {
$stmt = OC_DB::prepare( "DELETE FROM `*PREFIX*group_user` WHERE `uid` = ? AND `gid` = ?" ); $stmt = OC_DB::prepare( "DELETE FROM `*PREFIX*group_user` WHERE `uid` = ? AND `gid` = ?" );
$stmt->execute( array( $uid, $gid )); $stmt->execute( array( $uid, $gid ));
@ -145,13 +145,13 @@ class OC_Group_Database extends OC_Group_Backend {
* This function fetches all groups a user belongs to. It does not check * This function fetches all groups a user belongs to. It does not check
* if the user exists at all. * if the user exists at all.
*/ */
public function getUserGroups( $uid ){ public function getUserGroups( $uid ) {
// No magic! // No magic!
$stmt = OC_DB::prepare( "SELECT `gid` FROM `*PREFIX*group_user` WHERE `uid` = ?" ); $stmt = OC_DB::prepare( "SELECT `gid` FROM `*PREFIX*group_user` WHERE `uid` = ?" );
$result = $stmt->execute( array( $uid )); $result = $stmt->execute( array( $uid ));
$groups = array(); $groups = array();
while( $row = $result->fetchRow()){ while( $row = $result->fetchRow()) {
$groups[] = $row["gid"]; $groups[] = $row["gid"];
} }

View File

@ -34,8 +34,8 @@ class OC_Group_Dummy extends OC_Group_Backend {
* Trys to create a new group. If the group name already exists, false will * Trys to create a new group. If the group name already exists, false will
* be returned. * be returned.
*/ */
public function createGroup($gid){ public function createGroup($gid) {
if(!isset($this->groups[$gid])){ if(!isset($this->groups[$gid])) {
$this->groups[$gid]=array(); $this->groups[$gid]=array();
return true; return true;
}else{ }else{
@ -50,8 +50,8 @@ class OC_Group_Dummy extends OC_Group_Backend {
* *
* Deletes a group and removes it from the group_user-table * Deletes a group and removes it from the group_user-table
*/ */
public function deleteGroup($gid){ public function deleteGroup($gid) {
if(isset($this->groups[$gid])){ if(isset($this->groups[$gid])) {
unset($this->groups[$gid]); unset($this->groups[$gid]);
return true; return true;
}else{ }else{
@ -67,8 +67,8 @@ class OC_Group_Dummy extends OC_Group_Backend {
* *
* Checks whether the user is member of a group or not. * Checks whether the user is member of a group or not.
*/ */
public function inGroup($uid, $gid){ public function inGroup($uid, $gid) {
if(isset($this->groups[$gid])){ if(isset($this->groups[$gid])) {
return (array_search($uid,$this->groups[$gid])!==false); return (array_search($uid,$this->groups[$gid])!==false);
}else{ }else{
return false; return false;
@ -83,9 +83,9 @@ class OC_Group_Dummy extends OC_Group_Backend {
* *
* Adds a user to a group. * Adds a user to a group.
*/ */
public function addToGroup($uid, $gid){ public function addToGroup($uid, $gid) {
if(isset($this->groups[$gid])){ if(isset($this->groups[$gid])) {
if(array_search($uid,$this->groups[$gid])===false){ if(array_search($uid,$this->groups[$gid])===false) {
$this->groups[$gid][]=$uid; $this->groups[$gid][]=$uid;
return true; return true;
}else{ }else{
@ -104,9 +104,9 @@ class OC_Group_Dummy extends OC_Group_Backend {
* *
* removes the user from a group. * removes the user from a group.
*/ */
public function removeFromGroup($uid,$gid){ public function removeFromGroup($uid,$gid) {
if(isset($this->groups[$gid])){ if(isset($this->groups[$gid])) {
if(($index=array_search($uid,$this->groups[$gid]))!==false){ if(($index=array_search($uid,$this->groups[$gid]))!==false) {
unset($this->groups[$gid][$index]); unset($this->groups[$gid][$index]);
}else{ }else{
return false; return false;
@ -124,11 +124,11 @@ class OC_Group_Dummy extends OC_Group_Backend {
* This function fetches all groups a user belongs to. It does not check * This function fetches all groups a user belongs to. It does not check
* if the user exists at all. * if the user exists at all.
*/ */
public function getUserGroups($uid){ public function getUserGroups($uid) {
$groups=array(); $groups=array();
$allGroups=array_keys($this->groups); $allGroups=array_keys($this->groups);
foreach($allGroups as $group){ foreach($allGroups as $group) {
if($this->inGroup($uid,$group)){ if($this->inGroup($uid,$group)) {
$groups[]=$group; $groups[]=$group;
} }
} }
@ -150,7 +150,7 @@ class OC_Group_Dummy extends OC_Group_Backend {
* @returns array with user ids * @returns array with user ids
*/ */
public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
if(isset($this->groups[$gid])){ if(isset($this->groups[$gid])) {
return $this->groups[$gid]; return $this->groups[$gid];
}else{ }else{
return array(); return array();

View File

@ -37,12 +37,12 @@ class OC_Helper {
* *
* Returns a url to the given app and file. * Returns a url to the given app and file.
*/ */
public static function linkTo( $app, $file, $args = array() ){ public static function linkTo( $app, $file, $args = array() ) {
if( $app != '' ){ if( $app != '' ) {
$app_path = OC_App::getAppPath($app); $app_path = OC_App::getAppPath($app);
// Check if the app is in the app folder // Check if the app is in the app folder
if( $app_path && file_exists( $app_path.'/'.$file )){ if( $app_path && file_exists( $app_path.'/'.$file )) {
if(substr($file, -3) == 'php' || substr($file, -3) == 'css'){ if(substr($file, -3) == 'php' || substr($file, -3) == 'css') {
$urlLinkTo = OC::$WEBROOT . '/?app=' . $app; $urlLinkTo = OC::$WEBROOT . '/?app=' . $app;
$urlLinkTo .= ($file!='index.php')?'&getfile=' . urlencode($file):''; $urlLinkTo .= ($file!='index.php')?'&getfile=' . urlencode($file):'';
}else{ }else{
@ -54,7 +54,7 @@ class OC_Helper {
} }
} }
else{ else{
if( file_exists( OC::$SERVERROOT . '/core/'. $file )){ if( file_exists( OC::$SERVERROOT . '/core/'. $file )) {
$urlLinkTo = OC::$WEBROOT . '/core/'.$file; $urlLinkTo = OC::$WEBROOT . '/core/'.$file;
} }
else{ else{
@ -125,22 +125,22 @@ class OC_Helper {
* *
* Returns the path to the image. * Returns the path to the image.
*/ */
public static function imagePath( $app, $image ){ public static function imagePath( $app, $image ) {
// Read the selected theme from the config file // Read the selected theme from the config file
$theme=OC_Config::getValue( "theme" ); $theme=OC_Config::getValue( "theme" );
// Check if the app is in the app folder // Check if the app is in the app folder
if( file_exists( OC::$SERVERROOT."/themes/$theme/apps/$app/img/$image" )){ if( file_exists( OC::$SERVERROOT."/themes/$theme/apps/$app/img/$image" )) {
return OC::$WEBROOT."/themes/$theme/apps/$app/img/$image"; return OC::$WEBROOT."/themes/$theme/apps/$app/img/$image";
}elseif( file_exists(OC_App::getAppPath($app)."/img/$image" )){ }elseif( file_exists(OC_App::getAppPath($app)."/img/$image" )) {
return OC_App::getAppWebPath($app)."/img/$image"; return OC_App::getAppWebPath($app)."/img/$image";
}elseif( !empty( $app ) and file_exists( OC::$SERVERROOT."/themes/$theme/$app/img/$image" )){ }elseif( !empty( $app ) and file_exists( OC::$SERVERROOT."/themes/$theme/$app/img/$image" )) {
return OC::$WEBROOT."/themes/$theme/$app/img/$image"; return OC::$WEBROOT."/themes/$theme/$app/img/$image";
}elseif( !empty( $app ) and file_exists( OC::$SERVERROOT."/$app/img/$image" )){ }elseif( !empty( $app ) and file_exists( OC::$SERVERROOT."/$app/img/$image" )) {
return OC::$WEBROOT."/$app/img/$image"; return OC::$WEBROOT."/$app/img/$image";
}elseif( file_exists( OC::$SERVERROOT."/themes/$theme/core/img/$image" )){ }elseif( file_exists( OC::$SERVERROOT."/themes/$theme/core/img/$image" )) {
return OC::$WEBROOT."/themes/$theme/core/img/$image"; return OC::$WEBROOT."/themes/$theme/core/img/$image";
}elseif( file_exists( OC::$SERVERROOT."/core/img/$image" )){ }elseif( file_exists( OC::$SERVERROOT."/core/img/$image" )) {
return OC::$WEBROOT."/core/img/$image"; return OC::$WEBROOT."/core/img/$image";
}else{ }else{
echo('image not found: image:'.$image.' webroot:'.OC::$WEBROOT.' serverroot:'.OC::$SERVERROOT); echo('image not found: image:'.$image.' webroot:'.OC::$WEBROOT.' serverroot:'.OC::$SERVERROOT);
@ -155,26 +155,26 @@ class OC_Helper {
* *
* Returns the path to the image of this file type. * Returns the path to the image of this file type.
*/ */
public static function mimetypeIcon( $mimetype ){ public static function mimetypeIcon( $mimetype ) {
$alias=array('application/xml'=>'code/xml'); $alias=array('application/xml'=>'code/xml');
if(isset($alias[$mimetype])){ if(isset($alias[$mimetype])) {
$mimetype=$alias[$mimetype]; $mimetype=$alias[$mimetype];
} }
// Replace slash with a minus // Replace slash with a minus
$mimetype = str_replace( "/", "-", $mimetype ); $mimetype = str_replace( "/", "-", $mimetype );
// Is it a dir? // Is it a dir?
if( $mimetype == "dir" ){ if( $mimetype == "dir" ) {
return OC::$WEBROOT."/core/img/filetypes/folder.png"; return OC::$WEBROOT."/core/img/filetypes/folder.png";
} }
// Icon exists? // Icon exists?
if( file_exists( OC::$SERVERROOT."/core/img/filetypes/$mimetype.png" )){ if( file_exists( OC::$SERVERROOT."/core/img/filetypes/$mimetype.png" )) {
return OC::$WEBROOT."/core/img/filetypes/$mimetype.png"; return OC::$WEBROOT."/core/img/filetypes/$mimetype.png";
} }
//try only the first part of the filetype //try only the first part of the filetype
$mimetype=substr($mimetype,0,strpos($mimetype,'-')); $mimetype=substr($mimetype,0,strpos($mimetype,'-'));
if( file_exists( OC::$SERVERROOT."/core/img/filetypes/$mimetype.png" )){ if( file_exists( OC::$SERVERROOT."/core/img/filetypes/$mimetype.png" )) {
return OC::$WEBROOT."/core/img/filetypes/$mimetype.png"; return OC::$WEBROOT."/core/img/filetypes/$mimetype.png";
} }
else{ else{
@ -189,16 +189,16 @@ class OC_Helper {
* *
* Makes 2048 to 2 kB. * Makes 2048 to 2 kB.
*/ */
public static function humanFileSize( $bytes ){ public static function humanFileSize( $bytes ) {
if( $bytes < 1024 ){ if( $bytes < 1024 ) {
return "$bytes B"; return "$bytes B";
} }
$bytes = round( $bytes / 1024, 1 ); $bytes = round( $bytes / 1024, 1 );
if( $bytes < 1024 ){ if( $bytes < 1024 ) {
return "$bytes kB"; return "$bytes kB";
} }
$bytes = round( $bytes / 1024, 1 ); $bytes = round( $bytes / 1024, 1 );
if( $bytes < 1024 ){ if( $bytes < 1024 ) {
return "$bytes MB"; return "$bytes MB";
} }
@ -216,7 +216,7 @@ class OC_Helper {
* *
* Inspired by: http://www.php.net/manual/en/function.filesize.php#92418 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
*/ */
public static function computerFileSize( $str ){ public static function computerFileSize( $str ) {
$bytes = 0; $bytes = 0;
$str=strtolower($str); $str=strtolower($str);
@ -280,17 +280,17 @@ class OC_Helper {
* *
*/ */
static function copyr($src, $dest) { static function copyr($src, $dest) {
if(is_dir($src)){ if(is_dir($src)) {
if(!is_dir($dest)){ if(!is_dir($dest)) {
mkdir($dest); mkdir($dest);
} }
$files = scandir($src); $files = scandir($src);
foreach ($files as $file){ foreach ($files as $file) {
if ($file != "." && $file != ".."){ if ($file != "." && $file != "..") {
self::copyr("$src/$file", "$dest/$file"); self::copyr("$src/$file", "$dest/$file");
} }
} }
}elseif(file_exists($src)){ }elseif(file_exists($src)) {
copy($src, $dest); copy($src, $dest);
} }
} }
@ -303,13 +303,13 @@ class OC_Helper {
static function rmdirr($dir) { static function rmdirr($dir) {
if(is_dir($dir)) { if(is_dir($dir)) {
$files=scandir($dir); $files=scandir($dir);
foreach($files as $file){ foreach($files as $file) {
if ($file != "." && $file != ".."){ if ($file != "." && $file != "..") {
self::rmdirr("$dir/$file"); self::rmdirr("$dir/$file");
} }
} }
rmdir($dir); rmdir($dir);
}elseif(file_exists($dir)){ }elseif(file_exists($dir)) {
unlink($dir); unlink($dir);
} }
if(file_exists($dir)) { if(file_exists($dir)) {
@ -323,7 +323,7 @@ class OC_Helper {
* @return string * @return string
* does NOT work for ownClouds filesystem, use OC_FileSystem::getMimeType instead * does NOT work for ownClouds filesystem, use OC_FileSystem::getMimeType instead
*/ */
static function getMimeType($path){ static function getMimeType($path) {
$isWrapped=(strpos($path,'://')!==false) and (substr($path,0,7)=='file://'); $isWrapped=(strpos($path,'://')!==false) and (substr($path,0,7)=='file://');
if (@is_dir($path)) { if (@is_dir($path)) {
@ -331,9 +331,9 @@ class OC_Helper {
return "httpd/unix-directory"; return "httpd/unix-directory";
} }
if(strpos($path,'.')){ if(strpos($path,'.')) {
//try to guess the type by the file extension //try to guess the type by the file extension
if(!self::$mimetypes || self::$mimetypes != include('mimetypes.list.php')){ if(!self::$mimetypes || self::$mimetypes != include('mimetypes.list.php')) {
self::$mimetypes=include('mimetypes.list.php'); self::$mimetypes=include('mimetypes.list.php');
} }
$extension=strtolower(strrchr(basename($path), ".")); $extension=strtolower(strrchr(basename($path), "."));
@ -343,9 +343,9 @@ class OC_Helper {
$mimeType='application/octet-stream'; $mimeType='application/octet-stream';
} }
if($mimeType=='application/octet-stream' and function_exists('finfo_open') and function_exists('finfo_file') and $finfo=finfo_open(FILEINFO_MIME)){ if($mimeType=='application/octet-stream' and function_exists('finfo_open') and function_exists('finfo_file') and $finfo=finfo_open(FILEINFO_MIME)) {
$info = @strtolower(finfo_file($finfo,$path)); $info = @strtolower(finfo_file($finfo,$path));
if($info){ if($info) {
$mimeType=substr($info,0,strpos($info,';')); $mimeType=substr($info,0,strpos($info,';'));
} }
finfo_close($finfo); finfo_close($finfo);
@ -379,8 +379,8 @@ class OC_Helper {
* @param string data * @param string data
* @return string * @return string
*/ */
static function getStringMimeType($data){ static function getStringMimeType($data) {
if(function_exists('finfo_open') and function_exists('finfo_file')){ if(function_exists('finfo_open') and function_exists('finfo_file')) {
$finfo=finfo_open(FILEINFO_MIME); $finfo=finfo_open(FILEINFO_MIME);
return finfo_buffer($finfo, $data); return finfo_buffer($finfo, $data);
}else{ }else{
@ -429,7 +429,7 @@ class OC_Helper {
* @param string optional search path, defaults to $PATH * @param string optional search path, defaults to $PATH
* @return bool true if executable program found in path * @return bool true if executable program found in path
*/ */
public static function canExecute($name, $path = false){ public static function canExecute($name, $path = false) {
// path defaults to PATH from environment if not set // path defaults to PATH from environment if not set
if ($path === false) { if ($path === false) {
$path = getenv("PATH"); $path = getenv("PATH");
@ -473,12 +473,12 @@ class OC_Helper {
* @param resource target * @param resource target
* @return int the number of bytes copied * @return int the number of bytes copied
*/ */
public static function streamCopy($source,$target){ public static function streamCopy($source,$target) {
if(!$source or !$target){ if(!$source or !$target) {
return false; return false;
} }
$count=0; $count=0;
while(!feof($source)){ while(!feof($source)) {
$count+=fwrite($target,fread($source,8192)); $count+=fwrite($target,fread($source,8192));
} }
return $count; return $count;
@ -491,7 +491,7 @@ class OC_Helper {
* *
* temporary files are automatically cleaned up after the script is finished * temporary files are automatically cleaned up after the script is finished
*/ */
public static function tmpFile($postfix=''){ public static function tmpFile($postfix='') {
$file=get_temp_dir().'/'.md5(time().rand()).$postfix; $file=get_temp_dir().'/'.md5(time().rand()).$postfix;
$fh=fopen($file,'w'); $fh=fopen($file,'w');
fclose($fh); fclose($fh);
@ -505,7 +505,7 @@ class OC_Helper {
* *
* temporary files are automatically cleaned up after the script is finished * temporary files are automatically cleaned up after the script is finished
*/ */
public static function tmpFolder(){ public static function tmpFolder() {
$path=get_temp_dir().'/'.md5(time().rand()); $path=get_temp_dir().'/'.md5(time().rand());
mkdir($path); mkdir($path);
self::$tmpFiles[]=$path; self::$tmpFiles[]=$path;
@ -515,9 +515,9 @@ class OC_Helper {
/** /**
* remove all files created by self::tmpFile * remove all files created by self::tmpFile
*/ */
public static function cleanTmp(){ public static function cleanTmp() {
$leftoversFile=get_temp_dir().'/oc-not-deleted'; $leftoversFile=get_temp_dir().'/oc-not-deleted';
if(file_exists($leftoversFile)){ if(file_exists($leftoversFile)) {
$leftovers=file($leftoversFile); $leftovers=file($leftoversFile);
foreach($leftovers as $file) { foreach($leftovers as $file) {
self::rmdirr($file); self::rmdirr($file);
@ -525,8 +525,8 @@ class OC_Helper {
unlink($leftoversFile); unlink($leftoversFile);
} }
foreach(self::$tmpFiles as $file){ foreach(self::$tmpFiles as $file) {
if(file_exists($file)){ if(file_exists($file)) {
if(!self::rmdirr($file)) { if(!self::rmdirr($file)) {
file_put_contents($leftoversFile, $file."\n", FILE_APPEND); file_put_contents($leftoversFile, $file."\n", FILE_APPEND);
} }
@ -541,8 +541,8 @@ class OC_Helper {
* @param $filename * @param $filename
* @return string * @return string
*/ */
public static function buildNotExistingFileName($path, $filename){ public static function buildNotExistingFileName($path, $filename) {
if($path==='/'){ if($path==='/') {
$path=''; $path='';
} }
if ($pos = strrpos($filename, '.')) { if ($pos = strrpos($filename, '.')) {
@ -571,21 +571,21 @@ class OC_Helper {
* @param $parent * @param $parent
* @return bool * @return bool
*/ */
public static function issubdirectory($sub, $parent){ public static function issubdirectory($sub, $parent) {
if($sub == null || $sub == '' || $parent == null || $parent == ''){ if($sub == null || $sub == '' || $parent == null || $parent == '') {
return false; return false;
} }
$realpath_sub = realpath($sub); $realpath_sub = realpath($sub);
$realpath_parent = realpath($parent); $realpath_parent = realpath($parent);
if(($realpath_sub == false && substr_count($realpath_sub, './') != 0) || ($realpath_parent == false && substr_count($realpath_parent, './') != 0)){ //it checks for both ./ and ../ if(($realpath_sub == false && substr_count($realpath_sub, './') != 0) || ($realpath_parent == false && substr_count($realpath_parent, './') != 0)) { //it checks for both ./ and ../
return false; return false;
} }
if($realpath_sub && $realpath_sub != '' && $realpath_parent && $realpath_parent != ''){ if($realpath_sub && $realpath_sub != '' && $realpath_parent && $realpath_parent != '') {
if(substr($realpath_sub, 0, strlen($realpath_parent)) == $realpath_parent){ if(substr($realpath_sub, 0, strlen($realpath_parent)) == $realpath_parent) {
return true; return true;
} }
}else{ }else{
if(substr($sub, 0, strlen($parent)) == $parent){ if(substr($sub, 0, strlen($parent)) == $parent) {
return true; return true;
} }
} }
@ -610,7 +610,7 @@ class OC_Helper {
* based on http://www.php.net/manual/en/function.array-change-key-case.php#107715 * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
* *
*/ */
public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8'){ public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER; $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
$ret = array(); $ret = array();
foreach ($input as $k => $v) { foreach ($input as $k => $v) {

View File

@ -19,12 +19,12 @@ class OC_Hook{
* *
* TODO: write example * TODO: write example
*/ */
static public function connect( $signalclass, $signalname, $slotclass, $slotname ){ static public function connect( $signalclass, $signalname, $slotclass, $slotname ) {
// Create the data structure // Create the data structure
if( !array_key_exists( $signalclass, self::$registered )){ if( !array_key_exists( $signalclass, self::$registered )) {
self::$registered[$signalclass] = array(); self::$registered[$signalclass] = array();
} }
if( !array_key_exists( $signalname, self::$registered[$signalclass] )){ if( !array_key_exists( $signalname, self::$registered[$signalclass] )) {
self::$registered[$signalclass][$signalname] = array(); self::$registered[$signalclass][$signalname] = array();
} }
@ -48,17 +48,17 @@ class OC_Hook{
* *
* TODO: write example * TODO: write example
*/ */
static public function emit( $signalclass, $signalname, $params = array()){ static public function emit( $signalclass, $signalname, $params = array()) {
// Return false if there are no slots // Return false if there are no slots
if( !array_key_exists( $signalclass, self::$registered )){ if( !array_key_exists( $signalclass, self::$registered )) {
return false; return false;
} }
if( !array_key_exists( $signalname, self::$registered[$signalclass] )){ if( !array_key_exists( $signalname, self::$registered[$signalclass] )) {
return false; return false;
} }
// Call all slots // Call all slots
foreach( self::$registered[$signalclass][$signalname] as $i ){ foreach( self::$registered[$signalclass][$signalname] as $i ) {
call_user_func( array( $i["class"], $i["name"] ), $params ); call_user_func( array( $i["class"], $i["name"] ), $params );
} }
@ -71,9 +71,9 @@ class OC_Hook{
* @param string signalclass * @param string signalclass
* @param string signalname * @param string signalname
*/ */
static public function clear($signalclass='', $signalname=''){ static public function clear($signalclass='', $signalname='') {
if($signalclass){ if($signalclass) {
if($signalname){ if($signalname) {
self::$registered[$signalclass][$signalname]=array(); self::$registered[$signalclass][$signalname]=array();
}else{ }else{
self::$registered[$signalclass]=array(); self::$registered[$signalclass]=array();

View File

@ -262,7 +262,7 @@ class OC_Image {
* @returns The orientation or -1 if no EXIF data is available. * @returns The orientation or -1 if no EXIF data is available.
*/ */
public function getOrientation() { public function getOrientation() {
if(!is_callable('exif_read_data')){ if(!is_callable('exif_read_data')) {
OC_Log::write('core','OC_Image->fixOrientation() Exif module not enabled.', OC_Log::DEBUG); OC_Log::write('core','OC_Image->fixOrientation() Exif module not enabled.', OC_Log::DEBUG);
return -1; return -1;
} }
@ -612,7 +612,7 @@ class OC_Image {
$y = ($height_orig/2) - ($height/2); $y = ($height_orig/2) - ($height/2);
$x = 0; $x = 0;
} }
if($size>0){ if($size>0) {
$targetWidth=$size; $targetWidth=$size;
$targetHeight=$size; $targetHeight=$size;
}else{ }else{
@ -666,14 +666,14 @@ class OC_Image {
return true; return true;
} }
public function destroy(){ public function destroy() {
if($this->valid()){ if($this->valid()) {
imagedestroy($this->resource); imagedestroy($this->resource);
} }
$this->resource=null; $this->resource=null;
} }
public function __destruct(){ public function __destruct() {
$this->destroy(); $this->destroy();
} }
} }

View File

@ -55,22 +55,22 @@ class OC_Installer{
* It is the task of oc_app_install to create the tables and do whatever is * It is the task of oc_app_install to create the tables and do whatever is
* needed to get the app working. * needed to get the app working.
*/ */
public static function installApp( $data = array()){ public static function installApp( $data = array()) {
if(!isset($data['source'])){ if(!isset($data['source'])) {
OC_Log::write('core','No source specified when installing app',OC_Log::ERROR); OC_Log::write('core','No source specified when installing app',OC_Log::ERROR);
return false; return false;
} }
//download the file if necesary //download the file if necesary
if($data['source']=='http'){ if($data['source']=='http') {
$path=OC_Helper::tmpFile(); $path=OC_Helper::tmpFile();
if(!isset($data['href'])){ if(!isset($data['href'])) {
OC_Log::write('core','No href specified when installing app from http',OC_Log::ERROR); OC_Log::write('core','No href specified when installing app from http',OC_Log::ERROR);
return false; return false;
} }
copy($data['href'],$path); copy($data['href'],$path);
}else{ }else{
if(!isset($data['path'])){ if(!isset($data['path'])) {
OC_Log::write('core','No path specified when installing app from local file',OC_Log::ERROR); OC_Log::write('core','No path specified when installing app from local file',OC_Log::ERROR);
return false; return false;
} }
@ -79,10 +79,10 @@ class OC_Installer{
//detect the archive type //detect the archive type
$mime=OC_Helper::getMimeType($path); $mime=OC_Helper::getMimeType($path);
if($mime=='application/zip'){ if($mime=='application/zip') {
rename($path,$path.'.zip'); rename($path,$path.'.zip');
$path.='.zip'; $path.='.zip';
}elseif($mime=='application/x-gzip'){ }elseif($mime=='application/x-gzip') {
rename($path,$path.'.tgz'); rename($path,$path.'.tgz');
$path.='.tgz'; $path.='.tgz';
}else{ }else{
@ -94,40 +94,40 @@ class OC_Installer{
$extractDir=OC_Helper::tmpFolder(); $extractDir=OC_Helper::tmpFolder();
OC_Helper::rmdirr($extractDir); OC_Helper::rmdirr($extractDir);
mkdir($extractDir); mkdir($extractDir);
if($archive=OC_Archive::open($path)){ if($archive=OC_Archive::open($path)) {
$archive->extract($extractDir); $archive->extract($extractDir);
} else { } else {
OC_Log::write('core','Failed to open archive when installing app',OC_Log::ERROR); OC_Log::write('core','Failed to open archive when installing app',OC_Log::ERROR);
OC_Helper::rmdirr($extractDir); OC_Helper::rmdirr($extractDir);
if($data['source']=='http'){ if($data['source']=='http') {
unlink($path); unlink($path);
} }
return false; return false;
} }
//load the info.xml file of the app //load the info.xml file of the app
if(!is_file($extractDir.'/appinfo/info.xml')){ if(!is_file($extractDir.'/appinfo/info.xml')) {
//try to find it in a subdir //try to find it in a subdir
$dh=opendir($extractDir); $dh=opendir($extractDir);
while($folder=readdir($dh)){ while($folder=readdir($dh)) {
if($folder[0]!='.' and is_dir($extractDir.'/'.$folder)){ if($folder[0]!='.' and is_dir($extractDir.'/'.$folder)) {
if(is_file($extractDir.'/'.$folder.'/appinfo/info.xml')){ if(is_file($extractDir.'/'.$folder.'/appinfo/info.xml')) {
$extractDir.='/'.$folder; $extractDir.='/'.$folder;
} }
} }
} }
} }
if(!is_file($extractDir.'/appinfo/info.xml')){ if(!is_file($extractDir.'/appinfo/info.xml')) {
OC_Log::write('core','App does not provide an info.xml file',OC_Log::ERROR); OC_Log::write('core','App does not provide an info.xml file',OC_Log::ERROR);
OC_Helper::rmdirr($extractDir); OC_Helper::rmdirr($extractDir);
if($data['source']=='http'){ if($data['source']=='http') {
unlink($path); unlink($path);
} }
return false; return false;
} }
$info=OC_App::getAppInfo($extractDir.'/appinfo/info.xml',true); $info=OC_App::getAppInfo($extractDir.'/appinfo/info.xml',true);
// check the code for not allowed calls // check the code for not allowed calls
if(!OC_Installer::checkCode($info['id'],$extractDir)){ if(!OC_Installer::checkCode($info['id'],$extractDir)) {
OC_Log::write('core','App can\'t be installed because of not allowed code in the App',OC_Log::ERROR); OC_Log::write('core','App can\'t be installed because of not allowed code in the App',OC_Log::ERROR);
OC_Helper::rmdirr($extractDir); OC_Helper::rmdirr($extractDir);
return false; return false;
@ -135,17 +135,17 @@ class OC_Installer{
// check if the app is compatible with this version of ownCloud // check if the app is compatible with this version of ownCloud
$version=OC_Util::getVersion(); $version=OC_Util::getVersion();
if(!isset($info['require']) or ($version[0]>$info['require'])){ if(!isset($info['require']) or ($version[0]>$info['require'])) {
OC_Log::write('core','App can\'t be installed because it is not compatible with this version of ownCloud',OC_Log::ERROR); OC_Log::write('core','App can\'t be installed because it is not compatible with this version of ownCloud',OC_Log::ERROR);
OC_Helper::rmdirr($extractDir); OC_Helper::rmdirr($extractDir);
return false; return false;
} }
//check if an app with the same id is already installed //check if an app with the same id is already installed
if(self::isInstalled( $info['id'] )){ if(self::isInstalled( $info['id'] )) {
OC_Log::write('core','App already installed',OC_Log::WARN); OC_Log::write('core','App already installed',OC_Log::WARN);
OC_Helper::rmdirr($extractDir); OC_Helper::rmdirr($extractDir);
if($data['source']=='http'){ if($data['source']=='http') {
unlink($path); unlink($path);
} }
return false; return false;
@ -153,24 +153,24 @@ class OC_Installer{
$basedir=OC_App::getInstallPath().'/'.$info['id']; $basedir=OC_App::getInstallPath().'/'.$info['id'];
//check if the destination directory already exists //check if the destination directory already exists
if(is_dir($basedir)){ if(is_dir($basedir)) {
OC_Log::write('core','App directory already exists',OC_Log::WARN); OC_Log::write('core','App directory already exists',OC_Log::WARN);
OC_Helper::rmdirr($extractDir); OC_Helper::rmdirr($extractDir);
if($data['source']=='http'){ if($data['source']=='http') {
unlink($path); unlink($path);
} }
return false; return false;
} }
if(isset($data['pretent']) and $data['pretent']==true){ if(isset($data['pretent']) and $data['pretent']==true) {
return false; return false;
} }
//copy the app to the correct place //copy the app to the correct place
if(@!mkdir($basedir)){ if(@!mkdir($basedir)) {
OC_Log::write('core','Can\'t create app folder. Please fix permissions. ('.$basedir.')',OC_Log::ERROR); OC_Log::write('core','Can\'t create app folder. Please fix permissions. ('.$basedir.')',OC_Log::ERROR);
OC_Helper::rmdirr($extractDir); OC_Helper::rmdirr($extractDir);
if($data['source']=='http'){ if($data['source']=='http') {
unlink($path); unlink($path);
} }
return false; return false;
@ -181,12 +181,12 @@ class OC_Installer{
OC_Helper::rmdirr($extractDir); OC_Helper::rmdirr($extractDir);
//install the database //install the database
if(is_file($basedir.'/appinfo/database.xml')){ if(is_file($basedir.'/appinfo/database.xml')) {
OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml'); OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
} }
//run appinfo/install.php //run appinfo/install.php
if((!isset($data['noinstall']) or $data['noinstall']==false) and file_exists($basedir.'/appinfo/install.php')){ if((!isset($data['noinstall']) or $data['noinstall']==false) and file_exists($basedir.'/appinfo/install.php')) {
include($basedir.'/appinfo/install.php'); include($basedir.'/appinfo/install.php');
} }
@ -195,10 +195,10 @@ class OC_Installer{
OC_Appconfig::setValue($info['id'],'enabled','no'); OC_Appconfig::setValue($info['id'],'enabled','no');
//set remote/public handelers //set remote/public handelers
foreach($info['remote'] as $name=>$path){ foreach($info['remote'] as $name=>$path) {
OCP\CONFIG::setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path); OCP\CONFIG::setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
} }
foreach($info['public'] as $name=>$path){ foreach($info['public'] as $name=>$path) {
OCP\CONFIG::setAppValue('core', 'public_'.$name, $info['id'].'/'.$path); OCP\CONFIG::setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
} }
@ -214,9 +214,9 @@ class OC_Installer{
* *
* Checks whether or not an app is installed, i.e. registered in apps table. * Checks whether or not an app is installed, i.e. registered in apps table.
*/ */
public static function isInstalled( $app ){ public static function isInstalled( $app ) {
if( null == OC_Appconfig::getValue( $app, "installed_version" )){ if( null == OC_Appconfig::getValue( $app, "installed_version" )) {
return false; return false;
} }
@ -250,7 +250,7 @@ class OC_Installer{
* *
* upgrade.php can determine the current installed version of the app using "OC_Appconfig::getValue($appid,'installed_version')" * upgrade.php can determine the current installed version of the app using "OC_Appconfig::getValue($appid,'installed_version')"
*/ */
public static function upgradeApp( $data = array()){ public static function upgradeApp( $data = array()) {
// TODO: write function // TODO: write function
return true; return true;
} }
@ -275,7 +275,7 @@ class OC_Installer{
* The function will not delete preferences, tables and the configuration, * The function will not delete preferences, tables and the configuration,
* this has to be done by the function oc_app_uninstall(). * this has to be done by the function oc_app_uninstall().
*/ */
public static function removeApp( $name, $options = array()){ public static function removeApp( $name, $options = array()) {
// TODO: write function // TODO: write function
return true; return true;
} }
@ -285,16 +285,16 @@ class OC_Installer{
* *
* This function installs all apps found in the 'apps' directory that should be enabled by default; * This function installs all apps found in the 'apps' directory that should be enabled by default;
*/ */
public static function installShippedApps(){ public static function installShippedApps() {
foreach(OC::$APPSROOTS as $app_dir) { foreach(OC::$APPSROOTS as $app_dir) {
if($dir = opendir( $app_dir['path'] )){ if($dir = opendir( $app_dir['path'] )) {
while( false !== ( $filename = readdir( $dir ))){ while( false !== ( $filename = readdir( $dir ))) {
if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ){ if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
if( file_exists( $app_dir['path']."/$filename/appinfo/app.php" )){ if( file_exists( $app_dir['path']."/$filename/appinfo/app.php" )) {
if(!OC_Installer::isInstalled($filename)){ if(!OC_Installer::isInstalled($filename)) {
$info=OC_App::getAppInfo($filename); $info=OC_App::getAppInfo($filename);
$enabled = isset($info['default_enable']); $enabled = isset($info['default_enable']);
if( $enabled ){ if( $enabled ) {
OC_Installer::installShippedApp($filename); OC_Installer::installShippedApp($filename);
OC_Appconfig::setValue($filename,'enabled','yes'); OC_Appconfig::setValue($filename,'enabled','yes');
} }
@ -312,24 +312,24 @@ class OC_Installer{
* @param string $app id of the app to install * @param string $app id of the app to install
* @returns array see OC_App::getAppInfo * @returns array see OC_App::getAppInfo
*/ */
public static function installShippedApp($app){ public static function installShippedApp($app) {
//install the database //install the database
if(is_file(OC_App::getAppPath($app)."/appinfo/database.xml")){ if(is_file(OC_App::getAppPath($app)."/appinfo/database.xml")) {
OC_DB::createDbFromStructure(OC_App::getAppPath($app)."/appinfo/database.xml"); OC_DB::createDbFromStructure(OC_App::getAppPath($app)."/appinfo/database.xml");
} }
//run appinfo/install.php //run appinfo/install.php
if(is_file(OC_App::getAppPath($app)."/appinfo/install.php")){ if(is_file(OC_App::getAppPath($app)."/appinfo/install.php")) {
include(OC_App::getAppPath($app)."/appinfo/install.php"); include(OC_App::getAppPath($app)."/appinfo/install.php");
} }
$info=OC_App::getAppInfo($app); $info=OC_App::getAppInfo($app);
OC_Appconfig::setValue($app,'installed_version',OC_App::getAppVersion($app)); OC_Appconfig::setValue($app,'installed_version',OC_App::getAppVersion($app));
//set remote/public handelers //set remote/public handelers
foreach($info['remote'] as $name=>$path){ foreach($info['remote'] as $name=>$path) {
OCP\CONFIG::setAppValue('core', 'remote_'.$name, $app.'/'.$path); OCP\CONFIG::setAppValue('core', 'remote_'.$name, $app.'/'.$path);
} }
foreach($info['public'] as $name=>$path){ foreach($info['public'] as $name=>$path) {
OCP\CONFIG::setAppValue('core', 'public_'.$name, $app.'/'.$path); OCP\CONFIG::setAppValue('core', 'public_'.$name, $app.'/'.$path);
} }
@ -344,7 +344,7 @@ class OC_Installer{
* @param string $folder the folder of the app to check * @param string $folder the folder of the app to check
* @returns true for app is o.k. and false for app is not o.k. * @returns true for app is o.k. and false for app is not o.k.
*/ */
public static function checkCode($appname,$folder){ public static function checkCode($appname,$folder) {
$blacklist=array( $blacklist=array(
'exec(', 'exec(',
@ -355,7 +355,7 @@ class OC_Installer{
); );
// is the code checker enabled? // is the code checker enabled?
if(OC_Config::getValue('appcodechecker', false)){ if(OC_Config::getValue('appcodechecker', false)) {
// check if grep is installed // check if grep is installed
$grep = exec('which grep'); $grep = exec('which grep');

View File

@ -11,8 +11,8 @@ class OC_JSON{
/** /**
* set Content-Type header to jsonrequest * set Content-Type header to jsonrequest
*/ */
public static function setContentTypeHeader($type='application/json'){ public static function setContentTypeHeader($type='application/json') {
if (!self::$send_content_type_header){ if (!self::$send_content_type_header) {
// We send json data // We send json data
header( 'Content-Type: '.$type ); header( 'Content-Type: '.$type );
self::$send_content_type_header = true; self::$send_content_type_header = true;
@ -22,8 +22,8 @@ class OC_JSON{
/** /**
* Check if the app is enabled, send json error msg if not * Check if the app is enabled, send json error msg if not
*/ */
public static function checkAppEnabled($app){ public static function checkAppEnabled($app) {
if( !OC_App::isEnabled($app)){ if( !OC_App::isEnabled($app)) {
$l = OC_L10N::get('lib'); $l = OC_L10N::get('lib');
self::error(array( 'data' => array( 'message' => $l->t('Application is not enabled') ))); self::error(array( 'data' => array( 'message' => $l->t('Application is not enabled') )));
exit(); exit();
@ -33,8 +33,8 @@ class OC_JSON{
/** /**
* Check if the user is logged in, send json error msg if not * Check if the user is logged in, send json error msg if not
*/ */
public static function checkLoggedIn(){ public static function checkLoggedIn() {
if( !OC_User::isLoggedIn()){ if( !OC_User::isLoggedIn()) {
$l = OC_L10N::get('lib'); $l = OC_L10N::get('lib');
self::error(array( 'data' => array( 'message' => $l->t('Authentication error') ))); self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
exit(); exit();
@ -45,8 +45,8 @@ class OC_JSON{
* @brief Check an ajax get/post call if the request token is valid. * @brief Check an ajax get/post call if the request token is valid.
* @return json Error msg if not valid. * @return json Error msg if not valid.
*/ */
public static function callCheck(){ public static function callCheck() {
if( !OC_Util::isCallRegistered()){ if( !OC_Util::isCallRegistered()) {
$l = OC_L10N::get('lib'); $l = OC_L10N::get('lib');
self::error(array( 'data' => array( 'message' => $l->t('Token expired. Please reload page.') ))); self::error(array( 'data' => array( 'message' => $l->t('Token expired. Please reload page.') )));
exit(); exit();
@ -56,9 +56,9 @@ class OC_JSON{
/** /**
* Check if the user is a admin, send json error msg if not * Check if the user is a admin, send json error msg if not
*/ */
public static function checkAdminUser(){ public static function checkAdminUser() {
self::checkLoggedIn(); self::checkLoggedIn();
if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )){ if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )) {
$l = OC_L10N::get('lib'); $l = OC_L10N::get('lib');
self::error(array( 'data' => array( 'message' => $l->t('Authentication error') ))); self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
exit(); exit();
@ -68,9 +68,9 @@ class OC_JSON{
/** /**
* Check if the user is a subadmin, send json error msg if not * Check if the user is a subadmin, send json error msg if not
*/ */
public static function checkSubAdminUser(){ public static function checkSubAdminUser() {
self::checkLoggedIn(); self::checkLoggedIn();
if(!OC_Group::inGroup(OC_User::getUser(),'admin') && !OC_SubAdmin::isSubAdmin(OC_User::getUser())){ if(!OC_Group::inGroup(OC_User::getUser(),'admin') && !OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
$l = OC_L10N::get('lib'); $l = OC_L10N::get('lib');
self::error(array( 'data' => array( 'message' => $l->t('Authentication error') ))); self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
exit(); exit();
@ -80,7 +80,7 @@ class OC_JSON{
/** /**
* Send json error msg * Send json error msg
*/ */
public static function error($data = array()){ public static function error($data = array()) {
$data['status'] = 'error'; $data['status'] = 'error';
self::encodedPrint($data); self::encodedPrint($data);
} }
@ -88,7 +88,7 @@ class OC_JSON{
/** /**
* Send json success msg * Send json success msg
*/ */
public static function success($data = array()){ public static function success($data = array()) {
$data['status'] = 'success'; $data['status'] = 'success';
self::encodedPrint($data); self::encodedPrint($data);
} }
@ -96,7 +96,7 @@ class OC_JSON{
/** /**
* Convert OC_L10N_String to string, for use in json encodings * Convert OC_L10N_String to string, for use in json encodings
*/ */
protected static function to_string(&$value){ protected static function to_string(&$value) {
if ($value instanceof OC_L10N_String) { if ($value instanceof OC_L10N_String) {
$value = (string)$value; $value = (string)$value;
} }
@ -105,10 +105,10 @@ class OC_JSON{
/** /**
* Encode and print $data in json format * Encode and print $data in json format
*/ */
public static function encodedPrint($data,$setContentType=true){ public static function encodedPrint($data,$setContentType=true) {
// Disable mimesniffing, don't move this to setContentTypeHeader! // Disable mimesniffing, don't move this to setContentTypeHeader!
header( 'X-Content-Type-Options: nosniff' ); header( 'X-Content-Type-Options: nosniff' );
if($setContentType){ if($setContentType) {
self::setContentTypeHeader(); self::setContentTypeHeader();
} }
array_walk_recursive($data, array('OC_JSON', 'to_string')); array_walk_recursive($data, array('OC_JSON', 'to_string'));

View File

@ -66,9 +66,9 @@ class OC_L10N{
* get an L10N instance * get an L10N instance
* @return OC_L10N * @return OC_L10N
*/ */
public static function get($app,$lang=null){ public static function get($app,$lang=null) {
if(is_null($lang)){ if(is_null($lang)) {
if(!isset(self::$instances[$app])){ if(!isset(self::$instances[$app])) {
self::$instances[$app]=new OC_L10N($app); self::$instances[$app]=new OC_L10N($app);
} }
return self::$instances[$app]; return self::$instances[$app];
@ -86,12 +86,12 @@ class OC_L10N{
* If language is not set, the constructor tries to find the right * If language is not set, the constructor tries to find the right
* language. * language.
*/ */
public function __construct($app, $lang = null){ public function __construct($app, $lang = null) {
$this->app = $app; $this->app = $app;
$this->lang = $lang; $this->lang = $lang;
} }
protected function init(){ protected function init() {
if ($this->app === true) { if ($this->app === true) {
return; return;
} }
@ -104,7 +104,7 @@ class OC_L10N{
} }
// Use cache if possible // Use cache if possible
if(array_key_exists($app.'::'.$lang, self::$cache)){ if(array_key_exists($app.'::'.$lang, self::$cache)) {
$this->translations = self::$cache[$app.'::'.$lang]['t']; $this->translations = self::$cache[$app.'::'.$lang]['t'];
$this->localizations = self::$cache[$app.'::'.$lang]['l']; $this->localizations = self::$cache[$app.'::'.$lang]['l'];
@ -119,15 +119,15 @@ class OC_L10N{
OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/settings')) && file_exists($i18ndir.$lang.'.php')) { OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/settings')) && file_exists($i18ndir.$lang.'.php')) {
// Include the file, save the data from $CONFIG // Include the file, save the data from $CONFIG
include(strip_tags($i18ndir).strip_tags($lang).'.php'); include(strip_tags($i18ndir).strip_tags($lang).'.php');
if(isset($TRANSLATIONS) && is_array($TRANSLATIONS)){ if(isset($TRANSLATIONS) && is_array($TRANSLATIONS)) {
$this->translations = $TRANSLATIONS; $this->translations = $TRANSLATIONS;
} }
} }
if(file_exists(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php')){ if(file_exists(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php')) {
// Include the file, save the data from $CONFIG // Include the file, save the data from $CONFIG
include(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php'); include(OC::$SERVERROOT.'/core/l10n/l10n-'.$lang.'.php');
if(isset($LOCALIZATIONS) && is_array($LOCALIZATIONS)){ if(isset($LOCALIZATIONS) && is_array($LOCALIZATIONS)) {
$this->localizations = array_merge($this->localizations, $LOCALIZATIONS); $this->localizations = array_merge($this->localizations, $LOCALIZATIONS);
} }
} }
@ -146,7 +146,7 @@ class OC_L10N{
* Returns the translation. If no translation is found, $text will be * Returns the translation. If no translation is found, $text will be
* returned. * returned.
*/ */
public function t($text, $parameters = array()){ public function t($text, $parameters = array()) {
return new OC_L10N_String($this, $text, $parameters); return new OC_L10N_String($this, $text, $parameters);
} }
@ -164,10 +164,10 @@ class OC_L10N{
* *
* *
*/ */
public function tA($textArray){ public function tA($textArray) {
OC_Log::write('core', 'DEPRECATED: the method tA is deprecated and will be removed soon.',OC_Log::WARN); OC_Log::write('core', 'DEPRECATED: the method tA is deprecated and will be removed soon.',OC_Log::WARN);
$result = array(); $result = array();
foreach($textArray as $key => $text){ foreach($textArray as $key => $text) {
$result[$key] = (string)$this->t($text); $result[$key] = (string)$this->t($text);
} }
return $result; return $result;
@ -179,7 +179,7 @@ class OC_L10N{
* *
* Returns an associative array with all translations * Returns an associative array with all translations
*/ */
public function getTranslations(){ public function getTranslations() {
$this->init(); $this->init();
return $this->translations; return $this->translations;
} }
@ -206,9 +206,9 @@ class OC_L10N{
* - l10n-field: time * - l10n-field: time
* - params: timestamp (int/string) * - params: timestamp (int/string)
*/ */
public function l($type, $data){ public function l($type, $data) {
$this->init(); $this->init();
switch($type){ switch($type) {
// If you add something don't forget to add it to $localizations // If you add something don't forget to add it to $localizations
// at the top of the page // at the top of the page
case 'date': case 'date':
@ -233,7 +233,7 @@ class OC_L10N{
* This function is useful to avoid loading thousands of files if only one * This function is useful to avoid loading thousands of files if only one
* simple string is needed, for example in appinfo.php * simple string is needed, for example in appinfo.php
*/ */
public static function selectLanguage($text){ public static function selectLanguage($text) {
$lang = self::findLanguage(array_keys($text)); $lang = self::findLanguage(array_keys($text));
return $text[$lang]; return $text[$lang];
} }
@ -249,37 +249,37 @@ class OC_L10N{
* *
* If nothing works it returns 'en' * If nothing works it returns 'en'
*/ */
public static function findLanguage($app = null){ public static function findLanguage($app = null) {
if(!is_array($app) && self::$language != ''){ if(!is_array($app) && self::$language != '') {
return self::$language; return self::$language;
} }
if(OC_User::getUser() && OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang')){ if(OC_User::getUser() && OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang')) {
$lang = OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang'); $lang = OC_Preferences::getValue(OC_User::getUser(), 'core', 'lang');
self::$language = $lang; self::$language = $lang;
if(is_array($app)){ if(is_array($app)) {
$available = $app; $available = $app;
$lang_exists = array_search($lang, $available) !== false; $lang_exists = array_search($lang, $available) !== false;
} }
else { else {
$lang_exists = self::languageExists($app, $lang); $lang_exists = self::languageExists($app, $lang);
} }
if($lang_exists){ if($lang_exists) {
return $lang; return $lang;
} }
} }
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){ if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$accepted_languages = preg_split('/,\s*/', $_SERVER['HTTP_ACCEPT_LANGUAGE']); $accepted_languages = preg_split('/,\s*/', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if(is_array($app)){ if(is_array($app)) {
$available = $app; $available = $app;
} }
else{ else{
$available = self::findAvailableLanguages($app); $available = self::findAvailableLanguages($app);
} }
foreach($accepted_languages as $i){ foreach($accepted_languages as $i) {
$temp = explode(';', $i); $temp = explode(';', $i);
if(array_search($temp[0], $available) !== false){ if(array_search($temp[0], $available) !== false) {
return $temp[0]; return $temp[0];
} }
} }
@ -294,12 +294,12 @@ class OC_L10N{
* @param $app App that needs to be translated * @param $app App that needs to be translated
* @returns directory * @returns directory
*/ */
protected static function findI18nDir($app){ protected static function findI18nDir($app) {
// find the i18n dir // find the i18n dir
$i18ndir = OC::$SERVERROOT.'/core/l10n/'; $i18ndir = OC::$SERVERROOT.'/core/l10n/';
if($app != ''){ if($app != '') {
// Check if the app is in the app folder // Check if the app is in the app folder
if(file_exists(OC_App::getAppPath($app).'/l10n/')){ if(file_exists(OC_App::getAppPath($app).'/l10n/')) {
$i18ndir = OC_App::getAppPath($app).'/l10n/'; $i18ndir = OC_App::getAppPath($app).'/l10n/';
} }
else{ else{
@ -314,13 +314,13 @@ class OC_L10N{
* @param $app App that needs to be translated * @param $app App that needs to be translated
* @returns array an array of available languages * @returns array an array of available languages
*/ */
public static function findAvailableLanguages($app=null){ public static function findAvailableLanguages($app=null) {
$available=array('en');//english is always available $available=array('en');//english is always available
$dir = self::findI18nDir($app); $dir = self::findI18nDir($app);
if(is_dir($dir)){ if(is_dir($dir)) {
$files=scandir($dir); $files=scandir($dir);
foreach($files as $file){ foreach($files as $file) {
if(substr($file, -4, 4) == '.php'){ if(substr($file, -4, 4) == '.php') {
$i = substr($file, 0, -4); $i = substr($file, 0, -4);
$available[] = $i; $available[] = $i;
} }
@ -329,12 +329,12 @@ class OC_L10N{
return $available; return $available;
} }
public static function languageExists($app, $lang){ public static function languageExists($app, $lang) {
if ($lang == 'en'){//english is always available if ($lang == 'en') {//english is always available
return true; return true;
} }
$dir = self::findI18nDir($app); $dir = self::findI18nDir($app);
if(is_dir($dir)){ if(is_dir($dir)) {
return file_exists($dir.'/'.$lang.'.php'); return file_exists($dir.'/'.$lang.'.php');
} }
return false; return false;

View File

@ -8,16 +8,16 @@
class OC_L10N_String{ class OC_L10N_String{
protected $l10n; protected $l10n;
public function __construct($l10n, $text, $parameters){ public function __construct($l10n, $text, $parameters) {
$this->l10n = $l10n; $this->l10n = $l10n;
$this->text = $text; $this->text = $text;
$this->parameters = $parameters; $this->parameters = $parameters;
} }
public function __toString(){ public function __toString() {
$translations = $this->l10n->getTranslations(); $translations = $this->l10n->getTranslations();
if(array_key_exists($this->text, $translations)){ if(array_key_exists($this->text, $translations)) {
return vsprintf($translations[$this->text], $this->parameters); return vsprintf($translations[$this->text], $this->parameters);
} }
return vsprintf($this->text, $this->parameters); return vsprintf($this->text, $this->parameters);

View File

@ -45,7 +45,7 @@ class OC_Log_Owncloud {
*/ */
public static function write($app, $message, $level) { public static function write($app, $message, $level) {
$minLevel=min(OC_Config::getValue( "loglevel", OC_Log::WARN ),OC_Log::ERROR); $minLevel=min(OC_Config::getValue( "loglevel", OC_Log::WARN ),OC_Log::ERROR);
if($level>=$minLevel){ if($level>=$minLevel) {
$entry=array('app'=>$app, 'message'=>$message, 'level'=>$level,'time'=>time()); $entry=array('app'=>$app, 'message'=>$message, 'level'=>$level,'time'=>time());
$fh=fopen(self::$logFile, 'a'); $fh=fopen(self::$logFile, 'a');
fwrite($fh, json_encode($entry)."\n"); fwrite($fh, json_encode($entry)."\n");
@ -59,7 +59,7 @@ class OC_Log_Owncloud {
* @param int offset * @param int offset
* @return array * @return array
*/ */
public static function getEntries($limit=50, $offset=0){ public static function getEntries($limit=50, $offset=0) {
self::init(); self::init();
$minLevel=OC_Config::getValue( "loglevel", OC_Log::WARN ); $minLevel=OC_Config::getValue( "loglevel", OC_Log::WARN );
$entries = array(); $entries = array();

View File

@ -39,9 +39,9 @@ class OC_Mail {
$mailo = new PHPMailer(true); $mailo = new PHPMailer(true);
if($SMTPMODE=='sendmail') { if($SMTPMODE=='sendmail') {
$mailo->IsSendmail(); $mailo->IsSendmail();
}elseif($SMTPMODE=='smtp'){ }elseif($SMTPMODE=='smtp') {
$mailo->IsSMTP(); $mailo->IsSMTP();
}elseif($SMTPMODE=='qmail'){ }elseif($SMTPMODE=='qmail') {
$mailo->IsQmail(); $mailo->IsQmail();
}else{ }else{
$mailo->IsMail(); $mailo->IsMail();

View File

@ -52,20 +52,20 @@ class OC_Migrate{
* register a new migration provider * register a new migration provider
* @param OC_Migrate_Provider $provider * @param OC_Migrate_Provider $provider
*/ */
public static function registerProvider($provider){ public static function registerProvider($provider) {
self::$providers[]=$provider; self::$providers[]=$provider;
} }
/** /**
* @brief finds and loads the providers * @brief finds and loads the providers
*/ */
static private function findProviders(){ static private function findProviders() {
// Find the providers // Find the providers
$apps = OC_App::getAllApps(); $apps = OC_App::getAllApps();
foreach($apps as $app){ foreach($apps as $app) {
$path = OC_App::getAppPath($app) . '/appinfo/migrate.php'; $path = OC_App::getAppPath($app) . '/appinfo/migrate.php';
if( file_exists( $path ) ){ if( file_exists( $path ) ) {
include( $path ); include( $path );
} }
} }
@ -78,21 +78,21 @@ class OC_Migrate{
* @param otional $path string path to zip output folder * @param otional $path string path to zip output folder
* @return false on error, path to zip on success * @return false on error, path to zip on success
*/ */
public static function export( $uid=null, $type='user', $path=null ){ public static function export( $uid=null, $type='user', $path=null ) {
$datadir = OC_Config::getValue( 'datadirectory' ); $datadir = OC_Config::getValue( 'datadirectory' );
// Validate export type // Validate export type
$types = array( 'user', 'instance', 'system', 'userfiles' ); $types = array( 'user', 'instance', 'system', 'userfiles' );
if( !in_array( $type, $types ) ){ if( !in_array( $type, $types ) ) {
OC_Log::write( 'migration', 'Invalid export type', OC_Log::ERROR ); OC_Log::write( 'migration', 'Invalid export type', OC_Log::ERROR );
return json_encode( array( array( 'success' => false ) ) ); return json_encode( array( array( 'success' => false ) ) );
} }
self::$exporttype = $type; self::$exporttype = $type;
// Userid? // Userid?
if( self::$exporttype == 'user' ){ if( self::$exporttype == 'user' ) {
// Check user exists // Check user exists
if( !is_null($uid) ){ if( !is_null($uid) ) {
$db = new OC_User_Database; $db = new OC_User_Database;
if( !$db->userExists( $uid ) ){ if( !$db->userExists( $uid ) ) {
OC_Log::write('migration', 'User: '.$uid.' is not in the database and so cannot be exported.', OC_Log::ERROR); OC_Log::write('migration', 'User: '.$uid.' is not in the database and so cannot be exported.', OC_Log::ERROR);
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
@ -102,18 +102,18 @@ class OC_Migrate{
} }
} }
// Calculate zipname // Calculate zipname
if( self::$exporttype == 'user' ){ if( self::$exporttype == 'user' ) {
$zipname = 'oc_export_' . self::$uid . '_' . date("y-m-d_H-i-s") . '.zip'; $zipname = 'oc_export_' . self::$uid . '_' . date("y-m-d_H-i-s") . '.zip';
} else { } else {
$zipname = 'oc_export_' . self::$exporttype . '_' . date("y-m-d_H-i-s") . '.zip'; $zipname = 'oc_export_' . self::$exporttype . '_' . date("y-m-d_H-i-s") . '.zip';
} }
// Calculate path // Calculate path
if( self::$exporttype == 'user' ){ if( self::$exporttype == 'user' ) {
self::$zippath = $datadir . '/' . self::$uid . '/' . $zipname; self::$zippath = $datadir . '/' . self::$uid . '/' . $zipname;
} else { } else {
if( !is_null( $path ) ){ if( !is_null( $path ) ) {
// Validate custom path // Validate custom path
if( !file_exists( $path ) || !is_writeable( $path ) ){ if( !file_exists( $path ) || !is_writeable( $path ) ) {
OC_Log::write( 'migration', 'Path supplied is invalid.', OC_Log::ERROR ); OC_Log::write( 'migration', 'Path supplied is invalid.', OC_Log::ERROR );
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
@ -124,17 +124,17 @@ class OC_Migrate{
} }
} }
// Create the zip object // Create the zip object
if( !self::createZip() ){ if( !self::createZip() ) {
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
// Do the export // Do the export
self::findProviders(); self::findProviders();
$exportdata = array(); $exportdata = array();
switch( self::$exporttype ){ switch( self::$exporttype ) {
case 'user': case 'user':
// Connect to the db // Connect to the db
self::$dbpath = $datadir . '/' . self::$uid . '/migration.db'; self::$dbpath = $datadir . '/' . self::$uid . '/migration.db';
if( !self::connectDB() ){ if( !self::connectDB() ) {
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
self::$content = new OC_Migration_Content( self::$zip, self::$MDB2 ); self::$content = new OC_Migration_Content( self::$zip, self::$MDB2 );
@ -158,14 +158,14 @@ class OC_Migrate{
// Add the export to the zip // Add the export to the zip
self::$content->addFromString( $dbexport, "dbexport.xml" ); self::$content->addFromString( $dbexport, "dbexport.xml" );
// Add user data // Add user data
foreach(OC_User::getUsers() as $user){ foreach(OC_User::getUsers() as $user) {
self::$content->addDir(OC_User::getHome($user), true, "/userdata/" ); self::$content->addDir(OC_User::getHome($user), true, "/userdata/" );
} }
break; break;
case 'userfiles': case 'userfiles':
self::$content = new OC_Migration_Content( self::$zip ); self::$content = new OC_Migration_Content( self::$zip );
// Creates a zip with all of the users files // Creates a zip with all of the users files
foreach(OC_User::getUsers() as $user){ foreach(OC_User::getUsers() as $user) {
self::$content->addDir(OC_User::getHome($user), true, "/" ); self::$content->addDir(OC_User::getHome($user), true, "/" );
} }
break; break;
@ -178,12 +178,12 @@ class OC_Migrate{
} }
break; break;
} }
if( !$info = self::getExportInfo( $exportdata ) ){ if( !$info = self::getExportInfo( $exportdata ) ) {
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
// Add the export info json to the export zip // Add the export info json to the export zip
self::$content->addFromString( $info, 'export_info.json' ); self::$content->addFromString( $info, 'export_info.json' );
if( !self::$content->finish() ){ if( !self::$content->finish() ) {
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
return json_encode( array( 'success' => true, 'data' => self::$zippath ) ); return json_encode( array( 'success' => true, 'data' => self::$zippath ) );
@ -195,22 +195,22 @@ class OC_Migrate{
* @param optional $type type of import (user or instance) * @param optional $type type of import (user or instance)
* @param optional $uid userid of new user * @param optional $uid userid of new user
*/ */
public static function import( $path, $type='user', $uid=null ){ public static function import( $path, $type='user', $uid=null ) {
$datadir = OC_Config::getValue( 'datadirectory' ); $datadir = OC_Config::getValue( 'datadirectory' );
// Extract the zip // Extract the zip
if( !$extractpath = self::extractZip( $path ) ){ if( !$extractpath = self::extractZip( $path ) ) {
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
// Get export_info.json // Get export_info.json
$scan = scandir( $extractpath ); $scan = scandir( $extractpath );
// Check for export_info.json // Check for export_info.json
if( !in_array( 'export_info.json', $scan ) ){ if( !in_array( 'export_info.json', $scan ) ) {
OC_Log::write( 'migration', 'Invalid import file, export_info.json note found', OC_Log::ERROR ); OC_Log::write( 'migration', 'Invalid import file, export_info.json note found', OC_Log::ERROR );
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
$json = json_decode( file_get_contents( $extractpath . 'export_info.json' ) ); $json = json_decode( file_get_contents( $extractpath . 'export_info.json' ) );
if( $json->exporttype != $type ){ if( $json->exporttype != $type ) {
OC_Log::write( 'migration', 'Invalid import file', OC_Log::ERROR ); OC_Log::write( 'migration', 'Invalid import file', OC_Log::ERROR );
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
@ -219,13 +219,13 @@ class OC_Migrate{
$currentuser = OC_User::getUser(); $currentuser = OC_User::getUser();
// Have we got a user if type is user // Have we got a user if type is user
if( self::$exporttype == 'user' ){ if( self::$exporttype == 'user' ) {
self::$uid = !is_null($uid) ? $uid : $currentuser; self::$uid = !is_null($uid) ? $uid : $currentuser;
} }
// We need to be an admin if we are not importing our own data // We need to be an admin if we are not importing our own data
if(($type == 'user' && self::$uid != $currentuser) || $type != 'user' ){ if(($type == 'user' && self::$uid != $currentuser) || $type != 'user' ) {
if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )){ if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )) {
// Naughty. // Naughty.
OC_Log::write( 'migration', 'Import not permitted.', OC_Log::ERROR ); OC_Log::write( 'migration', 'Import not permitted.', OC_Log::ERROR );
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
@ -233,23 +233,23 @@ class OC_Migrate{
} }
// Handle export types // Handle export types
switch( self::$exporttype ){ switch( self::$exporttype ) {
case 'user': case 'user':
// Check user availability // Check user availability
if( !OC_User::userExists( self::$uid ) ){ if( !OC_User::userExists( self::$uid ) ) {
OC_Log::write( 'migration', 'User doesn\'t exist', OC_Log::ERROR ); OC_Log::write( 'migration', 'User doesn\'t exist', OC_Log::ERROR );
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
// Copy data // Copy data
if( !self::copy_r( $extractpath . $json->exporteduser, $datadir . '/' . self::$uid ) ){ if( !self::copy_r( $extractpath . $json->exporteduser, $datadir . '/' . self::$uid ) ) {
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
// Import user app data // Import user app data
if( !$appsimported = self::importAppData( $extractpath . $json->exporteduser . '/migration.db', $json, self::$uid ) ){ if( !$appsimported = self::importAppData( $extractpath . $json->exporteduser . '/migration.db', $json, self::$uid ) ) {
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
// All done! // All done!
if( !self::unlink_r( $extractpath ) ){ if( !self::unlink_r( $extractpath ) ) {
OC_Log::write( 'migration', 'Failed to delete the extracted zip', OC_Log::ERROR ); OC_Log::write( 'migration', 'Failed to delete the extracted zip', OC_Log::ERROR );
} }
return json_encode( array( 'success' => true, 'data' => $appsimported ) ); return json_encode( array( 'success' => true, 'data' => $appsimported ) );
@ -262,19 +262,19 @@ class OC_Migrate{
// Delete current data folder. // Delete current data folder.
OC_Log::write( 'migration', "Deleting current data dir", OC_Log::INFO ); OC_Log::write( 'migration', "Deleting current data dir", OC_Log::INFO );
if( !self::unlink_r( $datadir, false ) ){ if( !self::unlink_r( $datadir, false ) ) {
OC_Log::write( 'migration', 'Failed to delete the current data dir', OC_Log::ERROR ); OC_Log::write( 'migration', 'Failed to delete the current data dir', OC_Log::ERROR );
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
// Copy over data // Copy over data
if( !self::copy_r( $extractpath . 'userdata', $datadir ) ){ if( !self::copy_r( $extractpath . 'userdata', $datadir ) ) {
OC_Log::write( 'migration', 'Failed to copy over data directory', OC_Log::ERROR ); OC_Log::write( 'migration', 'Failed to copy over data directory', OC_Log::ERROR );
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
// Import the db // Import the db
if( !OC_DB::replaceDB( $extractpath . 'dbexport.xml' ) ){ if( !OC_DB::replaceDB( $extractpath . 'dbexport.xml' ) ) {
return json_encode( array( 'success' => false ) ); return json_encode( array( 'success' => false ) );
} }
// Done // Done
@ -291,15 +291,15 @@ class OC_Migrate{
* $param optional $deleteRootToo bool delete the root directory * $param optional $deleteRootToo bool delete the root directory
* @return bool * @return bool
*/ */
private static function unlink_r( $dir, $deleteRootToo=true ){ private static function unlink_r( $dir, $deleteRootToo=true ) {
if( !$dh = @opendir( $dir ) ){ if( !$dh = @opendir( $dir ) ) {
return false; return false;
} }
while (false !== ($obj = readdir($dh))){ while (false !== ($obj = readdir($dh))) {
if($obj == '.' || $obj == '..') { if($obj == '.' || $obj == '..') {
continue; continue;
} }
if (!@unlink($dir . '/' . $obj)){ if (!@unlink($dir . '/' . $obj)) {
self::unlink_r($dir.'/'.$obj, true); self::unlink_r($dir.'/'.$obj, true);
} }
} }
@ -316,16 +316,16 @@ class OC_Migrate{
* @param $dest string path to destination * @param $dest string path to destination
* @return bool * @return bool
*/ */
private static function copy_r( $path, $dest ){ private static function copy_r( $path, $dest ) {
if( is_dir($path) ){ if( is_dir($path) ) {
@mkdir( $dest ); @mkdir( $dest );
$objects = scandir( $path ); $objects = scandir( $path );
if( sizeof( $objects ) > 0 ){ if( sizeof( $objects ) > 0 ) {
foreach( $objects as $file ){ foreach( $objects as $file ) {
if( $file == "." || $file == ".." || $file == ".htaccess") if( $file == "." || $file == ".." || $file == ".htaccess")
continue; continue;
// go on // go on
if( is_dir( $path . '/' . $file ) ){ if( is_dir( $path . '/' . $file ) ) {
self::copy_r( $path .'/' . $file, $dest . '/' . $file ); self::copy_r( $path .'/' . $file, $dest . '/' . $file );
} else { } else {
copy( $path . '/' . $file, $dest . '/' . $file ); copy( $path . '/' . $file, $dest . '/' . $file );
@ -334,7 +334,7 @@ class OC_Migrate{
} }
return true; return true;
} }
elseif( is_file( $path ) ){ elseif( is_file( $path ) ) {
return copy( $path, $dest ); return copy( $path, $dest );
} else { } else {
return false; return false;
@ -346,10 +346,10 @@ class OC_Migrate{
* @param $path string path to the zip * @param $path string path to the zip
* @return string path to extract location (with a trailing slash) or false on failure * @return string path to extract location (with a trailing slash) or false on failure
*/ */
static private function extractZip( $path ){ static private function extractZip( $path ) {
self::$zip = new ZipArchive; self::$zip = new ZipArchive;
// Validate path // Validate path
if( !file_exists( $path ) ){ if( !file_exists( $path ) ) {
OC_Log::write( 'migration', 'Zip not found', OC_Log::ERROR ); OC_Log::write( 'migration', 'Zip not found', OC_Log::ERROR );
return false; return false;
} }
@ -358,7 +358,7 @@ class OC_Migrate{
return false; return false;
} }
$to = get_temp_dir() . '/oc_import_' . self::$exporttype . '_' . date("y-m-d_H-i-s") . '/'; $to = get_temp_dir() . '/oc_import_' . self::$exporttype . '_' . date("y-m-d_H-i-s") . '/';
if( !self::$zip->extractTo( $to ) ){ if( !self::$zip->extractTo( $to ) ) {
return false; return false;
} }
self::$zip->close(); self::$zip->close();
@ -369,13 +369,13 @@ class OC_Migrate{
* @brief connects to a MDB2 database scheme * @brief connects to a MDB2 database scheme
* @returns bool * @returns bool
*/ */
static private function connectScheme(){ static private function connectScheme() {
// We need a mdb2 database connection // We need a mdb2 database connection
self::$MDB2->loadModule( 'Manager' ); self::$MDB2->loadModule( 'Manager' );
self::$MDB2->loadModule( 'Reverse' ); self::$MDB2->loadModule( 'Reverse' );
// Connect if this did not happen before // Connect if this did not happen before
if( !self::$schema ){ if( !self::$schema ) {
require_once 'MDB2/Schema.php'; require_once 'MDB2/Schema.php';
self::$schema=MDB2_Schema::factory( self::$MDB2 ); self::$schema=MDB2_Schema::factory( self::$MDB2 );
} }
@ -387,23 +387,23 @@ class OC_Migrate{
* @brief creates a migration.db in the users data dir with their app data in * @brief creates a migration.db in the users data dir with their app data in
* @return bool whether operation was successfull * @return bool whether operation was successfull
*/ */
private static function exportAppData( ){ private static function exportAppData( ) {
$success = true; $success = true;
$return = array(); $return = array();
// Foreach provider // Foreach provider
foreach( self::$providers as $provider ){ foreach( self::$providers as $provider ) {
// Check if the app is enabled // Check if the app is enabled
if( OC_App::isEnabled( $provider->getID() ) ){ if( OC_App::isEnabled( $provider->getID() ) ) {
$success = true; $success = true;
// Does this app use the database? // Does this app use the database?
if( file_exists( OC_App::getAppPath($provider->getID()).'/appinfo/database.xml' ) ){ if( file_exists( OC_App::getAppPath($provider->getID()).'/appinfo/database.xml' ) ) {
// Create some app tables // Create some app tables
$tables = self::createAppTables( $provider->getID() ); $tables = self::createAppTables( $provider->getID() );
if( is_array( $tables ) ){ if( is_array( $tables ) ) {
// Save the table names // Save the table names
foreach($tables as $table){ foreach($tables as $table) {
$return['apps'][$provider->getID()]['tables'][] = $table; $return['apps'][$provider->getID()]['tables'][] = $table;
} }
} else { } else {
@ -413,7 +413,7 @@ class OC_Migrate{
} }
// Run the export function? // Run the export function?
if( $success ){ if( $success ) {
// Set the provider properties // Set the provider properties
$provider->setData( self::$uid, self::$content ); $provider->setData( self::$uid, self::$content );
$return['apps'][$provider->getID()]['success'] = $provider->export(); $return['apps'][$provider->getID()]['success'] = $provider->export();
@ -438,7 +438,7 @@ class OC_Migrate{
* @param optional $array array of data to include in the returned json * @param optional $array array of data to include in the returned json
* @return bool * @return bool
*/ */
static private function getExportInfo( $array=array() ){ static private function getExportInfo( $array=array() ) {
$info = array( $info = array(
'ocversion' => OC_Util::getVersion(), 'ocversion' => OC_Util::getVersion(),
'exporttime' => time(), 'exporttime' => time(),
@ -447,7 +447,7 @@ class OC_Migrate{
'exporteduser' => self::$uid 'exporteduser' => self::$uid
); );
if( !is_array( $array ) ){ if( !is_array( $array ) ) {
OC_Log::write( 'migration', 'Supplied $array was not an array in getExportInfo()', OC_Log::ERROR ); OC_Log::write( 'migration', 'Supplied $array was not an array in getExportInfo()', OC_Log::ERROR );
} }
// Merge in other data // Merge in other data
@ -462,23 +462,23 @@ class OC_Migrate{
* @param $db optional path to migration.db, defaults to user data dir * @param $db optional path to migration.db, defaults to user data dir
* @return bool whether the operation was successful * @return bool whether the operation was successful
*/ */
static private function connectDB( $path=null ){ static private function connectDB( $path=null ) {
// Has the dbpath been set? // Has the dbpath been set?
self::$dbpath = !is_null( $path ) ? $path : self::$dbpath; self::$dbpath = !is_null( $path ) ? $path : self::$dbpath;
if( !self::$dbpath ){ if( !self::$dbpath ) {
OC_Log::write( 'migration', 'connectDB() was called without dbpath being set', OC_Log::ERROR ); OC_Log::write( 'migration', 'connectDB() was called without dbpath being set', OC_Log::ERROR );
return false; return false;
} }
// Already connected // Already connected
if(!self::$MDB2){ if(!self::$MDB2) {
require_once 'MDB2.php'; require_once 'MDB2.php';
$datadir = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); $datadir = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
// DB type // DB type
if( class_exists( 'SQLite3' ) ){ if( class_exists( 'SQLite3' ) ) {
$dbtype = 'sqlite3'; $dbtype = 'sqlite3';
} else if( is_callable( 'sqlite_open' ) ){ } else if( is_callable( 'sqlite_open' ) ) {
$dbtype = 'sqlite'; $dbtype = 'sqlite';
} else { } else {
OC_Log::write( 'migration', 'SQLite not found', OC_Log::ERROR ); OC_Log::write( 'migration', 'SQLite not found', OC_Log::ERROR );
@ -502,7 +502,7 @@ class OC_Migrate{
// Try to establish connection // Try to establish connection
self::$MDB2 = MDB2::factory( $dsn, $options ); self::$MDB2 = MDB2::factory( $dsn, $options );
// Die if we could not connect // Die if we could not connect
if( PEAR::isError( self::$MDB2 ) ){ if( PEAR::isError( self::$MDB2 ) ) {
die( self::$MDB2->getMessage() ); die( self::$MDB2->getMessage() );
OC_Log::write( 'migration', 'Failed to create/connect to migration.db', OC_Log::FATAL ); OC_Log::write( 'migration', 'Failed to create/connect to migration.db', OC_Log::FATAL );
OC_Log::write( 'migration', self::$MDB2->getUserInfo(), OC_Log::FATAL ); OC_Log::write( 'migration', self::$MDB2->getUserInfo(), OC_Log::FATAL );
@ -521,9 +521,9 @@ class OC_Migrate{
* @param $appid string id of the app * @param $appid string id of the app
* @return bool whether the operation was successful * @return bool whether the operation was successful
*/ */
static private function createAppTables( $appid ){ static private function createAppTables( $appid ) {
if( !self::connectScheme() ){ if( !self::connectScheme() ) {
return false; return false;
} }
@ -538,7 +538,7 @@ class OC_Migrate{
$content = str_replace( '*dbprefix*', '', $content ); $content = str_replace( '*dbprefix*', '', $content );
$xml = new SimpleXMLElement($content); $xml = new SimpleXMLElement($content);
foreach($xml->table as $table){ foreach($xml->table as $table) {
$tables[] = (string)$table->name; $tables[] = (string)$table->name;
} }
@ -550,7 +550,7 @@ class OC_Migrate{
unlink( $file2 ); unlink( $file2 );
// Die in case something went wrong // Die in case something went wrong
if( $definition instanceof MDB2_Schema_Error ){ if( $definition instanceof MDB2_Schema_Error ) {
OC_Log::write( 'migration', 'Failed to parse database.xml for: '.$appid, OC_Log::FATAL ); OC_Log::write( 'migration', 'Failed to parse database.xml for: '.$appid, OC_Log::FATAL );
OC_Log::write( 'migration', $definition->getMessage().': '.$definition->getUserInfo(), OC_Log::FATAL ); OC_Log::write( 'migration', $definition->getMessage().': '.$definition->getUserInfo(), OC_Log::FATAL );
return false; return false;
@ -561,7 +561,7 @@ class OC_Migrate{
$ret = self::$schema->createDatabase( $definition ); $ret = self::$schema->createDatabase( $definition );
// Die in case something went wrong // Die in case something went wrong
if( $ret instanceof MDB2_Error ){ if( $ret instanceof MDB2_Error ) {
OC_Log::write( 'migration', 'Failed to create tables for: '.$appid, OC_Log::FATAL ); OC_Log::write( 'migration', 'Failed to create tables for: '.$appid, OC_Log::FATAL );
OC_Log::write( 'migration', $ret->getMessage().': '.$ret->getUserInfo(), OC_Log::FATAL ); OC_Log::write( 'migration', $ret->getMessage().': '.$ret->getUserInfo(), OC_Log::FATAL );
return false; return false;
@ -575,10 +575,10 @@ class OC_Migrate{
* @param $path string path to zip destination * @param $path string path to zip destination
* @return bool * @return bool
*/ */
static private function createZip(){ static private function createZip() {
self::$zip = new ZipArchive; self::$zip = new ZipArchive;
// Check if properties are set // Check if properties are set
if( !self::$zippath ){ if( !self::$zippath ) {
OC_Log::write('migration', 'createZip() called but $zip and/or $zippath have not been set', OC_Log::ERROR); OC_Log::write('migration', 'createZip() called but $zip and/or $zippath have not been set', OC_Log::ERROR);
return false; return false;
} }
@ -594,11 +594,11 @@ class OC_Migrate{
* @brief returns an array of apps that support migration * @brief returns an array of apps that support migration
* @return array * @return array
*/ */
static public function getApps(){ static public function getApps() {
$allapps = OC_App::getAllApps(); $allapps = OC_App::getAllApps();
foreach($allapps as $app){ foreach($allapps as $app) {
$path = self::getAppPath($app) . '/lib/migrate.php'; $path = self::getAppPath($app) . '/lib/migrate.php';
if( file_exists( $path ) ){ if( file_exists( $path ) ) {
$supportsmigration[] = $app; $supportsmigration[] = $app;
} }
} }
@ -612,11 +612,11 @@ class OC_Migrate{
* @param $uid optional uid to use * @param $uid optional uid to use
* @return array of apps with import statuses, or false on failure. * @return array of apps with import statuses, or false on failure.
*/ */
public static function importAppData( $db, $info, $uid=null ){ public static function importAppData( $db, $info, $uid=null ) {
// Check if the db exists // Check if the db exists
if( file_exists( $db ) ){ if( file_exists( $db ) ) {
// Connect to the db // Connect to the db
if(!self::connectDB( $db )){ if(!self::connectDB( $db )) {
OC_Log::write('migration','Failed to connect to migration.db',OC_Log::ERROR); OC_Log::write('migration','Failed to connect to migration.db',OC_Log::ERROR);
return false; return false;
} }
@ -634,25 +634,25 @@ class OC_Migrate{
'newuid' => self::$uid 'newuid' => self::$uid
); );
foreach( self::$providers as $provider){ foreach( self::$providers as $provider) {
// Is the app in the export? // Is the app in the export?
$id = $provider->getID(); $id = $provider->getID();
if( isset( $info->apps->$id ) ){ if( isset( $info->apps->$id ) ) {
// Is the app installed // Is the app installed
if( !OC_App::isEnabled( $id ) ){ if( !OC_App::isEnabled( $id ) ) {
OC_Log::write( 'migration', 'App: ' . $id . ' is not installed, can\'t import data.', OC_Log::INFO ); OC_Log::write( 'migration', 'App: ' . $id . ' is not installed, can\'t import data.', OC_Log::INFO );
$appsstatus[$id] = 'notsupported'; $appsstatus[$id] = 'notsupported';
} else { } else {
// Did it succeed on export? // Did it succeed on export?
if( $info->apps->$id->success ){ if( $info->apps->$id->success ) {
// Give the provider the content object // Give the provider the content object
if( !self::connectDB( $db ) ){ if( !self::connectDB( $db ) ) {
return false; return false;
} }
$content = new OC_Migration_Content( self::$zip, self::$MDB2 ); $content = new OC_Migration_Content( self::$zip, self::$MDB2 );
$provider->setData( self::$uid, $content, $info ); $provider->setData( self::$uid, $content, $info );
// Then do the import // Then do the import
if( !$appsstatus[$id] = $provider->import( $info->apps->$id, $importinfo ) ){ if( !$appsstatus[$id] = $provider->import( $info->apps->$id, $importinfo ) ) {
// Failed to import app // Failed to import app
OC_Log::write( 'migration', 'Failed to import app data for user: ' . self::$uid . ' for app: ' . $id, OC_Log::ERROR ); OC_Log::write( 'migration', 'Failed to import app data for user: ' . self::$uid . ' for app: ' . $id, OC_Log::ERROR );
} }
@ -674,17 +674,17 @@ class OC_Migrate{
* @param $hash string hash of the user to be created * @param $hash string hash of the user to be created
* @return bool result of user creation * @return bool result of user creation
*/ */
public static function createUser( $uid, $hash ){ public static function createUser( $uid, $hash ) {
// Check if userid exists // Check if userid exists
if(OC_User::userExists( $uid )){ if(OC_User::userExists( $uid )) {
return false; return false;
} }
// Create the user // Create the user
$query = OC_DB::prepare( "INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )" ); $query = OC_DB::prepare( "INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )" );
$result = $query->execute( array( $uid, $hash)); $result = $query->execute( array( $uid, $hash));
if( !$result ){ if( !$result ) {
OC_Log::write('migration', 'Failed to create the new user "'.$uid.""); OC_Log::write('migration', 'Failed to create the new user "'.$uid."");
} }
return $result ? true : false; return $result ? true : false;

View File

@ -38,12 +38,12 @@ class OC_Migration_Content{
* @param optional $db a MDB2 database object (required for exporttype user) * @param optional $db a MDB2 database object (required for exporttype user)
* @return bool * @return bool
*/ */
public function __construct( $zip, $db=null ){ public function __construct( $zip, $db=null ) {
$this->zip = $zip; $this->zip = $zip;
$this->db = $db; $this->db = $db;
if( !is_null( $db ) ){ if( !is_null( $db ) ) {
// Get db path // Get db path
$db = $this->db->getDatabase(); $db = $this->db->getDatabase();
$this->tmpfiles[] = $db; $this->tmpfiles[] = $db;
@ -53,7 +53,7 @@ class OC_Migration_Content{
// @brief prepares the db // @brief prepares the db
// @param $query the sql query to prepare // @param $query the sql query to prepare
public function prepare( $query ){ public function prepare( $query ) {
// Optimize the query // Optimize the query
$query = $this->processQuery( $query ); $query = $this->processQuery( $query );
@ -78,7 +78,7 @@ class OC_Migration_Content{
* @param $query the query to process * @param $query the query to process
* @return string of processed query * @return string of processed query
*/ */
private function processQuery( $query ){ private function processQuery( $query ) {
$query = str_replace( '`', '\'', $query ); $query = str_replace( '`', '\'', $query );
$query = str_replace( 'NOW()', 'datetime(\'now\')', $query ); $query = str_replace( 'NOW()', 'datetime(\'now\')', $query );
$query = str_replace( 'now()', 'datetime(\'now\')', $query ); $query = str_replace( 'now()', 'datetime(\'now\')', $query );
@ -92,22 +92,22 @@ class OC_Migration_Content{
* @param $options array of options. * @param $options array of options.
* @return bool * @return bool
*/ */
public function copyRows( $options ){ public function copyRows( $options ) {
if( !array_key_exists( 'table', $options ) ){ if( !array_key_exists( 'table', $options ) ) {
return false; return false;
} }
$return = array(); $return = array();
// Need to include 'where' in the query? // Need to include 'where' in the query?
if( array_key_exists( 'matchval', $options ) && array_key_exists( 'matchcol', $options ) ){ if( array_key_exists( 'matchval', $options ) && array_key_exists( 'matchcol', $options ) ) {
// If only one matchval, create an array // If only one matchval, create an array
if(!is_array($options['matchval'])){ if(!is_array($options['matchval'])) {
$options['matchval'] = array( $options['matchval'] ); $options['matchval'] = array( $options['matchval'] );
} }
foreach( $options['matchval'] as $matchval ){ foreach( $options['matchval'] as $matchval ) {
// Run the query for this match value (where x = y value) // Run the query for this match value (where x = y value)
$sql = 'SELECT * FROM `*PREFIX*' . $options['table'] . '` WHERE `' . $options['matchcol'] . '` LIKE ?'; $sql = 'SELECT * FROM `*PREFIX*' . $options['table'] . '` WHERE `' . $options['matchcol'] . '` LIKE ?';
$query = OC_DB::prepare( $sql ); $query = OC_DB::prepare( $sql );
@ -135,12 +135,12 @@ class OC_Migration_Content{
* @param $options array of copyRows options * @param $options array of copyRows options
* @return void * @return void
*/ */
private function insertData( $data, $options ){ private function insertData( $data, $options ) {
$return = array(); $return = array();
// Foreach row of data to insert // Foreach row of data to insert
while( $row = $data->fetchRow() ){ while( $row = $data->fetchRow() ) {
// Now save all this to the migration.db // Now save all this to the migration.db
foreach($row as $field=>$value){ foreach($row as $field=>$value) {
$fields[] = $field; $fields[] = $field;
$values[] = $value; $values[] = $value;
} }
@ -153,14 +153,14 @@ class OC_Migration_Content{
$sql .= $valuessql . " )"; $sql .= $valuessql . " )";
// Make the query // Make the query
$query = $this->prepare( $sql ); $query = $this->prepare( $sql );
if( !$query ){ if( !$query ) {
OC_Log::write( 'migration', 'Invalid sql produced: '.$sql, OC_Log::FATAL ); OC_Log::write( 'migration', 'Invalid sql produced: '.$sql, OC_Log::FATAL );
return false; return false;
exit(); exit();
} else { } else {
$query->execute( $values ); $query->execute( $values );
// Do we need to return some values? // Do we need to return some values?
if( array_key_exists( 'idcol', $options ) ){ if( array_key_exists( 'idcol', $options ) ) {
// Yes we do // Yes we do
$return[] = $row[$options['idcol']]; $return[] = $row[$options['idcol']];
} else { } else {
@ -185,7 +185,7 @@ class OC_Migration_Content{
$dirname = basename($dir); $dirname = basename($dir);
$this->zip->addEmptyDir($internaldir . $dirname); $this->zip->addEmptyDir($internaldir . $dirname);
$internaldir.=$dirname.='/'; $internaldir.=$dirname.='/';
if( !file_exists( $dir ) ){ if( !file_exists( $dir ) ) {
return false; return false;
} }
if ($dirhandle = opendir($dir)) { if ($dirhandle = opendir($dir)) {
@ -214,11 +214,11 @@ class OC_Migration_Content{
* @param $path the relative path inside of the zip to save the file to * @param $path the relative path inside of the zip to save the file to
* @return bool * @return bool
*/ */
public function addFromString( $data, $path ){ public function addFromString( $data, $path ) {
// Create a temp file // Create a temp file
$file = tempnam( get_temp_dir(). '/', 'oc_export_tmp_' ); $file = tempnam( get_temp_dir(). '/', 'oc_export_tmp_' );
$this->tmpfiles[] = $file; $this->tmpfiles[] = $file;
if( !file_put_contents( $file, $data ) ){ if( !file_put_contents( $file, $data ) ) {
OC_Log::write( 'migation', 'Failed to save data to a temporary file', OC_Log::ERROR ); OC_Log::write( 'migation', 'Failed to save data to a temporary file', OC_Log::ERROR );
return false; return false;
} }
@ -231,8 +231,8 @@ class OC_Migration_Content{
* @brief closes the zip, removes temp files * @brief closes the zip, removes temp files
* @return bool * @return bool
*/ */
public function finish(){ public function finish() {
if( !$this->zip->close() ){ if( !$this->zip->close() ) {
OC_Log::write( 'migration', 'Failed to write the zip file with error: '.$this->zip->getStatusString(), OC_Log::ERROR ); OC_Log::write( 'migration', 'Failed to write the zip file with error: '.$this->zip->getStatusString(), OC_Log::ERROR );
return false; return false;
} }
@ -243,9 +243,9 @@ class OC_Migration_Content{
/** /**
* @brief cleans up after the zip * @brief cleans up after the zip
*/ */
private function cleanup(){ private function cleanup() {
// Delete tmp files // Delete tmp files
foreach($this->tmpfiles as $i){ foreach($this->tmpfiles as $i) {
unlink( $i ); unlink( $i );
} }
} }

Some files were not shown because too many files have changed in this diff Show More