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'));
$maxUploadFilesize = OCP\Util::humanFileSize(min($upload_max_filesize, $post_max_size));
if($_POST) {
if(isset($_POST['maxUploadSize'])){
if(isset($_POST['maxUploadSize'])) {
if(($setMaxSize = OC_Files::setUploadLimit(OCP\Util::computerFileSize($_POST['maxUploadSize']))) !== false) {
$maxUploadFilesize = OCP\Util::humanFileSize($setMaxSize);
}

View File

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

View File

@ -35,7 +35,7 @@ $dir = $_POST['dir'];
$error='';
$totalSize=0;
foreach($files['size'] as $size){
foreach($files['size'] as $size) {
$totalSize+=$size;
}
if($totalSize>OC_Filesystem::free_space('/')) {
@ -46,7 +46,7 @@ if($totalSize>OC_Filesystem::free_space('/')) {
$result=array();
if(strpos($dir, '..') === false) {
$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]);
if(is_uploaded_file($files['tmp_name'][$i]) and OC_Filesystem::fromTmpFile($files['tmp_name'][$i], $target)) {
$meta=OC_FileCache_Cached::get($target);

View File

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

View File

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

View File

@ -29,7 +29,7 @@ OCP\User::checkLoggedIn();
$filename = $_GET["file"];
if(!OC_Filesystem::file_exists($filename)){
if(!OC_Filesystem::file_exists($filename)) {
header("HTTP/1.0 404 Not Found");
$tmpl = new OCP\Template( '', '404', 'guest' );
$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', 'filelist' );
OCP\Util::addscript( 'files', 'fileactions' );
if(!isset($_SESSION['timezone'])){
if(!isset($_SESSION['timezone'])) {
OCP\Util::addscript( 'files', 'timezone' );
}
OCP\App::setActiveNavigationEntry( 'files_index' );
@ -44,9 +44,9 @@ if(!OC_Filesystem::is_dir($dir.'/')) {
}
$files = array();
foreach( OC_Files::getdirectorycontent( $dir ) as $i ){
foreach( OC_Files::getdirectorycontent( $dir ) as $i ) {
$i['date'] = OCP\Util::formatDate($i['mtime'] );
if($i['type']=='file'){
if($i['type']=='file') {
$fileinfo=pathinfo($i['name']);
$i['basename']=$fileinfo['filename'];
if (!empty($fileinfo['extension'])) {
@ -56,7 +56,7 @@ foreach( OC_Files::getdirectorycontent( $dir ) as $i ){
$i['extension']='';
}
}
if($i['directory']=='/'){
if($i['directory']=='/') {
$i['directory']='';
}
$files[] = $i;
@ -65,8 +65,8 @@ foreach( OC_Files::getdirectorycontent( $dir ) as $i ){
// Make breadcrumb
$breadcrumb = array();
$pathtohere = '';
foreach( explode( '/', $dir ) as $i ){
if( $i != '' ){
foreach( explode( '/', $dir ) as $i ) {
if( $i != '' ) {
$pathtohere .= '/'.str_replace('+','%20', urlencode($i));
$breadcrumb[] = array( 'dir' => $pathtohere, 'name' => $i );
}

View File

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

View File

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

View File

@ -36,18 +36,18 @@ class OC_CryptStream{
private $size;
private static $rootView;
public function stream_open($path, $mode, $options, &$opened_path){
if(!self::$rootView){
public function stream_open($path, $mode, $options, &$opened_path) {
if(!self::$rootView) {
self::$rootView=new OC_FilesystemView('');
}
$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->path=self::$sourceStreams[basename($path)]['path'];
$this->size=self::$sourceStreams[basename($path)]['size'];
}else{
$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;
}else{
$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
$this->source=self::$rootView->fopen($path,$mode);
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);
}
}
if(is_resource($this->source)){
if(is_resource($this->source)) {
$this->meta=stream_get_meta_data($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();
fseek($this->source,$offset,$whence);
}
public function stream_tell(){
public function stream_tell() {
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
//This makes this function a lot simpler but will breake everything the moment it's fixed
$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);
die();
}
$pos=ftell($this->source);
$data=fread($this->source,8192);
if(strlen($data)){
if(strlen($data)) {
$result=OC_Crypt::decrypt($data);
}else{
$result='';
}
$length=$this->size-$pos;
if($length<8192){
if($length<8192) {
$result=substr($result,0,$length);
}
return $result;
}
public function stream_write($data){
public function stream_write($data) {
$length=strlen($data);
$currentPos=ftell($this->source);
if($this->writeCache){
if($this->writeCache) {
$data=$this->writeCache.$data;
$this->writeCache='';
}
if($currentPos%8192!=0){
if($currentPos%8192!=0) {
//make sure we always start on a block start
fseek($this->source,-($currentPos%8192),SEEK_CUR);
$encryptedBlock=fread($this->source,8192);
@ -113,8 +113,8 @@ class OC_CryptStream{
fseek($this->source,-($currentPos%8192),SEEK_CUR);
}
$currentPos=ftell($this->source);
while($remainingLength=strlen($data)>0){
if($remainingLength<8192){
while($remainingLength=strlen($data)>0) {
if($remainingLength<8192) {
$this->writeCache=$data;
$data='';
}else{
@ -127,8 +127,8 @@ class OC_CryptStream{
return $length;
}
public function stream_set_option($option,$arg1,$arg2){
switch($option){
public function stream_set_option($option,$arg1,$arg2) {
switch($option) {
case STREAM_OPTION_BLOCKING:
stream_set_blocking($this->source,$arg1);
break;
@ -140,33 +140,33 @@ class OC_CryptStream{
}
}
public function stream_stat(){
public function stream_stat() {
return fstat($this->source);
}
public function stream_lock($mode){
public function stream_lock($mode) {
flock($this->source,$mode);
}
public function stream_flush(){
public function stream_flush() {
return fflush($this->source);
}
public function stream_eof(){
public function stream_eof() {
return feof($this->source);
}
private function flush(){
if($this->writeCache){
private function flush() {
if($this->writeCache) {
$encrypted=OC_Crypt::encrypt($this->writeCache);
fwrite($this->source,$encrypted);
$this->writeCache='';
}
}
public function stream_close(){
public function stream_close() {
$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),'');
}
return fclose($this->source);

View File

@ -34,21 +34,21 @@ class OC_FileProxy_Encryption extends OC_FileProxy{
* @param string $path
* @return bool
*/
private static function shouldEncrypt($path){
if(is_null(self::$enableEncryption)){
private static function shouldEncrypt($path) {
if(is_null(self::$enableEncryption)) {
self::$enableEncryption=(OCP\Config::getAppValue('files_encryption','enable_encryption','true')=='true');
}
if(!self::$enableEncryption){
if(!self::$enableEncryption) {
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'));
}
if(self::isEncrypted($path)){
if(self::isEncrypted($path)) {
return true;
}
$extension=substr($path,strrpos($path,'.')+1);
if(array_search($extension,self::$blackList)===false){
if(array_search($extension,self::$blackList)===false) {
return true;
}
}
@ -58,13 +58,13 @@ class OC_FileProxy_Encryption extends OC_FileProxy{
* @param string $path
* @return bool
*/
private static function isEncrypted($path){
private static function isEncrypted($path) {
$metadata=OC_FileCache_Cached::get($path,'');
return isset($metadata['encrypted']) and (bool)$metadata['encrypted'];
}
public function preFile_put_contents($path,&$data){
if(self::shouldEncrypt($path)){
public function preFile_put_contents($path,&$data) {
if(self::shouldEncrypt($path)) {
if (!is_resource($data)) {//stream put contents should have been converter to fopen
$size=strlen($data);
$data=OC_Crypt::blockEncrypt($data);
@ -73,24 +73,24 @@ class OC_FileProxy_Encryption extends OC_FileProxy{
}
}
public function postFile_get_contents($path,$data){
if(self::isEncrypted($path)){
public function postFile_get_contents($path,$data) {
if(self::isEncrypted($path)) {
$cached=OC_FileCache_Cached::get($path,'');
$data=OC_Crypt::blockDecrypt($data,'',$cached['size']);
}
return $data;
}
public function postFopen($path,&$result){
if(!$result){
public function postFopen($path,&$result) {
if(!$result) {
return $result;
}
$meta=stream_get_meta_data($result);
if(self::isEncrypted($path)){
if(self::isEncrypted($path)) {
fclose($result);
$result=fopen('crypt://'.$path,$meta['mode']);
}elseif(self::shouldEncrypt($path) and $meta['mode']!='r' and $meta['mode']!='rb'){
if(OC_Filesystem::file_exists($path) and OC_Filesystem::filesize($path)>0){
}elseif(self::shouldEncrypt($path) and $meta['mode']!='r' and $meta['mode']!='rb') {
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
OCP\Util::writeLog('files_encryption','Decrypting '.$path.' before writing',OCP\Util::DEBUG);
$tmp=fopen('php://temp');
@ -104,23 +104,23 @@ class OC_FileProxy_Encryption extends OC_FileProxy{
return $result;
}
public function postGetMimeType($path,$mime){
if(self::isEncrypted($path)){
public function postGetMimeType($path,$mime) {
if(self::isEncrypted($path)) {
$mime=OCP\Files::getMimeType('crypt://'.$path,'w');
}
return $mime;
}
public function postStat($path,$data){
if(self::isEncrypted($path)){
public function postStat($path,$data) {
if(self::isEncrypted($path)) {
$cached=OC_FileCache_Cached::get($path,'');
$data['size']=$cached['size'];
}
return $data;
}
public function postFileSize($path,$size){
if(self::isEncrypted($path)){
public function postFileSize($path,$size) {
if(self::isEncrypted($path)) {
$cached=OC_FileCache_Cached::get($path,'');
return $cached['size'];
}else{

View File

@ -7,6 +7,6 @@
<option selected="selected" value="<?php echo $type;?>"><?php echo $type;?></option>
<?php endforeach;?>
</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>
</form>

View File

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

View File

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

View File

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

View File

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

View File

@ -15,40 +15,40 @@ class OC_FileStorage_SMB extends OC_FileStorage_StreamWrapper{
private $root;
private $share;
public function __construct($params){
public function __construct($params) {
$this->host=$params['host'];
$this->user=$params['user'];
$this->password=$params['password'];
$this->share=$params['share'];
$this->root=isset($params['root'])?$params['root']:'/';
if(!$this->root || $this->root[0]!='/'){
if(!$this->root || $this->root[0]!='/') {
$this->root='/'.$this->root;
}
if(substr($this->root,-1,1)!='/'){
if(substr($this->root,-1,1)!='/') {
$this->root.='/';
}
if(!$this->share || $this->share[0]!='/'){
if(!$this->share || $this->share[0]!='/') {
$this->share='/'.$this->share;
}
if(substr($this->share,-1,1)=='/'){
if(substr($this->share,-1,1)=='/') {
$this->share=substr($this->share,0,-1);
}
//create the root folder if necesary
if(!$this->is_dir('')){
if(!$this->is_dir('')) {
$this->mkdir('');
}
}
public function constructUrl($path){
if(substr($path,-1)=='/'){
public function constructUrl($path) {
if(substr($path,-1)=='/') {
$path=substr($path,0,-1);
}
return 'smb://'.$this->user.':'.$this->password.'@'.$this->host.$this->share.$this->root.$path;
}
public function stat($path){
if(!$path and $this->root=='/'){//mtime doesn't work for shares
public function stat($path) {
if(!$path and $this->root=='/') {//mtime doesn't work for shares
$mtime=$this->shareMTime();
$stat=stat($this->constructUrl($path));
$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
}
@ -67,8 +67,8 @@ class OC_FileStorage_SMB extends OC_FileStorage_StreamWrapper{
* @param int $time
* @return bool
*/
public function hasUpdated($path,$time){
if(!$path and $this->root=='/'){
public function hasUpdated($path,$time) {
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
return true;
}else{
@ -80,13 +80,13 @@ class OC_FileStorage_SMB extends OC_FileStorage_StreamWrapper{
/**
* get the best guess for the modification time of the share
*/
private function shareMTime(){
private function shareMTime() {
$dh=$this->opendir('');
$lastCtime=0;
while($file=readdir($dh)){
if($file!='.' and $file!='..'){
while($file=readdir($dh)) {
if($file!='.' and $file!='..') {
$ctime=$this->filemtime($file);
if($ctime>$lastCtime){
if($ctime>$lastCtime) {
$lastCtime=$ctime;
}
}

View File

@ -10,12 +10,12 @@
abstract class OC_FileStorage_StreamWrapper extends OC_Filestorage_Common{
abstract public function constructUrl($path);
public function mkdir($path){
public function mkdir($path) {
return mkdir($this->constructUrl($path));
}
public function rmdir($path){
if($this->file_exists($path)){
public function rmdir($path) {
if($this->file_exists($path)) {
$succes=rmdir($this->constructUrl($path));
clearstatcache();
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));
}
public function filetype($path){
public function filetype($path) {
return filetype($this->constructUrl($path));
}
public function isReadable($path){
public function isReadable($path) {
return true;//not properly supported
}
public function isUpdatable($path){
public function isUpdatable($path) {
return true;//not properly supported
}
public function file_exists($path){
public function file_exists($path) {
return file_exists($this->constructUrl($path));
}
public function unlink($path){
public function unlink($path) {
$succes=unlink($this->constructUrl($path));
clearstatcache();
return $succes;
}
public function fopen($path,$mode){
public function fopen($path,$mode) {
return fopen($this->constructUrl($path),$mode);
}
public function free_space($path){
public function free_space($path) {
return 0;
}
public function touch($path,$mtime=null){
if(is_null($mtime)){
public function touch($path,$mtime=null) {
if(is_null($mtime)) {
$fh=$this->fopen($path,'a');
fwrite($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);
}
public function uploadFile($path,$target){
public function uploadFile($path,$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));
}
public function stat($path){
public function stat($path) {
return stat($this->constructUrl($path));
}

View File

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

View File

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

View File

@ -7,21 +7,21 @@
*/
$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{}
return;
}else{
class Test_Filestorage_FTP extends Test_FileStorage {
private $config;
public function setUp(){
public function setUp() {
$id=uniqid();
$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->instance=new OC_Filestorage_FTP($this->config['ftp']);
}
public function tearDown(){
public function tearDown() {
OCP\Files::rmdirr($this->instance->constructUrl(''));
}
}

View File

@ -21,7 +21,7 @@
*/
$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{}
return;
}else{
@ -29,14 +29,14 @@ if(!is_array($config) or !isset($config['google']) or !$config['google']['run'])
private $config;
public function setUp(){
public function setUp() {
$id=uniqid();
$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->instance=new OC_Filestorage_Google($this->config['google']);
}
public function tearDown(){
public function tearDown() {
$this->instance->rmdir('/');
}
}

View File

@ -8,21 +8,21 @@
$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{}
return;
}else{
class Test_Filestorage_SMB extends Test_FileStorage {
private $config;
public function setUp(){
public function setUp() {
$id=uniqid();
$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->instance=new OC_Filestorage_SMB($this->config['smb']);
}
public function tearDown(){
public function tearDown() {
OCP\Files::rmdirr($this->instance->constructUrl(''));
}
}

View File

@ -7,14 +7,14 @@
*/
$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{}
return;
}else{
class Test_Filestorage_SWIFT extends Test_FileStorage {
private $config;
public function setUp(){
public function setUp() {
$id=uniqid();
$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
@ -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('');
}

View File

@ -7,21 +7,21 @@
*/
$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{}
return;
}else{
class Test_Filestorage_DAV extends Test_FileStorage {
private $config;
public function setUp(){
public function setUp() {
$id=uniqid();
$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->instance=new OC_Filestorage_DAV($this->config['webdav']);
}
public function tearDown(){
public function tearDown() {
$this->instance->rmdir('/');
}
}

View File

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

View File

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

View File

@ -9,7 +9,7 @@ $file = $_GET['file'];
$revision=(int)$_GET['revision'];
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 )));
}else{
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';
if(Storage::isversioned($rel_path)) {
$versions = Storage::getVersions($rel_path);
foreach ($versions as $v){
foreach ($versions as $v) {
unlink($abs_path . $v['version']);
}
}
@ -66,7 +66,7 @@ class Hooks {
$info=pathinfo($abs_newpath);
if(!file_exists($info['dirname'])) mkdir($info['dirname'],0700,true);
$versions = Storage::getVersions($rel_oldpath);
foreach ($versions as $v){
foreach ($versions as $v) {
rename($abs_oldpath.$v['version'], $abs_newpath.$v['version']);
}
}

View File

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

View File

@ -1,6 +1,6 @@
<?php
$state = OCP\Config::getSystemValue('ldapIgnoreNamingRules', 'doSet');
if($state == 'doSet'){
if($state == 'doSet') {
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.
//it's a bit spaghetti, but hey.
$state = OCP\Config::getSystemValue('ldapIgnoreNamingRules', 'unset');
if($state == 'unset'){
if($state == 'unset') {
OCP\Config::setSystemValue('ldapIgnoreNamingRules', false);
}

View File

@ -231,7 +231,7 @@ class GROUP_LDAP extends lib\Access implements \OCP\GroupInterface {
* @param string $gid
* @return bool
*/
public function groupExists($gid){
public function groupExists($gid) {
if($this->connection->isCached('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');
if ($_POST) {
foreach($params as $param){
if(isset($_POST[$param])){
foreach($params as $param) {
if(isset($_POST[$param])) {
if('ldap_agent_password' == $param) {
OCP\Config::setAppValue('user_ldap', $param, base64_encode($_POST[$param]));
} elseif('ldap_cache_ttl' == $param) {
@ -58,7 +58,7 @@ if ($_POST) {
// fill template
$tmpl = new OCP\Template( 'user_ldap', 'settings');
foreach($params as $param){
foreach($params as $param) {
$value = OCP\Config::getAppValue('user_ldap', $param,'');
$tmpl->assign($param, $value);
}

View File

@ -21,11 +21,11 @@
*/
class Test_Group_Ldap extends UnitTestCase {
function setUp(){
function setUp() {
OC_Group::clearBackends();
}
function testSingleBackend(){
function testSingleBackend() {
OC_Group::useBackend(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
*/
public function checkPassword($uid, $password){
public function checkPassword($uid, $password) {
//find out dn of the user name
$filter = \OCP\Util::mb_str_replace('%uid', $uid, $this->connection->ldapLoginFilter, 'UTF-8');
$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?
$ocname = $this->dn2username($dn);
if($ocname){
if($ocname) {
//update some settings, if necessary
$this->updateQuota($dn);
$this->updateEmail($dn);
@ -100,7 +100,7 @@ class USER_LDAP extends lib\Access implements \OCP\UserInterface {
*
* 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');
if(is_null($ldap_users)) {
$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
* @return boolean
*/
public function userExists($uid){
public function userExists($uid) {
if($this->connection->isCached('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
* @return boolean
*/
public function getHome($uid){
public function getHome($uid) {
if($this->userExists($uid)) {
$homedir = \OCP\Config::getUserValue($uid, 'user_ldap', 'homedir', false);
if(!$homedir) {

View File

@ -22,9 +22,9 @@
*/
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']));
}
}

View File

@ -50,7 +50,7 @@ class OC_USER_WEBDAVAUTH extends OC_User_Backend {
$url= 'http://'.urlencode($uid).':'.urlencode($password).'@'.$this->webdavauth_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);
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
*/
public function userExists( $uid ){
public function userExists( $uid ) {
return false;
}
/*
* 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();
return $returnArray;

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
<?php
if(!isset($_)){//also provide standalone error page
if(!isset($_)) {//also provide standalone error page
require_once '../../lib/base.php';
$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>
<p class="exception">
<?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 'Message: ' . $_['message'] . "\n";
echo 'Error Code: ' . $_['code'] . "\n";

View File

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

View File

@ -24,7 +24,7 @@
<?php foreach($_['headers'] as $header): ?>
<?php
echo '<'.$header['tag'].' ';
foreach($header['attributes'] as $name=>$value){
foreach($header['attributes'] as $name=>$value) {
echo "$name='$value' ";
};
echo '/>';
@ -33,7 +33,7 @@
<script type="text/javascript">
requesttoken = '<?php echo $_['requesttoken']; ?>';
OC.EventSource.requesttoken=requesttoken;
$(document).bind('ajaxSend', function(elm, xhr, s){
$(document).bind('ajaxSend', function(elm, xhr, s) {
xhr.setRequestHeader('requesttoken', requesttoken);
});
</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 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">
<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>
</div></header>

View File

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

View File

@ -191,7 +191,7 @@ class MDB2_Driver_Datatype_sqlite3 extends MDB2_Driver_Datatype_Common
$notnull = empty($field['notnull']) ? '' : ' NOT NULL';
$unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
$name = $db->quoteIdentifier($name, true);
if($autoinc){
if($autoinc) {
return $name.' '.$this->getTypeDeclaration($field).$autoinc;
}else{
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;
}
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 = '';
if (!empty($changes['name'])) {
$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)
{
if($this->connection){
if($this->connection) {
return $this->connection->escapeString($text);
}else{
return str_replace("'","''",$text);//TODO; more
@ -324,7 +324,7 @@ class MDB2_Driver_sqlite3 extends MDB2_Driver_Common
**/
function connect()
{
if($this->connection instanceof SQLite3){
if($this->connection instanceof SQLite3) {
return MDB2_OK;
}
$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(!strpos($database_file,'.db')){
if(!strpos($database_file,'.db')) {
$database_file="$datadir/$database_file.db";
}
if (!file_exists($database_file)) {
@ -387,7 +387,7 @@ class MDB2_Driver_sqlite3 extends MDB2_Driver_Common
$php_errormsg = '';
$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->_lasterror = $this->connection->lastErrorMsg();
@ -1055,7 +1055,7 @@ class MDB2_BufferedResult_sqlite3 extends MDB2_Result_sqlite3
function seek($rownum = 0)
{
$this->result->reset();
for($i=0;$i<$rownum;$i++){
for($i=0;$i<$rownum;$i++) {
$this->result->fetchArray();
}
$this->rownum = $rownum - 1;
@ -1093,7 +1093,7 @@ class MDB2_BufferedResult_sqlite3 extends MDB2_Result_sqlite3
{
$rows = 0;
$this->result->reset();
while($this->result->fetchArray()){
while($this->result->fetchArray()) {
$rows++;
}
$this->result->reset();
@ -1113,8 +1113,8 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
// }}}
// {{{ function bindValue($parameter, &$value, $type = null)
private function getParamType($type){
switch(strtolower($type)){
private function getParamType($type) {
switch(strtolower($type)) {
case 'text':
return SQLITE3_TEXT;
case 'boolean':
@ -1139,8 +1139,8 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
*
* @access public
*/
function bindValue($parameter, $value, $type = null){
if($type){
function bindValue($parameter, $value, $type = null) {
if($type) {
$type=$this->getParamType($type);
$this->statement->bindValue($parameter,$value,$type);
}else{
@ -1162,8 +1162,8 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
*
* @access public
*/
function bindParam($parameter, &$value, $type = null){
if($type){
function bindParam($parameter, &$value, $type = null) {
if($type) {
$type=$this->getParamType($type);
$this->statement->bindParam($parameter,$value,$type);
}else{
@ -1193,7 +1193,7 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
* a MDB2 error on failure
* @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)) {
$result =& parent::_execute($result_class, $result_wrap_class);
return $result;
@ -1313,7 +1313,7 @@ class MDB2_Statement_sqlite3 extends MDB2_Statement_Common
}
$values = (array)$values;
if (!empty($values)) {
if(count($this->types)){
if(count($this->types)) {
$types=$this->types;
}else{
$types=null;

View File

@ -48,12 +48,12 @@ class OC_App{
*
* 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
$apps = self::getEnabledApps();
// prevent app.php from printing output
ob_start();
foreach( $apps as $app ){
foreach( $apps as $app ) {
if((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
self::loadApp($app);
self::$loadedApps[] = $app;
@ -94,12 +94,12 @@ class OC_App{
* @param string $app
* @param string/array $types
*/
public static function isType($app,$types){
public static function isType($app,$types) {
if(is_string($types)) {
$types=array($types);
}
$appTypes=self::getAppTypes($app);
foreach($types as $type){
foreach($types as $type) {
if(array_search($type, $appTypes)!==false) {
return true;
}
@ -112,7 +112,7 @@ class OC_App{
* @param string $app
* @return array
*/
private static function getAppTypes($app){
private static function getAppTypes($app) {
//load the cache
if(count(self::$appTypes)==0) {
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
*/
public static function setAppTypes($app){
public static function setAppTypes($app) {
$appData=self::getAppInfo($app);
if(isset($appData['types'])) {
@ -143,13 +143,13 @@ class OC_App{
/**
* get all enabled apps
*/
public static function getEnabledApps(){
public static function getEnabledApps() {
if(!OC_Config::getValue('installed', false))
return array();
$apps=array('files');
$query = OC_DB::prepare( 'SELECT `appid` FROM `*PREFIX*appconfig` WHERE `configkey` = \'enabled\' AND `configvalue`=\'yes\'' );
$result=$query->execute();
while($row=$result->fetchRow()){
while($row=$result->fetchRow()) {
if(array_search($row['appid'], $apps)===false) {
$apps[]=$row['appid'];
}
@ -164,7 +164,7 @@ class OC_App{
*
* 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' )) {
return true;
}
@ -179,7 +179,7 @@ class OC_App{
*
* This function set an app as enabled in appconfig.
*/
public static function enable( $app ){
public static function enable( $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
if(!is_numeric($app)) {
@ -215,7 +215,7 @@ class OC_App{
*
* 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
OC_Appconfig::setValue( $app, 'enabled', 'no' );
}
@ -237,7 +237,7 @@ class OC_App{
* - order: integer, that influences the position of your application in
* the navigation. Lower values come first.
*/
public static function addNavigationEntry( $data ){
public static function addNavigationEntry( $data ) {
$data['active']=false;
if(!isset($data['icon'])) {
$data['icon']='';
@ -255,7 +255,7 @@ class OC_App{
* property from all other entries. The templates can use this for
* highlighting the current position of the user.
*/
public static function setActiveNavigationEntry( $id ){
public static function setActiveNavigationEntry( $id ) {
self::$activeapp = $id;
return true;
}
@ -267,7 +267,7 @@ class OC_App{
* This function returns the id of the active navigation entry (set by
* setActiveNavigationEntry
*/
public static function getActiveNavigationEntry(){
public static function getActiveNavigationEntry() {
return self::$activeapp;
}
@ -278,7 +278,7 @@ class OC_App{
* This function returns an array containing all settings pages added. The
* entries are sorted by the key 'order' ascending.
*/
public static function getSettingsNavigation(){
public static function getSettingsNavigation() {
$l=OC_L10N::get('lib');
$settings = array();
@ -320,8 +320,8 @@ class OC_App{
}
/// This is private as well. It simply works, so don't ask for more details
private static function proceedNavigation( $list ){
foreach( $list as &$naventry ){
private static function proceedNavigation( $list ) {
foreach( $list as &$naventry ) {
$naventry['subnavigation'] = array();
if( $naventry['id'] == self::$activeapp ) {
$naventry['active'] = true;
@ -331,7 +331,7 @@ class OC_App{
}
} 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;
}
@ -388,7 +388,7 @@ class OC_App{
/**
* 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';
$version=@file_get_contents($file);
if($version) {
@ -405,7 +405,7 @@ class OC_App{
* @param boolean path (optional)
* @returns array
*/
public static function getAppInfo($appid,$path=false){
public static function getAppInfo($appid,$path=false) {
if($path) {
$file=$appid;
}else{
@ -423,18 +423,18 @@ class OC_App{
$data['info']=array();
$data['remote']=array();
$data['public']=array();
foreach($xml->children() as $child){
foreach($xml->children() as $child) {
if($child->getName()=='remote') {
foreach($child->children() as $remote){
foreach($child->children() as $remote) {
$data['remote'][$remote->getName()]=(string)$remote;
}
}elseif($child->getName()=='public') {
foreach($child->children() as $public){
foreach($child->children() as $public) {
$data['public'][$public->getName()]=(string)$public;
}
}elseif($child->getName()=='types') {
$data['types']=array();
foreach($child->children() as $type){
foreach($child->children() as $type) {
$data['types'][]=$type->getName();
}
}elseif($child->getName()=='description') {
@ -459,7 +459,7 @@ class OC_App{
* - children: array that is empty if the key 'active' is false or
* contains the subentries if the key 'active' is true
*/
public static function getNavigation(){
public static function getNavigation() {
$navigation = self::proceedNavigation( self::$navigation );
return $navigation;
}
@ -468,7 +468,7 @@ class OC_App{
* get the id of loaded app
* @return string
*/
public static function getCurrentApp(){
public static function getCurrentApp() {
$script=substr($_SERVER["SCRIPT_NAME"], strlen(OC::$WEBROOT)+1);
$topFolder=substr($script, 0, strpos($script, '/'));
if($topFolder=='apps') {
@ -483,9 +483,9 @@ class OC_App{
/**
* get the forms for either settings, admin or personal
*/
public static function getForms($type){
public static function getForms($type) {
$forms=array();
switch($type){
switch($type) {
case 'settings':
$source=self::$settingsForms;
break;
@ -496,7 +496,7 @@ class OC_App{
$source=self::$personalForms;
break;
}
foreach($source as $form){
foreach($source as $form) {
$forms[]=include $form;
}
return $forms;
@ -505,32 +505,32 @@ class OC_App{
/**
* register a settings form to be shown
*/
public static function registerSettings($app,$page){
public static function registerSettings($app,$page) {
self::$settingsForms[]= $app.'/'.$page.'.php';
}
/**
* register an admin form to be shown
*/
public static function registerAdmin($app,$page){
public static function registerAdmin($app,$page) {
self::$adminForms[]= $app.'/'.$page.'.php';
}
/**
* register a personal form to be shown
*/
public static function registerPersonal($app,$page){
public static function registerPersonal($app,$page) {
self::$personalForms[]= $app.'/'.$page.'.php';
}
/**
* get a list of all apps in the apps folder
*/
public static function getAllApps(){
public static function getAllApps() {
$apps=array();
foreach(OC::$APPSROOTS as $apps_dir) {
$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')) {
$apps[]=$file;
}
@ -565,7 +565,7 @@ class OC_App{
* This is important if you upgrade ownCloud and have non ported 3rd
* party apps installed.
*/
public static function checkAppsRequirements($apps = array()){
public static function checkAppsRequirements($apps = array()) {
if (empty($apps)) {
$apps = OC_App::getEnabledApps();
}
@ -583,7 +583,7 @@ class OC_App{
/**
* get the installed version of all apps
*/
public static function getAppVersions(){
public static function getAppVersions() {
static $versions;
if (isset($versions)) { // simple cache, needs to be fixed
return $versions; // when function is used besides in checkUpgrade
@ -591,7 +591,7 @@ class OC_App{
$versions=array();
$query = OC_DB::prepare( 'SELECT `appid`, `configvalue` FROM `*PREFIX*appconfig` WHERE `configkey` = \'installed_version\'' );
$result = $query->execute();
while($row = $result->fetchRow()){
while($row = $result->fetchRow()) {
$versions[$row['appid']]=$row['configvalue'];
}
return $versions;
@ -601,7 +601,7 @@ class OC_App{
* update the database for the app and call the update script
* @param string appid
*/
public static function updateApp($appid){
public static function updateApp($appid) {
if(file_exists(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
$appData=self::getAppInfo($appid);
foreach($appData['remote'] as $name=>$path){
foreach($appData['remote'] as $name=>$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);
}
@ -629,7 +629,7 @@ class OC_App{
* @param string appid
* @return OC_FilesystemView
*/
public static function getStorage($appid){
public static function getStorage($appid) {
if(OC_App::isEnabled($appid)) {//sanity check
if(OC_User::isLoggedIn()) {
$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
* entry in the appconfig table.
*/
public static function getApps(){
public static function getApps() {
// No magic in here!
$query = OC_DB::prepare( 'SELECT DISTINCT `appid` FROM `*PREFIX*appconfig`' );
$result = $query->execute();
$apps = array();
while( $row = $result->fetchRow()){
while( $row = $result->fetchRow()) {
$apps[] = $row["appid"];
}
@ -66,13 +66,13 @@ class OC_Appconfig{
* This function gets all keys of an app. Please note that the values are
* not returned.
*/
public static function getKeys( $app ){
public static function getKeys( $app ) {
// No magic in here as well
$query = OC_DB::prepare( 'SELECT `configkey` FROM `*PREFIX*appconfig` WHERE `appid` = ?' );
$result = $query->execute( array( $app ));
$keys = array();
while( $row = $result->fetchRow()){
while( $row = $result->fetchRow()) {
$keys[] = $row["configkey"];
}
@ -89,12 +89,12 @@ class OC_Appconfig{
* This function gets a value from the appconfig table. If the key does
* 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 :-)
$query = OC_DB::prepare( 'SELECT `configvalue` FROM `*PREFIX*appconfig` WHERE `appid` = ? AND `configkey` = ?' );
$result = $query->execute( array( $app, $key ));
$row = $result->fetchRow();
if($row){
if($row) {
return $row["configvalue"];
}else{
return $default;
@ -107,7 +107,7 @@ class OC_Appconfig{
* @param string $key
* @return bool
*/
public static function hasKey($app,$key){
public static function hasKey($app,$key) {
$exists = self::getKeys( $app );
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.
*/
public static function setValue( $app, $key, $value ){
public static function setValue( $app, $key, $value ) {
// 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->execute( array( $app, $key, $value ));
}
@ -141,7 +141,7 @@ class OC_Appconfig{
*
* Deletes a key.
*/
public static function deleteKey( $app, $key ){
public static function deleteKey( $app, $key ) {
// Boring!
$query = OC_DB::prepare( 'DELETE FROM `*PREFIX*appconfig` WHERE `appid` = ? AND `configkey` = ?' );
$query->execute( array( $app, $key ));
@ -156,7 +156,7 @@ class OC_Appconfig{
*
* Removes all keys in appconfig belonging to the app.
*/
public static function deleteApp( $app ){
public static function deleteApp( $app ) {
// Nothing special
$query = OC_DB::prepare( 'DELETE FROM `*PREFIX*appconfig` WHERE `appid` = ?' );
$query->execute( array( $app ));
@ -170,14 +170,14 @@ class OC_Appconfig{
* @param key
* @return array
*/
public static function getValues($app,$key){
if($app!==false and $key!==false){
public static function getValues($app,$key) {
if($app!==false and $key!==false) {
return false;
}
$fields='`configvalue`';
$where='WHERE';
$params=array();
if($app!==false){
if($app!==false) {
$fields.=', `configkey`';
$where.=' `appid` = ?';
$params[]=$app;
@ -192,7 +192,7 @@ class OC_Appconfig{
$query=OC_DB::prepare($queryString);
$result=$query->execute($params);
$values=array();
while($row=$result->fetchRow()){
while($row=$result->fetchRow()) {
$values[$row[$key]]=$row['configvalue'];
}
return $values;

View File

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

View File

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

View File

@ -13,10 +13,10 @@ class OC_Archive_ZIP extends OC_Archive{
private $zip=null;
private $path;
function __construct($source){
function __construct($source) {
$this->path=$source;
$this->zip=new ZipArchive();
if($this->zip->open($source,ZipArchive::CREATE)){
if($this->zip->open($source,ZipArchive::CREATE)) {
}else{
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
* @return bool
*/
function addFolder($path){
function addFolder($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
* @return bool
*/
function addFile($path,$source=''){
if($source and $source[0]=='/' and file_exists($source)){
function addFile($path,$source='') {
if($source and $source[0]=='/' and file_exists($source)) {
$result=$this->zip->addFile($source,$path);
}else{
$result=$this->zip->addFromString($path,$source);
}
if($result){
if($result) {
$this->zip->close();//close and reopen to save the zip
$this->zip->open($this->path);
}
@ -53,7 +53,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string dest
* @return bool
*/
function rename($source,$dest){
function rename($source,$dest) {
$source=$this->stripPath($source);
$dest=$this->stripPath($dest);
$this->zip->renameName($source,$dest);
@ -63,7 +63,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path
* @return int
*/
function filesize($path){
function filesize($path) {
$stat=$this->zip->statName($path);
return $stat['size'];
}
@ -72,7 +72,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path
* @return int
*/
function mtime($path){
function mtime($path) {
return filemtime($this->path);
}
/**
@ -80,13 +80,13 @@ class OC_Archive_ZIP extends OC_Archive{
* @param path
* @return array
*/
function getFolder($path){
function getFolder($path) {
$files=$this->getFiles();
$folderContent=array();
$pathLength=strlen($path);
foreach($files as $file){
if(substr($file,0,$pathLength)==$path and $file!=$path){
if(strrpos(substr($file,0,-1),'/')<=$pathLength){
foreach($files as $file) {
if(substr($file,0,$pathLength)==$path and $file!=$path) {
if(strrpos(substr($file,0,-1),'/')<=$pathLength) {
$folderContent[]=substr($file,$pathLength);
}
}
@ -97,10 +97,10 @@ class OC_Archive_ZIP extends OC_Archive{
*get all files in the archive
* @return array
*/
function getFiles(){
function getFiles() {
$fileCount=$this->zip->numFiles;
$files=array();
for($i=0;$i<$fileCount;$i++){
for($i=0;$i<$fileCount;$i++) {
$files[]=$this->zip->getNameIndex($i);
}
return $files;
@ -110,7 +110,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path
* @return string
*/
function getFile($path){
function getFile($path) {
return $this->zip->getFromName($path);
}
/**
@ -119,7 +119,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string dest
* @return bool
*/
function extractFile($path,$dest){
function extractFile($path,$dest) {
$fp = $this->zip->getStream($path);
file_put_contents($dest,$fp);
}
@ -129,7 +129,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string dest
* @return bool
*/
function extract($dest){
function extract($dest) {
return $this->zip->extractTo($dest);
}
/**
@ -137,7 +137,7 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string path
* @return bool
*/
function fileExists($path){
function fileExists($path) {
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
* @return bool
*/
function remove($path){
if($this->fileExists($path.'/')){
function remove($path) {
if($this->fileExists($path.'/')) {
return $this->zip->deleteName($path.'/');
}else{
return $this->zip->deleteName($path);
@ -158,18 +158,18 @@ class OC_Archive_ZIP extends OC_Archive{
* @param string mode
* @return resource
*/
function getStream($path,$mode){
if($mode=='r' or $mode=='rb'){
function getStream($path,$mode) {
if($mode=='r' or $mode=='rb') {
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
if(strrpos($path,'.')!==false){
if(strrpos($path,'.')!==false) {
$ext=substr($path,strrpos($path,'.'));
}else{
$ext='';
}
$tmpFile=OCP\Files::tmpFile($ext);
OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack');
if($this->fileExists($path)){
if($this->fileExists($path)) {
$this->extractFile($path,$tmpFile);
}
self::$tempFiles[$tmpFile]=$path;
@ -181,15 +181,15 @@ class OC_Archive_ZIP extends OC_Archive{
/**
* write back temporary files
*/
function writeBack($tmpFile){
if(isset(self::$tempFiles[$tmpFile])){
function writeBack($tmpFile) {
if(isset(self::$tempFiles[$tmpFile])) {
$this->addFile(self::$tempFiles[$tmpFile],$tmpFile);
unlink($tmpFile);
}
}
private function stripPath($path){
if(!$path || $path[0]=='/'){
private function stripPath($path) {
if(!$path || $path[0]=='/') {
return substr($path,1);
}else{
return $path;

View File

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

View File

@ -32,7 +32,7 @@ class OC_BackgroundJob_RegularTask{
* @param $method method name
* @return true
*/
static public function register( $klass, $method ){
static public function register( $klass, $method ) {
// Create the data structure
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 )
*/
static public function all(){
static public function all() {
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
* wait.
*/
public static function doAllSteps(){
public static function doAllSteps() {
// Do our regular work
$lasttask = OC_Appconfig::getValue( 'core', 'backgroundjobs_task', '' );
$regular_tasks = OC_BackgroundJob_RegularTask::all();
ksort( $regular_tasks );
foreach( $regular_tasks as $key => $value ){
if( strcmp( $key, $lasttask ) > 0 ){
foreach( $regular_tasks as $key => $value ) {
if( strcmp( $key, $lasttask ) > 0 ) {
// Set "restart here" config value
OC_Appconfig::setValue( 'core', 'backgroundjobs_task', $key );
call_user_func( $value );
@ -52,7 +52,7 @@ class OC_BackgroundJob_Worker{
// Do our queued tasks
$queued_tasks = OC_BackgroundJob_QueuedTask::all();
foreach( $queued_tasks as $task ){
foreach( $queued_tasks as $task ) {
OC_BackgroundJob_QueuedTask::delete( $task['id'] );
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
* services.
*/
public static function doNextStep(){
public static function doNextStep() {
$laststep = OC_Appconfig::getValue( 'core', 'backgroundjobs_step', 'regular_tasks' );
if( $laststep == 'regular_tasks' ){
if( $laststep == 'regular_tasks' ) {
// get last app
$lasttask = OC_Appconfig::getValue( 'core', 'backgroundjobs_task', '' );
@ -81,8 +81,8 @@ class OC_BackgroundJob_Worker{
$done = false;
// search for next background job
foreach( $regular_tasks as $key => $value ){
if( strcmp( $key, $lasttask ) > 0 ){
foreach( $regular_tasks as $key => $value ) {
if( strcmp( $key, $lasttask ) > 0 ) {
OC_Appconfig::setValue( 'core', 'backgroundjobs_task', $key );
$done = true;
call_user_func( $value );
@ -90,14 +90,14 @@ class OC_BackgroundJob_Worker{
}
}
if( $done == false ){
if( $done == false ) {
// Next time load queued tasks
OC_Appconfig::setValue( 'core', 'backgroundjobs_step', 'queued_tasks' );
}
}
else{
$tasks = OC_BackgroundJob_QueuedTask::all();
if( count( $tasks )){
if( count( $tasks )) {
$task = $tasks[0];
// delete job before we execute it. This prevents endless loops
// of failing jobs.

View File

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

View File

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

View File

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

View File

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

View File

@ -52,7 +52,7 @@ class OC_Config{
* This function returns all keys saved in config.php. Please note that it
* does not return the values.
*/
public static function getKeys(){
public static function getKeys() {
self::readData();
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,
* $default will be returned.
*/
public static function getValue( $key, $default = null ){
public static function getValue( $key, $default = null ) {
self::readData();
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
* not be written, false will be returned.
*/
public static function setValue( $key, $value ){
public static function setValue( $key, $value ) {
self::readData();
// Add change
@ -105,7 +105,7 @@ class OC_Config{
* This function removes a key from the config.php. If owncloud has no
* write access to config.php, the function will return false.
*/
public static function deleteKey( $key ){
public static function deleteKey( $key ) {
self::readData();
if( array_key_exists( $key, self::$cache )) {
@ -125,7 +125,7 @@ class OC_Config{
*
* Reads the config file and saves it to the cache
*/
private static function readData(){
private static function readData() {
if( self::$init ) {
return true;
}
@ -153,7 +153,7 @@ class OC_Config{
* Saves the config to the config file.
*
*/
public static function writeData(){
public static function writeData() {
// Create a php file ...
$content = "<?php\n\$CONFIG = ";
$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
*/
protected function validateUserPass($username, $password){
protected function validateUserPass($username, $password) {
if (OC_User::isLoggedIn()) {
OC_Util::setupFS($username);
return true;
} else {
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);
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'];
}
$properties = array_fill_keys($paths, array());
if(count($paths)>0){
if(count($paths)>0) {
$placeholders = join(',', array_fill(0, count($paths), '?'));
$query = OC_DB::prepare( 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ?' . ' AND `propertypath` IN ('.$placeholders.')' );
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 );
$lockList = array();
while( $row = $result->fetchRow()){
while( $row = $result->fetchRow()) {
$lockInfo = new Sabre_DAV_Locks_LockInfo();
$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
// If it was null, we need to delete the property
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->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) {
$this->touch($propertyValue);
} 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->execute( array( OC_User::getUser(), $this->path, $propertyName,$propertyValue ));
} 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 ));
$this->property_cache = array();
while( $row = $result->fetchRow()){
while( $row = $result->fetchRow()) {
$this->property_cache[$row['propertyname']] = $row['propertyvalue'];
}
}
// if the array was empty, we need to return everything
if(count($properties) == 0){
if(count($properties) == 0) {
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) {
throw new Sabre_DAV_Exception('Setting members of the group is not supported yet');
}
function updatePrincipal($path, $mutations){return 0;}
function searchPrincipals($prefixPath, array $searchProperties){return 0;}
function updatePrincipal($path, $mutations) {return 0;}
function searchPrincipals($prefixPath, array $searchProperties) {return 0;}
}

View File

@ -41,7 +41,7 @@ class OC_DB {
* check which backend we should use
* @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)
if(class_exists('PDO') && OC_Config::getValue('installed', false)) {
$type = OC_Config::getValue( "dbtype", "sqlite" );
@ -63,7 +63,7 @@ class OC_DB {
*
* Connects to the database as specified in config.php
*/
public static function connect($backend=null){
public static function connect($backend=null) {
if(self::$connection) {
return;
}
@ -84,7 +84,7 @@ class OC_DB {
/**
* connect to the database using pdo
*/
public static function connectPDO(){
public static function connectPDO() {
if(self::$connection) {
if(self::$backend==self::BACKEND_MDB2) {
self::disconnect();
@ -149,7 +149,7 @@ class OC_DB {
}
try{
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>');
die();
}
@ -194,7 +194,7 @@ class OC_DB {
'quote_identifier' => true );
// Add the dsn according to the database type
switch($type){
switch($type) {
case 'sqlite':
case 'sqlite3':
$dsn = array(
@ -262,7 +262,7 @@ class OC_DB {
*
* 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 (self::$backend == self::BACKEND_MDB2) {
@ -305,7 +305,7 @@ class OC_DB {
}else{
try{
$result=self::$connection->prepare($query);
}catch(PDOException $e){
}catch(PDOException $e) {
$entry = 'DB Error: "'.$e->getMessage().'"<br />';
$entry .= 'Offending command was: '.$query.'<br />';
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
* cause trouble!
*/
public static function insertid($table=null){
public static function insertid($table=null) {
self::connect();
if($table !== null) {
$prefix = OC_Config::getValue( "dbtableprefix", "oc_" );
@ -343,7 +343,7 @@ class OC_DB {
*
* This is good bye, good bye, yeah!
*/
public static function disconnect(){
public static function disconnect() {
// Cut connection if required
if(self::$connection) {
if(self::$backend==self::BACKEND_MDB2) {
@ -364,7 +364,7 @@ class OC_DB {
*
* 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();
// write the scheme
@ -386,7 +386,7 @@ class OC_DB {
*
* TODO: write more documentation
*/
public static function createDbFromStructure( $file ){
public static function createDbFromStructure( $file ) {
$CONFIG_DBNAME = OC_Config::getValue( "dbname", "owncloud" );
$CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
$CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
@ -445,7 +445,7 @@ class OC_DB {
* @brief update the database scheme
* @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_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.sqlite.org/lang_createtable.html
* 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 );
}
*/
@ -496,7 +496,7 @@ class OC_DB {
*
* Connects to a MDB2 database scheme
*/
private static function connectScheme(){
private static function connectScheme() {
// We need a mdb2 database connection
self::connectMDB2();
self::$MDB2->loadModule('Manager');
@ -519,7 +519,7 @@ class OC_DB {
* This function replaces *PREFIX* with the value of $CONFIG_DBTABLEPREFIX
* and replaces the ` woth ' or " according to the database driver.
*/
private static function processQuery( $query ){
private static function processQuery( $query ) {
self::connect();
// We need Database type and table prefix
if(is_null(self::$type)) {
@ -554,7 +554,7 @@ class OC_DB {
* @brief drop a table
* @param string $tableNamme the table to drop
*/
public static function dropTable($tableName){
public static function dropTable($tableName) {
self::connectMDB2();
self::$MDB2->loadModule('Manager');
self::$MDB2->dropTable($tableName);
@ -564,7 +564,7 @@ class OC_DB {
* remove all tables defined in a database structure xml file
* @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_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
self::connectScheme();
@ -584,7 +584,7 @@ class OC_DB {
// Delete our temporary file
unlink( $file2 );
$tables=array_keys($definition['tables']);
foreach($tables as $table){
foreach($tables as $table) {
self::dropTable($table);
}
}
@ -593,13 +593,13 @@ class OC_DB {
* @brief replaces the owncloud tables with a new set
* @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();
self::beginTransaction();
// Delete the old tables
self::removeDBStructure( OC::$SERVERROOT . '/db_structure.xml' );
foreach($apps as $app){
foreach($apps as $app) {
$path = OC_App::getAppPath($app).'/appinfo/database.xml';
if(file_exists($path)) {
self::removeDBStructure( $path );
@ -614,7 +614,7 @@ class OC_DB {
/**
* Start a transaction
*/
public static function beginTransaction(){
public static function beginTransaction() {
self::connect();
if (self::$backend==self::BACKEND_MDB2 && !self::$connection->supports('transactions')) {
return false;
@ -640,10 +640,10 @@ class OC_DB {
* @param mixed $result
* @return bool
*/
public static function isError($result){
public static function isError($result) {
if(!$result) {
return true;
}elseif(self::$backend==self::BACKEND_MDB2 and PEAR::isError($result)){
}elseif(self::$backend==self::BACKEND_MDB2 and PEAR::isError($result)) {
return true;
}else{
return false;
@ -658,16 +658,16 @@ class PDOStatementWrapper{
private $statement=null;
private $lastArguments=array();
public function __construct($statement){
public function __construct($statement) {
$this->statement=$statement;
}
/**
* make execute return the result instead of a bool
*/
public function execute($input=array()){
public function execute($input=array()) {
$this->lastArguments=$input;
if(count($input)>0){
if(count($input)>0) {
$result=$this->statement->execute($input);
}else{
$result=$this->statement->execute();
@ -682,7 +682,7 @@ class PDOStatementWrapper{
/**
* provide numRows
*/
public function numRows(){
public function numRows() {
$regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
if (preg_match($regex, $this->statement->queryString, $output) > 0) {
$query = OC_DB::prepare("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);
@ -695,14 +695,14 @@ class PDOStatementWrapper{
/**
* provide an alias for fetch
*/
public function fetchRow(){
public function fetchRow() {
return $this->statement->fetch();
}
/**
* 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);
}
@ -711,7 +711,7 @@ class PDOStatementWrapper{
* fetch single column from the next row
* @param int $colnum the column number to fetch
*/
public function fetchOne($colnum = 0){
public function fetchOne($colnum = 0) {
return $this->statement->fetchColumn($colnum);
}
}

View File

@ -31,18 +31,18 @@ class OC_EventSource{
private $fallback;
private $fallBackId=0;
public function __construct(){
public function __construct() {
@ob_end_clean();
header('Cache-Control: no-cache');
$this->fallback=isset($_GET['fallback']) and $_GET['fallback']=='true';
if($this->fallback){
if($this->fallback) {
$this->fallBackId=$_GET['fallback_id'];
header("Content-Type: text/html");
echo str_repeat('<span></span>'.PHP_EOL,10); //dummy data to keep IE happy
}else{
header("Content-Type: text/event-stream");
}
if( !OC_Util::isCallRegistered()){
if( !OC_Util::isCallRegistered()) {
exit();
}
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
*/
public function send($type,$data=null){
if(is_null($data)){
public function send($type,$data=null) {
if(is_null($data)) {
$data=$type;
$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;
echo $response;
}else{
if($type){
if($type) {
echo 'event: '.$type.PHP_EOL;
}
echo 'data: '.json_encode($data).PHP_EOL;
@ -77,7 +77,7 @@ class OC_EventSource{
/**
* 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
}
}

View File

@ -42,9 +42,9 @@ class OC_FileCache{
* - encrypted
* - versioned
*/
public static function get($path,$root=false){
if(OC_FileCache_Update::hasUpdated($path,$root)){
if($root===false){//filesystem hooks are only valid for the default root
public static function get($path,$root=false) {
if(OC_FileCache_Update::hasUpdated($path,$root)) {
if($root===false) {//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$path));
}else{
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
*/
public static function put($path,$data,$root=false){
if($root===false){
public static function put($path,$data,$root=false) {
if($root===false) {
$root=OC_Filesystem::getRoot();
}
$fullpath=$root.$path;
$parent=self::getParentId($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);
unset(OC_FileCache_Cached::$savedData[$fullpath]);
}
if($id!=-1){
if($id!=-1) {
self::update($id,$data);
return;
}
@ -84,14 +84,14 @@ class OC_FileCache{
$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;
return;
}
if(!isset($data['encrypted'])){
if(!isset($data['encrypted'])) {
$data['encrypted']=false;
}
if(!isset($data['versioned'])){
if(!isset($data['versioned'])) {
$data['versioned']=false;
}
$mimePart=dirname($data['mimetype']);
@ -103,11 +103,11 @@ class OC_FileCache{
$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(?,?,?,?,?,?,?,?,?,?,?,?,?)');
$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);
}
if($cache=OC_Cache::getUserCache(true)){
if($cache=OC_Cache::getUserCache(true)) {
$cache->remove('fileid/'.$fullpath);//ensure we don't have -1 cached
}
}
@ -117,13 +117,13 @@ class OC_FileCache{
* @param int $id
* @param array $data
*/
private static function update($id,$data){
private static function update($id,$data) {
$arguments=array();
$queryParts=array();
foreach(array('size','mtime','ctime','mimetype','encrypted','versioned','writable') as $attribute){
if(isset($data[$attribute])){
foreach(array('size','mtime','ctime','mimetype','encrypted','versioned','writable') as $attribute) {
if(isset($data[$attribute])) {
//Convert to int it args are false
if($data[$attribute] === false){
if($data[$attribute] === false) {
$arguments[] = 0;
}else{
$arguments[] = $data[$attribute];
@ -131,7 +131,7 @@ class OC_FileCache{
$queryParts[]='`'.$attribute.'`=?';
}
}
if(isset($data['mimetype'])){
if(isset($data['mimetype'])) {
$arguments[]=dirname($data['mimetype']);
$queryParts[]='`mimepart`=?';
}
@ -140,7 +140,7 @@ class OC_FileCache{
$sql = 'UPDATE `*PREFIX*fscache` SET '.implode(' , ',$queryParts).' WHERE `id`=?';
$query=OC_DB::prepare($sql);
$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);
}
}
@ -151,8 +151,8 @@ class OC_FileCache{
* @param string newPath
* @param string root (optional)
*/
public static function move($oldPath,$newPath,$root=false){
if($root===false){
public static function move($oldPath,$newPath,$root=false) {
if($root===false) {
$root=OC_Filesystem::getRoot();
}
// 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->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->remove('fileid/'.$oldPath);
}
@ -173,12 +173,12 @@ class OC_FileCache{
$query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `path` LIKE ?');
$oldLength=strlen($oldPath);
$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'];
$new=$newPath.substr($old,$oldLength);
$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->remove('fileid/'.$old);
}
@ -190,8 +190,8 @@ class OC_FileCache{
* @param string path
* @param string root (optional)
*/
public static function delete($path,$root=false){
if($root===false){
public static function delete($path,$root=false) {
if($root===false) {
$root=OC_Filesystem::getRoot();
}
$query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE `path_hash`=?');
@ -211,20 +211,20 @@ class OC_FileCache{
* @param string root (optional)
* @return array of filepaths
*/
public static function search($search,$returnData=false,$root=false){
if($root===false){
public static function search($search,$returnData=false,$root=false) {
if($root===false) {
$root=OC_Filesystem::getRoot();
}
$rootLen=strlen($root);
if(!$returnData){
if(!$returnData) {
$query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `name` LIKE ? AND `user`=?');
}else{
$query=OC_DB::prepare('SELECT * FROM `*PREFIX*fscache` WHERE `name` LIKE ? AND `user`=?');
}
$result=$query->execute(array("%$search%",OC_User::getUser()));
$names=array();
while($row=$result->fetchRow()){
if(!$returnData){
while($row=$result->fetchRow()) {
if(!$returnData) {
$names[]=substr($row['path'],$rootLen);
}else{
$row['path']=substr($row['path'],$rootLen);
@ -249,8 +249,8 @@ class OC_FileCache{
* - encrypted
* - versioned
*/
public static function getFolderContent($path,$root=false,$mimetype_filter=''){
if(OC_FileCache_Update::hasUpdated($path,$root,true)){
public static function getFolderContent($path,$root=false,$mimetype_filter='') {
if(OC_FileCache_Update::hasUpdated($path,$root,true)) {
OC_FileCache_Update::updateFolder($path,$root);
}
return OC_FileCache_Cached::getFolderContent($path,$root,$mimetype_filter);
@ -262,7 +262,7 @@ class OC_FileCache{
* @param string root (optional)
* @return bool
*/
public static function inCache($path,$root=false){
public static function inCache($path,$root=false) {
return self::getId($path,$root)!=-1;
}
@ -272,30 +272,30 @@ class OC_FileCache{
* @param string root (optional)
* @return int
*/
public static function getId($path,$root=false){
if($root===false){
public static function getId($path,$root=false) {
if($root===false) {
$root=OC_Filesystem::getRoot();
}
$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);
}
$query=OC_DB::prepare('SELECT `id` FROM `*PREFIX*fscache` WHERE `path_hash`=?');
$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);
return -1;
}
$result=$result->fetchRow();
if(is_array($result)){
if(is_array($result)) {
$id=$result['id'];
}else{
$id=-1;
}
if($cache=OC_Cache::getUserCache(true)){
if($cache=OC_Cache::getUserCache(true)) {
$cache->set('fileid/'.$fullPath,$id);
}
@ -308,8 +308,8 @@ class OC_FileCache{
* @param string user (optional)
* @return string
*/
public static function getPath($id,$user=''){
if(!$user){
public static function getPath($id,$user='') {
if(!$user) {
$user=OC_User::getUser();
}
$query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `id`=? AND `user`=?');
@ -317,7 +317,7 @@ class OC_FileCache{
$row=$result->fetchRow();
$path=$row['path'];
$root='/'.$user.'/files';
if(substr($path,0,strlen($root))!=$root){
if(substr($path,0,strlen($root))!=$root) {
return false;
}
return substr($path,strlen($root));
@ -328,8 +328,8 @@ class OC_FileCache{
* @param string $path
* @return int
*/
private static function getParentId($path){
if($path=='/'){
private static function getParentId($path) {
if($path=='/') {
return -1;
}else{
return self::getId(dirname($path),'');
@ -342,10 +342,10 @@ class OC_FileCache{
* @param int $sizeDiff
* @param string root (optinal)
*/
public static function increaseSize($path,$sizeDiff, $root=false){
public static function increaseSize($path,$sizeDiff, $root=false) {
if($sizeDiff==0) return;
$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->execute(array($sizeDiff,$id));
$id=self::getParentId($path);
@ -360,8 +360,8 @@ class OC_FileCache{
* @param int count (optional)
* @param string root (optional)
*/
public static function scan($path,$eventSource=false,&$count=0,$root=false){
if($eventSource){
public static function scan($path,$eventSource=false,&$count=0,$root=false) {
if($eventSource) {
$eventSource->send('scanning',array('file'=>$path,'count'=>$count));
}
$lastSend=$count;
@ -369,7 +369,7 @@ class OC_FileCache{
if (substr($path, 0, 7) == '/Shared') {
return;
}
if($root===false){
if($root===false) {
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView($root);
@ -377,16 +377,16 @@ class OC_FileCache{
self::scanFile($path,$root);
$dh=$view->opendir($path.'/');
$totalSize=0;
if($dh){
if($dh) {
while (($filename = readdir($dh)) !== false) {
if($filename != '.' and $filename != '..'){
if($filename != '.' and $filename != '..') {
$file=$path.'/'.$filename;
if($view->is_dir($file.'/')){
if($view->is_dir($file.'/')) {
self::scan($file,$eventSource,$count,$root);
}else{
$totalSize+=self::scanFile($file,$root);
$count++;
if($count>$lastSend+25 and $eventSource){
if($count>$lastSend+25 and $eventSource) {
$lastSend=$count;
$eventSource->send('scanning',array('file'=>$path,'count'=>$count));
}
@ -405,12 +405,12 @@ class OC_FileCache{
* @param string root (optional)
* @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)
if (substr($path, 0, 7) == '/Shared') {
return;
}
if($root===false){
if($root===false) {
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView($root);
@ -419,14 +419,14 @@ class OC_FileCache{
clearstatcache();
$mimetype=$view->getMimeType($path);
$stat=$view->stat($path);
if($mimetype=='httpd/unix-directory'){
if($mimetype=='httpd/unix-directory') {
$writable=$view->is_writable($path.'/');
}else{
$writable=$view->is_writable($path);
}
$stat['mimetype']=$mimetype;
$stat['writable']=$writable;
if($path=='/'){
if($path=='/') {
$path='';
}
self::put($path,$stat,$root);
@ -446,14 +446,14 @@ class OC_FileCache{
* seccond mimetype part can be ommited
* e.g. searchByMime('audio')
*/
public static function searchByMime($part1,$part2=null,$root=false){
if($root===false){
public static function searchByMime($part1,$part2=null,$root=false) {
if($root===false) {
$root=OC_Filesystem::getRoot();
}
$rootLen=strlen($root);
$root .= '%';
$user=OC_User::getUser();
if(!$part2){
if(!$part2) {
$query=OC_DB::prepare('SELECT `path` FROM `*PREFIX*fscache` WHERE `mimepart`=? AND `user`=? AND `path` LIKE ?');
$result=$query->execute(array($part1,$user, $root));
}else{
@ -461,7 +461,7 @@ class OC_FileCache{
$result=$query->execute(array($part1.'/'.$part2,$user, $root));
}
$names=array();
while($row=$result->fetchRow()){
while($row=$result->fetchRow()) {
$names[]=substr($row['path'],$rootLen);
}
return $names;
@ -470,7 +470,7 @@ class OC_FileCache{
/**
* 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->execute();
}
@ -479,8 +479,8 @@ class OC_FileCache{
* clear filecache entries
* @param string user (optonal)
*/
public static function clear($user=''){
if($user){
public static function clear($user='') {
if($user) {
$query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE user=?');
$query->execute(array($user));
}else{

View File

@ -13,20 +13,20 @@
class OC_FileCache_Cached{
public static $savedData=array();
public static function get($path,$root=false){
if($root===false){
public static function get($path,$root=false) {
if($root===false) {
$root=OC_Filesystem::getRoot();
}
$path=$root.$path;
$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();
if(is_array($result)){
if(isset(self::$savedData[$path])){
if(is_array($result)) {
if(isset(self::$savedData[$path])) {
$result=array_merge($result,self::$savedData[$path]);
}
return $result;
}else{
if(isset(self::$savedData[$path])){
if(isset(self::$savedData[$path])) {
return self::$savedData[$path];
}else{
return array();
@ -50,17 +50,17 @@ class OC_FileCache_Cached{
* - encrypted
* - versioned
*/
public static function getFolderContent($path,$root=false,$mimetype_filter=''){
if($root===false){
public static function getFolderContent($path,$root=false,$mimetype_filter='') {
if($root===false) {
$root=OC_Filesystem::getRoot();
}
$parent=OC_FileCache::getId($path,$root);
if($parent==-1){
if($parent==-1) {
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` = ?)');
$result=$query->execute(array($parent, $mimetype_filter.'%', 'httpd/unix-directory'))->fetchAll();
if(is_array($result)){
if(is_array($result)) {
return $result;
}else{
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
* @return bool
*/
public static function hasUpdated($path,$root=false,$folder=false){
if($root===false){
public static function hasUpdated($path,$root=false,$folder=false) {
if($root===false) {
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView($root);
}
if(!$view->file_exists($path)){
if(!$view->file_exists($path)) {
return false;
}
$cachedData=OC_FileCache_Cached::get($path,$root);
if(isset($cachedData['mtime'])){
if(isset($cachedData['mtime'])) {
$cachedMTime=$cachedData['mtime'];
if($folder){
if($folder) {
return $view->hasUpdated($path.'/',$cachedMTime);
}else{
return $view->hasUpdated($path,$cachedMTime);
}
}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 true;
@ -46,19 +46,19 @@ class OC_FileCache_Update{
/**
* delete non existing files from the cache
*/
public static function cleanFolder($path,$root=false){
if($root===false){
public static function cleanFolder($path,$root=false) {
if($root===false) {
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView($root);
}
$cachedContent=OC_FileCache_Cached::getFolderContent($path,$root);
foreach($cachedContent as $fileData){
foreach($cachedContent as $fileData) {
$path=$fileData['path'];
$file=$view->getRelativePath($path);
if(!$view->file_exists($file)){
if($root===false){//filesystem hooks are only valid for the default root
if(!$view->file_exists($file)) {
if($root===false) {//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_delete',array('path'=>$file));
}else{
self::delete($file,$root);
@ -72,19 +72,19 @@ class OC_FileCache_Update{
* @param string path
* @param string root (optional)
*/
public static function updateFolder($path,$root=false){
if($root===false){
public static function updateFolder($path,$root=false) {
if($root===false) {
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView($root);
}
$dh=$view->opendir($path.'/');
if($dh){//check for changed/new files
if($dh) {//check for changed/new files
while (($filename = readdir($dh)) !== false) {
if($filename != '.' and $filename != '..'){
if($filename != '.' and $filename != '..') {
$file=$path.'/'.$filename;
if(self::hasUpdated($file,$root)){
if($root===false){//filesystem hooks are only valid for the default root
if(self::hasUpdated($file,$root)) {
if($root===false) {//filesystem hooks are only valid for the default root
OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$file));
}else{
self::update($file,$root);
@ -97,7 +97,7 @@ class OC_FileCache_Update{
self::cleanFolder($path,$root);
//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));
}else{
self::update($path,$root);
@ -109,7 +109,7 @@ class OC_FileCache_Update{
* @param array $params
* @param string root (optional)
*/
public static function fileSystemWatcherWrite($params){
public static function fileSystemWatcherWrite($params) {
$path=$params['path'];
self::update($path);
}
@ -119,7 +119,7 @@ class OC_FileCache_Update{
* @param array $params
* @param string root (optional)
*/
public static function fileSystemWatcherDelete($params){
public static function fileSystemWatcherDelete($params) {
$path=$params['path'];
self::delete($path);
}
@ -129,7 +129,7 @@ class OC_FileCache_Update{
* @param array $params
* @param string root (optional)
*/
public static function fileSystemWatcherRename($params){
public static function fileSystemWatcherRename($params) {
$oldPath=$params['oldpath'];
$newPath=$params['newpath'];
self::rename($oldPath,$newPath);
@ -140,8 +140,8 @@ class OC_FileCache_Update{
* @param string path
* @param string root (optional)
*/
public static function update($path,$root=false){
if($root===false){
public static function update($path,$root=false) {
if($root===false) {
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView($root);
@ -153,10 +153,10 @@ class OC_FileCache_Update{
$cached=OC_FileCache_Cached::get($path,$root);
$cachedSize=isset($cached['size'])?$cached['size']:0;
if($view->is_dir($path.'/')){
if(OC_FileCache::inCache($path,$root)){
if($view->is_dir($path.'/')) {
if(OC_FileCache::inCache($path,$root)) {
$cachedContent=OC_FileCache_Cached::getFolderContent($path,$root);
foreach($cachedContent as $file){
foreach($cachedContent as $file) {
$size+=$file['size'];
}
$mtime=$view->filemtime($path.'/');
@ -179,9 +179,9 @@ class OC_FileCache_Update{
* @param string path
* @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);
if(!isset($cached['size'])){
if(!isset($cached['size'])) {
return;
}
$size=$cached['size'];
@ -195,11 +195,11 @@ class OC_FileCache_Update{
* @param string newPath
* @param string root (optional)
*/
public static function rename($oldPath,$newPath,$root=false){
if(!OC_FileCache::inCache($oldPath,$root)){
public static function rename($oldPath,$newPath,$root=false) {
if(!OC_FileCache::inCache($oldPath,$root)) {
return;
}
if($root===false){
if($root===false) {
$view=OC_Filesystem::getView();
}else{
$view=new OC_FilesystemView($root);

View File

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

View File

@ -32,15 +32,15 @@ class OC_FileProxy_Quota extends OC_FileProxy{
* get the quota for the current user
* @return int
*/
private function getQuota(){
if($this->userQuota!=-1){
private function getQuota() {
if($this->userQuota!=-1) {
return $this->userQuota;
}
$userQuota=OC_Preferences::getValue(OC_User::getUser(),'files','quota','default');
if($userQuota=='default'){
if($userQuota=='default') {
$userQuota=OC_AppConfig::getValue('files','default_quota','none');
}
if($userQuota=='none'){
if($userQuota=='none') {
$this->userQuota=0;
}else{
$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
* @return int
*/
private function getFreeSpace(){
private function getFreeSpace() {
$rootInfo=OC_FileCache_Cached::get('');
// TODO Remove after merge of share_api
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($sharedInfo['size'])?$usedSpace-$sharedInfo['size']:$usedSpace;
$totalSpace=$this->getQuota();
if($totalSpace==0){
if($totalSpace==0) {
return 0;
}
return $totalSpace-$usedSpace;
}
public function postFree_space($path,$space){
public function postFree_space($path,$space) {
$free=$this->getFreeSpace();
if($free==0){
if($free==0) {
return $space;
}
return min($free,$space);
}
public function preFile_put_contents($path,$data){
public function preFile_put_contents($path,$data) {
if (is_resource($data)) {
$data = '';//TODO: find a way to get the length of the stream without emptying it
}
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);
}
public function preFromTmpFile($tmpfile,$path){
public function preFromTmpFile($tmpfile,$path) {
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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -146,22 +146,22 @@ class OC_Filesystem{
* @param string path
* @return string
*/
static public function getMountPoint($path){
static public function getMountPoint($path) {
OC_Hook::emit(self::CLASSNAME,'get_mountpoint',array('path'=>$path));
if(!$path){
if(!$path) {
$path='/';
}
if($path[0]!=='/'){
if($path[0]!=='/') {
$path='/'.$path;
}
$path=str_replace('//', '/',$path);
$foundMountPoint='';
$mountPoints=array_keys(OC_Filesystem::$mounts);
foreach($mountPoints as $mountpoint){
if($mountpoint==$path){
foreach($mountPoints as $mountpoint) {
if($mountpoint==$path) {
return $mountpoint;
}
if(strpos($path,$mountpoint)===0 and strlen($mountpoint)>strlen($foundMountPoint)){
if(strpos($path,$mountpoint)===0 and strlen($mountpoint)>strlen($foundMountPoint)) {
$foundMountPoint=$mountpoint;
}
}
@ -173,7 +173,7 @@ class OC_Filesystem{
* @param string path
* @return bool
*/
static public function getInternalPath($path){
static public function getInternalPath($path) {
$mountPoint=self::getMountPoint($path);
$internalPath=substr($path,strlen($mountPoint));
return $internalPath;
@ -183,10 +183,10 @@ class OC_Filesystem{
* @param string path
* @return OC_Filestorage
*/
static public function getStorage($path){
static public function getStorage($path) {
$mountpoint=self::getMountPoint($path);
if($mountpoint){
if(!isset(OC_Filesystem::$storages[$mountpoint])){
if($mountpoint) {
if(!isset(OC_Filesystem::$storages[$mountpoint])) {
$mount=OC_Filesystem::$mounts[$mountpoint];
OC_Filesystem::$storages[$mountpoint]=OC_Filesystem::createStorage($mount['class'],$mount['arguments']);
}
@ -194,27 +194,27 @@ class OC_Filesystem{
}
}
static public function init($root){
if(self::$defaultInstance){
static public function init($root) {
if(self::$defaultInstance) {
return false;
}
self::$defaultInstance=new OC_FilesystemView($root);
//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');
if(isset($mountConfig['global'])){
foreach($mountConfig['global'] as $mountPoint=>$options){
if(isset($mountConfig['global'])) {
foreach($mountConfig['global'] as $mountPoint=>$options) {
self::mount($options['class'],$options['options'],$mountPoint);
}
}
if(isset($mountConfig['group'])){
foreach($mountConfig['group'] as $group=>$mounts){
if(OC_Group::inGroup(OC_User::getUser(),$group)){
foreach($mounts as $mountPoint=>$options){
if(isset($mountConfig['group'])) {
foreach($mountConfig['group'] as $group=>$mounts) {
if(OC_Group::inGroup(OC_User::getUser(),$group)) {
foreach($mounts as $mountPoint=>$options) {
$mountPoint=self::setUserVars($mountPoint);
foreach($options as &$option){
foreach($options as &$option) {
$option=self::setUserVars($option);
}
self::mount($options['class'],$options['options'],$mountPoint);
@ -223,12 +223,12 @@ class OC_Filesystem{
}
}
if(isset($mountConfig['user'])){
foreach($mountConfig['user'] as $user=>$mounts){
if($user==='all' or strtolower($user)===strtolower(OC_User::getUser())){
foreach($mounts as $mountPoint=>$options){
if(isset($mountConfig['user'])) {
foreach($mountConfig['user'] as $user=>$mounts) {
if($user==='all' or strtolower($user)===strtolower(OC_User::getUser())) {
foreach($mounts as $mountPoint=>$options) {
$mountPoint=self::setUserVars($mountPoint);
foreach($options as &$option){
foreach($options as &$option) {
$option=self::setUserVars($option);
}
self::mount($options['class'],$options['options'],$mountPoint);
@ -239,7 +239,7 @@ class OC_Filesystem{
$mtime=filemtime(OC::$SERVERROOT.'/config/mount.php');
$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_Appconfig::setValue('files','mountconfigmtime',$mtime);
}
@ -253,7 +253,7 @@ class OC_Filesystem{
* @param string intput
* @return string
*/
private static function setUserVars($input){
private static function setUserVars($input) {
return str_replace('$user',OC_User::getUser(),$input);
}
@ -261,14 +261,14 @@ class OC_Filesystem{
* get the default filesystem view
* @return OC_FilesystemView
*/
static public function getView(){
static public function getView() {
return self::$defaultInstance;
}
/**
* tear down the filesystem, removing all storage providers
*/
static public function tearDown(){
static public function tearDown() {
self::$storages=array();
}
@ -278,8 +278,8 @@ class OC_Filesystem{
* @param array arguments
* @return OC_Filestorage
*/
static private function createStorage($class,$arguments){
if(class_exists($class)){
static private function createStorage($class,$arguments) {
if(class_exists($class)) {
try {
return new $class($arguments);
} catch (Exception $exception) {
@ -297,7 +297,7 @@ class OC_Filesystem{
* @param string fakeRoot
* @return bool
*/
static public function chroot($fakeRoot){
static public function chroot($fakeRoot) {
return self::$defaultInstance->chroot($fakeRoot);
}
@ -307,14 +307,14 @@ class OC_Filesystem{
*
* Returns path like /admin/files
*/
static public function getRoot(){
static public function getRoot() {
return self::$defaultInstance->getRoot();
}
/**
* clear all mounts and storage backends
*/
public static function clearMounts(){
public static function clearMounts() {
self::$mounts=array();
self::$storages=array();
}
@ -324,11 +324,11 @@ class OC_Filesystem{
* @param OC_Filestorage storage
* @param string mountpoint
*/
static public function mount($class,$arguments,$mountpoint){
if($mountpoint[0]!='/'){
static public function mount($class,$arguments,$mountpoint) {
if($mountpoint[0]!='/') {
$mountpoint='/'.$mountpoint;
}
if(substr($mountpoint,-1)!=='/'){
if(substr($mountpoint,-1)!=='/') {
$mountpoint=$mountpoint.'/';
}
self::$mounts[$mountpoint]=array('class'=>$class,'arguments'=>$arguments);
@ -340,14 +340,14 @@ class OC_Filesystem{
* @param string path
* @return string
*/
static public function getLocalFile($path){
static public function getLocalFile($path) {
return self::$defaultInstance->getLocalFile($path);
}
/**
* @param string path
* @return string
*/
static public function getLocalFolder($path){
static public function getLocalFolder($path) {
return self::$defaultInstance->getLocalFolder($path);
}
@ -370,11 +370,11 @@ class OC_Filesystem{
* @param string path
* @return bool
*/
static public function isValidPath($path){
if(!$path || $path[0]!=='/'){
static public function isValidPath($path) {
if(!$path || $path[0]!=='/') {
$path='/'.$path;
}
if(strstr($path,'/../') || strrchr($path, '/') === '/..' ){
if(strstr($path,'/../') || strrchr($path, '/') === '/..' ) {
return false;
}
return true;
@ -385,7 +385,7 @@ class OC_Filesystem{
* Listens to write and rename hooks
* @param array $data from hook
*/
static public function isBlacklisted($data){
static public function isBlacklisted($data) {
$blacklist = array('.htaccess');
if (isset($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.
*/
static public function mkdir($path){
static public function mkdir($path) {
return self::$defaultInstance->mkdir($path);
}
static public function rmdir($path){
static public function rmdir($path) {
return self::$defaultInstance->rmdir($path);
}
static public function opendir($path){
static public function opendir($path) {
return self::$defaultInstance->opendir($path);
}
static public function readdir($path){
static public function 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);
}
static public function is_file($path){
static public function is_file($path) {
return self::$defaultInstance->is_file($path);
}
static public function stat($path){
static public function stat($path) {
return self::$defaultInstance->stat($path);
}
static public function filetype($path){
static public function filetype($path) {
return self::$defaultInstance->filetype($path);
}
static public function filesize($path){
static public function filesize($path) {
return self::$defaultInstance->filesize($path);
}
static public function readfile($path){
static public function readfile($path) {
return self::$defaultInstance->readfile($path);
}
/**
* @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);
}
/**
* @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);
}
static public function isCreatable($path) {
@ -460,55 +460,55 @@ class OC_Filesystem{
static public function 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);
}
static public function filectime($path){
static public function filectime($path) {
return self::$defaultInstance->filectime($path);
}
static public function filemtime($path){
static public function 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);
}
static public function file_get_contents($path){
static public function 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);
}
static public function unlink($path){
static public function 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);
}
static public function copy($path1,$path2){
static public function 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);
}
static public function toTmpFile($path){
static public function 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);
}
static public function getMimeType($path){
static public function 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);
}
static public function free_space($path='/'){
static public function free_space($path='/') {
return self::$defaultInstance->free_space($path);
}
static public function search($query){
static public function search($query) {
return OC_FileCache::search($query);
}
@ -517,7 +517,7 @@ class OC_Filesystem{
* @param int $time
* @return bool
*/
static public function hasUpdated($path,$time){
static public function hasUpdated($path,$time) {
return self::$defaultInstance->hasUpdated($path,$time);
}
@ -536,26 +536,26 @@ class OC_Filesystem{
* @param bool $stripTrailingSlash
* @return string
*/
public static function normalizePath($path,$stripTrailingSlash=true){
if($path==''){
public static function normalizePath($path,$stripTrailingSlash=true) {
if($path=='') {
return '/';
}
//no windows style slashes
$path=str_replace('\\','/',$path);
//add leading slash
if($path[0]!=='/'){
if($path[0]!=='/') {
$path='/'.$path;
}
//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);
}
//remove duplicate slashes
while(strpos($path,'//')!==false){
while(strpos($path,'//')!==false) {
$path=str_replace('//','/',$path);
}
//normalize unicode if possible
if(class_exists('Normalizer')){
if(class_exists('Normalizer')) {
$path=Normalizer::normalize($path);
}
return $path;

View File

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

View File

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

View File

@ -42,8 +42,8 @@ class OC_Group {
* @param string $backend The backend to use for user managment
* @returns true/false
*/
public static function useBackend( $backend ){
if($backend instanceof OC_Group_Interface){
public static function useBackend( $backend ) {
if($backend instanceof OC_Group_Interface) {
self::$_usedBackends[]=$backend;
}
}
@ -51,7 +51,7 @@ class OC_Group {
/**
* remove all used backends
*/
public static function clearBackends(){
public static function clearBackends() {
self::$_usedBackends=array();
}
@ -65,27 +65,27 @@ class OC_Group {
*
* 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
// 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;
}
// No empty group names!
if( !$gid ){
if( !$gid ) {
return false;
}
// No duplicate group names
if( in_array( $gid, self::getGroups())){
if( in_array( $gid, self::getGroups())) {
return false;
}
$run = true;
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
foreach(self::$_usedBackends as $backend){
foreach(self::$_usedBackends as $backend) {
if(!$backend->implementsActions(OC_GROUP_BACKEND_CREATE_GROUP))
continue;
@ -106,18 +106,18 @@ class OC_Group {
*
* 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
if( $gid == "admin" ){
if( $gid == "admin" ) {
return false;
}
$run = true;
OC_Hook::emit( "OC_Group", "pre_deleteGroup", array( "run" => &$run, "gid" => $gid ));
if($run){
if($run) {
//delete the group from all backends
foreach(self::$_usedBackends as $backend){
foreach(self::$_usedBackends as $backend) {
if(!$backend->implementsActions(OC_GROUP_BACKEND_DELETE_GROUP))
continue;
@ -139,9 +139,9 @@ class OC_Group {
*
* Checks whether the user is member of a group or not.
*/
public static function inGroup( $uid, $gid ){
foreach(self::$_usedBackends as $backend){
if($backend->inGroup($uid,$gid)){
public static function inGroup( $uid, $gid ) {
foreach(self::$_usedBackends as $backend) {
if($backend->inGroup($uid,$gid)) {
return true;
}
}
@ -156,9 +156,9 @@ class OC_Group {
*
* Adds a user to a group.
*/
public static function addToGroup( $uid, $gid ){
public static function addToGroup( $uid, $gid ) {
// Does the group exist?
if( !OC_Group::groupExists($gid)){
if( !OC_Group::groupExists($gid)) {
return false;
}
@ -166,19 +166,19 @@ class OC_Group {
$run = true;
OC_Hook::emit( "OC_Group", "pre_addToGroup", array( "run" => &$run, "uid" => $uid, "gid" => $gid ));
if($run){
if($run) {
$succes=false;
//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))
continue;
if($backend->groupExists($gid)){
if($backend->groupExists($gid)) {
$succes|=$backend->addToGroup($uid, $gid);
}
}
if($succes){
if($succes) {
OC_Hook::emit( "OC_User", "post_addToGroup", array( "uid" => $uid, "gid" => $gid ));
}
return $succes;
@ -195,13 +195,13 @@ class OC_Group {
*
* removes the user from a group.
*/
public static function removeFromGroup( $uid, $gid ){
public static function removeFromGroup( $uid, $gid ) {
$run = true;
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
foreach(self::$_usedBackends as $backend){
foreach(self::$_usedBackends as $backend) {
if(!$backend->implementsActions(OC_GROUP_BACKEND_REMOVE_FROM_GOUP))
continue;
@ -222,9 +222,9 @@ class OC_Group {
* This function fetches all groups a user belongs to. It does not check
* if the user exists at all.
*/
public static function getUserGroups( $uid ){
public static function getUserGroups( $uid ) {
$groups=array();
foreach(self::$_usedBackends as $backend){
foreach(self::$_usedBackends as $backend) {
$groups=array_merge($backend->getUserGroups($uid),$groups);
}
asort($groups);
@ -251,9 +251,9 @@ class OC_Group {
* @param string $gid
* @return bool
*/
public static function groupExists($gid){
foreach(self::$_usedBackends as $backend){
if ($backend->groupExists($gid)){
public static function groupExists($gid) {
foreach(self::$_usedBackends as $backend) {
if ($backend->groupExists($gid)) {
return true;
}
}
@ -266,7 +266,7 @@ class OC_Group {
*/
public static function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
$users=array();
foreach(self::$_usedBackends as $backend){
foreach(self::$_usedBackends as $backend) {
$users = array_merge($backend->usersInGroup($gid, $search, $limit, $offset), $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
* compared with OC_USER_BACKEND_CREATE_USER etc.
*/
public function getSupportedActions(){
public function getSupportedActions() {
$actions = 0;
foreach($this->possibleActions AS $action => $methodName){
foreach($this->possibleActions AS $action => $methodName) {
if(method_exists($this, $methodName)) {
$actions |= $action;
}
@ -71,7 +71,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface {
* Returns the supported actions as int to be
* compared with OC_GROUP_BACKEND_CREATE_GROUP etc.
*/
public function implementsActions($actions){
public function implementsActions($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.
*/
public function inGroup($uid, $gid){
public function inGroup($uid, $gid) {
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
* if the user exists at all.
*/
public function getUserGroups($uid){
public function getUserGroups($uid) {
return array();
}
@ -115,7 +115,7 @@ abstract class OC_Group_Backend implements OC_Group_Interface {
* @param string $gid
* @return bool
*/
public function groupExists($gid){
public function groupExists($gid) {
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
* be returned.
*/
public function createGroup( $gid ){
public function createGroup( $gid ) {
// Check for existence
$stmt = OC_DB::prepare( "SELECT `gid` FROM `*PREFIX*groups` WHERE `gid` = ?" );
$result = $stmt->execute( array( $gid ));
if( $result->fetchRow() ){
if( $result->fetchRow() ) {
// Can not add an existing group
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
*/
public function deleteGroup( $gid ){
public function deleteGroup( $gid ) {
// Delete the group
$stmt = OC_DB::prepare( "DELETE FROM `*PREFIX*groups` WHERE `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.
*/
public function inGroup( $uid, $gid ){
public function inGroup( $uid, $gid ) {
// check
$stmt = OC_DB::prepare( "SELECT `uid` FROM `*PREFIX*group_user` WHERE `gid` = ? AND `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.
*/
public function addToGroup( $uid, $gid ){
public function addToGroup( $uid, $gid ) {
// 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->execute( array( $uid, $gid ));
return true;
@ -130,7 +130,7 @@ class OC_Group_Database extends OC_Group_Backend {
*
* 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->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
* if the user exists at all.
*/
public function getUserGroups( $uid ){
public function getUserGroups( $uid ) {
// No magic!
$stmt = OC_DB::prepare( "SELECT `gid` FROM `*PREFIX*group_user` WHERE `uid` = ?" );
$result = $stmt->execute( array( $uid ));
$groups = array();
while( $row = $result->fetchRow()){
while( $row = $result->fetchRow()) {
$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
* be returned.
*/
public function createGroup($gid){
if(!isset($this->groups[$gid])){
public function createGroup($gid) {
if(!isset($this->groups[$gid])) {
$this->groups[$gid]=array();
return true;
}else{
@ -50,8 +50,8 @@ class OC_Group_Dummy extends OC_Group_Backend {
*
* Deletes a group and removes it from the group_user-table
*/
public function deleteGroup($gid){
if(isset($this->groups[$gid])){
public function deleteGroup($gid) {
if(isset($this->groups[$gid])) {
unset($this->groups[$gid]);
return true;
}else{
@ -67,8 +67,8 @@ class OC_Group_Dummy extends OC_Group_Backend {
*
* Checks whether the user is member of a group or not.
*/
public function inGroup($uid, $gid){
if(isset($this->groups[$gid])){
public function inGroup($uid, $gid) {
if(isset($this->groups[$gid])) {
return (array_search($uid,$this->groups[$gid])!==false);
}else{
return false;
@ -83,9 +83,9 @@ class OC_Group_Dummy extends OC_Group_Backend {
*
* Adds a user to a group.
*/
public function addToGroup($uid, $gid){
if(isset($this->groups[$gid])){
if(array_search($uid,$this->groups[$gid])===false){
public function addToGroup($uid, $gid) {
if(isset($this->groups[$gid])) {
if(array_search($uid,$this->groups[$gid])===false) {
$this->groups[$gid][]=$uid;
return true;
}else{
@ -104,9 +104,9 @@ class OC_Group_Dummy extends OC_Group_Backend {
*
* removes the user from a group.
*/
public function removeFromGroup($uid,$gid){
if(isset($this->groups[$gid])){
if(($index=array_search($uid,$this->groups[$gid]))!==false){
public function removeFromGroup($uid,$gid) {
if(isset($this->groups[$gid])) {
if(($index=array_search($uid,$this->groups[$gid]))!==false) {
unset($this->groups[$gid][$index]);
}else{
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
* if the user exists at all.
*/
public function getUserGroups($uid){
public function getUserGroups($uid) {
$groups=array();
$allGroups=array_keys($this->groups);
foreach($allGroups as $group){
if($this->inGroup($uid,$group)){
foreach($allGroups as $group) {
if($this->inGroup($uid,$group)) {
$groups[]=$group;
}
}
@ -150,7 +150,7 @@ class OC_Group_Dummy extends OC_Group_Backend {
* @returns array with user ids
*/
public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
if(isset($this->groups[$gid])){
if(isset($this->groups[$gid])) {
return $this->groups[$gid];
}else{
return array();

View File

@ -37,12 +37,12 @@ class OC_Helper {
*
* Returns a url to the given app and file.
*/
public static function linkTo( $app, $file, $args = array() ){
if( $app != '' ){
public static function linkTo( $app, $file, $args = array() ) {
if( $app != '' ) {
$app_path = OC_App::getAppPath($app);
// Check if the app is in the app folder
if( $app_path && file_exists( $app_path.'/'.$file )){
if(substr($file, -3) == 'php' || substr($file, -3) == 'css'){
if( $app_path && file_exists( $app_path.'/'.$file )) {
if(substr($file, -3) == 'php' || substr($file, -3) == 'css') {
$urlLinkTo = OC::$WEBROOT . '/?app=' . $app;
$urlLinkTo .= ($file!='index.php')?'&getfile=' . urlencode($file):'';
}else{
@ -54,7 +54,7 @@ class OC_Helper {
}
}
else{
if( file_exists( OC::$SERVERROOT . '/core/'. $file )){
if( file_exists( OC::$SERVERROOT . '/core/'. $file )) {
$urlLinkTo = OC::$WEBROOT . '/core/'.$file;
}
else{
@ -125,22 +125,22 @@ class OC_Helper {
*
* 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
$theme=OC_Config::getValue( "theme" );
// 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";
}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";
}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";
}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";
}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";
}elseif( file_exists( OC::$SERVERROOT."/core/img/$image" )){
}elseif( file_exists( OC::$SERVERROOT."/core/img/$image" )) {
return OC::$WEBROOT."/core/img/$image";
}else{
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.
*/
public static function mimetypeIcon( $mimetype ){
public static function mimetypeIcon( $mimetype ) {
$alias=array('application/xml'=>'code/xml');
if(isset($alias[$mimetype])){
if(isset($alias[$mimetype])) {
$mimetype=$alias[$mimetype];
}
// Replace slash with a minus
$mimetype = str_replace( "/", "-", $mimetype );
// Is it a dir?
if( $mimetype == "dir" ){
if( $mimetype == "dir" ) {
return OC::$WEBROOT."/core/img/filetypes/folder.png";
}
// 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";
}
//try only the first part of the filetype
$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";
}
else{
@ -189,16 +189,16 @@ class OC_Helper {
*
* Makes 2048 to 2 kB.
*/
public static function humanFileSize( $bytes ){
if( $bytes < 1024 ){
public static function humanFileSize( $bytes ) {
if( $bytes < 1024 ) {
return "$bytes B";
}
$bytes = round( $bytes / 1024, 1 );
if( $bytes < 1024 ){
if( $bytes < 1024 ) {
return "$bytes kB";
}
$bytes = round( $bytes / 1024, 1 );
if( $bytes < 1024 ){
if( $bytes < 1024 ) {
return "$bytes MB";
}
@ -216,7 +216,7 @@ class OC_Helper {
*
* Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
*/
public static function computerFileSize( $str ){
public static function computerFileSize( $str ) {
$bytes = 0;
$str=strtolower($str);
@ -280,17 +280,17 @@ class OC_Helper {
*
*/
static function copyr($src, $dest) {
if(is_dir($src)){
if(!is_dir($dest)){
if(is_dir($src)) {
if(!is_dir($dest)) {
mkdir($dest);
}
$files = scandir($src);
foreach ($files as $file){
if ($file != "." && $file != ".."){
foreach ($files as $file) {
if ($file != "." && $file != "..") {
self::copyr("$src/$file", "$dest/$file");
}
}
}elseif(file_exists($src)){
}elseif(file_exists($src)) {
copy($src, $dest);
}
}
@ -303,13 +303,13 @@ class OC_Helper {
static function rmdirr($dir) {
if(is_dir($dir)) {
$files=scandir($dir);
foreach($files as $file){
if ($file != "." && $file != ".."){
foreach($files as $file) {
if ($file != "." && $file != "..") {
self::rmdirr("$dir/$file");
}
}
rmdir($dir);
}elseif(file_exists($dir)){
}elseif(file_exists($dir)) {
unlink($dir);
}
if(file_exists($dir)) {
@ -323,7 +323,7 @@ class OC_Helper {
* @return string
* 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://');
if (@is_dir($path)) {
@ -331,9 +331,9 @@ class OC_Helper {
return "httpd/unix-directory";
}
if(strpos($path,'.')){
if(strpos($path,'.')) {
//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');
}
$extension=strtolower(strrchr(basename($path), "."));
@ -343,9 +343,9 @@ class OC_Helper {
$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));
if($info){
if($info) {
$mimeType=substr($info,0,strpos($info,';'));
}
finfo_close($finfo);
@ -379,8 +379,8 @@ class OC_Helper {
* @param string data
* @return string
*/
static function getStringMimeType($data){
if(function_exists('finfo_open') and function_exists('finfo_file')){
static function getStringMimeType($data) {
if(function_exists('finfo_open') and function_exists('finfo_file')) {
$finfo=finfo_open(FILEINFO_MIME);
return finfo_buffer($finfo, $data);
}else{
@ -429,7 +429,7 @@ class OC_Helper {
* @param string optional search path, defaults to $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
if ($path === false) {
$path = getenv("PATH");
@ -473,12 +473,12 @@ class OC_Helper {
* @param resource target
* @return int the number of bytes copied
*/
public static function streamCopy($source,$target){
if(!$source or !$target){
public static function streamCopy($source,$target) {
if(!$source or !$target) {
return false;
}
$count=0;
while(!feof($source)){
while(!feof($source)) {
$count+=fwrite($target,fread($source,8192));
}
return $count;
@ -491,7 +491,7 @@ class OC_Helper {
*
* 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;
$fh=fopen($file,'w');
fclose($fh);
@ -505,7 +505,7 @@ class OC_Helper {
*
* 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());
mkdir($path);
self::$tmpFiles[]=$path;
@ -515,9 +515,9 @@ class OC_Helper {
/**
* remove all files created by self::tmpFile
*/
public static function cleanTmp(){
public static function cleanTmp() {
$leftoversFile=get_temp_dir().'/oc-not-deleted';
if(file_exists($leftoversFile)){
if(file_exists($leftoversFile)) {
$leftovers=file($leftoversFile);
foreach($leftovers as $file) {
self::rmdirr($file);
@ -525,8 +525,8 @@ class OC_Helper {
unlink($leftoversFile);
}
foreach(self::$tmpFiles as $file){
if(file_exists($file)){
foreach(self::$tmpFiles as $file) {
if(file_exists($file)) {
if(!self::rmdirr($file)) {
file_put_contents($leftoversFile, $file."\n", FILE_APPEND);
}
@ -541,8 +541,8 @@ class OC_Helper {
* @param $filename
* @return string
*/
public static function buildNotExistingFileName($path, $filename){
if($path==='/'){
public static function buildNotExistingFileName($path, $filename) {
if($path==='/') {
$path='';
}
if ($pos = strrpos($filename, '.')) {
@ -571,21 +571,21 @@ class OC_Helper {
* @param $parent
* @return bool
*/
public static function issubdirectory($sub, $parent){
if($sub == null || $sub == '' || $parent == null || $parent == ''){
public static function issubdirectory($sub, $parent) {
if($sub == null || $sub == '' || $parent == null || $parent == '') {
return false;
}
$realpath_sub = realpath($sub);
$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;
}
if($realpath_sub && $realpath_sub != '' && $realpath_parent && $realpath_parent != ''){
if(substr($realpath_sub, 0, strlen($realpath_parent)) == $realpath_parent){
if($realpath_sub && $realpath_sub != '' && $realpath_parent && $realpath_parent != '') {
if(substr($realpath_sub, 0, strlen($realpath_parent)) == $realpath_parent) {
return true;
}
}else{
if(substr($sub, 0, strlen($parent)) == $parent){
if(substr($sub, 0, strlen($parent)) == $parent) {
return true;
}
}
@ -610,7 +610,7 @@ class OC_Helper {
* 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;
$ret = array();
foreach ($input as $k => $v) {

View File

@ -19,12 +19,12 @@ class OC_Hook{
*
* TODO: write example
*/
static public function connect( $signalclass, $signalname, $slotclass, $slotname ){
static public function connect( $signalclass, $signalname, $slotclass, $slotname ) {
// Create the data structure
if( !array_key_exists( $signalclass, self::$registered )){
if( !array_key_exists( $signalclass, self::$registered )) {
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();
}
@ -48,17 +48,17 @@ class OC_Hook{
*
* 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
if( !array_key_exists( $signalclass, self::$registered )){
if( !array_key_exists( $signalclass, self::$registered )) {
return false;
}
if( !array_key_exists( $signalname, self::$registered[$signalclass] )){
if( !array_key_exists( $signalname, self::$registered[$signalclass] )) {
return false;
}
// 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 );
}
@ -71,9 +71,9 @@ class OC_Hook{
* @param string signalclass
* @param string signalname
*/
static public function clear($signalclass='', $signalname=''){
if($signalclass){
if($signalname){
static public function clear($signalclass='', $signalname='') {
if($signalclass) {
if($signalname) {
self::$registered[$signalclass][$signalname]=array();
}else{
self::$registered[$signalclass]=array();

View File

@ -262,7 +262,7 @@ class OC_Image {
* @returns The orientation or -1 if no EXIF data is available.
*/
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);
return -1;
}
@ -612,7 +612,7 @@ class OC_Image {
$y = ($height_orig/2) - ($height/2);
$x = 0;
}
if($size>0){
if($size>0) {
$targetWidth=$size;
$targetHeight=$size;
}else{
@ -666,14 +666,14 @@ class OC_Image {
return true;
}
public function destroy(){
if($this->valid()){
public function destroy() {
if($this->valid()) {
imagedestroy($this->resource);
}
$this->resource=null;
}
public function __destruct(){
public function __destruct() {
$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
* needed to get the app working.
*/
public static function installApp( $data = array()){
if(!isset($data['source'])){
public static function installApp( $data = array()) {
if(!isset($data['source'])) {
OC_Log::write('core','No source specified when installing app',OC_Log::ERROR);
return false;
}
//download the file if necesary
if($data['source']=='http'){
if($data['source']=='http') {
$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);
return false;
}
copy($data['href'],$path);
}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);
return false;
}
@ -79,10 +79,10 @@ class OC_Installer{
//detect the archive type
$mime=OC_Helper::getMimeType($path);
if($mime=='application/zip'){
if($mime=='application/zip') {
rename($path,$path.'.zip');
$path.='.zip';
}elseif($mime=='application/x-gzip'){
}elseif($mime=='application/x-gzip') {
rename($path,$path.'.tgz');
$path.='.tgz';
}else{
@ -94,40 +94,40 @@ class OC_Installer{
$extractDir=OC_Helper::tmpFolder();
OC_Helper::rmdirr($extractDir);
mkdir($extractDir);
if($archive=OC_Archive::open($path)){
if($archive=OC_Archive::open($path)) {
$archive->extract($extractDir);
} else {
OC_Log::write('core','Failed to open archive when installing app',OC_Log::ERROR);
OC_Helper::rmdirr($extractDir);
if($data['source']=='http'){
if($data['source']=='http') {
unlink($path);
}
return false;
}
//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
$dh=opendir($extractDir);
while($folder=readdir($dh)){
if($folder[0]!='.' and is_dir($extractDir.'/'.$folder)){
if(is_file($extractDir.'/'.$folder.'/appinfo/info.xml')){
while($folder=readdir($dh)) {
if($folder[0]!='.' and is_dir($extractDir.'/'.$folder)) {
if(is_file($extractDir.'/'.$folder.'/appinfo/info.xml')) {
$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_Helper::rmdirr($extractDir);
if($data['source']=='http'){
if($data['source']=='http') {
unlink($path);
}
return false;
}
$info=OC_App::getAppInfo($extractDir.'/appinfo/info.xml',true);
// 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_Helper::rmdirr($extractDir);
return false;
@ -135,17 +135,17 @@ class OC_Installer{
// check if the app is compatible with this version of ownCloud
$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_Helper::rmdirr($extractDir);
return false;
}
//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_Helper::rmdirr($extractDir);
if($data['source']=='http'){
if($data['source']=='http') {
unlink($path);
}
return false;
@ -153,24 +153,24 @@ class OC_Installer{
$basedir=OC_App::getInstallPath().'/'.$info['id'];
//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_Helper::rmdirr($extractDir);
if($data['source']=='http'){
if($data['source']=='http') {
unlink($path);
}
return false;
}
if(isset($data['pretent']) and $data['pretent']==true){
if(isset($data['pretent']) and $data['pretent']==true) {
return false;
}
//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_Helper::rmdirr($extractDir);
if($data['source']=='http'){
if($data['source']=='http') {
unlink($path);
}
return false;
@ -181,12 +181,12 @@ class OC_Installer{
OC_Helper::rmdirr($extractDir);
//install the database
if(is_file($basedir.'/appinfo/database.xml')){
if(is_file($basedir.'/appinfo/database.xml')) {
OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
}
//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');
}
@ -195,10 +195,10 @@ class OC_Installer{
OC_Appconfig::setValue($info['id'],'enabled','no');
//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);
}
foreach($info['public'] as $name=>$path){
foreach($info['public'] as $name=>$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.
*/
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;
}
@ -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')"
*/
public static function upgradeApp( $data = array()){
public static function upgradeApp( $data = array()) {
// TODO: write function
return true;
}
@ -275,7 +275,7 @@ class OC_Installer{
* The function will not delete preferences, tables and the configuration,
* 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
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;
*/
public static function installShippedApps(){
public static function installShippedApps() {
foreach(OC::$APPSROOTS as $app_dir) {
if($dir = opendir( $app_dir['path'] )){
while( false !== ( $filename = readdir( $dir ))){
if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ){
if( file_exists( $app_dir['path']."/$filename/appinfo/app.php" )){
if(!OC_Installer::isInstalled($filename)){
if($dir = opendir( $app_dir['path'] )) {
while( false !== ( $filename = readdir( $dir ))) {
if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
if( file_exists( $app_dir['path']."/$filename/appinfo/app.php" )) {
if(!OC_Installer::isInstalled($filename)) {
$info=OC_App::getAppInfo($filename);
$enabled = isset($info['default_enable']);
if( $enabled ){
if( $enabled ) {
OC_Installer::installShippedApp($filename);
OC_Appconfig::setValue($filename,'enabled','yes');
}
@ -312,24 +312,24 @@ class OC_Installer{
* @param string $app id of the app to install
* @returns array see OC_App::getAppInfo
*/
public static function installShippedApp($app){
public static function installShippedApp($app) {
//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");
}
//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");
}
$info=OC_App::getAppInfo($app);
OC_Appconfig::setValue($app,'installed_version',OC_App::getAppVersion($app));
//set remote/public handelers
foreach($info['remote'] as $name=>$path){
foreach($info['remote'] as $name=>$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);
}
@ -344,7 +344,7 @@ class OC_Installer{
* @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.
*/
public static function checkCode($appname,$folder){
public static function checkCode($appname,$folder) {
$blacklist=array(
'exec(',
@ -355,7 +355,7 @@ class OC_Installer{
);
// is the code checker enabled?
if(OC_Config::getValue('appcodechecker', false)){
if(OC_Config::getValue('appcodechecker', false)) {
// check if grep is installed
$grep = exec('which grep');

View File

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

View File

@ -66,9 +66,9 @@ class OC_L10N{
* get an L10N instance
* @return OC_L10N
*/
public static function get($app,$lang=null){
if(is_null($lang)){
if(!isset(self::$instances[$app])){
public static function get($app,$lang=null) {
if(is_null($lang)) {
if(!isset(self::$instances[$app])) {
self::$instances[$app]=new OC_L10N($app);
}
return self::$instances[$app];
@ -86,12 +86,12 @@ class OC_L10N{
* If language is not set, the constructor tries to find the right
* language.
*/
public function __construct($app, $lang = null){
public function __construct($app, $lang = null) {
$this->app = $app;
$this->lang = $lang;
}
protected function init(){
protected function init() {
if ($this->app === true) {
return;
}
@ -104,7 +104,7 @@ class OC_L10N{
}
// 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->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')) {
// Include the file, save the data from $CONFIG
include(strip_tags($i18ndir).strip_tags($lang).'.php');
if(isset($TRANSLATIONS) && is_array($TRANSLATIONS)){
if(isset($TRANSLATIONS) && is_array($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(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);
}
}
@ -146,7 +146,7 @@ class OC_L10N{
* Returns the translation. If no translation is found, $text will be
* returned.
*/
public function t($text, $parameters = array()){
public function t($text, $parameters = array()) {
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);
$result = array();
foreach($textArray as $key => $text){
foreach($textArray as $key => $text) {
$result[$key] = (string)$this->t($text);
}
return $result;
@ -179,7 +179,7 @@ class OC_L10N{
*
* Returns an associative array with all translations
*/
public function getTranslations(){
public function getTranslations() {
$this->init();
return $this->translations;
}
@ -206,9 +206,9 @@ class OC_L10N{
* - l10n-field: time
* - params: timestamp (int/string)
*/
public function l($type, $data){
public function l($type, $data) {
$this->init();
switch($type){
switch($type) {
// If you add something don't forget to add it to $localizations
// at the top of the page
case 'date':
@ -233,7 +233,7 @@ class OC_L10N{
* This function is useful to avoid loading thousands of files if only one
* 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));
return $text[$lang];
}
@ -249,37 +249,37 @@ class OC_L10N{
*
* If nothing works it returns 'en'
*/
public static function findLanguage($app = null){
if(!is_array($app) && self::$language != ''){
public static function findLanguage($app = null) {
if(!is_array($app) && 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');
self::$language = $lang;
if(is_array($app)){
if(is_array($app)) {
$available = $app;
$lang_exists = array_search($lang, $available) !== false;
}
else {
$lang_exists = self::languageExists($app, $lang);
}
if($lang_exists){
if($lang_exists) {
return $lang;
}
}
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$accepted_languages = preg_split('/,\s*/', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if(is_array($app)){
if(is_array($app)) {
$available = $app;
}
else{
$available = self::findAvailableLanguages($app);
}
foreach($accepted_languages as $i){
foreach($accepted_languages as $i) {
$temp = explode(';', $i);
if(array_search($temp[0], $available) !== false){
if(array_search($temp[0], $available) !== false) {
return $temp[0];
}
}
@ -294,12 +294,12 @@ class OC_L10N{
* @param $app App that needs to be translated
* @returns directory
*/
protected static function findI18nDir($app){
protected static function findI18nDir($app) {
// find the i18n dir
$i18ndir = OC::$SERVERROOT.'/core/l10n/';
if($app != ''){
if($app != '') {
// 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/';
}
else{
@ -314,13 +314,13 @@ class OC_L10N{
* @param $app App that needs to be translated
* @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
$dir = self::findI18nDir($app);
if(is_dir($dir)){
if(is_dir($dir)) {
$files=scandir($dir);
foreach($files as $file){
if(substr($file, -4, 4) == '.php'){
foreach($files as $file) {
if(substr($file, -4, 4) == '.php') {
$i = substr($file, 0, -4);
$available[] = $i;
}
@ -329,12 +329,12 @@ class OC_L10N{
return $available;
}
public static function languageExists($app, $lang){
if ($lang == 'en'){//english is always available
public static function languageExists($app, $lang) {
if ($lang == 'en') {//english is always available
return true;
}
$dir = self::findI18nDir($app);
if(is_dir($dir)){
if(is_dir($dir)) {
return file_exists($dir.'/'.$lang.'.php');
}
return false;

View File

@ -8,16 +8,16 @@
class OC_L10N_String{
protected $l10n;
public function __construct($l10n, $text, $parameters){
public function __construct($l10n, $text, $parameters) {
$this->l10n = $l10n;
$this->text = $text;
$this->parameters = $parameters;
}
public function __toString(){
public function __toString() {
$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($this->text, $this->parameters);

View File

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

View File

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

View File

@ -52,20 +52,20 @@ class OC_Migrate{
* register a new migration provider
* @param OC_Migrate_Provider $provider
*/
public static function registerProvider($provider){
public static function registerProvider($provider) {
self::$providers[]=$provider;
}
/**
* @brief finds and loads the providers
*/
static private function findProviders(){
static private function findProviders() {
// Find the providers
$apps = OC_App::getAllApps();
foreach($apps as $app){
foreach($apps as $app) {
$path = OC_App::getAppPath($app) . '/appinfo/migrate.php';
if( file_exists( $path ) ){
if( file_exists( $path ) ) {
include( $path );
}
}
@ -78,21 +78,21 @@ class OC_Migrate{
* @param otional $path string path to zip output folder
* @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' );
// Validate export type
$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 );
return json_encode( array( array( 'success' => false ) ) );
}
self::$exporttype = $type;
// Userid?
if( self::$exporttype == 'user' ){
if( self::$exporttype == 'user' ) {
// Check user exists
if( !is_null($uid) ){
if( !is_null($uid) ) {
$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);
return json_encode( array( 'success' => false ) );
}
@ -102,18 +102,18 @@ class OC_Migrate{
}
}
// Calculate zipname
if( self::$exporttype == 'user' ){
if( self::$exporttype == 'user' ) {
$zipname = 'oc_export_' . self::$uid . '_' . date("y-m-d_H-i-s") . '.zip';
} else {
$zipname = 'oc_export_' . self::$exporttype . '_' . date("y-m-d_H-i-s") . '.zip';
}
// Calculate path
if( self::$exporttype == 'user' ){
if( self::$exporttype == 'user' ) {
self::$zippath = $datadir . '/' . self::$uid . '/' . $zipname;
} else {
if( !is_null( $path ) ){
if( !is_null( $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 );
return json_encode( array( 'success' => false ) );
}
@ -124,17 +124,17 @@ class OC_Migrate{
}
}
// Create the zip object
if( !self::createZip() ){
if( !self::createZip() ) {
return json_encode( array( 'success' => false ) );
}
// Do the export
self::findProviders();
$exportdata = array();
switch( self::$exporttype ){
switch( self::$exporttype ) {
case 'user':
// Connect to the db
self::$dbpath = $datadir . '/' . self::$uid . '/migration.db';
if( !self::connectDB() ){
if( !self::connectDB() ) {
return json_encode( array( 'success' => false ) );
}
self::$content = new OC_Migration_Content( self::$zip, self::$MDB2 );
@ -158,14 +158,14 @@ class OC_Migrate{
// Add the export to the zip
self::$content->addFromString( $dbexport, "dbexport.xml" );
// Add user data
foreach(OC_User::getUsers() as $user){
foreach(OC_User::getUsers() as $user) {
self::$content->addDir(OC_User::getHome($user), true, "/userdata/" );
}
break;
case 'userfiles':
self::$content = new OC_Migration_Content( self::$zip );
// 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, "/" );
}
break;
@ -178,12 +178,12 @@ class OC_Migrate{
}
break;
}
if( !$info = self::getExportInfo( $exportdata ) ){
if( !$info = self::getExportInfo( $exportdata ) ) {
return json_encode( array( 'success' => false ) );
}
// Add the export info json to the export zip
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' => true, 'data' => self::$zippath ) );
@ -195,22 +195,22 @@ class OC_Migrate{
* @param optional $type type of import (user or instance)
* @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' );
// Extract the zip
if( !$extractpath = self::extractZip( $path ) ){
if( !$extractpath = self::extractZip( $path ) ) {
return json_encode( array( 'success' => false ) );
}
// Get export_info.json
$scan = scandir( $extractpath );
// 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 );
return json_encode( array( 'success' => false ) );
}
$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 );
return json_encode( array( 'success' => false ) );
}
@ -219,13 +219,13 @@ class OC_Migrate{
$currentuser = OC_User::getUser();
// Have we got a user if type is user
if( self::$exporttype == 'user' ){
if( self::$exporttype == 'user' ) {
self::$uid = !is_null($uid) ? $uid : $currentuser;
}
// We need to be an admin if we are not importing our own data
if(($type == 'user' && self::$uid != $currentuser) || $type != 'user' ){
if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )){
if(($type == 'user' && self::$uid != $currentuser) || $type != 'user' ) {
if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )) {
// Naughty.
OC_Log::write( 'migration', 'Import not permitted.', OC_Log::ERROR );
return json_encode( array( 'success' => false ) );
@ -233,23 +233,23 @@ class OC_Migrate{
}
// Handle export types
switch( self::$exporttype ){
switch( self::$exporttype ) {
case 'user':
// 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 );
return json_encode( array( 'success' => false ) );
}
// 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 ) );
}
// 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 ) );
}
// 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 );
}
return json_encode( array( 'success' => true, 'data' => $appsimported ) );
@ -262,19 +262,19 @@ class OC_Migrate{
// Delete current data folder.
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 );
return json_encode( array( 'success' => false ) );
}
// 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 );
return json_encode( array( 'success' => false ) );
}
// Import the db
if( !OC_DB::replaceDB( $extractpath . 'dbexport.xml' ) ){
if( !OC_DB::replaceDB( $extractpath . 'dbexport.xml' ) ) {
return json_encode( array( 'success' => false ) );
}
// Done
@ -291,15 +291,15 @@ class OC_Migrate{
* $param optional $deleteRootToo bool delete the root directory
* @return bool
*/
private static function unlink_r( $dir, $deleteRootToo=true ){
if( !$dh = @opendir( $dir ) ){
private static function unlink_r( $dir, $deleteRootToo=true ) {
if( !$dh = @opendir( $dir ) ) {
return false;
}
while (false !== ($obj = readdir($dh))){
while (false !== ($obj = readdir($dh))) {
if($obj == '.' || $obj == '..') {
continue;
}
if (!@unlink($dir . '/' . $obj)){
if (!@unlink($dir . '/' . $obj)) {
self::unlink_r($dir.'/'.$obj, true);
}
}
@ -316,16 +316,16 @@ class OC_Migrate{
* @param $dest string path to destination
* @return bool
*/
private static function copy_r( $path, $dest ){
if( is_dir($path) ){
private static function copy_r( $path, $dest ) {
if( is_dir($path) ) {
@mkdir( $dest );
$objects = scandir( $path );
if( sizeof( $objects ) > 0 ){
foreach( $objects as $file ){
if( sizeof( $objects ) > 0 ) {
foreach( $objects as $file ) {
if( $file == "." || $file == ".." || $file == ".htaccess")
continue;
// go on
if( is_dir( $path . '/' . $file ) ){
if( is_dir( $path . '/' . $file ) ) {
self::copy_r( $path .'/' . $file, $dest . '/' . $file );
} else {
copy( $path . '/' . $file, $dest . '/' . $file );
@ -334,7 +334,7 @@ class OC_Migrate{
}
return true;
}
elseif( is_file( $path ) ){
elseif( is_file( $path ) ) {
return copy( $path, $dest );
} else {
return false;
@ -346,10 +346,10 @@ class OC_Migrate{
* @param $path string path to the zip
* @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;
// Validate path
if( !file_exists( $path ) ){
if( !file_exists( $path ) ) {
OC_Log::write( 'migration', 'Zip not found', OC_Log::ERROR );
return false;
}
@ -358,7 +358,7 @@ class OC_Migrate{
return false;
}
$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;
}
self::$zip->close();
@ -369,13 +369,13 @@ class OC_Migrate{
* @brief connects to a MDB2 database scheme
* @returns bool
*/
static private function connectScheme(){
static private function connectScheme() {
// We need a mdb2 database connection
self::$MDB2->loadModule( 'Manager' );
self::$MDB2->loadModule( 'Reverse' );
// Connect if this did not happen before
if( !self::$schema ){
if( !self::$schema ) {
require_once 'MDB2/Schema.php';
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
* @return bool whether operation was successfull
*/
private static function exportAppData( ){
private static function exportAppData( ) {
$success = true;
$return = array();
// Foreach provider
foreach( self::$providers as $provider ){
foreach( self::$providers as $provider ) {
// Check if the app is enabled
if( OC_App::isEnabled( $provider->getID() ) ){
if( OC_App::isEnabled( $provider->getID() ) ) {
$success = true;
// 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
$tables = self::createAppTables( $provider->getID() );
if( is_array( $tables ) ){
if( is_array( $tables ) ) {
// Save the table names
foreach($tables as $table){
foreach($tables as $table) {
$return['apps'][$provider->getID()]['tables'][] = $table;
}
} else {
@ -413,7 +413,7 @@ class OC_Migrate{
}
// Run the export function?
if( $success ){
if( $success ) {
// Set the provider properties
$provider->setData( self::$uid, self::$content );
$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
* @return bool
*/
static private function getExportInfo( $array=array() ){
static private function getExportInfo( $array=array() ) {
$info = array(
'ocversion' => OC_Util::getVersion(),
'exporttime' => time(),
@ -447,7 +447,7 @@ class OC_Migrate{
'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 );
}
// Merge in other data
@ -462,23 +462,23 @@ class OC_Migrate{
* @param $db optional path to migration.db, defaults to user data dir
* @return bool whether the operation was successful
*/
static private function connectDB( $path=null ){
static private function connectDB( $path=null ) {
// Has the dbpath been set?
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 );
return false;
}
// Already connected
if(!self::$MDB2){
if(!self::$MDB2) {
require_once 'MDB2.php';
$datadir = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" );
// DB type
if( class_exists( 'SQLite3' ) ){
if( class_exists( 'SQLite3' ) ) {
$dbtype = 'sqlite3';
} else if( is_callable( 'sqlite_open' ) ){
} else if( is_callable( 'sqlite_open' ) ) {
$dbtype = 'sqlite';
} else {
OC_Log::write( 'migration', 'SQLite not found', OC_Log::ERROR );
@ -502,7 +502,7 @@ class OC_Migrate{
// Try to establish connection
self::$MDB2 = MDB2::factory( $dsn, $options );
// Die if we could not connect
if( PEAR::isError( self::$MDB2 ) ){
if( PEAR::isError( self::$MDB2 ) ) {
die( self::$MDB2->getMessage() );
OC_Log::write( 'migration', 'Failed to create/connect to migration.db', 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
* @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;
}
@ -538,7 +538,7 @@ class OC_Migrate{
$content = str_replace( '*dbprefix*', '', $content );
$xml = new SimpleXMLElement($content);
foreach($xml->table as $table){
foreach($xml->table as $table) {
$tables[] = (string)$table->name;
}
@ -550,7 +550,7 @@ class OC_Migrate{
unlink( $file2 );
// 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', $definition->getMessage().': '.$definition->getUserInfo(), OC_Log::FATAL );
return false;
@ -561,7 +561,7 @@ class OC_Migrate{
$ret = self::$schema->createDatabase( $definition );
// 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', $ret->getMessage().': '.$ret->getUserInfo(), OC_Log::FATAL );
return false;
@ -575,10 +575,10 @@ class OC_Migrate{
* @param $path string path to zip destination
* @return bool
*/
static private function createZip(){
static private function createZip() {
self::$zip = new ZipArchive;
// 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);
return false;
}
@ -594,11 +594,11 @@ class OC_Migrate{
* @brief returns an array of apps that support migration
* @return array
*/
static public function getApps(){
static public function getApps() {
$allapps = OC_App::getAllApps();
foreach($allapps as $app){
foreach($allapps as $app) {
$path = self::getAppPath($app) . '/lib/migrate.php';
if( file_exists( $path ) ){
if( file_exists( $path ) ) {
$supportsmigration[] = $app;
}
}
@ -612,11 +612,11 @@ class OC_Migrate{
* @param $uid optional uid to use
* @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
if( file_exists( $db ) ){
if( file_exists( $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);
return false;
}
@ -634,25 +634,25 @@ class OC_Migrate{
'newuid' => self::$uid
);
foreach( self::$providers as $provider){
foreach( self::$providers as $provider) {
// Is the app in the export?
$id = $provider->getID();
if( isset( $info->apps->$id ) ){
if( isset( $info->apps->$id ) ) {
// 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 );
$appsstatus[$id] = 'notsupported';
} else {
// Did it succeed on export?
if( $info->apps->$id->success ){
if( $info->apps->$id->success ) {
// Give the provider the content object
if( !self::connectDB( $db ) ){
if( !self::connectDB( $db ) ) {
return false;
}
$content = new OC_Migration_Content( self::$zip, self::$MDB2 );
$provider->setData( self::$uid, $content, $info );
// 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
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
* @return bool result of user creation
*/
public static function createUser( $uid, $hash ){
public static function createUser( $uid, $hash ) {
// Check if userid exists
if(OC_User::userExists( $uid )){
if(OC_User::userExists( $uid )) {
return false;
}
// Create the user
$query = OC_DB::prepare( "INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )" );
$result = $query->execute( array( $uid, $hash));
if( !$result ){
if( !$result ) {
OC_Log::write('migration', 'Failed to create the new user "'.$uid."");
}
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)
* @return bool
*/
public function __construct( $zip, $db=null ){
public function __construct( $zip, $db=null ) {
$this->zip = $zip;
$this->db = $db;
if( !is_null( $db ) ){
if( !is_null( $db ) ) {
// Get db path
$db = $this->db->getDatabase();
$this->tmpfiles[] = $db;
@ -53,7 +53,7 @@ class OC_Migration_Content{
// @brief prepares the db
// @param $query the sql query to prepare
public function prepare( $query ){
public function prepare( $query ) {
// Optimize the query
$query = $this->processQuery( $query );
@ -78,7 +78,7 @@ class OC_Migration_Content{
* @param $query the query to process
* @return string of processed query
*/
private function processQuery( $query ){
private function processQuery( $query ) {
$query = str_replace( '`', '\'', $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.
* @return bool
*/
public function copyRows( $options ){
if( !array_key_exists( 'table', $options ) ){
public function copyRows( $options ) {
if( !array_key_exists( 'table', $options ) ) {
return false;
}
$return = array();
// 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(!is_array($options['matchval'])){
if(!is_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)
$sql = 'SELECT * FROM `*PREFIX*' . $options['table'] . '` WHERE `' . $options['matchcol'] . '` LIKE ?';
$query = OC_DB::prepare( $sql );
@ -135,12 +135,12 @@ class OC_Migration_Content{
* @param $options array of copyRows options
* @return void
*/
private function insertData( $data, $options ){
private function insertData( $data, $options ) {
$return = array();
// Foreach row of data to insert
while( $row = $data->fetchRow() ){
while( $row = $data->fetchRow() ) {
// Now save all this to the migration.db
foreach($row as $field=>$value){
foreach($row as $field=>$value) {
$fields[] = $field;
$values[] = $value;
}
@ -153,14 +153,14 @@ class OC_Migration_Content{
$sql .= $valuessql . " )";
// Make the query
$query = $this->prepare( $sql );
if( !$query ){
if( !$query ) {
OC_Log::write( 'migration', 'Invalid sql produced: '.$sql, OC_Log::FATAL );
return false;
exit();
} else {
$query->execute( $values );
// Do we need to return some values?
if( array_key_exists( 'idcol', $options ) ){
if( array_key_exists( 'idcol', $options ) ) {
// Yes we do
$return[] = $row[$options['idcol']];
} else {
@ -185,7 +185,7 @@ class OC_Migration_Content{
$dirname = basename($dir);
$this->zip->addEmptyDir($internaldir . $dirname);
$internaldir.=$dirname.='/';
if( !file_exists( $dir ) ){
if( !file_exists( $dir ) ) {
return false;
}
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
* @return bool
*/
public function addFromString( $data, $path ){
public function addFromString( $data, $path ) {
// Create a temp file
$file = tempnam( get_temp_dir(). '/', 'oc_export_tmp_' );
$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 );
return false;
}
@ -231,8 +231,8 @@ class OC_Migration_Content{
* @brief closes the zip, removes temp files
* @return bool
*/
public function finish(){
if( !$this->zip->close() ){
public function finish() {
if( !$this->zip->close() ) {
OC_Log::write( 'migration', 'Failed to write the zip file with error: '.$this->zip->getStatusString(), OC_Log::ERROR );
return false;
}
@ -243,9 +243,9 @@ class OC_Migration_Content{
/**
* @brief cleans up after the zip
*/
private function cleanup(){
private function cleanup() {
// Delete tmp files
foreach($this->tmpfiles as $i){
foreach($this->tmpfiles as $i) {
unlink( $i );
}
}

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