diff options
author | Bart Visscher <bartv@thisnet.nl> | 2012-09-07 15:42:37 +0200 |
---|---|---|
committer | Bart Visscher <bartv@thisnet.nl> | 2012-09-07 15:51:44 +0200 |
commit | 5eba5798274823fe3147a8d671ca5e15b3eb7843 (patch) | |
tree | eb9cfb3fc687b8be26dde07a08fd23ca3455991f /lib | |
parent | b483f2aab856e3324026588a9702043072fd7ad2 (diff) | |
parent | 3829460ab8cbb6de65c53583a20fd04cbe7927dd (diff) | |
download | nextcloud-server-5eba5798274823fe3147a8d671ca5e15b3eb7843.tar.gz nextcloud-server-5eba5798274823fe3147a8d671ca5e15b3eb7843.zip |
Merge branch 'master' into routing
Conflicts:
apps/files/js/fileactions.js
lib/base.php
lib/helper.php
lib/ocs.php
Diffstat (limited to 'lib')
116 files changed, 2265 insertions, 1879 deletions
diff --git a/lib/MDB2/Driver/Datatype/sqlite3.php b/lib/MDB2/Driver/Datatype/sqlite3.php index 66c68b93778..ca4c1cbceb8 100644 --- a/lib/MDB2/Driver/Datatype/sqlite3.php +++ b/lib/MDB2/Driver/Datatype/sqlite3.php @@ -20,7 +20,7 @@ * */ -require_once('MDB2/Driver/Datatype/Common.php'); +require_once 'MDB2/Driver/Datatype/Common.php'; /** * MDB2 SQLite driver @@ -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; diff --git a/lib/MDB2/Driver/Function/sqlite3.php b/lib/MDB2/Driver/Function/sqlite3.php index 790bd0e747b..235a106e183 100644 --- a/lib/MDB2/Driver/Function/sqlite3.php +++ b/lib/MDB2/Driver/Function/sqlite3.php @@ -20,7 +20,7 @@ * */ -require_once('MDB2/Driver/Function/Common.php'); +require_once 'MDB2/Driver/Function/Common.php'; /** * MDB2 SQLite driver for the function modules diff --git a/lib/MDB2/Driver/Manager/sqlite3.php b/lib/MDB2/Driver/Manager/sqlite3.php index 10255a3619a..921153c17dd 100644 --- a/lib/MDB2/Driver/Manager/sqlite3.php +++ b/lib/MDB2/Driver/Manager/sqlite3.php @@ -20,7 +20,7 @@ * */ -require_once('MDB2/Driver/Manager/Common.php'); +require_once 'MDB2/Driver/Manager/Common.php'; /** * MDB2 SQLite driver for the management modules @@ -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); diff --git a/lib/MDB2/Driver/Reverse/sqlite3.php b/lib/MDB2/Driver/Reverse/sqlite3.php index e5c758e3503..36626478ce8 100644 --- a/lib/MDB2/Driver/Reverse/sqlite3.php +++ b/lib/MDB2/Driver/Reverse/sqlite3.php @@ -20,7 +20,7 @@ * */ -require_once('MDB2/Driver/Reverse/Common.php'); +require_once 'MDB2/Driver/Reverse/Common.php'; /** * MDB2 SQlite driver for the schema reverse engineering module diff --git a/lib/MDB2/Driver/sqlite3.php b/lib/MDB2/Driver/sqlite3.php index 6bfccadad9a..9757e4faf94 100644 --- a/lib/MDB2/Driver/sqlite3.php +++ b/lib/MDB2/Driver/sqlite3.php @@ -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; diff --git a/lib/app.php b/lib/app.php index 5c0ec2f01ef..f5c328afe7c 100755 --- a/lib/app.php +++ b/lib/app.php @@ -48,20 +48,20 @@ 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 ){ - if((is_null($types) or self::isType($app,$types)) && !in_array($app, self::$loadedApps)){ + foreach( $apps as $app ) { + if((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) { self::loadApp($app); self::$loadedApps[] = $app; } } ob_end_clean(); - if (!defined('DEBUG') || !DEBUG){ + if (!defined('DEBUG') || !DEBUG) { if (is_null($types)) { OC_Util::$core_scripts = OC_Util::$scripts; OC_Util::$scripts = array(); @@ -82,10 +82,10 @@ class OC_App{ * load a single app * @param string app */ - public static function loadApp($app){ - if(is_file(self::getAppPath($app).'/appinfo/app.php')){ + public static function loadApp($app) { + if(is_file(self::getAppPath($app).'/appinfo/app.php')) { self::checkUpgrade($app); - require_once( $app.'/appinfo/app.php' ); + require_once $app.'/appinfo/app.php'; } } @@ -94,13 +94,13 @@ class OC_App{ * @param string $app * @param string/array $types */ - public static function isType($app,$types){ - if(is_string($types)){ + public static function isType($app,$types) { + if(is_string($types)) { $types=array($types); } $appTypes=self::getAppTypes($app); - foreach($types as $type){ - if(array_search($type,$appTypes)!==false){ + foreach($types as $type) { + if(array_search($type, $appTypes)!==false) { return true; } } @@ -112,14 +112,14 @@ 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'); + if(count(self::$appTypes)==0) { + self::$appTypes=OC_Appconfig::getValues(false, 'types'); } - if(isset(self::$appTypes[$app])){ - return explode(',',self::$appTypes[$app]); + if(isset(self::$appTypes[$app])) { + return explode(',', self::$appTypes[$app]); }else{ return array(); } @@ -128,29 +128,29 @@ 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'])){ - $appTypes=implode(',',$appData['types']); + if(isset($appData['types'])) { + $appTypes=implode(',', $appData['types']); }else{ $appTypes=''; } - OC_Appconfig::setValue($app,'types',$appTypes); + OC_Appconfig::setValue($app, 'types', $appTypes); } /** * 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()){ - if(array_search($row['appid'],$apps)===false){ + while($row=$result->fetchRow()) { + if(array_search($row['appid'], $apps)===false) { $apps[]=$row['appid']; } } @@ -164,8 +164,8 @@ class OC_App{ * * This function checks whether or not an app is enabled. */ - public static function isEnabled( $app ){ - if( 'files'==$app or 'yes' == OC_Appconfig::getValue( $app, 'enabled' )){ + public static function isEnabled( $app ) { + if( 'files'==$app or 'yes' == OC_Appconfig::getValue( $app, 'enabled' )) { return true; } @@ -179,24 +179,24 @@ class OC_App{ * * This function set an app as enabled in appconfig. */ - public static function enable( $app ){ - if(!OC_Installer::isInstalled($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)){ + if(!is_numeric($app)) { $app = OC_Installer::installShippedApp($app); }else{ - $download=OC_OCSClient::getApplicationDownload($app,1); + $download=OC_OCSClient::getApplicationDownload($app, 1); if(isset($download['downloadlink']) and $download['downloadlink']!='') { $app=OC_Installer::installApp(array('source'=>'http','href'=>$download['downloadlink'])); } } } - if($app!==false){ + if($app!==false) { // check if the app is compatible with this version of ownCloud $info=OC_App::getAppInfo($app); $version=OC_Util::getVersion(); - if(!isset($info['require']) or ($version[0]>$info['require'])){ - OC_Log::write('core','App "'.$info['name'].'" can\'t be installed because it is not compatible with this version of ownCloud',OC_Log::ERROR); + if(!isset($info['require']) or ($version[0]>$info['require'])) { + OC_Log::write('core', 'App "'.$info['name'].'" can\'t be installed because it is not compatible with this version of ownCloud', OC_Log::ERROR); return false; }else{ OC_Appconfig::setValue( $app, 'enabled', 'yes' ); @@ -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,9 +237,9 @@ 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'])){ + if(!isset($data['icon'])) { $data['icon']=''; } OC_App::$navigation[] = $data; @@ -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,12 +278,12 @@ 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(){ - $l=OC_L10N::get('core'); + public static function getSettingsNavigation() { + $l=OC_L10N::get('lib'); $settings = array(); // by default, settings only contain the help menu - if(OC_Config::getValue('knowledgebaseenabled', true)==true){ + if(OC_Config::getValue('knowledgebaseenabled', true)==true) { $settings = array( array( "id" => "help", "order" => 1000, "href" => OC_Helper::linkTo( "settings", "help.php" ), "name" => $l->t("Help"), "icon" => OC_Helper::imagePath( "settings", "help.svg" )) ); @@ -300,7 +300,7 @@ class OC_App{ $settings[]=array( "id" => "settings", "order" => 1000, "href" => OC_Helper::linkTo( "settings", "settings.php" ), "name" => $l->t("Settings"), "icon" => OC_Helper::imagePath( "settings", "settings.svg" )); //SubAdmins are also allowed to access user management - if(OC_SubAdmin::isSubAdmin($_SESSION["user_id"]) || OC_Group::inGroup( $_SESSION["user_id"], "admin" )){ + if(OC_SubAdmin::isSubAdmin($_SESSION["user_id"]) || OC_Group::inGroup( $_SESSION["user_id"], "admin" )) { // admin users menu $settings[] = array( "id" => "core_users", "order" => 2, "href" => OC_Helper::linkTo( "settings", "users.php" ), "name" => $l->t("Users"), "icon" => OC_Helper::imagePath( "settings", "users.svg" )); } @@ -320,10 +320,10 @@ 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 ){ + if( $naventry['id'] == self::$activeapp ) { $naventry['active'] = true; } else{ @@ -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; } @@ -349,7 +349,7 @@ class OC_App{ return $dir['path']; } - OC_Log::write('core','No application directories are marked as writable.',OC_Log::ERROR); + OC_Log::write('core', 'No application directories are marked as writable.', OC_Log::ERROR); return null; } @@ -388,10 +388,10 @@ 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){ + if($version) { return trim($version); }else{ $appData=self::getAppInfo($appid); @@ -405,38 +405,41 @@ class OC_App{ * @param boolean path (optional) * @returns array */ - public static function getAppInfo($appid,$path=false){ - if($path){ + public static function getAppInfo($appid,$path=false) { + if($path) { $file=$appid; }else{ - if(isset(self::$appInfo[$appid])){ + if(isset(self::$appInfo[$appid])) { return self::$appInfo[$appid]; } $file= self::getAppPath($appid).'/appinfo/info.xml'; } $data=array(); $content=@file_get_contents($file); - if(!$content){ + if(!$content) { return; } $xml = new SimpleXMLElement($content); $data['info']=array(); $data['remote']=array(); $data['public']=array(); - foreach($xml->children() as $child){ - if($child->getName()=='remote'){ - foreach($child->children() as $remote){ + foreach($xml->children() as $child) { + if($child->getName()=='remote') { + foreach($child->children() as $remote) { $data['remote'][$remote->getName()]=(string)$remote; } - }elseif($child->getName()=='public'){ - foreach($child->children() as $public){ + }elseif($child->getName()=='public') { + foreach($child->children() as $public) { $data['public'][$public->getName()]=(string)$public; } - }elseif($child->getName()=='types'){ + }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') { + $xml=(string)$child->asXML(); + $data[$child->getName()]=substr($xml, 13, -14);//script <description> tags }else{ $data[$child->getName()]=(string)$child; } @@ -456,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; } @@ -465,12 +468,12 @@ class OC_App{ * get the id of loaded app * @return string */ - public static function getCurrentApp(){ - $script=substr($_SERVER["SCRIPT_NAME"],strlen(OC::$WEBROOT)+1); - $topFolder=substr($script,0,strpos($script,'/')); - if($topFolder=='apps'){ + public static function getCurrentApp() { + $script=substr($_SERVER["SCRIPT_NAME"], strlen(OC::$WEBROOT)+1); + $topFolder=substr($script, 0, strpos($script, '/')); + if($topFolder=='apps') { $length=strlen($topFolder); - return substr($script,$length+1,strpos($script,'/',$length+1)-$length-1); + return substr($script, $length+1, strpos($script, '/', $length+1)-$length-1); }else{ return $topFolder; } @@ -480,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; @@ -493,7 +496,7 @@ class OC_App{ $source=self::$personalForms; break; } - foreach($source as $form){ + foreach($source as $form) { $forms[]=include $form; } return $forms; @@ -502,33 +505,33 @@ 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)){ - if($file[0]!='.' and is_file($apps_dir['path'].'/'.$file.'/appinfo/app.php')){ + while($file=readdir($dh)) { + if($file[0]!='.' and is_file($apps_dir['path'].'/'.$file.'/appinfo/app.php')) { $apps[]=$file; } } @@ -549,7 +552,7 @@ class OC_App{ if ($currentVersion) { $installedVersion = $versions[$app]; if (version_compare($currentVersion, $installedVersion, '>')) { - OC_Log::write($app, 'starting app upgrade from '.$installedVersion.' to '.$currentVersion,OC_Log::DEBUG); + OC_Log::write($app, 'starting app upgrade from '.$installedVersion.' to '.$currentVersion, OC_Log::DEBUG); OC_App::updateApp($app); OC_Appconfig::setValue($app, 'installed_version', OC_App::getAppVersion($app)); } @@ -562,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(); } @@ -570,8 +573,8 @@ class OC_App{ foreach($apps as $app) { // check if the app is compatible with this version of ownCloud $info = OC_App::getAppInfo($app); - if(!isset($info['require']) or ($version[0]>$info['require'])){ - OC_Log::write('core','App "'.$info['name'].'" ('.$app.') can\'t be used because it is not compatible with this version of ownCloud',OC_Log::ERROR); + if(!isset($info['require']) or ($version[0]>$info['require'])) { + OC_Log::write('core', 'App "'.$info['name'].'" ('.$app.') can\'t be used because it is not compatible with this version of ownCloud', OC_Log::ERROR); OC_App::disable( $app ); } } @@ -580,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 @@ -588,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; @@ -598,24 +601,24 @@ class OC_App{ * update the database for the app and call the update script * @param string appid */ - public static function updateApp($appid){ - if(file_exists(self::getAppPath($appid).'/appinfo/database.xml')){ + public static function updateApp($appid) { + if(file_exists(self::getAppPath($appid).'/appinfo/database.xml')) { OC_DB::updateDbFromStructure(self::getAppPath($appid).'/appinfo/database.xml'); } - if(!self::isEnabled($appid)){ + if(!self::isEnabled($appid)) { return; } - if(file_exists(self::getAppPath($appid).'/appinfo/update.php')){ + if(file_exists(self::getAppPath($appid).'/appinfo/update.php')) { self::loadApp($appid); include self::getAppPath($appid).'/appinfo/update.php'; } //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); } @@ -626,20 +629,20 @@ class OC_App{ * @param string appid * @return OC_FilesystemView */ - public static function getStorage($appid){ - if(OC_App::isEnabled($appid)){//sanity check - if(OC_User::isLoggedIn()){ + public static function getStorage($appid) { + if(OC_App::isEnabled($appid)) {//sanity check + if(OC_User::isLoggedIn()) { $view = new OC_FilesystemView('/'.OC_User::getUser()); if(!$view->file_exists($appid)) { $view->mkdir($appid); } return new OC_FilesystemView('/'.OC_User::getUser().'/'.$appid); }else{ - OC_Log::write('core','Can\'t get app storage, app, user not logged in',OC_Log::ERROR); + OC_Log::write('core', 'Can\'t get app storage, app, user not logged in', OC_Log::ERROR); return false; } }else{ - OC_Log::write('core','Can\'t get app storage, app '.$appid.' not enabled',OC_Log::ERROR); + OC_Log::write('core', 'Can\'t get app storage, app '.$appid.' not enabled', OC_Log::ERROR); false; } } diff --git a/lib/appconfig.php b/lib/appconfig.php index 0e608b540bd..7f58b878504 100644 --- a/lib/appconfig.php +++ b/lib/appconfig.php @@ -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; diff --git a/lib/archive.php b/lib/archive.php index 5ac4edbfd1e..b4459c2b6ce 100644 --- a/lib/archive.php +++ b/lib/archive.php @@ -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); diff --git a/lib/archive/tar.php b/lib/archive/tar.php index 095362d0cd6..ebd581fc162 100644 --- a/lib/archive/tar.php +++ b/lib/archive/tar.php @@ -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; } diff --git a/lib/archive/zip.php b/lib/archive/zip.php index 396b1f6c054..45992ee3d89 100644 --- a/lib/archive/zip.php +++ b/lib/archive/zip.php @@ -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; diff --git a/lib/backgroundjob/queuedtask.php b/lib/backgroundjob/queuedtask.php index a7ec3efbf33..8264e1a0ae6 100644 --- a/lib/backgroundjob/queuedtask.php +++ b/lib/backgroundjob/queuedtask.php @@ -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)); diff --git a/lib/backgroundjob/regulartask.php b/lib/backgroundjob/regulartask.php index 53bd4eb5e9b..9976872ee13 100644 --- a/lib/backgroundjob/regulartask.php +++ b/lib/backgroundjob/regulartask.php @@ -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; } } diff --git a/lib/backgroundjob/worker.php b/lib/backgroundjob/worker.php index 8684e0df117..e966ac9647c 100644 --- a/lib/backgroundjob/worker.php +++ b/lib/backgroundjob/worker.php @@ -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. diff --git a/lib/base.php b/lib/base.php index 237b6ab7081..fc682fecfca 100644 --- a/lib/base.php +++ b/lib/base.php @@ -51,7 +51,8 @@ class OC{ */ public static $THIRDPARTYWEBROOT = ''; /** - * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) 'path' and web path in 'url' + * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) 'path' and + * web path in 'url' */ public static $APPSROOTS = array(); /* @@ -73,53 +74,60 @@ class OC{ /** * SPL autoload */ - public static function autoload($className){ - if(array_key_exists($className,OC::$CLASSPATH)){ + 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 */ - $path = preg_replace('/apps\//','', OC::$CLASSPATH[$className]); + $path = preg_replace('/apps\//', '', OC::$CLASSPATH[$className]); require_once $path; } - elseif(strpos($className,'OC_')===0){ - require_once strtolower(str_replace('_','/',substr($className,3)) . '.php'); + elseif(strpos($className, 'OC_')===0) { + $path = strtolower(str_replace('_', '/', substr($className, 3)) . '.php'); } - elseif(strpos($className,'OCP\\')===0){ - require_once 'public/'.strtolower(str_replace('\\','/',substr($className,3)) . '.php'); + elseif(strpos($className, 'OCP\\')===0) { + $path = 'public/'.strtolower(str_replace('\\', '/', substr($className, 3)) . '.php'); } - elseif(strpos($className,'OCA\\')===0){ - require_once 'apps/'.strtolower(str_replace('\\','/',substr($className,3)) . '.php'); + elseif(strpos($className, 'OCA\\')===0) { + $path = 'apps/'.strtolower(str_replace('\\', '/', substr($className, 3)) . '.php'); } - elseif(strpos($className,'Sabre_')===0) { - require_once str_replace('_','/',$className) . '.php'; + elseif(strpos($className, 'Sabre_')===0) { + $path = str_replace('_', '/', $className) . '.php'; } - elseif(strpos($className,'Symfony\\')===0){ - require_once str_replace('\\','/',$className) . '.php'; + elseif(strpos($className, 'Symfony\\')===0) { + $path = str_replace('\\', '/', $className) . '.php'; } - elseif(strpos($className,'Test_')===0){ - require_once 'tests/lib/'.strtolower(str_replace('_','/',substr($className,5)) . '.php'); + elseif(strpos($className, 'Test_')===0) { + $path = 'tests/lib/'.strtolower(str_replace('_', '/', substr($className, 5)) . '.php'); + }else{ + return false; + } + + if($fullPath = stream_resolve_include_path($path)) { + require_once $path; } + 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))); + OC::$SERVERROOT=str_replace("\\", '/', substr(__FILE__, 0, -13)); + OC::$SUBURI= str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT))); $scriptName=$_SERVER["SCRIPT_NAME"]; - if(substr($scriptName,-1)=='/'){ + if(substr($scriptName, -1)=='/') { $scriptName.='index.php'; //make sure suburi follows the same rules as scriptName - if(substr(OC::$SUBURI,-9)!='index.php'){ - if(substr(OC::$SUBURI,-1)!='/'){ + if(substr(OC::$SUBURI, -9)!='index.php') { + if(substr(OC::$SUBURI, -1)!='/') { OC::$SUBURI=OC::$SUBURI.'/'; } OC::$SUBURI=OC::$SUBURI.'index.php'; } } - OC::$WEBROOT=substr($scriptName,0,strlen($scriptName)-strlen(OC::$SUBURI)); + OC::$WEBROOT=substr($scriptName, 0, strlen($scriptName)-strlen(OC::$SUBURI)); - if(OC::$WEBROOT!='' and OC::$WEBROOT[0]!=='/'){ + if(OC::$WEBROOT!='' and OC::$WEBROOT[0]!=='/') { OC::$WEBROOT='/'.OC::$WEBROOT; } @@ -130,13 +138,13 @@ class OC{ ); // search the 3rdparty folder - if(OC_Config::getValue('3rdpartyroot', '')<>'' and OC_Config::getValue('3rdpartyurl', '')<>''){ + if(OC_Config::getValue('3rdpartyroot', '')<>'' and OC_Config::getValue('3rdpartyurl', '')<>'') { OC::$THIRDPARTYROOT=OC_Config::getValue('3rdpartyroot', ''); OC::$THIRDPARTYWEBROOT=OC_Config::getValue('3rdpartyurl', ''); - }elseif(file_exists(OC::$SERVERROOT.'/3rdparty')){ + }elseif(file_exists(OC::$SERVERROOT.'/3rdparty')) { OC::$THIRDPARTYROOT=OC::$SERVERROOT; OC::$THIRDPARTYWEBROOT=OC::$WEBROOT; - }elseif(file_exists(OC::$SERVERROOT.'/../3rdparty')){ + }elseif(file_exists(OC::$SERVERROOT.'/../3rdparty')) { OC::$THIRDPARTYWEBROOT=rtrim(dirname(OC::$WEBROOT), '/'); OC::$THIRDPARTYROOT=rtrim(dirname(OC::$SERVERROOT), '/'); }else{ @@ -145,21 +153,21 @@ class OC{ } // search the apps folder $config_paths = OC_Config::getValue('apps_paths', array()); - if(! empty($config_paths)){ + if(! empty($config_paths)) { foreach($config_paths as $paths) { if( isset($paths['url']) && isset($paths['path'])) { - $paths['url'] = rtrim($paths['url'],'/'); - $paths['path'] = rtrim($paths['path'],'/'); + $paths['url'] = rtrim($paths['url'], '/'); + $paths['path'] = rtrim($paths['path'], '/'); OC::$APPSROOTS[] = $paths; } } - }elseif(file_exists(OC::$SERVERROOT.'/apps')){ + }elseif(file_exists(OC::$SERVERROOT.'/apps')) { OC::$APPSROOTS[] = array('path'=> OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true); - }elseif(file_exists(OC::$SERVERROOT.'/../apps')){ + }elseif(file_exists(OC::$SERVERROOT.'/../apps')) { OC::$APPSROOTS[] = array('path'=> rtrim(dirname(OC::$SERVERROOT), '/').'/apps', 'url' => '/apps', 'writable' => true); } - if(empty(OC::$APPSROOTS)){ + if(empty(OC::$APPSROOTS)) { echo("apps directory not found! Please put the ownCloud apps folder in the ownCloud folder or the folder above. You can also configure the location in the config.php file."); exit; } @@ -181,7 +189,7 @@ class OC{ public static function checkInstalled() { // Redirect to installer if not installed if (!OC_Config::getValue('installed', false) && OC::$SUBURI != '/index.php') { - if(!OC::$CLI){ + if(!OC::$CLI) { $url = 'http://'.$_SERVER['SERVER_NAME'].OC::$WEBROOT.'/index.php'; header("Location: $url"); } @@ -191,7 +199,7 @@ class OC{ public static function checkSSL() { // redirect to https site if configured - if( OC_Config::getValue( "forcessl", false )){ + if( OC_Config::getValue( "forcessl", false )) { ini_set("session.cookie_secure", "on"); if(OC_Request::serverProtocol()<>'https' and !OC::$CLI) { $url = "https://". OC_Request::serverHost() . $_SERVER['REQUEST_URI']; @@ -202,24 +210,25 @@ class OC{ } public static function checkUpgrade() { - if(OC_Config::getValue('installed', false)){ - $installedVersion=OC_Config::getValue('version','0.0.0'); - $currentVersion=implode('.',OC_Util::getVersion()); + if(OC_Config::getValue('installed', false)) { + $installedVersion=OC_Config::getValue('version', '0.0.0'); + $currentVersion=implode('.', OC_Util::getVersion()); if (version_compare($currentVersion, $installedVersion, '>')) { - OC_Log::write('core','starting upgrade from '.$installedVersion.' to '.$currentVersion,OC_Log::DEBUG); + OC_Log::write('core', 'starting upgrade from '.$installedVersion.' to '.$currentVersion, OC_Log::DEBUG); $result=OC_DB::updateDbFromStructure(OC::$SERVERROOT.'/db_structure.xml'); - if(!$result){ + if(!$result) { echo 'Error while upgrading the database'; die(); } if(file_exists(OC::$SERVERROOT."/config/config.php") and !is_writable(OC::$SERVERROOT."/config/config.php")) { $tmpl = new OC_Template( '', 'error', 'guest' ); - $tmpl->assign('errors',array(1=>array('error'=>"Can't write into config directory 'config'",'hint'=>"You can usually fix this by giving the webserver user write access to the config directory in owncloud"))); + $tmpl->assign('errors', array(1=>array('error'=>"Can't write into config directory 'config'",'hint'=>"You can usually fix this by giving the webserver user write access to the config directory in owncloud"))); $tmpl->printPage(); exit; } + OC_Minimizer::clearCache(); - OC_Config::setValue('version',implode('.',OC_Util::getVersion())); + OC_Config::setValue('version', implode('.', OC_Util::getVersion())); OC_App::checkAppsRequirements(); // load all apps to also upgrade enabled apps OC_App::loadApps(); @@ -239,10 +248,10 @@ class OC{ OC_Util::addScript( "eventsource" ); OC_Util::addScript( "config" ); //OC_Util::addScript( "multiselect" ); - OC_Util::addScript('search','result'); + OC_Util::addScript('search', 'result'); - if( OC_Config::getValue( 'installed', false )){ - if( OC_Appconfig::getValue( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax' ){ + if( OC_Config::getValue( 'installed', false )) { + if( OC_Appconfig::getValue( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax' ) { OC_Util::addScript( 'backgroundjobs' ); } } @@ -254,7 +263,7 @@ class OC{ } public static function initSession() { - ini_set('session.cookie_httponly','1;'); + ini_set('session.cookie_httponly', '1;'); session_start(); } @@ -267,7 +276,7 @@ class OC{ return OC::$router; } - public static function init(){ + public static function init() { // register autoloader spl_autoload_register(array('OC','autoload')); setlocale(LC_ALL, 'en_US.UTF-8'); @@ -275,13 +284,13 @@ class OC{ // set some stuff //ob_start(); error_reporting(E_ALL | E_STRICT); - if (defined('DEBUG') && DEBUG){ + if (defined('DEBUG') && DEBUG) { ini_set('display_errors', 1); } self::$CLI=(php_sapi_name() == 'cli'); date_default_timezone_set('UTC'); - ini_set('arg_separator.output','&'); + ini_set('arg_separator.output', '&'); // try to switch magic quotes off. if(function_exists('set_magic_quotes_runtime')) { @@ -294,29 +303,27 @@ class OC{ //try to set the maximum execution time to 60min @set_time_limit(3600); - @ini_set('max_execution_time',3600); - @ini_set('max_input_time',3600); + @ini_set('max_execution_time', 3600); + @ini_set('max_input_time', 3600); //try to set the maximum filesize to 10G - @ini_set('upload_max_filesize','10G'); - @ini_set('post_max_size','10G'); - @ini_set('file_uploads','50'); + @ini_set('upload_max_filesize', '10G'); + @ini_set('post_max_size', '10G'); + @ini_set('file_uploads', '50'); //try to set the session lifetime to 60min - @ini_set('gc_maxlifetime','3600'); + @ini_set('gc_maxlifetime', '3600'); //set http auth headers for apache+php-cgi work around - if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) - { + if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) { list($name, $password) = explode(':', base64_decode($matches[1])); $_SERVER['PHP_AUTH_USER'] = strip_tags($name); $_SERVER['PHP_AUTH_PW'] = strip_tags($password); } //set http auth headers for apache+php-cgi work around if variable gets renamed by apache - if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) - { + if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) { list($name, $password) = explode(':', base64_decode($matches[1])); $_SERVER['PHP_AUTH_USER'] = strip_tags($name); $_SERVER['PHP_AUTH_PW'] = strip_tags($password); @@ -324,8 +331,15 @@ class OC{ self::initPaths(); + // set debug mode if an xdebug session is active + if (!defined('DEBUG') || !DEBUG) { + if(isset($_COOKIE['XDEBUG_SESSION'])) { + define('DEBUG', true); + } + } + // register the stream wrappers - require_once('streamwrappers.php'); + require_once 'streamwrappers.php'; stream_wrapper_register("fakedir", "OC_FakeDirStream"); stream_wrapper_register('static', 'OC_StaticStreamWrapper'); stream_wrapper_register('close', 'OC_CloseStreamWrapper'); @@ -343,7 +357,7 @@ class OC{ } // User and Groups - if( !OC_Config::getValue( "installed", false )){ + if( !OC_Config::getValue( "installed", false )) { $_SESSION['user_id'] = ''; } @@ -354,20 +368,23 @@ class OC{ // This includes plugins for users and filesystems as well global $RUNTIME_NOAPPS; global $RUNTIME_APPTYPES; - if(!$RUNTIME_NOAPPS ){ - if($RUNTIME_APPTYPES){ + if(!$RUNTIME_NOAPPS ) { + if($RUNTIME_APPTYPES) { OC_App::loadApps($RUNTIME_APPTYPES); }else{ OC_App::loadApps(); } } + //setup extra user backends + OC_User::setupBackends(); + // register cache cleanup jobs OC_BackgroundJob_RegularTask::register('OC_Cache_FileGlobal', 'gc'); OC_Hook::connect('OC_User', 'post_login', 'OC_Cache_File', 'loginListener'); // Check for blacklisted files - OC_Hook::connect('OC_Filesystem','write','OC_Filesystem','isBlacklisted'); + OC_Hook::connect('OC_Filesystem', 'write', 'OC_Filesystem', 'isBlacklisted'); OC_Hook::connect('OC_Filesystem', 'rename', 'OC_Filesystem', 'isBlacklisted'); //make sure temporary files are cleaned up @@ -375,7 +392,7 @@ class OC{ //parse the given parameters self::$REQUESTEDAPP = (isset($_GET['app']) && trim($_GET['app']) != '' && !is_null($_GET['app'])?str_replace(array('\0', '/', '\\', '..'), '', strip_tags($_GET['app'])):OC_Config::getValue('defaultapp', 'files')); - if(substr_count(self::$REQUESTEDAPP, '?') != 0){ + if(substr_count(self::$REQUESTEDAPP, '?') != 0) { $app = substr(self::$REQUESTEDAPP, 0, strpos(self::$REQUESTEDAPP, '?')); $param = substr($_GET['app'], strpos($_GET['app'], '?') + 1); parse_str($param, $get); @@ -384,7 +401,7 @@ class OC{ $_GET['app'] = $app; } self::$REQUESTEDFILE = (isset($_GET['getfile'])?$_GET['getfile']:null); - if(substr_count(self::$REQUESTEDFILE, '?') != 0){ + if(substr_count(self::$REQUESTEDFILE, '?') != 0) { $file = substr(self::$REQUESTEDFILE, 0, strpos(self::$REQUESTEDFILE, '?')); $param = substr(self::$REQUESTEDFILE, strpos(self::$REQUESTEDFILE, '?') + 1); parse_str($param, $get); @@ -392,10 +409,10 @@ class OC{ self::$REQUESTEDFILE = $file; $_GET['getfile'] = $file; } - if(!is_null(self::$REQUESTEDFILE)){ + if(!is_null(self::$REQUESTEDFILE)) { $subdir = OC_App::getAppPath(OC::$REQUESTEDAPP) . '/' . self::$REQUESTEDFILE; $parent = OC_App::getAppPath(OC::$REQUESTEDAPP); - if(!OC_Helper::issubdirectory($subdir, $parent)){ + if(!OC_Helper::issubdirectory($subdir, $parent)) { self::$REQUESTEDFILE = null; header('HTTP/1.0 404 Not Found'); exit; @@ -410,19 +427,19 @@ class OC{ if (!OC_Config::getValue('installed', false)) { // Check for autosetup: $autosetup_file = OC::$SERVERROOT."/config/autoconfig.php"; - if( file_exists( $autosetup_file )){ - OC_Log::write('core','Autoconfig file found, setting up owncloud...',OC_Log::INFO); - include( $autosetup_file ); + if( file_exists( $autosetup_file )) { + OC_Log::write('core', 'Autoconfig file found, setting up owncloud...', OC_Log::INFO); + include $autosetup_file; $_POST['install'] = 'true'; $_POST = array_merge ($_POST, $AUTOCONFIG); unlink($autosetup_file); } OC_Util::addScript('setup'); - require_once('setup.php'); + require_once 'setup.php'; exit(); } // Handle WebDAV - if($_SERVER['REQUEST_METHOD']=='PROPFIND'){ + if($_SERVER['REQUEST_METHOD']=='PROPFIND') { header('location: '.OC_Helper::linkToRemote('webdav')); return; } @@ -439,12 +456,14 @@ class OC{ $file = OC::$REQUESTEDFILE; $param = array('app' => $app, 'file' => $file); // Handle app css files - if(substr($file,-3) == 'css') { + if(substr($file, -3) == 'css') { self::loadCSSFile($param); return; } // Someone is logged in : if(OC_User::isLoggedIn()) { + OC_App::loadApps(); + OC_User::setupBackends(); if(isset($_GET["logout"]) and ($_GET["logout"])) { OC_App::loadApps(); OC_User::logout(); @@ -455,7 +474,7 @@ class OC{ } $file_ext = substr($param['file'], -3); if ($file_ext != 'php' - || !self::loadAppScriptFile($param)) { + || !self::loadAppScriptFile($param)) { header('HTTP/1.0 404 Not Found'); } } @@ -473,7 +492,7 @@ class OC{ $file = $app_path . '/' . $file; unset($app, $app_path); if (file_exists($file)) { - require_once($file); + require_once $file; return true; } return false; @@ -512,18 +531,20 @@ class OC{ protected static function tryRememberLogin() { if(!isset($_COOKIE["oc_remember_login"]) - || !isset($_COOKIE["oc_token"]) - || !isset($_COOKIE["oc_username"]) - || !$_COOKIE["oc_remember_login"]) { + || !isset($_COOKIE["oc_token"]) + || !isset($_COOKIE["oc_username"]) + || !$_COOKIE["oc_remember_login"]) + { return false; } OC_App::loadApps(array('authentication')); if(defined("DEBUG") && DEBUG) { - OC_Log::write('core','Trying to login from cookie',OC_Log::DEBUG); + OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG); } // confirm credentials in cookie if(isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username']) && - OC_Preferences::getValue($_COOKIE['oc_username'], "login", "token") === $_COOKIE['oc_token']) { + OC_Preferences::getValue($_COOKIE['oc_username'], "login", "token") === $_COOKIE['oc_token']) + { OC_User::setUserId($_COOKIE['oc_username']); OC_Util::redirectToDefaultPage(); } @@ -541,11 +562,16 @@ class OC{ || ($_SESSION['sectoken']!=$_POST['sectoken']) ) { return false; } + OC_App::loadApps(); + + //setup extra user backends + OC_User::setupBackends(); + if(OC_User::login($_POST["user"], $_POST["password"])) { - if(!empty($_POST["remember_login"])){ + if(!empty($_POST["remember_login"])) { if(defined("DEBUG") && DEBUG) { - OC_Log::write('core','Setting remember login to cookie', OC_Log::DEBUG); + OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG); } $token = md5($_POST["user"].time().$_POST['password']); OC_Preferences::setValue($_POST['user'], 'login', 'token', $token); @@ -561,11 +587,11 @@ 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')); - if (OC_User::login($_SERVER["PHP_AUTH_USER"],$_SERVER["PHP_AUTH_PW"])) { + if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) { //OC_Log::write('core',"Logged in with HTTP Authentication",OC_Log::DEBUG); OC_User::unsetMagicInCookie(); $_REQUEST['redirect_url'] = (isset($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI']:''); @@ -577,7 +603,7 @@ class OC{ } // define runtime variables - unless this already has been done -if( !isset( $RUNTIME_NOAPPS )){ +if( !isset( $RUNTIME_NOAPPS )) { $RUNTIME_NOAPPS = false; } @@ -587,7 +613,7 @@ if(!function_exists('get_temp_dir')) { if( $temp=getenv('TMP') ) return $temp; if( $temp=getenv('TEMP') ) return $temp; if( $temp=getenv('TMPDIR') ) return $temp; - $temp=tempnam(__FILE__,''); + $temp=tempnam(__FILE__, ''); if (file_exists($temp)) { unlink($temp); return dirname($temp); diff --git a/lib/cache.php b/lib/cache.php index fed990b5b34..62003793d5f 100644 --- a/lib/cache.php +++ b/lib/cache.php @@ -44,8 +44,8 @@ class OC_Cache { self::$global_cache = new OC_Cache_Broker(self::$global_cache_fast, self::$global_cache); } } - if($fast){ - if(self::$global_cache_fast){ + if($fast) { + if(self::$global_cache_fast) { return self::$global_cache_fast; }else{ return false; @@ -74,8 +74,8 @@ class OC_Cache { } } - if($fast){ - if(self::$user_cache_fast){ + if($fast) { + if(self::$user_cache_fast) { return self::$user_cache_fast; }else{ return false; @@ -138,7 +138,7 @@ class OC_Cache { * @return true */ static public function isFast() { - if(is_null(self::$isFast)){ + if(is_null(self::$isFast)) { self::$isFast=function_exists('xcache_set') || function_exists('apc_store'); } return self::$isFast; diff --git a/lib/cache/apc.php b/lib/cache/apc.php index c192fe2f196..6dda0a0ff8c 100644 --- a/lib/cache/apc.php +++ b/lib/cache/apc.php @@ -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) { diff --git a/lib/cache/broker.php b/lib/cache/broker.php index c2aceabaf53..a161dbfa3bb 100644 --- a/lib/cache/broker.php +++ b/lib/cache/broker.php @@ -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); } diff --git a/lib/cache/file.php b/lib/cache/file.php index b9073dee09a..a4f83f76c94 100644 --- a/lib/cache/file.php +++ b/lib/cache/file.php @@ -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); } } diff --git a/lib/cache/fileglobal.php b/lib/cache/fileglobal.php index d4336553c38..6d01964e185 100644 --- a/lib/cache/fileglobal.php +++ b/lib/cache/fileglobal.php @@ -57,19 +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(){ + public function clear($prefix='') { $cache_dir = self::getCacheDir(); - if($cache_dir and is_dir($cache_dir)){ + $prefix = $this->fixKey($prefix); + if($cache_dir and is_dir($cache_dir)) { $dh=opendir($cache_dir); - while($file=readdir($dh)){ - if($file!='.' and $file!='..'){ + while($file=readdir($dh)) { + if($file!='.' and $file!='..' and ($prefix==='' || strpos($file, $prefix) === 0)) { unlink($cache_dir.$file); } } diff --git a/lib/cache/xcache.php b/lib/cache/xcache.php index 951f9b47545..0739e4a2fa2 100644 --- a/lib/cache/xcache.php +++ b/lib/cache/xcache.php @@ -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; } diff --git a/lib/config.php b/lib/config.php index 266d559126c..032d401264c 100644 --- a/lib/config.php +++ b/lib/config.php @@ -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,10 +67,10 @@ 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 )){ + if( array_key_exists( $key, self::$cache )) { return self::$cache[$key]; } @@ -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,10 +105,10 @@ 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 )){ + if( array_key_exists( $key, self::$cache )) { // Delete key from cache unset( self::$cache[$key] ); @@ -125,18 +125,18 @@ class OC_Config{ * * Reads the config file and saves it to the cache */ - private static function readData(){ - if( self::$init ){ + private static function readData() { + if( self::$init ) { return true; } - if( !file_exists( OC::$SERVERROOT."/config/config.php" )){ + if( !file_exists( OC::$SERVERROOT."/config/config.php" )) { return false; } // Include the file, save the data from $CONFIG - include( OC::$SERVERROOT."/config/config.php" ); - if( isset( $CONFIG ) && is_array( $CONFIG )){ + include OC::$SERVERROOT."/config/config.php"; + if( isset( $CONFIG ) && is_array( $CONFIG )) { self::$cache = $CONFIG; } @@ -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); @@ -164,7 +164,9 @@ class OC_Config{ $result=@file_put_contents( $filename, $content ); if(!$result) { $tmpl = new OC_Template( '', 'error', 'guest' ); - $tmpl->assign('errors',array(1=>array('error'=>"Can't write into config directory 'config'",'hint'=>"You can usually fix this by giving the webserver user write access to the config directory in owncloud"))); + $tmpl->assign('errors', array(1=>array( + 'error'=>"Can't write into config directory 'config'", + 'hint'=>"You can usually fix this by giving the webserver user write access to the config directory in owncloud"))); $tmpl->printPage(); exit; } diff --git a/lib/connector/sabre/auth.php b/lib/connector/sabre/auth.php index 8197571e949..34fc5fee50c 100644 --- a/lib/connector/sabre/auth.php +++ b/lib/connector/sabre/auth.php @@ -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; } diff --git a/lib/connector/sabre/client.php b/lib/connector/sabre/client.php index 7e8f21264f9..8df5fb9a9ad 100644 --- a/lib/connector/sabre/client.php +++ b/lib/connector/sabre/client.php @@ -1,173 +1,173 @@ -<?php
-
-/**
- * ownCloud
- *
- * @author Bjoern Schiessle
- * @copyright 2012 Bjoern Schiessle <schiessle@owncloud.com>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
- *
- * You should have received a copy of the GNU Affero General Public
- * License along with this library. If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-class OC_Connector_Sabre_Client extends Sabre_DAV_Client {
-
- protected $trustedCertificates;
-
- /**
- * Add trusted root certificates to the webdav client.
- *
- * The parameter certificates should be a absulute path to a file which contains
- * all trusted certificates
- *
- * @param string $certificates
- */
- public function addTrustedCertificates($certificates) {
- $this->trustedCertificates = $certificates;
- }
-
- /**
- * Copied from SabreDAV with some modification to use user defined curlSettings
- * Performs an actual HTTP request, and returns the result.
- *
- * If the specified url is relative, it will be expanded based on the base
- * url.
- *
- * The returned array contains 3 keys:
- * * body - the response body
- * * httpCode - a HTTP code (200, 404, etc)
- * * headers - a list of response http headers. The header names have
- * been lowercased.
- *
- * @param string $method
- * @param string $url
- * @param string $body
- * @param array $headers
- * @return array
- */
- public function request($method, $url = '', $body = null, $headers = array()) {
-
- $url = $this->getAbsoluteUrl($url);
-
- $curlSettings = array(
- CURLOPT_RETURNTRANSFER => true,
- // Return headers as part of the response
- CURLOPT_HEADER => true,
- CURLOPT_POSTFIELDS => $body,
- // Automatically follow redirects
- CURLOPT_FOLLOWLOCATION => true,
- CURLOPT_MAXREDIRS => 5,
- );
-
- if($this->trustedCertificates) {
- $curlSettings[CURLOPT_CAINFO] = $this->trustedCertificates;
- }
-
- switch ($method) {
- case 'HEAD' :
-
- // do not read body with HEAD requests (this is neccessary because cURL does not ignore the body with HEAD
- // requests when the Content-Length header is given - which in turn is perfectly valid according to HTTP
- // specs...) cURL does unfortunately return an error in this case ("transfer closed transfer closed with
- // ... bytes remaining to read") this can be circumvented by explicitly telling cURL to ignore the
- // response body
- $curlSettings[CURLOPT_NOBODY] = true;
- $curlSettings[CURLOPT_CUSTOMREQUEST] = 'HEAD';
- break;
-
- default:
- $curlSettings[CURLOPT_CUSTOMREQUEST] = $method;
- break;
-
- }
-
- // Adding HTTP headers
- $nHeaders = array();
- foreach($headers as $key=>$value) {
-
- $nHeaders[] = $key . ': ' . $value;
-
- }
- $curlSettings[CURLOPT_HTTPHEADER] = $nHeaders;
-
- if ($this->proxy) {
- $curlSettings[CURLOPT_PROXY] = $this->proxy;
- }
-
- if ($this->userName && $this->authType) {
- $curlType = 0;
- if ($this->authType & self::AUTH_BASIC) {
- $curlType |= CURLAUTH_BASIC;
- }
- if ($this->authType & self::AUTH_DIGEST) {
- $curlType |= CURLAUTH_DIGEST;
- }
- $curlSettings[CURLOPT_HTTPAUTH] = $curlType;
- $curlSettings[CURLOPT_USERPWD] = $this->userName . ':' . $this->password;
- }
-
- list(
- $response,
- $curlInfo,
- $curlErrNo,
- $curlError
- ) = $this->curlRequest($url, $curlSettings);
-
- $headerBlob = substr($response, 0, $curlInfo['header_size']);
- $response = substr($response, $curlInfo['header_size']);
-
- // In the case of 100 Continue, or redirects we'll have multiple lists
- // of headers for each separate HTTP response. We can easily split this
- // because they are separated by \r\n\r\n
- $headerBlob = explode("\r\n\r\n", trim($headerBlob, "\r\n"));
-
- // We only care about the last set of headers
- $headerBlob = $headerBlob[count($headerBlob)-1];
-
- // Splitting headers
- $headerBlob = explode("\r\n", $headerBlob);
-
- $headers = array();
- foreach($headerBlob as $header) {
- $parts = explode(':', $header, 2);
- if (count($parts)==2) {
- $headers[strtolower(trim($parts[0]))] = trim($parts[1]);
- }
- }
-
- $response = array(
- 'body' => $response,
- 'statusCode' => $curlInfo['http_code'],
- 'headers' => $headers
- );
-
- if ($curlErrNo) {
- throw new Sabre_DAV_Exception('[CURL] Error while making request: ' . $curlError . ' (error code: ' . $curlErrNo . ')');
- }
-
- if ($response['statusCode']>=400) {
- switch ($response['statusCode']) {
- case 404:
- throw new Sabre_DAV_Exception_NotFound('Resource ' . $url . ' not found.');
- break;
-
- default:
- throw new Sabre_DAV_Exception('HTTP error response. (errorcode ' . $response['statusCode'] . ')');
- }
- }
-
- return $response;
-
- }
+<?php + +/** + * ownCloud + * + * @author Bjoern Schiessle + * @copyright 2012 Bjoern Schiessle <schiessle@owncloud.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see <http://www.gnu.org/licenses/>. + * + */ + +class OC_Connector_Sabre_Client extends Sabre_DAV_Client { + + protected $trustedCertificates; + + /** + * Add trusted root certificates to the webdav client. + * + * The parameter certificates should be a absulute path to a file which contains + * all trusted certificates + * + * @param string $certificates + */ + public function addTrustedCertificates($certificates) { + $this->trustedCertificates = $certificates; + } + + /** + * Copied from SabreDAV with some modification to use user defined curlSettings + * Performs an actual HTTP request, and returns the result. + * + * If the specified url is relative, it will be expanded based on the base + * url. + * + * The returned array contains 3 keys: + * * body - the response body + * * httpCode - a HTTP code (200, 404, etc) + * * headers - a list of response http headers. The header names have + * been lowercased. + * + * @param string $method + * @param string $url + * @param string $body + * @param array $headers + * @return array + */ + public function request($method, $url = '', $body = null, $headers = array()) { + + $url = $this->getAbsoluteUrl($url); + + $curlSettings = array( + CURLOPT_RETURNTRANSFER => true, + // Return headers as part of the response + CURLOPT_HEADER => true, + CURLOPT_POSTFIELDS => $body, + // Automatically follow redirects + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => 5, + ); + + if($this->trustedCertificates) { + $curlSettings[CURLOPT_CAINFO] = $this->trustedCertificates; + } + + switch ($method) { + case 'HEAD' : + + // do not read body with HEAD requests (this is neccessary because cURL does not ignore the body with HEAD + // requests when the Content-Length header is given - which in turn is perfectly valid according to HTTP + // specs...) cURL does unfortunately return an error in this case ("transfer closed transfer closed with + // ... bytes remaining to read") this can be circumvented by explicitly telling cURL to ignore the + // response body + $curlSettings[CURLOPT_NOBODY] = true; + $curlSettings[CURLOPT_CUSTOMREQUEST] = 'HEAD'; + break; + + default: + $curlSettings[CURLOPT_CUSTOMREQUEST] = $method; + break; + + } + + // Adding HTTP headers + $nHeaders = array(); + foreach($headers as $key=>$value) { + + $nHeaders[] = $key . ': ' . $value; + + } + $curlSettings[CURLOPT_HTTPHEADER] = $nHeaders; + + if ($this->proxy) { + $curlSettings[CURLOPT_PROXY] = $this->proxy; + } + + if ($this->userName && $this->authType) { + $curlType = 0; + if ($this->authType & self::AUTH_BASIC) { + $curlType |= CURLAUTH_BASIC; + } + if ($this->authType & self::AUTH_DIGEST) { + $curlType |= CURLAUTH_DIGEST; + } + $curlSettings[CURLOPT_HTTPAUTH] = $curlType; + $curlSettings[CURLOPT_USERPWD] = $this->userName . ':' . $this->password; + } + + list( + $response, + $curlInfo, + $curlErrNo, + $curlError + ) = $this->curlRequest($url, $curlSettings); + + $headerBlob = substr($response, 0, $curlInfo['header_size']); + $response = substr($response, $curlInfo['header_size']); + + // In the case of 100 Continue, or redirects we'll have multiple lists + // of headers for each separate HTTP response. We can easily split this + // because they are separated by \r\n\r\n + $headerBlob = explode("\r\n\r\n", trim($headerBlob, "\r\n")); + + // We only care about the last set of headers + $headerBlob = $headerBlob[count($headerBlob)-1]; + + // Splitting headers + $headerBlob = explode("\r\n", $headerBlob); + + $headers = array(); + foreach($headerBlob as $header) { + $parts = explode(':', $header, 2); + if (count($parts)==2) { + $headers[strtolower(trim($parts[0]))] = trim($parts[1]); + } + } + + $response = array( + 'body' => $response, + 'statusCode' => $curlInfo['http_code'], + 'headers' => $headers + ); + + if ($curlErrNo) { + throw new Sabre_DAV_Exception('[CURL] Error while making request: ' . $curlError . ' (error code: ' . $curlErrNo . ')'); + } + + if ($response['statusCode']>=400) { + switch ($response['statusCode']) { + case 404: + throw new Sabre_DAV_Exception_NotFound('Resource ' . $url . ' not found.'); + break; + + default: + throw new Sabre_DAV_Exception('HTTP error response. (errorcode ' . $response['statusCode'] . ')'); + } + } + + return $response; + + } }
\ No newline at end of file diff --git a/lib/connector/sabre/directory.php b/lib/connector/sabre/directory.php index a7502446152..8fff77ac749 100644 --- a/lib/connector/sabre/directory.php +++ b/lib/connector/sabre/directory.php @@ -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 diff --git a/lib/connector/sabre/locks.php b/lib/connector/sabre/locks.php index a01653d960a..dbcc57558e0 100644 --- a/lib/connector/sabre/locks.php +++ b/lib/connector/sabre/locks.php @@ -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']; diff --git a/lib/connector/sabre/node.php b/lib/connector/sabre/node.php index afcabe7bef6..2916575e2d5 100644 --- a/lib/connector/sabre/node.php +++ b/lib/connector/sabre/node.php @@ -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; } diff --git a/lib/connector/sabre/principal.php b/lib/connector/sabre/principal.php index d1456f7c642..cfc72eda9f9 100644 --- a/lib/connector/sabre/principal.php +++ b/lib/connector/sabre/principal.php @@ -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;} } diff --git a/lib/db.php b/lib/db.php index de72dee2554..ee69e5f8299 100644 --- a/lib/db.php +++ b/lib/db.php @@ -41,15 +41,16 @@ class OC_DB { * check which backend we should use * @return BACKEND_MDB2 or BACKEND_PDO */ - private static function getDBBackend(){ - if(class_exists('PDO') && OC_Config::getValue('installed', false)){//check if we can use PDO, else use MDB2 (installation always needs to be done my mdb2) + 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" ); if($type=='oci') { //oracle also always needs mdb2 return self::BACKEND_MDB2; } if($type=='sqlite3') $type='sqlite'; $drivers=PDO::getAvailableDrivers(); - if(array_search($type,$drivers)!==false){ + if(array_search($type, $drivers)!==false) { return self::BACKEND_PDO; } } @@ -62,14 +63,14 @@ class OC_DB { * * Connects to the database as specified in config.php */ - public static function connect($backend=null){ - if(self::$connection){ + public static function connect($backend=null) { + if(self::$connection) { return; } - if(is_null($backend)){ + if(is_null($backend)) { $backend=self::getDBBackend(); } - if($backend==self::BACKEND_PDO){ + if($backend==self::BACKEND_PDO) { self::connectPDO(); self::$connection=self::$PDO; self::$backend=self::BACKEND_PDO; @@ -83,9 +84,9 @@ class OC_DB { /** * connect to the database using pdo */ - public static function connectPDO(){ - if(self::$connection){ - if(self::$backend==self::BACKEND_MDB2){ + public static function connectPDO() { + if(self::$connection) { + if(self::$backend==self::BACKEND_MDB2) { self::disconnect(); }else{ return; @@ -97,8 +98,8 @@ class OC_DB { $user = OC_Config::getValue( "dbuser", "" ); $pass = OC_Config::getValue( "dbpassword", "" ); $type = OC_Config::getValue( "dbtype", "sqlite" ); - if(strpos($host,':')){ - list($host,$port)=explode(':',$host,2); + if(strpos($host, ':')) { + list($host, $port)=explode(':', $host,2); }else{ $port=false; } @@ -106,9 +107,9 @@ class OC_DB { $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT.'/data' ); // do nothing if the connection already has been established - if(!self::$PDO){ + if(!self::$PDO) { // Add the dsn according to the database type - switch($type){ + switch($type) { case 'sqlite': $dsn='sqlite2:'.$datadir.'/'.$name.'.db'; break; @@ -116,7 +117,7 @@ class OC_DB { $dsn='sqlite:'.$datadir.'/'.$name.'.db'; break; case 'mysql': - if($port){ + if($port) { $dsn='mysql:dbname='.$name.';host='.$host.';port='.$port; }else{ $dsn='mysql:dbname='.$name.';host='.$host; @@ -124,7 +125,7 @@ class OC_DB { $opts[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES 'UTF8'"; break; case 'pgsql': - if($port){ + if($port) { $dsn='pgsql:dbname='.$name.';host='.$host.';port='.$port; }else{ $dsn='pgsql:dbname='.$name.';host='.$host; @@ -139,22 +140,22 @@ class OC_DB { /** END OF FIX***/ break; case 'oci': // Oracle with PDO is unsupported - if ($port) { - $dsn = 'oci:dbname=//' . $host . ':' . $port . '/' . $name; - } else { - $dsn = 'oci:dbname=//' . $host . '/' . $name; - } - break; + if ($port) { + $dsn = 'oci:dbname=//' . $host . ':' . $port . '/' . $name; + } else { + $dsn = 'oci:dbname=//' . $host . '/' . $name; + } + break; } try{ - self::$PDO=new PDO($dsn,$user,$pass,$opts); - }catch(PDOException $e){ + self::$PDO=new PDO($dsn, $user, $pass, $opts); + }catch(PDOException $e) { echo( '<b>can not connect to database, using '.$type.'. ('.$e->getMessage().')</center>'); die(); } // We always, really always want associative arrays - self::$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); - self::$PDO->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); + self::$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); + self::$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } return true; } @@ -162,9 +163,9 @@ class OC_DB { /** * connect to the database using mdb2 */ - public static function connectMDB2(){ - if(self::$connection){ - if(self::$backend==self::BACKEND_PDO){ + public static function connectMDB2() { + if(self::$connection) { + if(self::$backend==self::BACKEND_PDO) { self::disconnect(); }else{ return; @@ -180,9 +181,9 @@ class OC_DB { $datadir=OC_Config::getValue( "datadirectory", "$SERVERROOT/data" ); // do nothing if the connection already has been established - if(!self::$MDB2){ + if(!self::$MDB2) { // Require MDB2.php (not required in the head of the file so we only load it when needed) - require_once('MDB2.php'); + require_once 'MDB2.php'; // Prepare options array $options = array( @@ -193,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( @@ -239,10 +240,10 @@ class OC_DB { self::$MDB2 = MDB2::factory( $dsn, $options ); // Die if we could not connect - if( PEAR::isError( self::$MDB2 )){ + if( PEAR::isError( self::$MDB2 )) { echo( '<b>can not connect to database, using '.$type.'. ('.self::$MDB2->getUserInfo().')</center>'); - OC_Log::write('core',self::$MDB2->getUserInfo(),OC_Log::FATAL); - OC_Log::write('core',self::$MDB2->getMessage(),OC_Log::FATAL); + OC_Log::write('core', self::$MDB2->getUserInfo(), OC_Log::FATAL); + OC_Log::write('core', self::$MDB2->getMessage(), OC_Log::FATAL); die( $error ); } @@ -261,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) { @@ -290,24 +291,24 @@ class OC_DB { self::connect(); // return the result - if(self::$backend==self::BACKEND_MDB2){ + if(self::$backend==self::BACKEND_MDB2) { $result = self::$connection->prepare( $query ); // Die if we have an error (error means: bad query, not 0 results!) if( PEAR::isError($result)) { $entry = 'DB Error: "'.$result->getMessage().'"<br />'; $entry .= 'Offending command was: '.$query.'<br />'; - OC_Log::write('core',$entry,OC_Log::FATAL); + OC_Log::write('core', $entry,OC_Log::FATAL); error_log('DB error: '.$entry); die( $entry ); } }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); + OC_Log::write('core', $entry,OC_Log::FATAL); error_log('DB error: '.$entry); die( $entry ); } @@ -326,9 +327,9 @@ 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){ + if($table !== null) { $prefix = OC_Config::getValue( "dbtableprefix", "oc_" ); $suffix = OC_Config::getValue( "dbsequencesuffix", "_id_seq" ); $table = str_replace( '*PREFIX*', $prefix, $table ); @@ -342,10 +343,10 @@ 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){ + if(self::$connection) { + if(self::$backend==self::BACKEND_MDB2) { self::$connection->disconnect(); } self::$connection=false; @@ -363,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 @@ -385,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" ); @@ -405,11 +406,12 @@ 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 ); } - */ + file_put_contents( $file2, $content ); // Try to create tables @@ -419,10 +421,10 @@ class OC_DB { unlink( $file2 ); // Die in case something went wrong - if( $definition instanceof MDB2_Schema_Error ){ + if( $definition instanceof MDB2_Schema_Error ) { die( $definition->getMessage().': '.$definition->getUserInfo()); } - if(OC_Config::getValue('dbtype','sqlite')==='oci'){ + if(OC_Config::getValue('dbtype', 'sqlite')==='oci') { unset($definition['charset']); //or MDB2 tries SHUTDOWN IMMEDIATE $oldname = $definition['name']; $definition['name']=OC_Config::getValue( "dbuser", $oldname ); @@ -431,7 +433,7 @@ class OC_DB { $ret=self::$schema->createDatabase( $definition ); // Die in case something went wrong - if( $ret instanceof MDB2_Error ){ + if( $ret instanceof MDB2_Error ) { echo (self::$MDB2->getDebugOutput()); die ($ret->getMessage() . ': ' . $ret->getUserInfo()); } @@ -443,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" ); @@ -455,7 +457,7 @@ class OC_DB { $previousSchema = self::$schema->getDefinitionFromDatabase(); if (PEAR::isError($previousSchema)) { $error = $previousSchema->getMessage(); - OC_Log::write('core','Failed to get existing database structure for upgrading ('.$error.')',OC_Log::FATAL); + OC_Log::write('core', 'Failed to get existing database structure for upgrading ('.$error.')', OC_Log::FATAL); return false; } @@ -469,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 ); } */ @@ -482,7 +484,7 @@ class OC_DB { if (PEAR::isError($op)) { $error = $op->getMessage(); $detail = $op->getDebugInfo(); - OC_Log::write('core','Failed to update database structure ('.$error.', '.$detail.')',OC_Log::FATAL); + OC_Log::write('core', 'Failed to update database structure ('.$error.', '.$detail.')', OC_Log::FATAL); return false; } return true; @@ -494,15 +496,15 @@ 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'); self::$MDB2->loadModule('Reverse'); // Connect if this did not happen before - if(!self::$schema){ - require_once('MDB2/Schema.php'); + if(!self::$schema) { + require_once 'MDB2/Schema.php'; self::$schema=MDB2_Schema::factory(self::$MDB2); } @@ -517,29 +519,29 @@ 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)){ + if(is_null(self::$type)) { self::$type=OC_Config::getValue( "dbtype", "sqlite" ); } $type = self::$type; - if(is_null(self::$prefix)){ + if(is_null(self::$prefix)) { self::$prefix=OC_Config::getValue( "dbtableprefix", "oc_" ); } $prefix = self::$prefix; // differences in escaping of table names ('`' for mysql) and getting the current timestamp - if( $type == 'sqlite' || $type == 'sqlite3' ){ + if( $type == 'sqlite' || $type == 'sqlite3' ) { $query = str_replace( '`', '"', $query ); - $query = str_replace( 'NOW()', 'datetime(\'now\')', $query ); - $query = str_replace( 'now()', 'datetime(\'now\')', $query ); - }elseif( $type == 'pgsql' ){ + $query = str_ireplace( 'NOW()', 'datetime(\'now\')', $query ); + $query = str_ireplace( 'UNIX_TIMESTAMP()', 'strftime(\'%s\',\'now\')', $query ); + }elseif( $type == 'pgsql' ) { $query = str_replace( '`', '"', $query ); - }elseif( $type == 'oci' ){ + $query = str_ireplace( 'UNIX_TIMESTAMP()', 'cast(extract(epoch from current_timestamp) as integer)', $query ); + }elseif( $type == 'oci' ) { $query = str_replace( '`', '"', $query ); - $query = str_replace( 'NOW()', 'CURRENT_TIMESTAMP', $query ); - $query = str_replace( 'now()', 'CURRENT_TIMESTAMP', $query ); + $query = str_ireplace( 'NOW()', 'CURRENT_TIMESTAMP', $query ); } // replace table name prefix @@ -552,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); @@ -562,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(); @@ -582,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); } } @@ -591,15 +593,15 @@ 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)){ + if(file_exists($path)) { self::removeDBStructure( $path ); } } @@ -607,13 +609,12 @@ class OC_DB { // Create new tables self::createDBFromStructure( $file ); self::commit(); - - } + } /** * 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; @@ -625,9 +626,9 @@ class OC_DB { /** * Commit the database changes done during a transaction that is in progress */ - public static function commit(){ + public static function commit() { self::connect(); - if(!self::$inTransaction){ + if(!self::$inTransaction) { return false; } self::$connection->commit(); @@ -639,10 +640,10 @@ class OC_DB { * @param mixed $result * @return bool */ - public static function isError($result){ - if(!$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; @@ -657,21 +658,21 @@ 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(); } - if($result){ + if($result) { return $this; }else{ return false; @@ -681,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); @@ -694,15 +695,15 @@ 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){ - return call_user_func_array(array($this->statement,$name),$arguments); + public function __call($name,$arguments) { + return call_user_func_array(array($this->statement,$name), $arguments); } /** @@ -710,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); } } diff --git a/lib/eventsource.php b/lib/eventsource.php index 45a20806b6e..900b5b101e6 100644 --- a/lib/eventsource.php +++ b/lib/eventsource.php @@ -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 } }
\ No newline at end of file diff --git a/lib/filecache.php b/lib/filecache.php index 364b908bcfa..adcf97753ed 100644 --- a/lib/filecache.php +++ b/lib/filecache.php @@ -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,17 +151,21 @@ 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 + if (self::inCache($newPath, $root)) { + self::delete($newPath, $root); + } $oldPath=$root.$oldPath; $newPath=$root.$newPath; $newParent=self::getParentId($newPath); $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); } @@ -169,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); } @@ -186,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`=?'); @@ -207,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); @@ -245,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); @@ -258,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; } @@ -268,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); } @@ -304,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`=?'); @@ -313,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)); @@ -324,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),''); @@ -338,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); @@ -356,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; @@ -365,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); @@ -373,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)); } @@ -401,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); @@ -415,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); @@ -442,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{ @@ -457,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; @@ -466,10 +470,24 @@ 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(); } + + /** + * clear filecache entries + * @param string user (optonal) + */ + public static function clear($user='') { + if($user) { + $query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE user=?'); + $query->execute(array($user)); + }else{ + $query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache`'); + $query->execute(); + } + } } //watch for changes and try to keep the cache up to date diff --git a/lib/filecache/cached.php b/lib/filecache/cached.php index 505f1a5e2a0..261bd2f572b 100644 --- a/lib/filecache/cached.php +++ b/lib/filecache/cached.php @@ -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); diff --git a/lib/filecache/update.php b/lib/filecache/update.php index 7b5f18fe5c1..3d10f5ea7b6 100644 --- a/lib/filecache/update.php +++ b/lib/filecache/update.php @@ -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); diff --git a/lib/fileproxy.php b/lib/fileproxy.php index a1c79874bf7..17380c656a3 100644 --- a/lib/fileproxy.php +++ b/lib/fileproxy.php @@ -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(); } } diff --git a/lib/fileproxy/quota.php b/lib/fileproxy/quota.php index 4c6261fc514..adbff3d301a 100644 --- a/lib/fileproxy/quota.php +++ b/lib/fileproxy/quota.php @@ -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); } }
\ No newline at end of file diff --git a/lib/files.php b/lib/files.php index 0c71f6e5e42..63dd96b9509 100644 --- a/lib/files.php +++ b/lib/files.php @@ -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(); @@ -56,7 +56,11 @@ class OC_Files { foreach ($files as &$file) { $file['directory'] = $directory; $file['type'] = ($file['mimetype'] == 'httpd/unix-directory') ? 'dir' : 'file'; - $permissions = OCP\Share::PERMISSION_READ | OCP\Share::PERMISSION_SHARE; + $permissions = OCP\Share::PERMISSION_READ; + // NOTE: Remove check when new encryption is merged + if (!$file['encrypted']) { + $permissions |= OCP\Share::PERMISSION_SHARE; + } if ($file['type'] == 'dir' && $file['writable']) { $permissions |= OCP\Share::PERMISSION_CREATE; } @@ -83,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); @@ -97,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); @@ -127,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); @@ -147,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 @@ -165,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); } } @@ -197,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') && !OC_Filesystem::file_exists($targetDir.'/'.$target)){ + 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); @@ -215,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); @@ -230,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{ @@ -253,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); @@ -268,7 +272,7 @@ class OC_Files { */ static function validateZipDownload($dir, $files) { if(!OC_Config::getValue('allowZipDownload', true)) { - $l = OC_L10N::get('files'); + $l = OC_L10N::get('lib'); header("HTTP/1.0 409 Conflict"); $tmpl = new OC_Template( '', 'error', 'user' ); $errors = array( @@ -285,15 +289,15 @@ 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{ $totalsize += OC_Filesystem::filesize($dir.'/'.$files); } if($totalsize > $zipLimit) { - $l = OC_L10N::get('files'); + $l = OC_L10N::get('lib'); header("HTTP/1.0 409 Conflict"); $tmpl = new OC_Template( '', 'error', 'user' ); $errors = array( @@ -315,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); } @@ -325,7 +329,7 @@ class OC_Files { * @param string path * @return array */ - static function getTree($path){ + static function getTree($path) { return OC_Filesystem::getTree($path); } @@ -337,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"; @@ -349,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{ @@ -362,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 @@ -417,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); } @@ -428,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']); diff --git a/lib/filestorage/common.php b/lib/filestorage/common.php index e2828e56170..351714437c5 100644 --- a/lib/filestorage/common.php +++ b/lib/filestorage/common.php @@ -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; } } diff --git a/lib/filestorage/commontest.php b/lib/filestorage/commontest.php index 4d06e4fa321..b88bb232c36 100644 --- a/lib/filestorage/commontest.php +++ b/lib/filestorage/commontest.php @@ -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); } }
\ No newline at end of file diff --git a/lib/filestorage/local.php b/lib/filestorage/local.php index b19205f45b1..e26d3d3ef91 100644 --- a/lib/filestorage/local.php +++ b/lib/filestorage/local.php @@ -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; } } diff --git a/lib/filestorage/temporary.php b/lib/filestorage/temporary.php index 8f2373c8e95..876ba045a63 100644 --- a/lib/filestorage/temporary.php +++ b/lib/filestorage/temporary.php @@ -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(); } } diff --git a/lib/filesystem.php b/lib/filesystem.php index 327329f9d91..92eb4fa4778 100644 --- a/lib/filesystem.php +++ b/lib/filesystem.php @@ -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); @@ -236,6 +236,13 @@ 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 + OC_FileCache::clear(); + OC_Appconfig::setValue('files','mountconfigmtime',$mtime); + } } self::$loaded=true; @@ -246,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); } @@ -254,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(); } @@ -271,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) { @@ -290,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); } @@ -300,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(); } @@ -317,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); @@ -333,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); } @@ -363,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; @@ -378,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']; @@ -396,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) { @@ -453,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); } @@ -510,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); } @@ -529,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; @@ -559,4 +566,4 @@ OC_Hook::connect('OC_Filesystem','post_delete','OC_Filesystem','removeETagHook') OC_Hook::connect('OC_Filesystem','post_rename','OC_Filesystem','removeETagHook'); OC_Util::setupFS(); -require_once('filecache.php'); +require_once 'filecache.php'; diff --git a/lib/filesystemview.php b/lib/filesystemview.php index 461a0262560..743f9403011 100644 --- a/lib/filesystemview.php +++ b/lib/filesystemview.php @@ -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()) { diff --git a/lib/geo.php b/lib/geo.php index 964605b1c1c..4eb785da355 100644 --- a/lib/geo.php +++ b/lib/geo.php @@ -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']; diff --git a/lib/group.php b/lib/group.php index dd70a94eb0d..b56a4ad456c 100644 --- a/lib/group.php +++ b/lib/group.php @@ -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; diff --git a/lib/group/backend.php b/lib/group/backend.php index 5969986c652..1ba34c940cf 100644 --- a/lib/group/backend.php +++ b/lib/group/backend.php @@ -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)); } diff --git a/lib/group/database.php b/lib/group/database.php index 52608b2db73..f3012563acf 100644 --- a/lib/group/database.php +++ b/lib/group/database.php @@ -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"]; } diff --git a/lib/group/dummy.php b/lib/group/dummy.php index 51eca28f3f4..8116dcbd675 100644 --- a/lib/group/dummy.php +++ b/lib/group/dummy.php @@ -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(); diff --git a/lib/helper.php b/lib/helper.php index 69856085dbe..ed4bf53250a 100644 --- a/lib/helper.php +++ b/lib/helper.php @@ -32,16 +32,17 @@ class OC_Helper { * @brief Creates an url * @param $app app * @param $file file + * @param $args array with param=>value, will be appended to the returned url * @returns the url * * Returns a url to the given app and file. */ - public static function linkTo( $app, $file ){ - 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 . '/index.php/apps/' . $app; $urlLinkTo .= ($file!='index.php') ? '/' . $file : ''; }else{ @@ -53,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{ @@ -61,6 +62,10 @@ class OC_Helper { } } + foreach($args as $k => $v) { + $urlLinkTo .= '&'.$k.'='.$v; + } + return $urlLinkTo; } @@ -68,12 +73,13 @@ class OC_Helper { * @brief Creates an absolute url * @param $app app * @param $file file + * @param $args array with param=>value, will be appended to the returned url * @returns the url * * Returns a absolute url to the given app and file. */ - public static function linkToAbsolute( $app, $file ) { - $urlLinkTo = self::linkTo( $app, $file ); + public static function linkToAbsolute( $app, $file, $args = array() ) { + $urlLinkTo = self::linkTo( $app, $file, $args ); return self::makeURLAbsolute($urlLinkTo); } @@ -119,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); @@ -149,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{ @@ -183,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"; } @@ -210,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); @@ -274,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); } } @@ -297,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)) { @@ -317,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)) { @@ -325,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), ".")); @@ -337,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); @@ -373,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{ @@ -423,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"); @@ -467,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; @@ -485,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); @@ -499,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; @@ -509,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); @@ -519,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); } @@ -535,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, '.')) { @@ -565,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; } } @@ -604,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) { diff --git a/lib/hook.php b/lib/hook.php index ee390d6cd5a..1bf80f604f6 100644 --- a/lib/hook.php +++ b/lib/hook.php @@ -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(); diff --git a/lib/image.php b/lib/image.php index e87cf9e16d9..f4b3c2cc071 100644 --- a/lib/image.php +++ b/lib/image.php @@ -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(); } } diff --git a/lib/installer.php b/lib/installer.php index b8a3226aa0b..9135c60fc05 100644 --- a/lib/installer.php +++ b/lib/installer.php @@ -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'); diff --git a/lib/json.php b/lib/json.php index 32ae734e4a5..518c3c87c49 100644 --- a/lib/json.php +++ b/lib/json.php @@ -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,9 +22,9 @@ 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)){ - $l = OC_L10N::get('core'); + 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,9 +33,9 @@ class OC_JSON{ /** * Check if the user is logged in, send json error msg if not */ - public static function checkLoggedIn(){ - if( !OC_User::isLoggedIn()){ - $l = OC_L10N::get('core'); + 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,9 +45,9 @@ 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()){ - $l = OC_L10N::get('core'); + 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,10 +56,10 @@ 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' )){ - $l = OC_L10N::get('core'); + 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,10 +68,10 @@ 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())){ - $l = OC_L10N::get('core'); + 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')); diff --git a/lib/l10n.php b/lib/l10n.php index cfa0e26486b..90877cbd747 100644 --- a/lib/l10n.php +++ b/lib/l10n.php @@ -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; } @@ -99,12 +99,12 @@ class OC_L10N{ $lang = $this->lang; $this->app = true; // Find the right language - if(is_null($lang)){ + if(is_null($lang) || $lang == '') { $lang = self::findLanguage($app); } // 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']; @@ -113,18 +113,21 @@ class OC_L10N{ $i18ndir = self::findI18nDir($app); // Localization is in /l10n, Texts are in $i18ndir // (Just no need to define date/time format etc. twice) - if((OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC_App::getAppPath($app).'/l10n/') || OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/core/l10n/') || OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/settings')) && file_exists($i18ndir.$lang.'.php')) { + if((OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC_App::getAppPath($app).'/l10n/') || + OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/core/l10n/') || + OC_Helper::issubdirectory($i18ndir.$lang.'.php', OC::$SERVERROOT.'/lib/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); } } @@ -134,16 +137,16 @@ class OC_L10N{ } } - /** - * @brief Translating - * @param $text The text we need a translation for - * @param $parameters default:array() Parameters for sprintf - * @returns Translation or the same text - * - * Returns the translation. If no translation is found, $text will be - * returned. - */ - public function t($text, $parameters = array()){ + /** + * @brief Translating + * @param $text String The text we need a translation for + * @param array|\default $parameters default:array() Parameters for sprintf + * @return \OC_L10N_String Translation or the same text + * + * Returns the translation. If no translation is found, $text will be + * returned. + */ + public function t($text, $parameters = array()) { return new OC_L10N_String($this, $text, $parameters); } @@ -161,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; @@ -176,7 +179,7 @@ class OC_L10N{ * * Returns an associative array with all translations */ - public function getTranslations(){ + public function getTranslations() { $this->init(); return $this->translations; } @@ -203,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': @@ -230,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]; } @@ -246,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]; } } @@ -291,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{ @@ -311,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; } @@ -326,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; diff --git a/lib/l10n/ca.php b/lib/l10n/ca.php index 8e4c30caec9..031207227ec 100644 --- a/lib/l10n/ca.php +++ b/lib/l10n/ca.php @@ -21,5 +21,8 @@ "last month" => "el mes passat", "months ago" => "mesos enrere", "last year" => "l'any passat", -"years ago" => "fa anys" +"years ago" => "fa anys", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s està disponible. Obtén <a href=\"%s\">més informació</a>", +"up to date" => "actualitzat", +"updates check is disabled" => "la comprovació d'actualitzacions està desactivada" ); diff --git a/lib/l10n/cs_CZ.php b/lib/l10n/cs_CZ.php index 933dbe541f5..00815f97533 100644 --- a/lib/l10n/cs_CZ.php +++ b/lib/l10n/cs_CZ.php @@ -4,14 +4,14 @@ "Settings" => "Nastavení", "Users" => "Uživatelé", "Apps" => "Aplikace", -"Admin" => "Admin", +"Admin" => "Administrace", "ZIP download is turned off." => "Stahování ZIPu je vypnuto.", -"Files need to be downloaded one by one." => "Soubory je nutno stahovat samostatně.", +"Files need to be downloaded one by one." => "Soubory musí být stahovány jednotlivě.", "Back to Files" => "Zpět k souborům", -"Selected files too large to generate zip file." => "Vybarné soubory jsou pro vytvoření zipu příliš velké.", +"Selected files too large to generate zip file." => "Vybrané soubory jsou příliš velké pro vytvoření zip souboru.", "Application is not enabled" => "Aplikace není povolena", -"Authentication error" => "Chyba autorizace", -"Token expired. Please reload page." => "Realce expirovala. Obnovte prosím stranu.", +"Authentication error" => "Chyba ověření", +"Token expired. Please reload page." => "Token vypršel. Obnovte prosím stránku.", "seconds ago" => "před vteřinami", "1 minute ago" => "před 1 minutou", "%d minutes ago" => "před %d minutami", @@ -21,5 +21,8 @@ "last month" => "minulý měsíc", "months ago" => "před měsíci", "last year" => "loni", -"years ago" => "před lety" +"years ago" => "před lety", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s je dostupná. Získat <a href=\"%s\">více informací</a>", +"up to date" => "aktuální", +"updates check is disabled" => "kontrola aktualizací je vypnuta" ); diff --git a/lib/l10n/da.php b/lib/l10n/da.php new file mode 100644 index 00000000000..7a9ee26b477 --- /dev/null +++ b/lib/l10n/da.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Hjælp", +"Personal" => "Personlig", +"Settings" => "Indstillinger", +"Users" => "Brugere", +"Apps" => "Apps", +"Admin" => "Admin", +"ZIP download is turned off." => "ZIP-download er slået fra.", +"Files need to be downloaded one by one." => "Filer skal downloades en for en.", +"Back to Files" => "Tilbage til Filer", +"Selected files too large to generate zip file." => "De markerede filer er for store til at generere en ZIP-fil.", +"Application is not enabled" => "Programmet er ikke aktiveret", +"Authentication error" => "Adgangsfejl", +"Token expired. Please reload page." => "Adgang er udløbet. Genindlæs siden.", +"seconds ago" => "sekunder siden", +"1 minute ago" => "1 minut siden", +"%d minutes ago" => "%d minutter siden", +"today" => "I dag", +"yesterday" => "I går", +"%d days ago" => "%d dage siden", +"last month" => "Sidste måned", +"months ago" => "måneder siden", +"last year" => "Sidste år", +"years ago" => "år siden" +); diff --git a/lib/l10n/de.php b/lib/l10n/de.php index e77ec97df75..4a567003de2 100644 --- a/lib/l10n/de.php +++ b/lib/l10n/de.php @@ -21,5 +21,8 @@ "last month" => "Letzten Monat", "months ago" => "Vor Monaten", "last year" => "Letztes Jahr", -"years ago" => "Vor Jahren" +"years ago" => "Vor Jahren", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s ist verfügbar. <a href=\"%s\">Weitere Informationen</a>", +"up to date" => "aktuell", +"updates check is disabled" => "Die Update-Überprüfung ist ausgeschaltet" ); diff --git a/lib/l10n/eo.php b/lib/l10n/eo.php index 96bcb06a8d7..3f89e2eca73 100644 --- a/lib/l10n/eo.php +++ b/lib/l10n/eo.php @@ -4,6 +4,7 @@ "Settings" => "Agordo", "Users" => "Uzantoj", "Apps" => "Aplikaĵoj", +"Admin" => "Administranto", "ZIP download is turned off." => "ZIP-elŝuto estas malkapabligita.", "Files need to be downloaded one by one." => "Dosieroj devas elŝutiĝi unuope.", "Back to Files" => "Reen al la dosieroj", diff --git a/lib/l10n/es.php b/lib/l10n/es.php index 174fe0720fd..6d2a310ca3b 100644 --- a/lib/l10n/es.php +++ b/lib/l10n/es.php @@ -21,5 +21,8 @@ "last month" => "este mes", "months ago" => "hace meses", "last year" => "este año", -"years ago" => "hace años" +"years ago" => "hace años", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s está disponible. Obtén <a href=\"%s\">más información</a>", +"up to date" => "actualizado", +"updates check is disabled" => "comprobar actualizaciones está desactivado" ); diff --git a/lib/l10n/eu.php b/lib/l10n/eu.php new file mode 100644 index 00000000000..461bf458778 --- /dev/null +++ b/lib/l10n/eu.php @@ -0,0 +1,28 @@ +<?php $TRANSLATIONS = array( +"Help" => "Laguntza", +"Personal" => "Pertsonala", +"Settings" => "Ezarpenak", +"Users" => "Erabiltzaileak", +"Apps" => "Aplikazioak", +"Admin" => "Admin", +"ZIP download is turned off." => "ZIP deskarga ez dago gaituta.", +"Files need to be downloaded one by one." => "Fitxategiak banan-banan deskargatu behar dira.", +"Back to Files" => "Itzuli fitxategietara", +"Selected files too large to generate zip file." => "Hautatuko fitxategiak oso handiak dira zip fitxategia sortzeko.", +"Application is not enabled" => "Aplikazioa ez dago gaituta", +"Authentication error" => "Autentikazio errorea", +"Token expired. Please reload page." => "Tokena iraungitu da. Mesedez birkargatu orria.", +"seconds ago" => "orain dela segundu batzuk", +"1 minute ago" => "orain dela minutu 1", +"%d minutes ago" => "orain dela %d minutu", +"today" => "gaur", +"yesterday" => "atzo", +"%d days ago" => "orain dela %d egun", +"last month" => "joan den hilabetea", +"months ago" => "orain dela hilabete batzuk", +"last year" => "joan den urtea", +"years ago" => "orain dela urte batzuk", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s eskuragarri dago. Lortu <a href=\"%s\">informazio gehiago</a>", +"up to date" => "eguneratuta", +"updates check is disabled" => "eguneraketen egiaztapena ez dago gaituta" +); diff --git a/lib/l10n/fi_FI.php b/lib/l10n/fi_FI.php index dda2c760373..6f0ebcd16e6 100644 --- a/lib/l10n/fi_FI.php +++ b/lib/l10n/fi_FI.php @@ -21,5 +21,8 @@ "last month" => "viime kuussa", "months ago" => "kuukautta sitten", "last year" => "viime vuonna", -"years ago" => "vuotta sitten" +"years ago" => "vuotta sitten", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s on saatavilla. Lue <a href=\"%s\">lisätietoja</a>", +"up to date" => "ajan tasalla", +"updates check is disabled" => "päivitysten tarkistus on pois käytöstä" ); diff --git a/lib/l10n/fr.php b/lib/l10n/fr.php index c674b79b959..c10259e6376 100644 --- a/lib/l10n/fr.php +++ b/lib/l10n/fr.php @@ -21,5 +21,8 @@ "last month" => "le mois dernier", "months ago" => "il y a plusieurs mois", "last year" => "l'année dernière", -"years ago" => "il y a plusieurs années" +"years ago" => "il y a plusieurs années", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s est disponible. Obtenez <a href=\"%s\">plus d'informations</a>", +"up to date" => "À jour", +"updates check is disabled" => "la vérification des mises à jour est désactivée" ); diff --git a/lib/l10n/he.php b/lib/l10n/he.php new file mode 100644 index 00000000000..149637d09d2 --- /dev/null +++ b/lib/l10n/he.php @@ -0,0 +1,28 @@ +<?php $TRANSLATIONS = array( +"Help" => "עזרה", +"Personal" => "אישי", +"Settings" => "הגדרות", +"Users" => "משתמשים", +"Apps" => "יישומים", +"Admin" => "מנהל", +"ZIP download is turned off." => "הורדת ZIP כבויה", +"Files need to be downloaded one by one." => "יש להוריד את הקבצים אחד אחרי השני.", +"Back to Files" => "חזרה לקבצים", +"Selected files too large to generate zip file." => "הקבצים הנבחרים גדולים מידי ליצירת קובץ zip.", +"Application is not enabled" => "יישומים אינם מופעלים", +"Authentication error" => "שגיאת הזדהות", +"Token expired. Please reload page." => "פג תוקף. נא לטעון שוב את הדף.", +"seconds ago" => "שניות", +"1 minute ago" => "לפני דקה אחת", +"%d minutes ago" => "לפני %d דקות", +"today" => "היום", +"yesterday" => "אתמול", +"%d days ago" => "לפני %d ימים", +"last month" => "חודש שעבר", +"months ago" => "חודשים", +"last year" => "שנה שעברה", +"years ago" => "שנים", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s זמין. קבלת <a href=\"%s\">מידע נוסף</a>", +"up to date" => "עדכני", +"updates check is disabled" => "בדיקת עדכונים מנוטרלת" +); diff --git a/lib/l10n/hu_HU.php b/lib/l10n/hu_HU.php new file mode 100644 index 00000000000..eb074b79c61 --- /dev/null +++ b/lib/l10n/hu_HU.php @@ -0,0 +1,25 @@ +<?php $TRANSLATIONS = array( +"Help" => "Súgó", +"Personal" => "Személyes", +"Settings" => "Beállítások", +"Users" => "Felhasználók", +"Apps" => "Alkalmazások", +"Admin" => "Admin", +"ZIP download is turned off." => "ZIP-letöltés letiltva", +"Files need to be downloaded one by one." => "A file-okat egyenként kell letölteni", +"Back to Files" => "Vissza a File-okhoz", +"Selected files too large to generate zip file." => "Túl nagy file-ok a zip-generáláshoz", +"Application is not enabled" => "Az alkalmazás nincs engedélyezve", +"Authentication error" => "Hitelesítési hiba", +"Token expired. Please reload page." => "A token lejárt. Frissítsd az oldalt.", +"seconds ago" => "másodperccel ezelőtt", +"1 minute ago" => "1 perccel ezelőtt", +"%d minutes ago" => "%d perccel ezelőtt", +"today" => "ma", +"yesterday" => "tegnap", +"%d days ago" => "%d évvel ezelőtt", +"last month" => "múlt hónapban", +"months ago" => "hónappal ezelőtt", +"last year" => "tavaly", +"years ago" => "évvel ezelőtt" +); diff --git a/lib/l10n/it.php b/lib/l10n/it.php index 2c88818dc6c..c4c7d90610b 100644 --- a/lib/l10n/it.php +++ b/lib/l10n/it.php @@ -21,5 +21,8 @@ "last month" => "il mese scorso", "months ago" => "mesi fa", "last year" => "l'anno scorso", -"years ago" => "anni fa" +"years ago" => "anni fa", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s è disponibile. Ottieni <a href=\"%s\">ulteriori informazioni</a>", +"up to date" => "aggiornato", +"updates check is disabled" => "il controllo degli aggiornamenti è disabilitato" ); diff --git a/lib/l10n/ja_JP.php b/lib/l10n/ja_JP.php new file mode 100644 index 00000000000..10f7276703a --- /dev/null +++ b/lib/l10n/ja_JP.php @@ -0,0 +1,28 @@ +<?php $TRANSLATIONS = array( +"Help" => "ヘルプ", +"Personal" => "個人設定", +"Settings" => "設定", +"Users" => "ユーザ", +"Apps" => "アプリ", +"Admin" => "管理者", +"ZIP download is turned off." => "ZIPダウンロードは無効です。", +"Files need to be downloaded one by one." => "ファイルは1つずつダウンロードする必要があります。", +"Back to Files" => "ファイルに戻る", +"Selected files too large to generate zip file." => "選択したファイルはZIPファイルの生成には大きすぎます。", +"Application is not enabled" => "アプリケーションは無効です", +"Authentication error" => "認証エラー", +"Token expired. Please reload page." => "トークンが無効になりました。ページを再読込してください。", +"seconds ago" => "秒前", +"1 minute ago" => "1分前", +"%d minutes ago" => "%d 分前", +"today" => "今日", +"yesterday" => "昨日", +"%d days ago" => "%d 日前", +"last month" => "先月", +"months ago" => "月前", +"last year" => "昨年", +"years ago" => "年前", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s が利用可能です。<a href=\"%s\">詳細情報</a> を確認ください", +"up to date" => "最新です", +"updates check is disabled" => "更新チェックは無効です" +); diff --git a/lib/l10n/nl.php b/lib/l10n/nl.php index 01bc4d3e19f..a90fc6caa6c 100644 --- a/lib/l10n/nl.php +++ b/lib/l10n/nl.php @@ -21,5 +21,8 @@ "last month" => "vorige maand", "months ago" => "maanden geleden", "last year" => "vorig jaar", -"years ago" => "jaar geleden" +"years ago" => "jaar geleden", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s is beschikbaar. Verkrijg <a href=\"%s\">meer informatie</a>", +"up to date" => "Bijgewerkt", +"updates check is disabled" => "Meest recente versie controle is uitgeschakeld" ); diff --git a/lib/l10n/pl.php b/lib/l10n/pl.php new file mode 100644 index 00000000000..087aaa227d3 --- /dev/null +++ b/lib/l10n/pl.php @@ -0,0 +1,28 @@ +<?php $TRANSLATIONS = array( +"Help" => "Pomoc", +"Personal" => "Osobiste", +"Settings" => "Ustawienia", +"Users" => "Użytkownicy", +"Apps" => "Aplikacje", +"Admin" => "Administrator", +"ZIP download is turned off." => "Pobieranie ZIP jest wyłączone.", +"Files need to be downloaded one by one." => "Pliki muszą zostać pobrane pojedynczo.", +"Back to Files" => "Wróć do plików", +"Selected files too large to generate zip file." => "Wybrane pliki są zbyt duże, aby wygenerować plik zip.", +"Application is not enabled" => "Aplikacja nie jest włączona", +"Authentication error" => "Błąd uwierzytelniania", +"Token expired. Please reload page." => "Token wygasł. Proszę ponownie załadować stronę.", +"seconds ago" => "sekund temu", +"1 minute ago" => "1 minutę temu", +"%d minutes ago" => "%d minut temu", +"today" => "dzisiaj", +"yesterday" => "wczoraj", +"%d days ago" => "%d dni temu", +"last month" => "ostatni miesiąc", +"months ago" => "miesięcy temu", +"last year" => "ostatni rok", +"years ago" => "lat temu", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s jest dostępna. Uzyskaj <a href=\"%s\">więcej informacji</a>", +"up to date" => "Aktualne", +"updates check is disabled" => "wybór aktualizacji jest wyłączony" +); diff --git a/lib/l10n/ru.php b/lib/l10n/ru.php index 07dacc598ae..3b2681ba8d1 100644 --- a/lib/l10n/ru.php +++ b/lib/l10n/ru.php @@ -21,5 +21,6 @@ "last month" => "в прошлом месяце", "months ago" => "месяцы назад", "last year" => "в прошлом году", -"years ago" => "годы назад" +"years ago" => "годы назад", +"updates check is disabled" => "проверка обновлений отключена" ); diff --git a/lib/l10n/sl.php b/lib/l10n/sl.php index fad16417253..273773f2f7b 100644 --- a/lib/l10n/sl.php +++ b/lib/l10n/sl.php @@ -21,5 +21,8 @@ "last month" => "prejšnji mesec", "months ago" => "mesecev nazaj", "last year" => "lani", -"years ago" => "let nazaj" +"years ago" => "let nazaj", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s je na voljo. <a href=\"%s\">Več informacij.</a>", +"up to date" => "ažuren", +"updates check is disabled" => "preverjanje za posodobitve je onemogočeno" ); diff --git a/lib/l10n/string.php b/lib/l10n/string.php index 4769790a16d..8eef10071e6 100644 --- a/lib/l10n/string.php +++ b/lib/l10n/string.php @@ -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); diff --git a/lib/l10n/sv.php b/lib/l10n/sv.php index cff3a63c442..3d377133f22 100644 --- a/lib/l10n/sv.php +++ b/lib/l10n/sv.php @@ -21,5 +21,8 @@ "last month" => "förra månaden", "months ago" => "månader sedan", "last year" => "förra året", -"years ago" => "år sedan" +"years ago" => "år sedan", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s finns. Få <a href=\"%s\">mer information</a>", +"up to date" => "uppdaterad", +"updates check is disabled" => "uppdateringskontroll är inaktiverad" ); diff --git a/lib/l10n/th_TH.php b/lib/l10n/th_TH.php index cb2610fa204..2aa2ffaba8c 100644 --- a/lib/l10n/th_TH.php +++ b/lib/l10n/th_TH.php @@ -21,5 +21,8 @@ "last month" => "เดือนที่แล้ว", "months ago" => "เดือนมาแล้ว", "last year" => "ปีที่แล้ว", -"years ago" => "ปีที่ผ่านมา" +"years ago" => "ปีที่ผ่านมา", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s พร้อมให้ใช้งานได้แล้ว. <a href=\"%s\">ดูรายละเอียดเพิ่มเติม</a>", +"up to date" => "ทันสมัย", +"updates check is disabled" => "การตรวจสอบชุดอัพเดทถูกปิดใช้งานไว้" ); diff --git a/lib/l10n/zh_CN.php b/lib/l10n/zh_CN.php index 2d05ad3567e..8229c77d2dd 100644 --- a/lib/l10n/zh_CN.php +++ b/lib/l10n/zh_CN.php @@ -21,5 +21,8 @@ "last month" => "上月", "months ago" => "几月前", "last year" => "上年", -"years ago" => "几年前" +"years ago" => "几年前", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s 已存在. 点此 <a href=\"%s\">获取更多信息</a>", +"up to date" => "已更新。", +"updates check is disabled" => "检查更新功能被关闭。" ); diff --git a/lib/l10n/zh_TW.php b/lib/l10n/zh_TW.php new file mode 100644 index 00000000000..c9a26a53b2a --- /dev/null +++ b/lib/l10n/zh_TW.php @@ -0,0 +1,28 @@ +<?php $TRANSLATIONS = array( +"Help" => "說明", +"Personal" => "個人", +"Settings" => "設定", +"Users" => "使用者", +"Apps" => "應用程式", +"Admin" => "管理", +"ZIP download is turned off." => "ZIP 下載已關閉", +"Files need to be downloaded one by one." => "檔案需要逐一下載", +"Back to Files" => "回到檔案列表", +"Selected files too large to generate zip file." => "選擇的檔案太大以致於無法產生壓縮檔", +"Application is not enabled" => "應用程式未啟用", +"Authentication error" => "認證錯誤", +"Token expired. Please reload page." => "Token 過期. 請重新整理頁面", +"seconds ago" => "幾秒前", +"1 minute ago" => "1 分鐘前", +"%d minutes ago" => "%d 分鐘前", +"today" => "今天", +"yesterday" => "昨天", +"%d days ago" => "%d 天前", +"last month" => "上個月", +"months ago" => "幾個月前", +"last year" => "去年", +"years ago" => "幾年前", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s 已經可用. 取得 <a href=\"%s\">更多資訊</a>", +"up to date" => "最新的", +"updates check is disabled" => "檢查更新已停用" +); diff --git a/lib/log/owncloud.php b/lib/log/owncloud.php index 9eb21832c55..d4644163ad5 100644 --- a/lib/log/owncloud.php +++ b/lib/log/owncloud.php @@ -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(); diff --git a/lib/mail.php b/lib/mail.php index acdadeffd33..8d30fff9f28 100644 --- a/lib/mail.php +++ b/lib/mail.php @@ -12,7 +12,7 @@ * A class to handle mail sending. */ -require_once('class.phpmailer.php'); +require_once 'class.phpmailer.php'; class OC_Mail { @@ -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(); @@ -55,6 +55,7 @@ class OC_Mail { $mailo->From =$fromaddress; $mailo->FromName = $fromname;; + $mailo->Sender =$fromaddress; $a=explode(' ',$toaddress); try { foreach($a as $ad) { diff --git a/lib/migrate.php b/lib/migrate.php index 7d7169c4e46..823b3574f16 100644 --- a/lib/migrate.php +++ b/lib/migrate.php @@ -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,14 +369,14 @@ 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 ){ - require_once('MDB2/Schema.php'); + 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){ - require_once('MDB2.php'); + 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; diff --git a/lib/migration/content.php b/lib/migration/content.php index e04ac224f79..64b8168cd98 100644 --- a/lib/migration/content.php +++ b/lib/migration/content.php @@ -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 ); } } diff --git a/lib/migration/provider.php b/lib/migration/provider.php index 259b1fe7ae6..234ab3351f3 100644 --- a/lib/migration/provider.php +++ b/lib/migration/provider.php @@ -10,7 +10,7 @@ abstract class OC_Migration_Provider{ protected $olduid=false; protected $appinfo=false; - public function __construct( $appid ){ + public function __construct( $appid ) { // Set the id $this->id = $appid; OC_Migrate::registerProvider( $this ); @@ -32,11 +32,11 @@ abstract class OC_Migration_Provider{ * @brief sets the OC_Migration_Content object to $this->content * @param $content a OC_Migration_Content object */ - public function setData( $uid, $content, $info=null ){ + public function setData( $uid, $content, $info=null ) { $this->content = $content; $this->uid = $uid; $id = $this->id; - if( !is_null( $info ) ){ + if( !is_null( $info ) ) { $this->olduid = $info->exporteduser; $this->appinfo = $info->apps->$id; } @@ -46,7 +46,7 @@ abstract class OC_Migration_Provider{ * @brief returns the appid of the provider * @return string */ - public function getID(){ + public function getID() { return $this->id; } } diff --git a/lib/minimizer.php b/lib/minimizer.php index 3dc89e331a6..d50ab0d2397 100644 --- a/lib/minimizer.php +++ b/lib/minimizer.php @@ -1,16 +1,15 @@ <?php abstract class OC_Minimizer { - public function getLastModified($files) { - $last_modified = 0; + public function generateETag($files) { + $etag = ''; + sort($files); foreach($files as $file_info) { $file = $file_info[0] . '/' . $file_info[2]; - $filemtime = filemtime($file); - if ($filemtime > $last_modified) { - $last_modified = $filemtime; - } + $stat = stat($file); + $etag .= $file.$stat['mtime'].$stat['size']; } - return $last_modified; + return md5($etag); } abstract public function minimizeFiles($files); @@ -18,23 +17,21 @@ abstract class OC_Minimizer { public function output($files, $cache_key) { header('Content-Type: '.$this->contentType); OC_Response::enableCaching(); - $last_modified = $this->getLastModified($files); - OC_Response::setLastModifiedHeader($last_modified); + $etag = $this->generateETag($files); + $cache_key .= '-'.$etag; $gzout = false; $cache = OC_Cache::getGlobalCache(); - if (!OC_Request::isNoCache() && (!defined('DEBUG') || !DEBUG)){ + if (!OC_Request::isNoCache() && (!defined('DEBUG') || !DEBUG)) { + OC_Response::setETagHeader($etag); $gzout = $cache->get($cache_key.'.gz'); - if ($gzout) { - OC_Response::setETagHeader(md5($gzout)); - } } if (!$gzout) { $out = $this->minimizeFiles($files); $gzout = gzencode($out); - OC_Response::setETagHeader(md5($gzout)); $cache->set($cache_key.'.gz', $gzout); + OC_Response::setETagHeader($etag); } if ($encoding = OC_Request::acceptGZip()) { header('Content-Encoding: '.$encoding); @@ -45,6 +42,12 @@ abstract class OC_Minimizer { header('Content-Length: '.strlen($out)); echo $out; } + + public function clearCache() { + $cache = OC_Cache::getGlobalCache(); + $cache->clear('core.css'); + $cache->clear('core.js'); + } } if (!function_exists('gzdecode')) { diff --git a/lib/minimizer/css.php b/lib/minimizer/css.php index 110935ea3b7..8d130572e2b 100644 --- a/lib/minimizer/css.php +++ b/lib/minimizer/css.php @@ -1,6 +1,6 @@ <?php -require_once('mediawiki/CSSMin.php'); +require_once 'mediawiki/CSSMin.php'; class OC_Minimizer_CSS extends OC_Minimizer { @@ -16,7 +16,7 @@ class OC_Minimizer_CSS extends OC_Minimizer $in_root = false; foreach(OC::$APPSROOTS as $app_root) { - if(strpos($file, $app_root['path']) === 0) { + if(strpos($file, $app_root['path'].'/') === 0) { $in_root = rtrim($webroot.$app_root['url'], '/'); break; } @@ -30,7 +30,7 @@ class OC_Minimizer_CSS extends OC_Minimizer $remote .= dirname($file_info[2]); $css_out .= CSSMin::remap($css, dirname($file), $remote, true); } - if (!defined('DEBUG') || !DEBUG){ + if (!defined('DEBUG') || !DEBUG) { $css_out = CSSMin::minify($css_out); } return $css_out; diff --git a/lib/minimizer/js.php b/lib/minimizer/js.php index 0f5cb7e5577..bd2d836deb0 100644 --- a/lib/minimizer/js.php +++ b/lib/minimizer/js.php @@ -1,6 +1,6 @@ <?php -require_once('mediawiki/JavaScriptMinifier.php'); +require_once 'mediawiki/JavaScriptMinifier.php'; class OC_Minimizer_JS extends OC_Minimizer { @@ -13,7 +13,7 @@ class OC_Minimizer_JS extends OC_Minimizer $js_out .= '/* ' . $file . ' */' . "\n"; $js_out .= file_get_contents($file); } - if (!defined('DEBUG') || !DEBUG){ + if (!defined('DEBUG') || !DEBUG) { $js_out = JavaScriptMinifier::minify($js_out); } return $js_out; diff --git a/lib/ocs.php b/lib/ocs.php index 64e89648e1b..85b5234379b 100644 --- a/lib/ocs.php +++ b/lib/ocs.php @@ -284,7 +284,7 @@ class OC_OCS { if(isset($_SERVER['PHP_AUTH_PW'])) $authpw=$_SERVER['PHP_AUTH_PW']; else $authpw=''; if(empty($authuser)) { - if($forceuser){ + if($forceuser) { header('WWW-Authenticate: Basic realm="your valid user account or api key"'); header('HTTP/1.0 401 Unauthorized'); exit; @@ -292,8 +292,8 @@ class OC_OCS { $identifieduser=''; } }else{ - if(!OC_User::login($authuser,$authpw)){ - if($forceuser){ + if(!OC_User::login($authuser,$authpw)) { + if($forceuser) { header('WWW-Authenticate: Basic realm="your valid user account or api key"'); header('HTTP/1.0 401 Unauthorized'); exit; @@ -365,7 +365,7 @@ class OC_OCS { xmlwriter_write_attribute($writer,'details',$tagattribute); } foreach($entry as $key=>$value) { - if(is_array($value)){ + if(is_array($value)) { foreach($value as $k=>$v) { xmlwriter_write_element($writer,$k,$v); } @@ -385,7 +385,7 @@ class OC_OCS { xmlwriter_write_attribute($writer,'details',$tagattribute); } foreach($entry as $key=>$value) { - if(is_array($value)){ + if(is_array($value)) { xmlwriter_start_element($writer,$entrykey); foreach($value as $k=>$v) { xmlwriter_write_element($writer,$k,$v); @@ -418,7 +418,7 @@ class OC_OCS { if (is_numeric($key)) { $key = $node; } - if (is_array($value)){ + if (is_array($value)) { xmlwriter_start_element($writer,$key); OC_OCS::toxml($writer,$value,$node); xmlwriter_end_element($writer); @@ -458,8 +458,8 @@ class OC_OCS { * @return string xml/json */ private static function personCheck($format,$login,$passwd) { - if($login<>''){ - if(OC_User::login($login,$passwd)){ + if($login<>'') { + if(OC_User::login($login,$passwd)) { $xml['person']['personid']=$login; echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'person','check',2)); }else{ @@ -536,7 +536,7 @@ class OC_OCS { */ private static function privateDataSet($format, $app, $key, $value) { $user=OC_OCS::checkpassword(); - if(OC_OCS::setData($user,$app,$key,$value)){ + if(OC_OCS::setData($user,$app,$key,$value)) { echo(OC_OCS::generatexml($format,'ok',100,'')); } } @@ -549,11 +549,11 @@ class OC_OCS { * @return string xml/json */ private static function privateDataDelete($format, $app, $key) { - if($key=="" or $app==""){ + if($key=="" or $app=="") { return; //key and app are NOT optional here } $user=OC_OCS::checkpassword(); - if(OC_OCS::deleteData($user,$app,$key)){ + if(OC_OCS::deleteData($user,$app,$key)) { echo(OC_OCS::generatexml($format,'ok',100,'')); } } @@ -567,21 +567,21 @@ class OC_OCS { * @return array */ public static function getData($user,$app="",$key="") { - if($app){ + if($app) { $apps=array($app); }else{ $apps=OC_Preferences::getApps($user); } - if($key){ + if($key) { $keys=array($key); }else{ - foreach($apps as $app){ + foreach($apps as $app) { $keys=OC_Preferences::getKeys($user,$app); } } $result=array(); - foreach($apps as $app){ - foreach($keys as $key){ + foreach($apps as $app) { + foreach($keys as $key) { $value=OC_Preferences::getValue($user,$app,$key); $result[]=array('app'=>$app,'key'=>$key,'value'=>$value); } @@ -648,7 +648,7 @@ class OC_OCS { $login=OC_OCS::checkpassword(); if(OC_Group::inGroup($login, 'admin') or ($login==$user)) { - if(OC_User::userExists($user)){ + if(OC_User::userExists($user)) { // calculate the disc space $user_dir = '/'.$user.'/files'; OC_Filesystem::init($user_dir); @@ -709,7 +709,7 @@ class OC_OCS { private static function publicKeyGet($format,$user) { $login=OC_OCS::checkpassword(); - if(OC_User::userExists($user)){ + if(OC_User::userExists($user)) { // calculate the disc space $txt='this is the public key of '.$user; echo($txt); @@ -728,7 +728,7 @@ class OC_OCS { $login=OC_OCS::checkpassword(); if(OC_Group::inGroup($login, 'admin') or ($login==$user)) { - if(OC_User::userExists($user)){ + if(OC_User::userExists($user)) { // calculate the disc space $txt='this is the private key of '.$user; echo($txt); diff --git a/lib/ocsclient.php b/lib/ocsclient.php index f05a9af31c2..8596ea0b3c7 100644 --- a/lib/ocsclient.php +++ b/lib/ocsclient.php @@ -34,7 +34,7 @@ class OC_OCSClient{ * * This function returns the url of the OCS AppStore server. It´s possible to set it in the config file or it will fallback to the default */ - private static function getAppStoreURL(){ + private static function getAppStoreURL() { $url = OC_Config::getValue('appstoreurl', 'http://api.apps.owncloud.com/v1'); return($url); } @@ -44,7 +44,7 @@ class OC_OCSClient{ * @returns string of the KB server * This function returns the url of the OCS knowledge base server. It´s possible to set it in the config file or it will fallback to the default */ - private static function getKBURL(){ + private static function getKBURL() { $url = OC_Config::getValue('knowledgebaseurl', 'http://api.apps.owncloud.com/v1'); return($url); } @@ -56,14 +56,14 @@ class OC_OCSClient{ * * This function returns a list of all the application categories on the OCS server */ - public static function getCategories(){ - if(OC_Config::getValue('appstoreenabled', true)==false){ + public static function getCategories() { + if(OC_Config::getValue('appstoreenabled', true)==false) { return NULL; } $url=OC_OCSClient::getAppStoreURL().'/content/categories'; $xml=@file_get_contents($url); - if($xml==FALSE){ + if($xml==FALSE) { return NULL; } $data=simplexml_load_string($xml); @@ -88,8 +88,8 @@ class OC_OCSClient{ * * This function returns a list of all the applications on the OCS server */ - public static function getApplications($categories,$page){ - if(OC_Config::getValue('appstoreenabled', true)==false){ + public static function getApplications($categories,$page,$filter) { + if(OC_Config::getValue('appstoreenabled', true)==false) { return(array()); } @@ -98,10 +98,13 @@ class OC_OCSClient{ }else{ $categoriesstring=$categories; } - $url=OC_OCSClient::getAppStoreURL().'/content/data?categories='.urlencode($categoriesstring).'&sortmode=new&page='.urlencode($page).'&pagesize=100'; + + $version='&version='.implode('x',\OC_Util::getVersion()); + $filterurl='&filter='.urlencode($filter); + $url=OC_OCSClient::getAppStoreURL().'/content/data?categories='.urlencode($categoriesstring).'&sortmode=new&page='.urlencode($page).'&pagesize=100'.$filterurl.$version; $apps=array(); $xml=@file_get_contents($url); - if($xml==FALSE){ + if($xml==FALSE) { return NULL; } $data=simplexml_load_string($xml); @@ -132,14 +135,14 @@ class OC_OCSClient{ * * This function returns an applications from the OCS server */ - public static function getApplication($id){ - if(OC_Config::getValue('appstoreenabled', true)==false){ + public static function getApplication($id) { + if(OC_Config::getValue('appstoreenabled', true)==false) { return NULL; } $url=OC_OCSClient::getAppStoreURL().'/content/data/'.urlencode($id); $xml=@file_get_contents($url); - if($xml==FALSE){ + if($xml==FALSE) { OC_Log::write('core','Unable to parse OCS content',OC_Log::FATAL); return NULL; } @@ -169,14 +172,14 @@ class OC_OCSClient{ * * This function returns an download url for an applications from the OCS server */ - public static function getApplicationDownload($id,$item){ - if(OC_Config::getValue('appstoreenabled', true)==false){ + public static function getApplicationDownload($id,$item) { + if(OC_Config::getValue('appstoreenabled', true)==false) { return NULL; } $url=OC_OCSClient::getAppStoreURL().'/content/download/'.urlencode($id).'/'.urlencode($item); $xml=@file_get_contents($url); - if($xml==FALSE){ + if($xml==FALSE) { OC_Log::write('core','Unable to parse OCS content',OC_Log::FATAL); return NULL; } @@ -199,8 +202,8 @@ class OC_OCSClient{ * * This function returns a list of all the knowledgebase entries from the OCS server */ - public static function getKnownledgebaseEntries($page,$pagesize,$search=''){ - if(OC_Config::getValue('knowledgebaseenabled', true)==false){ + public static function getKnownledgebaseEntries($page,$pagesize,$search='') { + if(OC_Config::getValue('knowledgebaseenabled', true)==false) { $kbe=array(); $kbe['totalitems']=0; return $kbe; @@ -213,7 +216,7 @@ class OC_OCSClient{ $kbe=array(); $xml=@file_get_contents($url); - if($xml==FALSE){ + if($xml==FALSE) { OC_Log::write('core','Unable to parse knowledgebase content',OC_Log::FATAL); return NULL; } diff --git a/lib/preferences.php b/lib/preferences.php index de5747fcccc..3d61887785c 100644 --- a/lib/preferences.php +++ b/lib/preferences.php @@ -45,13 +45,13 @@ class OC_Preferences{ * This function returns a list of all users that have at least one entry * in the preferences table. */ - public static function getUsers(){ + public static function getUsers() { // No need for more comments $query = OC_DB::prepare( 'SELECT DISTINCT( `userid` ) FROM `*PREFIX*preferences`' ); $result = $query->execute(); $users = array(); - while( $row = $result->fetchRow()){ + while( $row = $result->fetchRow()) { $users[] = $row["userid"]; } @@ -66,13 +66,13 @@ class OC_Preferences{ * This function returns a list of all apps of the user that have at least * one entry in the preferences table. */ - public static function getApps( $user ){ + public static function getApps( $user ) { // No need for more comments $query = OC_DB::prepare( 'SELECT DISTINCT( `appid` ) FROM `*PREFIX*preferences` WHERE `userid` = ?' ); $result = $query->execute( array( $user )); $apps = array(); - while( $row = $result->fetchRow()){ + while( $row = $result->fetchRow()) { $apps[] = $row["appid"]; } @@ -88,13 +88,13 @@ class OC_Preferences{ * This function gets all keys of an app of an user. Please note that the * values are not returned. */ - public static function getKeys( $user, $app ){ + public static function getKeys( $user, $app ) { // No need for more comments $query = OC_DB::prepare( 'SELECT `configkey` FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid` = ?' ); $result = $query->execute( array( $user, $app )); $keys = array(); - while( $row = $result->fetchRow()){ + while( $row = $result->fetchRow()) { $keys[] = $row["configkey"]; } @@ -112,13 +112,13 @@ class OC_Preferences{ * This function gets a value from the prefernces table. If the key does * not exist the default value will be returnes */ - public static function getValue( $user, $app, $key, $default = null ){ + public static function getValue( $user, $app, $key, $default = null ) { // Try to fetch the value, return default if not exists. $query = OC_DB::prepare( 'SELECT `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?' ); $result = $query->execute( array( $user, $app, $key )); $row = $result->fetchRow(); - if($row){ + if($row) { return $row["configvalue"]; }else{ return $default; @@ -136,13 +136,13 @@ class OC_Preferences{ * Adds a value to the preferences. If the key did not exist before, it * will be added automagically. */ - public static function setValue( $user, $app, $key, $value ){ + public static function setValue( $user, $app, $key, $value ) { // Check if the key does exist $query = OC_DB::prepare( 'SELECT `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?' ); $values=$query->execute(array($user,$app,$key))->fetchAll(); $exists=(count($values)>0); - if( !$exists ){ + if( !$exists ) { $query = OC_DB::prepare( 'INSERT INTO `*PREFIX*preferences` ( `userid`, `appid`, `configkey`, `configvalue` ) VALUES( ?, ?, ?, ? )' ); $query->execute( array( $user, $app, $key, $value )); } @@ -162,7 +162,7 @@ class OC_Preferences{ * * Deletes a key. */ - public static function deleteKey( $user, $app, $key ){ + public static function deleteKey( $user, $app, $key ) { // No need for more comments $query = OC_DB::prepare( 'DELETE FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?' ); $result = $query->execute( array( $user, $app, $key )); @@ -178,7 +178,7 @@ class OC_Preferences{ * * Removes all keys in appconfig belonging to the app and the user. */ - public static function deleteApp( $user, $app ){ + public static function deleteApp( $user, $app ) { // No need for more comments $query = OC_DB::prepare( 'DELETE FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid` = ?' ); $result = $query->execute( array( $user, $app )); @@ -193,7 +193,7 @@ class OC_Preferences{ * * Removes all keys in appconfig belonging to the user. */ - public static function deleteUser( $user ){ + public static function deleteUser( $user ) { // No need for more comments $query = OC_DB::prepare( 'DELETE FROM `*PREFIX*preferences` WHERE `userid` = ?' ); $result = $query->execute( array( $user )); @@ -208,7 +208,7 @@ class OC_Preferences{ * * Removes all keys in preferences belonging to the app. */ - public static function deleteAppFromAllUsers( $app ){ + public static function deleteAppFromAllUsers( $app ) { // No need for more comments $query = OC_DB::prepare( 'DELETE FROM `*PREFIX*preferences` WHERE `appid` = ?' ); $result = $query->execute( array( $app )); diff --git a/lib/public/app.php b/lib/public/app.php index be38bbff98a..eb824f043e9 100644 --- a/lib/public/app.php +++ b/lib/public/app.php @@ -45,7 +45,7 @@ class App { * It'll remain in our public API for compatibility reasons * */ - public static function register( $data ){ + public static function register( $data ) { return true; // don't do anything } @@ -66,7 +66,7 @@ class 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 ) { return \OC_App::addNavigationEntry( $data ); } @@ -80,7 +80,7 @@ class 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 ) { return \OC_App::setActiveNavigationEntry( $id ); } @@ -90,7 +90,7 @@ class App { * @param $app string appid * @param $page string page to be included */ - public static function registerPersonal( $app, $page ){ + public static function registerPersonal( $app, $page ) { return \OC_App::registerPersonal( $app, $page ); } @@ -100,7 +100,7 @@ class App { * @param $app string appid * @param $page string page to be included */ - public static function registerAdmin( $app, $page ){ + public static function registerAdmin( $app, $page ) { return \OC_App::registerAdmin( $app, $page ); } @@ -111,7 +111,7 @@ class App { * @param boolean path (optional) * @returns array */ - public static function getAppInfo( $app, $path=false ){ + public static function getAppInfo( $app, $path=false ) { return \OC_App::getAppInfo( $app, $path); } @@ -124,7 +124,7 @@ class App { * * This function checks whether or not an app is enabled. */ - public static function isEnabled( $app ){ + public static function isEnabled( $app ) { return \OC_App::isEnabled( $app ); } @@ -134,7 +134,7 @@ class App { * @param $app app * @returns true/false */ - public static function checkAppEnabled( $app ){ + public static function checkAppEnabled( $app ) { return \OC_Util::checkAppEnabled( $app ); } @@ -144,7 +144,7 @@ class App { * @param $app app * @returns true/false */ - public static function getAppVersion( $app ){ + public static function getAppVersion( $app ) { return \OC_App::getAppVersion( $app ); } diff --git a/lib/public/backgroundjob.php b/lib/public/backgroundjob.php index 2962346dbc9..aba7d2b7620 100644 --- a/lib/public/backgroundjob.php +++ b/lib/public/backgroundjob.php @@ -52,7 +52,7 @@ class BackgroundJob { * @param $method method name * @return true */ - public static function addRegularTask( $klass, $method ){ + public static function addRegularTask( $klass, $method ) { return \OC_BackgroundJob_RegularTask::register( $klass, $method ); } @@ -62,7 +62,7 @@ class BackgroundJob { * * key is string "$klass-$method", value is array( $klass, $method ) */ - static public function allRegularTasks(){ + static public function allRegularTasks() { return \OC_BackgroundJob_RegularTask::all(); } @@ -71,7 +71,7 @@ class BackgroundJob { * @param $id ID of the task * @return associative array */ - public static function findQueuedTask( $id ){ + public static function findQueuedTask( $id ) { return \OC_BackgroundJob_QueuedTask::find( $id ); } @@ -79,7 +79,7 @@ class BackgroundJob { * @brief Gets all queued tasks * @return array with associative arrays */ - public static function allQueuedTasks(){ + public static function allQueuedTasks() { return \OC_BackgroundJob_QueuedTask::all(); } @@ -88,7 +88,7 @@ class BackgroundJob { * @param $app app name * @return array with associative arrays */ - public static function queuedTaskWhereAppIs( $app ){ + public static function queuedTaskWhereAppIs( $app ) { return \OC_BackgroundJob_QueuedTask::whereAppIs( $app ); } @@ -100,7 +100,7 @@ class BackgroundJob { * @param $parameters all useful data as text * @return id of task */ - public static function addQueuedTask( $app, $klass, $method, $parameters ){ + public static function addQueuedTask( $app, $klass, $method, $parameters ) { return \OC_BackgroundJob_QueuedTask::add( $app, $klass, $method, $parameters ); } @@ -111,7 +111,7 @@ class BackgroundJob { * * Deletes a report */ - public static function deleteQueuedTask( $id ){ + public static function deleteQueuedTask( $id ) { return \OC_BackgroundJob_QueuedTask::delete( $id ); } } diff --git a/lib/public/config.php b/lib/public/config.php index f3120b9aaa2..fa9658e7288 100644 --- a/lib/public/config.php +++ b/lib/public/config.php @@ -49,7 +49,7 @@ class Config { * This function gets the value from config.php. If it does not exist, * $default will be returned. */ - public static function getSystemValue( $key, $default = null ){ + public static function getSystemValue( $key, $default = null ) { return(\OC_Config::getValue( $key, $default )); } @@ -63,7 +63,7 @@ class 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 setSystemValue( $key, $value ){ + public static function setSystemValue( $key, $value ) { return(\OC_Config::setValue( $key, $value )); } @@ -78,7 +78,7 @@ class Config { * This function gets a value from the appconfig table. If the key does * not exist the default value will be returnes */ - public static function getAppValue( $app, $key, $default = null ){ + public static function getAppValue( $app, $key, $default = null ) { return(\OC_Appconfig::getValue( $app, $key, $default )); } @@ -92,7 +92,7 @@ class Config { * * Sets a value. If the key did not exist before it will be created. */ - public static function setAppValue( $app, $key, $value ){ + public static function setAppValue( $app, $key, $value ) { return(\OC_Appconfig::setValue( $app, $key, $value )); } @@ -108,7 +108,7 @@ class Config { * This function gets a value from the prefernces table. If the key does * not exist the default value will be returnes */ - public static function getUserValue( $user, $app, $key, $default = null ){ + public static function getUserValue( $user, $app, $key, $default = null ) { return(\OC_Preferences::getValue( $user, $app, $key, $default )); } @@ -124,7 +124,7 @@ class Config { * Adds a value to the preferences. If the key did not exist before, it * will be added automagically. */ - public static function setUserValue( $user, $app, $key, $value ){ + public static function setUserValue( $user, $app, $key, $value ) { return(\OC_Preferences::setValue( $user, $app, $key, $value )); } diff --git a/lib/public/db.php b/lib/public/db.php index e1da62e2d27..5ac356bb475 100644 --- a/lib/public/db.php +++ b/lib/public/db.php @@ -43,7 +43,7 @@ class 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 ) { return(\OC_DB::prepare($query,$limit,$offset)); } @@ -58,7 +58,7 @@ class 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) { return(\OC_DB::insertid($table)); } @@ -66,7 +66,7 @@ class DB { /** * @brief Start a transaction */ - public static function beginTransaction(){ + public static function beginTransaction() { return(\OC_DB::beginTransaction()); } @@ -74,7 +74,7 @@ class DB { /** * @brief Commit the database changes done during a transaction that is in progress */ - public static function commit(){ + public static function commit() { return(\OC_DB::commit()); } @@ -84,7 +84,7 @@ class DB { * @param mixed $result * @return bool */ - public static function isError($result){ + public static function isError($result) { return(\OC_DB::isError($result)); } diff --git a/lib/public/files.php b/lib/public/files.php index be5952d362a..2f4f459bd91 100644 --- a/lib/public/files.php +++ b/lib/public/files.php @@ -52,7 +52,7 @@ class Files { * @return string * does NOT work for ownClouds filesystem, use OC_FileSystem::getMimeType instead */ - static function getMimeType( $path ){ + static function getMimeType( $path ) { return(\OC_Helper::getMimeType( $path )); } @@ -63,7 +63,7 @@ class Files { * @param resource target * @return int the number of bytes copied */ - public static function streamCopy( $source, $target ){ + public static function streamCopy( $source, $target ) { return(\OC_Helper::streamCopy( $source, $target )); } @@ -75,7 +75,7 @@ class Files { * * temporary files are automatically cleaned up after the script is finished */ - public static function tmpFile( $postfix='' ){ + public static function tmpFile( $postfix='' ) { return(\OC_Helper::tmpFile( $postfix )); } @@ -86,7 +86,7 @@ class Files { * * temporary files are automatically cleaned up after the script is finished */ - public static function tmpFolder(){ + public static function tmpFolder() { return(\OC_Helper::tmpFolder()); } @@ -98,7 +98,7 @@ class Files { * @param $filename * @return string */ - public static function buildNotExistingFileName( $path, $filename ){ + public static function buildNotExistingFileName( $path, $filename ) { return(\OC_Helper::buildNotExistingFileName( $path, $filename )); } @@ -107,7 +107,7 @@ class Files { * @param $app app * @return OC_FilesystemView */ - public static function getStorage( $app ){ + public static function getStorage( $app ) { return \OC_App::getStorage( $app ); } diff --git a/lib/public/json.php b/lib/public/json.php index c37b42c3f74..93be920c6d7 100644 --- a/lib/public/json.php +++ b/lib/public/json.php @@ -41,7 +41,7 @@ class JSON { * @param string $setContentType the optional content type * @return string json formatted string. */ - public static function encodedPrint( $data, $setContentType=true ){ + public static function encodedPrint( $data, $setContentType=true ) { return(\OC_JSON::encodedPrint( $data, $setContentType )); } @@ -60,7 +60,7 @@ class JSON { * * @return string json formatted error string if not authenticated. */ - public static function checkLoggedIn(){ + public static function checkLoggedIn() { return(\OC_JSON::checkLoggedIn()); } @@ -84,7 +84,7 @@ class JSON { * * @return string json formatted error string if not valid. */ - public static function callCheck(){ + public static function callCheck() { return(\OC_JSON::callCheck()); } @@ -97,7 +97,7 @@ class JSON { * @param array $data The data to use * @return string json formatted string. */ - public static function success( $data = array() ){ + public static function success( $data = array() ) { return(\OC_JSON::success( $data )); } @@ -119,7 +119,7 @@ class JSON { * @param array $data The data to use * @return string json formatted error string. */ - public static function error( $data = array() ){ + public static function error( $data = array() ) { return(\OC_JSON::error( $data )); } @@ -128,7 +128,7 @@ class JSON { * @param array $type The contwnt type header * @return string json formatted string. */ - public static function setContentTypeHeader( $type='application/json' ){ + public static function setContentTypeHeader( $type='application/json' ) { return(\OC_JSON::setContentTypeHeader( $type )); } @@ -148,7 +148,7 @@ class JSON { * @param string $app The app to check * @return string json formatted string if not enabled. */ - public static function checkAppEnabled( $app ){ + public static function checkAppEnabled( $app ) { return(\OC_JSON::checkAppEnabled( $app )); } @@ -167,7 +167,7 @@ class JSON { * * @return string json formatted string if not admin user. */ - public static function checkAdminUser(){ + public static function checkAdminUser() { return(\OC_JSON::checkAdminUser()); } diff --git a/lib/public/share.php b/lib/public/share.php index 9ad0f0f68f6..cf61681424f 100644 --- a/lib/public/share.php +++ b/lib/public/share.php @@ -23,6 +23,7 @@ namespace OCP; \OC_Hook::connect('OC_User', 'post_deleteUser', 'OCP\Share', 'post_deleteUser'); \OC_Hook::connect('OC_User', 'post_addToGroup', 'OCP\Share', 'post_addToGroup'); \OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OCP\Share', 'post_removeFromGroup'); +\OC_Hook::connect('OC_User', 'post_deleteGroup', 'OCP\Share', 'post_deleteGroup'); /** * This class provides the ability for apps to share their content between users. @@ -339,7 +340,7 @@ class Share { // TODO } // Delete - return self::delete($item['id'], true); + return self::delete($item['id']); } return false; } @@ -357,7 +358,7 @@ class Share { if ($item = self::getItems($itemType, $itemSource, $shareType, $shareWith, \OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) { // Check if this item is a reshare and verify that the permissions granted don't exceed the parent shared item if (isset($item['parent'])) { - $query = \OC_DB::prepare('SELECT `permissions` FROM `*PREFIX*share` WHERE `id` = ?',1); + $query = \OC_DB::prepare('SELECT `permissions` FROM `*PREFIX*share` WHERE `id` = ?', 1); $result = $query->execute(array($item['parent']))->fetchRow(); if (~(int)$result['permissions'] & $permissions) { $message = 'Setting permissions for '.$itemSource.' failed, because the permissions exceed permissions granted to '.\OC_User::getUser(); @@ -563,6 +564,7 @@ class Share { } else { if ($itemType == 'file' || $itemType == 'folder') { $where .= ' `file_target` = ?'; + $item = \OC_Filesystem::normalizePath($item); } else { $where .= ' `item_target` = ?'; } @@ -762,9 +764,9 @@ class Share { // TODO Don't check if inside folder $parent = $checkReshare['id']; $itemSource = $checkReshare['item_source']; - // TODO Suggest item/file target - $suggestedItemTarget = $checkReshare['item_target']; $fileSource = $checkReshare['file_source']; + $suggestedItemTarget = $checkReshare['item_target']; + $suggestedFileTarget = $checkReshare['file_target']; $filePath = $checkReshare['file_target']; } } else { @@ -774,6 +776,8 @@ class Share { } } else { $parent = null; + $suggestedItemTarget = null; + $suggestedFileTarget = null; if (!$backend->isValidSource($itemSource, $uidOwner)) { $message = 'Sharing '.$itemSource.' failed, because the sharing backend for '.$itemType.' could not find its source'; \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); @@ -782,7 +786,7 @@ class Share { $parent = null; if ($backend instanceof Share_Backend_File_Dependent) { $filePath = $backend->getFilePath($itemSource, $uidOwner); - if ($itemType == 'file' && $itemType == 'folder') { + if ($itemType == 'file' || $itemType == 'folder') { $fileSource = $itemSource; } else { $fileSource = \OC_FileCache::getId($filePath); @@ -800,35 +804,34 @@ class Share { $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (`item_type`, `item_source`, `item_target`, `parent`, `share_type`, `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`) VALUES (?,?,?,?,?,?,?,?,?,?,?)'); // Share with a group if ($shareType == self::SHARE_TYPE_GROUP) { + $groupItemTarget = self::generateTarget($itemType, $itemSource, $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget); if (isset($fileSource)) { if ($parentFolder) { if ($parentFolder === true) { - $groupFileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith['group'], $uidOwner); + $groupFileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith['group'], $uidOwner, $suggestedFileTarget); // Set group default file target for future use $parentFolders[0]['folder'] = $groupFileTarget; } else { // Get group default file target $groupFileTarget = $parentFolder[0]['folder'].$itemSource; $parent = $parentFolder[0]['id']; - unset($parentFolder[0]); - // Only loop through users we know have different file target paths - $uidSharedWith = array_keys($parentFolder); } } else { - $groupFileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith['group'], $uidOwner); + $groupFileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith['group'], $uidOwner, $suggestedFileTarget); } } else { $groupFileTarget = null; } - $groupItemTarget = self::generateTarget($itemType, $itemSource, $shareType, $shareWith['group'], $uidOwner); - $uniqueTargets = array(); + $query->execute(array($itemType, $itemSource, $groupItemTarget, $parent, $shareType, $shareWith['group'], $uidOwner, $permissions, time(), $fileSource, $groupFileTarget)); + // Save this id, any extra rows for this group share will need to reference it + $parent = \OC_DB::insertid('*PREFIX*share'); // Loop through all users of this group in case we need to add an extra row foreach ($shareWith['users'] as $uid) { - $itemTarget = self::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $uid, $uidOwner); + $itemTarget = self::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $uid, $uidOwner, $suggestedItemTarget, $parent); if (isset($fileSource)) { if ($parentFolder) { if ($parentFolder === true) { - $fileTarget = self::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $uid, $uidOwner); + $fileTarget = self::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $uid, $uidOwner, $suggestedFileTarget, $parent); if ($fileTarget != $groupFileTarget) { $parentFolders[$uid]['folder'] = $fileTarget; } @@ -837,24 +840,14 @@ class Share { $parent = $parentFolder[$uid]['id']; } } else { - $fileTarget = self::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $uid, $uidOwner); + $fileTarget = self::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $uid, $uidOwner, $suggestedFileTarget, $parent); } } else { $fileTarget = null; } // Insert an extra row for the group share if the item or file target is unique for this user if ($itemTarget != $groupItemTarget || (isset($fileSource) && $fileTarget != $groupFileTarget)) { - $uniqueTargets[] = array('uid' => $uid, 'item_target' => $itemTarget, 'file_target' => $fileTarget); - } - } - $query->execute(array($itemType, $itemSource, $groupItemTarget, $parent, $shareType, $shareWith['group'], $uidOwner, $permissions, time(), $fileSource, $groupFileTarget)); - // Save this id, any extra rows for this group share will need to reference it - $parent = \OC_DB::insertid('*PREFIX*share'); - foreach ($uniqueTargets as $unique) { - $query->execute(array($itemType, $itemSource, $unique['item_target'], $parent, self::$shareTypeGroupUserUnique, $unique['uid'], $uidOwner, $permissions, time(), $fileSource, $unique['file_target'])); - $id = \OC_DB::insertid('*PREFIX*share'); - if ($parentFolder === true) { - $parentFolders['id'] = $id; + $query->execute(array($itemType, $itemSource, $itemTarget, $parent, self::$shareTypeGroupUserUnique, $uid, $uidOwner, $permissions, time(), $fileSource, $fileTarget)); } } if ($parentFolder === true) { @@ -862,18 +855,18 @@ class Share { return $parentFolders; } } else { - $itemTarget = self::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner); + $itemTarget = self::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedItemTarget); if (isset($fileSource)) { if ($parentFolder) { if ($parentFolder === true) { - $fileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith, $uidOwner); + $fileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith, $uidOwner, $suggestedFileTarget); $parentFolders['folder'] = $fileTarget; } else { $fileTarget = $parentFolder['folder'].$itemSource; $parent = $parentFolder['id']; } } else { - $fileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith, $uidOwner); + $fileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith, $uidOwner, $suggestedFileTarget); } } else { $fileTarget = null; @@ -895,14 +888,16 @@ class Share { * @param string Item source * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK * @param string User or group the item is being shared with + * @param string The suggested target originating from a reshare (optional) + * @param int The id of the parent group share (optional) * @return string Item target - * - * TODO Use a suggested item target by default - * */ - private static function generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner) { + private static function generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedTarget = null, $groupParent = null) { $backend = self::getBackend($itemType); if ($shareType == self::SHARE_TYPE_LINK) { + if (isset($suggestedTarget)) { + return $suggestedTarget; + } return $backend->generateTarget($itemSource, false); } else { if ($itemType == 'file' || $itemType == 'folder') { @@ -920,19 +915,35 @@ class Share { $exclude = null; // Backend has 3 opportunities to generate a unique target for ($i = 0; $i < 2; $i++) { - if ($shareType == self::SHARE_TYPE_GROUP) { - $target = $backend->generateTarget($itemSource, false, $exclude); + // Check if suggested target exists first + if ($i == 0 && isset($suggestedTarget)) { + $target = $suggestedTarget; } else { - $target = $backend->generateTarget($itemSource, $shareWith, $exclude); - } - if (is_array($exclude) && in_array($target, $exclude)) { - break; + if ($shareType == self::SHARE_TYPE_GROUP) { + $target = $backend->generateTarget($itemSource, false, $exclude); + } else { + $target = $backend->generateTarget($itemSource, $shareWith, $exclude); + } + if (is_array($exclude) && in_array($target, $exclude)) { + break; + } } // Check if target already exists - if ($checkTarget = self::getItems($itemType, $target, $shareType, $shareWith, null, self::FORMAT_NONE, null, 1)) { - // If matching target is from the same owner, use the same target. The share type will be different so this isn't the same share. - if ($checkTarget['uid_owner'] == $uidOwner) { - return $target; + $checkTarget = self::getItems($itemType, $target, $shareType, $shareWith); + if (!empty($checkTarget)) { + foreach ($checkTarget as $item) { + // Skip item if it is the group parent row + if (isset($groupParent) && $item['id'] == $groupParent) { + if (count($checkTarget) == 1) { + return $target; + } else { + continue; + } + } + // If matching target is from the same owner, use the same target. The share type will be different so this isn't the same share. + if ($item['uid_owner'] == $uidOwner) { + return $target; + } } if (!isset($exclude)) { $exclude = array(); @@ -1023,7 +1034,27 @@ class Share { } public static function post_addToGroup($arguments) { - // TODO + // Find the group shares and check if the user needs a unique target + $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `share_type` = ? AND `share_with` = ?'); + $result = $query->execute(array(self::SHARE_TYPE_GROUP, $arguments['gid'])); + $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (`item_type`, `item_source`, `item_target`, `parent`, `share_type`, `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`) VALUES (?,?,?,?,?,?,?,?,?,?,?)'); + while ($item = $result->fetchRow()) { + if ($item['item_type'] == 'file' || $item['item_type'] == 'file') { + $itemTarget = null; + } else { + $itemTarget = self::generateTarget($item['item_type'], $item['item_source'], self::SHARE_TYPE_USER, $arguments['uid'], $item['uid_owner'], $item['item_target'], $item['id']); + } + if (isset($item['file_source'])) { + $fileTarget = self::generateTarget($item['item_type'], $item['item_source'], self::SHARE_TYPE_USER, $arguments['uid'], $item['uid_owner'], $item['file_target'], $item['id']); + } else { + $fileTarget = null; + } + // Insert an extra row for the group share if the item or file target is unique for this user + if ($itemTarget != $item['item_target'] || $fileTarget != $item['file_target']) { + $query->execute(array($item['item_type'], $item['item_source'], $itemTarget, $item['id'], self::$shareTypeGroupUserUnique, $arguments['uid'], $item['uid_owner'], $item['permissions'], $item['stime'], $item['file_source'], $fileTarget)); + \OC_DB::insertid('*PREFIX*share'); + } + } } public static function post_removeFromGroup($arguments) { @@ -1040,6 +1071,14 @@ class Share { } } + public static function post_deleteGroup($arguments) { + $query = \OC_DB::prepare('SELECT id FROM `*PREFIX*share` WHERE `share_type` = ? AND `share_with` = ?'); + $result = $query->execute(array(self::SHARE_TYPE_GROUP, $arguments['gid'])); + while ($item = $result->fetchRow()) { + self::delete($item['id']); + } + } + } /** diff --git a/lib/public/template.php b/lib/public/template.php index 11c740d13ac..4cda3650866 100644 --- a/lib/public/template.php +++ b/lib/public/template.php @@ -39,7 +39,7 @@ namespace OCP; * * For further information have a look at OC_Helper::imagePath */ -function image_path( $app, $image ){ +function image_path( $app, $image ) { return(\image_path( $app, $image )); } @@ -50,7 +50,7 @@ function image_path( $app, $image ){ * @param $mimetype mimetype * @returns link to the image */ -function mimetype_icon( $mimetype ){ +function mimetype_icon( $mimetype ) { return(\mimetype_icon( $mimetype )); } @@ -61,7 +61,7 @@ function mimetype_icon( $mimetype ){ * @param $bytes size in bytes * @returns size as string */ -function human_file_size( $bytes ){ +function human_file_size( $bytes ) { return(\human_file_size( $bytes )); } diff --git a/lib/public/user.php b/lib/public/user.php index 6228268d75b..b530321f21d 100644 --- a/lib/public/user.php +++ b/lib/public/user.php @@ -40,7 +40,7 @@ class User { * @brief get the user id of the user currently logged in. * @return string uid or false */ - public static function getUser(){ + public static function getUser() { return \OC_USER::getUser(); } @@ -51,7 +51,7 @@ class User { * * Get a list of all users. */ - public static function getUsers($search = '', $limit = -1, $offset = 0) { + public static function getUsers($search = '', $limit = null, $offset = null) { return \OC_USER::getUsers(); } @@ -62,7 +62,7 @@ class User { * * Checks if the user is logged in */ - public static function isLoggedIn(){ + public static function isLoggedIn() { return \OC_USER::isLoggedIn(); } @@ -72,7 +72,7 @@ class User { * @param string $uid the username * @return boolean */ - public static function userExists( $uid ){ + public static function userExists( $uid ) { return \OC_USER::userExists( $uid ); } @@ -83,7 +83,7 @@ class User { * * Logout, destroys session */ - public static function logout(){ + public static function logout() { return \OC_USER::logout(); } @@ -96,7 +96,7 @@ class User { * * Check if the password is correct without logging in the user */ - public static function checkPassword( $uid, $password ){ + public static function checkPassword( $uid, $password ) { return \OC_USER::checkPassword( $uid, $password ); } @@ -104,7 +104,7 @@ class User { /** * Check if the user is a admin, redirects to home if not */ - public static function checkAdminUser(){ + public static function checkAdminUser() { \OC_Util::checkAdminUser(); } @@ -113,7 +113,7 @@ class User { * Check if the user is logged in, redirects to home if not. With * redirect URL parameter to the request URI. */ - public static function checkLoggedIn(){ + public static function checkLoggedIn() { \OC_Util::checkLoggedIn(); } diff --git a/lib/public/util.php b/lib/public/util.php index 6ad578441e2..ed23521b040 100644 --- a/lib/public/util.php +++ b/lib/public/util.php @@ -48,7 +48,7 @@ class Util { * @brief get the current installed version of ownCloud * @return array */ - public static function getVersion(){ + public static function getVersion() { return(\OC_Util::getVersion()); } @@ -85,7 +85,7 @@ class Util { * @brief add a css file * @param url $url */ - public static function addStyle( $application, $file = null ){ + public static function addStyle( $application, $file = null ) { \OC_Util::addStyle( $application, $file ); } @@ -95,7 +95,7 @@ class Util { * @param appid $application * @param filename $file */ - public static function addScript( $application, $file = null ){ + public static function addScript( $application, $file = null ) { \OC_Util::addScript( $application, $file ); } @@ -105,7 +105,7 @@ class Util { * @param array $attributes array of attributes for the element * @param string $text the text content for the element */ - public static function addHeader( $tag, $attributes, $text=''){ + public static function addHeader( $tag, $attributes, $text='') { \OC_Util::addHeader( $tag, $attributes, $text ); } @@ -114,7 +114,7 @@ class Util { * @param int timestamp $timestamp * @param bool dateOnly option to ommit time from the result */ - public static function formatDate( $timestamp,$dateOnly=false){ + public static function formatDate( $timestamp,$dateOnly=false) { return(\OC_Util::formatDate( $timestamp,$dateOnly )); } @@ -124,12 +124,13 @@ class Util { * @brief Creates an absolute url * @param $app app * @param $file file + * @param $args array with param=>value, will be appended to the returned url * @returns the url * * Returns a absolute url to the given app and file. */ - public static function linkToAbsolute( $app, $file ) { - return(\OC_Helper::linkToAbsolute( $app, $file )); + public static function linkToAbsolute( $app, $file, $args = array() ) { + return(\OC_Helper::linkToAbsolute( $app, $file, $args )); } @@ -160,12 +161,13 @@ class Util { * @brief Creates an url * @param $app app * @param $file file + * @param $args array with param=>value, will be appended to the returned url * @returns the url * * Returns a url to the given app and file. */ - public static function linkTo( $app, $file ){ - return(\OC_Helper::linkTo( $app, $file )); + public static function linkTo( $app, $file, $args = array() ) { + return(\OC_Helper::linkTo( $app, $file, $args )); } /** @@ -197,7 +199,7 @@ class Util { * * Returns the path to the image. */ - public static function imagePath( $app, $image ){ + public static function imagePath( $app, $image ) { return(\OC_Helper::imagePath( $app, $image )); } @@ -209,7 +211,7 @@ class Util { * * Makes 2048 to 2 kB. */ - public static function humanFileSize( $bytes ){ + public static function humanFileSize( $bytes ) { return(\OC_Helper::humanFileSize( $bytes )); } @@ -222,7 +224,7 @@ class Util { * * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418 */ - public static function computerFileSize( $str ){ + public static function computerFileSize( $str ) { return(\OC_Helper::computerFileSize( $str )); } @@ -238,7 +240,7 @@ class Util { * * TODO: write example */ - static public function connectHook( $signalclass, $signalname, $slotclass, $slotname ){ + static public function connectHook( $signalclass, $signalname, $slotclass, $slotname ) { return(\OC_Hook::connect( $signalclass, $signalname, $slotclass, $slotname )); } @@ -254,7 +256,7 @@ class Util { * * TODO: write example */ - static public function emitHook( $signalclass, $signalname, $params = array()){ + static public function emitHook( $signalclass, $signalname, $params = array()) { return(\OC_Hook::emit( $signalclass, $signalname, $params )); } @@ -263,7 +265,7 @@ class Util { * Register an get/post call. This is important to prevent CSRF attacks * TODO: write example */ - public static function callRegister(){ + public static function callRegister() { return(\OC_Util::callRegister()); } @@ -272,7 +274,7 @@ class Util { * Check an ajax get/post call if the request token is valid. exit if not. * Todo: Write howto */ - public static function callCheck(){ + public static function callCheck() { return(\OC_Util::callCheck()); } @@ -284,7 +286,7 @@ class Util { * @param string or array of strings * @return array with sanitized strings or a single sinitized string, depends on the input parameter. */ - public static function sanitizeHTML( $value ){ + public static function sanitizeHTML( $value ) { return(\OC_Util::sanitizeHTML($value)); } @@ -298,7 +300,7 @@ class Util { * * */ - 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') { return(\OC_Helper::mb_array_change_key_case($input, $case, $encoding)); } diff --git a/lib/request.php b/lib/request.php index 3fe61fbddcd..87262d98625 100644 --- a/lib/request.php +++ b/lib/request.php @@ -15,7 +15,7 @@ class OC_Request { * reverse proxies */ public static function serverHost() { - if(OC::$CLI){ + if(OC::$CLI) { return 'localhost'; } if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { @@ -49,7 +49,7 @@ class OC_Request { $proto = 'http'; } } - return($proto); + return $proto; } /** @@ -57,7 +57,7 @@ class OC_Request { * @returns string Path info or false when not found */ public static function getPathInfo() { - if (array_key_exists('PATH_INFO', $_SERVER)){ + if (array_key_exists('PATH_INFO', $_SERVER)) { $path_info = $_SERVER['PATH_INFO']; }else{ $path_info = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME'])); diff --git a/lib/response.php b/lib/response.php index a75135c0176..49d79fda709 100644 --- a/lib/response.php +++ b/lib/response.php @@ -111,12 +111,13 @@ class OC_Response { if (empty($etag)) { return; } + $etag = '"'.$etag.'"'; if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { self::setStatus(self::STATUS_NOT_MODIFIED); exit; } - header('ETag: "'.$etag.'"'); + header('ETag: '.$etag); } /** diff --git a/lib/search.php b/lib/search.php index 9dfd0cf69ef..0b6ad050024 100644 --- a/lib/search.php +++ b/lib/search.php @@ -31,7 +31,7 @@ class OC_Search{ /** * remove all registered search providers */ - public static function clearProviders(){ + public static function clearProviders() { self::$providers=array(); self::$registeredProviders=array(); } @@ -40,7 +40,7 @@ class OC_Search{ * register a new search provider to be used * @param string $provider class name of a OC_Search_Provider */ - public static function registerProvider($class,$options=array()){ + public static function registerProvider($class,$options=array()) { self::$registeredProviders[]=array('class'=>$class,'options'=>$options); } @@ -49,10 +49,10 @@ class OC_Search{ * @param string query * @return array An array of OC_Search_Result's */ - public static function search($query){ + public static function search($query) { self::initProviders(); $results=array(); - foreach(self::$providers as $provider){ + foreach(self::$providers as $provider) { $results=array_merge($results, $provider->search($query)); } return $results; @@ -61,11 +61,11 @@ class OC_Search{ /** * create instances of all the registered search providers */ - private static function initProviders(){ - if(count(self::$providers)>0){ + private static function initProviders() { + if(count(self::$providers)>0) { return; } - foreach(self::$registeredProviders as $provider){ + foreach(self::$registeredProviders as $provider) { $class=$provider['class']; $options=$provider['options']; self::$providers[]=new $class($options); diff --git a/lib/search/provider.php b/lib/search/provider.php index b83c5aa61b6..b617b9c5d94 100644 --- a/lib/search/provider.php +++ b/lib/search/provider.php @@ -5,7 +5,7 @@ abstract class OC_Search_Provider { private $options; - public function __construct($options){ + public function __construct($options) { $this->options=$options; } diff --git a/lib/search/provider/file.php b/lib/search/provider/file.php index a37af495599..50e16457672 100644 --- a/lib/search/provider/file.php +++ b/lib/search/provider/file.php @@ -1,30 +1,30 @@ <?php class OC_Search_Provider_File extends OC_Search_Provider{ - function search($query){ + function search($query) { $files=OC_FileCache::search($query,true); $results=array(); - foreach($files as $fileData){ + foreach($files as $fileData) { $file=$fileData['path']; $mime=$fileData['mimetype']; - if($mime=='httpd/unix-directory'){ - $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'index.php' ).'?dir='.$file,'Files'); + if($mime=='httpd/unix-directory') { + $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'index.php', array('dir' => $file)),'Files'); }else{ $mimeBase=$fileData['mimepart']; - switch($mimeBase){ + switch($mimeBase) { case 'audio': break; case 'text': - $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'download.php' ).'?file='.$file,'Text'); + $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'download.php', array('dir' => $file) ),'Text'); break; case 'image': - $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'download.php' ).'?file='.$file,'Images'); + $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'download.php', array('dir' => $file) ),'Images'); break; default: - if($mime=='application/xml'){ - $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'download.php' ).'?file='.$file,'Text'); + if($mime=='application/xml') { + $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'download.php', array('dir' => $file) ),'Text'); }else{ - $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'download.php' ).'?file='.$file,'Files'); + $results[]=new OC_Search_Result(basename($file),'',OC_Helper::linkTo( 'files', 'download.php', array('dir' => $file) ),'Files'); } } } diff --git a/lib/search/result.php b/lib/search/result.php index cd78a5cf253..63b5cfabce6 100644 --- a/lib/search/result.php +++ b/lib/search/result.php @@ -15,7 +15,7 @@ class OC_Search_Result{ * @param string $link link for the result * @param string $type the type of result as human readable string ('File', 'Music', etc) */ - public function __construct($name,$text,$link,$type){ + public function __construct($name,$text,$link,$type) { $this->name=$name; $this->text=$text; $this->link=$link; diff --git a/lib/setup.php b/lib/setup.php index 271fe55fd70..f27254a42a4 100644 --- a/lib/setup.php +++ b/lib/setup.php @@ -74,7 +74,7 @@ class OC_Setup { $datadir = htmlspecialchars_decode($options['directory']); //use sqlite3 when available, otherise sqlite2 will be used. - if($dbtype=='sqlite' and class_exists('SQLite3')){ + if($dbtype=='sqlite' and class_exists('SQLite3')) { $dbtype='sqlite3'; } @@ -114,7 +114,7 @@ class OC_Setup { //add prefix to the mysql user name to prevent collisions $dbusername=substr('oc_'.$username,0,16); - if($dbusername!=$oldUser){ + if($dbusername!=$oldUser) { //hash the password so we don't need to store the admin config in the config file $dbpassword=md5(time().$password); @@ -128,7 +128,7 @@ class OC_Setup { self::createDatabase($dbname, $dbusername, $connection); } else { - if($dbuser!=$oldUser){ + if($dbuser!=$oldUser) { OC_Config::setValue('dbuser', $dbuser); OC_Config::setValue('dbpassword', $dbpass); } @@ -140,7 +140,7 @@ class OC_Setup { //fill the database if needed $query="select count(*) from information_schema.tables where table_schema='$dbname' AND table_name = '{$dbtableprefix}users';"; $result = mysql_query($query,$connection); - if($result){ + if($result) { $row=mysql_fetch_row($result); } if(!$result or $row[0]==0) { @@ -345,7 +345,7 @@ class OC_Setup { } else { //delete the old sqlite database first, might cause infinte loops otherwise - if(file_exists("$datadir/owncloud.db")){ + if(file_exists("$datadir/owncloud.db")) { unlink("$datadir/owncloud.db"); } //in case of sqlite, we can always fill the database diff --git a/lib/streamwrappers.php b/lib/streamwrappers.php index f502c6170bd..1e5b19a11f0 100644 --- a/lib/streamwrappers.php +++ b/lib/streamwrappers.php @@ -5,17 +5,17 @@ class OC_FakeDirStream{ private $name; private $index; - public function dir_opendir($path,$options){ + public function dir_opendir($path,$options) { $this->name=substr($path,strlen('fakedir://')); $this->index=0; - if(!isset(self::$dirs[$this->name])){ + if(!isset(self::$dirs[$this->name])) { self::$dirs[$this->name]=array(); } return true; } - public function dir_readdir(){ - if($this->index>=count(self::$dirs[$this->name])){ + public function dir_readdir() { + if($this->index>=count(self::$dirs[$this->name])) { return false; } $filename=self::$dirs[$this->name][$this->index]; @@ -222,35 +222,35 @@ class OC_CloseStreamWrapper{ private $path=''; private $source; private static $open=array(); - public function stream_open($path, $mode, $options, &$opened_path){ + public function stream_open($path, $mode, $options, &$opened_path) { $path=substr($path,strlen('close://')); $this->path=$path; $this->source=fopen($path,$mode); - if(is_resource($this->source)){ + if(is_resource($this->source)) { $this->meta=stream_get_meta_data($this->source); } self::$open[]=$path; return is_resource($this->source); } - public function stream_seek($offset, $whence=SEEK_SET){ + public function stream_seek($offset, $whence=SEEK_SET) { 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) { return fread($this->source,$count); } - public function stream_write($data){ + public function stream_write($data) { return fwrite($this->source,$data); } - 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; @@ -262,39 +262,39 @@ class OC_CloseStreamWrapper{ } } - 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); } public function url_stat($path) { $path=substr($path,strlen('close://')); - if(file_exists($path)){ + if(file_exists($path)) { return stat($path); }else{ return false; } } - public function stream_close(){ + public function stream_close() { fclose($this->source); - if(isset(self::$callBacks[$this->path])){ + if(isset(self::$callBacks[$this->path])) { call_user_func(self::$callBacks[$this->path],$this->path); } } - public function unlink($path){ + public function unlink($path) { $path=substr($path,strlen('close://')); return unlink($path); } diff --git a/lib/subadmin.php b/lib/subadmin.php index 4752492df30..363e4a97cad 100644 --- a/lib/subadmin.php +++ b/lib/subadmin.php @@ -36,7 +36,7 @@ class OC_SubAdmin{ * @param $gid gid of the group * @return boolean */ - public static function createSubAdmin($uid, $gid){ + public static function createSubAdmin($uid, $gid) { $stmt = OC_DB::prepare('INSERT INTO `*PREFIX*group_admin` (`gid`,`uid`) VALUES(?,?)'); $result = $stmt->execute(array($gid, $uid)); OC_Hook::emit( "OC_SubAdmin", "post_createSubAdmin", array( "gid" => $gid )); @@ -49,7 +49,7 @@ class OC_SubAdmin{ * @param $gid gid of the group * @return boolean */ - public static function deleteSubAdmin($uid, $gid){ + public static function deleteSubAdmin($uid, $gid) { $stmt = OC_DB::prepare('DELETE FROM `*PREFIX*group_admin` WHERE `gid` = ? AND `uid` = ?'); $result = $stmt->execute(array($gid, $uid)); OC_Hook::emit( "OC_SubAdmin", "post_deleteSubAdmin", array( "gid" => $gid )); @@ -61,11 +61,11 @@ class OC_SubAdmin{ * @param $uid uid of the SubAdmin * @return array */ - public static function getSubAdminsGroups($uid){ + public static function getSubAdminsGroups($uid) { $stmt = OC_DB::prepare('SELECT `gid` FROM `*PREFIX*group_admin` WHERE `uid` = ?'); $result = $stmt->execute(array($uid)); $gids = array(); - while($row = $result->fetchRow()){ + while($row = $result->fetchRow()) { $gids[] = $row['gid']; } return $gids; @@ -76,11 +76,11 @@ class OC_SubAdmin{ * @param $gid gid of the group * @return array */ - public static function getGroupsSubAdmins($gid){ + public static function getGroupsSubAdmins($gid) { $stmt = OC_DB::prepare('SELECT `uid` FROM `*PREFIX*group_admin` WHERE `gid` = ?'); $result = $stmt->execute(array($gid)); $uids = array(); - while($row = $result->fetchRow()){ + while($row = $result->fetchRow()) { $uids[] = $row['uid']; } return $uids; @@ -90,11 +90,11 @@ class OC_SubAdmin{ * @brief get all SubAdmins * @return array */ - public static function getAllSubAdmins(){ + public static function getAllSubAdmins() { $stmt = OC_DB::prepare('SELECT * FROM `*PREFIX*group_admin`'); $result = $stmt->execute(); $subadmins = array(); - while($row = $result->fetchRow()){ + while($row = $result->fetchRow()) { $subadmins[] = $row; } return $subadmins; @@ -106,11 +106,11 @@ class OC_SubAdmin{ * @param $gid gid of the group * @return bool */ - public static function isSubAdminofGroup($uid, $gid){ + public static function isSubAdminofGroup($uid, $gid) { $stmt = OC_DB::prepare('SELECT COUNT(*) AS `count` FROM `*PREFIX*group_admin` WHERE `uid` = ? AND `gid` = ?'); $result = $stmt->execute(array($uid, $gid)); $result = $result->fetchRow(); - if($result['count'] >= 1){ + if($result['count'] >= 1) { return true; } return false; @@ -121,11 +121,11 @@ class OC_SubAdmin{ * @param $uid uid of the subadmin * @return bool */ - public static function isSubAdmin($uid){ + public static function isSubAdmin($uid) { $stmt = OC_DB::prepare('SELECT COUNT(*) AS `count` FROM `*PREFIX*group_admin` WHERE `uid` = ?'); $result = $stmt->execute(array($uid)); $result = $result->fetchRow(); - if($result['count'] > 0){ + if($result['count'] > 0) { return true; } return false; @@ -137,16 +137,16 @@ class OC_SubAdmin{ * @param $user uid of the user * @return bool */ - public static function isUserAccessible($subadmin, $user){ - if(!self::isSubAdmin($subadmin)){ + public static function isUserAccessible($subadmin, $user) { + if(!self::isSubAdmin($subadmin)) { return false; } - if(OC_Group::inGroup($user, 'admin')){ + if(OC_Group::inGroup($user, 'admin')) { return false; } $accessiblegroups = self::getSubAdminsGroups($subadmin); - foreach($accessiblegroups as $accessiblegroup){ - if(OC_Group::inGroup($user, $accessiblegroup)){ + foreach($accessiblegroups as $accessiblegroup) { + if(OC_Group::inGroup($user, $accessiblegroup)) { return true; } } @@ -156,7 +156,7 @@ class OC_SubAdmin{ /* * @brief alias for self::isSubAdminofGroup() */ - public static function isGroupAccessible($subadmin, $group){ + public static function isGroupAccessible($subadmin, $group) { return self::isSubAdminofGroup($subadmin, $group); } @@ -165,7 +165,7 @@ class OC_SubAdmin{ * @param $parameters * @return boolean */ - public static function post_deleteUser($parameters){ + public static function post_deleteUser($parameters) { $stmt = OC_DB::prepare('DELETE FROM `*PREFIX*group_admin` WHERE `uid` = ?'); $result = $stmt->execute(array($parameters['uid'])); return true; @@ -176,7 +176,7 @@ class OC_SubAdmin{ * @param $parameters * @return boolean */ - public static function post_deleteGroup($parameters){ + public static function post_deleteGroup($parameters) { $stmt = OC_DB::prepare('DELETE FROM `*PREFIX*group_admin` WHERE `gid` = ?'); $result = $stmt->execute(array($parameters['gid'])); return true; diff --git a/lib/template.php b/lib/template.php index fe8a3c79943..8c872a2059b 100644 --- a/lib/template.php +++ b/lib/template.php @@ -25,12 +25,13 @@ * @brief make OC_Helper::linkTo available as a simple function * @param $app app * @param $file file + * @param $args array with param=>value, will be appended to the returned url * @returns link to the file * * For further information have a look at OC_Helper::linkTo */ -function link_to( $app, $file ){ - return OC_Helper::linkTo( $app, $file ); +function link_to( $app, $file, $args = array() ) { + return OC_Helper::linkTo( $app, $file, $args ); } /** @@ -41,7 +42,7 @@ function link_to( $app, $file ){ * * For further information have a look at OC_Helper::imagePath */ -function image_path( $app, $image ){ +function image_path( $app, $image ) { return OC_Helper::imagePath( $app, $image ); } @@ -52,7 +53,7 @@ function image_path( $app, $image ){ * * For further information have a look at OC_Helper::mimetypeIcon */ -function mimetype_icon( $mimetype ){ +function mimetype_icon( $mimetype ) { return OC_Helper::mimetypeIcon( $mimetype ); } @@ -63,7 +64,7 @@ function mimetype_icon( $mimetype ){ * * For further information have a look at OC_Helper::humanFileSize */ -function human_file_size( $bytes ){ +function human_file_size( $bytes ) { return OC_Helper::humanFileSize( $bytes ); } @@ -76,7 +77,7 @@ function simple_file_size($bytes) { } function relative_modified_date($timestamp) { - $l=OC_L10N::get('template'); + $l=OC_L10N::get('lib'); $timediff = time() - $timestamp; $diffminutes = round($timediff/60); $diffhours = round($diffminutes/60); @@ -98,25 +99,25 @@ function relative_modified_date($timestamp) { } function html_select_options($options, $selected, $params=array()) { - if (!is_array($selected)){ + if (!is_array($selected)) { $selected=array($selected); } - if (isset($params['combine']) && $params['combine']){ + if (isset($params['combine']) && $params['combine']) { $options = array_combine($options, $options); } $value_name = $label_name = false; - if (isset($params['value'])){ + if (isset($params['value'])) { $value_name = $params['value']; } - if (isset($params['label'])){ + if (isset($params['label'])) { $label_name = $params['label']; } $html = ''; - foreach($options as $value => $label){ - if ($value_name && is_array($label)){ + foreach($options as $value => $label) { + if ($value_name && is_array($label)) { $value = $label[$value_name]; } - if ($label_name && is_array($label)){ + if ($label_name && is_array($label)) { $label = $label[$label_name]; } $select = in_array($value, $selected) ? ' selected="selected"' : ''; @@ -149,7 +150,7 @@ class OC_Template{ * according layout. For now, renderas can be set to "guest", "user" or * "admin". */ - public function __construct( $app, $name, $renderas = "" ){ + public function __construct( $app, $name, $renderas = "" ) { // Set the private data $this->renderas = $renderas; $this->application = $app; @@ -174,14 +175,14 @@ class OC_Template{ * sidebar, just the application. Useful to use just a specific * app on the desktop in a standalone window. */ - public static function detectFormfactor(){ + public static function detectFormfactor() { // please add more useragent strings for other devices - if(isset($_SERVER['HTTP_USER_AGENT'])){ + if(isset($_SERVER['HTTP_USER_AGENT'])) { if(stripos($_SERVER['HTTP_USER_AGENT'],'ipad')>0) { $mode='tablet'; - }elseif(stripos($_SERVER['HTTP_USER_AGENT'],'iphone')>0){ + }elseif(stripos($_SERVER['HTTP_USER_AGENT'],'iphone')>0) { $mode='mobile'; - }elseif((stripos($_SERVER['HTTP_USER_AGENT'],'N9')>0) and (stripos($_SERVER['HTTP_USER_AGENT'],'nokia')>0)){ + }elseif((stripos($_SERVER['HTTP_USER_AGENT'],'N9')>0) and (stripos($_SERVER['HTTP_USER_AGENT'],'nokia')>0)) { $mode='mobile'; }else{ $mode='default'; @@ -200,11 +201,11 @@ class OC_Template{ // if the formfactor is not yet autodetected do the // autodetection now. For possible formfactors check the // detectFormfactor documentation - if(!isset($_SESSION['formfactor'])){ + if(!isset($_SESSION['formfactor'])) { $_SESSION['formfactor'] = self::detectFormfactor(); } // allow manual override via GET parameter - if(isset($_GET['formfactor'])){ + if(isset($_GET['formfactor'])) { $_SESSION['formfactor']=$_GET['formfactor']; } $formfactor=$_SESSION['formfactor']; @@ -239,9 +240,9 @@ class OC_Template{ $app = $this->application; // Check if it is a app template or not. - if( $app != "" ){ + if( $app != "" ) { // Check if the app is in the app folder or in the root - if( file_exists(OC_App::getAppPath($app)."/templates/" )){ + if( file_exists(OC_App::getAppPath($app)."/templates/" )) { // Check if the template is overwritten by the selected theme if ($this->checkPathForTemplate(OC::$SERVERROOT."/themes/$theme/apps/$app/templates/", $name, $fext)) { }elseif ($this->checkPathForTemplate(OC_App::getAppPath($app)."/templates/", $name, $fext)) { @@ -281,9 +282,9 @@ class OC_Template{ { if ($name =='') return false; $template = null; - if( is_file( $path.$name.$fext.'.php' )){ + if( is_file( $path.$name.$fext.'.php' )) { $template = $path.$name.$fext.'.php'; - }elseif( is_file( $path.$name.'.php' )){ + }elseif( is_file( $path.$name.'.php' )) { $template = $path.$name.'.php'; } if ($template) { @@ -306,7 +307,7 @@ class OC_Template{ * * If the key existed before, it will be overwritten */ - public function assign( $key, $value, $sanitizeHTML=true ){ + public function assign( $key, $value, $sanitizeHTML=true ) { if($sanitizeHTML == true) $value=OC_Util::sanitizeHTML($value); $this->vars[$key] = $value; return true; @@ -322,8 +323,8 @@ class OC_Template{ * exists, the value will be appended. It can be accessed via * $_[$key][$position] in the template. */ - public function append( $key, $value ){ - if( array_key_exists( $key, $this->vars )){ + public function append( $key, $value ) { + if( array_key_exists( $key, $this->vars )) { $this->vars[$key][] = $value; } else{ @@ -337,7 +338,7 @@ class OC_Template{ * @param array $attributes array of attrobutes for the element * @param string $text the text content for the element */ - public function addHeader( $tag, $attributes, $text=''){ + public function addHeader( $tag, $attributes, $text='') { $this->headers[]=array('tag'=>$tag,'attributes'=>$attributes,'text'=>$text); } @@ -347,9 +348,9 @@ class OC_Template{ * * This function proceeds the template and prints its output. */ - public function printPage(){ + public function printPage() { $data = $this->fetchPage(); - if( $data === false ){ + if( $data === false ) { return false; } else{ @@ -365,10 +366,10 @@ class OC_Template{ * This function proceeds the template. If $this->renderas is set, it * will produce a full page. */ - public function fetchPage(){ + public function fetchPage() { $data = $this->_fetch(); - if( $this->renderas ){ + if( $this->renderas ) { $page = new OC_TemplateLayout($this->renderas); if($this->renderas == 'user') { $page->assign('requesttoken', $this->vars['requesttoken']); @@ -376,7 +377,7 @@ class OC_Template{ // Add custom headers $page->assign('headers',$this->headers, false); - foreach(OC_Util::$headers as $header){ + foreach(OC_Util::$headers as $header) { $page->append('headers',$header); } @@ -394,7 +395,7 @@ class OC_Template{ * * Includes the template file, fetches its output */ - private function _fetch(){ + private function _fetch() { // Register the variables $_ = $this->vars; $l = $this->l10n; @@ -416,12 +417,12 @@ class OC_Template{ * Includes another template. use <?php echo $this->inc('template'); ?> to * do this. */ - public function inc( $file, $additionalparams = null ){ + public function inc( $file, $additionalparams = null ) { // $_ erstellen $_ = $this->vars; $l = $this->l10n; - if( !is_null($additionalparams)){ + if( !is_null($additionalparams)) { $_ = array_merge( $additionalparams, $this->vars ); } @@ -442,9 +443,9 @@ class OC_Template{ * @param $parameters Parameters for the template * @returns true/false */ - public static function printUserPage( $application, $name, $parameters = array() ){ + public static function printUserPage( $application, $name, $parameters = array() ) { $content = new OC_Template( $application, $name, "user" ); - foreach( $parameters as $key => $value ){ + foreach( $parameters as $key => $value ) { $content->assign( $key, $value, false ); } print $content->printPage(); @@ -457,9 +458,9 @@ class OC_Template{ * @param $parameters Parameters for the template * @returns true/false */ - public static function printAdminPage( $application, $name, $parameters = array() ){ + public static function printAdminPage( $application, $name, $parameters = array() ) { $content = new OC_Template( $application, $name, "admin" ); - foreach( $parameters as $key => $value ){ + foreach( $parameters as $key => $value ) { $content->assign( $key, $value, false ); } return $content->printPage(); @@ -472,9 +473,9 @@ class OC_Template{ * @param $parameters Parameters for the template * @returns true/false */ - public static function printGuestPage( $application, $name, $parameters = array() ){ + public static function printGuestPage( $application, $name, $parameters = array() ) { $content = new OC_Template( $application, $name, "guest" ); - foreach( $parameters as $key => $value ){ + foreach( $parameters as $key => $value ) { $content->assign( $key, $value, false ); } return $content->printPage(); diff --git a/lib/templatelayout.php b/lib/templatelayout.php index 18fd23aac95..ad013edad8c 100644 --- a/lib/templatelayout.php +++ b/lib/templatelayout.php @@ -7,13 +7,13 @@ */ class OC_TemplateLayout extends OC_Template { - public function __construct( $renderas ){ + public function __construct( $renderas ) { // Decide which page we show - if( $renderas == 'user' ){ + if( $renderas == 'user' ) { parent::__construct( 'core', 'layout.user' ); $this->assign('searchurl',OC_Helper::linkTo( 'search', 'index.php' ), false); - if(array_search(OC_APP::getCurrentApp(),array('settings','admin','help'))!==false){ + if(array_search(OC_APP::getCurrentApp(),array('settings','admin','help'))!==false) { $this->assign('bodyid','body-settings', false); }else{ $this->assign('bodyid','body-user', false); @@ -36,7 +36,7 @@ class OC_TemplateLayout extends OC_Template { } $apps_paths = array(); - foreach(OC_App::getEnabledApps() as $app){ + foreach(OC_App::getEnabledApps() as $app) { $apps_paths[$app] = OC_App::getAppWebPath($app); } $this->assign( 'apps_paths', str_replace('\\/', '/',json_encode($apps_paths)),false ); // Ugly unescape slashes waiting for better solution @@ -96,7 +96,7 @@ class OC_TemplateLayout extends OC_Template { return false; } - static public function findStylesheetFiles($styles){ + static public function findStylesheetFiles($styles) { // Read the selected theme from the config file $theme=OC_Config::getValue( 'theme' ); @@ -104,7 +104,7 @@ class OC_TemplateLayout extends OC_Template { $fext = self::getFormFactorExtension(); $files = array(); - foreach($styles as $style){ + foreach($styles as $style) { // is it in 3rdparty? if(self::appendIfExist($files, OC::$THIRDPARTYROOT, OC::$THIRDPARTYWEBROOT, $style.'.css')) { @@ -132,7 +132,7 @@ class OC_TemplateLayout extends OC_Template { } // Add the theme css files. you can override the default values here if(!empty($theme)) { - foreach($styles as $style){ + foreach($styles as $style) { if(self::appendIfExist($files, OC::$SERVERROOT, OC::$WEBROOT, "themes/$theme/apps/$style$fext.css" )) { }elseif(self::appendIfExist($files, OC::$SERVERROOT, OC::$WEBROOT, "themes/$theme/apps/$style.css" )) { @@ -147,7 +147,7 @@ class OC_TemplateLayout extends OC_Template { return $files; } - static public function findJavascriptFiles($scripts){ + static public function findJavascriptFiles($scripts) { // Read the selected theme from the config file $theme=OC_Config::getValue( 'theme' ); @@ -155,7 +155,7 @@ class OC_TemplateLayout extends OC_Template { $fext = self::getFormFactorExtension(); $files = array(); - foreach($scripts as $script){ + foreach($scripts as $script) { // Is it in 3rd party? if(self::appendIfExist($files, OC::$THIRDPARTYROOT, OC::$THIRDPARTYWEBROOT, $script.'.js')) { diff --git a/lib/updater.php b/lib/updater.php index 967f64c0b30..ad42f2bf605 100644 --- a/lib/updater.php +++ b/lib/updater.php @@ -28,7 +28,7 @@ class OC_Updater{ /** * Check if a new version is available */ - public static function check(){ + public static function check() { OC_Appconfig::setValue('core', 'lastupdatedat',microtime(true)); if(OC_Appconfig::getValue('core', 'installedat','')=='') OC_Appconfig::setValue('core', 'installedat',microtime(true)); @@ -43,7 +43,7 @@ class OC_Updater{ //fetch xml data from updater $url=$updaterurl.'?version='.$versionstring; $xml=@file_get_contents($url); - if($xml==FALSE){ + if($xml==FALSE) { return array(); } $data=@simplexml_load_string($xml); @@ -57,16 +57,18 @@ class OC_Updater{ return $tmp; } - public static function ShowUpdatingHint(){ - if(OC_Config::getValue('updatechecker', true)==true){ + public static function ShowUpdatingHint() { + $l = OC_L10N::get('lib'); + + if(OC_Config::getValue('updatechecker', true)==true) { $data=OC_Updater::check(); if(isset($data['version']) and $data['version']<>'') { - $txt='<span style="color:#AA0000; font-weight:bold;">'.$data['versionstring'].' is available. Get <a href="'.$data['web'].'">more information</a></span>'; + $txt='<span style="color:#AA0000; font-weight:bold;">'.$l->t('%s is available. Get <a href="%s">more information</a>',array($data['versionstring'], $data['web'])).'</span>'; }else{ - $txt='up to date'; + $txt=$l->t('up to date'); } }else{ - $txt='updates check is disabled'; + $txt=$l->t('updates check is disabled'); } return($txt); } @@ -75,7 +77,7 @@ class OC_Updater{ /** * do ownCloud update */ - public static function doUpdate(){ + public static function doUpdate() { //update ownCloud core diff --git a/lib/user.php b/lib/user.php index c432f6074a6..89dab9f9647 100644 --- a/lib/user.php +++ b/lib/user.php @@ -40,6 +40,8 @@ class OC_User { // The backend used for user management private static $_usedBackends = array(); + private static $_setupedBackends = array(); + // Backends available (except database) private static $_backends = array(); @@ -50,7 +52,7 @@ class OC_User { * * Makes a list of backends that can be used by other modules */ - public static function registerBackend( $backend ){ + public static function registerBackend( $backend ) { self::$_backends[] = $backend; return true; } @@ -61,7 +63,7 @@ class OC_User { * * Returns the names of all backends. */ - public static function getBackends(){ + public static function getBackends() { return self::$_backends; } @@ -71,7 +73,7 @@ class OC_User { * * Returns the names of all used backends. */ - public static function getUsedBackends(){ + public static function getUsedBackends() { return array_keys(self::$_usedBackends); } @@ -82,17 +84,17 @@ class OC_User { * * Set the User Authentication Module */ - public static function useBackend( $backend = 'database' ){ - if($backend instanceof OC_User_Interface){ + public static function useBackend( $backend = 'database' ) { + if($backend instanceof OC_User_Interface) { self::$_usedBackends[get_class($backend)]=$backend; }else{ // You'll never know what happens - if( null === $backend OR !is_string( $backend )){ + if( null === $backend OR !is_string( $backend )) { $backend = 'database'; } // Load backend - switch( $backend ){ + switch( $backend ) { case 'database': case 'mysql': case 'sqlite': @@ -110,11 +112,33 @@ class OC_User { /** * remove all used backends */ - public static function clearBackends(){ + public static function clearBackends() { self::$_usedBackends=array(); } /** + * setup the configured backends in config.php + */ + public static function setupBackends() { + $backends=OC_Config::getValue('user_backends',array()); + foreach($backends as $i=>$config) { + $class=$config['class']; + $arguments=$config['arguments']; + if(class_exists($class) and array_search($i,self::$_setupedBackends)===false) { + // make a reflection object + $reflectionObj = new ReflectionClass($class); + + // use Reflection to create a new instance, using the $args + $backend = $reflectionObj->newInstanceArgs($arguments); + self::useBackend($backend); + $_setupedBackends[]=$i; + }else{ + OC_Log::write('core','User backend '.$class.' not found.',OC_Log::ERROR); + } + } + } + + /** * @brief Create a new user * @param $uid The username of the user to create * @param $password The password of the new user @@ -125,23 +149,23 @@ class OC_User { * * Allowed characters in the username are: "a-z", "A-Z", "0-9" and "_.@-" */ - public static function createUser( $uid, $password ){ + public static function createUser( $uid, $password ) { // Check the name for bad characters // Allowed are: "a-z", "A-Z", "0-9" and "_.@-" - if( preg_match( '/[^a-zA-Z0-9 _\.@\-]/', $uid )){ + if( preg_match( '/[^a-zA-Z0-9 _\.@\-]/', $uid )) { throw new Exception('Only the following characters are allowed in a username: "a-z", "A-Z", "0-9", and "_.@-"'); } // No empty username - if(trim($uid) == ''){ + if(trim($uid) == '') { throw new Exception('A valid username must be provided'); } // No empty password - if(trim($password) == ''){ + if(trim($password) == '') { throw new Exception('A valid password must be provided'); } // Check if user already exists - if( self::userExists($uid) ){ + if( self::userExists($uid) ) { throw new Exception('The username is already being used'); } @@ -149,9 +173,9 @@ class OC_User { $run = true; OC_Hook::emit( "OC_User", "pre_createUser", array( "run" => &$run, "uid" => $uid, "password" => $password )); - if( $run ){ + if( $run ) { //create the user in the first backend that supports creating users - foreach(self::$_usedBackends as $backend){ + foreach(self::$_usedBackends as $backend) { if(!$backend->implementsActions(OC_USER_BACKEND_CREATE_USER)) continue; @@ -171,17 +195,17 @@ class OC_User { * * Deletes a user */ - public static function deleteUser( $uid ){ + public static function deleteUser( $uid ) { $run = true; OC_Hook::emit( "OC_User", "pre_deleteUser", array( "run" => &$run, "uid" => $uid )); - if( $run ){ + if( $run ) { //delete the user from all backends - foreach(self::$_usedBackends as $backend){ + foreach(self::$_usedBackends as $backend) { $backend->deleteUser($uid); } // We have to delete the user from all groups - foreach( OC_Group::getUserGroups( $uid ) as $i ){ + foreach( OC_Group::getUserGroups( $uid ) as $i ) { OC_Group::removeFromGroup( $uid, $i ); } // Delete the user's keys in preferences @@ -203,14 +227,14 @@ class OC_User { * * Log in a user and regenerate a new session - if the password is ok */ - public static function login( $uid, $password ){ + public static function login( $uid, $password ) { $run = true; OC_Hook::emit( "OC_User", "pre_login", array( "run" => &$run, "uid" => $uid )); - if( $run ){ + if( $run ) { $uid = self::checkPassword( $uid, $password ); $enabled = self::isEnabled($uid); - if($uid && $enabled){ + if($uid && $enabled) { session_regenerate_id(true); self::setUserId($uid); OC_Hook::emit( "OC_User", "post_login", array( "uid" => $uid, 'password'=>$password )); @@ -236,7 +260,7 @@ class OC_User { * * Logout, destroys session */ - public static function logout(){ + public static function logout() { OC_Hook::emit( "OC_User", "logout", array()); session_unset(); session_destroy(); @@ -250,10 +274,11 @@ class OC_User { * * Checks if the user is logged in */ - public static function isLoggedIn(){ + public static function isLoggedIn() { if( isset($_SESSION['user_id']) AND $_SESSION['user_id']) { OC_App::loadApps(array('authentication')); - if (self::userExists($_SESSION['user_id']) ){ + self::setupBackends(); + if (self::userExists($_SESSION['user_id']) ) { return true; } } @@ -264,8 +289,8 @@ class OC_User { * @brief get the user id of the user currently logged in. * @return string uid or false */ - public static function getUser(){ - if( isset($_SESSION['user_id']) AND $_SESSION['user_id'] ){ + public static function getUser() { + if( isset($_SESSION['user_id']) AND $_SESSION['user_id'] ) { return $_SESSION['user_id']; } else{ @@ -279,7 +304,7 @@ class OC_User { * * generates a password */ - public static function generatePassword(){ + public static function generatePassword() { return uniqId(); } @@ -291,15 +316,15 @@ class OC_User { * * Change the password of a user */ - public static function setPassword( $uid, $password ){ + public static function setPassword( $uid, $password ) { $run = true; OC_Hook::emit( "OC_User", "pre_setPassword", array( "run" => &$run, "uid" => $uid, "password" => $password )); - if( $run ){ + if( $run ) { $success = false; - foreach(self::$_usedBackends as $backend){ - if($backend->implementsActions(OC_USER_BACKEND_SET_PASSWORD)){ - if($backend->userExists($uid)){ + foreach(self::$_usedBackends as $backend) { + if($backend->implementsActions(OC_USER_BACKEND_SET_PASSWORD)) { + if($backend->userExists($uid)) { $success |= $backend->setPassword($uid,$password); } } @@ -321,11 +346,11 @@ class OC_User { * Check if the password is correct without logging in the user * returns the user id or false */ - public static function checkPassword( $uid, $password ){ - foreach(self::$_usedBackends as $backend){ - if($backend->implementsActions(OC_USER_BACKEND_CHECK_PASSWORD)){ + public static function checkPassword( $uid, $password ) { + foreach(self::$_usedBackends as $backend) { + if($backend->implementsActions(OC_USER_BACKEND_CHECK_PASSWORD)) { $result=$backend->checkPassword( $uid, $password ); - if($result){ + if($result) { return $result; } } @@ -341,11 +366,11 @@ class OC_User { * Check if the password is correct without logging in the user * returns the user id or false */ - public static function getHome($uid){ - foreach(self::$_usedBackends as $backend){ - if($backend->implementsActions(OC_USER_BACKEND_GET_HOME)){ + public static function getHome($uid) { + foreach(self::$_usedBackends as $backend) { + if($backend->implementsActions(OC_USER_BACKEND_GET_HOME)) { $result=$backend->getHome($uid); - if($result){ + if($result) { return $result; } } @@ -376,10 +401,10 @@ class OC_User { * @param string $uid the username * @return boolean */ - public static function userExists($uid){ - foreach(self::$_usedBackends as $backend){ + public static function userExists($uid) { + foreach(self::$_usedBackends as $backend) { $result=$backend->userExists($uid); - if($result===true){ + if($result===true) { return true; } } @@ -390,7 +415,7 @@ class OC_User { * disables a user * @param string $userid the user to disable */ - public static function disableUser($userid){ + public static function disableUser($userid) { $query = "INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, `configkey`, `configvalue`) VALUES(?, ?, ?, ?)"; $query = OC_DB::prepare($query); $query->execute(array($userid, 'core', 'enabled', 'false')); @@ -400,7 +425,7 @@ class OC_User { * enable a user * @param string $userid */ - public static function enableUser($userid){ + public static function enableUser($userid) { $query = "DELETE FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid` = ? AND `configkey` = ? AND `configvalue` = ?"; $query = OC_DB::prepare($query); $query->execute(array($userid, 'core', 'enabled', 'false')); @@ -411,7 +436,7 @@ class OC_User { * @param string $userid * @return bool */ - public static function isEnabled($userid){ + public static function isEnabled($userid) { $query = "SELECT `userid` FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid` = ? AND `configkey` = ? AND `configvalue` = ?"; $query = OC_DB::prepare($query); $results = $query->execute(array($userid, 'core', 'enabled', 'false')); @@ -422,7 +447,7 @@ class OC_User { * @brief Set cookie value to use in next page load * @param string $username username to be set */ - public static function setMagicInCookie($username, $token){ + public static function setMagicInCookie($username, $token) { $secure_cookie = OC_Config::getValue("forcessl", false); setcookie("oc_username", $username, time()+60*60*24*15, '', '', $secure_cookie); setcookie("oc_token", $token, time()+60*60*24*15, '', '', $secure_cookie); @@ -432,7 +457,7 @@ class OC_User { /** * @brief Remove cookie for "remember username" */ - public static function unsetMagicInCookie(){ + public static function unsetMagicInCookie() { unset($_COOKIE["oc_username"]); unset($_COOKIE["oc_token"]); unset($_COOKIE["oc_remember_login"]); diff --git a/lib/user/backend.php b/lib/user/backend.php index 36e4bd9f761..2a95db93690 100644 --- a/lib/user/backend.php +++ b/lib/user/backend.php @@ -59,9 +59,9 @@ abstract class OC_User_Backend implements OC_User_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; } @@ -78,7 +78,7 @@ abstract class OC_User_Backend implements OC_User_Interface { * Returns the supported actions as int to be * compared with OC_USER_BACKEND_CREATE_USER etc. */ - public function implementsActions($actions){ + public function implementsActions($actions) { return (bool)($this->getSupportedActions() & $actions); } @@ -89,7 +89,7 @@ abstract class OC_User_Backend implements OC_User_Interface { * * Deletes a user */ - public function deleteUser( $uid ){ + public function deleteUser( $uid ) { return false; } @@ -99,7 +99,7 @@ abstract class OC_User_Backend implements OC_User_Interface { * * Get a list of all users. */ - public function getUsers($search = '', $limit = -1, $offset = 0) { + public function getUsers($search = '', $limit = null, $offset = null) { return array(); } @@ -108,7 +108,7 @@ abstract class OC_User_Backend implements OC_User_Interface { * @param string $uid the username * @return boolean */ - public function userExists($uid){ + public function userExists($uid) { return false; } @@ -117,7 +117,7 @@ abstract class OC_User_Backend implements OC_User_Interface { * @param string $uid the username * @return boolean */ - public function getHome($uid){ + public function getHome($uid) { return false; } } diff --git a/lib/user/database.php b/lib/user/database.php index 52f3b35fa5c..76b44a2f6ca 100644 --- a/lib/user/database.php +++ b/lib/user/database.php @@ -44,8 +44,8 @@ class OC_User_Database extends OC_User_Backend { */ static private $hasher=null; - private function getHasher(){ - if(!self::$hasher){ + private function getHasher() { + if(!self::$hasher) { //we don't want to use DES based crypt(), since it doesn't return a has with a recognisable prefix $forcePortable=(CRYPT_BLOWFISH!=1); self::$hasher=new PasswordHash(8,$forcePortable); @@ -63,8 +63,8 @@ class OC_User_Database extends OC_User_Backend { * Creates a new user. Basic checking of username is done in OC_User * itself, not in its subclasses. */ - public function createUser( $uid, $password ){ - if( $this->userExists($uid) ){ + public function createUser( $uid, $password ) { + if( $this->userExists($uid) ) { return false; }else{ $hasher=$this->getHasher(); @@ -83,7 +83,7 @@ class OC_User_Database extends OC_User_Backend { * * Deletes a user */ - public function deleteUser( $uid ){ + public function deleteUser( $uid ) { // Delete user-group-relation $query = OC_DB::prepare( 'DELETE FROM `*PREFIX*users` WHERE uid = ?' ); $query->execute( array( $uid )); @@ -98,8 +98,8 @@ class OC_User_Database extends OC_User_Backend { * * Change the password of a user */ - public function setPassword( $uid, $password ){ - if( $this->userExists($uid) ){ + public function setPassword( $uid, $password ) { + if( $this->userExists($uid) ) { $hasher=$this->getHasher(); $hash = $hasher->HashPassword($password.OC_Config::getValue('passwordsalt', '')); $query = OC_DB::prepare( 'UPDATE `*PREFIX*users` SET `password` = ? WHERE `uid` = ?' ); @@ -120,22 +120,22 @@ class OC_User_Database extends OC_User_Backend { * Check if the password is correct without logging in the user * returns the user id or false */ - public function checkPassword( $uid, $password ){ + public function checkPassword( $uid, $password ) { $query = OC_DB::prepare( 'SELECT `uid`, `password` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)' ); $result = $query->execute( array( $uid)); $row=$result->fetchRow(); - if($row){ + if($row) { $storedHash=$row['password']; - if ($storedHash[0]=='$'){//the new phpass based hashing + if ($storedHash[0]=='$') {//the new phpass based hashing $hasher=$this->getHasher(); - if($hasher->CheckPassword($password.OC_Config::getValue('passwordsalt', ''), $storedHash)){ + if($hasher->CheckPassword($password.OC_Config::getValue('passwordsalt', ''), $storedHash)) { return $row['uid']; }else{ return false; } }else{//old sha1 based hashing - if(sha1($password)==$storedHash){ + if(sha1($password)==$storedHash) { //upgrade to new hashing $this->setPassword($row['uid'],$password); return $row['uid']; @@ -169,7 +169,7 @@ class OC_User_Database extends OC_User_Backend { * @param string $uid the username * @return boolean */ - public function userExists($uid){ + public function userExists($uid) { $query = OC_DB::prepare( 'SELECT * FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)' ); $result = $query->execute( array( $uid )); @@ -181,8 +181,8 @@ class OC_User_Database extends OC_User_Backend { * @param string $uid the username * @return boolean */ - public function getHome($uid){ - if($this->userExists($uid)){ + public function getHome($uid) { + if($this->userExists($uid)) { return OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ) . '/' . $uid; }else{ return false; diff --git a/lib/user/dummy.php b/lib/user/dummy.php index da3edfb2df4..4dbbc02b888 100644 --- a/lib/user/dummy.php +++ b/lib/user/dummy.php @@ -35,8 +35,8 @@ class OC_User_Dummy extends OC_User_Backend { * Creates a new user. Basic checking of username is done in OC_User * itself, not in its subclasses. */ - public function createUser($uid, $password){ - if(isset($this->users[$uid])){ + public function createUser($uid, $password) { + if(isset($this->users[$uid])) { return false; }else{ $this->users[$uid]=$password; @@ -51,8 +51,8 @@ class OC_User_Dummy extends OC_User_Backend { * * Deletes a user */ - public function deleteUser( $uid ){ - if(isset($this->users[$uid])){ + public function deleteUser( $uid ) { + if(isset($this->users[$uid])) { unset($this->users[$uid]); return true; }else{ @@ -68,8 +68,8 @@ class OC_User_Dummy extends OC_User_Backend { * * Change the password of a user */ - public function setPassword($uid, $password){ - if(isset($this->users[$uid])){ + public function setPassword($uid, $password) { + if(isset($this->users[$uid])) { $this->users[$uid]=$password; return true; }else{ @@ -86,8 +86,8 @@ class OC_User_Dummy extends OC_User_Backend { * Check if the password is correct without logging in the user * returns the user id or false */ - public function checkPassword($uid, $password){ - if(isset($this->users[$uid])){ + public function checkPassword($uid, $password) { + if(isset($this->users[$uid])) { return ($this->users[$uid]==$password); }else{ return false; @@ -100,7 +100,7 @@ class OC_User_Dummy extends OC_User_Backend { * * Get a list of all users. */ - public function getUsers($search = '', $limit = -1, $offset = 0) { + public function getUsers($search = '', $limit = null, $offset = null) { return array_keys($this->users); } @@ -109,7 +109,7 @@ class OC_User_Dummy extends OC_User_Backend { * @param string $uid the username * @return boolean */ - public function userExists($uid){ + public function userExists($uid) { return isset($this->users[$uid]); } } diff --git a/lib/user/http.php b/lib/user/http.php index 5149678e4ed..2668341408d 100644 --- a/lib/user/http.php +++ b/lib/user/http.php @@ -30,14 +30,14 @@ class OC_User_HTTP extends OC_User_Backend { * @param string path * @return array */ - private function parseUrl($url){ + private function parseUrl($url) { $parts=parse_url($url); $url=$parts['scheme'].'://'.$parts['host']; - if(isset($parts['port'])){ + if(isset($parts['port'])) { $url.=':'.$parts['port']; } $url.=$parts['path']; - if(isset($parts['query'])){ + if(isset($parts['query'])) { $url.='?'.$parts['query']; } return array($parts['user'],$url); @@ -49,7 +49,7 @@ class OC_User_HTTP extends OC_User_Backend { * @param string url * @return boolean */ - private function matchUrl($url){ + private function matchUrl($url) { return ! is_null(parse_url($url,PHP_URL_USER)); } @@ -62,8 +62,8 @@ class OC_User_HTTP extends OC_User_Backend { * Check if the password is correct without logging in the user * returns the user id or false */ - public function checkPassword($uid, $password){ - if(!$this->matchUrl($uid)){ + public function checkPassword($uid, $password) { + if(!$this->matchUrl($uid)) { return false; } list($user,$url)=$this->parseUrl($uid); @@ -87,7 +87,7 @@ class OC_User_HTTP extends OC_User_Backend { * @param string $uid the username * @return boolean */ - public function userExists($uid){ + public function userExists($uid) { return $this->matchUrl($uid); } @@ -96,8 +96,8 @@ class OC_User_HTTP extends OC_User_Backend { * @param string $uid the username * @return boolean */ - public function getHome($uid){ - if($this->userExists($uid)){ + public function getHome($uid) { + if($this->userExists($uid)) { return OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ) . '/' . $uid; }else{ return false; diff --git a/lib/user/interface.php b/lib/user/interface.php index a4903898fb1..3d9f4691f24 100644 --- a/lib/user/interface.php +++ b/lib/user/interface.php @@ -48,7 +48,7 @@ interface OC_User_Interface { * * Get a list of all users. */ - public function getUsers($search = '', $limit = -1, $offset = 0); + public function getUsers($search = '', $limit = null, $offset = null); /** * @brief check if a user exists diff --git a/lib/util.php b/lib/util.php index 10b88b24438..5046550d6a2 100755 --- a/lib/util.php +++ b/lib/util.php @@ -14,13 +14,13 @@ class OC_Util { public static $core_scripts=array(); // Can be set up - public static function setupFS( $user = '' ){// configure the initial filesystem based on the configuration - if(self::$fsSetup){//setting up the filesystem twice can only lead to trouble + public static function setupFS( $user = '' ) {// configure the initial filesystem based on the configuration + if(self::$fsSetup) {//setting up the filesystem twice can only lead to trouble return false; } // If we are not forced to load a specific user we load the one that is logged in - if( $user == "" && OC_User::isLoggedIn()){ + if( $user == "" && OC_User::isLoggedIn()) { $user = OC_User::getUser(); } @@ -33,16 +33,16 @@ class OC_Util { $CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); //first set up the local "root" storage - if(!self::$rootMounted){ + if(!self::$rootMounted) { OC_Filesystem::mount('OC_Filestorage_Local',array('datadir'=>$CONFIG_DATADIRECTORY),'/'); self::$rootMounted=true; } - if( $user != "" ){ //if we aren't logged in, there is no use to set up the filesystem + if( $user != "" ) { //if we aren't logged in, there is no use to set up the filesystem $user_dir = '/'.$user.'/files'; $user_root = OC_User::getHome($user); $userdirectory = $user_root . '/files'; - if( !is_dir( $userdirectory )){ + if( !is_dir( $userdirectory )) { mkdir( $userdirectory, 0755, true ); } //jail the user into his "home" directory @@ -58,12 +58,19 @@ class OC_Util { OC_Filesystem::mount($options['class'], $options['options'], $mountPoint); } } + + $mtime=filemtime($user_root.'/mount.php'); + $previousMTime=OC_Preferences::getValue($user,'files','mountconfigmtime',0); + if($mtime>$previousMTime) {//mount config has changed, filecache needs to be updated + OC_FileCache::clear($user); + OC_Preferences::setValue($user,'files','mountconfigmtime',$mtime); + } } OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $user_dir)); } } - public static function tearDownFS(){ + public static function tearDownFS() { OC_Filesystem::tearDown(); self::$fsSetup=false; } @@ -72,24 +79,24 @@ class OC_Util { * get the current installed version of ownCloud * @return array */ - public static function getVersion(){ + public static function getVersion() { // hint: We only can count up. So the internal version number of ownCloud 4.5 will be 4,9,0. This is not visible to the user - return array(4,83,5); + return array(4,83,6); } /** * get the current installed version string of ownCloud * @return string */ - public static function getVersionString(){ - return '4.5 beta 1'; + public static function getVersionString() { + return '4.5 beta 2'; } /** * get the current installed edition of ownCloud. There is the community edition that just returns an empty string and the enterprise edition that returns "Enterprise". * @return string */ - public static function getEditionString(){ + public static function getEditionString() { return ''; } @@ -99,12 +106,12 @@ class OC_Util { * @param appid $application * @param filename $file */ - public static function addScript( $application, $file = null ){ - if( is_null( $file )){ + public static function addScript( $application, $file = null ) { + if( is_null( $file )) { $file = $application; $application = ""; } - if( !empty( $application )){ + if( !empty( $application )) { self::$scripts[] = "$application/js/$file"; }else{ self::$scripts[] = "js/$file"; @@ -117,12 +124,12 @@ class OC_Util { * @param appid $application * @param filename $file */ - public static function addStyle( $application, $file = null ){ - if( is_null( $file )){ + public static function addStyle( $application, $file = null ) { + if( is_null( $file )) { $file = $application; $application = ""; } - if( !empty( $application )){ + if( !empty( $application )) { self::$styles[] = "$application/css/$file"; }else{ self::$styles[] = "css/$file"; @@ -135,7 +142,7 @@ class OC_Util { * @param array $attributes array of attributes for the element * @param string $text the text content for the element */ - public static function addHeader( $tag, $attributes, $text=''){ + public static function addHeader( $tag, $attributes, $text='') { self::$headers[]=array('tag'=>$tag,'attributes'=>$attributes,'text'=>$text); } @@ -145,8 +152,8 @@ class OC_Util { * @param int timestamp $timestamp * @param bool dateOnly option to ommit time from the result */ - public static function formatDate( $timestamp,$dateOnly=false){ - if(isset($_SESSION['timezone'])){//adjust to clients timezone if we know it + public static function formatDate( $timestamp,$dateOnly=false) { + if(isset($_SESSION['timezone'])) {//adjust to clients timezone if we know it $systemTimeZone = intval(date('O')); $systemTimeZone=(round($systemTimeZone/100,0)*60)+($systemTimeZone%100); $clientTimeZone=$_SESSION['timezone']*60; @@ -190,11 +197,11 @@ class OC_Util { * check if the current server configuration is suitable for ownCloud * @return array arrays with error messages and hints */ - public static function checkServer(){ + public static function checkServer() { $errors=array(); //check for database drivers - if(!(is_callable('sqlite_open') or class_exists('SQLite3')) and !is_callable('mysql_connect') and !is_callable('pg_connect')){ + if(!(is_callable('sqlite_open') or class_exists('SQLite3')) and !is_callable('mysql_connect') and !is_callable('pg_connect')) { $errors[]=array('error'=>'No database drivers (sqlite, mysql, or postgresql) installed.<br/>','hint'=>'');//TODO: sane hint } @@ -216,25 +223,25 @@ class OC_Util { $CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); //check for correct file permissions - if(!stristr(PHP_OS, 'WIN')){ + if(!stristr(PHP_OS, 'WIN')) { $permissionsModHint="Please change the permissions to 0770 so that the directory cannot be listed by other users."; $prems=substr(decoct(@fileperms($CONFIG_DATADIRECTORY)),-3); - if(substr($prems,-1)!='0'){ + if(substr($prems,-1)!='0') { OC_Helper::chmodr($CONFIG_DATADIRECTORY,0770); clearstatcache(); $prems=substr(decoct(@fileperms($CONFIG_DATADIRECTORY)),-3); - if(substr($prems,2,1)!='0'){ + if(substr($prems,2,1)!='0') { $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY.') is readable for other users<br/>','hint'=>$permissionsModHint); } } - if( OC_Config::getValue( "enablebackup", false )){ + if( OC_Config::getValue( "enablebackup", false )) { $CONFIG_BACKUPDIRECTORY = OC_Config::getValue( "backupdirectory", OC::$SERVERROOT."/backup" ); $prems=substr(decoct(@fileperms($CONFIG_BACKUPDIRECTORY)),-3); - if(substr($prems,-1)!='0'){ + if(substr($prems,-1)!='0') { OC_Helper::chmodr($CONFIG_BACKUPDIRECTORY,0770); clearstatcache(); $prems=substr(decoct(@fileperms($CONFIG_BACKUPDIRECTORY)),-3); - if(substr($prems,2,1)!='0'){ + if(substr($prems,2,1)!='0') { $errors[]=array('error'=>'Data directory ('.$CONFIG_BACKUPDIRECTORY.') is readable for other users<br/>','hint'=>$permissionsModHint); } } @@ -243,36 +250,39 @@ class OC_Util { //TODO: permissions checks for windows hosts } // Create root dir. - if(!is_dir($CONFIG_DATADIRECTORY)){ + if(!is_dir($CONFIG_DATADIRECTORY)) { $success=@mkdir($CONFIG_DATADIRECTORY); if(!$success) { $errors[]=array('error'=>"Can't create data directory (".$CONFIG_DATADIRECTORY.")",'hint'=>"You can usually fix this by giving the webserver write access to the ownCloud directory '".OC::$SERVERROOT."' (in a terminal, use the command 'chown -R www-data:www-data /path/to/your/owncloud/install/data' "); } - } else if(!is_writable($CONFIG_DATADIRECTORY)){ + } else if(!is_writable($CONFIG_DATADIRECTORY)) { $errors[]=array('error'=>'Data directory ('.$CONFIG_DATADIRECTORY.') not writable by ownCloud<br/>','hint'=>$permissionsHint); } // check if all required php modules are present - if(!class_exists('ZipArchive')){ + if(!class_exists('ZipArchive')) { $errors[]=array('error'=>'PHP module zip not installed.<br/>','hint'=>'Please ask your server administrator to install the module.'); } - if(!function_exists('mb_detect_encoding')){ + if(!function_exists('mb_detect_encoding')) { $errors[]=array('error'=>'PHP module mb multibyte not installed.<br/>','hint'=>'Please ask your server administrator to install the module.'); } - if(!function_exists('ctype_digit')){ + if(!function_exists('ctype_digit')) { $errors[]=array('error'=>'PHP module ctype is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.'); } - if(!function_exists('json_encode')){ + if(!function_exists('json_encode')) { $errors[]=array('error'=>'PHP module JSON is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.'); } - if(!function_exists('imagepng')){ + if(!function_exists('imagepng')) { $errors[]=array('error'=>'PHP module GD is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.'); } - if(floatval(phpversion())<5.3){ + if(!function_exists('gzencode')) { + $errors[]=array('error'=>'PHP module zlib is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.'); + } + if(floatval(phpversion())<5.3) { $errors[]=array('error'=>'PHP 5.3 is required.<br/>','hint'=>'Please ask your server administrator to update PHP to version 5.3 or higher. PHP 5.2 is no longer supported by ownCloud and the PHP community.'); } - if(!defined('PDO::ATTR_DRIVER_NAME')){ + if(!defined('PDO::ATTR_DRIVER_NAME')) { $errors[]=array('error'=>'PHP PDO module is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.'); } @@ -306,8 +316,8 @@ class OC_Util { /** * Check if the app is enabled, redirects to home if not */ - public static function checkAppEnabled($app){ - if( !OC_App::isEnabled($app)){ + public static function checkAppEnabled($app) { + if( !OC_App::isEnabled($app)) { header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' )); exit(); } @@ -317,10 +327,10 @@ class OC_Util { * Check if the user is logged in, redirects to home if not. With * redirect URL parameter to the request URI. */ - public static function checkLoggedIn(){ + public static function checkLoggedIn() { // Check if we are a user - if( !OC_User::isLoggedIn()){ - header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ).'?redirect_url='.urlencode($_SERVER["REQUEST_URI"])); + if( !OC_User::isLoggedIn()) { + header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php', array('redirect_url' => urlencode($_SERVER["REQUEST_URI"])))); exit(); } } @@ -328,10 +338,10 @@ class OC_Util { /** * Check if the user is a admin, redirects to home if not */ - public static function checkAdminUser(){ + public static function checkAdminUser() { // Check if we are a user self::checkLoggedIn(); - if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )){ + if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )) { header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' )); exit(); } @@ -341,13 +351,13 @@ class OC_Util { * Check if the user is a subadmin, redirects to home if not * @return array $groups where the current user is subadmin */ - public static function checkSubAdminUser(){ + public static function checkSubAdminUser() { // Check if we are a user self::checkLoggedIn(); - if(OC_Group::inGroup(OC_User::getUser(),'admin')){ + if(OC_Group::inGroup(OC_User::getUser(),'admin')) { return true; } - if(!OC_SubAdmin::isSubAdmin(OC_User::getUser())){ + if(!OC_SubAdmin::isSubAdmin(OC_User::getUser())) { header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' )); exit(); } @@ -357,7 +367,7 @@ class OC_Util { /** * Redirect to the user default page */ - public static function redirectToDefaultPage(){ + public static function redirectToDefaultPage() { if(isset($_REQUEST['redirect_url']) && (substr($_REQUEST['redirect_url'], 0, strlen(OC::$WEBROOT)) == OC::$WEBROOT || $_REQUEST['redirect_url'][0] == '/')) { $location = $_REQUEST['redirect_url']; } @@ -382,9 +392,9 @@ class OC_Util { * get an id unqiue for this instance * @return string */ - public static function getInstanceId(){ + public static function getInstanceId() { $id=OC_Config::getValue('instanceid',null); - if(is_null($id)){ + if(is_null($id)) { $id=uniqid(); OC_Config::setValue('instanceid',$id); } @@ -396,7 +406,7 @@ class OC_Util { * Todo: Write howto * @return $token Generated token. */ - public static function callRegister(){ + public static function callRegister() { //mamimum time before token exires $maxtime=(60*60); // 1 hour @@ -412,7 +422,7 @@ class OC_Util { foreach($_SESSION as $key=>$value) { // search all tokens in the session if(substr($key,0,12)=='requesttoken') { - if($value+$maxtime<time()){ + if($value+$maxtime<time()) { // remove outdated tokens unset($_SESSION[$key]); } @@ -428,14 +438,14 @@ class OC_Util { * @brief Check an ajax get/post call if the request token is valid. * @return boolean False if request token is not set or is invalid. */ - public static function isCallRegistered(){ + public static function isCallRegistered() { //mamimum time before token exires $maxtime=(60*60); // 1 hour if(isset($_GET['requesttoken'])) { $token=$_GET['requesttoken']; - }elseif(isset($_POST['requesttoken'])){ + }elseif(isset($_POST['requesttoken'])) { $token=$_POST['requesttoken']; - }elseif(isset($_SERVER['HTTP_REQUESTTOKEN'])){ + }elseif(isset($_SERVER['HTTP_REQUESTTOKEN'])) { $token=$_SERVER['HTTP_REQUESTTOKEN']; }else{ //no token found. @@ -443,7 +453,7 @@ class OC_Util { } if(isset($_SESSION['requesttoken-'.$token])) { $timestamp=$_SESSION['requesttoken-'.$token]; - if($timestamp+$maxtime<time()){ + if($timestamp+$maxtime<time()) { return false; }else{ //token valid @@ -458,7 +468,7 @@ class OC_Util { * @brief Check an ajax get/post call if the request token is valid. exit if not. * Todo: Write howto */ - public static function callCheck(){ + public static function callCheck() { if(!OC_Util::isCallRegistered()) { exit; } @@ -473,7 +483,7 @@ class OC_Util { * @param string or array of strings * @return array with sanitized strings or a single sanitized string, depends on the input parameter. */ - public static function sanitizeHTML( &$value ){ + public static function sanitizeHTML( &$value ) { if (is_array($value) || is_object($value)) array_walk_recursive($value,'OC_Util::sanitizeHTML'); else $value = htmlentities($value, ENT_QUOTES, 'UTF-8'); //Specify encoding for PHP<5.4 return $value; diff --git a/lib/vcategories.php b/lib/vcategories.php index 05dfe18db6f..f5123adeeb6 100644 --- a/lib/vcategories.php +++ b/lib/vcategories.php @@ -125,7 +125,7 @@ class OC_VCategories { * $result = $stmt->execute(); * $objects = array(); * if(!is_null($result)) { - * while( $row = $result->fetchRow()){ + * while( $row = $result->fetchRow()) { * $objects[] = $row['carddata']; * } * } @@ -183,7 +183,7 @@ class OC_VCategories { if(!is_null($objects)) { foreach($objects as $key=>&$value) { $vobject = OC_VObject::parse($value[1]); - if(!is_null($vobject)){ + if(!is_null($vobject)) { $categories = $vobject->getAsArray('CATEGORIES'); //OC_Log::write('core','OC_VCategories::delete, before: '.$key.': '.print_r($categories, true), OC_Log::DEBUG); foreach($names as $name) { diff --git a/lib/vobject.php b/lib/vobject.php index ec80e1d605a..b5a04b4bf65 100644 --- a/lib/vobject.php +++ b/lib/vobject.php @@ -30,7 +30,7 @@ class OC_VObject{ /** * @returns Sabre_VObject_Component */ - public function getVObject(){ + public function getVObject() { return $this->vobject; } @@ -39,11 +39,11 @@ class OC_VObject{ * @param string VObject as string * @returns Sabre_VObject or null */ - public static function parse($data){ + public static function parse($data) { try { Sabre_VObject_Property::$classMap['LAST-MODIFIED'] = 'Sabre_VObject_Property_DateTime'; $vobject = Sabre_VObject_Reader::read($data); - if ($vobject instanceof Sabre_VObject_Component){ + if ($vobject instanceof Sabre_VObject_Component) { $vobject = new OC_VObject($vobject); } return $vobject; @@ -58,8 +58,8 @@ class OC_VObject{ * @param string $value * @return string */ - public static function escapeSemicolons($value){ - foreach($value as &$i ){ + public static function escapeSemicolons($value) { + foreach($value as &$i ) { $i = implode("\\\\;", explode(';', $i)); } return implode(';',$value); @@ -70,11 +70,11 @@ class OC_VObject{ * @param string $value * @return array */ - public static function unescapeSemicolons($value){ + public static function unescapeSemicolons($value) { $array = explode(';',$value); - for($i=0;$i<count($array);$i++){ - if(substr($array[$i],-2,2)=="\\\\"){ - if(isset($array[$i+1])){ + for($i=0;$i<count($array);$i++) { + if(substr($array[$i],-2,2)=="\\\\") { + if(isset($array[$i+1])) { $array[$i] = substr($array[$i],0,count($array[$i])-2).';'.$array[$i+1]; unset($array[$i+1]); } @@ -91,16 +91,16 @@ class OC_VObject{ * Constuctor * @param Sabre_VObject_Component or string */ - public function __construct($vobject_or_name){ - if (is_object($vobject_or_name)){ + public function __construct($vobject_or_name) { + if (is_object($vobject_or_name)) { $this->vobject = $vobject_or_name; } else { $this->vobject = new Sabre_VObject_Component($vobject_or_name); } } - public function add($item, $itemValue = null){ - if ($item instanceof OC_VObject){ + public function add($item, $itemValue = null) { + if ($item instanceof OC_VObject) { $item = $item->getVObject(); } $this->vobject->add($item, $itemValue); @@ -113,12 +113,12 @@ class OC_VObject{ * @param object $parameters of property * @returns Sabre_VObject_Property newly created */ - public function addProperty($name, $value, $parameters=array()){ - if(is_array($value)){ + public function addProperty($name, $value, $parameters=array()) { + if(is_array($value)) { $value = OC_VObject::escapeSemicolons($value); } $property = new Sabre_VObject_Property( $name, $value ); - foreach($parameters as $name => $value){ + foreach($parameters as $name => $value) { $property->parameters[] = new Sabre_VObject_Parameter($name, $value); } @@ -126,13 +126,13 @@ class OC_VObject{ return $property; } - public function setUID(){ + public function setUID() { $uid = substr(md5(rand().time()),0,10); $this->vobject->add('UID',$uid); } - public function setString($name, $string){ - if ($string != ''){ + public function setString($name, $string) { + if ($string != '') { $string = strtr($string, array("\r\n"=>"\n")); $this->vobject->__set($name, $string); }else{ @@ -150,11 +150,11 @@ class OC_VObject{ * @param int $dateType * @return void */ - public function setDateTime($name, $datetime, $dateType=Sabre_VObject_Property_DateTime::LOCALTZ){ - if ($datetime == 'now'){ + public function setDateTime($name, $datetime, $dateType=Sabre_VObject_Property_DateTime::LOCALTZ) { + if ($datetime == 'now') { $datetime = new DateTime(); } - if ($datetime instanceof DateTime){ + if ($datetime instanceof DateTime) { $datetime_element = new Sabre_VObject_Property_DateTime($name); $datetime_element->setDateTime($datetime, $dateType); $this->vobject->__set($name, $datetime_element); @@ -163,45 +163,45 @@ class OC_VObject{ } } - public function getAsString($name){ + public function getAsString($name) { return $this->vobject->__isset($name) ? $this->vobject->__get($name)->value : ''; } - public function getAsArray($name){ + public function getAsArray($name) { $values = array(); - if ($this->vobject->__isset($name)){ + if ($this->vobject->__isset($name)) { $values = explode(',', $this->getAsString($name)); $values = array_map('trim', $values); } return $values; } - public function &__get($name){ - if ($name == 'children'){ + public function &__get($name) { + if ($name == 'children') { return $this->vobject->children; } $return = $this->vobject->__get($name); - if ($return instanceof Sabre_VObject_Component){ + if ($return instanceof Sabre_VObject_Component) { $return = new OC_VObject($return); } return $return; } - public function __set($name, $value){ + public function __set($name, $value) { return $this->vobject->__set($name, $value); } - public function __unset($name){ + public function __unset($name) { return $this->vobject->__unset($name); } - public function __isset($name){ + public function __isset($name) { return $this->vobject->__isset($name); } - public function __call($function,$arguments){ + public function __call($function,$arguments) { return call_user_func_array(array($this->vobject, $function), $arguments); } } |