diff options
author | Michael Gapczynski <mtgap@owncloud.com> | 2012-09-12 01:06:57 -0400 |
---|---|---|
committer | Michael Gapczynski <mtgap@owncloud.com> | 2012-09-12 01:06:57 -0400 |
commit | 60feaf9abfbc60d950de9c2b820ad46b3b973eb3 (patch) | |
tree | f9931192ec8f3cf20840f87462592bf5a03b4af1 /lib | |
parent | b194ac3ddeeab6ce923a313725b3ce85fe849baa (diff) | |
parent | 54d4e556fe3302d1e580cb6d4abbfcd5699263a5 (diff) | |
download | nextcloud-server-60feaf9abfbc60d950de9c2b820ad46b3b973eb3.tar.gz nextcloud-server-60feaf9abfbc60d950de9c2b820ad46b3b973eb3.zip |
Merge branch 'master' into share_expiration
Conflicts:
core/js/share.js
lib/util.php
Diffstat (limited to 'lib')
122 files changed, 3372 insertions, 2897 deletions
diff --git a/lib/MDB2/Driver/Datatype/sqlite3.php b/lib/MDB2/Driver/Datatype/sqlite3.php index d74badbe4f1..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; @@ -383,5 +383,3 @@ class MDB2_Driver_Datatype_sqlite3 extends MDB2_Driver_Datatype_Common // }}} } - -?>
\ No newline at end of file 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/Native/sqlite3.php b/lib/MDB2/Driver/Native/sqlite3.php index de650107238..344d523bdf3 100644 --- a/lib/MDB2/Driver/Native/sqlite3.php +++ b/lib/MDB2/Driver/Native/sqlite3.php @@ -31,4 +31,3 @@ require_once 'MDB2/Driver/Native/Common.php'; class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common { } -?>
\ No newline at end of file diff --git a/lib/MDB2/Driver/Reverse/sqlite3.php b/lib/MDB2/Driver/Reverse/sqlite3.php index 33e5b590268..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 @@ -584,5 +584,3 @@ class MDB2_Driver_Reverse_sqlite3 extends MDB2_Driver_Reverse_Common 'This DBMS can not obtain tableInfo from result sets', __FUNCTION__); } } - -?>
\ No newline at end of file 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 74315903467..28f1f16ebaf 100755 --- a/lib/app.php +++ b/lib/app.php @@ -48,30 +48,27 @@ 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 (is_null($types)) { + if (!defined('DEBUG') || !DEBUG) { + if (is_null($types) + && empty(OC_Util::$core_scripts) + && empty(OC_Util::$core_styles)) { OC_Util::$core_scripts = OC_Util::$scripts; OC_Util::$scripts = array(); OC_Util::$core_styles = OC_Util::$styles; OC_Util::$styles = array(); - - if (!OC_AppConfig::getValue('core', 'remote_core.css', false)) { - OC_AppConfig::setValue('core', 'remote_core.css', '/core/minimizer.php'); - OC_AppConfig::setValue('core', 'remote_core.js', '/core/minimizer.php'); - } } } // return @@ -82,10 +79,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 +91,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 +109,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 +125,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 +161,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 +176,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 +212,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 +234,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 +252,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 +264,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,15 +275,15 @@ 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" )) - ); + ); } // if the user is logged-in @@ -300,7 +297,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" )); } @@ -313,17 +310,17 @@ class OC_App{ $settings[]=array( "id" => "admin", "order" => 1000, "href" => OC_Helper::linkTo( "settings", "admin.php" ), "name" => $l->t("Admin"), "icon" => OC_Helper::imagePath( "settings", "admin.svg" )); } - } + } $navigation = self::proceedNavigation($settings); return $navigation; } /// 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 +328,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 +346,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 +385,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 +402,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 +456,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 +465,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 +480,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 +493,7 @@ class OC_App{ $source=self::$personalForms; break; } - foreach($source as $form){ + foreach($source as $form) { $forms[]=include $form; } return $forms; @@ -502,33 +502,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 +549,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 +562,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 +570,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'].'" 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 +580,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 +588,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 +598,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 +626,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 372cded9a5f..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,29 +89,29 @@ 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; } } - + /** * @brief check if a key is set in the appconfig * @param string $app * @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 ); } - + /** * @brief sets a value in the appconfig * @param $app app @@ -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,28 +156,28 @@ 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 )); return true; } - + /** * get multiply values, either the app or key can be used as wildcard by setting it to false * @param app * @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 fabd7cc7a51..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; @@ -28,7 +28,7 @@ abstract class OC_Archive{ return new OC_Archive_TAR($path); } } - + abstract function __construct($source); /** * add an empty folder to the archive @@ -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 f6efd6d0ecc..639d2392b63 100644 --- a/lib/archive/tar.php +++ b/lib/archive/tar.php @@ -6,7 +6,7 @@ * See the COPYING-README file. */ -require_once '3rdparty/Archive/Tar.php'; +require_once 'Archive/Tar.php'; class OC_Archive_TAR extends OC_Archive{ const PLAIN=0; @@ -14,17 +14,17 @@ class OC_Archive_TAR extends OC_Archive{ const BZIP=2; private $fileList; - + /** * @var Archive_Tar tar */ 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)]); + $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,'.')){ - $extension=substr($file,strrpos($file,'.')); - switch($extension){ + static public function getTarType($file) { + if(strpos($file, '.')) { + $extension=substr($file, strrpos($file, '.')); + switch($extension) { case 'gz': case 'tgz': return self::GZIP; @@ -55,23 +55,23 @@ 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); + $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); } } - $result=$this->tar->addModify(array($tmpBase.$path),'',$tmpBase); + $result=$this->tar->addModify(array($tmpBase.$path), '', $tmpBase); rmdir($tmpBase.$path); $this->fileList=false; return $result; @@ -82,17 +82,17 @@ 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(); - $result=$this->tar->_addfile($source,$header,$dummy,$dummy,$path); + $result=$this->tar->_addfile($source, $header, $dummy, $dummy, $path); }else{ - $result=$this->tar->addString($path,$source); + $result=$this->tar->addString($path, $source); } $this->fileList=false; return $result; @@ -104,36 +104,36 @@ 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); - rename($tmp.$source,$tmp.$dest); + rename($tmp.$source, $tmp.$dest); $this->tar=null; unlink($this->path); - $types=array(null,'gz','bz'); - $this->tar=new Archive_Tar($this->path,$types[self::getTarType($this->path)]); - $this->tar->createModify(array($tmp),'',$tmp.'/'); + $types=array(null, 'gz', 'bz'); + $this->tar=new Archive_Tar($this->path, $types[self::getTarType($this->path)]); + $this->tar->createModify(array($tmp), '', $tmp.'/'); $this->fileList=false; 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; } } return null; } - + /** * get the uncompressed size of a file in the 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]=='/'){ - $file=substr($file,1); + foreach($files as $file) { + if($file[0]=='/') { + $file=substr($file, 1); } - if(substr($file,0,$pathLength)==$path and $file!=$path){ - $result=substr($file,$pathLength); - if($pos=strpos($result,'/')){ - $result=substr($result,0,$pos+1); + if(substr($file, 0, $pathLength)==$path and $file!=$path) { + $result=substr($file, $pathLength); + 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,18 +202,18 @@ 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)){ - $success=$this->tar->extractList(array('/'.$path),$tmp); + if($this->fileExists('/'.$path)) { + $success=$this->tar->extractList(array('/'.$path), $tmp); }else{ - $success=$this->tar->extractList(array($path),$tmp); + $success=$this->tar->extractList(array($path), $tmp); } - if($success){ - rename($tmp.$path,$dest); + if($success) { + rename($tmp.$path, $dest); } OCP\Files::rmdirr($tmp); return $success; @@ -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,36 +232,36 @@ 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; } } - + /** * remove a file or folder from the 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; @@ -272,7 +272,7 @@ class OC_Archive_TAR extends OC_Archive{ $this->tar=null; unlink($this->path); $this->reopen(); - $this->tar->createModify(array($tmp),'',$tmp); + $this->tar->createModify(array($tmp), '', $tmp); return true; } /** @@ -281,24 +281,24 @@ class OC_Archive_TAR extends OC_Archive{ * @param string mode * @return resource */ - function getStream($path,$mode){ - if(strrpos($path,'.')!==false){ - $ext=substr($path,strrpos($path,'.')); + function getStream($path,$mode) { + if(strrpos($path, '.')!==false) { + $ext=substr($path, strrpos($path, '.')); }else{ $ext=''; } $tmpFile=OCP\Files::tmpFile($ext); - if($this->fileExists($path)){ - $this->extractFile($path,$tmpFile); - }elseif($mode=='r' or $mode=='rb'){ + if($this->fileExists($path)) { + $this->extractFile($path, $tmpFile); + }elseif($mode=='r' or $mode=='rb') { return false; } - if($mode=='r' or $mode=='rb'){ - return fopen($tmpFile,$mode); + if($mode=='r' or $mode=='rb') { + return fopen($tmpFile, $mode); }else{ OC_CloseStreamWrapper::$callBacks[$tmpFile]=array($this,'writeBack'); self::$tempFiles[$tmpFile]=$path; - return fopen('close://'.$tmpFile,$mode); + return fopen('close://'.$tmpFile, $mode); } } @@ -306,9 +306,9 @@ class OC_Archive_TAR extends OC_Archive{ /** * write back temporary files */ - function writeBack($tmpFile){ - if(isset(self::$tempFiles[$tmpFile])){ - $this->addFile(self::$tempFiles[$tmpFile],$tmpFile); + function writeBack($tmpFile) { + if(isset(self::$tempFiles[$tmpFile])) { + $this->addFile(self::$tempFiles[$tmpFile], $tmpFile); unlink($tmpFile); } } @@ -316,12 +316,12 @@ 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; } $types=array(null,'gz','bz'); - $this->tar=new Archive_Tar($this->path,$types[self::getTarType($this->path)]); + $this->tar=new Archive_Tar($this->path, $types[self::getTarType($this->path)]); } } diff --git a/lib/archive/zip.php b/lib/archive/zip.php index c1a5c35738b..a2b07f1a35d 100644 --- a/lib/archive/zip.php +++ b/lib/archive/zip.php @@ -12,13 +12,13 @@ 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); + 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)){ - $result=$this->zip->addFile($source,$path); + 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); + $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,17 +53,17 @@ 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); + $this->zip->renameName($source, $dest); } /** * get the uncompressed size of a file in the 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,14 +80,14 @@ 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){ - $folderContent[]=substr($file,$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,9 +119,9 @@ 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); + file_put_contents($dest, $fp); } /** * extract the archive @@ -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,22 +158,22 @@ 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){ - $ext=substr($path,strrpos($path,'.')); + 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)){ - $this->extractFile($path,$tmpFile); + if($this->fileExists($path)) { + $this->extractFile($path, $tmpFile); } self::$tempFiles[$tmpFile]=$path; - return fopen('close://'.$tmpFile,$mode); + return fopen('close://'.$tmpFile, $mode); } } @@ -181,16 +181,16 @@ class OC_Archive_ZIP extends OC_Archive{ /** * write back temporary files */ - function writeBack($tmpFile){ - if(isset(self::$tempFiles[$tmpFile])){ - $this->addFile(self::$tempFiles[$tmpFile],$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]=='/'){ - return substr($path,1); + 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 b4f0429b319..e966ac9647c 100644 --- a/lib/backgroundjob/worker.php +++ b/lib/backgroundjob/worker.php @@ -22,7 +22,7 @@ /** * This class does the dirty work. - * + * * TODO: locking in doAllSteps */ class OC_BackgroundJob_Worker{ @@ -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,11 +52,11 @@ 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'] ); } - + return true; } @@ -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', '' ); @@ -79,10 +79,10 @@ class OC_BackgroundJob_Worker{ $regular_tasks = OC_BackgroundJob_RegularTask::all(); ksort( $regular_tasks ); $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. @@ -112,7 +112,7 @@ class OC_BackgroundJob_Worker{ OC_Appconfig::setValue( 'core', 'backgroundjobs_task', '' ); } } - + return true; } } diff --git a/lib/base.php b/lib/base.php index b4f3e667133..679acdb6e5d 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(); /* @@ -69,50 +70,57 @@ 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 = str_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,'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; } @@ -123,13 +131,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{ @@ -138,21 +146,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; } @@ -174,7 +182,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"); } @@ -184,7 +192,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']; @@ -195,24 +203,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(); @@ -232,14 +241,14 @@ 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' ); } } - + OC_Util::addStyle( "styles" ); OC_Util::addStyle( "multiselect" ); OC_Util::addStyle( "jquery-ui-1.8.16.custom" ); @@ -247,11 +256,11 @@ class OC{ } public static function initSession() { - ini_set('session.cookie_httponly','1;'); + ini_set('session.cookie_httponly', '1;'); session_start(); } - public static function init(){ + public static function init() { // register autoloader spl_autoload_register(array('OC','autoload')); setlocale(LC_ALL, 'en_US.UTF-8'); @@ -259,13 +268,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')) { @@ -278,29 +287,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); @@ -308,8 +315,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'); @@ -327,7 +341,7 @@ class OC{ } // User and Groups - if( !OC_Config::getValue( "installed", false )){ + if( !OC_Config::getValue( "installed", false )) { $_SESSION['user_id'] = ''; } @@ -338,16 +352,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 @@ -355,7 +376,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); @@ -364,7 +385,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); @@ -372,10 +393,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; @@ -390,30 +411,31 @@ 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; } // Handle app css files - if(substr(OC::$REQUESTEDFILE,-3) == 'css') { + if(substr(OC::$REQUESTEDFILE, -3) == 'css') { self::loadCSSFile(); return; } // Someone is logged in : if(OC_User::isLoggedIn()) { OC_App::loadApps(); + OC_User::setupBackends(); if(isset($_GET["logout"]) and ($_GET["logout"])) { OC_User::logout(); header("Location: ".OC::$WEBROOT.'/'); @@ -424,8 +446,7 @@ class OC{ $file = 'index.php'; } $file_ext = substr($file, -3); - if ($file_ext != 'php' - || !self::loadAppScriptFile($app, $file)) { + if ($file_ext != 'php'|| !self::loadAppScriptFile($app, $file)) { header('HTTP/1.0 404 Not Found'); } } @@ -440,7 +461,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; @@ -469,7 +490,7 @@ class OC{ // Someone wants to log in : } elseif (OC::tryFormLogin()) { $error = true; - + // The user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP } elseif (OC::tryBasicAuthLogin()) { $error = true; @@ -479,18 +500,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(); } @@ -508,11 +531,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); @@ -528,11 +556,11 @@ class OC{ protected static function tryBasicAuthLogin() { if (!isset($_SERVER["PHP_AUTH_USER"]) - || !isset($_SERVER["PHP_AUTH_PW"])){ - return false; + || !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']:''); @@ -544,7 +572,7 @@ class OC{ } // define runtime variables - unless this already has been done -if( !isset( $RUNTIME_NOAPPS )){ +if( !isset( $RUNTIME_NOAPPS )) { $RUNTIME_NOAPPS = false; } @@ -554,7 +582,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 55f189a5da8..62003793d5f 100644 --- a/lib/cache.php +++ b/lib/cache.php @@ -38,14 +38,14 @@ class OC_Cache { if (!self::$global_cache_fast && function_exists('apc_store')) { self::$global_cache_fast = new OC_Cache_APC(true); } - + self::$global_cache = new OC_Cache_FileGlobal(); if (self::$global_cache_fast) { 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; @@ -67,15 +67,15 @@ class OC_Cache { if (!self::$user_cache_fast && function_exists('apc_store')) { self::$user_cache_fast = new OC_Cache_APC(); } - + self::$user_cache = new OC_Cache_File(); if (self::$user_cache_fast) { self::$user_cache = new OC_Cache_Broker(self::$user_cache_fast, self::$user_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 562c3d17167..27d8b19f36e 100644 --- a/lib/cache/file.php +++ b/lib/cache/file.php @@ -8,16 +8,21 @@ class OC_Cache_File{ + protected $storage; protected function getStorage() { - if(OC_User::isLoggedIn()){ + if (isset($this->storage)) { + return $this->storage; + } + if(OC_User::isLoggedIn()) { $subdir = 'cache'; $view = new OC_FilesystemView('/'.OC_User::getUser()); if(!$view->file_exists($subdir)) { $view->mkdir($subdir); } - return new OC_FilesystemView('/'.OC_User::getUser().'/'.$subdir); + $this->storage = new OC_FilesystemView('/'.OC_User::getUser().'/'.$subdir); + return $this->storage; }else{ - OC_Log::write('core','Can\'t get cache storage, user not logged in', OC_Log::ERROR); + OC_Log::write('core', 'Can\'t get cache storage, user not logged in', OC_Log::ERROR); return false; } } @@ -56,22 +61,43 @@ 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); } } } return true; } + + public function gc() { + $storage = $this->getStorage(); + if($storage and $storage->is_dir('/')) { + $now = time(); + $dh=$storage->opendir('/'); + while($file=readdir($dh)) { + if($file!='.' and $file!='..') { + $mtime = $storage->filemtime('/'.$file); + if ($mtime < $now) { + $storage->unlink('/'.$file); + } + } + } + } + } + + public static function loginListener() { + $c = new self(); + $c->gc(); + } } diff --git a/lib/cache/fileglobal.php b/lib/cache/fileglobal.php index 1c2c9bdc82d..6d01964e185 100644 --- a/lib/cache/fileglobal.php +++ b/lib/cache/fileglobal.php @@ -8,7 +8,7 @@ class OC_Cache_FileGlobal{ - protected function getCacheDir() { + static protected function getCacheDir() { $cache_dir = get_temp_dir().'/owncloud-'.OC_Util::getInstanceId().'/'; if (!is_dir($cache_dir)) { mkdir($cache_dir); @@ -23,7 +23,7 @@ class OC_Cache_FileGlobal{ public function get($key) { $key = $this->fixKey($key); if ($this->hasKey($key)) { - $cache_dir = $this->getCacheDir(); + $cache_dir = self::getCacheDir(); return file_get_contents($cache_dir.$key); } return null; @@ -31,7 +31,7 @@ class OC_Cache_FileGlobal{ public function set($key, $value, $ttl=0) { $key = $this->fixKey($key); - $cache_dir = $this->getCacheDir(); + $cache_dir = self::getCacheDir(); if ($cache_dir and file_put_contents($cache_dir.$key, $value)) { if ($ttl === 0) { $ttl = 86400; // 60*60*24 @@ -43,7 +43,7 @@ class OC_Cache_FileGlobal{ public function hasKey($key) { $key = $this->fixKey($key); - $cache_dir = $this->getCacheDir(); + $cache_dir = self::getCacheDir(); if ($cache_dir && is_file($cache_dir.$key)) { $mtime = filemtime($cache_dir.$key); if ($mtime < time()) { @@ -56,23 +56,46 @@ class OC_Cache_FileGlobal{ } public function remove($key) { - $cache_dir = $this->getCacheDir(); - if(!$cache_dir){ + $cache_dir = self::getCacheDir(); + if(!$cache_dir) { return false; } $key = $this->fixKey($key); return unlink($cache_dir.$key); } - public function clear(){ - $cache_dir = $this->getCacheDir(); - if($cache_dir and is_dir($cache_dir)){ + public function clear($prefix='') { + $cache_dir = self::getCacheDir(); + $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); } } } } + + static public function gc() { + $last_run = OC_AppConfig::getValue('core', 'global_cache_gc_lastrun', 0); + $now = time(); + if (($now - $last_run) < 300) { + // only do cleanup every 5 minutes + return; + } + OC_AppConfig::setValue('core', 'global_cache_gc_lastrun', $now); + $cache_dir = self::getCacheDir(); + if($cache_dir and is_dir($cache_dir)) { + $dh=opendir($cache_dir); + while($file=readdir($dh)) { + if($file!='.' and $file!='..') { + $mtime = filemtime($cache_dir.$file); + if ($mtime < $now) { + unlink($cache_dir.$file); + } + } + } + } + } } diff --git a/lib/cache/xcache.php b/lib/cache/xcache.php index 951f9b47545..cecdf46351c 100644 --- a/lib/cache/xcache.php +++ b/lib/cache/xcache.php @@ -28,10 +28,10 @@ class OC_Cache_XCache { } public function set($key, $value, $ttl=0) { - if($ttl>0){ - return xcache_set($this->getNamespace().$key,$value,$ttl); + if($ttl>0) { + return xcache_set($this->getNamespace().$key, $value, $ttl); }else{ - return xcache_set($this->getNamespace().$key,$value); + return xcache_set($this->getNamespace().$key, $value); } } @@ -43,7 +43,7 @@ class OC_Cache_XCache { return xcache_unset($this->getNamespace().$key); } - 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 99f696e3a07..0c34c7ea29f 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; } @@ -45,4 +45,4 @@ class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic { } } } -} +} 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 cd3ed60292c..39606577f6d 100644 --- a/lib/connector/sabre/directory.php +++ b/lib/connector/sabre/directory.php @@ -60,7 +60,7 @@ class OC_Connector_Sabre_Directory extends OC_Connector_Sabre_Node implements Sa } } else { $newPath = $this->path . '/' . $name; - OC_Filesystem::file_put_contents($newPath,$data); + OC_Filesystem::file_put_contents($newPath, $data); return OC_Connector_Sabre_Node::getETagPropertyForPath($newPath); } @@ -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 @@ -195,12 +195,10 @@ class OC_Connector_Sabre_Directory extends OC_Connector_Sabre_Node implements Sa */ public function getProperties($properties) { $props = parent::getProperties($properties); - if (in_array(self::GETETAG_PROPERTYNAME, $properties) - && !isset($props[self::GETETAG_PROPERTYNAME])) { - $props[self::GETETAG_PROPERTYNAME] = - OC_Connector_Sabre_Node::getETagPropertyForPath($this->path); + if (in_array(self::GETETAG_PROPERTYNAME, $properties) && !isset($props[self::GETETAG_PROPERTYNAME])) { + $props[self::GETETAG_PROPERTYNAME] + = OC_Connector_Sabre_Node::getETagPropertyForPath($this->path); } return $props; } } - diff --git a/lib/connector/sabre/file.php b/lib/connector/sabre/file.php index 9d571fceb0d..5bd38240d44 100644 --- a/lib/connector/sabre/file.php +++ b/lib/connector/sabre/file.php @@ -126,4 +126,3 @@ class OC_Connector_Sabre_File extends OC_Connector_Sabre_Node implements Sabre_D } } - diff --git a/lib/connector/sabre/locks.php b/lib/connector/sabre/locks.php index 0ddc8b18d2f..dbcc57558e0 100644 --- a/lib/connector/sabre/locks.php +++ b/lib/connector/sabre/locks.php @@ -42,7 +42,7 @@ class OC_Connector_Sabre_Locks extends Sabre_DAV_Locks_Backend_Abstract { // pure sql. MySQL's non-standard string concatination prevents us // from doing this though. // NOTE: SQLite requires time() to be inserted directly. That's ugly - // but otherwise reading locks from SQLite Databases will return + // but otherwise reading locks from SQLite Databases will return // nothing $query = 'SELECT * FROM `*PREFIX*locks` WHERE `userid` = ? AND (`created` + `timeout`) > '.time().' AND (( `uri` = ?)'; $params = array(OC_User::getUser(),$uri); @@ -75,9 +75,9 @@ class OC_Connector_Sabre_Locks extends Sabre_DAV_Locks_Backend_Abstract { $stmt = OC_DB::prepare( $query ); $result = $stmt->execute( $params ); - + $lockList = array(); - while( $row = $result->fetchRow()){ + while( $row = $result->fetchRow()) { $lockInfo = new Sabre_DAV_Locks_LockInfo(); $lockInfo->owner = $row['owner']; @@ -114,7 +114,7 @@ class OC_Connector_Sabre_Locks extends Sabre_DAV_Locks_Backend_Abstract { foreach($locks as $lock) { if ($lock->token == $lockInfo->token) $exists = true; } - + if ($exists) { $query = OC_DB::prepare( 'UPDATE `*PREFIX*locks` SET `owner` = ?, `timeout` = ?, `scope` = ?, `depth` = ?, `uri` = ?, `created` = ? WHERE `userid` = ? AND `token` = ?' ); $result = $query->execute( array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,OC_User::getUser(),$lockInfo->token)); diff --git a/lib/connector/sabre/node.php b/lib/connector/sabre/node.php index b9bf474a041..2916575e2d5 100644 --- a/lib/connector/sabre/node.php +++ b/lib/connector/sabre/node.php @@ -80,9 +80,9 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr $oldPath = $this->path; OC_Filesystem::rename($this->path,$newPath); - + $this->path = $newPath; - + $query = OC_DB::prepare( 'UPDATE `*PREFIX*properties` SET `propertypath` = ? WHERE `userid` = ? AND `propertypath` = ?' ); $query->execute( array( $newPath,OC_User::getUser(), $oldPath )); @@ -123,8 +123,8 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr } - /** - * sets the last modification time of the file (mtime) to the value given + /** + * sets the last modification time of the file (mtime) to the value given * in the second parameter or to now if the second param is empty. * Even if the modification time is set to a custom value the access time is set to now. */ @@ -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,16 +186,16 @@ 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; } - + $props = array(); foreach($properties as $property) { if (isset($this->property_cache[$property])) $props[$property] = $this->property_cache[$property]; diff --git a/lib/connector/sabre/principal.php b/lib/connector/sabre/principal.php index d1456f7c642..ee95ae63306 100644 --- a/lib/connector/sabre/principal.php +++ b/lib/connector/sabre/principal.php @@ -66,7 +66,7 @@ class OC_Connector_Sabre_Principal implements Sabre_DAVACL_IPrincipalBackend { */ public function getGroupMemberSet($principal) { // TODO: for now the group principal has only one member, the user itself - list($prefix,$name) = Sabre_DAV_URLUtil::splitPath($principal); + list($prefix, $name) = Sabre_DAV_URLUtil::splitPath($principal); $principal = $this->getPrincipalByPath($prefix); if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); @@ -115,6 +115,12 @@ 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 4214451c85f..ee69e5f8299 100644 --- a/lib/db.php +++ b/lib/db.php @@ -27,7 +27,7 @@ class OC_DB { const BACKEND_PDO=0; const BACKEND_MDB2=1; - + static private $connection; //the prefered connection to use, either PDO or MDB2 static private $backend=null; static private $MDB2=false; @@ -41,35 +41,36 @@ 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; } } return self::BACKEND_MDB2; } - + /** * @brief connects to the database * @returns true if connection can be established or nothing (die()) * * 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,18 +98,18 @@ 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; } $opts = array(); $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,32 +140,32 @@ 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; } - + /** * 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( @@ -234,22 +235,22 @@ class OC_DB { } break; } - + // 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 )) { 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 ); } - + // We always, really always want associative arrays self::$MDB2->setFetchMode(MDB2_FETCHMODE_ASSOC); } - + // we are done. great! return true; } @@ -261,8 +262,8 @@ 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) { //MDB2 uses or emulates limits & offset internally @@ -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" ); @@ -394,7 +395,7 @@ class OC_DB { // read file $content = file_get_contents( $file ); - + // Make changes and save them to an in-memory file $file2 = 'static://db_scheme'; $content = str_replace( '*dbname*', $CONFIG_DBNAME, $content ); @@ -405,45 +406,46 @@ 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 $definition = self::$schema->parseDatabaseDefinitionFile( $file2 ); - + //clean up memory 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 ); } - + $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()); } return true; } - + /** * @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" ); @@ -451,11 +453,11 @@ class OC_DB { // read file $content = file_get_contents( $file ); - + $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,20 +471,20 @@ 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 ); $op = self::$schema->updateDatabase($file2, $previousSchema, array(), false); - + //clean up memory unlink( $file2 ); - + 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 @@ -547,22 +549,22 @@ class OC_DB { return $query; } - + /** * @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); } - + /** * 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(); @@ -578,42 +580,41 @@ class OC_DB { // get the tables $definition = self::$schema->parseDatabaseDefinitionFile( $file2 ); - + // Delete our temporary file unlink( $file2 ); $tables=array_keys($definition['tables']); - foreach($tables as $table){ + foreach($tables as $table) { self::dropTable($table); } } - + /** * @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 ){ - $apps = OC_App::getAllApps(); - self::beginTransaction(); - // Delete the old tables - self::removeDBStructure( OC::$SERVERROOT . '/db_structure.xml' ); - - foreach($apps as $app){ - $path = OC_App::getAppPath($app).'/appinfo/database.xml'; - if(file_exists($path)){ - self::removeDBStructure( $path ); - } - } - - // Create new tables - self::createDBFromStructure( $file ); - self::commit(); - - } - + 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) { + $path = OC_App::getAppPath($app).'/appinfo/database.xml'; + if(file_exists($path)) { + self::removeDBStructure( $path ); + } + } + + // 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,31 +658,31 @@ 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; } } - + /** * 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); @@ -690,28 +691,27 @@ class PDOStatementWrapper{ return $this->statement->rowCount(); } } - + /** * 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); } - + /** * Provide a simple fetchOne. * 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 95af2e471bc..900b5b101e6 100644 --- a/lib/eventsource.php +++ b/lib/eventsource.php @@ -30,19 +30,19 @@ 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 e85d6747f90..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,37 +61,37 @@ 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; } - + // add parent directory to the file cache if it does not exist yet. if ($parent == -1 && $fullpath != $root) { $parentDir = substr(dirname($path), 0, strrpos(dirname($path), DIRECTORY_SEPARATOR)); self::scanFile($parentDir); $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,16 +131,16 @@ class OC_FileCache{ $queryParts[]='`'.$attribute.'`=?'; } } - if(isset($data['mimetype'])){ + if(isset($data['mimetype'])) { $arguments[]=dirname($data['mimetype']); $queryParts[]='`mimepart`=?'; } $arguments[]=$id; - + $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,20 +190,20 @@ 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`=?'); $query->execute(array(md5($root.$path))); - + //delete everything inside the folder $query=OC_DB::prepare('DELETE FROM `*PREFIX*fscache` WHERE `path` LIKE ?'); $query->execute(array($root.$path.'/%')); OC_Cache::remove('fileid/'.$root.$path); } - + /** * return array of filenames matching the querty * @param string $query @@ -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,44 +272,44 @@ 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); } - + return $id; } - + /** * get the file path from the id, relative to the home folder of the user * @param int id * @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,24 +328,24 @@ 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),''); } } - + /** * adjust the size of the parent folders * @param string $path * @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)); } @@ -390,7 +394,7 @@ class OC_FileCache{ } } } - + OC_FileCache_Update::cleanFolder($path,$root); self::increaseSize($path,$totalSize,$root); } @@ -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 95cc0ac300e..4e8ff23793e 100644 --- a/lib/filecache/cached.php +++ b/lib/filecache/cached.php @@ -12,21 +12,21 @@ */ 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])){ - $result=array_merge($result,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,20 +50,20 @@ 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){ + $parent=OC_FileCache::getId($path, $root); + 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); + OC_Log::write('files', 'getFolderContent(): file not found in cache ('.$path.')', OC_Log::DEBUG); return false; } } diff --git a/lib/filecache/update.php b/lib/filecache/update.php index 0b5ff8e2446..2b64a2a90ff 100644 --- a/lib/filecache/update.php +++ b/lib/filecache/update.php @@ -18,50 +18,50 @@ 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'])){ + $cachedData=OC_FileCache_Cached::get($path, $root); + if(isset($cachedData['mtime'])) { $cachedMTime=$cachedData['mtime']; - if($folder){ - return $view->hasUpdated($path.'/',$cachedMTime); + if($folder) { + return $view->hasUpdated($path.'/', $cachedMTime); }else{ - return $view->hasUpdated($path,$cachedMTime); + 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; } } - + /** * 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 - OC_Hook::emit('OC_Filesystem','post_delete',array('path'=>$file)); + 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); + self::delete($file, $root); } } } @@ -72,35 +72,35 @@ 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 - OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$file)); + 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); + self::update($file, $root); } } } } } - self::cleanFolder($path,$root); + 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 - OC_Hook::emit('OC_Filesystem','post_write',array('path'=>$path)); + 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); + 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,10 +129,10 @@ 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); + self::rename($oldPath, $newPath); } /** @@ -140,38 +140,38 @@ 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); } $mimetype=$view->getMimeType($path); - + $size=0; $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)){ - $cachedContent=OC_FileCache_Cached::getFolderContent($path,$root); - foreach($cachedContent as $file){ + if($view->is_dir($path.'/')) { + if(OC_FileCache::inCache($path, $root)) { + $cachedContent=OC_FileCache_Cached::getFolderContent($path, $root); + foreach($cachedContent as $file) { $size+=$file['size']; } $mtime=$view->filemtime($path.'/'); $ctime=$view->filectime($path.'/'); $writable=$view->is_writable($path.'/'); - OC_FileCache::put($path,array('size'=>$size,'mtime'=>$mtime,'ctime'=>$ctime,'mimetype'=>$mimetype,'writable'=>$writable)); + OC_FileCache::put($path, array('size'=>$size,'mtime'=>$mtime,'ctime'=>$ctime,'mimetype'=>$mimetype,'writable'=>$writable)); }else{ $count=0; - OC_FileCache::scan($path,null,$count,$root); + OC_FileCache::scan($path, null, $count, $root); return; //increaseSize is already called inside scan } }else{ - $size=OC_FileCache::scanFile($path,$root); + $size=OC_FileCache::scanFile($path, $root); } - OC_FileCache::increaseSize(dirname($path),$size-$cachedSize,$root); + OC_FileCache::increaseSize(dirname($path), $size-$cachedSize, $root); } /** @@ -179,14 +179,14 @@ class OC_FileCache_Update{ * @param string path * @param string root (optional) */ - public static function delete($path,$root=false){ - $cached=OC_FileCache_Cached::get($path,$root); - if(!isset($cached['size'])){ + public static function delete($path,$root=false) { + $cached=OC_FileCache_Cached::get($path, $root); + if(!isset($cached['size'])) { return; } $size=$cached['size']; - OC_FileCache::increaseSize(dirname($path),-$size,$root); - OC_FileCache::delete($path,$root); + OC_FileCache::increaseSize(dirname($path), -$size, $root); + OC_FileCache::delete($path, $root); } /** @@ -195,20 +195,20 @@ 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); } - $cached=OC_FileCache_Cached::get($oldPath,$root); + $cached=OC_FileCache_Cached::get($oldPath, $root); $oldSize=$cached['size']; - OC_FileCache::increaseSize(dirname($oldPath),-$oldSize,$root); - OC_FileCache::increaseSize(dirname($newPath),$oldSize,$root); - OC_FileCache::move($oldPath,$newPath); + OC_FileCache::increaseSize(dirname($oldPath), -$oldSize, $root); + OC_FileCache::increaseSize(dirname($newPath), $oldSize, $root); + OC_FileCache::move($oldPath, $newPath); } }
\ No newline at end of file diff --git a/lib/fileproxy.php b/lib/fileproxy.php index ec04faa9bc5..17380c656a3 100644 --- a/lib/fileproxy.php +++ b/lib/fileproxy.php @@ -43,7 +43,7 @@ class OC_FileProxy{ private static $proxies=array(); public static $enabled=true; - + /** * fallback function when a proxy operation is not implemented * @param string $function the name of the proxy operation @@ -51,45 +51,45 @@ 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]; } } - + /** * 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 7316224cc61..adbff3d301a 100644 --- a/lib/fileproxy/quota.php +++ b/lib/fileproxy/quota.php @@ -27,33 +27,33 @@ class OC_FileProxy_Quota extends OC_FileProxy{ private $userQuota=-1; - + /** * 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); } return $this->userQuota; - + } - + /** * 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 1a1fffa0a50..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 @@ -406,9 +410,9 @@ class OC_Files { //check for write permissions if(is_writable(OC::$SERVERROOT.'/.htaccess')) { file_put_contents(OC::$SERVERROOT.'/.htaccess', $htaccess); - return OC_Helper::computerFileSize($size); + return OC_Helper::computerFileSize($size); } else { OC_Log::write('files','Can\'t write upload limit to '.OC::$SERVERROOT.'/.htaccess. Please check the file permissions',OC_Log::WARN); } - + return false; } @@ -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 c829be62f74..351714437c5 100644 --- a/lib/filestorage/common.php +++ b/lib/filestorage/common.php @@ -21,11 +21,11 @@ */ /** - * Storage backend class for providing common filesystem operation methods + * Storage backend class for providing common filesystem operation methods * which are not storage-backend specific. * * OC_Filestorage_Common is never used directly; it is extended by all other - * storage backends, where its methods may be overridden, and additional + * storage backends, where its methods may be overridden, and additional * (backend-specific) methods are defined. * * Some OC_Filestorage_Common methods call functions which are first defined @@ -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; @@ -115,85 +115,85 @@ abstract class OC_Filestorage_Common extends OC_Filestorage { * @param $empty Flag indicating whether directory will be emptied * @returns true/false * - * @note By default the directory specified by $directory will be + * @note By default the directory specified by $directory will be * deleted together with its contents. To avoid this set $empty to true */ public function deleteAll( $directory, $empty = false ) { - + // strip leading slash if( substr( $directory, 0, 1 ) == "/" ) { - + $directory = substr( $directory, 1 ); - + } - + // strip trailing slash if( substr( $directory, -1) == "/" ) { - + $directory = substr( $directory, 0, -1 ); - + } - + if ( !$this->file_exists( \OCP\USER::getUser() . '/' . $directory ) || !$this->is_dir( \OCP\USER::getUser() . '/' . $directory ) ) { - + return false; - + } elseif( !$this->is_readable( \OCP\USER::getUser() . '/' . $directory ) ) { - + return false; - + } else { - + $directoryHandle = $this->opendir( \OCP\USER::getUser() . '/' . $directory ); - + while ( $contents = readdir( $directoryHandle ) ) { - + if ( $contents != '.' && $contents != '..') { - + $path = $directory . "/" . $contents; - + if ( $this->is_dir( $path ) ) { - + deleteAll( $path ); - + } else { - + $this->unlink( \OCP\USER::getUser() .'/' . $path ); // TODO: make unlink use same system path as is_dir - + } } - + } - + //$this->closedir( $directoryHandle ); // TODO: implement closedir in OC_FSV if ( $empty == false ) { - + if ( !$this->rmdir( $directory ) ) { - + return false; - + } - + } - + return true; } - + } - 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 b5126a407b3..b88bb232c36 100644 --- a/lib/filestorage/commontest.php +++ b/lib/filestorage/commontest.php @@ -31,45 +31,45 @@ class OC_Filestorage_CommonTest extends OC_Filestorage_Common{ * @var OC_FileStorage_Local */ 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 22d17469df3..80aa548047c 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){ - // sets the modification time of the file to the given value. + 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); @@ -72,35 +72,35 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{ if( $result ) { clearstatcache( true, $this->datadir.$path ); } - + 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){ - return disk_free_space($this->datadir.$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 fbb02900456..92eb4fa4778 100644 --- a/lib/filesystem.php +++ b/lib/filesystem.php @@ -3,22 +3,22 @@ /** * ownCloud * -* @author Frank Karlitschek -* @copyright 2012 Frank Karlitschek frank@owncloud.org -* +* @author Frank Karlitschek +* @copyright 2012 Frank Karlitschek frank@owncloud.org +* * 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 +* 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 +* +* 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/>. -* +* */ @@ -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,38 +183,38 @@ 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']); } return OC_Filesystem::$storages[$mountpoint]; } } - - 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,8 +236,15 @@ 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,25 +261,25 @@ 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(); } - + /** * create a new storage of a specific type * @param string type * @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) { @@ -284,13 +291,13 @@ class OC_Filesystem{ return false; } } - + /** * change the root to a fake root * @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,33 +324,33 @@ 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); } - + /** * return the path to a local version of the file * we need this because we can't know if a file is stored local or not from outside the filestorage and for some purposes a local file is needed * @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); } - + /** * return path to file which reflects one visible in browser * @param string path @@ -357,28 +364,28 @@ class OC_Filesystem{ } return $newpath; } - + /** * check if the requested path is valid * @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; } - + /** * checks if a file is blacklsited for storage in the 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']; @@ -392,50 +399,50 @@ 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 a888e5340ea..3a17af510cf 100644 --- a/lib/filesystemview.php +++ b/lib/filesystemview.php @@ -48,22 +48,22 @@ class OC_FilesystemView { } public function getAbsolutePath($path) { - if(!$path){ + if(!$path) { $path='/'; } - if($path[0]!=='/'){ + if($path[0]!=='/') { $path='/'.$path; } return $this->fakeRoot.$path; } - + /** * change the root to a fake toor * @param string fakeRoot * @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); @@ -295,12 +295,12 @@ class OC_FilesystemView { OC_Filesystem::signal_post_create, array( OC_Filesystem::signal_param_path => $path) ); - } + }/* OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_write, array( OC_Filesystem::signal_param_path => $path) - ); + );*/ OC_FileProxy::runPostProxies('file_put_contents', $absolutePath, $count); return $count > 0; }else{ @@ -325,7 +325,7 @@ class OC_FilesystemView { if(OC_FileProxy::runPreProxies('rename', $absolutePath1, $absolutePath2) and OC_Filesystem::isValidPath($path2)) { $path1 = $this->getRelativePath($absolutePath1); $path2 = $this->getRelativePath($absolutePath2); - + if($path1 == null or $path2 == null) { return false; } @@ -352,7 +352,7 @@ class OC_FilesystemView { $storage1 = $this->getStorage($path1); $storage1->unlink($this->getInternalPath($path1.$postFix1)); $result = $count>0; - } + } OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_rename, @@ -373,7 +373,7 @@ class OC_FilesystemView { if(OC_FileProxy::runPreProxies('copy', $absolutePath1, $absolutePath2) and OC_Filesystem::isValidPath($path2)) { $path1 = $this->getRelativePath($absolutePath1); $path2 = $this->getRelativePath($absolutePath2); - + if($path1 == null or $path2 == null) { return false; } @@ -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 a967ab28a96..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 72cf5dc89af..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,12 +266,12 @@ 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; } - + /** * @brief get a list of all users in several groups * @param array $gids 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 3cf464dfa7b..70b2f78862b 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 . '/?app=' . $app; $urlLinkTo .= ($file!='index.php')?'&getfile=' . urlencode($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 b53755310e0..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(); @@ -83,4 +83,3 @@ class OC_Hook{ } } } - diff --git a/lib/image.php b/lib/image.php index 90c64320a7c..861353e039d 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; } @@ -383,7 +383,7 @@ class OC_Image { /** * @brief Loads an image from an open file handle. * It is the responsibility of the caller to position the pointer at the correct place and to close the handle again. - * @param $handle + * @param $handle * @returns An image resource or false on error */ public function loadFromFileHandle($handle) { @@ -468,7 +468,7 @@ class OC_Image { break; */ default: - + // this is mostly file created from encrypted file $this->resource = imagecreatefromstring(\OC_Filesystem::file_get_contents(\OC_Filesystem::getLocalPath($imagepath))); $itype = IMAGETYPE_PNG; @@ -534,7 +534,7 @@ class OC_Image { $width_orig=imageSX($this->resource); $height_orig=imageSY($this->resource); $ratio_orig = $width_orig/$height_orig; - + if ($ratio_orig > 1) { $new_height = round($maxsize/$ratio_orig); $new_width = $maxsize; @@ -543,28 +543,14 @@ class OC_Image { $new_height = $maxsize; } - $process = imagecreatetruecolor(round($new_width), round($new_height)); - if ($process == false) { - OC_Log::write('core',__METHOD__.'(): Error creating true color image',OC_Log::ERROR); - imagedestroy($process); - return false; - } - - imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig); - if ($process == false) { - OC_Log::write('core',__METHOD__.'(): Error resampling process image '.$new_width.'x'.$new_height,OC_Log::ERROR); - imagedestroy($process); - return false; - } - imagedestroy($this->resource); - $this->resource = $process; + $this->preciseResize(round($new_width), round($new_height)); return true; } public function preciseResize($width, $height) { if (!$this->valid()) { OC_Log::write('core',__METHOD__.'(): No image loaded', OC_Log::ERROR); - return false; + return false; } $width_orig=imageSX($this->resource); $height_orig=imageSY($this->resource); @@ -612,7 +598,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 +652,36 @@ class OC_Image { return true; } - public function destroy(){ - if($this->valid()){ + /** + * @brief Resizes the image to fit within a boundry while preserving ratio. + * @param $maxWidth + * @param $maxHeight + * @returns bool + */ + public function fitIn($maxWidth, $maxHeight) { + if(!$this->valid()) { + OC_Log::write('core',__METHOD__.'(): No image loaded', OC_Log::ERROR); + return false; + } + $width_orig=imageSX($this->resource); + $height_orig=imageSY($this->resource); + $ratio = $width_orig/$height_orig; + + $newWidth = min($maxWidth, $ratio*$maxHeight); + $newHeight = min($maxHeight, $maxWidth/$ratio); + + $this->preciseResize(round($newWidth), round($newHeight)); + return true; + } + + 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 3d9d5c96fa3..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,33 +45,33 @@ 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(); } } - + /** * 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(); } } - + /** * 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 e7f5ffea0e4..90877cbd747 100644 --- a/lib/l10n.php +++ b/lib/l10n.php @@ -28,17 +28,17 @@ class OC_L10N{ * cached instances */ protected static $instances=array(); - + /** * cache */ protected static $cache = array(); - + /** * The best language */ protected static $language = ''; - + /** * App of this object */ @@ -53,7 +53,7 @@ class OC_L10N{ * Translations */ private $translations = array(); - + /** * Localization */ @@ -61,14 +61,14 @@ class OC_L10N{ 'date' => 'd.m.Y', 'datetime' => 'd.m.Y H:i:s', 'time' => 'H:i:s'); - + /** * 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]; @@ -76,7 +76,7 @@ class OC_L10N{ return new OC_L10N($app,$lang); } } - + /** * @brief The constructor * @param $app the app requesting l10n @@ -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; } @@ -188,7 +191,7 @@ class OC_L10N{ * @returns String or false * * Returns the localized data. - * + * * Implemented types: * - date * - Creates a date @@ -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]; } @@ -241,42 +244,42 @@ class OC_L10N{ * @returns language * * If $app is an array, ownCloud assumes that these are the available - * languages. Otherwise ownCloud tries to find the files in the l10n + * languages. Otherwise ownCloud tries to find the files in the l10n * folder. * * 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..b3c1c52ecee 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", @@ -20,5 +21,8 @@ "last month" => "lasta monato", "months ago" => "monatojn antaŭe", "last year" => "lasta jaro", -"years ago" => "jarojn antaŭe" +"years ago" => "jarojn antaŭe", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s haveblas. Ekhavu <a href=\"%s\">pli da informo</a>", +"up to date" => "ĝisdata", +"updates check is disabled" => "ĝisdateckontrolo estas malkapabligita" ); 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/et_EE.php b/lib/l10n/et_EE.php index d8da90a3cbf..87f222af838 100644 --- a/lib/l10n/et_EE.php +++ b/lib/l10n/et_EE.php @@ -21,5 +21,8 @@ "last month" => "eelmisel kuul", "months ago" => "kuud tagasi", "last year" => "eelmisel aastal", -"years ago" => "aastat tagasi" +"years ago" => "aastat tagasi", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s on saadaval. Vaata <a href=\"%s\">lisainfot</a>", +"up to date" => "ajakohane", +"updates check is disabled" => "uuenduste kontrollimine on välja lülitatud" ); 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..74425f0e134 100644 --- a/lib/l10n/ru.php +++ b/lib/l10n/ru.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/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/uk.php b/lib/l10n/uk.php index 18f6a4a623d..423aa12b2d7 100644 --- a/lib/l10n/uk.php +++ b/lib/l10n/uk.php @@ -20,5 +20,6 @@ "last month" => "минулого місяця", "months ago" => "місяці тому", "last year" => "минулого року", -"years ago" => "роки тому" +"years ago" => "роки тому", +"updates check is disabled" => "перевірка оновлень відключена" ); diff --git a/lib/l10n/vi.php b/lib/l10n/vi.php new file mode 100644 index 00000000000..fc41d69819a --- /dev/null +++ b/lib/l10n/vi.php @@ -0,0 +1,28 @@ +<?php $TRANSLATIONS = array( +"Help" => "Giúp đỡ", +"Personal" => "Cá nhân", +"Settings" => "Cài đặt", +"Users" => "Người dùng", +"Apps" => "Ứng dụng", +"Admin" => "Quản trị", +"ZIP download is turned off." => "Tải về ZIP đã bị tắt.", +"Files need to be downloaded one by one." => "Tập tin cần phải được tải về từng người một.", +"Back to Files" => "Trở lại tập tin", +"Selected files too large to generate zip file." => "Tập tin được chọn quá lớn để tạo tập tin ZIP.", +"Application is not enabled" => "Ứng dụng không được BẬT", +"Authentication error" => "Lỗi xác thực", +"Token expired. Please reload page." => "Mã Token đã hết hạn. Hãy tải lại trang.", +"seconds ago" => "1 giây trước", +"1 minute ago" => "1 phút trước", +"%d minutes ago" => "%d phút trước", +"today" => "hôm nay", +"yesterday" => "hôm qua", +"%d days ago" => "%d ngày trước", +"last month" => "tháng trước", +"months ago" => "tháng trước", +"last year" => "năm trước", +"years ago" => "năm trước", +"%s is available. Get <a href=\"%s\">more information</a>" => "%s có sẵn. <a href=\"%s\">xem thêm ở đây</a>", +"up to date" => "đến ngày", +"updates check is disabled" => "đã TĂT chức năng cập nhật " +); 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 0ac9a97c1bf..8d30fff9f28 100644 --- a/lib/mail.php +++ b/lib/mail.php @@ -12,12 +12,12 @@ * A class to handle mail sending. */ -require_once('class.phpmailer.php'); +require_once 'class.phpmailer.php'; class OC_Mail { /** - * send an email + * send an email * * @param string $toaddress * @param string $toname @@ -31,17 +31,17 @@ class OC_Mail { $SMTPMODE = OC_Config::getValue( 'mail_smtpmode', 'sendmail' ); $SMTPHOST = OC_Config::getValue( 'mail_smtphost', '127.0.0.1' ); - $SMTPAUTH = OC_Config::getValue( 'mail_smtpauth', false ); - $SMTPUSERNAME = OC_Config::getValue( 'mail_smtpname', '' ); - $SMTPPASSWORD = OC_Config::getValue( 'mail_smtppassword', '' ); + $SMTPAUTH = OC_Config::getValue( 'mail_smtpauth', false ); + $SMTPUSERNAME = OC_Config::getValue( 'mail_smtpname', '' ); + $SMTPPASSWORD = OC_Config::getValue( 'mail_smtppassword', '' ); $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 e998cf1f4a8..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,37 +219,37 @@ 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 ) ); + return json_encode( array( 'success' => false ) ); } } // 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 { @@ -411,9 +411,9 @@ class OC_Migrate{ $success = false; } } - + // 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(); @@ -421,7 +421,7 @@ class OC_Migrate{ $return['apps'][$provider->getID()]['success'] = false; $return['apps'][$provider->getID()]['message'] = 'failed to create the app tables'; } - + // Now add some app info the the return array $appinfo = OC_App::getAppInfo( $provider->getID() ); $return['apps'][$provider->getID()]['version'] = OC_App::getAppVersion($provider->getID()); @@ -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 5c89e6bacd6..64b8168cd98 100644 --- a/lib/migration/content.php +++ b/lib/migration/content.php @@ -25,42 +25,42 @@ * provides methods to add and access data from the migration */ class OC_Migration_Content{ - + private $zip=false; // Holds the MDB2 object private $db=null; // Holds an array of tmpfiles to delete after zip creation private $tmpfiles=false; - + /** * @brief sets up the * @param $zip ZipArchive object * @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; } - + } - + // @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 ); - + // Optimize the query $query = $this->db->prepare( $query ); - + // Die if we have an error (error means: bad query, not 0 results!) if( PEAR::isError( $query ) ) { $entry = 'DB Error: "'.$result->getMessage().'"<br />'; @@ -68,17 +68,17 @@ class OC_Migration_Content{ OC_Log::write( 'migration', $entry, OC_Log::FATAL ); return false; } else { - return $query; + return $query; } - + } - + /** * @brief processes the db query * @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 ); @@ -86,28 +86,28 @@ class OC_Migration_Content{ $query = str_replace( '*PREFIX*', '', $query ); return $query; } - + /** * @brief copys rows to migration.db from the main database * @param $options array of options. * @return bool */ - public function copyRows( $options ){ - if( !array_key_exists( 'table', $options ) ){ - return false; + 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'])){ - $options['matchval'] = 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 ); @@ -122,29 +122,29 @@ class OC_Migration_Content{ $query = OC_DB::prepare( $sql ); $results = $query->execute(); $return = $this->insertData( $results, $options ); - + } - + return $return; - + } - + /** * @brief saves a sql data set into migration.db * @param $data a sql data set returned from self::prepare()->query() * @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; } - + // Generate some sql $sql = "INSERT INTO `" . $options['table'] . '` ( `'; $fieldssql = implode( '`, `', $fields ); @@ -153,19 +153,19 @@ class OC_Migration_Content{ $sql .= $valuessql . " )"; // Make the query $query = $this->prepare( $sql ); - if( !$query ){ - OC_Log::write( 'migration', 'Invalid sql produced: '.$sql, OC_Log::FATAL ); + 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']]; + $return[] = $row[$options['idcol']]; } else { // Take a guess and return the first field :) - $return[] = reset($row); + $return[] = reset($row); } } $fields = ''; @@ -173,11 +173,11 @@ class OC_Migration_Content{ } return $return; } - + /** * @brief adds a directory to the zip object * @param $dir string path of the directory to add - * @param $recursive bool + * @param $recursive bool * @param $internaldir string path of folder to add dir to in zip * @return bool */ @@ -185,14 +185,14 @@ class OC_Migration_Content{ $dirname = basename($dir); $this->zip->addEmptyDir($internaldir . $dirname); $internaldir.=$dirname.='/'; - if( !file_exists( $dir ) ){ - return false; + if( !file_exists( $dir ) ) { + return false; } if ($dirhandle = opendir($dir)) { while (false !== ( $file = readdir($dirhandle))) { - + if (( $file != '.' ) && ( $file != '..' )) { - + if (is_dir($dir . '/' . $file) && $recursive) { $this->addDir($dir . '/' . $file, $recursive, $internaldir); } elseif (is_file($dir . '/' . $file)) { @@ -207,46 +207,46 @@ class OC_Migration_Content{ } return true; } - + /** * @brief adds a file to the zip from a given string * @param $data string of data to add * @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; + return false; } // Add file to the zip $this->zip->addFile( $file, $path ); return true; } - + /** * @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; + return false; } $this->cleanup(); - return true; - } - + return true; + } + /** * @brief cleans up after the zip */ - private function cleanup(){ + private function cleanup() { // Delete tmp files - foreach($this->tmpfiles as $i){ - unlink( $i ); - } + foreach($this->tmpfiles as $i) { + unlink( $i ); + } } } diff --git a/lib/migration/provider.php b/lib/migration/provider.php index 91336f3019d..234ab3351f3 100644 --- a/lib/migration/provider.php +++ b/lib/migration/provider.php @@ -3,50 +3,50 @@ * provides search functionalty */ abstract class OC_Migration_Provider{ - + protected $id=false; - protected $content=false; + protected $content=false; protected $uid=false; protected $olduid=false; protected $appinfo=false; - - public function __construct( $appid ){ + + public function __construct( $appid ) { // Set the id $this->id = $appid; OC_Migrate::registerProvider( $this ); } - + /** * @brief exports data for apps * @return array appdata to be exported */ abstract function export( ); - + /** * @brief imports data for the app * @return void */ abstract function import( ); - + /** * @brief sets the OC_Migration_Content object to $this->content * @param $content a OC_Migration_Content object */ - public function setData( $uid, $content, $info=null ){ - $this->content = $content; + 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; } } - + /** * @brief returns the appid of the provider * @return string */ - public function getID(){ - return $this->id; + 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 3157aae99e6..7350c3c8821 100644 --- a/lib/ocs.php +++ b/lib/ocs.php @@ -84,7 +84,7 @@ class OC_OCS { $method='get'; }elseif($_SERVER['REQUEST_METHOD'] == 'PUT') { $method='put'; - parse_str(file_get_contents("php://input"),$put_vars); + parse_str(file_get_contents("php://input"), $put_vars); }elseif($_SERVER['REQUEST_METHOD'] == 'POST') { $method='post'; }else{ @@ -94,89 +94,89 @@ class OC_OCS { // preprocess url $url = strtolower($_SERVER['REQUEST_URI']); - if(substr($url,(strlen($url)-1))<>'/') $url.='/'; - $ex=explode('/',$url); + if(substr($url, (strlen($url)-1))<>'/') $url.='/'; + $ex=explode('/', $url); $paracount=count($ex); $format = self::readData($method, 'format', 'text', ''); // eventhandler // CONFIG // apiconfig - GET - CONFIG - if(($method=='get') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'config')){ + if(($method=='get') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'config')) { OC_OCS::apiconfig($format); // PERSON // personcheck - POST - PERSON/CHECK - }elseif(($method=='post') and ($ex[$paracount-4] == 'v1.php') and ($ex[$paracount-3]=='person') and ($ex[$paracount-2] == 'check')){ + } elseif(($method=='post') and ($ex[$paracount-4] == 'v1.php') and ($ex[$paracount-3]=='person') and ($ex[$paracount-2] == 'check')) { $login = self::readData($method, 'login', 'text'); $passwd = self::readData($method, 'password', 'text'); - OC_OCS::personcheck($format,$login,$passwd); + OC_OCS::personcheck($format, $login, $passwd); // ACTIVITY // activityget - GET ACTIVITY page,pagesize als urlparameter - }elseif(($method=='get') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'activity')){ + }elseif(($method=='get') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'activity')) { $page = self::readData($method, 'page', 'int', 0); - $pagesize = self::readData($method, 'pagesize','int', 10); + $pagesize = self::readData($method, 'pagesize', 'int', 10); if($pagesize<1 or $pagesize>100) $pagesize=10; - OC_OCS::activityget($format,$page,$pagesize); + OC_OCS::activityget($format, $page, $pagesize); // activityput - POST ACTIVITY - }elseif(($method=='post') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'activity')){ + }elseif(($method=='post') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'activity')) { $message = self::readData($method, 'message', 'text'); - OC_OCS::activityput($format,$message); + OC_OCS::activityput($format, $message); // PRIVATEDATA // get - GET DATA - }elseif(($method=='get') and ($ex[$paracount-4] == 'v1.php') and ($ex[$paracount-2] == 'getattribute')){ + }elseif(($method=='get') and ($ex[$paracount-4] == 'v1.php') and ($ex[$paracount-2] == 'getattribute')) { OC_OCS::privateDataGet($format); - }elseif(($method=='get') and ($ex[$paracount-5] == 'v1.php') and ($ex[$paracount-3] == 'getattribute')){ + }elseif(($method=='get') and ($ex[$paracount-5] == 'v1.php') and ($ex[$paracount-3] == 'getattribute')) { $app=$ex[$paracount-2]; OC_OCS::privateDataGet($format, $app); - }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-4] == 'getattribute')){ + }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-4] == 'getattribute')) { $key=$ex[$paracount-2]; $app=$ex[$paracount-3]; - OC_OCS::privateDataGet($format, $app,$key); + OC_OCS::privateDataGet($format, $app, $key); // set - POST DATA - }elseif(($method=='post') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-4] == 'setattribute')){ + }elseif(($method=='post') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-4] == 'setattribute')) { $key=$ex[$paracount-2]; $app=$ex[$paracount-3]; $value = self::readData($method, 'value', 'text'); OC_OCS::privatedataset($format, $app, $key, $value); // delete - POST DATA - }elseif(($method=='post') and ($ex[$paracount-6] =='v1.php') and ($ex[$paracount-4] == 'deleteattribute')){ + }elseif(($method=='post') and ($ex[$paracount-6] =='v1.php') and ($ex[$paracount-4] == 'deleteattribute')) { $key=$ex[$paracount-2]; $app=$ex[$paracount-3]; OC_OCS::privatedatadelete($format, $app, $key); // CLOUD - // systemWebApps - }elseif(($method=='get') and ($ex[$paracount-5] == 'v1.php') and ($ex[$paracount-4]=='cloud') and ($ex[$paracount-3] == 'system') and ($ex[$paracount-2] == 'webapps')){ + // systemWebApps + }elseif(($method=='get') and ($ex[$paracount-5] == 'v1.php') and ($ex[$paracount-4]=='cloud') and ($ex[$paracount-3] == 'system') and ($ex[$paracount-2] == 'webapps')) { OC_OCS::systemwebapps($format); - // quotaget - }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-5]=='cloud') and ($ex[$paracount-4] == 'user') and ($ex[$paracount-2] == 'quota')){ + // quotaget + }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-5]=='cloud') and ($ex[$paracount-4] == 'user') and ($ex[$paracount-2] == 'quota')) { $user=$ex[$paracount-3]; - OC_OCS::quotaget($format,$user); + OC_OCS::quotaget($format, $user); - // quotaset - }elseif(($method=='post') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-5]=='cloud') and ($ex[$paracount-4] == 'user') and ($ex[$paracount-2] == 'quota')){ + // quotaset + }elseif(($method=='post') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-5]=='cloud') and ($ex[$paracount-4] == 'user') and ($ex[$paracount-2] == 'quota')) { $user=$ex[$paracount-3]; $quota = self::readData('post', 'quota', 'int'); - OC_OCS::quotaset($format,$user,$quota); + OC_OCS::quotaset($format, $user, $quota); - // keygetpublic - }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-5]=='cloud') and ($ex[$paracount-4] == 'user') and ($ex[$paracount-2] == 'publickey')){ + // keygetpublic + }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-5]=='cloud') and ($ex[$paracount-4] == 'user') and ($ex[$paracount-2] == 'publickey')) { $user=$ex[$paracount-3]; - OC_OCS::publicKeyGet($format,$user); + OC_OCS::publicKeyGet($format, $user); - // keygetprivate - }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-5]=='cloud') and ($ex[$paracount-4] == 'user') and ($ex[$paracount-2] == 'privatekey')){ + // keygetprivate + }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-5]=='cloud') and ($ex[$paracount-4] == 'user') and ($ex[$paracount-2] == 'privatekey')) { $user=$ex[$paracount-3]; - OC_OCS::privateKeyGet($format,$user); + OC_OCS::privateKeyGet($format, $user); // add more calls here @@ -196,7 +196,7 @@ class OC_OCS { }else{ $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n"; $txt.=OC_OCS::getdebugoutput(); - echo(OC_OCS::generatexml($format,'failed',999,$txt)); + echo(OC_OCS::generatexml($format, 'failed', 999, $txt)); } exit(); } @@ -229,7 +229,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; @@ -237,8 +237,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; @@ -283,69 +283,69 @@ class OC_OCS { $writer = xmlwriter_open_memory(); xmlwriter_set_indent( $writer, 2 ); xmlwriter_start_document($writer ); - xmlwriter_start_element($writer,'ocs'); - xmlwriter_start_element($writer,'meta'); - xmlwriter_write_element($writer,'status',$status); - xmlwriter_write_element($writer,'statuscode',$statuscode); - xmlwriter_write_element($writer,'message',$message); + xmlwriter_start_element($writer, 'ocs'); + xmlwriter_start_element($writer, 'meta'); + xmlwriter_write_element($writer, 'status', $status); + xmlwriter_write_element($writer, 'statuscode', $statuscode); + xmlwriter_write_element($writer, 'message', $message); if($itemscount<>'') xmlwriter_write_element($writer,'totalitems',$itemscount); - if(!empty($itemsperpage)) xmlwriter_write_element($writer,'itemsperpage',$itemsperpage); + if(!empty($itemsperpage)) xmlwriter_write_element($writer, 'itemsperpage', $itemsperpage); xmlwriter_end_element($writer); if($dimension=='0') { // 0 dimensions - xmlwriter_write_element($writer,'data',$data); + xmlwriter_write_element($writer, 'data', $data); }elseif($dimension=='1') { - xmlwriter_start_element($writer,'data'); + xmlwriter_start_element($writer, 'data'); foreach($data as $key=>$entry) { - xmlwriter_write_element($writer,$key,$entry); + xmlwriter_write_element($writer, $key, $entry); } xmlwriter_end_element($writer); }elseif($dimension=='2') { xmlwriter_start_element($writer,'data'); foreach($data as $entry) { - xmlwriter_start_element($writer,$tag); - if(!empty($tagattribute)) { - xmlwriter_write_attribute($writer,'details',$tagattribute); - } - foreach($entry as $key=>$value) { - if(is_array($value)){ - foreach($value as $k=>$v) { - xmlwriter_write_element($writer,$k,$v); - } - } else { - xmlwriter_write_element($writer,$key,$value); - } - } - xmlwriter_end_element($writer); - } + xmlwriter_start_element($writer, $tag); + if(!empty($tagattribute)) { + xmlwriter_write_attribute($writer, 'details', $tagattribute); + } + foreach($entry as $key=>$value) { + if(is_array($value)) { + foreach($value as $k=>$v) { + xmlwriter_write_element($writer, $k, $v); + } + } else { + xmlwriter_write_element($writer, $key, $value); + } + } + xmlwriter_end_element($writer); + } xmlwriter_end_element($writer); }elseif($dimension=='3') { - xmlwriter_start_element($writer,'data'); + xmlwriter_start_element($writer, 'data'); foreach($data as $entrykey=>$entry) { - xmlwriter_start_element($writer,$tag); - if(!empty($tagattribute)) { - xmlwriter_write_attribute($writer,'details',$tagattribute); - } - foreach($entry as $key=>$value) { - if(is_array($value)){ - xmlwriter_start_element($writer,$entrykey); - foreach($value as $k=>$v) { - xmlwriter_write_element($writer,$k,$v); - } - xmlwriter_end_element($writer); - } else { - xmlwriter_write_element($writer,$key,$value); - } - } - xmlwriter_end_element($writer); + xmlwriter_start_element($writer, $tag); + if(!empty($tagattribute)) { + xmlwriter_write_attribute($writer, 'details', $tagattribute); + } + foreach($entry as $key=>$value) { + if(is_array($value)) { + xmlwriter_start_element($writer, $entrykey); + foreach($value as $k=>$v) { + xmlwriter_write_element($writer, $k, $v); + } + xmlwriter_end_element($writer); + } else { + xmlwriter_write_element($writer, $key, $value); + } + } + xmlwriter_end_element($writer); } xmlwriter_end_element($writer); }elseif($dimension=='dynamic') { - xmlwriter_start_element($writer,'data'); - OC_OCS::toxml($writer,$data,'comment'); + xmlwriter_start_element($writer, 'data'); + OC_OCS::toxml($writer, $data, 'comment'); xmlwriter_end_element($writer); } @@ -363,19 +363,16 @@ class OC_OCS { if (is_numeric($key)) { $key = $node; } - if (is_array($value)){ - xmlwriter_start_element($writer,$key); - OC_OCS::toxml($writer,$value,$node); + if (is_array($value)) { + xmlwriter_start_element($writer, $key); + OC_OCS::toxml($writer,$value, $node); xmlwriter_end_element($writer); }else{ - xmlwriter_write_element($writer,$key,$value); + xmlwriter_write_element($writer, $key, $value); } } } - - - /** * return the config data of this server * @param string $format @@ -383,17 +380,16 @@ class OC_OCS { */ private static function apiConfig($format) { $user=OC_OCS::checkpassword(false); - $url=substr(OCP\Util::getServerHost().$_SERVER['SCRIPT_NAME'],0,-11).''; + $url=substr(OCP\Util::getServerHost().$_SERVER['SCRIPT_NAME'], 0, -11).''; $xml['version']='1.7'; $xml['website']='ownCloud'; $xml['host']=OCP\Util::getServerHost(); $xml['contact']=''; $xml['ssl']='false'; - echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'config','',1)); + echo(OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'config', '', 1)); } - /** * check if the provided login/apikey/password is valid * @param string $format @@ -402,20 +398,18 @@ 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)); + echo(OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'person', 'check', 2)); }else{ - echo(OC_OCS::generatexml($format,'failed',102,'login not valid')); + echo(OC_OCS::generatexml($format, 'failed', 102, 'login not valid')); } }else{ - echo(OC_OCS::generatexml($format,'failed',101,'please specify all mandatory fields')); + echo(OC_OCS::generatexml($format, 'failed', 101, 'please specify all mandatory fields')); } } - - // ACTIVITY API ############################################# /** @@ -425,12 +419,12 @@ class OC_OCS { * @param string $pagesize * @return string xml/json */ - private static function activityGet($format,$page,$pagesize) { + private static function activityGet($format, $page, $pagesize) { $user=OC_OCS::checkpassword(); //TODO - $txt=OC_OCS::generatexml($format,'ok',100,'',$xml,'activity','full',2,$totalcount,$pagesize); + $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'activity', 'full', 2, $totalcount,$pagesize); echo($txt); } @@ -443,7 +437,7 @@ class OC_OCS { private static function activityPut($format,$message) { // not implemented in ownCloud $user=OC_OCS::checkpassword(); - echo(OC_OCS::generatexml($format,'ok',100,'')); + echo(OC_OCS::generatexml($format, 'ok', 100, '')); } // PRIVATEDATA API ############################################# @@ -455,9 +449,9 @@ class OC_OCS { * @param string $key * @return string xml/json */ - private static function privateDataGet($format,$app="",$key="") { + private static function privateDataGet($format, $app="", $key="") { $user=OC_OCS::checkpassword(); - $result=OC_OCS::getData($user,$app,$key); + $result=OC_OCS::getData($user, $app, $key); $xml=array(); foreach($result as $i=>$log) { $xml[$i]['key']=$log['key']; @@ -480,8 +474,8 @@ class OC_OCS { */ private static function privateDataSet($format, $app, $key, $value) { $user=OC_OCS::checkpassword(); - if(OC_OCS::setData($user,$app,$key,$value)){ - echo(OC_OCS::generatexml($format,'ok',100,'')); + if(OC_OCS::setData($user, $app, $key, $value)) { + echo(OC_OCS::generatexml($format, 'ok', 100, '')); } } @@ -493,15 +487,15 @@ 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)){ - echo(OC_OCS::generatexml($format,'ok',100,'')); + if(OC_OCS::deleteData($user, $app, $key)) { + echo(OC_OCS::generatexml($format, 'ok', 100, '')); } } - + /** * get private data * @param string $user @@ -510,24 +504,24 @@ class OC_OCS { * @param bool $like use LIKE instead of = when comparing keys * @return array */ - public static function getData($user,$app="",$key="") { - if($app){ + public static function getData($user, $app="", $key="") { + if($app) { $apps=array($app); }else{ $apps=OC_Preferences::getApps($user); } - if($key){ + if($key) { $keys=array($key); }else{ - foreach($apps as $app){ - $keys=OC_Preferences::getKeys($user,$app); + foreach($apps as $app) { + $keys=OC_Preferences::getKeys($user, $app); } } $result=array(); - foreach($apps as $app){ - foreach($keys as $key){ - $value=OC_Preferences::getValue($user,$app,$key); - $result[]=array('app'=>$app,'key'=>$key,'value'=>$value); + foreach($apps as $app) { + foreach($keys as $key) { + $value=OC_Preferences::getValue($user, $app, $key); + $result[]=array('app'=>$app, 'key'=>$key, 'value'=>$value); } } return $result; @@ -542,7 +536,7 @@ class OC_OCS { * @return bool */ public static function setData($user, $app, $key, $value) { - return OC_Preferences::setValue($user,$app,$key,$value); + return OC_Preferences::setValue($user, $app, $key, $value); } /** @@ -553,7 +547,7 @@ class OC_OCS { * @return string xml/json */ public static function deleteData($user, $app, $key) { - return OC_Preferences::deleteKey($user,$app,$key); + return OC_Preferences::deleteKey($user, $app, $key); } @@ -592,7 +586,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); @@ -653,7 +647,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); @@ -672,7 +666,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 ae35470cff6..8596ea0b3c7 100644 --- a/lib/ocsclient.php +++ b/lib/ocsclient.php @@ -29,22 +29,22 @@ class OC_OCSClient{ /** - * @brief Get the url of the OCS AppStore server. + * @brief Get the url of the OCS AppStore server. * @returns string of the AppStore server * * 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); } /** - * @brief Get the url of the OCS KB server. + * @brief Get the url of the OCS KB server. * @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,18 +56,18 @@ 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); - + $tmp=$data->data; $cats=array(); @@ -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); @@ -119,9 +122,9 @@ class OC_OCSClient{ $app['preview']=(string)$tmp[$i]->smallpreviewpic1; $app['changed']=strtotime($tmp[$i]->changed); $app['description']=(string)$tmp[$i]->description; - + $apps[]=$app; - } + } return $apps; } @@ -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; } @@ -184,10 +187,10 @@ class OC_OCSClient{ $tmp=$data->data->content; $app=array(); - if(isset($tmp->downloadlink)) { + if(isset($tmp->downloadlink)) { $app['downloadlink']=$tmp->downloadlink; }else{ - $app['downloadlink']=''; + $app['downloadlink']=''; } return $app; } @@ -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 b6c4c3a163f..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 e74f1550740..809a656f17f 100644 --- a/lib/public/app.php +++ b/lib/public/app.php @@ -26,7 +26,7 @@ * */ -// use OCP namespace for all classes that are considered public. +// use OCP namespace for all classes that are considered public. // This means that they should be used by apps instead of the internal ownCloud classes namespace OCP; @@ -34,120 +34,109 @@ namespace OCP; * This class provides functions to manage apps in ownCloud */ class App { - /** - * @brief Makes owncloud aware of this app - * @brief This call is deprecated and not necessary to use. - * @param $data array with all information - * @returns true/false - * - * @deprecated this method is deprecated - * Do not call it anymore - * It'll remain in our public API for compatibility reasons - * - */ - public static function register( $data ){ + /** + * @brief Makes owncloud aware of this app + * @brief This call is deprecated and not necessary to use. + * @param $data array with all information + * @returns true/false + * + * @deprecated this method is deprecated + * Do not call it anymore + * It'll remain in our public API for compatibility reasons + * + */ + public static function register( $data ) { return true; // don't do anything - } + } - /** - * @brief adds an entry to the navigation - * @param $data array containing the data - * @returns true/false - * - * This function adds a new entry to the navigation visible to users. $data - * is an associative array. - * The following keys are required: - * - id: unique id for this entry ('addressbook_index') - * - href: link to the page - * - name: Human readable name ('Addressbook') - * - * The following keys are optional: - * - icon: path to the icon of the app - * - order: integer, that influences the position of your application in - * the navigation. Lower values come first. - */ - public static function addNavigationEntry( $data ){ + /** + * @brief adds an entry to the navigation + * @param $data array containing the data + * @returns true/false + * + * This function adds a new entry to the navigation visible to users. $data + * is an associative array. + * The following keys are required: + * - id: unique id for this entry ('addressbook_index') + * - href: link to the page + * - name: Human readable name ('Addressbook') + * + * The following keys are optional: + * - icon: path to the icon of the app + * - order: integer, that influences the position of your application in + * the navigation. Lower values come first. + */ + public static function addNavigationEntry( $data ) { return \OC_App::addNavigationEntry( $data ); } - - /** - * @brief marks a navigation entry as active - * @param $id id of the entry - * @returns true/false - * - * This function sets a navigation entry as active and removes the 'active' - * property from all other entries. The templates can use this for - * highlighting the current position of the user. - */ - public static function setActiveNavigationEntry( $id ){ + /** + * @brief marks a navigation entry as active + * @param $id id of the entry + * @returns true/false + * + * This function sets a navigation entry as active and removes the 'active' + * property from all other entries. The templates can use this for + * highlighting the current position of the user. + */ + public static function setActiveNavigationEntry( $id ) { return \OC_App::setActiveNavigationEntry( $id ); } - - /** - * @brief Register a Configuration Screen that should appear in the personal settings section. - * @param $app string appid - * @param $page string page to be included - */ - public static function registerPersonal( $app, $page ){ + /** + * @brief Register a Configuration Screen that should appear in the personal settings section. + * @param $app string appid + * @param $page string page to be included + */ + public static function registerPersonal( $app, $page ) { return \OC_App::registerPersonal( $app, $page ); } - /** - * @brief Register a Configuration Screen that should appear in the Admin section. - * @param $app string appid - * @param $page string page to be included + * @brief Register a Configuration Screen that should appear in the Admin section. + * @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 ); } - - /** - * @brief Read app metadata from the info.xml file - * @param string $app id of the app or the path of the info.xml file - * @param boolean path (optional) - * @returns array - */ - public static function getAppInfo( $app, $path=false ){ + /** + * @brief Read app metadata from the info.xml file + * @param string $app id of the app or the path of the info.xml file + * @param boolean path (optional) + * @returns array + */ + public static function getAppInfo( $app, $path=false ) { return \OC_App::getAppInfo( $app, $path); } - - - /** - * @brief checks whether or not an app is enabled - * @param $app app - * @returns true/false - * - * This function checks whether or not an app is enabled. - */ - public static function isEnabled( $app ){ + /** + * @brief checks whether or not an app is enabled + * @param $app app + * @returns true/false + * + * This function checks whether or not an app is enabled. + */ + public static function isEnabled( $app ) { return \OC_App::isEnabled( $app ); } + /** + * @brief Check if the app is enabled, redirects to home if not + * @param $app app + * @returns true/false + */ + public static function checkAppEnabled( $app ) { + return \OC_Util::checkAppEnabled( $app ); + } - /** - * @brief Check if the app is enabled, redirects to home if not - * @param $app app - * @returns true/false - */ - public static function checkAppEnabled( $app ){ - return \OC_Util::checkAppEnabled( $app ); - } - - - /** - * @brief Get the last version of the app, either from appinfo/version or from appinfo/info.xml - * @param $app app - * @returns true/false - */ - public static function getAppVersion( $app ){ + /** + * @brief Get the last version of the app, either from appinfo/version or from appinfo/info.xml + * @param $app app + * @returns true/false + */ + public static function getAppVersion( $app ) { return \OC_App::getAppVersion( $app ); } - - - } diff --git a/lib/public/backgroundjob.php b/lib/public/backgroundjob.php index 834bebb5c3c..aba7d2b7620 100644 --- a/lib/public/backgroundjob.php +++ b/lib/public/backgroundjob.php @@ -24,7 +24,7 @@ * Public interface of ownCloud forbackground jobs. */ -// use OCP namespace for all classes that are considered public. +// use OCP namespace for all classes that are considered public. // This means that they should be used by apps instead of the internal ownCloud classes namespace OCP; @@ -42,7 +42,7 @@ namespace OCP; * An example of the queued task would be the creation of the thumbnail. As * soon as the user uploads a picture the gallery app registers the queued * task "create thumbnail" and saves the path in the parameter instead of doing - * the work right away. This makes the app more responsive. As soon as the task + * the work right away. This makes the app more responsive. As soon as the task * is done it will be deleted from the list. */ class BackgroundJob { @@ -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 ab01902ffe6..377150115ff 100644 --- a/lib/public/config.php +++ b/lib/public/config.php @@ -27,7 +27,7 @@ */ /** - * @brief use OCP namespace for all classes that are considered public. + * @brief use OCP namespace for all classes that are considered public. * * Classes that use this namespace are for use by apps, and not for use by internal * OC classes @@ -38,8 +38,6 @@ namespace OCP; * This class provides functions to read and write configuration data. configuration can be on a system, application or user level */ class Config { - - /** * @brief Gets a value from config.php * @param $key key @@ -49,11 +47,10 @@ 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 )); } - /** * @brief Sets a value * @param $key key @@ -63,74 +60,64 @@ 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 )); } - - /** - * @brief Gets the config value - * @param $app app - * @param $key key - * @param $default = null, default value if the key does not exist - * @returns the value or $default - * - * 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 ){ + /** + * @brief Gets the config value + * @param $app app + * @param $key key + * @param $default = null, default value if the key does not exist + * @returns the value or $default + * + * 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 ) { return(\OC_Appconfig::getValue( $app, $key, $default )); } - - /** - * @brief sets a value in the appconfig - * @param $app app - * @param $key key - * @param $value value - * @returns true/false - * - * Sets a value. If the key did not exist before it will be created. - */ - public static function setAppValue( $app, $key, $value ){ + /** + * @brief sets a value in the appconfig + * @param $app app + * @param $key key + * @param $value value + * @returns true/false + * + * Sets a value. If the key did not exist before it will be created. + */ + public static function setAppValue( $app, $key, $value ) { return(\OC_Appconfig::setValue( $app, $key, $value )); } - - /** - * @brief Gets the preference - * @param $user user - * @param $app app - * @param $key key - * @param $default = null, default value if the key does not exist - * @returns the value or $default - * - * 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 ){ + /** + * @brief Gets the preference + * @param $user user + * @param $app app + * @param $key key + * @param $default = null, default value if the key does not exist + * @returns the value or $default + * + * 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 ) { return(\OC_Preferences::getValue( $user, $app, $key, $default )); } - - /** - * @brief sets a value in the preferences - * @param $user user - * @param $app app - * @param $key key - * @param $value value - * @returns true/false - * - * 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 ){ + /** + * @brief sets a value in the preferences + * @param $user user + * @param $app app + * @param $key key + * @param $value value + * @returns true/false + * + * 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 ) { return(\OC_Preferences::setValue( $user, $app, $key, $value )); } - - - - - - } diff --git a/lib/public/db.php b/lib/public/db.php index 23c670cf442..6ce62b27ca2 100644 --- a/lib/public/db.php +++ b/lib/public/db.php @@ -26,7 +26,7 @@ * */ -// use OCP namespace for all classes that are considered public. +// use OCP namespace for all classes that are considered public. // This means that they should be used by apps instead of the internal ownCloud classes namespace OCP; @@ -34,8 +34,6 @@ namespace OCP; * This class provides access to the internal database system. Use this class exlusively if you want to access databases */ class DB { - - /** * @brief Prepare a SQL query * @param $query Query string @@ -43,11 +41,10 @@ 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)); } - /** * @brief gets last value of autoincrement * @param $table string The optional table name (will replace *PREFIX*) and add sequence suffix @@ -58,36 +55,30 @@ 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)); } - /** * @brief Start a transaction */ - public static function beginTransaction(){ + public static function beginTransaction() { return(\OC_DB::beginTransaction()); } - /** * @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()); } - /** * @brief check if a result is an error, works with MDB2 and PDOException * @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 32b3f036744..90889c59ad8 100644 --- a/lib/public/files.php +++ b/lib/public/files.php @@ -26,7 +26,7 @@ * */ -// use OCP namespace for all classes that are considered public. +// use OCP namespace for all classes that are considered public. // This means that they should be used by apps instead of the internal ownCloud classes namespace OCP; @@ -34,8 +34,6 @@ namespace OCP; * This class provides access to the internal filesystem abstraction layer. Use this class exlusively if you want to access files */ class Files { - - /** * @brief Recusive deletion of folders * @param string $dir path to the folder @@ -45,29 +43,26 @@ class Files { \OC_Helper::rmdirr( $dir ); } - /** * get the mimetype form a local file * @param string path * @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 )); } - /** * copy the contents of one stream to another * @param resource source * @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 )); } - /** * create a temporary file with an unique filename * @param string postfix @@ -75,22 +70,20 @@ 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 )); } - /** * create a temporary folder with an unique filename * @return string * * temporary files are automatically cleaned up after the script is finished */ - public static function tmpFolder(){ + public static function tmpFolder() { return(\OC_Helper::tmpFolder()); } - /** * Adds a suffix to the name in case the file exists * @@ -98,20 +91,16 @@ class Files { * @param $filename * @return string */ - public static function buildNotExistingFileName( $path, $filename ){ + public static function buildNotExistingFileName( $path, $filename ) { return(\OC_Helper::buildNotExistingFileName( $path, $filename )); } - /** - * @param string appid - * @param $app app - * @return OC_FilesystemView - */ - public static function getStorage( $app ){ + /** + * @param string appid + * @param $app app + * @return OC_FilesystemView + */ + public static function getStorage( $app ) { return \OC_App::getStorage( $app ); } - - - - } diff --git a/lib/public/json.php b/lib/public/json.php index 99df79173eb..2186dd8ee49 100644 --- a/lib/public/json.php +++ b/lib/public/json.php @@ -26,7 +26,7 @@ * */ -// use OCP namespace for all classes that are considered public. +// use OCP namespace for all classes that are considered public. // This means that they should be used by apps instead of the internal ownCloud classes namespace OCP; @@ -34,92 +34,91 @@ namespace OCP; * This class provides convinient functions to generate and send JSON data. Usefull for Ajax calls */ class JSON { - /** * @brief Encode and print $data in JSON format * @param array $data The data to use * @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 )); } /** * Check if the user is logged in, send json error msg if not. - * + * * This method checks if a user is logged in. If not, a json error * response will be return and the method will exit from execution * of the script. * The returned json will be in the format: - * + * * {"status":"error","data":{"message":"Authentication error."}} - * + * * Add this call to the start of all ajax method files that requires * an authenticated user. - * + * * @return string json formatted error string if not authenticated. */ - public static function checkLoggedIn(){ + public static function checkLoggedIn() { return(\OC_JSON::checkLoggedIn()); } /** * Check an ajax get/post call if the request token is valid. - * + * * This method checks for a valid variable 'requesttoken' in $_GET, * $_POST and $_SERVER. If a valid token is not found, a json error * response will be return and the method will exit from execution * of the script. * The returned json will be in the format: - * + * * {"status":"error","data":{"message":"Token expired. Please reload page."}} - * - * Add this call to the start of all ajax method files that creates, + * + * Add this call to the start of all ajax method files that creates, * updates or deletes anything. * In cases where you e.g. use an ajax call to load a dialog containing * a submittable form, you will need to add the requesttoken first as a * parameter to the ajax call, then assign it to the template and finally * add a hidden input field also named 'requesttoken' containing the value. - * + * * @return string json formatted error string if not valid. */ - public static function callCheck(){ + public static function callCheck() { return(\OC_JSON::callCheck()); } /** * Send json success msg - * + * * Return a json success message with optional extra data. - * @see OCP\JSON::error() for the format to use. - * + * @see OCP\JSON::error() for the format to use. + * * @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 )); } /** * Send json error msg - * - * Return a json error message with optional extra data for + * + * Return a json error message with optional extra data for * error message or app specific data. - * + * * Example use: - * + * * $id = [some value] * OCP\JSON::error(array('data':array('message':'An error happened', 'id': $id))); - * + * * Will return the json formatted string: - * + * * {"status":"error","data":{"message":"An error happened", "id":[some value]}} - * + * * @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,47 +127,46 @@ 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 )); } /** * Check if the App is enabled and send JSON error message instead - * + * * This method checks if a specific app is enabled. If not, a json error * response will be return and the method will exit from execution * of the script. * The returned json will be in the format: - * + * * {"status":"error","data":{"message":"Application is not enabled."}} - * + * * Add this call to the start of all ajax method files that requires * a specific app to be enabled. - * + * * @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 )); } /** * Check if the user is a admin, send json error msg if not - * + * * This method checks if the current user has admin rights. If not, a json error * response will be return and the method will exit from execution * of the script. * The returned json will be in the format: - * + * * {"status":"error","data":{"message":"Authentication error."}} - * + * * Add this call to the start of all ajax method files that requires * administrative rights. - * + * * @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/response.php b/lib/public/response.php index 8dff3bcd354..95e67a85720 100644 --- a/lib/public/response.php +++ b/lib/public/response.php @@ -26,7 +26,7 @@ * */ -// use OCP namespace for all classes that are considered public. +// use OCP namespace for all classes that are considered public. // This means that they should be used by apps instead of the internal ownCloud classes namespace OCP; @@ -34,8 +34,6 @@ namespace OCP; * This class provides convinient functions to send the correct http response headers */ class Response { - - /** * @brief Enable response caching by sending correct HTTP headers * @param $cache_time time to cache the response @@ -47,7 +45,6 @@ class Response { return(\OC_Response::enableCaching( $cache_time )); } - /** * Checks and set Last-Modified header, when the request matches sends a * 'not modified' response @@ -57,7 +54,6 @@ class Response { return(\OC_Response::setLastModifiedHeader( $lastModified )); } - /** * @brief disable browser caching * @see enableCaching with cache_time = 0 @@ -66,7 +62,6 @@ class Response { return(\OC_Response::disableCaching()); } - /** * Checks and set ETag header, when the request matches sends a * 'not modified' response @@ -76,7 +71,6 @@ class Response { return(\OC_Response::setETagHeader( $etag )); } - /** * @brief Send file as response, checking and setting caching headers * @param $filepath of file to send @@ -102,6 +96,4 @@ class Response { static public function redirect( $location ) { return(\OC_Response::redirect( $location )); } - - -} +}
\ No newline at end of file diff --git a/lib/public/share.php b/lib/public/share.php index a9fd23bfac8..b215d7f9389 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. @@ -229,6 +230,16 @@ class Share { $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner)); } else if ($shareType === self::SHARE_TYPE_LINK) { if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') { + if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) { + // If password is set delete the old link + if (isset($shareWith)) { + self::delete($checkExists['id']); + } else { + $message = 'Sharing '.$itemSource.' failed, because this item is already shared with a link'; + \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); + throw new \Exception($message); + } + } // Generate hash of password - same method as user passwords if (isset($shareWith)) { $forcePortable = (CRYPT_BLOWFISH != 1); @@ -241,26 +252,26 @@ class Share { \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); throw new \Exception($message); return false; - } else if ($shareType === self::SHARE_TYPE_CONTACT) { - if (!\OC_App::isEnabled('contacts')) { - $message = 'Sharing '.$itemSource.' failed, because the contacts app is not enabled'; - \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); - return false; - } - $vcard = \OC_Contacts_App::getContactVCard($shareWith); - if (!isset($vcard)) { - $message = 'Sharing '.$itemSource.' failed, because the contact does not exist'; - \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); - throw new \Exception($message); - } - $details = \OC_Contacts_VCard::structureContact($vcard); - // TODO Add ownCloud user to contacts vcard - if (!isset($details['EMAIL'])) { - $message = 'Sharing '.$itemSource.' failed, because no email address is associated with the contact'; - \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); - throw new \Exception($message); - } - return self::shareItem($itemType, $itemSource, self::SHARE_TYPE_EMAIL, $details['EMAIL'], $permissions); +// } else if ($shareType === self::SHARE_TYPE_CONTACT) { +// if (!\OC_App::isEnabled('contacts')) { +// $message = 'Sharing '.$itemSource.' failed, because the contacts app is not enabled'; +// \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); +// return false; +// } +// $vcard = \OC_Contacts_App::getContactVCard($shareWith); +// if (!isset($vcard)) { +// $message = 'Sharing '.$itemSource.' failed, because the contact does not exist'; +// \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); +// throw new \Exception($message); +// } +// $details = \OC_Contacts_VCard::structureContact($vcard); +// // TODO Add ownCloud user to contacts vcard +// if (!isset($details['EMAIL'])) { +// $message = 'Sharing '.$itemSource.' failed, because no email address is associated with the contact'; +// \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR); +// throw new \Exception($message); +// } +// return self::shareItem($itemType, $itemSource, self::SHARE_TYPE_EMAIL, $details['EMAIL'], $permissions); } else { // Future share types need to include their own conditions $message = 'Share type '.$shareType.' is not valid for '.$itemSource; @@ -326,10 +337,21 @@ class Share { public static function unshareFromSelf($itemType, $itemTarget) { if ($item = self::getItemSharedWith($itemType, $itemTarget)) { if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) { - // TODO + // Insert an extra row for the group share and set permission to 0 to prevent it from showing up for the user + $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 (?,?,?,?,?,?,?,?,?,?,?)'); + $query->execute(array($item['item_type'], $item['item_source'], $item['item_target'], $item['id'], self::$shareTypeGroupUserUnique, \OC_User::getUser(), $item['uid_owner'], 0, $item['stime'], $item['file_source'], $item['file_target'])); + \OC_DB::insertid('*PREFIX*share'); + // Delete all reshares by this user of the group share + self::delete($item['id'], true, \OC_User::getUser()); + } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) { + // Set permission to 0 to prevent it from showing up for the user + $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?'); + $query->execute(array(0, $item['id'])); + self::delete($item['id'], true); + } else { + self::delete($item['id']); } - // Delete - return self::delete($item['id'], true); + return true; } return false; } @@ -347,7 +369,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(); @@ -446,8 +468,11 @@ class Share { $collectionTypes[] = $type; } } - if (count($collectionTypes) > 1) { + if (!self::getBackend($itemType) instanceof Share_Backend_Collection) { unset($collectionTypes[0]); + } + // Return array if collections were found or the item type is a collection itself - collections can be inside collections + if (count($collectionTypes) > 0) { return $collectionTypes; } return false; @@ -492,9 +517,13 @@ class Share { $root = ''; if ($includeCollections && !isset($item) && ($collectionTypes = self::getCollectionItemTypes($itemType))) { // If includeCollections is true, find collections of this item type, e.g. a music album contains songs - $itemTypes = array_merge(array($itemType), $collectionTypes); + if (!in_array($itemType, $collectionTypes)) { + $itemTypes = array_merge(array($itemType), $collectionTypes); + } else { + $itemTypes = $collectionTypes; + } $placeholders = join(',', array_fill(0, count($itemTypes), '?')); - $where = ' WHERE `item_type` IN ('.$placeholders.')'; + $where .= ' WHERE item_type IN ('.$placeholders.'))'; $queryArgs = $itemTypes; } else { $where = ' WHERE `item_type` = ?'; @@ -563,12 +592,13 @@ class Share { } else { if ($itemType == 'file' || $itemType == 'folder') { $where .= ' `file_target` = ?'; + $item = \OC_Filesystem::normalizePath($item); } else { $where .= ' `item_target` = ?'; } } $queryArgs[] = $item; - if ($includeCollections && $collectionTypes = self::getCollectionItemTypes($itemType)) { + if ($includeCollections && $collectionTypes) { $placeholders = join(',', array_fill(0, count($collectionTypes), '?')); $where .= ' OR item_type IN ('.$placeholders.'))'; $queryArgs = array_merge($queryArgs, $collectionTypes); @@ -627,6 +657,9 @@ class Share { $row['share_with'] = $items[$row['parent']]['share_with']; // Remove the parent group share unset($items[$row['parent']]); + if ($row['permissions'] == 0) { + continue; + } } else if (!isset($uidOwner)) { // Check if the same target already exists if (isset($targets[$row[$column]])) { @@ -681,29 +714,54 @@ class Share { } } // Check if this is a collection of the requested item type - if ($includeCollections && $row['item_type'] != $itemType) { + if ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) { if (($collectionBackend = self::getBackend($row['item_type'])) && $collectionBackend instanceof Share_Backend_Collection) { - $row['collection'] = array('item_type' => $itemType, $column => $row[$column]); - // Fetch all of the children sources - $children = $collectionBackend->getChildren($row[$column]); - foreach ($children as $child) { - $childItem = $row; - $childItem['item_source'] = $child; - // $childItem['item_target'] = $child['target']; TODO - if (isset($item)) { - if ($childItem[$column] == $item) { - // Return only the item instead of a 2-dimensional array - if ($limit == 1 && $format == self::FORMAT_NONE) { - return $childItem; + // Collections can be inside collections, check if the item is a collection + if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) { + $collectionItems[] = $row; + } else { + $collection = array(); + $collection['item_type'] = $row['item_type']; + if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') { + $collection['path'] = basename($row['path']); + } + $row['collection'] = $collection; + // Fetch all of the children sources + $children = $collectionBackend->getChildren($row[$column]); + foreach ($children as $child) { + $childItem = $row; + $childItem['item_type'] = $itemType; + if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') { + $childItem['item_source'] = $child['source']; + $childItem['item_target'] = $child['target']; + } + if ($backend instanceof Share_Backend_File_Dependent) { + if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') { + $childItem['file_source'] = $child['source']; } else { - // Unset the items array and break out of both loops - $items = array(); - $items[] = $childItem; - break 2; + $childItem['file_source'] = \OC_FileCache::getId($child['file_path']); } + $childItem['file_target'] = \OC_Filesystem::normalizePath($child['file_path']); + } + if (isset($item)) { + if ($childItem[$column] == $item) { + // Return only the item instead of a 2-dimensional array + if ($limit == 1) { + if ($format == self::FORMAT_NONE) { + return $childItem; + } else { + // Unset the items array and break out of both loops + $items = array(); + $items[] = $childItem; + break 2; + } + } else { + $collectionItems[] = $childItem; + } + } + } else { + $collectionItems[] = $childItem; } - } else { - $collectionItems[] = $childItem; } } } @@ -769,9 +827,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 { @@ -781,6 +839,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); @@ -789,7 +849,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); @@ -807,35 +867,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; } @@ -844,24 +903,15 @@ 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)); + \OC_DB::insertid('*PREFIX*share'); } } if ($parentFolder === true) { @@ -869,18 +919,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; @@ -902,14 +952,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') { @@ -927,19 +979,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(); @@ -1030,7 +1098,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) { @@ -1047,6 +1135,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']); + } + } + } /** @@ -1121,10 +1217,8 @@ interface Share_Backend_Collection extends Share_Backend { /** * @brief Get the sources of the children of the item * @param string Item source - * @return array Returns an array of sources + * @return array Returns an array of children each inside an array with the keys: source, target, and file_path if applicable */ public function getChildren($itemSource); } - -?> diff --git a/lib/public/template.php b/lib/public/template.php index a0ed618cb2c..4cda3650866 100644 --- a/lib/public/template.php +++ b/lib/public/template.php @@ -26,7 +26,7 @@ * */ -// use OCP namespace for all classes that are considered public. +// use OCP namespace for all classes that are considered public. // This means that they should be used by apps instead of the internal ownCloud classes namespace OCP; @@ -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 )); } @@ -88,13 +88,13 @@ function simple_file_size($bytes) { /** * @brief Generate html code for an options block. - * @param $options the options - * @param $selected which one is selected? - * @param $params the parameters + * @param $options the options + * @param $selected which one is selected? + * @param $params the parameters * @returns html options */ function html_select_options($options, $selected, $params=array()) { - return(\html_select_options($options, $selected, $params)); + return(\html_select_options($options, $selected, $params)); } diff --git a/lib/public/user.php b/lib/public/user.php index 2fa599488a7..b320ce8ea0c 100644 --- a/lib/public/user.php +++ b/lib/public/user.php @@ -26,7 +26,7 @@ * */ -// use OCP namespace for all classes that are considered public. +// use OCP namespace for all classes that are considered public. // This means that they should be used by apps instead of the internal ownCloud classes namespace OCP; @@ -34,60 +34,53 @@ namespace OCP; * This class provides access to the user management. You can get information about the currently logged in user and the permissions for example */ 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(); } - /** * @brief Get a list of all users * @returns array with all uids * * 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(); } - /** * @brief Check if the user is logged in * @returns true/false * * Checks if the user is logged in */ - public static function isLoggedIn(){ + public static function isLoggedIn() { return \OC_USER::isLoggedIn(); } - /** * @brief check if a user exists * @param string $uid the username * @return boolean */ - public static function userExists( $uid ){ + public static function userExists( $uid ) { return \OC_USER::userExists( $uid ); } - /** * @brief Loggs the user out including all the session data * @returns true * * Logout, destroys session */ - public static function logout(){ + public static function logout() { return \OC_USER::logout(); } - /** * @brief Check if the password is correct * @param $uid The username @@ -96,27 +89,22 @@ 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 ); } + /** + * Check if the user is a admin, redirects to home if not + */ + public static function checkAdminUser() { + \OC_Util::checkAdminUser(); + } - /** - * Check if the user is a admin, redirects to home if not - */ - public static function checkAdminUser(){ - \OC_Util::checkAdminUser(); - } - - - /** - * Check if the user is logged in, redirects to home if not. With - * redirect URL parameter to the request URI. - */ - public static function checkLoggedIn(){ - \OC_Util::checkLoggedIn(); - } - - - + /** + * Check if the user is logged in, redirects to home if not. With + * redirect URL parameter to the request URI. + */ + public static function checkLoggedIn() { + \OC_Util::checkLoggedIn(); + } } diff --git a/lib/public/util.php b/lib/public/util.php index 8d7303bf7a4..747448e62eb 100644 --- a/lib/public/util.php +++ b/lib/public/util.php @@ -34,8 +34,6 @@ namespace OCP; * This class provides different helper functions to make the life of a developer easier */ class Util { - - // consts for Logging const DEBUG=0; const INFO=1; @@ -43,16 +41,14 @@ class Util { const ERROR=3; const FATAL=4; - /** * @brief get the current installed version of ownCloud * @return array */ - public static function getVersion(){ + public static function getVersion() { return(\OC_Util::getVersion()); } - /** * @brief send an email * @param string $toaddress @@ -68,36 +64,33 @@ class Util { \OC_MAIL::send( $toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname, $html=0, $altbody='', $ccaddress='', $ccname='', $bcc=''); } - - /** + /** * @brief write a message in the log * @param string $app * @param string $message * @param int level - */ - public static function writeLog( $app, $message, $level ) { - // call the internal log class - \OC_LOG::write( $app, $message, $level ); - } - + */ + public static function writeLog( $app, $message, $level ) { + // call the internal log class + \OC_LOG::write( $app, $message, $level ); + } /** * @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 ); - } - + } /** * @brief add a javascript file * @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 ); - } + } /** * @brief Add a custom element to the header @@ -105,7 +98,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,25 +107,23 @@ 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 )); } - - /** * @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 )); } - /** * @brief Creates an absolute url for remote use * @param $service id @@ -155,17 +146,17 @@ class Util { return \OC_Helper::linkToPublic($service); } - /** * @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,11 +188,10 @@ 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 )); } - /** * @brief Make a human file size * @param $bytes file size in bytes @@ -209,7 +199,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 +212,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,11 +228,10 @@ 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 )); } - /** * @brief emitts a signal * @param $signalclass class name of emitter @@ -254,25 +243,23 @@ 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 )); } - /** - * Register an get/post call. This is important to prevent CSRF attacks + * 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()); } - /** * 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 +271,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 +285,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 f8a4b8e96eb..0b6ad050024 100644 --- a/lib/search.php +++ b/lib/search.php @@ -27,45 +27,45 @@ class OC_Search{ static private $providers=array(); static private $registeredProviders=array(); - + /** * remove all registered search providers */ - public static function clearProviders(){ + public static function clearProviders() { self::$providers=array(); self::$registeredProviders=array(); } - + /** * 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); } - + /** * search all provider for $query * @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; } - + /** * 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 b3ee79b4770..b617b9c5d94 100644 --- a/lib/search/provider.php +++ b/lib/search/provider.php @@ -4,11 +4,11 @@ */ abstract class OC_Search_Provider { private $options; - - public function __construct($options){ + + public function __construct($options) { $this->options=$options; } - + /** * search for $query * @param string $query 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 f7e8c6950ce..c21c8be3957 100644 --- a/lib/setup.php +++ b/lib/setup.php @@ -9,7 +9,7 @@ $opts = array( 'hasSQLite' => $hasSQLite, 'hasMySQL' => $hasMySQL, 'hasPostgreSQL' => $hasPostgreSQL, - 'hasOracle' => $hasOracle, + 'hasOracle' => $hasOracle, 'directory' => $datadir, 'errors' => array(), ); @@ -18,7 +18,7 @@ if(isset($_POST['install']) AND $_POST['install']=='true') { // We have to launch the installation process : $e = OC_Setup::install($_POST); $errors = array('errors' => $e); - + if(count($e) > 0) { //OC_Template::printGuestPage("", "error", array("errors" => $errors)); $options = array_merge($_POST, $opts, $errors); @@ -37,7 +37,7 @@ class OC_Setup { public static function install($options) { $error = array(); $dbtype = $options['dbtype']; - + if(empty($options['adminlogin'])) { $error[] = 'Set an admin username.'; } @@ -51,10 +51,10 @@ class OC_Setup { if($dbtype=='mysql' or $dbtype == 'pgsql' or $dbtype == 'oci') { //mysql and postgresql needs more config options if($dbtype=='mysql') $dbprettyname = 'MySQL'; - else if($dbtype=='pgsql') - $dbprettyname = 'PostgreSQL'; - else - $dbprettyname = 'Oracle'; + else if($dbtype=='pgsql') + $dbprettyname = 'PostgreSQL'; + else + $dbprettyname = 'Oracle'; if(empty($options['dbuser'])) { @@ -63,7 +63,7 @@ class OC_Setup { if(empty($options['dbname'])) { $error[] = "$dbprettyname enter the database name."; } - if(empty($options['dbhost'])) { + if($dbtype != 'oci' && empty($options['dbhost'])) { $error[] = "$dbprettyname set the database host."; } } @@ -72,9 +72,9 @@ class OC_Setup { $username = htmlspecialchars_decode($options['adminlogin']); $password = htmlspecialchars_decode($options['adminpass']); $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'; } @@ -84,8 +84,8 @@ class OC_Setup { //write the config file OC_Config::setValue('datadirectory', $datadir); - OC_Config::setValue('dbtype', $dbtype); - OC_Config::setValue('version',implode('.',OC_Util::getVersion())); + OC_Config::setValue('dbtype', $dbtype); + OC_Config::setValue('version',implode('.',OC_Util::getVersion())); if($dbtype == 'mysql') { $dbuser = $options['dbuser']; $dbpass = $options['dbpass']; @@ -107,14 +107,14 @@ class OC_Setup { } else { $oldUser=OC_Config::getValue('dbuser', false); - + $query="SELECT user FROM mysql.user WHERE user='$dbuser'"; //this should be enough to check for admin rights in mysql if(mysql_query($query, $connection)) { //use the admin login data for the new database user //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) { @@ -184,9 +184,9 @@ class OC_Setup { $dbusername='oc_'.$username; //create a new password so we don't need to store the admin config in the config file $dbpassword=md5(time()); - + self::pg_createDBUser($dbusername, $dbpassword, $connection); - + OC_CONFIG::setValue('dbuser', $dbusername); OC_CONFIG::setValue('dbpassword', $dbpassword); @@ -232,120 +232,128 @@ class OC_Setup { } } } - elseif($dbtype == 'oci') { - $dbuser = $options['dbuser']; - $dbpass = $options['dbpass']; - $dbname = $options['dbname']; - $dbtablespace = $options['dbtablespace']; - $dbhost = $options['dbhost']; - $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; - OC_CONFIG::setValue('dbname', $dbname); - OC_CONFIG::setValue('dbtablespace', $dbtablespace); - OC_CONFIG::setValue('dbhost', $dbhost); - OC_CONFIG::setValue('dbtableprefix', $dbtableprefix); - - $e_host = addslashes($dbhost); - $e_dbname = addslashes($dbname); - //check if the database user has admin right - $connection_string = '//'.$e_host.'/'.$e_dbname; - $connection = @oci_connect($dbuser, $dbpass, $connection_string); - if(!$connection) { - $e = oci_error(); - $error[] = array( - 'error' => 'Oracle username and/or password not valid', - 'hint' => 'You need to enter either an existing account or the administrator.' - ); - return $error; - } else { - //check for roles creation rights in oracle - - $query="SELECT count(*) FROM user_role_privs, role_sys_privs WHERE user_role_privs.granted_role = role_sys_privs.role AND privilege = 'CREATE ROLE'"; - $stmt = oci_parse($connection, $query); - if (!$stmt) { - $entry='DB Error: "'.oci_last_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.'<br />'; - echo($entry); - } - $result = oci_execute($stmt); - if($result) { - $row = oci_fetch_row($stmt); - } - if($result and $row[0] > 0) { - //use the admin login data for the new database user - - //add prefix to the oracle user name to prevent collisions - $dbusername='oc_'.$username; - //create a new password so we don't need to store the admin config in the config file - $dbpassword=md5(time().$dbpass); - - //oracle passwords are treated as identifiers: - // must start with aphanumeric char - // needs to be shortened to 30 bytes, as the two " needed to escape the identifier count towards the identifier length. - $dbpassword=substr($dbpassword, 0, 30); - - self::oci_createDBUser($dbusername, $dbpassword, $dbtablespace, $connection); - - OC_CONFIG::setValue('dbuser', $dbusername); - OC_CONFIG::setValue('dbname', $dbusername); - OC_CONFIG::setValue('dbpassword', $dbpassword); - - //create the database not neccessary, oracle implies user = schema - //self::oci_createDatabase($dbname, $dbusername, $connection); - } else { - - OC_CONFIG::setValue('dbuser', $dbuser); - OC_CONFIG::setValue('dbname', $dbname); - OC_CONFIG::setValue('dbpassword', $dbpass); - - //create the database not neccessary, oracle implies user = schema - //self::oci_createDatabase($dbname, $dbuser, $connection); - } - - //FIXME check tablespace exists: select * from user_tablespaces - - // the connection to dbname=oracle is not needed anymore - oci_close($connection); - - // connect to the oracle database (schema=$dbuser) an check if the schema needs to be filled - $dbuser = OC_CONFIG::getValue('dbuser'); - //$dbname = OC_CONFIG::getValue('dbname'); - $dbpass = OC_CONFIG::getValue('dbpassword'); - - $e_host = addslashes($dbhost); - $e_dbname = addslashes($dbname); - - $connection_string = '//'.$e_host.'/'.$e_dbname; - $connection = @oci_connect($dbuser, $dbpass, $connection_string); - if(!$connection) { - $error[] = array( - 'error' => 'Oracle username and/or password not valid', - 'hint' => 'You need to enter either an existing account or the administrator.' - ); - return $error; - } else { - $query = "SELECT count(*) FROM user_tables WHERE table_name = :un"; - $stmt = oci_parse($connection, $query); - $un = $dbtableprefix.'users'; - oci_bind_by_name($stmt, ':un', $un); - if (!$stmt) { - $entry='DB Error: "'.oci_last_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.'<br />'; - echo($entry); - } - $result = oci_execute($stmt); - - if($result) { - $row = oci_fetch_row($stmt); - } - if(!$result or $row[0]==0) { - OC_DB::createDbFromStructure('db_structure.xml'); - } - } - } - } + elseif($dbtype == 'oci') { + $dbuser = $options['dbuser']; + $dbpass = $options['dbpass']; + $dbname = $options['dbname']; + $dbtablespace = $options['dbtablespace']; + $dbhost = isset($options['dbhost'])?$options['dbhost']:''; + $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_'; + OC_CONFIG::setValue('dbname', $dbname); + OC_CONFIG::setValue('dbtablespace', $dbtablespace); + OC_CONFIG::setValue('dbhost', $dbhost); + OC_CONFIG::setValue('dbtableprefix', $dbtableprefix); + + $e_host = addslashes($dbhost); + $e_dbname = addslashes($dbname); + //check if the database user has admin right + if ($e_host == '') { + $easy_connect_string = $e_dbname; // use dbname as easy connect name + } else { + $easy_connect_string = '//'.$e_host.'/'.$e_dbname; + } + $connection = @oci_connect($dbuser, $dbpass, $easy_connect_string); + if(!$connection) { + $e = oci_error(); + $error[] = array( + 'error' => 'Oracle username and/or password not valid', + 'hint' => 'You need to enter either an existing account or the administrator.' + ); + return $error; + } else { + //check for roles creation rights in oracle + + $query="SELECT count(*) FROM user_role_privs, role_sys_privs WHERE user_role_privs.granted_role = role_sys_privs.role AND privilege = 'CREATE ROLE'"; + $stmt = oci_parse($connection, $query); + if (!$stmt) { + $entry='DB Error: "'.oci_last_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.'<br />'; + echo($entry); + } + $result = oci_execute($stmt); + if($result) { + $row = oci_fetch_row($stmt); + } + if($result and $row[0] > 0) { + //use the admin login data for the new database user + + //add prefix to the oracle user name to prevent collisions + $dbusername='oc_'.$username; + //create a new password so we don't need to store the admin config in the config file + $dbpassword=md5(time().$dbpass); + + //oracle passwords are treated as identifiers: + // must start with aphanumeric char + // needs to be shortened to 30 bytes, as the two " needed to escape the identifier count towards the identifier length. + $dbpassword=substr($dbpassword, 0, 30); + + self::oci_createDBUser($dbusername, $dbpassword, $dbtablespace, $connection); + + OC_CONFIG::setValue('dbuser', $dbusername); + OC_CONFIG::setValue('dbname', $dbusername); + OC_CONFIG::setValue('dbpassword', $dbpassword); + + //create the database not neccessary, oracle implies user = schema + //self::oci_createDatabase($dbname, $dbusername, $connection); + } else { + + OC_CONFIG::setValue('dbuser', $dbuser); + OC_CONFIG::setValue('dbname', $dbname); + OC_CONFIG::setValue('dbpassword', $dbpass); + + //create the database not neccessary, oracle implies user = schema + //self::oci_createDatabase($dbname, $dbuser, $connection); + } + + //FIXME check tablespace exists: select * from user_tablespaces + + // the connection to dbname=oracle is not needed anymore + oci_close($connection); + + // connect to the oracle database (schema=$dbuser) an check if the schema needs to be filled + $dbuser = OC_CONFIG::getValue('dbuser'); + //$dbname = OC_CONFIG::getValue('dbname'); + $dbpass = OC_CONFIG::getValue('dbpassword'); + + $e_host = addslashes($dbhost); + $e_dbname = addslashes($dbname); + + if ($e_host == '') { + $easy_connect_string = $e_dbname; // use dbname as easy connect name + } else { + $easy_connect_string = '//'.$e_host.'/'.$e_dbname; + } + $connection = @oci_connect($dbuser, $dbpass, $easy_connect_string); + if(!$connection) { + $error[] = array( + 'error' => 'Oracle username and/or password not valid', + 'hint' => 'You need to enter either an existing account or the administrator.' + ); + return $error; + } else { + $query = "SELECT count(*) FROM user_tables WHERE table_name = :un"; + $stmt = oci_parse($connection, $query); + $un = $dbtableprefix.'users'; + oci_bind_by_name($stmt, ':un', $un); + if (!$stmt) { + $entry='DB Error: "'.oci_last_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.'<br />'; + echo($entry); + } + $result = oci_execute($stmt); + + if($result) { + $row = oci_fetch_row($stmt); + } + if(!$result or $row[0]==0) { + OC_DB::createDbFromStructure('db_structure.xml'); + } + } + } + } 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 @@ -428,7 +436,7 @@ class OC_Setup { } } $query = "REVOKE ALL PRIVILEGES ON DATABASE \"$e_name\" FROM PUBLIC"; - $result = pg_query($connection, $query); + $result = pg_query($connection, $query); } private static function pg_createDBUser($name,$password,$connection) { @@ -462,79 +470,79 @@ class OC_Setup { } } } - /** - * - * @param String $name - * @param String $password - * @param String $tablespace - * @param resource $connection - */ - private static function oci_createDBUser($name, $password, $tablespace, $connection) { - - $query = "SELECT * FROM all_users WHERE USERNAME = :un"; - $stmt = oci_parse($connection, $query); - if (!$stmt) { - $entry='DB Error: "'.oci_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.'<br />'; - echo($entry); - } - oci_bind_by_name($stmt, ':un', $name); - $result = oci_execute($stmt); - if(!$result) { - $entry='DB Error: "'.oci_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.'<br />'; - echo($entry); - } - - if(! oci_fetch_row($stmt)) { - //user does not exists let's create it :) - //password must start with alphabetic character in oracle - $query = 'CREATE USER '.$name.' IDENTIFIED BY "'.$password.'" DEFAULT TABLESPACE '.$tablespace; //TODO set default tablespace - $stmt = oci_parse($connection, $query); - if (!$stmt) { - $entry='DB Error: "'.oci_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.'<br />'; - echo($entry); - } - //oci_bind_by_name($stmt, ':un', $name); - $result = oci_execute($stmt); - if(!$result) { - $entry='DB Error: "'.oci_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.', name:'.$name.', password:'.$password.'<br />'; - echo($entry); - } - } else { // change password of the existing role - $query = "ALTER USER :un IDENTIFIED BY :pw"; - $stmt = oci_parse($connection, $query); - if (!$stmt) { - $entry='DB Error: "'.oci_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.'<br />'; - echo($entry); - } - oci_bind_by_name($stmt, ':un', $name); - oci_bind_by_name($stmt, ':pw', $password); - $result = oci_execute($stmt); - if(!$result) { - $entry='DB Error: "'.oci_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.'<br />'; - echo($entry); - } - } - // grant neccessary roles - $query = 'GRANT CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE TRIGGER, UNLIMITED TABLESPACE TO '.$name; - $stmt = oci_parse($connection, $query); - if (!$stmt) { - $entry='DB Error: "'.oci_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.'<br />'; - echo($entry); - } - $result = oci_execute($stmt); - if(!$result) { - $entry='DB Error: "'.oci_error($connection).'"<br />'; - $entry.='Offending command was: '.$query.', name:'.$name.', password:'.$password.'<br />'; - echo($entry); - } - } + /** + * + * @param String $name + * @param String $password + * @param String $tablespace + * @param resource $connection + */ + private static function oci_createDBUser($name, $password, $tablespace, $connection) { + + $query = "SELECT * FROM all_users WHERE USERNAME = :un"; + $stmt = oci_parse($connection, $query); + if (!$stmt) { + $entry='DB Error: "'.oci_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.'<br />'; + echo($entry); + } + oci_bind_by_name($stmt, ':un', $name); + $result = oci_execute($stmt); + if(!$result) { + $entry='DB Error: "'.oci_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.'<br />'; + echo($entry); + } + + if(! oci_fetch_row($stmt)) { + //user does not exists let's create it :) + //password must start with alphabetic character in oracle + $query = 'CREATE USER '.$name.' IDENTIFIED BY "'.$password.'" DEFAULT TABLESPACE '.$tablespace; //TODO set default tablespace + $stmt = oci_parse($connection, $query); + if (!$stmt) { + $entry='DB Error: "'.oci_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.'<br />'; + echo($entry); + } + //oci_bind_by_name($stmt, ':un', $name); + $result = oci_execute($stmt); + if(!$result) { + $entry='DB Error: "'.oci_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.', name:'.$name.', password:'.$password.'<br />'; + echo($entry); + } + } else { // change password of the existing role + $query = "ALTER USER :un IDENTIFIED BY :pw"; + $stmt = oci_parse($connection, $query); + if (!$stmt) { + $entry='DB Error: "'.oci_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.'<br />'; + echo($entry); + } + oci_bind_by_name($stmt, ':un', $name); + oci_bind_by_name($stmt, ':pw', $password); + $result = oci_execute($stmt); + if(!$result) { + $entry='DB Error: "'.oci_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.'<br />'; + echo($entry); + } + } + // grant neccessary roles + $query = 'GRANT CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE TRIGGER, UNLIMITED TABLESPACE TO '.$name; + $stmt = oci_parse($connection, $query); + if (!$stmt) { + $entry='DB Error: "'.oci_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.'<br />'; + echo($entry); + } + $result = oci_execute($stmt); + if(!$result) { + $entry='DB Error: "'.oci_error($connection).'"<br />'; + $entry.='Offending command was: '.$query.', name:'.$name.', password:'.$password.'<br />'; + echo($entry); + } + } /** * create .htaccess files for apache hosts @@ -552,7 +560,7 @@ class OC_Setup { $content.= "</IfModule>\n"; $content.= "<IfModule mod_rewrite.c>\n"; $content.= "RewriteEngine on\n"; - $content.= "RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n"; + $content.= "RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n"; $content.= "RewriteRule ^.well-known/host-meta /public.php?service=host-meta [QSA,L]\n"; $content.= "RewriteRule ^.well-known/carddav /remote.php/carddav/ [R]\n"; $content.= "RewriteRule ^.well-known/caldav /remote.php/caldav/ [R]\n"; 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 718fe922ffe..363e4a97cad 100644 --- a/lib/subadmin.php +++ b/lib/subadmin.php @@ -3,7 +3,7 @@ * ownCloud * * @author Georg Ehrke - * @copyright 2012 Georg Ehrke + * @copyright 2012 Georg Ehrke * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE @@ -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,96 +76,96 @@ 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; } - + /** * @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; } - + /** * @brief checks if a user is a SubAdmin of a group * @param $uid uid of the 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; } - + /** * @brief checks if a user is a 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; } - + /** * @brief checks if a user is a accessible by a subadmin * @param $subadmin uid of the 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; } } return false; } - + /* * @brief alias for self::isSubAdminofGroup() */ - public static function isGroupAccessible($subadmin, $group){ + public static function isGroupAccessible($subadmin, $group) { return self::isSubAdminofGroup($subadmin, $group); } /** * @brief delete all SubAdmins by uid - * @param $parameters + * @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 a10ddcd5c33..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; @@ -161,7 +162,7 @@ class OC_Template{ header('X-Frame-Options: Sameorigin'); header('X-XSS-Protection: 1; mode=block'); header('X-Content-Type-Options: nosniff'); - + $this->findTemplate($name); } @@ -171,17 +172,17 @@ class OC_Template{ * mobile -> interface for smartphones * tablet -> interface for tablets * standalone -> the default interface but without header, footer and - * sidebar, just the application. Useful to use just a specific - * app on the desktop in a standalone window. + * 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,21 +201,21 @@ 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']; - if($formfactor=='default') { + if($formfactor=='default') { $fext=''; - }elseif($formfactor=='mobile') { + }elseif($formfactor=='mobile') { $fext='.mobile'; - }elseif($formfactor=='tablet') { + }elseif($formfactor=='tablet') { $fext='.tablet'; - }elseif($formfactor=='standalone') { + }elseif($formfactor=='standalone') { $fext='.standalone'; }else{ $fext=''; @@ -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 588a7845997..c898628bcdf 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); @@ -29,19 +29,29 @@ class OC_TemplateLayout extends OC_Template { break; } } - }else{ - parent::__construct( 'core', 'layout.guest' ); + } else if ($renderas == 'guest') { + parent::__construct('core', 'layout.guest'); + } else { + parent::__construct('core', 'layout.base'); } $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 + if (OC_Config::getValue('installed', false) && !OC_AppConfig::getValue('core', 'remote_core.css', false)) { + OC_AppConfig::setValue('core', 'remote_core.css', '/core/minimizer.php'); + OC_AppConfig::setValue('core', 'remote_core.js', '/core/minimizer.php'); + } + // Add the js files $jsfiles = self::findJavascriptFiles(OC_Util::$scripts); $this->assign('jsfiles', array(), false); + if (!empty(OC_Util::$core_scripts)) { + $this->append( 'jsfiles', OC_Helper::linkToRemote('core.js', false)); + } foreach($jsfiles as $info) { $root = $info[0]; $web = $info[1]; @@ -51,8 +61,10 @@ class OC_TemplateLayout extends OC_Template { // Add the css files $cssfiles = self::findStylesheetFiles(OC_Util::$styles); - $this->assign('cssfiles', array()); + if (!empty(OC_Util::$core_styles)) { + $this->append( 'cssfiles', OC_Helper::linkToRemote('core.css', false)); + } foreach($cssfiles as $info) { $root = $info[0]; $web = $info[1]; @@ -63,7 +75,7 @@ class OC_TemplateLayout extends OC_Template { foreach(OC::$APPSROOTS as $app_root) { if($root == $app_root['path']) { $in_root = true; - break; + break; } } @@ -94,7 +106,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' ); @@ -102,7 +114,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')) { @@ -130,7 +142,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" )) { @@ -145,7 +157,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' ); @@ -153,7 +165,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 c14ef2d6ca6..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,42 +401,42 @@ 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; } } return false; } - + /** * 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')); } - + /** * 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')); } - + /** * checks if a user is enabled * @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 a4cffe5d0c1..76b44a2f6ca 100644 --- a/lib/user/database.php +++ b/lib/user/database.php @@ -43,9 +43,9 @@ class OC_User_Database extends OC_User_Backend { * @var PasswordHash */ 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); @@ -53,7 +53,7 @@ class OC_User_Database extends OC_User_Backend { return self::$hasher; } - + /** * @brief Create a new user * @param $uid The username of the user to create @@ -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 ){ - $query = OC_DB::prepare( 'SELECT `uid`, `password` FROM `*PREFIX*users` WHERE `uid` = ?' ); + 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,10 +169,10 @@ class OC_User_Database extends OC_User_Backend { * @param string $uid the username * @return boolean */ - public function userExists($uid){ - $query = OC_DB::prepare( 'SELECT * FROM `*PREFIX*users` WHERE `uid` = ?' ); + public function userExists($uid) { + $query = OC_DB::prepare( 'SELECT * FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)' ); $result = $query->execute( array( $uid )); - + return $result->numRows() > 0; } @@ -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 547c0201b69..2668341408d 100644 --- a/lib/user/http.php +++ b/lib/user/http.php @@ -30,29 +30,29 @@ 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); - + } - + /** * check if an url is a valid login * @param string url * @return boolean */ - private function matchUrl($url){ + private function matchUrl($url) { return ! is_null(parse_url($url,PHP_URL_USER)); } - + /** * @brief Check if the password is correct * @param $uid The username @@ -62,12 +62,12 @@ 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); - + $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$password); @@ -76,7 +76,7 @@ class OC_User_HTTP extends OC_User_Backend { curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); - + curl_close($ch); return $status==200; @@ -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 01f53cb2f38..f28f83ad717 100755 --- a/lib/util.php +++ b/lib/util.php @@ -14,38 +14,42 @@ 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()) { + $user = OC_User::getUser(); + } + + // the filesystem will finish when $user is not empty, + // mark fs setup here to avoid doing the setup from loading + // OC_Filesystem + if ($user != '') { + self::$fsSetup=true; + } + $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 we are not forced to load a specific user we load the one that is logged in - if( $user == "" && OC_User::isLoggedIn()){ - $user = OC_User::getUser(); - } - - 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'; - OC_Filesystem::mount('OC_Filestorage_Local',array('datadir'=>$user_root), $user); - if( !is_dir( $userdirectory )){ + if( !is_dir( $userdirectory )) { mkdir( $userdirectory, 0755, true ); } - OC_Filesystem::mount('OC_Filestorage_Local',array('datadir'=>$user_root), $user); - //jail the user into his "home" directory + OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $user_root), $user); OC_Filesystem::init($user_dir); $quotaProxy=new OC_FileProxy_Quota(); OC_FileProxy::register($quotaProxy); - self::$fsSetup=true; // Load personal mount config if (is_file($user_root.'/mount.php')) { $mountConfig = include($user_root.'/mount.php'); @@ -54,18 +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 setupFS4all(){ - foreach(OC_User::getUsers() as $user){ - OC_Filesystem::mount('OC_Filestorage_Local',array('datadir'=>OC_User::getHome($singleuser)), $user); - } - } - - public static function tearDownFS(){ + public static function tearDownFS() { OC_Filesystem::tearDown(); self::$fsSetup=false; } @@ -74,23 +79,24 @@ class OC_Util { * get the current installed version of ownCloud * @return array */ - public static function getVersion(){ - return array(4,82,5); + 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,7); } /** * get the current installed version string of ownCloud * @return string */ - public static function getVersionString(){ - return '5 pre alpha 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 ''; } @@ -100,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"; @@ -118,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"; @@ -136,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); } @@ -146,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; @@ -191,12 +197,14 @@ 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(); + $web_server_restart= false; //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 + $web_server_restart= true; } //common hint for all file permissons error messages @@ -210,32 +218,32 @@ class OC_Util { // Check if there is a writable install folder. if(OC_Config::getValue('appstoreenabled', true)) { if( OC_App::getInstallPath() === null || !is_writable(OC_App::getInstallPath())) { - $errors[]=array('error'=>"Can't write into apps directory",'hint'=>"You can usually fix this by giving the webserver user write access to the apps directory + $errors[]=array('error'=>"Can't write into apps directory",'hint'=>"You can usually fix this by giving the webserver user write access to the apps directory in owncloud or disabling the appstore in the config file."); } } $CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); //check for correct file permissions - if(!stristr(PHP_OS, 'WIN')){ - $permissionsModHint="Please change the permissions to 0770 so that the directory cannot be listed by other users."; + 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); } } @@ -244,37 +252,52 @@ 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.'); + $web_server_restart= false; } - 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.'); + $web_server_restart= false; } - 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.'); + $web_server_restart= false; } - 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.'); + $web_server_restart= false; } - 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.'); + $web_server_restart= false; + } + if(!function_exists('gzencode')) { + $errors[]=array('error'=>'PHP module zlib is not installed.<br/>','hint'=>'Please ask your server administrator to install the module.'); + $web_server_restart= false; } - if(floatval(phpversion())<5.3){ + 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.'); + $web_server_restart= false; } - 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.'); + $web_server_restart= false; + } + + if($web_server_restart) { + $errors[]=array('error'=>'PHP modules have been installed, but they are still listed as missing?<br/>','hint'=>'Please ask your server administrator to restart the web server.'); } return $errors; @@ -307,8 +330,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(); } @@ -318,10 +341,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(); } } @@ -329,10 +352,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(); } @@ -342,13 +365,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(); } @@ -358,7 +381,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']; } @@ -383,9 +406,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); } @@ -397,7 +420,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 @@ -409,15 +432,15 @@ class OC_Util { // cleanup old tokens garbage collector // only run every 20th time so we don't waste cpu cycles - if(rand(0,20)==0) { + if(rand(0,20)==0) { 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]); + unset($_SESSION[$key]); } - } + } } } // return the token @@ -429,14 +452,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. @@ -444,7 +467,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 @@ -459,22 +482,22 @@ 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; } } - + /** * @brief Public function to sanitize HTML * * This function is used to sanitize HTML and should be applied on any * string or array of strings before displaying it on a web page. - * + * * @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 20d9e3b5d61..f5123adeeb6 100644 --- a/lib/vcategories.php +++ b/lib/vcategories.php @@ -125,11 +125,11 @@ class OC_VCategories { * $result = $stmt->execute(); * $objects = array(); * if(!is_null($result)) { - * while( $row = $result->fetchRow()){ + * while( $row = $result->fetchRow()) { * $objects[] = $row['carddata']; * } * } - * $categories->rescan($objects); + * $categories->rescan($objects); */ public function rescan($objects, $sync=true, $reset=true) { if($reset === true) { @@ -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) { @@ -219,7 +219,7 @@ class OC_VCategories { if(!is_array($haystack)) { return false; } - return array_search(strtolower($needle),array_map('strtolower',$haystack)); + return array_search(strtolower($needle),array_map('strtolower',$haystack)); } } 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); } } |